Skip to content

Commit ad48171

Browse files
Phil Stainerphilstainer
authored andcommitted
refactor(getWorktrees): update command and improve worktree parsing
1 parent 4a556f0 commit ad48171

1 file changed

Lines changed: 24 additions & 11 deletions

File tree

src/helpers/worktree/getWorktrees.ts

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import { executeCommand } from '#/helpers/general';
2-
import { BARE_REPOSITORY } from '#/src/config/constants';
32
import { getCurrentBranchName, isInsideBareRepository } from '../git';
4-
import { removeFirstAndLastCharacter } from '../string';
53

64
export const getWorktrees = async (
75
withBareRepo = false,
86
showCurrentWorktree = false
97
) => {
10-
const command = 'git worktree list';
8+
const command = 'git worktree list --porcelain';
119

1210
try {
1311
const { stdout } = await executeCommand(command);
@@ -34,15 +32,29 @@ const getFilteredWorktrees = async (
3432
const currentWorktree = await getCurrentBranchName();
3533

3634
let splitWorktrees = stdout
37-
.split('\n')
38-
.filter((str) => str !== '')
39-
.map((str) => {
40-
const [path, hash, worktree] = str.split(' ').filter((str) => str !== '');
35+
.trim()
36+
.split('\n\n')
37+
.map((path): { path: string; hash: string; worktree: string } => {
38+
let worktree: string | null = null;
39+
let commit: string | null = null;
40+
let branch: string | null = null;
41+
42+
path.split('\n').forEach((line) => {
43+
if (line.startsWith('worktree ')) {
44+
worktree = line.slice(9);
45+
} else if (line.startsWith('HEAD ')) {
46+
commit = line.slice(5, 12); // Short commit hash
47+
} else if (line.startsWith('branch refs/heads/')) {
48+
branch = line.slice(18);
49+
}
50+
});
51+
52+
if (!worktree) throw new Error('Missing worktree!');
4153

4254
return {
43-
path,
44-
hash: worktree ? hash : '',
45-
worktree: removeFirstAndLastCharacter(worktree ? worktree : hash),
55+
path: worktree ?? '',
56+
hash: commit ?? '',
57+
worktree: branch ?? commit ?? '',
4658
};
4759
});
4860

@@ -52,8 +64,9 @@ const getFilteredWorktrees = async (
5264
);
5365

5466
if (!includeBare)
67+
// Filter out bare worktree and worktrees that are not in the bare directory e.g have been manually moved
5568
splitWorktrees = splitWorktrees.filter(
56-
({ worktree }) => worktree !== BARE_REPOSITORY
69+
({ path }) => !path.endsWith('.bare')
5770
);
5871

5972
return splitWorktrees;

0 commit comments

Comments
 (0)