cucco 4.1.0

An interactive CLI for creating conventional commits, with git hooks support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Scope detection from staged paths and ast-grep rules.

#[cfg(feature = "ast-grep")]
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
#[cfg(feature = "ast-grep")]
use ast_grep_config::{GlobalRules, RuleCollection, RuleConfig};
#[cfg(feature = "ast-grep")]
use ast_grep_language::{LanguageExt, SupportLang};
use gix::Repository;
use gix::bstr::ByteSlice;
use gix::diff::index::ChangeRef;
use indexmap::IndexSet;
use regex::Regex;

use crate::config::Config;

/// A staged change to a single path, along with the blob id whose content
/// represents that change (the index-side blob for additions/modifications,
/// the HEAD-side blob for deletions).
struct StagedChange {
    path: PathBuf,
    #[cfg_attr(
        not(feature = "ast-grep"),
        expect(dead_code, reason = "only read by ast-grep detection")
    )]
    id: gix::ObjectId,
}

/// Scopes detected from the staged changes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScopeMatches {
    /// Names of every scope matched by a staged change.
    pub matches: Vec<String>,
}

impl ScopeMatches {
    /// The scope to pre-assign, but only when exactly one scope matched.
    /// With zero or multiple matches the choice is ambiguous, so callers
    /// fall back to prompting.
    pub fn suggested(&self) -> Option<&str> {
        match self.matches.as_slice() {
            [only] => Some(only),
            _ => None,
        }
    }
}

#[cfg(feature = "ast-grep")]
struct CompiledAstGrepRules {
    rules: RuleCollection<SupportLang>,
    ids_to_scope: HashMap<String, String>,
}

impl Config {
    /// Compile every scope's path patterns once, so detection doesn't recompile
    /// regexes for each staged file. Doubles as validation at config-load time.
    fn compile_scope_patterns(&self) -> Result<Vec<(&str, Vec<Regex>)>> {
        self.commit_scopes
            .iter()
            .filter(|(_, scope)| !scope.patterns.is_empty())
            .map(|(name, scope)| {
                let regexes = scope
                    .patterns
                    .iter()
                    .map(|pattern| {
                        Regex::new(pattern).with_context(|| {
                            format!("invalid scope path regex for `{name}`: `{pattern}`")
                        })
                    })
                    .collect::<Result<Vec<_>>>()?;
                Ok((name.as_str(), regexes))
            })
            .collect()
    }

    /// Checks that every configured scope path pattern is a valid regex.
    ///
    /// # Errors
    ///
    /// Returns an error naming the scope and pattern that failed to compile.
    pub fn validate_scope_patterns(&self) -> Result<()> {
        self.compile_scope_patterns().map(|_| ())
    }

    /// Checks that every configured ast-grep rule compiles.
    ///
    /// # Errors
    ///
    /// Returns an error if a rule is invalid.
    #[cfg(feature = "ast-grep")]
    pub fn validate_ast_grep_rules(&self) -> Result<()> {
        self.compile_ast_grep_rules().map(|_| ())
    }

    #[cfg(feature = "ast-grep")]
    fn compile_ast_grep_rules(&self) -> Result<CompiledAstGrepRules> {
        let globals = GlobalRules::default();
        let mut ids_to_scope = HashMap::new();
        let mut compiled_rules = Vec::new();

        for (index, (scope_name, scope)) in self.commit_scopes.iter().enumerate() {
            let Some(ast_grep) = &scope.ast_grep else {
                continue;
            };
            let mut serializable = ast_grep.clone();
            let id = if serializable.id.is_empty() {
                format!("{index:04}-{scope_name}")
            } else {
                format!("{index:04}-{}", serializable.id)
            };

            serializable.id = id.clone();
            ids_to_scope.insert(id, scope_name.clone());
            compiled_rules.push(RuleConfig::try_from(serializable, &globals)?);
        }

        Ok(CompiledAstGrepRules {
            rules: RuleCollection::try_new(compiled_rules)?,
            ids_to_scope,
        })
    }
}

/// Detects the scopes matched by the staged changes.
///
/// Path patterns are checked first, then ast-grep rules against the staged
/// blob contents.
///
/// # Errors
///
/// Returns an error if the staged changes cannot be read or a pattern or rule
/// is invalid.
pub fn detect_scope_matches(repo: &Repository, config: &Config) -> Result<ScopeMatches> {
    let changed = staged_changes(repo)?;
    if changed.is_empty() {
        return Ok(ScopeMatches::default());
    }

    let compiled_patterns = config.compile_scope_patterns()?;
    let pattern_scopes = changed
        .iter()
        .map(|change| normalize_relative_path(&change.path))
        .flat_map(|path| {
            compiled_patterns
                .iter()
                .filter(move |(_, regexes)| regexes.iter().any(|re| re.is_match(&path)))
                .map(|(scope_name, _)| scope_name.to_string())
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();

    #[cfg(feature = "ast-grep")]
    let ast_grep_scopes = detect_ast_grep_scopes(repo, config, &changed)?;
    #[cfg(not(feature = "ast-grep"))]
    let ast_grep_scopes = Vec::new();

    let matched_scopes: IndexSet<String> =
        pattern_scopes.into_iter().chain(ast_grep_scopes).collect();

    Ok(ScopeMatches {
        matches: matched_scopes.into_iter().collect(),
    })
}

fn staged_changes(repo: &Repository) -> Result<Vec<StagedChange>> {
    let index = repo.index_or_empty().context("could not read index")?;
    let head_tree_id = repo
        .head_tree_id_or_empty()
        .context("could not resolve HEAD tree")?;

    let mut changes: IndexSet<(PathBuf, gix::ObjectId)> = IndexSet::new();
    let mut record = |location: &gix::bstr::BStr, id: gix::ObjectId| {
        changes.insert((PathBuf::from(location.to_str_lossy().into_owned()), id));
    };
    repo.tree_index_status(
        &head_tree_id,
        &index,
        None,
        gix::status::tree_index::TrackRenames::Disabled,
        |change, _, _| {
            match change {
                ChangeRef::Addition { location, id, .. }
                | ChangeRef::Deletion { location, id, .. }
                | ChangeRef::Modification { location, id, .. } => {
                    record(&location, id.into_owned());
                }
                ChangeRef::Rewrite {
                    source_location,
                    source_id,
                    location,
                    id,
                    ..
                } => {
                    record(&source_location, source_id.into_owned());
                    record(&location, id.into_owned());
                }
            }

            Ok(gix::diff::index::Action::Continue(()))
        },
    )
    .context("could not diff HEAD tree against index")?;

    Ok(changes
        .into_iter()
        .map(|(path, id)| StagedChange { path, id })
        .collect())
}

fn normalize_relative_path(path: &Path) -> String {
    let path = path.to_string_lossy().replace('\\', "/");

    if path.starts_with('/') {
        path
    } else {
        format!("/{path}")
    }
}

#[cfg(feature = "ast-grep")]
fn detect_ast_grep_scopes(
    repo: &Repository,
    config: &Config,
    changed: &[StagedChange],
) -> Result<Vec<String>> {
    if config.commit_scopes.values().all(|s| s.ast_grep.is_none()) {
        return Ok(Vec::new());
    }

    let compiled_rules = config.compile_ast_grep_rules()?;

    let matched_scopes: IndexSet<String> = changed
        .iter()
        .flat_map(|change| {
            let applicable_rules = compiled_rules.rules.for_path(&change.path);
            if applicable_rules.is_empty() {
                return Vec::new();
            }
            let Ok(blob) = repo.find_blob(change.id) else {
                return Vec::new();
            };
            let Ok(source) = std::str::from_utf8(&blob.data) else {
                return Vec::new();
            };

            applicable_rules
                .into_iter()
                .filter(|rule| {
                    rule.language
                        .ast_grep(source)
                        .root()
                        .find(&rule.matcher)
                        .is_some()
                })
                .filter_map(|rule| compiled_rules.ids_to_scope.get(&rule.id).cloned())
                .collect()
        })
        .collect();

    Ok(matched_scopes.into_iter().collect())
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use indexmap::IndexMap;

    use super::*;
    use crate::config::CommitScope;

    fn empty_config(workdir: PathBuf) -> Config {
        Config {
            autocomplete: false,
            breaking_changes: false,
            commit_types: IndexMap::new(),
            commit_scopes: IndexMap::new(),
            emoji: false,
            issues: false,
            sign: false,
            force_config_scopes: false,
            allow_empty_scope: true,
            workdir,
        }
    }

    #[test]
    fn test_suggested_requires_exactly_one_match() {
        let matches = |names: &[&str]| ScopeMatches {
            matches: names.iter().map(|name| name.to_string()).collect(),
        };

        assert_eq!(matches(&[]).suggested(), None);
        assert_eq!(matches(&["core"]).suggested(), Some("core"));
        assert_eq!(matches(&["core", "build"]).suggested(), None);
    }

    #[test]
    fn test_normalize_relative_path() {
        assert_eq!(
            normalize_relative_path(Path::new("src/lib.rs")),
            "/src/lib.rs"
        );
        assert_eq!(
            normalize_relative_path(Path::new("/src/lib.rs")),
            "/src/lib.rs"
        );
    }

    fn config_with_patterns(patterns: Vec<String>) -> Config {
        let mut config = empty_config(PathBuf::from("."));
        config.commit_scopes.insert(
            "core".into(),
            CommitScope {
                name: "core".into(),
                description: None,
                patterns,
                #[cfg(feature = "ast-grep")]
                ast_grep: None,
            },
        );
        config
    }

    #[test]
    fn test_validate_scope_patterns_accepts_valid_regexes() {
        let config = config_with_patterns(vec![
            "^/crates/core/.*\\.rs$".into(),
            "^/src/.*\\.rs$".into(),
        ]);
        assert!(config.validate_scope_patterns().is_ok());
    }

    #[test]
    fn test_validate_scope_patterns_rejects_invalid_regex() {
        // An unbalanced group is not a valid regex.
        let config = config_with_patterns(vec!["^/src/(".into()]);
        let err = config.validate_scope_patterns().unwrap_err();
        assert!(err.to_string().contains("core"), "error names the scope");
    }

    #[test]
    fn test_detect_scope_matches_from_staged_paths() -> Result<(), Box<dyn Error>> {
        let tempdir = tempfile::tempdir()?;
        let repo = git2::Repository::init(tempdir.path())?;

        let mut index = repo.index()?;
        let tree_id = index.write_tree()?;
        let tree = repo.find_tree(tree_id)?;
        let sig = git2::Signature::now("Tester", "test@example.com")?;
        repo.commit(Some("HEAD"), &sig, &sig, "chore: initial", &tree, &[])?;

        let gix_repo = gix::discover(tempdir.path())?;

        std::fs::create_dir_all(tempdir.path().join("crates/core/src"))?;
        std::fs::write(
            tempdir.path().join("crates/core/src/lib.rs"),
            "pub fn core() {}\n",
        )?;

        let mut index = repo.index()?;
        index.add_path(Path::new("crates/core/src/lib.rs"))?;
        index.write()?;

        let mut config = empty_config(tempdir.path().to_path_buf());
        config.commit_scopes.insert(
            "core".into(),
            CommitScope {
                name: "core".into(),
                description: None,
                patterns: vec!["^/crates/core/.*\\.rs$".into()],
                #[cfg(feature = "ast-grep")]
                ast_grep: None,
            },
        );

        let matches = detect_scope_matches(&gix_repo, &config)?;
        assert_eq!(matches.suggested(), Some("core"));

        tempdir.close()?;
        Ok(())
    }

    #[cfg(feature = "ast-grep")]
    #[test]
    fn test_detect_scope_matches_from_ast_grep_rules() -> Result<(), Box<dyn Error>> {
        let tempdir = tempfile::tempdir()?;
        let repo = git2::Repository::init(tempdir.path())?;
        let gix_repo = gix::discover(tempdir.path())?;

        std::fs::create_dir_all(tempdir.path().join("src"))?;
        std::fs::write(
            tempdir.path().join("src/lib.rs"),
            "#[test]\nfn detects_test_scope() {}\n",
        )?;

        let mut index = repo.index()?;
        index.add_path(Path::new("src/lib.rs"))?;
        index.write()?;

        let mut config = empty_config(tempdir.path().to_path_buf());
        config
            .commit_scopes
            .insert("test".into(), function_scope("test", None));

        let matches = detect_scope_matches(&gix_repo, &config)?;
        assert_eq!(matches.suggested(), Some("test"));

        tempdir.close()?;
        Ok(())
    }

    #[cfg(feature = "ast-grep")]
    fn function_scope(name: &str, file_globs: Option<Vec<String>>) -> CommitScope {
        let files_yaml = match &file_globs {
            Some(globs) => {
                let items: Vec<String> = globs.iter().map(|g| format!("  - '{g}'")).collect();
                format!("files:\n{}\n", items.join("\n"))
            }
            None => String::new(),
        };
        let yaml = format!(
            "id: test-rule\nlanguage: Rust\nrule:\n  pattern: fn $NAME() {{}}\n{files_yaml}"
        );
        let ast_grep = ast_grep_config::from_str::<
            ast_grep_config::SerializableRuleConfig<SupportLang>,
        >(&yaml)
        .unwrap();

        CommitScope {
            name: name.into(),
            description: None,
            patterns: vec![],
            ast_grep: Some(ast_grep),
        }
    }

    #[cfg(feature = "ast-grep")]
    #[test]
    fn test_ast_grep_matches_staged_blob_not_worktree() -> Result<(), Box<dyn Error>> {
        let tempdir = tempfile::tempdir()?;
        let repo = git2::Repository::init(tempdir.path())?;
        let gix_repo = gix::discover(tempdir.path())?;

        std::fs::create_dir_all(tempdir.path().join("src"))?;
        std::fs::write(tempdir.path().join("src/lib.rs"), "fn matches() {}\n")?;

        let mut index = repo.index()?;
        index.add_path(Path::new("src/lib.rs"))?;
        index.write()?;

        // Overwrite the worktree copy with content that would NOT match
        // after staging, so the staged blob is the only thing that matches.
        std::fs::write(tempdir.path().join("src/lib.rs"), "no match here\n")?;

        let mut config = empty_config(tempdir.path().to_path_buf());
        config
            .commit_scopes
            .insert("test".into(), function_scope("test", None));

        let matches = detect_scope_matches(&gix_repo, &config)?;
        assert_eq!(
            matches.suggested(),
            Some("test"),
            "should match on staged content even though the worktree copy no longer matches"
        );

        tempdir.close()?;
        Ok(())
    }

    #[cfg(feature = "ast-grep")]
    #[test]
    fn test_ast_grep_ignores_unstaged_worktree_edits() -> Result<(), Box<dyn Error>> {
        let tempdir = tempfile::tempdir()?;
        let repo = git2::Repository::init(tempdir.path())?;
        let gix_repo = gix::discover(tempdir.path())?;

        std::fs::create_dir_all(tempdir.path().join("src"))?;
        std::fs::write(tempdir.path().join("src/lib.rs"), "no match here\n")?;

        let mut index = repo.index()?;
        index.add_path(Path::new("src/lib.rs"))?;
        index.write()?;

        // Edit the worktree copy to something that WOULD match, without staging it.
        std::fs::write(tempdir.path().join("src/lib.rs"), "fn matches() {}\n")?;

        let mut config = empty_config(tempdir.path().to_path_buf());
        config
            .commit_scopes
            .insert("test".into(), function_scope("test", None));

        let matches = detect_scope_matches(&gix_repo, &config)?;
        assert_eq!(
            matches.suggested(),
            None,
            "unstaged worktree edits must not influence scope detection"
        );

        tempdir.close()?;
        Ok(())
    }

    #[cfg(feature = "ast-grep")]
    #[test]
    fn test_ast_grep_matches_renamed_file_old_path_filter() -> Result<(), Box<dyn Error>> {
        let tempdir = tempfile::tempdir()?;
        let repo = git2::Repository::init(tempdir.path())?;

        std::fs::create_dir_all(tempdir.path().join("tests"))?;
        std::fs::write(tempdir.path().join("tests/a.rs"), "fn matches() {}\n")?;

        let mut index = repo.index()?;
        index.add_path(Path::new("tests/a.rs"))?;
        let tree_id = index.write_tree()?;
        index.write()?;
        let tree = repo.find_tree(tree_id)?;
        let sig = git2::Signature::now("Tester", "test@example.com")?;
        repo.commit(Some("HEAD"), &sig, &sig, "chore: initial", &tree, &[])?;

        // Stage a rename: remove the old path, add the new path with the same content.
        std::fs::create_dir_all(tempdir.path().join("src"))?;
        std::fs::rename(
            tempdir.path().join("tests/a.rs"),
            tempdir.path().join("src/a.rs"),
        )?;
        let mut index = repo.index()?;
        index.remove_path(Path::new("tests/a.rs"))?;
        index.add_path(Path::new("src/a.rs"))?;
        index.write()?;

        let gix_repo = gix::discover(tempdir.path())?;

        let mut config = empty_config(tempdir.path().to_path_buf());
        config.commit_scopes.insert(
            "test".into(),
            function_scope("test", Some(vec!["tests/**".into()])),
        );

        let matches = detect_scope_matches(&gix_repo, &config)?;
        assert_eq!(
            matches.suggested(),
            Some("test"),
            "a rule filtered on the old path should still match the renamed file's staged content"
        );

        tempdir.close()?;
        Ok(())
    }

    #[cfg(feature = "ast-grep")]
    #[test]
    fn test_ast_grep_matches_staged_deletion() -> Result<(), Box<dyn Error>> {
        let tempdir = tempfile::tempdir()?;
        let repo = git2::Repository::init(tempdir.path())?;

        std::fs::create_dir_all(tempdir.path().join("src"))?;
        std::fs::write(tempdir.path().join("src/lib.rs"), "fn matches() {}\n")?;

        let mut index = repo.index()?;
        index.add_path(Path::new("src/lib.rs"))?;
        let tree_id = index.write_tree()?;
        index.write()?;
        let tree = repo.find_tree(tree_id)?;
        let sig = git2::Signature::now("Tester", "test@example.com")?;
        repo.commit(Some("HEAD"), &sig, &sig, "chore: initial", &tree, &[])?;

        // Stage the deletion and remove the file from the worktree too.
        std::fs::remove_file(tempdir.path().join("src/lib.rs"))?;
        let mut index = repo.index()?;
        index.remove_path(Path::new("src/lib.rs"))?;
        index.write()?;

        let gix_repo = gix::discover(tempdir.path())?;

        let mut config = empty_config(tempdir.path().to_path_buf());
        config
            .commit_scopes
            .insert("test".into(), function_scope("test", None));

        let matches = detect_scope_matches(&gix_repo, &config)?;
        assert_eq!(
            matches.suggested(),
            Some("test"),
            "a staged deletion should still match against the removed content"
        );

        tempdir.close()?;
        Ok(())
    }
}