graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Close destructive-git lexer false negatives (#1269)
Rach Pradhan2bf7daad6986
diff --git a/src/destructive_git.zig b/src/destructive_git.zigindex 0ddc0be6..5c81054f 100644--- a/src/destructive_git.zig+++ b/src/destructive_git.zig@@ -13,17 +13,21 @@//! --hard"` is still caught (and so is the same text inside a commit//! message: a known false positive, one extra y/n).//!-//! Flagged per subcommand:+//! Flagged per subcommand (a long option also in any unambiguous+//! abbreviation of 3+ letters, as git accepts them: `--har`, `--for`)://! reset --hard (any target)//! clean -f in any short bundle (-f, -df, -xdf, -d -f) or --force//! checkout -f/--force, a `--` pathspec, an argument no branch name can-//! spell (`.`, `./src`, `.env`, `:/`, a glob), or any long option-//! not on the branch-only list below+//! spell (`.`, `./src`, `.env`, `:/`, a glob), two positionals+//! (`<tree-ish> <path>`), or any long option not on the+//! branch-only list below//! restore any pathspec that reaches the working tree (not --staged alone)//! switch --discard-changes, -f/--force//! push --force*, -f, a `+refspec`, --mirror, --delete/-d, `:ref`, --prune//! branch -D, or delete (-d/--delete) with -f/--force//! stash drop, clear+//! config setting `alias.<name>` to any of the above (so does a global+//! `-c alias.<name>=<value>`); `!cmd` values are read as shell//!//! Deliberately not flagged: read-only verbs, `checkout -b`/`switch -c`,//! `restore --staged` (unstaging keeps the working tree), `clean -n`, and@@ -34,7 +38,7 @@const std = @import("std");pub fn isDestructiveGit(cmd: []const u8) bool {- return scan(cmd, 0);+ return scan(cmd, 0, .seek);}/// Nesting bound for quoted / substituted spans scanned as commands.@@ -42,10 +46,14 @@ const max_depth = 4;/// Longer words are compared on their prefix; flags and subcommands are short.const word_cap = 512;-fn scan(src: []const u8, depth: u8) bool {- if (std.mem.indexOf(u8, src, "git") == null) return false;+/// `start` is `.globals` when `src` is the argument list of a git+/// invocation (an alias value) rather than a shell command.+fn scan(src: []const u8, depth: u8, start: Segment.State) bool {+ // Fast path for plain text only: quotes and backslashes can spell git+ // without the literal letters (`g''it`, `g\it`).+ if (start == .seek and std.mem.indexOfAny(u8, src, "'\"\\") == null and !mentionsGit(src)) return false;var lx: Lexer = .{ .src = src, .depth = depth };- var seg: Segment = .{};+ var seg: Segment = .{ .depth = depth, .state = start };while (true) {const tok = lx.next();if (lx.nested_hit) return true;@@ -53,13 +61,21 @@ fn scan(src: []const u8, depth: u8) bool {.word => |w| seg.feed(w),.sep => {if (seg.verdict()) return true;- seg = .{};+ seg = .{ .depth = depth };},.end => return seg.verdict(),}}}+fn mentionsGit(src: []const u8) bool {+ var i: usize = 0;+ while (i + 3 <= src.len) : (i += 1) {+ if (std.ascii.eqlIgnoreCase(src[i..][0..3], "git")) return true;+ }+ return false;+}+const Tok = union(enum) { word: []const u8, sep, end };fn isBlank(c: u8) bool {@@ -91,18 +107,19 @@ const Lexer = struct {len: usize = 0,/// The next word or separator. Redirections (`>/dev/null`, `2>&1`,- /// `<<EOF`) are dropped with their target, so they neither glue onto a- /// flag nor read as an argument.+ /// `&>log`, `<<EOF`) are dropped with their target, so they neither glue+ /// onto a flag nor read as an argument.fn next(lx: *Lexer) Tok {const s = lx.src;while (true) {lx.skipBlanks();if (lx.i >= s.len) return .end;- if (isSep(s[lx.i])) {+ const amp_redirect = s[lx.i] == '&' and lx.i + 1 < s.len and s[lx.i + 1] == '>';+ if (isSep(s[lx.i]) and !amp_redirect) {while (lx.i < s.len and isSep(s[lx.i])) lx.i += 1;return .sep;}- if (isRedirect(s[lx.i])) {+ if (isRedirect(s[lx.i]) or amp_redirect) {while (lx.i < s.len and (isRedirect(s[lx.i]) or s[lx.i] == '&' or s[lx.i] == '|')) lx.i += 1;lx.skipBlanks();if (lx.i < s.len and !isSep(s[lx.i])) _ = lx.word(); // the target@@ -142,22 +159,13 @@ const Lexer = struct {lx.quoted(s[lx.i + 1 .. end]);lx.i = end + 1;},- '"' => {- var end = lx.i + 1;- while (end < s.len and s[end] != '"') : (end += 1) {- if (s[end] == '\\') end += 1;- }- end = @min(end, s.len);- lx.quoted(s[lx.i + 1 .. end]);- lx.i = end + 1;- },- '`' => {- const end = std.mem.indexOfScalarPos(u8, s, lx.i + 1, '`') orelse s.len;+ '"', '`' => {+ const end = spanEnd(s, lx.i + 1, c);lx.quoted(s[lx.i + 1 .. end]);lx.i = end + 1;},'$' => if (lx.i + 1 < s.len and s[lx.i + 1] == '(') {- const end = closingParen(s, lx.i + 2);+ const end = spanEnd(s, lx.i + 2, ')');lx.quoted(s[lx.i + 2 .. end]);lx.i = end + 1;} else {@@ -178,7 +186,7 @@ const Lexer = struct {/// mentions git it is scanned as a command in its own right.fn quoted(lx: *Lexer, inner: []const u8) void {for (inner) |c| lx.push(c);- if (lx.depth < max_depth and scan(inner, lx.depth + 1)) lx.nested_hit = true;+ if (lx.depth < max_depth and scan(inner, lx.depth + 1, .seek)) lx.nested_hit = true;}fn push(lx: *Lexer, c: u8) void {@@ -189,27 +197,54 @@ const Lexer = struct {}};-/// Index of the `)` closing a `$(` whose body starts at `from` (or s.len).-fn closingParen(s: []const u8, from: usize) usize {- var nest: usize = 1;+/// Index of the `closer` (`"`, backtick or the `)` of `$(`) ending a span+/// whose body starts at `from`, or s.len. Spans nested inside are skipped+/// whole, so `"$(git -C "$d" reset --hard)"` is one string and a `)` inside+/// quotes does not close a `$(`. Iterative with a fixed nesting stack; past+/// it the rest of the input is the span.+fn spanEnd(s: []const u8, from: usize, closer: u8) usize {+ var stack: [32]u8 = undefined;+ stack[0] = closer;+ var top: usize = 1;var i = from;while (i < s.len) : (i += 1) {- switch (s[i]) {- '(' => nest += 1,- ')' => {- nest -= 1;- if (nest == 0) return i;- },- else => {},+ const c = s[i];+ const in = stack[top - 1];+ if (c == in) {+ top -= 1;+ if (top == 0) return i;+ continue;}+ if (c == '\\') {+ i += 1;+ continue;+ }+ const opens: u8 = switch (in) {+ '"' => if (c == '`') '`' else if (c == '$' and i + 1 < s.len and s[i + 1] == '(') ')' else 0,+ ')' => switch (c) {+ '\'' => {+ i = std.mem.indexOfScalarPos(u8, s, i + 1, '\'') orelse return s.len;+ continue;+ },+ '"', '`' => c,+ '(' => ')',+ else => 0,+ },+ else => 0, // backticks: only `\` escapes+ };+ if (opens == 0) continue;+ if (top == stack.len) return s.len;+ if (c == '$') i += 1; // past the `(`+ stack[top] = opens;+ top += 1;}return s.len;}-const Sub = enum { none, reset, clean, checkout, restore, @"switch", push, branch, stash, other };+const Sub = enum { none, reset, clean, checkout, restore, @"switch", push, branch, stash, config, other };fn subOf(w: []const u8) Sub {- inline for (.{ "reset", "clean", "checkout", "restore", "switch", "push", "branch", "stash" }) |name| {+ inline for (.{ "reset", "clean", "checkout", "restore", "switch", "push", "branch", "stash", "config" }) |name| {if (std.mem.eql(u8, w, name)) return @field(Sub, name);}return .other;@@ -220,11 +255,36 @@ fn eqlAny(w: []const u8, set: []const []const u8) bool {return false;}-/// `git.exe` too, and any path to it (`/usr/bin/git`).+/// Whether long option `name` spells `full`: whole, or cut to 3+ letters+/// after the `--` (git takes any unambiguous prefix; an ambiguous one is an+/// error, so reading it as `full` costs at most a y/n).+fn abbrev(name: []const u8, full: []const u8, min: usize) bool {+ return name.len >= @max(min, 5) and std.mem.startsWith(u8, full, name);+}++fn abbrevAny(name: []const u8, set: []const []const u8) bool {+ for (set) |full| if (abbrev(name, full, 0)) return true;+ return false;+}++/// `git.exe` too, any path to it (`/usr/bin/git`), in any case (`GIT.EXE`).fn isGitWord(w: []const u8) bool {const start = if (std.mem.lastIndexOfAny(u8, w, "/\\")) |i| i + 1 else 0;const base = w[start..];- return std.mem.eql(u8, base, "git") or std.mem.eql(u8, base, "git.exe");+ return std.ascii.eqlIgnoreCase(base, "git") or std.ascii.eqlIgnoreCase(base, "git.exe");+}++/// A config key in the `alias` section (section names are case-blind).+fn isAliasKey(k: []const u8) bool {+ return k.len > "alias.".len and std.ascii.startsWithIgnoreCase(k, "alias.");+}++/// Whether an alias with value `v` runs something destructive: `!cmd` is a+/// shell command, anything else the arguments of a git invocation.+fn aliasRuns(v: []const u8, depth: u8) bool {+ if (depth >= max_depth) return false;+ if (v.len > 0 and v[0] == '!') return scan(v[1..], depth + 1, .seek);+ return scan(v, depth + 1, .globals);}/// git's global options that take the next word as their value.@@ -237,8 +297,13 @@ const checkout_branch_only = [_][]const u8{ "--track", "--no-track", "--detach",/// One `;`/`&&`/`|`-separated command: what the git invocation in it asks for.const Segment = struct {- state: enum { seek, globals, args } = .seek,+ const State = enum { seek, globals, args };++ depth: u8 = 0,+ state: State = .seek,skip_next: bool = false,+ cfg_next: bool = false, // the word after a global `-c`+ cfg_key: bool = false, // `config` saw an alias key; its value is nextsub: Sub = .none,after_dashdash: bool = false,positionals: usize = 0,@@ -254,18 +319,28 @@ const Segment = struct {seg.skip_next = false;return;}+ if (seg.cfg_next) {+ seg.cfg_next = false;+ const eq = std.mem.indexOfScalar(u8, w, '=') orelse return;+ if (isAliasKey(w[0..eq])) seg.hit = seg.hit or aliasRuns(w[eq + 1 ..], seg.depth);+ return;+ }if (w.len == 0) return; // `""`: nothing to classifyswitch (seg.state) {.seek => if (isGitWord(w)) {seg.state = .globals;},.globals => if (w.len > 1 and w[0] == '-') {- seg.skip_next = eqlAny(w, &global_valued);+ if (std.mem.eql(u8, w, "-c")) {+ seg.cfg_next = true;+ } else seg.skip_next = eqlAny(w, &global_valued);} else {seg.sub = subOf(w);seg.state = .args;},- .args => if (seg.after_dashdash) {+ .args => if (seg.cfg_key) {+ seg.positional(w); // an alias value may start with `-`+ } else if (seg.after_dashdash) {seg.path(w);} else if (std.mem.eql(u8, w, "--")) {seg.after_dashdash = true;@@ -288,24 +363,27 @@ const Segment = struct {.push => &.{ "--push-option", "--repo", "--receive-pack", "--exec" },.checkout => &.{"--orphan"},.@"switch" => &.{ "--orphan", "--create", "--force-create" },+ .config => &.{ "--file", "--blob", "--type", "--default", "--comment", "--value" },else => &.{},};- if (name.len == w.len and eqlAny(name, valued)) seg.skip_next = true;- const is_force = std.mem.eql(u8, name, "--force");+ if (name.len == w.len and abbrevAny(name, valued)) seg.skip_next = true;+ const is_force = abbrev(name, "--force", 0);switch (seg.sub) {- .reset => seg.hit = seg.hit or std.mem.eql(u8, name, "--hard"),+ .reset => seg.hit = seg.hit or abbrev(name, "--hard", 0),.clean => seg.hit = seg.hit or is_force,- .checkout => seg.hit = seg.hit or !eqlAny(name, &checkout_branch_only),+ .checkout => seg.hit = seg.hit or !abbrevAny(name, &checkout_branch_only),.restore => {- if (std.mem.eql(u8, name, "--staged")) seg.staged = true;- if (std.mem.eql(u8, name, "--worktree")) seg.worktree = true;- if (std.mem.eql(u8, name, "--pathspec-from-file")) seg.pathspec = true;+ if (abbrev(name, "--staged", 0)) seg.staged = true;+ if (abbrev(name, "--worktree", 0)) seg.worktree = true;+ // `--pathspec-f` could still be --pathspec-file-nul.+ if (abbrev(name, "--pathspec-from-file", "--pathspec-fr".len)) seg.pathspec = true;},- .@"switch" => seg.hit = seg.hit or is_force or std.mem.eql(u8, name, "--discard-changes"),- .push => seg.hit = seg.hit or std.mem.startsWith(u8, name, "--force") or eqlAny(name, &.{ "--mirror", "--delete", "--prune" }),+ .@"switch" => seg.hit = seg.hit or is_force or abbrev(name, "--discard-changes", 0),+ .push => seg.hit = seg.hit or is_force or std.mem.startsWith(u8, name, "--force") or+ abbrevAny(name, &.{ "--mirror", "--delete", "--prune" }),.branch => {if (is_force) seg.force = true;- if (std.mem.eql(u8, name, "--delete")) seg.delete = true;+ if (abbrev(name, "--delete", 0)) seg.delete = true;},else => {},}@@ -321,6 +399,7 @@ const Segment = struct {.checkout => "bB",.@"switch" => "cC",.branch => "u",+ .config => "f",else => "",};for (letters, 0..) |c, i| {@@ -364,6 +443,12 @@ const Segment = struct {.stash => if (seg.positionals == 0 and (std.mem.eql(u8, w, "drop") or std.mem.eql(u8, w, "clear"))) {seg.hit = true;},+ .config => if (seg.cfg_key) {+ seg.cfg_key = false;+ seg.hit = seg.hit or aliasRuns(w, seg.depth);+ } else if (isAliasKey(w)) {+ seg.cfg_key = true;+ },else => {},}}@@ -375,10 +460,12 @@ const Segment = struct {}fn verdict(seg: *const Segment) bool {- return switch (seg.sub) {+ return seg.hit or switch (seg.sub) {.restore => seg.pathspec and (!seg.staged or seg.worktree),- .branch => seg.hit or (seg.delete and seg.force),- else => seg.hit,+ .branch => seg.delete and seg.force,+ // `checkout <tree-ish> <path>` overwrites the path.+ .checkout => seg.positionals >= 2,+ else => false,};}};@@ -452,6 +539,43 @@ test "#1269: destructive git in every common spelling is flagged" {"git branch -d -f x","git branch -df x","git reset \\\n --hard",+ // Quotes and backslashes that spell git without the literal letters.+ "gi''t reset --hard",+ "g\"i\"t reset --hard",+ "\"g\"it clean -fdx",+ "g\\it push -f",+ "sh -c 'g\\it reset --hard'",+ // `$(...)` inside double quotes, with quotes of its own.+ "out=\"$(git -C \"$dir\" reset --hard)\"",+ "msg=\"$(git -C \"$d\" clean -fd 2>&1)\"",+ "echo \"$(git reset \"--hard\")\"",+ "echo $(echo \")\"; git reset --hard)",+ // Abbreviated long options.+ "git reset --har",+ "git clean --for",+ "git branch --del --force z",+ "git switch --discard main",+ "git push --mirro x",+ "git push --for",+ "git push origin --del old",+ "git restore --staged --wor .",+ "git checkout --for main",+ // Two positionals: `<tree-ish> <path>`.+ "git checkout main src/main.zig",+ "git checkout HEAD~1 src/a.zig",+ // `&>` / `&>>` redirect, not a separator.+ "git reset &>/dev/null --hard",+ "git clean &>/dev/null -fd",+ "git clean &>>log -fd",+ // Aliases whose value is destructive.+ "git config alias.x 'reset --hard' && git x",+ "git config --global alias.nuke '!git clean -fdx'",+ "git config set alias.x \"push --force\"",+ "git -c alias.x='reset --hard' x",+ "git -c 'alias.x=!git reset --hard' x",+ // Case-insensitive git word (Windows).+ "Git reset --hard",+ "GIT.EXE clean -fd",};for (cases) |c| std.testing.expect(isDestructiveGit(c)) catch |err| {std.debug.print("not flagged: {s}\n", .{c});@@ -500,6 +624,20 @@ test "#1269: read-only and branch-only git is not flagged" {"ls -la","echo reset --hard","",+ "git checkout --det",+ "git checkout --detach HEAD~1",+ "git checkout --orphan gh-pages main",+ "git log --grep 'reset --hard'",+ "git push --follow-tags",+ "git restore --staged --source=HEAD f",+ "git restore --sta f",+ "git config alias.st status",+ "git config --global alias.lg 'log --oneline'",+ "git -c alias.x=status x",+ "git status &>/dev/null && echo ok",+ "git status 2>&1 & git log",+ "echo \"$(git status)\"",+ "gitk --all &>/dev/null",};for (cases) |c| std.testing.expect(!isDestructiveGit(c)) catch |err| {std.debug.print("flagged: {s}\n", .{c});