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
use anyhow::Result;
use clap::Parser;
pub use git_surgeon::{diff, hunk_id, patch};
mod blame;
mod hunk;
mod skill;
mod update;
#[derive(Parser)]
#[command(name = "git-surgeon", version)]
#[command(about = "Non-interactive hunk-level git staging for AI agents")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(clap::Subcommand)]
enum Commands {
/// List hunks in the diff
Hunks {
/// Show staged hunks (git diff --cached)
#[arg(long)]
staged: bool,
/// Filter to a specific file
#[arg(long)]
file: Option<String>,
/// Show hunks from a specific commit
#[arg(long)]
commit: Option<String>,
/// Show full diff with line numbers (like show, but for all hunks)
#[arg(long)]
full: bool,
/// Show git blame information for each line
#[arg(long)]
blame: bool,
},
/// Show full diff for a specific hunk
Show {
/// Hunk ID
id: String,
/// Look up hunk in a specific commit
#[arg(long)]
commit: Option<String>,
},
/// Stage hunks by ID
Stage {
/// Hunk IDs to stage
ids: Vec<String>,
/// Hunk-relative line range (e.g. 5-30) to apply only part of a hunk
#[arg(long, value_parser = parse_line_range)]
lines: Option<(usize, usize)>,
},
/// Unstage hunks by ID
Unstage {
/// Hunk IDs to unstage
ids: Vec<String>,
/// Hunk-relative line range (e.g. 5-30) to apply only part of a hunk
#[arg(long, value_parser = parse_line_range)]
lines: Option<(usize, usize)>,
},
/// Discard working tree changes for hunks
Discard {
/// Hunk IDs to discard
ids: Vec<String>,
/// Hunk-relative line range (e.g. 5-30) to apply only part of a hunk
#[arg(long, value_parser = parse_line_range)]
lines: Option<(usize, usize)>,
},
/// Undo hunks from a commit, reverse-applying them to the working tree
Undo {
/// Hunk IDs to undo
ids: Vec<String>,
/// Commit to undo hunks from
#[arg(long)]
from: String,
/// Hunk-relative line range (e.g. 5-30) to apply only part of a hunk
#[arg(long, value_parser = parse_line_range)]
lines: Option<(usize, usize)>,
},
/// Fold one or more commits into an earlier commit (default: fold HEAD into the target)
Fold {
/// Target commit to fold changes into
target: String,
/// Source commit(s) to fold (defaults to HEAD). Multiple values fold all into target in one pass.
#[arg(long, num_args = 1.., action = clap::ArgAction::Append)]
from: Vec<String>,
},
/// Fold staged changes into an earlier commit
Amend {
/// Target commit to fold staged changes into
commit: String,
},
/// Move a commit to a different position in history
#[command(group = clap::ArgGroup::new("position").required(true))]
Move {
/// Commit SHA to move
commit: String,
/// Move after this commit
#[arg(long, group = "position")]
after: Option<String>,
/// Move before this commit
#[arg(long, group = "position")]
before: Option<String>,
/// Move to the end of the branch (after HEAD)
#[arg(long, group = "position")]
to_end: bool,
},
/// Hidden: rewrite rebase todo for fold or move
#[command(name = "_edit-todo", hide = true)]
EditTodo {
/// Path to the rebase todo file
file: String,
/// Source commit SHA(s)
#[arg(long, action = clap::ArgAction::Append)]
source: Vec<String>,
/// Target commit SHA
#[arg(long)]
target: String,
/// Rewrite mode: fixup (default Git todo action) or move
#[arg(long, default_value = "fixup")]
mode: String,
},
/// Change the commit message of an existing commit
Reword {
/// Target commit to reword
commit: String,
/// New commit message (multiple -m values are joined by blank lines)
#[arg(short, long, required = true, num_args = 1)]
message: Vec<String>,
},
/// Stage hunks and commit in one step
Commit {
/// Hunk IDs (optionally with :START-END range suffix)
ids: Vec<String>,
/// Commit message (multiple -m values are joined by blank lines, like git commit)
#[arg(short, long, required = true, num_args = 1)]
message: Vec<String>,
},
/// Commit hunks directly to another branch without checking it out
CommitTo {
/// Target branch name
branch: String,
/// Hunk IDs (optionally with :START-END range suffix)
ids: Vec<String>,
/// Commit message (multiple -m values are joined by blank lines, like git commit)
#[arg(short, long, required = true, num_args = 1)]
message: Vec<String>,
},
/// Undo all changes to specific files from a commit
UndoFile {
/// File paths to undo
files: Vec<String>,
/// Commit to undo files from
#[arg(long)]
from: String,
},
/// Split a commit into multiple commits by hunk selection
#[command(disable_help_flag = false)]
Split {
/// Commit to split (e.g. HEAD, abc1234)
commit: String,
/// Remaining args: --pick <ids...> -m <msg> [-m <body>...] [--rest-message <msg>...]
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Squash commits from <commit>..HEAD into a single commit
Squash {
/// The oldest commit to include. All commits from here to HEAD are combined.
commit: String,
/// Commit message (required)
#[arg(short, long, required = true, num_args = 1)]
message: Vec<String>,
/// Force squash even if range contains merge commits (which will be flattened)
#[arg(long)]
force: bool,
/// Do not preserve the author from the oldest commit (use current user instead)
#[arg(long)]
no_preserve_author: bool,
},
/// Update git-surgeon to the latest version
Update,
/// Hidden: background update check
#[command(name = "_check-update", hide = true)]
CheckUpdate,
/// Install the git-surgeon skill for AI coding assistants
InstallSkill {
/// Install for Claude Code (~/.claude/skills/)
#[arg(long)]
claude: bool,
/// Install for OpenCode (~/.config/opencode/skills/)
#[arg(long)]
opencode: bool,
/// Install for Codex (~/.codex/skills/)
#[arg(long)]
codex: bool,
},
}
/// A group of hunk IDs (with optional line ranges) and a commit message.
pub struct PickGroup {
pub ids: Vec<(String, Option<(usize, usize)>)>,
pub message_parts: Vec<String>,
}
/// Parse the trailing args of the split command into pick groups and optional rest-message.
fn parse_split_args(args: &[String]) -> anyhow::Result<(Vec<PickGroup>, Option<Vec<String>>)> {
let mut groups: Vec<PickGroup> = Vec::new();
let mut rest_messages: Vec<String> = Vec::new();
// State for the group currently being built
let mut current_ids: Vec<(String, Option<(usize, usize)>)> = Vec::new();
let mut current_msgs: Vec<String> = Vec::new();
let mut seen_rest = false;
// Helper to flush the current state into a PickGroup
fn flush_group(
groups: &mut Vec<PickGroup>,
ids: &mut Vec<(String, Option<(usize, usize)>)>,
msgs: &mut Vec<String>,
) -> anyhow::Result<()> {
if !ids.is_empty() {
if msgs.is_empty() {
anyhow::bail!("--pick group missing --message");
}
groups.push(PickGroup {
ids: std::mem::take(ids),
message_parts: std::mem::take(msgs),
});
} else if !msgs.is_empty() {
anyhow::bail!("--message without preceding --pick");
}
Ok(())
}
let mut i = 0;
while i < args.len() {
let arg = &args[i];
if arg == "--pick" {
if seen_rest {
anyhow::bail!("--pick not allowed after --rest-message");
}
// Only flush if current group has messages (preserves backwards compat
// with multiple --pick flags before --message)
if !current_msgs.is_empty() {
flush_group(&mut groups, &mut current_ids, &mut current_msgs)?;
}
i += 1;
// Collect IDs until we hit a flag
while i < args.len() && !args[i].starts_with('-') {
let parsed = parse_pick_id(&args[i])?;
current_ids.extend(parsed);
i += 1;
}
if current_ids.is_empty() {
anyhow::bail!("--pick requires at least one hunk ID");
}
} else if arg == "--message" || arg == "-m" {
if seen_rest {
anyhow::bail!("--message not allowed after --rest-message");
}
i += 1;
if i >= args.len() {
anyhow::bail!("--message requires a value");
}
if current_ids.is_empty() {
anyhow::bail!("--message without preceding --pick");
}
current_msgs.push(args[i].clone());
i += 1;
} else if arg == "--rest-message" {
// Flush any pending pick group first
flush_group(&mut groups, &mut current_ids, &mut current_msgs)?;
seen_rest = true;
i += 1;
if i >= args.len() {
anyhow::bail!("--rest-message requires a value");
}
rest_messages.push(args[i].clone());
i += 1;
} else {
anyhow::bail!("unexpected argument: {}", arg);
}
}
// Flush the final group
flush_group(&mut groups, &mut current_ids, &mut current_msgs)?;
if groups.is_empty() {
anyhow::bail!("at least one --pick ... --message pair is required");
}
let rest_message = if rest_messages.is_empty() {
None
} else {
Some(rest_messages)
};
Ok((groups, rest_message))
}
///// Parse a pick ID that may have comma-separated ranges (e.g., "id:2,5-6,34").
/// Returns a list of (id, optional range) tuples - one per range, or one with None if no ranges.
#[allow(clippy::type_complexity)]
fn parse_pick_id(s: &str) -> anyhow::Result<Vec<(String, Option<(usize, usize)>)>> {
if let Some((id, range_str)) = s.split_once(':') {
let mut results = Vec::new();
for part in range_str.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
let range = parse_line_range(part).map_err(|e| anyhow::anyhow!(e))?;
results.push((id.to_string(), Some(range)));
}
if results.is_empty() {
// Edge case: "id:" with nothing after
Ok(vec![(id.to_string(), None)])
} else {
Ok(results)
}
} else {
Ok(vec![(s.to_string(), None)])
}
}
fn parse_line_range(s: &str) -> Result<(usize, usize), String> {
let (start, end) = if let Some((a, b)) = s.split_once('-') {
let start: usize = a.parse().map_err(|_| "invalid start number".to_string())?;
let end: usize = b.parse().map_err(|_| "invalid end number".to_string())?;
(start, end)
} else {
let n: usize = s.parse().map_err(|_| "invalid line number".to_string())?;
(n, n)
};
if start == 0 || end == 0 || start > end {
return Err("range must be 1-based and start <= end".to_string());
}
Ok((start, end))
}
fn main() -> Result<()> {
let cli = Cli::parse();
// Show update notification on non-update commands
if !matches!(cli.command, Commands::Update | Commands::CheckUpdate) {
update::check_and_notify();
}
match cli.command {
Commands::Hunks {
staged,
file,
commit,
full,
blame,
} => hunk::list_hunks(staged, file.as_deref(), commit.as_deref(), full, blame)?,
Commands::Show { id, commit } => hunk::show_hunk(&id, commit.as_deref())?,
Commands::Stage { ids, lines } => hunk::apply_hunks(&ids, patch::ApplyMode::Stage, lines)?,
Commands::Unstage { ids, lines } => {
hunk::apply_hunks(&ids, patch::ApplyMode::Unstage, lines)?
}
Commands::Discard { ids, lines } => {
hunk::apply_hunks(&ids, patch::ApplyMode::Discard, lines)?
}
Commands::Commit { ids, message } => hunk::commit_hunks(&ids, &message.join("\n\n"))?,
Commands::CommitTo {
branch,
ids,
message,
} => hunk::commit_to_hunks(&branch, &ids, &message.join("\n\n"))?,
Commands::Fold { target, from } => hunk::fold(&target, &from)?,
Commands::Amend { commit } => hunk::amend(&commit)?,
Commands::Move {
commit,
after,
before,
to_end,
} => hunk::move_commit(&commit, after.as_deref(), before.as_deref(), to_end)?,
Commands::EditTodo {
file,
source,
target,
mode,
} => hunk::edit_todo(&file, &source, &target, &mode)?,
Commands::Reword { commit, message } => hunk::reword(&commit, &message.join("\n\n"))?,
Commands::Undo { ids, from, lines } => hunk::undo_hunks(&ids, &from, lines)?,
Commands::UndoFile { files, from } => hunk::undo_files(&files, &from)?,
Commands::Split { commit, args } => {
let (pick_groups, rest_message) = parse_split_args(&args)?;
hunk::split(&commit, &pick_groups, rest_message.as_deref())?;
}
Commands::Squash {
commit,
message,
force,
no_preserve_author,
} => {
hunk::squash(&commit, &message.join("\n\n"), force, !no_preserve_author)?;
}
Commands::Update => update::run()?,
Commands::CheckUpdate => update::run_background_check()?,
Commands::InstallSkill {
claude,
opencode,
codex,
} => {
let mut platforms = Vec::new();
if claude {
platforms.push(skill::Platform::Claude);
}
if opencode {
platforms.push(skill::Platform::OpenCode);
}
if codex {
platforms.push(skill::Platform::Codex);
}
skill::install_skill(&platforms)?;
}
}
Ok(())
}