33
44from sys_lang import get_sys_lang
55
6- from . import data
6+ from . import data , log
77
88def cli () -> sn :
99 from . import env , language , settings
@@ -12,3 +12,62 @@ def cli() -> sn:
1212 language .generate_random_lang (excludes = ['en' ]) if env .is_debug_mode () else get_sys_lang ())
1313 settings .load (cli )
1414 return cli
15+
16+ def config_file (cli : sn ) -> None : # for --init
17+
18+ # Init target_path
19+ import find_project_root
20+ project_root = find_project_root (max_depth = 20 ) # type: ignore
21+ if project_root :
22+ config_dir , in_project_root = Path (project_root ), True
23+ else :
24+ log .warn (cli .msgs .warn_NO_PROJECT_ROOT_FOUND )
25+ user_resp = input (f'{ cli .msgs .prompt_INIT_CONFIG_HERE_ANYWAY } ? (y/N): ' ).strip ().lower ()
26+ if not user_resp .startswith ('y' ) : return
27+ config_dir , in_project_root = Path .cwd (), False
28+ target_path = config_dir / f'.{ cli .short_name or cli .name } .config.json5'
29+
30+ # Handle existing file
31+ if target_path .exists ():
32+ if cli .config .force :
33+ log .info (f'{ cli .msgs .log_OVERWRITING_CONFIG_AT } { target_path } ...\n ' )
34+ else :
35+ log .warn (f'{ cli .msgs .warn_CONFIG_EXISTS_AT } { target_path } . { cli .msgs .log_SKIPPING } init...' )
36+ log .tip (f'{ cli .msgs .tip_PASS_FORCE_TO_OVERWRITE } .' )
37+ return
38+
39+ # Fetch/write from jsDelivr
40+ if not getattr (config_file , 'cached_default' , None ):
41+ from . import jsdelivr , url
42+ jsd_url = f'{ jsdelivr .create_pkg_ver_url (cli )} /{ target_path .name } '
43+ log .debug (f'{ log .colors .bw } { jsd_url } ' )
44+ config_file .cached_default = url .get (jsd_url )
45+ data .file .write (str (target_path ), config_file .cached_default )
46+ log .success (f'{ cli .msgs .log_DEFAULT_CONFIG_CREATED_AT } { target_path } ' )
47+ if not in_project_root : log .tip (f'{ cli .msgs .tip_MOVE_CONFIG_TO_ROOT } .' )
48+
49+ def config_filepath (cli : sn ) -> None : # for settings.load()
50+
51+ # Check --config <path>
52+ if getattr (cli .config , 'config' , '' ):
53+ cli .config_filepath = Path (cli .config .config ).resolve ()
54+ if cli .config_filepath .exists ():
55+ log .debug (f'Config file found: { cli .config_filepath } ' )
56+ return
57+ else :
58+ log .warn (f'{ cli .msgs .warn_SPECIFIED_CONFIG } { cli .config_filepath } { cli .msgs .warn_NOT_FOUND } ' )
59+
60+ # Search upwards
61+ possible_config_filenames = [
62+ f'{ prefix } { name } .config.json{ suffix } '
63+ for prefix in ['.' , '' ] for name in [cli .short_name , cli .name ] for suffix in ['5' , '' , 'c' ]
64+ ]
65+ current_dir = Path .cwd ().resolve ()
66+ for parent in [current_dir , * current_dir .parents ]:
67+ for filename in possible_config_filenames :
68+ possible_config_filepath = parent / filename
69+ if possible_config_filepath .exists ():
70+ cli .config_filepath = possible_config_filepath
71+ return
72+
73+ cli .config_filepath = None
0 commit comments