nils-git-cli 0.27.0

CLI crate for nils-git-cli in the nils-cli workspace.
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
use crate::clipboard;
use crate::commit_shared::{
    DiffNumstat, diff_numstat, git_output, git_status_code, git_stdout_trimmed_optional,
    is_lockfile, parse_name_status_z,
};
use anyhow::{Result, anyhow};
use nils_common::git::{self as common_git, GitContextError};
use serde_json::{Map, Number, Value};
use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::path::Path;
use time::OffsetDateTime;
use time::format_description;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OutputMode {
    Clipboard,
    Stdout,
    Both,
}

struct ContextJsonArgs {
    mode: OutputMode,
    pretty: bool,
    bundle: bool,
    out_dir: Option<String>,
    extra_args: Vec<String>,
}

enum ParseOutcome<T> {
    Continue(T),
    Exit(i32),
}

pub fn run(args: &[String]) -> i32 {
    match common_git::require_work_tree() {
        Ok(()) => {}
        Err(GitContextError::GitNotFound) => {
            eprintln!("❗ git is required but was not found in PATH.");
            return 1;
        }
        Err(GitContextError::NotRepository) => {
            eprintln!("❌ Not a git repository.");
            return 1;
        }
    }

    let parsed = match parse_args(args) {
        ParseOutcome::Continue(value) => value,
        ParseOutcome::Exit(code) => return code,
    };

    if !parsed.extra_args.is_empty() {
        eprintln!(
            "⚠️  Ignoring unknown arguments: {}",
            parsed.extra_args.join(" ")
        );
    }

    match git_status_code(&["diff", "--cached", "--quiet", "--exit-code"]) {
        Some(0) => {
            eprintln!("⚠️  No staged changes to record");
            return 1;
        }
        Some(1) => {}
        _ => {
            eprintln!("❌ Failed to check staged changes.");
            return 1;
        }
    }

    let out_dir = match resolve_out_dir(parsed.out_dir.as_deref()) {
        Ok(dir) => dir,
        Err(message) => {
            eprintln!("{message}");
            return 1;
        }
    };

    if fs::create_dir_all(&out_dir).is_err() {
        eprintln!("❌ Failed to create output directory: {out_dir}");
        return 1;
    }

    let patch_path = format!("{out_dir}/staged.patch");
    let manifest_path = format!("{out_dir}/commit-context.json");

    let patch_bytes = match git_output(&[
        "-c",
        "core.quotepath=false",
        "diff",
        "--cached",
        "--no-color",
    ]) {
        Ok(output) => output.stdout,
        Err(_) => {
            eprintln!("❌ Failed to write staged patch: {patch_path}");
            return 1;
        }
    };

    if fs::write(&patch_path, &patch_bytes).is_err() {
        eprintln!("❌ Failed to write staged patch: {patch_path}");
        return 1;
    }

    let json = match build_json(parsed.pretty) {
        Ok(value) => value,
        Err(err) => {
            eprintln!("{err:#}");
            return 1;
        }
    };

    if fs::write(&manifest_path, format!("{json}\n")).is_err() {
        eprintln!("❌ Failed to write JSON manifest: {manifest_path}");
        return 1;
    }

    let patch_text = String::from_utf8_lossy(&patch_bytes).to_string();

    match parsed.mode {
        OutputMode::Stdout => {
            print_bundle_or_json(&json, &patch_text, parsed.bundle);
            return 0;
        }
        OutputMode::Both => {
            print_bundle_or_json(&json, &patch_text, parsed.bundle);
        }
        OutputMode::Clipboard => {}
    }

    if parsed.bundle {
        let bundle = build_bundle(&json, &patch_text);
        let _ = clipboard::set_clipboard_best_effort(&bundle);
    } else {
        let _ = clipboard::set_clipboard_best_effort(&json);
    }

    if parsed.mode == OutputMode::Clipboard {
        println!("✅ JSON commit context copied to clipboard with:");
        if parsed.bundle {
            println!("  • Bundle (JSON + patch)");
        } else {
            println!("  • JSON manifest");
        }
        println!("  • Patch file written to: {patch_path}");
        println!("  • Manifest file written to: {manifest_path}");
    }

    0
}

fn parse_args(args: &[String]) -> ParseOutcome<ContextJsonArgs> {
    let mut mode = OutputMode::Clipboard;
    let mut pretty = false;
    let mut bundle = false;
    let mut out_dir: Option<String> = None;
    let mut extra_args: Vec<String> = Vec::new();

    let mut iter = args.iter().peekable();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--stdout" | "-p" | "--print" => mode = OutputMode::Stdout,
            "--both" => mode = OutputMode::Both,
            "--pretty" => pretty = true,
            "--bundle" => bundle = true,
            "--out-dir" => {
                let value = iter.next().map(|v| v.to_string()).unwrap_or_default();
                if value.is_empty() {
                    eprintln!("❌ Missing value for --out-dir");
                    return ParseOutcome::Exit(2);
                }
                out_dir = Some(value);
            }
            value if value.starts_with("--out-dir=") => {
                let value = value.trim_start_matches("--out-dir=").to_string();
                out_dir = Some(value);
            }
            "--help" | "-h" => {
                print_usage();
                return ParseOutcome::Exit(0);
            }
            other => extra_args.push(other.to_string()),
        }
    }

    ParseOutcome::Continue(ContextJsonArgs {
        mode,
        pretty,
        bundle,
        out_dir,
        extra_args,
    })
}

fn print_usage() {
    println!(
        "Usage: git-cli commit context-json [--stdout|--both] [--pretty] [--bundle] [--out-dir <path>]"
    );
    println!("  --stdout    Print to stdout only (JSON by default; bundle with --bundle)");
    println!(
        "  --both      Print to stdout and copy to clipboard (JSON by default; bundle with --bundle)"
    );
    println!("  --pretty    Pretty-print JSON (default is compact)");
    println!("  --bundle    Print/copy a single bundle (JSON + patch content)");
    println!("  --out-dir   Write files to this directory (default: <git-dir>/commit-context)");
}

fn resolve_out_dir(out_dir: Option<&str>) -> Result<String> {
    let trimmed = out_dir.map(|value| value.trim()).unwrap_or("");
    if !trimmed.is_empty() {
        return Ok(trimmed.trim_end_matches('/').to_string());
    }

    let git_dir = git_stdout_trimmed_optional(&["rev-parse", "--git-dir"]).unwrap_or_default();
    if git_dir.is_empty() {
        return Err(anyhow!("❌ Failed to resolve git dir."));
    }

    Ok(format!("{}/commit-context", git_dir.trim_end_matches('/')))
}

fn build_json(pretty: bool) -> Result<String> {
    let branch = git_stdout_trimmed_optional(&["symbolic-ref", "--quiet", "--short", "HEAD"]);
    let head = git_stdout_trimmed_optional(&["rev-parse", "--short", "HEAD"]);
    let repo_name =
        git_stdout_trimmed_optional(&["rev-parse", "--show-toplevel"]).and_then(|path| {
            Path::new(&path)
                .file_name()
                .and_then(|s| s.to_str())
                .map(|s| s.to_string())
        });
    let generated_at = generated_at();

    let name_status = git_output(&[
        "-c",
        "core.quotepath=false",
        "diff",
        "--cached",
        "--name-status",
        "-z",
    ])?;

    let entries = parse_name_status_z(&name_status.stdout)?;

    let mut status_counts: BTreeMap<String, i64> = BTreeMap::new();
    let mut top_dir_counts: BTreeMap<String, i64> = BTreeMap::new();

    let mut insertions: i64 = 0;
    let mut deletions: i64 = 0;
    let mut file_count: i64 = 0;
    let mut binary_file_count: i64 = 0;
    let mut lockfile_count: i64 = 0;
    let mut root_file_count: i64 = 0;

    let mut files: Vec<Value> = Vec::new();

    for entry in entries {
        file_count += 1;

        let status_letter = entry
            .status_raw
            .chars()
            .next()
            .map(|ch| ch.to_string())
            .unwrap_or_else(|| "".to_string());

        *status_counts.entry(status_letter.clone()).or_insert(0) += 1;

        if let Some((top, _)) = entry.path.split_once('/') {
            *top_dir_counts.entry(top.to_string()).or_insert(0) += 1;
        } else {
            root_file_count += 1;
        }

        let lockfile = is_lockfile(&entry.path);
        if lockfile {
            lockfile_count += 1;
        }

        let diff = diff_numstat(&entry.path).unwrap_or(DiffNumstat {
            added: None,
            deleted: None,
            binary: false,
        });

        if diff.binary {
            binary_file_count += 1;
        } else {
            if let Some(n) = diff.added {
                insertions += n;
            }
            if let Some(n) = diff.deleted {
                deletions += n;
            }
        }

        let mut file_obj = Map::new();
        file_obj.insert("path".to_string(), Value::String(entry.path.clone()));
        file_obj.insert("status".to_string(), Value::String(status_letter));

        if entry.status_raw.len() > 1 {
            let score_raw = &entry.status_raw[1..];
            if let Ok(score) = score_raw.parse::<i64>() {
                file_obj.insert("score".to_string(), Value::Number(Number::from(score)));
            }
        }

        if let Some(old_path) = entry.old_path.as_ref() {
            file_obj.insert("oldPath".to_string(), Value::String(old_path.clone()));
        }

        if diff.binary {
            file_obj.insert("insertions".to_string(), Value::Null);
            file_obj.insert("deletions".to_string(), Value::Null);
        } else {
            match diff.added {
                Some(n) => {
                    file_obj.insert("insertions".to_string(), Value::Number(Number::from(n)));
                }
                None => {
                    file_obj.insert("insertions".to_string(), Value::Null);
                }
            }
            match diff.deleted {
                Some(n) => {
                    file_obj.insert("deletions".to_string(), Value::Number(Number::from(n)));
                }
                None => {
                    file_obj.insert("deletions".to_string(), Value::Null);
                }
            }
        }

        file_obj.insert("binary".to_string(), Value::Bool(diff.binary));
        file_obj.insert("lockfile".to_string(), Value::Bool(lockfile));

        files.push(Value::Object(file_obj));
    }

    let status_counts_values: Vec<Value> = status_counts
        .into_iter()
        .map(|(status, count)| {
            let mut obj = Map::new();
            obj.insert("status".to_string(), Value::String(status));
            obj.insert("count".to_string(), Value::Number(Number::from(count)));
            Value::Object(obj)
        })
        .collect();

    let top_dir_values: Vec<Value> = top_dir_counts
        .into_iter()
        .map(|(name, count)| {
            let mut obj = Map::new();
            obj.insert("name".to_string(), Value::String(name));
            obj.insert("count".to_string(), Value::Number(Number::from(count)));
            Value::Object(obj)
        })
        .collect();

    let mut summary = Map::new();
    summary.insert(
        "fileCount".to_string(),
        Value::Number(Number::from(file_count)),
    );
    summary.insert(
        "insertions".to_string(),
        Value::Number(Number::from(insertions)),
    );
    summary.insert(
        "deletions".to_string(),
        Value::Number(Number::from(deletions)),
    );
    summary.insert(
        "binaryFileCount".to_string(),
        Value::Number(Number::from(binary_file_count)),
    );
    summary.insert(
        "lockfileCount".to_string(),
        Value::Number(Number::from(lockfile_count)),
    );
    summary.insert(
        "rootFileCount".to_string(),
        Value::Number(Number::from(root_file_count)),
    );
    summary.insert(
        "topLevelDirCount".to_string(),
        Value::Number(Number::from(top_dir_values.len() as i64)),
    );

    let mut staged = Map::new();
    staged.insert("summary".to_string(), Value::Object(summary));
    staged.insert(
        "statusCounts".to_string(),
        Value::Array(status_counts_values),
    );

    let mut structure = Map::new();
    structure.insert("topLevelDirs".to_string(), Value::Array(top_dir_values));
    staged.insert("structure".to_string(), Value::Object(structure));
    staged.insert("files".to_string(), Value::Array(files));

    let mut patch = Map::new();
    patch.insert(
        "path".to_string(),
        Value::String("staged.patch".to_string()),
    );
    patch.insert(
        "format".to_string(),
        Value::String("git diff --cached".to_string()),
    );
    staged.insert("patch".to_string(), Value::Object(patch));

    let mut repo = Map::new();
    repo.insert(
        "name".to_string(),
        repo_name.map(Value::String).unwrap_or(Value::Null),
    );

    let mut git = Map::new();
    git.insert(
        "branch".to_string(),
        branch.map(Value::String).unwrap_or(Value::Null),
    );
    git.insert(
        "head".to_string(),
        head.map(Value::String).unwrap_or(Value::Null),
    );

    let mut root = Map::new();
    root.insert("schemaVersion".to_string(), Value::Number(Number::from(1)));
    root.insert(
        "generatedAt".to_string(),
        generated_at.map(Value::String).unwrap_or(Value::Null),
    );
    root.insert("repo".to_string(), Value::Object(repo));
    root.insert("git".to_string(), Value::Object(git));
    root.insert("staged".to_string(), Value::Object(staged));

    let value = Value::Object(root);

    if pretty {
        Ok(serde_json::to_string_pretty(&value)?)
    } else {
        Ok(serde_json::to_string(&value)?)
    }
}

fn generated_at() -> Option<String> {
    if env::var("GIT_CLI_FIXTURE_DATE_MODE").ok().as_deref() == Some("fixed") {
        return Some("2000-01-02T03:04:05Z".to_string());
    }

    let format =
        format_description::parse("[year]-[month]-[day]T[hour]:[minute]:[second]Z").ok()?;
    OffsetDateTime::now_utc().format(&format).ok()
}

fn print_bundle_or_json(json: &str, patch_text: &str, bundle: bool) {
    if bundle {
        print!("{}", build_bundle(json, patch_text));
    } else {
        println!("{json}");
    }
}

fn build_bundle(json: &str, patch_text: &str) -> String {
    let mut out = String::new();
    out.push_str("===== commit-context.json =====\n");
    out.push_str(json);
    out.push('\n');
    out.push('\n');
    out.push_str("===== staged.patch =====\n");
    out.push_str(patch_text);
    out
}