-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
205 lines (190 loc) · 6.89 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
import { exec, spawn } from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from 'electron';
import initContextMenu from 'electron-context-menu';
import logging from 'electron-log';
import Store from 'electron-store';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
let window;
async function openRepo() {
const result = await dialog.showOpenDialog(window, {
title: 'Open Repo',
properties: ['openDirectory'],
});
const folder_path = result.filePaths[0];
if (folder_path !== undefined) {
const git_path = path.join(folder_path, '.git');
if (fs.existsSync(git_path)) {
return folder_path;
} else {
await dialog.showMessageBox(window, {
message: 'Not a Git repository!',
});
return await openRepo();
}
}
}
const app_menu_template = [
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'toggledevtools' },
{ type: 'separator' },
{ role: 'resetzoom' },
{ role: 'zoomin' },
{ role: 'zoomout' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
},
{
label: 'Help',
submenu: [
{ label: 'Homepage', click: () => shell.openExternal('https://github.com/adamsol/GitQuill') },
],
},
];
Menu.setApplicationMenu(Menu.buildFromTemplate(app_menu_template));
initContextMenu({ showSelectAll: false });
Store.initRenderer();
app.whenReady().then(async () => {
window = new BrowserWindow({
webPreferences: {
preload: path.join(app.getAppPath(), 'preload.cjs'),
sandbox: false, // https://github.com/sindresorhus/electron-store/issues/268#issuecomment-1809555869
},
icon: path.join(__dirname, 'img/logo.jpg'),
});
window.maximize();
async function log(repo_path, repr, func, { msg } = {}) {
const t = performance.now();
if (!fs.existsSync(path.join(repo_path, '.git'))) {
throw new Error('Not a Git repository!');
}
const file_path = path.join(repo_path, '.git/.quill/app.log');
try {
const result = await func();
const ms = `${Math.round(performance.now() - t)}`.padStart(3, ' ');
logging.transports.file.resolvePathFn = () => file_path;
logging.info(`[${ms} ms] ${repr}` + (msg ? `\n${msg}` : ''));
return result;
} catch (e) {
const ms = `${Math.round(performance.now() - t)}`.padStart(3, ' ');
logging.transports.file.resolvePathFn = () => file_path;
logging.error(`[${ms} ms] ${repr}\n${e}`);
throw e;
}
}
ipcMain.handle('open-repo', async () => {
return await openRepo();
});
ipcMain.handle('open-terminal', (event, repo_path) => {
const platform = os.platform();
let cmd;
if (platform === 'win32') {
cmd = 'start cmd';
} else if (platform === 'linux') {
cmd = 'gnome-terminal';
} else if (platform === 'darwin') {
cmd = 'open -a Terminal';
}
exec(cmd, { cwd: repo_path });
});
ipcMain.handle('call-git', async (event, repo_path, ...args) => {
let options = {};
if (typeof args.at(-1) === 'object') {
options = args.at(-1);
args = args.slice(0, -1);
}
const run = async () => await log(
repo_path,
`call-git ${JSON.stringify(args)}`,
() => new Promise((resolve, reject) => {
const stdout = [], stderr = [];
const process = spawn('git', args, { cwd: repo_path });
process.stdout.setEncoding('utf8');
process.stdout.on('data', buffer => stdout.push(buffer));
process.stderr.setEncoding('utf8');
process.stderr.on('data', buffer => stderr.push(buffer));
process.on('close', code => {
if (code === 0) {
resolve(stdout.join(''));
} else {
reject(new Error([...stdout, ...stderr].join('')));
}
});
}),
options,
);
let retries = 3;
let delay = 100;
while (true) {
try {
return await run();
} catch (e) {
if (e.message.includes(`.git/index.lock': File exists`) && retries > 0) {
await new Promise(r => setTimeout(r, delay));
retries -= 1;
delay *= 2;
continue;
}
throw e;
}
}
});
ipcMain.handle('read-file', async (event, repo_path, file_path, { null_if_not_exists = false } = {}) => {
return await log(
repo_path,
`read-file ${file_path}`,
async () => {
try {
return await fs.promises.readFile(path.join(repo_path, file_path), { encoding: 'utf8' });
} catch (e) {
if (null_if_not_exists && e.code === 'ENOENT') {
return null;
}
throw e;
}
},
);
});
ipcMain.handle('write-file', async (event, repo_path, file_path, content, { make_directory = false } = {}) => {
return await log(
repo_path,
`write-file ${file_path}`,
async () => {
file_path = path.join(repo_path, file_path);
if (make_directory) {
try {
await fs.promises.mkdir(path.dirname(file_path));
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
}
await fs.promises.writeFile(file_path, content);
},
);
});
ipcMain.handle('delete-file', async (event, repo_path, file_path) => {
return await log(
repo_path,
`delete-file ${file_path}`,
() => fs.promises.unlink(path.join(repo_path, file_path)),
);
});
window.on('focus', () => window.webContents.send('window-focus'));
window.on('blur', () => window.webContents.send('window-blur'));
// https://stackoverflow.com/questions/32402327/how-can-i-force-external-links-from-browser-window-to-open-in-a-default-browser
window.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
await window.loadFile('index.html');
});