Browse Source

Removes namespaces

Splits common Git constants into a separate file
main
Eric Amodio 1 year ago
parent
commit
06a174edd8
95 changed files with 923 additions and 899 deletions
  1. +2
    -2
      src/commands/copyShaToClipboard.ts
  2. +2
    -2
      src/commands/diffLineWithWorking.ts
  3. +14
    -15
      src/commands/diffWith.ts
  4. +2
    -2
      src/commands/diffWithPrevious.ts
  5. +2
    -2
      src/commands/diffWithRevision.ts
  6. +4
    -4
      src/commands/diffWithRevisionFrom.ts
  7. +3
    -3
      src/commands/diffWithWorking.ts
  8. +2
    -2
      src/commands/externalDiff.ts
  9. +2
    -2
      src/commands/ghpr/openOrCreateWorktree.ts
  10. +14
    -18
      src/commands/git/branch.ts
  11. +12
    -9
      src/commands/git/cherry-pick.ts
  12. +4
    -4
      src/commands/git/fetch.ts
  13. +9
    -9
      src/commands/git/log.ts
  14. +20
    -19
      src/commands/git/merge.ts
  15. +5
    -7
      src/commands/git/pull.ts
  16. +12
    -13
      src/commands/git/push.ts
  17. +14
    -13
      src/commands/git/rebase.ts
  18. +9
    -9
      src/commands/git/reset.ts
  19. +3
    -3
      src/commands/git/revert.ts
  20. +6
    -10
      src/commands/git/stash.ts
  21. +3
    -3
      src/commands/git/status.ts
  22. +12
    -11
      src/commands/git/switch.ts
  23. +15
    -9
      src/commands/git/tag.ts
  24. +10
    -9
      src/commands/git/worktree.ts
  25. +2
    -2
      src/commands/openCommitOnRemote.ts
  26. +2
    -2
      src/commands/openFileAtRevision.ts
  27. +2
    -2
      src/commands/openFileOnRemote.ts
  28. +5
    -5
      src/commands/openOnRemote.ts
  29. +2
    -2
      src/commands/openRevisionFile.ts
  30. +42
    -33
      src/commands/quickCommand.steps.ts
  31. +2
    -2
      src/commands/showCommitsInView.ts
  32. +4
    -3
      src/commands/showQuickBranchHistory.ts
  33. +1
    -1
      src/commands/showQuickCommitFile.ts
  34. +13
    -13
      src/env/node/git/git.ts
  35. +69
    -60
      src/env/node/git/localGitProvider.ts
  36. +7
    -6
      src/git/actions/commit.ts
  37. +5
    -10
      src/git/formatters/commitFormatter.ts
  38. +3
    -3
      src/git/fsProvider.ts
  39. +15
    -14
      src/git/gitProviderService.ts
  40. +9
    -8
      src/git/gitUri.ts
  41. +2
    -2
      src/git/models/branch.ts
  42. +10
    -9
      src/git/models/commit.ts
  43. +3
    -0
      src/git/models/constants.ts
  44. +273
    -283
      src/git/models/reference.ts
  45. +3
    -3
      src/git/models/reflog.ts
  46. +5
    -10
      src/git/models/repository.ts
  47. +9
    -21
      src/git/models/status.ts
  48. +2
    -2
      src/git/models/worktree.ts
  49. +6
    -5
      src/git/parsers/blameParser.ts
  50. +2
    -2
      src/git/parsers/logParser.ts
  51. +2
    -2
      src/git/remotes/bitbucket-server.ts
  52. +2
    -2
      src/git/remotes/bitbucket.ts
  53. +2
    -2
      src/git/remotes/gerrit.ts
  54. +2
    -2
      src/git/remotes/gitea.ts
  55. +2
    -2
      src/git/remotes/github.ts
  56. +2
    -2
      src/git/remotes/gitlab.ts
  57. +4
    -4
      src/git/search.ts
  58. +10
    -14
      src/hovers/hovers.ts
  59. +2
    -2
      src/plus/github/github.ts
  60. +24
    -23
      src/plus/github/githubGitProvider.ts
  61. +25
    -19
      src/plus/webviews/graph/graphWebview.ts
  62. +10
    -9
      src/quickpicks/items/gitCommands.ts
  63. +5
    -4
      src/quickpicks/referencePicker.ts
  64. +2
    -2
      src/terminal/linkProvider.ts
  65. +2
    -2
      src/trackers/trackedDocument.ts
  66. +3
    -2
      src/uris/deepLinks/deepLinkService.ts
  67. +9
    -3
      src/views/branchesView.ts
  68. +5
    -2
      src/views/commitsView.ts
  69. +5
    -5
      src/views/nodes/UncommittedFilesNode.ts
  70. +2
    -6
      src/views/nodes/branchTrackingStatusFilesNode.ts
  71. +3
    -3
      src/views/nodes/branchTrackingStatusNode.ts
  72. +12
    -11
      src/views/nodes/compareBranchNode.ts
  73. +8
    -8
      src/views/nodes/compareResultsNode.ts
  74. +3
    -5
      src/views/nodes/fileHistoryNode.ts
  75. +3
    -3
      src/views/nodes/fileHistoryTrackerNode.ts
  76. +4
    -5
      src/views/nodes/lineHistoryNode.ts
  77. +5
    -8
      src/views/nodes/lineHistoryTrackerNode.ts
  78. +5
    -5
      src/views/nodes/mergeConflictCurrentChangesNode.ts
  79. +14
    -8
      src/views/nodes/mergeConflictIncomingChangesNode.ts
  80. +5
    -5
      src/views/nodes/mergeStatusNode.ts
  81. +5
    -5
      src/views/nodes/rebaseStatusNode.ts
  82. +2
    -2
      src/views/nodes/repositoryNode.ts
  83. +2
    -2
      src/views/nodes/resultsFileNode.ts
  84. +1
    -1
      src/views/nodes/statusFileNode.ts
  85. +2
    -2
      src/views/nodes/tagNode.ts
  86. +3
    -3
      src/views/nodes/viewNode.ts
  87. +2
    -2
      src/views/nodes/worktreeNode.ts
  88. +9
    -3
      src/views/remotesView.ts
  89. +5
    -5
      src/views/repositoriesView.ts
  90. +5
    -5
      src/views/searchAndCompareView.ts
  91. +5
    -2
      src/views/stashesView.ts
  92. +5
    -2
      src/views/tagsView.ts
  93. +12
    -8
      src/views/viewCommands.ts
  94. +2
    -2
      src/webviews/commitDetails/commitDetailsWebviewView.ts
  95. +2
    -2
      src/webviews/rebase/rebaseEditor.ts

+ 2
- 2
src/commands/copyShaToClipboard.ts View File

@ -4,7 +4,7 @@ import { configuration } from '../configuration';
import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { shortenRevision } from '../git/models/reference';
import { Logger } from '../logger';
import { showGenericErrorMessage } from '../messages';
import { command } from '../system/command';
@ -86,7 +86,7 @@ export class CopyShaToClipboardCommand extends ActiveEditorCommand {
}
await env.clipboard.writeText(
configuration.get('advanced.abbreviateShaOnCopy') ? GitRevision.shorten(args.sha) : args.sha,
configuration.get('advanced.abbreviateShaOnCopy') ? shortenRevision(args.sha) : args.sha,
);
} catch (ex) {
Logger.error(ex, 'CopyShaToClipboardCommand');

+ 2
- 2
src/commands/diffLineWithWorking.ts View File

@ -4,7 +4,7 @@ import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import type { GitCommit } from '../git/models/commit';
import { GitRevision } from '../git/models/reference';
import { uncommittedStaged } from '../git/models/constants';
import { Logger } from '../logger';
import { showFileNotUnderSourceControlWarningMessage, showGenericErrorMessage } from '../messages';
import { command, executeCommand } from '../system/command';
@ -56,7 +56,7 @@ export class DiffLineWithWorkingCommand extends ActiveEditorCommand {
if (args.commit.isUncommitted) {
const status = await this.container.git.getStatusForFile(gitUri.repoPath!, gitUri);
if (status?.indexStatus != null) {
lhsSha = GitRevision.uncommittedStaged;
lhsSha = uncommittedStaged;
lhsUri = this.container.git.getAbsoluteUri(
status.originalPath || status.path,
args.commit.repoPath,

+ 14
- 15
src/commands/diffWith.ts View File

@ -4,7 +4,8 @@ import { Commands, CoreCommands, GlyphChars } from '../constants';
import type { Container } from '../container';
import type { GitCommit } from '../git/models/commit';
import { isCommit } from '../git/models/commit';
import { GitRevision } from '../git/models/reference';
import { deletedOrMissing } from '../git/models/constants';
import { isShaLike, isUncommitted, shortenRevision } from '../git/models/reference';
import { Logger } from '../logger';
import { showGenericErrorMessage } from '../messages';
import { command, executeCoreCommand } from '../system/command';
@ -96,19 +97,19 @@ export class DiffWithCommand extends Command {
[args.lhs.sha, args.rhs.sha] = await Promise.all([
await this.container.git.resolveReference(args.repoPath, args.lhs.sha, args.lhs.uri, {
// If the ref looks like a sha, don't wait too long, since it should work
timeout: GitRevision.isShaLike(args.lhs.sha) ? 100 : undefined,
timeout: isShaLike(args.lhs.sha) ? 100 : undefined,
}),
await this.container.git.resolveReference(args.repoPath, args.rhs.sha, args.rhs.uri, {
// If the ref looks like a sha, don't wait too long, since it should work
timeout: GitRevision.isShaLike(args.rhs.sha) ? 100 : undefined,
timeout: isShaLike(args.rhs.sha) ? 100 : undefined,
}),
]);
if (args.lhs.sha !== GitRevision.deletedOrMissing) {
if (args.lhs.sha !== deletedOrMissing) {
lhsSha = args.lhs.sha;
}
if (args.rhs.sha && args.rhs.sha !== GitRevision.deletedOrMissing) {
if (args.rhs.sha && args.rhs.sha !== deletedOrMissing) {
// Ensure that the file still exists in this commit
const status = await this.container.git.getFileStatusForCommit(
args.repoPath,
@ -116,13 +117,13 @@ export class DiffWithCommand extends Command {
args.rhs.sha,
);
if (status?.status === 'D') {
args.rhs.sha = GitRevision.deletedOrMissing;
args.rhs.sha = deletedOrMissing;
} else {
rhsSha = args.rhs.sha;
}
if (status?.status === 'A' && args.lhs.sha.endsWith('^')) {
args.lhs.sha = GitRevision.deletedOrMissing;
args.lhs.sha = deletedOrMissing;
}
}
@ -131,11 +132,11 @@ export class DiffWithCommand extends Command {
this.container.git.getBestRevisionUri(args.repoPath, args.rhs.uri.fsPath, args.rhs.sha),
]);
let rhsSuffix = GitRevision.shorten(rhsSha, { strings: { uncommitted: 'Working Tree' } });
let rhsSuffix = shortenRevision(rhsSha, { strings: { uncommitted: 'Working Tree' } });
if (rhs == null) {
if (GitRevision.isUncommitted(args.rhs.sha)) {
if (isUncommitted(args.rhs.sha)) {
rhsSuffix = 'deleted';
} else if (rhsSuffix.length === 0 && args.rhs.sha === GitRevision.deletedOrMissing) {
} else if (rhsSuffix.length === 0 && args.rhs.sha === deletedOrMissing) {
rhsSuffix = 'not in Working Tree';
} else {
rhsSuffix = `deleted${rhsSuffix.length === 0 ? '' : ` in ${rhsSuffix}`}`;
@ -144,7 +145,7 @@ export class DiffWithCommand extends Command {
rhsSuffix = `added${rhsSuffix.length === 0 ? '' : ` in ${rhsSuffix}`}`;
}
let lhsSuffix = args.lhs.sha !== GitRevision.deletedOrMissing ? GitRevision.shorten(lhsSha) : '';
let lhsSuffix = args.lhs.sha !== deletedOrMissing ? shortenRevision(lhsSha) : '';
if (lhs == null && args.rhs.sha.length === 0) {
if (rhs != null) {
lhsSuffix = lhsSuffix.length === 0 ? '' : `not in ${lhsSuffix}`;
@ -180,10 +181,8 @@ export class DiffWithCommand extends Command {
void (await executeCoreCommand(
CoreCommands.Diff,
lhs ??
this.container.git.getRevisionUri(GitRevision.deletedOrMissing, args.lhs.uri.fsPath, args.repoPath),
rhs ??
this.container.git.getRevisionUri(GitRevision.deletedOrMissing, args.rhs.uri.fsPath, args.repoPath),
lhs ?? this.container.git.getRevisionUri(deletedOrMissing, args.lhs.uri.fsPath, args.repoPath),
rhs ?? this.container.git.getRevisionUri(deletedOrMissing, args.rhs.uri.fsPath, args.repoPath),
title,
args.showOptions,
));

+ 2
- 2
src/commands/diffWithPrevious.ts View File

@ -3,7 +3,7 @@ import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import type { GitCommit } from '../git/models/commit';
import { GitRevision } from '../git/models/reference';
import { deletedOrMissing } from '../git/models/constants';
import { Logger } from '../logger';
import { showCommitHasNoPreviousCommitWarningMessage, showGenericErrorMessage } from '../messages';
import { command, executeCommand } from '../system/command';
@ -112,7 +112,7 @@ export class DiffWithPreviousCommand extends ActiveEditorCommand {
diffUris.previous = GitUri.fromFile(
diffUris.current.fileName,
diffUris.current.repoPath!,
GitRevision.deletedOrMissing,
deletedOrMissing,
);
}

+ 2
- 2
src/commands/diffWithRevision.ts View File

@ -2,7 +2,7 @@ import type { TextDocumentShowOptions, TextEditor, Uri } from 'vscode';
import { Commands, GlyphChars, quickPickTitleMaxChars } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { shortenRevision } from '../git/models/reference';
import { Logger } from '../logger';
import { showGenericErrorMessage } from '../messages';
import { showCommitPicker } from '../quickpicks/commitPicker';
@ -50,7 +50,7 @@ export class DiffWithRevisionCommand extends ActiveEditorCommand {
const pick = await showCommitPicker(
log,
`${title}${gitUri.getFormattedFileName({
suffix: gitUri.sha ? `:${GitRevision.shorten(gitUri.sha)}` : undefined,
suffix: gitUri.sha ? `:${shortenRevision(gitUri.sha)}` : undefined,
truncateTo: quickPickTitleMaxChars - title.length,
})}`,
'Choose a commit to compare with',

+ 4
- 4
src/commands/diffWithRevisionFrom.ts View File

@ -2,7 +2,7 @@ import type { TextDocumentShowOptions, TextEditor, Uri } from 'vscode';
import { Commands, GlyphChars, quickPickTitleMaxChars } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitReference, GitRevision } from '../git/models/reference';
import { isBranchReference, shortenRevision } from '../git/models/reference';
import { showNoRepositoryWarningMessage } from '../messages';
import { showStashPicker } from '../quickpicks/commitPicker';
import { showReferencePicker } from '../quickpicks/referencePicker';
@ -74,7 +74,7 @@ export class DiffWithRevisionFromCommand extends ActiveEditorCommand {
if (pick == null) return;
ref = pick.ref;
sha = GitReference.isBranch(pick) && pick.remote ? `remotes/${ref}` : ref;
sha = isBranchReference(pick) && pick.remote ? `remotes/${ref}` : ref;
}
if (ref == null) return;
@ -88,7 +88,7 @@ export class DiffWithRevisionFromCommand extends ActiveEditorCommand {
const rename = files.find(s => s.path === path);
if (rename?.originalPath != null) {
renamedUri = this.container.git.getAbsoluteUri(rename.originalPath, gitUri.repoPath);
renamedTitle = `${basename(rename.originalPath)} (${GitRevision.shorten(ref)})`;
renamedTitle = `${basename(rename.originalPath)} (${shortenRevision(ref)})`;
}
}
@ -97,7 +97,7 @@ export class DiffWithRevisionFromCommand extends ActiveEditorCommand {
lhs: {
sha: sha,
uri: renamedUri ?? gitUri,
title: renamedTitle ?? `${basename(gitUri.fsPath)} (${GitRevision.shorten(ref)})`,
title: renamedTitle ?? `${basename(gitUri.fsPath)} (${shortenRevision(ref)})`,
},
rhs: {
sha: '',

+ 3
- 3
src/commands/diffWithWorking.ts View File

@ -3,7 +3,7 @@ import { window } from 'vscode';
import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { deletedOrMissing, uncommittedStaged } from '../git/models/constants';
import { Logger } from '../logger';
import { showGenericErrorMessage } from '../messages';
import { command, executeCommand } from '../system/command';
@ -64,7 +64,7 @@ export class DiffWithWorkingCommand extends ActiveEditorCommand {
return;
}
if (gitUri.sha === GitRevision.deletedOrMissing) {
if (gitUri.sha === deletedOrMissing) {
void window.showWarningMessage('Unable to open compare. File has been deleted from the working tree');
return;
@ -77,7 +77,7 @@ export class DiffWithWorkingCommand extends ActiveEditorCommand {
void (await executeCommand<DiffWithCommandArgs>(Commands.DiffWith, {
repoPath: gitUri.repoPath,
lhs: {
sha: GitRevision.uncommittedStaged,
sha: uncommittedStaged,
uri: gitUri.documentUri(),
},
rhs: {

+ 2
- 2
src/commands/externalDiff.ts View File

@ -6,7 +6,7 @@ import { configuration } from '../configuration';
import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { isUncommitted } from '../git/models/reference';
import { Logger } from '../logger';
import { showGenericErrorMessage } from '../messages';
import { getRepositoryOrShowPicker } from '../quickpicks/repositoryPicker';
@ -37,7 +37,7 @@ export class ExternalDiffCommand extends Command {
if (isCommandContextViewNodeHasFileCommit(context)) {
const previousSha = await context.node.commit.getPreviousSha();
const ref1 = GitRevision.isUncommitted(previousSha) ? '' : previousSha;
const ref1 = isUncommitted(previousSha) ? '' : previousSha;
const ref2 = context.node.commit.isUncommitted ? '' : context.node.commit.sha;
args.files = [

+ 2
- 2
src/commands/ghpr/openOrCreateWorktree.ts View File

@ -4,7 +4,7 @@ import { Commands } from '../../constants';
import type { Container } from '../../container';
import { add as addRemote } from '../../git/actions/remote';
import { create as createWorktree, open as openWorktree } from '../../git/actions/worktree';
import { GitReference } from '../../git/models/reference';
import { createReference } from '../../git/models/reference';
import type { GitRemote } from '../../git/models/remote';
import { parseGitRemoteUrl } from '../../git/parsers/remoteParser';
import { Logger } from '../../logger';
@ -118,7 +118,7 @@ export class OpenOrCreateWorktreeCommand extends Command {
await createWorktree(
repo,
undefined,
GitReference.create(`${remote.name}/${ref}`, repo.path, {
createReference(`${remote.name}/${ref}`, repo.path, {
refType: 'branch',
name: `${remote.name}/${ref}`,
remote: true,

+ 14
- 18
src/commands/git/branch.ts View File

@ -1,7 +1,7 @@
import { QuickInputButtons } from 'vscode';
import type { Container } from '../../container';
import type { GitBranchReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import type { GitBranchReference, GitReference } from '../../git/models/reference';
import { getNameWithoutRemote, getReferenceLabel, isRevisionReference } from '../../git/models/reference';
import { Repository } from '../../git/models/repository';
import type { QuickPickItemOfT } from '../../quickpicks/items/common';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -302,7 +302,7 @@ export class BranchGitCommand extends QuickCommand {
`Choose a branch${context.showTags ? ' or tag' : ''} to create the new branch from`,
picked: state.reference?.ref ?? (await state.repo.getBranch())?.ref,
titleContext: ' from',
value: GitReference.isRevision(state.reference) ? state.reference.ref : undefined,
value: isRevisionReference(state.reference) ? state.reference.ref : undefined,
});
// Always break on the first step (so we will go back)
if (result === StepResultBreak) break;
@ -313,12 +313,12 @@ export class BranchGitCommand extends QuickCommand {
if (state.counter < 4 || state.name == null) {
const result = yield* inputBranchNameStep(state, context, {
placeholder: 'Please provide a name for the new branch',
titleContext: ` from ${GitReference.toString(state.reference, {
titleContext: ` from ${getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
label: state.reference.refType !== 'branch',
})}`,
value: state.name ?? GitReference.getNameWithoutRemote(state.reference),
value: state.name ?? getNameWithoutRemote(state.reference),
});
if (result === StepResultBreak) continue;
@ -350,14 +350,12 @@ export class BranchGitCommand extends QuickCommand {
[
createFlagsQuickPickItem<CreateFlags>(state.flags, [], {
label: context.title,
detail: `Will create a new branch named ${state.name} from ${GitReference.toString(
state.reference,
)}`,
detail: `Will create a new branch named ${state.name} from ${getReferenceLabel(state.reference)}`,
}),
createFlagsQuickPickItem<CreateFlags>(state.flags, ['--switch'], {
label: `${context.title} and Switch`,
description: '--switch',
detail: `Will create and switch to a new branch named ${state.name} from ${GitReference.toString(
detail: `Will create and switch to a new branch named ${state.name} from ${getReferenceLabel(
state.reference,
)}`,
}),
@ -423,7 +421,7 @@ export class BranchGitCommand extends QuickCommand {
const confirmations: FlagsQuickPickItem<DeleteFlags>[] = [
createFlagsQuickPickItem<DeleteFlags>(state.flags, [], {
label: context.title,
detail: `Will delete ${GitReference.toString(state.references)}`,
detail: `Will delete ${getReferenceLabel(state.references)}`,
}),
];
if (!state.references.every(b => b.remote)) {
@ -431,7 +429,7 @@ export class BranchGitCommand extends QuickCommand {
createFlagsQuickPickItem<DeleteFlags>(state.flags, ['--force'], {
label: `Force ${context.title}`,
description: '--force',
detail: `Will forcibly delete ${GitReference.toString(state.references)}`,
detail: `Will forcibly delete ${getReferenceLabel(state.references)}`,
}),
);
@ -442,16 +440,14 @@ export class BranchGitCommand extends QuickCommand {
state.references.filter(b => !b.remote).length > 1 ? 's' : ''
}`,
description: '--remotes',
detail: `Will delete ${GitReference.toString(
state.references,
)} and any remote tracking branches`,
detail: `Will delete ${getReferenceLabel(state.references)} and any remote tracking branches`,
}),
createFlagsQuickPickItem<DeleteFlags>(state.flags, ['--force', '--remotes'], {
label: `Force ${context.title} & Remote${
state.references.filter(b => !b.remote).length > 1 ? 's' : ''
}`,
description: '--force --remotes',
detail: `Will forcibly delete ${GitReference.toString(
detail: `Will forcibly delete ${getReferenceLabel(
state.references,
)} and any remote tracking branches`,
}),
@ -488,10 +484,10 @@ export class BranchGitCommand extends QuickCommand {
if (state.counter < 4 || state.name == null) {
const result = yield* inputBranchNameStep(state, context, {
placeholder: `Please provide a new name for ${GitReference.toString(state.reference, {
placeholder: `Please provide a new name for ${getReferenceLabel(state.reference, {
icon: false,
})}`,
titleContext: ` ${GitReference.toString(state.reference, false)}`,
titleContext: ` ${getReferenceLabel(state.reference, false)}`,
value: state.name ?? state.reference.name,
});
if (result === StepResultBreak) continue;
@ -518,7 +514,7 @@ export class BranchGitCommand extends QuickCommand {
[
createFlagsQuickPickItem<RenameFlags>(state.flags, ['-m'], {
label: context.title,
detail: `Will rename ${GitReference.toString(state.reference)} to ${state.name}`,
detail: `Will rename ${getReferenceLabel(state.reference)} to ${state.name}`,
}),
],
context,

+ 12
- 9
src/commands/git/cherry-pick.ts View File

@ -1,7 +1,8 @@
import type { Container } from '../../container';
import type { GitBranch } from '../../git/models/branch';
import type { GitLog } from '../../git/models/log';
import { GitReference, GitRevision } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { createRevisionRange, getReferenceLabel, isRevisionReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
import { createFlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -138,7 +139,9 @@ export class CherryPickGitCommand extends QuickCommand {
context.destination = branch;
}
context.title = `${this.title} into ${GitReference.toString(context.destination, { icon: false })}`;
context.title = `${this.title} into ${getReferenceLabel(context.destination, {
icon: false,
})}`;
if (state.counter < 2 || state.references == null || state.references.length === 0) {
const result: StepResult<GitReference> = yield* pickBranchOrTagStep(
@ -161,7 +164,7 @@ export class CherryPickGitCommand extends QuickCommand {
continue;
}
if (GitReference.isRevision(result)) {
if (isRevisionReference(result)) {
state.references = [result];
context.selectedBranchOrTag = undefined;
} else {
@ -170,7 +173,7 @@ export class CherryPickGitCommand extends QuickCommand {
}
if (state.counter < 3 && context.selectedBranchOrTag != null) {
const ref = GitRevision.createRange(context.destination.ref, context.selectedBranchOrTag.ref);
const ref = createRevisionRange(context.destination.ref, context.selectedBranchOrTag.ref);
let log = context.cache.get(ref);
if (log == null) {
@ -187,10 +190,10 @@ export class CherryPickGitCommand extends QuickCommand {
picked: state.references?.map(r => r.ref),
placeholder: (context, log) =>
log == null
? `No pickable commits found on ${GitReference.toString(context.selectedBranchOrTag, {
? `No pickable commits found on ${getReferenceLabel(context.selectedBranchOrTag, {
icon: false,
})}`
: `Choose commits to cherry-pick into ${GitReference.toString(context.destination, {
: `Choose commits to cherry-pick into ${getReferenceLabel(context.destination, {
icon: false,
})}`,
},
@ -220,21 +223,21 @@ export class CherryPickGitCommand extends QuickCommand {
[
createFlagsQuickPickItem<Flags>(state.flags, [], {
label: this.title,
detail: `Will apply ${GitReference.toString(state.references)} to ${GitReference.toString(
detail: `Will apply ${getReferenceLabel(state.references)} to ${getReferenceLabel(
context.destination,
)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--edit'], {
label: `${this.title} & Edit`,
description: '--edit',
detail: `Will edit and apply ${GitReference.toString(state.references)} to ${GitReference.toString(
detail: `Will edit and apply ${getReferenceLabel(state.references)} to ${getReferenceLabel(
context.destination,
)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--no-commit'], {
label: `${this.title} without Committing`,
description: '--no-commit',
detail: `Will apply ${GitReference.toString(state.references)} to ${GitReference.toString(
detail: `Will apply ${getReferenceLabel(state.references)} to ${getReferenceLabel(
context.destination,
)} without Committing`,
}),

+ 4
- 4
src/commands/git/fetch.ts View File

@ -1,7 +1,7 @@
import { GlyphChars } from '../../constants';
import type { Container } from '../../container';
import type { GitBranchReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel, isBranchReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
import { createFlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -66,7 +66,7 @@ export class FetchGitCommand extends QuickCommand {
}
execute(state: FetchStepState) {
if (GitReference.isBranch(state.reference)) {
if (isBranchReference(state.reference)) {
return state.repos[0].fetch({ branch: state.reference });
}
@ -148,13 +148,13 @@ export class FetchGitCommand extends QuickCommand {
let step: QuickPickStep<FlagsQuickPickItem<Flags>>;
if (state.repos.length === 1 && GitReference.isBranch(state.reference)) {
if (state.repos.length === 1 && isBranchReference(state.reference)) {
step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context, lastFetchedOn),
[
createFlagsQuickPickItem<Flags>(state.flags, [], {
label: this.title,
detail: `Will fetch ${GitReference.toString(state.reference)}`,
detail: `Will fetch ${getReferenceLabel(state.reference)}`,
}),
],
);

+ 9
- 9
src/commands/git/log.ts View File

@ -3,7 +3,8 @@ import type { Container } from '../../container';
import { showDetailsView } from '../../git/actions/commit';
import { GitCommit } from '../../git/models/commit';
import type { GitLog } from '../../git/models/log';
import { GitReference } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { getReferenceLabel, isRevisionRangeReference, isRevisionReference } from '../../git/models/reference';
import { Repository } from '../../git/models/repository';
import { formatPath } from '../../system/formatPath';
import { pad } from '../../system/string';
@ -66,8 +67,8 @@ export class LogGitCommand extends QuickCommand {
counter++;
if (
args.state.reference !== 'HEAD' &&
GitReference.isRevision(args.state.reference) &&
!GitReference.isRevisionRange(args.state.reference)
isRevisionReference(args.state.reference) &&
!isRevisionRangeReference(args.state.reference)
) {
counter++;
}
@ -147,14 +148,13 @@ export class LogGitCommand extends QuickCommand {
context.selectedBranchOrTag = undefined;
}
if (!GitReference.isRevision(state.reference) || GitReference.isRevisionRange(state.reference)) {
if (!isRevisionReference(state.reference) || isRevisionRangeReference(state.reference)) {
context.selectedBranchOrTag = state.reference;
}
context.title = `${this.title}${pad(GlyphChars.Dot, 2, 2)}${GitReference.toString(
context.selectedBranchOrTag,
{ icon: false },
)}`;
context.title = `${this.title}${pad(GlyphChars.Dot, 2, 2)}${getReferenceLabel(context.selectedBranchOrTag, {
icon: false,
})}`;
if (state.fileName) {
context.title += `${pad(GlyphChars.Dot, 2, 2)}${formatPath(state.fileName, {
@ -181,7 +181,7 @@ export class LogGitCommand extends QuickCommand {
onDidLoadMore: log => context.cache.set(ref, Promise.resolve(log)),
placeholder: (context, log) =>
log == null
? `No commits found in ${GitReference.toString(context.selectedBranchOrTag, {
? `No commits found in ${getReferenceLabel(context.selectedBranchOrTag, {
icon: false,
})}`
: 'Choose a commit',

+ 20
- 19
src/commands/git/merge.ts View File

@ -1,7 +1,8 @@
import type { Container } from '../../container';
import type { GitBranch } from '../../git/models/branch';
import type { GitLog } from '../../git/models/log';
import { GitReference, GitRevision } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { createRevisionRange, getReferenceLabel, isRevisionReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { DirectiveQuickPickItem } from '../../quickpicks/items/directive';
import { createDirectiveQuickPickItem, Directive } from '../../quickpicks/items/directive';
@ -134,7 +135,9 @@ export class MergeGitCommand extends QuickCommand {
context.destination = branch;
}
context.title = `${this.title} into ${GitReference.toString(context.destination, { icon: false })}`;
context.title = `${this.title} into ${getReferenceLabel(context.destination, {
icon: false,
})}`;
context.pickCommitForItem = false;
if (state.counter < 2 || state.reference == null) {
@ -162,7 +165,7 @@ export class MergeGitCommand extends QuickCommand {
context.selectedBranchOrTag = undefined;
}
if (!GitReference.isRevision(state.reference)) {
if (!isRevisionReference(state.reference)) {
context.selectedBranchOrTag = state.reference;
}
@ -185,10 +188,10 @@ export class MergeGitCommand extends QuickCommand {
onDidLoadMore: log => context.cache.set(ref, Promise.resolve(log)),
placeholder: (context, log) =>
log == null
? `No commits found on ${GitReference.toString(context.selectedBranchOrTag, {
? `No commits found on ${getReferenceLabel(context.selectedBranchOrTag, {
icon: false,
})}`
: `Choose a commit to merge into ${GitReference.toString(context.destination, {
: `Choose a commit to merge into ${getReferenceLabel(context.destination, {
icon: false,
})}`,
picked: state.reference?.ref,
@ -212,7 +215,7 @@ export class MergeGitCommand extends QuickCommand {
private async *confirmStep(state: MergeStepState, context: Context): AsyncStepResultGenerator<Flags[]> {
const aheadBehind = await this.container.git.getAheadBehindCommitCount(state.repo.path, [
GitRevision.createRange(context.destination.name, state.reference.name),
createRevisionRange(context.destination.name, state.reference.name),
]);
const count = aheadBehind != null ? aheadBehind.ahead + aheadBehind.behind : 0;
if (count === 0) {
@ -221,9 +224,9 @@ export class MergeGitCommand extends QuickCommand {
[],
createDirectiveQuickPickItem(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: `${GitReference.toString(context.destination, {
detail: `${getReferenceLabel(context.destination, {
capitalize: true,
})} is up to date with ${GitReference.toString(state.reference)}`,
})} is up to date with ${getReferenceLabel(state.reference)}`,
}),
);
const selection: StepSelection<typeof step> = yield step;
@ -236,23 +239,23 @@ export class MergeGitCommand extends QuickCommand {
[
createFlagsQuickPickItem<Flags>(state.flags, [], {
label: this.title,
detail: `Will merge ${pluralize('commit', count)} from ${GitReference.toString(
detail: `Will merge ${pluralize('commit', count)} from ${getReferenceLabel(
state.reference,
)} into ${GitReference.toString(context.destination)}`,
)} into ${getReferenceLabel(context.destination)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--ff-only'], {
label: `Fast-forward ${this.title}`,
description: '--ff-only',
detail: `Will fast-forward merge ${pluralize('commit', count)} from ${GitReference.toString(
detail: `Will fast-forward merge ${pluralize('commit', count)} from ${getReferenceLabel(
state.reference,
)} into ${GitReference.toString(context.destination)}`,
)} into ${getReferenceLabel(context.destination)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--squash'], {
label: `Squash ${this.title}`,
description: '--squash',
detail: `Will squash ${pluralize('commit', count)} from ${GitReference.toString(
detail: `Will squash ${pluralize('commit', count)} from ${getReferenceLabel(
state.reference,
)} into one when merging into ${GitReference.toString(context.destination)}`,
)} into one when merging into ${getReferenceLabel(context.destination)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--no-ff'], {
label: `${this.title} without Fast-Forwarding`,
@ -260,16 +263,14 @@ export class MergeGitCommand extends QuickCommand {
detail: `Will create a merge commit when merging ${pluralize(
'commit',
count,
)} from ${GitReference.toString(state.reference)} into ${GitReference.toString(
context.destination,
)}`,
)} from ${getReferenceLabel(state.reference)} into ${getReferenceLabel(context.destination)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--no-ff', '--no-commit'], {
label: `${this.title} without Fast-Forwarding or Committing`,
description: '--no-ff --no-commit',
detail: `Will merge ${pluralize('commit', count)} from ${GitReference.toString(
detail: `Will merge ${pluralize('commit', count)} from ${getReferenceLabel(
state.reference,
)} into ${GitReference.toString(context.destination)} without Committing`,
)} into ${getReferenceLabel(context.destination)} without Committing`,
}),
],
);

+ 5
- 7
src/commands/git/pull.ts View File

@ -2,7 +2,7 @@ import { GlyphChars } from '../../constants';
import type { Container } from '../../container';
import { isBranch } from '../../git/models/branch';
import type { GitBranchReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel, isBranchReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import { createDirectiveQuickPickItem, Directive } from '../../quickpicks/items/directive';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -70,7 +70,7 @@ export class PullGitCommand extends QuickCommand {
}
async execute(state: PullStepState) {
if (GitReference.isBranch(state.reference)) {
if (isBranchReference(state.reference)) {
// Only resort to a branch fetch if the branch isn't the current one
if (!isBranch(state.reference) || !state.reference.current) {
const currentBranch = await state.repos[0].getBranch();
@ -159,7 +159,7 @@ export class PullGitCommand extends QuickCommand {
detail: `Will pull ${state.repos.length} repositories by rebasing`,
}),
]);
} else if (GitReference.isBranch(state.reference)) {
} else if (isBranchReference(state.reference)) {
if (state.reference.remote) {
step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),
@ -188,10 +188,8 @@ export class PullGitCommand extends QuickCommand {
label: this.title,
detail: `Will pull${
branch.state.behind
? ` ${pluralize('commit', branch.state.behind)} into ${GitReference.toString(
branch,
)}`
: ` into ${GitReference.toString(branch)}`
? ` ${pluralize('commit', branch.state.behind)} into ${getReferenceLabel(branch)}`
: ` into ${getReferenceLabel(branch)}`
}`,
}),
]);

+ 12
- 13
src/commands/git/push.ts View File

@ -2,8 +2,8 @@ import { configuration } from '../../configuration';
import { CoreGitConfiguration, GlyphChars } from '../../constants';
import type { Container } from '../../container';
import { getRemoteNameFromBranchName } from '../../git/models/branch';
import type { GitBranchReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import type { GitBranchReference, GitReference } from '../../git/models/reference';
import { getReferenceLabel, isBranchReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import { createDirectiveQuickPickItem, Directive } from '../../quickpicks/items/directive';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -74,7 +74,7 @@ export class PushGitCommand extends QuickCommand {
execute(state: State<Repository[]>) {
const index = state.flags.indexOf('--set-upstream');
if (index !== -1) {
if (!GitReference.isBranch(state.reference)) return Promise.resolve();
if (!isBranchReference(state.reference)) return Promise.resolve();
return this.container.git.pushAll(state.repos, {
force: false,
@ -183,7 +183,7 @@ export class PushGitCommand extends QuickCommand {
const items: FlagsQuickPickItem<Flags>[] = [];
if (GitReference.isBranch(state.reference)) {
if (isBranchReference(state.reference)) {
if (state.reference.remote) {
step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),
@ -204,7 +204,7 @@ export class PushGitCommand extends QuickCommand {
['--set-upstream', remote.name, branch.name],
{
label: `Publish ${branch.name} to ${remote.name}`,
detail: `Will publish ${GitReference.toString(branch)} to ${remote.name}`,
detail: `Will publish ${getReferenceLabel(branch)} to ${remote.name}`,
},
),
);
@ -248,7 +248,7 @@ export class PushGitCommand extends QuickCommand {
],
createDirectiveQuickPickItem(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: `Cannot push; ${GitReference.toString(
detail: `Cannot push; ${getReferenceLabel(
branch,
)} is behind ${branch.getRemoteName()} by ${pluralize('commit', branch.state.behind)}`,
}),
@ -257,10 +257,9 @@ export class PushGitCommand extends QuickCommand {
step = this.createConfirmStep(appendReposToTitle(`Confirm ${context.title}`, state, context), [
createFlagsQuickPickItem<Flags>(state.flags, [branch.getRemoteName()!], {
label: this.title,
detail: `Will push ${pluralize(
'commit',
branch.state.ahead,
)} from ${GitReference.toString(branch)} to ${branch.getRemoteName()}`,
detail: `Will push ${pluralize('commit', branch.state.ahead)} from ${getReferenceLabel(
branch,
)} to ${branch.getRemoteName()}`,
}),
]);
} else {
@ -296,7 +295,7 @@ export class PushGitCommand extends QuickCommand {
['--set-upstream', remote.name, status.branch],
{
label: `Publish ${branch.name} to ${remote.name}`,
detail: `Will publish ${GitReference.toString(branch)} to ${remote.name}`,
detail: `Will publish ${getReferenceLabel(branch)} to ${remote.name}`,
},
),
);
@ -344,7 +343,7 @@ export class PushGitCommand extends QuickCommand {
if (state.reference != null) {
pushDetails = `${
status?.state.ahead
? ` commits up to and including ${GitReference.toString(state.reference, {
? ` commits up to and including ${getReferenceLabel(state.reference, {
label: false,
})}`
: ''
@ -383,7 +382,7 @@ export class PushGitCommand extends QuickCommand {
status?.state.behind
? createDirectiveQuickPickItem(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: `Cannot push; ${GitReference.toString(branch)} is behind${
detail: `Cannot push; ${getReferenceLabel(branch)} is behind${
status?.upstream ? ` ${getRemoteNameFromBranchName(status.upstream)}` : ''
} by ${pluralize('commit', status.state.behind)}`,
})

+ 14
- 13
src/commands/git/rebase.ts View File

@ -1,7 +1,8 @@
import type { Container } from '../../container';
import type { GitBranch } from '../../git/models/branch';
import type { GitLog } from '../../git/models/log';
import { GitReference, GitRevision } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { createRevisionRange, getReferenceLabel, isRevisionReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { DirectiveQuickPickItem } from '../../quickpicks/items/directive';
import { createDirectiveQuickPickItem, Directive } from '../../quickpicks/items/directive';
@ -143,7 +144,7 @@ export class RebaseGitCommand extends QuickCommand {
context.destination = branch;
}
context.title = `${this.title} ${GitReference.toString(context.destination, { icon: false })}`;
context.title = `${this.title} ${getReferenceLabel(context.destination, { icon: false })}`;
context.pickCommitForItem = false;
if (state.counter < 2 || state.reference == null) {
@ -171,7 +172,7 @@ export class RebaseGitCommand extends QuickCommand {
context.selectedBranchOrTag = undefined;
}
if (!GitReference.isRevision(state.reference)) {
if (!isRevisionReference(state.reference)) {
context.selectedBranchOrTag = state.reference;
}
@ -194,10 +195,10 @@ export class RebaseGitCommand extends QuickCommand {
onDidLoadMore: log => context.cache.set(ref, Promise.resolve(log)),
placeholder: (context, log) =>
log == null
? `No commits found on ${GitReference.toString(context.selectedBranchOrTag, {
? `No commits found on ${getReferenceLabel(context.selectedBranchOrTag, {
icon: false,
})}`
: `Choose a commit to rebase ${GitReference.toString(context.destination, {
: `Choose a commit to rebase ${getReferenceLabel(context.destination, {
icon: false,
})} onto`,
picked: state.reference?.ref,
@ -222,8 +223,8 @@ export class RebaseGitCommand extends QuickCommand {
private async *confirmStep(state: RebaseStepState, context: Context): AsyncStepResultGenerator<Flags[]> {
const aheadBehind = await this.container.git.getAheadBehindCommitCount(state.repo.path, [
state.reference.refType === 'revision'
? GitRevision.createRange(state.reference.ref, context.destination.ref)
: GitRevision.createRange(context.destination.name, state.reference.name),
? createRevisionRange(state.reference.ref, context.destination.ref)
: createRevisionRange(context.destination.name, state.reference.name),
]);
const count = aheadBehind != null ? aheadBehind.ahead + aheadBehind.behind : 0;
@ -233,9 +234,9 @@ export class RebaseGitCommand extends QuickCommand {
[],
createDirectiveQuickPickItem(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: `${GitReference.toString(context.destination, {
detail: `${getReferenceLabel(context.destination, {
capitalize: true,
})} is up to date with ${GitReference.toString(state.reference)}`,
})} is up to date with ${getReferenceLabel(state.reference)}`,
}),
);
const selection: StepSelection<typeof step> = yield step;
@ -248,17 +249,17 @@ export class RebaseGitCommand extends QuickCommand {
[
createFlagsQuickPickItem<Flags>(state.flags, [], {
label: this.title,
detail: `Will update ${GitReference.toString(context.destination)} by applying ${pluralize(
detail: `Will update ${getReferenceLabel(context.destination)} by applying ${pluralize(
'commit',
count,
)} on top of ${GitReference.toString(state.reference)}`,
)} on top of ${getReferenceLabel(state.reference)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--interactive'], {
label: `Interactive ${this.title}`,
description: '--interactive',
detail: `Will interactively update ${GitReference.toString(
detail: `Will interactively update ${getReferenceLabel(
context.destination,
)} by applying ${pluralize('commit', count)} on top of ${GitReference.toString(state.reference)}`,
)} by applying ${pluralize('commit', count)} on top of ${getReferenceLabel(state.reference)}`,
}),
],
);

+ 9
- 9
src/commands/git/reset.ts View File

@ -1,8 +1,8 @@
import type { Container } from '../../container';
import type { GitBranch } from '../../git/models/branch';
import type { GitLog } from '../../git/models/log';
import type { GitRevisionReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import type { GitReference, GitRevisionReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
import { createFlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -123,7 +123,7 @@ export class ResetGitCommand extends QuickCommand {
context.destination = branch;
}
context.title = `${this.title} ${GitReference.toString(context.destination, { icon: false })}`;
context.title = `${this.title} ${getReferenceLabel(context.destination, { icon: false })}`;
if (state.counter < 2 || state.reference == null) {
const ref = context.destination.ref;
@ -175,23 +175,23 @@ export class ResetGitCommand extends QuickCommand {
[
createFlagsQuickPickItem<Flags>(state.flags, [], {
label: this.title,
detail: `Will reset (leaves changes in the working tree) ${GitReference.toString(
detail: `Will reset (leaves changes in the working tree) ${getReferenceLabel(
context.destination,
)} to ${GitReference.toString(state.reference)}`,
)} to ${getReferenceLabel(state.reference)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--soft'], {
label: `Soft ${this.title}`,
description: '--soft',
detail: `Will soft reset (leaves changes in the index and working tree) ${GitReference.toString(
detail: `Will soft reset (leaves changes in the index and working tree) ${getReferenceLabel(
context.destination,
)} to ${GitReference.toString(state.reference)}`,
)} to ${getReferenceLabel(state.reference)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--hard'], {
label: `Hard ${this.title}`,
description: '--hard',
detail: `Will hard reset (discards all changes) ${GitReference.toString(
detail: `Will hard reset (discards all changes) ${getReferenceLabel(
context.destination,
)} to ${GitReference.toString(state.reference)}`,
)} to ${getReferenceLabel(state.reference)}`,
}),
],
);

+ 3
- 3
src/commands/git/revert.ts View File

@ -2,7 +2,7 @@ import type { Container } from '../../container';
import type { GitBranch } from '../../git/models/branch';
import type { GitLog } from '../../git/models/log';
import type { GitRevisionReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
import { createFlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -180,12 +180,12 @@ export class RevertGitCommand extends QuickCommand {
createFlagsQuickPickItem<Flags>(state.flags, ['--no-edit'], {
label: this.title,
description: '--no-edit',
detail: `Will revert ${GitReference.toString(state.references)}`,
detail: `Will revert ${getReferenceLabel(state.references)}`,
}),
createFlagsQuickPickItem<Flags>(state.flags, ['--edit'], {
label: `${this.title} & Edit`,
description: '--edit',
detail: `Will revert and edit ${GitReference.toString(state.references)}`,
detail: `Will revert and edit ${getReferenceLabel(state.references)}`,
}),
],
);

+ 6
- 10
src/commands/git/stash.ts View File

@ -7,7 +7,7 @@ import { reveal, showDetailsView } from '../../git/actions/stash';
import { StashApplyError, StashApplyErrorReason } from '../../git/errors';
import type { GitStashCommit } from '../../git/models/commit';
import type { GitStashReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import { Logger } from '../../logger';
import { showGenericErrorMessage } from '../../messages';
@ -348,12 +348,10 @@ export class StashGitCommand extends QuickCommand {
label: context.title,
detail:
state.subcommand === 'pop'
? `Will delete ${GitReference.toString(
? `Will delete ${getReferenceLabel(
state.reference,
)} and apply the changes to the working tree`
: `Will apply the changes from ${GitReference.toString(
state.reference,
)} to the working tree`,
: `Will apply the changes from ${getReferenceLabel(state.reference)} to the working tree`,
item: state.subcommand,
},
// Alternate confirmation (if pop then apply, and vice versa)
@ -361,10 +359,8 @@ export class StashGitCommand extends QuickCommand {
label: getTitle(this.title, state.subcommand === 'pop' ? 'apply' : 'pop'),
detail:
state.subcommand === 'pop'
? `Will apply the changes from ${GitReference.toString(
state.reference,
)} to the working tree`
: `Will delete ${GitReference.toString(
? `Will apply the changes from ${getReferenceLabel(state.reference)} to the working tree`
: `Will delete ${getReferenceLabel(
state.reference,
)} and apply the changes to the working tree`,
item: state.subcommand === 'pop' ? 'apply' : 'pop',
@ -431,7 +427,7 @@ export class StashGitCommand extends QuickCommand {
[
{
label: context.title,
detail: `Will delete ${GitReference.toString(state.reference)}`,
detail: `Will delete ${getReferenceLabel(state.reference)}`,
},
],
undefined,

+ 3
- 3
src/commands/git/status.ts View File

@ -1,6 +1,6 @@
import { GlyphChars } from '../../constants';
import type { Container } from '../../container';
import { GitReference } from '../../git/models/reference';
import { createReference, getReferenceLabel } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { GitStatus } from '../../git/models/status';
import { CommandQuickPickItem } from '../../quickpicks/items/common';
@ -84,8 +84,8 @@ export class StatusGitCommand extends QuickCommand {
context.status = (await state.repo.getStatus())!;
if (context.status == null) return;
context.title = `${this.title}${pad(GlyphChars.Dot, 2, 2)}${GitReference.toString(
GitReference.create(context.status.branch, state.repo.path, {
context.title = `${this.title}${pad(GlyphChars.Dot, 2, 2)}${getReferenceLabel(
createReference(context.status.branch, state.repo.path, {
refType: 'branch',
name: context.status.branch,
remote: false,

+ 12
- 11
src/commands/git/switch.ts View File

@ -1,7 +1,8 @@
import { ProgressLocation, window } from 'vscode';
import { BranchSorting } from '../../config';
import type { Container } from '../../container';
import { GitReference } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { getNameWithoutRemote, getReferenceLabel, isBranchReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { QuickPickItemOfT } from '../../quickpicks/items/common';
import { isStringArray } from '../../system/array';
@ -155,7 +156,7 @@ export class SwitchGitCommand extends QuickCommand {
state.reference = result;
}
if (GitReference.isBranch(state.reference) && state.reference.remote) {
if (isBranchReference(state.reference) && state.reference.remote) {
context.title = `Create Branch and ${this.title}`;
const { values: branches } = await this.container.git.getBranches(state.reference.repoPath, {
@ -166,10 +167,10 @@ export class SwitchGitCommand extends QuickCommand {
if (branches.length === 0) {
const result = yield* inputBranchNameStep(state as SwitchStepState, context, {
placeholder: 'Please provide a name for the new branch',
titleContext: ` based on ${GitReference.toString(state.reference, {
titleContext: ` based on ${getReferenceLabel(state.reference, {
icon: false,
})}`,
value: state.createBranch ?? GitReference.getNameWithoutRemote(state.reference),
value: state.createBranch ?? getNameWithoutRemote(state.reference),
});
if (result === StepResultBreak) continue;
@ -207,9 +208,9 @@ export class SwitchGitCommand extends QuickCommand {
{
label: `${context.title} and Fast-Forward`,
description: '',
detail: `Will switch to and fast-forward local ${GitReference.toString(
state.reference,
)} in $(repo) ${state.repos[0].formattedName}`,
detail: `Will switch to and fast-forward local ${getReferenceLabel(state.reference)} in $(repo) ${
state.repos[0].formattedName
}`,
item: 'switch+fast-forward',
},
];
@ -227,10 +228,10 @@ export class SwitchGitCommand extends QuickCommand {
description: state.createBranch ? '-b' : '',
detail: `Will ${
state.createBranch
? `create and switch to a new branch named ${
state.createBranch
} from ${GitReference.toString(state.reference)}`
: `switch to ${context.switchToLocalFrom != null ? 'local ' : ''}${GitReference.toString(
? `create and switch to a new branch named ${state.createBranch} from ${getReferenceLabel(
state.reference,
)}`
: `switch to ${context.switchToLocalFrom != null ? 'local ' : ''}${getReferenceLabel(
state.reference,
)}`
} in ${

+ 15
- 9
src/commands/git/tag.ts View File

@ -1,8 +1,8 @@
import type { QuickPickItem } from 'vscode';
import { QuickInputButtons } from 'vscode';
import type { Container } from '../../container';
import type { GitTagReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import type { GitReference, GitTagReference } from '../../git/models/reference';
import { getNameWithoutRemote, getReferenceLabel, isRevisionReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import type { QuickPickItemOfT } from '../../quickpicks/items/common';
import type { FlagsQuickPickItem } from '../../quickpicks/items/flags';
@ -242,7 +242,7 @@ export class TagGitCommand extends QuickCommand {
`Choose a branch${context.showTags ? ' or tag' : ''} to create the new tag from`,
picked: state.reference?.ref ?? (await state.repo.getBranch())?.ref,
titleContext: ' from',
value: GitReference.isRevision(state.reference) ? state.reference.ref : undefined,
value: isRevisionReference(state.reference) ? state.reference.ref : undefined,
});
// Always break on the first step (so we will go back)
if (result === StepResultBreak) break;
@ -253,8 +253,11 @@ export class TagGitCommand extends QuickCommand {
if (state.counter < 4 || state.name == null) {
const result = yield* inputTagNameStep(state, context, {
placeholder: 'Please provide a name for the new tag',
titleContext: ` at ${GitReference.toString(state.reference, { capitalize: true, icon: false })}`,
value: state.name ?? GitReference.getNameWithoutRemote(state.reference),
titleContext: ` at ${getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
})}`,
value: state.name ?? getNameWithoutRemote(state.reference),
});
if (result === StepResultBreak) continue;
@ -295,7 +298,10 @@ export class TagGitCommand extends QuickCommand {
): AsyncStepResultGenerator<string> {
const step = createInputStep({
title: appendReposToTitle(
`${context.title} at ${GitReference.toString(state.reference, { capitalize: true, icon: false })}`,
`${context.title} at ${getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
})}`,
state,
context,
),
@ -323,7 +329,7 @@ export class TagGitCommand extends QuickCommand {
createFlagsQuickPickItem<CreateFlags>(state.flags, state.message.length !== 0 ? ['-m'] : [], {
label: context.title,
description: state.message.length !== 0 ? '-m' : '',
detail: `Will create a new tag named ${state.name} at ${GitReference.toString(state.reference)}`,
detail: `Will create a new tag named ${state.name} at ${getReferenceLabel(state.reference)}`,
}),
createFlagsQuickPickItem<CreateFlags>(
state.flags,
@ -331,7 +337,7 @@ export class TagGitCommand extends QuickCommand {
{
label: `Force ${context.title}`,
description: `--force${state.message.length !== 0 ? ' -m' : ''}`,
detail: `Will forcibly create a new tag named ${state.name} at ${GitReference.toString(
detail: `Will forcibly create a new tag named ${state.name} at ${getReferenceLabel(
state.reference,
)}`,
},
@ -381,7 +387,7 @@ export class TagGitCommand extends QuickCommand {
[
{
label: context.title,
detail: `Will delete ${GitReference.toString(state.references)}`,
detail: `Will delete ${getReferenceLabel(state.references)}`,
},
],
context,

+ 10
- 9
src/commands/git/worktree.ts View File

@ -11,7 +11,8 @@ import {
WorktreeDeleteError,
WorktreeDeleteErrorReason,
} from '../../git/errors';
import { GitReference } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { getNameWithoutRemote, getReferenceLabel, isRevisionReference } from '../../git/models/reference';
import type { Repository } from '../../git/models/repository';
import { GitWorktree } from '../../git/models/worktree';
import { showGenericErrorMessage } from '../../messages';
@ -310,7 +311,7 @@ export class WorktreeGitCommand extends QuickCommand {
`Choose a branch${context.showTags ? ' or tag' : ''} to create the new worktree for`,
picked: state.reference?.ref ?? (await state.repo.getBranch())?.ref,
titleContext: ' for',
value: GitReference.isRevision(state.reference) ? state.reference.ref : undefined,
value: isRevisionReference(state.reference) ? state.reference.ref : undefined,
});
// Always break on the first step (so we will go back)
if (result === StepResultBreak) break;
@ -327,7 +328,7 @@ export class WorktreeGitCommand extends QuickCommand {
state.uri = context.defaultUri;
} else {
const result = yield* this.createCommandChoosePathStep(state, context, {
titleContext: ` for ${GitReference.toString(state.reference, {
titleContext: ` for ${getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
label: state.reference.refType !== 'branch',
@ -356,18 +357,18 @@ export class WorktreeGitCommand extends QuickCommand {
const isRemoteBranch = state.reference?.refType === 'branch' && state.reference?.remote;
if (isRemoteBranch && !state.flags.includes('-b')) {
state.flags.push('-b');
state.createBranch = GitReference.getNameWithoutRemote(state.reference);
state.createBranch = getNameWithoutRemote(state.reference);
}
if (state.flags.includes('-b') && state.createBranch == null) {
const result = yield* inputBranchNameStep(state, context, {
placeholder: 'Please provide a name for the new branch',
titleContext: ` from ${GitReference.toString(state.reference, {
titleContext: ` from ${getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
label: state.reference.refType !== 'branch',
})}`,
value: state.createBranch ?? GitReference.getNameWithoutRemote(state.reference),
value: state.createBranch ?? getNameWithoutRemote(state.reference),
});
if (result === StepResultBreak) {
// Clear the flags, since we can backup after the confirm step below (which is non-standard)
@ -409,7 +410,7 @@ export class WorktreeGitCommand extends QuickCommand {
const force: MessageItem = { title: 'Create Anyway' };
const cancel: MessageItem = { title: 'Cancel', isCloseAffordance: true };
const result = await window.showWarningMessage(
`Unable to create the new worktree because ${GitReference.toString(state.reference, {
`Unable to create the new worktree because ${getReferenceLabel(state.reference, {
icon: false,
quoted: true,
})} is already checked out.\n\nWould you like to create a new branch for this worktree or forcibly create it anyway?`,
@ -569,7 +570,7 @@ export class WorktreeGitCommand extends QuickCommand {
state.reference != null
? Uri.joinPath(
recommendedRootUri,
...GitReference.getNameWithoutRemote(state.reference).replace(/\\/g, '/').split('/'),
...getNameWithoutRemote(state.reference).replace(/\\/g, '/').split('/'),
)
: recommendedRootUri;
const recommendedFriendlyPath = truncateLeft(GitWorktree.getFriendlyPath(recommendedUri), 65);
@ -583,7 +584,7 @@ export class WorktreeGitCommand extends QuickCommand {
const step: QuickPickStep<FlagsQuickPickItem<CreateFlags, Uri>> = createConfirmStep(
appendReposToTitle(
`Confirm ${context.title} \u2022 ${GitReference.toString(state.reference, {
`Confirm ${context.title} \u2022 ${getReferenceLabel(state.reference, {
icon: false,
label: false,
})}`,

+ 2
- 2
src/commands/openCommitOnRemote.ts View File

@ -2,7 +2,7 @@ import type { TextEditor, Uri } from 'vscode';
import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { deletedOrMissing } from '../git/models/constants';
import { RemoteResourceType } from '../git/models/remoteResource';
import { Logger } from '../logger';
import { showFileNotUnderSourceControlWarningMessage, showGenericErrorMessage } from '../messages';
@ -91,7 +91,7 @@ export class OpenCommitOnRemoteCommand extends ActiveEditorCommand {
// If the line is uncommitted, use previous commit
args.sha = blame.commit.isUncommitted
? (await blame.commit.getPreviousSha()) ?? GitRevision.deletedOrMissing
? (await blame.commit.getPreviousSha()) ?? deletedOrMissing
: blame.commit.sha;
}

+ 2
- 2
src/commands/openFileAtRevision.ts View File

@ -5,7 +5,7 @@ import { Commands, GlyphChars, quickPickTitleMaxChars } from '../constants';
import type { Container } from '../container';
import { openFileAtRevision } from '../git/actions/commit';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { shortenRevision } from '../git/models/reference';
import { Logger } from '../logger';
import { showCommitHasNoPreviousCommitWarningMessage, showGenericErrorMessage } from '../messages';
import { showCommitPicker } from '../quickpicks/commitPicker';
@ -125,7 +125,7 @@ export class OpenFileAtRevisionCommand extends ActiveEditorCommand {
const pick = await showCommitPicker(
log,
`${title}${gitUri.getFormattedFileName({
suffix: gitUri.sha ? `:${GitRevision.shorten(gitUri.sha)}` : undefined,
suffix: gitUri.sha ? `:${shortenRevision(gitUri.sha)}` : undefined,
truncateTo: quickPickTitleMaxChars - title.length,
})}`,
`Choose a commit to ${

+ 2
- 2
src/commands/openFileOnRemote.ts View File

@ -6,7 +6,7 @@ import { Commands, GlyphChars } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { getBranchNameWithoutRemote, getRemoteNameFromBranchName } from '../git/models/branch';
import { GitRevision } from '../git/models/reference';
import { isSha } from '../git/models/reference';
import { RemoteResourceType } from '../git/models/remoteResource';
import { Logger } from '../logger';
import { showGenericErrorMessage } from '../messages';
@ -128,7 +128,7 @@ export class OpenFileOnRemoteCommand extends ActiveEditorCommand {
: undefined;
let sha = args.sha ?? gitUri.sha;
if (args.branchOrTag == null && sha != null && !GitRevision.isSha(sha) && remotes.length !== 0) {
if (args.branchOrTag == null && sha != null && !isSha(sha) && remotes.length !== 0) {
const [remoteName, branchName] = splitSingle(sha, '/');
if (branchName != null) {
const remote = remotes.find(r => r.name === remoteName);

+ 5
- 5
src/commands/openOnRemote.ts View File

@ -1,6 +1,6 @@
import { Commands, GlyphChars } from '../constants';
import type { Container } from '../container';
import { GitRevision } from '../git/models/reference';
import { createRevisionRange, shortenRevision } from '../git/models/reference';
import { GitRemote } from '../git/models/remote';
import type { RemoteResource } from '../git/models/remoteResource';
import { RemoteResourceType } from '../git/models/remoteResource';
@ -102,13 +102,13 @@ export class OpenOnRemoteCommand extends Command {
break;
case RemoteResourceType.Commit:
title = `${getTitlePrefix('Commit')}${pad(GlyphChars.Dot, 2, 2)}${GitRevision.shorten(
title = `${getTitlePrefix('Commit')}${pad(GlyphChars.Dot, 2, 2)}${shortenRevision(
args.resource.sha,
)}`;
break;
case RemoteResourceType.Comparison:
title = `${getTitlePrefix('Comparison')}${pad(GlyphChars.Dot, 2, 2)}${GitRevision.createRange(
title = `${getTitlePrefix('Comparison')}${pad(GlyphChars.Dot, 2, 2)}${createRevisionRange(
args.resource.base,
args.resource.compare,
args.resource.notation ?? '...',
@ -125,7 +125,7 @@ export class OpenOnRemoteCommand extends Command {
: `Create Pull Request on ${provider}`
}${pad(GlyphChars.Dot, 2, 2)}${
args.resource.base?.branch
? GitRevision.createRange(args.resource.base.branch, args.resource.compare.branch, '...')
? createRevisionRange(args.resource.base.branch, args.resource.compare.branch, '...')
: args.resource.compare.branch
}`;
@ -143,7 +143,7 @@ export class OpenOnRemoteCommand extends Command {
break;
case RemoteResourceType.Revision: {
title = `${getTitlePrefix('File')}${pad(GlyphChars.Dot, 2, 2)}${GitRevision.shorten(
title = `${getTitlePrefix('File')}${pad(GlyphChars.Dot, 2, 2)}${shortenRevision(
args.resource.sha,
)}${pad(GlyphChars.Dot, 1, 1)}${args.resource.fileName}`;
break;

+ 2
- 2
src/commands/openRevisionFile.ts View File

@ -4,7 +4,7 @@ import { Commands } from '../constants';
import type { Container } from '../container';
import { openFileAtRevision } from '../git/actions/commit';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { deletedOrMissing } from '../git/models/constants';
import { Logger } from '../logger';
import { showGenericErrorMessage } from '../messages';
import { command } from '../system/command';
@ -43,7 +43,7 @@ export class OpenRevisionFileCommand extends ActiveEditorCommand {
args.revisionUri =
commit?.file?.status === 'D'
? this.container.git.getRevisionUri(
(await commit.getPreviousSha()) ?? GitRevision.deletedOrMissing,
(await commit.getPreviousSha()) ?? deletedOrMissing,
commit.file,
commit.repoPath,
)

+ 42
- 33
src/commands/quickCommand.steps.ts View File

@ -18,8 +18,17 @@ import type { GitCommit, GitStashCommit } from '../git/models/commit';
import { isCommit, isStash } from '../git/models/commit';
import type { GitContributor } from '../git/models/contributor';
import type { GitLog } from '../git/models/log';
import type { GitBranchReference, GitRevisionReference, GitTagReference } from '../git/models/reference';
import { GitReference, GitRevision } from '../git/models/reference';
import type { GitBranchReference, GitReference, GitRevisionReference, GitTagReference } from '../git/models/reference';
import {
createReference,
createRevisionRange,
getReferenceLabel,
isBranchReference,
isRevisionRange,
isRevisionReference,
isStashReference,
isTagReference,
} from '../git/models/reference';
import { GitRemote } from '../git/models/remote';
import { RemoteResourceType } from '../git/models/remoteResource';
import { Repository } from '../git/models/repository';
@ -443,7 +452,7 @@ export function getValidateGitReferenceFn(
repos = repos[0];
}
if (inRefMode && options?.ranges && GitRevision.isRange(value)) {
if (inRefMode && options?.ranges && isRevisionRange(value)) {
quickpick.items = [
createRefQuickPickItem(value, repos.path, true, {
alwaysShow: true,
@ -827,11 +836,11 @@ export async function* pickBranchOrTagStep<
}
if (button === RevealInSideBarQuickInputButton) {
if (GitReference.isBranch(item)) {
if (isBranchReference(item)) {
void BranchActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isTag(item)) {
} else if (isTagReference(item)) {
void TagActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isRevision(item)) {
} else if (isRevisionReference(item)) {
void CommitActions.showDetailsView(item, { pin: false, preserveFocus: true });
}
}
@ -863,11 +872,11 @@ export async function* pickBranchOrTagStep<
if (quickpick.activeItems.length === 0) return;
const item = quickpick.activeItems[0].item;
if (GitReference.isBranch(item)) {
if (isBranchReference(item)) {
void BranchActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isTag(item)) {
} else if (isTagReference(item)) {
void TagActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isRevision(item)) {
} else if (isRevisionReference(item)) {
void CommitActions.showDetailsView(item, { pin: false, preserveFocus: true });
}
},
@ -926,7 +935,7 @@ export async function* pickBranchOrTagStepMultiRepo<
)}(or enter a reference using #)`,
matchOnDescription: true,
matchOnDetail: true,
value: value ?? (GitReference.isRevision(state.reference) ? state.reference.ref : undefined),
value: value ?? (isRevisionReference(state.reference) ? state.reference.ref : undefined),
selectValueWhenShown: true,
items:
branchesAndOrTags.length === 0
@ -935,11 +944,11 @@ export async function* pickBranchOrTagStepMultiRepo<
additionalButtons: [showTagsButton],
onDidClickItemButton: (quickpick, button, { item }) => {
if (button === RevealInSideBarQuickInputButton) {
if (GitReference.isBranch(item)) {
if (isBranchReference(item)) {
void BranchActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isTag(item)) {
} else if (isTagReference(item)) {
void TagActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isRevision(item)) {
} else if (isRevisionReference(item)) {
void CommitActions.showDetailsView(item, { pin: false, preserveFocus: true });
}
}
@ -976,11 +985,11 @@ export async function* pickBranchOrTagStepMultiRepo<
if (quickpick.activeItems.length === 0) return;
const item = quickpick.activeItems[0].item;
if (GitReference.isBranch(item)) {
if (isBranchReference(item)) {
void BranchActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isTag(item)) {
} else if (isTagReference(item)) {
void TagActions.reveal(item, { select: true, focus: false, expand: true });
} else if (GitReference.isRevision(item)) {
} else if (isRevisionReference(item)) {
void CommitActions.showDetailsView(item, { pin: false, preserveFocus: true });
}
},
@ -1733,21 +1742,21 @@ export async function* showCommitOrStashStep<
const step: QuickPickStep<CommitFilesQuickPickItem | GitCommandQuickPickItem | CommandQuickPickItem> =
createPickStep({
title: appendReposToTitle(
GitReference.toString(state.reference, {
getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
}),
state,
context,
),
placeholder: GitReference.toString(state.reference, { capitalize: true, icon: false }),
placeholder: getReferenceLabel(state.reference, { capitalize: true, icon: false }),
ignoreFocusOut: true,
items: await getShowCommitOrStashStepItems(state),
// additionalButtons: [ShowDetailsView, RevealInSideBar],
onDidClickItemButton: (quickpick, button, _item) => {
switch (button) {
case ShowDetailsViewQuickInputButton:
if (GitReference.isStash(state.reference)) {
if (isStashReference(state.reference)) {
void StashActions.showDetailsView(state.reference, { pin: false, preserveFocus: true });
} else {
void CommitActions.showDetailsView(state.reference, {
@ -1757,7 +1766,7 @@ export async function* showCommitOrStashStep<
}
break;
case RevealInSideBarQuickInputButton:
if (GitReference.isStash(state.reference)) {
if (isStashReference(state.reference)) {
void StashActions.reveal(state.reference, {
select: true,
focus: false,
@ -1882,7 +1891,7 @@ async function getShowCommitOrStashStepItems<
command: 'reset',
state: {
repo: state.repo,
reference: GitReference.create(`${state.reference.ref}^`, state.reference.repoPath, {
reference: createReference(`${state.reference.ref}^`, state.reference.repoPath, {
refType: 'revision',
name: `${state.reference.name}^`,
message: state.reference.message,
@ -2007,14 +2016,14 @@ export function* showCommitOrStashFilesStep<
const step: QuickPickStep<CommitFilesQuickPickItem | CommitFileQuickPickItem> = createPickStep({
title: appendReposToTitle(
GitReference.toString(state.reference, {
getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
}),
state,
context,
),
placeholder: GitReference.toString(state.reference, { capitalize: true, icon: false }),
placeholder: getReferenceLabel(state.reference, { capitalize: true, icon: false }),
ignoreFocusOut: true,
items: [
new CommitFilesQuickPickItem(state.reference, {
@ -2031,7 +2040,7 @@ export function* showCommitOrStashFilesStep<
onDidClickItemButton: (quickpick, button, _item) => {
switch (button) {
case ShowDetailsViewQuickInputButton:
if (GitReference.isStash(state.reference)) {
if (isStashReference(state.reference)) {
void StashActions.showDetailsView(state.reference, { pin: false, preserveFocus: true });
} else {
void CommitActions.showDetailsView(state.reference, {
@ -2041,7 +2050,7 @@ export function* showCommitOrStashFilesStep<
}
break;
case RevealInSideBarQuickInputButton:
if (GitReference.isStash(state.reference)) {
if (isStashReference(state.reference)) {
void StashActions.reveal(state.reference, {
select: true,
focus: false,
@ -2078,7 +2087,7 @@ export async function* showCommitOrStashFileStep<
>(state: State, context: Context): AsyncStepResultGenerator<CommandQuickPickItem> {
const step: QuickPickStep<CommandQuickPickItem> = createPickStep<CommandQuickPickItem>({
title: appendReposToTitle(
GitReference.toString(state.reference, {
getReferenceLabel(state.reference, {
capitalize: true,
icon: false,
}),
@ -2088,7 +2097,7 @@ export async function* showCommitOrStashFileStep<
),
placeholder: `${formatPath(state.fileName, {
relativeTo: state.repo.path,
})} in ${GitReference.toString(state.reference, {
})} in ${getReferenceLabel(state.reference, {
icon: false,
})}`,
ignoreFocusOut: true,
@ -2098,7 +2107,7 @@ export async function* showCommitOrStashFileStep<
onDidClickItemButton: (quickpick, button, _item) => {
switch (button) {
case ShowDetailsViewQuickInputButton:
if (GitReference.isStash(state.reference)) {
if (isStashReference(state.reference)) {
void StashActions.showDetailsView(state.reference, { pin: false, preserveFocus: true });
} else {
void CommitActions.showDetailsView(state.reference, {
@ -2108,7 +2117,7 @@ export async function* showCommitOrStashFileStep<
}
break;
case RevealInSideBarQuickInputButton:
if (GitReference.isStash(state.reference)) {
if (isStashReference(state.reference)) {
void StashActions.reveal(state.reference, {
select: true,
focus: false,
@ -2322,8 +2331,8 @@ function getShowRepositoryStatusStepItems<
command: 'log',
state: {
repo: state.repo,
reference: GitReference.create(
GitRevision.createRange(context.status.ref, context.status.upstream),
reference: createReference(
createRevisionRange(context.status.ref, context.status.upstream),
state.repo.path,
),
},
@ -2340,8 +2349,8 @@ function getShowRepositoryStatusStepItems<
command: 'log',
state: {
repo: state.repo,
reference: GitReference.create(
GitRevision.createRange(context.status.upstream, context.status.ref),
reference: createReference(
createRevisionRange(context.status.upstream, context.status.ref),
state.repo.path,
),
},

+ 2
- 2
src/commands/showCommitsInView.ts View File

@ -4,7 +4,7 @@ import type { Container } from '../container';
import { executeGitCommand } from '../git/actions';
import { showDetailsView } from '../git/actions/commit';
import { GitUri } from '../git/gitUri';
import { GitReference } from '../git/models/reference';
import { createReference } from '../git/models/reference';
import { createSearchQueryForCommits } from '../git/search';
import { Logger } from '../logger';
import { showFileNotUnderSourceControlWarningMessage, showGenericErrorMessage } from '../messages';
@ -81,7 +81,7 @@ export class ShowCommitsInViewCommand extends ActiveEditorCommand {
}
if (args.refs.length === 1) {
return showDetailsView(GitReference.create(args.refs[0], args.repoPath!, { refType: 'revision' }));
return showDetailsView(createReference(args.refs[0], args.repoPath!, { refType: 'revision' }));
}
return executeGitCommand({

+ 4
- 3
src/commands/showQuickBranchHistory.ts View File

@ -3,7 +3,8 @@ import { Commands } from '../constants';
import type { Container } from '../container';
import { executeGitCommand } from '../git/actions';
import { GitUri } from '../git/gitUri';
import { GitReference } from '../git/models/reference';
import type { GitReference } from '../git/models/reference';
import { createReference } from '../git/models/reference';
import { command } from '../system/command';
import type { CommandContext } from './base';
import { ActiveEditorCachedCommand, getCommandUri } from './base';
@ -41,13 +42,13 @@ export class ShowQuickBranchHistoryCommand extends ActiveEditorCachedCommand {
ref =
args.branch === 'HEAD'
? 'HEAD'
: GitReference.create(args.branch, repoPath, {
: createReference(args.branch, repoPath, {
refType: 'branch',
name: args.branch,
remote: false,
});
} else if (args?.tag != null) {
ref = GitReference.create(args.tag, repoPath, { refType: 'tag', name: args.tag });
ref = createReference(args.tag, repoPath, { refType: 'tag', name: args.tag });
}
}

+ 1
- 1
src/commands/showQuickCommitFile.ts View File

@ -142,7 +142,7 @@ export class ShowQuickCommitFileCommand extends ActiveEditorCachedCommand {
}
}
// const shortSha = GitRevision.shorten(args.sha);
// const shortSha = shorten(args.sha);
// if (args.commit instanceof GitBlameCommit) {
// args.commit = (await this.container.git.getCommit(args.commit.repoPath, args.commit.ref))!;

+ 13
- 13
src/env/node/git/git.ts View File

@ -8,7 +8,7 @@ import { GlyphChars, LogLevel, slowCallWarningThreshold } from '../../../constan
import type { GitCommandOptions, GitSpawnOptions } from '../../../git/commandOptions';
import { GitErrorHandling } from '../../../git/commandOptions';
import type { GitDiffFilter } from '../../../git/models/diff';
import { GitRevision } from '../../../git/models/reference';
import { isUncommitted, isUncommittedStaged, shortenRevision } from '../../../git/models/reference';
import type { GitUser } from '../../../git/models/user';
import { GitBranchParser } from '../../../git/parsers/branchParser';
import { GitLogParser } from '../../../git/parsers/logParser';
@ -378,7 +378,7 @@ export class Git {
let stdin;
if (ref) {
if (GitRevision.isUncommittedStaged(ref)) {
if (isUncommittedStaged(ref)) {
// Pipe the blame contents to stdin
params.push('--contents', '-');
@ -565,10 +565,10 @@ export class Git {
if (ref1.endsWith('^3^')) {
ref1 = rootSha;
}
params.push(GitRevision.isUncommittedStaged(ref1) ? '--staged' : ref1);
params.push(isUncommittedStaged(ref1) ? '--staged' : ref1);
}
if (ref2) {
params.push(GitRevision.isUncommittedStaged(ref2) ? '--staged' : ref2);
params.push(isUncommittedStaged(ref2) ? '--staged' : ref2);
}
try {
@ -620,7 +620,7 @@ export class Git {
// if (ref.endsWith('^3^')) {
// ref = rootSha;
// }
// params.push(GitRevision.isUncommittedStaged(ref) ? '--staged' : ref);
// params.push(isUncommittedStaged(ref) ? '--staged' : ref);
params.push('--no-index');
@ -866,7 +866,7 @@ export class Git {
params.push('--all', '--single-worktree');
}
if (ref && !GitRevision.isUncommittedStaged(ref)) {
if (ref && !isUncommittedStaged(ref)) {
params.push(ref);
}
@ -895,7 +895,7 @@ export class Git {
'log',
...(options?.stdin ? ['--stdin'] : emptyArray),
...args,
...(options?.ref && !GitRevision.isUncommittedStaged(options.ref) ? [options.ref] : emptyArray),
...(options?.ref && !isUncommittedStaged(options.ref) ? [options.ref] : emptyArray),
...(!args.includes('--') ? ['--'] : emptyArray),
);
}
@ -1078,7 +1078,7 @@ export class Git {
}
}
if (ref && !GitRevision.isUncommittedStaged(ref)) {
if (ref && !isUncommittedStaged(ref)) {
// If we are reversing, we must add a range (with HEAD) because we are using --ancestry-path for better reverse walking
if (reverse) {
params.push('--reverse', '--ancestry-path', `${ref}..HEAD`);
@ -1235,7 +1235,7 @@ export class Git {
// log__shortstat(repoPath: string, options: { ref?: string }) {
// const params = ['log', '--shortstat', '--oneline'];
// if (options.ref && !GitRevision.isUncommittedStaged(options.ref)) {
// if (options.ref && !isUncommittedStaged(options.ref)) {
// params.push(options.ref);
// }
// return this.git<string>({ cwd: repoPath, configs: gitLogDefaultConfigs }, ...params, '--');
@ -1247,7 +1247,7 @@ export class Git {
{ ref, untracked }: { ref?: string; untracked?: boolean } = {},
): Promise<string | undefined> {
const params = ['ls-files'];
if (ref && !GitRevision.isUncommitted(ref)) {
if (ref && !isUncommitted(ref)) {
params.push(`--with-tree=${ref}`);
}
@ -1511,7 +1511,7 @@ export class Git {
const sha = await this.log__recent(repoPath, ordering);
if (sha === undefined) return undefined;
return [`(HEAD detached at ${GitRevision.shorten(sha)})`, sha];
return [`(HEAD detached at ${shortenRevision(sha)})`, sha];
}
defaultExceptionHandler(ex, repoPath);
@ -1606,10 +1606,10 @@ export class Git {
): Promise<TOut | undefined> {
const [file, root] = splitPath(fileName, repoPath, true);
if (GitRevision.isUncommittedStaged(ref)) {
if (isUncommittedStaged(ref)) {
ref = ':';
}
if (GitRevision.isUncommitted(ref)) throw new Error(`ref=${ref} is uncommitted`);
if (isUncommitted(ref)) throw new Error(`ref=${ref} is uncommitted`);
const opts: GitCommandOptions = {
configs: gitLogDefaultConfigs,

+ 69
- 60
src/env/node/git/localGitProvider.ts View File

@ -59,6 +59,7 @@ import {
} from '../../../git/models/branch';
import type { GitStashCommit } from '../../../git/models/commit';
import { GitCommit, GitCommitIdentity } from '../../../git/models/commit';
import { deletedOrMissing, uncommitted, uncommittedStaged } from '../../../git/models/constants';
import { GitContributor } from '../../../git/models/contributor';
import type { GitDiff, GitDiffFilter, GitDiffHunkLine, GitDiffShortStat } from '../../../git/models/diff';
import type { GitFile, GitFileStatus } from '../../../git/models/file';
@ -76,7 +77,17 @@ import type { GitLog } from '../../../git/models/log';
import type { GitMergeStatus } from '../../../git/models/merge';
import type { GitRebaseStatus } from '../../../git/models/rebase';
import type { GitBranchReference } from '../../../git/models/reference';
import { GitReference, GitRevision } from '../../../git/models/reference';
import {
createReference,
getReferenceFromBranch,
isBranchReference,
isRevisionRange,
isSha,
isShaLike,
isUncommitted,
isUncommittedStaged,
shortenRevision,
} from '../../../git/models/reference';
import type { GitReflog } from '../../../git/models/reflog';
import { getRemoteIconUri, GitRemote } from '../../../git/models/remote';
import { RemoteResourceType } from '../../../git/models/remoteResource';
@ -728,10 +739,10 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log()
async getBestRevisionUri(repoPath: string, path: string, ref: string | undefined): Promise<Uri | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
// TODO@eamodio Align this with isTrackedCore?
if (!ref || (GitRevision.isUncommitted(ref) && !GitRevision.isUncommittedStaged(ref))) {
if (!ref || (isUncommitted(ref) && !isUncommittedStaged(ref))) {
// Make sure the file exists in the repo
let data = await this.git.ls_files(repoPath, path);
if (data != null) return this.getAbsoluteUri(path, repoPath);
@ -743,7 +754,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return undefined;
}
if (GitRevision.isUncommittedStaged(ref)) return this.getScmGitUri(path, repoPath);
if (isUncommittedStaged(ref)) return this.getScmGitUri(path, repoPath);
return this.getRevisionUri(repoPath, path, ref);
}
@ -785,10 +796,8 @@ export class LocalGitProvider implements GitProvider, Disposable {
}
getRevisionUri(repoPath: string, path: string, ref: string): Uri {
if (GitRevision.isUncommitted(ref)) {
return GitRevision.isUncommittedStaged(ref)
? this.getScmGitUri(path, repoPath)
: this.getAbsoluteUri(path, repoPath);
if (isUncommitted(ref)) {
return isUncommittedStaged(ref) ? this.getScmGitUri(path, repoPath) : this.getAbsoluteUri(path, repoPath);
}
path = normalizePath(this.getAbsoluteUri(path, repoPath).fsPath);
@ -805,7 +814,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
scheme: Schemes.GitLens,
authority: encodeGitLensRevisionUriAuthority(metadata),
path: path,
query: ref ? JSON.stringify({ ref: GitRevision.shorten(ref) }) : undefined,
query: ref ? JSON.stringify({ ref: shortenRevision(ref) }) : undefined,
});
return uri;
}
@ -1029,7 +1038,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
options?: { all?: boolean; branch?: GitBranchReference; prune?: boolean; pull?: boolean; remote?: string },
): Promise<void> {
const { branch: branchRef, ...opts } = options ?? {};
if (GitReference.isBranch(branchRef)) {
if (isBranchReference(branchRef)) {
const repo = this.container.git.getRepository(repoPath);
const branch = await repo?.getBranch(branchRef?.name);
if (!branch?.remote && branch?.upstream == null) return undefined;
@ -1677,7 +1686,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
const commit = log.commits.get(options.ref);
if (commit == null && !options?.firstIfNotFound) {
// If the ref isn't a valid sha we will never find it, so let it fall through so we return the first
if (GitRevision.isSha(options.ref) || GitRevision.isUncommitted(options.ref)) return undefined;
if (isSha(options.ref) || isUncommitted(options.ref)) return undefined;
}
}
@ -1887,7 +1896,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
webviewItem: 'gitlens:tag',
webviewItemValue: {
type: 'tag',
ref: GitReference.create(tagName, repoPath, {
ref: createReference(tagName, repoPath, {
id: tagId,
refType: 'tag',
name: tagName,
@ -1932,7 +1941,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
webviewItem: 'gitlens:branch+remote',
webviewItemValue: {
type: 'branch',
ref: GitReference.create(tip, repoPath, {
ref: createReference(tip, repoPath, {
id: remoteBranchId,
refType: 'branch',
name: tip,
@ -1975,7 +1984,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
}`,
webviewItemValue: {
type: 'branch',
ref: GitReference.create(tip, repoPath, {
ref: createReference(tip, repoPath, {
id: branchId,
refType: 'branch',
name: tip,
@ -2057,7 +2066,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
webviewItem: 'gitlens:stash',
webviewItemValue: {
type: 'stash',
ref: GitReference.create(commit.sha, repoPath, {
ref: createReference(commit.sha, repoPath, {
refType: 'stash',
name: stashCommit.name,
number: stashCommit.number,
@ -2071,7 +2080,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
}`,
webviewItemValue: {
type: 'commit',
ref: GitReference.create(commit.sha, repoPath, {
ref: createReference(commit.sha, repoPath, {
refType: 'revision',
message: commit.message,
}),
@ -2539,7 +2548,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log()
async getFileStatusForCommit(repoPath: string, uri: Uri, ref: string): Promise<GitFile | undefined> {
if (ref === GitRevision.deletedOrMissing || GitRevision.isUncommitted(ref)) return undefined;
if (ref === deletedOrMissing || isUncommitted(ref)) return undefined;
const [relativePath, root] = splitPath(uri, repoPath);
@ -2799,7 +2808,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
moreLimit = moreLimit ?? configuration.get('advanced.maxSearchItems') ?? 0;
// If the log is for a range, then just get everything prior + more
if (GitRevision.isRange(log.sha)) {
if (isRevisionRange(log.sha)) {
const moreLog = await this.getLog(log.repoPath, {
...options,
limit: moreLimit === 0 ? 0 : (options?.limit ?? 0) + moreLimit,
@ -3215,11 +3224,11 @@ export class LocalGitProvider implements GitProvider, Disposable {
type: 'merge',
repoPath: repoPath,
mergeBase: mergeBase,
HEAD: GitReference.create(merge, repoPath, { refType: 'revision' }),
current: GitReference.fromBranch(branch!),
HEAD: createReference(merge, repoPath, { refType: 'revision' }),
current: getReferenceFromBranch(branch!),
incoming:
possibleSourceBranches?.length === 1
? GitReference.create(possibleSourceBranches[0], repoPath, {
? createReference(possibleSourceBranches[0], repoPath, {
refType: 'branch',
name: possibleSourceBranches[0],
remote: false,
@ -3274,18 +3283,18 @@ export class LocalGitProvider implements GitProvider, Disposable {
type: 'rebase',
repoPath: repoPath,
mergeBase: mergeBase,
HEAD: GitReference.create(rebase, repoPath, { refType: 'revision' }),
onto: GitReference.create(onto, repoPath, { refType: 'revision' }),
HEAD: createReference(rebase, repoPath, { refType: 'revision' }),
onto: createReference(onto, repoPath, { refType: 'revision' }),
current:
possibleSourceBranch != null
? GitReference.create(possibleSourceBranch, repoPath, {
? createReference(possibleSourceBranch, repoPath, {
refType: 'branch',
name: possibleSourceBranch,
remote: false,
})
: undefined,
incoming: GitReference.create(branch, repoPath, {
incoming: createReference(branch, repoPath, {
refType: 'branch',
name: branch,
remote: false,
@ -3293,7 +3302,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
steps: {
current: {
number: stepsNumber ?? 0,
commit: GitReference.create(rebase, repoPath, {
commit: createReference(rebase, repoPath, {
refType: 'revision',
message: stepsMessage,
}),
@ -3323,7 +3332,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
const relativePath = this.getRelativePath(uri, repoPath);
if (GitRevision.isUncommittedStaged(ref)) {
if (isUncommittedStaged(ref)) {
return {
current: GitUri.fromFile(relativePath, repoPath, ref),
next: GitUri.fromFile(relativePath, repoPath, undefined),
@ -3338,7 +3347,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
if (status.indexStatus != null) {
return {
current: GitUri.fromFile(relativePath, repoPath, ref),
next: GitUri.fromFile(relativePath, repoPath, GitRevision.uncommittedStaged),
next: GitUri.fromFile(relativePath, repoPath, uncommittedStaged),
};
}
}
@ -3367,10 +3376,10 @@ export class LocalGitProvider implements GitProvider, Disposable {
// editorLine?: number
): Promise<GitUri | undefined> {
// If we have no ref (or staged ref) there is no next commit
if (!ref || GitRevision.isUncommittedStaged(ref)) return undefined;
if (!ref || isUncommittedStaged(ref)) return undefined;
let filters: GitDiffFilter[] | undefined;
if (ref === GitRevision.deletedOrMissing) {
if (ref === deletedOrMissing) {
// If we are trying to move next from a deleted or missing ref then get the first commit
ref = undefined;
filters = ['A'];
@ -3407,7 +3416,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return GitUri.fromFile(
renamedFile ?? file ?? relativePath,
repoPath,
nextRenamedRef ?? nextRef ?? GitRevision.deletedOrMissing,
nextRenamedRef ?? nextRef ?? deletedOrMissing,
);
}
@ -3439,7 +3448,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
skip: number = 0,
firstParent: boolean = false,
): Promise<PreviousComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
const relativePath = this.getRelativePath(uri, repoPath);
@ -3460,13 +3469,13 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Diff working with staged
return {
current: GitUri.fromFile(relativePath, repoPath, undefined),
previous: GitUri.fromFile(relativePath, repoPath, GitRevision.uncommittedStaged),
previous: GitUri.fromFile(relativePath, repoPath, uncommittedStaged),
};
}
return {
// Diff staged with HEAD (or prior if more skips)
current: GitUri.fromFile(relativePath, repoPath, GitRevision.uncommittedStaged),
current: GitUri.fromFile(relativePath, repoPath, uncommittedStaged),
previous: await this.getPreviousUri(repoPath, uri, ref, skip - 1, undefined, firstParent),
};
} else if (status.workingTreeStatus != null) {
@ -3482,12 +3491,12 @@ export class LocalGitProvider implements GitProvider, Disposable {
}
}
// If we are at the index (staged), diff staged with HEAD
else if (GitRevision.isUncommittedStaged(ref)) {
else if (isUncommittedStaged(ref)) {
const current =
skip === 0
? GitUri.fromFile(relativePath, repoPath, ref)
: (await this.getPreviousUri(repoPath, uri, undefined, skip - 1, undefined, firstParent))!;
if (current == null || current.sha === GitRevision.deletedOrMissing) return undefined;
if (current == null || current.sha === deletedOrMissing) return undefined;
return {
current: current,
@ -3500,7 +3509,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
skip === 0
? GitUri.fromFile(relativePath, repoPath, ref)
: (await this.getPreviousUri(repoPath, uri, ref, skip - 1, undefined, firstParent))!;
if (current == null || current.sha === GitRevision.deletedOrMissing) return undefined;
if (current == null || current.sha === deletedOrMissing) return undefined;
return {
current: current,
@ -3516,7 +3525,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
ref: string | undefined,
skip: number = 0,
): Promise<PreviousLineComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
let relativePath = this.getRelativePath(uri, repoPath);
@ -3546,7 +3555,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Diff working with staged
return {
current: GitUri.fromFile(relativePath, repoPath, undefined),
previous: GitUri.fromFile(relativePath, repoPath, GitRevision.uncommittedStaged),
previous: GitUri.fromFile(relativePath, repoPath, uncommittedStaged),
line: editorLine,
};
}
@ -3564,10 +3573,10 @@ export class LocalGitProvider implements GitProvider, Disposable {
let hunkLine = await this.getDiffForLine(gitUri, editorLine, undefined);
if (hunkLine == null) {
// Next, check if we have a diff in the index (staged)
hunkLine = await this.getDiffForLine(gitUri, editorLine, undefined, GitRevision.uncommittedStaged);
hunkLine = await this.getDiffForLine(gitUri, editorLine, undefined, uncommittedStaged);
if (hunkLine != null) {
ref = GitRevision.uncommittedStaged;
ref = uncommittedStaged;
} else {
skip++;
}
@ -3585,12 +3594,12 @@ export class LocalGitProvider implements GitProvider, Disposable {
}
}
} else {
if (GitRevision.isUncommittedStaged(ref)) {
if (isUncommittedStaged(ref)) {
const current =
skip === 0
? GitUri.fromFile(relativePath, repoPath, ref)
: (await this.getPreviousUri(repoPath, uri, undefined, skip - 1, editorLine))!;
if (current.sha === GitRevision.deletedOrMissing) return undefined;
if (current.sha === deletedOrMissing) return undefined;
return {
current: current,
@ -3618,7 +3627,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
skip === 0
? GitUri.fromFile(relativePath, repoPath, ref)
: (await this.getPreviousUri(repoPath, uri, ref, skip - 1, editorLine))!;
if (current.sha === GitRevision.deletedOrMissing) return undefined;
if (current.sha === deletedOrMissing) return undefined;
return {
current: current,
@ -3636,11 +3645,11 @@ export class LocalGitProvider implements GitProvider, Disposable {
editorLine?: number,
firstParent: boolean = false,
): Promise<GitUri | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
const scope = getLogScope();
if (ref === GitRevision.uncommitted) {
if (ref === uncommitted) {
ref = undefined;
}
@ -3660,18 +3669,18 @@ export class LocalGitProvider implements GitProvider, Disposable {
} catch (ex) {
const msg: string = ex?.toString() ?? '';
// If the line count is invalid just fallback to the most recent commit
if ((ref == null || GitRevision.isUncommittedStaged(ref)) && GitErrors.invalidLineCount.test(msg)) {
if ((ref == null || isUncommittedStaged(ref)) && GitErrors.invalidLineCount.test(msg)) {
if (ref == null) {
const status = await this.getStatusForFile(repoPath, uri);
if (status?.indexStatus != null) {
return GitUri.fromFile(relativePath, repoPath, GitRevision.uncommittedStaged);
return GitUri.fromFile(relativePath, repoPath, uncommittedStaged);
}
}
ref = await this.git.log__file_recent(repoPath, relativePath, {
ordering: configuration.get('advanced.commitOrdering'),
});
return GitUri.fromFile(relativePath, repoPath, ref ?? GitRevision.deletedOrMissing);
return GitUri.fromFile(relativePath, repoPath, ref ?? deletedOrMissing);
}
Logger.error(ex, scope);
@ -3683,7 +3692,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// If the previous ref matches the ref we asked for assume we are at the end of the history
if (ref != null && ref === previousRef) return undefined;
return GitUri.fromFile(file ?? relativePath, repoPath, previousRef ?? GitRevision.deletedOrMissing);
return GitUri.fromFile(file ?? relativePath, repoPath, previousRef ?? deletedOrMissing);
}
@log()
@ -4054,7 +4063,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
let repository: Repository | undefined;
if (typeof pathOrUri === 'string') {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
repository = this.container.git.getRepository(Uri.file(pathOrUri));
repoPath = repoPath || repository?.path;
@ -4066,7 +4075,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
if (pathOrUri instanceof GitUri) {
// Always use the ref of the GitUri
ref = pathOrUri.sha;
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
}
repository = this.container.git.getRepository(pathOrUri);
@ -4099,7 +4108,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
ref: string | undefined,
repository: Repository | undefined,
): Promise<[string, string] | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
try {
while (true) {
@ -4129,7 +4138,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
}
}
if (!tracked && ref && !GitRevision.isUncommitted(ref)) {
if (!tracked && ref && !isUncommitted(ref)) {
tracked = Boolean(await this.git.ls_files(repoPath, relativePath, { ref: ref }));
// If we still haven't found this file, make sure it wasn't deleted in that ref (i.e. check the previous)
if (!tracked) {
@ -4260,16 +4269,16 @@ export class LocalGitProvider implements GitProvider, Disposable {
) {
if (
!ref ||
ref === GitRevision.deletedOrMissing ||
(pathOrUri == null && GitRevision.isSha(ref)) ||
(pathOrUri != null && GitRevision.isUncommitted(ref))
ref === deletedOrMissing ||
(pathOrUri == null && isSha(ref)) ||
(pathOrUri != null && isUncommitted(ref))
) {
return ref;
}
if (pathOrUri == null) {
// If it doesn't look like a sha at all (e.g. branch name) or is a stash ref (^3) don't try to resolve it
if ((!options?.force && !GitRevision.isShaLike(ref)) || ref.endsWith('^3')) return ref;
if ((!options?.force && !isShaLike(ref)) || ref.endsWith('^3')) return ref;
return (await this.git.rev_parse__verify(repoPath, ref)) ?? ref;
}
@ -4290,7 +4299,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
]);
const verified = getSettledValue(verifiedResult);
if (verified == null) return GitRevision.deletedOrMissing;
if (verified == null) return deletedOrMissing;
const resolved = getSettledValue(resolvedResult);
@ -4563,7 +4572,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log()
async validateReference(repoPath: string, ref: string): Promise<boolean> {
if (ref == null || ref.length === 0) return false;
if (ref === GitRevision.deletedOrMissing || GitRevision.isUncommitted(ref)) return true;
if (ref === deletedOrMissing || isUncommitted(ref)) return true;
return (await this.git.rev_parse__verify(repoPath, ref)) != null;
}

+ 7
- 6
src/git/actions/commit.ts View File

@ -18,9 +18,10 @@ import { findOrOpenEditor, findOrOpenEditors } from '../../system/utils';
import { GitUri } from '../gitUri';
import type { GitCommit } from '../models/commit';
import { isCommit } from '../models/commit';
import { deletedOrMissing } from '../models/constants';
import type { GitFile } from '../models/file';
import type { GitRevisionReference } from '../models/reference';
import { GitReference, GitRevision } from '../models/reference';
import { getReferenceFromRevision, isUncommitted, isUncommittedStaged } from '../models/reference';
export async function applyChanges(file: string | GitFile, ref1: GitRevisionReference, ref2?: GitRevisionReference) {
// Open the working file to ensure undo will work
@ -270,9 +271,9 @@ export async function openChangesWithDiffTool(
commitOrRef.repoPath,
GitUri.fromFile(file, file.repoPath ?? commitOrRef.repoPath),
{
ref1: GitRevision.isUncommitted(commitOrRef.ref) ? '' : `${commitOrRef.ref}^`,
ref2: GitRevision.isUncommitted(commitOrRef.ref) ? '' : commitOrRef.ref,
staged: GitRevision.isUncommittedStaged(commitOrRef.ref) || file.indexStatus != null,
ref1: isUncommitted(commitOrRef.ref) ? '' : `${commitOrRef.ref}^`,
ref2: isUncommitted(commitOrRef.ref) ? '' : commitOrRef.ref,
staged: isUncommittedStaged(commitOrRef.ref) || file.indexStatus != null,
tool: tool,
},
);
@ -410,7 +411,7 @@ export async function openFileAtRevision(
}
uri = Container.instance.git.getRevisionUri(
file.status === 'D' ? (await commit.getPreviousSha()) ?? GitRevision.deletedOrMissing : commit.sha,
file.status === 'D' ? (await commit.getPreviousSha()) ?? deletedOrMissing : commit.sha,
file,
commit.repoPath,
);
@ -596,7 +597,7 @@ export async function showInCommitGraph(
options?: { preserveFocus?: boolean },
): Promise<void> {
void (await executeCommand<ShowInCommitGraphCommandArgs>(Commands.ShowInCommitGraph, {
ref: GitReference.fromRevision(commit),
ref: getReferenceFromRevision(commit),
preserveFocus: options?.preserveFocus,
}));
}

+ 5
- 10
src/git/formatters/commitFormatter.ts View File

@ -30,9 +30,10 @@ import type { ContactPresence } from '../../vsls/vsls';
import type { PreviousLineComparisonUrisResult } from '../gitProvider';
import type { GitCommit } from '../models/commit';
import { isCommit } from '../models/commit';
import { uncommitted, uncommittedStaged } from '../models/constants';
import type { IssueOrPullRequest } from '../models/issue';
import { PullRequest } from '../models/pullRequest';
import { GitReference, GitRevision } from '../models/reference';
import { getReferenceFromRevision, isUncommittedStaged, shortenRevision } from '../models/reference';
import { GitRemote } from '../models/remote';
import type { RemoteProvider } from '../remotes/remoteProvider';
import type { FormatOptions, RequiredTokenOptions } from './formatter';
@ -362,11 +363,7 @@ export class CommitFormatter extends Formatter {
const { previousLineComparisonUris: diffUris } = this._options;
if (diffUris?.previous != null) {
commands = `[\`${this._padOrTruncate(
GitRevision.shorten(
GitRevision.isUncommittedStaged(diffUris.current.sha)
? diffUris.current.sha
: GitRevision.uncommitted,
)!,
shortenRevision(isUncommittedStaged(diffUris.current.sha) ? diffUris.current.sha : uncommitted)!,
this._options.tokenOptions.commands,
)}\`](${ShowCommitsInViewCommand.getMarkdownCommandArgs(
this._item.sha,
@ -393,9 +390,7 @@ export class CommitFormatter extends Formatter {
)} "Open Blame Prior to this Change")`;
} else {
commands = `[\`${this._padOrTruncate(
GitRevision.shorten(
this._item.isUncommittedStaged ? GitRevision.uncommittedStaged : GitRevision.uncommitted,
)!,
shortenRevision(this._item.isUncommittedStaged ? uncommittedStaged : uncommitted)!,
this._options.tokenOptions.commands,
)}\`](${ShowCommitsInViewCommand.getMarkdownCommandArgs(
this._item.sha,
@ -443,7 +438,7 @@ export class CommitFormatter extends Formatter {
if (arePlusFeaturesEnabled()) {
commands += ` &nbsp;[$(gitlens-graph)](${Command.getMarkdownCommandArgsCore<ShowInCommitGraphCommandArgs>(
Commands.ShowInCommitGraph,
{ ref: GitReference.fromRevision(this._item) },
{ ref: getReferenceFromRevision(this._item) },
)} "Open in Commit Graph")`;
}

+ 3
- 3
src/git/fsProvider.ts View File

@ -8,7 +8,7 @@ import { map } from '../system/iterable';
import { normalizePath, relative } from '../system/path';
import { TernarySearchTree } from '../system/searchTree';
import { GitUri, isGitUri } from './gitUri';
import { GitRevision } from './models/reference';
import { deletedOrMissing } from './models/constants';
import type { GitTreeEntry } from './models/tree';
const emptyArray = new Uint8Array(0);
@ -70,7 +70,7 @@ export class GitFileSystemProvider implements FileSystemProvider, Disposable {
async readFile(uri: Uri): Promise<Uint8Array> {
const { path, ref, repoPath } = fromGitLensFSUri(uri);
if (ref === GitRevision.deletedOrMissing) return emptyArray;
if (ref === deletedOrMissing) return emptyArray;
const data = await this.container.git.getRevisionContent(repoPath, path, ref);
return data != null ? data : emptyArray;
@ -84,7 +84,7 @@ export class GitFileSystemProvider implements FileSystemProvider, Disposable {
async stat(uri: Uri): Promise<FileStat> {
const { path, ref, repoPath } = fromGitLensFSUri(uri);
if (ref === GitRevision.deletedOrMissing) {
if (ref === deletedOrMissing) {
return {
type: FileType.File,
size: 0,

+ 15
- 14
src/git/gitProviderService.ts View File

@ -48,6 +48,7 @@ import type { GitUri } from './gitUri';
import type { GitBlame, GitBlameLine, GitBlameLines } from './models/blame';
import type { BranchSortOptions, GitBranch } from './models/branch';
import { GitCommit, GitCommitIdentity } from './models/commit';
import { deletedOrMissing, uncommitted, uncommittedStaged } from './models/constants';
import type { GitContributor } from './models/contributor';
import type { GitDiff, GitDiffFilter, GitDiffHunkLine, GitDiffShortStat } from './models/diff';
import type { GitFile } from './models/file';
@ -58,7 +59,7 @@ import type { GitMergeStatus } from './models/merge';
import type { PullRequest, PullRequestState, SearchedPullRequest } from './models/pullRequest';
import type { GitRebaseStatus } from './models/rebase';
import type { GitBranchReference, GitReference } from './models/reference';
import { GitRevision } from './models/reference';
import { createRevisionRange, isSha, isUncommitted, isUncommittedParent } from './models/reference';
import type { GitReflog } from './models/reflog';
import { GitRemote } from './models/remote';
import type { RepositoryChangeEvent } from './models/repository';
@ -968,7 +969,7 @@ export class GitProviderService implements Disposable {
path: string,
ref: string | undefined,
): Promise<Uri | undefined> {
if (repoPath == null || ref === GitRevision.deletedOrMissing) return undefined;
if (repoPath == null || ref === deletedOrMissing) return undefined;
const { provider, path: rp } = this.getProvider(repoPath);
return provider.getBestRevisionUri(rp, provider.getRelativePath(path, rp), ref);
@ -1245,7 +1246,7 @@ export class GitProviderService implements Disposable {
@log<GitProviderService['getBranchAheadRange']>({ args: { 0: b => b.name } })
async getBranchAheadRange(branch: GitBranch): Promise<string | undefined> {
if (branch.state.ahead > 0) {
return GitRevision.createRange(branch.upstream?.name, branch.ref);
return createRevisionRange(branch.upstream?.name, branch.ref);
}
if (branch.upstream == null) {
@ -1266,7 +1267,7 @@ export class GitProviderService implements Disposable {
const possibleBranch = weightedBranch!.branch.upstream?.name ?? weightedBranch!.branch.ref;
if (possibleBranch !== branch.ref) {
return GitRevision.createRange(possibleBranch, branch.ref);
return createRevisionRange(possibleBranch, branch.ref);
}
}
}
@ -1358,7 +1359,7 @@ export class GitProviderService implements Disposable {
async getCommit(repoPath: string | Uri, ref: string): Promise<GitCommit | undefined> {
const { provider, path } = this.getProvider(repoPath);
if (ref === GitRevision.uncommitted || ref === GitRevision.uncommittedStaged) {
if (ref === uncommitted || ref === uncommittedStaged) {
const now = new Date();
const user = await this.getCurrentUser(repoPath);
return new GitCommit(
@ -1515,7 +1516,7 @@ export class GitProviderService implements Disposable {
@log()
async getFileStatusForCommit(repoPath: string | Uri, uri: Uri, ref: string): Promise<GitFile | undefined> {
if (ref === GitRevision.deletedOrMissing || GitRevision.isUncommitted(ref)) return undefined;
if (ref === deletedOrMissing || isUncommitted(ref)) return undefined;
const { provider, path } = this.getProvider(repoPath);
return provider.getFileStatusForCommit(path, uri, ref);
@ -1641,7 +1642,7 @@ export class GitProviderService implements Disposable {
skip: number = 0,
firstParent: boolean = false,
): Promise<PreviousComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return Promise.resolve(undefined);
if (ref === deletedOrMissing) return Promise.resolve(undefined);
const { provider, path } = this.getProvider(repoPath);
return provider.getPreviousComparisonUris(path, uri, ref, skip, firstParent);
@ -1655,7 +1656,7 @@ export class GitProviderService implements Disposable {
ref: string | undefined,
skip: number = 0,
): Promise<PreviousLineComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return Promise.resolve(undefined);
if (ref === deletedOrMissing) return Promise.resolve(undefined);
const { provider, path } = this.getProvider(repoPath);
return provider.getPreviousComparisonUrisForLine(path, uri, editorLine, ref, skip);
@ -1736,7 +1737,7 @@ export class GitProviderService implements Disposable {
remoteOrProvider: GitRemote | RichRemoteProvider,
options?: { timeout?: number },
): Promise<PullRequest | undefined> {
if (GitRevision.isUncommitted(ref)) return undefined;
if (isUncommitted(ref)) return undefined;
let provider;
if (GitRemote.is(remoteOrProvider)) {
@ -2410,15 +2411,15 @@ export class GitProviderService implements Disposable {
pathOrUri?: string | Uri,
options?: { timeout?: number },
) {
if (pathOrUri != null && GitRevision.isUncommittedParent(ref)) {
if (pathOrUri != null && isUncommittedParent(ref)) {
ref = 'HEAD';
}
if (
!ref ||
ref === GitRevision.deletedOrMissing ||
(pathOrUri == null && GitRevision.isSha(ref)) ||
(pathOrUri != null && GitRevision.isUncommitted(ref))
ref === deletedOrMissing ||
(pathOrUri == null && isSha(ref)) ||
(pathOrUri != null && isUncommitted(ref))
) {
return ref;
}
@ -2467,7 +2468,7 @@ export class GitProviderService implements Disposable {
@log()
async validateReference(repoPath: string | Uri, ref: string) {
if (ref == null || ref.length === 0) return false;
if (ref === GitRevision.deletedOrMissing || GitRevision.isUncommitted(ref)) return true;
if (ref === deletedOrMissing || isUncommitted(ref)) return true;
const { provider, path } = this.getProvider(repoPath);
return provider.validateReference(path, ref);

+ 9
- 8
src/git/gitUri.ts View File

@ -12,8 +12,9 @@ import { basename, getBestPath, normalizePath, relativeDir, splitPath } from '..
// import { CharCode } from '../system/string';
import { isVirtualUri } from '../system/utils';
import type { RevisionUriData } from './gitProvider';
import { uncommittedStaged } from './models/constants';
import type { GitFile } from './models/file';
import { GitRevision } from './models/reference';
import { isUncommitted, isUncommittedStaged, shortenRevision } from './models/reference';
const slash = 47; //CharCode.Slash;
@ -69,7 +70,7 @@ export class GitUri extends (Uri as any as UriEx) {
ref = commitOrRepoPath.sha;
}
if (GitRevision.isUncommittedStaged(ref) || !GitRevision.isUncommitted(ref)) {
if (isUncommittedStaged(ref) || !isUncommitted(ref)) {
this.sha = ref;
}
@ -89,7 +90,7 @@ export class GitUri extends (Uri as any as UriEx) {
ref = commitOrRepoPath.sha;
}
if (ref && (GitRevision.isUncommittedStaged(ref) || !GitRevision.isUncommitted(ref))) {
if (ref && (isUncommittedStaged(ref) || !isUncommitted(ref))) {
this.sha = ref;
}
@ -154,7 +155,7 @@ export class GitUri extends (Uri as any as UriEx) {
fragment: uri.fragment,
});
this.repoPath = commitOrRepoPath.repoPath;
if (GitRevision.isUncommittedStaged(commitOrRepoPath.sha) || !GitRevision.isUncommitted(commitOrRepoPath.sha)) {
if (isUncommittedStaged(commitOrRepoPath.sha) || !isUncommitted(commitOrRepoPath.sha)) {
this.sha = commitOrRepoPath.sha;
}
}
@ -171,12 +172,12 @@ export class GitUri extends (Uri as any as UriEx) {
@memoize()
get isUncommitted(): boolean {
return GitRevision.isUncommitted(this.sha);
return isUncommitted(this.sha);
}
@memoize()
get isUncommittedStaged(): boolean {
return GitRevision.isUncommittedStaged(this.sha);
return isUncommittedStaged(this.sha);
}
@memoize()
@ -186,7 +187,7 @@ export class GitUri extends (Uri as any as UriEx) {
@memoize()
get shortSha(): string {
return GitRevision.shorten(this.sha);
return shortenRevision(this.sha);
}
@memoize()
@ -268,7 +269,7 @@ export class GitUri extends (Uri as any as UriEx) {
switch (data.ref) {
case '':
case '~':
ref = GitRevision.uncommittedStaged;
ref = uncommittedStaged;
break;
case null:

+ 2
- 2
src/git/models/branch.ts View File

@ -10,7 +10,7 @@ import type { RemoteProvider } from '../remotes/remoteProvider';
import type { RichRemoteProvider } from '../remotes/richRemoteProvider';
import type { PullRequest, PullRequestState } from './pullRequest';
import type { GitBranchReference, GitReference } from './reference';
import { GitRevision } from './reference';
import { shortenRevision } from './reference';
import type { GitRemote } from './remote';
import { getUpstreamStatus } from './status';
@ -215,7 +215,7 @@ export class GitBranch implements GitBranchReference {
}
export function formatDetachedHeadName(sha: string): string {
return `(${GitRevision.shorten(sha)}...)`;
return `(${shortenRevision(sha)}...)`;
}
export function getBranchNameWithoutRemote(name: string): string {

+ 10
- 9
src/git/models/commit.ts View File

@ -13,11 +13,12 @@ import { pad, pluralize } from '../../system/string';
import type { PreviousLineComparisonUrisResult } from '../gitProvider';
import { GitUri } from '../gitUri';
import type { RichRemoteProvider } from '../remotes/richRemoteProvider';
import { uncommitted } from './constants';
import type { GitFile } from './file';
import { GitFileChange, GitFileWorkingTreeStatus } from './file';
import type { PullRequest } from './pullRequest';
import type { GitReference, GitRevisionReference, GitStashReference } from './reference';
import { GitRevision } from './reference';
import { isSha, isUncommitted, isUncommittedParent, isUncommittedStaged } from './reference';
import type { GitRemote } from './remote';
import type { Repository } from './repository';
@ -140,12 +141,12 @@ export class GitCommit implements GitRevisionReference {
@memoize()
get isUncommitted(): boolean {
return GitRevision.isUncommitted(this.sha);
return isUncommitted(this.sha);
}
@memoize()
get isUncommittedStaged(): boolean {
return GitRevision.isUncommittedStaged(this.sha);
return isUncommittedStaged(this.sha);
}
private _message: string | undefined;
@ -177,7 +178,7 @@ export class GitCommit implements GitRevisionReference {
this._resolvedPreviousSha ??
(this.file != null ? this.file.previousSha : this.parents[0]) ??
`${this.sha}^`;
return GitRevision.isUncommittedParent(previousSha) ? 'HEAD' : previousSha;
return isUncommittedParent(previousSha) ? 'HEAD' : previousSha;
}
private _etagFileSystem: number | undefined;
@ -488,7 +489,7 @@ export class GitCommit implements GitRevisionReference {
this.repoPath,
this.file.uri,
editorLine,
ref ?? (this.sha === GitRevision.uncommitted ? undefined : this.sha),
ref ?? (this.sha === uncommitted ? undefined : this.sha),
)
: Promise.resolve(undefined);
}
@ -498,13 +499,13 @@ export class GitCommit implements GitRevisionReference {
if (this._previousShaPromise == null) {
async function getCore(this: GitCommit) {
if (this.file != null) {
if (this.file.previousSha != null && GitRevision.isSha(this.file.previousSha)) {
if (this.file.previousSha != null && isSha(this.file.previousSha)) {
return this.file.previousSha;
}
const sha = await this.container.git.resolveReference(
this.repoPath,
GitRevision.isUncommitted(this.sha, true) ? 'HEAD' : `${this.sha}^`,
isUncommitted(this.sha, true) ? 'HEAD' : `${this.sha}^`,
this.file.originalPath ?? this.file.path,
);
@ -513,11 +514,11 @@ export class GitCommit implements GitRevisionReference {
}
const parent = this.parents[0];
if (parent != null && GitRevision.isSha(parent)) return parent;
if (parent != null && isSha(parent)) return parent;
const sha = await this.container.git.resolveReference(
this.repoPath,
GitRevision.isUncommitted(this.sha, true) ? 'HEAD' : `${this.sha}^`,
isUncommitted(this.sha, true) ? 'HEAD' : `${this.sha}^`,
);
this._resolvedPreviousSha = sha;

+ 3
- 0
src/git/models/constants.ts View File

@ -0,0 +1,3 @@
export const deletedOrMissing = '0000000000000000000000000000000000000000-';
export const uncommitted = '0000000000000000000000000000000000000000';
export const uncommittedStaged = '0000000000000000000000000000000000000000:';

+ 273
- 283
src/git/models/reference.ts View File

@ -1,6 +1,7 @@
import { configuration } from '../../configuration';
import { GlyphChars } from '../../constants';
import { getBranchNameWithoutRemote, getRemoteNameFromBranchName, splitBranchNameAndRemote } from './branch';
import { deletedOrMissing, uncommitted, uncommittedStaged } from './constants';
const rangeRegex = /^(\S*?)(\.\.\.?)(\S*)\s*$/;
const shaLikeRegex = /(^[0-9a-f]{40}([\^@~:]\S*)?$)|(^[0]{40}(:|-)$)/;
@ -14,94 +15,87 @@ function isMatch(regex: RegExp, ref: string | undefined) {
return !ref ? false : regex.test(ref);
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace GitRevision {
export const deletedOrMissing = '0000000000000000000000000000000000000000-';
export const uncommitted = '0000000000000000000000000000000000000000';
export const uncommittedStaged = '0000000000000000000000000000000000000000:';
export function createRange(
ref1: string | undefined,
ref2: string | undefined,
notation: '..' | '...' = '..',
): string {
return `${ref1 ?? ''}${notation}${ref2 ?? ''}`;
}
export function createRevisionRange(
ref1: string | undefined,
ref2: string | undefined,
notation: '..' | '...' = '..',
): string {
return `${ref1 ?? ''}${notation}${ref2 ?? ''}`;
}
export function isRange(ref: string | undefined) {
return ref?.includes('..') ?? false;
}
export function isRevisionRange(ref: string | undefined) {
return ref?.includes('..') ?? false;
}
export function isSha(ref: string) {
return isMatch(shaRegex, ref);
}
export function isSha(ref: string) {
return isMatch(shaRegex, ref);
}
export function isShaLike(ref: string) {
return isMatch(shaLikeRegex, ref);
}
export function isShaLike(ref: string) {
return isMatch(shaLikeRegex, ref);
}
export function isShaParent(ref: string) {
return isMatch(shaParentRegex, ref);
}
export function isShaParent(ref: string) {
return isMatch(shaParentRegex, ref);
}
export function isUncommitted(ref: string | undefined, exact: boolean = false) {
return ref === uncommitted || ref === uncommittedStaged || (!exact && isMatch(uncommittedRegex, ref));
}
export function isUncommitted(ref: string | undefined, exact: boolean = false) {
return ref === uncommitted || ref === uncommittedStaged || (!exact && isMatch(uncommittedRegex, ref));
}
export function isUncommittedParent(ref: string | undefined) {
return ref === `${uncommitted}^` || ref === `${uncommittedStaged}^`;
}
export function isUncommittedParent(ref: string | undefined) {
return ref === `${uncommitted}^` || ref === `${uncommittedStaged}^`;
}
export function isUncommittedStaged(ref: string | undefined, exact: boolean = false): boolean {
return ref === uncommittedStaged || (!exact && isMatch(uncommittedStagedRegex, ref));
}
export function isUncommittedStaged(ref: string | undefined, exact: boolean = false): boolean {
return ref === uncommittedStaged || (!exact && isMatch(uncommittedStagedRegex, ref));
}
export function shorten(
ref: string | undefined,
options?: {
force?: boolean;
strings?: { uncommitted?: string; uncommittedStaged?: string; working?: string };
},
) {
if (ref === deletedOrMissing) return '(deleted)';
if (!ref) return options?.strings?.working ?? '';
if (isUncommitted(ref)) {
return isUncommittedStaged(ref)
? options?.strings?.uncommittedStaged ?? 'Index'
: options?.strings?.uncommitted ?? 'Working Tree';
}
export function shortenRevision(
ref: string | undefined,
options?: {
force?: boolean;
strings?: { uncommitted?: string; uncommittedStaged?: string; working?: string };
},
) {
if (ref === deletedOrMissing) return '(deleted)';
if (!ref) return options?.strings?.working ?? '';
if (isUncommitted(ref)) {
return isUncommittedStaged(ref)
? options?.strings?.uncommittedStaged ?? 'Index'
: options?.strings?.uncommitted ?? 'Working Tree';
}
if (GitRevision.isRange(ref)) return ref;
if (!options?.force && !isShaLike(ref)) return ref;
if (isRevisionRange(ref)) return ref;
if (!options?.force && !isShaLike(ref)) return ref;
// Don't allow shas to be shortened to less than 5 characters
const len = Math.max(5, configuration.get('advanced.abbreviatedShaLength'));
// Don't allow shas to be shortened to less than 5 characters
const len = Math.max(5, configuration.get('advanced.abbreviatedShaLength'));
// If we have a suffix, append it
const match = shaShortenRegex.exec(ref);
if (match != null) {
const [, rev, suffix] = match;
// If we have a suffix, append it
const match = shaShortenRegex.exec(ref);
if (match != null) {
const [, rev, suffix] = match;
if (suffix != null) {
return `${rev.substr(0, len)}${suffix}`;
}
if (suffix != null) {
return `${rev.substr(0, len)}${suffix}`;
}
return ref.substr(0, len);
}
export function splitRange(ref: string): { ref1: string; ref2: string; notation: '..' | '...' } | undefined {
const match = rangeRegex.exec(ref);
if (match == null) return undefined;
return ref.substr(0, len);
}
const [, ref1, notation, ref2] = match;
return {
ref1: ref1,
notation: notation as '..' | '...',
ref2: ref2,
};
}
export function splitRevisionRange(ref: string): { ref1: string; ref2: string; notation: '..' | '...' } | undefined {
const match = rangeRegex.exec(ref);
if (match == null) return undefined;
const [, ref1, notation, ref2] = match;
return {
ref1: ref1,
notation: notation as '..' | '...',
ref2: ref2,
};
}
export interface GitBranchReference {
@ -146,244 +140,240 @@ export interface GitTagReference {
export type GitReference = GitBranchReference | GitRevisionReference | GitStashReference | GitTagReference;
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace GitReference {
export function create(
ref: string,
repoPath: string,
options: {
refType: 'branch';
name: string;
id?: string;
remote: boolean;
upstream?: { name: string; missing: boolean };
},
): GitBranchReference;
export function create(
ref: string,
repoPath: string,
options?: { refType: 'revision'; name?: string; message?: string },
): GitRevisionReference;
export function create(
ref: string,
repoPath: string,
options: { refType: 'stash'; name: string; number: string | undefined; message?: string },
): GitStashReference;
export function create(
ref: string,
repoPath: string,
options: { refType: 'tag'; name: string; id?: string },
): GitTagReference;
export function create(
ref: string,
repoPath: string,
options:
| {
id?: string;
refType: 'branch';
name: string;
remote: boolean;
upstream?: { name: string; missing: boolean };
}
| { refType?: 'revision'; name?: string; message?: string }
| { refType: 'stash'; name: string; number: string | undefined; message?: string }
| { id?: string; refType: 'tag'; name: string } = { refType: 'revision' },
): GitReference {
switch (options.refType) {
case 'branch':
return {
refType: 'branch',
repoPath: repoPath,
ref: ref,
name: options.name,
id: options.id,
remote: options.remote,
upstream: options.upstream,
};
case 'stash':
return {
refType: 'stash',
repoPath: repoPath,
ref: ref,
name: options.name,
number: options.number,
message: options.message,
};
case 'tag':
return {
refType: 'tag',
repoPath: repoPath,
ref: ref,
name: options.name,
id: options.id,
};
default:
return {
refType: 'revision',
repoPath: repoPath,
ref: ref,
name:
options.name ?? GitRevision.shorten(ref, { force: true, strings: { working: 'Working Tree' } }),
message: options.message,
};
}
}
export function fromBranch(branch: GitBranchReference) {
return create(branch.ref, branch.repoPath, {
id: branch.id,
refType: branch.refType,
name: branch.name,
remote: branch.remote,
upstream: branch.upstream,
});
export function createReference(
ref: string,
repoPath: string,
options: {
refType: 'branch';
name: string;
id?: string;
remote: boolean;
upstream?: { name: string; missing: boolean };
},
): GitBranchReference;
export function createReference(
ref: string,
repoPath: string,
options?: { refType: 'revision'; name?: string; message?: string },
): GitRevisionReference;
export function createReference(
ref: string,
repoPath: string,
options: { refType: 'stash'; name: string; number: string | undefined; message?: string },
): GitStashReference;
export function createReference(
ref: string,
repoPath: string,
options: { refType: 'tag'; name: string; id?: string },
): GitTagReference;
export function createReference(
ref: string,
repoPath: string,
options:
| {
id?: string;
refType: 'branch';
name: string;
remote: boolean;
upstream?: { name: string; missing: boolean };
}
| { refType?: 'revision'; name?: string; message?: string }
| { refType: 'stash'; name: string; number: string | undefined; message?: string }
| { id?: string; refType: 'tag'; name: string } = { refType: 'revision' },
): GitReference {
switch (options.refType) {
case 'branch':
return {
refType: 'branch',
repoPath: repoPath,
ref: ref,
name: options.name,
id: options.id,
remote: options.remote,
upstream: options.upstream,
};
case 'stash':
return {
refType: 'stash',
repoPath: repoPath,
ref: ref,
name: options.name,
number: options.number,
message: options.message,
};
case 'tag':
return {
refType: 'tag',
repoPath: repoPath,
ref: ref,
name: options.name,
id: options.id,
};
default:
return {
refType: 'revision',
repoPath: repoPath,
ref: ref,
name: options.name ?? shortenRevision(ref, { force: true, strings: { working: 'Working Tree' } }),
message: options.message,
};
}
}
export function fromRevision(revision: GitRevisionReference) {
if (revision.refType === 'stash') {
return create(revision.ref, revision.repoPath, {
refType: revision.refType,
name: revision.name,
number: revision.number,
message: revision.message,
});
}
export function getReferenceFromBranch(branch: GitBranchReference) {
return createReference(branch.ref, branch.repoPath, {
id: branch.id,
refType: branch.refType,
name: branch.name,
remote: branch.remote,
upstream: branch.upstream,
});
}
return create(revision.ref, revision.repoPath, {
export function getReferenceFromRevision(revision: GitRevisionReference) {
if (revision.refType === 'stash') {
return createReference(revision.ref, revision.repoPath, {
refType: revision.refType,
name: revision.name,
number: revision.number,
message: revision.message,
});
}
export function fromTag(tag: GitTagReference) {
return create(tag.ref, tag.repoPath, {
id: tag.id,
refType: tag.refType,
name: tag.name,
});
}
return createReference(revision.ref, revision.repoPath, {
refType: revision.refType,
name: revision.name,
message: revision.message,
});
}
export function getNameWithoutRemote(ref: GitReference) {
if (ref.refType === 'branch') {
return ref.remote ? getBranchNameWithoutRemote(ref.name) : ref.name;
}
return ref.name;
}
export function getReferenceFromTag(tag: GitTagReference) {
return createReference(tag.ref, tag.repoPath, {
id: tag.id,
refType: tag.refType,
name: tag.name,
});
}
export function isBranch(ref: GitReference | undefined): ref is GitBranchReference {
return ref?.refType === 'branch';
export function getNameWithoutRemote(ref: GitReference) {
if (ref.refType === 'branch') {
return ref.remote ? getBranchNameWithoutRemote(ref.name) : ref.name;
}
return ref.name;
}
export function isRevision(ref: GitReference | undefined): ref is GitRevisionReference {
return ref?.refType === 'revision';
}
export function isBranchReference(ref: GitReference | undefined): ref is GitBranchReference {
return ref?.refType === 'branch';
}
export function isRevisionRange(ref: GitReference | undefined): ref is GitRevisionReference {
return ref?.refType === 'revision' && GitRevision.isRange(ref.ref);
}
export function isRevisionReference(ref: GitReference | undefined): ref is GitRevisionReference {
return ref?.refType === 'revision';
}
export function isStash(ref: GitReference | undefined): ref is GitStashReference {
return ref?.refType === 'stash' || (ref?.refType === 'revision' && Boolean((ref as any)?.stashName));
}
export function isRevisionRangeReference(ref: GitReference | undefined): ref is GitRevisionReference {
return ref?.refType === 'revision' && isRevisionRange(ref.ref);
}
export function isTag(ref: GitReference | undefined): ref is GitTagReference {
return ref?.refType === 'tag';
}
export function isStashReference(ref: GitReference | undefined): ref is GitStashReference {
return ref?.refType === 'stash' || (ref?.refType === 'revision' && Boolean((ref as any)?.stashName));
}
export function toString(
refs: GitReference | GitReference[] | undefined,
options?: { capitalize?: boolean; expand?: boolean; icon?: boolean; label?: boolean; quoted?: boolean } | false,
) {
if (refs == null) return '';
options =
options === false
? {}
: { expand: true, icon: true, label: options?.label ?? options?.expand ?? true, ...options };
let result;
if (!Array.isArray(refs) || refs.length === 1) {
const ref = Array.isArray(refs) ? refs[0] : refs;
let refName = options?.quoted ? `'${ref.name}'` : ref.name;
switch (ref.refType) {
case 'branch':
if (ref.remote) {
refName = `${getRemoteNameFromBranchName(refName)}: ${getBranchNameWithoutRemote(refName)}`;
refName = options?.quoted ? `'${refName}'` : refName;
}
export function isTagReference(ref: GitReference | undefined): ref is GitTagReference {
return ref?.refType === 'tag';
}
result = `${options.label ? `${ref.remote ? 'remote ' : ''}branch ` : ''}${
options.icon ? `$(git-branch)${GlyphChars.Space}${refName}` : refName
}`;
break;
case 'tag':
result = `${options.label ? 'tag ' : ''}${
options.icon ? `$(tag)${GlyphChars.Space}${refName}` : refName
}`;
break;
default: {
if (GitReference.isStash(ref)) {
let message;
if (options.expand && ref.message) {
message = `${ref.number != null ? `${ref.number}: ` : ''}${
ref.message.length > 20
? `${ref.message.substring(0, 20).trimRight()}${GlyphChars.Ellipsis}`
: ref.message
}`;
}
export function getReferenceLabel(
refs: GitReference | GitReference[] | undefined,
options?: { capitalize?: boolean; expand?: boolean; icon?: boolean; label?: boolean; quoted?: boolean } | false,
) {
if (refs == null) return '';
options =
options === false
? {}
: { expand: true, icon: true, label: options?.label ?? options?.expand ?? true, ...options };
let result;
if (!Array.isArray(refs) || refs.length === 1) {
const ref = Array.isArray(refs) ? refs[0] : refs;
let refName = options?.quoted ? `'${ref.name}'` : ref.name;
switch (ref.refType) {
case 'branch':
if (ref.remote) {
refName = `${getRemoteNameFromBranchName(refName)}: ${getBranchNameWithoutRemote(refName)}`;
refName = options?.quoted ? `'${refName}'` : refName;
}
result = `${options.label ? 'stash ' : ''}${
options.icon
? `$(archive)${GlyphChars.Space}${message ?? ref.name}`
: `${message ?? ref.number ?? ref.name}`
result = `${options.label ? `${ref.remote ? 'remote ' : ''}branch ` : ''}${
options.icon ? `$(git-branch)${GlyphChars.Space}${refName}` : refName
}`;
break;
case 'tag':
result = `${options.label ? 'tag ' : ''}${
options.icon ? `$(tag)${GlyphChars.Space}${refName}` : refName
}`;
break;
default: {
if (isStashReference(ref)) {
let message;
if (options.expand && ref.message) {
message = `${ref.number != null ? `${ref.number}: ` : ''}${
ref.message.length > 20
? `${ref.message.substring(0, 20).trimRight()}${GlyphChars.Ellipsis}`
: ref.message
}`;
} else if (GitRevision.isRange(ref.ref)) {
result = refName;
} else {
let message;
if (options.expand && ref.message) {
message =
ref.message.length > 20
? ` (${ref.message.substring(0, 20).trimRight()}${GlyphChars.Ellipsis})`
: ` (${ref.message})`;
}
}
let prefix;
if (options.expand && options.label && GitRevision.isShaParent(ref.ref)) {
refName = ref.name.endsWith('^') ? ref.name.substr(0, ref.name.length - 1) : ref.name;
if (options?.quoted) {
refName = `'${refName}'`;
}
prefix = 'before ';
} else {
prefix = '';
}
result = `${options.label ? 'stash ' : ''}${
options.icon
? `$(archive)${GlyphChars.Space}${message ?? ref.name}`
: `${message ?? ref.number ?? ref.name}`
}`;
} else if (isRevisionRange(ref.ref)) {
result = refName;
} else {
let message;
if (options.expand && ref.message) {
message =
ref.message.length > 20
? ` (${ref.message.substring(0, 20).trimRight()}${GlyphChars.Ellipsis})`
: ` (${ref.message})`;
}
result = `${options.label ? `${prefix}commit ` : ''}${
options.icon
? `$(git-commit)${GlyphChars.Space}${refName}${message ?? ''}`
: `${refName}${message ?? ''}`
}`;
let prefix;
if (options.expand && options.label && isShaParent(ref.ref)) {
refName = ref.name.endsWith('^') ? ref.name.substr(0, ref.name.length - 1) : ref.name;
if (options?.quoted) {
refName = `'${refName}'`;
}
prefix = 'before ';
} else {
prefix = '';
}
break;
result = `${options.label ? `${prefix}commit ` : ''}${
options.icon
? `$(git-commit)${GlyphChars.Space}${refName}${message ?? ''}`
: `${refName}${message ?? ''}`
}`;
}
break;
}
return options.capitalize && options.expand && options.label !== false
? `${result[0].toLocaleUpperCase()}${result.substring(1)}`
: result;
}
const expanded = options.expand ? ` (${refs.map(r => r.name).join(', ')})` : '';
switch (refs[0].refType) {
case 'branch':
return `${refs.length} branches${expanded}`;
case 'tag':
return `${refs.length} tags${expanded}`;
default:
return `${refs.length} ${GitReference.isStash(refs[0]) ? 'stashes' : 'commits'}${expanded}`;
}
return options.capitalize && options.expand && options.label !== false
? `${result[0].toLocaleUpperCase()}${result.substring(1)}`
: result;
}
const expanded = options.expand ? ` (${refs.map(r => r.name).join(', ')})` : '';
switch (refs[0].refType) {
case 'branch':
return `${refs.length} branches${expanded}`;
case 'tag':
return `${refs.length} tags${expanded}`;
default:
return `${refs.length} ${isStashReference(refs[0]) ? 'stashes' : 'commits'}${expanded}`;
}
}

+ 3
- 3
src/git/models/reflog.ts View File

@ -2,7 +2,7 @@ import { DateStyle } from '../../config';
import { Container } from '../../container';
import { formatDate, fromNow } from '../../system/date';
import { memoize } from '../../system/decorators/memoize';
import { GitRevision } from './reference';
import { shortenRevision } from './reference';
export interface GitReflog {
readonly repoPath: string;
@ -64,7 +64,7 @@ export class GitReflogRecord {
@memoize()
get previousShortSha() {
return GitRevision.shorten(this._previousSha);
return shortenRevision(this._previousSha);
}
get selector() {
@ -73,7 +73,7 @@ export class GitReflogRecord {
@memoize()
get shortSha() {
return GitRevision.shorten(this.sha);
return shortenRevision(this.sha);
}
update(previousSha?: string, selector?: string) {

+ 5
- 10
src/git/models/repository.ts View File

@ -34,8 +34,8 @@ import type { GitDiffShortStat } from './diff';
import type { GitLog } from './log';
import type { GitMergeStatus } from './merge';
import type { GitRebaseStatus } from './rebase';
import type { GitBranchReference, GitTagReference } from './reference';
import { GitReference } from './reference';
import type { GitBranchReference, GitReference, GitTagReference } from './reference';
import { getNameWithoutRemote, isBranchReference } from './reference';
import type { GitRemote } from './remote';
import type { GitStash } from './stash';
import type { GitStatus } from './status';
@ -526,12 +526,7 @@ export class Repository implements Disposable {
const branchesByOrigin = groupByMap(remoteBranches, b => getRemoteNameFromBranchName(b.name));
for (const [remote, branches] of branchesByOrigin.entries()) {
this.runTerminalCommand(
'push',
'-d',
remote,
...branches.map(b => GitReference.getNameWithoutRemote(b)),
);
this.runTerminalCommand('push', '-d', remote, ...branches.map(b => getNameWithoutRemote(b)));
}
}
}
@ -825,7 +820,7 @@ export class Repository implements Disposable {
return window.withProgress(
{
location: ProgressLocation.Notification,
title: GitReference.isBranch(opts.reference)
title: isBranchReference(opts.reference)
? `${opts.publish != null ? 'Publishing ' : 'Pushing '}${opts.reference.name}...`
: `Pushing ${this.formattedName}...`,
},
@ -872,7 +867,7 @@ export class Repository implements Disposable {
};
}) {
try {
if (GitReference.isBranch(options?.reference)) {
if (isBranchReference(options?.reference)) {
const repo = await this.container.git.getOrOpenScmRepository(this.path);
if (repo == null) return;

+ 9
- 21
src/git/models/status.ts View File

@ -6,6 +6,7 @@ import { pluralize } from '../../system/string';
import type { GitTrackingState } from './branch';
import { formatDetachedHeadName, getRemoteNameFromBranchName, isDetachedHead } from './branch';
import { GitCommit, GitCommitIdentity } from './commit';
import { uncommitted, uncommittedStaged } from './constants';
import type { GitFile, GitFileStatus } from './file';
import {
getGitFileFormattedDirectory,
@ -17,7 +18,6 @@ import {
GitFileIndexStatus,
GitFileWorkingTreeStatus,
} from './file';
import { GitRevision } from './reference';
import type { GitRemote } from './remote';
import type { GitUser } from './user';
@ -452,19 +452,13 @@ export class GitStatusFile implements GitFile {
new GitCommit(
container,
this.repoPath,
GitRevision.uncommitted,
uncommitted,
new GitCommitIdentity('You', user?.email ?? undefined, now),
new GitCommitIdentity('You', user?.email ?? undefined, now),
'Uncommitted changes',
[GitRevision.uncommittedStaged],
[uncommittedStaged],
'Uncommitted changes',
new GitFileChange(
this.repoPath,
this.path,
this.status,
this.originalPath,
GitRevision.uncommittedStaged,
),
new GitFileChange(this.repoPath, this.path, this.status, this.originalPath, uncommittedStaged),
undefined,
[],
),
@ -483,26 +477,20 @@ export class GitStatusFile implements GitFile {
new GitCommit(
container,
this.repoPath,
GitRevision.uncommitted,
uncommitted,
new GitCommitIdentity('You', user?.email ?? undefined, now),
new GitCommitIdentity('You', user?.email ?? undefined, now),
'Uncommitted changes',
[GitRevision.uncommittedStaged],
[uncommittedStaged],
'Uncommitted changes',
new GitFileChange(
this.repoPath,
this.path,
this.status,
this.originalPath,
GitRevision.uncommittedStaged,
),
new GitFileChange(this.repoPath, this.path, this.status, this.originalPath, uncommittedStaged),
undefined,
[],
),
new GitCommit(
container,
this.repoPath,
GitRevision.uncommittedStaged,
uncommittedStaged,
new GitCommitIdentity('You', user?.email ?? undefined, older),
new GitCommitIdentity('You', user?.email ?? undefined, older),
'Uncommitted changes',
@ -518,7 +506,7 @@ export class GitStatusFile implements GitFile {
new GitCommit(
container,
this.repoPath,
this.workingTreeStatus != null ? GitRevision.uncommitted : GitRevision.uncommittedStaged,
this.workingTreeStatus != null ? uncommitted : uncommittedStaged,
new GitCommitIdentity('You', user?.email ?? undefined, now),
new GitCommitIdentity('You', user?.email ?? undefined, now),
'Uncommitted changes',

+ 2
- 2
src/git/models/worktree.ts View File

@ -4,7 +4,7 @@ import { Container } from '../../container';
import { memoize } from '../../system/decorators/memoize';
import { normalizePath, relative } from '../../system/path';
import type { GitBranch } from './branch';
import { GitRevision } from './reference';
import { shortenRevision } from './reference';
import type { GitStatus } from './status';
export class GitWorktree {
@ -32,7 +32,7 @@ export class GitWorktree {
case 'bare':
return '(bare)';
case 'detached':
return GitRevision.shorten(this.sha);
return shortenRevision(this.sha);
default:
return this.branch || this.friendlyPath;
}

+ 6
- 5
src/git/parsers/blameParser.ts View File

@ -4,8 +4,9 @@ import { getLines } from '../../system/string';
import type { GitBlame, GitBlameAuthor } from '../models/blame';
import type { GitCommitLine } from '../models/commit';
import { GitCommit, GitCommitIdentity } from '../models/commit';
import { uncommitted } from '../models/constants';
import { GitFileChange, GitFileIndexStatus } from '../models/file';
import { GitRevision } from '../models/reference';
import { isUncommitted } from '../models/reference';
import type { GitUser } from '../models/user';
interface BlameEntry {
@ -71,7 +72,7 @@ export class GitBlameParser {
switch (key) {
case 'author':
if (entry.sha === GitRevision.uncommitted) {
if (entry.sha === uncommitted) {
entry.author = 'You';
} else {
entry.author = line.slice(key.length + 1).trim();
@ -79,7 +80,7 @@ export class GitBlameParser {
break;
case 'author-mail': {
if (entry.sha === GitRevision.uncommitted) {
if (entry.sha === uncommitted) {
entry.authorEmail = currentUser?.email;
continue;
}
@ -106,7 +107,7 @@ export class GitBlameParser {
break;
case 'committer':
if (GitRevision.isUncommitted(entry.sha)) {
if (isUncommitted(entry.sha)) {
entry.committer = 'You';
} else {
entry.committer = line.slice(key.length + 1).trim();
@ -114,7 +115,7 @@ export class GitBlameParser {
break;
case 'committer-mail': {
if (GitRevision.isUncommitted(entry.sha)) {
if (isUncommitted(entry.sha)) {
entry.committerEmail = currentUser?.email;
continue;
}

+ 2
- 2
src/git/parsers/logParser.ts View File

@ -6,10 +6,10 @@ import { normalizePath, relative } from '../../system/path';
import { getLines } from '../../system/string';
import type { GitCommitLine } from '../models/commit';
import { GitCommit, GitCommitIdentity } from '../models/commit';
import { uncommitted } from '../models/constants';
import type { GitFile, GitFileChangeStats } from '../models/file';
import { GitFileChange, GitFileIndexStatus } from '../models/file';
import type { GitLog } from '../models/log';
import { GitRevision } from '../models/reference';
import type { GitUser } from '../models/user';
import { isUserMatch } from '../models/user';
@ -481,7 +481,7 @@ export class GitLogParser {
break;
case 97: // 'a': // author
if (GitRevision.uncommitted === entry.sha) {
if (uncommitted === entry.sha) {
entry.author = 'You';
} else {
entry.author = line.substring(4);

+ 2
- 2
src/git/remotes/bitbucket-server.ts View File

@ -2,7 +2,7 @@ import type { Range, Uri } from 'vscode';
import type { DynamicAutolinkReference } from '../../annotations/autolinks';
import type { AutolinkReference } from '../../config';
import { AutolinkType } from '../../config';
import { GitRevision } from '../models/reference';
import { isSha } from '../models/reference';
import type { Repository } from '../models/repository';
import { RemoteProvider } from './remoteProvider';
@ -91,7 +91,7 @@ export class BitbucketServerRemote extends RemoteProvider {
let index = path.indexOf('/', 1);
if (index !== -1) {
const sha = path.substring(1, index);
if (GitRevision.isSha(sha)) {
if (isSha(sha)) {
const uri = repository.toAbsoluteUri(path.substr(index), { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine, endLine: endLine };
}

+ 2
- 2
src/git/remotes/bitbucket.ts View File

@ -2,7 +2,7 @@ import type { Range, Uri } from 'vscode';
import type { DynamicAutolinkReference } from '../../annotations/autolinks';
import type { AutolinkReference } from '../../config';
import { AutolinkType } from '../../config';
import { GitRevision } from '../models/reference';
import { isSha } from '../models/reference';
import type { Repository } from '../models/repository';
import { RemoteProvider } from './remoteProvider';
@ -83,7 +83,7 @@ export class BitbucketRemote extends RemoteProvider {
let index = path.indexOf('/', 1);
if (index !== -1) {
const sha = path.substring(1, index);
if (GitRevision.isSha(sha)) {
if (isSha(sha)) {
const uri = repository.toAbsoluteUri(path.substr(index), { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine, endLine: endLine };
}

+ 2
- 2
src/git/remotes/gerrit.ts View File

@ -1,7 +1,7 @@
import type { Range, Uri } from 'vscode';
import type { DynamicAutolinkReference } from '../../annotations/autolinks';
import type { AutolinkReference } from '../../config';
import { GitRevision } from '../models/reference';
import { isSha } from '../models/reference';
import type { Repository } from '../models/repository';
import { RemoteProvider } from './remoteProvider';
@ -97,7 +97,7 @@ export class GerritRemote extends RemoteProvider {
let index = path.indexOf('/', 1);
if (index !== -1) {
const sha = path.substring(1, index);
if (GitRevision.isSha(sha) || sha == 'HEAD') {
if (isSha(sha) || sha == 'HEAD') {
const uri = repository.toAbsoluteUri(path.substr(index), { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine };
}

+ 2
- 2
src/git/remotes/gitea.ts View File

@ -2,7 +2,7 @@ import type { Range, Uri } from 'vscode';
import type { DynamicAutolinkReference } from '../../annotations/autolinks';
import type { AutolinkReference } from '../../config';
import { AutolinkType } from '../../config';
import { GitRevision } from '../models/reference';
import { isSha } from '../models/reference';
import type { Repository } from '../models/repository';
import { RemoteProvider } from './remoteProvider';
@ -79,7 +79,7 @@ export class GiteaRemote extends RemoteProvider {
index = path.indexOf('/', offset);
if (index !== -1) {
const sha = path.substring(offset, index);
if (GitRevision.isSha(sha)) {
if (isSha(sha)) {
const uri = repository.toAbsoluteUri(path.substr(index), { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine, endLine: endLine };
}

+ 2
- 2
src/git/remotes/github.ts View File

@ -15,7 +15,7 @@ import type { Account } from '../models/author';
import type { DefaultBranch } from '../models/defaultBranch';
import type { IssueOrPullRequest, SearchedIssue } from '../models/issue';
import type { PullRequest, PullRequestState, SearchedPullRequest } from '../models/pullRequest';
import { GitRevision } from '../models/reference';
import { isSha } from '../models/reference';
import type { Repository } from '../models/repository';
import { ensurePaidPlan, RichRemoteProvider } from './richRemoteProvider';
@ -180,7 +180,7 @@ export class GitHubRemote extends RichRemoteProvider {
let index = path.indexOf('/', 1);
if (index !== -1) {
const sha = path.substring(1, index);
if (GitRevision.isSha(sha)) {
if (isSha(sha)) {
const uri = repository.toAbsoluteUri(path.substr(index), { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine, endLine: endLine };
}

+ 2
- 2
src/git/remotes/gitlab.ts View File

@ -15,7 +15,7 @@ import type { Account } from '../models/author';
import type { DefaultBranch } from '../models/defaultBranch';
import type { IssueOrPullRequest, SearchedIssue } from '../models/issue';
import type { PullRequest, PullRequestState, SearchedPullRequest } from '../models/pullRequest';
import { GitRevision } from '../models/reference';
import { isSha } from '../models/reference';
import type { Repository } from '../models/repository';
import { ensurePaidPlan, RichRemoteProvider } from './richRemoteProvider';
@ -223,7 +223,7 @@ export class GitLabRemote extends RichRemoteProvider {
let index = path.indexOf('/', 1);
if (index !== -1) {
const sha = path.substring(1, index);
if (GitRevision.isSha(sha)) {
if (isSha(sha)) {
const uri = repository.toAbsoluteUri(path.substr(index), { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine, endLine: endLine };
}

+ 4
- 4
src/git/search.ts View File

@ -1,5 +1,5 @@
import type { GitRevisionReference } from './models/reference';
import { GitRevision } from './models/reference';
import { isSha, shortenRevision } from './models/reference';
import type { GitUser } from './models/user';
export type SearchOperators =
@ -91,13 +91,13 @@ export function getSearchQueryComparisonKey(search: SearchQuery | StoredSearchQu
export function createSearchQueryForCommit(ref: string): string;
export function createSearchQueryForCommit(commit: GitRevisionReference): string;
export function createSearchQueryForCommit(refOrCommit: string | GitRevisionReference) {
return `#:${typeof refOrCommit === 'string' ? GitRevision.shorten(refOrCommit) : refOrCommit.name}`;
return `#:${typeof refOrCommit === 'string' ? shortenRevision(refOrCommit) : refOrCommit.name}`;
}
export function createSearchQueryForCommits(refs: string[]): string;
export function createSearchQueryForCommits(commits: GitRevisionReference[]): string;
export function createSearchQueryForCommits(refsOrCommits: (string | GitRevisionReference)[]) {
return refsOrCommits.map(r => `#:${typeof r === 'string' ? GitRevision.shorten(r) : r.name}`).join(' ');
return refsOrCommits.map(r => `#:${typeof r === 'string' ? shortenRevision(r) : r.name}`).join(' ');
}
const normalizeSearchOperatorsMap = new Map<SearchOperators, SearchOperators>([
@ -133,7 +133,7 @@ export function parseSearchQuery(search: SearchQuery): Map {
({ value, text } = match.groups);
if (text) {
op = text === '@me' ? 'author:' : GitRevision.isSha(text) ? 'commit:' : 'message:';
op = text === '@me' ? 'author:' : isSha(text) ? 'commit:' : 'message:';
value = text;
}

+ 10
- 14
src/hovers/hovers.ts View File

@ -8,9 +8,10 @@ import { Container } from '../container';
import { CommitFormatter } from '../git/formatters/commitFormatter';
import { GitUri } from '../git/gitUri';
import type { GitCommit } from '../git/models/commit';
import { uncommittedStaged } from '../git/models/constants';
import type { GitDiffHunk, GitDiffHunkLine } from '../git/models/diff';
import type { PullRequest } from '../git/models/pullRequest';
import { GitRevision } from '../git/models/reference';
import { isUncommittedStaged, shortenRevision } from '../git/models/reference';
import type { GitRemote } from '../git/models/remote';
import { Logger } from '../logger';
import { getNewLogScope } from '../logScope';
@ -34,7 +35,7 @@ export async function changesMessage(
// TODO: Figure out how to optimize this
let ref;
if (commit.isUncommitted) {
if (GitRevision.isUncommittedStaged(documentRef)) {
if (isUncommittedStaged(documentRef)) {
ref = documentRef;
}
} else {
@ -60,13 +61,8 @@ export async function changesMessage(
let hunkLine = await Container.instance.git.getDiffForLine(uri, editorLine, ref, documentRef);
// If we didn't find a diff & ref is undefined (meaning uncommitted), check for a staged diff
if (hunkLine == null && ref == null && documentRef !== GitRevision.uncommittedStaged) {
hunkLine = await Container.instance.git.getDiffForLine(
uri,
editorLine,
undefined,
GitRevision.uncommittedStaged,
);
if (hunkLine == null && ref == null && documentRef !== uncommittedStaged) {
hunkLine = await Container.instance.git.getDiffForLine(uri, editorLine, undefined, uncommittedStaged);
}
return hunkLine != null ? getDiffFromHunkLine(hunkLine) : undefined;
@ -97,10 +93,10 @@ export async function changesMessage(
previous =
compareUris.previous.sha == null || compareUris.previous.isUncommitted
? ` &nbsp;_${GitRevision.shorten(compareUris.previous.sha, {
? ` &nbsp;_${shortenRevision(compareUris.previous.sha, {
strings: { working: 'Working Tree' },
})}_ &nbsp;${GlyphChars.ArrowLeftRightLong}&nbsp; `
: ` &nbsp;[$(git-commit) ${GitRevision.shorten(
: ` &nbsp;[$(git-commit) ${shortenRevision(
compareUris.previous.sha || '',
)}](${ShowQuickCommitCommand.getMarkdownCommandArgs(
compareUris.previous.sha || '',
@ -108,12 +104,12 @@ export async function changesMessage(
current =
compareUris.current.sha == null || compareUris.current.isUncommitted
? `_${GitRevision.shorten(compareUris.current.sha, {
? `_${shortenRevision(compareUris.current.sha, {
strings: {
working: 'Working Tree',
},
})}_`
: `[$(git-commit) ${GitRevision.shorten(
: `[$(git-commit) ${shortenRevision(
compareUris.current.sha || '',
)}](${ShowQuickCommitCommand.getMarkdownCommandArgs(compareUris.current.sha || '')} "Show Commit")`;
} else {
@ -123,7 +119,7 @@ export async function changesMessage(
previousSha = await commit.getPreviousSha();
}
if (previousSha) {
previous = ` &nbsp;[$(git-commit) ${GitRevision.shorten(
previous = ` &nbsp;[$(git-commit) ${shortenRevision(
previousSha,
)}](${ShowQuickCommitCommand.getMarkdownCommandArgs(previousSha)} "Show Commit") &nbsp;${
GlyphChars.ArrowLeftRightLong

+ 2
- 2
src/plus/github/github.ts View File

@ -23,7 +23,7 @@ import type { Account } from '../../git/models/author';
import type { DefaultBranch } from '../../git/models/defaultBranch';
import type { IssueOrPullRequest, SearchedIssue } from '../../git/models/issue';
import type { PullRequest, SearchedPullRequest } from '../../git/models/pullRequest';
import { GitRevision } from '../../git/models/reference';
import { isSha } from '../../git/models/reference';
import type { GitUser } from '../../git/models/user';
import { getGitHubNoReplyAddressParts } from '../../git/remotes/github';
import type { RichRemoteProvider } from '../../git/remotes/richRemoteProvider';
@ -978,7 +978,7 @@ export class GitHubApi implements Disposable {
ref: string,
path: string,
): Promise<(GitHubCommit & { viewer?: string }) | undefined> {
if (GitRevision.isSha(ref)) return this.getCommit(token, owner, repo, ref);
if (isSha(ref)) return this.getCommit(token, owner, repo, ref);
// TODO: optimize this -- only need to get the sha for the ref
const results = await this.getCommits(token, owner, repo, ref, { limit: 1, path: path });

+ 24
- 23
src/plus/github/githubGitProvider.ts View File

@ -43,6 +43,7 @@ import type { BranchSortOptions } from '../../git/models/branch';
import { getBranchId, GitBranch, sortBranches } from '../../git/models/branch';
import type { GitCommitLine, GitCommitStats } from '../../git/models/commit';
import { getChangedFilesCount, GitCommit, GitCommitIdentity } from '../../git/models/commit';
import { deletedOrMissing, uncommitted } from '../../git/models/constants';
import { GitContributor } from '../../git/models/contributor';
import type { GitDiff, GitDiffFilter, GitDiffHunkLine, GitDiffShortStat } from '../../git/models/diff';
import type { GitFile } from '../../git/models/file';
@ -59,8 +60,8 @@ import { GitGraphRowType } from '../../git/models/graph';
import type { GitLog } from '../../git/models/log';
import type { GitMergeStatus } from '../../git/models/merge';
import type { GitRebaseStatus } from '../../git/models/rebase';
import type { GitBranchReference } from '../../git/models/reference';
import { GitReference, GitRevision } from '../../git/models/reference';
import type { GitBranchReference, GitReference } from '../../git/models/reference';
import { createReference, isRevisionRange, isSha, isShaLike, isUncommitted } from '../../git/models/reference';
import type { GitReflog } from '../../git/models/reflog';
import { getRemoteIconUri, GitRemote, GitRemoteType } from '../../git/models/remote';
import type { RepositoryChangeEvent } from '../../git/models/repository';
@ -350,7 +351,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
getRevisionUri(repoPath: string, path: string, ref: string): Uri {
const uri = this.createProviderUri(repoPath, ref, path);
return ref === GitRevision.deletedOrMissing ? uri.with({ query: '~' }) : uri;
return ref === deletedOrMissing ? uri.with({ query: '~' }) : uri;
}
@log()
@ -1209,7 +1210,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
}`,
webviewItemValue: {
type: 'branch',
ref: GitReference.create(branch.name, repoPath, {
ref: createReference(branch.name, repoPath, {
refType: 'branch',
name: branch.name,
remote: false,
@ -1234,7 +1235,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
webviewItem: 'gitlens:branch+remote',
webviewItemValue: {
type: 'branch',
ref: GitReference.create(branch.name, repoPath, {
ref: createReference(branch.name, repoPath, {
refType: 'branch',
name: branch.name,
remote: true,
@ -1263,7 +1264,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
webviewItem: 'gitlens:tag',
webviewItemValue: {
type: 'tag',
ref: GitReference.create(t.name, repoPath, {
ref: createReference(t.name, repoPath, {
refType: 'tag',
name: t.name,
}),
@ -1291,7 +1292,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
}+current`,
webviewItemValue: {
type: 'commit',
ref: GitReference.create(commit.sha, repoPath, {
ref: createReference(commit.sha, repoPath, {
refType: 'revision',
message: commit.message,
}),
@ -1498,7 +1499,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
@log()
async getFileStatusForCommit(repoPath: string, uri: Uri, ref: string): Promise<GitFile | undefined> {
if (ref === GitRevision.deletedOrMissing || GitRevision.isUncommitted(ref)) return undefined;
if (ref === deletedOrMissing || isUncommitted(ref)) return undefined;
const commit = await this.getCommitForFile(repoPath, uri, { ref: ref });
if (commit == null) return undefined;
@ -1657,7 +1658,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
moreLimit = this.getPagingLimit(moreLimit);
// // If the log is for a range, then just get everything prior + more
// if (GitRevision.isRange(log.sha)) {
// if (isRange(log.sha)) {
// const moreLog = await this.getLog(log.repoPath, {
// ...options,
// limit: moreLimit === 0 ? 0 : (options?.limit ?? 0) + moreLimit,
@ -2162,11 +2163,11 @@ export class GitHubGitProvider implements GitProvider, Disposable {
skip: number = 0,
_firstParent: boolean = false,
): Promise<PreviousComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
const scope = getLogScope();
if (ref === GitRevision.uncommitted) {
if (ref === uncommitted) {
ref = undefined;
}
@ -2199,10 +2200,10 @@ export class GitHubGitProvider implements GitProvider, Disposable {
await this.getBestRevisionUri(
repoPath,
relativePath,
result.values[offset + skip - 1]?.oid ?? GitRevision.deletedOrMissing,
result.values[offset + skip - 1]?.oid ?? deletedOrMissing,
),
);
if (current == null || current.sha === GitRevision.deletedOrMissing) return undefined;
if (current == null || current.sha === deletedOrMissing) return undefined;
return {
current: current,
@ -2210,7 +2211,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
await this.getBestRevisionUri(
repoPath,
relativePath,
result.values[offset + skip]?.oid ?? GitRevision.deletedOrMissing,
result.values[offset + skip]?.oid ?? deletedOrMissing,
),
),
};
@ -2230,7 +2231,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
ref: string | undefined,
skip: number = 0,
): Promise<PreviousLineComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined;
if (ref === deletedOrMissing) return undefined;
const scope = getLogScope();
@ -2573,9 +2574,9 @@ export class GitHubGitProvider implements GitProvider, Disposable {
) {
if (
!ref ||
ref === GitRevision.deletedOrMissing ||
(pathOrUri == null && GitRevision.isSha(ref)) ||
(pathOrUri != null && GitRevision.isUncommitted(ref))
ref === deletedOrMissing ||
(pathOrUri == null && isSha(ref)) ||
(pathOrUri != null && isUncommitted(ref))
) {
return ref;
}
@ -2583,7 +2584,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
let relativePath;
if (pathOrUri != null) {
relativePath = this.getRelativePath(pathOrUri, repoPath);
} else if (!GitRevision.isShaLike(ref) || ref.endsWith('^3')) {
} else if (!isShaLike(ref) || ref.endsWith('^3')) {
// If it doesn't look like a sha at all (e.g. branch name) or is a stash ref (^3) don't try to resolve it
return ref;
}
@ -2603,7 +2604,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
if (resolved != null) return resolved;
return relativePath ? GitRevision.deletedOrMissing : ref;
return relativePath ? deletedOrMissing : ref;
}
@log()
@ -3100,7 +3101,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
if (typeof ref === 'string') {
if (ref) {
if (GitRevision.isSha(ref)) {
if (isSha(ref)) {
metadata = { v: 1, ref: { id: ref, type: 2 /* RepositoryRefType.Commit */ } };
} else {
metadata = { v: 1, ref: { id: ref, type: 4 /* RepositoryRefType.Tree */ } };
@ -3168,10 +3169,10 @@ export class GitHubGitProvider implements GitProvider, Disposable {
return revision.revision;
}
if (GitRevision.isSha(ref)) return ref;
if (isSha(ref)) return ref;
// TODO@eamodio need to handle ranges
if (GitRevision.isRange(ref)) return undefined;
if (isRevisionRange(ref)) return undefined;
const [branchResults, tagResults] = await Promise.allSettled([
this.getBranches(repoPath, { filter: b => b.name === ref }),

+ 25
- 19
src/plus/webviews/graph/graphWebview.ts View File

@ -41,16 +41,24 @@ import * as TagActions from '../../../git/actions/tag';
import * as WorktreeActions from '../../../git/actions/worktree';
import { GitSearchError } from '../../../git/errors';
import { getBranchId, getBranchNameWithoutRemote, getRemoteNameFromBranchName } from '../../../git/models/branch';
import { uncommitted } from '../../../git/models/constants';
import { GitContributor } from '../../../git/models/contributor';
import type { GitGraph } from '../../../git/models/graph';
import { GitGraphRowType } from '../../../git/models/graph';
import type {
GitBranchReference,
GitReference,
GitRevisionReference,
GitStashReference,
GitTagReference,
} from '../../../git/models/reference';
import { GitReference, GitRevision } from '../../../git/models/reference';
import {
createReference,
getReferenceFromBranch,
getReferenceLabel,
isSha,
shortenRevision,
} from '../../../git/models/reference';
import { getRemoteIconUri } from '../../../git/models/remote';
import { RemoteResourceType } from '../../../git/models/remoteResource';
import type { RepositoryChangeEvent, RepositoryFileSystemChangeEvent } from '../../../git/models/repository';
@ -272,7 +280,7 @@ export class GraphWebview extends WebviewBase {
} else {
this.repository = this.container.git.getRepository(args.ref.repoPath);
id = args.ref.ref;
if (!GitRevision.isSha(id)) {
if (!isSha(id)) {
id = await this.container.git.resolveReference(args.ref.repoPath, id, undefined, {
force: true,
});
@ -890,7 +898,7 @@ export class GraphWebview extends WebviewBase {
webviewItem: 'gitlens:upstreamStatus',
webviewItemValue: {
type: 'upstreamStatus',
ref: GitReference.fromBranch(branch),
ref: getReferenceFromBranch(branch),
ahead: branch.state.ahead,
behind: branch.state.behind,
},
@ -1126,17 +1134,17 @@ export class GraphWebview extends WebviewBase {
switch (type) {
case GitGraphRowType.Stash:
return GitReference.create(id, repoPath, {
return createReference(id, repoPath, {
refType: 'stash',
name: id,
number: undefined,
});
case GitGraphRowType.Working:
return GitReference.create(GitRevision.uncommitted, repoPath, { refType: 'revision' });
return createReference(uncommitted, repoPath, { refType: 'revision' });
default:
return GitReference.create(id, repoPath, { refType: 'revision' });
return createReference(id, repoPath, { refType: 'revision' });
}
}
@ -1753,11 +1761,7 @@ export class GraphWebview extends WebviewBase {
webviewItem: 'gitlens:wip',
webviewItemValue: {
type: 'commit',
ref: this.getRevisionReference(
this.repository.path,
GitRevision.uncommitted,
GitGraphRowType.Working,
)!,
ref: this.getRevisionReference(this.repository.path, uncommitted, GitGraphRowType.Working)!,
},
}),
};
@ -1790,8 +1794,7 @@ export class GraphWebview extends WebviewBase {
// If we have a set of data refresh to the same set
const limit = Math.max(defaultItemLimit, this._graph?.ids.size ?? defaultItemLimit);
const ref =
this._selectedId == null || this._selectedId === GitRevision.uncommitted ? 'HEAD' : this._selectedId;
const ref = this._selectedId == null || this._selectedId === uncommitted ? 'HEAD' : this._selectedId;
const columns = this.getColumns();
const columnSettings = this.getColumnSettings(columns);
@ -1960,7 +1963,7 @@ export class GraphWebview extends WebviewBase {
if (this._selectedId === id) return;
this._selectedId = id;
if (id === GitRevision.uncommitted) {
if (id === uncommitted) {
id = GitGraphRowType.Working;
}
this._selectedRows = id != null ? { [id]: true } : undefined;
@ -2091,7 +2094,7 @@ export class GraphWebview extends WebviewBase {
if (ref.upstream != null) {
return RepoActions.rebase(
ref.repoPath,
GitReference.create(ref.upstream.name, ref.repoPath, {
createReference(ref.upstream.name, ref.repoPath, {
refType: 'branch',
name: ref.upstream.name,
remote: true,
@ -2157,7 +2160,7 @@ export class GraphWebview extends WebviewBase {
if (ref == null) return Promise.resolve();
let sha = ref.ref;
if (!GitRevision.isSha(sha)) {
if (!isSha(sha)) {
sha = await this.container.git.resolveReference(ref.repoPath, sha, undefined, { force: true });
}
@ -2250,7 +2253,7 @@ export class GraphWebview extends WebviewBase {
return RepoActions.reset(
ref.repoPath,
GitReference.create(`${ref.ref}^`, ref.repoPath, {
createReference(`${ref.ref}^`, ref.repoPath, {
refType: 'revision',
name: `${ref.name}^`,
message: ref.message,
@ -2331,7 +2334,7 @@ export class GraphWebview extends WebviewBase {
if (commit?.hash !== ref.ref) {
void window.showWarningMessage(
`Commit ${GitReference.toString(ref, {
`Commit ${getReferenceLabel(ref, {
capitalize: true,
icon: false,
})} cannot be undone, because it is no longer the most recent commit.`,
@ -2460,7 +2463,10 @@ export class GraphWebview extends WebviewBase {
return this.container.searchAndCompareView.compare(
ref.repoPath,
{ ref: commonAncestor, label: `ancestry with ${ref.ref} (${GitRevision.shorten(commonAncestor)})` },
{
ref: commonAncestor,
label: `ancestry with ${ref.ref} (${shortenRevision(commonAncestor)})`,
},
'',
);
}

+ 10
- 9
src/quickpicks/items/gitCommands.ts View File

@ -8,7 +8,8 @@ import type { GitBranch } from '../../git/models/branch';
import type { GitCommit } from '../../git/models/commit';
import { isStash } from '../../git/models/commit';
import type { GitContributor } from '../../git/models/contributor';
import { GitReference, GitRevision } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { createReference, isRevisionRange, shortenRevision } from '../../git/models/reference';
import type { GitRemote } from '../../git/models/remote';
import { getRemoteUpstreamDescription, GitRemoteType } from '../../git/models/remote';
import type { Repository } from '../../git/models/repository';
@ -107,8 +108,8 @@ export async function createBranchQuickPickItem(
if (options?.ref) {
if (branch.sha) {
description = description
? `${description} $(git-commit)${GlyphChars.Space}${GitRevision.shorten(branch.sha)}`
: `$(git-commit)${GlyphChars.Space}${GitRevision.shorten(branch.sha)}`;
? `${description} $(git-commit)${GlyphChars.Space}${shortenRevision(branch.sha)}`
: `$(git-commit)${GlyphChars.Space}${shortenRevision(branch.sha)}`;
}
if (branch.date !== undefined) {
@ -253,7 +254,7 @@ export function createRefQuickPickItem(
alwaysShow: options?.alwaysShow,
buttons: options?.buttons,
picked: picked,
item: GitReference.create(ref, repoPath, { refType: 'revision', name: 'Working Tree' }),
item: createReference(ref, repoPath, { refType: 'revision', name: 'Working Tree' }),
current: false,
ref: ref,
remote: false,
@ -267,7 +268,7 @@ export function createRefQuickPickItem(
alwaysShow: options?.alwaysShow,
buttons: options?.buttons,
picked: picked,
item: GitReference.create(ref, repoPath, { refType: 'revision', name: 'HEAD' }),
item: createReference(ref, repoPath, { refType: 'revision', name: 'HEAD' }),
current: false,
ref: ref,
remote: false,
@ -276,13 +277,13 @@ export function createRefQuickPickItem(
let gitRef;
if (typeof ref === 'string') {
gitRef = GitReference.create(ref, repoPath);
gitRef = createReference(ref, repoPath);
} else {
gitRef = ref;
ref = gitRef.ref;
}
if (GitRevision.isRange(ref)) {
if (isRevisionRange(ref)) {
return {
label: `Range ${gitRef.name}`,
description: '',
@ -435,7 +436,7 @@ export function createTagQuickPickItem(
}
if (options?.ref) {
description = `${description}${pad('$(git-commit)', description ? 2 : 0, 1)}${GitRevision.shorten(tag.sha)}`;
description = `${description}${pad('$(git-commit)', description ? 2 : 0, 1)}${shortenRevision(tag.sha)}`;
description = `${description ? `${description}${pad(GlyphChars.Dot, 2, 2)}` : ''}${tag.formattedDate}`;
}
@ -501,7 +502,7 @@ export function createWorktreeQuickPickItem(
icon = '$(git-branch)';
break;
case 'detached':
label = GitRevision.shorten(worktree.sha);
label = shortenRevision(worktree.sha);
icon = '$(git-commit)';
break;
}

+ 5
- 4
src/quickpicks/referencePicker.ts View File

@ -11,7 +11,8 @@ import { reveal as revealBranch } from '../git/actions/branch';
import { showDetailsView } from '../git/actions/commit';
import { reveal as revealTag } from '../git/actions/tag';
import type { BranchSortOptions, GitBranch } from '../git/models/branch';
import { GitReference } from '../git/models/reference';
import type { GitReference } from '../git/models/reference';
import { isBranchReference, isRevisionReference, isTagReference } from '../git/models/reference';
import type { GitTag, TagSortOptions } from '../git/models/tag';
import type { KeyboardScope, Keys } from '../keyboard';
import { getQuickPickIgnoreFocusOut } from '../system/utils';
@ -137,11 +138,11 @@ export async function showReferencePicker(
}),
quickpick.onDidTriggerItemButton(({ button, item: { item } }) => {
if (button === RevealInSideBarQuickInputButton) {
if (GitReference.isBranch(item)) {
if (isBranchReference(item)) {
void revealBranch(item, { select: true, expand: true });
} else if (GitReference.isTag(item)) {
} else if (isTagReference(item)) {
void revealTag(item, { select: true, expand: true });
} else if (GitReference.isRevision(item)) {
} else if (isRevisionReference(item)) {
void showDetailsView(item, {
pin: false,
preserveFocus: true,

+ 2
- 2
src/terminal/linkProvider.ts View File

@ -12,7 +12,7 @@ import type { Container } from '../container';
import type { PagedResult } from '../git/gitProvider';
import type { GitBranch } from '../git/models/branch';
import { getBranchNameWithoutRemote } from '../git/models/branch';
import { GitReference } from '../git/models/reference';
import { createReference } from '../git/models/reference';
import type { GitTag } from '../git/models/tag';
const commandsRegexShared =
@ -157,7 +157,7 @@ export class GitTerminalLinkProvider implements Disposable, TerminalLinkProvider
command: 'log',
state: {
repo: repoPath,
reference: GitReference.create(ref, repoPath, { refType: 'revision' }),
reference: createReference(ref, repoPath, { refType: 'revision' }),
},
},
},

+ 2
- 2
src/trackers/trackedDocument.ts View File

@ -4,7 +4,7 @@ import { ContextKeys } from '../constants';
import type { Container } from '../container';
import { setContext } from '../context';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models/reference';
import { deletedOrMissing } from '../git/models/constants';
import { Logger } from '../logger';
import type { Deferrable } from '../system/function';
import { debounce } from '../system/function';
@ -88,7 +88,7 @@ export class TrackedDocument implements Disposable {
}
get isRevision() {
return this._uri != null ? Boolean(this._uri.sha) && this._uri.sha !== GitRevision.deletedOrMissing : false;
return this._uri != null ? Boolean(this._uri.sha) && this._uri.sha !== deletedOrMissing : false;
}
private _isTracked: boolean = false;

+ 3
- 2
src/uris/deepLinks/deepLinkService.ts View File

@ -3,7 +3,8 @@ import { configuration } from '../../configuration';
import { Commands } from '../../constants';
import type { Container } from '../../container';
import { getBranchNameWithoutRemote } from '../../git/models/branch';
import { GitReference } from '../../git/models/reference';
import type { GitReference } from '../../git/models/reference';
import { createReference } from '../../git/models/reference';
import type { GitRemote } from '../../git/models/remote';
import { parseGitRemoteUrl } from '../../git/parsers/remoteParser';
import { Logger } from '../../logger';
@ -453,7 +454,7 @@ export class DeepLinkService implements Disposable {
}
void (await executeCommand<ShowInCommitGraphCommandArgs>(Commands.ShowInCommitGraph, {
ref: GitReference.create(targetSha, repo.path),
ref: createReference(targetSha, repo.path),
}));
action = DeepLinkServiceAction.DeepLinkResolved;

+ 9
- 3
src/views/branchesView.ts View File

@ -8,7 +8,7 @@ import { GitUri } from '../git/gitUri';
import type { GitCommit } from '../git/models/commit';
import { isCommit } from '../git/models/commit';
import type { GitBranchReference, GitRevisionReference } from '../git/models/reference';
import { GitReference } from '../git/models/reference';
import { getReferenceLabel } from '../git/models/reference';
import type { RepositoryChangeEvent } from '../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../git/models/repository';
import { executeCommand } from '../system/command';
@ -259,7 +259,10 @@ export class BranchesView extends ViewBase
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(branch, { icon: false, quoted: true })} in the side bar...`,
title: `Revealing ${getReferenceLabel(branch, {
icon: false,
quoted: true,
})} in the side bar...`,
cancellable: true,
},
async (progress, token) => {
@ -285,7 +288,10 @@ export class BranchesView extends ViewBase
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(commit, { icon: false, quoted: true })} in the side bar...`,
title: `Revealing ${getReferenceLabel(commit, {
icon: false,
quoted: true,
})} in the side bar...`,
cancellable: true,
},
async (progress, token) => {

+ 5
- 2
src/views/commitsView.ts View File

@ -14,7 +14,7 @@ import { GitUri } from '../git/gitUri';
import type { GitCommit } from '../git/models/commit';
import { isCommit } from '../git/models/commit';
import type { GitRevisionReference } from '../git/models/reference';
import { GitReference } from '../git/models/reference';
import { getReferenceLabel } from '../git/models/reference';
import type { RepositoryChangeEvent } from '../git/models/repository';
import { Repository, RepositoryChange, RepositoryChangeComparisonMode } from '../git/models/repository';
import { executeCommand } from '../system/command';
@ -400,7 +400,10 @@ export class CommitsView extends ViewBase {
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(commit, { icon: false, quoted: true })} in the side bar...`,
title: `Revealing ${getReferenceLabel(commit, {
icon: false,
quoted: true,
})} in the side bar...`,
cancellable: true,
},
async (progress, token) => {

+ 5
- 5
src/views/nodes/UncommittedFilesNode.ts View File

@ -4,9 +4,9 @@ import { ViewFilesLayout } from '../../config';
import { GitUri } from '../../git/gitUri';
import type { GitTrackingState } from '../../git/models/branch';
import { GitCommit, GitCommitIdentity } from '../../git/models/commit';
import { uncommitted, uncommittedStaged } from '../../git/models/constants';
import type { GitFileWithCommit } from '../../git/models/file';
import { GitFileChange } from '../../git/models/file';
import { GitRevision } from '../../git/models/reference';
import type { GitStatus, GitStatusFile } from '../../git/models/status';
import { groupBy, makeHierarchical } from '../../system/array';
import { flatMap } from '../../system/iterable';
@ -59,14 +59,14 @@ export class UncommittedFilesNode extends ViewNode
older.setMilliseconds(older.getMilliseconds() - 1);
return [
this.getFileWithPseudoCommit(f, GitRevision.uncommitted, GitRevision.uncommittedStaged),
this.getFileWithPseudoCommit(f, GitRevision.uncommittedStaged, 'HEAD', older),
this.getFileWithPseudoCommit(f, uncommitted, uncommittedStaged),
this.getFileWithPseudoCommit(f, uncommittedStaged, 'HEAD', older),
];
} else if (f.indexStatus != null) {
return [this.getFileWithPseudoCommit(f, GitRevision.uncommittedStaged, 'HEAD')];
return [this.getFileWithPseudoCommit(f, uncommittedStaged, 'HEAD')];
}
return [this.getFileWithPseudoCommit(f, GitRevision.uncommitted, 'HEAD')];
return [this.getFileWithPseudoCommit(f, uncommitted, 'HEAD')];
}),
];

+ 2
- 6
src/views/nodes/branchTrackingStatusFilesNode.ts View File

@ -3,7 +3,7 @@ import { ViewFilesLayout } from '../../configuration';
import { GitUri } from '../../git/gitUri';
import type { GitBranch } from '../../git/models/branch';
import type { GitFileWithCommit } from '../../git/models/file';
import { GitRevision } from '../../git/models/reference';
import { createRevisionRange } from '../../git/models/reference';
import { groupBy, makeHierarchical } from '../../system/array';
import { filter, flatMap, map } from '../../system/iterable';
import { joinPaths, normalizePath } from '../../system/path';
@ -50,11 +50,7 @@ export class BranchTrackingStatusFilesNode extends ViewNode {
async getChildren(): Promise<ViewNode[]> {
const log = await this.view.container.git.getLog(this.repoPath, {
limit: 0,
ref: GitRevision.createRange(
this.status.upstream,
this.branch.ref,
this.direction === 'behind' ? '...' : '..',
),
ref: createRevisionRange(this.status.upstream, this.branch.ref, this.direction === 'behind' ? '...' : '..'),
});
let files: GitFileWithCommit[];

+ 3
- 3
src/views/nodes/branchTrackingStatusNode.ts View File

@ -4,7 +4,7 @@ import { GitUri } from '../../git/gitUri';
import type { GitBranch, GitTrackingState } from '../../git/models/branch';
import { getRemoteNameFromBranchName } from '../../git/models/branch';
import type { GitLog } from '../../git/models/log';
import { GitRevision } from '../../git/models/reference';
import { createRevisionRange } from '../../git/models/reference';
import { GitRemote } from '../../git/models/remote';
import { fromNow } from '../../system/date';
import { gate } from '../../system/decorators/gate';
@ -282,8 +282,8 @@ export class BranchTrackingStatusNode extends ViewNode impleme
if (this._log == null) {
const range =
this.upstreamType === 'ahead'
? GitRevision.createRange(this.status.upstream, this.status.ref)
: GitRevision.createRange(this.status.ref, this.status.upstream);
? createRevisionRange(this.status.upstream, this.status.ref)
: createRevisionRange(this.status.ref, this.status.upstream);
this._log = await this.view.container.git.getLog(this.uri.repoPath!, {
limit: this.limit ?? this.view.config.defaultItemLimit,

+ 12
- 11
src/views/nodes/compareBranchNode.ts View File

@ -3,7 +3,7 @@ import { ViewShowBranchComparison } from '../../configuration';
import { GlyphChars } from '../../constants';
import type { GitUri } from '../../git/gitUri';
import type { GitBranch } from '../../git/models/branch';
import { GitRevision } from '../../git/models/reference';
import { createRevisionRange, shortenRevision } from '../../git/models/reference';
import { CommandQuickPickItem } from '../../quickpicks/items/common';
import { showReferencePicker } from '../../quickpicks/referencePicker';
import type { StoredBranchComparison, StoredBranchComparisons } from '../../storage';
@ -75,7 +75,7 @@ export class CompareBranchNode extends ViewNode
const behind = this.behind;
const aheadBehindCounts = await this.view.container.git.getAheadBehindCommitCount(this.branch.repoPath, [
GitRevision.createRange(behind.ref1, behind.ref2, '...'),
createRevisionRange(behind.ref1, behind.ref2, '...'),
]);
const mergeBase =
(await this.view.container.git.getMergeBase(this.repoPath, behind.ref1, behind.ref2, {
@ -89,7 +89,7 @@ export class CompareBranchNode extends ViewNode
this.repoPath,
'Behind',
{
query: this.getCommitsQuery(GitRevision.createRange(behind.ref1, behind.ref2, '..')),
query: this.getCommitsQuery(createRevisionRange(behind.ref1, behind.ref2, '..')),
comparison: behind,
direction: 'behind',
files: {
@ -111,7 +111,7 @@ export class CompareBranchNode extends ViewNode
'Ahead',
{
query: this.getCommitsQuery(
GitRevision.createRange(ahead.ref1, this.compareWithWorkingTree ? '' : ahead.ref2, '..'),
createRevisionRange(ahead.ref1, this.compareWithWorkingTree ? '' : ahead.ref2, '..'),
),
comparison: ahead,
direction: 'ahead',
@ -157,11 +157,12 @@ export class CompareBranchNode extends ViewNode
this.compareWithWorkingTree ? 'Working Tree' : this.branch.name
} with a branch, tag, or ref`;
} else {
label = `Compare ${
this.compareWithWorkingTree ? 'Working Tree' : this.branch.name
} with ${GitRevision.shorten(this._compareWith.ref, {
strings: { working: 'Working Tree' },
})}`;
label = `Compare ${this.compareWithWorkingTree ? 'Working Tree' : this.branch.name} with ${shortenRevision(
this._compareWith.ref,
{
strings: { working: 'Working Tree' },
},
)}`;
state = TreeItemCollapsibleState.Collapsed;
}
@ -253,7 +254,7 @@ export class CompareBranchNode extends ViewNode
}
private async getAheadFilesQuery(): Promise<FilesQueryResults> {
const comparison = GitRevision.createRange(this._compareWith?.ref || 'HEAD', this.branch.ref || 'HEAD', '...');
const comparison = createRevisionRange(this._compareWith?.ref || 'HEAD', this.branch.ref || 'HEAD', '...');
const [filesResult, workingFilesResult, statsResult, workingStatsResult] = await Promise.allSettled([
this.view.container.git.getDiffStatus(this.repoPath, comparison),
@ -307,7 +308,7 @@ export class CompareBranchNode extends ViewNode
}
private async getBehindFilesQuery(): Promise<FilesQueryResults> {
const comparison = GitRevision.createRange(this.branch.ref, this._compareWith?.ref || 'HEAD', '...');
const comparison = createRevisionRange(this.branch.ref, this._compareWith?.ref || 'HEAD', '...');
const [filesResult, statsResult] = await Promise.allSettled([
this.view.container.git.getDiffStatus(this.repoPath, comparison),

+ 8
- 8
src/views/nodes/compareResultsNode.ts View File

@ -1,7 +1,7 @@
import { ThemeIcon, TreeItem, TreeItemCollapsibleState, window } from 'vscode';
import { md5 } from '@env/crypto';
import { GitUri } from '../../git/gitUri';
import { GitRevision } from '../../git/models/reference';
import { createRevisionRange, shortenRevision } from '../../git/models/reference';
import type { StoredNamedRef } from '../../storage';
import { gate } from '../../system/decorators/gate';
import { debug, log } from '../../system/decorators/log';
@ -79,7 +79,7 @@ export class CompareResultsNode extends ViewNode {
const behind = this.behind;
const aheadBehindCounts = await this.view.container.git.getAheadBehindCommitCount(this.repoPath, [
GitRevision.createRange(behind.ref1 || 'HEAD', behind.ref2, '...'),
createRevisionRange(behind.ref1 || 'HEAD', behind.ref2, '...'),
]);
const mergeBase =
(await this.view.container.git.getMergeBase(this.repoPath, behind.ref1, behind.ref2, {
@ -93,7 +93,7 @@ export class CompareResultsNode extends ViewNode {
this.repoPath,
'Behind',
{
query: this.getCommitsQuery(GitRevision.createRange(behind.ref1, behind.ref2, '..')),
query: this.getCommitsQuery(createRevisionRange(behind.ref1, behind.ref2, '..')),
comparison: behind,
direction: 'behind',
files: {
@ -114,7 +114,7 @@ export class CompareResultsNode extends ViewNode {
this.repoPath,
'Ahead',
{
query: this.getCommitsQuery(GitRevision.createRange(ahead.ref1, ahead.ref2, '..')),
query: this.getCommitsQuery(createRevisionRange(ahead.ref1, ahead.ref2, '..')),
comparison: ahead,
direction: 'ahead',
files: {
@ -155,10 +155,10 @@ export class CompareResultsNode extends ViewNode {
const item = new TreeItem(
`Comparing ${
this._ref.label ?? GitRevision.shorten(this._ref.ref, { strings: { working: 'Working Tree' } })
this._ref.label ?? shortenRevision(this._ref.ref, { strings: { working: 'Working Tree' } })
} with ${
this._compareWith.label ??
GitRevision.shorten(this._compareWith.ref, { strings: { working: 'Working Tree' } })
shortenRevision(this._compareWith.ref, { strings: { working: 'Working Tree' } })
}`,
TreeItemCollapsibleState.Collapsed,
);
@ -239,14 +239,14 @@ export class CompareResultsNode extends ViewNode {
private async getAheadFilesQuery(): Promise<FilesQueryResults> {
return this.getAheadBehindFilesQuery(
GitRevision.createRange(this._compareWith?.ref || 'HEAD', this._ref.ref || 'HEAD', '...'),
createRevisionRange(this._compareWith?.ref || 'HEAD', this._ref.ref || 'HEAD', '...'),
this._ref.ref === '',
);
}
private async getBehindFilesQuery(): Promise<FilesQueryResults> {
return this.getAheadBehindFilesQuery(
GitRevision.createRange(this._ref.ref || 'HEAD', this._compareWith.ref || 'HEAD', '...'),
createRevisionRange(this._ref.ref || 'HEAD', this._compareWith.ref || 'HEAD', '...'),
false,
);
}

+ 3
- 5
src/views/nodes/fileHistoryNode.ts View File

@ -2,8 +2,8 @@ import { Disposable, TreeItem, TreeItemCollapsibleState, Uri, window } from 'vsc
import { configuration } from '../../configuration';
import type { GitUri } from '../../git/gitUri';
import type { GitBranch } from '../../git/models/branch';
import { deletedOrMissing } from '../../git/models/constants';
import type { GitLog } from '../../git/models/log';
import { GitRevision } from '../../git/models/reference';
import type { RepositoryChangeEvent, RepositoryFileSystemChangeEvent } from '../../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../../git/models/repository';
import { Logger } from '../../logger';
@ -156,15 +156,13 @@ export class FileHistoryNode extends SubscribeableViewNode impl
if (this.folder && this.uri.fileName === '') {
return `${basename(this.uri.path)}${
this.uri.sha
? ` ${this.uri.sha === GitRevision.deletedOrMissing ? this.uri.shortSha : `(${this.uri.shortSha})`}`
? ` ${this.uri.sha === deletedOrMissing ? this.uri.shortSha : `(${this.uri.shortSha})`}`
: ''
}`;
}
return `${this.uri.fileName}${
this.uri.sha
? ` ${this.uri.sha === GitRevision.deletedOrMissing ? this.uri.shortSha : `(${this.uri.shortSha})`}`
: ''
this.uri.sha ? ` ${this.uri.sha === deletedOrMissing ? this.uri.shortSha : `(${this.uri.shortSha})`}` : ''
}`;
}

+ 3
- 3
src/views/nodes/fileHistoryTrackerNode.ts View File

@ -5,7 +5,7 @@ import { ContextKeys } from '../../constants';
import { setContext } from '../../context';
import type { GitCommitish } from '../../git/gitUri';
import { GitUri, unknownGitUri } from '../../git/gitUri';
import { GitReference, GitRevision } from '../../git/models/reference';
import { isBranchReference, isSha } from '../../git/models/reference';
import { Logger } from '../../logger';
import { getLogScope } from '../../logScope';
import { showReferencePicker } from '../../quickpicks/referencePicker';
@ -73,7 +73,7 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode
let branch;
if (!commitish.sha || commitish.sha === 'HEAD') {
branch = await this.view.container.git.getBranch(this.uri.repoPath);
} else if (!GitRevision.isSha(commitish.sha)) {
} else if (!isSha(commitish.sha)) {
({
values: [branch],
} = await this.view.container.git.getBranches(this.uri.repoPath, {
@ -119,7 +119,7 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode
);
if (pick == null) return;
if (GitReference.isBranch(pick)) {
if (isBranchReference(pick)) {
const branch = await this.view.container.git.getBranch(this.uri.repoPath);
this._base = branch?.name === pick.name ? undefined : pick.ref;
} else {

+ 4
- 5
src/views/nodes/lineHistoryNode.ts View File

@ -1,10 +1,11 @@
import { Disposable, Selection, TreeItem, TreeItemCollapsibleState, window } from 'vscode';
import type { GitUri } from '../../git/gitUri';
import type { GitBranch } from '../../git/models/branch';
import { deletedOrMissing } from '../../git/models/constants';
import type { GitFile } from '../../git/models/file';
import { GitFileIndexStatus } from '../../git/models/file';
import type { GitLog } from '../../git/models/log';
import { GitRevision } from '../../git/models/reference';
import { isUncommitted } from '../../git/models/reference';
import type { RepositoryChangeEvent, RepositoryFileSystemChangeEvent } from '../../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../../git/models/repository';
import { Logger } from '../../logger';
@ -66,7 +67,7 @@ export class LineHistoryNode
const range = this.branch != null ? await this.view.container.git.getBranchAheadRange(this.branch) : undefined;
const [log, blame, getBranchAndTagTips, unpublishedCommits] = await Promise.all([
this.getLog(selection),
this.uri.sha == null || GitRevision.isUncommitted(this.uri.sha)
this.uri.sha == null || isUncommitted(this.uri.sha)
? this.editorContents
? await this.view.container.git.getBlameForRangeContents(this.uri, selection, this.editorContents)
: await this.view.container.git.getBlameForRange(this.uri, selection)
@ -177,9 +178,7 @@ export class LineHistoryNode
get label() {
return `${this.uri.fileName}${this.lines}${
this.uri.sha
? ` ${this.uri.sha === GitRevision.deletedOrMissing ? this.uri.shortSha : `(${this.uri.shortSha})`}`
: ''
this.uri.sha ? ` ${this.uri.sha === deletedOrMissing ? this.uri.shortSha : `(${this.uri.shortSha})`}` : ''
}`;
}

+ 5
- 8
src/views/nodes/lineHistoryTrackerNode.ts View File

@ -5,7 +5,8 @@ import { ContextKeys } from '../../constants';
import { setContext } from '../../context';
import type { GitCommitish } from '../../git/gitUri';
import { GitUri, unknownGitUri } from '../../git/gitUri';
import { GitReference, GitRevision } from '../../git/models/reference';
import { deletedOrMissing } from '../../git/models/constants';
import { isBranchReference, isSha } from '../../git/models/reference';
import { Logger } from '../../logger';
import { getLogScope } from '../../logScope';
import { showReferencePicker } from '../../quickpicks/referencePicker';
@ -59,11 +60,7 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode
this.view.message = 'There was no selection provided for line history.';
this.view.description = `${this.uri.fileName}${
this.uri.sha
? ` ${
this.uri.sha === GitRevision.deletedOrMissing
? this.uri.shortSha
: `(${this.uri.shortSha})`
}`
? ` ${this.uri.sha === deletedOrMissing ? this.uri.shortSha : `(${this.uri.shortSha})`}`
: ''
}${!this.followingEditor ? ' (pinned)' : ''}`;
return [];
@ -81,7 +78,7 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode
let branch;
if (!commitish.sha || commitish.sha === 'HEAD') {
branch = await this.view.container.git.getBranch(this.uri.repoPath);
} else if (!GitRevision.isSha(commitish.sha)) {
} else if (!isSha(commitish.sha)) {
({
values: [branch],
} = await this.view.container.git.getBranches(this.uri.repoPath, {
@ -129,7 +126,7 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode
);
if (pick == null) return;
if (GitReference.isBranch(pick)) {
if (isBranchReference(pick)) {
const branch = await this.view.container.git.getBranch(this.uri.repoPath);
this._base = branch?.name === pick.name ? undefined : pick.ref;
} else {

+ 5
- 5
src/views/nodes/mergeConflictCurrentChangesNode.ts View File

@ -8,7 +8,7 @@ import { GitUri } from '../../git/gitUri';
import type { GitFile } from '../../git/models/file';
import type { GitMergeStatus } from '../../git/models/merge';
import type { GitRebaseStatus } from '../../git/models/rebase';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import type { FileHistoryView } from '../fileHistoryView';
import type { LineHistoryView } from '../lineHistoryView';
import type { ViewsWithCommits } from '../viewBase';
@ -33,8 +33,8 @@ export class MergeConflictCurrentChangesNode extends ViewNode
const item = new TreeItem('Current changes', TreeItemCollapsibleState.None);
item.contextValue = ContextValues.MergeConflictCurrentChanges;
item.description = `${GitReference.toString(this.status.current, { expand: false, icon: false })}${
commit != null ? ` (${GitReference.toString(commit, { expand: false, icon: false })})` : ' (HEAD)'
item.description = `${getReferenceLabel(this.status.current, { expand: false, icon: false })}${
commit != null ? ` (${getReferenceLabel(commit, { expand: false, icon: false })})` : ' (HEAD)'
}`;
item.iconPath = this.view.config.avatars
? (await commit?.getAvatarUri({ defaultStyle: configuration.get('defaultGravatarsStyle') })) ??
@ -42,7 +42,7 @@ export class MergeConflictCurrentChangesNode extends ViewNode
: new ThemeIcon('diff');
const markdown = new MarkdownString(
`Current changes to $(file)${GlyphChars.Space}${this.file.path} on ${GitReference.toString(
`Current changes to $(file)${GlyphChars.Space}${this.file.path} on ${getReferenceLabel(
this.status.current,
)}${
commit != null
@ -88,7 +88,7 @@ export class MergeConflictCurrentChangesNode extends ViewNode
rhs: {
sha: 'HEAD',
uri: GitUri.fromFile(this.file, this.status.repoPath),
title: `${this.file.path} (${GitReference.toString(this.status.current, {
title: `${this.file.path} (${getReferenceLabel(this.status.current, {
expand: false,
icon: false,
})})`,

+ 14
- 8
src/views/nodes/mergeConflictIncomingChangesNode.ts View File

@ -8,7 +8,7 @@ import { GitUri } from '../../git/gitUri';
import type { GitFile } from '../../git/models/file';
import type { GitMergeStatus } from '../../git/models/merge';
import type { GitRebaseStatus } from '../../git/models/rebase';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import type { FileHistoryView } from '../fileHistoryView';
import type { LineHistoryView } from '../lineHistoryView';
import type { ViewsWithCommits } from '../viewBase';
@ -36,10 +36,13 @@ export class MergeConflictIncomingChangesNode extends ViewNode
const item = new TreeItem('Incoming changes', TreeItemCollapsibleState.None);
item.contextValue = ContextValues.MergeConflictIncomingChanges;
item.description = `${GitReference.toString(this.status.incoming, { expand: false, icon: false })}${
item.description = `${getReferenceLabel(this.status.incoming, { expand: false, icon: false })}${
this.status.type === 'rebase'
? ` (${GitReference.toString(this.status.steps.current.commit, { expand: false, icon: false })})`
: ` (${GitReference.toString(this.status.HEAD, { expand: false, icon: false })})`
? ` (${getReferenceLabel(this.status.steps.current.commit, {
expand: false,
icon: false,
})})`
: ` (${getReferenceLabel(this.status.HEAD, { expand: false, icon: false })})`
}`;
item.iconPath = this.view.config.avatars
? (await commit?.getAvatarUri({ defaultStyle: configuration.get('defaultGravatarsStyle') })) ??
@ -49,7 +52,7 @@ export class MergeConflictIncomingChangesNode extends ViewNode
const markdown = new MarkdownString(
`Incoming changes to $(file)${GlyphChars.Space}${this.file.path}${
this.status.incoming != null
? ` from ${GitReference.toString(this.status.incoming)}${
? ` from ${getReferenceLabel(this.status.incoming)}${
commit != null
? `\n\n${await CommitFormatter.fromTemplateAsync(
`\${avatar}&nbsp;__\${author}__, \${ago} &nbsp; _(\${date})_ \n\n\${message}\n\n\${link}\${' via 'pullRequest}`,
@ -63,11 +66,14 @@ export class MergeConflictIncomingChangesNode extends ViewNode
},
)}`
: this.status.type === 'rebase'
? `\n\n${GitReference.toString(this.status.steps.current.commit, {
? `\n\n${getReferenceLabel(this.status.steps.current.commit, {
capitalize: true,
label: false,
})}`
: `\n\n${getReferenceLabel(this.status.HEAD, {
capitalize: true,
label: false,
})}`
: `\n\n${GitReference.toString(this.status.HEAD, { capitalize: true, label: false })}`
}`
: ''
}`,
@ -104,7 +110,7 @@ export class MergeConflictIncomingChangesNode extends ViewNode
uri: GitUri.fromFile(this.file, this.status.repoPath),
title: `${this.file.path} (${
this.status.incoming != null
? GitReference.toString(this.status.incoming, { expand: false, icon: false })
? getReferenceLabel(this.status.incoming, { expand: false, icon: false })
: 'incoming'
})`,
},

+ 5
- 5
src/views/nodes/mergeStatusNode.ts View File

@ -3,7 +3,7 @@ import { ViewFilesLayout } from '../../configuration';
import { GitUri } from '../../git/gitUri';
import type { GitBranch } from '../../git/models/branch';
import type { GitMergeStatus } from '../../git/models/merge';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import type { GitStatus } from '../../git/models/status';
import { makeHierarchical } from '../../system/array';
import { joinPaths, normalizePath } from '../../system/path';
@ -69,9 +69,9 @@ export class MergeStatusNode extends ViewNode {
const item = new TreeItem(
`${this.status?.hasConflicts ? 'Resolve conflicts before merging' : 'Merging'} ${
this.mergeStatus.incoming != null
? `${GitReference.toString(this.mergeStatus.incoming, { expand: false, icon: false })} `
? `${getReferenceLabel(this.mergeStatus.incoming, { expand: false, icon: false })} `
: ''
}into ${GitReference.toString(this.mergeStatus.current, { expand: false, icon: false })}`,
}into ${getReferenceLabel(this.mergeStatus.current, { expand: false, icon: false })}`,
TreeItemCollapsibleState.Expanded,
);
item.id = this.id;
@ -83,8 +83,8 @@ export class MergeStatusNode extends ViewNode {
const markdown = new MarkdownString(
`${`Merging ${
this.mergeStatus.incoming != null ? GitReference.toString(this.mergeStatus.incoming) : ''
}into ${GitReference.toString(this.mergeStatus.current)}`}${
this.mergeStatus.incoming != null ? getReferenceLabel(this.mergeStatus.incoming) : ''
}into ${getReferenceLabel(this.mergeStatus.current)}`}${
this.status?.hasConflicts ? `\n\n${pluralize('conflicted file', this.status.conflicts.length)}` : ''
}`,
true,

+ 5
- 5
src/views/nodes/rebaseStatusNode.ts View File

@ -9,7 +9,7 @@ import type { GitBranch } from '../../git/models/branch';
import type { GitCommit } from '../../git/models/commit';
import type { GitRebaseStatus } from '../../git/models/rebase';
import type { GitRevisionReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import type { GitStatus } from '../../git/models/status';
import { makeHierarchical } from '../../system/array';
import { executeCoreCommand } from '../../system/command';
@ -83,7 +83,7 @@ export class RebaseStatusNode extends ViewNode {
const item = new TreeItem(
`${this.status?.hasConflicts ? 'Resolve conflicts to continue rebasing' : 'Rebasing'} ${
this.rebaseStatus.incoming != null
? `${GitReference.toString(this.rebaseStatus.incoming, { expand: false, icon: false })}`
? `${getReferenceLabel(this.rebaseStatus.incoming, { expand: false, icon: false })}`
: ''
} (${this.rebaseStatus.steps.current.number}/${this.rebaseStatus.steps.total})`,
TreeItemCollapsibleState.Expanded,
@ -97,10 +97,10 @@ export class RebaseStatusNode extends ViewNode {
const markdown = new MarkdownString(
`${`Rebasing ${
this.rebaseStatus.incoming != null ? GitReference.toString(this.rebaseStatus.incoming) : ''
}onto ${GitReference.toString(this.rebaseStatus.current)}`}\n\nStep ${
this.rebaseStatus.incoming != null ? getReferenceLabel(this.rebaseStatus.incoming) : ''
}onto ${getReferenceLabel(this.rebaseStatus.current)}`}\n\nStep ${
this.rebaseStatus.steps.current.number
} of ${this.rebaseStatus.steps.total}\\\nPaused at ${GitReference.toString(
} of ${this.rebaseStatus.steps.total}\\\nPaused at ${getReferenceLabel(
this.rebaseStatus.steps.current.commit,
{ icon: true },
)}${this.status?.hasConflicts ? `\n\n${pluralize('conflicted file', this.status.conflicts.length)}` : ''}`,

+ 2
- 2
src/views/nodes/repositoryNode.ts View File

@ -120,7 +120,7 @@ export class RepositoryNode extends SubscribeableViewNode {
}
if (this.view.config.includeWorkingTree && status.files.length !== 0) {
const range = undefined; //status.upstream ? GitRevision.createRange(status.upstream, branch.ref) : undefined;
const range = undefined; //status.upstream ? createRange(status.upstream, branch.ref) : undefined;
children.push(new StatusFilesNode(this.view, this, status, range));
}
@ -376,7 +376,7 @@ export class RepositoryNode extends SubscribeableViewNode {
index++;
}
const range = undefined; //status.upstream ? GitRevision.createRange(status.upstream, status.sha) : undefined;
const range = undefined; //status.upstream ? createRange(status.upstream, status.sha) : undefined;
this._children.splice(index, deleteCount, new StatusFilesNode(this.view, this, status, range));
} else if (index !== -1) {
this._children.splice(index, 1);

+ 2
- 2
src/views/nodes/resultsFileNode.ts View File

@ -7,7 +7,7 @@ import { GitUri } from '../../git/gitUri';
import type { GitFile } from '../../git/models/file';
import { getGitFileStatusIcon } from '../../git/models/file';
import type { GitRevisionReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import { createReference } from '../../git/models/reference';
import { joinPaths, relativeDir } from '../../system/path';
import type { View } from '../viewBase';
import type { FileNode } from './folderNode';
@ -32,7 +32,7 @@ export class ResultsFileNode extends ViewRefFileNode implements FileNode {
}
get ref(): GitRevisionReference {
return GitReference.create(this.ref1 || this.ref2, this.uri.repoPath!);
return createReference(this.ref1 || this.ref2, this.uri.repoPath!);
}
getChildren(): ViewNode[] {

+ 1
- 1
src/views/nodes/statusFileNode.ts View File

@ -6,7 +6,7 @@ import { Commands } from '../../constants';
import { StatusFileFormatter } from '../../git/formatters/statusFormatter';
import { GitUri } from '../../git/gitUri';
import type { GitCommit } from '../../git/models/commit';
import type { GitFile} from '../../git/models/file';
import type { GitFile } from '../../git/models/file';
import { getGitFileStatusIcon } from '../../git/models/file';
import { joinPaths, relativeDir } from '../../system/path';
import { pluralize } from '../../system/string';

+ 2
- 2
src/views/nodes/tagNode.ts View File

@ -5,7 +5,7 @@ import { emojify } from '../../emojis';
import type { GitUri } from '../../git/gitUri';
import type { GitLog } from '../../git/models/log';
import type { GitTagReference } from '../../git/models/reference';
import { GitRevision } from '../../git/models/reference';
import { shortenRevision } from '../../git/models/reference';
import type { GitTag } from '../../git/models/tag';
import { gate } from '../../system/decorators/gate';
import { debug } from '../../system/decorators/log';
@ -79,7 +79,7 @@ export class TagNode extends ViewRefNode
item.id = this.id;
item.contextValue = ContextValues.Tag;
item.description = emojify(this.tag.message);
item.tooltip = `${this.tag.name}${pad(GlyphChars.Dash, 2, 2)}${GitRevision.shorten(this.tag.sha, {
item.tooltip = `${this.tag.name}${pad(GlyphChars.Dash, 2, 2)}${shortenRevision(this.tag.sha, {
force: true,
})}${
this.tag.date != null

+ 3
- 3
src/views/nodes/viewNode.ts View File

@ -5,8 +5,8 @@ import type { RepositoriesChangeEvent } from '../../git/gitProviderService';
import type { GitUri } from '../../git/gitUri';
import { unknownGitUri } from '../../git/gitUri';
import type { GitFile } from '../../git/models/file';
import type { GitRevisionReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import type { GitReference, GitRevisionReference } from '../../git/models/reference';
import { getReferenceLabel } from '../../git/models/reference';
import { GitRemote } from '../../git/models/remote';
import type { RepositoryChangeEvent } from '../../git/models/repository';
import { Repository, RepositoryChange, RepositoryChangeComparisonMode } from '../../git/models/repository';
@ -197,7 +197,7 @@ export abstract class ViewRefNode<
}
override toString(): string {
return `${super.toString()}:${GitReference.toString(this.ref, false)}`;
return `${super.toString()}:${getReferenceLabel(this.ref, false)}`;
}
}

+ 2
- 2
src/views/nodes/worktreeNode.ts View File

@ -6,7 +6,7 @@ import type { GitBranch } from '../../git/models/branch';
import type { GitLog } from '../../git/models/log';
import type { PullRequest } from '../../git/models/pullRequest';
import { PullRequestState } from '../../git/models/pullRequest';
import { GitRevision } from '../../git/models/reference';
import { shortenRevision } from '../../git/models/reference';
import { GitRemote, GitRemoteType } from '../../git/models/remote';
import type { GitWorktree } from '../../git/models/worktree';
import { gate } from '../../system/decorators/gate';
@ -310,7 +310,7 @@ export class WorktreeNode extends ViewNode
case 'detached': {
icon = new ThemeIcon('git-commit');
tooltip.appendMarkdown(
`${this.worktree.main ? '$(pass) ' : ''}Detached Worktree at $(git-commit) ${GitRevision.shorten(
`${this.worktree.main ? '$(pass) ' : ''}Detached Worktree at $(git-commit) ${shortenRevision(
this.worktree.sha,
)}${indicators}\\\n\`${this.worktree.friendlyPath}\``,
);

+ 9
- 3
src/views/remotesView.ts View File

@ -9,7 +9,7 @@ import { getRemoteNameFromBranchName } from '../git/models/branch';
import type { GitCommit } from '../git/models/commit';
import { isCommit } from '../git/models/commit';
import type { GitBranchReference, GitRevisionReference } from '../git/models/reference';
import { GitReference } from '../git/models/reference';
import { getReferenceLabel } from '../git/models/reference';
import type { GitRemote } from '../git/models/remote';
import type { RepositoryChangeEvent } from '../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../git/models/repository';
@ -284,7 +284,10 @@ export class RemotesView extends ViewBase {
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(branch, { icon: false, quoted: true })} in the side bar...`,
title: `Revealing ${getReferenceLabel(branch, {
icon: false,
quoted: true,
})} in the side bar...`,
cancellable: true,
},
async (progress, token) => {
@ -310,7 +313,10 @@ export class RemotesView extends ViewBase {
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(commit, { icon: false, quoted: true })} in the side bar...`,
title: `Revealing ${getReferenceLabel(commit, {
icon: false,
quoted: true,
})} in the side bar...`,
cancellable: true,
},
async (progress, token) => {

+ 5
- 5
src/views/repositoriesView.ts View File

@ -15,7 +15,7 @@ import type {
GitStashReference,
GitTagReference,
} from '../git/models/reference';
import { GitReference } from '../git/models/reference';
import { getReferenceLabel } from '../git/models/reference';
import type { GitRemote } from '../git/models/remote';
import type { GitWorktree } from '../git/models/worktree';
import { executeCommand } from '../system/command';
@ -508,7 +508,7 @@ export class RepositoriesView extends ViewBase
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(branch, {
title: `Revealing ${getReferenceLabel(branch, {
icon: false,
quoted: true,
})} in the Repositories view...`,
@ -569,7 +569,7 @@ export class RepositoriesView extends ViewBase
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(commit, {
title: `Revealing ${getReferenceLabel(commit, {
icon: false,
quoted: true,
})} in the Repositories view...`,
@ -673,7 +673,7 @@ export class RepositoriesView extends ViewBase
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(stash, {
title: `Revealing ${getReferenceLabel(stash, {
icon: false,
quoted: true,
})} in the Repositories view...`,
@ -734,7 +734,7 @@ export class RepositoriesView extends ViewBase
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(tag, {
title: `Revealing ${getReferenceLabel(tag, {
icon: false,
quoted: true,
})} in the Repositories view...`,

+ 5
- 5
src/views/searchAndCompareView.ts View File

@ -7,7 +7,7 @@ import type { Container } from '../container';
import { setContext } from '../context';
import { unknownGitUri } from '../git/gitUri';
import type { GitLog } from '../git/models/log';
import { GitRevision } from '../git/models/reference';
import { isRevisionRange, shortenRevision, splitRevisionRange } from '../git/models/reference';
import type { SearchQuery } from '../git/search';
import { getSearchQuery } from '../git/search';
import { ReferencesQuickPickIncludes, showReferencePicker } from '../quickpicks/referencePicker';
@ -195,8 +195,8 @@ export class SearchAndCompareViewNode extends ViewNode {
ref = pick.ref;
if (GitRevision.isRange(ref)) {
const range = GitRevision.splitRange(ref);
if (isRevisionRange(ref)) {
const range = splitRevisionRange(ref);
if (range != null) {
ref = range.ref1 || 'HEAD';
ref2 = range.ref2 || 'HEAD';
@ -225,8 +225,8 @@ export class SearchAndCompareViewNode extends ViewNode {
private getRefName(ref: string | StoredNamedRef): string {
return typeof ref === 'string'
? GitRevision.shorten(ref, { strings: { working: 'Working Tree' } })!
: ref.label ?? GitRevision.shorten(ref.ref)!;
? shortenRevision(ref, { strings: { working: 'Working Tree' } })!
: ref.label ?? shortenRevision(ref.ref)!;
}
private removeComparePicker(silent: boolean = false) {

+ 5
- 2
src/views/stashesView.ts View File

@ -12,7 +12,7 @@ import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import type { GitStashReference } from '../git/models/reference';
import { GitReference } from '../git/models/reference';
import { getReferenceLabel } from '../git/models/reference';
import type { RepositoryChangeEvent } from '../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../git/models/repository';
import { executeCommand } from '../system/command';
@ -245,7 +245,10 @@ export class StashesView extends ViewBase {
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(stash, { icon: false, quoted: true })} in the side bar...`,
title: `Revealing ${getReferenceLabel(stash, {
icon: false,
quoted: true,
})} in the side bar...`,
cancellable: true,
},
async (progress, token) => {

+ 5
- 2
src/views/tagsView.ts View File

@ -6,7 +6,7 @@ import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import type { GitTagReference } from '../git/models/reference';
import { GitReference } from '../git/models/reference';
import { getReferenceLabel } from '../git/models/reference';
import type { RepositoryChangeEvent } from '../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../git/models/repository';
import { executeCommand } from '../system/command';
@ -210,7 +210,10 @@ export class TagsView extends ViewBase {
return window.withProgress(
{
location: ProgressLocation.Notification,
title: `Revealing ${GitReference.toString(tag, { icon: false, quoted: true })} in the side bar...`,
title: `Revealing ${getReferenceLabel(tag, {
icon: false,
quoted: true,
})} in the side bar...`,
cancellable: true,
},
async (progress, token) => {

+ 12
- 8
src/views/viewCommands.ts View File

@ -21,8 +21,9 @@ import * as StashActions from '../git/actions/stash';
import * as TagActions from '../git/actions/tag';
import * as WorktreeActions from '../git/actions/worktree';
import { GitUri } from '../git/gitUri';
import { deletedOrMissing } from '../git/models/constants';
import type { GitStashReference } from '../git/models/reference';
import { GitReference, GitRevision } from '../git/models/reference';
import { createReference, getReferenceLabel, shortenRevision } from '../git/models/reference';
import {
executeActionCommand,
executeCommand,
@ -323,8 +324,8 @@ export class ViewCommands {
if (node instanceof ResultsFileNode) {
return CommitActions.applyChanges(
node.file,
GitReference.create(node.ref1, node.repoPath),
GitReference.create(node.ref2, node.repoPath),
createReference(node.ref1, node.repoPath),
createReference(node.ref2, node.repoPath),
);
}
@ -675,7 +676,7 @@ export class ViewCommands {
return RepoActions.rebase(
node.repoPath,
GitReference.create(upstream, node.repoPath, {
createReference(upstream, node.repoPath, {
refType: 'branch',
name: upstream,
remote: true,
@ -696,7 +697,7 @@ export class ViewCommands {
return RepoActions.reset(
node.repoPath,
GitReference.create(`${node.ref.ref}^`, node.ref.repoPath, {
createReference(`${node.ref.ref}^`, node.ref.repoPath, {
refType: 'revision',
name: `${node.ref.name}^`,
message: node.ref.message,
@ -812,7 +813,7 @@ export class ViewCommands {
if (commit?.hash !== node.ref.ref) {
void window.showWarningMessage(
`Commit ${GitReference.toString(node.ref, {
`Commit ${getReferenceLabel(node.ref, {
capitalize: true,
icon: false,
})} cannot be undone, because it is no longer the most recent commit.`,
@ -900,7 +901,10 @@ export class ViewCommands {
return this.container.searchAndCompareView.compare(
node.repoPath,
{ ref: commonAncestor, label: `ancestry with ${node.ref.ref} (${GitRevision.shorten(commonAncestor)})` },
{
ref: commonAncestor,
label: `ancestry with ${node.ref.ref} (${shortenRevision(commonAncestor)})`,
},
'',
);
}
@ -1234,7 +1238,7 @@ export class ViewCommands {
uri =
node.commit.file?.status === 'D'
? this.container.git.getRevisionUri(
(await node.commit.getPreviousSha()) ?? GitRevision.deletedOrMissing,
(await node.commit.getPreviousSha()) ?? deletedOrMissing,
node.commit.file.path,
node.commit.repoPath,
)

+ 2
- 2
src/webviews/commitDetails/commitDetailsWebviewView.ts View File

@ -25,7 +25,7 @@ import { serializeIssueOrPullRequest } from '../../git/models/issue';
import type { PullRequest } from '../../git/models/pullRequest';
import { serializePullRequest } from '../../git/models/pullRequest';
import type { GitRevisionReference } from '../../git/models/reference';
import { GitReference } from '../../git/models/reference';
import { getReferenceFromRevision } from '../../git/models/reference';
import type { GitRemote } from '../../git/models/remote';
import { Logger } from '../../logger';
import { getLogScope } from '../../logScope';
@ -305,7 +305,7 @@ export class CommitDetailsWebviewView extends WebviewViewBase
if (this._context.commit == null) return;
void executeCommand<ShowInCommitGraphCommandArgs>(Commands.ShowInCommitGraph, {
ref: GitReference.fromRevision(this._context.commit),
ref: getReferenceFromRevision(this._context.commit),
});
break;
case 'more':

+ 2
- 2
src/webviews/rebase/rebaseEditor.ts View File

@ -14,7 +14,7 @@ import type { Container } from '../../container';
import { setContext } from '../../context';
import { emojify } from '../../emojis';
import type { GitCommit } from '../../git/models/commit';
import { GitReference } from '../../git/models/reference';
import { createReference } from '../../git/models/reference';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../../git/models/repository';
import { Logger } from '../../logger';
import { showRebaseSwitchToTextWarningMessage } from '../../messages';
@ -514,7 +514,7 @@ export class RebaseEditorProvider implements CustomTextEditorProvider, Disposabl
this.container.events.fire(
'commit:selected',
{
commit: GitReference.create(sha, context.repoPath, { refType: 'revision' }),
commit: createReference(sha, context.repoPath, { refType: 'revision' }),
pin: false,
preserveFocus: true,
preserveVisibility: context.firstSelection

Loading…
Cancel
Save