aligndev 0.27.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -11
- package/dist/cli.js +11 -1
- package/dist/code/code-cli.d.ts +2 -1
- package/dist/code/code-cli.js +57 -34
- package/dist/code/machine-id.d.ts +1 -0
- package/dist/code/machine-id.js +34 -0
- package/dist/code/session-file.d.ts +8 -3
- package/dist/code/session-file.js +48 -33
- package/dist/guide/topics.js +2 -1
- package/dist/project/plans.d.ts +9 -0
- package/dist/project/plans.js +40 -0
- package/dist/project/status.js +6 -24
- package/dist/worktree/add.d.ts +20 -0
- package/dist/worktree/add.js +175 -0
- package/dist/worktree/git.d.ts +24 -0
- package/dist/worktree/git.js +103 -0
- package/dist/worktree/remove.d.ts +8 -0
- package/dist/worktree/remove.js +62 -0
- package/dist/worktree/worktree-cli.d.ts +10 -0
- package/dist/worktree/worktree-cli.js +122 -0
- package/package.json +1 -1
- package/templates/guide/code.md +11 -31
- package/templates/guide/playbook/channel-handling.md +6 -4
- package/templates/guide/playbook/consultation.md +5 -3
- package/templates/guide/playbook/playbook.md +7 -26
- package/templates/guide/playbook/project-lifecycle.md +19 -17
- package/templates/guide/playbook/project-workspace-setup.md +20 -53
- package/templates/guide/playbook/work-files-setup.md +33 -0
- package/templates/guide/playbook/working-session.md +57 -93
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CommandForms } from "../command-form.js";
|
|
2
|
+
import type { GitContext } from "../worktree/git.js";
|
|
3
|
+
import { type ProjectReport } from "./layout.js";
|
|
4
|
+
export interface PlansContext extends GitContext {
|
|
5
|
+
alignfirstCommand: string[];
|
|
6
|
+
forms: CommandForms;
|
|
7
|
+
}
|
|
8
|
+
export declare function validateEffectivePlans(ctx: PlansContext): string;
|
|
9
|
+
export declare function readReport(ctx: PlansContext): ProjectReport;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
2
|
+
import { runAlignfirst } from "../alignfirst-cli.js";
|
|
3
|
+
import { errorMessage } from "../errors.js";
|
|
4
|
+
import { readProjectReport } from "./layout.js";
|
|
5
|
+
export function validateEffectivePlans(ctx) {
|
|
6
|
+
try {
|
|
7
|
+
const result = runAlignfirst(ctx.alignfirstCommand, ["plans", "check", "--json"], ctx.cwd, ctx.env);
|
|
8
|
+
if (result.status !== 0) {
|
|
9
|
+
const diagnostic = result.stderr.trimEnd();
|
|
10
|
+
throw new Error(diagnostic === "" ? "alignfirst plans check failed" : diagnostic);
|
|
11
|
+
}
|
|
12
|
+
let value;
|
|
13
|
+
try {
|
|
14
|
+
value = JSON.parse(result.stdout);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new Error(`Invalid alignfirst plans check JSON report for ${ctx.cwd}`);
|
|
18
|
+
}
|
|
19
|
+
if (!isRecord(value) ||
|
|
20
|
+
!isRecord(value.plans) ||
|
|
21
|
+
typeof value.plans.target !== "string" ||
|
|
22
|
+
value.plans.target.trim().length === 0 ||
|
|
23
|
+
!isAbsolute(value.plans.target)) {
|
|
24
|
+
throw new Error(`Invalid alignfirst plans check report for ${ctx.cwd}`);
|
|
25
|
+
}
|
|
26
|
+
return value.plans.target;
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
throw new Error(`${errorMessage(error)}\nSee \`${ctx.forms.aligndev} guide work-files-setup\` for authorized preparation.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function isRecord(value) {
|
|
33
|
+
return typeof value === "object" && value !== null;
|
|
34
|
+
}
|
|
35
|
+
export function readReport(ctx) {
|
|
36
|
+
const report = readProjectReport(ctx.alignfirstCommand, ctx.cwd, ctx.env);
|
|
37
|
+
if ("error" in report)
|
|
38
|
+
throw new Error(report.error);
|
|
39
|
+
return report;
|
|
40
|
+
}
|
package/dist/project/status.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
2
|
import { realpathSync } from "node:fs";
|
|
3
3
|
import { basename } from "node:path";
|
|
4
|
+
import { readWorktrees } from "../worktree/git.js";
|
|
4
5
|
import { errorMessage, isNodeError } from "../errors.js";
|
|
5
6
|
const URL_WITH_AUTHORITY = /^[A-Za-z][A-Za-z\d+.-]*:\/\//u;
|
|
6
7
|
export function getProjectStatus(inventory, projectPath) {
|
|
@@ -37,7 +38,11 @@ function buildProjectDetails(project) {
|
|
|
37
38
|
aligndev: project.description.aligndev,
|
|
38
39
|
locations: project.description.locations,
|
|
39
40
|
workspaces: project.workspaces,
|
|
40
|
-
worktrees: readWorktrees(project.path)
|
|
41
|
+
worktrees: readWorktrees({ cwd: project.path, env: process.env }, project.path).map((tree) => ({
|
|
42
|
+
branch: tree.branch,
|
|
43
|
+
name: basename(tree.path),
|
|
44
|
+
path: tree.path,
|
|
45
|
+
})),
|
|
41
46
|
};
|
|
42
47
|
}
|
|
43
48
|
function readRemoteHost(projectPath) {
|
|
@@ -74,29 +79,6 @@ function scpRemoteHost(remoteUrl) {
|
|
|
74
79
|
const match = /^(?:[^@/:\s]+@)?(\[[^\]]+\]|[^/:\s]+):/u.exec(remoteUrl);
|
|
75
80
|
return match?.[1] ?? null;
|
|
76
81
|
}
|
|
77
|
-
function readWorktrees(projectPath) {
|
|
78
|
-
return runGit(projectPath, "worktree", "list", "--porcelain", "-z")
|
|
79
|
-
.split("\0\0")
|
|
80
|
-
.filter((record) => record.length > 0)
|
|
81
|
-
.map(parseWorktree);
|
|
82
|
-
}
|
|
83
|
-
function parseWorktree(record) {
|
|
84
|
-
const fields = record.split("\0");
|
|
85
|
-
const pathField = fields.find((field) => field.startsWith("worktree "));
|
|
86
|
-
if (pathField === undefined)
|
|
87
|
-
throw new Error("Git returned a worktree record without a path");
|
|
88
|
-
const path = realpathSync(pathField.slice("worktree ".length));
|
|
89
|
-
const branchField = fields.find((field) => field.startsWith("branch "));
|
|
90
|
-
return {
|
|
91
|
-
branch: branchField === undefined ? null : shortBranch(branchField.slice("branch ".length)),
|
|
92
|
-
name: basename(path),
|
|
93
|
-
path,
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
function shortBranch(branch) {
|
|
97
|
-
const prefix = "refs/heads/";
|
|
98
|
-
return branch.startsWith(prefix) ? branch.slice(prefix.length) : branch;
|
|
99
|
-
}
|
|
100
82
|
function runGit(projectPath, ...args) {
|
|
101
83
|
try {
|
|
102
84
|
return execFileSync("git", ["-C", projectPath, ...args], {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Repository, type Worktree } from "./git.js";
|
|
2
|
+
import type { WorktreeContext } from "./worktree-cli.js";
|
|
3
|
+
export interface AddOptions {
|
|
4
|
+
path: string;
|
|
5
|
+
branch: string;
|
|
6
|
+
newBranch: boolean;
|
|
7
|
+
start?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface AddReport {
|
|
10
|
+
mainWorktree: string;
|
|
11
|
+
worktree: Worktree;
|
|
12
|
+
directories: Record<".local" | ".plans", DirectoryReport>;
|
|
13
|
+
warnings: string[];
|
|
14
|
+
}
|
|
15
|
+
export interface DirectoryReport {
|
|
16
|
+
path: string;
|
|
17
|
+
mode: "symlink" | "tracked" | "companion" | "absent";
|
|
18
|
+
target: string | null;
|
|
19
|
+
}
|
|
20
|
+
export declare function addWorktree(ctx: WorktreeContext, repo: Repository, options: AddOptions): AddReport;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, readFileSync, realpathSync, statSync, symlinkSync, } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { errorMessage } from "../errors.js";
|
|
4
|
+
import { readReport, validateEffectivePlans } from "../project/plans.js";
|
|
5
|
+
import { canonicalPath, git, isInside, isProjectTrackedDirectory, pathExists, readRepository, } from "./git.js";
|
|
6
|
+
export function addWorktree(ctx, repo, options) {
|
|
7
|
+
const prepared = prepareAdd(ctx, repo, options);
|
|
8
|
+
createGitWorktree(ctx, options, prepared);
|
|
9
|
+
return finishSetup(ctx, repo, options, prepared);
|
|
10
|
+
}
|
|
11
|
+
function prepareAdd(ctx, repo, options) {
|
|
12
|
+
const destination = validateDestination(ctx, repo, options.path);
|
|
13
|
+
const branch = prepareBranch(ctx, repo, options);
|
|
14
|
+
const sourceCtx = { ...ctx, cwd: repo.mainWorktree };
|
|
15
|
+
const sourceReport = readReport(sourceCtx);
|
|
16
|
+
const plansTarget = validateEffectivePlans(sourceCtx);
|
|
17
|
+
const warnings = [];
|
|
18
|
+
const directories = planDirectories(sourceCtx, repo, destination, branch.commit, sourceReport, plansTarget, warnings);
|
|
19
|
+
return { destination, branch, directories, warnings };
|
|
20
|
+
}
|
|
21
|
+
function validateDestination(ctx, repo, input) {
|
|
22
|
+
const literal = resolve(ctx.cwd, input);
|
|
23
|
+
if (pathExists(literal))
|
|
24
|
+
throw new Error(`Destination already exists: ${literal}`);
|
|
25
|
+
const destination = canonicalPath(literal);
|
|
26
|
+
let ancestor = dirname(destination);
|
|
27
|
+
while (!pathExists(ancestor))
|
|
28
|
+
ancestor = dirname(ancestor);
|
|
29
|
+
if (!statSync(ancestor).isDirectory())
|
|
30
|
+
throw new Error(`Destination parent is not a directory: ${ancestor}`);
|
|
31
|
+
for (const tree of repo.worktrees) {
|
|
32
|
+
if (isInside(tree.path, destination) || isInside(destination, tree.path)) {
|
|
33
|
+
throw new Error(`Destination overlaps registered worktree ${tree.path}. Choose a new sibling directory.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return destination;
|
|
37
|
+
}
|
|
38
|
+
function prepareBranch(ctx, repo, options) {
|
|
39
|
+
git(ctx, "check-ref-format", `refs/heads/${options.branch}`);
|
|
40
|
+
if (options.branch.startsWith("-") || options.branch === "HEAD")
|
|
41
|
+
throw new Error("Invalid branch name.");
|
|
42
|
+
const occupied = repo.worktrees.find((tree) => tree.branch === options.branch);
|
|
43
|
+
if (occupied !== undefined)
|
|
44
|
+
throw new Error(`Branch ${options.branch} is already checked out at ${occupied.path}; reuse that worktree.`);
|
|
45
|
+
const localRef = `refs/heads/${options.branch}`;
|
|
46
|
+
const locals = git(ctx, "for-each-ref", "--format=%(refname)", "refs/heads").trim().split("\n");
|
|
47
|
+
const exists = locals.includes(localRef);
|
|
48
|
+
if (options.newBranch && exists)
|
|
49
|
+
throw new Error(`Branch already exists: ${options.branch}`);
|
|
50
|
+
let start = options.start ?? "HEAD";
|
|
51
|
+
let create = options.newBranch;
|
|
52
|
+
let track = false;
|
|
53
|
+
if (!options.newBranch) {
|
|
54
|
+
if (exists)
|
|
55
|
+
start = localRef;
|
|
56
|
+
else {
|
|
57
|
+
const remotes = git(ctx, "for-each-ref", "--format=%(refname)", "refs/remotes")
|
|
58
|
+
.trim()
|
|
59
|
+
.split("\n")
|
|
60
|
+
.filter((ref) => ref.slice("refs/remotes/".length).split("/").slice(1).join("/") === options.branch);
|
|
61
|
+
if (remotes.length !== 1 || remotes[0] === undefined) {
|
|
62
|
+
throw new Error(remotes.length === 0
|
|
63
|
+
? `No local or fetched remote branch: ${options.branch}`
|
|
64
|
+
: `Ambiguous remote branch ${options.branch}: ${remotes.join(", ")}. Choose explicitly with -b <branch> <remote/ref>.`);
|
|
65
|
+
}
|
|
66
|
+
start = remotes[0];
|
|
67
|
+
create = true;
|
|
68
|
+
track = true;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const commit = git(ctx, "rev-parse", "--verify", "--end-of-options", `${start}^{commit}`).trim();
|
|
72
|
+
return { create, start: !create ? options.branch : start, commit, track };
|
|
73
|
+
}
|
|
74
|
+
function planDirectories(ctx, repo, destination, commit, report, plansTarget, warnings) {
|
|
75
|
+
const local = planLocal(ctx, repo, destination, commit, warnings);
|
|
76
|
+
const plans = report.locations[".plans"];
|
|
77
|
+
if (plans.in === "companion") {
|
|
78
|
+
return { ".local": local, ".plans": { path: plans.path, mode: "companion", target: null } };
|
|
79
|
+
}
|
|
80
|
+
if (targetTracks(ctx, commit, ".plans")) {
|
|
81
|
+
throw new Error(`Target commit tracks .plans. See \`${ctx.forms.aligndev} guide work-files-setup\` for authorized preparation.`);
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
".local": local,
|
|
85
|
+
".plans": { path: join(destination, ".plans"), mode: "symlink", target: plansTarget },
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function planLocal(ctx, repo, destination, commit, warnings) {
|
|
89
|
+
const path = join(destination, ".local");
|
|
90
|
+
if (targetTracks(ctx, commit, ".local")) {
|
|
91
|
+
warnings.push("Target branch tracks .local; it remains branch-local and is not shared.");
|
|
92
|
+
return { path, mode: "tracked", target: null };
|
|
93
|
+
}
|
|
94
|
+
const source = join(repo.mainWorktree, ".local");
|
|
95
|
+
if (!pathExists(source))
|
|
96
|
+
return { path, mode: "absent", target: null };
|
|
97
|
+
if (!statSync(source).isDirectory())
|
|
98
|
+
throw new Error(`Source is not a usable directory: ${source}`);
|
|
99
|
+
const target = realpathSync(source);
|
|
100
|
+
if (isProjectTrackedDirectory(ctx, source, repo.commonDir)) {
|
|
101
|
+
warnings.push("Main-worktree .local belongs to tracked content on another branch; leaving .local absent.");
|
|
102
|
+
return { path, mode: "absent", target: null };
|
|
103
|
+
}
|
|
104
|
+
return { path, mode: "symlink", target };
|
|
105
|
+
}
|
|
106
|
+
function targetTracks(ctx, commit, path) {
|
|
107
|
+
return (git(ctx, "--literal-pathspecs", "ls-tree", "-r", "--name-only", "-z", commit, "--", path)
|
|
108
|
+
.length > 0);
|
|
109
|
+
}
|
|
110
|
+
function createGitWorktree(ctx, options, prepared) {
|
|
111
|
+
const { branch, destination } = prepared;
|
|
112
|
+
const createArgs = branch.create
|
|
113
|
+
? ["-b", options.branch, ...(branch.track ? ["--track"] : [])]
|
|
114
|
+
: [];
|
|
115
|
+
try {
|
|
116
|
+
git(ctx, "worktree", "add", ...createArgs, "--", destination, branch.start);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
throw new Error(`Git worktree creation failed: ${errorMessage(error)}\nInspect ${destination} and branch ${options.branch} for partial effects before retrying. No rollback was attempted.`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function finishSetup(ctx, repo, options, prepared) {
|
|
123
|
+
const { destination, directories, warnings } = prepared;
|
|
124
|
+
let step = "directory links and local Git exclusions";
|
|
125
|
+
try {
|
|
126
|
+
const targetCtx = { ...ctx, cwd: destination };
|
|
127
|
+
createLinks(targetCtx, repo, directories);
|
|
128
|
+
step = "effective work-files verification";
|
|
129
|
+
validateEffectivePlans(targetCtx);
|
|
130
|
+
const worktree = readRepository(targetCtx).worktrees.find((tree) => tree.path === destination);
|
|
131
|
+
if (worktree === undefined || worktree.branch !== options.branch) {
|
|
132
|
+
throw new Error("Created worktree does not have the requested branch in Git's registry.");
|
|
133
|
+
}
|
|
134
|
+
return { mainWorktree: repo.mainWorktree, worktree, directories, warnings };
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
throw new Error(`Worktree setup failed during ${step}: ${errorMessage(error)}\n` +
|
|
138
|
+
`Retained worktree ${destination} and branch ${options.branch}. Inspect and repair the failed step manually, ` +
|
|
139
|
+
`or remove it with \`${ctx.forms.aligndev} worktree remove ${quotePath(destination)}\` after preserving any work. No rollback was attempted.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function quotePath(path) {
|
|
143
|
+
return `'${path.replaceAll("'", "'\\''")}'`;
|
|
144
|
+
}
|
|
145
|
+
function createLinks(ctx, repo, directories) {
|
|
146
|
+
const links = Object.entries(directories).filter(([, directory]) => directory.mode === "symlink");
|
|
147
|
+
if (links.length === 0)
|
|
148
|
+
return;
|
|
149
|
+
for (const [name, directory] of links) {
|
|
150
|
+
if (directory.target === null)
|
|
151
|
+
throw new Error("Missing symlink target.");
|
|
152
|
+
symlinkSync(join(repo.mainWorktree, name), directory.path, "dir");
|
|
153
|
+
}
|
|
154
|
+
const exclude = git({ ...ctx, cwd: repo.mainWorktree }, "rev-parse", "--path-format=absolute", "--git-path", "info/exclude").trim();
|
|
155
|
+
let content = pathExists(exclude) ? readFileSync(exclude, "utf8") : "";
|
|
156
|
+
for (const [name] of links) {
|
|
157
|
+
const pattern = `/${name}`;
|
|
158
|
+
if (!content.split(/\r?\n/u).includes(pattern)) {
|
|
159
|
+
mkdirSync(dirname(exclude), { recursive: true });
|
|
160
|
+
const addition = `${content.endsWith("\n") || content === "" ? "" : "\n"}${pattern}\n`;
|
|
161
|
+
appendFileSync(exclude, addition);
|
|
162
|
+
content += addition;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
for (const [name, directory] of links) {
|
|
166
|
+
try {
|
|
167
|
+
git(ctx, "check-ignore", "-q", "--", name);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
throw new Error(`Generated link ${directory.path} is not ignored. Inspect conflicting tracked ignore rules; they were not edited.`);
|
|
171
|
+
}
|
|
172
|
+
if (realpathSync(directory.path) !== directory.target)
|
|
173
|
+
throw new Error(`Link target changed: ${directory.path}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface GitContext {
|
|
2
|
+
cwd: string;
|
|
3
|
+
env: NodeJS.ProcessEnv;
|
|
4
|
+
}
|
|
5
|
+
export interface Repository {
|
|
6
|
+
mainWorktree: string;
|
|
7
|
+
commonDir: string;
|
|
8
|
+
worktrees: Worktree[];
|
|
9
|
+
}
|
|
10
|
+
export interface Worktree {
|
|
11
|
+
path: string;
|
|
12
|
+
branch: string | null;
|
|
13
|
+
main: boolean;
|
|
14
|
+
exists: boolean;
|
|
15
|
+
locked: boolean;
|
|
16
|
+
prunable: boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare function readRepository(ctx: GitContext): Repository;
|
|
19
|
+
export declare function isProjectTrackedDirectory(ctx: GitContext, path: string, identity: string): boolean;
|
|
20
|
+
export declare function readWorktrees(ctx: GitContext, mainWorktree: string): Worktree[];
|
|
21
|
+
export declare function canonicalPath(path: string): string;
|
|
22
|
+
export declare function pathExists(path: string): boolean;
|
|
23
|
+
export declare function isInside(parent: string, path: string): boolean;
|
|
24
|
+
export declare function git(ctx: GitContext, ...args: string[]): string;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, lstatSync, realpathSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { errorMessage, isNodeError } from "../errors.js";
|
|
5
|
+
export function readRepository(ctx) {
|
|
6
|
+
const commonDir = repositoryIdentity(ctx);
|
|
7
|
+
if (git(ctx, "rev-parse", "--is-inside-work-tree").trim() !== "true" ||
|
|
8
|
+
basename(commonDir) !== ".git") {
|
|
9
|
+
throw new Error("A supported non-bare Git worktree with a main .git directory is required.");
|
|
10
|
+
}
|
|
11
|
+
const mainWorktree = realpathSync(dirname(commonDir));
|
|
12
|
+
const worktrees = readWorktrees(ctx, mainWorktree);
|
|
13
|
+
if (!worktrees.some((tree) => tree.main)) {
|
|
14
|
+
throw new Error("Cannot identify the main Git worktree.");
|
|
15
|
+
}
|
|
16
|
+
return { mainWorktree, commonDir, worktrees };
|
|
17
|
+
}
|
|
18
|
+
function repositoryIdentity(ctx) {
|
|
19
|
+
return realpathSync(git(ctx, "rev-parse", "--path-format=absolute", "--git-common-dir").trim());
|
|
20
|
+
}
|
|
21
|
+
export function isProjectTrackedDirectory(ctx, path, identity) {
|
|
22
|
+
const root = realpathSync(git(ctx, "rev-parse", "--show-toplevel").trim());
|
|
23
|
+
const logicalPath = join(realpathSync(dirname(path)), basename(path));
|
|
24
|
+
if (isInside(root, logicalPath) &&
|
|
25
|
+
hasTrackedFiles({ ...ctx, cwd: root }, relative(root, logicalPath)))
|
|
26
|
+
return true;
|
|
27
|
+
const resolved = realpathSync(path);
|
|
28
|
+
const source = { ...ctx, cwd: resolved };
|
|
29
|
+
if (optionalRepositoryIdentity(source) !== identity)
|
|
30
|
+
return false;
|
|
31
|
+
const sourceRoot = git(source, "rev-parse", "--show-toplevel").trim();
|
|
32
|
+
return hasTrackedFiles({ ...ctx, cwd: sourceRoot }, relative(sourceRoot, resolved));
|
|
33
|
+
}
|
|
34
|
+
function hasTrackedFiles(ctx, path) {
|
|
35
|
+
return (git(ctx, "--literal-pathspecs", "ls-files", "-z", "--", path === "" ? "." : path).length > 0);
|
|
36
|
+
}
|
|
37
|
+
function optionalRepositoryIdentity(ctx) {
|
|
38
|
+
try {
|
|
39
|
+
return repositoryIdentity(ctx);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (errorMessage(error).includes("not a git repository") ||
|
|
43
|
+
(isNodeError(error) && error.code === "ENOENT"))
|
|
44
|
+
return;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function readWorktrees(ctx, mainWorktree) {
|
|
49
|
+
return git(ctx, "worktree", "list", "--porcelain", "-z")
|
|
50
|
+
.split("\0\0")
|
|
51
|
+
.filter((record) => record.length > 0)
|
|
52
|
+
.map((record) => parseWorktree(record, mainWorktree));
|
|
53
|
+
}
|
|
54
|
+
function parseWorktree(record, mainWorktree) {
|
|
55
|
+
const fields = record.split("\0");
|
|
56
|
+
const pathField = fields.find((field) => field.startsWith("worktree "));
|
|
57
|
+
if (pathField === undefined)
|
|
58
|
+
throw new Error("Git returned a worktree record without a path.");
|
|
59
|
+
const path = canonicalPath(pathField.slice("worktree ".length));
|
|
60
|
+
const branchField = fields.find((field) => field.startsWith("branch "));
|
|
61
|
+
return {
|
|
62
|
+
path,
|
|
63
|
+
branch: branchField === undefined ? null : branchField.slice("branch refs/heads/".length),
|
|
64
|
+
main: path === mainWorktree,
|
|
65
|
+
exists: existsSync(path),
|
|
66
|
+
locked: fields.some((field) => field === "locked" || field.startsWith("locked ")),
|
|
67
|
+
prunable: fields.some((field) => field === "prunable" || field.startsWith("prunable ")),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export function canonicalPath(path) {
|
|
71
|
+
try {
|
|
72
|
+
return realpathSync(path);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (!isNodeError(error) || (error.code !== "ENOENT" && error.code !== "ENOTDIR"))
|
|
76
|
+
throw error;
|
|
77
|
+
const parent = dirname(path);
|
|
78
|
+
return parent === path ? resolve(path) : resolve(canonicalPath(parent), basename(path));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function pathExists(path) {
|
|
82
|
+
try {
|
|
83
|
+
lstatSync(path);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (isNodeError(error) && error.code === "ENOENT")
|
|
88
|
+
return false;
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function isInside(parent, path) {
|
|
93
|
+
const child = relative(parent, path);
|
|
94
|
+
return child === "" || (!isAbsolute(child) && child !== ".." && !child.startsWith(`..${sep}`));
|
|
95
|
+
}
|
|
96
|
+
export function git(ctx, ...args) {
|
|
97
|
+
return execFileSync("git", args, {
|
|
98
|
+
cwd: ctx.cwd,
|
|
99
|
+
env: ctx.env,
|
|
100
|
+
encoding: "utf8",
|
|
101
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
102
|
+
});
|
|
103
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Repository } from "./git.js";
|
|
2
|
+
import type { WorktreeContext } from "./worktree-cli.js";
|
|
3
|
+
export interface RemoveReport {
|
|
4
|
+
mainWorktree: string;
|
|
5
|
+
path: string;
|
|
6
|
+
removed: true;
|
|
7
|
+
}
|
|
8
|
+
export declare function removeWorktree(ctx: WorktreeContext, repo: Repository, input: string): RemoveReport;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { isNodeError } from "../errors.js";
|
|
4
|
+
import { readProjectReport } from "../project/layout.js";
|
|
5
|
+
import { canonicalPath, git, isInside, pathExists } from "./git.js";
|
|
6
|
+
export function removeWorktree(ctx, repo, input) {
|
|
7
|
+
const path = canonicalPath(resolve(ctx.cwd, input));
|
|
8
|
+
const target = repo.worktrees.find((tree) => tree.path === path);
|
|
9
|
+
if (target === undefined)
|
|
10
|
+
throw new Error(`Not an exact registered worktree root of this repository: ${path}`);
|
|
11
|
+
if (target.main)
|
|
12
|
+
throw new Error(`Cannot remove the main worktree: ${path}`);
|
|
13
|
+
if (target.locked)
|
|
14
|
+
throw new Error(`Cannot remove locked worktree: ${path}`);
|
|
15
|
+
if (!target.exists)
|
|
16
|
+
throw new Error(`Worktree is missing: ${path}. Inspect Git's registration manually.`);
|
|
17
|
+
const nested = repo.worktrees.find((tree) => tree.path !== path && isInside(path, tree.path));
|
|
18
|
+
if (nested !== undefined)
|
|
19
|
+
throw new Error(`Cannot remove ${path}: it contains another registered worktree root: ${nested.path}.`);
|
|
20
|
+
if (git({ ...ctx, cwd: path }, "status", "--porcelain", "-z", "--untracked-files=all").length > 0) {
|
|
21
|
+
throw new Error(`Cannot remove dirty worktree: ${path}. Preserve staged, modified and untracked files first.`);
|
|
22
|
+
}
|
|
23
|
+
protectSharedDirectories(ctx, repo, path);
|
|
24
|
+
git({ ...ctx, cwd: repo.mainWorktree }, "worktree", "remove", "--", path);
|
|
25
|
+
return { mainWorktree: repo.mainWorktree, path, removed: true };
|
|
26
|
+
}
|
|
27
|
+
function protectSharedDirectories(ctx, repo, target) {
|
|
28
|
+
for (const tree of repo.worktrees.filter((candidate) => candidate.exists)) {
|
|
29
|
+
const report = readProjectReport(ctx.alignfirstCommand, tree.path, ctx.env);
|
|
30
|
+
if ("error" in report)
|
|
31
|
+
throw new Error(`Cannot read shared-directory protection report for ${tree.path}: ${report.error}`);
|
|
32
|
+
const protectedPaths = [];
|
|
33
|
+
if (report.companion !== null)
|
|
34
|
+
protectedPaths.push(canonicalPath(report.companion.dir));
|
|
35
|
+
for (const name of [".plans", "_aligndev"]) {
|
|
36
|
+
const location = report.locations[name];
|
|
37
|
+
if (location.exists)
|
|
38
|
+
protectExistingTarget(protectedPaths, location.path);
|
|
39
|
+
}
|
|
40
|
+
if (tree.path !== target) {
|
|
41
|
+
for (const name of [".local", ".plans"]) {
|
|
42
|
+
const source = join(tree.path, name);
|
|
43
|
+
if (pathExists(source))
|
|
44
|
+
protectExistingTarget(protectedPaths, source);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
for (const path of protectedPaths) {
|
|
48
|
+
if (isInside(target, path)) {
|
|
49
|
+
throw new Error(`Cannot remove ${target}: it contains protected shared directory ${path} referenced by ${tree.path}.`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function protectExistingTarget(paths, path) {
|
|
55
|
+
try {
|
|
56
|
+
paths.push(realpathSync(path));
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (!isNodeError(error) || (error.code !== "ENOENT" && error.code !== "ENOTDIR"))
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CommandForms } from "../command-form.js";
|
|
2
|
+
import type { Output } from "../output.js";
|
|
3
|
+
import { type GitContext } from "./git.js";
|
|
4
|
+
export interface WorktreeContext extends GitContext {
|
|
5
|
+
stdout: Output;
|
|
6
|
+
stderr: Output;
|
|
7
|
+
forms: CommandForms;
|
|
8
|
+
alignfirstCommand: string[];
|
|
9
|
+
}
|
|
10
|
+
export declare function runWorktree(tokens: string[], ctx: WorktreeContext): number;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { addWorktree } from "./add.js";
|
|
3
|
+
import { readRepository } from "./git.js";
|
|
4
|
+
import { removeWorktree } from "./remove.js";
|
|
5
|
+
export function runWorktree(tokens, ctx) {
|
|
6
|
+
const command = parseWorktreeArgs(tokens, ctx.forms.aligndev);
|
|
7
|
+
if (command.kind === "help") {
|
|
8
|
+
ctx.stdout.write(renderHelp(ctx.forms.aligndev));
|
|
9
|
+
return 0;
|
|
10
|
+
}
|
|
11
|
+
const repo = readRepository(ctx);
|
|
12
|
+
if (command.kind === "list") {
|
|
13
|
+
const report = { mainWorktree: repo.mainWorktree, worktrees: repo.worktrees };
|
|
14
|
+
ctx.stdout.write(command.json ? json(report) : renderList(repo.worktrees));
|
|
15
|
+
return 0;
|
|
16
|
+
}
|
|
17
|
+
if (command.kind === "remove") {
|
|
18
|
+
const report = removeWorktree(ctx, repo, command.path);
|
|
19
|
+
ctx.stdout.write(command.json ? json(report) : `Removed ${report.path}; branch preserved.\n`);
|
|
20
|
+
return 0;
|
|
21
|
+
}
|
|
22
|
+
const report = addWorktree(ctx, repo, command.options);
|
|
23
|
+
for (const warning of report.warnings)
|
|
24
|
+
ctx.stderr.write(`Warning: ${warning}\n`);
|
|
25
|
+
ctx.stdout.write(command.json ? json(report) : renderAdd(report));
|
|
26
|
+
return 0;
|
|
27
|
+
}
|
|
28
|
+
function parseWorktreeArgs(tokens, aligndev) {
|
|
29
|
+
const [command, ...rest] = tokens;
|
|
30
|
+
if (command === undefined || command === "--help" || command === "-h") {
|
|
31
|
+
if (tokens.length > 1)
|
|
32
|
+
throw new Error("Unexpected worktree help arguments.");
|
|
33
|
+
return { kind: "help" };
|
|
34
|
+
}
|
|
35
|
+
if (command !== "add" && command !== "list" && command !== "remove") {
|
|
36
|
+
throw new Error(`Unknown worktree command: ${command}`);
|
|
37
|
+
}
|
|
38
|
+
const { values, positionals } = parseArgs({
|
|
39
|
+
args: rest,
|
|
40
|
+
strict: true,
|
|
41
|
+
allowPositionals: true,
|
|
42
|
+
options: {
|
|
43
|
+
json: { type: "boolean", default: false },
|
|
44
|
+
help: { type: "boolean", short: "h", default: false },
|
|
45
|
+
...(command === "add" ? { b: { type: "string" } } : {}),
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
if (values.help)
|
|
49
|
+
return { kind: "help" };
|
|
50
|
+
const newBranch = typeof values.b === "string" ? values.b : undefined;
|
|
51
|
+
const count = positionals.length;
|
|
52
|
+
const expected = command === "list" ? 0 : command === "remove" ? 1 : 2;
|
|
53
|
+
const validCount = command === "add" && newBranch !== undefined ? count === 1 || count === 2 : count === expected;
|
|
54
|
+
if (!validCount) {
|
|
55
|
+
throw new Error(`Invalid arguments. Run \`${aligndev} worktree ${command} --help\`.`);
|
|
56
|
+
}
|
|
57
|
+
if (command === "list")
|
|
58
|
+
return { kind: "list", json: values.json };
|
|
59
|
+
const path = positionals[0];
|
|
60
|
+
if (path === undefined)
|
|
61
|
+
throw new Error("A worktree path is required.");
|
|
62
|
+
if (command === "remove")
|
|
63
|
+
return { kind: "remove", path, json: values.json };
|
|
64
|
+
const branch = newBranch ?? positionals[1];
|
|
65
|
+
if (branch === undefined)
|
|
66
|
+
throw new Error("A branch is required.");
|
|
67
|
+
return {
|
|
68
|
+
kind: "add",
|
|
69
|
+
json: values.json,
|
|
70
|
+
options: {
|
|
71
|
+
path,
|
|
72
|
+
branch,
|
|
73
|
+
newBranch: newBranch !== undefined,
|
|
74
|
+
start: newBranch === undefined ? undefined : positionals[1],
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function json(report) {
|
|
79
|
+
return `${JSON.stringify(report, undefined, 2)}\n`;
|
|
80
|
+
}
|
|
81
|
+
function renderList(worktrees) {
|
|
82
|
+
return worktrees
|
|
83
|
+
.map((tree) => `${tree.path} [${tree.branch ?? "detached"}]${tree.main ? " main" : ""}${tree.exists ? "" : " missing"}${tree.locked ? " locked" : ""}${tree.prunable ? " prunable" : ""}\n`)
|
|
84
|
+
.join("");
|
|
85
|
+
}
|
|
86
|
+
function renderAdd(report) {
|
|
87
|
+
return [
|
|
88
|
+
`Worktree ready: ${report.worktree.path} [${report.worktree.branch}]`,
|
|
89
|
+
...Object.entries(report.directories).map(([name, directory]) => `${name}: ${directory.mode} ${directory.path}${directory.target === null ? "" : ` -> ${directory.target}`}`),
|
|
90
|
+
"Readiness covers Git and work files only; follow the project's install/build/test procedure.",
|
|
91
|
+
"",
|
|
92
|
+
].join("\n");
|
|
93
|
+
}
|
|
94
|
+
function renderHelp(command) {
|
|
95
|
+
return `Usage:
|
|
96
|
+
${command} worktree add <path> <branch> [--json]
|
|
97
|
+
${command} worktree add <path> -b <branch> [<start-point>] [--json]
|
|
98
|
+
${command} worktree list [--json]
|
|
99
|
+
${command} worktree remove <path> [--json]
|
|
100
|
+
${command} worktree <command> --help
|
|
101
|
+
|
|
102
|
+
Paths resolve from the caller, including linked worktrees and subdirectories.
|
|
103
|
+
Existing branches are reused; an unambiguous fetched remote branch may create its tracking branch.
|
|
104
|
+
-b creates a new branch from <start-point>, or the invoking worktree's HEAD. No fetch or base refresh.
|
|
105
|
+
The destination must be new and outside all registered worktrees. Occupied branches must be reused
|
|
106
|
+
at their listed path. Bare and nonstandard Git layouts are unsupported.
|
|
107
|
+
|
|
108
|
+
Add shares usable untracked main-worktree .plans and optional .local through symlinks, with local
|
|
109
|
+
Git exclusions. Companion plans are used directly. Tracked .local stays branch-local with a warning.
|
|
110
|
+
Missing or project-tracked effective plans require separately authorized preparation:
|
|
111
|
+
${command} guide work-files-setup
|
|
112
|
+
Add never registers a companion, migrates files, installs, builds or starts application processes.
|
|
113
|
+
Late setup failures retain the worktree and branch and report manual recovery.
|
|
114
|
+
|
|
115
|
+
List reads only Git's registry, including detached, missing, locked and prunable worktrees.
|
|
116
|
+
Remove accepts an exact linked root, refuses main/locked/dirty/protected shared targets, and uses
|
|
117
|
+
ordinary Git removal. It preserves branches, shared targets and companion registration; no force,
|
|
118
|
+
pruning, process teardown or recursive fallback. Stop project activity separately before removal.
|
|
119
|
+
|
|
120
|
+
--json prints one document on success; warnings and errors go to stderr. Failures exit 1.
|
|
121
|
+
`;
|
|
122
|
+
}
|