|
17 | 17 | * along with this program. If not, see <https://www.gnu.org/licenses/>.
|
18 | 18 | */
|
19 | 19 | 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'; |
21 | 21 | import { SHOW_USAGE } from '../help.js';
|
22 | 22 |
|
23 | 23 | const CHECKOUT = {
|
@@ -122,33 +122,47 @@ const CHECKOUT = {
|
122 | 122 | return;
|
123 | 123 | }
|
124 | 124 |
|
125 |
| - // Check out a branch |
| 125 | + // Check out a branch or commit |
126 | 126 | // TODO: Check out files.
|
127 | 127 | {
|
128 | 128 | if (positionals.length === 0 || positionals.length > 1) {
|
129 | 129 | stderr('error: Expected 1 argument, for <branch>.');
|
130 | 130 | throw SHOW_USAGE;
|
131 | 131 | }
|
132 | 132 | const { branches, current_branch } = await get_branch_data();
|
133 |
| - const branch_name = positionals.shift(); |
| 133 | + const reference = positionals.shift(); |
134 | 134 |
|
135 |
| - if (branch_name === current_branch) { |
136 |
| - stdout(`Already on '${branch_name}'`); |
| 135 | + if (reference === current_branch) { |
| 136 | + stdout(`Already on '${reference}'`); |
137 | 137 | return;
|
138 | 138 | }
|
139 | 139 |
|
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.`); |
142 | 145 |
|
143 | 146 | await git.checkout({
|
144 | 147 | fs,
|
145 | 148 | dir,
|
146 | 149 | gitdir,
|
147 | 150 | cache,
|
148 |
| - ref: branch_name, |
| 151 | + ref: reference, |
149 | 152 | force: options.force,
|
150 | 153 | });
|
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 | + } |
152 | 166 | }
|
153 | 167 | }
|
154 | 168 | };
|
|
0 commit comments