Skip to content

Commit 21953f4

Browse files
committed
!squash initial: add and add-from-fs
1 parent 8afed59 commit 21953f4

File tree

3 files changed

+567
-8
lines changed

3 files changed

+567
-8
lines changed

src/vcspull/cli/__init__.py

Lines changed: 92 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
from vcspull.__about__ import __version__
1414
from vcspull.log import setup_logger
1515

16+
from .add import add_repo, create_add_subparser
17+
from .add_from_fs import add_from_filesystem, create_add_from_fs_subparser
1618
from .sync import create_sync_subparser, sync
1719

1820
log = logging.getLogger(__name__)
@@ -41,9 +43,28 @@ def create_parser(
4143
def create_parser(return_subparsers: t.Literal[False]) -> argparse.ArgumentParser: ...
4244

4345

46+
@overload
47+
def create_parser(
48+
return_subparsers: t.Literal[True], get_all_subparsers: t.Literal[True]
49+
) -> tuple[
50+
argparse.ArgumentParser,
51+
argparse._SubParsersAction,
52+
dict[str, argparse.ArgumentParser],
53+
]: ...
54+
55+
4456
def create_parser(
4557
return_subparsers: bool = False,
46-
) -> argparse.ArgumentParser | tuple[argparse.ArgumentParser, t.Any]:
58+
get_all_subparsers: bool = False,
59+
) -> (
60+
argparse.ArgumentParser
61+
| tuple[argparse.ArgumentParser, t.Any]
62+
| tuple[
63+
argparse.ArgumentParser,
64+
argparse._SubParsersAction,
65+
dict[str, argparse.ArgumentParser],
66+
]
67+
):
4768
"""Create CLI argument parser for vcspull."""
4869
parser = argparse.ArgumentParser(
4970
prog="vcspull",
@@ -73,14 +94,41 @@ def create_parser(
7394
)
7495
create_sync_subparser(sync_parser)
7596

97+
add_parser = subparsers.add_parser(
98+
"add",
99+
help="add a new repository to the configuration",
100+
formatter_class=argparse.RawDescriptionHelpFormatter,
101+
description="Adds a new repository to the vcspull configuration file.",
102+
)
103+
create_add_subparser(add_parser)
104+
105+
add_from_fs_parser = subparsers.add_parser(
106+
"add-from-fs",
107+
help="scan a directory for git repositories and add them to the configuration",
108+
formatter_class=argparse.RawDescriptionHelpFormatter,
109+
description="Scans a directory for git repositories and adds them to the vcspull configuration file.",
110+
)
111+
create_add_from_fs_subparser(add_from_fs_parser)
112+
113+
all_subparsers_dict = {
114+
"sync": sync_parser,
115+
"add": add_parser,
116+
"add_from_fs": add_from_fs_parser,
117+
}
118+
119+
if get_all_subparsers:
120+
return parser, subparsers, all_subparsers_dict
121+
76122
if return_subparsers:
77123
return parser, sync_parser
78124
return parser
79125

80126

81127
def cli(_args: list[str] | None = None) -> None:
82128
"""CLI entry point for vcspull."""
83-
parser, sync_parser = create_parser(return_subparsers=True)
129+
parser, subparsers_action, all_parsers = create_parser(
130+
return_subparsers=True, get_all_subparsers=True
131+
)
84132
args = parser.parse_args(_args)
85133

86134
setup_logger(log=log, level=args.log_level.upper())
@@ -89,9 +137,45 @@ def cli(_args: list[str] | None = None) -> None:
89137
parser.print_help()
90138
return
91139
if args.subparser_name == "sync":
92-
sync(
93-
repo_patterns=args.repo_patterns,
94-
config=args.config,
95-
exit_on_error=args.exit_on_error,
96-
parser=sync_parser,
97-
)
140+
sync_parser = all_parsers["sync"]
141+
sync_kwargs = {
142+
"repo_patterns": args.repo_patterns
143+
if hasattr(args, "repo_patterns")
144+
else None,
145+
"config": args.config if hasattr(args, "config") else None,
146+
"exit_on_error": args.exit_on_error
147+
if hasattr(args, "exit_on_error")
148+
else False,
149+
"parser": sync_parser,
150+
}
151+
sync_kwargs = {
152+
k: v
153+
for k, v in sync_kwargs.items()
154+
if v is not None or k == "parser" or k == "exit_on_error"
155+
}
156+
sync(**sync_kwargs)
157+
elif args.subparser_name == "add":
158+
add_parser_instance = all_parsers["add"]
159+
add_repo_kwargs = {
160+
"repo_name_or_url": args.repo_name_or_url,
161+
"config_file_path_str": args.config if hasattr(args, "config") else None,
162+
"target_path_str": args.target_path
163+
if hasattr(args, "target_path")
164+
else None,
165+
"base_dir_key": args.base_dir_key
166+
if hasattr(args, "base_dir_key")
167+
else None,
168+
}
169+
add_repo(**add_repo_kwargs)
170+
elif args.subparser_name == "add_from_fs":
171+
add_from_fs_parser_instance = all_parsers["add_from_fs"]
172+
add_from_fs_kwargs = {
173+
"scan_dir_str": args.scan_dir,
174+
"config_file_path_str": args.config if hasattr(args, "config") else None,
175+
"recursive": args.recursive if hasattr(args, "recursive") else False,
176+
"base_dir_key_arg": args.base_dir_key
177+
if hasattr(args, "base_dir_key")
178+
else None,
179+
"yes": args.yes if hasattr(args, "yes") else False,
180+
}
181+
add_from_filesystem(**add_from_fs_kwargs)

src/vcspull/cli/add.py

Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
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

Comments
 (0)