wsb 0.85.227722

Workspace - A tool suite for file operations, version management, and development workflow automation
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
use crate::fleet::config::GitModules;
use crate::fleet::error::{Result, SuperGitError};
use crate::fleet::git::GitOps;
use crate::fleet::output::Formatter;
use std::path::{Path, PathBuf};
use std::process::Command;

/// A single action taken during the merge-back process, for audit trail.
#[derive(Debug)]
struct Action {
    repo_name: String,
    description: String,
    succeeded: bool,
}

/// Tracks everything the merge-back does for chronological replay on failure.
struct AuditLog {
    actions: Vec<Action>,
}

impl AuditLog {
    fn new() -> Self {
        Self {
            actions: Vec::new(),
        }
    }

    fn record(&mut self, repo_name: &str, description: &str, succeeded: bool) {
        self.actions.push(Action {
            repo_name: repo_name.to_string(),
            description: description.to_string(),
            succeeded,
        });
    }

    fn print_and_fail(&self, final_error: &str) -> SuperGitError {
        eprintln!();
        Formatter::print_error("Merge-back failed. Chronological action log:");
        eprintln!();
        for (i, action) in self.actions.iter().enumerate() {
            let symbol = if action.succeeded { "✓" } else { "✗" };
            let color_symbol = if action.succeeded {
                format!("\x1b[32m{}\x1b[0m", symbol) // green
            } else {
                format!("\x1b[31m{}\x1b[0m", symbol) // red
            };
            eprintln!(
                "  {:>3}. {} [{}] {}",
                i + 1,
                color_symbol,
                action.repo_name,
                action.description,
            );
        }
        eprintln!();
        SuperGitError::Other(final_error.to_string())
    }
}

/// Info collected about each repo during pre-flight.
struct RepoInfo {
    name: String,
    path: PathBuf,
    current_branch: String,
    main_branch: String,
}

pub fn execute<P: AsRef<Path>>(
    repo_root: P,
    message: &str,
    dry_run: bool,
    verbose: bool,
) -> Result<()> {
    let repo_root = repo_root.as_ref();
    let gitmodules = GitModules::parse(repo_root)?;

    Formatter::print_info(&format!(
        "Merge-back: superproject + {} submodule(s)",
        gitmodules.submodules.len()
    ));

    // ── Phase 1: Pre-flight checks ──────────────────────────────────────
    Formatter::print_info("Running pre-flight checks...");

    let mut repos: Vec<RepoInfo> = Vec::new();

    // Check superproject
    {
        let super_repo = GitOps::open_repo(repo_root)?;

        if GitOps::is_detached_head(&super_repo)? {
            return Err(SuperGitError::Other(
                "Superproject is in detached HEAD state".to_string(),
            ));
        }

        let current_branch = GitOps::current_branch(&super_repo)?;
        let main_branch = GitOps::get_default_branch(&super_repo)?;

        if current_branch == main_branch {
            return Err(SuperGitError::Other(format!(
                "Superproject is already on '{}'. Merge-back requires being on a feature branch.",
                main_branch
            )));
        }

        // Verify main branch exists (get_default_branch already does this, but be explicit)
        if !GitOps::branch_exists(&super_repo, &main_branch)? {
            return Err(SuperGitError::Other(format!(
                "Superproject has no '{}' branch",
                main_branch
            )));
        }

        if verbose {
            Formatter::print_info(&format!(
                "Superproject: on '{}', will merge into '{}'",
                current_branch, main_branch
            ));
        }

        repos.push(RepoInfo {
            name: "[SUPERPROJECT]".to_string(),
            path: repo_root.to_path_buf(),
            current_branch,
            main_branch,
        });
    }

    // Check each submodule
    for submodule in &gitmodules.submodules {
        let submodule_path = repo_root.join(&submodule.path);

        if !submodule_path.exists() {
            return Err(SuperGitError::Other(format!(
                "Submodule '{}' is not initialized. All submodules must be initialized for merge-back.",
                submodule.name
            )));
        }

        let sub_repo = GitOps::open_repo(&submodule_path)?;

        if GitOps::is_detached_head(&sub_repo)? {
            return Err(SuperGitError::Other(format!(
                "Submodule '{}' is in detached HEAD state",
                submodule.name
            )));
        }

        let current_branch = GitOps::current_branch(&sub_repo)?;
        let main_branch = GitOps::get_default_branch(&sub_repo)?;

        if current_branch == main_branch {
            return Err(SuperGitError::Other(format!(
                "Submodule '{}' is already on '{}'. Merge-back requires all repos to be on a feature branch.",
                submodule.name, main_branch
            )));
        }

        if !GitOps::branch_exists(&sub_repo, &main_branch)? {
            return Err(SuperGitError::Other(format!(
                "Submodule '{}' has no '{}' branch",
                submodule.name, main_branch
            )));
        }

        if verbose {
            Formatter::print_info(&format!(
                "'{}': on '{}', will merge into '{}'",
                submodule.name, current_branch, main_branch
            ));
        }

        repos.push(RepoInfo {
            name: submodule.name.clone(),
            path: submodule_path,
            current_branch,
            main_branch,
        });
    }

    Formatter::print_success(&format!(
        "Pre-flight passed for {} repo(s)",
        repos.len()
    ));

    if dry_run {
        Formatter::print_warning("DRY RUN: No changes will be made");
        println!();
        Formatter::print_info("Merge-back plan:");
        for repo in &repos {
            println!(
                "  {} [{}] '{}' → checkout '{}' → merge --ff-only '{}' → push",
                "→".cyan(),
                repo.name,
                repo.current_branch,
                repo.main_branch,
                repo.current_branch,
            );
        }
        return Ok(());
    }

    // ── Phase 2: Stage, commit, push all repos on current branch ────────
    let mut log = AuditLog::new();

    // Stage and commit all repos
    for repo_info in &repos {
        let repo = GitOps::open_repo(&repo_info.path).map_err(|e| {
            log.record(&repo_info.name, &format!("Open repo: {}", e), false);
            log.print_and_fail(&format!("Failed to open '{}'", repo_info.name))
        })?;

        let is_clean = GitOps::is_clean(&repo).map_err(|e| {
            log.record(&repo_info.name, &format!("Check clean: {}", e), false);
            log.print_and_fail(&format!("Failed to check status of '{}'", repo_info.name))
        })?;

        if !is_clean {
            // Stage
            let add_output = Command::new("git")
                .arg("add")
                .arg("-A")
                .current_dir(&repo_info.path)
                .output()
                .map_err(|e| {
                    log.record(&repo_info.name, &format!("Stage (git add -A): {}", e), false);
                    log.print_and_fail(&format!("Failed to stage in '{}'", repo_info.name))
                })?;

            if !add_output.status.success() {
                let err = String::from_utf8_lossy(&add_output.stderr);
                log.record(&repo_info.name, &format!("Stage (git add -A): {}", err), false);
                return Err(log.print_and_fail(&format!("Failed to stage in '{}'", repo_info.name)));
            }
            log.record(&repo_info.name, "Staged all changes (git add -A)", true);

            // Commit
            let commit_output = Command::new("git")
                .arg("commit")
                .arg("-m")
                .arg(message)
                .current_dir(&repo_info.path)
                .output()
                .map_err(|e| {
                    log.record(&repo_info.name, &format!("Commit: {}", e), false);
                    log.print_and_fail(&format!("Failed to commit in '{}'", repo_info.name))
                })?;

            if !commit_output.status.success() {
                let stderr = String::from_utf8_lossy(&commit_output.stderr);
                if !stderr.contains("nothing to commit") && !stderr.contains("nothing added") {
                    log.record(&repo_info.name, &format!("Commit: {}", stderr), false);
                    return Err(log.print_and_fail(&format!("Failed to commit in '{}'", repo_info.name)));
                }
                log.record(&repo_info.name, "Nothing to commit (clean after staging)", true);
            } else {
                log.record(
                    &repo_info.name,
                    &format!("Committed on '{}': {}", repo_info.current_branch, message),
                    true,
                );
            }
        } else {
            log.record(&repo_info.name, "Already clean, no commit needed", true);
        }
    }

    // Push all repos
    for repo_info in &repos {
        let push_output = Command::new("git")
            .arg("push")
            .arg("--set-upstream")
            .arg("origin")
            .arg("HEAD")
            .current_dir(&repo_info.path)
            .output()
            .map_err(|e| {
                log.record(&repo_info.name, &format!("Push: {}", e), false);
                log.print_and_fail(&format!("Failed to push '{}'", repo_info.name))
            })?;

        if !push_output.status.success() {
            let stderr = String::from_utf8_lossy(&push_output.stderr);
            if stderr.contains("Everything up-to-date") || stderr.contains("up to date") {
                log.record(&repo_info.name, "Push: already up to date", true);
            } else {
                log.record(&repo_info.name, &format!("Push: {}", stderr), false);
                return Err(log.print_and_fail(&format!("Failed to push '{}'", repo_info.name)));
            }
        } else {
            log.record(
                &repo_info.name,
                &format!("Pushed '{}' to origin", repo_info.current_branch),
                true,
            );
        }
    }

    // ── Phase 3: Checkout main in all repos ─────────────────────────────
    for repo_info in &repos {
        let checkout_output = Command::new("git")
            .arg("checkout")
            .arg(&repo_info.main_branch)
            .current_dir(&repo_info.path)
            .output()
            .map_err(|e| {
                log.record(
                    &repo_info.name,
                    &format!("Checkout '{}': {}", repo_info.main_branch, e),
                    false,
                );
                log.print_and_fail(&format!(
                    "Failed to checkout '{}' in '{}'",
                    repo_info.main_branch, repo_info.name
                ))
            })?;

        if !checkout_output.status.success() {
            let stderr = String::from_utf8_lossy(&checkout_output.stderr);
            log.record(
                &repo_info.name,
                &format!("Checkout '{}': {}", repo_info.main_branch, stderr),
                false,
            );
            return Err(log.print_and_fail(&format!(
                "Failed to checkout '{}' in '{}'",
                repo_info.main_branch, repo_info.name
            )));
        }
        log.record(
            &repo_info.name,
            &format!("Checked out '{}'", repo_info.main_branch),
            true,
        );
    }

    // ── Phase 4: Fast-forward merge from feature branch ─────────────────
    for repo_info in &repos {
        let merge_output = Command::new("git")
            .arg("merge")
            .arg("--ff-only")
            .arg(&repo_info.current_branch)
            .current_dir(&repo_info.path)
            .output()
            .map_err(|e| {
                log.record(
                    &repo_info.name,
                    &format!(
                        "Merge --ff-only '{}' into '{}': {}",
                        repo_info.current_branch, repo_info.main_branch, e
                    ),
                    false,
                );
                log.print_and_fail(&format!(
                    "Failed to merge '{}' into '{}' in '{}'",
                    repo_info.current_branch, repo_info.main_branch, repo_info.name
                ))
            })?;

        if !merge_output.status.success() {
            let stderr = String::from_utf8_lossy(&merge_output.stderr);
            log.record(
                &repo_info.name,
                &format!(
                    "Merge --ff-only '{}' into '{}': {}",
                    repo_info.current_branch, repo_info.main_branch, stderr
                ),
                false,
            );
            return Err(log.print_and_fail(&format!(
                "Cannot fast-forward merge '{}' into '{}' in '{}'. \
                 The branch may have diverged from '{}'. \
                 Rebase onto '{}' first.",
                repo_info.current_branch,
                repo_info.main_branch,
                repo_info.name,
                repo_info.main_branch,
                repo_info.main_branch,
            )));
        }
        log.record(
            &repo_info.name,
            &format!(
                "Merged '{}' into '{}' (fast-forward)",
                repo_info.current_branch, repo_info.main_branch
            ),
            true,
        );
    }

    // ── Phase 5: Push main in all repos ─────────────────────────────────
    for repo_info in &repos {
        let push_output = Command::new("git")
            .arg("push")
            .arg("origin")
            .arg(&repo_info.main_branch)
            .current_dir(&repo_info.path)
            .output()
            .map_err(|e| {
                log.record(
                    &repo_info.name,
                    &format!("Push '{}': {}", repo_info.main_branch, e),
                    false,
                );
                log.print_and_fail(&format!(
                    "Failed to push '{}' in '{}'",
                    repo_info.main_branch, repo_info.name
                ))
            })?;

        if !push_output.status.success() {
            let stderr = String::from_utf8_lossy(&push_output.stderr);
            if stderr.contains("Everything up-to-date") || stderr.contains("up to date") {
                log.record(
                    &repo_info.name,
                    &format!("Push '{}': already up to date", repo_info.main_branch),
                    true,
                );
            } else {
                log.record(
                    &repo_info.name,
                    &format!("Push '{}': {}", repo_info.main_branch, stderr),
                    false,
                );
                return Err(log.print_and_fail(&format!(
                    "Failed to push '{}' in '{}'",
                    repo_info.main_branch, repo_info.name
                )));
            }
        } else {
            log.record(
                &repo_info.name,
                &format!("Pushed '{}' to origin", repo_info.main_branch),
                true,
            );
        }
    }

    // ── Done ────────────────────────────────────────────────────────────
    println!();
    Formatter::print_success("Merge-back complete!");
    println!();
    for repo_info in &repos {
        Formatter::print_success(&format!(
            "[{}] '{}' merged into '{}' and pushed",
            repo_info.name, repo_info.current_branch, repo_info.main_branch
        ));
    }

    Ok(())
}

use colored::Colorize;