diffstalker 0.1.6 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/release.yml +5 -3
- package/CHANGELOG.md +36 -0
- package/bun.lock +378 -0
- package/dist/App.js +1162 -1
- package/dist/config.js +83 -2
- package/dist/core/ExplorerStateManager.js +266 -0
- package/dist/core/FilePathWatcher.js +133 -0
- package/dist/core/GitOperationQueue.js +109 -1
- package/dist/core/GitStateManager.js +525 -1
- package/dist/git/diff.js +471 -10
- package/dist/git/ignoreUtils.js +30 -0
- package/dist/git/status.js +237 -5
- package/dist/index.js +70 -16
- package/dist/ipc/CommandClient.js +165 -0
- package/dist/ipc/CommandServer.js +152 -0
- package/dist/services/commitService.js +22 -1
- package/dist/state/CommitFlowState.js +86 -0
- package/dist/state/UIState.js +182 -0
- package/dist/themes.js +127 -1
- package/dist/types/tabs.js +4 -0
- package/dist/ui/Layout.js +252 -0
- package/dist/ui/modals/BaseBranchPicker.js +110 -0
- package/dist/ui/modals/DiscardConfirm.js +77 -0
- package/dist/ui/modals/HotkeysModal.js +209 -0
- package/dist/ui/modals/ThemePicker.js +107 -0
- package/dist/ui/widgets/CommitPanel.js +58 -0
- package/dist/ui/widgets/CompareListView.js +216 -0
- package/dist/ui/widgets/DiffView.js +279 -0
- package/dist/ui/widgets/ExplorerContent.js +102 -0
- package/dist/ui/widgets/ExplorerView.js +95 -0
- package/dist/ui/widgets/FileList.js +185 -0
- package/dist/ui/widgets/Footer.js +46 -0
- package/dist/ui/widgets/Header.js +111 -0
- package/dist/ui/widgets/HistoryView.js +69 -0
- package/dist/utils/ansiToBlessed.js +125 -0
- package/dist/utils/ansiTruncate.js +108 -0
- package/dist/utils/baseBranchCache.js +44 -2
- package/dist/utils/commitFormat.js +38 -1
- package/dist/utils/diffFilters.js +21 -1
- package/dist/utils/diffRowCalculations.js +113 -1
- package/dist/utils/displayRows.js +351 -2
- package/dist/utils/explorerDisplayRows.js +169 -0
- package/dist/utils/fileCategories.js +26 -1
- package/dist/utils/formatDate.js +39 -1
- package/dist/utils/formatPath.js +58 -1
- package/dist/utils/languageDetection.js +236 -0
- package/dist/utils/layoutCalculations.js +98 -1
- package/dist/utils/lineBreaking.js +88 -5
- package/dist/utils/mouseCoordinates.js +165 -1
- package/dist/utils/pathUtils.js +27 -0
- package/dist/utils/rowCalculations.js +246 -4
- package/dist/utils/wordDiff.js +50 -0
- package/package.json +15 -19
- package/dist/components/BaseBranchPicker.js +0 -1
- package/dist/components/BottomPane.js +0 -1
- package/dist/components/CommitPanel.js +0 -1
- package/dist/components/CompareListView.js +0 -1
- package/dist/components/ExplorerContentView.js +0 -3
- package/dist/components/ExplorerView.js +0 -1
- package/dist/components/FileList.js +0 -1
- package/dist/components/Footer.js +0 -1
- package/dist/components/Header.js +0 -1
- package/dist/components/HistoryView.js +0 -1
- package/dist/components/HotkeysModal.js +0 -1
- package/dist/components/Modal.js +0 -1
- package/dist/components/ScrollableList.js +0 -1
- package/dist/components/ThemePicker.js +0 -1
- package/dist/components/TopPane.js +0 -1
- package/dist/components/UnifiedDiffView.js +0 -1
- package/dist/hooks/useCommitFlow.js +0 -1
- package/dist/hooks/useCompareState.js +0 -1
- package/dist/hooks/useExplorerState.js +0 -9
- package/dist/hooks/useGit.js +0 -1
- package/dist/hooks/useHistoryState.js +0 -1
- package/dist/hooks/useKeymap.js +0 -1
- package/dist/hooks/useLayout.js +0 -1
- package/dist/hooks/useMouse.js +0 -1
- package/dist/hooks/useTerminalSize.js +0 -1
- package/dist/hooks/useWatcher.js +0 -11
package/dist/git/status.js
CHANGED
|
@@ -1,5 +1,237 @@
|
|
|
1
|
-
import{simpleGit
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { simpleGit } from 'simple-git';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { getIgnoredFiles } from './ignoreUtils.js';
|
|
5
|
+
// Parse git diff --numstat output into a map of path -> stats
|
|
6
|
+
export function parseNumstat(output) {
|
|
7
|
+
const stats = new Map();
|
|
8
|
+
for (const line of output.trim().split('\n')) {
|
|
9
|
+
if (!line)
|
|
10
|
+
continue;
|
|
11
|
+
const parts = line.split('\t');
|
|
12
|
+
if (parts.length >= 3) {
|
|
13
|
+
const insertions = parts[0] === '-' ? 0 : parseInt(parts[0], 10);
|
|
14
|
+
const deletions = parts[1] === '-' ? 0 : parseInt(parts[1], 10);
|
|
15
|
+
const filepath = parts.slice(2).join('\t'); // Handle paths with tabs
|
|
16
|
+
stats.set(filepath, { insertions, deletions });
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return stats;
|
|
20
|
+
}
|
|
21
|
+
// Count lines in a file (for untracked files which don't show in numstat)
|
|
22
|
+
async function countFileLines(repoPath, filePath) {
|
|
23
|
+
try {
|
|
24
|
+
const fullPath = path.join(repoPath, filePath);
|
|
25
|
+
const content = await fs.promises.readFile(fullPath, 'utf-8');
|
|
26
|
+
// Count non-empty lines
|
|
27
|
+
return content.split('\n').filter((line) => line.length > 0).length;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function parseStatusCode(code) {
|
|
34
|
+
switch (code) {
|
|
35
|
+
case 'M':
|
|
36
|
+
return 'modified';
|
|
37
|
+
case 'A':
|
|
38
|
+
return 'added';
|
|
39
|
+
case 'D':
|
|
40
|
+
return 'deleted';
|
|
41
|
+
case '?':
|
|
42
|
+
return 'untracked';
|
|
43
|
+
case 'R':
|
|
44
|
+
return 'renamed';
|
|
45
|
+
case 'C':
|
|
46
|
+
return 'copied';
|
|
47
|
+
default:
|
|
48
|
+
return 'modified';
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export async function getStatus(repoPath) {
|
|
52
|
+
const git = simpleGit(repoPath);
|
|
53
|
+
try {
|
|
54
|
+
const isRepo = await git.checkIsRepo();
|
|
55
|
+
if (!isRepo) {
|
|
56
|
+
return {
|
|
57
|
+
files: [],
|
|
58
|
+
branch: { current: '', ahead: 0, behind: 0 },
|
|
59
|
+
isRepo: false,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const status = await git.status();
|
|
63
|
+
const files = [];
|
|
64
|
+
// Process staged files
|
|
65
|
+
for (const file of status.staged) {
|
|
66
|
+
files.push({
|
|
67
|
+
path: file,
|
|
68
|
+
status: 'added',
|
|
69
|
+
staged: true,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
// Process modified staged files
|
|
73
|
+
for (const file of status.modified) {
|
|
74
|
+
// Check if it's in the index (staged)
|
|
75
|
+
const existingStaged = files.find((f) => f.path === file && f.staged);
|
|
76
|
+
if (!existingStaged) {
|
|
77
|
+
files.push({
|
|
78
|
+
path: file,
|
|
79
|
+
status: 'modified',
|
|
80
|
+
staged: false,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// Process deleted files
|
|
85
|
+
for (const file of status.deleted) {
|
|
86
|
+
files.push({
|
|
87
|
+
path: file,
|
|
88
|
+
status: 'deleted',
|
|
89
|
+
staged: false,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
// Process untracked files
|
|
93
|
+
for (const file of status.not_added) {
|
|
94
|
+
files.push({
|
|
95
|
+
path: file,
|
|
96
|
+
status: 'untracked',
|
|
97
|
+
staged: false,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
// Process renamed files
|
|
101
|
+
for (const file of status.renamed) {
|
|
102
|
+
files.push({
|
|
103
|
+
path: file.to,
|
|
104
|
+
originalPath: file.from,
|
|
105
|
+
status: 'renamed',
|
|
106
|
+
staged: true,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
// Use the files array from status for more accurate staging info
|
|
110
|
+
// The status.files array has detailed index/working_dir info
|
|
111
|
+
const processedFiles = [];
|
|
112
|
+
const seen = new Set();
|
|
113
|
+
// Collect untracked files to check if they're ignored
|
|
114
|
+
const untrackedPaths = status.files.filter((f) => f.working_dir === '?').map((f) => f.path);
|
|
115
|
+
// Get the set of ignored files
|
|
116
|
+
const ignoredFiles = await getIgnoredFiles(repoPath, untrackedPaths);
|
|
117
|
+
for (const file of status.files) {
|
|
118
|
+
// Skip ignored files (marked with '!' in either column, or detected by check-ignore)
|
|
119
|
+
if (file.index === '!' || file.working_dir === '!' || ignoredFiles.has(file.path)) {
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const key = `${file.path}-${file.index !== ' ' && file.index !== '?'}`;
|
|
123
|
+
if (seen.has(key))
|
|
124
|
+
continue;
|
|
125
|
+
seen.add(key);
|
|
126
|
+
// Staged changes (index column)
|
|
127
|
+
if (file.index && file.index !== ' ' && file.index !== '?') {
|
|
128
|
+
processedFiles.push({
|
|
129
|
+
path: file.path,
|
|
130
|
+
status: parseStatusCode(file.index),
|
|
131
|
+
staged: true,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
// Unstaged changes (working_dir column)
|
|
135
|
+
if (file.working_dir && file.working_dir !== ' ') {
|
|
136
|
+
processedFiles.push({
|
|
137
|
+
path: file.path,
|
|
138
|
+
status: file.working_dir === '?' ? 'untracked' : parseStatusCode(file.working_dir),
|
|
139
|
+
staged: false,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// Fetch line stats for staged and unstaged files
|
|
144
|
+
const [stagedNumstat, unstagedNumstat] = await Promise.all([
|
|
145
|
+
git.diff(['--cached', '--numstat']).catch(() => ''),
|
|
146
|
+
git.diff(['--numstat']).catch(() => ''),
|
|
147
|
+
]);
|
|
148
|
+
const stagedStats = parseNumstat(stagedNumstat);
|
|
149
|
+
const unstagedStats = parseNumstat(unstagedNumstat);
|
|
150
|
+
// Apply stats to files
|
|
151
|
+
for (const file of processedFiles) {
|
|
152
|
+
const stats = file.staged ? stagedStats.get(file.path) : unstagedStats.get(file.path);
|
|
153
|
+
if (stats) {
|
|
154
|
+
file.insertions = stats.insertions;
|
|
155
|
+
file.deletions = stats.deletions;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// Count lines for untracked files (not in numstat output)
|
|
159
|
+
const untrackedFiles = processedFiles.filter((f) => f.status === 'untracked');
|
|
160
|
+
if (untrackedFiles.length > 0) {
|
|
161
|
+
const lineCounts = await Promise.all(untrackedFiles.map((f) => countFileLines(repoPath, f.path)));
|
|
162
|
+
for (let i = 0; i < untrackedFiles.length; i++) {
|
|
163
|
+
untrackedFiles[i].insertions = lineCounts[i];
|
|
164
|
+
untrackedFiles[i].deletions = 0;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
files: processedFiles,
|
|
169
|
+
branch: {
|
|
170
|
+
current: status.current || 'HEAD',
|
|
171
|
+
tracking: status.tracking || undefined,
|
|
172
|
+
ahead: status.ahead,
|
|
173
|
+
behind: status.behind,
|
|
174
|
+
},
|
|
175
|
+
isRepo: true,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return {
|
|
180
|
+
files: [],
|
|
181
|
+
branch: { current: '', ahead: 0, behind: 0 },
|
|
182
|
+
isRepo: false,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
export async function stageFile(repoPath, filePath) {
|
|
187
|
+
const git = simpleGit(repoPath);
|
|
188
|
+
await git.add(filePath);
|
|
189
|
+
}
|
|
190
|
+
export async function unstageFile(repoPath, filePath) {
|
|
191
|
+
const git = simpleGit(repoPath);
|
|
192
|
+
await git.reset(['HEAD', '--', filePath]);
|
|
193
|
+
}
|
|
194
|
+
export async function stageAll(repoPath) {
|
|
195
|
+
const git = simpleGit(repoPath);
|
|
196
|
+
await git.add('-A');
|
|
197
|
+
}
|
|
198
|
+
export async function unstageAll(repoPath) {
|
|
199
|
+
const git = simpleGit(repoPath);
|
|
200
|
+
await git.reset(['HEAD']);
|
|
201
|
+
}
|
|
202
|
+
export async function discardChanges(repoPath, filePath) {
|
|
203
|
+
const git = simpleGit(repoPath);
|
|
204
|
+
// Restore the file to its state in HEAD (discard working directory changes)
|
|
205
|
+
await git.checkout(['--', filePath]);
|
|
206
|
+
}
|
|
207
|
+
export async function commit(repoPath, message, amend = false) {
|
|
208
|
+
const git = simpleGit(repoPath);
|
|
209
|
+
await git.commit(message, undefined, amend ? { '--amend': null } : undefined);
|
|
210
|
+
}
|
|
211
|
+
export async function getHeadMessage(repoPath) {
|
|
212
|
+
const git = simpleGit(repoPath);
|
|
213
|
+
try {
|
|
214
|
+
const log = await git.log({ n: 1 });
|
|
215
|
+
return log.latest?.message || '';
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return '';
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
export async function getCommitHistory(repoPath, count = 50) {
|
|
222
|
+
const git = simpleGit(repoPath);
|
|
223
|
+
try {
|
|
224
|
+
const log = await git.log({ n: count });
|
|
225
|
+
return log.all.map((entry) => ({
|
|
226
|
+
hash: entry.hash,
|
|
227
|
+
shortHash: entry.hash.slice(0, 7),
|
|
228
|
+
message: entry.message.split('\n')[0], // First line only
|
|
229
|
+
author: entry.author_name,
|
|
230
|
+
date: new Date(entry.date),
|
|
231
|
+
refs: entry.refs || '',
|
|
232
|
+
}));
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return [];
|
|
236
|
+
}
|
|
237
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,59 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import G8 from"neo-blessed";import o from"neo-blessed";var MK=0.05;function k8(K,$,J,X=1){let Z=X+4,Q=K-Z,q=Math.floor(Q*J),Y=Q-q;return{width:$,height:K,headerHeight:X,topPaneHeight:q,bottomPaneHeight:Y,footerRow:K-1}}function j8(K,$,J,X){let Z=$+1,Q=Z+J,q=Q+1,Y=q+X,V=K-1;return{stagingPaneStart:Z,fileListEnd:Q,diffPaneStart:q,diffPaneEnd:Y,footerRow:V}}class OK{screen;headerBox;topSeparator;topPane;middleSeparator;bottomPane;bottomSeparator;footerBox;_dimensions;_splitRatio;constructor(K,$=0.4){this.screen=K,this._splitRatio=$,this._dimensions=this.calculateDimensions(),this.headerBox=this.createHeaderBox(),this.topSeparator=this.createSeparator(this._dimensions.headerHeight),this.topPane=this.createTopPane(),this.middleSeparator=this.createSeparator(this._dimensions.headerHeight+1+this._dimensions.topPaneHeight),this.bottomPane=this.createBottomPane(),this.bottomSeparator=this.createSeparator(this._dimensions.headerHeight+2+this._dimensions.topPaneHeight+this._dimensions.bottomPaneHeight),this.footerBox=this.createFooterBox(),K.on("resize",()=>this.onResize())}get dimensions(){return this._dimensions}get splitRatio(){return this._splitRatio}setSplitRatio(K){this._splitRatio=Math.min(0.85,Math.max(0.15,K)),this.updateLayout()}adjustSplitRatio(K){this.setSplitRatio(this._splitRatio+K)}calculateDimensions(){let K=this.screen.height||24,$=this.screen.width||80;return k8(K,$,this._splitRatio)}createHeaderBox(){return o.box({parent:this.screen,top:0,left:0,width:"100%",height:this._dimensions.headerHeight,tags:!0})}createSeparator(K){let $=this.screen.width||80;return o.box({parent:this.screen,top:K,left:0,width:"100%",height:1,content:"─".repeat($),style:{fg:"gray"}})}createTopPane(){return o.box({parent:this.screen,top:this._dimensions.headerHeight+1,left:0,width:"100%",height:this._dimensions.topPaneHeight,tags:!0,scrollable:!0,alwaysScroll:!0,wrap:!1,scrollbar:{ch:" ",track:{bg:"gray"},style:{inverse:!0}}})}createBottomPane(){return o.box({parent:this.screen,top:this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,left:0,width:"100%",height:this._dimensions.bottomPaneHeight,tags:!0,scrollable:!0,alwaysScroll:!0,wrap:!1,scrollbar:{ch:" ",track:{bg:"gray"},style:{inverse:!0}}})}createFooterBox(){return o.box({parent:this.screen,top:this._dimensions.footerRow,left:0,width:"100%",height:1,tags:!0})}onResize(){this._dimensions=this.calculateDimensions(),this.updateLayout()}updateLayout(){this._dimensions=this.calculateDimensions();let K=this.screen.width||80;this.headerBox.height=this._dimensions.headerHeight,this.headerBox.width=K,this.topSeparator.top=this._dimensions.headerHeight,this.topSeparator.width=K,this.topSeparator.setContent("─".repeat(K)),this.topPane.top=this._dimensions.headerHeight+1,this.topPane.height=this._dimensions.topPaneHeight,this.topPane.width=K,this.middleSeparator.top=this._dimensions.headerHeight+1+this._dimensions.topPaneHeight,this.middleSeparator.width=K,this.middleSeparator.setContent("─".repeat(K)),this.bottomPane.top=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,this.bottomPane.height=this._dimensions.bottomPaneHeight,this.bottomPane.width=K,this.bottomSeparator.top=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight+this._dimensions.bottomPaneHeight,this.bottomSeparator.width=K,this.bottomSeparator.setContent("─".repeat(K)),this.footerBox.top=this._dimensions.footerRow,this.footerBox.width=K}getPaneBoundaries(){return j8(this._dimensions.height,this._dimensions.headerHeight,this._dimensions.topPaneHeight,this._dimensions.bottomPaneHeight)}screenYToTopPaneRow(K){let $=this._dimensions.headerHeight+1,J=$+this._dimensions.topPaneHeight;if(K<$||K>=J)return-1;return K-$}screenYToBottomPaneRow(K){let $=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,J=$+this._dimensions.bottomPaneHeight;if(K<$||K>=J)return-1;return K-$}get topPaneTop(){return this._dimensions.headerHeight+1}get bottomPaneTop(){return this._dimensions.headerHeight+2+this._dimensions.topPaneHeight}}import*as F from"node:fs";import*as c from"node:path";import*as t from"node:os";var M8={targetFile:c.join(t.homedir(),".cache","diffstalker","target"),watcherEnabled:!1,debug:!1,theme:"dark"},h=c.join(t.homedir(),".config","diffstalker","config.json"),O8=["dark","light","dark-colorblind","light-colorblind","dark-ansi","light-ansi"];function N8(K){return typeof K==="string"&&O8.includes(K)}function $7(){let K={...M8};if(process.env.DIFFSTALKER_PAGER)K.pager=process.env.DIFFSTALKER_PAGER;if(F.existsSync(h))try{let $=JSON.parse(F.readFileSync(h,"utf-8"));if($.pager)K.pager=$.pager;if($.targetFile)K.targetFile=$.targetFile;if(N8($.theme))K.theme=$.theme;if(typeof $.splitRatio==="number"&&$.splitRatio>=0.15&&$.splitRatio<=0.85)K.splitRatio=$.splitRatio}catch{}return K}function NK(K){let $=c.dirname(h);if(!F.existsSync($))F.mkdirSync($,{recursive:!0});let J={};if(F.existsSync(h))try{J=JSON.parse(F.readFileSync(h,"utf-8"))}catch{}Object.assign(J,K),F.writeFileSync(h,JSON.stringify(J,null,2)+`
|
|
3
|
+
`)}function J7(K){let $=c.dirname(K);if(!F.existsSync($))F.mkdirSync($,{recursive:!0})}function e(K){let $=t.homedir();if(K.startsWith($))return"~"+K.slice($.length);return K}function H8(K){let $=`{bold}{green-fg}${K.current}{/green-fg}{/bold}`;if(K.tracking)$+=` {gray-fg}→{/gray-fg} {blue-fg}${K.tracking}{/blue-fg}`;if(K.ahead>0)$+=` {green-fg}↑${K.ahead}{/green-fg}`;if(K.behind>0)$+=` {red-fg}↓${K.behind}{/red-fg}`;return $}function X7(K,$,J,X,Z,Q){if(!K)return"{gray-fg}Waiting for target path...{/gray-fg}";let q=e(K),Y=X==="Not a git repository",V=`{bold}{cyan-fg}${q}{/cyan-fg}{/bold}`;if(J)V+=" {yellow-fg}⟳{/yellow-fg}";if(Y)V+=" {yellow-fg}(not a git repository){/yellow-fg}";else if(X)V+=` {red-fg}(${X}){/red-fg}`;if(Z?.enabled&&Z.sourceFile){let z=e(Z.sourceFile);V+=` {gray-fg}(follow: ${z}){/gray-fg}`}let _=$?H8($):"";if(_){let z=q.length;if(J)z+=2;if(Y)z+=24;else if(X)z+=X.length+3;if(Z?.enabled&&Z.sourceFile){let k=e(Z.sourceFile);z+=10+k.length}let U=$?$.current.length+($.tracking?3+$.tracking.length:0)+($.ahead>0?3+String($.ahead).length:0)+($.behind>0?3+String($.behind).length:0):0,B=Math.max(1,Q-z-U-2);return V+" ".repeat(B)+_}return V}function Z7(K){return K.replace(/\{[^}]+\}/g,"").length}function Q7(K,$,J,X,Z,Q){let q="{gray-fg}?{/gray-fg} ";if(q+=$?"{yellow-fg}[scroll]{/yellow-fg}":"{yellow-fg}m:[select]{/yellow-fg}",q+=" ",q+=J?"{blue-fg}[auto]{/blue-fg}":"{gray-fg}[auto]{/gray-fg}",q+=" ",q+=X?"{blue-fg}[wrap]{/blue-fg}":"{gray-fg}[wrap]{/gray-fg}",K==="explorer")q+=" ",q+=Z?"{blue-fg}[dots]{/blue-fg}":"{gray-fg}[dots]{/gray-fg}";let V=[{key:"1",label:"Diff",tab:"diff"},{key:"2",label:"Commit",tab:"commit"},{key:"3",label:"History",tab:"history"},{key:"4",label:"Compare",tab:"compare"},{key:"5",label:"Explorer",tab:"explorer"}].map(({key:B,label:k,tab:G})=>{if(K===G)return`{bold}{cyan-fg}[${B}]${k}{/cyan-fg}{/bold}`;return`[${B}]${k}`}).join(" "),_=Z7(q),z=Z7(V),U=Math.max(1,Q-_-z);return q+" ".repeat(U)+V}function HK(K){let $=K.filter((Z)=>!Z.staged&&Z.status!=="untracked"),J=K.filter((Z)=>!Z.staged&&Z.status==="untracked"),X=K.filter((Z)=>Z.staged);return{modified:$,untracked:J,staged:X,ordered:[...$,...J,...X]}}function r(K,$){if(K.length<=$)return K;let X=Math.max($,20);if(K.length<=X)return K;let Z=K.split("/");if(Z.length===1){let U=Math.floor((X-1)/2);return K.slice(0,U)+"…"+K.slice(-(X-U-1))}let Q=Z[Z.length-1],q=Z[0],Y="/…/";if(q.length+Y.length+Q.length>X){let U=X-2;if(Q.length>U){let B=Math.floor((U-1)/2);return"…/"+Q.slice(0,B)+"…"+Q.slice(-(U-B-1))}return"…/"+Q}let _=q,z=1;while(z<Z.length-1){let U=Z[z],B=_+"/"+U;if(B.length+Y.length+Q.length<=X)_=B,z++;else break}if(z===Z.length-1)return K;return _+Y+Q}function T8(K){switch(K){case"modified":return"M";case"added":return"A";case"deleted":return"D";case"untracked":return"?";case"renamed":return"R";case"copied":return"C";default:return" "}}function E8(K){switch(K){case"modified":return"yellow";case"added":return"green";case"deleted":return"red";case"untracked":return"gray";case"renamed":return"blue";case"copied":return"cyan";default:return"white"}}function I8(K,$){if(K===void 0&&$===void 0)return"";let J=[];if(K!==void 0&&K>0)J.push(`{green-fg}+${K}{/green-fg}`);if($!==void 0&&$>0)J.push(`{red-fg}-${$}{/red-fg}`);return J.length>0?" "+J.join(" "):""}function KK(K){let{modified:$,untracked:J,staged:X}=HK(K),Z=[],Q=0;if($.length>0)Z.push({type:"header",content:"Modified:",headerColor:"yellow"}),$.forEach((q)=>{Z.push({type:"file",file:q,fileIndex:Q++})});if(J.length>0){if($.length>0)Z.push({type:"spacer"});Z.push({type:"header",content:"Untracked:",headerColor:"gray"}),J.forEach((q)=>{Z.push({type:"file",file:q,fileIndex:Q++})})}if(X.length>0){if($.length>0||J.length>0)Z.push({type:"spacer"});Z.push({type:"header",content:"Staged:",headerColor:"green"}),X.forEach((q)=>{Z.push({type:"file",file:q,fileIndex:Q++})})}return Z}function q7(K,$,J,X,Z=0,Q){if(K.length===0)return"{gray-fg} No changes{/gray-fg}";let q=KK(K),Y=X-12,V=Q?q.slice(Z,Z+Q):q.slice(Z),_=[];for(let z of V)if(z.type==="header")_.push(`{bold}{${z.headerColor}-fg}${z.content}{/${z.headerColor}-fg}{/bold}`);else if(z.type==="spacer")_.push("");else if(z.type==="file"&&z.file&&z.fileIndex!==void 0){let U=z.file,k=z.fileIndex===$&&J,G=T8(U.status),M=E8(U.status),T=U.staged?"[-]":"[+]",N=U.staged?"red":"green",H=I8(U.insertions,U.deletions),E=H.replace(/\{[^}]+\}/g,"").length,A=Y-E,j=r(U.path,A),O="";if(k)O+="{cyan-fg}{bold}▸ {/bold}{/cyan-fg}";else O+=" ";if(O+=`{${N}-fg}${T}{/${N}-fg} `,O+=`{${M}-fg}${G}{/${M}-fg} `,k)O+=`{cyan-fg}{inverse}${j}{/inverse}{/cyan-fg}`;else O+=j;if(U.originalPath)O+=` {gray-fg}← ${r(U.originalPath,30)}{/gray-fg}`;O+=H,_.push(O)}return _.join(`
|
|
4
|
+
`)}function Y7(K){return KK(K).length}function z7(K,$){let{ordered:J}=HK(K);return J[$]??null}function V7(K,$){let X=KK($)[K];if(X?.type==="file"&&X.fileIndex!==void 0)return X.fileIndex;return null}function TK(K,$){let J=KK($);for(let X=0;X<J.length;X++)if(J[X].type==="file"&&J[X].fileIndex===K)return X;return 0}var D8={name:"dark",displayName:"Dark",colors:{addBg:"#022800",delBg:"#3D0100",addHighlight:"#044700",delHighlight:"#5C0200",text:"white",addLineNum:"#368F35",delLineNum:"#A14040",contextLineNum:"gray",addSymbol:"greenBright",delSymbol:"redBright"}},R8={name:"light",displayName:"Light",colors:{addBg:"#69db7c",delBg:"#ffa8b4",addHighlight:"#2f9d44",delHighlight:"#d1454b",text:"black",addLineNum:"#2f9d44",delLineNum:"#d1454b",contextLineNum:"#6c757d",addSymbol:"green",delSymbol:"red"}},F8={name:"dark-colorblind",displayName:"Dark (colorblind)",colors:{addBg:"#004466",delBg:"#660000",addHighlight:"#0077b3",delHighlight:"#b30000",text:"white",addLineNum:"#0077b3",delLineNum:"#b30000",contextLineNum:"gray",addSymbol:"cyanBright",delSymbol:"redBright"}},v8={name:"light-colorblind",displayName:"Light (colorblind)",colors:{addBg:"#99ccff",delBg:"#ffcccc",addHighlight:"#3366cc",delHighlight:"#993333",text:"black",addLineNum:"#3366cc",delLineNum:"#993333",contextLineNum:"#6c757d",addSymbol:"blue",delSymbol:"red"}},L8={name:"dark-ansi",displayName:"Dark (ANSI)",colors:{addBg:"green",delBg:"red",addHighlight:"greenBright",delHighlight:"redBright",text:"white",addLineNum:"greenBright",delLineNum:"redBright",contextLineNum:"gray",addSymbol:"greenBright",delSymbol:"redBright"}},W8={name:"light-ansi",displayName:"Light (ANSI)",colors:{addBg:"green",delBg:"red",addHighlight:"greenBright",delHighlight:"redBright",text:"black",addLineNum:"green",delLineNum:"red",contextLineNum:"gray",addSymbol:"green",delSymbol:"red"}},$K={dark:D8,light:R8,"dark-colorblind":F8,"light-colorblind":v8,"dark-ansi":L8,"light-ansi":W8},C=["dark","light","dark-colorblind","light-colorblind","dark-ansi","light-ansi"];function s(K){return $K[K]??$K.dark}function JK(K){let J=new Date().getTime()-K.getTime(),X=Math.floor(J/3600000),Z=Math.floor(J/86400000);if(X<1)return`${Math.floor(J/60000)}m ago`;else if(X<48)return`${X}h ago`;else if(Z<=14)return`${Z}d ago`;else return K.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function U7(K){return K.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function y8(K){return!(K.startsWith("index ")||K.startsWith("--- ")||K.startsWith("+++ ")||K.startsWith("similarity index"))}function _7(K){if(K.type!=="header")return!0;return y8(K.content)}function XK(K,$,J=!0){if($<=0)return[{text:K,isContinuation:!1}];if(K.length<=$)return[{text:K,isContinuation:!1}];let X=[],Z=K,Q=!0;while(Z.length>0){if(Z.length<=$){X.push({text:Z,isContinuation:!Q});break}X.push({text:Z.slice(0,$),isContinuation:!Q}),Z=Z.slice($),Q=!1}if(J)S8(K,$,X);return X}function S8(K,$,J){let X=J.map((Z)=>Z.text).join("");if(X!==K)throw Error(`[LineBreaking] Content was lost during breaking!
|
|
5
|
+
Original (${K.length} chars): "${K.slice(0,50)}${K.length>50?"...":""}"
|
|
6
|
+
Joined (${X.length} chars): "${X.slice(0,50)}${X.length>50?"...":""}"`);for(let Z=0;Z<J.length;Z++){let Q=J[Z];if(Q.text.length>$&&$>=1)throw Error(`[LineBreaking] Segment ${Z} exceeds maxWidth!
|
|
7
|
+
Segment length: ${Q.text.length}, maxWidth: ${$}
|
|
8
|
+
Segment: "${Q.text.slice(0,50)}${Q.text.length>50?"...":""}"`)}if(J.length>0&&J[0].isContinuation)throw Error("[LineBreaking] First segment incorrectly marked as continuation!");for(let Z=1;Z<J.length;Z++)if(!J[Z].isContinuation)throw Error(`[LineBreaking] Segment ${Z} should be marked as continuation but isn't!`)}function EK(K,$){if($<=0)return 1;if(K.length<=$)return 1;return Math.ceil(K.length/$)}import d from"fast-diff";function B7(K,$){if(!K||!$)return!1;let J=d(K,$),X=0,Z=0;for(let[q,Y]of J)if(Z+=Y.length,q===d.EQUAL)X+=Y.length;if(Z===0)return!1;return X/Z>=0.5}function G7(K,$){let J=d(K,$),X=[],Z=[];for(let[Q,q]of J)if(Q===d.EQUAL)X.push({text:q,type:"same"}),Z.push({text:q,type:"same"});else if(Q===d.DELETE)X.push({text:q,type:"changed"});else if(Q===d.INSERT)Z.push({text:q,type:"changed"});return{oldSegments:X,newSegments:Z}}import{createEmphasize as P8}from"emphasize";import{common as C8}from"lowlight";var DK=P8(C8),b8={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",html:"xml",htm:"xml",xml:"xml",svg:"xml",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"ini",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",bat:"dos",cmd:"dos",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",cxx:"cpp",rs:"rust",go:"go",zig:"zig",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",groovy:"groovy",gradle:"groovy",py:"python",rb:"ruby",pl:"perl",lua:"lua",php:"php",r:"r",hs:"haskell",ml:"ocaml",fs:"fsharp",fsx:"fsharp",ex:"elixir",exs:"elixir",erl:"erlang",clj:"clojure",cljs:"clojure",cs:"csharp",vb:"vbnet",md:"markdown",markdown:"markdown",rst:"plaintext",txt:"plaintext",Makefile:"makefile",Dockerfile:"dockerfile",cmake:"cmake",ini:"ini",conf:"ini",cfg:"ini",sql:"sql",vim:"vim",diff:"diff",patch:"diff"},A7={Makefile:"makefile",makefile:"makefile",GNUmakefile:"makefile",Dockerfile:"dockerfile",dockerfile:"dockerfile",Jenkinsfile:"groovy",Vagrantfile:"ruby",Gemfile:"ruby",Rakefile:"ruby",".gitignore":"plaintext",".gitattributes":"plaintext",".editorconfig":"ini",".prettierrc":"json",".eslintrc":"json","tsconfig.json":"json","package.json":"json","package-lock.json":"json","bun.lockb":"plaintext","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","Cargo.toml":"ini","Cargo.lock":"ini","go.mod":"go","go.sum":"plaintext"},IK=null;function k7(){if(!IK)IK=new Set(DK.listLanguages());return IK}function ZK(K){if(!K)return null;let $=K.split("/").pop()??"";if(A7[$]){let Z=A7[$];return k7().has(Z)?Z:null}let J=$.includes(".")?$.split(".").pop()?.toLowerCase():null;if(!J)return null;let X=b8[J];if(!X)return null;return k7().has(X)?X:null}function j7(K,$){if(!K||!$)return K;try{return DK.highlight($,K).value}catch{return K}}function RK(K,$){if(!$||K.length===0)return K;try{let J=K.join(`
|
|
9
|
+
`);return DK.highlight($,J).value.replace(/\x1b\[0m/g,"\x1B[39m").split(`
|
|
10
|
+
`)}catch{return K}}function b(K){let $;if(K.type==="addition"||K.type==="deletion")$=K.content.slice(1);else if(K.type==="context")$=K.content.startsWith(" ")?K.content.slice(1):K.content;else $=K.content;return $.replace(/[\x00-\x08\x0a-\x1f\x7f]/g,"").replace(/\t/g," ")}function M7(K){switch(K.type){case"header":return{type:"diff-header",content:K.content};case"hunk":return{type:"diff-hunk",content:K.content};case"addition":return{type:"diff-add",lineNum:K.newLineNum,content:b(K)};case"deletion":return{type:"diff-del",lineNum:K.oldLineNum,content:b(K)};case"context":return{type:"diff-context",lineNum:K.oldLineNum??K.newLineNum,content:b(K)}}}function x8(K){let $=K.match(/^diff --git a\/.+ b\/(.+)$/);return $?$[1]:null}function FK(K){if(!K)return[];let $=K.lines.filter(_7),J=[],X=[],Z=null,Q=0;while(Q<$.length){let q=$[Q];if(q.type==="header"){let B=x8(q.content);if(B){if(Z)X.push(Z),J.push({type:"spacer"});Z={language:ZK(B),startRowIndex:J.length,oldContent:[],oldRowIndices:[],newContent:[],newRowIndices:[]}}J.push(M7(q)),Q++;continue}if(q.type==="hunk"){J.push(M7(q)),Q++;continue}if(q.type==="context"){let B=b(q),k=J.length;if(J.push({type:"diff-context",lineNum:q.oldLineNum??q.newLineNum,content:B}),Z&&Z.language)Z.oldContent.push(B),Z.oldRowIndices.push(k),Z.newContent.push(B),Z.newRowIndices.push(k);Q++;continue}let Y=[];while(Q<$.length&&$[Q].type==="deletion")Y.push($[Q]),Q++;let V=[];while(Q<$.length&&$[Q].type==="addition")V.push($[Q]),Q++;let _=new Map,z=new Map,U=Math.min(Y.length,V.length);for(let B=0;B<U;B++){let k=b(Y[B]),G=b(V[B]);if(B7(k,G)){let{oldSegments:M,newSegments:T}=G7(k,G);_.set(B,M),z.set(B,T)}}for(let B=0;B<Y.length;B++){let k=Y[B],G=b(k),M=_.get(B),T=J.length;if(J.push({type:"diff-del",lineNum:k.oldLineNum,content:G,...M&&{wordDiffSegments:M}}),Z&&Z.language&&!M)Z.oldContent.push(G),Z.oldRowIndices.push(T)}for(let B=0;B<V.length;B++){let k=V[B],G=b(k),M=z.get(B),T=J.length;if(J.push({type:"diff-add",lineNum:k.newLineNum,content:G,...M&&{wordDiffSegments:M}}),Z&&Z.language&&!M)Z.newContent.push(G),Z.newRowIndices.push(T)}}if(Z)X.push(Z);for(let q of X){if(!q.language)continue;if(q.oldContent.length>0){let Y=RK(q.oldContent,q.language);for(let V=0;V<q.oldRowIndices.length;V++){let _=q.oldRowIndices[V],z=J[_],U=Y[V];if(U&&U!==z.content&&(z.type==="diff-del"||z.type==="diff-context"))z.highlighted=U}}if(q.newContent.length>0){let Y=RK(q.newContent,q.language);for(let V=0;V<q.newRowIndices.length;V++){let _=q.newRowIndices[V],z=J[_],U=Y[V];if(U&&U!==z.content&&(z.type==="diff-add"||z.type==="diff-context"))z.highlighted=U}}}return J}function O7(K,$){let J=[];if(K){J.push({type:"commit-header",content:`commit ${K.hash}`}),J.push({type:"commit-header",content:`Author: ${K.author}`}),J.push({type:"commit-header",content:`Date: ${U7(K.date)}`}),J.push({type:"spacer"});for(let X of K.message.split(`
|
|
11
|
+
`))J.push({type:"commit-message",content:` ${X}`});J.push({type:"spacer"})}return J.push(...FK($)),J}function vK(K){let $=0;for(let J of K)if("lineNum"in J&&J.lineNum!==void 0)$=Math.max($,J.lineNum);return Math.max(3,String($).length)}function LK(K,$,J){if(!J)return K;let Z=Math.max(10,$),Q=[];for(let q of K)if(q.type==="diff-add"||q.type==="diff-del"||q.type==="diff-context"){let Y=q.content;if(!Y||Y.length<=Z){Q.push(q);continue}let V=XK(Y,Z);for(let _=0;_<V.length;_++){let z=V[_];Q.push({...q,content:z.text,lineNum:z.isContinuation?void 0:q.lineNum,isContinuation:z.isContinuation})}}else Q.push(q);return Q}var N7={30:"black",31:"red",32:"green",33:"yellow",34:"blue",35:"magenta",36:"cyan",37:"white",90:"gray",91:"red",92:"green",93:"yellow",94:"blue",95:"magenta",96:"cyan",97:"white"};function QK(K){if(!K)return"";let $=[],J="",X=0;while(X<K.length){if(K[X]==="\x1B"&&K[X+1]==="["){let Q=X+2;while(Q<K.length&&K[Q]!=="m")Q++;if(K[Q]==="m"){let q=K.slice(X+2,Q).split(";").map(Number);for(let Y of q)if(Y===0)while($.length>0){let V=$.pop();if(V)J+=`{/${V}}`}else if(Y===1)$.push("bold"),J+="{bold}";else if(Y===2)$.push("gray-fg"),J+="{gray-fg}";else if(Y===3);else if(Y===4)$.push("underline"),J+="{underline}";else if(Y>=30&&Y<=37){let V=N7[Y];if(V)$.push(`${V}-fg`),J+=`{${V}-fg}`}else if(Y>=90&&Y<=97){let V=N7[Y];if(V)$.push(`${V}-fg`),J+=`{${V}-fg}`}X=Q+1;continue}}let Z=K[X];if(Z==="{"||Z==="}")J+=Z+Z;else J+=Z;X++}while($.length>0){let Z=$.pop();if(Z)J+=`{/${Z}}`}return J}var H7=/\x1b\[[0-9;]*m/g;function qK(K,$,J="…"){if($<=0)return J;if(!K.includes("\x1B")&&K.length<=$)return K;if(!K.includes("\x1B")){if(K.length<=$)return K;return K.slice(0,$-J.length)+J}let X=[],Z=0;H7.lastIndex=0;let Q;while((Q=H7.exec(K))!==null){if(Q.index>Z)X.push({type:"text",content:K.slice(Z,Q.index)});X.push({type:"ansi",content:Q[0]}),Z=Q.index+Q[0].length}if(Z<K.length)X.push({type:"text",content:K.slice(Z)});let q="",Y=0,V=$-J.length,_=!1,z=!1;for(let U of X)if(U.type==="ansi")q+=U.content,_=!0;else{let B=V-Y;if(B<=0){z=!0;break}if(U.content.length<=B)q+=U.content,Y+=U.content.length;else{q+=U.content.slice(0,B),Y+=B,z=!0;break}}if(z){if(_)q+="\x1B[0m";q+=J}return q}function R(K,$){if($<=0||K.length<=$)return K;if($<=1)return"…";return K.slice(0,$-1)+"…"}function WK(K,$){if(K===void 0)return" ".repeat($);return String(K).padStart($," ")}function x(K){return K.replace(/\{/g,"{{").replace(/\}/g,"}}")}function YK(K){let $=parseInt(K.slice(1,3),16),J=parseInt(K.slice(3,5),16),X=parseInt(K.slice(5,7),16);return`\x1B[48;2;${$};${J};${X}m`}function T7(K){let $=parseInt(K.slice(1,3),16),J=parseInt(K.slice(3,5),16),X=parseInt(K.slice(5,7),16);return`\x1B[38;2;${$};${J};${X}m`}var v="\x1B[0m";function E7(K,$,J,X,Z,Q){let{colors:q}=Z;switch(K.type){case"diff-header":{let Y=K.content;if(Y.startsWith("diff --git")){let V=Y.match(/diff --git a\/.+ b\/(.+)$/);if(V){let _=X-6;return`{bold}{cyan-fg}── ${R(V[1],_)} ──{/cyan-fg}{/bold}`}}return`{gray-fg}${x(R(Y,X))}{/gray-fg}`}case"diff-hunk":{let Y=K.content.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/);if(Y){let V=parseInt(Y[1],10),_=Y[2]?parseInt(Y[2],10):1,z=parseInt(Y[3],10),U=Y[4]?parseInt(Y[4],10):1,B=Y[5].trim(),k=V+_-1,G=z+U-1,M=_===1?`${V}`:`${V}-${k}`,T=U===1?`${z}`:`${z}-${G}`,N=`Lines ${M} → ${T}`,H=X-N.length-1,E=B&&H>3?" "+R(B,H):"";return`{cyan-fg}${N}{/cyan-fg}{gray-fg}${E}{/gray-fg}`}return`{cyan-fg}${x(R(K.content,X))}{/cyan-fg}`}case"diff-add":{let Y=K.isContinuation,V=Y?"»":"+",z=`${WK(K.lineNum,$)} ${V} `;if(Z.name.includes("ansi")){let N=Q?K.content||"":R(K.content||"",J),E=`${z}${N}`.padEnd(X," ");return`{green-bg}{white-fg}${x(E)}{/white-fg}{/green-bg}`}let U=YK(q.addBg),B=YK(q.addHighlight),k=T7("#ffffff");if(K.wordDiffSegments&&!Y){let N=K.content||"";if(!Q&&N.length>J){let j=R(N,J),D=`${z}${j}`.padEnd(X," ");return`{escape}${U}${k}${D}${v}{/escape}`}let H="";for(let j of K.wordDiffSegments)if(j.type==="changed")H+=`${B}${j.text}${U}`;else H+=j.text;let E=z.length+N.length,A=" ".repeat(Math.max(0,X-E));return`{escape}${U}${k}${z}${H}${A}${v}{/escape}`}if(K.highlighted&&!Y){let N=K.content||"";if(!Q&&N.length>J){let A=R(N,J),O=`${z}${A}`.padEnd(X," ");return`{escape}${U}${k}${O}${v}{/escape}`}let H=z.length+N.length,E=" ".repeat(Math.max(0,X-H));return`{escape}${U}${k}${z}${K.highlighted}${E}${v}{/escape}`}let G=Q?K.content||"":R(K.content||"",J),T=`${z}${G}`.padEnd(X," ");return`{escape}${U}${k}${T}${v}{/escape}`}case"diff-del":{let Y=K.isContinuation,V=Y?"»":"-",z=`${WK(K.lineNum,$)} ${V} `;if(Z.name.includes("ansi")){let N=Q?K.content||"":R(K.content||"",J),E=`${z}${N}`.padEnd(X," ");return`{red-bg}{white-fg}${x(E)}{/white-fg}{/red-bg}`}let U=YK(q.delBg),B=YK(q.delHighlight),k=T7("#ffffff");if(K.wordDiffSegments&&!Y){let N=K.content||"";if(!Q&&N.length>J){let j=R(N,J),D=`${z}${j}`.padEnd(X," ");return`{escape}${U}${k}${D}${v}{/escape}`}let H="";for(let j of K.wordDiffSegments)if(j.type==="changed")H+=`${B}${j.text}${U}`;else H+=j.text;let E=z.length+N.length,A=" ".repeat(Math.max(0,X-E));return`{escape}${U}${k}${z}${H}${A}${v}{/escape}`}if(K.highlighted&&!Y){let N=K.content||"";if(!Q&&N.length>J){let A=R(N,J),O=`${z}${A}`.padEnd(X," ");return`{escape}${U}${k}${O}${v}{/escape}`}let H=z.length+N.length,E=" ".repeat(Math.max(0,X-H));return`{escape}${U}${k}${z}${K.highlighted}${E}${v}{/escape}`}let G=Q?K.content||"":R(K.content||"",J),T=`${z}${G}`.padEnd(X," ");return`{escape}${U}${k}${T}${v}{/escape}`}case"diff-context":{let Y=K.isContinuation,V=Y?"»":" ",z=`${WK(K.lineNum,$)} ${V} `,U=K.content||"";if(K.highlighted&&!Y){let k=Q?K.highlighted:qK(K.highlighted,J),G=QK(k);return`{gray-fg}${z}{/gray-fg}${G}`}let B=Q?x(U):x(R(U,J));return`{gray-fg}${z}{/gray-fg}${B}`}case"commit-header":return`{yellow-fg}${x(R(K.content,X))}{/yellow-fg}`;case"commit-message":return x(R(K.content,X));case"spacer":return""}}function yK(K,$,J=0,X,Z="dark",Q=!1){let q=FK(K);if(q.length===0)return{content:"{gray-fg}No diff to display{/gray-fg}",totalRows:0};let Y=s(Z),V=vK(q),_=$-V-5,z=$-2,U=LK(q,_,Q),B=U.length;return{content:(X?U.slice(J,J+X):U.slice(J)).map((M)=>E7(M,V,_,z,Y,Q)).join(`
|
|
12
|
+
`),totalRows:B}}function I7(K,$,J,X=0,Z,Q="dark",q=!1){let Y=O7(K,$);if(Y.length===0)return{content:"{gray-fg}No commit selected{/gray-fg}",totalRows:0};let V=s(Q),_=vK(Y),z=J-_-5,U=J-2,B=LK(Y,z,q),k=B.length;return{content:(Z?B.slice(X,X+Z):B.slice(X)).map((T)=>E7(T,_,z,U,V,q)).join(`
|
|
13
|
+
`),totalRows:k}}function D7(K,$,J){let X=[],Z="{bold}Commit Message{/bold}";if(K.amend)Z+=" {yellow-fg}(amending){/yellow-fg}";X.push(Z),X.push("");let Q=K.inputFocused?"│":"│",q=K.inputFocused?"cyan":"gray",Y=Math.max(20,J-6);X.push(`{${q}-fg}┌${"─".repeat(Y+2)}┐{/${q}-fg}`);let V=K.message||(K.inputFocused?"":"Press i or Enter to edit..."),_=K.message?"":"{gray-fg}",z=K.message?"":"{/gray-fg}",U=V.length>Y?V.slice(0,Y-1)+"…":V.padEnd(Y);X.push(`{${q}-fg}${Q}{/${q}-fg} ${_}${U}${z} {${q}-fg}${Q}{/${q}-fg}`),X.push(`{${q}-fg}└${"─".repeat(Y+2)}┘{/${q}-fg}`),X.push("");let B=K.amend?"[x]":"[ ]",k=K.amend?"green":"gray";if(X.push(`{${k}-fg}${B}{/${k}-fg} Amend {gray-fg}(a){/gray-fg}`),K.error)X.push(""),X.push(`{red-fg}${K.error}{/red-fg}`);if(K.isCommitting)X.push(""),X.push("{yellow-fg}Committing...{/yellow-fg}");X.push("");let G=K.inputFocused?"Enter: commit | Esc: unfocus":"i/Enter: edit | Esc: cancel | a: toggle amend";return X.push(`{gray-fg}Staged: ${$} file(s) | ${G}{/gray-fg}`),X.join(`
|
|
14
|
+
`)}function w8(K,$){if(K.length<=$)return K;if($<=3)return K.slice(0,$);return K.slice(0,$-3)+"..."}function zK(K,$,J,X=20){let Z=$||"",Q=Math.max(0,J-X-1),q=Z;if(q.length>Q&&Q>3)q=q.slice(0,Q-3)+"...";else if(q.length>Q)q="";let Y=q?q.length+1:0,V=Math.max(X,J-Y);return{displayMessage:w8(K,V),displayRefs:q}}function R7(K,$,J,X,Z=0,Q){if(K.length===0)return"{gray-fg}No commits yet{/gray-fg}";let q=Q?K.slice(Z,Z+Q):K.slice(Z),Y=[];for(let V=0;V<q.length;V++){let _=q[V],B=Z+V===$&&J,k=JK(_.date),G=11+k.length+2+2,M=Math.max(10,X-G),{displayMessage:T,displayRefs:N}=zK(_.message,_.refs,M),H="";if(B)H+="{cyan-fg}{bold}▸ {/bold}{/cyan-fg}";else H+=" ";if(H+=`{yellow-fg}${_.shortHash}{/yellow-fg} `,B)H+=`{cyan-fg}{inverse}${SK(T)}{/inverse}{/cyan-fg}`;else H+=SK(T);if(H+=` {gray-fg}(${k}){/gray-fg}`,N)H+=` {green-fg}${SK(N)}{/green-fg}`;Y.push(H)}return Y.join(`
|
|
15
|
+
`)}function SK(K){return K.replace(/\{/g,"{{").replace(/\}/g,"}}")}function F7(K,$){return K[$]??null}function VK(K,$,J=!0,X=!0){let Z=[];if(K.length>0){if(Z.push({type:"section-header",sectionType:"commits"}),J)K.forEach((Q,q)=>{Z.push({type:"commit",commitIndex:q,commit:Q})})}if($.length>0){if(K.length>0)Z.push({type:"spacer"});if(Z.push({type:"section-header",sectionType:"files"}),X)$.forEach((Q,q)=>{Z.push({type:"file",fileIndex:q,file:Q})})}return Z}function l(K){return K.replace(/\{/g,"{{").replace(/\}/g,"}}")}function u8(K,$,J,X){let Z=$&&J,Q=JK(K.date),q=13+Q.length+2,Y=Math.max(10,X-q),{displayMessage:V,displayRefs:_}=zK(K.message,K.refs,Y),z=" ";if(z+=`{yellow-fg}${K.shortHash}{/yellow-fg} `,Z)z+=`{cyan-fg}{inverse}${l(V)}{/inverse}{/cyan-fg}`;else z+=l(V);if(z+=` {gray-fg}(${Q}){/gray-fg}`,_)z+=` {green-fg}${l(_)}{/green-fg}`;return z}function p8(K,$,J,X){let Z=$&&J,Q=K.isUncommitted??!1,q={added:"green",modified:"yellow",deleted:"red",renamed:"blue"},Y={added:"A",modified:"M",deleted:"D",renamed:"R"},V=5+String(K.additions).length+String(K.deletions).length,_=Q?14:0,z=Math.max(10,X-V-_),U=" ";if(Q)U+="{magenta-fg}{bold}*{/bold}{/magenta-fg}";let B=Q?"magenta":q[K.status];U+=`{${B}-fg}{bold}${Y[K.status]}{/bold}{/${B}-fg} `;let k=r(K.path,z);if(Z)U+=`{cyan-fg}{inverse}${l(k)}{/inverse}{/cyan-fg}`;else if(Q)U+=`{magenta-fg}${l(k)}{/magenta-fg}`;else U+=l(k);if(U+=` {gray-fg}({/gray-fg}{green-fg}+${K.additions}{/green-fg} {red-fg}-${K.deletions}{/red-fg}{gray-fg}){/gray-fg}`,Q)U+=" {magenta-fg}[uncommitted]{/magenta-fg}";return U}function v7(K,$,J,X,Z,Q=0,q){if(K.length===0&&$.length===0)return"{gray-fg}No changes compared to base branch{/gray-fg}";let Y=VK(K,$),V=q?Y.slice(Q,Q+q):Y.slice(Q),_=[];for(let z of V)if(z.type==="section-header"){let U=z.sectionType==="commits",B=U?K.length:$.length,k=U?"Commits":"Files";_.push(`{cyan-fg}{bold}▼ ${k}{/bold}{/cyan-fg} {gray-fg}(${B}){/gray-fg}`)}else if(z.type==="spacer")_.push("");else if(z.type==="commit"&&z.commit&&z.commitIndex!==void 0){let U=J?.type==="commit"&&J.index===z.commitIndex;_.push(u8(z.commit,U,X,Z))}else if(z.type==="file"&&z.file&&z.fileIndex!==void 0){let U=J?.type==="file"&&J.index===z.fileIndex;_.push(p8(z.file,U,X,Z-5))}return _.join(`
|
|
16
|
+
`)}function L7(K,$,J=!0,X=!0){let Z=0;if(K.length>0){if(Z+=1,J)Z+=K.length}if($.length>0){if(K.length>0)Z+=1;if(Z+=1,X)Z+=$.length}return Z}function PK(K,$,J,X=!0,Z=!0){let q=VK($,J,X,Z)[K];if(!q)return null;if(q.type==="commit"&&q.commitIndex!==void 0)return{type:"commit",index:q.commitIndex};if(q.type==="file"&&q.fileIndex!==void 0)return{type:"file",index:q.fileIndex};return null}function UK(K,$,J,X=!0,Z=!0){let Q=VK($,J,X,Z);for(let q=0;q<Q.length;q++){let Y=Q[q];if(K.type==="commit"&&Y.type==="commit"&&Y.commitIndex===K.index)return q;if(K.type==="file"&&Y.type==="file"&&Y.fileIndex===K.index)return q}return 0}function CK(K,$,J,X){let Z=VK($,J),Q=0;if(K)Q=UK(K,$,J);let q=X==="down"?1:-1,Y=Q+q;while(Y>=0&&Y<Z.length){let V=PK(Y,$,J);if(V)return V;Y+=q}return K}function a(K){return K.replace(/\{/g,"{{").replace(/\}/g,"}}")}function W7(K,$,J,X,Z=0,Q,q=!1,Y=null){if(Y)return`{red-fg}Error: ${a(Y)}{/red-fg}`;if(q)return"{gray-fg}Loading...{/gray-fg}";if(K.length===0)return"{gray-fg}(empty directory){/gray-fg}";let V=Q?K.slice(Z,Z+Q):K.slice(Z),_=Math.min(Math.max(...K.map((U)=>U.name.length+(U.isDirectory?1:0))),X-10),z=[];for(let U=0;U<V.length;U++){let B=V[U],M=Z+U===$&&J,N=(B.isDirectory?`${B.name}/`:B.name).padEnd(_+1),H="";if(M)if(B.isDirectory)H=`{cyan-fg}{bold}{inverse}${a(N)}{/inverse}{/bold}{/cyan-fg}`;else H=`{cyan-fg}{bold}{inverse}${a(N)}{/inverse}{/bold}{/cyan-fg}`;else if(B.isDirectory)H=`{blue-fg}${a(N)}{/blue-fg}`;else H=a(N);z.push(H)}return z.join(`
|
|
17
|
+
`)}function y7(K){return K.length}function bK(K,$,J){if(!K)return[];let X=K.split(`
|
|
18
|
+
`),Z=[],Q=$?ZK($):null;for(let q=0;q<X.length;q++){let Y=X[q],V=Q?j7(Y,Q):void 0;Z.push({type:"code",lineNum:q+1,content:Y,highlighted:V})}if(J)Z.push({type:"truncation",content:"(file truncated)"});return Z}function S7(K,$,J){if(!J)return K;let Z=Math.max(10,$),Q=[];for(let q of K)if(q.type==="code"){let Y=q.content;if(!Y||Y.length<=Z){Q.push(q);continue}let V=XK(Y,Z);for(let _=0;_<V.length;_++){let z=V[_];Q.push({type:"code",lineNum:z.isContinuation?0:q.lineNum,content:z.text,highlighted:void 0,isContinuation:z.isContinuation})}}else Q.push(q);return Q}function P7(K,$,J){if(!J)return K.length;let Z=Math.max(10,$),Q=0;for(let q of K)if(q.type==="code"){let Y=q.content;if(!Y||Y.length<=Z)Q+=1;else Q+=EK(Y,Z)}else Q+=1;return Q}function xK(K){let $=0;for(let J of K)if(J.type==="code"&&J.lineNum>$)$=J.lineNum;return Math.max(3,String($).length)}function C7(K,$){if(!$||!K)return K;let J=0;for(let Q of K)if(Q===" ")J++;else if(Q==="\t")J+=2;else break;if(J===0)return K;let X="·".repeat(J),Z=K.slice(J);return X+Z}function b7(K){return K.replace(/\{/g,"{{").replace(/\}/g,"}}")}function x7(K,$,J,X=0,Z,Q=!1,q=!1,Y=!1){if(!K)return"{gray-fg}Select a file to view its contents{/gray-fg}";if(!$)return"{gray-fg}Loading...{/gray-fg}";let V=bK($,K,Q);if(V.length===0)return"{gray-fg}(empty file){/gray-fg}";let _=xK(V),z=J-_-2,U=S7(V,z,q),B=Z?U.slice(X,X+Z):U.slice(X),k=[];for(let G of B){if(G.type==="truncation"){k.push(`{yellow-fg}${b7(G.content)}{/yellow-fg}`);continue}let M=G.isContinuation??!1,T;if(M)T=">>".padStart(_," ");else T=String(G.lineNum).padStart(_," ");let N=G.content,H=!q&&N.length>z,E=G.highlighted&&!M&&!Y,A;if(E&&G.highlighted){let O=H?qK(G.highlighted,z):G.highlighted;A=QK(O)}else{let O=N;if(Y&&!M)O=C7(O,!0);if(H)O=O.slice(0,Math.max(0,z-1))+"...";A=b7(O)}let j="";if(M)j=`{cyan-fg}${T}{/cyan-fg} ${A||" "}`;else j=`{gray-fg}${T}{/gray-fg} ${A||" "}`;k.push(j)}return k.join(`
|
|
19
|
+
`)}function w7(K,$,J,X,Z){if(!K)return 0;let Q=bK(K,$,J),q=xK(Q),Y=X-q-2;return P7(Q,Y,Z)}import*as BK from"node:fs";import*as L from"node:path";import{EventEmitter as m8}from"node:events";import{simpleGit as g8}from"simple-git";async function _K(K,$){if($.length===0)return new Set;let J=g8(K),X=new Set,Z=100;for(let Q=0;Q<$.length;Q+=Z){let q=$.slice(Q,Q+Z);try{let V=(await J.raw(["check-ignore",...q])).trim().split(`
|
|
20
|
+
`).filter((_)=>_.length>0);for(let _ of V)X.add(_)}catch{}}return X}var f8=1048576,h8=102400;function c8(K){let $=Math.min(K.length,8192);for(let J=0;J<$;J++)if(K[J]===0)return!0;return!1}class wK extends m8{repoPath;options;_state={currentPath:"",items:[],selectedIndex:0,selectedFile:null,isLoading:!1,error:null};constructor(K,$){super();this.repoPath=K,this.options=$}get state(){return this._state}updateState(K){this._state={...this._state,...K},this.emit("state-change",this._state)}async setOptions(K){this.options={...this.options,...K},await this.loadDirectory(this._state.currentPath)}async loadDirectory(K){this.updateState({isLoading:!0,error:null,currentPath:K});try{let $=L.join(this.repoPath,K),J=await BK.promises.readdir($,{withFileTypes:!0}),X=J.map((q)=>K?L.join(K,q.name):q.name),Z=this.options.hideGitignored?await _K(this.repoPath,X):new Set,Q=J.filter((q)=>{if(this.options.hideHidden&&q.name.startsWith("."))return!1;if(this.options.hideGitignored){let Y=K?L.join(K,q.name):q.name;if(Z.has(Y))return!1}return!0}).map((q)=>({name:q.name,path:K?L.join(K,q.name):q.name,isDirectory:q.isDirectory()}));if(Q.sort((q,Y)=>{if(q.isDirectory&&!Y.isDirectory)return-1;if(!q.isDirectory&&Y.isDirectory)return 1;return q.name.localeCompare(Y.name)}),K)Q.unshift({name:"..",path:L.dirname(K)||"",isDirectory:!0});this.updateState({items:Q,selectedIndex:0,selectedFile:null,isLoading:!1})}catch($){this.updateState({error:$ instanceof Error?$.message:"Failed to read directory",items:[],isLoading:!1})}}async loadFile(K){try{let $=L.join(this.repoPath,K),J=await BK.promises.stat($);if(J.size>f8){this.updateState({selectedFile:{path:K,content:`File too large to display (${(J.size/1024/1024).toFixed(2)} MB).
|
|
21
|
+
Maximum size: 1 MB`,truncated:!0}});return}let X=await BK.promises.readFile($);if(c8(X)){this.updateState({selectedFile:{path:K,content:"Binary file - cannot display"}});return}let Z=X.toString("utf-8"),Q=!1;if(J.size>h8)Z=`⚠ Large file (${(J.size/1024).toFixed(1)} KB)
|
|
22
|
+
|
|
23
|
+
`+Z;let q=5000,Y=Z.split(`
|
|
24
|
+
`);if(Y.length>q)Z=Y.slice(0,q).join(`
|
|
25
|
+
`)+`
|
|
26
|
+
|
|
27
|
+
... (truncated, ${Y.length-q} more lines)`,Q=!0;this.updateState({selectedFile:{path:K,content:Z,truncated:Q}})}catch($){this.updateState({selectedFile:{path:K,content:$ instanceof Error?`Error: ${$.message}`:"Failed to read file"}})}}async selectIndex(K){if(K<0||K>=this._state.items.length)return;let $=this._state.items[K];if(this.updateState({selectedIndex:K}),$&&!$.isDirectory)await this.loadFile($.path);else this.updateState({selectedFile:null})}navigateUp(K){let $=Math.max(0,this._state.selectedIndex-1);if($===this._state.selectedIndex)return null;if(this.selectIndex($),$<K)return $;return null}navigateDown(K,$){let J=Math.min(this._state.items.length-1,this._state.selectedIndex+1);if(J===this._state.selectedIndex)return null;this.selectIndex(J);let Z=this._state.items.length>$?$-2:$,Q=K+Z;if(J>=Q)return K+1;return null}async enterDirectory(){let K=this._state.items[this._state.selectedIndex];if(!K)return;if(K.isDirectory)if(K.name===".."){let $=L.dirname(this._state.currentPath);await this.loadDirectory($==="."?"":$)}else await this.loadDirectory(K.path)}async goUp(){if(this._state.currentPath){let K=L.dirname(this._state.currentPath);await this.loadDirectory(K==="."?"":K)}}dispose(){this.removeAllListeners()}}import d8 from"neo-blessed";class uK{box;screen;selectedIndex;currentTheme;onSelect;onCancel;constructor(K,$,J,X){if(this.screen=K,this.currentTheme=$,this.onSelect=J,this.onCancel=X,this.selectedIndex=C.indexOf($),this.selectedIndex<0)this.selectedIndex=0;let Z=50,Q=C.length+12;this.box=d8.box({parent:K,top:"center",left:"center",width:Z,height:Q,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape","q"],()=>{this.close(),this.onCancel()}),this.box.key(["enter","space"],()=>{let K=C[this.selectedIndex];this.close(),this.onSelect(K)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(C.length-1,this.selectedIndex+1),this.render()})}render(){let K=[];K.push("{bold}{cyan-fg} Select Theme{/cyan-fg}{/bold}"),K.push("");for(let J=0;J<C.length;J++){let X=C[J],Z=$K[X],Q=J===this.selectedIndex,q=X===this.currentTheme,Y=Q?"{cyan-fg}{bold}> ":" ";if(Y+=Z.displayName,Q)Y+="{/bold}{/cyan-fg}";if(q)Y+=" {gray-fg}(current){/gray-fg}";K.push(Y)}K.push(""),K.push("{gray-fg}Preview:{/gray-fg}");let $=s(C[this.selectedIndex]);K.push(" {green-fg}+ added line{/green-fg}"),K.push(" {red-fg}- deleted line{/red-fg}"),K.push(""),K.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent(K.join(`
|
|
28
|
+
`)),this.screen.render()}close(){this.box.destroy()}focus(){this.box.focus()}}import l8 from"neo-blessed";var w=[{title:"Navigation",entries:[{key:"j/k",description:"Move up/down"},{key:"Tab",description:"Toggle pane focus"}]},{title:"Staging",entries:[{key:"s",description:"Stage file"},{key:"U",description:"Unstage file"},{key:"A",description:"Stage all"},{key:"Z",description:"Unstage all"},{key:"Space",description:"Toggle stage"}]},{title:"Actions",entries:[{key:"c",description:"Commit panel"},{key:"r",description:"Refresh"},{key:"q",description:"Quit"}]},{title:"Resize",entries:[{key:"-",description:"Shrink top pane"},{key:"+",description:"Grow top pane"}]},{title:"Tabs",entries:[{key:"1",description:"Diff view"},{key:"2",description:"Commit panel"},{key:"3",description:"History view"},{key:"4",description:"Compare view"},{key:"5",description:"Explorer view"}]},{title:"Toggles",entries:[{key:"m",description:"Mouse mode"},{key:"w",description:"Wrap mode"},{key:"f",description:"Follow mode"},{key:"t",description:"Theme picker"},{key:"?",description:"This help"}]},{title:"Explorer",entries:[{key:"Enter",description:"Enter directory"},{key:"Backspace",description:"Go up"}]},{title:"Compare",entries:[{key:"b",description:"Base branch picker"},{key:"u",description:"Toggle uncommitted"}]},{title:"Diff",entries:[{key:"d",description:"Discard changes"}]}];class pK{box;screen;onClose;constructor(K,$){this.screen=K,this.onClose=$;let{width:J,height:X}=K,Z=J>=90,Q=Z?Math.min(80,J-4):Math.min(42,J-4),q=Math.min(this.calculateHeight(Z),X-4);this.box=l8.box({parent:K,top:"center",left:"center",width:Q,height:q,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render(Z,Q)}calculateHeight(K){if(K){let $=Math.ceil(w.length/2),J=w.slice(0,$),X=w.slice($),Z=J.reduce((q,Y)=>q+Y.entries.length+2,0),Q=X.reduce((q,Y)=>q+Y.entries.length+2,0);return Math.max(Z,Q)+5}else return w.reduce(($,J)=>$+J.entries.length+2,0)+5}setupKeyHandlers(){this.box.key(["escape","enter","?","q"],()=>{this.close(),this.onClose()}),this.box.on("click",()=>{this.close(),this.onClose()})}visibleWidth(K){return K.replace(/\{[^}]+\}/g,"").length}padToVisible(K,$){let J=this.visibleWidth(K),X=Math.max(0,$-J);return K+" ".repeat(X)}render(K,$){let J=[];if(J.push("{bold}{cyan-fg} Keyboard Shortcuts{/cyan-fg}{/bold}"),J.push(""),K){let X=Math.ceil(w.length/2),Z=w.slice(0,X),Q=w.slice(X),q=Math.floor(($-6)/2),Y=this.renderGroups(Z,q),V=this.renderGroups(Q,q),_=Math.max(Y.length,V.length);for(let z=0;z<_;z++){let U=this.padToVisible(Y[z]||"",q),B=V[z]||"";J.push(U+" "+B)}}else for(let X of w){J.push(`{bold}{gray-fg}${X.title}{/gray-fg}{/bold}`);for(let Z of X.entries)J.push(` {cyan-fg}${Z.key.padEnd(10)}{/cyan-fg} ${Z.description}`);J.push("")}J.push(""),J.push("{gray-fg}Press Esc, Enter, or ? to close{/gray-fg}"),this.box.setContent(J.join(`
|
|
29
|
+
`)),this.screen.render()}renderGroups(K,$){let J=[];for(let X of K){J.push(`{bold}{gray-fg}${X.title}{/gray-fg}{/bold}`);for(let Z of X.entries)J.push(` {cyan-fg}${Z.key.padEnd(10)}{/cyan-fg} ${Z.description}`);J.push("")}return J}close(){this.box.destroy()}focus(){this.box.focus()}}import o8 from"neo-blessed";class gK{box;screen;branches;selectedIndex;currentBranch;onSelect;onCancel;constructor(K,$,J,X,Z){if(this.screen=K,this.branches=$,this.currentBranch=J,this.onSelect=X,this.onCancel=Z,this.selectedIndex=J?$.indexOf(J):0,this.selectedIndex<0)this.selectedIndex=0;let Q=50,Y=Math.min($.length,15)+6;this.box=o8.box({parent:K,top:"center",left:"center",width:Q,height:Y,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape","q"],()=>{this.close(),this.onCancel()}),this.box.key(["enter","space"],()=>{let K=this.branches[this.selectedIndex];if(K)this.close(),this.onSelect(K)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(this.branches.length-1,this.selectedIndex+1),this.render()})}render(){let K=[];if(K.push("{bold}{cyan-fg} Select Base Branch{/cyan-fg}{/bold}"),K.push(""),this.branches.length===0)K.push("{gray-fg}No branches found{/gray-fg}");else for(let $=0;$<this.branches.length;$++){let J=this.branches[$],X=$===this.selectedIndex,Z=J===this.currentBranch,Q=X?"{cyan-fg}{bold}> ":" ";if(Q+=J,X)Q+="{/bold}{/cyan-fg}";if(Z)Q+=" {gray-fg}(current){/gray-fg}";K.push(Q)}K.push(""),K.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent(K.join(`
|
|
30
|
+
`)),this.screen.render()}close(){this.box.destroy()}focus(){this.box.focus()}}import r8 from"neo-blessed";class mK{box;screen;filePath;onConfirm;onCancel;constructor(K,$,J,X){this.screen=K,this.filePath=$,this.onConfirm=J,this.onCancel=X;let Z=Math.min(60,Math.max(40,$.length+20)),Q=7;this.box=r8.box({parent:K,top:"center",left:"center",width:Z,height:Q,border:{type:"line"},style:{border:{fg:"yellow"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["y","Y"],()=>{this.close(),this.onConfirm()}),this.box.key(["n","N","escape","q"],()=>{this.close(),this.onCancel()})}render(){let K=[];K.push("{bold}{yellow-fg} Discard Changes?{/yellow-fg}{/bold}"),K.push("");let $=this.box.width-6,J=this.filePath.length>$?"..."+this.filePath.slice(-($-3)):this.filePath;K.push(`{white-fg}${J}{/white-fg}`),K.push(""),K.push("{gray-fg}Press {/gray-fg}{green-fg}y{/green-fg}{gray-fg} to confirm, {/gray-fg}{red-fg}n{/red-fg}{gray-fg} or Esc to cancel{/gray-fg}"),this.box.setContent(K.join(`
|
|
31
|
+
`)),this.screen.render()}close(){this.box.destroy()}focus(){this.box.focus()}}import{EventEmitter as s8}from"node:events";function u7(K,$,J){if(!K.trim())return{valid:!1,error:"Commit message cannot be empty"};if($===0&&!J)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function p7(K){return K.trim()}var g7={message:"",amend:!1,isCommitting:!1,error:null,inputFocused:!1};class fK extends s8{_state={...g7};getHeadMessage;onCommit;onSuccess;stagedCount=0;constructor(K){super();this.getHeadMessage=K.getHeadMessage,this.onCommit=K.onCommit,this.onSuccess=K.onSuccess}get state(){return this._state}update(K){this._state={...this._state,...K},this.emit("change",this._state)}setStagedCount(K){this.stagedCount=K}setMessage(K){this.update({message:K,error:null})}setInputFocused(K){this.update({inputFocused:K}),this.emit("focus-change",K)}async toggleAmend(){let K=!this._state.amend;if(this.update({amend:K}),K&&!this._state.message)try{let $=await this.getHeadMessage();if($)this.update({message:$})}catch{}}async submit(){let K=u7(this._state.message,this.stagedCount,this._state.amend);if(!K.valid){this.update({error:K.error});return}this.update({isCommitting:!0,error:null});try{await this.onCommit(p7(this._state.message),this._state.amend),this.update({message:"",amend:!1,isCommitting:!1,inputFocused:!1}),this.onSuccess()}catch($){this.update({isCommitting:!1,error:$ instanceof Error?$.message:"Commit failed"})}}reset(){this._state={...g7},this.emit("change",this._state)}}import{EventEmitter as a8}from"node:events";var n8={currentPane:"files",bottomTab:"diff",selectedIndex:0,fileListScrollOffset:0,diffScrollOffset:0,historyScrollOffset:0,compareScrollOffset:0,explorerScrollOffset:0,explorerFileScrollOffset:0,historySelectedIndex:0,compareSelectedIndex:0,includeUncommitted:!1,explorerSelectedIndex:0,wrapMode:!1,autoTabEnabled:!1,mouseEnabled:!0,showMiddleDots:!1,hideHiddenFiles:!0,hideGitignored:!0,splitRatio:0.4,activeModal:null,pendingDiscard:null,commitInputFocused:!1};class hK extends a8{_state;constructor(K={}){super();this._state={...n8,...K}}get state(){return this._state}update(K){this._state={...this._state,...K},this.emit("change",this._state)}setPane(K){if(this._state.currentPane!==K)this.update({currentPane:K}),this.emit("pane-change",K)}setTab(K){if(this._state.bottomTab!==K){let $={diff:"files",commit:"commit",history:"history",compare:"compare",explorer:"explorer"};this.update({bottomTab:K,currentPane:$[K]}),this.emit("tab-change",K)}}setSelectedIndex(K){if(this._state.selectedIndex!==K)this.update({selectedIndex:K}),this.emit("selection-change",K)}setFileListScrollOffset(K){this.update({fileListScrollOffset:Math.max(0,K)}),this.emit("scroll-change",{type:"fileList",offset:K})}setDiffScrollOffset(K){this.update({diffScrollOffset:Math.max(0,K)}),this.emit("scroll-change",{type:"diff",offset:K})}setHistoryScrollOffset(K){this.update({historyScrollOffset:Math.max(0,K)}),this.emit("scroll-change",{type:"history",offset:K})}setCompareScrollOffset(K){this.update({compareScrollOffset:Math.max(0,K)}),this.emit("scroll-change",{type:"compare",offset:K})}setExplorerScrollOffset(K){this.update({explorerScrollOffset:Math.max(0,K)}),this.emit("scroll-change",{type:"explorer",offset:K})}setExplorerFileScrollOffset(K){this.update({explorerFileScrollOffset:Math.max(0,K)}),this.emit("scroll-change",{type:"explorerFile",offset:K})}setHistorySelectedIndex(K){this.update({historySelectedIndex:Math.max(0,K)})}setCompareSelectedIndex(K){this.update({compareSelectedIndex:Math.max(0,K)})}toggleIncludeUncommitted(){this.update({includeUncommitted:!this._state.includeUncommitted})}setExplorerSelectedIndex(K){this.update({explorerSelectedIndex:Math.max(0,K)})}toggleWrapMode(){this.update({wrapMode:!this._state.wrapMode,diffScrollOffset:0})}toggleAutoTab(){this.update({autoTabEnabled:!this._state.autoTabEnabled})}toggleMouse(){this.update({mouseEnabled:!this._state.mouseEnabled})}toggleMiddleDots(){this.update({showMiddleDots:!this._state.showMiddleDots})}toggleHideHiddenFiles(){this.update({hideHiddenFiles:!this._state.hideHiddenFiles})}toggleHideGitignored(){this.update({hideGitignored:!this._state.hideGitignored})}adjustSplitRatio(K){let $=Math.min(0.85,Math.max(0.15,this._state.splitRatio+K));this.update({splitRatio:$})}setSplitRatio(K){this.update({splitRatio:Math.min(0.85,Math.max(0.15,K))})}openModal(K){this.update({activeModal:K}),this.emit("modal-change",K)}closeModal(){this.update({activeModal:null}),this.emit("modal-change",null)}toggleModal(K){if(this._state.activeModal===K)this.closeModal();else this.openModal(K)}setPendingDiscard(K){this.update({pendingDiscard:K})}setCommitInputFocused(K){this.update({commitInputFocused:K})}togglePane(){let{bottomTab:K,currentPane:$}=this._state;if(K==="diff"||K==="commit")this.setPane($==="files"?"diff":"files");else if(K==="history")this.setPane($==="history"?"diff":"history");else if(K==="compare")this.setPane($==="compare"?"diff":"compare");else if(K==="explorer")this.setPane($==="explorer"?"diff":"explorer")}}import*as W from"node:path";import*as g from"node:fs";import{watch as z8}from"chokidar";import{EventEmitter as J9}from"node:events";import X9 from"ignore";class m7{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue(K){return new Promise(($,J)=>{this.queue.push({execute:K,resolve:$,reject:J}),this.processNext()})}enqueueMutation(K){return this.pendingMutations++,this.enqueue(K).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh(K){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await K()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let K=this.queue.shift();try{let $=await K.execute();K.resolve($)}catch($){K.reject($ instanceof Error?$:Error(String($)))}finally{this.isProcessing=!1,this.processNext()}}}var cK=new Map;function f7(K){let $=cK.get(K);if(!$)$=new m7,cK.set(K,$);return $}function h7(K){cK.delete(K)}import{simpleGit as y}from"simple-git";import*as l7 from"node:fs";import*as o7 from"node:path";function c7(K){let $=new Map;for(let J of K.trim().split(`
|
|
32
|
+
`)){if(!J)continue;let X=J.split("\t");if(X.length>=3){let Z=X[0]==="-"?0:parseInt(X[0],10),Q=X[1]==="-"?0:parseInt(X[1],10),q=X.slice(2).join("\t");$.set(q,{insertions:Z,deletions:Q})}}return $}async function i8(K,$){try{let J=o7.join(K,$);return(await l7.promises.readFile(J,"utf-8")).split(`
|
|
33
|
+
`).filter((Z)=>Z.length>0).length}catch{return 0}}function d7(K){switch(K){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";default:return"modified"}}async function r7(K){let $=y(K);try{if(!await $.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let X=await $.status(),Z=[];for(let G of X.staged)Z.push({path:G,status:"added",staged:!0});for(let G of X.modified)if(!Z.find((T)=>T.path===G&&T.staged))Z.push({path:G,status:"modified",staged:!1});for(let G of X.deleted)Z.push({path:G,status:"deleted",staged:!1});for(let G of X.not_added)Z.push({path:G,status:"untracked",staged:!1});for(let G of X.renamed)Z.push({path:G.to,originalPath:G.from,status:"renamed",staged:!0});let Q=[],q=new Set,Y=X.files.filter((G)=>G.working_dir==="?").map((G)=>G.path),V=await _K(K,Y);for(let G of X.files){if(G.index==="!"||G.working_dir==="!"||V.has(G.path))continue;let M=`${G.path}-${G.index!==" "&&G.index!=="?"}`;if(q.has(M))continue;if(q.add(M),G.index&&G.index!==" "&&G.index!=="?")Q.push({path:G.path,status:d7(G.index),staged:!0});if(G.working_dir&&G.working_dir!==" ")Q.push({path:G.path,status:G.working_dir==="?"?"untracked":d7(G.working_dir),staged:!1})}let[_,z]=await Promise.all([$.diff(["--cached","--numstat"]).catch(()=>""),$.diff(["--numstat"]).catch(()=>"")]),U=c7(_),B=c7(z);for(let G of Q){let M=G.staged?U.get(G.path):B.get(G.path);if(M)G.insertions=M.insertions,G.deletions=M.deletions}let k=Q.filter((G)=>G.status==="untracked");if(k.length>0){let G=await Promise.all(k.map((M)=>i8(K,M.path)));for(let M=0;M<k.length;M++)k[M].insertions=G[M],k[M].deletions=0}return{files:Q,branch:{current:X.current||"HEAD",tracking:X.tracking||void 0,ahead:X.ahead,behind:X.behind},isRepo:!0}}catch{return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}}async function s7(K,$){await y(K).add($)}async function a7(K,$){await y(K).reset(["HEAD","--",$])}async function n7(K){await y(K).add("-A")}async function i7(K){await y(K).reset(["HEAD"])}async function t7(K,$){await y(K).checkout(["--",$])}async function e7(K,$,J=!1){await y(K).commit($,void 0,J?{"--amend":null}:void 0)}async function K8(K){let $=y(K);try{return(await $.log({n:1})).latest?.message||""}catch{return""}}async function $8(K,$=50){let J=y(K);try{return(await J.log({n:$})).all.map((Z)=>({hash:Z.hash,shortHash:Z.hash.slice(0,7),message:Z.message.split(`
|
|
34
|
+
`)[0],author:Z.author_name,date:new Date(Z.date),refs:Z.refs||""}))}catch{return[]}}import{execSync as t8}from"node:child_process";import{simpleGit as n}from"simple-git";function e8(K){let $=K.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if($)return{oldStart:parseInt($[1],10),newStart:parseInt($[2],10)};return null}function GK(K){let $=K.split(`
|
|
35
|
+
`),J=[],X=0,Z=0;for(let Q of $)if(Q.startsWith("diff --git")||Q.startsWith("index ")||Q.startsWith("---")||Q.startsWith("+++")||Q.startsWith("new file")||Q.startsWith("deleted file")||Q.startsWith("Binary files")||Q.startsWith("similarity index")||Q.startsWith("rename from")||Q.startsWith("rename to"))J.push({type:"header",content:Q});else if(Q.startsWith("@@")){let q=e8(Q);if(q)X=q.oldStart,Z=q.newStart;J.push({type:"hunk",content:Q})}else if(Q.startsWith("+"))J.push({type:"addition",content:Q,newLineNum:Z++});else if(Q.startsWith("-"))J.push({type:"deletion",content:Q,oldLineNum:X++});else J.push({type:"context",content:Q,oldLineNum:X++,newLineNum:Z++});return J}async function i(K,$,J=!1){let X=n(K);try{let Z=[];if(J)Z.push("--cached");if($)Z.push("--",$);let Q=await X.diff(Z),q=GK(Q);return{raw:Q,lines:q}}catch{return{raw:"",lines:[]}}}async function dK(K,$){try{let J=t8(`cat "${$}"`,{cwd:K,encoding:"utf-8"}),X=[{type:"header",content:`diff --git a/${$} b/${$}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${$}`}],Z=J.split(`
|
|
36
|
+
`);X.push({type:"hunk",content:`@@ -0,0 +1,${Z.length} @@`});let Q=1;for(let Y of Z)X.push({type:"addition",content:"+"+Y,newLineNum:Q++});return{raw:X.map((Y)=>Y.content).join(`
|
|
37
|
+
`),lines:X}}catch{return{raw:"",lines:[]}}}async function lK(K){return i(K,void 0,!0)}async function oK(K){let $=n(K),J=new Set,X=[];try{let Z=await $.raw(["log","--oneline","--decorate=short","--all","-n","200"]),Q=/\(([^)]+)\)/g;for(let q of Z.split(`
|
|
38
|
+
`)){let Y=Q.exec(q);if(Y){let V=Y[1].split(",").map((_)=>_.trim());for(let _ of V){if(_.startsWith("HEAD")||_.startsWith("tag:")||!_.includes("/"))continue;let z=_.replace(/^.*-> /,"");if(z.includes("/")&&!J.has(z))J.add(z),X.push(z)}}Q.lastIndex=0}if(X.length>0)X.sort((q,Y)=>{let V=q.split("/").slice(1).join("/"),_=Y.split("/").slice(1).join("/"),z=V==="main"||V==="master",U=_==="main"||_==="master";if(z&&!U)return-1;if(!z&&U)return 1;if(z&&U){let B=q.startsWith("origin/"),k=Y.startsWith("origin/");if(B&&!k)return 1;if(!B&&k)return-1}return 0})}catch{}return[...new Set(X)]}async function J8(K){return(await oK(K))[0]??null}async function rK(K,$){let J=n(K),Z=(await J.raw(["merge-base",$,"HEAD"])).trim(),Q=await J.raw(["diff","--numstat",`${Z}...HEAD`]),q=await J.raw(["diff","--name-status",`${Z}...HEAD`]),Y=await J.raw(["diff",`${Z}...HEAD`]),V=Q.trim().split(`
|
|
39
|
+
`).filter((A)=>A),_=new Map;for(let A of V){let j=A.split("\t");if(j.length>=3){let O=j[0]==="-"?0:parseInt(j[0],10),D=j[1]==="-"?0:parseInt(j[1],10),I=j.slice(2).join("\t");_.set(I,{additions:O,deletions:D})}}let z=q.trim().split(`
|
|
40
|
+
`).filter((A)=>A),U=new Map;for(let A of z){let j=A.split("\t");if(j.length>=2){let O=j[0][0],D=j[j.length-1],I;switch(O){case"A":I="added";break;case"D":I="deleted";break;case"R":I="renamed";break;default:I="modified"}U.set(D,I)}}let B=[],k=Y.split(/(?=^diff --git )/m).filter((A)=>A.trim());for(let A of k){let j=A.match(/^diff --git a\/.+ b\/(.+)$/m);if(!j)continue;let O=j[1],D=GK(A),I=_.get(O)||{additions:0,deletions:0},P=U.get(O)||"modified";B.push({path:O,status:P,additions:I.additions,deletions:I.deletions,diff:{raw:A,lines:D}})}let G=0,M=0;for(let A of B)G+=A.additions,M+=A.deletions;let N=(await J.status()).files.length,E=(await J.log({from:Z,to:"HEAD"})).all.map((A)=>({hash:A.hash,shortHash:A.hash.slice(0,7),message:A.message.split(`
|
|
41
|
+
`)[0],author:A.author_name,date:new Date(A.date),refs:A.refs||""}));return{baseBranch:$,stats:{filesChanged:B.length,additions:G,deletions:M},files:B,commits:E,uncommittedCount:N}}async function sK(K,$){let J=n(K);try{let X=await J.raw(["show",$,"--format="]),Z=GK(X);return{raw:X,lines:Z}}catch{return{raw:"",lines:[]}}}async function X8(K,$){let J=n(K),X=await rK(K,$),Z=await J.diff(["--cached","--numstat"]),Q=await J.diff(["--numstat"]),q=await J.diff(["--cached"]),Y=await J.diff([]),V=new Map;for(let A of Z.trim().split(`
|
|
42
|
+
`).filter((j)=>j)){let j=A.split("\t");if(j.length>=3){let O=j[0]==="-"?0:parseInt(j[0],10),D=j[1]==="-"?0:parseInt(j[1],10),I=j.slice(2).join("\t");V.set(I,{additions:O,deletions:D,staged:!0,unstaged:!1})}}for(let A of Q.trim().split(`
|
|
43
|
+
`).filter((j)=>j)){let j=A.split("\t");if(j.length>=3){let O=j[0]==="-"?0:parseInt(j[0],10),D=j[1]==="-"?0:parseInt(j[1],10),I=j.slice(2).join("\t"),P=V.get(I);if(P)P.additions+=O,P.deletions+=D,P.unstaged=!0;else V.set(I,{additions:O,deletions:D,staged:!1,unstaged:!0})}}let _=await J.status(),z=new Map;for(let A of _.files)if(A.index==="A"||A.working_dir==="?")z.set(A.path,"added");else if(A.index==="D"||A.working_dir==="D")z.set(A.path,"deleted");else if(A.index==="R")z.set(A.path,"renamed");else z.set(A.path,"modified");let U=[],k=(q+Y).split(/(?=^diff --git )/m).filter((A)=>A.trim()),G=new Set;for(let A of k){let j=A.match(/^diff --git a\/.+ b\/(.+)$/m);if(!j)continue;let O=j[1];if(G.has(O))continue;G.add(O);let D=GK(A),I=V.get(O)||{additions:0,deletions:0},P=z.get(O)||"modified";U.push({path:O,status:P,additions:I.additions,deletions:I.deletions,diff:{raw:A,lines:D},isUncommitted:!0})}let M=new Set(X.files.map((A)=>A.path)),T=[];for(let A of X.files){let j=U.find((O)=>O.path===A.path);if(j)T.push(A),T.push(j);else T.push(A)}for(let A of U)if(!M.has(A.path))T.push(A);let N=0,H=0,E=new Set;for(let A of T){if(!E.has(A.path))E.add(A.path);N+=A.additions,H+=A.deletions}return{baseBranch:X.baseBranch,stats:{filesChanged:E.size,additions:N,deletions:H},files:T,commits:X.commits,uncommittedCount:X.uncommittedCount}}import*as S from"node:fs";import*as p from"node:path";import*as Z8 from"node:os";var AK=p.join(Z8.homedir(),".cache","diffstalker","base-branches.json");function K9(){let K=p.dirname(AK);if(!S.existsSync(K))S.mkdirSync(K,{recursive:!0})}function Q8(){try{if(S.existsSync(AK))return JSON.parse(S.readFileSync(AK,"utf-8"))}catch{}return{}}function $9(K){K9(),S.writeFileSync(AK,JSON.stringify(K,null,2)+`
|
|
44
|
+
`)}function q8(K){let $=Q8(),J=p.resolve(K);return $[J]}function Y8(K,$){let J=Q8(),X=p.resolve(K);J[X]=$,$9(J)}class V8 extends J9{repoPath;queue;gitWatcher=null;workingDirWatcher=null;ignorer=null;_state={status:null,diff:null,stagedDiff:"",selectedFile:null,isLoading:!1,error:null};_compareState={compareDiff:null,compareBaseBranch:null,compareLoading:!1,compareError:null};_historyState={commits:[],selectedCommit:null,commitDiff:null,isLoading:!1};_compareSelectionState={type:null,index:0,diff:null};constructor(K){super();this.repoPath=K,this.queue=f7(K)}get state(){return this._state}get compareState(){return this._compareState}get historyState(){return this._historyState}get compareSelectionState(){return this._compareSelectionState}updateState(K){this._state={...this._state,...K},this.emit("state-change",this._state)}updateCompareState(K){this._compareState={...this._compareState,...K},this.emit("compare-state-change",this._compareState)}updateHistoryState(K){this._historyState={...this._historyState,...K},this.emit("history-state-change",this._historyState)}updateCompareSelectionState(K){this._compareSelectionState={...this._compareSelectionState,...K},this.emit("compare-selection-change",this._compareSelectionState)}loadGitignore(){let K=X9();K.add(".git");let $=W.join(this.repoPath,".gitignore");if(g.existsSync($))K.add(g.readFileSync($,"utf-8"));let J=W.join(this.repoPath,".git","info","exclude");if(g.existsSync(J))K.add(g.readFileSync(J,"utf-8"));return K}startWatching(){let K=W.join(this.repoPath,".git");if(!g.existsSync(K))return;let $=W.join(K,"index"),J=W.join(K,"HEAD"),X=W.join(K,"refs"),Z=W.join(this.repoPath,".gitignore");this.gitWatcher=z8([$,J,X,Z],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorer=this.loadGitignore(),this.workingDirWatcher=z8(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(q)=>{let Y=W.relative(this.repoPath,q);if(!Y)return!1;return this.ignorer?.ignores(Y)??!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Q=()=>this.scheduleRefresh();this.gitWatcher.on("change",(q)=>{if(q===Z)this.ignorer=this.loadGitignore();Q()}),this.gitWatcher.on("add",Q),this.gitWatcher.on("unlink",Q),this.gitWatcher.on("error",(q)=>{let Y=q instanceof Error?q.message:String(q);this.emit("error",`Git watcher error: ${Y}`)}),this.workingDirWatcher.on("change",Q),this.workingDirWatcher.on("add",Q),this.workingDirWatcher.on("unlink",Q),this.workingDirWatcher.on("error",(q)=>{let Y=q instanceof Error?q.message:String(q);this.emit("error",`Working dir watcher error: ${Y}`)})}dispose(){this.gitWatcher?.close(),this.workingDirWatcher?.close(),h7(this.repoPath)}scheduleRefresh(){this.queue.scheduleRefresh(()=>this.doRefresh())}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});try{let K=await r7(this.repoPath);if(!K.isRepo){this.updateState({status:K,diff:null,stagedDiff:"",isLoading:!1,error:"Not a git repository"});return}let[$,J]=await Promise.all([lK(this.repoPath),i(this.repoPath,void 0,!1)]),X,Z=this._state.selectedFile;if(Z){let Q=K.files.find((q)=>q.path===Z.path&&q.staged===Z.staged);if(Q)if(Q.status==="untracked")X=await dK(this.repoPath,Q.path);else X=await i(this.repoPath,Q.path,Q.staged);else X=J.raw?J:$,this.updateState({selectedFile:null})}else if(J.raw)X=J;else if($.raw)X=$;else X={raw:"",lines:[]};this.updateState({status:K,diff:X,stagedDiff:$.raw,isLoading:!1})}catch(K){this.updateState({isLoading:!1,error:K instanceof Error?K.message:"Unknown error"})}}async selectFile(K){if(this.updateState({selectedFile:K}),!this._state.status?.isRepo)return;await this.queue.enqueue(async()=>{if(K){let $;if(K.status==="untracked")$=await dK(this.repoPath,K.path);else $=await i(this.repoPath,K.path,K.staged);this.updateState({diff:$})}else{let $=await lK(this.repoPath);this.updateState({diff:$})}})}async stage(K){let $=this._state.status;if($)this.updateState({status:{...$,files:$.files.map((J)=>J.path===K.path&&!J.staged?{...J,staged:!0}:J)}});try{await this.queue.enqueueMutation(()=>s7(this.repoPath,K.path)),this.scheduleRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to stage ${K.path}: ${J instanceof Error?J.message:String(J)}`})}}async unstage(K){let $=this._state.status;if($)this.updateState({status:{...$,files:$.files.map((J)=>J.path===K.path&&J.staged?{...J,staged:!1}:J)}});try{await this.queue.enqueueMutation(()=>a7(this.repoPath,K.path)),this.scheduleRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to unstage ${K.path}: ${J instanceof Error?J.message:String(J)}`})}}async discard(K){if(K.staged||K.status==="untracked")return;try{await this.queue.enqueueMutation(()=>t7(this.repoPath,K.path)),await this.refresh()}catch($){this.updateState({error:`Failed to discard ${K.path}: ${$ instanceof Error?$.message:String($)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>n7(this.repoPath)),await this.refresh()}catch(K){this.updateState({error:`Failed to stage all: ${K instanceof Error?K.message:String(K)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>i7(this.repoPath)),await this.refresh()}catch(K){this.updateState({error:`Failed to unstage all: ${K instanceof Error?K.message:String(K)}`})}}async commit(K,$=!1){try{await this.queue.enqueue(()=>e7(this.repoPath,K,$)),await this.refresh()}catch(J){this.updateState({error:`Failed to commit: ${J instanceof Error?J.message:String(J)}`})}}async getHeadCommitMessage(){return this.queue.enqueue(()=>K8(this.repoPath))}async refreshCompareDiff(K=!1){this.updateCompareState({compareLoading:!0,compareError:null});try{await this.queue.enqueue(async()=>{let $=this._compareState.compareBaseBranch;if(!$)$=q8(this.repoPath)??await J8(this.repoPath),this.updateCompareState({compareBaseBranch:$});if($){let J=K?await X8(this.repoPath,$):await rK(this.repoPath,$);this.updateCompareState({compareDiff:J,compareLoading:!1})}else this.updateCompareState({compareDiff:null,compareLoading:!1,compareError:"No base branch found"})})}catch($){this.updateCompareState({compareLoading:!1,compareError:`Failed to load compare diff: ${$ instanceof Error?$.message:String($)}`})}}async getCandidateBaseBranches(){return oK(this.repoPath)}async setCompareBaseBranch(K,$=!1){this.updateCompareState({compareBaseBranch:K}),Y8(this.repoPath,K),await this.refreshCompareDiff($)}async loadHistory(K=100){this.updateHistoryState({isLoading:!0});try{let $=await this.queue.enqueue(()=>$8(this.repoPath,K));this.updateHistoryState({commits:$,isLoading:!1})}catch($){this.updateHistoryState({isLoading:!1}),this.updateState({error:`Failed to load history: ${$ instanceof Error?$.message:String($)}`})}}async selectHistoryCommit(K){if(this.updateHistoryState({selectedCommit:K,commitDiff:null}),!K)return;try{await this.queue.enqueue(async()=>{let $=await sK(this.repoPath,K.hash);this.updateHistoryState({commitDiff:$})})}catch($){this.updateState({error:`Failed to load commit diff: ${$ instanceof Error?$.message:String($)}`})}}async selectCompareCommit(K){let $=this._compareState.compareDiff;if(!$||K<0||K>=$.commits.length){this.updateCompareSelectionState({type:null,index:0,diff:null});return}let J=$.commits[K];this.updateCompareSelectionState({type:"commit",index:K,diff:null});try{await this.queue.enqueue(async()=>{let X=await sK(this.repoPath,J.hash);this.updateCompareSelectionState({diff:X})})}catch(X){this.updateState({error:`Failed to load commit diff: ${X instanceof Error?X.message:String(X)}`})}}selectCompareFile(K){let $=this._compareState.compareDiff;if(!$||K<0||K>=$.files.length){this.updateCompareSelectionState({type:null,index:0,diff:null});return}let J=$.files[K];this.updateCompareSelectionState({type:"file",index:K,diff:J.diff})}}var kK=new Map;function U8(K){let $=kK.get(K);if(!$)$=new V8(K),kK.set(K,$);return $}function aK(K){let $=kK.get(K);if($)$.dispose(),kK.delete(K)}import*as m from"node:fs";import*as jK from"node:path";import{watch as Z9}from"chokidar";import{EventEmitter as Q9}from"node:events";import*as _8 from"node:path";import*as nK from"node:os";function B8(K){if(K.startsWith("~/"))return _8.join(nK.homedir(),K.slice(2));if(K==="~")return nK.homedir();return K}function iK(K){let $=K.split(`
|
|
45
|
+
`);for(let J=$.length-1;J>=0;J--){let X=$[J].trim();if(X)return X}return""}class tK extends Q9{targetFile;debug;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,lastUpdate:null,rawContent:null,sourceFile:null};constructor(K,$=!1){super();this.targetFile=K,this.debug=$,this._state.sourceFile=K}get state(){return this._state}updateState(K){this._state={...this._state,...K},this.emit("path-change",this._state)}processContent(K){if(!K)return null;let $=B8(K);return jK.isAbsolute($)?$:jK.resolve($)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let K=m.readFileSync(this.targetFile,"utf-8"),$=iK(K);if($&&$!==this.lastReadPath){let J=this.processContent($),X=new Date;if(this.debug&&J)process.stderr.write(`[diffstalker ${X.toISOString()}] Path change detected
|
|
46
|
+
`),process.stderr.write(` Source file: ${this.targetFile}
|
|
47
|
+
`),process.stderr.write(` Raw content: "${$}"
|
|
48
|
+
`),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
|
|
49
|
+
`),process.stderr.write(` Resolved: "${J}"
|
|
50
|
+
`);this.lastReadPath=J,this.updateState({path:J,lastUpdate:X,rawContent:$})}}catch{}}start(){if(J7(this.targetFile),!m.existsSync(this.targetFile))m.writeFileSync(this.targetFile,"");try{let K=m.readFileSync(this.targetFile,"utf-8"),$=iK(K);if($){let J=this.processContent($),X=new Date;if(this.debug&&J)process.stderr.write(`[diffstalker ${X.toISOString()}] Initial path read
|
|
51
|
+
`),process.stderr.write(` Source file: ${this.targetFile}
|
|
52
|
+
`),process.stderr.write(` Raw content: "${$}"
|
|
53
|
+
`),process.stderr.write(` Resolved: "${J}"
|
|
54
|
+
`);this.lastReadPath=J,this._state={path:J,lastUpdate:X,rawContent:$,sourceFile:this.targetFile}}}catch{}this.watcher=Z9(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.readTargetDebounced()),this.watcher.on("add",()=>this.readTargetDebounced())}stop(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.watcher)this.watcher.close(),this.watcher=null}}class eK{screen;layout;uiState;gitManager=null;fileWatcher=null;explorerManager=null;config;commandServer;repoPath;watcherState={enabled:!1};currentTheme;commitFlowState;commitTextarea=null;activeModal=null;bottomPaneTotalRows=0;constructor(K){this.config=K.config,this.commandServer=K.commandServer??null,this.repoPath=K.initialPath??process.cwd(),this.currentTheme=K.config.theme,this.uiState=new hK({splitRatio:K.config.splitRatio??0.4}),this.screen=G8.screen({smartCSR:!0,fullUnicode:!0,title:"diffstalker",mouse:!0,terminal:"xterm-256color"});let $=this.screen;if($.tput)$.tput.colors=256;if($.program?.tput)$.program.tput.colors=256;if(this.layout=new OK(this.screen,this.uiState.state.splitRatio),this.screen.on("resize",()=>{setImmediate(()=>this.render())}),this.commitFlowState=new fK({getHeadMessage:()=>this.gitManager?.getHeadCommitMessage()??Promise.resolve(""),onCommit:async(J,X)=>{await this.gitManager?.commit(J,X)},onSuccess:()=>{this.uiState.setTab("diff"),this.render()}}),this.commitTextarea=G8.textarea({parent:this.layout.bottomPane,top:3,left:1,width:"100%-4",height:1,inputOnFocus:!0,hidden:!0,style:{fg:"white",bg:"default"}}),this.commitTextarea.on("submit",()=>{this.commitFlowState.submit()}),this.commitTextarea.on("keypress",()=>{setImmediate(()=>{let J=this.commitTextarea?.getValue()??"";this.commitFlowState.setMessage(J)})}),this.setupKeyboardHandlers(),this.setupMouseHandlers(),this.setupStateListeners(),this.config.watcherEnabled)this.setupFileWatcher();if(this.commandServer)this.setupCommandHandler();this.initGitManager(),this.render()}setupKeyboardHandlers(){this.screen.key(["q","C-c"],()=>{this.exit()}),this.screen.key(["j","down"],()=>{if(this.activeModal)return;this.navigateDown()}),this.screen.key(["k","up"],()=>{if(this.activeModal)return;this.navigateUp()}),this.screen.key(["1"],()=>{if(this.activeModal)return;this.uiState.setTab("diff")}),this.screen.key(["2"],()=>{if(this.activeModal)return;this.uiState.setTab("commit")}),this.screen.key(["3"],()=>{if(this.activeModal)return;this.uiState.setTab("history")}),this.screen.key(["4"],()=>{if(this.activeModal)return;this.uiState.setTab("compare")}),this.screen.key(["5"],()=>{if(this.activeModal)return;this.uiState.setTab("explorer")}),this.screen.key(["tab"],()=>{if(this.activeModal)return;this.uiState.togglePane()}),this.screen.key(["s"],()=>{if(this.activeModal)return;this.stageSelected()}),this.screen.key(["S-u"],()=>{if(this.activeModal)return;this.unstageSelected()}),this.screen.key(["S-a"],()=>{if(this.activeModal)return;this.stageAll()}),this.screen.key(["S-z"],()=>{if(this.activeModal)return;this.unstageAll()}),this.screen.key(["enter","space"],()=>{if(this.activeModal)return;let K=this.uiState.state;if(K.bottomTab==="explorer"&&K.currentPane==="explorer")this.enterExplorerDirectory();else this.toggleSelected()}),this.screen.key(["backspace"],()=>{if(this.activeModal)return;let K=this.uiState.state;if(K.bottomTab==="explorer"&&K.currentPane==="explorer")this.goExplorerUp()}),this.screen.key(["c"],()=>{if(this.activeModal)return;this.uiState.setTab("commit")}),this.screen.key(["i"],()=>{if(this.uiState.state.bottomTab==="commit"&&!this.commitFlowState.state.inputFocused)this.focusCommitInput()}),this.screen.key(["a"],()=>{if(this.uiState.state.bottomTab==="commit"&&!this.commitFlowState.state.inputFocused)this.commitFlowState.toggleAmend(),this.render()}),this.screen.key(["escape"],()=>{if(this.uiState.state.bottomTab==="commit")if(this.commitFlowState.state.inputFocused)this.unfocusCommitInput();else this.uiState.setTab("diff")}),this.screen.key(["r"],()=>this.refresh()),this.screen.key(["w"],()=>this.uiState.toggleWrapMode()),this.screen.key(["m"],()=>this.toggleMouseMode()),this.screen.key(["S-t"],()=>this.uiState.toggleAutoTab()),this.screen.key(["-","_"],()=>{this.uiState.adjustSplitRatio(-MK),this.layout.setSplitRatio(this.uiState.state.splitRatio),this.render()}),this.screen.key(["=","+"],()=>{this.uiState.adjustSplitRatio(MK),this.layout.setSplitRatio(this.uiState.state.splitRatio),this.render()}),this.screen.key(["t"],()=>this.uiState.openModal("theme")),this.screen.key(["?"],()=>this.uiState.toggleModal("hotkeys")),this.screen.key(["f"],()=>this.toggleFollow()),this.screen.key(["b"],()=>{if(this.uiState.state.bottomTab==="compare")this.uiState.openModal("baseBranch")}),this.screen.key(["u"],()=>{if(this.uiState.state.bottomTab==="compare"){this.uiState.toggleIncludeUncommitted();let K=this.uiState.state.includeUncommitted;this.gitManager?.refreshCompareDiff(K)}}),this.screen.key(["d"],()=>{if(this.uiState.state.bottomTab==="diff"){let K=this.gitManager?.state.status?.files??[],$=this.uiState.state.selectedIndex,J=K[$];if(J&&!J.staged&&J.status!=="untracked")this.showDiscardConfirm(J)}})}setupMouseHandlers(){this.layout.topPane.on("wheeldown",()=>{this.handleTopPaneScroll(3)}),this.layout.topPane.on("wheelup",()=>{this.handleTopPaneScroll(-3)}),this.layout.bottomPane.on("wheeldown",()=>{this.handleBottomPaneScroll(3)}),this.layout.bottomPane.on("wheelup",()=>{this.handleBottomPaneScroll(-3)}),this.layout.topPane.on("click",($)=>{let J=this.layout.screenYToTopPaneRow($.y);if(J>=0)this.handleTopPaneClick(J)}),this.layout.footerBox.on("click",($)=>{this.handleFooterClick($.x)})}handleTopPaneClick(K){let $=this.uiState.state;if($.bottomTab==="history"){let J=$.historyScrollOffset+K;this.uiState.setHistorySelectedIndex(J),this.selectHistoryCommitByIndex(J)}else if($.bottomTab==="compare"){let J=this.gitManager?.compareState,X=J?.compareDiff?.commits??[],Z=J?.compareDiff?.files??[],Q=PK($.compareScrollOffset+K,X,Z);if(Q)this.selectCompareItem(Q)}else if($.bottomTab==="explorer"){let J=$.explorerScrollOffset+K;this.explorerManager?.selectIndex(J),this.uiState.setExplorerSelectedIndex(J)}else{let J=this.gitManager?.state.status?.files??[],X=V7(K+$.fileListScrollOffset,J);if(X!==null&&X>=0)this.uiState.setSelectedIndex(X),this.selectFileByIndex(X)}}handleFooterClick(K){let $=this.screen.width||80,J=[{tab:"explorer",label:"[5]Explorer",width:11},{tab:"compare",label:"[4]Compare",width:10},{tab:"history",label:"[3]History",width:10},{tab:"commit",label:"[2]Commit",width:9},{tab:"diff",label:"[1]Diff",width:7}],X=$;for(let{tab:Z,width:Q}of J){let q=X-Q-1;if(K>=q&&K<X){this.uiState.setTab(Z);return}X=q}if(K>=2&&K<=9)this.toggleMouseMode();else if(K>=11&&K<=16)this.uiState.toggleAutoTab();else if(K>=18&&K<=23)this.uiState.toggleWrapMode();else if(K>=25&&K<=30&&this.uiState.state.bottomTab==="explorer")this.uiState.toggleMiddleDots();else if(K===0)this.uiState.openModal("hotkeys")}handleTopPaneScroll(K){let $=this.uiState.state,J=this.layout.dimensions.topPaneHeight;if($.bottomTab==="history"){let X=this.gitManager?.historyState.commits.length??0,Z=Math.max(0,X-J),Q=Math.min(Z,Math.max(0,$.historyScrollOffset+K));this.uiState.setHistoryScrollOffset(Q)}else if($.bottomTab==="compare"){let X=this.gitManager?.compareState,Z=L7(X?.compareDiff?.commits??[],X?.compareDiff?.files??[]),Q=Math.max(0,Z-J),q=Math.min(Q,Math.max(0,$.compareScrollOffset+K));this.uiState.setCompareScrollOffset(q)}else if($.bottomTab==="explorer"){let X=y7(this.explorerManager?.state.items??[]),Z=Math.max(0,X-J),Q=Math.min(Z,Math.max(0,$.explorerScrollOffset+K));this.uiState.setExplorerScrollOffset(Q)}else{let X=this.gitManager?.state.status?.files??[],Z=Y7(X),Q=Math.max(0,Z-J),q=Math.min(Q,Math.max(0,$.fileListScrollOffset+K));this.uiState.setFileListScrollOffset(q)}}handleBottomPaneScroll(K){let $=this.uiState.state,J=this.layout.dimensions.bottomPaneHeight,X=this.screen.width||80;if($.bottomTab==="explorer"){let Z=this.explorerManager?.state.selectedFile,Q=w7(Z?.content??null,Z?.path??null,Z?.truncated??!1,X,$.wrapMode),q=Math.max(0,Q-J),Y=Math.min(q,Math.max(0,$.explorerFileScrollOffset+K));this.uiState.setExplorerFileScrollOffset(Y)}else{let Z=Math.max(0,this.bottomPaneTotalRows-J),Q=Math.min(Z,Math.max(0,$.diffScrollOffset+K));this.uiState.setDiffScrollOffset(Q)}}setupStateListeners(){this.uiState.on("change",()=>{this.render()}),this.uiState.on("tab-change",($)=>{if($==="history")this.gitManager?.loadHistory();else if($==="compare")this.gitManager?.refreshCompareDiff(this.uiState.state.includeUncommitted);else if($==="explorer"){if(!this.explorerManager?.state.items.length)this.explorerManager?.loadDirectory("")}}),this.uiState.on("modal-change",($)=>{if(this.activeModal)this.activeModal=null;if($==="theme")this.activeModal=new uK(this.screen,this.currentTheme,(J)=>{this.currentTheme=J,NK({theme:J}),this.activeModal=null,this.uiState.closeModal(),this.render()},()=>{this.activeModal=null,this.uiState.closeModal()}),this.activeModal.focus();else if($==="hotkeys")this.activeModal=new pK(this.screen,()=>{this.activeModal=null,this.uiState.closeModal()}),this.activeModal.focus();else if($==="baseBranch")this.gitManager?.getCandidateBaseBranches().then((J)=>{let X=this.gitManager?.compareState.compareBaseBranch??null;this.activeModal=new gK(this.screen,J,X,(Z)=>{this.activeModal=null,this.uiState.closeModal();let Q=this.uiState.state.includeUncommitted;this.gitManager?.setCompareBaseBranch(Z,Q)},()=>{this.activeModal=null,this.uiState.closeModal()}),this.activeModal.focus()})});let K=null;this.uiState.on("change",($)=>{if(K)clearTimeout(K);K=setTimeout(()=>{if($.splitRatio!==this.config.splitRatio)NK({splitRatio:$.splitRatio})},500)})}setupFileWatcher(){this.fileWatcher=new tK(this.config.targetFile),this.fileWatcher.on("path-change",($)=>{if($.path&&$.path!==this.repoPath)this.repoPath=$.path,this.watcherState={enabled:!0,sourceFile:$.sourceFile??this.config.targetFile,rawContent:$.rawContent??void 0,lastUpdate:$.lastUpdate??void 0},this.initGitManager(),this.render();if($.rawContent)this.navigateToFile($.rawContent),this.render()}),this.watcherState={enabled:!0,sourceFile:this.config.targetFile},this.fileWatcher.start();let K=this.fileWatcher.state;if(K.rawContent)this.watcherState.rawContent=K.rawContent,this.navigateToFile(K.rawContent)}initGitManager(){if(this.gitManager)this.gitManager.removeAllListeners(),aK(this.repoPath);this.gitManager=U8(this.repoPath),this.gitManager.on("state-change",()=>{this.render()}),this.gitManager.on("history-state-change",(K)=>{if(K.commits.length>0&&!K.selectedCommit){let $=this.uiState.state;if($.bottomTab==="history")this.selectHistoryCommitByIndex($.historySelectedIndex)}this.render()}),this.gitManager.on("compare-state-change",()=>{this.render()}),this.gitManager.on("compare-selection-change",()=>{this.render()}),this.gitManager.startWatching(),this.gitManager.refresh(),this.initExplorerManager()}initExplorerManager(){if(this.explorerManager)this.explorerManager.dispose();let K={hideHidden:!0,hideGitignored:!0};this.explorerManager=new wK(this.repoPath,K),this.explorerManager.on("state-change",()=>{this.render()}),this.explorerManager.loadDirectory("")}setupCommandHandler(){if(!this.commandServer)return;let K={navigateUp:()=>this.navigateUp(),navigateDown:()=>this.navigateDown(),switchTab:($)=>this.uiState.setTab($),togglePane:()=>this.uiState.togglePane(),stage:async()=>this.stageSelected(),unstage:async()=>this.unstageSelected(),stageAll:async()=>this.stageAll(),unstageAll:async()=>this.unstageAll(),commit:async($)=>this.commit($),refresh:async()=>this.refresh(),getState:()=>this.getAppState(),quit:()=>this.exit()};this.commandServer.setHandler(K),this.commandServer.notifyReady()}getAppState(){let K=this.uiState.state,$=this.gitManager?.state,J=this.gitManager?.historyState,X=$?.status?.files??[],Z=J?.commits??[];return{currentTab:K.bottomTab,currentPane:K.currentPane,selectedIndex:K.selectedIndex,totalFiles:X.length,stagedCount:X.filter((Q)=>Q.staged).length,files:X.map((Q)=>({path:Q.path,status:Q.status,staged:Q.staged})),historySelectedIndex:K.historySelectedIndex,historyCommitCount:Z.length,compareSelectedIndex:K.compareSelectedIndex,compareTotalItems:0,includeUncommitted:K.includeUncommitted,explorerPath:this.repoPath,explorerSelectedIndex:K.explorerSelectedIndex,explorerItemCount:0,wrapMode:K.wrapMode,mouseEnabled:K.mouseEnabled,autoTabEnabled:K.autoTabEnabled}}navigateUp(){let K=this.uiState.state;if(K.bottomTab==="history"){if(K.currentPane==="history")this.navigateHistoryUp();else if(K.currentPane==="diff")this.uiState.setDiffScrollOffset(Math.max(0,K.diffScrollOffset-3));return}if(K.bottomTab==="compare"){if(K.currentPane==="compare")this.navigateCompareUp();else if(K.currentPane==="diff")this.uiState.setDiffScrollOffset(Math.max(0,K.diffScrollOffset-3));return}if(K.bottomTab==="explorer"){if(K.currentPane==="explorer")this.navigateExplorerUp();else if(K.currentPane==="diff")this.uiState.setExplorerFileScrollOffset(Math.max(0,K.explorerFileScrollOffset-3));return}if(K.currentPane==="files"){let $=this.gitManager?.state.status?.files??[],J=Math.max(0,K.selectedIndex-1);this.uiState.setSelectedIndex(J),this.selectFileByIndex(J);let X=TK(J,$);if(X<K.fileListScrollOffset)this.uiState.setFileListScrollOffset(X)}else if(K.currentPane==="diff")this.uiState.setDiffScrollOffset(Math.max(0,K.diffScrollOffset-3))}navigateDown(){let K=this.uiState.state,$=this.gitManager?.state.status?.files??[];if(K.bottomTab==="history"){if(K.currentPane==="history")this.navigateHistoryDown();else if(K.currentPane==="diff")this.uiState.setDiffScrollOffset(K.diffScrollOffset+3);return}if(K.bottomTab==="compare"){if(K.currentPane==="compare")this.navigateCompareDown();else if(K.currentPane==="diff")this.uiState.setDiffScrollOffset(K.diffScrollOffset+3);return}if(K.bottomTab==="explorer"){if(K.currentPane==="explorer")this.navigateExplorerDown();else if(K.currentPane==="diff")this.uiState.setExplorerFileScrollOffset(K.explorerFileScrollOffset+3);return}if(K.currentPane==="files"){let J=Math.min($.length-1,K.selectedIndex+1);this.uiState.setSelectedIndex(J),this.selectFileByIndex(J);let X=TK(J,$),Z=K.fileListScrollOffset+this.layout.dimensions.topPaneHeight-1;if(X>=Z)this.uiState.setFileListScrollOffset(K.fileListScrollOffset+(X-Z+1))}else if(K.currentPane==="diff")this.uiState.setDiffScrollOffset(K.diffScrollOffset+3)}navigateHistoryUp(){let K=this.uiState.state,$=Math.max(0,K.historySelectedIndex-1);if($!==K.historySelectedIndex){if(this.uiState.setHistorySelectedIndex($),$<K.historyScrollOffset)this.uiState.setHistoryScrollOffset($);this.selectHistoryCommitByIndex($)}}navigateHistoryDown(){let K=this.uiState.state,$=this.gitManager?.historyState.commits??[],J=Math.min($.length-1,K.historySelectedIndex+1);if(J!==K.historySelectedIndex){this.uiState.setHistorySelectedIndex(J);let X=K.historyScrollOffset+this.layout.dimensions.topPaneHeight-1;if(J>=X)this.uiState.setHistoryScrollOffset(K.historyScrollOffset+1);this.selectHistoryCommitByIndex(J)}}selectHistoryCommitByIndex(K){let $=this.gitManager?.historyState.commits??[],J=F7($,K);if(J)this.uiState.setDiffScrollOffset(0),this.gitManager?.selectHistoryCommit(J)}compareSelection=null;navigateCompareUp(){let K=this.gitManager?.compareState,$=K?.compareDiff?.commits??[],J=K?.compareDiff?.files??[];if($.length===0&&J.length===0)return;let X=CK(this.compareSelection,$,J,"up");if(X&&(X.type!==this.compareSelection?.type||X.index!==this.compareSelection?.index)){this.selectCompareItem(X);let Z=this.uiState.state,Q=UK(X,$,J);if(Q<Z.compareScrollOffset)this.uiState.setCompareScrollOffset(Q)}}navigateCompareDown(){let K=this.gitManager?.compareState,$=K?.compareDiff?.commits??[],J=K?.compareDiff?.files??[];if($.length===0&&J.length===0)return;if(!this.compareSelection){if($.length>0)this.selectCompareItem({type:"commit",index:0});else if(J.length>0)this.selectCompareItem({type:"file",index:0});return}let X=CK(this.compareSelection,$,J,"down");if(X&&(X.type!==this.compareSelection?.type||X.index!==this.compareSelection?.index)){this.selectCompareItem(X);let Z=this.uiState.state,Q=UK(X,$,J),q=Z.compareScrollOffset+this.layout.dimensions.topPaneHeight-1;if(Q>=q)this.uiState.setCompareScrollOffset(Z.compareScrollOffset+(Q-q+1))}}selectCompareItem(K){if(this.compareSelection=K,this.uiState.setDiffScrollOffset(0),K.type==="commit")this.gitManager?.selectCompareCommit(K.index);else this.gitManager?.selectCompareFile(K.index)}navigateExplorerUp(){let K=this.uiState.state;if((this.explorerManager?.state.items??[]).length===0)return;let J=this.explorerManager?.navigateUp(K.explorerScrollOffset);if(J!==null&&J!==void 0)this.uiState.setExplorerScrollOffset(J);this.uiState.setExplorerSelectedIndex(this.explorerManager?.state.selectedIndex??0)}navigateExplorerDown(){let K=this.uiState.state;if((this.explorerManager?.state.items??[]).length===0)return;let J=this.layout.dimensions.topPaneHeight,X=this.explorerManager?.navigateDown(K.explorerScrollOffset,J);if(X!==null&&X!==void 0)this.uiState.setExplorerScrollOffset(X);this.uiState.setExplorerSelectedIndex(this.explorerManager?.state.selectedIndex??0)}async enterExplorerDirectory(){await this.explorerManager?.enterDirectory(),this.uiState.setExplorerScrollOffset(0),this.uiState.setExplorerFileScrollOffset(0),this.uiState.setExplorerSelectedIndex(0)}async goExplorerUp(){await this.explorerManager?.goUp(),this.uiState.setExplorerScrollOffset(0),this.uiState.setExplorerFileScrollOffset(0),this.uiState.setExplorerSelectedIndex(0)}selectFileByIndex(K){let $=this.gitManager?.state.status?.files??[],J=z7($,K);if(J)this.uiState.setDiffScrollOffset(0),this.gitManager?.selectFile(J)}navigateToFile(K){if(!K||!this.repoPath)return;let $=this.repoPath.endsWith("/")?this.repoPath:this.repoPath+"/";if(!K.startsWith($))return;let J=K.slice($.length);if(!J)return;let Z=(this.gitManager?.state.status?.files??[]).findIndex((Q)=>Q.path===J);if(Z>=0)this.uiState.setSelectedIndex(Z),this.selectFileByIndex(Z)}async stageSelected(){let $=(this.gitManager?.state.status?.files??[])[this.uiState.state.selectedIndex];if($&&!$.staged)await this.gitManager?.stage($)}async unstageSelected(){let $=(this.gitManager?.state.status?.files??[])[this.uiState.state.selectedIndex];if($?.staged)await this.gitManager?.unstage($)}async toggleSelected(){let $=(this.gitManager?.state.status?.files??[])[this.uiState.state.selectedIndex];if($)if($.staged)await this.gitManager?.unstage($);else await this.gitManager?.stage($)}async stageAll(){await this.gitManager?.stageAll()}async unstageAll(){await this.gitManager?.unstageAll()}showDiscardConfirm(K){this.activeModal=new mK(this.screen,K.path,async()=>{this.activeModal=null,await this.gitManager?.discard(K)},()=>{this.activeModal=null}),this.activeModal.focus()}async commit(K){await this.gitManager?.commit(K)}async refresh(){await this.gitManager?.refresh()}toggleMouseMode(){let K=!this.uiState.state.mouseEnabled;this.uiState.toggleMouse();let $=this.screen.program;if(K)$.enableMouse();else $.disableMouse()}toggleFollow(){if(this.fileWatcher)this.fileWatcher.stop(),this.fileWatcher=null,this.watcherState={enabled:!1};else this.setupFileWatcher();this.render()}focusCommitInput(){if(this.commitTextarea)this.commitTextarea.show(),this.commitTextarea.focus(),this.commitTextarea.setValue(this.commitFlowState.state.message),this.commitFlowState.setInputFocused(!0),this.render()}unfocusCommitInput(){if(this.commitTextarea){let K=this.commitTextarea.getValue()??"";this.commitFlowState.setMessage(K),this.commitTextarea.hide(),this.commitFlowState.setInputFocused(!1),this.screen.focusPush(this.layout.bottomPane),this.render()}}render(){this.updateHeader(),this.updateTopPane(),this.updateBottomPane(),this.updateFooter(),this.screen.render()}updateHeader(){let K=this.gitManager?.state,$=this.screen.width||80,J=X7(this.repoPath,K?.status?.branch??null,K?.isLoading??!1,K?.error??null,this.watcherState,$);this.layout.headerBox.setContent(J)}updateTopPane(){let K=this.gitManager?.state,$=this.gitManager?.historyState,J=this.gitManager?.compareState,X=K?.status?.files??[],Z=this.uiState.state,Q=this.screen.width||80,q;if(Z.bottomTab==="history"){let Y=$?.commits??[];q=R7(Y,Z.historySelectedIndex,Z.currentPane==="history",Q,Z.historyScrollOffset,this.layout.dimensions.topPaneHeight)}else if(Z.bottomTab==="compare"){let Y=J?.compareDiff,V=Y?.commits??[],_=Y?.files??[];q=v7(V,_,this.compareSelection,Z.currentPane==="compare",Q,Z.compareScrollOffset,this.layout.dimensions.topPaneHeight)}else if(Z.bottomTab==="explorer"){let Y=this.explorerManager?.state,V=Y?.items??[];q=W7(V,Z.explorerSelectedIndex,Z.currentPane==="explorer",Q,Z.explorerScrollOffset,this.layout.dimensions.topPaneHeight,Y?.isLoading??!1,Y?.error??null)}else q=q7(X,Z.selectedIndex,Z.currentPane==="files",Q,Z.fileListScrollOffset,this.layout.dimensions.topPaneHeight);this.layout.topPane.setContent(q)}updateBottomPane(){let K=this.gitManager?.state,$=this.gitManager?.historyState,J=K?.diff??null,X=this.uiState.state,Z=this.screen.width||80,q=(K?.status?.files??[]).filter((Y)=>Y.staged).length;if(this.commitFlowState.setStagedCount(q),X.bottomTab==="commit"){let Y=D7(this.commitFlowState.state,q,Z);if(this.layout.bottomPane.setContent(Y),this.commitTextarea)if(this.commitFlowState.state.inputFocused)this.commitTextarea.show();else this.commitTextarea.hide()}else if(X.bottomTab==="history"){if(this.commitTextarea)this.commitTextarea.hide();let Y=$?.selectedCommit??null,V=$?.commitDiff??null,{content:_,totalRows:z}=I7(Y,V,Z,X.diffScrollOffset,this.layout.dimensions.bottomPaneHeight,this.currentTheme,X.wrapMode);this.bottomPaneTotalRows=z,this.layout.bottomPane.setContent(_)}else if(X.bottomTab==="compare"){if(this.commitTextarea)this.commitTextarea.hide();let V=this.gitManager?.compareSelectionState?.diff??null;if(V){let{content:_,totalRows:z}=yK(V,Z,X.diffScrollOffset,this.layout.dimensions.bottomPaneHeight,this.currentTheme,X.wrapMode);this.bottomPaneTotalRows=z,this.layout.bottomPane.setContent(_)}else this.bottomPaneTotalRows=0,this.layout.bottomPane.setContent("{gray-fg}Select a commit or file to view diff{/gray-fg}")}else if(X.bottomTab==="explorer"){if(this.commitTextarea)this.commitTextarea.hide();let V=this.explorerManager?.state?.selectedFile??null,_=x7(V?.path??null,V?.content??null,Z,X.explorerFileScrollOffset,this.layout.dimensions.bottomPaneHeight,V?.truncated??!1,X.wrapMode,X.showMiddleDots);this.layout.bottomPane.setContent(_)}else{if(this.commitTextarea)this.commitTextarea.hide();let{content:Y,totalRows:V}=yK(J,Z,X.diffScrollOffset,this.layout.dimensions.bottomPaneHeight,this.currentTheme,X.wrapMode);this.bottomPaneTotalRows=V,this.layout.bottomPane.setContent(Y)}}updateFooter(){let K=this.uiState.state,$=this.screen.width||80,J=Q7(K.bottomTab,K.mouseEnabled,K.autoTabEnabled,K.wrapMode,K.showMiddleDots,$);this.layout.footerBox.setContent(J)}exit(){if(this.gitManager)aK(this.repoPath);if(this.explorerManager)this.explorerManager.dispose();if(this.fileWatcher)this.fileWatcher.stop();if(this.commandServer)this.commandServer.stop();this.screen.destroy()}start(){return new Promise((K)=>{this.screen.on("destroy",()=>{K()})})}}import*as A8 from"net";import*as u from"fs";import{EventEmitter as q9}from"events";class K7 extends q9{server=null;socketPath;handler=null;ready=!1;constructor(K){super();this.socketPath=K}setHandler(K){this.handler=K}notifyReady(){this.ready=!0,this.emit("ready")}isReady(){return this.ready&&this.handler!==null}async start(){if(u.existsSync(this.socketPath))u.unlinkSync(this.socketPath);return new Promise((K,$)=>{this.server=A8.createServer((J)=>{this.handleConnection(J)}),this.server.on("error",(J)=>{$(J)}),this.server.listen(this.socketPath,()=>{u.chmodSync(this.socketPath,384),K()})})}stop(){if(this.server)this.server.close(),this.server=null;if(u.existsSync(this.socketPath))u.unlinkSync(this.socketPath)}handleConnection(K){let $="";K.on("data",async(J)=>{$+=J.toString();let X=$.split(`
|
|
55
|
+
`);$=X.pop()||"";for(let Z of X)if(Z.trim()){let Q=await this.processCommand(Z);K.write(JSON.stringify(Q)+`
|
|
56
|
+
`)}}),K.on("error",(J)=>{this.emit("error",J)})}async processCommand(K){try{let $=JSON.parse(K);if($.action==="ping")return{success:!0,ready:this.isReady()};if(!this.handler)return{success:!1,error:"No handler registered"};switch($.action){case"navigateUp":return this.handler.navigateUp(),{success:!0};case"navigateDown":return this.handler.navigateDown(),{success:!0};case"switchTab":return this.handler.switchTab($.tab),{success:!0};case"togglePane":return this.handler.togglePane(),{success:!0};case"stage":return await this.handler.stage(),{success:!0};case"unstage":return await this.handler.unstage(),{success:!0};case"stageAll":return await this.handler.stageAll(),{success:!0};case"unstageAll":return await this.handler.unstageAll(),{success:!0};case"commit":return await this.handler.commit($.message),{success:!0};case"refresh":return await this.handler.refresh(),{success:!0};case"getState":return{success:!0,state:this.handler.getState()};case"quit":return this.handler.quit(),{success:!0};default:return{success:!1,error:`Unknown action: ${$.action}`}}}catch($){return{success:!1,error:$ instanceof Error?$.message:String($)}}}}function f(){process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[r")}f();process.on("exit",f);process.on("SIGINT",()=>{f(),process.exit(0)});process.on("SIGTERM",()=>{f(),process.exit(0)});process.on("uncaughtException",(K)=>{f(),console.error("Uncaught exception:",K),process.exit(1)});process.on("unhandledRejection",(K)=>{f(),console.error("Unhandled rejection:",K),process.exit(1)});function Y9(K){let $={};for(let J=0;J<K.length;J++){let X=K[J];if(X==="--follow"||X==="-f"){if($.follow=!0,K[J+1]&&!K[J+1].startsWith("-"))$.followFile=K[++J]}else if(X==="--once")$.once=!0;else if(X==="--debug"||X==="-d")$.debug=!0;else if(X==="--socket"||X==="-s")if(K[J+1]&&!K[J+1].startsWith("-"))$.socket=K[++J];else console.error("Error: --socket requires a path argument"),process.exit(1);else if(X==="--help"||X==="-h")console.log(`
|
|
3
57
|
diffstalker - Terminal git diff/status viewer
|
|
4
58
|
|
|
5
59
|
Usage: diffstalker [options] [path]
|
|
@@ -7,6 +61,7 @@ Usage: diffstalker [options] [path]
|
|
|
7
61
|
Options:
|
|
8
62
|
-f, --follow [FILE] Follow hook file for dynamic repo switching
|
|
9
63
|
(default: ~/.cache/diffstalker/target)
|
|
64
|
+
-s, --socket PATH Enable IPC server on Unix socket for testing
|
|
10
65
|
--once Show status once and exit
|
|
11
66
|
-d, --debug Log path changes to stderr for debugging
|
|
12
67
|
-h, --help Show this help message
|
|
@@ -24,20 +79,19 @@ Environment:
|
|
|
24
79
|
DIFFSTALKER_PAGER External pager for diff display
|
|
25
80
|
|
|
26
81
|
Keyboard:
|
|
27
|
-
j/k,
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
Enter/Space
|
|
33
|
-
Tab
|
|
34
|
-
1/2
|
|
35
|
-
c
|
|
36
|
-
r
|
|
37
|
-
q / Ctrl+C
|
|
82
|
+
j/k, Up/Down Navigate files / scroll diff
|
|
83
|
+
s Stage selected file
|
|
84
|
+
Shift+u Unstage selected file
|
|
85
|
+
Shift+a Stage all files
|
|
86
|
+
Shift+z Unstage all files
|
|
87
|
+
Enter/Space Toggle stage/unstage
|
|
88
|
+
Tab Switch between panes
|
|
89
|
+
1/2/3/4/5 Switch tabs (Diff/Commit/History/Compare/Explorer)
|
|
90
|
+
c Open commit panel
|
|
91
|
+
r Refresh
|
|
92
|
+
q / Ctrl+C Quit
|
|
38
93
|
|
|
39
94
|
Mouse:
|
|
40
|
-
Click
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
`),process.exit(0)):t.startsWith("-")||(o.initialPath=t)}return o}const s=p(process.argv.slice(2)),r=c();s.follow&&(r.watcherEnabled=!0,s.followFile&&(r.targetFile=s.followFile)),s.debug&&(r.debug=!0);const{waitUntilExit:d}=f(n(a,{config:r,initialPath:s.initialPath}));d().then(()=>{process.exit(0)});
|
|
95
|
+
Click Select file / focus pane
|
|
96
|
+
Scroll Navigate files / scroll diff
|
|
97
|
+
`),process.exit(0);else if(!X.startsWith("-"))$.initialPath=X}return $}async function z9(){let K=Y9(process.argv.slice(2)),$=$7();if(K.follow){if($.watcherEnabled=!0,K.followFile)$.targetFile=K.followFile}if(K.debug)$.debug=!0;let J=null;if(K.socket){J=new K7(K.socket);try{await J.start()}catch(Z){console.error("Failed to start command server:",Z),process.exit(1)}}if(await new eK({config:$,initialPath:K.initialPath,commandServer:J}).start(),J)J.stop();process.exit(0)}z9().catch((K)=>{console.error("Fatal error:",K),f(),process.exit(1)});
|