Skip to content

Commit e1f4999

Browse files
committed
!squash initial: add and add-from-fs
1 parent 475e137 commit e1f4999

File tree

3 files changed

+562
-8
lines changed

3 files changed

+562
-8
lines changed

src/vcspull/cli/__init__.py

Lines changed: 94 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,29 @@ 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],
49+
get_all_subparsers: t.Literal[True],
50+
) -> tuple[
51+
argparse.ArgumentParser,
52+
argparse._SubParsersAction,
53+
dict[str, argparse.ArgumentParser],
54+
]: ...
55+
56+
4457
def create_parser(
4558
return_subparsers: bool = False,
46-
) -> argparse.ArgumentParser | tuple[argparse.ArgumentParser, t.Any]:
59+
get_all_subparsers: bool = False,
60+
) -> (
61+
argparse.ArgumentParser
62+
| tuple[argparse.ArgumentParser, t.Any]
63+
| tuple[
64+
argparse.ArgumentParser,
65+
argparse._SubParsersAction,
66+
dict[str, argparse.ArgumentParser],
67+
]
68+
):
4769
"""Create CLI argument parser for vcspull."""
4870
parser = argparse.ArgumentParser(
4971
prog="vcspull",
@@ -73,14 +95,42 @@ def create_parser(
7395
)
7496
create_sync_subparser(sync_parser)
7597

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

80127

81128
def cli(_args: list[str] | None = None) -> None:
82129
"""CLI entry point for vcspull."""
83-
parser, sync_parser = create_parser(return_subparsers=True)
130+
parser, _subparsers_action, all_parsers = create_parser(
131+
return_subparsers=True,
132+
get_all_subparsers=True,
133+
)
84134
args = parser.parse_args(_args)
85135

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

src/vcspull/cli/add.py

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

0 commit comments

Comments
 (0)