@bakers-build/addon-workspace-git 0.6.1-next.6 → 0.6.1-next.7

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.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Recursively re-add the owner-write bit to a directory tree.
3
+ *
4
+ * A bakers.build worktree is a Drupal install, and Drupal hardens `web/sites/default`
5
+ * to `0555` and `settings.php` / `files/.htaccess` to `0444`. A directory
6
+ * without its write bit cannot have its entries unlinked, so removing the
7
+ * worktree (`git worktree remove --force` / `rm -rf`, however a tool does it)
8
+ * gets EACCES. Restoring `u+w` on every dir/file first is what makes removal
9
+ * succeed — this is not an ownership problem, only the permission bits.
10
+ *
11
+ * Best-effort per entry: a single un-chmod-able entry (already gone, foreign
12
+ * owner) must not abort the walk. Symlinks are never followed — chmod would
13
+ * touch the link target, which may live outside the tree.
14
+ */
15
+ export declare function restoreWritable(path: string): void;
package/dist/src/fs.js ADDED
@@ -0,0 +1,48 @@
1
+ import { chmodSync, lstatSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * Recursively re-add the owner-write bit to a directory tree.
5
+ *
6
+ * A bakers.build worktree is a Drupal install, and Drupal hardens `web/sites/default`
7
+ * to `0555` and `settings.php` / `files/.htaccess` to `0444`. A directory
8
+ * without its write bit cannot have its entries unlinked, so removing the
9
+ * worktree (`git worktree remove --force` / `rm -rf`, however a tool does it)
10
+ * gets EACCES. Restoring `u+w` on every dir/file first is what makes removal
11
+ * succeed — this is not an ownership problem, only the permission bits.
12
+ *
13
+ * Best-effort per entry: a single un-chmod-able entry (already gone, foreign
14
+ * owner) must not abort the walk. Symlinks are never followed — chmod would
15
+ * touch the link target, which may live outside the tree.
16
+ */
17
+ export function restoreWritable(path) {
18
+ let stat;
19
+ try {
20
+ stat = lstatSync(path);
21
+ }
22
+ catch {
23
+ return; // gone / inaccessible — nothing to restore
24
+ }
25
+ if (stat.isSymbolicLink()) {
26
+ return; // don't follow: the target lives elsewhere
27
+ }
28
+ try {
29
+ // Add owner-write, preserving every other bit (read/execute stay intact so
30
+ // a directory remains traversable and readable for the recursion below).
31
+ chmodSync(path, stat.mode | 0o200);
32
+ }
33
+ catch {
34
+ // best-effort: one un-chmod-able entry must not abort the walk
35
+ }
36
+ if (stat.isDirectory()) {
37
+ let entries;
38
+ try {
39
+ entries = readdirSync(path);
40
+ }
41
+ catch {
42
+ return;
43
+ }
44
+ for (const entry of entries) {
45
+ restoreWritable(join(path, entry));
46
+ }
47
+ }
48
+ }
@@ -1,10 +1,13 @@
1
- import type { BbWorkspace, EnsuredWorkspace, WorkspacePlugin } from '@bakers-build/conductor/contract';
1
+ import type { BbWorkspace, EnsuredWorkspace, WorkspacePlugin, WorktreeTeardown } from '@bakers-build/conductor/contract';
2
2
  import { type ConductorLogger } from '@bakers-build/core';
3
+ export { restoreWritable } from './fs.js';
3
4
  export { pushCurrentEnv, runBranchGit, setNoAutoSetupMerge, } from './git-config.js';
4
5
  export { loadInstructions } from './instructions.js';
6
+ export { removeGitWorktree, type WorktreeGitExec, } from './remove-git-worktree.js';
5
7
  /** Default branch template: `<prefix><key>-<title-slug>` (readable). */
6
8
  export declare const DEFAULT_BRANCH_TEMPLATE = "{branchPrefix}{key}-{titleSlug}";
7
- export type GitRunner = (args: string[], cwd: string) => Promise<void>;
9
+ /** Runs `git <args>` in a cwd; resolves with stdout when it has one. */
10
+ export type GitRunner = (args: string[], cwd: string) => Promise<string | undefined>;
8
11
  export interface GitWorkspaceOptions {
9
12
  /** Main clone (a git repo): config source + worktree base. */
10
13
  root: string;
@@ -40,7 +43,8 @@ export declare class GitWorkspace implements BbWorkspace {
40
43
  keyFor(identifier: string): string;
41
44
  private pathFor;
42
45
  ensure(identifier: string, title?: string, _baseRef?: string): Promise<EnsuredWorkspace>;
43
- remove(identifier: string): Promise<void>;
46
+ /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
47
+ remove(branch: string, worktreePath?: string): Promise<WorktreeTeardown>;
44
48
  }
45
49
  export declare function gitWorkspace(opts?: Pick<GitWorkspaceOptions, 'branchPrefix' | 'branchTemplate' | 'autoSetupMerge'>): WorkspacePlugin;
46
50
  export default gitWorkspace;
package/dist/src/index.js CHANGED
@@ -8,8 +8,11 @@ import { join, resolve } from 'node:path';
8
8
  import { deriveCheckoutRoot, exec, slugify, } from '@bakers-build/core';
9
9
  import { runBranchGit } from './git-config.js';
10
10
  import { loadInstructions } from './instructions.js';
11
+ import { removeGitWorktree } from './remove-git-worktree.js';
12
+ export { restoreWritable } from './fs.js';
11
13
  export { pushCurrentEnv, runBranchGit, setNoAutoSetupMerge, } from './git-config.js';
12
14
  export { loadInstructions } from './instructions.js';
15
+ export { removeGitWorktree, } from './remove-git-worktree.js';
13
16
  /** Default branch template: `<prefix><key>-<title-slug>` (readable). */
14
17
  export const DEFAULT_BRANCH_TEMPLATE = '{branchPrefix}{key}-{titleSlug}';
15
18
  function renderBranchTemplate(template, vars) {
@@ -21,8 +24,12 @@ function renderBranchTemplate(template, vars) {
21
24
  // trim trailing branch separators so the branch stays a valid, tidy ref.
22
25
  return rendered.replace(/[-_./]+$/g, '');
23
26
  }
24
- const defaultGitRunner = async (args, cwd) => {
25
- await exec('git', args, { cwd });
27
+ const defaultGitRunner = (args, cwd) => exec('git', args, { cwd });
28
+ const noopLogger = {
29
+ debug() { },
30
+ info() { },
31
+ warn() { },
32
+ error() { },
26
33
  };
27
34
  export class GitWorkspace {
28
35
  runGit;
@@ -80,7 +87,7 @@ export class GitWorkspace {
80
87
  }
81
88
  const branch = this.branchFor(identifier, title);
82
89
  await this.runGit(['-C', this.root, 'worktree', 'add', '--force', '-B', branch, path], this.root);
83
- // The `after_create` hook is run by the executor (BB-84), not here — the
90
+ // The `after_create` hook is run by the conductor, not here — the
84
91
  // workspace only reports that it created a fresh worktree.
85
92
  return {
86
93
  path,
@@ -89,10 +96,9 @@ export class GitWorkspace {
89
96
  ...extra,
90
97
  };
91
98
  }
92
- async remove(identifier) {
93
- const key = this.keyFor(identifier);
94
- const path = this.pathFor(key);
95
- await this.runGit(['-C', this.root, 'worktree', 'remove', '--force', path], this.root);
99
+ /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
100
+ remove(branch, worktreePath) {
101
+ return removeGitWorktree(this.root, branch, worktreePath, async (args, cwd) => (await this.runGit(['-C', cwd, ...args], cwd)) ?? '', this.logger ?? noopLogger);
96
102
  }
97
103
  }
98
104
  export function gitWorkspace(opts = {}) {
@@ -0,0 +1,25 @@
1
+ import type { WorktreeTeardown } from '@bakers-build/conductor/contract';
2
+ import type { ConductorLogger } from '@bakers-build/core';
3
+ /** Runs `git <args>` in `cwd`; resolves with stdout, rejects on non-zero exit. */
4
+ export type WorktreeGitExec = (args: string[], cwd: string) => Promise<string>;
5
+ /**
6
+ * Tear down one ticket worktree with git alone — the shared teardown of every
7
+ * workspace, and the fallback of a tool workspace whose tool lost track of it.
8
+ *
9
+ * It ASKS before acting (BB-293): git's registration and the directory on disk
10
+ * can come apart, so both are read and each case is handled explicitly:
11
+ * - the main checkout → refused, `unverified`;
12
+ * - nothing resolves a path → `unverified` (absence can only be claimed about
13
+ * a worktree that was actually located — BB-141 RC-2);
14
+ * - neither registered nor on disk → `already_absent`;
15
+ * - registered but gone from disk → `git worktree prune` sweeps the admin
16
+ * entry → `removed`;
17
+ * - on disk → restore Drupal's write bits, `git worktree remove --force`
18
+ * (only when registered, else git exits 128 on a handled condition),
19
+ * `rm -rf`, `prune` → `removed`, or `unverified` when the directory cannot
20
+ * be reclaimed (a foreign-owned leftover) — reported, never thrown.
21
+ *
22
+ * `worktreePath` is the stable key and wins over the mutable `branch`. git runs
23
+ * at `root` when given, else inside the worktree itself (the list is the same).
24
+ */
25
+ export declare function removeGitWorktree(root: string | undefined, branch: string, worktreePath: string | undefined, execGit: WorktreeGitExec, logger: ConductorLogger): Promise<WorktreeTeardown>;
@@ -0,0 +1,110 @@
1
+ import { existsSync, rmSync } from 'node:fs';
2
+ import { restoreWritable } from './fs.js';
3
+ function normPath(path) {
4
+ return path.replace(/\/+$/, '');
5
+ }
6
+ /**
7
+ * The ticket worktrees of `git worktree list --porcelain` (record 0, the main
8
+ * checkout, and `root` are never one). A `prunable` entry still carries its
9
+ * `worktree <path>` line, so it parses too.
10
+ */
11
+ function ticketWorktrees(output, root) {
12
+ const entries = [];
13
+ for (const record of output.split(/\n\s*\n/)) {
14
+ const path = record.match(/^worktree (.+)$/m)?.[1]?.trim();
15
+ if (!path)
16
+ continue;
17
+ const branch = record
18
+ .match(/^branch (.+)$/m)?.[1]
19
+ ?.trim()
20
+ .replace(/^refs\/heads\//, '') ?? null;
21
+ entries.push({ path, branch });
22
+ }
23
+ return entries
24
+ .slice(1)
25
+ .filter((e) => !root || normPath(e.path) !== normPath(root));
26
+ }
27
+ /**
28
+ * Tear down one ticket worktree with git alone — the shared teardown of every
29
+ * workspace, and the fallback of a tool workspace whose tool lost track of it.
30
+ *
31
+ * It ASKS before acting (BB-293): git's registration and the directory on disk
32
+ * can come apart, so both are read and each case is handled explicitly:
33
+ * - the main checkout → refused, `unverified`;
34
+ * - nothing resolves a path → `unverified` (absence can only be claimed about
35
+ * a worktree that was actually located — BB-141 RC-2);
36
+ * - neither registered nor on disk → `already_absent`;
37
+ * - registered but gone from disk → `git worktree prune` sweeps the admin
38
+ * entry → `removed`;
39
+ * - on disk → restore Drupal's write bits, `git worktree remove --force`
40
+ * (only when registered, else git exits 128 on a handled condition),
41
+ * `rm -rf`, `prune` → `removed`, or `unverified` when the directory cannot
42
+ * be reclaimed (a foreign-owned leftover) — reported, never thrown.
43
+ *
44
+ * `worktreePath` is the stable key and wins over the mutable `branch`. git runs
45
+ * at `root` when given, else inside the worktree itself (the list is the same).
46
+ */
47
+ export async function removeGitWorktree(root, branch, worktreePath, execGit, logger) {
48
+ if (root && worktreePath && normPath(worktreePath) === normPath(root)) {
49
+ logger.warn({ branch, worktreePath, root }, 'refusing to tear down the main checkout');
50
+ return 'unverified';
51
+ }
52
+ const prune = async (cwd) => {
53
+ try {
54
+ await execGit(['worktree', 'prune'], cwd);
55
+ }
56
+ catch {
57
+ // best-effort — pruning is a sweep, never the teardown's success gate
58
+ }
59
+ };
60
+ const cwd = root ?? worktreePath;
61
+ let known = [];
62
+ if (cwd) {
63
+ try {
64
+ known = ticketWorktrees(await execGit(['worktree', 'list', '--porcelain'], cwd), root);
65
+ }
66
+ catch {
67
+ // Degrade to the on-disk answer below.
68
+ }
69
+ }
70
+ const gitPath = worktreePath
71
+ ? known.find((e) => normPath(e.path) === normPath(worktreePath))?.path
72
+ : known.find((e) => e.branch === branch)?.path;
73
+ const path = worktreePath ?? gitPath;
74
+ if (!path) {
75
+ if (root)
76
+ await prune(root);
77
+ return 'unverified';
78
+ }
79
+ const registered = gitPath !== undefined;
80
+ const gitCwd = root ?? path;
81
+ if (!existsSync(path)) {
82
+ if (!registered) {
83
+ logger.info({ branch, worktreePath: path }, 'worktree already absent — nothing to tear down');
84
+ return 'already_absent';
85
+ }
86
+ await prune(gitCwd);
87
+ return 'removed';
88
+ }
89
+ // Drupal hardens web/sites/default (0555): restore owner-write first.
90
+ restoreWritable(path);
91
+ if (registered) {
92
+ try {
93
+ await execGit(['worktree', 'remove', '--force', path], gitCwd);
94
+ }
95
+ catch (err) {
96
+ logger.warn({ path, err: String(err) }, 'git worktree remove failed on a registered worktree');
97
+ }
98
+ }
99
+ if (existsSync(path)) {
100
+ try {
101
+ rmSync(path, { recursive: true, force: true });
102
+ }
103
+ catch (err) {
104
+ logger.warn({ path, err: String(err) }, 'worktree directory reclaim failed');
105
+ return 'unverified';
106
+ }
107
+ }
108
+ await prune(gitCwd);
109
+ return 'removed';
110
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-workspace-git",
3
- "version": "0.6.1-next.6",
3
+ "version": "0.6.1-next.7",
4
4
  "description": "bakers.build conductor workspace addon: plain git-worktree workspace + the WORKFLOW.md instruction loader.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,11 +20,11 @@
20
20
  "directory": "bakers-cli/addons/workspace-git"
21
21
  },
22
22
  "peerDependencies": {
23
- "@bakers-build/conductor": "^0.6.1-next.6",
24
- "@bakers-build/core": "^0.6.1-next.6"
23
+ "@bakers-build/conductor": "^0.6.1-next.7",
24
+ "@bakers-build/core": "^0.6.1-next.7"
25
25
  },
26
26
  "bakersBuild": {
27
- "commit": "12b97ff4aa2422d69dab286141f3234609f32351",
27
+ "commit": "b89398b187bf51f4f9ca5bfc1150469f73a879e6",
28
28
  "channel": "next"
29
29
  }
30
30
  }