1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt::Write as _;
3use std::io::Write;
4use std::path::{Path, PathBuf};
5
6use codeint_model::{Metric, MetricScope, RepoPath, SourceSet};
7
8use super::schema::{ConfigurationFile, LanguageGlobs};
9use super::starter_formats::{StarterRenderInput, StructuredSyntax, render_structured_starter};
10use crate::baseline::MeasuredBaselineMetric;
11use crate::boundaries::BoundaryPreset;
12use crate::command::InitFormat;
13use crate::config_error::ConfigFileKind;
14
15#[cfg(test)]
16mod tests;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct DetectedLanguage {
20 pub plugin: String,
21 pub include: Vec<RepoPath>,
22 pub known_dialects: Vec<String>,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct StarterBoundaryZone {
27 pub name: String,
28 pub pattern: String,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum StarterBoundaries {
33 WorkspaceZones(Vec<StarterBoundaryZone>),
34 Preset(BoundaryPreset),
35}
36
37impl StarterBoundaries {
38 pub fn from_workspace_packages(roots: &[RepoPath]) -> Option<StarterBoundaries> {
39 let unique_roots: BTreeSet<&RepoPath> = roots.iter().collect();
40 if unique_roots.len() < 2 {
41 return None;
42 }
43 let mut basename_counts: BTreeMap<&str, usize> = BTreeMap::new();
44 for root in &unique_roots {
45 *basename_counts.entry(workspace_basename(root)).or_insert(0) += 1;
46 }
47 let mut zones: Vec<StarterBoundaryZone> = unique_roots
48 .into_iter()
49 .map(|root| starter_zone_for_root(root, &basename_counts))
50 .collect();
51 zones.sort_by(|left, right| left.name.cmp(&right.name));
52 Some(StarterBoundaries::WorkspaceZones(zones))
53 }
54}
55
56fn workspace_basename(root: &RepoPath) -> &str {
57 root.as_str()
58 .rsplit_once('/')
59 .map_or(root.as_str(), |(_, last)| last)
60}
61
62fn starter_zone_for_root(
63 root: &RepoPath,
64 basename_counts: &BTreeMap<&str, usize>,
65) -> StarterBoundaryZone {
66 let basename = workspace_basename(root);
67 let candidate = if basename_counts.get(basename).copied().unwrap_or(0) == 1
68 && is_valid_zone_name(basename)
69 {
70 basename
71 } else {
72 root.as_str()
73 };
74 let name = if is_valid_zone_name(candidate) {
75 candidate.to_owned()
76 } else {
77 format!("package-{candidate}")
78 };
79 let pattern = format!("{}/**", globset::escape(root.as_str()));
80 StarterBoundaryZone { name, pattern }
81}
82
83fn is_valid_zone_name(name: &str) -> bool {
84 !name.trim().is_empty() && name != "*"
85}
86
87#[derive(Debug, thiserror::Error)]
88pub enum StarterConfigurationError {
89 #[error("{} already exists, and codeint init never replaces it", path.display())]
90 AlreadyExists { path: PathBuf },
91 #[error("cannot write {}", path.display())]
92 Unwritable {
93 path: PathBuf,
94 #[source]
95 source: std::io::Error,
96 },
97}
98
99pub fn published_schema_address() -> String {
100 format!(
101 "https://raw.githubusercontent.com/avidianity/codeint/v{}/schema/codeint.schema.json",
102 env!("CARGO_PKG_VERSION")
103 )
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub(super) enum StarterKind {
108 Standard,
109 Adoption,
110}
111
112pub fn write_starter_configuration(
113 repository_root: &Path,
114 languages: &[DetectedLanguage],
115 boundaries: Option<&StarterBoundaries>,
116) -> Result<PathBuf, StarterConfigurationError> {
117 write_starter_configuration_in_format(repository_root, languages, boundaries, InitFormat::Jsonc)
118}
119
120pub fn write_starter_configuration_in_format(
121 repository_root: &Path,
122 languages: &[DetectedLanguage],
123 boundaries: Option<&StarterBoundaries>,
124 format: InitFormat,
125) -> Result<PathBuf, StarterConfigurationError> {
126 write_starter(
127 repository_root,
128 languages,
129 boundaries,
130 StarterKind::Standard,
131 format,
132 )
133}
134
135pub fn write_adoption_starter_configuration(
136 repository_root: &Path,
137 languages: &[DetectedLanguage],
138 boundaries: Option<&StarterBoundaries>,
139 format: InitFormat,
140) -> Result<PathBuf, StarterConfigurationError> {
141 write_starter(
142 repository_root,
143 languages,
144 boundaries,
145 StarterKind::Adoption,
146 format,
147 )
148}
149
150pub fn write_adoption_zero_budgets(
151 repository_root: &Path,
152 languages: &[DetectedLanguage],
153 boundaries: Option<&StarterBoundaries>,
154 recorded: &[MeasuredBaselineMetric],
155 format: InitFormat,
156) -> Result<PathBuf, StarterConfigurationError> {
157 let path = repository_root.join(format.file_name());
158 let text = starter_configuration_text_for_format(
159 languages,
160 boundaries,
161 StarterKind::Adoption,
162 &zero_budget_keys(recorded),
163 format,
164 );
165 std::fs::write(&path, text).map_err(|source| StarterConfigurationError::Unwritable {
166 path: path.clone(),
167 source,
168 })?;
169 Ok(path)
170}
171
172pub(super) struct ZeroBudgetKeys {
173 pub(super) production: Vec<&'static str>,
174 pub(super) test: Vec<&'static str>,
175 pub(super) dependencies: Vec<&'static str>,
176}
177
178impl ZeroBudgetKeys {
179 fn none() -> ZeroBudgetKeys {
180 ZeroBudgetKeys {
181 production: Vec::new(),
182 test: Vec::new(),
183 dependencies: Vec::new(),
184 }
185 }
186
187 fn insert_into(&self, json: &mut serde_json::Value) {
188 let root = json
189 .as_object_mut()
190 .expect("the starter configuration serializes to a JSON object");
191 let budgets = object_entry(root, "budgets");
192 for key in &self.dependencies {
193 budgets.insert((*key).to_owned(), serde_json::json!(0));
194 }
195 for (source_set, keys) in [("production", &self.production), ("test", &self.test)] {
196 let section = object_entry(budgets, source_set);
197 for key in keys {
198 section.insert((*key).to_owned(), serde_json::json!(0));
199 }
200 }
201 }
202}
203
204fn object_entry<'a>(
205 parent: &'a mut serde_json::Map<String, serde_json::Value>,
206 key: &str,
207) -> &'a mut serde_json::Map<String, serde_json::Value> {
208 let entry = parent
209 .entry(key.to_owned())
210 .or_insert_with(|| serde_json::json!({}));
211 if !entry.is_object() {
212 *entry = serde_json::json!({});
213 }
214 entry
215 .as_object_mut()
216 .expect("the entry was just made a JSON object")
217}
218
219fn zero_budget_keys(recorded: &[MeasuredBaselineMetric]) -> ZeroBudgetKeys {
220 let keys_in = |source_set: Option<SourceSet>| -> Vec<&'static str> {
221 Metric::ALL
222 .into_iter()
223 .filter(|metric| *metric != Metric::TestGap)
224 .filter(|metric| match source_set {
225 Some(source_set) => metric.scope().applies_to_source_set(source_set),
226 None => metric.scope() == MetricScope::RepositoryWide,
227 })
228 .map(Metric::key)
229 .filter(|key| {
230 recorded
231 .iter()
232 .any(|item| item.source_set == source_set && item.metric == *key)
233 })
234 .collect()
235 };
236 ZeroBudgetKeys {
237 production: keys_in(Some(SourceSet::Production)),
238 test: keys_in(Some(SourceSet::Test)),
239 dependencies: keys_in(None),
240 }
241}
242
243fn write_starter(
244 repository_root: &Path,
245 languages: &[DetectedLanguage],
246 boundaries: Option<&StarterBoundaries>,
247 kind: StarterKind,
248 format: InitFormat,
249) -> Result<PathBuf, StarterConfigurationError> {
250 for existing_kind in ConfigFileKind::ALL {
251 let existing_path = repository_root.join(existing_kind.file_name());
252 match std::fs::symlink_metadata(&existing_path) {
253 Ok(_) => {
254 return Err(StarterConfigurationError::AlreadyExists {
255 path: existing_path,
256 });
257 }
258 Err(error)
259 if matches!(
260 error.kind(),
261 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
262 ) => {}
263 Err(source) => {
264 return Err(StarterConfigurationError::Unwritable {
265 path: existing_path,
266 source,
267 });
268 }
269 }
270 }
271 let path = repository_root.join(format.file_name());
272 let text = starter_configuration_text_for_format(
273 languages,
274 boundaries,
275 kind,
276 &ZeroBudgetKeys::none(),
277 format,
278 );
279 let unwritable = |source| StarterConfigurationError::Unwritable {
280 path: path.clone(),
281 source,
282 };
283 let mut file = std::fs::OpenOptions::new()
284 .write(true)
285 .create_new(true)
286 .open(&path)
287 .map_err(|source| {
288 if source.kind() == std::io::ErrorKind::AlreadyExists {
289 StarterConfigurationError::AlreadyExists { path: path.clone() }
290 } else {
291 unwritable(source)
292 }
293 })?;
294 file.write_all(text.as_bytes())
295 .and_then(|()| file.flush())
296 .map_err(unwritable)?;
297 Ok(path)
298}
299
300#[cfg(test)]
301fn starter_configuration_text(languages: &[DetectedLanguage]) -> String {
302 starter_configuration_text_with_boundaries(
303 languages,
304 None,
305 StarterKind::Standard,
306 &ZeroBudgetKeys::none(),
307 )
308}
309
310fn starter_configuration_text_for_format(
311 languages: &[DetectedLanguage],
312 boundaries: Option<&StarterBoundaries>,
313 kind: StarterKind,
314 zero_budgets: &ZeroBudgetKeys,
315 format: InitFormat,
316) -> String {
317 let schema_address = published_schema_address();
318 match format {
319 InitFormat::Jsonc => starter_json_text(
320 &schema_address,
321 languages,
322 boundaries,
323 kind,
324 zero_budgets,
325 true,
326 ),
327 InitFormat::Json => starter_json_text(
328 &schema_address,
329 languages,
330 boundaries,
331 kind,
332 zero_budgets,
333 false,
334 ),
335 InitFormat::Toml => render_structured(
336 StructuredSyntax::Toml,
337 &schema_address,
338 languages,
339 boundaries,
340 kind,
341 zero_budgets,
342 ),
343 InitFormat::Yaml => render_structured(
344 StructuredSyntax::Yaml,
345 &schema_address,
346 languages,
347 boundaries,
348 kind,
349 zero_budgets,
350 ),
351 }
352}
353
354fn render_structured(
355 syntax: StructuredSyntax,
356 schema_address: &str,
357 languages: &[DetectedLanguage],
358 boundaries: Option<&StarterBoundaries>,
359 kind: StarterKind,
360 zero_budgets: &ZeroBudgetKeys,
361) -> String {
362 let language_pairs: Vec<(String, Vec<RepoPath>, Vec<String>)> = languages
363 .iter()
364 .map(|lang| {
365 (
366 lang.plugin.clone(),
367 lang.include.clone(),
368 lang.known_dialects.clone(),
369 )
370 })
371 .collect();
372 let zones: Option<Vec<(String, String)>> = match boundaries {
373 Some(StarterBoundaries::WorkspaceZones(zones)) => Some(
374 zones
375 .iter()
376 .map(|z| (z.name.clone(), z.pattern.clone()))
377 .collect(),
378 ),
379 _ => None,
380 };
381 let preset = match boundaries {
382 Some(StarterBoundaries::Preset(preset)) => Some(*preset),
383 _ => None,
384 };
385 let input = StarterRenderInput {
386 schema_address,
387 languages: &language_pairs,
388 boundary_zones: zones.as_deref(),
389 boundary_preset: preset,
390 adoption: kind == StarterKind::Adoption,
391 production_zeros: &zero_budgets.production,
392 test_zeros: &zero_budgets.test,
393 dependency_zeros: &zero_budgets.dependencies,
394 };
395 render_structured_starter(syntax, &input)
396}
397
398#[cfg(test)]
399fn starter_configuration_text_with_boundaries(
400 languages: &[DetectedLanguage],
401 boundaries: Option<&StarterBoundaries>,
402 kind: StarterKind,
403 zero_budgets: &ZeroBudgetKeys,
404) -> String {
405 starter_configuration_text_for_format(
406 languages,
407 boundaries,
408 kind,
409 zero_budgets,
410 InitFormat::Jsonc,
411 )
412}
413
414fn starter_json_text(
415 schema_address: &str,
416 languages: &[DetectedLanguage],
417 boundaries: Option<&StarterBoundaries>,
418 kind: StarterKind,
419 zero_budgets: &ZeroBudgetKeys,
420 with_comments: bool,
421) -> String {
422 let detected_languages = (!languages.is_empty()).then(|| {
423 languages
424 .iter()
425 .map(|language| {
426 LanguageGlobs::new(
427 language.plugin.clone(),
428 language
429 .include
430 .iter()
431 .map(|path| globset::escape(path.as_str()))
432 .collect(),
433 )
434 })
435 .collect()
436 });
437 let starter = match kind {
438 StarterKind::Standard => {
439 ConfigurationFile::starter(schema_address.to_owned(), detected_languages)
440 }
441 StarterKind::Adoption => {
442 ConfigurationFile::adoption_starter(schema_address.to_owned(), detected_languages)
443 }
444 };
445 let mut json = serde_json::to_value(&starter)
446 .expect("the configuration types serialize to JSON without fallible keys");
447 if let Some(root) = json.as_object_mut() {
448 root.insert("coverage_reports".to_owned(), serde_json::json!([]));
449 }
450 zero_budgets.insert_into(&mut json);
451 let rendered = format!("{json:#}\n");
452 if !with_comments {
453 return rendered;
454 }
455 add_jsonc_hints(rendered, languages, boundaries, kind, zero_budgets)
456}
457
458fn add_jsonc_hints(
459 rendered: String,
460 languages: &[DetectedLanguage],
461 boundaries: Option<&StarterBoundaries>,
462 kind: StarterKind,
463 zero_budgets: &ZeroBudgetKeys,
464) -> String {
465 let rendered = if zero_budgets.production.is_empty() {
466 rendered.replacen(
467 " \"budgets\": {\n \"production\": {},",
468 " \"budgets\": {\n \"production\": {\n // \"test_gap\": 0.2\n },",
469 1,
470 )
471 } else {
472 rendered.replacen(
473 " \"budgets\": {\n \"production\": {\n",
474 " \"budgets\": {\n \"production\": {\n // \"test_gap\": 0.2,\n",
475 1,
476 )
477 };
478 let mut trailing_hints = String::new();
479 if kind == StarterKind::Adoption {
480 trailing_hints.push_str(NEW_FILE_BUDGETS_HINT);
481 }
482 for language in languages
483 .iter()
484 .filter(|language| !language.known_dialects.is_empty())
485 {
486 let plugin_json = serde_json::Value::String(language.plugin.clone()).to_string();
487 let _ = writeln!(
488 trailing_hints,
489 " // Optional: map {} folders to a Dialect with dialects.{} ({}).",
490 language.plugin,
491 language.plugin,
492 language.known_dialects.join(", ")
493 );
494 let _ = writeln!(trailing_hints, " // \"dialects\": {{ {plugin_json}: [] }}");
495 }
496 if let Some(starter_boundaries) = boundaries {
497 render_commented_boundaries(&mut trailing_hints, starter_boundaries);
498 }
499 if !trailing_hints.is_empty()
500 && let Some(prefix) = rendered.strip_suffix("}\n")
501 {
502 return format!("{prefix}{trailing_hints}}}\n");
503 }
504 rendered
505}
506
507const NEW_FILE_BUDGETS_HINT: &str = " // Optional: uncomment to hold every new file to a strict bar in codeint diff (add a comma above).\n // \"new_file_budgets\": {\n // \"production\": {\n // \"erosion\": 0,\n // \"cognitive_complexity\": 0,\n // \"hazards\": 0,\n // \"boundaries\": 0\n // }\n // }\n";
508
509fn render_commented_boundaries(output: &mut String, boundaries: &StarterBoundaries) {
510 match boundaries {
511 StarterBoundaries::WorkspaceZones(zones) if !zones.is_empty() => {
512 output.push_str(
513 " // Optional: uncomment to enforce Import boundaries between discovered Workspace packages (add a comma above).\n",
514 );
515 output.push_str(" // \"boundaries\": {\n");
516 output.push_str(" // \"zones\": {\n");
517 for (index, zone) in zones.iter().enumerate() {
518 let name = serde_json::to_string(&zone.name).expect("strings serialize to JSON");
519 let pattern =
520 serde_json::to_string(&zone.pattern).expect("strings serialize to JSON");
521 let comma = if index + 1 < zones.len() { "," } else { "" };
522 let _ = writeln!(
523 output,
524 " // {name}: {{ \"patterns\": [{pattern}] }}{comma}"
525 );
526 }
527 output.push_str(" // },\n");
528 output.push_str(" // \"rules\": []\n");
529 output.push_str(" // }\n");
530 }
531 StarterBoundaries::WorkspaceZones(_) => {}
532 StarterBoundaries::Preset(preset) => {
533 let preset_name = preset.as_str();
534 let _ = writeln!(
535 output,
536 " // Optional: uncomment to enable the {preset_name} Import boundaries preset (add a comma above)."
537 );
538 let _ = writeln!(
539 output,
540 " // \"boundaries\": {{ \"preset\": \"{preset_name}\" }}"
541 );
542 }
543 }
544}