forked from kevinmkchin/Obsidian-GitHub-Sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
327 lines (284 loc) · 9.24 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import {
App,
Notice,
Plugin,
PluginSettingTab,
Setting,
} from 'obsidian';
import { simpleGit, SimpleGit, SimpleGitOptions } from 'simple-git';
import { setIntervalAsync} from 'set-interval-async';
import * as path from 'path';
let simpleGitOptions: Partial<SimpleGitOptions>;
let git: SimpleGit;
interface GHSyncSettings {
ghUsername: string;
ghPersonalAccessToken: string;
ghRepoUrl: string;
gitLocation: string;
syncInterval: number;
inactionSecondsIntervalToSync: number;
}
const DEFAULT_SETTINGS: GHSyncSettings = {
ghUsername: '',
ghPersonalAccessToken: '',
ghRepoUrl: '',
gitLocation: '',
syncInterval: 0,
inactionSecondsIntervalToSync: 0,
}
let lastUpdate = new Date();
let isInactionSync = false;
let changeCount = 0;
export default class GHSyncPlugin extends Plugin {
settings: GHSyncSettings;
async SyncNotes()
{
const USER = this.settings.ghUsername;
const PAT = this.settings.ghPersonalAccessToken;
const REPO = this.settings.ghRepoUrl;
const remote = `https://${USER}:${PAT}@${REPO}`;
simpleGitOptions = {
//@ts-ignore
baseDir: this.app.vault.adapter.getBasePath(),
binary: this.settings.gitLocation,
maxConcurrentProcesses: 6,
trimmed: false,
};
git = simpleGit(simpleGitOptions);
let os = require("os");
let hostname = os.hostname();
let statusResult = await git.status().catch((e) => {
new Notice("Vault is not a Git repo or git binary cannot be found.\nProblem: "+e, 10000);
return; })
//@ts-ignore
let clean = statusResult.isClean();
let date = new Date();
let msg = hostname + " " + date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + ":" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
if (!clean) {
try {
const repoRoot: string = (await git.revparse(['--show-toplevel'])).trim(); // Определить корень репозитория
const pluginDir: string = path.join(repoRoot, '.obsidian/plugins/*');
const repoWithoutObsidianData = path.join(repoRoot, '[!.obsidian]*')
const syncPlugin = path.join(repoRoot, '.obsidian', 'plugins', 'obsidian-github-auto-sync*')
const args = ['rm', '-f', '--cached', syncPlugin];
await git.add(repoWithoutObsidianData).add(pluginDir).raw(args).commit(msg);
} catch (e) {
new Notice(e);
return;
}
} else {
new Notice("Working branch clean");
}
// configure remote
try {
await git.removeRemote('origin').catch((e) => { new Notice(e); });
await git.addRemote('origin', remote).catch((e) => { new Notice(e); });
}
catch (e) {
new Notice(e);
return;
}
// check if remote url valid by fetching
try {
await git.fetch();
} catch (e) {
new Notice(e + "\nGitHub Sync: Invalid remote URL. Username, PAT, or Repo URL might be incorrect.", 10000);
return;
}
// git pull origin main
try {
//@ts-ignore
await git.pull('origin', 'main', { '--no-rebase': null }, (err, update) => {})
} catch (e) {
let conflictStatus = await git.status().catch((e) => { new Notice(e, 10000); return; });
let conflictMsg = "Merge conflicts in:";
//@ts-ignore
for (let c of conflictStatus.conflicted)
{
conflictMsg += "\n\t"+c;
}
conflictMsg += "\nResolve them or click sync button again to push with unresolved conflicts."
new Notice(conflictMsg)
//@ts-ignore
for (let c of conflictStatus.conflicted)
{
this.app.workspace.openLinkText("", c, true);
}
return;
}
// resolve merge conflicts
// git push origin main
if (!clean) {
try {
git.push('origin', 'main');
} catch (e) {
new Notice(e, 10000);
}
}
}
async watchChange(isInterval = false) {
await this.loadSettings();
const now = new Date();
const dateDiffMilliseconds = now.getTime() - lastUpdate.getTime()
lastUpdate = new Date();
if (dateDiffMilliseconds > this.settings.inactionSecondsIntervalToSync * 1000 && !isInactionSync && this.settings.inactionSecondsIntervalToSync > 0 && changeCount > 0) {
isInactionSync = true;
console.log('start sync')
try {
await this.SyncNotes()
console.log('stop sync')
new Notice("s");
} catch (e) {
console.log('error sync')
console.log(e)
new Notice('e')
}
isInactionSync = false;
changeCount = 0;
}
}
async bindFunction() {
changeCount++;
await this.watchChange()
}
async onload() {
await this.loadSettings();
lastUpdate = new Date()
this.app.workspace.on('editor-change', this.bindFunction.bind(this))
if (this.settings.inactionSecondsIntervalToSync) {
const inactionInterval: number = this.settings.inactionSecondsIntervalToSync;
if (inactionInterval >= 1) {
try {
setIntervalAsync(async () => {
await this.watchChange(true);
}, inactionInterval * 1000);
new Notice("Auto sync enabled");
} catch (e) { /* empty */ }
}
}
const ribbonIconEl = this.addRibbonIcon('github', 'Sync with Remote', (evt: MouseEvent) => {
this.SyncNotes();
});
ribbonIconEl.addClass('gh-sync-ribbon');
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new GHSyncSettingTab(this.app, this));
if (!isNaN(this.settings.syncInterval))
{
let interval: number = this.settings.syncInterval;
if (interval >= 1)
{
try {
setIntervalAsync(async () => {
await this.SyncNotes();
}, interval * 60 * 1000);
new Notice("Auto sync enabled");
} catch (e) {
}
}
}
// check status
try {
const USER = this.settings.ghUsername;
const PAT = this.settings.ghPersonalAccessToken;
const REPO = this.settings.ghRepoUrl;
const remote = `https://${USER}:${PAT}@${REPO}`;
simpleGitOptions = {
//@ts-ignore
baseDir: this.app.vault.adapter.getBasePath(),
binary: this.settings.gitLocation,
maxConcurrentProcesses: 6,
trimmed: false,
};
git = simpleGit(simpleGitOptions);
//check for remote changes
let branchresult = await git.branch();
let currentbranchname = branchresult.current;
// git branch --set-upstream-to=origin/main main
await git.branch({'--set-upstream-to': 'origin/'+currentbranchname});
let statusUponOpening = await git.fetch().status();
if (statusUponOpening.behind > 0)
{
new Notice("GitHub Sync: " + statusUponOpening.behind + " commits behind remote branch.\nClick the GitHub ribbon icon to sync.")
}
} catch (e) {
// don't care
}
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class GHSyncSettingTab extends PluginSettingTab {
plugin: GHSyncPlugin;
constructor(app: App, plugin: GHSyncPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('GitHub username')
.setDesc('')
.addText(text => text
.setPlaceholder('')
.setValue(this.plugin.settings.ghUsername)
.onChange(async (value) => {
this.plugin.settings.ghUsername = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('GitHub personal access token')
.setDesc('')
.addText(text => text
.setPlaceholder('ghp_XXXXXXXXXXXXXXXXXXXXXXXX')
.setValue(this.plugin.settings.ghPersonalAccessToken)
.onChange(async (value) => {
this.plugin.settings.ghPersonalAccessToken = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('GitHub repo URL for this vault')
.setDesc('In this format: "github.com/username/repo"')
.addText(text => text
.setPlaceholder('')
.setValue(this.plugin.settings.ghRepoUrl)
.onChange(async (value) => {
this.plugin.settings.ghRepoUrl = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('git binary location (optional)')
.setDesc('If git is not findable via your system PATH, then provide its directory here')
.addText(text => text
.setPlaceholder('')
.setValue(this.plugin.settings.gitLocation)
.onChange(async (value) => {
this.plugin.settings.gitLocation = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Auto sync at interval (optional)')
.setDesc('Set a positive integer seconds interval after which your vault is synced automatically. Auto sync is disabled if this field is left empty or not a positive integer. Restart Obsidan to take effect.')
.addText(text => text
.setValue(String(this.plugin.settings.syncInterval))
.onChange(async (value) => {
this.plugin.settings.syncInterval = Number(value);
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Auto sync at interval on inaction (optional)')
.setDesc('Set a positive integer seconds interval inaction after which your vault is synced automatically. Auto sync is disabled if this field is left empty or not a positive integer. Restart Obsidan to take effect.')
.addText(text => text
.setValue(String(this.plugin.settings.inactionSecondsIntervalToSync))
.onChange(async (value) => {
this.plugin.settings.inactionSecondsIntervalToSync = Number(value);
await this.plugin.saveSettings();
}));
}
}