git-drive 0.1.0 → 0.1.2

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.
Files changed (68) hide show
  1. package/dist/commands/archive.js +32 -0
  2. package/dist/commands/init.js +55 -0
  3. package/dist/commands/link.js +139 -0
  4. package/dist/commands/list.js +83 -0
  5. package/dist/commands/push.js +99 -0
  6. package/dist/commands/restore.js +30 -0
  7. package/dist/commands/status.js +116 -0
  8. package/dist/config.js +62 -0
  9. package/dist/errors.js +30 -0
  10. package/dist/git.js +60 -0
  11. package/dist/index.js +100 -0
  12. package/dist/server.js +526 -0
  13. package/package.json +45 -14
  14. package/.github/workflows/ci.yml +0 -77
  15. package/.planning/codebase/ARCHITECTURE.md +0 -151
  16. package/.planning/codebase/CONCERNS.md +0 -191
  17. package/.planning/codebase/CONVENTIONS.md +0 -169
  18. package/.planning/codebase/INTEGRATIONS.md +0 -94
  19. package/.planning/codebase/STACK.md +0 -77
  20. package/.planning/codebase/STRUCTURE.md +0 -157
  21. package/.planning/codebase/TESTING.md +0 -156
  22. package/Dockerfile.cli +0 -30
  23. package/Dockerfile.server +0 -32
  24. package/README.md +0 -95
  25. package/docker-compose.yml +0 -48
  26. package/packages/cli/Dockerfile +0 -26
  27. package/packages/cli/package.json +0 -57
  28. package/packages/cli/src/commands/archive.ts +0 -39
  29. package/packages/cli/src/commands/init.ts +0 -34
  30. package/packages/cli/src/commands/link.ts +0 -115
  31. package/packages/cli/src/commands/list.ts +0 -94
  32. package/packages/cli/src/commands/push.ts +0 -64
  33. package/packages/cli/src/commands/restore.ts +0 -36
  34. package/packages/cli/src/commands/status.ts +0 -127
  35. package/packages/cli/src/config.ts +0 -73
  36. package/packages/cli/src/errors.ts +0 -23
  37. package/packages/cli/src/git.ts +0 -55
  38. package/packages/cli/src/index.ts +0 -97
  39. package/packages/cli/src/server.ts +0 -514
  40. package/packages/cli/tsconfig.json +0 -13
  41. package/packages/git-drive-docker/package.json +0 -15
  42. package/packages/server/package.json +0 -44
  43. package/packages/server/src/index.ts +0 -569
  44. package/packages/server/tsconfig.json +0 -9
  45. package/packages/ui/README.md +0 -73
  46. package/packages/ui/eslint.config.js +0 -23
  47. package/packages/ui/index.html +0 -13
  48. package/packages/ui/package.json +0 -42
  49. package/packages/ui/postcss.config.js +0 -6
  50. package/packages/ui/public/vite.svg +0 -1
  51. package/packages/ui/src/App.css +0 -23
  52. package/packages/ui/src/App.tsx +0 -726
  53. package/packages/ui/src/assets/react.svg +0 -8
  54. package/packages/ui/src/assets/vite.svg +0 -3
  55. package/packages/ui/src/index.css +0 -37
  56. package/packages/ui/src/main.tsx +0 -14
  57. package/packages/ui/tailwind.config.js +0 -11
  58. package/packages/ui/tsconfig.app.json +0 -28
  59. package/packages/ui/tsconfig.json +0 -26
  60. package/packages/ui/tsconfig.node.json +0 -12
  61. package/packages/ui/vite.config.ts +0 -7
  62. package/pnpm-workspace.yaml +0 -4
  63. package/rewrite_app.js +0 -731
  64. package/tsconfig.json +0 -14
  65. /package/{packages/cli/ui → ui}/assets/index-Cc2q1t5k.js +0 -0
  66. /package/{packages/cli/ui → ui}/assets/index-DrL7ojPA.css +0 -0
  67. /package/{packages/cli/ui → ui}/index.html +0 -0
  68. /package/{packages/cli/ui → ui}/vite.svg +0 -0
package/dist/git.js ADDED
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.git = git;
4
+ exports.listDrives = listDrives;
5
+ exports.getRepoRoot = getRepoRoot;
6
+ exports.getProjectName = getProjectName;
7
+ exports.getRemoteUrl = getRemoteUrl;
8
+ exports.isGitRepo = isGitRepo;
9
+ const child_process_1 = require("child_process");
10
+ const path_1 = require("path");
11
+ const node_disk_info_1 = require("node-disk-info");
12
+ function git(args, cwd) {
13
+ return (0, child_process_1.execSync)(`git ${args}`, {
14
+ cwd,
15
+ encoding: "utf-8",
16
+ stdio: ["pipe", "pipe", "pipe"],
17
+ }).trim();
18
+ }
19
+ async function listDrives() {
20
+ const drives = await (0, node_disk_info_1.getDiskInfo)();
21
+ return drives.filter((d) => {
22
+ const mp = d.mounted;
23
+ if (!mp)
24
+ return false;
25
+ if (mp === "/" || mp === "100%")
26
+ return false;
27
+ if (process.platform === "darwin") {
28
+ return mp.startsWith("/Volumes/") && !mp.startsWith("/Volumes/Recovery");
29
+ }
30
+ if (mp.startsWith("/sys") || mp.startsWith("/proc") || mp.startsWith("/run") || mp.startsWith("/snap") || mp.startsWith("/boot"))
31
+ return false;
32
+ if (d.filesystem === "tmpfs" || d.filesystem === "devtmpfs" || d.filesystem === "udev" || d.filesystem === "overlay")
33
+ return false;
34
+ return true;
35
+ });
36
+ }
37
+ function getRepoRoot() {
38
+ return git("rev-parse --show-toplevel");
39
+ }
40
+ function getProjectName() {
41
+ const root = getRepoRoot();
42
+ return (0, path_1.basename)(root);
43
+ }
44
+ function getRemoteUrl(remoteName) {
45
+ try {
46
+ return git(`remote get-url ${remoteName}`);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ function isGitRepo() {
53
+ try {
54
+ git("rev-parse --is-inside-work-tree");
55
+ return true;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
package/dist/index.js ADDED
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const child_process_1 = require("child_process");
5
+ const push_js_1 = require("./commands/push.js");
6
+ const list_js_1 = require("./commands/list.js");
7
+ const status_js_1 = require("./commands/status.js");
8
+ const link_js_1 = require("./commands/link.js");
9
+ const init_js_1 = require("./commands/init.js");
10
+ const errors_js_1 = require("./errors.js");
11
+ const server_js_1 = require("./server.js");
12
+ const commands = {
13
+ init: init_js_1.init,
14
+ push: push_js_1.push,
15
+ list: list_js_1.list,
16
+ status: status_js_1.status,
17
+ link: link_js_1.link,
18
+ server: startServer,
19
+ start: startServer,
20
+ ui: startServer,
21
+ };
22
+ // Commands that don't need the server running
23
+ const NO_SERVER_COMMANDS = ['server', 'start', 'ui'];
24
+ function printUsage() {
25
+ console.log(`
26
+ git-drive - Turn any external drive into a git remote backup for your code
27
+
28
+ Usage:
29
+ git-drive <command> [options]
30
+
31
+ Commands:
32
+ init Initialize git-drive on an external drive
33
+ link Link current repo to a drive
34
+ push Push current repo to drive
35
+ list Show connected drives and their status
36
+ status Show detailed status of drives and repos
37
+ server, start, ui Start the git-drive web UI server
38
+
39
+ Options:
40
+ -h, --help Show this help message
41
+
42
+ Examples:
43
+ git-drive init /Volumes/MyDrive Initialize git-drive on a drive
44
+ git-drive link Link current repo to a drive
45
+ git-drive push Push current repo to drive
46
+ git-drive list List connected drives
47
+ git-drive status Show detailed status
48
+ git-drive server Start the web UI at http://localhost:4483
49
+
50
+ Environment Variables:
51
+ GIT_DRIVE_PORT Port for the web server (default: 4483)
52
+
53
+ Docker:
54
+ docker run -it --rm -v /Volumes:/Volumes -p 4483:4483 git-drive
55
+
56
+ Documentation:
57
+ https://github.com/josmanvis/git-drive
58
+ `);
59
+ }
60
+ function startServer(_args) {
61
+ console.log('\n 🚀 Starting Git Drive server...\n');
62
+ console.log(' Web UI: http://localhost:4483\n');
63
+ console.log(' Press Ctrl+C to stop\n');
64
+ const serverPath = require.resolve('./server.js');
65
+ const child = (0, child_process_1.spawn)(process.execPath, [serverPath], {
66
+ stdio: 'inherit',
67
+ env: process.env
68
+ });
69
+ child.on('error', (err) => {
70
+ console.error('Failed to start server:', err.message);
71
+ process.exit(1);
72
+ });
73
+ child.on('exit', (code) => {
74
+ process.exit(code || 0);
75
+ });
76
+ }
77
+ const [command, ...args] = process.argv.slice(2);
78
+ (async () => {
79
+ try {
80
+ if (!command || command === "--help" || command === "-h") {
81
+ printUsage();
82
+ process.exit(0);
83
+ }
84
+ const handler = commands[command];
85
+ if (!handler) {
86
+ console.error(`Unknown command: ${command}\n`);
87
+ printUsage();
88
+ process.exit(1);
89
+ }
90
+ // Ensure server is running for commands that need it
91
+ if (!NO_SERVER_COMMANDS.includes(command)) {
92
+ await (0, server_js_1.ensureServerRunning)();
93
+ }
94
+ await handler(args);
95
+ }
96
+ catch (err) {
97
+ (0, errors_js_1.handleError)(err);
98
+ process.exit(1);
99
+ }
100
+ })();
package/dist/server.js ADDED
@@ -0,0 +1,526 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getServerPort = getServerPort;
7
+ exports.isServerRunning = isServerRunning;
8
+ exports.ensureServerRunning = ensureServerRunning;
9
+ const express_1 = __importDefault(require("express"));
10
+ const child_process_1 = require("child_process");
11
+ const path_1 = __importDefault(require("path"));
12
+ const fs_1 = require("fs");
13
+ const child_process_2 = require("child_process");
14
+ const node_disk_info_1 = require("node-disk-info");
15
+ const os_1 = require("os");
16
+ const app = (0, express_1.default)();
17
+ const port = process.env.GIT_DRIVE_PORT || 4483;
18
+ app.use(express_1.default.json());
19
+ // Serve static UI files from the ui directory
20
+ const uiPath = path_1.default.join(__dirname, '..', 'ui');
21
+ app.use(express_1.default.static(uiPath));
22
+ // ── Helpers ──────────────────────────────────────────────────────────
23
+ function git(args, cwd) {
24
+ return (0, child_process_2.execSync)(`git ${args}`, {
25
+ cwd,
26
+ encoding: 'utf-8',
27
+ stdio: ['pipe', 'pipe', 'pipe'],
28
+ }).trim();
29
+ }
30
+ function getGitDrivePath(mountpoint) {
31
+ return path_1.default.join(mountpoint, '.git-drive');
32
+ }
33
+ function ensureGitDriveDir(mountpoint) {
34
+ const gitDrivePath = getGitDrivePath(mountpoint);
35
+ if (!(0, fs_1.existsSync)(gitDrivePath)) {
36
+ try {
37
+ (0, fs_1.mkdirSync)(gitDrivePath, { recursive: true });
38
+ }
39
+ catch (err) {
40
+ throw new Error(`Failed to write to drive. Please ensure Terminal/Node has "Removable Volumes" access in macOS Privacy settings. Details: ${err.message}`);
41
+ }
42
+ }
43
+ return gitDrivePath;
44
+ }
45
+ function listRepos(gitDrivePath) {
46
+ if (!(0, fs_1.existsSync)(gitDrivePath))
47
+ return [];
48
+ return (0, fs_1.readdirSync)(gitDrivePath)
49
+ .filter((entry) => {
50
+ const entryPath = path_1.default.join(gitDrivePath, entry);
51
+ return ((0, fs_1.statSync)(entryPath).isDirectory() &&
52
+ (entry.endsWith('.git') || (0, fs_1.existsSync)(path_1.default.join(entryPath, 'HEAD'))));
53
+ })
54
+ .map((entry) => {
55
+ const entryPath = path_1.default.join(gitDrivePath, entry);
56
+ const stat = (0, fs_1.statSync)(entryPath);
57
+ return {
58
+ name: entry.replace(/\.git$/, ''),
59
+ path: entryPath,
60
+ lastModified: stat.mtime.toISOString(),
61
+ };
62
+ });
63
+ }
64
+ function loadLinks() {
65
+ const linksFile = path_1.default.join((0, os_1.homedir)(), '.config', 'git-drive', 'links.json');
66
+ if (!(0, fs_1.existsSync)(linksFile))
67
+ return {};
68
+ try {
69
+ return JSON.parse((0, fs_1.readFileSync)(linksFile, 'utf-8'));
70
+ }
71
+ catch {
72
+ return {};
73
+ }
74
+ }
75
+ // ── Server Health Check Utilities ────────────────────────────────────────────
76
+ const DEFAULT_PORT = 4483;
77
+ function getServerPort() {
78
+ return parseInt(process.env.GIT_DRIVE_PORT || String(DEFAULT_PORT), 10);
79
+ }
80
+ async function isServerRunning(port) {
81
+ const serverPort = port || getServerPort();
82
+ try {
83
+ const response = await fetch(`http://localhost:${serverPort}/api/drives`, {
84
+ method: 'HEAD',
85
+ signal: AbortSignal.timeout(1000),
86
+ });
87
+ return response.ok;
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
93
+ async function ensureServerRunning() {
94
+ const port = getServerPort();
95
+ const running = await isServerRunning(port);
96
+ if (!running) {
97
+ console.log('\n 🚀 Starting Git Drive server...\n');
98
+ // Start server in detached/background mode
99
+ const serverPath = require.resolve('./server.js');
100
+ const child = (0, child_process_1.spawn)(process.execPath, [serverPath], {
101
+ detached: true,
102
+ stdio: 'ignore',
103
+ env: process.env,
104
+ });
105
+ // Allow the parent process to exit independently
106
+ child.unref();
107
+ // Wait a moment for server to start
108
+ let retries = 10;
109
+ while (retries > 0) {
110
+ await new Promise(resolve => setTimeout(resolve, 300));
111
+ if (await isServerRunning(port)) {
112
+ break;
113
+ }
114
+ retries--;
115
+ }
116
+ if (retries === 0) {
117
+ throw new Error('Failed to start Git Drive server. Please run "git-drive server" manually.');
118
+ }
119
+ }
120
+ }
121
+ // ── API Routes ───────────────────────────────────────────────────────
122
+ // Health check endpoint
123
+ app.get('/api/health', (_req, res) => {
124
+ res.json({ status: 'ok', timestamp: new Date().toISOString() });
125
+ });
126
+ // List all connected drives
127
+ app.get('/api/drives', async (_req, res) => {
128
+ try {
129
+ const drives = await (0, node_disk_info_1.getDiskInfo)();
130
+ const result = drives
131
+ .filter((d) => {
132
+ const mp = d.mounted;
133
+ if (!mp)
134
+ return false;
135
+ if (mp === "/" || mp === "100%")
136
+ return false;
137
+ if (process.platform === "darwin") {
138
+ return mp.startsWith("/Volumes/") && !mp.startsWith("/Volumes/Recovery");
139
+ }
140
+ if (mp.startsWith("/sys") || mp.startsWith("/proc") || mp.startsWith("/run") || mp.startsWith("/snap") || mp.startsWith("/boot"))
141
+ return false;
142
+ if (d.filesystem === "tmpfs" || d.filesystem === "devtmpfs" || d.filesystem === "udev" || d.filesystem === "overlay")
143
+ return false;
144
+ return true;
145
+ })
146
+ .map((d) => ({
147
+ device: d.filesystem,
148
+ description: d.mounted,
149
+ size: d.blocks ? parseInt(d.blocks) * 1024 : 0,
150
+ isRemovable: true,
151
+ isSystem: d.mounted === '/',
152
+ mountpoints: [d.mounted],
153
+ hasGitDrive: (0, fs_1.existsSync)(getGitDrivePath(d.mounted)),
154
+ }));
155
+ res.json(result);
156
+ }
157
+ catch (err) {
158
+ res.status(500).json({ error: 'Failed to list drives' });
159
+ }
160
+ });
161
+ // List repos on a specific drive
162
+ app.get('/api/drives/:mountpoint/repos', (req, res) => {
163
+ try {
164
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
165
+ const gitDrivePath = getGitDrivePath(mountpoint);
166
+ if (!(0, fs_1.existsSync)(mountpoint)) {
167
+ res.status(404).json({ error: 'Drive not found or not mounted' });
168
+ return;
169
+ }
170
+ const repos = listRepos(gitDrivePath);
171
+ res.json({
172
+ mountpoint,
173
+ gitDrivePath,
174
+ initialized: (0, fs_1.existsSync)(gitDrivePath),
175
+ repos,
176
+ });
177
+ }
178
+ catch (err) {
179
+ res.status(500).json({ error: 'Failed to list repos' });
180
+ }
181
+ });
182
+ // Initialize git-drive on a drive
183
+ app.post('/api/drives/:mountpoint/init', (req, res) => {
184
+ try {
185
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
186
+ if (!(0, fs_1.existsSync)(mountpoint)) {
187
+ res.status(404).json({ error: 'Drive not found or not mounted' });
188
+ return;
189
+ }
190
+ const gitDrivePath = ensureGitDriveDir(mountpoint);
191
+ res.json({
192
+ mountpoint,
193
+ gitDrivePath,
194
+ message: 'Git Drive initialized on this drive',
195
+ });
196
+ }
197
+ catch (err) {
198
+ console.error("Init Error:", err);
199
+ res.status(500).json({ error: err.message || 'Failed to initialize drive' });
200
+ }
201
+ });
202
+ // Create a new bare repo on a drive
203
+ app.post('/api/drives/:mountpoint/repos', (req, res) => {
204
+ try {
205
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
206
+ const { name } = req.body;
207
+ if (!name || typeof name !== 'string') {
208
+ res.status(400).json({ error: 'Repo name is required' });
209
+ return;
210
+ }
211
+ const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '-');
212
+ if (!(0, fs_1.existsSync)(mountpoint)) {
213
+ res.status(404).json({ error: 'Drive not found or not mounted' });
214
+ return;
215
+ }
216
+ const gitDrivePath = ensureGitDriveDir(mountpoint);
217
+ const repoName = safeName.endsWith('.git') ? safeName : `${safeName}.git`;
218
+ const repoPath = path_1.default.join(gitDrivePath, repoName);
219
+ if ((0, fs_1.existsSync)(repoPath)) {
220
+ res.status(409).json({ error: 'Repository already exists' });
221
+ return;
222
+ }
223
+ git(`init --bare "${repoPath}"`);
224
+ res.status(201).json({
225
+ name: safeName.replace(/\.git$/, ''),
226
+ path: repoPath,
227
+ message: `Bare repository created: ${repoName}`,
228
+ remoteUrl: repoPath,
229
+ });
230
+ }
231
+ catch (err) {
232
+ res.status(500).json({ error: 'Failed to create repository' });
233
+ }
234
+ });
235
+ // Delete a repo from a drive
236
+ app.delete('/api/drives/:mountpoint/repos/:repoName', (req, res) => {
237
+ try {
238
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
239
+ const repoName = decodeURIComponent(req.params.repoName);
240
+ const gitDrivePath = getGitDrivePath(mountpoint);
241
+ const bareRepoName = repoName.endsWith('.git') ? repoName : `${repoName}.git`;
242
+ const repoPath = path_1.default.join(gitDrivePath, bareRepoName);
243
+ if (!(0, fs_1.existsSync)(repoPath)) {
244
+ const altPath = path_1.default.join(gitDrivePath, repoName);
245
+ if (!(0, fs_1.existsSync)(altPath)) {
246
+ res.status(404).json({ error: 'Repository not found' });
247
+ return;
248
+ }
249
+ (0, child_process_2.execSync)(`rm -rf "${altPath}"`);
250
+ }
251
+ else {
252
+ (0, child_process_2.execSync)(`rm -rf "${repoPath}"`);
253
+ }
254
+ res.json({ message: `Repository '${repoName}' deleted` });
255
+ }
256
+ catch (err) {
257
+ res.status(500).json({ error: 'Failed to delete repository' });
258
+ }
259
+ });
260
+ // Get info about a specific repo
261
+ app.get('/api/drives/:mountpoint/repos/:repoName', (req, res) => {
262
+ try {
263
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
264
+ const repoName = decodeURIComponent(req.params.repoName);
265
+ const gitDrivePath = getGitDrivePath(mountpoint);
266
+ const bareRepoName = repoName.endsWith('.git') ? repoName : `${repoName}.git`;
267
+ let repoPath = path_1.default.join(gitDrivePath, bareRepoName);
268
+ if (!(0, fs_1.existsSync)(repoPath)) {
269
+ repoPath = path_1.default.join(gitDrivePath, repoName);
270
+ if (!(0, fs_1.existsSync)(repoPath)) {
271
+ res.status(404).json({ error: 'Repository not found' });
272
+ return;
273
+ }
274
+ }
275
+ let branches = [];
276
+ try {
277
+ const branchOutput = git("branch --format='%(refname:short)'", repoPath);
278
+ branches = branchOutput
279
+ .split('\n')
280
+ .map((b) => b.trim().replace(/^'|'$/g, ''))
281
+ .filter(Boolean);
282
+ }
283
+ catch { }
284
+ let tags = [];
285
+ try {
286
+ const tagOutput = git("tag", repoPath);
287
+ tags = tagOutput.split('\n').map((t) => t.trim()).filter(Boolean);
288
+ }
289
+ catch { }
290
+ let lastCommit = null;
291
+ try {
292
+ const log = git('log -1 --format="%H|%s|%ci" --all', repoPath);
293
+ if (log) {
294
+ const [hash, message, date] = log.replace(/^"|"$/g, '').split('|');
295
+ lastCommit = { hash, message, date };
296
+ }
297
+ }
298
+ catch { }
299
+ const stat = (0, fs_1.statSync)(repoPath);
300
+ res.json({
301
+ name: repoName.replace(/\.git$/, ''),
302
+ path: repoPath,
303
+ branches,
304
+ tags,
305
+ lastCommit,
306
+ lastModified: stat.mtime.toISOString(),
307
+ remoteUrl: repoPath,
308
+ });
309
+ }
310
+ catch (err) {
311
+ res.status(500).json({ error: 'Failed to get repo info' });
312
+ }
313
+ });
314
+ // Local status check
315
+ app.get('/api/drives/:mountpoint/repos/:repoName/local-status', (req, res) => {
316
+ try {
317
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
318
+ let repoName = decodeURIComponent(req.params.repoName);
319
+ repoName = repoName.replace(/\.git$/, '');
320
+ const links = loadLinks();
321
+ let localPath = null;
322
+ for (const [p, data] of Object.entries(links)) {
323
+ if (data.mountpoint === mountpoint && data.repoName.replace(/\.git$/, '') === repoName) {
324
+ if ((0, fs_1.existsSync)(p)) {
325
+ localPath = p;
326
+ break;
327
+ }
328
+ }
329
+ }
330
+ if (!localPath) {
331
+ res.json({ linked: false });
332
+ return;
333
+ }
334
+ let hasChanges = false;
335
+ let unpushed = false;
336
+ try {
337
+ const statusOutput = git('status --porcelain', localPath);
338
+ hasChanges = statusOutput.trim().length > 0;
339
+ const unpushedOutput = git('log gd/main..HEAD --oneline', localPath);
340
+ unpushed = unpushedOutput.trim().length > 0;
341
+ }
342
+ catch { }
343
+ res.json({ linked: true, localPath, hasChanges, unpushed });
344
+ }
345
+ catch (err) {
346
+ res.status(500).json({ error: 'Failed to check local status' });
347
+ }
348
+ });
349
+ // Push to git-drive
350
+ app.post('/api/drives/:mountpoint/repos/:repoName/push', (req, res) => {
351
+ try {
352
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
353
+ let repoName = decodeURIComponent(req.params.repoName);
354
+ repoName = repoName.replace(/\.git$/, '');
355
+ const links = loadLinks();
356
+ let localPath = null;
357
+ for (const [p, data] of Object.entries(links)) {
358
+ if (data.mountpoint === mountpoint && data.repoName.replace(/\.git$/, '') === repoName) {
359
+ if ((0, fs_1.existsSync)(p)) {
360
+ localPath = p;
361
+ break;
362
+ }
363
+ }
364
+ }
365
+ if (!localPath) {
366
+ res.status(404).json({ error: 'Local linked repository not found.' });
367
+ return;
368
+ }
369
+ git('push gd --all', localPath);
370
+ git('push gd --tags', localPath);
371
+ try {
372
+ const gitDrivePath = getGitDrivePath(mountpoint);
373
+ const bareRepoName = repoName.endsWith('.git') ? repoName : `${repoName}.git`;
374
+ let repoPath = path_1.default.join(gitDrivePath, bareRepoName);
375
+ if (!(0, fs_1.existsSync)(repoPath))
376
+ repoPath = path_1.default.join(gitDrivePath, repoName);
377
+ const payload = {
378
+ date: new Date().toISOString(),
379
+ computer: (0, os_1.homedir)(),
380
+ user: process.env.USER || 'local-user',
381
+ localDir: localPath,
382
+ mode: 'web-ui',
383
+ };
384
+ const logFile = path_1.default.join(repoPath, "git-drive-pushlog.json");
385
+ (0, fs_1.appendFileSync)(logFile, JSON.stringify(payload) + "\n", "utf-8");
386
+ }
387
+ catch { }
388
+ res.json({ success: true, message: 'Successfully backed up local code to Git Drive!' });
389
+ }
390
+ catch (err) {
391
+ res.status(500).json({ error: err.message || 'Failed to push' });
392
+ }
393
+ });
394
+ // Browse repository files tree
395
+ app.get('/api/drives/:mountpoint/repos/:repoName/tree', (req, res) => {
396
+ try {
397
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
398
+ const repoName = decodeURIComponent(req.params.repoName);
399
+ const branch = req.query.branch || 'main';
400
+ const treePath = req.query.path || '';
401
+ const gitDrivePath = getGitDrivePath(mountpoint);
402
+ const bareRepoName = repoName.endsWith('.git') ? repoName : `${repoName}.git`;
403
+ let repoPath = path_1.default.join(gitDrivePath, bareRepoName);
404
+ if (!(0, fs_1.existsSync)(repoPath)) {
405
+ repoPath = path_1.default.join(gitDrivePath, repoName);
406
+ }
407
+ const target = treePath ? `${branch}:${treePath}` : branch;
408
+ const output = git(`ls-tree ${target}`, repoPath);
409
+ const files = output.split('\n').filter(Boolean).map((line) => {
410
+ const parts = line.split('\t');
411
+ const meta = parts[0].split(' ');
412
+ return {
413
+ mode: meta[0],
414
+ type: meta[1],
415
+ hash: meta[2],
416
+ path: parts[1],
417
+ name: parts[1].split('/').pop(),
418
+ };
419
+ });
420
+ res.json({ files });
421
+ }
422
+ catch (err) {
423
+ res.json({ files: [] });
424
+ }
425
+ });
426
+ // Get commit history
427
+ app.get('/api/drives/:mountpoint/repos/:repoName/commits', (req, res) => {
428
+ try {
429
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
430
+ const repoName = decodeURIComponent(req.params.repoName);
431
+ const branch = req.query.branch || 'main';
432
+ const gitDrivePath = getGitDrivePath(mountpoint);
433
+ const bareRepoName = repoName.endsWith('.git') ? repoName : `${repoName}.git`;
434
+ let repoPath = path_1.default.join(gitDrivePath, bareRepoName);
435
+ if (!(0, fs_1.existsSync)(repoPath)) {
436
+ repoPath = path_1.default.join(gitDrivePath, repoName);
437
+ }
438
+ let commits = [];
439
+ try {
440
+ const logOutput = git(`log ${branch} -n 100 --format="%H|%an|%ae|%s|%ci"`, repoPath);
441
+ commits = logOutput
442
+ .split('\n')
443
+ .filter(Boolean)
444
+ .map((line) => {
445
+ const [hash, author, email, message, date] = line.split('|');
446
+ return { hash, author, email, message, date };
447
+ });
448
+ }
449
+ catch { }
450
+ let pushLogs = [];
451
+ try {
452
+ const logFile = path_1.default.join(repoPath, "git-drive-pushlog.json");
453
+ if ((0, fs_1.existsSync)(logFile)) {
454
+ const rawLogs = (0, fs_1.readFileSync)(logFile, "utf-8").trim().split('\n');
455
+ pushLogs = rawLogs.map((l) => {
456
+ try {
457
+ return JSON.parse(l);
458
+ }
459
+ catch {
460
+ return null;
461
+ }
462
+ }).filter(Boolean);
463
+ pushLogs.reverse();
464
+ }
465
+ }
466
+ catch { }
467
+ res.json({ commits, pushLogs });
468
+ }
469
+ catch (err) {
470
+ res.status(500).json({ error: 'Failed to retrieve history' });
471
+ }
472
+ });
473
+ // Get single commit details
474
+ app.get('/api/drives/:mountpoint/repos/:repoName/commits/:hash', (req, res) => {
475
+ try {
476
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
477
+ const repoName = decodeURIComponent(req.params.repoName);
478
+ const hash = req.params.hash;
479
+ const gitDrivePath = getGitDrivePath(mountpoint);
480
+ const bareRepoName = repoName.endsWith('.git') ? repoName : `${repoName}.git`;
481
+ let repoPath = path_1.default.join(gitDrivePath, bareRepoName);
482
+ if (!(0, fs_1.existsSync)(repoPath))
483
+ repoPath = path_1.default.join(gitDrivePath, repoName);
484
+ const logOutput = git(`log -1 --format="%H|%an|%ae|%s|%ci" ${hash}`, repoPath);
485
+ const [commitHash, author, email, message, date] = logOutput.split('|');
486
+ const patch = git(`show --format="" ${hash}`, repoPath);
487
+ res.json({ hash: commitHash, author, email, message, date, patch });
488
+ }
489
+ catch (err) {
490
+ res.status(500).json({ error: 'Failed to retrieve commit details' });
491
+ }
492
+ });
493
+ // Read raw file content
494
+ app.get('/api/drives/:mountpoint/repos/:repoName/blob', (req, res) => {
495
+ try {
496
+ const mountpoint = decodeURIComponent(req.params.mountpoint);
497
+ const repoName = decodeURIComponent(req.params.repoName);
498
+ const branch = req.query.branch || 'main';
499
+ const filePath = req.query.path;
500
+ const gitDrivePath = getGitDrivePath(mountpoint);
501
+ const bareRepoName = repoName.endsWith('.git') ? repoName : `${repoName}.git`;
502
+ let repoPath = path_1.default.join(gitDrivePath, bareRepoName);
503
+ if (!(0, fs_1.existsSync)(repoPath)) {
504
+ repoPath = path_1.default.join(gitDrivePath, repoName);
505
+ }
506
+ const content = git(`show ${branch}:${filePath}`, repoPath);
507
+ res.send(content);
508
+ }
509
+ catch (err) {
510
+ res.status(500).json({ error: 'Failed to read file' });
511
+ }
512
+ });
513
+ // SPA fallback
514
+ app.get('*', (_req, res) => {
515
+ const indexPath = path_1.default.join(uiPath, 'index.html');
516
+ if ((0, fs_1.existsSync)(indexPath)) {
517
+ res.sendFile(indexPath);
518
+ }
519
+ else {
520
+ res.status(404).send('UI not built. The package may need to be rebuilt.');
521
+ }
522
+ });
523
+ // Start server
524
+ app.listen(port, () => {
525
+ console.log(`\n 🚀 Git Drive is running at http://localhost:${port}\n`);
526
+ });