Skip to content

Commit

Permalink
Merge pull request #75 from tiktok/feat-checkout-dash
Browse files Browse the repository at this point in the history
Supports "sparo checkout -"
  • Loading branch information
chengcyber authored May 31, 2024
2 parents 79b0f34 + 7ea9bdc commit a045b7f
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 5 deletions.
10 changes: 5 additions & 5 deletions apps/sparo-lib/src/cli/commands/checkout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.`);
}
}
}

Expand Down
18 changes: 18 additions & 0 deletions apps/sparo-lib/src/services/GitService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
10 changes: 10 additions & 0 deletions common/changes/sparo/feat-checkout-dash_2024-05-30-05-28.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "sparo",
"comment": "\"sparo checkout -\" can checkout to previous branch correctly",
"type": "none"
}
],
"packageName": "sparo"
}
1 change: 1 addition & 0 deletions common/reviews/api/sparo-lib.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit a045b7f

Please sign in to comment.