diff --git a/ctfcli/__main__.py b/ctfcli/__main__.py index c5b3058..a6e061e 100644 --- a/ctfcli/__main__.py +++ b/ctfcli/__main__.py @@ -14,16 +14,27 @@ from ctfcli.cli.templates import Templates from ctfcli.cli.pages import Pages from ctfcli.utils.plugins import get_plugin_dir +from ctfcli.utils.git import check_if_dir_is_inside_git_repo class CTFCLI(object): - def init(self, no_config=False): + def init(self, directory=None, no_config=False, no_git=False): + # Create our event directory if requested and use it as our base directory + if directory: + path = Path(directory) + path.mkdir() + click.secho(f"Created empty directory in {path.absolute()}", fg="green") + else: + path = Path(".") + + # Get variables from user ctf_url = click.prompt( "Please enter CTFd instance URL", default="", show_default=False ) ctf_token = click.prompt( "Please enter CTFd Admin Access Token", default="", show_default=False ) + # Confirm information with user if ( click.confirm(f"Do you want to continue with {ctf_url} and {ctf_token}") is False @@ -31,20 +42,29 @@ def init(self, no_config=False): click.echo("Aborted!") return - if Path(".ctf").exists(): + # Avoid colliding with existing .ctf directory + if (path / ".ctf").exists(): click.secho(".ctf/ folder already exists. Aborting!", fg="red") return - os.mkdir(".ctf") + # Create .ctf directory + (path / ".ctf").mkdir() + # Create initial .ctf/config file config = configparser.ConfigParser() config["config"] = {"url": ctf_url, "access_token": ctf_token} config["challenges"] = {} - - with open(".ctf/config", "a+") as f: + with (path / ".ctf" / "config").open(mode="a+") as f: config.write(f) - subprocess.call(["git", "init"]) + # Create a git repo in the event folder + if check_if_dir_is_inside_git_repo(dir=path.absolute()) is True: + click.secho("Already in git repo. Skipping git init.", fg="yellow") + elif no_git is True: + click.secho("Skipping git init.", fg="yellow") + else: + click.secho(f"Creating git repo in {path.absolute()}", fg="green") + subprocess.call(["git", "init", str(path)]) def config(self): return COMMANDS.get("config") diff --git a/ctfcli/utils/git.py b/ctfcli/utils/git.py index e13130d..d29640f 100644 --- a/ctfcli/utils/git.py +++ b/ctfcli/utils/git.py @@ -11,3 +11,25 @@ def get_git_repo_head_branch(repo): ).decode() head_branch = out.split()[1] return head_branch + + +def check_if_dir_is_inside_git_repo(dir=None): + """ + Checks whether a given directory is inside of a git repo. + """ + try: + out = ( + subprocess.check_output( + ["git", "rev-parse", "--is-inside-work-tree"], + cwd=dir, + stderr=subprocess.DEVNULL, + ) + .decode() + .strip() + ) + print(out) + if out == "true": + return True + return False + except subprocess.CalledProcessError: + return False