@laoyuehanni/dsh-git-worktree 0.4.0

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/lib/routes.js ADDED
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Route logic as pure functions: query/body in, status+body out. The HTTP
3
+ * shell (index.ts) owns req/res mechanics; everything testable lives here.
4
+ */
5
+ import { join } from 'node:path';
6
+ import { mkdir } from 'node:fs/promises';
7
+ import { GitError, addWorktree, addWorktreeCutout, cutoutBranchName, fsDirExists, isAbsoluteDir, probeRepo, switchBranch } from './git.js';
8
+ import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
9
+ import { resolveRootDir } from './settings.js';
10
+ /** Uniform failure envelope. */
11
+ function fail(status, error) {
12
+ return { status, body: { error } };
13
+ }
14
+ /** GitError to outcome: usage-shaped failures are 400, the rest 500. */
15
+ function gitFailure(error) {
16
+ const usage = error.stderr.includes('usage:') || error.stderr.includes('fatal: invalid');
17
+ return fail(usage ? 400 : 500, error.message);
18
+ }
19
+ /**
20
+ * GET /status 鈥?repository facts for one directory.
21
+ * @param deps - host dependencies.
22
+ * @param path - absolute directory the workspace reports.
23
+ */
24
+ export async function handleStatus(deps, path) {
25
+ if (path === undefined || !isAbsoluteDir(path))
26
+ return fail(400, 'query parameter "path" must be an absolute directory');
27
+ const facts = await probeRepo(deps.exec, path, deps.dirExists);
28
+ const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
29
+ if (facts === undefined)
30
+ return { status: 200, body: { repo: false } };
31
+ return {
32
+ status: 200,
33
+ body: {
34
+ repo: true,
35
+ repoName: facts.repoName,
36
+ repoRoot: facts.repoRoot,
37
+ currentBranch: facts.currentBranch,
38
+ branches: facts.branches,
39
+ worktrees: facts.worktrees,
40
+ rootDir,
41
+ },
42
+ };
43
+ }
44
+ /** Validate a JSON body object with exactly the expected keys. */
45
+ function readBody(body, keys, booleanKeys = []) {
46
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
47
+ return fail(400, 'request body must be a JSON object');
48
+ const record = body;
49
+ for (const key of Object.keys(record)) {
50
+ if (!keys.includes(key) && !booleanKeys.includes(key)) {
51
+ return fail(400, `unknown body key "${key}"`);
52
+ }
53
+ }
54
+ for (const key of keys) {
55
+ if (typeof record[key] !== 'string')
56
+ return fail(400, `body key "${key}" must be a string`);
57
+ }
58
+ for (const key of booleanKeys) {
59
+ // Optional flag: absent stays absent (`cutout?: boolean`), present must type-check.
60
+ if (record[key] !== undefined && typeof record[key] !== 'boolean') {
61
+ return fail(400, `body key "${key}" must be a boolean`);
62
+ }
63
+ }
64
+ return record;
65
+ }
66
+ /** Discriminator: a RouteOutcome carries the `status`/`body` pair no request body has. */
67
+ function isOutcome(value) {
68
+ return typeof value === 'object' && value !== null && 'status' in value && 'body' in value;
69
+ }
70
+ /**
71
+ * POST /worktree 鈥?create or reuse the worktree for a branch, then report the
72
+ * directory so the client can register it as a workspace. With `cutout: true`
73
+ * the branch is the CURRENT checkout (occupied by the main worktree, so git
74
+ * refuses to add it): a new branch is cut out of it (`<branch>-wt`, first
75
+ * free `-wt<N>` suffix) and isolated in the fresh worktree instead.
76
+ * @param deps - host dependencies.
77
+ * @param body - parsed request body.
78
+ */
79
+ export async function handleCreateWorktree(deps, body) {
80
+ const parsed = readBody(body, ['repoPath', 'branch'], ['cutout']);
81
+ if (isOutcome(parsed))
82
+ return parsed;
83
+ const { repoPath, branch, cutout } = parsed;
84
+ if (!isAbsoluteDir(repoPath))
85
+ return fail(400, '"repoPath" must be an absolute directory');
86
+ if (branch.trim() === '')
87
+ return fail(400, '"branch" must be non-empty');
88
+ const configured = deps.sectionRootDir()?.trim();
89
+ if (configured !== undefined && configured !== '' && !isAbsoluteConfigPath(configured)) {
90
+ return fail(400, `configured rootDir "${String(deps.sectionRootDir())}" is not an absolute path`);
91
+ }
92
+ try {
93
+ const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
94
+ if (facts === undefined)
95
+ return fail(400, `"${repoPath}" is not inside a git repository`);
96
+ const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
97
+ if (cutout === true) {
98
+ // The new branch name must be known before the folder name can be
99
+ // computed: the folder carries `<repoName>-<NEW branch>`. The name
100
+ // must be free in BOTH namespaces — the branch table and the storage
101
+ // folder: a leftover folder of a since-deleted branch would otherwise
102
+ // fail `worktree add` with a bare "already exists", so the suffix
103
+ // walk probes the folder too.
104
+ const dirExists = deps.dirExists ?? fsDirExists;
105
+ const newBranch = await cutoutBranchName(deps.exec, facts.repoRoot, branch, (candidate) => dirExists(join(rootDir, `${facts.repoName}-${sanitizeBranchDir(candidate)}`)));
106
+ const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(newBranch)}`);
107
+ await mkdir(rootDir, { recursive: true });
108
+ await addWorktreeCutout(deps.exec, facts.repoRoot, branch, newBranch, target);
109
+ return { status: 200, body: { path: target, created: true } };
110
+ }
111
+ // The folder name carries the belonging itself: `<repoName>-<branch>` —
112
+ // the sidebar group title (the folder basename) then reads as the parent
113
+ // repository plus the branch instead of a bare branch word.
114
+ const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(branch)}`);
115
+ await mkdir(rootDir, { recursive: true });
116
+ const result = await addWorktree(deps.exec, facts.repoRoot, branch, target, deps.dirExists);
117
+ return { status: 200, body: result };
118
+ }
119
+ catch (error) {
120
+ if (error instanceof GitError)
121
+ return gitFailure(error);
122
+ return fail(500, error instanceof Error ? error.message : String(error));
123
+ }
124
+ }
125
+ /**
126
+ * POST /switch 鈥?in-place branch switch of the main checkout.
127
+ * @param deps - host dependencies.
128
+ * @param body - parsed request body.
129
+ */
130
+ export async function handleSwitch(deps, body) {
131
+ const parsed = readBody(body, ['repoPath', 'branch']);
132
+ if (isOutcome(parsed))
133
+ return parsed;
134
+ const { repoPath, branch } = parsed;
135
+ if (!isAbsoluteDir(repoPath))
136
+ return fail(400, '"repoPath" must be an absolute directory');
137
+ if (branch.trim() === '')
138
+ return fail(400, '"branch" must be non-empty');
139
+ try {
140
+ const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
141
+ if (facts === undefined)
142
+ return fail(400, `"${repoPath}" is not inside a git repository`);
143
+ const switched = await switchBranch(deps.exec, facts.repoRoot, branch);
144
+ const result = { branch: switched };
145
+ return { status: 200, body: result };
146
+ }
147
+ catch (error) {
148
+ if (error instanceof GitError)
149
+ return gitFailure(error);
150
+ return fail(500, error instanceof Error ? error.message : String(error));
151
+ }
152
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Host-side settings support: resolve the worktree storage root from the
3
+ * settings section, and read the legacy settings file the pre-0.3 plugin
4
+ * persisted on its own (~/.dsh/git-worktree/settings.json). The stored value
5
+ * now lives in the dsh settings document under the `git-worktree` namespace;
6
+ * the legacy file is read once at startup and its value migrated across (the
7
+ * renamed file stays behind as a backup).
8
+ */
9
+ /** The persisted document shape the pre-0.3 plugin read and wrote on its own. */
10
+ export interface LegacySettings {
11
+ /** Worktree storage root; '' selected the default ~/.dsh/gitworktree. */
12
+ rootDir: string;
13
+ }
14
+ /**
15
+ * Resolve the effective worktree storage root: an explicit non-blank `rootDir`
16
+ * wins; otherwise `$DSH_HOME/gitworktree` (a blank `$DSH_HOME` counts as
17
+ * unset), else `~/.dsh/gitworktree`.
18
+ * @param rootDir - the settings-resolved section value (absent/blank = default).
19
+ * @param home - user home directory (`os.homedir()` seam).
20
+ * @param envHome - `$DSH_HOME` environment value seam.
21
+ * @returns an absolute directory path.
22
+ */
23
+ export declare function resolveRootDir(rootDir: string | undefined, home: string, envHome: string | undefined): string;
24
+ /**
25
+ * Reject a stored rootDir the plugin could not act on: a non-blank value that
26
+ * is not an absolute path. Blank/absent means the default location and passes.
27
+ * @param rootDir - the resolved section value.
28
+ */
29
+ export declare function validateRootDir(rootDir: string | undefined): void;
30
+ /**
31
+ * Decide what a legacy-file migration should store, if anything: the legacy
32
+ * root only crosses over when it names a directory (blank kept the default,
33
+ * which the section's absence already expresses) and the user layer has not
34
+ * recorded its own choice (key presence, not a value comparison — an override
35
+ * equal to the legacy value is still the user's own doing and must not be
36
+ * rewritten).
37
+ * @param legacy - the legacy file's stored value.
38
+ * @param userLayer - the namespace's raw user layer, when one exists.
39
+ * @returns the rootDir to write, or undefined to leave the section alone.
40
+ */
41
+ export declare function planLegacyMigration(legacy: LegacySettings, userLayer: Record<string, unknown> | undefined): string | undefined;
42
+ /**
43
+ * Load the legacy settings document.
44
+ * @param file - absolute settings file path.
45
+ * @returns the stored value, or the default when absent/unreadable/invalid.
46
+ */
47
+ export declare function loadLegacySettings(file: string): Promise<LegacySettings>;
48
+ /** Resolve the legacy settings file location for a home directory. */
49
+ export declare function settingsFileOf(home: string): string;
50
+ /** The backup name a migrated legacy file is renamed to (never deleted). */
51
+ export declare function migratedFileOf(file: string): string;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Host-side settings support: resolve the worktree storage root from the
3
+ * settings section, and read the legacy settings file the pre-0.3 plugin
4
+ * persisted on its own (~/.dsh/git-worktree/settings.json). The stored value
5
+ * now lives in the dsh settings document under the `git-worktree` namespace;
6
+ * the legacy file is read once at startup and its value migrated across (the
7
+ * renamed file stays behind as a backup).
8
+ */
9
+ import { readFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { isAbsoluteConfigPath } from './normalize.js';
12
+ /**
13
+ * Resolve the effective worktree storage root: an explicit non-blank `rootDir`
14
+ * wins; otherwise `$DSH_HOME/gitworktree` (a blank `$DSH_HOME` counts as
15
+ * unset), else `~/.dsh/gitworktree`.
16
+ * @param rootDir - the settings-resolved section value (absent/blank = default).
17
+ * @param home - user home directory (`os.homedir()` seam).
18
+ * @param envHome - `$DSH_HOME` environment value seam.
19
+ * @returns an absolute directory path.
20
+ */
21
+ export function resolveRootDir(rootDir, home, envHome) {
22
+ const configured = rootDir?.trim();
23
+ if (configured !== undefined && configured !== '')
24
+ return configured;
25
+ const base = typeof envHome === 'string' && envHome.trim() !== '' ? envHome : join(home, '.dsh');
26
+ return join(base, 'gitworktree');
27
+ }
28
+ /**
29
+ * Reject a stored rootDir the plugin could not act on: a non-blank value that
30
+ * is not an absolute path. Blank/absent means the default location and passes.
31
+ * @param rootDir - the resolved section value.
32
+ */
33
+ export function validateRootDir(rootDir) {
34
+ if (rootDir === undefined)
35
+ return;
36
+ const trimmed = rootDir.trim();
37
+ if (trimmed === '')
38
+ return;
39
+ if (!isAbsoluteConfigPath(trimmed)) {
40
+ throw new Error(`rootDir "${rootDir}" is not an absolute path`);
41
+ }
42
+ }
43
+ /**
44
+ * Decide what a legacy-file migration should store, if anything: the legacy
45
+ * root only crosses over when it names a directory (blank kept the default,
46
+ * which the section's absence already expresses) and the user layer has not
47
+ * recorded its own choice (key presence, not a value comparison — an override
48
+ * equal to the legacy value is still the user's own doing and must not be
49
+ * rewritten).
50
+ * @param legacy - the legacy file's stored value.
51
+ * @param userLayer - the namespace's raw user layer, when one exists.
52
+ * @returns the rootDir to write, or undefined to leave the section alone.
53
+ */
54
+ export function planLegacyMigration(legacy, userLayer) {
55
+ if (userLayer !== undefined && Object.hasOwn(userLayer, 'rootDir'))
56
+ return undefined;
57
+ const value = legacy.rootDir.trim();
58
+ return value === '' ? undefined : value;
59
+ }
60
+ /**
61
+ * Load the legacy settings document.
62
+ * @param file - absolute settings file path.
63
+ * @returns the stored value, or the default when absent/unreadable/invalid.
64
+ */
65
+ export async function loadLegacySettings(file) {
66
+ let raw;
67
+ try {
68
+ raw = await readFile(file, 'utf8');
69
+ }
70
+ catch {
71
+ return { rootDir: '' };
72
+ }
73
+ try {
74
+ const parsed = JSON.parse(raw);
75
+ if (typeof parsed !== 'object' || parsed === null)
76
+ return { rootDir: '' };
77
+ const rootDir = parsed.rootDir;
78
+ return typeof rootDir === 'string' ? { rootDir } : { rootDir: '' };
79
+ }
80
+ catch {
81
+ return { rootDir: '' };
82
+ }
83
+ }
84
+ /** Resolve the legacy settings file location for a home directory. */
85
+ export function settingsFileOf(home) {
86
+ return join(home, '.dsh', 'git-worktree', 'settings.json');
87
+ }
88
+ /** The backup name a migrated legacy file is renamed to (never deleted). */
89
+ export function migratedFileOf(file) {
90
+ return `${file}.migrated`;
91
+ }
package/lib/wire.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Shared wire contract between the host half (HTTP routes under
3
+ * `/plugin/git-worktree`) and the browser half (chip + plugin settings card).
4
+ * Zero runtime dependencies: constants and types only, imported by both
5
+ * builds.
6
+ */
7
+ /** Absolute pathname prefix every route of this plugin lives under. */
8
+ export declare const ROUTE_PREFIX = "/plugin/git-worktree";
9
+ /** GET ROUTE_PREFIX/status?path=<absolute dir> */
10
+ export declare const ROUTE_STATUS = "/plugin/git-worktree/status";
11
+ /** POST ROUTE_PREFIX/worktree — create-or-reuse a worktree for a branch. */
12
+ export declare const ROUTE_WORKTREE = "/plugin/git-worktree/worktree";
13
+ /** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */
14
+ export declare const ROUTE_SWITCH = "/plugin/git-worktree/switch";
15
+ /** One selectable branch row. */
16
+ export interface BranchEntry {
17
+ /** Display name: a bare local name (`main`) or `<remote>/<name>`. */
18
+ name: string;
19
+ kind: 'local' | 'remote';
20
+ }
21
+ /** One existing worktree of the repository. */
22
+ export interface WorktreeEntry {
23
+ /** Absolute path of the worktree directory. */
24
+ path: string;
25
+ /** Checked-out local branch name; absent for a detached or bare worktree. */
26
+ branch: string | undefined;
27
+ /** True for the main worktree (the one holding `.git`). */
28
+ main: boolean;
29
+ }
30
+ /** Response of GET status — `repo: false` for a directory outside any git repository. */
31
+ export type RepoStatus = {
32
+ repo: false;
33
+ } | {
34
+ repo: true;
35
+ /** Main repository directory basename — the root folder of `<rootDir>/<repoName>/`. */
36
+ repoName: string;
37
+ /** Absolute path of the main worktree directory. */
38
+ repoRoot: string;
39
+ /** Branch checked out by the directory the client asked about. */
40
+ currentBranch: string;
41
+ /** Local branches plus remote branches without a same-named local one. */
42
+ branches: BranchEntry[];
43
+ /** Every worktree of the repository, main first (git order). */
44
+ worktrees: WorktreeEntry[];
45
+ /** Resolved worktree storage root (absolute) — what the settings say today. */
46
+ rootDir: string;
47
+ };
48
+ /** POST worktree request body. */
49
+ export interface CreateWorktreeBody {
50
+ /** Any directory inside the repository (workspace cwd). */
51
+ repoPath: string;
52
+ /** Chosen branch display name: local (`feat-x`) or remote (`origin/feat-x`). */
53
+ branch: string;
54
+ /** True: cut a NEW branch out of `branch` (the current checkout's
55
+ * branch — occupied by the main worktree) and isolate it in a fresh
56
+ * worktree. The storage folder is named after the new branch. */
57
+ cutout?: boolean;
58
+ }
59
+ /** POST worktree response body. */
60
+ export interface CreateWorktreeResult {
61
+ /** The worktree directory (created or reused). */
62
+ path: string;
63
+ /** False when an existing worktree for the branch was reused. */
64
+ created: boolean;
65
+ }
66
+ /** POST switch request body. */
67
+ export interface SwitchBody {
68
+ /** Any directory inside the main worktree. */
69
+ repoPath: string;
70
+ /** Target branch display name (local, or remote whose local twin is created by dwim). */
71
+ branch: string;
72
+ }
73
+ /** POST switch response body. */
74
+ export interface SwitchResult {
75
+ /** The branch actually checked out after the switch. */
76
+ branch: string;
77
+ }
78
+ /** Error envelope every non-2xx response carries. */
79
+ export interface RouteError {
80
+ error: string;
81
+ }
package/lib/wire.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Shared wire contract between the host half (HTTP routes under
3
+ * `/plugin/git-worktree`) and the browser half (chip + plugin settings card).
4
+ * Zero runtime dependencies: constants and types only, imported by both
5
+ * builds.
6
+ */
7
+ /** Absolute pathname prefix every route of this plugin lives under. */
8
+ export const ROUTE_PREFIX = '/plugin/git-worktree';
9
+ /** GET ROUTE_PREFIX/status?path=<absolute dir> */
10
+ export const ROUTE_STATUS = `${ROUTE_PREFIX}/status`;
11
+ /** POST ROUTE_PREFIX/worktree — create-or-reuse a worktree for a branch. */
12
+ export const ROUTE_WORKTREE = `${ROUTE_PREFIX}/worktree`;
13
+ /** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */
14
+ export const ROUTE_SWITCH = `${ROUTE_PREFIX}/switch`;
package/package.json ADDED
@@ -0,0 +1,102 @@
1
+ {
2
+ "name": "@laoyuehanni/dsh-git-worktree",
3
+ "version": "0.4.0",
4
+ "description": "DSH plugin: branch visibility and git worktree isolation for Web UI sessions",
5
+ "keywords": [
6
+ "dsh",
7
+ "deepseek",
8
+ "cordis",
9
+ "plugin",
10
+ "git",
11
+ "worktree",
12
+ "branch"
13
+ ],
14
+ "homepage": "https://github.com/LaoYueHanNi/dsh-git-worktree#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/LaoYueHanNi/dsh-git-worktree/issues"
17
+ },
18
+ "license": "MIT",
19
+ "author": "LaoYueHanNi",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/LaoYueHanNi/dsh-git-worktree.git"
23
+ },
24
+ "type": "module",
25
+ "main": "lib/index.js",
26
+ "types": "lib/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./lib/index.d.ts",
30
+ "default": "./lib/index.js"
31
+ },
32
+ "./wire": {
33
+ "types": "./lib/wire.d.ts",
34
+ "default": "./lib/wire.js"
35
+ },
36
+ "./client": {
37
+ "default": "./lib/client.js"
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "files": [
42
+ "lib",
43
+ "cordis.patch.yml",
44
+ "README.md",
45
+ "README.zh.md"
46
+ ],
47
+ "publishConfig": {
48
+ "registry": "https://registry.npmjs.org/",
49
+ "access": "public"
50
+ },
51
+ "dsh": {
52
+ "bundle": {
53
+ "patch": "./cordis.patch.yml"
54
+ },
55
+ "client": {
56
+ "platform": "web",
57
+ "inject": [
58
+ "@deepseek-ai/dsh-client-runtime",
59
+ "@deepseek-ai/dsh-client-ui-conversation",
60
+ "@deepseek-ai/dsh-client-ui-settings",
61
+ "@deepseek-ai/dsh-client-ui-settings-plugins"
62
+ ]
63
+ }
64
+ },
65
+ "scripts": {
66
+ "build": "tsc -p tsconfig.json",
67
+ "build:client": "tsdown",
68
+ "build:all": "npm run build && npm run build:client",
69
+ "watch:client": "tsdown --watch",
70
+ "test": "vitest run",
71
+ "typecheck": "tsc -p tsconfig.client.json --noEmit",
72
+ "prepublishOnly": "npm run typecheck && npm test && npm run build && npm run build:client"
73
+ },
74
+ "peerDependencies": {
75
+ "@deepseek-ai/cordis": "^4.0.1",
76
+ "@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.7",
77
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.7 || ^0.1.1-rc.2",
78
+ "@deepseek-ai/schemastery": "^3.18.1"
79
+ },
80
+ "devDependencies": {
81
+ "@deepseek-ai/cordis": "^4.0.1",
82
+ "@deepseek-ai/dsh-api-remotes": "^0.1.0-rc.7",
83
+ "@deepseek-ai/dsh-client-locale": "^0.1.0-rc.7",
84
+ "@deepseek-ai/dsh-client-runtime": "^0.1.0-rc.7",
85
+ "@deepseek-ai/dsh-client-ui-conversation": "^0.1.0-rc.7",
86
+ "@deepseek-ai/dsh-client-ui-primitives": "^0.1.0-rc.7",
87
+ "@deepseek-ai/dsh-client-ui-settings": "^0.1.0-rc.7",
88
+ "@deepseek-ai/dsh-client-ui-settings-plugins": "^0.1.0-rc.7",
89
+ "@deepseek-ai/dsh-client-ui-slots": "^0.1.0-rc.7",
90
+ "@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.7",
91
+ "@types/node": "^24.13.3",
92
+ "@types/react": "~18.3.1",
93
+ "playwright-core": "^1.55.1",
94
+ "react": "^18.2.0",
95
+ "tsdown": "^0.14.0",
96
+ "typescript": "^5.9.3",
97
+ "vitest": "^3.2.4"
98
+ },
99
+ "engines": {
100
+ "node": ">=22.19"
101
+ }
102
+ }