Skip to content

Commit 057b3ac

Browse files
AtkinsSJKernelDeimos
authored andcommitted
feat(git): Allow checking out a commit instead of a branch
1 parent 2c9b1a3 commit 057b3ac

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

packages/git/src/subcommands/checkout.js

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
* along with this program. If not, see <https://www.gnu.org/licenses/>.
1818
*/
1919
import git from 'isomorphic-git';
20-
import { find_repo_root } from '../git-helpers.js';
20+
import { find_repo_root, shorten_hash } from '../git-helpers.js';
2121
import { SHOW_USAGE } from '../help.js';
2222

2323
const CHECKOUT = {
@@ -122,33 +122,47 @@ const CHECKOUT = {
122122
return;
123123
}
124124

125-
// Check out a branch
125+
// Check out a branch or commit
126126
// TODO: Check out files.
127127
{
128128
if (positionals.length === 0 || positionals.length > 1) {
129129
stderr('error: Expected 1 argument, for <branch>.');
130130
throw SHOW_USAGE;
131131
}
132132
const { branches, current_branch } = await get_branch_data();
133-
const branch_name = positionals.shift();
133+
const reference = positionals.shift();
134134

135-
if (branch_name === current_branch) {
136-
stdout(`Already on '${branch_name}'`);
135+
if (reference === current_branch) {
136+
stdout(`Already on '${reference}'`);
137137
return;
138138
}
139139

140-
if (!branches.includes(branch_name))
141-
throw new Error(`Branch '${branch_name}' not found.`);
140+
const old_oid = await git.resolveRef({ fs, dir, gitdir, ref: 'HEAD' });
141+
142+
const oid = await git.resolveRef({ fs, dir, gitdir, ref: reference });
143+
if (!oid)
144+
throw new Error(`Reference '${reference}' not found.`);
142145

143146
await git.checkout({
144147
fs,
145148
dir,
146149
gitdir,
147150
cache,
148-
ref: branch_name,
151+
ref: reference,
149152
force: options.force,
150153
});
151-
stdout(`Switched to branch '${branch_name}'`);
154+
if (branches.includes(reference)) {
155+
stdout(`Switched to branch '${reference}'`);
156+
} else {
157+
const commit = await git.readCommit({ fs, dir, gitdir, oid });
158+
const commit_title = commit.commit.message.split('\n', 2)[0];
159+
160+
const old_commit = await git.readCommit({ fs, dir, gitdir, oid: old_oid });
161+
const old_commit_title = old_commit.commit.message.split('\n', 2)[0];
162+
163+
stdout(`Previous HEAD position was ${shorten_hash(old_oid)} ${old_commit_title}`);
164+
stdout(`HEAD is now at ${shorten_hash(oid)} ${commit_title}`);
165+
}
152166
}
153167
}
154168
};

0 commit comments

Comments
 (0)