weave-cli 0.3.6

Entity-level semantic merge CLI. Resolves conflicts at the function/class level instead of lines.
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
use std::collections::HashSet;
use std::path::Path;
use std::process::Command;

use sem_core::parser::plugins::create_default_registry;
use weave_core::entity_merge_with_registry;

const SUPPORTED_EXTENSIONS: &[&str] = &[
    "ts", "tsx", "js", "jsx", "py", "rs", "go", "java", "c", "cpp", "cc", "h", "hpp", "rb", "cs",
    "dart",
];

struct Stats {
    merge_commits: usize,
    files_tested: usize,
    both_clean: usize,
    weave_wins: usize,
    both_conflict: usize,
    regressions: usize,
    matches_human: usize,
    differs_from_human: usize,
}

#[derive(serde::Serialize)]
struct CaseRecord {
    commit: String,
    file: String,
    category: String, // "match", "diff", "regression"
    dir: String,      // relative path in save dir
}

#[derive(serde::Serialize)]
struct BenchResults {
    repo: String,
    merge_commits: usize,
    files_tested: usize,
    both_clean: usize,
    weave_wins: usize,
    both_conflict: usize,
    regressions: usize,
    matches_human: usize,
    differs_from_human: usize,
    resolution_rate: f64,
    human_match_rate: f64,
    cases: Vec<CaseRecord>,
}

pub fn run(
    repo_path: &str,
    limit: usize,
    show_diff: bool,
    save_dir: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let repo = Path::new(repo_path).canonicalize()?;
    // Support both regular and bare repos
    let is_git = repo.join(".git").exists() || repo.join("HEAD").exists();
    if !is_git {
        return Err(format!("{} is not a git repository", repo_path).into());
    }

    let repo_name = repo
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();
    println!("weave real-world benchmark");
    println!("==========================");
    println!("repo: {} ({})", repo_name, repo.display());
    println!("scanning up to {} merge commits\n", limit);

    // Create save directory if requested
    if let Some(dir) = save_dir {
        std::fs::create_dir_all(dir)?;
    }

    let output = Command::new("git")
        .args(["log", "--merges", "--format=%H", &format!("-{}", limit)])
        .current_dir(&repo)
        .output()?;

    let merge_commits: Vec<String> = String::from_utf8(output.stdout)?
        .lines()
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect();

    println!("found {} merge commits\n", merge_commits.len());

    let registry = create_default_registry();

    let mut stats = Stats {
        merge_commits: merge_commits.len(),
        files_tested: 0,
        both_clean: 0,
        weave_wins: 0,
        both_conflict: 0,
        regressions: 0,
        matches_human: 0,
        differs_from_human: 0,
    };

    let mut cases: Vec<CaseRecord> = Vec::new();

    for (i, merge_commit) in merge_commits.iter().enumerate() {
        // Get the two parents
        let output = Command::new("git")
            .args([
                "rev-parse",
                &format!("{}^1", merge_commit),
                &format!("{}^2", merge_commit),
            ])
            .current_dir(&repo)
            .output()?;
        let parents: Vec<String> = String::from_utf8(output.stdout)?
            .lines()
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .collect();

        if parents.len() != 2 {
            continue; // skip octopus merges
        }
        let (p1, p2) = (&parents[0], &parents[1]);

        // Get merge base
        let output = Command::new("git")
            .args(["merge-base", p1, p2])
            .current_dir(&repo)
            .output()?;
        let base = String::from_utf8(output.stdout)?.trim().to_string();
        if base.is_empty() {
            continue;
        }

        // Files changed in each branch relative to base
        let files_p1 = changed_files(&repo, &base, p1)?;
        let files_p2 = changed_files(&repo, &base, p2)?;

        // Only care about files touched by BOTH branches
        let both_touched: Vec<&String> = files_p1.intersection(&files_p2).collect();

        for file in both_touched {
            let ext = Path::new(file)
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("");
            if !SUPPORTED_EXTENSIONS.contains(&ext) {
                continue;
            }

            // Get all four versions: base, ours (p1), theirs (p2), human (merge commit)
            let (base_content, ours, theirs, human) = match (
                git_show(&repo, &base, file),
                git_show(&repo, p1, file),
                git_show(&repo, p2, file),
                git_show(&repo, merge_commit, file),
            ) {
                (Some(b), Some(o), Some(t), Some(h)) => (b, o, t, h),
                _ => continue, // file added/deleted on one side
            };

            // Skip large or binary files
            if base_content.len() > 1_000_000 || base_content.contains('\0') {
                continue;
            }

            // If both sides made identical changes, skip (trivial merge)
            if ours == theirs {
                continue;
            }

            stats.files_tested += 1;

            let git_clean = diffy::merge(&base_content, &ours, &theirs).is_ok();
            let weave_result = entity_merge_with_registry(
                &base_content,
                &ours,
                &theirs,
                file,
                &registry,
                &weave_core::MarkerFormat::default(),
            );
            // Check content for actual weave conflict markers only.
            // Don't use is_clean() as it can false-positive when the conflicts vec has entries
            // but the content was resolved correctly. Also use specific marker format to avoid
            // false positives on source code containing literal conflict marker strings.
            let weave_clean = !weave_result.content.contains("<<<<<<< ours")
                && !weave_result.content.contains(">>>>>>> theirs");

            match (weave_clean, git_clean) {
                (true, true) => stats.both_clean += 1,
                (false, false) => stats.both_conflict += 1,
                (false, true) => {
                    stats.regressions += 1;
                    println!("  REGR   {}  {}", short(merge_commit), file);
                    if let Some(dir) = save_dir {
                        let case_dir = save_case(
                            dir,
                            merge_commit,
                            file,
                            &base_content,
                            &ours,
                            &theirs,
                            &human,
                            &weave_result.content,
                        )?;
                        cases.push(CaseRecord {
                            commit: merge_commit.clone(),
                            file: file.clone(),
                            category: "regression".to_string(),
                            dir: case_dir,
                        });
                    }
                }
                (true, false) => {
                    stats.weave_wins += 1;
                    if normalize(&weave_result.content) == normalize(&human) {
                        stats.matches_human += 1;
                        println!("  MATCH  {}  {}", short(merge_commit), file);
                        if let Some(dir) = save_dir {
                            let case_dir = save_case(
                                dir,
                                merge_commit,
                                file,
                                &base_content,
                                &ours,
                                &theirs,
                                &human,
                                &weave_result.content,
                            )?;
                            cases.push(CaseRecord {
                                commit: merge_commit.clone(),
                                file: file.clone(),
                                category: "match".to_string(),
                                dir: case_dir,
                            });
                        }
                    } else {
                        stats.differs_from_human += 1;
                        println!("  DIFF   {}  {}", short(merge_commit), file);
                        if show_diff {
                            print_inline_diff(&weave_result.content, &human);
                        }
                        if let Some(dir) = save_dir {
                            let case_dir = save_case(
                                dir,
                                merge_commit,
                                file,
                                &base_content,
                                &ours,
                                &theirs,
                                &human,
                                &weave_result.content,
                            )?;
                            cases.push(CaseRecord {
                                commit: merge_commit.clone(),
                                file: file.clone(),
                                category: "diff".to_string(),
                                dir: case_dir,
                            });
                        }
                    }
                }
            }
        }

        if (i + 1) % 100 == 0 {
            eprint!("\r  processed {}/{} merges...", i + 1, merge_commits.len());
        }
    }

    eprintln!();
    print_results(&stats, &repo_name);

    // Write results.json
    if let Some(dir) = save_dir {
        let total_git_conflicts = stats.weave_wins + stats.both_conflict;
        let results = BenchResults {
            repo: repo_name.clone(),
            merge_commits: stats.merge_commits,
            files_tested: stats.files_tested,
            both_clean: stats.both_clean,
            weave_wins: stats.weave_wins,
            both_conflict: stats.both_conflict,
            regressions: stats.regressions,
            matches_human: stats.matches_human,
            differs_from_human: stats.differs_from_human,
            resolution_rate: if total_git_conflicts > 0 {
                stats.weave_wins as f64 / total_git_conflicts as f64 * 100.0
            } else {
                0.0
            },
            human_match_rate: if stats.weave_wins > 0 {
                stats.matches_human as f64 / stats.weave_wins as f64 * 100.0
            } else {
                0.0
            },
            cases,
        };
        let json = serde_json::to_string_pretty(&results)?;
        std::fs::write(Path::new(dir).join("results.json"), &json)?;
        println!("\nsaved {} cases to {}/", results.cases.len(), dir);
    }

    Ok(())
}

/// Save a test case to disk: base, ours, theirs, human, weave
#[allow(clippy::too_many_arguments)]
fn save_case(
    save_dir: &str,
    commit: &str,
    file: &str,
    base: &str,
    ours: &str,
    theirs: &str,
    human: &str,
    weave: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    // Create a directory name from commit + file
    let safe_file = file.replace('/', "_");
    let dir_name = format!("{}_{}", short(commit), safe_file);
    let case_path = Path::new(save_dir).join(&dir_name);
    std::fs::create_dir_all(&case_path)?;

    std::fs::write(case_path.join("base"), base)?;
    std::fs::write(case_path.join("ours"), ours)?;
    std::fs::write(case_path.join("theirs"), theirs)?;
    std::fs::write(case_path.join("human"), human)?;
    std::fs::write(case_path.join("weave"), weave)?;

    Ok(dir_name)
}

fn changed_files(
    repo: &Path,
    base: &str,
    head: &str,
) -> Result<HashSet<String>, Box<dyn std::error::Error>> {
    let output = Command::new("git")
        .args([
            "diff",
            "--name-only",
            "--diff-filter=M",
            &format!("{}..{}", base, head),
        ])
        .current_dir(repo)
        .output()?;
    Ok(String::from_utf8(output.stdout)?
        .lines()
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect())
}

fn git_show(repo: &Path, rev: &str, file: &str) -> Option<String> {
    let output = Command::new("git")
        .args(["show", &format!("{}:{}", rev, file)])
        .current_dir(repo)
        .output()
        .ok()?;
    if output.status.success() {
        String::from_utf8(output.stdout).ok()
    } else {
        None
    }
}

fn short(hash: &str) -> &str {
    &hash[..8.min(hash.len())]
}

fn normalize(s: &str) -> String {
    s.lines()
        .map(|l| l.trim_end())
        .collect::<Vec<_>>()
        .join("\n")
}

fn print_inline_diff(weave: &str, human: &str) {
    let weave_lines: Vec<&str> = weave.lines().collect();
    let human_lines: Vec<&str> = human.lines().collect();
    let max = weave_lines.len().max(human_lines.len());
    let mut diffs = 0;
    for i in 0..max {
        let w = weave_lines.get(i).copied().unwrap_or("");
        let h = human_lines.get(i).copied().unwrap_or("");
        if w.trim_end() != h.trim_end() {
            if diffs == 0 {
                println!("         --- weave / +++ human ---");
            }
            println!("    L{:>4} - {}", i + 1, w);
            println!("    L{:>4} + {}", i + 1, h);
            diffs += 1;
            if diffs >= 10 {
                println!("    ... ({} more lines differ)", max - i - 1);
                break;
            }
        }
    }
    println!();
}

fn print_results(s: &Stats, repo_name: &str) {
    let total_git_conflicts = s.weave_wins + s.both_conflict;

    println!("results: {}", repo_name);
    println!("{}", "=".repeat(40));
    println!("merge commits:          {}", s.merge_commits);
    println!("files tested:           {}", s.files_tested);
    println!();
    println!("both clean:             {}", s.both_clean);
    println!("weave wins:             {}", s.weave_wins);
    println!("both conflict:          {}", s.both_conflict);
    println!("regressions:            {}", s.regressions);
    println!();

    if s.weave_wins > 0 {
        println!("of {} weave wins:", s.weave_wins);
        println!(
            "  matches human:  {} ({:.0}%)",
            s.matches_human,
            s.matches_human as f64 / s.weave_wins as f64 * 100.0
        );
        println!(
            "  differs:        {} ({:.0}%)",
            s.differs_from_human,
            s.differs_from_human as f64 / s.weave_wins as f64 * 100.0
        );
    }

    if total_git_conflicts > 0 {
        println!(
            "\nweave resolved {}/{} git conflicts ({:.0}%)",
            s.weave_wins,
            total_git_conflicts,
            s.weave_wins as f64 / total_git_conflicts as f64 * 100.0
        );
    }

    if s.regressions > 0 {
        println!(
            "\nWARNING: {} regressions (git clean, weave conflict)",
            s.regressions
        );
    }
}