Coverage for src/somesy/cli/init.py: 95%
99 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-03 13:13 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-03 13:13 +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
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 return
122 root = Path.cwd()
123 output = output_file if output_file.is_absolute() else root / output_file
124 if output.exists() and not overwrite:
125 raise FileExistsError(f"Output file already exists: {output}")
126 sources = harvest_sources(root)
127 git_metadata = harvest_git(root)
128 fallback = _prompt_missing_metadata(sources, git_metadata, non_interactive)
129 source_content = [content for _, content in sources]
130 if fallback:
131 source_content.append(fallback)
132 metadata = merge_metadata(
133 source_content, git_metadata, allow_incomplete=non_interactive
134 )
135 source_names = {path.name for path, _ in sources}
136 incomplete = (
137 any(
138 getattr(metadata, field, None) is None
139 for field in ("name", "description", "license")
140 )
141 or not metadata.authors()
142 )
143 config = None
144 if source_names or incomplete:
145 config_data = {
146 f"no_sync_{key}": filename not in source_names
147 for key, filename in {
148 "pyproject": "pyproject.toml",
149 "package_json": "package.json",
150 "julia": "Project.toml",
151 "fortran": "fpm.toml",
152 "pom_xml": "pom.xml",
153 "mkdocs": "mkdocs.yml",
154 "rust": "Cargo.toml",
155 }.items()
156 }
157 config = SomesyConfig.model_validate(config_data)
158 write_somesy_file(metadata, output, config=config, overwrite=overwrite)
159 typer.echo(f"Created {output}")
162# (config key, prompt label, default file, sync by default)
163_CONFIG_TARGETS = [
164 ("cff", "CFF", "CITATION.cff", True),
165 ("codemeta", "codemeta.json", "codemeta.json", True),
166 ("pyproject", "pyproject.toml", "pyproject.toml", True),
167 ("package_json", "package.json", "package.json", False),
168 ("julia", "Project.toml (Julia)", "Project.toml", True),
169 ("fortran", "fpm.toml (Fortran)", "fpm.toml", True),
170 ("pom_xml", "pom.xml", "pom.xml", True),
171 ("mkdocs", "mkdocs.yml", "mkdocs.yml", True),
172 ("rust", "Cargo.toml", "Cargo.toml", True),
173]
176@app.command()
177@wrap_exceptions
178def config():
179 """Set CLI configs for somesy."""
180 # check if input file exists, if not, try to find it from default list
181 input_file_default = discover_input()
183 # prompt for inputs
184 input_file = Path(typer.prompt("Input file path", default=input_file_default))
185 options: dict[str, Any] = {"input_file": Path(input_file)}
187 for key, label, default_file, default_sync in _CONFIG_TARGETS:
188 options[f"no_sync_{key}"] = not typer.confirm(
189 f"Do you want to sync to a {label} file?", default=default_sync
190 )
191 if target_file := typer.prompt(f"{label} file path", default=default_file):
192 options[f"{key}_file"] = target_file
194 # ----
196 options["show_info"] = typer.confirm(
197 "Do you want to show info about the sync process?"
198 )
199 options["verbose"] = typer.confirm("Do you want to show verbose logs?")
200 options["debug"] = typer.confirm("Do you want to show debug logs?")
202 set_log_level(
203 SomesyLogLevel.from_flags(
204 debug=options["debug"],
205 verbose=options["verbose"],
206 info=options["show_info"],
207 )
208 )
210 logger.debug(f"CLI options entered: {options}")
212 init_config(input_file, options)
213 logger.info(
214 f"[bold green]Input file is updated/created at {input_file}[/bold green]"
215 )