ferrflow 6.0.0

Universal semantic versioning for monorepos and classic repos
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
use anyhow::{Context, Result, anyhow};
use gix::ObjectId;
use std::collections::HashMap;
use std::path::Path;

use crate::error_code::{self, ErrorCodeExt};

use super::auth::{configure_git_command, get_remote_url};
use super::repo::Repository;
use super::retry::retry_transient;
use super::shell::run_git;

// Resolved in-process via gix rather than `git rev-list -n 1` per tag: this
// runs once per pushed tag, and each process spawn costs 10-20ms on Windows —
// seconds on a 200-package release. Fully peeling matters: an annotated tag's
// ref points at the tag object, while the remote comparison below uses the
// ls-remote `^{}` (commit) form.
pub(super) fn local_tag_target_sha(repo: &Repository, tag: &str) -> Result<String> {
    let reference = repo
        .find_reference(&format!("refs/tags/{tag}"))
        .with_context(|| format!("could not resolve tag '{tag}' to a commit"))?;
    let id = reference
        .into_fully_peeled_id()
        .with_context(|| format!("could not peel tag '{tag}' to a commit"))?;
    Ok(id.to_string())
}

pub(super) fn parse_ls_remote_tags(stdout: &str) -> HashMap<String, String> {
    let mut tag_objects: HashMap<String, String> = HashMap::new();
    let mut dereferenced: HashMap<String, String> = HashMap::new();
    for line in stdout.lines() {
        let Some((sha, refname)) = line.split_once('\t') else {
            continue;
        };
        let Some(name) = refname.strip_prefix("refs/tags/") else {
            continue;
        };
        if let Some(base) = name.strip_suffix("^{}") {
            dereferenced.insert(base.to_string(), sha.trim().to_string());
        } else {
            tag_objects.insert(name.to_string(), sha.trim().to_string());
        }
    }
    let mut out = tag_objects;
    for (name, sha) in dereferenced {
        out.insert(name, sha);
    }
    out
}

pub(super) fn remote_tag_target_shas(
    workdir: &Path,
    push_url: &str,
    tags: &[&str],
) -> Result<HashMap<String, String>> {
    if tags.is_empty() {
        return Ok(HashMap::new());
    }
    let mut cmd = std::process::Command::new("git");
    cmd.current_dir(workdir);
    configure_git_command(&mut cmd, push_url);
    cmd.arg("ls-remote").arg("--tags").arg(push_url);
    for tag in tags {
        cmd.arg(format!("refs/tags/{tag}"));
    }
    let output = cmd
        .output()
        .with_context(|| "spawn `git ls-remote --tags` failed (is git in PATH?)")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!("git ls-remote --tags failed: {}", stderr.trim()));
    }
    Ok(parse_ls_remote_tags(&String::from_utf8_lossy(
        &output.stdout,
    )))
}

pub fn force_push_tags(repo: &Repository, remote_name: &str, tags: &[&str]) -> Result<()> {
    if tags.is_empty() {
        return Ok(());
    }
    retry_transient("force-push floating tags", || {
        try_force_push_tags_once(repo, remote_name, tags)
    })
}

fn try_force_push_tags_once(repo: &Repository, remote_name: &str, tags: &[&str]) -> Result<()> {
    shell_push_tags(repo, remote_name, tags, true).error_code(error_code::GIT_FLOATING_TAGS)
}

pub fn verify_remote_branch(
    repo: &Repository,
    remote_name: &str,
    branch: &str,
    expected_oid: ObjectId,
) -> Result<()> {
    super::validate::ensure_safe_refname_fragment(remote_name, "remote name")?;
    super::validate::ensure_safe_refname_fragment(branch, "branch name")?;
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow!("Bare repositories are not supported"))?;
    let url = get_remote_url(repo, remote_name)
        .ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;

    let mut cmd = std::process::Command::new("git");
    cmd.current_dir(workdir);
    configure_git_command(&mut cmd, &url);
    cmd.args([
        "ls-remote",
        "--heads",
        &url,
        &format!("refs/heads/{branch}"),
    ]);

    let output = cmd
        .output()
        .with_context(|| "spawn `git ls-remote --heads` failed (is git in PATH?)")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!("git ls-remote --heads failed: {}", stderr.trim()));
    }

    let expected_ref = format!("refs/heads/{branch}");
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        let Some((sha, refname)) = line.split_once('\t') else {
            continue;
        };
        if refname.trim() == expected_ref {
            let actual = ObjectId::from_hex(sha.trim().as_bytes())
                .with_context(|| format!("invalid sha from remote: {sha}"))?;
            if actual == expected_oid {
                return Ok(());
            }
            Err(anyhow!(
                "Remote branch '{}' points to {} but expected {}",
                branch,
                actual,
                expected_oid,
            ))
            .error_code(error_code::GIT_PUSH_VERIFY_FAILED)?;
        }
    }
    Err(anyhow!("Remote branch '{}' not found after push", branch))
        .error_code(error_code::GIT_REMOTE_BRANCH_NOT_FOUND)?;
    Ok(())
}

fn resolve_push_source(repo: &Repository, branch: &str) -> String {
    let local_ref = format!("refs/heads/{branch}");
    if repo.find_reference(&local_ref).is_ok() {
        local_ref
    } else {
        "HEAD".to_string()
    }
}

// Overwrite the remote branch with the local one. Used by the persistent
// release PR (#703): each run rebuilds the same release branch from the
// fresh release commit and force-pushes it, so the open PR updates in place
// instead of a new branch/PR being opened per version.
pub fn force_push_branch(repo: &Repository, remote_name: &str, branch: &str) -> Result<()> {
    super::validate::ensure_safe_refname_fragment(remote_name, "remote name")?;
    super::validate::ensure_safe_refname_fragment(branch, "branch name")?;
    retry_transient(&format!("force-push branch '{branch}'"), || {
        try_force_push_branch_once(repo, remote_name, branch)
    })
}

fn try_force_push_branch_once(repo: &Repository, remote_name: &str, branch: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow!("bare repos are not supported"))?;
    let push_url = get_remote_url(repo, remote_name)
        .ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;
    let source = resolve_push_source(repo, branch);
    // A leading '+' on the refspec forces the update.
    let refspec = format!("+{source}:refs/heads/{branch}");

    let mut cmd = std::process::Command::new("git");
    cmd.current_dir(workdir);
    configure_git_command(&mut cmd, &push_url);
    cmd.arg("push").arg(&push_url).arg(&refspec);

    let output = cmd
        .output()
        .with_context(|| format!("spawn `git push --force` for branch '{branch}' failed"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let detail = format!("{stdout}{stderr}").trim().to_string();
        return Err(anyhow!("Failed to force-push branch '{branch}': {detail}"))
            .error_code(error_code::GIT_FORCE_PUSH_BRANCH);
    }
    Ok(())
}

// SAFETY GUARD for the persistent release PR: before force-pushing the
// release branch we make sure we won't clobber work a human pushed onto it.
// Returns the subject of the first commit on the remote release branch (not
// on `base`) that FerrFlow didn't author (i.e. isn't a `chore(release):`
// commit), or None when the branch is absent or holds only release commits.
pub fn release_branch_foreign_commit(
    repo: &Repository,
    remote_name: &str,
    branch: &str,
    base: &str,
) -> Result<Option<String>> {
    super::validate::ensure_safe_refname_fragment(remote_name, "remote name")?;
    super::validate::ensure_safe_refname_fragment(branch, "branch name")?;
    super::validate::ensure_safe_refname_fragment(base, "target branch")?;
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow!("bare repos are not supported"))?;
    let url = get_remote_url(repo, remote_name)
        .ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;

    let mut ls = std::process::Command::new("git");
    ls.current_dir(workdir);
    configure_git_command(&mut ls, &url);
    ls.args([
        "ls-remote",
        "--heads",
        &url,
        &format!("refs/heads/{branch}"),
    ]);
    let ls_out = ls
        .output()
        .with_context(|| "spawn `git ls-remote` failed")
        .error_code(error_code::GIT_INSPECT_RELEASE_BRANCH)?;
    if !ls_out.status.success() {
        return Err(anyhow!(
            "git ls-remote failed: {}",
            String::from_utf8_lossy(&ls_out.stderr).trim()
        ))
        .error_code(error_code::GIT_INSPECT_RELEASE_BRANCH);
    }
    // Branch not on the remote yet — nothing to clobber.
    if String::from_utf8_lossy(&ls_out.stdout).trim().is_empty() {
        return Ok(None);
    }

    let mut fetch = std::process::Command::new("git");
    fetch.current_dir(workdir);
    configure_git_command(&mut fetch, &url);
    fetch.args(["fetch", "--quiet", &url, &format!("refs/heads/{branch}")]);
    let fetch_out = fetch
        .output()
        .with_context(|| "spawn `git fetch` for release branch failed")
        .error_code(error_code::GIT_INSPECT_RELEASE_BRANCH)?;
    if !fetch_out.status.success() {
        return Err(anyhow!(
            "git fetch of release branch failed: {}",
            String::from_utf8_lossy(&fetch_out.stderr).trim()
        ))
        .error_code(error_code::GIT_INSPECT_RELEASE_BRANCH);
    }

    let mut log = std::process::Command::new("git");
    log.current_dir(workdir);
    log.args(["log", "--format=%s", &format!("{base}..FETCH_HEAD")]);
    let log_out = log
        .output()
        .with_context(|| "spawn `git log` for release branch failed")
        .error_code(error_code::GIT_INSPECT_RELEASE_BRANCH)?;
    if !log_out.status.success() {
        return Err(anyhow!(
            "git log of release branch failed: {}",
            String::from_utf8_lossy(&log_out.stderr).trim()
        ))
        .error_code(error_code::GIT_INSPECT_RELEASE_BRANCH);
    }
    for subject in String::from_utf8_lossy(&log_out.stdout).lines() {
        let subject = subject.trim();
        if !subject.is_empty() && !subject.starts_with("chore(release):") {
            return Ok(Some(subject.to_string()));
        }
    }
    Ok(None)
}

pub fn push_tags(repo: &Repository, remote_name: &str, tags: &[&str]) -> Result<()> {
    if tags.is_empty() {
        return Ok(());
    }
    super::validate::ensure_safe_refname_fragment(remote_name, "remote name")?;
    for tag in tags {
        super::validate::ensure_safe_refname_fragment(tag, "tag name")?;
    }
    retry_transient("push tags", || try_push_tags_once(repo, remote_name, tags))
}

fn try_push_tags_once(repo: &Repository, remote_name: &str, tags: &[&str]) -> Result<()> {
    shell_push_tags(repo, remote_name, tags, false).error_code(error_code::GIT_PUSH_TAGS)
}

fn shell_push_tags(repo: &Repository, remote_name: &str, tags: &[&str], force: bool) -> Result<()> {
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow!("bare repos are not supported"))?;
    let push_url = get_remote_url(repo, remote_name)
        .ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;

    let remote_shas = remote_tag_target_shas(workdir, &push_url, tags).unwrap_or_else(|err| {
        tracing::warn!(
            "  Warning: could not enumerate remote tag state ({err}); falling back to a plain push"
        );
        HashMap::new()
    });

    let mut to_push: Vec<&str> = Vec::with_capacity(tags.len());
    let mut already_synced: Vec<&str> = Vec::new();
    let mut diverged: Vec<(String, String, String)> = Vec::new();
    for tag in tags {
        let local_sha = local_tag_target_sha(repo, tag)?;
        match remote_shas.get(*tag) {
            Some(remote_sha) if remote_sha == &local_sha => already_synced.push(*tag),
            Some(remote_sha) if !force => {
                diverged.push(((*tag).to_string(), local_sha, remote_sha.clone()));
            }
            _ => to_push.push(*tag),
        }
    }

    if !already_synced.is_empty() {
        tracing::info!(
            "  ↻ Already on remote at the same commit: {}",
            already_synced.join(", ")
        );
    }
    if !diverged.is_empty() {
        let joined = diverged
            .iter()
            .map(|(t, l, r)| {
                format!(
                    "{t} (local {} != remote {})",
                    &l[..7.min(l.len())],
                    &r[..7.min(r.len())]
                )
            })
            .collect::<Vec<_>>()
            .join(", ");
        return Err(anyhow!(
            "Tag(s) already exist on remote pointing to a different commit: {joined}. \
             This usually means a previous release run partially succeeded — \
             delete the divergent remote tag(s) and retry, or use --force if you really want to overwrite."
        ));
    }
    if to_push.is_empty() {
        return Ok(());
    }

    let prefix = if force { "+" } else { "" };
    let mut cmd = std::process::Command::new("git");
    cmd.current_dir(workdir);
    configure_git_command(&mut cmd, &push_url);
    cmd.arg("push").arg(&push_url);
    for tag in &to_push {
        cmd.arg(format!("{prefix}refs/tags/{tag}:refs/tags/{tag}"));
    }

    let output = cmd
        .output()
        .with_context(|| "spawn `git push` for tags failed (is git in PATH?)")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let detail = format!("{stdout}{stderr}").trim().to_string();
        let label = if force {
            "Failed to force-push floating tags"
        } else {
            "Failed to push tags"
        };
        return Err(anyhow!("{label}: {detail}"));
    }
    Ok(())
}

fn try_push_branch(repo: &Repository, remote_name: &str, branch: &str) -> Result<()> {
    retry_transient(&format!("push branch '{branch}'"), || {
        try_push_branch_once(repo, remote_name, branch)
    })
}

fn try_push_branch_once(repo: &Repository, remote_name: &str, branch: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow!("bare repos are not supported"))?;
    let push_url = get_remote_url(repo, remote_name)
        .ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;
    let source = resolve_push_source(repo, branch);
    let refspec = format!("{source}:refs/heads/{branch}");

    let mut cmd = std::process::Command::new("git");
    cmd.current_dir(workdir);
    configure_git_command(&mut cmd, &push_url);
    cmd.arg("push").arg(&push_url).arg(&refspec);

    let output = cmd
        .output()
        .with_context(|| format!("spawn `git push` for branch '{branch}' failed"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let detail = format!("{stdout}{stderr}").trim().to_string();
        return Err(anyhow!("Failed to push branch '{branch}': {detail}"))
            .error_code(error_code::GIT_PUSH_BRANCH);
    }
    Ok(())
}

pub fn reset_branch_to_remote(repo: &Repository, remote_name: &str, branch: &str) -> Result<()> {
    super::validate::ensure_safe_refname_fragment(remote_name, "remote name")?;
    super::validate::ensure_safe_refname_fragment(branch, "branch name")?;
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow!("bare repos are not supported"))?;
    let push_url = get_remote_url(repo, remote_name)
        .ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;

    let mut fetch_cmd = std::process::Command::new("git");
    fetch_cmd.current_dir(workdir);
    configure_git_command(&mut fetch_cmd, &push_url);
    fetch_cmd.arg("fetch").arg(remote_name).arg(format!(
        "+refs/heads/{branch}:refs/remotes/{remote_name}/{branch}"
    ));
    let fetch_out = fetch_cmd
        .output()
        .with_context(|| format!("Failed to fetch '{remote_name}/{branch}' for reset"))?;
    if !fetch_out.status.success() {
        let stderr = String::from_utf8_lossy(&fetch_out.stderr);
        return Err(anyhow!(
            "Failed to fetch '{remote_name}/{branch}' for reset: {}",
            stderr.trim()
        ));
    }

    let remote_oid = run_git(
        workdir,
        &["rev-parse", &format!("refs/remotes/{remote_name}/{branch}")],
    )
    .with_context(|| {
        format!("Could not find remote ref refs/remotes/{remote_name}/{branch} after fetch")
    })?
    .trim()
    .to_string();

    let local_ref = format!("refs/heads/{branch}");
    if repo.find_reference(&local_ref).is_ok() {
        run_git(workdir, &["update-ref", &local_ref, &remote_oid])?;
        run_git(workdir, &["checkout", "-f", branch])?;
    } else {
        run_git(workdir, &["checkout", "-f", &remote_oid])?;
    }
    run_git(workdir, &["clean", "-fd"]).ok();

    Ok(())
}

// Rebasing here would rewrite HEAD while the release tags created in an
// earlier phase stay pinned to the pre-rebase commit, so the run would push
// orphaned tags — or collide with a version a concurrent run just published
// (E2006). A rejected push is surfaced instead, letting the regenerate loop in
// `monorepo::release` reset to the remote tip and recompute the whole plan
// against the new base.
pub fn push(repo: &Repository, remote_name: &str, branch: &str) -> Result<()> {
    try_push_branch(repo, remote_name, branch)
        .with_context(|| format!("Failed to push branch '{branch}'"))
        .error_code(error_code::GIT_PUSH_BRANCH)?;

    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow!("bare repos are not supported"))?;
    let head_str = run_git(workdir, &["rev-parse", "HEAD"])?.trim().to_string();
    let head_oid = ObjectId::from_hex(head_str.as_bytes())
        .with_context(|| format!("invalid HEAD sha: {head_str}"))?;
    verify_remote_branch(repo, remote_name, branch, head_oid)
        .with_context(|| "Post-push verification failed: release commit not on remote branch")
        .error_code(error_code::GIT_PUSH_VERIFY_FAILED)?;

    Ok(())
}