"""Utilities for initializing ccu."""importosfrompathlibimportPathimportsubprocessimportclickfromccu.settingsimportCCU_HOME_PROFILE_LINES="\n# Added by {0}\n. {1}\n"
[docs]def_write_completion_script(package:str,shell:str)->Path:"""Write the completion script."""hyphenated_package=f"{package.replace('_','-')}"script=CCU_HOME.joinpath(f".{hyphenated_package}-complete.{shell}")env={**os.environ}env[f"_{package.upper()}_COMPLETE"]=f"{shell}_source"ifnotscript.exists()or(input("Completion script exists! Overwrite (Y/N)? ").lower()=="y"):withscript.open(mode="w",encoding="utf-8")asfile:_=subprocess.run(args=hyphenated_package,stdout=file,check=False,env=env,)click.echo(f"Completion script written to {script.relative_to(Path.home())}")returnscript
@click.command("init",context_settings={"help_option_names":["-h","--help"]})defmain()->None:"""Enable tab completion and create the ccu home directory."""# Create ccu homeCCU_HOME.mkdir(parents=True,exist_ok=True)# Create .config/ccu/config.toml (shell_completion.sh)package=str(__package__).split(".")[0]shell=os.getenv("SHELL","/bin/bash").split("/")[-1]script=_write_completion_script(package,shell)profile=Path.home().joinpath(f".{shell}rc")new_lines=_PROFILE_LINES.format(package,script)withprofile.open(mode="r",encoding="utf-8")asfile:lines=file.readlines()source_line=new_lines.splitlines()[-1]completion_added=any(line.rstrip()==source_lineforlineinlines)ifnotcompletion_added:withprofile.open(mode="a",encoding="utf-8")asfile:file.writelines(new_lines)click.echo(f"The following lines have been added to your .{shell}rc file")click.echo(new_lines)