1
1
use anyhow:: anyhow;
2
+ use cargo:: core:: shell:: Shell ;
2
3
use cargo:: core:: { features, CliUnstable } ;
3
4
use cargo:: { self , drop_print, drop_println, CliResult , Config } ;
4
5
use clap:: { AppSettings , Arg , ArgMatches } ;
@@ -21,12 +22,13 @@ lazy_static::lazy_static! {
21
22
] ) ;
22
23
}
23
24
24
- pub fn main ( config : & mut Config ) -> CliResult {
25
+ pub fn main ( config : & mut LazyConfig ) -> CliResult {
26
+ let args = cli ( ) . try_get_matches ( ) ?;
27
+
25
28
// CAUTION: Be careful with using `config` until it is configured below.
26
29
// In general, try to avoid loading config values unless necessary (like
27
30
// the [alias] table).
28
-
29
- let args = cli ( ) . try_get_matches ( ) ?;
31
+ let config = config. get_mut ( ) ;
30
32
31
33
// Global args need to be extracted before expanding aliases because the
32
34
// clap code for extracting a subcommand discards global options
@@ -463,6 +465,34 @@ See 'cargo help <command>' for more information on a specific command.\n",
463
465
. subcommands ( commands:: builtin ( ) )
464
466
}
465
467
468
+ pub struct LazyConfig {
469
+ config : Option < Config > ,
470
+ }
471
+
472
+ impl LazyConfig {
473
+ pub fn new ( ) -> Self {
474
+ Self { config : None }
475
+ }
476
+
477
+ pub fn is_init ( & self ) -> bool {
478
+ self . config . is_some ( )
479
+ }
480
+
481
+ pub fn get ( & mut self ) -> & Config {
482
+ self . get_mut ( )
483
+ }
484
+
485
+ pub fn get_mut ( & mut self ) -> & mut Config {
486
+ self . config . get_or_insert_with ( || match Config :: default ( ) {
487
+ Ok ( cfg) => cfg,
488
+ Err ( e) => {
489
+ let mut shell = Shell :: new ( ) ;
490
+ cargo:: exit_with_error ( e. into ( ) , & mut shell)
491
+ }
492
+ } )
493
+ }
494
+ }
495
+
466
496
#[ test]
467
497
fn verify_cli ( ) {
468
498
cli ( ) . debug_assert ( ) ;
0 commit comments