-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-worktree.js
More file actions
199 lines (172 loc) · 5.15 KB
/
setup-worktree.js
File metadata and controls
199 lines (172 loc) · 5.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const SCRIPT_DIR = __dirname;
const DEFAULT_ENV_RELATIVE_PATH = path.join('apps', 'server', '.env');
function run(command, args, options = {}) {
return spawnSync(command, args, { encoding: 'utf8', ...options });
}
function usage() {
console.log(
'Usage: node setup-worktree.js [worktree-path] [--from <path>] [--force]'
);
console.log('');
console.log('Defaults:');
console.log(' - worktree-path defaults to current directory');
console.log(
` - source ${DEFAULT_ENV_RELATIVE_PATH} is auto-detected from another worktree`
);
console.log('');
console.log('Examples:');
console.log(' node setup-worktree.js');
console.log(' npm run setup-worktree');
console.log(' node setup-worktree.js . --force');
console.log(
' node setup-worktree.js --from /Users/ganeshdole/Project/brainbox/apps/server/.env'
);
}
function fail(message) {
console.error(`Error: ${message}`);
process.exit(1);
}
function toEnvFilePath(inputPath) {
const resolved = path.resolve(inputPath);
if (!fs.existsSync(resolved)) {
fail(`--from path does not exist: ${resolved}`);
}
if (fs.statSync(resolved).isDirectory()) {
return path.join(resolved, DEFAULT_ENV_RELATIVE_PATH);
}
return resolved;
}
function isGitWorktree(repoPath) {
const result = run(
'git',
['-C', repoPath, 'rev-parse', '--is-inside-work-tree'],
{
stdio: 'ignore',
}
);
return result.status === 0;
}
function resolveWorktreeRoot(repoPath) {
const result = run('git', ['-C', repoPath, 'rev-parse', '--show-toplevel']);
if (result.status !== 0) {
fail(`unable to resolve git worktree root for: ${repoPath}`);
}
return path.resolve(result.stdout.trim());
}
function listWorktrees(repoPath) {
const result = run('git', [
'-C',
repoPath,
'worktree',
'list',
'--porcelain',
]);
if (result.status !== 0) {
fail('unable to list git worktrees.');
}
const paths = [];
const lines = result.stdout.split(/\r?\n/);
for (const line of lines) {
if (line.startsWith('worktree ')) {
paths.push(line.slice('worktree '.length));
}
}
return paths;
}
function detectSourceEnv(worktreePath, explicitFromPath) {
if (explicitFromPath) {
const explicitEnv = toEnvFilePath(explicitFromPath);
if (!fs.existsSync(explicitEnv)) {
fail(`source env file not found at ${explicitEnv}`);
}
return explicitEnv;
}
const localScriptEnv = path.join(SCRIPT_DIR, DEFAULT_ENV_RELATIVE_PATH);
if (
path.resolve(SCRIPT_DIR) !== worktreePath &&
fs.existsSync(localScriptEnv)
) {
return localScriptEnv;
}
const otherWorktrees = listWorktrees(worktreePath)
.map((worktree) => path.resolve(worktree))
.filter((worktree) => worktree !== worktreePath);
for (const other of otherWorktrees) {
const candidate = path.join(other, DEFAULT_ENV_RELATIVE_PATH);
if (fs.existsSync(candidate)) {
return candidate;
}
}
fail(
`could not auto-detect source ${DEFAULT_ENV_RELATIVE_PATH} from another worktree. Pass --from <path-to-env-or-repo>.`
);
}
const args = process.argv.slice(2);
let force = false;
let fromPath = '';
let rawWorktreePath = '';
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === '--help' || arg === '-h') {
usage();
process.exit(0);
}
if (arg === '--force') {
force = true;
continue;
}
if (arg === '--from') {
const next = args[index + 1];
if (!next) {
fail('missing value for --from');
}
fromPath = next;
index += 1;
continue;
}
if (arg.startsWith('--from=')) {
fromPath = arg.slice('--from='.length);
continue;
}
if (arg.startsWith('--')) {
fail(`unknown option: ${arg}`);
}
if (rawWorktreePath) {
fail('only one worktree path is allowed.');
}
rawWorktreePath = arg;
}
const worktreePath = path.resolve(rawWorktreePath || process.cwd());
if (!fs.existsSync(worktreePath) || !fs.statSync(worktreePath).isDirectory()) {
fail(`worktree path does not exist: ${worktreePath}`);
}
if (!isGitWorktree(worktreePath)) {
fail(`not a git worktree/repo: ${worktreePath}`);
}
const worktreeRoot = resolveWorktreeRoot(worktreePath);
const sourceEnv = detectSourceEnv(worktreeRoot, fromPath);
const destEnv = path.join(worktreeRoot, DEFAULT_ENV_RELATIVE_PATH);
if (path.resolve(sourceEnv) === path.resolve(destEnv)) {
console.log(`Info: source and destination are the same file: ${destEnv}`);
console.log('Skipping copy.');
} else if (fs.existsSync(destEnv) && !force) {
console.log(`Info: destination env file already exists at ${destEnv}`);
console.log('Use --force to overwrite it.');
} else {
fs.copyFileSync(sourceEnv, destEnv);
console.log(`Copied: ${sourceEnv} -> ${destEnv}`);
}
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
console.log(`Running npm install in ${worktreeRoot} ...`);
const installResult = spawnSync(npmCmd, ['install'], {
cwd: worktreeRoot,
stdio: 'inherit',
});
if (installResult.status !== 0) {
fail('npm install failed in worktree.');
}
console.log('Done. Worktree is bootstrapped.');