Keep It Simple: A Python Design Dilemma
While building an AI agent with Git capabilities, I found myself repeating the same logic: checking whether the agent’s working directory was a Git repository before attempting any Git operation. This check appeared inside every Git-related tool that I made available to the agent. For example, if I wanted to commit a Git message I would have written something like this: def commit_git_message(working_directory, directory=None, message): """ This function checks if the given directory is a Git repo and executes a git commit operation """ # get the absolute path of the given directory abs_working_dir = Path(working_directory).resolve() if directory: target_dir = abs_working_dir / directory else: target_dir = abs_working_dir # check if target directory is inside the working directory if not target_dir.is_relative_to(abs_working_dir): return f'Error: Cannot work on "{target_dir}" as it is outside the permitted working directory' # check if the working directory is indeed a directory if not target_dir.is_dir(): return f'Error: "{target_dir}" is not a directory' try: # the following command returns "true" if the directory is a Git repo or inside a Git repo check_git_dir = subprocess.run( ["git", "rev-parse", "--is-inside-work-tree"], cwd=str(target_dir), capture_output=True, check=True, ) if check_git_dir.returncode != 0: return f'Error: "{target_dir}" is not a Git directory' except subprocess.CalledProcessError as e: return str(e) ### test of the logic Now imagine this logic repeated inside every Git tool like some boilerplate code. Not very DRY. ...