feat: support checkout -

This commit is contained in:
Cheng Liu 2024-05-29 22:26:46 -07:00
parent b53d31c54a
commit ce5f4221e3
No known key found for this signature in database
GPG key ID: EEC8452F7DB85CD6
3 changed files with 24 additions and 5 deletions

View file

@ -122,11 +122,11 @@ export class CheckoutCommand implements ICommand<ICheckoutCommandOptions> {
if (!branch) {
const checkoutIndex: number = process.argv.findIndex((value: string) => value === 'checkout');
if (checkoutIndex >= 0 && process.argv[checkoutIndex + 1] === '-') {
branch = '-';
// FIXME: supports "sparo checkout -"
throw new Error(
`Git's "-" token is not yet supported. If this feature is important for your work, please let us know by creating a GitHub issue.`
);
// - is a shortcut of @{-1}
branch = gitService.getPreviousBranch(1);
if (!branch) {
throw new Error(`Argument "-" is unknown revision or path not in the working tree.`);
}
}
}

View file

@ -445,6 +445,24 @@ Please specify a directory on the command line
return currentBranch;
}
/**
* Retrieves the previous branch name using `@{-n}` syntax
*
* Assume:
* git checkout feature
* git checkout main
* ---
* `git checkout @{-1}` equals to run `git checkout feature`.
* Running `getPreviousBranch(1)` works in the similar way and returns "feature" in this case.
*/
public getPreviousBranch(n: number): string {
const result: string = this.executeGitCommandAndCaptureOutput({
args: ['rev-parse', '--symbolic-full-name', '--abbrev-ref=loose', `@{-${n}}`]
}).trim();
this._terminalService.terminal.writeDebugLine(`getPreviousBranch ${n}: ${result}`);
return result;
}
/**
* Check existence for a list of branch name
*/

View file

@ -46,6 +46,7 @@ export class GitService {
getIsSparseCheckoutMode(): boolean | undefined;
// (undocumented)
getObjectType(object: string): IObjectType | undefined;
getPreviousBranch(n: number): string;
// (undocumented)
getRepoInfo(): GitRepoInfo;
get gitPath(): string | undefined;