Coverage for src/somesy/cli/init.py: 95%
107 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
1"""Set config files for somesy."""
3import logging
4from pathlib import Path
5from typing import Any
7import typer
9from somesy.commands import init_config, write_somesy_file
10from somesy.core.core import discover_input
11from somesy.core.log import SomesyLogLevel, set_log_level
12from somesy.core.models import Person, SomesyConfig, SomesyInput
13from somesy.core.types import LicenseEnum
14from somesy.git.harvest import harvest as harvest_git
15from somesy.harvest import harvest_sources
16from somesy.merge import merge_metadata
18from .util import file_arg_config, wrap_exceptions
20logger = logging.getLogger("somesy")
21app = typer.Typer()
24def _prompt_missing_metadata(
25 sources: list[tuple[Path, dict[str, Any]]],
26 git_metadata,
27 non_interactive: bool = False,
28) -> dict[str, Any]:
29 """Prompt or warn for required metadata that harvesting did not provide."""
30 harvested = [content for _, content in sources]
31 if git_metadata is not None:
32 harvested.append(
33 git_metadata.model_dump(exclude_none=True, exclude_defaults=False)
34 )
35 fallback: dict[str, Any] = {}
37 for field, prompt in {
38 "name": "Project name",
39 "description": "Project description",
40 }.items():
41 if not any(source.get(field) for source in harvested):
42 if non_interactive:
43 logger.warning("Missing required metadata: %s", field)
44 else:
45 fallback[field] = typer.prompt(prompt)
47 if not any(source.get("license") for source in harvested):
48 if non_interactive:
49 logger.warning("Missing required metadata: license")
50 else:
51 while True:
52 value = typer.prompt("SPDX license")
53 try:
54 fallback["license"] = LicenseEnum(value)
55 break
56 except ValueError:
57 typer.echo(f"Unknown SPDX license: {value}")
59 def is_author(person: Any) -> bool:
60 return (
61 person.get("author", False)
62 if isinstance(person, dict)
63 else getattr(person, "author", False)
64 )
66 has_author = any(
67 any(is_author(person) for person in source.get(key, []) or [])
68 for source in harvested
69 for key in ("people", "entities", "authors")
70 )
71 if not has_author:
72 if non_interactive:
73 logger.warning("Missing required metadata: author")
74 else:
75 author_type = typer.prompt(
76 "Author type", type=str, default="person"
77 ).lower()
78 while author_type not in {"person", "entity"}:
79 typer.echo("Author type must be 'person' or 'entity'.")
80 author_type = typer.prompt("Author type", default="person").lower()
81 if author_type == "person":
82 person = {
83 "given_names": typer.prompt("Author given names"),
84 "family_names": typer.prompt("Author family names"),
85 "author": True,
86 }
87 email = typer.prompt("Author email", default="")
88 if email:
89 person["email"] = email
90 fallback["people"] = [Person(**person)]
91 else:
92 name = typer.prompt("Author organization")
93 fallback["entities"] = [{"name": name, "author": True}]
94 email = typer.prompt("Author email", default="")
95 if email:
96 fallback["entities"][0]["email"] = email
98 return fallback
101@app.callback(invoke_without_command=True)
102@wrap_exceptions
103def initialize(
104 ctx: typer.Context,
105 output_file: Path = typer.Option(
106 Path("somesy.toml"),
107 "--output-file",
108 "-o",
109 help="Path for the generated somesy.toml file (default: somesy.toml).",
110 **file_arg_config,
111 ),
112 overwrite: bool = typer.Option(False, "--overwrite"),
113 non_interactive: bool = typer.Option(
114 False,
115 "--non-interactive",
116 help="Do not prompt for missing metadata; report warnings instead.",
117 ),
118):
119 """Harvest project metadata and create a somesy.toml file."""
120 if ctx.invoked_subcommand is not None:
121 ignored = [
122 name
123 for name, given in (
124 ("--output-file", output_file != Path("somesy.toml")),
125 ("--overwrite", overwrite),
126 ("--non-interactive", non_interactive),
127 )
128 if given
129 ]
130 if ignored:
131 logger.warning(
132 f"Option(s) {', '.join(ignored)} of 'init' are ignored by "
133 f"'init {ctx.invoked_subcommand}'."
134 )
135 return
136 root = Path.cwd()
137 output = output_file if output_file.is_absolute() else root / output_file
138 if output.exists() and not overwrite:
139 raise FileExistsError(f"Output file already exists: {output}")
140 sources = harvest_sources(root)
141 git_metadata = harvest_git(root)
142 fallback = _prompt_missing_metadata(sources, git_metadata, non_interactive)
143 source_content = [content for _, content in sources]
144 if fallback:
145 source_content.append(fallback)
146 metadata = merge_metadata(
147 source_content, git_metadata, allow_incomplete=non_interactive
148 )
149 source_names = {path.name for path, _ in sources}
150 incomplete = (
151 any(
152 getattr(metadata, field, None) is None
153 for field in ("name", "description", "license")
154 )
155 or not metadata.authors()
156 )
157 config = None
158 if source_names or incomplete:
159 config_data = {
160 f"no_sync_{key}": filename not in source_names
161 for key, filename in {
162 "pyproject": "pyproject.toml",
163 "package_json": "package.json",
164 "julia": "Project.toml",
165 "fortran": "fpm.toml",
166 "pom_xml": "pom.xml",
167 "mkdocs": "mkdocs.yml",
168 "rust": "Cargo.toml",
169 }.items()
170 }
171 config = SomesyConfig.model_validate(config_data)
172 write_somesy_file(metadata, output, config=config, overwrite=overwrite)
173 typer.echo(f"Created {output}")
176# (config key, prompt label, default file, sync by default)
177_CONFIG_TARGETS = [
178 ("cff", "CFF", "CITATION.cff", True),
179 ("codemeta", "codemeta.json", "codemeta.json", True),
180 ("pyproject", "pyproject.toml", "pyproject.toml", True),
181 ("package_json", "package.json", "package.json", False),
182 ("julia", "Project.toml (Julia)", "Project.toml", True),
183 ("fortran", "fpm.toml (Fortran)", "fpm.toml", True),
184 ("pom_xml", "pom.xml", "pom.xml", True),
185 ("mkdocs", "mkdocs.yml", "mkdocs.yml", True),
186 ("rust", "Cargo.toml", "Cargo.toml", True),
187]
190@app.command()
191@wrap_exceptions
192def config():
193 """Set CLI configs for somesy."""
194 # check if input file exists, if not, try to find it from default list
195 try:
196 input_file_default = discover_input()
197 except FileNotFoundError:
198 input_file_default = Path("somesy.toml") # first-time creation
200 # prompt for inputs
201 input_file = Path(typer.prompt("Input file path", default=input_file_default))
202 # validate the target before asking anything else
203 if not input_file.exists() and not SomesyInput.is_somesy_file_path(input_file):
204 raise FileNotFoundError(
205 f"Input file not found: {input_file} (only somesy.toml files can be "
206 "created by this command)."
207 )
208 options: dict[str, Any] = {"input_file": Path(input_file)}
210 for key, label, default_file, default_sync in _CONFIG_TARGETS:
211 options[f"no_sync_{key}"] = not typer.confirm(
212 f"Do you want to sync to a {label} file?", default=default_sync
213 )
214 if target_file := typer.prompt(f"{label} file path", default=default_file):
215 options[f"{key}_file"] = target_file
217 # ----
219 options["show_info"] = typer.confirm(
220 "Do you want to show info about the sync process?"
221 )
222 options["verbose"] = typer.confirm("Do you want to show verbose logs?")
223 options["debug"] = typer.confirm("Do you want to show debug logs?")
225 set_log_level(
226 SomesyLogLevel.from_flags(
227 debug=options["debug"],
228 verbose=options["verbose"],
229 info=options["show_info"],
230 )
231 )
233 logger.debug(f"CLI options entered: {options}")
235 init_config(input_file, options)
236 logger.info(
237 f"[bold green]Input file is updated/created at {input_file}[/bold green]"
238 )