Merge branch 'master' into pr/107958

This commit is contained in:
João Moreno
2020-11-10 11:59:25 +01:00
1255 changed files with 47690 additions and 33323 deletions

View File

@@ -6,7 +6,7 @@
import { lstat, Stats } from 'fs';
import * as os from 'os';
import * as path from 'path';
import { commands, Disposable, LineChange, MessageOptions, OutputChannel, Position, ProgressLocation, QuickPickItem, Range, SourceControlResourceState, TextDocumentShowOptions, TextEditor, Uri, ViewColumn, window, workspace, WorkspaceEdit, WorkspaceFolder, TimelineItem, env, Selection } from 'vscode';
import { commands, Disposable, LineChange, MessageOptions, OutputChannel, Position, ProgressLocation, QuickPickItem, Range, SourceControlResourceState, TextDocumentShowOptions, TextEditor, Uri, ViewColumn, window, workspace, WorkspaceEdit, WorkspaceFolder, TimelineItem, env, Selection, TextDocumentContentProvider } from 'vscode';
import TelemetryReporter from 'vscode-extension-telemetry';
import * as nls from 'vscode-nls';
import { Branch, GitErrorCodes, Ref, RefType, Status, CommitOptions, RemoteSourceProvider } from './api/git';
@@ -31,14 +31,14 @@ class CheckoutItem implements QuickPickItem {
constructor(protected ref: Ref) { }
async run(repository: Repository): Promise<void> {
async run(repository: Repository, opts?: { detached?: boolean }): Promise<void> {
const ref = this.ref.name;
if (!ref) {
return;
}
await repository.checkout(ref);
await repository.checkout(ref, opts);
}
}
@@ -99,32 +99,36 @@ class MergeItem implements QuickPickItem {
}
}
class CreateBranchItem implements QuickPickItem {
class RebaseItem implements QuickPickItem {
constructor(private cc: CommandCenter) { }
get label(): string { return this.ref.name || ''; }
description: string = '';
get label(): string { return '$(plus) ' + localize('create branch', 'Create new branch...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
constructor(readonly ref: Ref) { }
async run(repository: Repository): Promise<void> {
await this.cc.branch(repository);
if (this.ref?.name) {
await repository.rebase(this.ref.name);
}
}
}
class CreateBranchItem implements QuickPickItem {
get label(): string { return '$(plus) ' + localize('create branch', 'Create new branch...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class CreateBranchFromItem implements QuickPickItem {
constructor(private cc: CommandCenter) { }
get label(): string { return '$(plus) ' + localize('create branch from', 'Create new branch from...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
async run(repository: Repository): Promise<void> {
await this.cc.branch(repository);
}
class CheckoutDetachedItem implements QuickPickItem {
get label(): string { return '$(debug-disconnect) ' + localize('checkout detached', 'Checkout detached...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class HEADItem implements QuickPickItem {
@@ -203,18 +207,53 @@ async function categorizeResourceByResolution(resources: Resource[]): Promise<{
function createCheckoutItems(repository: Repository): CheckoutItem[] {
const config = workspace.getConfiguration('git');
const checkoutType = config.get<string>('checkoutType') || 'all';
const includeTags = checkoutType === 'all' || checkoutType === 'tags';
const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';
const checkoutTypeConfig = config.get<string | string[]>('checkoutType');
let checkoutTypes: string[];
const heads = repository.refs.filter(ref => ref.type === RefType.Head)
.map(ref => new CheckoutItem(ref));
const tags = (includeTags ? repository.refs.filter(ref => ref.type === RefType.Tag) : [])
.map(ref => new CheckoutTagItem(ref));
const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
.map(ref => new CheckoutRemoteHeadItem(ref));
if (checkoutTypeConfig === 'all' || !checkoutTypeConfig || checkoutTypeConfig.length === 0) {
checkoutTypes = ['local', 'remote', 'tags'];
} else if (typeof checkoutTypeConfig === 'string') {
checkoutTypes = [checkoutTypeConfig];
} else {
checkoutTypes = checkoutTypeConfig;
}
return [...heads, ...tags, ...remoteHeads];
const processors = checkoutTypes.map(getCheckoutProcessor)
.filter(p => !!p) as CheckoutProcessor[];
for (const ref of repository.refs) {
for (const processor of processors) {
processor.onRef(ref);
}
}
return processors.reduce<CheckoutItem[]>((r, p) => r.concat(...p.items), []);
}
class CheckoutProcessor {
private refs: Ref[] = [];
get items(): CheckoutItem[] { return this.refs.map(r => new this.ctor(r)); }
constructor(private type: RefType, private ctor: { new(ref: Ref): CheckoutItem }) { }
onRef(ref: Ref): void {
if (ref.type === this.type) {
this.refs.push(ref);
}
}
}
function getCheckoutProcessor(type: string): CheckoutProcessor | undefined {
switch (type) {
case 'local':
return new CheckoutProcessor(RefType.Head, CheckoutItem);
case 'remote':
return new CheckoutProcessor(RefType.RemoteHead, CheckoutRemoteHeadItem);
case 'tags':
return new CheckoutProcessor(RefType.Tag, CheckoutTagItem);
}
return undefined;
}
function sanitizeRemoteName(name: string) {
@@ -232,6 +271,7 @@ enum PushType {
Push,
PushTo,
PushFollowTags,
PushTags
}
interface PushOptions {
@@ -240,9 +280,27 @@ interface PushOptions {
silent?: boolean;
}
class CommandErrorOutputTextDocumentContentProvider implements TextDocumentContentProvider {
private items = new Map<string, string>();
set(uri: Uri, contents: string): void {
this.items.set(uri.path, contents);
}
delete(uri: Uri): void {
this.items.delete(uri.path);
}
provideTextDocumentContent(uri: Uri): string | undefined {
return this.items.get(uri.path);
}
}
export class CommandCenter {
private disposables: Disposable[];
private commandErrors = new CommandErrorOutputTextDocumentContentProvider();
constructor(
private git: Git,
@@ -259,6 +317,8 @@ export class CommandCenter {
return commands.registerCommand(commandId, command);
}
});
this.disposables.push(workspace.registerTextDocumentContentProvider('git-output', this.commandErrors));
}
@command('git.setLogLevel')
@@ -333,7 +393,9 @@ export class CommandCenter {
right = toGitUri(resource.resourceUri, resource.resourceGroupType === ResourceGroupType.Index ? 'index' : 'wt', { submoduleOf: repository.root });
}
} else {
if (resource.type !== Status.DELETED_BY_THEM) {
if (resource.type === Status.DELETED_BY_US || resource.type === Status.DELETED_BY_THEM) {
left = toGitUri(resource.resourceUri, '~1');
} else {
left = this.getLeftResource(resource);
}
@@ -363,7 +425,7 @@ export class CommandCenter {
}
if (!left) {
await commands.executeCommand<void>('vscode.open', right, opts, title);
await commands.executeCommand<void>('vscode.open', right, { ...opts, override: resource.type === Status.BOTH_MODIFIED ? false : undefined }, title);
} else {
await commands.executeCommand<void>('vscode.diff', left, right, title, opts);
}
@@ -458,8 +520,7 @@ export class CommandCenter {
}
}
@command('git.clone')
async clone(url?: string, parentPath?: string): Promise<void> {
async cloneRepository(url?: string, parentPath?: string, options: { recursive?: boolean } = {}): Promise<void> {
if (!url || typeof url !== 'string') {
url = await pickRemoteSource(this.model, {
providerLabel: provider => localize('clonefrom', "Clone from {0}", provider.name),
@@ -515,38 +576,57 @@ export class CommandCenter {
const repositoryPath = await window.withProgress(
opts,
(progress, token) => this.git.clone(url!, parentPath!, progress, token)
(progress, token) => this.git.clone(url!, { parentPath: parentPath!, progress, recursive: options.recursive }, token)
);
let message = localize('proposeopen', "Would you like to open the cloned repository?");
const open = localize('openrepo', "Open");
const openNewWindow = localize('openreponew', "Open in New Window");
const choices = [open, openNewWindow];
const config = workspace.getConfiguration('git');
const openAfterClone = config.get<'always' | 'alwaysNewWindow' | 'whenNoFolderOpen' | 'prompt'>('openAfterClone');
const addToWorkspace = localize('add', "Add to Workspace");
if (workspace.workspaceFolders) {
message = localize('proposeopen2', "Would you like to open the cloned repository, or add it to the current workspace?");
choices.push(addToWorkspace);
enum PostCloneAction { Open, OpenNewWindow, AddToWorkspace }
let action: PostCloneAction | undefined = undefined;
if (openAfterClone === 'always') {
action = PostCloneAction.Open;
} else if (openAfterClone === 'alwaysNewWindow') {
action = PostCloneAction.OpenNewWindow;
} else if (openAfterClone === 'whenNoFolderOpen' && !workspace.workspaceFolders) {
action = PostCloneAction.Open;
}
const result = await window.showInformationMessage(message, ...choices);
if (action === undefined) {
let message = localize('proposeopen', "Would you like to open the cloned repository?");
const open = localize('openrepo', "Open");
const openNewWindow = localize('openreponew', "Open in New Window");
const choices = [open, openNewWindow];
const addToWorkspace = localize('add', "Add to Workspace");
if (workspace.workspaceFolders) {
message = localize('proposeopen2', "Would you like to open the cloned repository, or add it to the current workspace?");
choices.push(addToWorkspace);
}
const result = await window.showInformationMessage(message, ...choices);
action = result === open ? PostCloneAction.Open
: result === openNewWindow ? PostCloneAction.OpenNewWindow
: result === addToWorkspace ? PostCloneAction.AddToWorkspace : undefined;
}
const openFolder = result === open;
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"openFolder": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: action === PostCloneAction.Open || action === PostCloneAction.OpenNewWindow ? 1 : 0 });
const uri = Uri.file(repositoryPath);
if (openFolder) {
if (action === PostCloneAction.Open) {
commands.executeCommand('vscode.openFolder', uri, { forceReuseWindow: true });
} else if (result === addToWorkspace) {
} else if (action === PostCloneAction.AddToWorkspace) {
workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
} else if (result === openNewWindow) {
} else if (action === PostCloneAction.OpenNewWindow) {
commands.executeCommand('vscode.openFolder', uri, { forceNewWindow: true });
}
} catch (err) {
@@ -572,6 +652,16 @@ export class CommandCenter {
}
}
@command('git.clone')
async clone(url?: string, parentPath?: string): Promise<void> {
this.cloneRepository(url, parentPath);
}
@command('git.cloneRecursive')
async cloneRecursive(url?: string, parentPath?: string): Promise<void> {
this.cloneRepository(url, parentPath, { recursive: true });
}
@command('git.init')
async init(skipFolderPrompt = false): Promise<void> {
let repositoryPath: string | undefined = undefined;
@@ -738,7 +828,10 @@ export class CommandCenter {
try {
document = await workspace.openTextDocument(uri);
} catch (error) {
await commands.executeCommand('vscode.open', uri, opts);
await commands.executeCommand('vscode.open', uri, {
...opts,
override: arg instanceof Resource && arg.type === Status.BOTH_MODIFIED ? false : undefined
});
continue;
}
@@ -830,6 +923,27 @@ export class CommandCenter {
}
}
@command('git.rename', { repository: true })
async rename(repository: Repository, fromUri: Uri): Promise<void> {
if (!fromUri) {
return;
}
const from = path.relative(repository.root, fromUri.path);
let to = await window.showInputBox({
value: from,
valueSelection: [from.length - path.basename(from).length, from.length]
});
to = to?.trim();
if (!to) {
return;
}
await repository.move(from, to);
}
@command('git.stage')
async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
this.outputChannel.appendLine(`git.stage ${resourceStates.length}`);
@@ -1198,7 +1312,7 @@ export class CommandCenter {
if (scmResources.length === 1) {
if (untrackedCount > 0) {
message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST.", path.basename(scmResources[0].resourceUri.fsPath));
message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST if you proceed.", path.basename(scmResources[0].resourceUri.fsPath));
yes = localize('delete file', "Delete file");
} else {
if (scmResources[0].type === Status.DELETED) {
@@ -1303,7 +1417,7 @@ export class CommandCenter {
private async _cleanTrackedChanges(repository: Repository, resources: Resource[]): Promise<void> {
const message = resources.length === 1
? localize('confirm discard all single', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].resourceUri.fsPath))
: localize('confirm discard all', "Are you sure you want to discard ALL changes in {0} files?\nThis is IRREVERSIBLE!\nYour current working set will be FOREVER LOST.", resources.length);
: localize('confirm discard all', "Are you sure you want to discard ALL changes in {0} files?\nThis is IRREVERSIBLE!\nYour current working set will be FOREVER LOST if you proceed.", resources.length);
const yes = resources.length === 1
? localize('discardAll multiple', "Discard 1 File")
: localize('discardAll', "Discard All {0} Files", resources.length);
@@ -1317,7 +1431,7 @@ export class CommandCenter {
}
private async _cleanUntrackedChange(repository: Repository, resource: Resource): Promise<void> {
const message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST.", path.basename(resource.resourceUri.fsPath));
const message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST if you proceed.", path.basename(resource.resourceUri.fsPath));
const yes = localize('delete file', "Delete file");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
@@ -1329,7 +1443,7 @@ export class CommandCenter {
}
private async _cleanUntrackedChanges(repository: Repository, resources: Resource[]): Promise<void> {
const message = localize('confirm delete multiple', "Are you sure you want to DELETE {0} files?", resources.length);
const message = localize('confirm delete multiple', "Are you sure you want to DELETE {0} files?\nThis is IRREVERSIBLE!\nThese files will be FOREVER LOST if you proceed.", resources.length);
const yes = localize('delete files', "Delete Files");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
@@ -1374,7 +1488,7 @@ export class CommandCenter {
? localize('unsaved files single', "The following file has unsaved changes which won't be included in the commit if you proceed: {0}.\n\nWould you like to save it before committing?", path.basename(documents[0].uri.fsPath))
: localize('unsaved files', "There are {0} unsaved files.\n\nWould you like to save them before committing?", documents.length);
const saveAndCommit = localize('save and commit', "Save All & Commit");
const commit = localize('commit', "Commit Anyway");
const commit = localize('commit', "Commit Staged Changes");
const pick = await window.showWarningMessage(message, { modal: true }, saveAndCommit, commit);
if (pick === saveAndCommit) {
@@ -1401,7 +1515,7 @@ export class CommandCenter {
}
// prompt the user if we want to commit all or not
const message = localize('no staged changes', "There are no staged changes to commit.\n\nWould you like to automatically stage all your changes and commit them directly?");
const message = localize('no staged changes', "There are no staged changes to commit.\n\nWould you like to stage all your changes and commit them directly?");
const yes = localize('yes', "Yes");
const always = localize('always', "Always");
const never = localize('never', "Never");
@@ -1435,10 +1549,18 @@ export class CommandCenter {
// no staged changes and no tracked unstaged changes
|| (noStagedChanges && smartCommitChanges === 'tracked' && repository.workingTreeGroup.resourceStates.every(r => r.type === Status.UNTRACKED))
)
// amend allows changing only the commit message
&& !opts.amend
&& !opts.empty
) {
window.showInformationMessage(localize('no changes', "There are no changes to commit."));
return false;
const commitAnyway = localize('commit anyway', "Create Empty Commit");
const answer = await window.showInformationMessage(localize('no changes', "There are no changes to commit."), commitAnyway);
if (answer !== commitAnyway) {
return false;
}
opts.empty = true;
}
if (opts.noVerify) {
@@ -1667,20 +1789,38 @@ export class CommandCenter {
}
@command('git.checkout', { repository: true })
async checkout(repository: Repository, treeish: string): Promise<boolean> {
if (typeof treeish === 'string') {
await repository.checkout(treeish);
async checkout(repository: Repository, treeish?: string): Promise<boolean> {
return this._checkout(repository, { treeish });
}
@command('git.checkoutDetached', { repository: true })
async checkoutDetached(repository: Repository, treeish?: string): Promise<boolean> {
return this._checkout(repository, { detached: true, treeish });
}
private async _checkout(repository: Repository, opts?: { detached?: boolean, treeish?: string }): Promise<boolean> {
if (typeof opts?.treeish === 'string') {
await repository.checkout(opts?.treeish, opts);
return true;
}
const createBranch = new CreateBranchItem(this);
const createBranchFrom = new CreateBranchFromItem(this);
const picks = [createBranch, createBranchFrom, ...createCheckoutItems(repository)];
const placeHolder = localize('select a ref to checkout', 'Select a ref to checkout');
const createBranch = new CreateBranchItem();
const createBranchFrom = new CreateBranchFromItem();
const checkoutDetached = new CheckoutDetachedItem();
const picks: QuickPickItem[] = [];
if (!opts?.detached) {
picks.push(createBranch, createBranchFrom, checkoutDetached);
}
picks.push(...createCheckoutItems(repository));
const quickpick = window.createQuickPick();
quickpick.items = picks;
quickpick.placeholder = placeHolder;
quickpick.placeholder = opts?.detached
? localize('select a ref to checkout detached', 'Select a ref to checkout in detached mode')
: localize('select a ref to checkout', 'Select a ref to checkout');
quickpick.show();
const choice = await new Promise<QuickPickItem | undefined>(c => quickpick.onDidAccept(() => c(quickpick.activeItems[0])));
@@ -1694,8 +1834,31 @@ export class CommandCenter {
await this._branch(repository, quickpick.value);
} else if (choice === createBranchFrom) {
await this._branch(repository, quickpick.value, true);
} else if (choice === checkoutDetached) {
return this._checkout(repository, { detached: true });
} else {
await (choice as CheckoutItem).run(repository);
const item = choice as CheckoutItem;
try {
await item.run(repository, opts);
} catch (err) {
if (err.gitErrorCode !== GitErrorCodes.DirtyWorkTree) {
throw err;
}
const force = localize('force', "Force Checkout");
const stash = localize('stashcheckout', "Stash & Checkout");
const choice = await window.showWarningMessage(localize('local changes', "Your local changes would be overwritten by checkout."), { modal: true }, force, stash);
if (choice === force) {
await this.cleanAll(repository);
await item.run(repository, opts);
} else if (choice === stash) {
await this.stash(repository);
await item.run(repository, opts);
await this.stashPopLatest(repository);
}
}
}
return true;
@@ -1848,6 +2011,44 @@ export class CommandCenter {
await choice.run(repository);
}
@command('git.rebase', { repository: true })
async rebase(repository: Repository): Promise<void> {
const config = workspace.getConfiguration('git');
const checkoutType = config.get<string>('checkoutType') || 'all';
const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';
const heads = repository.refs.filter(ref => ref.type === RefType.Head)
.filter(ref => ref.name !== repository.HEAD?.name)
.filter(ref => ref.name || ref.commit);
const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
.filter(ref => ref.name || ref.commit);
const picks = [...heads, ...remoteHeads]
.map(ref => new RebaseItem(ref));
// set upstream branch as first
if (repository.HEAD?.upstream) {
const upstreamName = `${repository.HEAD?.upstream.remote}/${repository.HEAD?.upstream.name}`;
const index = picks.findIndex(e => e.ref.name === upstreamName);
if (index > -1) {
const [ref] = picks.splice(index, 1);
ref.description = '(upstream)';
picks.unshift(ref);
}
}
const placeHolder = localize('select a branch to rebase onto', 'Select a branch to rebase onto');
const choice = await window.showQuickPick<RebaseItem>(picks, { placeHolder });
if (!choice) {
return;
}
await choice.run(repository);
}
@command('git.createTag', { repository: true })
async createTag(repository: Repository): Promise<void> {
const inputTagName = await window.showInputBox({
@@ -2025,6 +2226,10 @@ export class CommandCenter {
return;
}
if (pushOptions.pushType === PushType.PushTags) {
await repository.pushTags(undefined, forcePushMode);
}
if (!repository.HEAD || !repository.HEAD.name) {
if (!pushOptions.silent) {
window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
@@ -2096,6 +2301,21 @@ export class CommandCenter {
await this._push(repository, { pushType: PushType.PushFollowTags, forcePush: true });
}
@command('git.cherryPick', { repository: true })
async cherryPick(repository: Repository): Promise<void> {
const hash = await window.showInputBox({
placeHolder: localize('commit hash', "Commit Hash"),
prompt: localize('provide commit hash', "Please provide the commit hash"),
ignoreFocusOut: true
});
if (!hash) {
return;
}
await repository.cherryPick(hash);
}
@command('git.pushTo', { repository: true })
async pushTo(repository: Repository): Promise<void> {
await this._push(repository, { pushType: PushType.PushTo });
@@ -2106,6 +2326,11 @@ export class CommandCenter {
await this._push(repository, { pushType: PushType.PushTo, forcePush: true });
}
@command('git.pushTags', { repository: true })
async pushTags(repository: Repository): Promise<void> {
await this._push(repository, { pushType: PushType.PushTags });
}
@command('git.addRemote', { repository: true })
async addRemote(repository: Repository): Promise<string | undefined> {
const url = await pickRemoteSource(this.model, {
@@ -2139,6 +2364,7 @@ export class CommandCenter {
}
await repository.addRemote(name, url);
await repository.fetch(name);
return name;
}
@@ -2352,7 +2578,45 @@ export class CommandCenter {
return;
}
const message = await this.getStashMessage();
const config = workspace.getConfiguration('git', Uri.file(repository.root));
const promptToSaveFilesBeforeStashing = config.get<'always' | 'staged' | 'never'>('promptToSaveFilesBeforeStash');
if (promptToSaveFilesBeforeStashing !== 'never') {
let documents = workspace.textDocuments
.filter(d => !d.isUntitled && d.isDirty && isDescendant(repository.root, d.uri.fsPath));
if (promptToSaveFilesBeforeStashing === 'staged' || repository.indexGroup.resourceStates.length > 0) {
documents = documents
.filter(d => repository.indexGroup.resourceStates.some(s => pathEquals(s.resourceUri.fsPath, d.uri.fsPath)));
}
if (documents.length > 0) {
const message = documents.length === 1
? localize('unsaved stash files single', "The following file has unsaved changes which won't be included in the stash if you proceed: {0}.\n\nWould you like to save it before stashing?", path.basename(documents[0].uri.fsPath))
: localize('unsaved stash files', "There are {0} unsaved files.\n\nWould you like to save them before stashing?", documents.length);
const saveAndStash = localize('save and stash', "Save All & Stash");
const stash = localize('stash', "Stash Anyway");
const pick = await window.showWarningMessage(message, { modal: true }, saveAndStash, stash);
if (pick === saveAndStash) {
await Promise.all(documents.map(d => d.save()));
} else if (pick !== stash) {
return; // do not stash on cancel
}
}
}
let message: string | undefined;
if (config.get<boolean>('useCommitInputAsStashMessage') && (!repository.sourceControl.commitTemplate || repository.inputBox.value !== repository.sourceControl.commitTemplate)) {
message = repository.inputBox.value;
}
message = await window.showInputBox({
value: message,
prompt: localize('provide stash message', "Optionally provide a stash message"),
placeHolder: localize('stash message', "Stash message")
});
if (typeof message === 'undefined') {
return;
@@ -2361,13 +2625,6 @@ export class CommandCenter {
await repository.createStash(message, includeUntracked);
}
private async getStashMessage(): Promise<string | undefined> {
return await window.showInputBox({
prompt: localize('provide stash message', "Optionally provide a stash message"),
placeHolder: localize('stash message', "Stash message")
});
}
@command('git.stash', { repository: true })
stash(repository: Repository): Promise<void> {
return this._stash(repository);
@@ -2435,6 +2692,16 @@ export class CommandCenter {
return;
}
// request confirmation for the operation
const yes = localize('yes', "Yes");
const result = await window.showWarningMessage(
localize('sure drop', "Are you sure you want to drop the stash: {0}?", stash.description),
yes
);
if (result !== yes) {
return;
}
await repository.dropStash(stash.index);
}
@@ -2498,7 +2765,11 @@ export class CommandCenter {
@command('git.rebaseAbort', { repository: true })
async rebaseAbort(repository: Repository): Promise<void> {
await repository.rebaseAbort();
if (repository.rebaseCommit) {
await repository.rebaseAbort();
} else {
await window.showInformationMessage(localize('no rebase', "No rebase in progress."));
}
}
private createCommand(id: string, key: string, method: Function, options: CommandOptions): (...args: any[]) => any {
@@ -2549,6 +2820,31 @@ export class CommandCenter {
const outputChannel = this.outputChannel as OutputChannel;
choices.set(openOutputChannelChoice, () => outputChannel.show());
const showCommandOutputChoice = localize('show command output', "Show Command Output");
if (err.stderr) {
choices.set(showCommandOutputChoice, async () => {
const timestamp = new Date().getTime();
const uri = Uri.parse(`git-output:/git-error-${timestamp}`);
let command = 'git';
if (err.gitArgs) {
command = `${command} ${err.gitArgs.join(' ')}`;
} else if (err.gitCommand) {
command = `${command} ${err.gitCommand}`;
}
this.commandErrors.set(uri, `> ${command}\n${err.stderr}`);
try {
const doc = await workspace.openTextDocument(uri);
await window.showTextDocument(doc);
} finally {
this.commandErrors.delete(uri);
}
});
}
switch (err.gitErrorCode) {
case GitErrorCodes.DirtyWorkTree:
message = localize('clean repo', "Please clean your repository working tree before checkout.");

View File

@@ -0,0 +1,39 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { workspace, Uri } from 'vscode';
import { getExtensionContext } from './main';
import { TextDecoder } from 'util';
const emojiRegex = /:([-+_a-z0-9]+):/g;
let emojiMap: Record<string, string> | undefined;
let emojiMapPromise: Promise<void> | undefined;
export async function ensureEmojis() {
if (emojiMap === undefined) {
if (emojiMapPromise === undefined) {
emojiMapPromise = loadEmojiMap();
}
await emojiMapPromise;
}
}
async function loadEmojiMap() {
const context = getExtensionContext();
const uri = (Uri as any).joinPath(context.extensionUri, 'resources', 'emojis.json');
emojiMap = JSON.parse(new TextDecoder('utf8').decode(await workspace.fs.readFile(uri)));
}
export function emojify(message: string) {
if (emojiMap === undefined) {
return message;
}
return message.replace(emojiRegex, (s, code) => {
return emojiMap?.[code] || s;
});
}

View File

@@ -13,7 +13,6 @@ import * as iconv from 'iconv-lite-umd';
import * as filetype from 'file-type';
import { assign, groupBy, IDisposable, toDisposable, dispose, mkdirp, readBytes, detectUnicodeEncoding, Encoding, onceEvent, splitInChunks, Limiter } from './util';
import { CancellationToken, Progress, Uri } from 'vscode';
import { URI } from 'vscode-uri';
import { detectEncoding } from './encoding';
import { Ref, RefType, Branch, Remote, GitErrorCodes, LogOptions, Change, Status, CommitOptions, BranchQuery } from './api/git';
import * as byline from 'byline';
@@ -261,6 +260,7 @@ export interface IGitErrorData {
exitCode?: number;
gitErrorCode?: string;
gitCommand?: string;
gitArgs?: string[];
}
export class GitError {
@@ -272,6 +272,7 @@ export class GitError {
exitCode?: number;
gitErrorCode?: string;
gitCommand?: string;
gitArgs?: string[];
constructor(data: IGitErrorData) {
if (data.error) {
@@ -288,6 +289,7 @@ export class GitError {
this.exitCode = data.exitCode;
this.gitErrorCode = data.gitErrorCode;
this.gitCommand = data.gitCommand;
this.gitArgs = data.gitArgs;
}
toString(): string {
@@ -351,6 +353,12 @@ function sanitizePath(path: string): string {
const COMMIT_FORMAT = '%H%n%aN%n%aE%n%at%n%ct%n%P%n%B';
export interface ICloneOptions {
readonly parentPath: string;
readonly progress: Progress<{ increment: number }>;
readonly recursive?: boolean;
}
export class Git {
readonly path: string;
@@ -373,18 +381,18 @@ export class Git {
return;
}
async clone(url: string, parentPath: string, progress: Progress<{ increment: number }>, cancellationToken?: CancellationToken): Promise<string> {
async clone(url: string, options: ICloneOptions, cancellationToken?: CancellationToken): Promise<string> {
let baseFolderName = decodeURI(url).replace(/[\/]+$/, '').replace(/^.*[\/\\]/, '').replace(/\.git$/, '') || 'repository';
let folderName = baseFolderName;
let folderPath = path.join(parentPath, folderName);
let folderPath = path.join(options.parentPath, folderName);
let count = 1;
while (count < 20 && await new Promise(c => exists(folderPath, c))) {
folderName = `${baseFolderName}-${count++}`;
folderPath = path.join(parentPath, folderName);
folderPath = path.join(options.parentPath, folderName);
}
await mkdirp(parentPath);
await mkdirp(options.parentPath);
const onSpawn = (child: cp.ChildProcess) => {
const decoder = new StringDecoder('utf8');
@@ -408,14 +416,18 @@ export class Git {
}
if (totalProgress !== previousProgress) {
progress.report({ increment: totalProgress - previousProgress });
options.progress.report({ increment: totalProgress - previousProgress });
previousProgress = totalProgress;
}
});
};
try {
await this.exec(parentPath, ['clone', url.includes(' ') ? encodeURI(url) : url, folderPath, '--progress'], { cancellationToken, onSpawn });
let command = ['clone', url.includes(' ') ? encodeURI(url) : url, folderPath, '--progress'];
if (options.recursive) {
command.push('--recursive');
}
await this.exec(options.parentPath, command, { cancellationToken, onSpawn });
} catch (err) {
if (err.stderr) {
err.stderr = err.stderr.replace(/^Cloning.+$/m, '').trim();
@@ -526,7 +538,8 @@ export class Git {
stderr: result.stderr,
exitCode: result.exitCode,
gitErrorCode: getGitErrorCode(result.stderr),
gitCommand: args[0]
gitCommand: args[0],
gitArgs: args
}));
}
@@ -679,7 +692,7 @@ export function parseGitmodules(raw: string): Submodule[] {
return;
}
const propertyMatch = /^\s*(\w+)\s+=\s+(.*)$/.exec(line);
const propertyMatch = /^\s*(\w+)\s*=\s*(.*)$/.exec(line);
if (!propertyMatch) {
return;
@@ -1155,7 +1168,7 @@ export class Repository {
break;
}
const originalUri = URI.file(path.isAbsolute(resourcePath) ? resourcePath : path.join(this.repositoryRoot, resourcePath));
const originalUri = Uri.file(path.isAbsolute(resourcePath) ? resourcePath : path.join(this.repositoryRoot, resourcePath));
let status: Status = Status.UNTRACKED;
// Copy or Rename status comes with a number, e.g. 'R100'. We don't need the number, so we use only first character of the status.
@@ -1183,7 +1196,7 @@ export class Repository {
break;
}
const uri = URI.file(path.isAbsolute(newPath) ? newPath : path.join(this.repositoryRoot, newPath));
const uri = Uri.file(path.isAbsolute(newPath) ? newPath : path.join(this.repositoryRoot, newPath));
result.push({
uri,
renameUri: uri,
@@ -1233,7 +1246,7 @@ export class Repository {
}
if (paths && paths.length) {
for (const chunk of splitInChunks(paths, MAX_CLI_LENGTH)) {
for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
await this.run([...args, '--', ...chunk]);
}
} else {
@@ -1286,13 +1299,17 @@ export class Repository {
await this.run(['update-index', add, '--cacheinfo', mode, hash, path]);
}
async checkout(treeish: string, paths: string[], opts: { track?: boolean } = Object.create(null)): Promise<void> {
async checkout(treeish: string, paths: string[], opts: { track?: boolean, detached?: boolean } = Object.create(null)): Promise<void> {
const args = ['checkout', '-q'];
if (opts.track) {
args.push('--track');
}
if (opts.detached) {
args.push('--detach');
}
if (treeish) {
args.push(treeish);
}
@@ -1308,6 +1325,7 @@ export class Repository {
} catch (err) {
if (/Please,? commit your changes or stash them/.test(err.stderr || '')) {
err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
err.gitTreeish = treeish;
}
throw err;
@@ -1405,6 +1423,11 @@ export class Repository {
await this.run(args);
}
async move(from: string, to: string): Promise<void> {
const args = ['mv', from, to];
await this.run(args);
}
async setBranchUpstream(name: string, upstream: string): Promise<void> {
const args = ['branch', '--set-upstream-to', upstream, name];
await this.run(args);
@@ -1455,7 +1478,7 @@ export class Repository {
const args = ['clean', '-f', '-q'];
for (const paths of groups) {
for (const chunk of splitInChunks(paths, MAX_CLI_LENGTH)) {
for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
promises.push(limiter.queue(() => this.run([...args, '--', ...chunk])));
}
}
@@ -1495,7 +1518,7 @@ export class Repository {
try {
if (paths && paths.length > 0) {
for (const chunk of splitInChunks(paths, MAX_CLI_LENGTH)) {
for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
await this.run([...args, '--', ...chunk]);
}
} else {
@@ -1527,9 +1550,11 @@ export class Repository {
await this.run(args);
}
async fetch(options: { remote?: string, ref?: string, all?: boolean, prune?: boolean, depth?: number, silent?: boolean } = {}): Promise<void> {
async fetch(options: { remote?: string, ref?: string, all?: boolean, prune?: boolean, depth?: number, silent?: boolean, readonly cancellationToken?: CancellationToken } = {}): Promise<void> {
const args = ['fetch'];
const spawnOptions: SpawnOptions = {};
const spawnOptions: SpawnOptions = {
cancellationToken: options.cancellationToken,
};
if (options.remote) {
args.push(options.remote);
@@ -1608,7 +1633,25 @@ export class Repository {
}
}
async push(remote?: string, name?: string, setUpstream: boolean = false, tags = false, forcePushMode?: ForcePushMode): Promise<void> {
async rebase(branch: string, options: PullOptions = {}): Promise<void> {
const args = ['rebase'];
args.push(branch);
try {
await this.run(args, options);
} catch (err) {
if (/^CONFLICT \([^)]+\): \b/m.test(err.stdout || '')) {
err.gitErrorCode = GitErrorCodes.Conflict;
} else if (/cannot rebase onto multiple branches/i.test(err.stderr || '')) {
err.gitErrorCode = GitErrorCodes.CantRebaseMultipleBranches;
}
throw err;
}
}
async push(remote?: string, name?: string, setUpstream: boolean = false, followTags = false, forcePushMode?: ForcePushMode, tags = false): Promise<void> {
const args = ['push'];
if (forcePushMode === ForcePushMode.ForceWithLease) {
@@ -1621,10 +1664,14 @@ export class Repository {
args.push('-u');
}
if (tags) {
if (followTags) {
args.push('--follow-tags');
}
if (tags) {
args.push('--tags');
}
if (remote) {
args.push(remote);
}
@@ -1650,6 +1697,11 @@ export class Repository {
}
}
async cherryPick(commitHash: string): Promise<void> {
const args = ['cherry-pick', commitHash];
await this.run(args);
}
async blame(path: string): Promise<string> {
try {
const args = ['blame', sanitizePath(path)];
@@ -1734,11 +1786,17 @@ export class Repository {
}
}
getStatus(limit = 5000): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
getStatus(opts?: { limit?: number, ignoreSubmodules?: boolean }): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
return new Promise<{ status: IFileStatus[]; didHitLimit: boolean; }>((c, e) => {
const parser = new GitStatusParser();
const env = { GIT_OPTIONAL_LOCKS: '0' };
const child = this.stream(['status', '-z', '-u'], { env });
const args = ['status', '-z', '-u'];
if (opts?.ignoreSubmodules) {
args.push('--ignore-submodules');
}
const child = this.stream(args, { env });
const onExit = (exitCode: number) => {
if (exitCode !== 0) {
@@ -1748,13 +1806,15 @@ export class Repository {
stderr,
exitCode,
gitErrorCode: getGitErrorCode(stderr),
gitCommand: 'status'
gitCommand: 'status',
gitArgs: args
}));
}
c({ status: parser.status, didHitLimit: false });
};
const limit = opts?.limit ?? 5000;
const onStdoutData = (raw: string) => {
parser.update(raw);
@@ -1818,7 +1878,7 @@ export class Repository {
args.push('--sort', `-${opts.sort}`);
}
args.push('--format', '%(refname) %(objectname)');
args.push('--format', '%(refname) %(objectname) %(*objectname)');
if (opts?.pattern) {
args.push(opts.pattern);
@@ -1833,12 +1893,12 @@ export class Repository {
const fn = (line: string): Ref | null => {
let match: RegExpExecArray | null;
if (match = /^refs\/heads\/([^ ]+) ([0-9a-f]{40})$/.exec(line)) {
if (match = /^refs\/heads\/([^ ]+) ([0-9a-f]{40}) ([0-9a-f]{40})?$/.exec(line)) {
return { name: match[1], commit: match[2], type: RefType.Head };
} else if (match = /^refs\/remotes\/([^/]+)\/([^ ]+) ([0-9a-f]{40})$/.exec(line)) {
} else if (match = /^refs\/remotes\/([^/]+)\/([^ ]+) ([0-9a-f]{40}) ([0-9a-f]{40})?$/.exec(line)) {
return { name: `${match[1]}/${match[2]}`, commit: match[3], type: RefType.RemoteHead, remote: match[1] };
} else if (match = /^refs\/tags\/([^ ]+) ([0-9a-f]{40})$/.exec(line)) {
return { name: match[1], commit: match[2], type: RefType.Tag };
} else if (match = /^refs\/tags\/([^ ]+) ([0-9a-f]{40}) ([0-9a-f]{40})?$/.exec(line)) {
return { name: match[1], commit: match[3] ?? match[2], type: RefType.Tag };
}
return null;

View File

@@ -169,7 +169,14 @@ export async function _activate(context: ExtensionContext): Promise<GitExtension
}
}
let _context: ExtensionContext;
export function getExtensionContext(): ExtensionContext {
return _context;
}
export async function activate(context: ExtensionContext): Promise<GitExtension> {
_context = context;
const result = await _activate(context);
context.subscriptions.push(registerAPICommands(result));
return result;

View File

@@ -34,4 +34,4 @@ export class GitProtocolHandler implements UriHandler {
dispose(): void {
this.disposables = dispose(this.disposables);
}
}
}

View File

@@ -80,12 +80,22 @@ class RemoteSourceProviderQuickPick {
export interface PickRemoteSourceOptions {
readonly providerLabel?: (provider: RemoteSourceProvider) => string;
readonly urlLabel?: string;
readonly providerName?: string;
}
export async function pickRemoteSource(model: Model, options: PickRemoteSourceOptions = {}): Promise<string | undefined> {
const quickpick = window.createQuickPick<(QuickPickItem & { provider?: RemoteSourceProvider, url?: string })>();
quickpick.ignoreFocusOut = true;
if (options.providerName) {
const provider = model.getRemoteProviders()
.filter(provider => provider.name === options.providerName)[0];
if (provider) {
return await pickProviderSource(provider);
}
}
const providers = model.getRemoteProviders()
.map(provider => ({ label: (provider.icon ? `$(${provider.icon}) ` : '') + (options.providerLabel ? options.providerLabel(provider) : provider.name), alwaysShow: true, provider }));
@@ -116,16 +126,22 @@ export async function pickRemoteSource(model: Model, options: PickRemoteSourceOp
if (result.url) {
return result.url;
} else if (result.provider) {
const quickpick = new RemoteSourceProviderQuickPick(result.provider);
const remote = await quickpick.pick();
if (remote) {
if (typeof remote.url === 'string') {
return remote.url;
} else if (remote.url.length > 0) {
return await window.showQuickPick(remote.url, { ignoreFocusOut: true, placeHolder: localize('pick url', "Choose a URL to clone from.") });
}
}
return await pickProviderSource(result.provider);
}
}
return undefined;
}
async function pickProviderSource(provider: RemoteSourceProvider): Promise<string | undefined> {
const quickpick = new RemoteSourceProviderQuickPick(provider);
const remote = await quickpick.pick();
if (remote) {
if (typeof remote.url === 'string') {
return remote.url;
} else if (remote.url.length > 0) {
return await window.showQuickPick(remote.url, { ignoreFocusOut: true, placeHolder: localize('pick url', "Choose a URL to clone from.") });
}
}

View File

@@ -5,7 +5,7 @@
import * as fs from 'fs';
import * as path from 'path';
import { CancellationToken, Command, Disposable, Event, EventEmitter, Memento, OutputChannel, ProgressLocation, ProgressOptions, scm, SourceControl, SourceControlInputBox, SourceControlInputBoxValidation, SourceControlInputBoxValidationType, SourceControlResourceDecorations, SourceControlResourceGroup, SourceControlResourceState, ThemeColor, Uri, window, workspace, WorkspaceEdit, FileDecoration } from 'vscode';
import { CancellationToken, Command, Disposable, Event, EventEmitter, Memento, OutputChannel, ProgressLocation, ProgressOptions, scm, SourceControl, SourceControlInputBox, SourceControlInputBoxValidation, SourceControlInputBoxValidationType, SourceControlResourceDecorations, SourceControlResourceGroup, SourceControlResourceState, ThemeColor, Uri, window, workspace, WorkspaceEdit, FileDecoration, commands } from 'vscode';
import * as nls from 'vscode-nls';
import { Branch, Change, GitErrorCodes, LogOptions, Ref, RefType, Remote, Status, CommitOptions, BranchQuery } from './api/git';
import { AutoFetcher } from './autofetch';
@@ -292,6 +292,7 @@ export const enum Operation {
Fetch = 'Fetch',
Pull = 'Pull',
Push = 'Push',
CherryPick = 'CherryPick',
Sync = 'Sync',
Show = 'Show',
Stage = 'Stage',
@@ -300,6 +301,7 @@ export const enum Operation {
RenameBranch = 'RenameBranch',
DeleteRef = 'DeleteRef',
Merge = 'Merge',
Rebase = 'Rebase',
Ignore = 'Ignore',
Tag = 'Tag',
DeleteTag = 'DeleteTag',
@@ -314,6 +316,8 @@ export const enum Operation {
Blame = 'Blame',
Log = 'Log',
LogFile = 'LogFile',
Move = 'Move'
}
function isReadOnly(operation: Operation): boolean {
@@ -642,6 +646,7 @@ export class Repository implements Disposable {
}
this._rebaseCommit = rebaseCommit;
commands.executeCommand('setContext', 'gitRebaseInProgress', !!this._rebaseCommit);
}
get rebaseCommit(): Commit | undefined {
@@ -744,11 +749,11 @@ export class Repository implements Disposable {
onConfigListener(updateIndexGroupVisibility, this, this.disposables);
updateIndexGroupVisibility();
const onConfigListenerForBranchSortOrder = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.branchSortOrder', root));
onConfigListenerForBranchSortOrder(this.updateModelState, this, this.disposables);
const onConfigListenerForUntracked = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.untrackedChanges', root));
onConfigListenerForUntracked(this.updateModelState, this, this.disposables);
filterEvent(workspace.onDidChangeConfiguration, e =>
e.affectsConfiguration('git.branchSortOrder', root)
|| e.affectsConfiguration('git.untrackedChanges', root)
|| e.affectsConfiguration('git.ignoreSubmodules', root)
)(this.updateModelState, this, this.disposables);
const updateInputBoxVisibility = () => {
const config = workspace.getConfiguration('git', root);
@@ -862,6 +867,12 @@ export class Repository implements Disposable {
return;
}
const path = uri.path;
if (this.mergeGroup.resourceStates.some(r => r.resourceUri.path === path)) {
return undefined;
}
return toGitUri(uri, '', { replaceFileExtension: true });
}
@@ -1051,6 +1062,14 @@ export class Repository implements Disposable {
await this.run(Operation.RenameBranch, () => this.repository.renameBranch(name));
}
async cherryPick(commitHash: string): Promise<void> {
await this.run(Operation.CherryPick, () => this.repository.cherryPick(commitHash));
}
async move(from: string, to: string): Promise<void> {
await this.run(Operation.Move, () => this.repository.move(from, to));
}
async getBranch(name: string): Promise<Branch> {
return await this.run(Operation.GetBranch, () => this.repository.getBranch(name));
}
@@ -1067,6 +1086,10 @@ export class Repository implements Disposable {
await this.run(Operation.Merge, () => this.repository.merge(ref));
}
async rebase(branch: string): Promise<void> {
await this.run(Operation.Rebase, () => this.repository.rebase(branch));
}
async tag(name: string, message?: string): Promise<void> {
await this.run(Operation.Tag, () => this.repository.tag(name, message));
}
@@ -1075,8 +1098,8 @@ export class Repository implements Disposable {
await this.run(Operation.DeleteTag, () => this.repository.deleteTag(name));
}
async checkout(treeish: string): Promise<void> {
await this.run(Operation.Checkout, () => this.repository.checkout(treeish, []));
async checkout(treeish: string, opts?: { detached?: boolean }): Promise<void> {
await this.run(Operation.Checkout, () => this.repository.checkout(treeish, [], opts));
}
async checkoutTracking(treeish: string): Promise<void> {
@@ -1113,21 +1136,31 @@ export class Repository implements Disposable {
@throttle
async fetchDefault(options: { silent?: boolean } = {}): Promise<void> {
await this.run(Operation.Fetch, () => this.repository.fetch(options));
await this._fetch({ silent: options.silent });
}
@throttle
async fetchPrune(): Promise<void> {
await this.run(Operation.Fetch, () => this.repository.fetch({ prune: true }));
await this._fetch({ prune: true });
}
@throttle
async fetchAll(): Promise<void> {
await this.run(Operation.Fetch, () => this.repository.fetch({ all: true }));
await this._fetch({ all: true });
}
async fetch(remote?: string, ref?: string, depth?: number): Promise<void> {
await this.run(Operation.Fetch, () => this.repository.fetch({ remote, ref, depth }));
await this._fetch({ remote, ref, depth });
}
private async _fetch(options: { remote?: string, ref?: string, all?: boolean, prune?: boolean, depth?: number, silent?: boolean } = {}): Promise<void> {
if (!options.prune) {
const config = workspace.getConfiguration('git', Uri.file(this.root));
const prune = config.get<boolean>('pruneOnFetch');
options.prune = prune;
}
await this.run(Operation.Fetch, async () => this.repository.fetch(options));
}
@throttle
@@ -1163,11 +1196,12 @@ export class Repository implements Disposable {
const fetchOnPull = config.get<boolean>('fetchOnPull');
const tags = config.get<boolean>('pullTags');
// When fetchOnPull is enabled, fetch all branches when pulling
if (fetchOnPull) {
await this.repository.pull(rebase, undefined, undefined, { unshallow, tags });
} else {
await this.repository.pull(rebase, remote, branch, { unshallow, tags });
await this.repository.fetch({ all: true });
}
await this.repository.pull(rebase, remote, branch, { unshallow, tags });
});
});
}
@@ -1193,6 +1227,10 @@ export class Repository implements Disposable {
await this.run(Operation.Push, () => this._push(remote, undefined, false, true, forcePushMode));
}
async pushTags(remote?: string, forcePushMode?: ForcePushMode): Promise<void> {
await this.run(Operation.Push, () => this._push(remote, undefined, false, false, forcePushMode, true));
}
async blame(path: string): Promise<string> {
return await this.run(Operation.Blame, () => this.repository.blame(path));
}
@@ -1223,11 +1261,18 @@ export class Repository implements Disposable {
const config = workspace.getConfiguration('git', Uri.file(this.root));
const fetchOnPull = config.get<boolean>('fetchOnPull');
const tags = config.get<boolean>('pullTags');
const followTags = config.get<boolean>('followTagsWhenSync');
const supportCancellation = config.get<boolean>('supportCancellation');
const fn = fetchOnPull
? async (cancellationToken?: CancellationToken) => await this.repository.pull(rebase, undefined, undefined, { tags, cancellationToken })
: async (cancellationToken?: CancellationToken) => await this.repository.pull(rebase, remoteName, pullBranch, { tags, cancellationToken });
const fn = async (cancellationToken?: CancellationToken) => {
// When fetchOnPull is enabled, fetch all branches when pulling
if (fetchOnPull) {
await this.repository.fetch({ all: true, cancellationToken });
}
await this.repository.pull(rebase, remoteName, pullBranch, { tags, cancellationToken });
};
if (supportCancellation) {
const opts: ProgressOptions = {
@@ -1250,7 +1295,7 @@ export class Repository implements Disposable {
const shouldPush = this.HEAD && (typeof this.HEAD.ahead === 'number' ? this.HEAD.ahead > 0 : true);
if (shouldPush) {
await this._push(remoteName, pushBranch);
await this._push(remoteName, pushBranch, false, followTags);
}
});
});
@@ -1412,9 +1457,9 @@ export class Repository implements Disposable {
return ignored;
}
private async _push(remote?: string, refspec?: string, setUpstream: boolean = false, tags = false, forcePushMode?: ForcePushMode): Promise<void> {
private async _push(remote?: string, refspec?: string, setUpstream: boolean = false, followTags = false, forcePushMode?: ForcePushMode, tags = false): Promise<void> {
try {
await this.repository.push(remote, refspec, setUpstream, tags, forcePushMode);
await this.repository.push(remote, refspec, setUpstream, followTags, forcePushMode, tags);
} catch (err) {
if (!remote || !refspec) {
throw err;
@@ -1512,9 +1557,12 @@ export class Repository implements Disposable {
@throttle
private async updateModelState(): Promise<void> {
const { status, didHitLimit } = await this.repository.getStatus();
const config = workspace.getConfiguration('git');
const scopedConfig = workspace.getConfiguration('git', Uri.file(this.repository.root));
const ignoreSubmodules = scopedConfig.get<boolean>('ignoreSubmodules');
const { status, didHitLimit } = await this.repository.getStatus({ ignoreSubmodules });
const config = workspace.getConfiguration('git');
const shouldIgnore = config.get<boolean>('ignoreLimitWarning') === true;
const useIcons = !config.get<boolean>('decorations.enabled', true);
this.isRepositoryHuge = didHitLimit;
@@ -1786,6 +1834,28 @@ export class Repository implements Disposable {
return `${this.HEAD.behind}${this.HEAD.ahead}`;
}
get syncTooltip(): string {
if (!this.HEAD
|| !this.HEAD.name
|| !this.HEAD.commit
|| !this.HEAD.upstream
|| !(this.HEAD.ahead || this.HEAD.behind)
) {
return localize('sync changes', "Synchronize Changes");
}
const remoteName = this.HEAD && this.HEAD.remote || this.HEAD.upstream.remote;
const remote = this.remotes.find(r => r.name === remoteName);
if ((remote && remote.isReadOnly) || !this.HEAD.ahead) {
return localize('pull n', "Pull {0} commits from {1}/{2}", this.HEAD.behind, this.HEAD.upstream.remote, this.HEAD.upstream.name);
} else if (!this.HEAD.behind) {
return localize('push n', "Push {0} commits to {1}/{2}", this.HEAD.ahead, this.HEAD.upstream.remote, this.HEAD.upstream.name);
} else {
return localize('pull push n', "Pull {0} and push {1} commits between {2}/{3}", this.HEAD.behind, this.HEAD.ahead, this.HEAD.upstream.remote, this.HEAD.upstream.name);
}
}
private updateInputBoxPlaceholder(): void {
const branchName = this.headShortName;

View File

@@ -28,7 +28,7 @@ class CheckoutStatusBar {
return {
command: 'git.checkout',
tooltip: `${this.repository.headLabel}`,
tooltip: localize('checkout', "Checkout branch/tag..."),
title,
arguments: [this.repository.sourceControl]
};
@@ -150,7 +150,7 @@ class SyncStatusBar {
const rebaseWhenSync = config.get<string>('rebaseWhenSync');
command = rebaseWhenSync ? 'git.syncRebase' : 'git.sync';
tooltip = localize('sync changes', "Synchronize Changes");
tooltip = this.repository.syncTooltip;
} else {
icon = '$(cloud-upload)';
command = 'git.publish';

View File

@@ -184,6 +184,17 @@ suite('git', () => {
{ name: 'deps/spdlog', path: 'deps/spdlog', url: 'https://github.com/gabime/spdlog.git' }
]);
});
test('whitespace again #108371', () => {
const sample = `[submodule "deps/spdlog"]
path= deps/spdlog
url=https://github.com/gabime/spdlog.git
`;
assert.deepEqual(parseGitmodules(sample), [
{ name: 'deps/spdlog', path: 'deps/spdlog', url: 'https://github.com/gabime/spdlog.git' }
]);
});
});
suite('parseGitCommit', () => {

View File

@@ -4,10 +4,11 @@
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vscode-nls';
import { CancellationToken, Disposable, env, Event, EventEmitter, ThemeIcon, Timeline, TimelineChangeEvent, TimelineItem, TimelineOptions, TimelineProvider, Uri, workspace } from 'vscode';
import { CancellationToken, ConfigurationChangeEvent, Disposable, env, Event, EventEmitter, ThemeIcon, Timeline, TimelineChangeEvent, TimelineItem, TimelineOptions, TimelineProvider, Uri, workspace } from 'vscode';
import { Model } from './model';
import { Repository, Resource } from './repository';
import { debounce } from './decorators';
import { emojify, ensureEmojis } from './emoji';
const localize = nls.loadMessageBundle();
@@ -75,6 +76,7 @@ export class GitTimelineProvider implements TimelineProvider {
constructor(private readonly model: Model) {
this.disposable = Disposable.from(
model.onDidOpenRepository(this.onRepositoriesChanged, this),
workspace.onDidChangeConfiguration(this.onConfigurationChanged, this)
);
if (model.repositories.length) {
@@ -110,6 +112,8 @@ export class GitTimelineProvider implements TimelineProvider {
);
}
const config = workspace.getConfiguration('git.timeline');
// TODO@eamodio: Ensure that the uri is a file -- if not we could get the history of the repo?
let limit: number | undefined;
@@ -129,6 +133,8 @@ export class GitTimelineProvider implements TimelineProvider {
limit = options.limit === undefined ? undefined : options.limit + 1;
}
await ensureEmojis();
const commits = await repo.logFile(uri, {
maxEntries: limit,
hash: options.cursor,
@@ -146,13 +152,20 @@ export class GitTimelineProvider implements TimelineProvider {
const dateFormatter = new Intl.DateTimeFormat(env.language, { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' });
const items = commits.map<GitTimelineItem>((c, i) => {
const date = c.commitDate; // c.authorDate
const dateType = config.get<'committed' | 'authored'>('date');
const showAuthor = config.get<boolean>('showAuthor');
const item = new GitTimelineItem(c.hash, commits[i + 1]?.hash ?? `${c.hash}^`, c.message, date?.getTime() ?? 0, c.hash, 'git:file:commit');
const items = commits.map<GitTimelineItem>((c, i) => {
const date = dateType === 'authored' ? c.authorDate : c.commitDate;
const message = emojify(c.message);
const item = new GitTimelineItem(c.hash, commits[i + 1]?.hash ?? `${c.hash}^`, message, date?.getTime() ?? 0, c.hash, 'git:file:commit');
item.iconPath = new (ThemeIcon as any)('git-commit');
item.description = c.authorName;
item.detail = `${c.authorName} (${c.authorEmail}) \u2014 ${c.hash.substr(0, 8)}\n${dateFormatter.format(date)}\n\n${c.message}`;
if (showAuthor) {
item.description = c.authorName;
}
item.detail = `${c.authorName} (${c.authorEmail}) — ${c.hash.substr(0, 8)}\n${dateFormatter.format(date)}\n\n${message}`;
item.command = {
title: 'Open Comparison',
command: 'git.timeline.openDiff',
@@ -173,7 +186,7 @@ export class GitTimelineProvider implements TimelineProvider {
// TODO@eamodio: Replace with a better icon -- reflecting its status maybe?
item.iconPath = new (ThemeIcon as any)('git-commit');
item.description = '';
item.detail = localize('git.timeline.detail', '{0} \u2014 {1}\n{2}\n\n{3}', you, localize('git.index', 'Index'), dateFormatter.format(date), Resource.getStatusText(index.type));
item.detail = localize('git.timeline.detail', '{0} {1}\n{2}\n\n{3}', you, localize('git.index', 'Index'), dateFormatter.format(date), Resource.getStatusText(index.type));
item.command = {
title: 'Open Comparison',
command: 'git.timeline.openDiff',
@@ -191,7 +204,7 @@ export class GitTimelineProvider implements TimelineProvider {
// TODO@eamodio: Replace with a better icon -- reflecting its status maybe?
item.iconPath = new (ThemeIcon as any)('git-commit');
item.description = '';
item.detail = localize('git.timeline.detail', '{0} \u2014 {1}\n{2}\n\n{3}', you, localize('git.workingTree', 'Working Tree'), dateFormatter.format(date), Resource.getStatusText(working.type));
item.detail = localize('git.timeline.detail', '{0} {1}\n{2}\n\n{3}', you, localize('git.workingTree', 'Working Tree'), dateFormatter.format(date), Resource.getStatusText(working.type));
item.command = {
title: 'Open Comparison',
command: 'git.timeline.openDiff',
@@ -214,6 +227,12 @@ export class GitTimelineProvider implements TimelineProvider {
}
}
private onConfigurationChanged(e: ConfigurationChangeEvent) {
if (e.affectsConfiguration('git.timeline.date') || e.affectsConfiguration('git.timeline.showAuthor')) {
this.fireChanged();
}
}
private onRepositoriesChanged(_repo: Repository) {
// console.log(`GitTimelineProvider.onRepositoriesChanged`);