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
|
-- Git staging plugin for micro editor
--
-- This plugin allows you to stage or unstage specific line ranges by selecting them.
--
-- Commands:
-- my-git-stage - Stage the currently selected lines (from unstaged changes)
-- my-git-unstage - Unstage the currently selected lines (from staged changes)
--
-- How it works:
-- 1. Select the lines you want to stage/unstage in the editor
-- 2. Run the command (my-git-stage or my-git-unstage)
-- 3. The plugin generates a modified patch containing only the selected changes
-- 4. The patch is applied to the git index using git apply --cached --recount
--
-- Inspired by gitu's selective staging implementation.
local micro = import("micro")
local config = import("micro/config")
local shell = import("micro/shell")
local util = import("micro/util")
local os = import("os")
-- Helper function to get selection line range
-- Returns: startLine, endLine (1-based), or nil if no selection
function getSelectionRange(cursor)
if not cursor:HasSelection() then
return nil, nil
end
local startLine = cursor.CurSelection[1].Y + 1 -- Convert to 1-based
local endLine = cursor.CurSelection[2].Y + 1
-- Ensure startLine <= endLine (in case selection was made backwards)
if startLine > endLine then
startLine, endLine = endLine, startLine
end
return startLine, endLine
end
-- Check if file is tracked by git
-- Returns: true/false
function isFileInGit(filePath)
local cmd = string.format("git ls-files --error-unmatch '%s' 2>/dev/null", filePath)
local handle = io.popen(cmd)
if not handle then
return false
end
local output = handle:read("*a")
local success = handle:close()
return success and output ~= ""
end
-- Get git diff for a file with context
-- cached: true for staged changes, false for unstaged changes
-- Returns: diff output string, or nil on error
function getDiffForFile(filePath, cached)
local cachedFlag = cached and "--cached" or ""
-- Use default 3 lines of context for proper patch generation
local cmd = string.format("git diff %s --no-ext-diff --no-color '%s' 2>&1",
cachedFlag, filePath)
local handle = io.popen(cmd)
if not handle then
return nil
end
local output = handle:read("*a")
handle:close()
-- Empty output means no changes
if not output or output == "" then
return nil
end
return output
end
-- Parse a unified diff hunk header line
-- Input: "@@ -1,3 +5,4 @@" or "@@ -1 +5,4 @@" etc.
-- Returns: oldStart, oldCount, newStart, newCount (all numbers)
function parseHunkHeader(line)
-- Match patterns like: @@ -oldStart,oldCount +newStart,newCount @@
-- Also handle single-line format: @@ -oldStart +newStart @@
local oldStart, oldCount, newStart, newCount = line:match("^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@")
if not oldStart then
return nil
end
-- Convert to numbers, default count to 1 if not specified
oldStart = tonumber(oldStart)
oldCount = oldCount ~= "" and tonumber(oldCount) or 1
newStart = tonumber(newStart)
newCount = newCount ~= "" and tonumber(newCount) or 1
return oldStart, oldCount, newStart, newCount
end
-- Parse diff output into header and hunks
-- Returns: {header = string, hunks = [{header = string, lines = {string}, newStart = num, newCount = num}]}
function parseDiff(diffOutput)
local lines = {}
for line in diffOutput:gmatch("[^\r\n]+") do
table.insert(lines, line)
end
local result = {
header = "",
hunks = {}
}
local i = 1
local headerLines = {}
-- Parse diff header (lines before first @@)
while i <= #lines and not lines[i]:match("^@@") do
table.insert(headerLines, lines[i])
i = i + 1
end
result.header = table.concat(headerLines, "\n") .. "\n"
-- Parse hunks
while i <= #lines do
if lines[i]:match("^@@") then
local hunkHeader = lines[i]
local oldStart, oldCount, newStart, newCount = parseHunkHeader(hunkHeader)
local hunk = {
header = hunkHeader,
lines = {},
newStart = newStart,
newCount = newCount
}
i = i + 1
-- Collect hunk lines (until next @@ or end)
while i <= #lines and not lines[i]:match("^@@") do
table.insert(hunk.lines, lines[i])
i = i + 1
end
table.insert(result.hunks, hunk)
else
i = i + 1
end
end
return result
end
-- Check if a hunk overlaps with the given line range
-- We check based on the "new" side (working tree for staging, index for unstaging)
function hunkOverlapsRange(newStart, newCount, rangeStart, rangeEnd)
local hunkEnd = newStart + newCount - 1
-- Hunk overlaps if: hunkStart <= rangeEnd AND hunkEnd >= rangeStart
return newStart <= rangeEnd and hunkEnd >= rangeStart
end
-- Modify hunk content to only include selected lines
-- This is the key transformation: convert unselected additions/deletions to context lines
-- mode: "normal" for staging, "reverse" for unstaging
-- rangeStart, rangeEnd: the selected line range in the file
function modifyHunkForLineRange(hunk, rangeStart, rangeEnd, mode)
-- Track which line in the file each hunk line corresponds to
local newStart = hunk.newStart
local currentLine = newStart
local modifiedLines = {}
for _, line in ipairs(hunk.lines) do
local firstChar = line:sub(1, 1)
local inRange = currentLine >= rangeStart and currentLine <= rangeEnd
if firstChar == '+' then
-- Addition line
if mode == "normal" then
-- Staging: keep + lines in range, discard others
if inRange then
table.insert(modifiedLines, line)
end
else
-- Unstaging (reverse mode): keep + lines in range, convert others to context
if inRange then
table.insert(modifiedLines, line)
else
-- Convert to context line
table.insert(modifiedLines, " " .. line:sub(2))
end
end
currentLine = currentLine + 1
elseif firstChar == '-' then
-- Deletion line
if mode == "normal" then
-- Staging: keep - lines in range, convert others to context
if inRange then
table.insert(modifiedLines, line)
else
-- Convert to context line
table.insert(modifiedLines, " " .. line:sub(2))
end
else
-- Unstaging (reverse mode): keep - lines in range, discard others
if inRange then
table.insert(modifiedLines, line)
end
end
-- Deletion lines don't advance currentLine (they're not in the "new" side)
elseif firstChar == ' ' then
-- Context line - always keep
table.insert(modifiedLines, line)
currentLine = currentLine + 1
elseif firstChar == '\\' then
-- "No newline at end of file" marker - keep it
table.insert(modifiedLines, line)
end
end
-- Return modified hunk
return {
header = hunk.header,
lines = modifiedLines
}
end
-- Filter and modify hunks to only include selected lines
-- Returns: modified hunks array
function filterAndModifyHunks(hunks, startLine, endLine, mode)
local result = {}
for _, hunk in ipairs(hunks) do
if hunkOverlapsRange(hunk.newStart, hunk.newCount, startLine, endLine) then
local modified = modifyHunkForLineRange(hunk, startLine, endLine, mode)
-- Only include if there are actual changes (not just context)
local hasChanges = false
for _, line in ipairs(modified.lines) do
local firstChar = line:sub(1, 1)
if firstChar == '+' or firstChar == '-' then
hasChanges = true
break
end
end
if hasChanges then
table.insert(result, modified)
end
end
end
return result
end
-- Build a complete patch from header and modified hunks
-- Returns: patch string
function buildPatch(header, hunks)
local parts = {}
-- Add header (it's already a multi-line string with trailing newline)
table.insert(parts, header)
-- Add hunks
for _, hunk in ipairs(hunks) do
table.insert(parts, hunk.header .. "\n")
for _, line in ipairs(hunk.lines) do
table.insert(parts, line .. "\n")
end
end
return table.concat(parts, "")
end
-- Apply a patch to the git index
-- reverse: true to unstage, false to stage
-- Returns: success (bool), error message (string or nil)
function applyPatchToIndex(patch, reverse)
-- Write patch to temp file
local tmpfile = string.format("%s/micro-git-patch-%d.patch", os.TempDir(), _G.os.time())
local f = io.open(tmpfile, "w")
if not f then
return false, "Failed to create temp file"
end
f:write(patch)
f:close()
-- Apply the patch to index
-- --recount is CRITICAL: it recalculates hunk headers after we modified the content
local reverseFlag = reverse and "--reverse" or ""
local cmd = string.format("git apply --cached --recount %s '%s' 2>&1", reverseFlag, tmpfile)
local handle = io.popen(cmd)
if not handle then
os.Remove(tmpfile)
return false, "Failed to run git apply"
end
local output = handle:read("*a")
local success = handle:close()
os.Remove(tmpfile)
if not success then
return false, "git apply failed: " .. output
end
return true, nil
end
-- Main function: stage selected lines
function gitStage(bp, args)
local filePath = bp.Buf.Path
-- Validate preconditions
if not filePath or filePath == "" then
micro.InfoBar():Error("✗ No file path - save the buffer first")
return
end
local startLine, endLine = getSelectionRange(bp.Cursor)
if not startLine then
micro.InfoBar():Error("✗ No selection - select lines to stage first")
return
end
if not isFileInGit(filePath) then
micro.InfoBar():Error("✗ File is not in a git repository")
return
end
-- Get unstaged changes
local diff = getDiffForFile(filePath, false)
if not diff then
micro.InfoBar():Error("✗ No unstaged changes in this file")
return
end
-- Parse and filter diff
local parsed = parseDiff(diff)
local modified = filterAndModifyHunks(parsed.hunks, startLine, endLine, "normal")
if #modified == 0 then
micro.InfoBar():Message("ℹ Selected lines have no unstaged changes")
return
end
-- Build and apply patch
local patch = buildPatch(parsed.header, modified)
local success, err = applyPatchToIndex(patch, false)
if not success then
micro.InfoBar():Error("✗ Failed to stage: " .. (err or "unknown error"))
return
end
-- Success message
local filename = filePath:match("([^/]+)$") or filePath
if startLine == endLine then
micro.InfoBar():Message(string.format("✓ Staged line %d in %s", startLine, filename))
else
micro.InfoBar():Message(string.format("✓ Staged lines %d-%d in %s", startLine, endLine, filename))
end
end
-- Main function: unstage selected lines
function gitUnstage(bp, args)
local filePath = bp.Buf.Path
-- Validate preconditions
if not filePath or filePath == "" then
micro.InfoBar():Error("✗ No file path - save the buffer first")
return
end
local startLine, endLine = getSelectionRange(bp.Cursor)
if not startLine then
micro.InfoBar():Error("✗ No selection - select lines to unstage first")
return
end
if not isFileInGit(filePath) then
micro.InfoBar():Error("✗ File is not in a git repository")
return
end
-- Get staged changes
local diff = getDiffForFile(filePath, true)
if not diff then
micro.InfoBar():Error("✗ No staged changes in this file")
return
end
-- Parse and filter diff
local parsed = parseDiff(diff)
local modified = filterAndModifyHunks(parsed.hunks, startLine, endLine, "reverse")
if #modified == 0 then
micro.InfoBar():Message("ℹ Selected lines have no staged changes")
return
end
-- Build and apply patch (in reverse to unstage)
local patch = buildPatch(parsed.header, modified)
local success, err = applyPatchToIndex(patch, true)
if not success then
micro.InfoBar():Error("✗ Failed to unstage: " .. (err or "unknown error"))
return
end
-- Success message
local filename = filePath:match("([^/]+)$") or filePath
if startLine == endLine then
micro.InfoBar():Message(string.format("✓ Unstaged line %d in %s", startLine, filename))
else
micro.InfoBar():Message(string.format("✓ Unstaged lines %d-%d in %s", startLine, endLine, filename))
end
end
|