-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathgit.rs
More file actions
959 lines (868 loc) · 32.5 KB
/
git.rs
File metadata and controls
959 lines (868 loc) · 32.5 KB
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
use std::collections::HashSet;
use std::path::Path;
use anyhow::{anyhow, Result};
#[cfg(test)]
#[path = "git_tests.rs"]
mod tests;
/// Runs a git command and returns the output as a string.
/// Thin wrapper over [`run_git_command_with_env`] with no `PATH` override.
#[cfg(feature = "local_fs")]
pub async fn run_git_command(repo_path: &Path, args: &[&str]) -> Result<String> {
run_git_command_with_env(repo_path, args, None).await
}
/// Like [`run_git_command`] but sets `PATH` on the child when `path_env` is
/// `Some`. Used by callers whose hooks need user-installed binaries (e.g.
/// the LFS `pre-push` hook → `git-lfs`). See `specs/APP-4188/TECH.md`.
#[cfg(feature = "local_fs")]
pub async fn run_git_command_with_env(
repo_path: &Path,
args: &[&str],
path_env: Option<&str>,
) -> Result<String> {
use command::r#async::Command;
use command::Stdio;
log::debug!(
"[GIT OPERATION] git.rs run_git_command git {}",
args.join(" ")
);
let mut cmd = Command::new(warp_util::wsl::git_binary());
cmd.arg("-c")
.arg("diff.autoRefreshIndex=false")
.args(args)
.current_dir(repo_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.env("GIT_OPTIONAL_LOCKS", "0")
.kill_on_drop(true);
if let Some(path_env) = path_env {
cmd.env("PATH", path_env);
}
let output = cmd
.output()
.await
.map_err(|e| anyhow!("Failed to execute git command: {}", e))?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr);
// Handle git diff specific behavior:
// - Exit code 0: no differences
// - Exit code 1: differences found (this is normal for diff commands)
// - Exit code > 1: actual error
if output.status.success() || (output.status.code() == Some(1) && !stdout.is_empty()) {
Ok(stdout)
} else {
Err(anyhow!("Git command failed: {}, {}", stderr, stdout))
}
}
#[cfg(not(feature = "local_fs"))]
pub async fn run_git_command(_repo_path: &Path, _args: &[&str]) -> Result<String> {
Err(anyhow!("Not supported on wasm"))
}
#[cfg(not(feature = "local_fs"))]
pub async fn run_git_command_with_env(
_repo_path: &Path,
_args: &[&str],
_path_env: Option<&str>,
) -> Result<String> {
Err(anyhow!("Not supported on wasm"))
}
/// Returns the set of local branch names for the repo at `repo_path`.
/// Uses a synchronous subprocess call — suitable for call sites in
/// synchronous view handlers where the result is needed immediately.
/// Returns an empty set on any failure (not a git repo, git not found, etc.).
#[cfg(feature = "local_fs")]
pub fn list_local_branches_sync(repo_path: &Path) -> HashSet<String> {
let output = command::blocking::Command::new(warp_util::wsl::git_binary())
.args(["branch", "--list", "--format=%(refname:short)"])
.current_dir(repo_path)
.stdout(command::Stdio::piped())
.stderr(command::Stdio::null())
.output();
match output {
Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout)
.lines()
.map(|line| line.trim().to_string())
.filter(|line| !line.is_empty())
.collect(),
_ => HashSet::new(),
}
}
#[cfg(not(feature = "local_fs"))]
pub fn list_local_branches_sync(_repo_path: &Path) -> HashSet<String> {
HashSet::new()
}
/// Fetches the current git branch.
#[cfg(not(feature = "local_fs"))]
pub async fn detect_current_branch(_repo_path: &Path) -> Result<String> {
Err(anyhow!("Not supported without local_fs"))
}
/// Fetches the current git branch.
/// In detached HEAD state this returns the literal string "HEAD".
#[cfg(feature = "local_fs")]
pub async fn detect_current_branch(repo_path: &Path) -> Result<String> {
log::debug!("[GIT OPERATION] git.rs detect_current_branch git rev-parse --abbrev-ref HEAD");
let result = run_git_command(repo_path, &["rev-parse", "--abbrev-ref", "HEAD"]).await;
if result.is_err() {
log::debug!("[GIT OPERATION] git.rs detect_current_branch git branch --show-current");
run_git_command(repo_path, &["branch", "--show-current"]).await
} else {
result
}
.map(|branch_name| branch_name.trim().to_owned())
}
/// Like [`detect_current_branch`], but in detached HEAD state returns the short
/// commit SHA instead of the literal "HEAD".
/// (Matches the shell command `git symbolic-ref --short HEAD || git rev-parse --short HEAD`.)
#[cfg(feature = "local_fs")]
pub async fn detect_current_branch_display(repo_path: &Path) -> Result<String> {
let branch = detect_current_branch(repo_path).await?;
if branch == "HEAD" {
run_git_command(repo_path, &["rev-parse", "--short", "HEAD"])
.await
.map(|sha| sha.trim().to_owned())
} else {
Ok(branch)
}
}
#[cfg(not(feature = "local_fs"))]
pub async fn detect_current_branch_display(_repo_path: &Path) -> Result<String> {
Err(anyhow!("Not supported without local_fs"))
}
/// Detects the main branch using git-branchless style heuristics.
#[cfg(not(feature = "local_fs"))]
pub async fn detect_main_branch(_repo_path: &Path) -> Result<String> {
Err(anyhow!("Not supported without local_fs"))
}
/// Detects the main branch using git-branchless style heuristics.
#[cfg(feature = "local_fs")]
pub async fn detect_main_branch(repo_path: &Path) -> Result<String> {
// First try to get the default branch from origin
log::debug!(
"[GIT OPERATION] git.rs detect_main_branch git symbolic-ref refs/remotes/origin/HEAD"
);
match run_git_command(repo_path, &["symbolic-ref", "refs/remotes/origin/HEAD"]).await {
Ok(output) => {
let branch_ref = output.trim();
if let Some(branch_name) = branch_ref.strip_prefix("refs/remotes/") {
return Ok(branch_name.to_string());
}
}
Err(_) => {
// If remote fetch fails, fall back to candidates.
}
}
// Fallback: try common main branch names in order of preference.
let candidates = ["origin/main", "origin/master", "main", "master", "develop"];
for candidate in candidates {
log::debug!(
"[GIT OPERATION] git.rs detect_main_branch git rev-parse --verify {candidate}^{{}}"
);
let result = run_git_command(
repo_path,
&["rev-parse", "--verify", &format!("{candidate}^{{}}")],
)
.await;
if result.is_ok() {
return Ok(candidate.to_string());
}
}
// Final fallback if all else fails.
log::debug!("[GIT OPERATION] git.rs detect_main_branch git branch --show-current");
run_git_command(repo_path, &["branch", "--show-current"]).await
}
/// Returns the SHA where `HEAD` forked from any other ref. Use
/// `<fork>..HEAD` for "commits unique to this branch".
#[cfg(not(feature = "local_fs"))]
pub async fn detect_fork_point(
_repo_path: &Path,
_current_branch_name: Option<&str>,
) -> Result<Option<String>> {
Err(anyhow!("Not supported without local_fs"))
}
/// See the no-`local_fs` stub above for documentation.
#[cfg(feature = "local_fs")]
pub async fn detect_fork_point(
repo_path: &Path,
current_branch_name: Option<&str>,
) -> Result<Option<String>> {
// Exclude `<current>` and `origin/<current>` so the branch isn't
// subtracted from itself.
let current = current_branch_name
.map(str::trim)
.filter(|branch| !branch.is_empty() && *branch != "HEAD");
let branch_exclude = current.map(|c| format!("--exclude={c}"));
let remote_exclude = current.map(|c| format!("--exclude=origin/{c}"));
let mut args: Vec<&str> = vec!["rev-list", "HEAD", "--not"];
args.extend(branch_exclude.as_deref());
args.push("--branches");
args.extend(remote_exclude.as_deref());
args.push("--remotes");
let unique = match run_git_command(repo_path, &args).await {
Ok(out) => out,
Err(e) => {
log::debug!("detect_fork_point: rev-list failed: {e}");
return Ok(None);
}
};
// Last non-empty line = oldest unique commit; its parent = fork point.
// No unique commits means HEAD is fully shared, so fork = HEAD.
let target = match unique.lines().rfind(|l| !l.trim().is_empty()) {
Some(sha) => format!("{}^", sha.trim()),
None => "HEAD".to_string(),
};
Ok(run_git_command(repo_path, &["rev-parse", &target])
.await
.ok()
.map(|s| s.trim().to_string()))
}
/// Git summary for a repo: current branch + uncommitted diff stats.
#[derive(Debug, Clone)]
#[cfg(feature = "local_fs")]
pub struct RepoGitSummary {
pub branch: String,
pub lines_added: u32,
pub lines_removed: u32,
}
/// Runs git commands in `repo_root` to get current branch + diff stats.
/// Returns None if not a git repo or git is unavailable.
#[cfg(feature = "local_fs")]
pub async fn get_repo_git_summary(repo_root: &Path) -> Option<RepoGitSummary> {
use crate::context_chips::display_chip::GitLineChanges;
let branch = {
log::debug!("[GIT OPERATION] git.rs get_repo_git_summary git symbolic-ref --short HEAD");
let result = run_git_command(repo_root, &["symbolic-ref", "--short", "HEAD"]).await;
match result {
Ok(output) => Some(output.trim().to_string()),
Err(_) => {
// Fallback to rev-parse for detached HEAD
log::debug!(
"[GIT OPERATION] git.rs get_repo_git_summary git rev-parse --short HEAD"
);
run_git_command(repo_root, &["rev-parse", "--short", "HEAD"])
.await
.ok()
.map(|o| o.trim().to_string())
}
}
};
// Tracked file changes (git diff --shortstat HEAD doesn't include untracked files).
log::debug!("[GIT OPERATION] git.rs get_repo_git_summary git diff --shortstat HEAD");
let stats = run_git_command(repo_root, &["diff", "--shortstat", "HEAD"])
.await
.ok()
.and_then(|o| GitLineChanges::parse_from_git_output(&o));
let mut lines_added = stats.as_ref().map_or(0, |s| s.lines_added);
let lines_removed = stats.as_ref().map_or(0, |s| s.lines_removed);
// Also count lines in untracked files to match what the git diff chip shows.
log::debug!(
"[GIT OPERATION] git.rs get_repo_git_summary git ls-files --others --exclude-standard"
);
if let Ok(untracked_output) =
run_git_command(repo_root, &["ls-files", "--others", "--exclude-standard"]).await
{
for file_name in untracked_output.lines() {
if file_name.is_empty() {
continue;
}
lines_added += count_lines_if_text_file(&repo_root.join(file_name));
}
}
let branch = branch?;
Some(RepoGitSummary {
branch,
lines_added,
lines_removed,
})
}
/// Short summary of a commit: hash and subject line.
#[derive(Debug, Clone)]
pub struct Commit {
pub hash: String,
pub subject: String,
pub files_changed: usize,
pub additions: usize,
pub deletions: usize,
}
/// A single changed file with per-file addition/deletion counts.
#[derive(Debug, Clone)]
pub struct FileChangeEntry {
pub path: String,
pub additions: usize,
pub deletions: usize,
}
/// Returns per-file change entries. When `include_unstaged` is true, returns all
/// uncommitted changes (staged + unstaged + untracked) vs HEAD; otherwise only staged changes.
#[cfg(feature = "local_fs")]
pub async fn get_file_change_entries(
repo_path: &Path,
include_unstaged: bool,
) -> Result<Vec<FileChangeEntry>> {
let args: &[&str] = if include_unstaged {
&["diff", "--numstat", "HEAD"]
} else {
&["diff", "--cached", "--numstat"]
};
let output = run_git_command(repo_path, args).await.unwrap_or_default();
let mut entries = Vec::new();
for line in output.lines() {
if line.is_empty() {
continue;
}
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 3 {
entries.push(FileChangeEntry {
path: parts[2].to_string(),
additions: parts[0].parse().unwrap_or(0),
deletions: parts[1].parse().unwrap_or(0),
});
}
}
// Also include untracked files when showing all changes.
if include_unstaged {
if let Ok(untracked) =
run_git_command(repo_path, &["ls-files", "--others", "--exclude-standard"]).await
{
for file_name in untracked.lines() {
if file_name.is_empty() {
continue;
}
let additions = count_lines_if_text_file(&repo_path.join(file_name)) as usize;
entries.push(FileChangeEntry {
path: file_name.to_string(),
additions,
deletions: 0,
});
}
}
}
Ok(entries)
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_file_change_entries(
_repo_path: &Path,
_include_unstaged: bool,
) -> Result<Vec<FileChangeEntry>> {
Err(anyhow!("Not supported on wasm"))
}
/// Unpushed commits: `<upstream>..HEAD`, or `<fork_point>..HEAD` if no upstream.
#[cfg(feature = "local_fs")]
pub async fn get_unpushed_commits(
repo_path: &Path,
current_branch_name: Option<&str>,
upstream_ref: Option<&str>,
) -> Result<Vec<Commit>> {
let output = if let Some(upstream_ref) = upstream_ref.map(str::trim).filter(|s| !s.is_empty()) {
let range = format!("{upstream_ref}..HEAD");
run_git_command(
repo_path,
&["log", &range, "--format=COMMIT:%H\t%s", "--numstat"],
)
.await?
} else {
// No upstream — fall back to the fork-point commit so we show
// exactly the commits unique to this branch
let fork_point = detect_fork_point(repo_path, current_branch_name)
.await
.ok()
.flatten();
let range = match fork_point {
Some(sha) => format!("{sha}..HEAD"),
None => "HEAD".to_string(),
};
run_git_command(
repo_path,
&["log", &range, "--format=COMMIT:%H\t%s", "--numstat"],
)
.await
.inspect_err(|e| log::warn!("Fallback unpushed-commits log failed: {e}"))
.unwrap_or_default()
};
parse_commit_log(&output)
}
#[cfg(feature = "local_fs")]
fn parse_commit_log(output: &str) -> Result<Vec<Commit>> {
let mut commits = Vec::new();
let mut current: Option<Commit> = None;
for line in output.lines() {
if let Some(rest) = line.strip_prefix("COMMIT:") {
if let Some(commit) = current.take() {
commits.push(commit);
}
let parts: Vec<&str> = rest.splitn(2, '\t').collect();
if parts.len() == 2 {
current = Some(Commit {
hash: parts[0].to_string(),
subject: parts[1].to_string(),
files_changed: 0,
additions: 0,
deletions: 0,
});
}
} else if !line.is_empty() {
// numstat line: "<additions>\t<deletions>\t<path>"
if let Some(ref mut commit) = current {
let parts: Vec<&str> = line.splitn(3, '\t').collect();
if parts.len() == 3 {
commit.additions += parts[0].parse::<usize>().unwrap_or(0);
commit.deletions += parts[1].parse::<usize>().unwrap_or(0);
commit.files_changed += 1;
}
}
}
}
if let Some(commit) = current {
commits.push(commit);
}
Ok(commits)
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_unpushed_commits(
_repo_path: &Path,
_current_branch_name: Option<&str>,
_upstream_ref: Option<&str>,
) -> Result<Vec<Commit>> {
Err(anyhow!("Not supported on wasm"))
}
/// Returns the list of files changed in a specific commit, with per-file stats.
#[cfg(feature = "local_fs")]
pub async fn get_commit_files(repo_path: &Path, hash: &str) -> Result<Vec<FileChangeEntry>> {
let output = run_git_command(
repo_path,
&[
"diff-tree",
"--root",
"--no-commit-id",
"-r",
"--numstat",
hash,
],
)
.await?;
let mut entries = Vec::new();
for line in output.lines() {
if line.is_empty() {
continue;
}
let parts: Vec<&str> = line.splitn(3, '\t').collect();
if parts.len() == 3 {
entries.push(FileChangeEntry {
path: parts[2].to_string(),
additions: parts[0].parse().unwrap_or(0),
deletions: parts[1].parse().unwrap_or(0),
});
}
}
Ok(entries)
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_commit_files(_repo_path: &Path, _hash: &str) -> Result<Vec<FileChangeEntry>> {
Err(anyhow!("Not supported on wasm"))
}
/// Maximum number of characters of diff content to send to AI for commit
/// message / PR title / PR description generation.
#[cfg(feature = "local_fs")]
const MAX_DIFF_CHARS_FOR_AI: usize = 16_000;
/// Per-file cap for untracked-file content we synthesise into the diff sent
/// to AI. Keeps any one new file from dominating the budget.
#[cfg(feature = "local_fs")]
const MAX_UNTRACKED_FILE_BYTES: usize = 4_000;
/// Number of leading bytes examined when classifying an untracked file as
/// binary, mirroring the heuristic in `count_lines_if_text_file`.
#[cfg(feature = "local_fs")]
const BINARY_CHECK_BYTES: usize = 1_024;
/// Maximum number of bytes in a PR title passed to `gh pr create`. GitHub's
/// hard limit is 256; we cap short of that to leave headroom for an
/// ellipsis marker. Measured in bytes because it's fed to
/// [`truncate_on_char_boundary`], which slices on byte offsets.
#[cfg(feature = "local_fs")]
const MAX_PR_TITLE_BYTES: usize = 200;
/// Returns a prefix of `s` whose length is at most `byte_cap` and which ends
/// on a UTF-8 char boundary. Plain `&s[..byte_cap]` panics when the cut
/// point lands inside a multi-byte code point, which is reachable in diffs
/// and source files containing non-ASCII text.
#[cfg(feature = "local_fs")]
fn truncate_on_char_boundary(s: &str, byte_cap: usize) -> &str {
if s.len() <= byte_cap {
return s;
}
let mut cut = byte_cap;
while cut > 0 && !s.is_char_boundary(cut) {
cut -= 1;
}
&s[..cut]
}
/// Returns the diff for commit message generation, truncated to avoid token
/// limits. When `include_unstaged` is true, diffs against HEAD (all
/// uncommitted changes) and also appends untracked files as synthetic diff
/// hunks so the LLM has full context even when the commit consists entirely
/// of new files. When `include_unstaged` is false, diffs only staged changes.
#[cfg(feature = "local_fs")]
pub async fn get_diff_for_commit_message(
repo_path: &Path,
include_unstaged: bool,
) -> Result<String> {
let mut diff = if !include_unstaged {
run_git_command(repo_path, &["diff", "--cached"]).await?
} else if run_git_command(repo_path, &["rev-parse", "--verify", "HEAD"])
.await
.is_ok()
{
run_git_command(repo_path, &["diff", "HEAD"]).await?
} else {
// No HEAD before the first commit. Include staged changes plus
// unstaged edits to staged files; untracked files are added below.
let mut diff = run_git_command(repo_path, &["diff", "--cached"]).await?;
diff.push_str(&run_git_command(repo_path, &["diff"]).await?);
diff
};
// `git diff HEAD` only shows changes to already-tracked files. New files that
// haven't been staged yet are invisible to it, so we synthesise diff hunks for
// them here — mirroring the logic in `get_file_change_entries`.
if include_unstaged {
if let Ok(untracked) = run_git_command(
repo_path,
&["ls-files", "--others", "--exclude-standard", "-z"],
)
.await
{
// `-z` separates paths with NUL bytes and disables C-style
// quoting, so paths containing spaces or non-ASCII characters
// round-trip intact.
// Cap the read to cover both the binary-check window and the
// synthesised-hunk budget.
let read_cap = BINARY_CHECK_BYTES.max(MAX_UNTRACKED_FILE_BYTES);
for file_name_bytes in untracked.as_bytes().split(|b| *b == 0) {
if file_name_bytes.is_empty() {
continue;
}
let Ok(file_name) = std::str::from_utf8(file_name_bytes) else {
continue;
};
let file_path = repo_path.join(file_name);
// Async + bounded so a large untracked file doesn't block
// the executor or balloon memory.
let Ok(file) = tokio::fs::File::open(&file_path).await else {
continue;
};
let mut bytes = Vec::with_capacity(read_cap);
use tokio::io::AsyncReadExt as _;
if file
.take(read_cap as u64)
.read_to_end(&mut bytes)
.await
.is_err()
{
continue;
}
let check_len = bytes.len().min(BINARY_CHECK_BYTES);
if warp_util::file_type::is_buffer_binary(&bytes[..check_len]) {
continue;
}
let Ok(content) = std::str::from_utf8(&bytes) else {
continue;
};
let content = truncate_on_char_boundary(content, MAX_UNTRACKED_FILE_BYTES);
let line_count = content.lines().count();
diff.push_str(&format!(
"diff --git a/{file_name} b/{file_name}\nnew file mode 100644\n\
--- /dev/null\n+++ b/{file_name}\n@@ -0,0 +1,{line_count} @@\n"
));
for line in content.lines() {
diff.push('+');
diff.push_str(line);
diff.push('\n');
}
}
}
}
if diff.len() <= MAX_DIFF_CHARS_FOR_AI {
Ok(diff)
} else {
Ok(format!(
"{}\n... (diff truncated)",
truncate_on_char_boundary(&diff, MAX_DIFF_CHARS_FOR_AI)
))
}
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_diff_for_commit_message(
_repo_path: &Path,
_include_unstaged: bool,
) -> Result<String> {
Err(anyhow!("Not supported on wasm"))
}
/// Commits changes. If `include_unstaged` is true, stages all changes first via `git add -A`.
/// `path_env` is forwarded so commit hooks can find tools on the user's `PATH`.
#[cfg(feature = "local_fs")]
pub async fn run_commit(
repo_path: &Path,
message: &str,
include_unstaged: bool,
path_env: Option<&str>,
) -> Result<String> {
if include_unstaged {
run_git_command_with_env(repo_path, &["add", "-A"], path_env).await?;
}
run_git_command_with_env(repo_path, &["commit", "-m", message], path_env).await
}
#[cfg(not(feature = "local_fs"))]
pub async fn run_commit(
_repo_path: &Path,
_message: &str,
_include_unstaged: bool,
_path_env: Option<&str>,
) -> Result<String> {
Err(anyhow!("Not supported on wasm"))
}
/// Per-file stats for what would land in a PR: default branch vs
/// `origin/<current>` (or HEAD when unpushed).
#[cfg(feature = "local_fs")]
pub async fn get_branch_diff_entries(repo_path: &Path) -> Result<Vec<FileChangeEntry>> {
let base = detect_main_branch(repo_path).await?;
let base = base.trim();
let current = detect_current_branch(repo_path).await?;
let remote_ref = format!("origin/{current}");
// Use the remote ref if it exists, otherwise fall back to HEAD.
let end_ref = if run_git_command(repo_path, &["rev-parse", "--verify", &remote_ref])
.await
.is_ok()
{
remote_ref
} else {
"HEAD".to_string()
};
let range = format!("{base}..{end_ref}");
let output = run_git_command(repo_path, &["diff", "--numstat", &range]).await?;
let mut entries = Vec::new();
for line in output.lines() {
if line.is_empty() {
continue;
}
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 3 {
entries.push(FileChangeEntry {
path: parts[2].to_string(),
additions: parts[0].parse().unwrap_or(0),
deletions: parts[1].parse().unwrap_or(0),
});
}
}
Ok(entries)
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_branch_diff_entries(_repo_path: &Path) -> Result<Vec<FileChangeEntry>> {
Err(anyhow!("Not supported on wasm"))
}
/// Pushes the given branch to origin, setting upstream tracking if not already configured.
/// `path_env` is forwarded so the LFS `pre-push` hook can find `git-lfs`.
#[cfg(feature = "local_fs")]
pub async fn run_push(repo_path: &Path, branch: &str, path_env: Option<&str>) -> Result<String> {
run_git_command_with_env(
repo_path,
&["push", "--set-upstream", "origin", branch],
path_env,
)
.await
}
#[cfg(not(feature = "local_fs"))]
pub async fn run_push(_repo_path: &Path, _branch: &str, _path_env: Option<&str>) -> Result<String> {
Err(anyhow!("Not supported on wasm"))
}
// ── gh CLI helpers ───────────────────────────────────────────────────────────
/// PR information returned by `gh pr view`.
#[derive(Debug, Clone)]
pub struct PrInfo {
pub number: u64,
pub url: String,
}
/// Runs a `gh` CLI command and returns stdout on success. `path_env`, when
/// `Some`, is set as the child's `PATH` so a Homebrew-installed `gh` is
/// findable from macOS GUI launches (launchd's minimal `PATH` excludes it).
#[cfg(feature = "local_fs")]
async fn run_gh_command(repo_path: &Path, args: &[&str], path_env: Option<&str>) -> Result<String> {
use command::r#async::Command;
use command::Stdio;
log::debug!(
"[GIT OPERATION] git.rs run_gh_command gh {}",
args.join(" ")
);
let mut cmd = Command::new(warp_util::wsl::gh_binary());
cmd.args(args)
.current_dir(repo_path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.env("HOMEBREW_NO_AUTO_UPDATE", "1")
.kill_on_drop(true);
if let Some(path_env) = path_env {
cmd.env("PATH", path_env);
}
let output = cmd
.output()
.await
.map_err(|e| anyhow!("Failed to execute gh command: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
if output.status.success() {
Ok(stdout)
} else {
Err(anyhow!("gh command failed: {stderr}"))
}
}
/// Looks up the PR for the current branch via `gh pr view`.
/// Returns `Ok(None)` if there is simply no PR for this branch.
/// Returns `Err` for real failures (auth, network, gh not installed).
#[cfg(feature = "local_fs")]
pub async fn get_pr_for_branch(repo_path: &Path, path_env: Option<&str>) -> Result<Option<PrInfo>> {
match run_gh_command(repo_path, &["pr", "view", "--json", "number,url"], path_env).await {
Ok(stdout) => {
let parsed: serde_json::Value = serde_json::from_str(stdout.trim())
.map_err(|e| anyhow!("Failed to parse gh output: {e}"))?;
let number = parsed["number"]
.as_u64()
.ok_or_else(|| anyhow!("Missing 'number' in gh output"))?;
let url = parsed["url"]
.as_str()
.ok_or_else(|| anyhow!("Missing 'url' in gh output"))?
.to_string();
Ok(Some(PrInfo { number, url }))
}
Err(e) => {
let msg = e.to_string();
if msg.contains("no pull requests found") {
Ok(None)
} else {
Err(e)
}
}
}
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_pr_for_branch(
_repo_path: &Path,
_path_env: Option<&str>,
) -> Result<Option<PrInfo>> {
Err(anyhow!("Not supported on wasm"))
}
/// PR-ready diff (default branch vs `origin/<current>` or HEAD),
/// truncated for AI token limits.
#[cfg(feature = "local_fs")]
pub async fn get_diff_for_pr(repo_path: &Path) -> Result<String> {
let base = detect_main_branch(repo_path).await?;
let base = base.trim();
let current = detect_current_branch(repo_path).await?;
let remote_ref = format!("origin/{current}");
let end_ref = if run_git_command(repo_path, &["rev-parse", "--verify", &remote_ref])
.await
.is_ok()
{
remote_ref
} else {
"HEAD".to_string()
};
let range = format!("{base}..{end_ref}");
let mut diff = run_git_command(repo_path, &["diff", &range]).await?;
if diff.len() > MAX_DIFF_CHARS_FOR_AI {
diff = format!(
"{}\n... (diff truncated)",
truncate_on_char_boundary(&diff, MAX_DIFF_CHARS_FOR_AI)
);
}
Ok(diff)
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_diff_for_pr(_repo_path: &Path) -> Result<String> {
Err(anyhow!("Not supported on wasm"))
}
/// Commit subject lines on the current branch since the default branch.
#[cfg(feature = "local_fs")]
pub async fn get_branch_commit_messages(repo_path: &Path) -> Result<Vec<String>> {
let base = detect_main_branch(repo_path).await?;
let base = base.trim();
let range = format!("{base}..HEAD");
let output = run_git_command(repo_path, &["log", &range, "--format=%s"]).await?;
Ok(output
.lines()
.filter(|l| !l.is_empty())
.map(|l| l.to_string())
.collect())
}
#[cfg(not(feature = "local_fs"))]
pub async fn get_branch_commit_messages(_repo_path: &Path) -> Result<Vec<String>> {
Err(anyhow!("Not supported on wasm"))
}
/// Creates a PR for the current branch (must already be pushed). Falls back
/// to `--fill` when title/body are `None`. Always targets the detected
/// default branch.
#[cfg(feature = "local_fs")]
pub async fn create_pr(
repo_path: &Path,
title: Option<&str>,
body: Option<&str>,
path_env: Option<&str>,
) -> Result<PrInfo> {
let base = detect_main_branch(repo_path).await?;
let base = base.trim();
let base = base.strip_prefix("origin/").unwrap_or(base);
let sanitized_title;
let args: Vec<&str> = match (title, body) {
(Some(t), Some(b)) => {
sanitized_title = sanitize_pr_title(t);
vec![
"pr",
"create",
"--base",
base,
"--title",
&sanitized_title,
"--body",
b,
]
}
_ => vec!["pr", "create", "--base", base, "--fill"],
};
let stdout = run_gh_command(repo_path, &args, path_env).await?;
// `gh pr create` prints the PR URL on success.
let url = stdout.trim().to_string();
// Extract PR number from the URL (e.g. https://github.com/owner/repo/pull/123)
let number = url
.rsplit('/')
.next()
.and_then(|s| s.parse::<u64>().ok())
.ok_or_else(|| anyhow!("Could not parse PR number from URL: {url}"))?;
Ok(PrInfo { number, url })
}
/// Trims an AI-generated PR title to a single line and caps its length.
#[cfg(feature = "local_fs")]
fn sanitize_pr_title(raw: &str) -> String {
let first_line = raw.lines().next().unwrap_or("").trim();
truncate_on_char_boundary(first_line, MAX_PR_TITLE_BYTES).to_string()
}
#[cfg(not(feature = "local_fs"))]
pub async fn create_pr(
_repo_path: &Path,
_title: Option<&str>,
_body: Option<&str>,
_path_env: Option<&str>,
) -> Result<PrInfo> {
Err(anyhow!("Not supported on wasm"))
}
/// Counts newlines in a file, returning 0 for binary or oversized files.
#[cfg(feature = "local_fs")]
fn count_lines_if_text_file(path: &Path) -> u32 {
const MAX_FILE_SIZE: u64 = 20_000_000;
const BINARY_CHECK_SIZE: usize = 1024;
let Ok(metadata) = std::fs::metadata(path) else {
return 0;
};
if metadata.len() > MAX_FILE_SIZE || !metadata.is_file() {
return 0;
}
let Ok(content) = std::fs::read(path) else {
return 0;
};
let check_len = content.len().min(BINARY_CHECK_SIZE);
if warp_util::file_type::is_buffer_binary(&content[..check_len]) {
return 0;
}
bytecount::count(&content, b'\n') as u32
}