|
| 1 | +"""CLI functionality for vcspull add.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import logging |
| 7 | +import pathlib |
| 8 | +import typing as t |
| 9 | + |
| 10 | +import yaml |
| 11 | + |
| 12 | +from vcspull.config import ( |
| 13 | + expand_dir, |
| 14 | + find_home_config_files, |
| 15 | +) |
| 16 | + |
| 17 | +if t.TYPE_CHECKING: |
| 18 | + pass |
| 19 | + |
| 20 | +log = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +def save_config_yaml(file_path: pathlib.Path, data: dict[str, t.Any]) -> None: |
| 24 | + """Save dictionary to a YAML file.""" |
| 25 | + with open(file_path, "w") as f: |
| 26 | + yaml.dump(data, f, sort_keys=False, indent=2, default_flow_style=False) |
| 27 | + |
| 28 | + |
| 29 | +def create_add_subparser(parser: argparse.ArgumentParser) -> None: |
| 30 | + """Configure :py:class:`argparse.ArgumentParser` for ``vcspull add``.""" |
| 31 | + parser.add_argument( |
| 32 | + "-c", |
| 33 | + "--config", |
| 34 | + dest="config", |
| 35 | + metavar="file", |
| 36 | + help="path to custom config file (default: .vcspull.yaml or ~/.vcspull.yaml)", |
| 37 | + ) |
| 38 | + parser.add_argument( |
| 39 | + "repo_name_or_url", |
| 40 | + help="Name of the repository or its URL. If only name, URL may be inferred or prompted.", |
| 41 | + ) |
| 42 | + parser.add_argument( |
| 43 | + "target_path", |
| 44 | + nargs="?", |
| 45 | + help="Optional local path for the repository (can be relative or absolute). Overrides default naming.", |
| 46 | + ) |
| 47 | + parser.add_argument( |
| 48 | + "--base-dir-key", |
| 49 | + help="Specify the top-level directory key from vcspull config (e.g., '~/study/python/') under which to add this repo." |
| 50 | + " If not given, vcspull will try to infer or use the current working directory.", |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +def add_repo( |
| 55 | + repo_name_or_url: str, |
| 56 | + config_file_path_str: str | None, |
| 57 | + target_path_str: str | None = None, |
| 58 | + base_dir_key: str | None = None, |
| 59 | +) -> None: |
| 60 | + """Add a repository to the vcspull configuration.""" |
| 61 | + config_file_path: pathlib.Path |
| 62 | + if config_file_path_str: |
| 63 | + config_file_path = pathlib.Path(config_file_path_str).expanduser().resolve() |
| 64 | + else: |
| 65 | + # Default to ~/.vcspull.yaml if no global --config is passed |
| 66 | + # Behavior of find_home_config_files might need adjustment if it returns a list |
| 67 | + home_configs = find_home_config_files(filetype=["yaml"]) |
| 68 | + if not home_configs: |
| 69 | + # If no global --config and no home config, default to creating .vcspull.yaml in CWD |
| 70 | + config_file_path = pathlib.Path.cwd() / ".vcspull.yaml" |
| 71 | + log.info( |
| 72 | + f"No config specified and no default found, will create at {config_file_path}" |
| 73 | + ) |
| 74 | + elif len(home_configs) > 1: |
| 75 | + # This case should ideally be handled by the main CLI arg parsing for --config |
| 76 | + log.error( |
| 77 | + "Multiple home_config files found, please specify one with -c/--config" |
| 78 | + ) |
| 79 | + return |
| 80 | + else: |
| 81 | + config_file_path = home_configs[0] |
| 82 | + |
| 83 | + raw_config: dict[str, t.Any] = {} |
| 84 | + if config_file_path.exists() and config_file_path.is_file(): |
| 85 | + try: |
| 86 | + with open(config_file_path) as f: |
| 87 | + raw_config = yaml.safe_load(f) or {} |
| 88 | + if not isinstance(raw_config, dict): |
| 89 | + log.error( |
| 90 | + f"Config file {config_file_path} is not a valid YAML dictionary. Aborting." |
| 91 | + ) |
| 92 | + return |
| 93 | + except Exception as e: |
| 94 | + log.error(f"Error loading YAML from {config_file_path}: {e}. Aborting.") |
| 95 | + return |
| 96 | + else: |
| 97 | + log.info( |
| 98 | + f"Config file {config_file_path} not found. A new one will be created." |
| 99 | + ) |
| 100 | + |
| 101 | + repo_name: str |
| 102 | + repo_url: str |
| 103 | + |
| 104 | + # Simplistic parsing of repo_name_or_url, assuming it's a URL if it contains '://' or 'git@' |
| 105 | + # A more robust solution would involve libvcs or regex |
| 106 | + if ( |
| 107 | + "://" in repo_name_or_url |
| 108 | + or repo_name_or_url.startswith("git@") |
| 109 | + or repo_name_or_url.startswith("git+") |
| 110 | + or repo_name_or_url.startswith("hg+") |
| 111 | + or repo_name_or_url.startswith("svn+") |
| 112 | + ): |
| 113 | + repo_url = repo_name_or_url |
| 114 | + # Try to infer name from URL |
| 115 | + repo_name = pathlib.Path(repo_url.split("/")[-1]).stem |
| 116 | + if target_path_str: |
| 117 | + repo_name = pathlib.Path( |
| 118 | + target_path_str |
| 119 | + ).name # if target_path is specified, use its name for repo_name |
| 120 | + else: |
| 121 | + repo_name = repo_name_or_url |
| 122 | + # URL is not provided, for now, we can make it an error or set a placeholder |
| 123 | + # In future, could try to infer from a local git repo if target_path_str points to one |
| 124 | + log.error( |
| 125 | + "Repository URL must be provided if repo_name_or_url is not a URL. Functionality to infer URL is not yet implemented." |
| 126 | + ) |
| 127 | + # For now, let's assume a placeholder or require URL to be part of repo_name_or_url |
| 128 | + # This part needs a decision: either make URL mandatory with name, or implement inference |
| 129 | + # Let's require the user to provide a URL for now by just using repo_name_or_url as URL if it seems like one |
| 130 | + # This means the first arg must be a URL if only one arg is given and it's not just a name. |
| 131 | + # To simplify, let's assume if not detected as URL, then it's just a name and we need target_path to be a URL |
| 132 | + # Or, the user *must* provide two arguments: name then url. The current subparser takes one `repo_name_or_url` and optional `target_path`. |
| 133 | + # This argument parsing needs refinement in `create_add_subparser` to accept name and url separately. |
| 134 | + # For now, this will likely fail if a plain name is given without a clear URL source. |
| 135 | + # Let's adjust the expectation: repo_name_or_url IS THE URL, and repo_name is derived or taken from target_path. |
| 136 | + # This means first arg is always URL-like or repo name. Second is target_path (which becomes name) |
| 137 | + |
| 138 | + # Re-evaluating argument strategy based on user request for `vcspull add my-repo <url>`: |
| 139 | + # `repo_name_or_url` will be `my-repo` |
| 140 | + # `target_path` will be `<url>` |
| 141 | + # This means `create_add_subparser` needs adjustment. |
| 142 | + # For now, let's proceed with the current subparser and assume `repo_name_or_url` is the name, and `target_path` (if provided) is the URL for this specific case. |
| 143 | + # This is getting complicated. Let's simplify the add command for now: |
| 144 | + # `vcspull add <NAME> <URL>` |
| 145 | + # The current `repo_name_or_url` and `target_path` can be repurposed. |
| 146 | + |
| 147 | + # Let's rename parser args for clarity: repo_name, repo_url |
| 148 | + # This requires changing create_add_subparser and the cli call in __init__.py |
| 149 | + # Given the current structure, repo_name_or_url = actual name, target_path = actual_url |
| 150 | + if target_path_str is None: |
| 151 | + log.error("If first argument is a name, second argument (URL) is required.") |
| 152 | + return |
| 153 | + repo_name = repo_name_or_url |
| 154 | + repo_url = target_path_str |
| 155 | + |
| 156 | + # Determine the base directory key for the config |
| 157 | + actual_base_dir_key: str |
| 158 | + if base_dir_key: |
| 159 | + actual_base_dir_key = ( |
| 160 | + base_dir_key if base_dir_key.endswith("/") else base_dir_key + "/" |
| 161 | + ) |
| 162 | + elif target_path_str and not ( |
| 163 | + "://" in target_path_str or target_path_str.startswith("git@") |
| 164 | + ): # if target_path is a path, not url |
| 165 | + # Infer from target_path_str if it's a local path |
| 166 | + # This assumes target_path_str is the actual clone path if provided and is not the URL itself |
| 167 | + # This logic is getting tangled due to the argument overloading. Let's stick to the idea that repo_name is derived or is first arg, url is second or inferred |
| 168 | + # For simplicity, let's assume if base_dir_key is not given, we use a default or CWD based key |
| 169 | + # This needs to be more robust. Example: if repo is to be cloned to /home/user/study/python/myrepo |
| 170 | + # and vcspull.yaml has '~/study/python/': ..., then this is the key. |
| 171 | + # We can use os.path.commonpath or iterate through existing keys. |
| 172 | + # For now, default to current working directory's representation or a new top-level key if no match. |
| 173 | + cwd_path = pathlib.Path.cwd() |
| 174 | + resolved_target_dir_parent = ( |
| 175 | + pathlib.Path(target_path_str).parent.resolve() |
| 176 | + if target_path_str |
| 177 | + and not ("://" in target_path_str or target_path_str.startswith("git@")) |
| 178 | + else cwd_path |
| 179 | + ) |
| 180 | + |
| 181 | + found_key = None |
| 182 | + for key_path_str in raw_config.keys(): |
| 183 | + expanded_key_path = expand_dir(pathlib.Path(key_path_str), cwd_path) |
| 184 | + if ( |
| 185 | + resolved_target_dir_parent == expanded_key_path |
| 186 | + or resolved_target_dir_parent.is_relative_to(expanded_key_path) |
| 187 | + ): |
| 188 | + # Check if resolved_target_dir_parent is a subdirectory or same as an existing key path |
| 189 | + try: |
| 190 | + if resolved_target_dir_parent.relative_to(expanded_key_path): |
| 191 | + found_key = key_path_str |
| 192 | + break |
| 193 | + except ValueError: # Not a sub-path |
| 194 | + if resolved_target_dir_parent == expanded_key_path: |
| 195 | + found_key = key_path_str |
| 196 | + break |
| 197 | + if found_key: |
| 198 | + actual_base_dir_key = found_key |
| 199 | + else: |
| 200 | + # Default to a key based on the target repo's parent directory or CWD |
| 201 | + # Make it relative to home if possible, or absolute |
| 202 | + try: |
| 203 | + actual_base_dir_key = ( |
| 204 | + "~/" |
| 205 | + + str(resolved_target_dir_parent.relative_to(pathlib.Path.home())) |
| 206 | + + "/" |
| 207 | + ) |
| 208 | + except ValueError: |
| 209 | + actual_base_dir_key = str(resolved_target_dir_parent) + "/" |
| 210 | + else: |
| 211 | + # Default base directory key if not specified and target_path is not a local path |
| 212 | + # This could be "." or a user-configurable default |
| 213 | + actual_base_dir_key = "./" # Default to relative current directory key |
| 214 | + |
| 215 | + if not actual_base_dir_key.endswith("/"): # Ensure trailing slash for consistency |
| 216 | + actual_base_dir_key += "/" |
| 217 | + |
| 218 | + # Ensure the base directory key exists in the config |
| 219 | + if actual_base_dir_key not in raw_config: |
| 220 | + raw_config[actual_base_dir_key] = {} |
| 221 | + elif not isinstance(raw_config[actual_base_dir_key], dict): |
| 222 | + log.error( |
| 223 | + f"Configuration section '{actual_base_dir_key}' is not a dictionary. Aborting." |
| 224 | + ) |
| 225 | + return |
| 226 | + |
| 227 | + # Check if repo already exists under this base key |
| 228 | + if repo_name in raw_config[actual_base_dir_key]: |
| 229 | + log.warning( |
| 230 | + f"Repository '{repo_name}' already exists under '{actual_base_dir_key}'." |
| 231 | + f" Current URL: {raw_config[actual_base_dir_key][repo_name]}." |
| 232 | + f" To update, remove and re-add, or edit the YAML file manually." |
| 233 | + ) |
| 234 | + return |
| 235 | + |
| 236 | + # Add the repository |
| 237 | + # Simplest form: {repo_name: repo_url} |
| 238 | + # More complex form (if remotes, etc., were supported): {repo_name: {"url": repo_url, ...}} |
| 239 | + raw_config[actual_base_dir_key][repo_name] = repo_url |
| 240 | + |
| 241 | + try: |
| 242 | + save_config_yaml(config_file_path, raw_config) |
| 243 | + log.info( |
| 244 | + f"Successfully added '{repo_name}' ({repo_url}) to {config_file_path} under '{actual_base_dir_key}'." |
| 245 | + ) |
| 246 | + except Exception as e: |
| 247 | + log.error(f"Error saving config to {config_file_path}: {e}") |
0 commit comments