wsb 0.275.7622

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
use crate::fleet::error::{Result, SuperGitError};
use crate::fleet::git::SubmoduleTree;
use crate::fleet::output::Formatter;
use crate::prelude::*;
use chrono::{DateTime, Duration, Utc};
use std::fs;
use std::io::Write;

const EMPTY_TREE_OID: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/// Reserved subdirectory holding the superproject's own diffs.
const SUPERPROJECT_OUTDIR: &str = "_superproject";

/// Run a git command in the given working directory, capturing stdout.
fn git(repo_path: &Path, args: &[&str]) -> Result<String> {
    let output = crate::git_backend::git_command()
        .args(args)
        .current_dir(repo_path)
        .output()
        .map_err(|e| SuperGitError::Other(format!("Failed to execute git: {}", e)))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SuperGitError::Other(format!(
            "git {} failed: {}",
            args.join(" "),
            stderr.trim()
        )));
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum DiffBase {
    Explicit(String),
    Since(String),
}

impl DiffBase {
    fn as_ref(&self) -> &str {
        match self {
            Self::Explicit(base) | Self::Since(base) => base,
        }
    }
}

fn parse_since_duration(input: &str) -> Result<Duration> {
    if input.len() < 2 {
        return Err(SuperGitError::Other(format!(
            "Invalid --since value '{}'. Expected formats like 2d, 4h, 30m, 15s, or 1w",
            input
        )));
    }

    let (number, unit) = input.split_at(input.len() - 1);
    let value: i64 = number.parse().map_err(|_| {
        SuperGitError::Other(format!(
            "Invalid --since value '{}'. Expected a positive integer followed by s, m, h, d, or w",
            input
        ))
    })?;

    if value <= 0 {
        return Err(SuperGitError::Other(format!(
            "Invalid --since value '{}'. Duration must be greater than zero",
            input
        )));
    }

    let duration = match unit {
        "s" => Duration::seconds(value),
        "m" => Duration::minutes(value),
        "h" => Duration::hours(value),
        "d" => Duration::days(value),
        "w" => Duration::weeks(value),
        _ => {
            return Err(SuperGitError::Other(format!(
                "Invalid --since unit '{}'. Supported units: s, m, h, d, w",
                unit
            )));
        }
    };

    Ok(duration)
}

fn resolve_since_base(repo_path: &Path, since: &str) -> Result<DiffBase> {
    let cutoff: DateTime<Utc> = Utc::now() - parse_since_duration(since)?;
    let cutoff_arg = format!("--before={}", cutoff.to_rfc3339());
    let stdout = git(repo_path, &["rev-list", "-1", &cutoff_arg, "HEAD"])?;
    let base = stdout.trim();

    if base.is_empty() {
        Ok(DiffBase::Since(EMPTY_TREE_OID.to_string()))
    } else {
        Ok(DiffBase::Since(base.to_string()))
    }
}

fn resolve_diff_base(
    repo_path: &Path,
    base: Option<&str>,
    since: Option<&str>,
) -> Result<Option<DiffBase>> {
    match (base, since) {
        (Some(base_ref), None) => Ok(Some(DiffBase::Explicit(base_ref.to_string()))),
        (None, Some(since_value)) => resolve_since_base(repo_path, since_value).map(Some),
        (None, None) => Ok(None),
        (Some(_), Some(_)) => Err(SuperGitError::Other(
            "--base and --since cannot be used together".to_string(),
        )),
    }
}

/// List files changed between index and worktree (unstaged changes).
fn unstaged_changed_files(repo_path: &Path) -> Result<Vec<String>> {
    let stdout = git(repo_path, &["diff", "--name-only"])?;
    Ok(stdout
        .lines()
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
        .collect())
}

/// List files changed between HEAD and index (staged changes).
fn staged_changed_files(repo_path: &Path) -> Result<Vec<String>> {
    let stdout = git(repo_path, &["diff", "--cached", "--name-only"])?;
    Ok(stdout
        .lines()
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
        .collect())
}

/// List files changed between a base ref and HEAD.
fn changed_files_against_base(repo_path: &Path, base_ref: &str) -> Result<Vec<String>> {
    let stdout = git(repo_path, &["diff", "--name-only", base_ref])?;
    Ok(stdout
        .lines()
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
        .collect())
}

/// Get the diff for a single file: index vs worktree (unstaged).
fn diff_index_to_worktree(repo_path: &Path, file: &str) -> Result<String> {
    let output = crate::git_backend::git_command()
        .args(["diff", "--", file])
        .current_dir(repo_path)
        .output()
        .map_err(|e| SuperGitError::Other(format!("Failed to execute git diff: {}", e)))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SuperGitError::Other(format!(
            "git diff -- {} failed: {}",
            file,
            stderr.trim()
        )));
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Get the diff for a single file: HEAD vs index (staged).
fn diff_head_to_index(repo_path: &Path, file: &str) -> Result<String> {
    let output = crate::git_backend::git_command()
        .args(["diff", "--cached", "--", file])
        .current_dir(repo_path)
        .output()
        .map_err(|e| SuperGitError::Other(format!("Failed to execute git diff --cached: {}", e)))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SuperGitError::Other(format!(
            "git diff --cached -- {} failed: {}",
            file,
            stderr.trim()
        )));
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Get the diff for a single file between a base ref and HEAD.
fn diff_against_base(repo_path: &Path, base_ref: &str, file: &str) -> Result<String> {
    let output = crate::git_backend::git_command()
        .args(["diff", base_ref, "--", file])
        .current_dir(repo_path)
        .output()
        .map_err(|e| {
            SuperGitError::Other(format!("Failed to execute git diff {}: {}", base_ref, e))
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SuperGitError::Other(format!(
            "git diff {} -- {} failed: {}",
            base_ref,
            file,
            stderr.trim()
        )));
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

fn write_diff_file(outdir: &Path, file: &str, diff: &str, append: bool) -> Result<()> {
    let diff_path = outdir.join(format!("{}.diff", file));
    if let Some(parent) = diff_path.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            SuperGitError::Other(format!(
                "Failed to create directory '{}': {}",
                parent.display(),
                e
            ))
        })?;
    }

    if append {
        let mut f = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&diff_path)
            .map_err(|e| {
                SuperGitError::Other(format!(
                    "Failed to open '{}' for appending: {}",
                    diff_path.display(),
                    e
                ))
            })?;
        f.write_all(diff.as_bytes()).map_err(|e| {
            SuperGitError::Other(format!(
                "Failed to write to '{}': {}",
                diff_path.display(),
                e
            ))
        })?;
    } else {
        fs::write(&diff_path, diff).map_err(|e| {
            SuperGitError::Other(format!("Failed to write '{}': {}", diff_path.display(), e))
        })?;
    }

    Ok(())
}

/// Generate per-file diff files for a single git repo.
///
/// Behavior mirrors the bash `gitdiff_per_file` function:
/// - No base: diffs unstaged changes. With `--staged`, also appends staged diffs.
/// - With base: diffs against the given base ref (commit, branch, tag).
///
/// Each changed file `path/to/file.rs` gets a corresponding `outdir/path/to/file.rs.diff`.
pub fn generate_per_file_diffs(
    repo_path: &Path,
    base: Option<&str>,
    since: Option<&str>,
    outdir: &Path,
    include_staged: bool,
) -> Result<Vec<String>> {
    let mut written_files: Vec<String> = Vec::new();
    let resolved_base = resolve_diff_base(repo_path, base, since)?;

    match resolved_base.as_ref() {
        Some(base_ref) => {
            let base_ref = base_ref.as_ref();
            let names = changed_files_against_base(repo_path, base_ref)?;
            for file in &names {
                let diff = diff_against_base(repo_path, base_ref, file)?;
                if !diff.is_empty() {
                    write_diff_file(outdir, file, &diff, false)?;
                    written_files.push(file.clone());
                }
            }
        }
        None => {
            let names = unstaged_changed_files(repo_path)?;
            for file in &names {
                let diff = diff_index_to_worktree(repo_path, file)?;
                if !diff.is_empty() {
                    write_diff_file(outdir, file, &diff, false)?;
                    written_files.push(file.clone());
                }
            }

            if include_staged {
                let staged_names = staged_changed_files(repo_path)?;
                for file in &staged_names {
                    let diff = diff_head_to_index(repo_path, file)?;
                    if !diff.is_empty() {
                        let is_append = written_files.contains(file);
                        write_diff_file(outdir, file, &diff, is_append)?;
                        if !written_files.contains(file) {
                            written_files.push(file.clone());
                        }
                    }
                }
            }
        }
    }

    Ok(written_files)
}

/// Fleet diff: generate per-file diffs for superproject + all submodules.
/// Superproject diffs go into `outdir/_superproject/`.
/// Each submodule's diffs go into `outdir/<submodule_name>/`.
pub fn execute<P: AsRef<Path>>(
    repo_root: P,
    base: Option<&str>,
    since: Option<&str>,
    outdir: &str,
    include_staged: bool,
    clean: bool,
    verbose: bool,
) -> Result<()> {
    let repo_root = repo_root.as_ref();
    let tree = SubmoduleTree::discover_allow_empty(repo_root)?;
    let outdir_path = Path::new(outdir);

    // Submodule diffs are written to `outdir/<path from root>`, which mirrors the
    // nesting and keeps same-named submodules at different depths apart. The
    // superproject's own reserved directory must not be shadowed by a submodule.
    if let Some(node) = tree
        .top_down()
        .iter()
        .find(|node| node.display_path == SUPERPROJECT_OUTDIR)
    {
        return Err(SuperGitError::Other(format!(
            "Submodule '{}' would collide with the reserved '{}' output directory; \
             pass a different --output directory or rename the submodule path",
            node.label(),
            SUPERPROJECT_OUTDIR
        )));
    }

    if clean && outdir_path.exists() {
        fs::remove_dir_all(outdir_path).map_err(|e| {
            SuperGitError::Other(format!(
                "Failed to remove '{}': {}",
                outdir_path.display(),
                e
            ))
        })?;
    }

    Formatter::print_info(&format!(
        "Generating per-file diffs for superproject + {} submodule(s) into '{}'",
        tree.len(),
        outdir
    ));

    let mut total_files = 0;
    let mut failed = 0;

    // Superproject
    {
        let super_outdir = outdir_path.join(SUPERPROJECT_OUTDIR);
        if verbose {
            Formatter::print_submodule_header("[SUPERPROJECT]");
        }
        match generate_per_file_diffs(repo_root, base, since, &super_outdir, include_staged) {
            Ok(files) => {
                if files.is_empty() {
                    if verbose {
                        Formatter::print_info("No changes");
                    }
                } else {
                    Formatter::print_success(&format!(
                        "Superproject: {} diff file(s) written",
                        files.len()
                    ));
                    total_files += files.len();
                }
            }
            Err(e) => {
                Formatter::print_error(&format!("Superproject diff failed: {}", e));
                failed += 1;
            }
        }
    }

    // Submodules, at every depth
    for node in tree.top_down() {
        if !node.initialized {
            Formatter::print_warning(&format!(
                "Submodule '{}' not initialized, skipping",
                node.label()
            ));
            continue;
        }

        let sub_outdir = outdir_path.join(&node.display_path);
        if verbose {
            Formatter::print_submodule_header(node.label());
        }

        match generate_per_file_diffs(&node.abs_path, base, since, &sub_outdir, include_staged) {
            Ok(files) => {
                if files.is_empty() {
                    if verbose {
                        Formatter::print_info(&format!("No changes in '{}'", node.label()));
                    }
                } else {
                    Formatter::print_success(&format!(
                        "'{}': {} diff file(s) written",
                        node.label(),
                        files.len()
                    ));
                    total_files += files.len();
                }
            }
            Err(e) => {
                Formatter::print_error(&format!("Diff failed for '{}': {}", node.label(), e));
                failed += 1;
            }
        }
    }

    if total_files > 0 || failed == 0 {
        Formatter::print_success(&format!(
            "Total: {} diff file(s) written to '{}'",
            total_files, outdir
        ));
    }

    if failed > 0 {
        return Err(SuperGitError::Other(format!(
            "{} repo(s) failed to generate diffs",
            failed
        )));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::parse_since_duration;

    #[test]
    fn parse_since_duration_supports_expected_units() {
        assert_eq!(parse_since_duration("15s").unwrap().num_seconds(), 15);
        assert_eq!(parse_since_duration("30m").unwrap().num_minutes(), 30);
        assert_eq!(parse_since_duration("2h").unwrap().num_hours(), 2);
        assert_eq!(parse_since_duration("3d").unwrap().num_days(), 3);
        assert_eq!(parse_since_duration("2w").unwrap().num_weeks(), 2);
    }

    #[test]
    fn parse_since_duration_rejects_invalid_values() {
        assert!(parse_since_duration("0d").is_err());
        assert!(parse_since_duration("abc").is_err());
        assert!(parse_since_duration("10x").is_err());
    }
}