Skip to main content

gitpoulpi_cli_backend/
conflicts.rs

1use std::path::{Path, PathBuf};
2
3use gitpoulpi_core::domain::{
4    classify_sides, encode_text, BlobContent, ConflictEntry, ConflictOperation, ConflictRefusal,
5    ConflictResolution, ConflictSet, ConflictSide, EncodeError, MarkerStyle, MergeDocument, Oid,
6    RawStage, RepoRef, ResolveOptions, SideLabels, StageEntry, MAX_TEXT_BLOB_BYTES, MODE_GITLINK,
7    MODE_SYMLINK,
8};
9use gitpoulpi_core::{Error, Result};
10
11use crate::content::repo_relative;
12use crate::process::{
13    cat_file_batch_capped, git_at_least, run, run_bytes, run_merge_file, run_with_stdin,
14};
15
16fn stage_content(repo: &RepoRef, stage: u8, path: &str) -> Option<String> {
17    run(&repo.root, &["show", &format!(":{stage}:{path}")]).ok()
18}
19
20pub fn conflicts(repo: &RepoRef) -> Result<Vec<ConflictSet>> {
21    let raw = run(&repo.root, &["diff", "--name-only", "--diff-filter=U"])?;
22    let sets = raw
23        .lines()
24        .filter(|l| !l.trim().is_empty())
25        .map(|path| ConflictSet {
26            path: path.into(),
27            base: stage_content(repo, 1, path),
28            ours: stage_content(repo, 2, path),
29            theirs: stage_content(repo, 3, path),
30        })
31        .collect();
32    Ok(sets)
33}
34
35/// See `GitBackend::resolve_conflict`.
36///
37/// The stale guard runs first and nothing is written before every check
38/// passed. Regular files are written in place (so the exec bit survives)
39/// and staged with `git add`; a side's whole file goes in through
40/// `checkout --ours/--theirs` and `update-index` with the stage's own blob
41/// and mode, so the staged result is that stage, exactly.
42pub fn resolve_conflict(
43    repo: &RepoRef,
44    path: &Path,
45    resolution: ConflictResolution,
46    opts: &ResolveOptions,
47) -> Result<()> {
48    let rel = repo_relative(path)?;
49    let unmerged = entry_for_opt(repo, &rel)?;
50    if let Some(expected) = opts.expected {
51        let now = unmerged.as_ref().map_or([None; 3], ResolveOptions::oids_of);
52        if now != expected {
53            return Err(Error::ConflictRefused(ConflictRefusal::Stale));
54        }
55    }
56    match resolution {
57        ConflictResolution::TakeSide(side) => take_side(repo, &rel, unmerged, side, opts.stage),
58        ConflictResolution::UseContent(text) => {
59            write_worktree(repo, &rel, text.as_bytes())?;
60            stage_added(repo, &rel, opts)
61        }
62        ConflictResolution::UseEncoded { text, encoding } => {
63            let bytes = encode_text(&text, &encoding).map_err(|e| match e {
64                EncodeError::Unencodable { line } => {
65                    Error::ConflictRefused(ConflictRefusal::Unencodable { line })
66                }
67                EncodeError::UnknownEncoding(label) => {
68                    Error::Backend(format!("unknown encoding {label}"))
69                }
70            })?;
71            write_worktree(repo, &rel, &bytes)?;
72            stage_added(repo, &rel, opts)
73        }
74        ConflictResolution::Delete => remove_path(repo, &rel, opts.stage),
75    }
76}
77
78fn stage_added(repo: &RepoRef, rel: &str, opts: &ResolveOptions) -> Result<()> {
79    if opts.stage {
80        run(&repo.root, &["--literal-pathspecs", "add", "--", rel])?;
81    }
82    Ok(())
83}
84
85/// Writes `bytes` as the file at `rel`. A regular file is overwritten in
86/// place (its mode stays); a symlink or directory in the way is removed
87/// first (writing through a symlink would change its target).
88fn write_worktree(repo: &RepoRef, rel: &str, bytes: &[u8]) -> Result<()> {
89    let full = repo.root.join(rel);
90    if let Some(parent) = full.parent() {
91        std::fs::create_dir_all(parent)?;
92    }
93    if let Ok(meta) = std::fs::symlink_metadata(&full) {
94        if !meta.is_file() {
95            crate::snapshot_ops::remove_any(&full)?;
96        }
97    }
98    std::fs::write(&full, bytes)?;
99    Ok(())
100}
101
102/// Writes a symlink to `target` (a plain file holding the target text
103/// where symlinks are not available, as git does with
104/// `core.symlinks=false`).
105fn write_symlink(repo: &RepoRef, rel: &str, target: &[u8]) -> Result<()> {
106    let full = repo.root.join(rel);
107    if let Some(parent) = full.parent() {
108        std::fs::create_dir_all(parent)?;
109    }
110    crate::snapshot_ops::remove_any(&full)?;
111    #[cfg(unix)]
112    {
113        let target = String::from_utf8_lossy(target).into_owned();
114        std::os::unix::fs::symlink(target, &full)?;
115    }
116    #[cfg(not(unix))]
117    std::fs::write(&full, target)?;
118    Ok(())
119}
120
121/// Index entries through `update-index --index-info`: `<mode> <oid>
122/// <stage>\t<path>` lines, a mode of 0 removing every stage of the path.
123fn index_info(repo: &RepoRef, lines: &[String]) -> Result<()> {
124    let mut input = String::new();
125    for line in lines {
126        input.push_str(line);
127        input.push('\0');
128    }
129    run_with_stdin(&repo.root, &["update-index", "-z", "--index-info"], &input)?;
130    Ok(())
131}
132
133const ZERO_OID: &str = "0000000000000000000000000000000000000000";
134
135/// The path goes: the file (when staging or not) and, when staging, every
136/// index entry.
137fn remove_path(repo: &RepoRef, rel: &str, stage: bool) -> Result<()> {
138    crate::snapshot_ops::remove_any(&repo.root.join(rel))?;
139    if stage {
140        index_info(repo, &[format!("0 {ZERO_OID}\t{rel}")])?;
141    }
142    Ok(())
143}
144
145fn take_side(
146    repo: &RepoRef,
147    rel: &str,
148    unmerged: Option<ConflictEntry>,
149    side: ConflictSide,
150    stage: bool,
151) -> Result<()> {
152    let stage_no: u8 = match side {
153        ConflictSide::Base => 1,
154        ConflictSide::Ours => 2,
155        ConflictSide::Theirs => 3,
156    };
157    let Some(entry) = unmerged else {
158        return Err(Error::ConflictRefused(ConflictRefusal::NotConflicted));
159    };
160    let Some(taken) = entry.stage(side) else {
161        // That side has no file here: it deleted the path. Base missing
162        // (add/add) has nothing to take.
163        if side == ConflictSide::Base {
164            return Err(Error::Backend(
165                "there is no common ancestor version of this file".into(),
166            ));
167        }
168        return remove_path(repo, rel, stage);
169    };
170    if taken.mode == MODE_GITLINK {
171        // A submodule pointer: the index is all there is, no checkout.
172        if stage {
173            index_info(
174                repo,
175                &[
176                    format!("0 {ZERO_OID}\t{rel}"),
177                    format!("{:o} {} 0\t{rel}", taken.mode, taken.oid),
178                ],
179            )?;
180        }
181        return Ok(());
182    }
183    match side {
184        ConflictSide::Ours | ConflictSide::Theirs => {
185            let flag = if side == ConflictSide::Ours {
186                "--ours"
187            } else {
188                "--theirs"
189            };
190            run(
191                &repo.root,
192                &["--literal-pathspecs", "checkout", flag, "--", rel],
193            )?;
194        }
195        ConflictSide::Base => {
196            let bytes = run_bytes(
197                &repo.root,
198                &["cat-file", "blob", &format!(":{stage_no}:{rel}")],
199            )?;
200            if taken.mode == MODE_SYMLINK {
201                write_symlink(repo, rel, &bytes)?;
202            } else {
203                write_worktree(repo, rel, &bytes)?;
204            }
205        }
206    }
207    if stage {
208        index_info(
209            repo,
210            &[
211                format!("0 {ZERO_OID}\t{rel}"),
212                format!("{:o} {} 0\t{rel}", taken.mode, taken.oid),
213            ],
214        )?;
215    }
216    Ok(())
217}
218
219/// See `GitBackend::unresolve_conflict`: the stages go back into the
220/// index, then the file git would have left in the working tree.
221pub fn unresolve_conflict(repo: &RepoRef, path: &Path, entry: &ConflictEntry) -> Result<()> {
222    let rel = repo_relative(path)?;
223    if entry_for_opt(repo, &rel)?.is_some() {
224        return Err(Error::ConflictRefused(ConflictRefusal::AlreadyConflicted));
225    }
226    let mut lines = vec![format!("0 {ZERO_OID}\t{rel}")];
227    for (n, stage) in [(1, entry.base), (2, entry.ours), (3, entry.theirs)] {
228        if let Some(stage) = stage {
229            lines.push(format!("{:o} {} {n}\t{rel}", stage.mode, stage.oid));
230        }
231    }
232    index_info(repo, &lines)?;
233
234    // The working tree file.
235    let doc = merge_document(repo, path)?;
236    if doc.conflict_count() > 0 {
237        let crlf = [&doc.ours, &doc.theirs]
238            .into_iter()
239            .flatten()
240            .next()
241            .is_some_and(|b| matches!(b.content, BlobContent::Text { crlf: true, .. }));
242        let eol = if crlf { "\r\n" } else { "\n" };
243        let mut text = doc.render_markers(&MarkerStyle {
244            marker_size: 7,
245            diff3: false,
246            ours_label: &doc.labels.git_ours_label,
247            base_label: "",
248            theirs_label: &doc.labels.git_theirs_label,
249            eol,
250            final_newline: doc.final_newline,
251        });
252        if doc.bom {
253            text.insert(0, '\u{feff}');
254        }
255        // Text decoded with a fallback encoding goes back in it.
256        let bytes = match &doc.encoding {
257            Some(label) => encode_text(&text, label).unwrap_or_else(|_| text.into_bytes()),
258            None => text.into_bytes(),
259        };
260        return write_worktree(repo, &rel, &bytes);
261    }
262    // Not a text merge: git leaves our version (the surviving side's for
263    // a delete/modify) in the working tree.
264    let Some((n, shown)) = [(2, entry.ours), (3, entry.theirs), (1, entry.base)]
265        .into_iter()
266        .find_map(|(n, s)| s.map(|s| (n, s)))
267    else {
268        return Ok(());
269    };
270    if shown.mode == MODE_GITLINK {
271        return Ok(());
272    }
273    let bytes = run_bytes(&repo.root, &["cat-file", "blob", &format!(":{n}:{rel}")])?;
274    if shown.mode == MODE_SYMLINK {
275        write_symlink(repo, &rel, &bytes)
276    } else {
277        write_worktree(repo, &rel, &bytes)
278    }
279}
280
281// -- the cheap listing -------------------------------------------------------------
282
283/// `<mode> <oid> <stage>\t<path>` records of `git ls-files -u -z`, folded
284/// into one [`ConflictEntry`] per path (git lists a path's stages
285/// together, in stage order, paths sorted).
286pub fn parse_unmerged(raw: &str) -> Result<Vec<ConflictEntry>> {
287    let mut entries: Vec<ConflictEntry> = Vec::new();
288    let mut pending: Option<(String, [Option<StageEntry>; 3])> = None;
289    let flush = |pending: &mut Option<(String, [Option<StageEntry>; 3])>,
290                 entries: &mut Vec<ConflictEntry>| {
291        if let Some((path, [base, ours, theirs])) = pending.take() {
292            entries.extend(ConflictEntry::from_stages(path.into(), base, ours, theirs));
293        }
294    };
295    for record in raw.split('\0').filter(|r| !r.is_empty()) {
296        let bad = || Error::Backend(format!("git ls-files -u gave `{record}`"));
297        let (meta, path) = record.split_once('\t').ok_or_else(bad)?;
298        let mut words = meta.split(' ');
299        let mode = u32::from_str_radix(words.next().ok_or_else(bad)?, 8).map_err(|_| bad())?;
300        let oid = Oid::from_hex(words.next().ok_or_else(bad)?).ok_or_else(bad)?;
301        let stage: usize = words.next().ok_or_else(bad)?.parse().map_err(|_| bad())?;
302        if !(1..=3).contains(&stage) {
303            return Err(bad());
304        }
305        if pending.as_ref().is_some_and(|(p, _)| p != path) {
306            flush(&mut pending, &mut entries);
307        }
308        let slot = pending.get_or_insert_with(|| (path.to_string(), [None; 3]));
309        slot.1[stage - 1] = Some(StageEntry { mode, oid });
310    }
311    flush(&mut pending, &mut entries);
312    Ok(entries)
313}
314
315/// See `GitBackend::conflict_entries`: one `git ls-files -u -z`, no blob
316/// read.
317pub fn conflict_entries(repo: &RepoRef) -> Result<Vec<ConflictEntry>> {
318    parse_unmerged(&run(&repo.root, &["ls-files", "-u", "-z"])?)
319}
320
321fn entry_for_opt(repo: &RepoRef, rel: &str) -> Result<Option<ConflictEntry>> {
322    let raw = run(
323        &repo.root,
324        &["--literal-pathspecs", "ls-files", "-u", "-z", "--", rel],
325    )?;
326    Ok(parse_unmerged(&raw)?
327        .into_iter()
328        .find(|e| e.path.to_str() == Some(rel)))
329}
330
331fn entry_for(repo: &RepoRef, rel: &str) -> Result<ConflictEntry> {
332    entry_for_opt(repo, rel)?.ok_or_else(|| Error::Backend(format!("{rel} is not conflicted")))
333}
334
335// -- the document ----------------------------------------------------------------------
336
337/// See `GitBackend::merge_document`.
338///
339/// One `ls-files -u`, one `cat-file --batch` for the stages, one
340/// `merge-file` (and, the first time in a process, `git --version`).
341pub fn merge_document(repo: &RepoRef, path: &Path) -> Result<MergeDocument> {
342    let rel = repo_relative(path)?;
343    let entry = entry_for(repo, &rel)?;
344    let stages = [entry.base, entry.ours, entry.theirs];
345    // A gitlink's oid is a commit in another repository: never read.
346    let readable: Vec<String> = stages
347        .iter()
348        .flatten()
349        .filter(|s| s.mode != MODE_GITLINK)
350        .map(|s| s.oid.to_hex())
351        .collect();
352    let mut objects =
353        cat_file_batch_capped(&repo.root, &readable, MAX_TEXT_BLOB_BYTES)?.into_iter();
354    let raws = stages.map(|stage| {
355        stage.map(|entry| {
356            if entry.mode == MODE_GITLINK {
357                return RawStage {
358                    entry,
359                    size: 0,
360                    bytes: None,
361                };
362            }
363            let object = objects.next().expect("one object per readable stage");
364            RawStage {
365                entry,
366                size: object.size,
367                bytes: object.bytes,
368            }
369        })
370    });
371    document_from_stages(repo, entry, raws)
372}
373
374/// Everything after the stages are read, shared with `Git2Backend` (which
375/// reads them natively): runs git's 3-way merge on them, reads the labels
376/// and the file on disk, and assembles the document.
377pub fn document_from_stages(
378    repo: &RepoRef,
379    entry: ConflictEntry,
380    raws: [Option<RawStage>; 3],
381) -> Result<MergeDocument> {
382    let oids = [
383        entry.base.map(|s| s.oid),
384        entry.ours.map(|s| s.oid),
385        entry.theirs.map(|s| s.oid),
386    ];
387    let (blobs, job) = classify_sides(&entry, raws);
388    let merged = match job {
389        Some(job) => {
390            let output = merge_stage_bytes(repo, &job, oids)?;
391            Some((job.marker, output))
392        }
393        None => None,
394    };
395    let labels = side_labels(repo);
396    let worktree = read_worktree_file(repo, &entry.path);
397    MergeDocument::assemble(entry, blobs, merged, labels, worktree.as_deref())
398}
399
400/// `git merge-file -p --zdiff3` over the three sides, with a marker size
401/// no line can be mistaken for. `--zdiff3` (git 2.35+; `--diff3` before)
402/// is git's own merge with the base kept in each conflict and the lines
403/// both sides share trimmed off its edges, as `git merge` writes them.
404/// Blobs are passed by id on git 2.43+ (`--object-id`) and through
405/// temporary files under the git dir before.
406fn merge_stage_bytes(
407    repo: &RepoRef,
408    job: &gitpoulpi_core::domain::MergeJob,
409    oids: [Option<Oid>; 3],
410) -> Result<Vec<u8>> {
411    merge_stage_bytes_with(repo, job, oids, git_at_least(2, 43))
412}
413
414/// [`merge_stage_bytes`] with the blob-passing method chosen by the
415/// caller (so the pre-2.43 path is testable on a newer git).
416fn merge_stage_bytes_with(
417    repo: &RepoRef,
418    job: &gitpoulpi_core::domain::MergeJob,
419    oids: [Option<Oid>; 3],
420    object_id: bool,
421) -> Result<Vec<u8>> {
422    const EMPTY_BLOB: &str = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
423    let style = if git_at_least(2, 35) {
424        "--zdiff3"
425    } else {
426        "--diff3"
427    };
428    let marker = format!("--marker-size={}", job.marker);
429    let head = ["merge-file", "-p", style, &marker];
430    let labels = ["-L", "ours", "-L", "base", "-L", "theirs"];
431
432    if object_id {
433        let base = oids[0].map_or_else(|| EMPTY_BLOB.to_string(), |o| o.to_hex());
434        let ours = oids[1].map(|o| o.to_hex()).unwrap_or_default();
435        let theirs = oids[2].map(|o| o.to_hex()).unwrap_or_default();
436        let mut args: Vec<&str> = head.to_vec();
437        args.push("--object-id");
438        args.extend(labels);
439        args.extend([ours.as_str(), base.as_str(), theirs.as_str()]);
440        return run_merge_file(&repo.root, &args);
441    }
442
443    let dir = merge_tmp_dir(repo)?;
444    let result = (|| {
445        let files = [
446            ("ours", &job.ours),
447            ("base", &job.base),
448            ("theirs", &job.theirs),
449        ];
450        let mut paths = Vec::new();
451        for (name, bytes) in files {
452            let file = dir.join(name);
453            std::fs::write(&file, bytes)?;
454            paths.push(file.to_string_lossy().into_owned());
455        }
456        let mut args: Vec<&str> = head.to_vec();
457        args.extend(labels);
458        args.extend(paths.iter().map(String::as_str));
459        run_merge_file(&repo.root, &args)
460    })();
461    let _ = std::fs::remove_dir_all(&dir);
462    result
463}
464
465/// A fresh directory under `<git-dir>/gitpoulpi/merge-tmp/`.
466fn merge_tmp_dir(repo: &RepoRef) -> Result<PathBuf> {
467    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
468    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
469    let dir = git_dir(&repo.root)
470        .join("gitpoulpi")
471        .join("merge-tmp")
472        .join(format!("{}-{n}", std::process::id()));
473    std::fs::create_dir_all(&dir)?;
474    Ok(dir)
475}
476
477/// The file on disk at `path`: its bytes, a symlink's target, or `None`
478/// when there is nothing there. A file over the size cap is not read; it
479/// is reported as empty (so it counts as present, and as edited).
480fn read_worktree_file(repo: &RepoRef, path: &Path) -> Option<Vec<u8>> {
481    let full = repo.root.join(path);
482    let meta = std::fs::symlink_metadata(&full).ok()?;
483    if meta.file_type().is_symlink() {
484        return std::fs::read_link(&full)
485            .ok()
486            .map(|t| t.to_string_lossy().into_owned().into_bytes());
487    }
488    if !meta.is_file() {
489        return None;
490    }
491    if meta.len() > MAX_TEXT_BLOB_BYTES {
492        return Some(Vec::new());
493    }
494    std::fs::read(&full).ok()
495}
496
497// -- labels --------------------------------------------------------------------------------
498
499/// The git directory of the worktree at `root`: `.git` itself, or what a
500/// linked worktree's (or submodule's) `.git` file points at.
501pub fn git_dir(root: &Path) -> PathBuf {
502    let dot_git = root.join(".git");
503    if dot_git.is_file() {
504        if let Some(target) = std::fs::read_to_string(&dot_git).ok().and_then(|t| {
505            t.trim()
506                .strip_prefix("gitdir:")
507                .map(|p| p.trim().to_string())
508        }) {
509            let target = PathBuf::from(target);
510            return if target.is_absolute() {
511                target
512            } else {
513                root.join(target)
514            };
515        }
516    }
517    dot_git
518}
519
520pub(crate) fn read_trimmed(path: &Path) -> Option<String> {
521    let text = std::fs::read_to_string(path).ok()?;
522    let text = text.trim();
523    (!text.is_empty()).then(|| text.to_string())
524}
525
526pub(crate) fn short(sha: &str) -> &str {
527    sha.get(..7).unwrap_or(sha)
528}
529
530fn branch_of(refname: &str) -> &str {
531    refname.strip_prefix("refs/heads/").unwrap_or(refname)
532}
533
534/// The pane labels for whatever operation is stopped, read from the git
535/// directory without a process (plan 3.5). Roles and refs, never a bare
536/// ours / theirs: a rebase swaps what they mean.
537pub fn side_labels(repo: &RepoRef) -> SideLabels {
538    let dir = git_dir(&repo.root);
539    let head = read_trimmed(&dir.join("HEAD")).unwrap_or_default();
540    let head_branch = head
541        .strip_prefix("ref: ")
542        .map(|r| branch_of(r).to_string())
543        .unwrap_or_else(|| short(&head).to_string());
544    let message_first_line = || {
545        read_trimmed(&dir.join("MERGE_MSG"))
546            .and_then(|m| m.lines().next().map(str::to_string))
547            .unwrap_or_default()
548    };
549    let mut labels = SideLabels {
550        base: "Base".to_string(),
551        git_ours_label: "HEAD".to_string(),
552        ..SideLabels::default()
553    };
554
555    if let Some(sha) = read_trimmed(&dir.join("CHERRY_PICK_HEAD")) {
556        let summary = message_first_line();
557        labels.op = ConflictOperation::CherryPick;
558        labels.current = format!("Current · {head_branch}");
559        labels.incoming = format!("Incoming · {} {summary}", short(&sha))
560            .trim_end()
561            .to_string();
562        labels.description = format!("cherry-picking {}", short(&sha));
563        labels.git_theirs_label = format!("{} ({summary})", short(&sha));
564    } else if let Some(sha) = read_trimmed(&dir.join("REVERT_HEAD")) {
565        let line = message_first_line();
566        let summary = line
567            .strip_prefix("Revert \"")
568            .and_then(|l| l.strip_suffix('"'))
569            .unwrap_or(&line)
570            .to_string();
571        labels.op = ConflictOperation::Revert;
572        labels.current = format!("Current · {head_branch}");
573        labels.incoming = format!("Incoming · revert of {} {summary}", short(&sha))
574            .trim_end()
575            .to_string();
576        labels.description = format!("reverting {}", short(&sha));
577        labels.git_theirs_label = format!("parent of {} ({summary})", short(&sha));
578    } else if dir.join("rebase-merge").is_dir() {
579        let rebase = dir.join("rebase-merge");
580        let onto = read_trimmed(&rebase.join("onto")).unwrap_or_default();
581        let branch = read_trimmed(&rebase.join("head-name")).unwrap_or_default();
582        let stopped = read_trimmed(&dir.join("REBASE_HEAD"))
583            .or_else(|| read_trimmed(&rebase.join("stopped-sha")))
584            .unwrap_or_default();
585        let summary = read_trimmed(&rebase.join("message"))
586            .and_then(|m| m.lines().next().map(str::to_string))
587            .unwrap_or_default();
588        let step = read_trimmed(&rebase.join("msgnum"))
589            .zip(read_trimmed(&rebase.join("end")))
590            .map(|(n, end)| format!(" · step {n}/{end}"))
591            .unwrap_or_default();
592        labels.op = ConflictOperation::Rebase;
593        labels.current = format!("Current · onto {}", short(&onto));
594        labels.incoming = format!("Incoming · your commit {} {summary}", short(&stopped))
595            .trim_end()
596            .to_string();
597        labels.description = format!(
598            "rebasing {} onto {}{step}",
599            branch_of(&branch),
600            short(&onto)
601        );
602        labels.git_theirs_label = format!("{} ({summary})", short(&stopped));
603    } else if let Some(sha) = read_trimmed(&dir.join("MERGE_HEAD")) {
604        // `MERGE_HEAD` has one line per merged commit; the message names
605        // the branch ("Merge branch 'x'", "Merge remote-tracking branch
606        // 'origin/x'", "Merge tag 'v1'").
607        let sha = sha.lines().next().unwrap_or_default().to_string();
608        let message = message_first_line();
609        let name = message
610            .split('\'')
611            .nth(1)
612            .filter(|n| !n.is_empty())
613            .unwrap_or_else(|| short(&sha))
614            .to_string();
615        labels.op = ConflictOperation::Merge;
616        labels.current = format!("Current · {head_branch}");
617        labels.incoming = format!("Incoming · {name}");
618        labels.description = format!("merging {name} into {head_branch}");
619        labels.git_theirs_label = name;
620    } else {
621        labels.current = "Current · working tree".to_string();
622        labels.incoming = "Incoming · stash".to_string();
623        labels.git_theirs_label = "Stashed changes".to_string();
624    }
625    labels
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use gitpoulpi_testkit::ConflictFixture;
632
633    #[test]
634    fn unmerged_records_fold_into_one_entry_per_path() {
635        let a = "a".repeat(40);
636        let b = "b".repeat(40);
637        let raw = format!(
638            "100644 {a} 1\tx y.txt\0100644 {a} 2\tx y.txt\0100755 {b} 3\tx y.txt\0\
639             100644 {b} 2\tz\0"
640        );
641        let entries = parse_unmerged(&raw).unwrap();
642        assert_eq!(entries.len(), 2);
643        assert_eq!(entries[0].path.to_str(), Some("x y.txt"));
644        assert_eq!(
645            entries[0].kind,
646            gitpoulpi_core::domain::ConflictKind::BothModified
647        );
648        assert_eq!(entries[0].theirs.unwrap().mode, 0o100755);
649        assert_eq!(
650            entries[1].kind,
651            gitpoulpi_core::domain::ConflictKind::AddedByUs
652        );
653        assert!(parse_unmerged("").unwrap().is_empty());
654        assert!(parse_unmerged("junk\0").is_err());
655    }
656
657    /// Before git 2.43 `merge-file` cannot take object ids, so the blobs go
658    /// through temporary files: the same merge, and nothing left behind.
659    #[test]
660    fn the_temp_file_path_merges_like_the_object_id_path() {
661        let fx = ConflictFixture::text();
662        let repo = fx.repo_ref();
663        let entry = entry_for(&repo, "notes.txt").unwrap();
664        let stage = |s: Option<StageEntry>| {
665            let s = s.unwrap();
666            let bytes = fx.stage_bytes(
667                if s == entry.ours.unwrap() {
668                    2
669                } else if s == entry.theirs.unwrap() {
670                    3
671                } else {
672                    1
673                },
674                "notes.txt",
675            );
676            RawStage {
677                entry: s,
678                size: bytes.as_ref().map_or(0, |b| b.len() as u64),
679                bytes,
680            }
681        };
682        let (_, job) = classify_sides(
683            &entry,
684            [
685                Some(stage(entry.base)),
686                Some(stage(entry.ours)),
687                Some(stage(entry.theirs)),
688            ],
689        );
690        let job = job.unwrap();
691        let oids = [
692            entry.base.map(|s| s.oid),
693            entry.ours.map(|s| s.oid),
694            entry.theirs.map(|s| s.oid),
695        ];
696        let by_file = merge_stage_bytes_with(&repo, &job, oids, false).unwrap();
697        // `--object-id` is git 2.43+: older git only has the temp-file path.
698        if crate::process::git_at_least(2, 43) {
699            let by_id = merge_stage_bytes_with(&repo, &job, oids, true).unwrap();
700            assert_eq!(by_id, by_file);
701        }
702        let tmp = git_dir(&repo.root).join("gitpoulpi").join("merge-tmp");
703        assert_eq!(std::fs::read_dir(tmp).unwrap().count(), 0, "cleaned up");
704    }
705
706    #[test]
707    fn a_linked_worktrees_git_file_is_followed() {
708        let dir = tempfile::tempdir().unwrap();
709        std::fs::write(
710            dir.path().join(".git"),
711            "gitdir: ../main/.git/worktrees/w\n",
712        )
713        .unwrap();
714        assert_eq!(
715            git_dir(dir.path()),
716            dir.path().join("../main/.git/worktrees/w")
717        );
718    }
719
720    #[test]
721    fn git_versions_parse() {
722        assert_eq!(
723            crate::process::parse_git_version("git version 2.45.2.windows.1\n"),
724            Some((2, 45))
725        );
726        assert_eq!(crate::process::parse_git_version("nonsense"), None);
727    }
728}