@bakers-build/addon-workspace-git 0.9.1-next.5 → 0.9.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.
@@ -4,22 +4,15 @@ export { restoreWritable } from './fs.js';
4
4
  export { pushCurrentEnv, runBranchGit, setNoAutoSetupMerge, } from './git-config.js';
5
5
  export { loadInstructions } from './instructions.js';
6
6
  export { removeGitWorktree, type WorktreeGitExec, } from './remove-git-worktree.js';
7
- /** Default branch template: `<prefix><key>-<title-slug>` (readable). */
8
- export declare const DEFAULT_BRANCH_TEMPLATE = "{branch_prefix}{key}-{title_slug}";
7
+ export { ensureRunClone, removeRunCloneWorkspace, targetOf, } from './run-clone.js';
8
+ export declare const DEFAULT_WORKTREE_DIR = ".bakers-worktrees";
9
9
  /** Runs `git <args>` in a cwd; resolves with stdout when it has one. */
10
10
  export type GitRunner = (args: string[], cwd: string) => Promise<string | undefined>;
11
11
  export interface GitWorkspaceOptions {
12
12
  /** Main clone (a git repo): config source + worktree base. */
13
13
  root: string;
14
- /** Where per-ticket worktrees live. Default: `${root}-worktrees`. */
15
- worktreesRoot?: string;
16
- /** Branch name prefix per ticket. Default: 'bakers/'. */
17
- branchPrefix?: string;
18
- /**
19
- * Branch name template. Vars: {branch_prefix}, {key} (sanitized identifier),
20
- * {identifier}, {title_slug}. Default: `{branch_prefix}{key}-{title_slug}`.
21
- */
22
- branchTemplate?: string;
14
+ /** Directory of new worktrees, relative to `root` or absolute. Default: {@link DEFAULT_WORKTREE_DIR}. */
15
+ worktreeDir?: string;
23
16
  /**
24
17
  * Default `false`: before creating a worktree, set `branch.autoSetupMerge=false`
25
18
  * in `root`, and give runs `push.default=current`. `true` leaves Git alone.
@@ -28,29 +21,36 @@ export interface GitWorkspaceOptions {
28
21
  /** Receives the warning when `branch.autoSetupMerge` cannot be written. */
29
22
  logger?: ConductorLogger;
30
23
  runGit?: GitRunner;
24
+ /** The runtime isolates: a fresh run clone per ensure instead of a linked worktree. */
25
+ clone?: boolean;
26
+ /** Run clones borrow the root's objects (`git clone --shared`). */
27
+ shared?: boolean;
31
28
  }
32
29
  export declare class GitWorkspace implements BbWorkspace {
33
30
  private readonly runGit;
34
31
  private readonly root;
35
- private readonly worktreesRoot;
36
- private readonly branchPrefix;
37
- private readonly branchTemplate;
32
+ private readonly worktreeDir;
38
33
  private readonly autoSetupMerge;
39
34
  private readonly logger;
35
+ private readonly clone;
36
+ private readonly shared;
40
37
  constructor(options: GitWorkspaceOptions);
41
- /** Render the branch name for a ticket from the configured template. */
42
- branchFor(identifier: string, title?: string): string;
43
- keyFor(identifier: string): string;
44
- private pathFor;
45
- ensure(identifier: string, title?: string, _baseRef?: string): Promise<EnsuredWorkspace>;
38
+ /**
39
+ * Check out the ticket `branch` at `<worktreeDir>/<branch>`. `_identifier`
40
+ * is unused: the conductor passes the ticket's `branch_name`, which push and
41
+ * PR use, so the workspace never renders a branch of its own.
42
+ */
43
+ ensure(_identifier: string, branch?: string, baseRef?: string): Promise<EnsuredWorkspace>;
44
+ /** Create `branch` at the root's HEAD unless it exists; an existing one stays put. */
45
+ private ensureBranch;
46
46
  /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
47
47
  remove(branch: string, worktreePath?: string): Promise<WorktreeTeardown>;
48
48
  }
49
49
  /** The addon entry's `with` value (see options.schema.json). */
50
50
  export interface GitWorkspaceAddonOptions {
51
- branch_prefix?: string;
52
- branch_template?: string;
51
+ worktree_dir?: string;
53
52
  auto_setup_merge?: boolean;
53
+ shared?: boolean;
54
54
  }
55
55
  export declare function gitWorkspace(opts?: GitWorkspaceAddonOptions): WorkspacePlugin;
56
56
  export default gitWorkspace;
package/dist/src/index.js CHANGED
@@ -4,26 +4,19 @@
4
4
  // loader that used to be a core util). `@bakers-build/addon-herdr` depends on this
5
5
  // package for it: the one addon→addon edge the layered acyclic rule permits.
6
6
  import { existsSync } from 'node:fs';
7
- import { join, resolve } from 'node:path';
8
- import { deriveCheckoutRoot, exec, slugify, } from '@bakers-build/core';
7
+ import { resolve } from 'node:path';
8
+ import { deriveCheckoutRoot, exec, } 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';
11
+ import { removeGitWorktree, ticketWorktrees } from './remove-git-worktree.js';
12
+ import { ensureRunClone, removeRunCloneWorkspace, targetOf, } from './run-clone.js';
12
13
  export { restoreWritable } from './fs.js';
13
14
  export { pushCurrentEnv, runBranchGit, setNoAutoSetupMerge, } from './git-config.js';
14
15
  export { loadInstructions } from './instructions.js';
15
16
  export { removeGitWorktree, } from './remove-git-worktree.js';
16
- /** Default branch template: `<prefix><key>-<title-slug>` (readable). */
17
- export const DEFAULT_BRANCH_TEMPLATE = '{branch_prefix}{key}-{title_slug}';
18
- function renderBranchTemplate(template, vars) {
19
- const rendered = template.replace(/\{(\w+)\}/g, (whole, key) => {
20
- const value = vars[key];
21
- return value === undefined ? whole : value;
22
- });
23
- // An empty title slug leaves a dangling separator (e.g. `bakers/GL-9-`) —
24
- // trim trailing branch separators so the branch stays a valid, tidy ref.
25
- return rendered.replace(/[-_./]+$/g, '');
26
- }
17
+ export { ensureRunClone, removeRunCloneWorkspace, targetOf, } from './run-clone.js';
18
+ // shortcut: one default for all executors, upgrade when an executor needs another value.
19
+ export const DEFAULT_WORKTREE_DIR = '.bakers-worktrees';
27
20
  const defaultGitRunner = (args, cwd) => exec('git', args, { cwd });
28
21
  const noopLogger = {
29
22
  debug() { },
@@ -34,59 +27,88 @@ const noopLogger = {
34
27
  export class GitWorkspace {
35
28
  runGit;
36
29
  root;
37
- worktreesRoot;
38
- branchPrefix;
39
- branchTemplate;
30
+ worktreeDir;
40
31
  autoSetupMerge;
41
32
  logger;
33
+ clone;
34
+ shared;
42
35
  constructor(options) {
43
36
  this.runGit = options.runGit ?? defaultGitRunner;
44
37
  this.root = resolve(options.root);
45
- this.worktreesRoot = options.worktreesRoot
46
- ? resolve(options.worktreesRoot)
47
- : `${this.root}-worktrees`;
48
- this.branchPrefix = options.branchPrefix ?? 'bakers/';
49
- this.branchTemplate = options.branchTemplate ?? DEFAULT_BRANCH_TEMPLATE;
38
+ this.worktreeDir = resolve(this.root, options.worktreeDir ?? DEFAULT_WORKTREE_DIR);
50
39
  this.autoSetupMerge = options.autoSetupMerge ?? false;
51
40
  this.logger = options.logger;
41
+ this.clone = options.clone ?? false;
42
+ this.shared = options.shared ?? false;
52
43
  }
53
- /** Render the branch name for a ticket from the configured template. */
54
- branchFor(identifier, title) {
55
- return renderBranchTemplate(this.branchTemplate, {
56
- branch_prefix: this.branchPrefix,
57
- key: this.keyFor(identifier),
58
- identifier,
59
- title_slug: slugify(title ?? ''),
60
- });
61
- }
62
- keyFor(identifier) {
63
- return identifier.replace(/[^A-Za-z0-9._-]/g, '_');
64
- }
65
- pathFor(key) {
66
- return resolve(join(this.worktreesRoot, key));
67
- }
68
- async ensure(identifier, title, _baseRef) {
69
- const key = this.keyFor(identifier);
70
- // Reject empty and dot-leading keys: a dot-leading key would produce an
71
- // invalid git ref (e.g. `bakers/.hidden`) and covers '.'/'..' too.
72
- if (key === '' || key.startsWith('.')) {
73
- throw new Error(`invalid workspace identifier: ${identifier}`);
44
+ /**
45
+ * Check out the ticket `branch` at `<worktreeDir>/<branch>`. `_identifier`
46
+ * is unused: the conductor passes the ticket's `branch_name`, which push and
47
+ * PR use, so the workspace never renders a branch of its own.
48
+ */
49
+ async ensure(_identifier, branch, baseRef) {
50
+ if (!branch)
51
+ throw new Error('git workspace requires a branch name');
52
+ // A ref git accepts has no `..`, leading `/`, `-` or `.`, so the path
53
+ // below cannot leave worktreeDir; `@{-1}` expands, hence the comparison.
54
+ let checked;
55
+ try {
56
+ checked = await this.runGit(['check-ref-format', '--branch', branch], this.root);
74
57
  }
75
- const path = this.pathFor(key);
58
+ catch {
59
+ checked = undefined;
60
+ }
61
+ if (checked?.trim() !== branch) {
62
+ throw new Error(`invalid branch name: ${branch}`);
63
+ }
64
+ const path = resolve(this.worktreeDir, branch);
76
65
  const env = this.autoSetupMerge
77
66
  ? undefined
78
67
  : await runBranchGit(this.root, this.logger);
79
68
  const extra = env ? { env } : {};
80
- if (existsSync(path)) {
69
+ if (this.clone) {
70
+ const created = !existsSync(path);
71
+ await this.ensureBranch(branch);
72
+ const target = targetOf(baseRef);
73
+ if (target && baseRef?.startsWith('origin/')) {
74
+ try {
75
+ await this.runGit(['-C', this.root, 'fetch', '--quiet', 'origin', '--', target], this.root);
76
+ }
77
+ catch {
78
+ // Offline or no remote: the clone carries the target as last fetched.
79
+ }
80
+ }
81
+ const clone = ensureRunClone({
82
+ parent: this.root,
83
+ workspace: path,
84
+ branch,
85
+ ...(target ? { target } : {}),
86
+ shared: this.shared,
87
+ });
81
88
  return {
82
89
  path,
83
90
  instructions: loadInstructions(path),
91
+ created,
92
+ clone,
93
+ ...extra,
94
+ };
95
+ }
96
+ // Reuse the branch's worktree wherever it lives: old `<root>-worktrees/`
97
+ // checkouts keep working and are never moved.
98
+ const listed = await this.runGit(['-C', this.root, 'worktree', 'list', '--porcelain'], this.root);
99
+ const existing = ticketWorktrees(listed ?? '', this.root).find((w) => w.branch === branch && existsSync(w.path))?.path ?? (existsSync(path) ? path : undefined);
100
+ if (existing) {
101
+ return {
102
+ path: existing,
103
+ instructions: loadInstructions(existing),
84
104
  created: false,
85
105
  ...extra,
86
106
  };
87
107
  }
88
- const branch = this.branchFor(identifier, title);
89
- await this.runGit(['-C', this.root, 'worktree', 'add', '--force', '-B', branch, path], this.root);
108
+ await this.ensureBranch(branch);
109
+ // No `-B`: an existing ticket branch is checked out, never reset;
110
+ // `--force` takes over a registration whose directory is gone.
111
+ await this.runGit(['-C', this.root, 'worktree', 'add', '--force', path, branch], this.root);
90
112
  // The `after_create` hook is run by the conductor, not here — the
91
113
  // workspace only reports that it created a fresh worktree.
92
114
  return {
@@ -96,8 +118,27 @@ export class GitWorkspace {
96
118
  ...extra,
97
119
  };
98
120
  }
121
+ /** Create `branch` at the root's HEAD unless it exists; an existing one stays put. */
122
+ async ensureBranch(branch) {
123
+ try {
124
+ await this.runGit([
125
+ '-C',
126
+ this.root,
127
+ 'rev-parse',
128
+ '--verify',
129
+ '--quiet',
130
+ `refs/heads/${branch}`,
131
+ ], this.root);
132
+ }
133
+ catch {
134
+ await this.runGit(['-C', this.root, 'branch', branch], this.root);
135
+ }
136
+ }
99
137
  /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
100
- remove(branch, worktreePath) {
138
+ async remove(branch, worktreePath) {
139
+ const removed = removeRunCloneWorkspace(worktreePath);
140
+ if (removed)
141
+ return removed;
101
142
  return removeGitWorktree(this.root, branch, worktreePath, async (args, cwd) => (await this.runGit(['-C', cwd, ...args], cwd)) ?? '', this.logger ?? noopLogger);
102
143
  }
103
144
  }
@@ -112,12 +153,12 @@ export function gitWorkspace(opts = {}) {
112
153
  const root = await deriveCheckoutRoot(config.config_path);
113
154
  return new GitWorkspace({
114
155
  root,
115
- ...(opts.branch_prefix ? { branchPrefix: opts.branch_prefix } : {}),
116
- ...(opts.branch_template
117
- ? { branchTemplate: opts.branch_template }
118
- : {}),
156
+ ...(opts.worktree_dir ? { worktreeDir: opts.worktree_dir } : {}),
119
157
  ...(opts.auto_setup_merge ? { autoSetupMerge: true } : {}),
120
158
  ...(deps?.logger ? { logger: deps.logger } : {}),
159
+ clone: config.runtime?.isolates === true,
160
+ // A runtime's `shared` wins; the workspace option is the deprecated fallback.
161
+ shared: config.runtime?.shared ?? opts.shared ?? false,
121
162
  });
122
163
  },
123
164
  };
@@ -2,6 +2,15 @@ import type { WorktreeTeardown } from '@bakers-build/conductor/contract';
2
2
  import type { ConductorLogger } from '@bakers-build/core';
3
3
  /** Runs `git <args>` in `cwd`; resolves with stdout, rejects on non-zero exit. */
4
4
  export type WorktreeGitExec = (args: string[], cwd: string) => Promise<string>;
5
+ /**
6
+ * The ticket worktrees of `git worktree list --porcelain` (record 0, the main
7
+ * checkout, and `root` are never one). A `prunable` entry still carries its
8
+ * `worktree <path>` line, so it parses too.
9
+ */
10
+ export declare function ticketWorktrees(output: string, root: string | undefined): {
11
+ path: string;
12
+ branch: string | null;
13
+ }[];
5
14
  /**
6
15
  * Tear down one ticket worktree with git alone — the shared teardown of every
7
16
  * workspace, and the fallback of a tool workspace whose tool lost track of it.
@@ -8,7 +8,7 @@ function normPath(path) {
8
8
  * checkout, and `root` are never one). A `prunable` entry still carries its
9
9
  * `worktree <path>` line, so it parses too.
10
10
  */
11
- function ticketWorktrees(output, root) {
11
+ export function ticketWorktrees(output, root) {
12
12
  const entries = [];
13
13
  for (const record of output.split(/\n\s*\n/)) {
14
14
  const path = record.match(/^worktree (.+)$/m)?.[1]?.trim();
@@ -0,0 +1,14 @@
1
+ import type { WorktreeTeardown } from '@bakers-build/conductor/contract';
2
+ import { type RunClone, type RunCloneOptions } from '@bakers-build/core';
3
+ /**
4
+ * {@link createRunClone}, once more after restoring owner-write when the first
5
+ * refresh fails: a site may have hardened directories it must rewrite.
6
+ */
7
+ export declare function ensureRunClone(options: RunCloneOptions): RunClone;
8
+ /** `origin/<branch>` → `<branch>`: the ref a run clone carries as its target. */
9
+ export declare const targetOf: (baseRef: string | undefined) => string | undefined;
10
+ /**
11
+ * Remove a run clone's directory and Git directory. `undefined` when
12
+ * `worktreePath` is no run clone, so the caller tears down a linked worktree.
13
+ */
14
+ export declare function removeRunCloneWorkspace(worktreePath: string | undefined): WorktreeTeardown | undefined;
@@ -0,0 +1,34 @@
1
+ import { existsSync, rmSync } from 'node:fs';
2
+ import { createRunClone, loadRunClone, removeRunClone, } from '@bakers-build/core';
3
+ import { restoreWritable } from './fs.js';
4
+ /**
5
+ * {@link createRunClone}, once more after restoring owner-write when the first
6
+ * refresh fails: a site may have hardened directories it must rewrite.
7
+ */
8
+ export function ensureRunClone(options) {
9
+ try {
10
+ return createRunClone(options);
11
+ }
12
+ catch (err) {
13
+ if (!existsSync(options.workspace))
14
+ throw err;
15
+ restoreWritable(options.workspace);
16
+ return createRunClone(options);
17
+ }
18
+ }
19
+ /** `origin/<branch>` → `<branch>`: the ref a run clone carries as its target. */
20
+ export const targetOf = (baseRef) => baseRef?.replace(/^origin\//, '');
21
+ /**
22
+ * Remove a run clone's directory and Git directory. `undefined` when
23
+ * `worktreePath` is no run clone, so the caller tears down a linked worktree.
24
+ */
25
+ export function removeRunCloneWorkspace(worktreePath) {
26
+ if (!worktreePath || !loadRunClone(worktreePath))
27
+ return undefined;
28
+ restoreWritable(worktreePath);
29
+ rmSync(worktreePath, { recursive: true, force: true });
30
+ if (existsSync(worktreePath))
31
+ return 'unverified';
32
+ removeRunClone(worktreePath);
33
+ return 'removed';
34
+ }
@@ -4,20 +4,21 @@
4
4
  "title": "@bakers-build/addon-workspace-git options",
5
5
  "type": "object",
6
6
  "properties": {
7
- "branch_prefix": {
7
+ "worktree_dir": {
8
8
  "type": "string",
9
- "description": "Prefix of every ticket branch.",
10
- "default": "bakers/"
11
- },
12
- "branch_template": {
13
- "type": "string",
14
- "description": "Branch name template. Placeholders: {branch_prefix}, {key}, {identifier}, {title_slug}.",
15
- "default": "{branch_prefix}{key}-{title_slug}"
9
+ "description": "Directory of new worktrees, relative to the repository root or absolute; a ticket checks out at `<worktree_dir>/<branch_name>`.",
10
+ "default": ".bakers-worktrees"
16
11
  },
17
12
  "auto_setup_merge": {
18
13
  "type": "boolean",
19
14
  "description": "`false` sets `branch.autoSetupMerge=false` in the root repository before creating a worktree, so run branches have no upstream and push with `push.default=current`; `true` leaves Git alone but does not revert an earlier change.",
20
15
  "default": false
16
+ },
17
+ "shared": {
18
+ "type": "boolean",
19
+ "default": false,
20
+ "description": "Deprecated: set shared on the isolating runtime (runtime-bwrap, runtime-docker) instead; a value set there wins. Run clones borrow the parent repository's objects (git clone --shared) instead of copying them.",
21
+ "deprecated": true
21
22
  }
22
23
  },
23
24
  "additionalProperties": false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-workspace-git",
3
- "version": "0.9.1-next.5",
3
+ "version": "0.9.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",
@@ -22,11 +22,11 @@
22
22
  "directory": "bakers-cli/addons/workspace-git"
23
23
  },
24
24
  "peerDependencies": {
25
- "@bakers-build/conductor": "^0.9.1-next.5",
26
- "@bakers-build/core": "^0.9.1-next.5"
25
+ "@bakers-build/conductor": "^0.9.1-next.7",
26
+ "@bakers-build/core": "^0.9.1-next.7"
27
27
  },
28
28
  "bakersBuild": {
29
- "commit": "d9242cad6cabee1faf010b5d46ac1bac33f6e0a1",
29
+ "commit": "03781c6f8dc8c4c3d87fdcf12ae37df35abc6286",
30
30
  "channel": "next"
31
31
  }
32
32
  }