forked from desktop/desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp-store.ts
5824 lines (4948 loc) · 173 KB
/
app-store.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
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
import * as Path from 'path'
import { ipcRenderer, remote } from 'electron'
import { pathExists } from 'fs-extra'
import { escape } from 'querystring'
import {
AccountsStore,
CloningRepositoriesStore,
GitHubUserStore,
GitStore,
IssuesStore,
PullRequestCoordinator,
RepositoriesStore,
SignInStore,
} from '.'
import { Account } from '../../models/account'
import { AppMenu, IMenu } from '../../models/app-menu'
import { IAuthor } from '../../models/author'
import { Branch, IAheadBehind } from '../../models/branch'
import { BranchesTab } from '../../models/branches-tab'
import { CloneRepositoryTab } from '../../models/clone-repository-tab'
import { CloningRepository } from '../../models/cloning-repository'
import { Commit, ICommitContext, CommitOneLine } from '../../models/commit'
import {
DiffSelection,
DiffSelectionType,
DiffType,
ImageDiffType,
ITextDiff,
} from '../../models/diff'
import { FetchType } from '../../models/fetch'
import {
GitHubRepository,
hasWritePermission,
} from '../../models/github-repository'
import { Owner } from '../../models/owner'
import { PullRequest } from '../../models/pull-request'
import {
forkPullRequestRemoteName,
IRemote,
remoteEquals,
} from '../../models/remote'
import {
ILocalRepositoryState,
nameOf,
Repository,
isRepositoryWithGitHubRepository,
RepositoryWithGitHubRepository,
getNonForkGitHubRepository,
} from '../../models/repository'
import {
CommittedFileChange,
WorkingDirectoryFileChange,
WorkingDirectoryStatus,
AppFileStatusKind,
} from '../../models/status'
import { TipState, tipEquals } from '../../models/tip'
import { ICommitMessage } from '../../models/commit-message'
import {
Progress,
ICheckoutProgress,
IFetchProgress,
IRevertProgress,
IRebaseProgress,
} from '../../models/progress'
import { Popup, PopupType } from '../../models/popup'
import { IGitAccount } from '../../models/git-account'
import { themeChangeMonitor } from '../../ui/lib/theme-change-monitor'
import { getAppPath } from '../../ui/lib/app-proxy'
import {
ApplicationTheme,
getPersistedTheme,
setPersistedTheme,
getAutoSwitchPersistedTheme,
setAutoSwitchPersistedTheme,
} from '../../ui/lib/application-theme'
import {
getAppMenu,
updatePreferredAppMenuItemLabels,
} from '../../ui/main-process-proxy'
import {
API,
getAccountForEndpoint,
getDotComAPIEndpoint,
IAPIOrganization,
IAPIRepository,
getEndpointForRepository,
} from '../api'
import { shell } from '../app-shell'
import {
CompareAction,
HistoryTabMode,
Foldout,
FoldoutType,
IAppState,
ICompareBranch,
ICompareFormUpdate,
ICompareToBranch,
IDisplayHistory,
PossibleSelections,
RepositorySectionTab,
SelectionType,
ComparisonMode,
MergeConflictState,
isMergeConflictState,
RebaseConflictState,
IRebaseState,
IRepositoryState,
ChangesSelectionKind,
ChangesWorkingDirectorySelection,
IDivergingBranchBannerState,
} from '../app-state'
import {
ExternalEditor,
findEditorOrDefault,
getAvailableEditors,
launchExternalEditor,
parse,
} from '../editors'
import { assertNever, fatalError, forceUnwrap } from '../fatal-error'
import { findAccountForRemoteURL } from '../find-account'
import { formatCommitMessage } from '../format-commit-message'
import { getGenericHostname, getGenericUsername } from '../generic-git-auth'
import { getAccountForRepository } from '../get-account-for-repository'
import {
abortMerge,
addRemote,
checkoutBranch,
createBranch,
createCommit,
deleteBranch,
formatAsLocalRef,
getAuthorIdentity,
getBranchAheadBehind,
getChangedFiles,
getCommitDiff,
getMergeBase,
getRemotes,
getWorkingDirectoryDiff,
isCoAuthoredByTrailer,
mergeTree,
pull as pullRepo,
push as pushRepo,
renameBranch,
updateRef,
saveGitIgnore,
appendIgnoreRule,
createMergeCommit,
getBranchesPointedAt,
isGitRepository,
abortRebase,
continueRebase,
rebase,
PushOptions,
RebaseResult,
getRebaseSnapshot,
IStatusResult,
GitError,
} from '../git'
import {
installGlobalLFSFilters,
installLFSHooks,
isUsingLFS,
} from '../git/lfs'
import { inferLastPushForRepository } from '../infer-last-push-for-repository'
import { updateMenuState } from '../menu-update'
import { merge } from '../merge'
import {
IMatchedGitHubRepository,
matchGitHubRepository,
} from '../repository-matching'
import {
initializeRebaseFlowForConflictedRepository,
formatRebaseValue,
isCurrentBranchForcePush,
} from '../rebase'
import { RetryAction, RetryActionType } from '../../models/retry-actions'
import {
Default as DefaultShell,
findShellOrDefault,
launchShell,
parse as parseShell,
Shell,
} from '../shells'
import {
ILaunchStats,
StatsStore,
markUsageStatsNoteSeen,
hasSeenUsageStatsNote,
} from '../stats'
import { hasShownWelcomeFlow, markWelcomeFlowComplete } from '../welcome'
import {
getWindowState,
WindowState,
windowStateChannelName,
} from '../window-state'
import { TypedBaseStore } from './base-store'
import { AheadBehindUpdater } from './helpers/ahead-behind-updater'
import { MergeResult } from '../../models/merge'
import { promiseWithMinimumTimeout, sleep } from '../promise'
import { BackgroundFetcher } from './helpers/background-fetcher'
import { inferComparisonBranch } from './helpers/infer-comparison-branch'
import { validatedRepositoryPath } from './helpers/validated-repository-path'
import { RepositoryStateCache } from './repository-state-cache'
import { readEmoji } from '../read-emoji'
import { GitStoreCache } from './git-store-cache'
import { GitErrorContext } from '../git-error-context'
import {
setNumber,
setBoolean,
getBoolean,
getNumber,
getNumberArray,
setNumberArray,
} from '../local-storage'
import { ExternalEditorError } from '../editors/shared'
import { ApiRepositoriesStore } from './api-repositories-store'
import {
updateChangedFiles,
updateConflictState,
selectWorkingDirectoryFiles,
} from './updates/changes-state'
import {
ManualConflictResolution,
ManualConflictResolutionKind,
} from '../../models/manual-conflict-resolution'
import { BranchPruner } from './helpers/branch-pruner'
import { enableUpdateRemoteUrl } from '../feature-flag'
import { Banner, BannerType } from '../../models/banner'
import * as moment from 'moment'
import { isDarkModeEnabled } from '../../ui/lib/dark-theme'
import { ComputedAction } from '../../models/computed-action'
import {
createDesktopStashEntry,
getLastDesktopStashEntryForBranch,
popStashEntry,
dropDesktopStashEntry,
} from '../git/stash'
import {
UncommittedChangesStrategy,
UncommittedChangesStrategyKind,
uncommittedChangesStrategyKindDefault,
getUncommittedChangesStrategy,
askToStash,
parseStrategy,
} from '../../models/uncommitted-changes-strategy'
import { IStashEntry, StashedChangesLoadStates } from '../../models/stash-entry'
import { RebaseFlowStep, RebaseStep } from '../../models/rebase-flow-step'
import { arrayEquals, shallowEquals } from '../equality'
import { MenuLabelsEvent } from '../../models/menu-labels'
import { findRemoteBranchName } from './helpers/find-branch-name'
import { updateRemoteUrl } from './updates/update-remote-url'
import { findBranchesForFastForward } from './helpers/find-branches-for-fast-forward'
import {
TutorialStep,
orderedTutorialSteps,
isValidTutorialStep,
} from '../../models/tutorial-step'
import { OnboardingTutorialAssessor } from './helpers/tutorial-assessor'
import { getUntrackedFiles } from '../status'
import { enableProgressBarOnIcon } from '../feature-flag'
import { isBranchPushable } from '../helpers/push-control'
import {
findAssociatedPullRequest,
isPullRequestAssociatedWithBranch,
} from '../helpers/pull-request-matching'
import { parseRemote } from '../../lib/remote-parsing'
import { createTutorialRepository } from './helpers/create-tutorial-repository'
import { sendNonFatalException } from '../helpers/non-fatal-exception'
import { getDefaultDir } from '../../ui/lib/default-dir'
import { WorkflowPreferences } from '../../models/workflow-preferences'
import { getAttributableEmailsFor } from '../email'
const LastSelectedRepositoryIDKey = 'last-selected-repository-id'
const RecentRepositoriesKey = 'recently-selected-repositories'
/**
* maximum number of repositories shown in the "Recent" repositories group
* in the repository switcher dropdown
*/
const RecentRepositoriesLength = 3
const defaultSidebarWidth: number = 250
const sidebarWidthConfigKey: string = 'sidebar-width'
const defaultCommitSummaryWidth: number = 250
const commitSummaryWidthConfigKey: string = 'commit-summary-width'
const defaultStashedFilesWidth: number = 250
const stashedFilesWidthConfigKey: string = 'stashed-files-width'
const confirmRepoRemovalDefault: boolean = true
const confirmDiscardChangesDefault: boolean = true
const askForConfirmationOnForcePushDefault = true
const confirmRepoRemovalKey: string = 'confirmRepoRemoval'
const confirmDiscardChangesKey: string = 'confirmDiscardChanges'
const confirmForcePushKey: string = 'confirmForcePush'
const uncommittedChangesStrategyKindKey: string =
'uncommittedChangesStrategyKind'
const externalEditorKey: string = 'externalEditor'
const imageDiffTypeDefault = ImageDiffType.TwoUp
const imageDiffTypeKey = 'image-diff-type'
const hideWhitespaceInDiffDefault = false
const hideWhitespaceInDiffKey = 'hide-whitespace-in-diff'
const shellKey = 'shell'
// background fetching should occur hourly when Desktop is active, but this
// lower interval ensures user interactions like switching repositories and
// switching between apps does not result in excessive fetching in the app
const BackgroundFetchMinimumInterval = 30 * 60 * 1000
export class AppStore extends TypedBaseStore<IAppState> {
private readonly gitStoreCache: GitStoreCache
private accounts: ReadonlyArray<Account> = new Array<Account>()
private repositories: ReadonlyArray<Repository> = new Array<Repository>()
private recentRepositories: ReadonlyArray<number> = new Array<number>()
private selectedRepository: Repository | CloningRepository | null = null
/** The background fetcher for the currently selected repository. */
private currentBackgroundFetcher: BackgroundFetcher | null = null
/** The ahead/behind updater or the currently selected repository */
private currentAheadBehindUpdater: AheadBehindUpdater | null = null
private currentBranchPruner: BranchPruner | null = null
private showWelcomeFlow = false
private focusCommitMessage = false
private currentPopup: Popup | null = null
private currentFoldout: Foldout | null = null
private currentBanner: Banner | null = null
private errors: ReadonlyArray<Error> = new Array<Error>()
private emitQueued = false
private readonly localRepositoryStateLookup = new Map<
number,
ILocalRepositoryState
>()
/** Map from shortcut (e.g., :+1:) to on disk URL. */
private emoji = new Map<string, string>()
/**
* The Application menu as an AppMenu instance or null if
* the main process has not yet provided the renderer with
* a copy of the application menu structure.
*/
private appMenu: AppMenu | null = null
/**
* Used to highlight access keys throughout the app when the
* Alt key is pressed. Only applicable on non-macOS platforms.
*/
private highlightAccessKeys: boolean = false
/**
* A value indicating whether or not the current application
* window has focus.
*/
private appIsFocused: boolean = false
private sidebarWidth: number = defaultSidebarWidth
private commitSummaryWidth: number = defaultCommitSummaryWidth
private stashedFilesWidth: number = defaultStashedFilesWidth
private windowState: WindowState
private windowZoomFactor: number = 1
private isUpdateAvailableBannerVisible: boolean = false
private askForConfirmationOnRepositoryRemoval: boolean = confirmRepoRemovalDefault
private confirmDiscardChanges: boolean = confirmDiscardChangesDefault
private askForConfirmationOnForcePush = askForConfirmationOnForcePushDefault
private imageDiffType: ImageDiffType = imageDiffTypeDefault
private hideWhitespaceInDiff: boolean = hideWhitespaceInDiffDefault
private uncommittedChangesStrategyKind: UncommittedChangesStrategyKind = uncommittedChangesStrategyKindDefault
private selectedExternalEditor: ExternalEditor | null = null
private resolvedExternalEditor: ExternalEditor | null = null
/** The user's preferred shell. */
private selectedShell = DefaultShell
/** The current repository filter text */
private repositoryFilterText: string = ''
private currentMergeTreePromise: Promise<void> | null = null
/** The function to resolve the current Open in Desktop flow. */
private resolveOpenInDesktop:
| ((repository: Repository | null) => void)
| null = null
private selectedCloneRepositoryTab = CloneRepositoryTab.DotCom
private selectedBranchesTab = BranchesTab.Branches
private selectedTheme = ApplicationTheme.Light
private automaticallySwitchTheme = false
private hasUserViewedStash = false
/** Which step the user needs to complete next in the onboarding tutorial */
private currentOnboardingTutorialStep = TutorialStep.NotApplicable
private readonly tutorialAssessor: OnboardingTutorialAssessor
public constructor(
private readonly gitHubUserStore: GitHubUserStore,
private readonly cloningRepositoriesStore: CloningRepositoriesStore,
private readonly issuesStore: IssuesStore,
private readonly statsStore: StatsStore,
private readonly signInStore: SignInStore,
private readonly accountsStore: AccountsStore,
private readonly repositoriesStore: RepositoriesStore,
private readonly pullRequestCoordinator: PullRequestCoordinator,
private readonly repositoryStateCache: RepositoryStateCache,
private readonly apiRepositoriesStore: ApiRepositoriesStore
) {
super()
this.showWelcomeFlow = !hasShownWelcomeFlow()
this.gitStoreCache = new GitStoreCache(
shell,
this.statsStore,
(repo, store) => this.onGitStoreUpdated(repo, store),
error => this.emitError(error)
)
const window = remote.getCurrentWindow()
this.windowState = getWindowState(window)
this.onWindowZoomFactorChanged(window.webContents.zoomFactor)
this.wireupIpcEventHandlers(window)
this.wireupStoreEventHandlers()
getAppMenu()
this.tutorialAssessor = new OnboardingTutorialAssessor(
this.getResolvedExternalEditor
)
}
/** Figure out what step of the tutorial the user needs to do next */
private async updateCurrentTutorialStep(
repository: Repository
): Promise<void> {
const currentStep = await this.tutorialAssessor.getCurrentStep(
repository.isTutorialRepository,
this.repositoryStateCache.get(repository)
)
// only emit an update if its changed
if (currentStep !== this.currentOnboardingTutorialStep) {
this.currentOnboardingTutorialStep = currentStep
log.info(`Current tutorial step is now ${currentStep}`)
this.recordTutorialStepCompleted(currentStep)
this.emitUpdate()
}
}
private recordTutorialStepCompleted(step: TutorialStep): void {
if (!isValidTutorialStep(step)) {
return
}
this.statsStore.recordHighestTutorialStepCompleted(
orderedTutorialSteps.indexOf(step)
)
switch (step) {
case TutorialStep.PickEditor:
// don't need to record anything for the first step
break
case TutorialStep.CreateBranch:
this.statsStore.recordTutorialEditorInstalled()
break
case TutorialStep.EditFile:
this.statsStore.recordTutorialBranchCreated()
break
case TutorialStep.MakeCommit:
this.statsStore.recordTutorialFileEdited()
break
case TutorialStep.PushBranch:
this.statsStore.recordTutorialCommitCreated()
break
case TutorialStep.OpenPullRequest:
this.statsStore.recordTutorialBranchPushed()
break
case TutorialStep.AllDone:
this.statsStore.recordTutorialPrCreated()
this.statsStore.recordTutorialCompleted()
break
default:
assertNever(step, 'Unaccounted for step type')
}
}
public async _resumeTutorial(repository: Repository) {
this.tutorialAssessor.resumeTutorial()
await this.updateCurrentTutorialStep(repository)
}
public async _pauseTutorial(repository: Repository) {
this.tutorialAssessor.pauseTutorial()
await this.updateCurrentTutorialStep(repository)
}
/** Call via `Dispatcher` when the user opts to skip the pick editor step of the onboarding tutorial */
public async _skipPickEditorTutorialStep(repository: Repository) {
this.tutorialAssessor.skipPickEditor()
await this.updateCurrentTutorialStep(repository)
}
/**
* Call via `Dispatcher` when the user has either created a pull request or opts to
* skip the create pull request step of the onboarding tutorial
*/
public async _markPullRequestTutorialStepAsComplete(repository: Repository) {
this.tutorialAssessor.markPullRequestTutorialStepAsComplete()
await this.updateCurrentTutorialStep(repository)
}
private wireupIpcEventHandlers(window: Electron.BrowserWindow) {
ipcRenderer.on(
windowStateChannelName,
(event: Electron.IpcRendererEvent, windowState: WindowState) => {
this.windowState = windowState
this.emitUpdate()
}
)
ipcRenderer.on('zoom-factor-changed', (event: any, zoomFactor: number) => {
this.onWindowZoomFactorChanged(zoomFactor)
})
ipcRenderer.on(
'app-menu',
(event: Electron.IpcRendererEvent, { menu }: { menu: IMenu }) => {
this.setAppMenu(menu)
}
)
}
private wireupStoreEventHandlers() {
this.gitHubUserStore.onDidUpdate(() => {
this.emitUpdate()
})
this.cloningRepositoriesStore.onDidUpdate(() => {
this.emitUpdate()
})
this.cloningRepositoriesStore.onDidError(e => this.emitError(e))
this.signInStore.onDidAuthenticate((account, method) => {
this._addAccount(account)
if (this.showWelcomeFlow) {
this.statsStore.recordWelcomeWizardSignInMethod(method)
}
})
this.signInStore.onDidUpdate(() => this.emitUpdate())
this.signInStore.onDidError(error => this.emitError(error))
this.accountsStore.onDidUpdate(accounts => {
this.accounts = accounts
this.emitUpdate()
})
this.accountsStore.onDidError(error => this.emitError(error))
this.repositoriesStore.onDidUpdate(updateRepositories => {
this.repositories = updateRepositories
this.updateRepositorySelectionAfterRepositoriesChanged()
this.emitUpdate()
})
this.pullRequestCoordinator.onPullRequestsChanged((repo, pullRequests) =>
this.onPullRequestChanged(repo, pullRequests)
)
this.pullRequestCoordinator.onIsLoadingPullRequests(
(repository, isLoadingPullRequests) => {
this.repositoryStateCache.updateBranchesState(repository, () => {
return { isLoadingPullRequests }
})
this.emitUpdate()
}
)
this.apiRepositoriesStore.onDidUpdate(() => this.emitUpdate())
this.apiRepositoriesStore.onDidError(error => this.emitError(error))
}
/** Load the emoji from disk. */
public loadEmoji() {
const rootDir = getAppPath()
readEmoji(rootDir)
.then(emoji => {
this.emoji = emoji
this.emitUpdate()
})
.catch(err => {
log.warn(`Unexpected issue when trying to read emoji into memory`, err)
})
}
protected emitUpdate() {
// If the window is hidden then we won't get an animation frame, but there
// may still be work we wanna do in response to the state change. So
// immediately emit the update.
if (this.windowState === 'hidden') {
this.emitUpdateNow()
return
}
if (this.emitQueued) {
return
}
this.emitQueued = true
window.requestAnimationFrame(() => {
this.emitUpdateNow()
})
}
private emitUpdateNow() {
this.emitQueued = false
const state = this.getState()
super.emitUpdate(state)
updateMenuState(state, this.appMenu)
}
/**
* Called when we have reason to suspect that the zoom factor
* has changed. Note that this doesn't necessarily mean that it
* has changed with regards to our internal state which is why
* we double check before emitting an update.
*/
private onWindowZoomFactorChanged(zoomFactor: number) {
const current = this.windowZoomFactor
this.windowZoomFactor = zoomFactor
if (zoomFactor !== current) {
this.emitUpdate()
}
}
private getSelectedState(): PossibleSelections | null {
const repository = this.selectedRepository
if (!repository) {
return null
}
if (repository instanceof CloningRepository) {
const progress = this.cloningRepositoriesStore.getRepositoryState(
repository
)
if (!progress) {
return null
}
return {
type: SelectionType.CloningRepository,
repository,
progress,
}
}
if (repository.missing) {
return { type: SelectionType.MissingRepository, repository }
}
return {
type: SelectionType.Repository,
repository,
state: this.repositoryStateCache.get(repository),
}
}
public getState(): IAppState {
const repositories = [
...this.repositories,
...this.cloningRepositoriesStore.repositories,
]
return {
accounts: this.accounts,
repositories,
recentRepositories: this.recentRepositories,
localRepositoryStateLookup: this.localRepositoryStateLookup,
windowState: this.windowState,
windowZoomFactor: this.windowZoomFactor,
appIsFocused: this.appIsFocused,
selectedState: this.getSelectedState(),
signInState: this.signInStore.getState(),
currentPopup: this.currentPopup,
currentFoldout: this.currentFoldout,
errors: this.errors,
showWelcomeFlow: this.showWelcomeFlow,
focusCommitMessage: this.focusCommitMessage,
emoji: this.emoji,
sidebarWidth: this.sidebarWidth,
commitSummaryWidth: this.commitSummaryWidth,
stashedFilesWidth: this.stashedFilesWidth,
appMenuState: this.appMenu ? this.appMenu.openMenus : [],
highlightAccessKeys: this.highlightAccessKeys,
isUpdateAvailableBannerVisible: this.isUpdateAvailableBannerVisible,
currentBanner: this.currentBanner,
askForConfirmationOnRepositoryRemoval: this
.askForConfirmationOnRepositoryRemoval,
askForConfirmationOnDiscardChanges: this.confirmDiscardChanges,
askForConfirmationOnForcePush: this.askForConfirmationOnForcePush,
uncommittedChangesStrategyKind: this.uncommittedChangesStrategyKind,
selectedExternalEditor: this.selectedExternalEditor,
imageDiffType: this.imageDiffType,
hideWhitespaceInDiff: this.hideWhitespaceInDiff,
selectedShell: this.selectedShell,
repositoryFilterText: this.repositoryFilterText,
resolvedExternalEditor: this.resolvedExternalEditor,
selectedCloneRepositoryTab: this.selectedCloneRepositoryTab,
selectedBranchesTab: this.selectedBranchesTab,
selectedTheme: this.selectedTheme,
automaticallySwitchTheme: this.automaticallySwitchTheme,
apiRepositories: this.apiRepositoriesStore.getState(),
optOutOfUsageTracking: this.statsStore.getOptOut(),
currentOnboardingTutorialStep: this.currentOnboardingTutorialStep,
}
}
private onGitStoreUpdated(repository: Repository, gitStore: GitStore) {
const prevRepositoryState = this.repositoryStateCache.get(repository)
this.repositoryStateCache.updateBranchesState(repository, state => {
let { currentPullRequest } = state
const { tip, currentRemote: remote } = gitStore
// If the tip has changed we need to re-evaluate whether or not the
// current pull request is still valid. Note that we're not using
// updateCurrentPullRequest here because we know for certain that
// the list of open pull requests haven't changed so we can find
// a happy path where the tip has changed but the current PR is
// still valid which doesn't require us to iterate through the
// list of open PRs.
if (
!tipEquals(state.tip, tip) ||
!remoteEquals(prevRepositoryState.remote, remote)
) {
if (tip.kind !== TipState.Valid || remote === null) {
// The tip isn't a branch so or the current branch doesn't have a remote
// so there can't be a current pull request.
currentPullRequest = null
} else {
const { branch } = tip
if (
!currentPullRequest ||
!isPullRequestAssociatedWithBranch(
branch,
currentPullRequest,
remote
)
) {
// Either we don't have a current pull request or the current pull
// request no longer matches the tip, let's go hunting for a new one.
const prs = state.openPullRequests
currentPullRequest = findAssociatedPullRequest(branch, prs, remote)
}
if (
tip.kind === TipState.Valid &&
state.tip.kind === TipState.Valid &&
tip.branch.name !== state.tip.branch.name
) {
this.refreshBranchProtectionState(repository)
}
}
}
return {
tip: gitStore.tip,
defaultBranch: gitStore.defaultBranch,
allBranches: gitStore.allBranches,
recentBranches: gitStore.recentBranches,
pullWithRebase: gitStore.pullWithRebase,
currentPullRequest,
}
})
let selectWorkingDirectory = false
let selectStashEntry = false
this.repositoryStateCache.updateChangesState(repository, state => {
const stashEntry = gitStore.currentBranchStashEntry
// Figure out what selection changes we need to make as a result of this
// change.
if (state.selection.kind === ChangesSelectionKind.Stash) {
if (state.stashEntry !== null) {
if (stashEntry === null) {
// We're showing a stash now and the stash entry has just dissapeared
// so we need to switch back over to the working directory.
selectWorkingDirectory = true
} else if (state.stashEntry.stashSha !== stashEntry.stashSha) {
// The current stash entry has changed from underneath so we must
// ensure we have a valid selection.
selectStashEntry = true
}
}
}
return {
commitMessage: gitStore.commitMessage,
showCoAuthoredBy: gitStore.showCoAuthoredBy,
coAuthors: gitStore.coAuthors,
stashEntry,
}
})
this.repositoryStateCache.update(repository, () => ({
commitLookup: gitStore.commitLookup,
localCommitSHAs: gitStore.localCommitSHAs,
localTags: gitStore.localTags,
aheadBehind: gitStore.aheadBehind,
tagsToPush: gitStore.tagsToPush,
remote: gitStore.currentRemote,
lastFetched: gitStore.lastFetched,
}))
// _selectWorkingDirectoryFiles and _selectStashedFile will
// emit updates by themselves.
if (selectWorkingDirectory) {
this._selectWorkingDirectoryFiles(repository)
} else if (selectStashEntry) {
this._selectStashedFile(repository)
} else {
this.emitUpdate()
}
}
private clearBranchProtectionState(repository: Repository) {
this.repositoryStateCache.updateChangesState(repository, () => ({
currentBranchProtected: false,
}))
this.emitUpdate()
}
private async refreshBranchProtectionState(repository: Repository) {
const gitStore = this.gitStoreCache.get(repository)
if (
gitStore.tip.kind === TipState.Valid &&
repository.gitHubRepository !== null
) {
const gitHubRepo = repository.gitHubRepository
const branchName = findRemoteBranchName(
gitStore.tip,
gitStore.currentRemote,
gitHubRepo
)
if (branchName !== null) {
const account = getAccountForEndpoint(
this.accounts,
gitHubRepo.endpoint
)
if (account === null) {
return
}
// If the user doesn't have write access to the repository
// it doesn't matter if the branch is protected or not and
// we can avoid the API call. See the `showNoWriteAccess`
// prop in the `CommitMessage` component where we specifically
// test for this scenario and show a message specifically
// about write access before showing a branch protection
// warning.
if (!hasWritePermission(gitHubRepo)) {
this.repositoryStateCache.updateChangesState(repository, () => ({
currentBranchProtected: false,
}))
this.emitUpdate()
return
}
const name = gitHubRepo.name
const owner = gitHubRepo.owner.login
const api = API.fromAccount(account)
const pushControl = await api.fetchPushControl(owner, name, branchName)
const currentBranchProtected = !isBranchPushable(pushControl)
this.repositoryStateCache.updateChangesState(repository, () => ({
currentBranchProtected,
}))
this.emitUpdate()
}
}
}
private clearSelectedCommit(repository: Repository) {
this.repositoryStateCache.updateCommitSelection(repository, () => ({
sha: null,
file: null,
changedFiles: [],
diff: null,
}))
}
/** This shouldn't be called directly. See `Dispatcher`. */
public async _changeCommitSelection(
repository: Repository,
sha: string
): Promise<void> {
const { commitSelection } = this.repositoryStateCache.get(repository)
if (commitSelection.sha === sha) {
return
}
this.repositoryStateCache.updateCommitSelection(repository, () => ({
sha,
file: null,
changedFiles: [],
diff: null,
}))
this.emitUpdate()
}
private updateOrSelectFirstCommit(
repository: Repository,
commitSHAs: ReadonlyArray<string>
) {
const state = this.repositoryStateCache.get(repository)
let selectedSHA = state.commitSelection.sha
if (selectedSHA != null) {
const index = commitSHAs.findIndex(sha => sha === selectedSHA)
if (index < 0) {
// selected SHA is not in this list
// -> clear the selection in the app state
selectedSHA = null
this.clearSelectedCommit(repository)
}
}
if (selectedSHA == null && commitSHAs.length > 0) {
this._changeCommitSelection(repository, commitSHAs[0])
this._loadChangedFilesForCurrentSelection(repository)
}
}
private startAheadBehindUpdater(repository: Repository) {
if (this.currentAheadBehindUpdater != null) {
fatalError(
`An ahead/behind updater is already active and cannot start updating on ${repository.name}`
)
}
const updater = new AheadBehindUpdater(repository, aheadBehindCache => {
this.repositoryStateCache.updateCompareState(repository, () => ({
aheadBehindCache,
}))
this.emitUpdate()
})
this.currentAheadBehindUpdater = updater
this.currentAheadBehindUpdater.start()
}
private stopAheadBehindUpdate() {
const updater = this.currentAheadBehindUpdater
if (updater != null) {
updater.stop()
this.currentAheadBehindUpdater = null
}
}
/** This shouldn't be called directly. See `Dispatcher`. */
public async _initializeCompare(
repository: Repository,
initialAction?: CompareAction
) {
const state = this.repositoryStateCache.get(repository)
const { branchesState, compareState } = state
const { tip, currentPullRequest } = branchesState
const currentBranch = tip.kind === TipState.Valid ? tip.branch : null
const allBranches =
currentBranch != null
? branchesState.allBranches.filter(b => b.name !== currentBranch.name)