-
Notifications
You must be signed in to change notification settings - Fork 1
/
GHForPG.js
executable file
·1798 lines (1653 loc) · 78.9 KB
/
GHForPG.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$(function () {
$('body').one('pinegrow-ready', function (e, pinegrow) {
//Add a framework id, it should be unique to this framework and version. Best practice is to define the prefix as a variable that can be used throughout the framework.
let framework_id = 'shd_github_for_pinegrow';
//Instantiate a new framework
var framework = new PgFramework(framework_id, 'GitHub-for-Pinegrow');
// Define a framework type - if you plan on having multiple versions, this should be the same for each version.
framework.type = 'GitHub-for-Pinegrow';
//Prevent the activation of multiple versions of the framework - if this should be allowed, change to false
framework.allow_single_type = true;
//Optional, add a badge to the framework list notify user of new or updated status
//framework.info_badge = 'v1.0.0';
//Add a description of the plugin
framework.description = 'Adds GitHub functionality to Pinegrow';
//Add a framework author to be displayed with the framework templates
framework.author = 'Robert "Bo" Means';
//Add a website "https://pinegrow.com" or mailto "mailto:[email protected]" link for redirect on author name click
framework.author_link = 'https://robertmeans.net';
// Tell Pinegrow about the framework
pinegrow.addFramework(framework);
//uncomment the line below for debugging - opens devtools on Pinegrow Launch
//require('nw.gui').Window.get().showDevTools();
//Establish the base directory for node modules
const frameBase = framework.getBaseUrl();
//Load in the Octokit module
const {
Octokit
} = require(crsaMakeFileFromUrl(frameBase + '/node_modules/@octokit/rest/dist-node/index.js'));
//Load in Git functions from the isomorphic-git library
const Git = require(crsaMakeFileFromUrl(frameBase + '/node_modules/isomorphic-git/index.cjs'));
const http = require(crsaMakeFileFromUrl(frameBase + '/node_modules/isomorphic-git/http/node/index.cjs'));
//Load in glob for easier file handling
const glob = require(crsaMakeFileFromUrl(frameBase + '/node_modules/fast-glob/out/index.js'));
//Add in better folder selector
const openFolderExplorer = require(crsaMakeFileFromUrl(frameBase + '/node_modules/nw-programmatic-folder-select/index.js'));
//load in file management packages
const Path = require('path');
const fse = require('fs-extra');
//Function to poulate settings with existing values, clear settings, save new settings.
let ghManipulateSettingsFields = () => {
//First, let's get all of the form fields and buttons
let userNameField = ghById('gh-user-name');
let emailField = ghById('gh-user-email');
let accountTokenField = ghById('gh-token');
let retrieveSettingsButton = ghById('gh-retrieve-settings');
let clearSettingsButton = ghById('gh-clear-settings');
let saveSettingsButton = ghById('gh-save-settings');
let cancelSettingsButton = ghById('gh-cancel-settings');
let userErrorMessage = ghById('gh-username-error');
let emailErrorMessage = ghById('gh-email-error');
let tokenErrorMessage = ghById('gh-token-error');
let credentialsErrorMessage = ghById('gh-git-config-missing');
let projectNotOpenError = ghById('gh-settings-project-error');
let credentialsNotificationMessage = ghById('gh-settings-retrieved-notification');
let credentialsMessage = ghById('gh-correct-credentials');
let configNotification = ghById('gh-settings-config-notification');
let showToken = ghById('gh-show-token');
//check if the user has already stored any credentials in local storage, if so add them to the form
if (localStorage.getItem('gh-settings-user-name')) {
userNameField.value = localStorage.getItem('gh-settings-user-name');
emailField.value = localStorage.getItem('gh-settings-email');
accountTokenField.value = localStorage.getItem('gh-settings-token');
}
//Allow toggle of the token field between plain text and encoded
showToken.addEventListener('click', () => {
accountTokenField.type = showToken.checked ? "text" : "password";
});
//allow user to retrieve settings from gitconfig file
retrieveSettingsButton.addEventListener('click', async () => {
//Throw error if project isn't open
if (!pinegrow.getCurrentProject()) {
projectNotOpenError.style.visibility = 'visible';
return;
}
let projectDirectory = ghProjectDirectory();
//Get gitconfig file
let ghCredentials = await ghFetchGitConfig(projectDirectory);
//Throw error if file doesn't exist
if (ghCredentials === false || ghCredentials === undefined) {
credentialsErrorMessage.style.visibility = 'visible';
return;
}
if (ghCredentials.userName === undefined || ghCredentials.userToken === undefined) {
credentialsErrorMessage.style.visibility = 'visible';
localStorage.setItem('gh-config-file-error', true);
return;
}
//Set form values to retrieved credentials
credentialsNotificationMessage.style.visibility = 'visible';
userNameField.value = ghCredentials.userName;
accountTokenField.value = ghCredentials.userToken;
});
clearSettingsButton.addEventListener('click', () => {
localStorage.removeItem('gh-settings-user-name');
localStorage.removeItem('gh-settings-email');
localStorage.removeItem('gh-settings-token');
localStorage.removeItem('gh-config-file-error');
userNameField.value = '';
emailField.value = '';
accountTokenField.value = '';
accountTokenField.type = "password";
showToken.checked = false;
saveSettingsButton.className = 'btn btn-primary';
userErrorMessage.style.visibility = 'hidden';
emailErrorMessage.style.visibility = 'hidden';
tokenErrorMessage.style.visibility = 'hidden';
credentialsErrorMessage.style.visibility = 'hidden';
projectNotOpenError.style.visibility = 'hidden';
credentialsNotificationMessage.style.visibility = 'hidden';
credentialsMessage.style.visibility = 'hidden';
if (pinegrow.getCurrentProject()) {
let projectDirectory = ghProjectDirectory();
ghDeleteGitConfig(projectDirectory);
}
});
saveSettingsButton.addEventListener('click', async () => {
localStorage.setItem('gh-settings-user-name', userNameField.value);
localStorage.setItem('gh-settings-email', emailField.value);
localStorage.setItem('gh-settings-token', accountTokenField.value);
if (emailField.value === '' || emailField.value === null) {
emailErrorMessage.style.visibility = 'visible';
return;
}
let errorCheck = await ghVerifyGitHubAccount();
if (true === errorCheck) {
saveSettingsButton.className = 'btn btn-success';
userErrorMessage.style.visibility = 'hidden';
emailErrorMessage.style.visibility = 'hidden';
tokenErrorMessage.style.visibility = 'hidden';
credentialsErrorMessage.style.visibility = 'hidden';
projectNotOpenError.style.visibility = 'hidden';
credentialsNotificationMessage.style.visibility = 'hidden';
credentialsMessage.style.visibility = 'visible';
accountTokenField.type = "password";
if (pinegrow.getCurrentProject()) {
let projectDirectory = ghProjectDirectory();
if (localStorage.getItem('gh-config-file-error')) {
configNotification.style.visibility = 'visible';
localStorage.removeItem('gh-config-file-error');
ghWriteGitConfig(projectDirectory);
}
}
} else if (-1 === errorCheck) {
userErrorMessage.style.visibility = 'visible';
localStorage.removeItem('gh-settings-user-name');
credentialsMessage.style.visibility = 'hidden';
emailErrorMessage.style.visibility = 'hidden';
tokenErrorMessage.style.visibility = 'hidden';
credentialsNotificationMessage.style.visibility = 'hidden';
} else {
tokenErrorMessage.style.visibility = 'visible';
localStorage.removeItem('gh-settings-token');
credentialsMessage.style.visibility = 'hidden';
userErrorMessage.style.visibility = 'hidden';
emailErrorMessage.style.visibility = 'hidden';
credentialsNotificationMessage.style.visibility = 'hidden';
}
});
cancelSettingsButton.addEventListener('click', () => {
saveSettingsButton.className = 'btn btn-primary';
userErrorMessage.style.visibility = 'hidden';
tokenErrorMessage.style.visibility = 'hidden';
credentialsMessage.style.visibility = 'hidden';
projectNotOpenError.style.visibility = 'hidden';
credentialsNotificationMessage.style.visibility = 'hidden'
accountTokenField.type = "password";
showToken.checked = false;
})
};
//Function to gather new repo information.
let ghManipulateCreateFields = async () => {
let createModal = ghById('gh-create-modal');
let closeButton = ghById('gh-create-close-button');
let repoNameField = ghById('gh-new-repo-name');
let useExistingControl = ghById('gh-use-existing-folder');
let repoDescription = ghById('gh-repo-description');
let repoCommitMessage = ghById('gh-create-commit-message');
let repoCommitMessageGroup = ghById('gh-create-commit-message-group');
let repoLicense = ghById('gh-repo-license');
let repoPrivate = ghById('gh-repo-private');
let repoInitialize = ghById('gh-auto-init');
let repoInitializeGroup = ghById('gh-auto-initialize-group');
let repoNameError = ghById('gh-repo-name-error');
let newFolderGroup = ghById('gh-create-new-folder-group');
let folderButton = ghById('gh-get-new-save-folder');
let folderPath = ghById('gh-new-save-location');
let folderNameGroup = ghById('gh-new-folder-name-group');
let folderName = ghById('gh-new-folder-name');
let useExisting = false;
let correctCredentials = ghById('gh-create-correct-credentials');
let incorrectCredentials = ghById('gh-create-incorrect-credentials');
let createMessage = ghById('gh-create-message-box');
let createNewRepo = ghById('gh-create-repo-button');
let createResetButton = ghById('gh-create-reset');
let createPathError = ghById('gh-create-path-error');
let createLicenseError = ghById('gh-license-error');
let newFolderNameError = ghById('gh-create-folder-name-error');
createMessage.innerHTML = '<p>No message at this time</p>';
useExistingControl.addEventListener('click', () => {
if (pinegrow.getCurrentProject()) {
if (useExistingControl.checked) {
newFolderGroup.style.display = 'none';
folderNameGroup.style.display = 'none';
repoCommitMessageGroup.style.display = 'block';
repoInitializeGroup.style.display = 'none';
useExisting = true;
let currentProject = pinegrow.getCurrentProject();
let sanitizedName = ghSanitizeRepoName(currentProject.name)
repoNameField.value = sanitizedName;
} else {
newFolderGroup.style.display = 'block';
folderNameGroup.style.display = 'block';
repoCommitMessageGroup.style.display = 'none';
repoInitializeGroup.style.display = 'block';
useExisting = false;
repoNameField.value = '';
}
} else {
createMessage.innerHTML = '<p>You must have a project open to use this option.</p>';
useExistingControl.checked = false;
}
});
repoNameField.addEventListener('input', () => {
if (!useExistingControl.checked) {
folderName.value = repoNameField.value;
}
});
folderButton.addEventListener('click', () => {
openFolderExplorer(window, (selection) => {
folderPath.innerHTML = selection;
});
});
createResetButton.addEventListener('click', () => {
folderPath.innerHTML = '';
createModal.querySelectorAll('.gh-error').forEach(el => {
el.style.display = 'none';
});
createModal.querySelector('.gh-logged-in').style.display = 'none';
createMessage.innerHTML = '<p>No message at this time</p>';
createNewRepo.disabled = false;
})
createNewRepo.addEventListener('click', async () => {
let errorCheck = await ghVerifyGitHubAccount();
if (!errorCheck) {
createMessage.innerHTML = '<p>Please check your credentials.</p>';
incorrectCredentials.style.display = "block";
return;
} else {
correctCredentials.style.display = "block";
}
if (repoNameField.value === '' || repoNameField.value === undefined) {
createMessage.innerHTML = '<p>Please add a repo name.</p>';
repoNameError.style.display = 'block';
return;
}
if (repoLicense.value === '') {
createMessage.innerHTML = '<p>Please select a license.</p>';
createLicenseError.style.display = 'block';
return;
}
if (folderPath.innerHTML === '' && !useExisting) {
createMessage.innerHTML = '<p>Please add a path to save your local repo.</p>';
createPathError.style.display = 'block';
return;
}
if ((folderName.value === '' || folderName.value === undefined) && !useExisting) {
createMessage.innerHTML = '<p>Please add a name for your local repo folder.</p>';
newFolderNameError.style.display = 'block';
return;
}
createMessage.innerHTML = "";
let repoArgs = {
"name": repoNameField.value
};
repoArgs['description'] = repoDescription.value;
repoArgs['license_template'] = repoLicense.value;
if (repoPrivate.checked) {
repoArgs['private'] = true;
}
if (repoInitialize.checked) {
repoArgs['auto_init'] = true;
}
let repoCreated = await ghCreateRepo(repoArgs);
ghStatusUpdate(repoCreated.status, createMessage, 'New Repo created.');
if (!useExisting && repoCreated.status == "201") {
let owner = localStorage.getItem('gh-settings-user-name');
let newFolder = folderName.value;
let dir = Path.join(folderPath.innerHTML, newFolder);
let repo = "https://github.com/" + owner + "/" + repoNameField.value;
const onAuth = () => ({
username: localStorage.getItem('gh-settings-user-name'),
password: localStorage.getItem('gh-settings-token')
});
await ghClone(onAuth, repo, dir, createMessage, '');
let content = '_pgbackup';
let ignoreFile = Path.join(dir, '.gitignore');
try {
fse.writeFileSync(ignoreFile, content);
} catch (err) {
console.error(err);
}
let projectData = {
repo: repoNameField.value,
owner: owner,
branch: 'main'
};
ghCreateJsonFile(projectData, dir, 'githubinfo.json');
ghWriteGitConfig(dir);
} else if (useExisting && repoCreated.status == "201") {
let owner = localStorage.getItem('gh-settings-user-name');
let projectDirectory = ghProjectDirectory();
await Git.init({
fs: fse,
dir: projectDirectory,
defaultBranch: 'main'
});
let projectData = {
repo: repoNameField.value,
owner: owner,
branch: 'main'
};
let commitMessage = (repoCommitMessage.value) ? repoCommitMessage.value : undefined;
ghCreateJsonFile(projectData, projectDirectory, 'githubinfo.json');
let remoteUrl = 'https://github.com/' + owner + '/' + repoNameField.value;
let newAccountConfigValues = `[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = ${remoteUrl}
[branch "main"]
merge = refs/heads/main
remote = origin`
await ghWriteConfig(newAccountConfigValues, projectDirectory);
await ghWriteGitConfig(projectDirectory);
let uploadStatus = await ghUploadToRepoNew(projectDirectory, projectData, 'main', commitMessage);
ghStatusUpdate(uploadStatus, createMessage, 'Files uploaded');
}
createNewRepo.disabled = true;
});
closeButton.addEventListener('click', () => {
createResetButton.click();
})
};
//Function to gather existing repo information.
let ghManipulateCloneFields = async () => {
let repoOwner = ghById('gh-existing-repo-owner');
let repoName = ghById('gh-existing-repo-name');
let branchName = ghById('gh-clone-branch-name');
let folderButton = ghById('gh-get-save-folder');
let saveLocation = ghById('gh-save-location');
let folderName = ghById('gh-clone-folder-name');
let folderVerification = ghById('gh-clone-verification');
let folderOkayButton = ghById('gh-clone-folder-okay');
let folderCancelButton = ghById('gh-clone-folder-cancel');
let clearButton = ghById('gh-clone-clear');
let cloneButton = ghById('gh-get-existing-repo-button');
let loginError = ghById('gh-clone-log-error');
let logCheck = await ghVerifyGitHubAccount();
if (logCheck !== true) {
loginError.style.visibility = 'visible';
} else {
loginError.style.visibility = 'hidden';
}
let cloneMessage = ghById('gh-clone-message-box');
cloneMessage.innerHTML = '<p>No message at this time</p>';
folderButton.addEventListener('click', () => {
openFolderExplorer(window, (selection) => {
saveLocation.innerHTML = selection;
});
});
//Redo error checking?
cloneButton.addEventListener('click', async () => {
if (logCheck === true && folderName.value && saveLocation.innerHTML != '' && repoOwner.value && repoName.value) {
let cloneBranch = (branchName.value) ? branchName.value : '';
cloneMessage.innerHTML = "";
let newFolder = folderName.value;
let dir = Path.join(saveLocation.innerHTML, newFolder);
let dirCheck = fse.existsSync(dir);
if (dirCheck) {
folderVerification.classList.add('visible');
cloneMessage.innerHTML = "<p>Please verify existing folder overwrite.</p>";
} else {
let url = "https://github.com/" + repoOwner.value + "/" + repoName.value + '.git';
const onAuth = () => ({
username: localStorage.getItem('gh-settings-user-name'),
password: localStorage.getItem('gh-settings-token')
});
let cloneRepo = await ghClone(onAuth, url, dir, cloneMessage, cloneBranch);
if (cloneRepo) {
let successMessage = document.createElement('p');
successMessage.innerHTML = 'Repo successfully cloned.';
cloneMessage.appendChild(successMessage);
let projectData = {
repo: repoName.value,
owner: owner,
branch: 'main'
};
ghCreateJsonFile(projectData, dir, 'githubinfo.json');
ghWriteGitConfig(dir);
let content = '_pgbackup';
let ignoreFile = Path.join(dir, '.gitignore');
try {
const gitIgnore = fse.writeFileSync(ignoreFile, content);
} catch (err) {
console.error(err);
}
}
}
} else {
cloneMessage.innerHTML = '<p style="color: red;">Check that your credentials are valid and you have filled out all of the fields.</p>';
}
});
folderOkayButton.addEventListener('click', async () => {
cloneMessage.innerHTML = '';
let newFolder = folderName.value
let dir = Path.join(saveLocation.innerHTML, newFolder);
let cloneBranch = (branchName.value) ? branchName.value : '';
let url = "https://github.com/" + repoOwner.value + "/" + repoName.value + '.git';
const onAuth = () => ({
username: localStorage.getItem('gh-settings-user-name'),
password: localStorage.getItem('gh-settings-token')
});
await ghClone(onAuth, url, dir, cloneMessage, cloneBranch);
if (cloneRepo) {
let successMessage = document.createElement('p');
successMessage.innerHTML = 'Repo successfully cloned.';
cloneMessage.appendChild(successMessage);
let projectData = {
repo: repoName.value,
owner: owner,
branch: 'main'
};
ghCreateJsonFile(projectData, dir, 'githubinfo.json');
ghWriteGitConfig(dir);
let ignoreFile = Path.join(dir, '.gitignore');
try {
const gitIgnore = fse.writeFileSync(ignoreFile, content);
} catch (err) {
console.error(err);
}
}
});
folderCancelButton.addEventListener('click', () => {
folderVerification.classList.remove('visible');
cloneMessage.innerHTML = "";
});
clearButton.addEventListener('click', () => {
repoOwner.value = '';
repoName.value = '';
saveLocation.innerHTML = '';
folderName.value = '';
cloneMessage.innerHTML = '';
if (folderVerification.classList.contains('visible')) folderVerification.classList.remove('visible')
});
};
//Function to gather branch info
let ghManipulateBranchFields = async () => {
let branchRepoOwner = ghById('gh-branch-repo-owner');
let branchRepoName = ghById('gh-branch-repo-name');
let branchBranchName = ghById('gh-branch-branch-name');
let branchNewName = ghById('gh-branch-new-name');
let branchFolderButton = ghById('gh-branch-get-save-folder');
let branchFolderPath = ghById('gh-branch-save-location');
let branchFolderName = ghById('gh-branch-folder-name');
let branchVerification = ghById('gh-branch-verification');
let branchOkay = ghById('gh-branch-folder-okay');
let branchCancel = ghById('gh-branch-folder-cancel');
let branchMessage = ghById('gh-branch-message-box');
let branchSubmit = ghById('gh-branch-submit');
let branchReset = ghById('gh-branch-reset-button');
let branchClose = ghById('gh-branch-close');
let correctCredentials = ghById('gh-branch-correct-credentials');
let incorrectCredentials = ghById('gh-branch-incorrect-credentials');
branchMessage.innerHTML = '<p>No message at this time.</p>';
let errorCheck = await ghVerifyGitHubAccount();
if (errorCheck) {
correctCredentials.style.display = 'block';
incorrectCredentials.style.display = 'none';
} else {
correctCredentials.style.display = 'none';
incorrectCredentials.style.display = 'block';
}
let octokit = await ghCreateOctokitInstance();
branchNewName.addEventListener('input', () => branchFolderName.value = branchNewName.value);
branchFolderButton.addEventListener('click', () => {
openFolderExplorer(window, (selection) => {
branchFolderPath.innerHTML = selection;
});
});
branchReset.addEventListener('click', () => {
branchFolderPath.innerHTML = '';
branchMessage.innerHTML = '';
if (branchVerification.classList.contains('visible')) branchVerification.classList.remove('visible');
});
branchClose.addEventListener('click', () => branchReset.click());
branchSubmit.addEventListener('click', async () => {
if (errorCheck && branchRepoOwner.value && branchRepoName.value && branchNewName.value && (branchFolderPath.innerHTML != '' || branchFolderPath.innerHTML != undefined) && branchFolderName.value) {
let branchBranch = (branchBranchName.value) ? branchBranchName.value : '';
branchMessage.innerHTML = '';
let newFolder = branchFolderName.value;
let dir = Path.join(branchFolderPath.innerHTML, newFolder);
let dirCheck = fse.existsSync(dir);
if (dirCheck) {
branchVerification.classList.add('visible');
branchMessage.innerHTML('<p>Please verify existing folder overwrite.</p>');
} else {
let cloneAndBranch = await ghCloneAndBranch(dir, branchMessage, branchBranch);
}
} else {
cloneMessage.innerHTML = '<p style="color: red;">Check that your credentials are valid and you have filled out all of the fields.</p>';
}
});
branchOkay.addEventListener('click', async () => {
let branchBranch = (branchBranchName.value) ? branchBranchName.value : '';
branchMessage.innerHTML = '';
let newFolder = branchFolderName.value;
let dir = Path.join(branchFolderPath.innerHTML, newFolder);
let cloneAndBranch = await ghCloneAndBranch(dir, branchMessage, branchBranch);
});
branchCancel.addEventListener('click', function () {
branchVerification.classList.remove('visible');
branchMessage.innerHTML = "";
});
let ghCloneAndBranch = async (dir, branchMessage, branchBranch) => {
let url = "https://github.com/" + branchRepoOwner.value + "/" + branchRepoName.value + '.git';
const onAuth = () => ({
username: localStorage.getItem('gh-settings-user-name'),
password: localStorage.getItem('gh-settings-token')
});
let baseRepoCreate = await ghClone(onAuth, url, dir, branchMessage, branchBranch);
if (baseRepoCreate) {
let successMessage = document.createElement('p');
successMessage.innerHTML = 'Repo successfully cloned.';
branchMessage.appendChild(successMessage);
let currentBranch = (branchBranchName.value === '' || branchBranchName.value === undefined) ? 'main' : branchBranchName.value;
let args = {
octokit: octokit,
owner: branchRepoOwner.value,
repo: branchRepoName.value,
currentBranch,
newBranch: branchNewName.value
}
let currentSha = await ghGetCurrentCommit(args);
let createBranch = await ghCreateRef(args, currentSha.commitSha);
branchMessage.innerHTML = '<p>Branch created and reference updated.</p>';
let projectData = {
repo: args.repo,
owner: args.owner,
branch: args.newBranch
}
ghCreateJsonFile(projectData, dir, 'githubinfo.json');
ghWriteGitConfig(dir);
}
}
}
let ghManipulateForkFields = async () => {
let closeButton = ghById('gh-fork-close');
let forkOwner = ghById('gh-fork-repo-owner');
let forkNameField = ghById('gh-fork-repo-name');
let forkSaveFolderButton = ghById('gh-fork-get-save-folder');
let forkSaveLocation = ghById('gh-fork-save-location');
let forkNewFolderName = ghById('gh-fork-folder-name');
let forkFolderVerification = ghById('gh-fork-verification')
let forkOkayButton = ghById('gh-fork-folder-okay');
let forkReset = ghById('gh-fork-reset-button');
let forkButton = ghById('gh-fork-button');
let loginError = ghById('gh-fork-log-error');
let forkMessage = ghById('gh-fork-message-box');
let mainOwner = '';
let logCheck = await ghVerifyGitHubAccount();
if (logCheck !== true) {
loginError.style.visibility = 'visible';
} else {
loginError.style.visibility = 'hidden';
mainOwner = localStorage.getItem('gh-settings-user-name')
}
forkMessage.innerHTML = '<p>No message at this time</p>';
forkSaveFolderButton.addEventListener('click', () => {
openFolderExplorer(window, (selection) => {
forkSaveLocation.innerHTML = selection;
});
});
forkNameField.addEventListener('input', () => forkNewFolderName.value = forkNameField.value);
forkReset.addEventListener('click', () => {
forkMessage.innerHTML = '<p>No message at this time</p>';
});
closeButton.addEventListener('click', () => {
forkReset.click();
});
forkButton.addEventListener('click', async () => {
if (logCheck !== true) return;
if (forkOwner.value === '' || forkNameField === '') return;
let octokit = await ghCreateOctokitInstance();
let newFork = await octokit.rest.repos.createFork({
owner: forkOwner.value,
repo: forkNameField.value
});
ghStatusUpdate(newFork.status, forkMessage, 'Repo forked - creating local clone.');
let dir = Path.join(forkSaveLocation.innerHTML, forkNewFolderName);
let dirCheck = fse.existsSync(dir);
if (dirCheck) {
forkFolderVerification.classList.add('visible');
cloneMessage.innerHTML = "<p>Please verify existing folder overwrite.</p>";
} else {
let url = "https://github.com/" + mainOwner + "/" + forkNameField.value + '.git';
const onAuth = () => ({
username: mainOwner,
password: localStorage.getItem('gh-settings-token')
});
let forkRepo = await ghClone(onAuth, url, dir, forkMessage, '');
if (forkRepo) {
let successMessage = document.createElement('p');
successMessage.innerHTML = 'Local copy created';
forkMessage.appendChild(successMessage);
let projectData = {
repo: forkNameField.value,
owner: mainOwner,
branch: 'main'
};
ghCreateJsonFile(projectData, dir, 'githubinfo.json');
ghWriteGitConfig(dir);
let content = '_pgbackup';
let ignoreFile = Path.join(dir, '.gitignore');
try {
const gitIgnore = fse.writeFileSync(ignoreFile, content);
} catch (err) {
console.error(err);
}
}
}
forkOkayButton.addEventListener('click', async () => {
cloneMessage.innerHTML = '';
let forkDir = Path.join(forkSaveLocation.innerHTML, forkNewFolderName);
let url = "https://github.com/" + mainOwner + "/" + forkNameField.value + '.git';
const onAuth = () => ({
username: mainOwner,
password: localStorage.getItem('gh-settings-token')
});
let forkRepo = await ghClone(onAuth, url, forkDir, forkMessage, '');
if (forkRepo) {
let successMessage = document.createElement('p');
successMessage.innerHTML = 'Local copy created';
forkMessage.appendChild(successMessage);
let projectData = {
repo: forkNameField.value,
owner: mainOwner,
branch: 'main'
};
ghCreateJsonFile(projectData, forkDir, 'githubinfo.json');
ghWriteGitConfig(forkDir);
let content = '_pgbackup';
let ignoreFile = Path.join(forkDir, '.gitignore');
try {
const gitIgnore = fse.writeFileSync(ignoreFile, content);
} catch (err) {
console.error(err);
}
}
});
})
};
//Function to gather staging and commit information.
let ghManipulateCommitFields = () => {
let projectDirectory = ghProjectDirectory();
let gitStatus = ghById('gh-commit-git-status-box');
let statusButton = ghById('gh-status-button');
let commitMessageBox = ghById('gh-commit-message-box');
let directoryHead = ghById('ghProjectTree');
let directoryFolders = directoryHead.querySelectorAll('[data-gh-type="folder"]');
directoryFolders.forEach(folder => {
let folderIcon = folder.querySelector('i');
folderIcon.addEventListener('click', function (evt) {
folderIcon.classList.contains('icon-right') ? folderIcon.classList.replace('icon-right', 'icon-down') : folderIcon.classList.replace('icon-down', 'icon-right');
let fileList = folder.querySelector('ul');
fileList.classList.contains('gh-hidden') ? fileList.classList.replace('gh-hidden', 'gh-visible') : fileList.classList.replace('gh-visible', 'gh-hidden');
})
let folderInput = folder.querySelector('input');
folderInput.addEventListener('click', (evt) => {
let fileList = folder.querySelector('ul');
let fileInputs = fileList.querySelectorAll('li > input');
let checkStatus = folderInput.checked;
fileInputs.forEach(input => {
input.checked = checkStatus ? true : false;
});
});
});
let messageError = ghById('gh-commit-message-error');
let emailError = ghById('gh-commit-email-error');
let credentialsError = ghById('gh-commit-credentials-error');
let commitMessage = ghById('gh-commit-message');
let authorEmail = ghById('gh-commit-email');
let unstageButton = ghById('gh-unstage-button');
let stageButton = ghById('gh-stage-button');
let commitButton = ghById('gh-commit-button');
let pushButton = ghById('gh-push-button');
let currentCommitStatus = localStorage.getItem('gh-commited');
if (currentCommitStatus === true) {
commitButton.disabled = false;
commitMessage.disabled = false;
authorEmail.disabled = false;
}
statusButton.addEventListener('click', async () => {
let stagedFiles = await ghStagedFiles();
gitStatus.innerHTML = '<p>Currently Staged Files:</p>' + stagedFiles;
});
stageButton.addEventListener('click', async () => {
let filesToStage = ghGetFiles(directoryHead);
let stageFiles = await ghStageFiles(filesToStage);
if (stageFiles) {
let stagedFiles = await ghStagedFiles();
gitStatus.innerHTML = '<p>Currently Staged Files:</p>' + stagedFiles;
localStorage.setItem('gh-commited', true);
commitButton.disabled = false;
commitMessage.disabled = false;
authorEmail.disabled = false;
}
});
unstageButton.addEventListener('click', async () => {
let filesToUnstage = ghGetFiles(directoryHead);
let unstageFiles = await ghUnstageFiles(filesToUnstage);
if (unstageFiles) {
let stagedFiles = await ghStagedFiles();
gitStatus.innerHTML = '<p>Currently Staged Files:</p>' + stagedFiles;
}
});
commitButton.addEventListener('click', async () => {
let projectDirectory = ghProjectDirectory();
if (commitMessage.value === '') {
messageError.style.display = "block";
return;
}
let errorCheck = await ghVerifyGitHubAccount();
if (!errorCheck) {
credentialsError.style.display = "block";
return;
}
if (authorEmail.value === '') {
emailError.style.display = "block";
return;
}
let sha = await Git.commit({
fs: fse,
dir: projectDirectory,
author: {
name: localStorage.getItem('gh-settings-user-name'),
email: authorEmail.value
},
message: commitMessage.value
});
if (sha) {
let content = {
"committed": true
};
let filename = "githubinfo.json";
let appendCommit = ghAppendJsonFile(content, projectDirectory, filename);
}
commitMessageBox.innerHTML = "<p>Files committed by " + localStorage.getItem('gh-settings-user-name') + " as SHA " + sha + "</p>";
});
pushButton.addEventListener('click', async () => {
let projectDirectory = ghProjectDirectory();
let errorCheck = await ghVerifyGitHubAccount();
if (!errorCheck) {
credentialsError.classList = 'gh-visible gh-error';
return;
}
let jsonData = ghReadJsonFile(projectDirectory, 'githubinfo.json');
if (!jsonData.committed) {
commitMessageBox.innerHTML = "<p>No files committed. Please make a commit and try again.</p>";
return;
}
const onAuth = () => ({
username: localStorage.getItem('gh-settings-user-name'),
password: localStorage.getItem('gh-settings-token')
});
let pushRequest = await Git.push({
fs: fse,
http,
dir: projectDirectory,
onAuth,
author: {
name: localStorage.getItem('gh-settings-user-name')
}
});
let content = {
"committed": false
};
ghAppendJsonFile(content, projectDirectory, 'githubinfo.json');
});
let cancelButton = ghById('gh-commit-cancel');
let closeButton = ghById('gh-commit-x');
let resetModal = () => {
let commitDynamicContainer = ghById('gh-commit-dynamic-container');
if (commitDynamicContainer) commitDynamicContainer.remove();
messageError.style.display = "none";
credentialsError.style.display = "none";
emailError.style.display = "none";
gitStatus.innerHTML = '';
commitMessage.value = '';
authorEmail.value = '';
};
[cancelButton, closeButton].forEach(button => {
button.addEventListener('click', resetModal);
});
cancelButton.addEventListener('click', () => {
closeButton.removeEventListener('click', resetModal);
});
closeButton.addEventListener('click', () => {
cancelButton.removeEventListener('click', resetModal);
});
};
let ghManipulatePullFields = () => {
let projectDirectory = ghProjectDirectory();
let messageArea = ghById('gh-pull-message-box');
let pullButton = ghById('gh-pull-button');
let closeX = ghById('gh-pull-x');
let cancelButton = ghById('gh-pull-cancel');
let pullIt = () => {
return Git.pull({
fs: fse,
http,
dir: projectDirectory,
singleBranch: true
})
.then(() => messageArea.innerHTML = ('Pull successful'))
.catch(err => {
console.error(err);
});
};
pullButton.addEventListener('click', pullIt);
closeX.addEventListener('click', () => {
cancelButton.click();
});
cancelButton.addEventListener('click', () => {
messageArea.innerHTML = "";
})
}
//Function to add all the initial field listeners to each modal
let ghAddFieldsListeners = () => {
ghManipulateSettingsFields();
ghManipulateCreateFields();
ghManipulateCloneFields();
ghManipulateBranchFields();
ghManipulateForkFields();
}
//Function to add the click listeners to the initial menu items
let ghAddModalListener = ({
targetId,
modalName
}) => {
//Adds the click listener to the settings menu item
let modalItem = ghById(targetId);
let modalId = '#gh-' + modalName + '-modal';
modalItem.addEventListener('click', () => $(modalId).modal('show'));
};
let ghGetFileAsBASE64 = (filePath) => fse.readFile(filePath, 'base64');
let ghSetBranchToCommit = ({
octokit,
owner,
repo,
currentBranch
}, commitSha) => octokit.git.updateRef({
owner,
repo,
ref: `heads/${currentBranch}`,
sha: commitSha
});
//HTML for the main menu
let $menu = $(`
<li id="github-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><span>GitHub</span></a>
<ul class="dropdown-menu" id="gh-dropdown">
<li><a href="#" id="gh-create-repo">Create New Repo</a></li>
<li><a href="#" id="gh-clone-repo">Clone Existing Repo</a></li>
<li><a href="#" id="gh-branch-repo">Branch Existing Repo</a></li>
<li><a href="#" id="gh-fork-repo">Fork Existing Repo</a></li>
<hr id="ruler-one">
<li><a href="#" id="gh-settings">Settings...</a></li>
</ul>
</li>
`);
//Adds the main GitHub menu to Pinegrow upon open
pinegrow.addPluginControlToTopbar(framework, $menu, true, function () {
ghAddStyling();
ghAddTheModals();
});
// Check if we are opening another project in a new window
if (pinegrow.getCurrentProject()) {
addToGHMenu();
}
//Adds project specific GitHub menu items
//Replaced anonymous callback function with 'addToGHMenu' to solve problem with opening
//project in a new window not triggering menu addition
pinegrow.addEventHandler('on_project_loaded', addToGHMenu);
//Removes extra menu items on project close
pinegrow.addEventHandler('on_project_closed', removeFromGHMenu);
//Function to add the styling to the page
function ghAddStyling() {
let styleLink = document.createElement('link');
styleLink.setAttribute('rel', 'stylesheet');
let styleFile = framework.getResourceUrl('./assets/style.css');
styleLink.setAttribute('href', styleFile);
const theApp = ghById('pgapp');
theApp.appendChild(styleLink);
}
//Function to add modals to the page
async function ghAddModal({
targetId,
modalName
}) {
let modalDiv = document.createElement('div');
let modalId = modalName + 'ModalContainer';