@jondotsoy/envs 0.0.0-stage → 0.0.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 +14 -2
- package/package.json +20 -4
- package/src/bin/envs.ts +4 -0
- package/src/envs.ts +230 -0
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# init
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
To install dependencies:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bun install
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
To run:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun run index.ts
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This project was created using `bun init` in bun v1.4.2. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jondotsoy/envs",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"module": "index.ts",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"envs": "src/bin/envs.ts"
|
|
8
|
+
},
|
|
9
|
+
"devDependencies": {
|
|
10
|
+
"@types/bun": "latest",
|
|
11
|
+
"ajv": "^8.20.0"
|
|
12
|
+
},
|
|
13
|
+
"peerDependencies": {
|
|
14
|
+
"typescript": "^7"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"src"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "bun scripts/build.ts"
|
|
21
|
+
}
|
|
22
|
+
}
|
package/src/bin/envs.ts
ADDED
package/src/envs.ts
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { $ } from "bun";
|
|
4
|
+
|
|
5
|
+
export const HELP = `Usage: envs <command>
|
|
6
|
+
|
|
7
|
+
Commands:
|
|
8
|
+
init Create the .envs/ directory (.gitignore, values.yml)
|
|
9
|
+
pull Read each worktree's .env and write it into .envs/values.yml
|
|
10
|
+
push Write defaults and .envs/values.yml into the .env of each worktree
|
|
11
|
+
edit Pull, open .envs/values.yml in VS Code (code -w), then push
|
|
12
|
+
help Show this help message
|
|
13
|
+
`;
|
|
14
|
+
|
|
15
|
+
export interface Context {
|
|
16
|
+
/** Directory the command runs from. */
|
|
17
|
+
cwd: string;
|
|
18
|
+
log(message: string): void;
|
|
19
|
+
error(message: string): void;
|
|
20
|
+
/** Opens a file in the editor and resolves with its exit code once closed. */
|
|
21
|
+
openEditor(path: string): Promise<number>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const defaultContext = (): Context => ({
|
|
25
|
+
cwd: process.cwd(),
|
|
26
|
+
log: (message) => console.log(message),
|
|
27
|
+
error: (message) => console.error(message),
|
|
28
|
+
openEditor: async (path) => {
|
|
29
|
+
const proc = Bun.spawn(["code", "-w", path], {
|
|
30
|
+
env: { ...process.env },
|
|
31
|
+
stdio: ["inherit", "inherit", "inherit"],
|
|
32
|
+
});
|
|
33
|
+
return await proc.exited;
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
interface Values {
|
|
38
|
+
defaults?: Record<string, string>;
|
|
39
|
+
envs?: Record<string, Record<string, string>>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface Worktree {
|
|
43
|
+
name: string;
|
|
44
|
+
path: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Root of the main git workspace; inside a worktree this is the parent repo. Falls back to cwd outside git. */
|
|
48
|
+
export async function findRoot(cwd: string): Promise<string> {
|
|
49
|
+
const result = await $`git rev-parse --path-format=absolute --git-common-dir`
|
|
50
|
+
.cwd(cwd)
|
|
51
|
+
.nothrow()
|
|
52
|
+
.quiet();
|
|
53
|
+
if (result.exitCode !== 0) return cwd;
|
|
54
|
+
return dirname(result.stdout.toString().trim());
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Lists the main workspace and its worktrees; `name` is the branch (or dir name when detached). */
|
|
58
|
+
export async function listWorktrees(cwd: string): Promise<Worktree[]> {
|
|
59
|
+
const out = await $`git worktree list --porcelain`.cwd(cwd).text();
|
|
60
|
+
return out
|
|
61
|
+
.trim()
|
|
62
|
+
.split("\n\n")
|
|
63
|
+
.map((block) => {
|
|
64
|
+
const lines = block.split("\n");
|
|
65
|
+
const path = lines.find((l) => l.startsWith("worktree "))!.slice(9);
|
|
66
|
+
const branch = lines.find((l) => l.startsWith("branch "));
|
|
67
|
+
return {
|
|
68
|
+
path,
|
|
69
|
+
name: branch
|
|
70
|
+
? branch.slice("branch refs/heads/".length)
|
|
71
|
+
: basename(path),
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Minimal .env parser: KEY=VALUE lines, `#` comments, optional quotes and `export`. */
|
|
77
|
+
export function parseDotenv(text: string): Record<string, string> {
|
|
78
|
+
const result: Record<string, string> = {};
|
|
79
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
80
|
+
const line = raw.trim();
|
|
81
|
+
if (!line || line.startsWith("#")) continue;
|
|
82
|
+
const match = line.match(/^(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/);
|
|
83
|
+
if (!match) continue;
|
|
84
|
+
let value = match[2]!.trim();
|
|
85
|
+
const quote = value[0];
|
|
86
|
+
if ((quote === '"' || quote === "'") && value.lastIndexOf(quote) > 0) {
|
|
87
|
+
value = value.slice(1, value.lastIndexOf(quote));
|
|
88
|
+
} else {
|
|
89
|
+
value = value.replace(/\s+#.*$/, "");
|
|
90
|
+
}
|
|
91
|
+
result[match[1]!] = value;
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function formatDotenvValue(value: string): string {
|
|
97
|
+
if (value !== "" && !/[\s#"'\\$]/.test(value)) return value;
|
|
98
|
+
return value.includes('"') ? `'${value}'` : `"${value}"`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Sets KEY=VALUE for each entry, updating existing lines in place and appending new ones. */
|
|
102
|
+
export function updateDotenv(
|
|
103
|
+
text: string,
|
|
104
|
+
entries: Record<string, string>,
|
|
105
|
+
): string {
|
|
106
|
+
const pending = new Map(Object.entries(entries));
|
|
107
|
+
const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
|
|
108
|
+
const updated = lines.map((line) => {
|
|
109
|
+
const key = line.trim().match(/^(?:export\s+)?([\w.-]+)\s*=/)?.[1];
|
|
110
|
+
if (key === undefined || !pending.has(key)) return line;
|
|
111
|
+
const value = pending.get(key)!;
|
|
112
|
+
pending.delete(key);
|
|
113
|
+
return `${key}=${formatDotenvValue(value)}`;
|
|
114
|
+
});
|
|
115
|
+
for (const [key, value] of pending) {
|
|
116
|
+
updated.push(`${key}=${formatDotenvValue(value)}`);
|
|
117
|
+
}
|
|
118
|
+
return updated.join("\n") + "\n";
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Reads values.yml; returns undefined (after reporting) when `envs init` was not run. */
|
|
122
|
+
async function readValues(
|
|
123
|
+
ctx: Context,
|
|
124
|
+
): Promise<{ path: string; values: Values } | undefined> {
|
|
125
|
+
const path = join(await findRoot(ctx.cwd), ".envs/values.yml");
|
|
126
|
+
if (!(await Bun.file(path).exists())) {
|
|
127
|
+
ctx.error(`${path} not found. Run \`envs init\` first.`);
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
const values = (Bun.YAML.parse(await Bun.file(path).text()) ?? {}) as Values;
|
|
131
|
+
return { path, values };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function init(ctx: Context): Promise<number> {
|
|
135
|
+
const root = await findRoot(ctx.cwd);
|
|
136
|
+
const files = { ".envs/.gitignore": "*\n", ".envs/values.yml": "" };
|
|
137
|
+
await mkdir(join(root, ".envs"), { recursive: true });
|
|
138
|
+
for (const [name, content] of Object.entries(files)) {
|
|
139
|
+
const path = join(root, name);
|
|
140
|
+
if (await Bun.file(path).exists()) {
|
|
141
|
+
ctx.log(`${path} already exists`);
|
|
142
|
+
} else {
|
|
143
|
+
await Bun.write(path, content);
|
|
144
|
+
ctx.log(`Created ${path}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function push(ctx: Context): Promise<number> {
|
|
151
|
+
const read = await readValues(ctx);
|
|
152
|
+
if (!read) return 1;
|
|
153
|
+
const { values } = read;
|
|
154
|
+
for (const { name, path } of await listWorktrees(ctx.cwd)) {
|
|
155
|
+
// Defaults apply to every worktree; per-worktree values override them.
|
|
156
|
+
const entries: Record<string, string> = {};
|
|
157
|
+
for (const [key, value] of Object.entries(values.defaults ?? {})) {
|
|
158
|
+
entries[key] = String(value);
|
|
159
|
+
}
|
|
160
|
+
for (const [key, byWorktree] of Object.entries(values.envs ?? {})) {
|
|
161
|
+
if (name in byWorktree) entries[key] = String(byWorktree[name]);
|
|
162
|
+
}
|
|
163
|
+
if (Object.keys(entries).length === 0) continue;
|
|
164
|
+
const dotenv = Bun.file(join(path, ".env"));
|
|
165
|
+
const current = (await dotenv.exists()) ? await dotenv.text() : "";
|
|
166
|
+
await Bun.write(dotenv, updateDotenv(current, entries));
|
|
167
|
+
ctx.log(`Pushed ${name}`);
|
|
168
|
+
}
|
|
169
|
+
return 0;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function pull(ctx: Context): Promise<number> {
|
|
173
|
+
const read = await readValues(ctx);
|
|
174
|
+
if (!read) return 1;
|
|
175
|
+
const { path: valuesPath, values } = read;
|
|
176
|
+
const envs = (values.envs ??= {});
|
|
177
|
+
for (const { name, path } of await listWorktrees(ctx.cwd)) {
|
|
178
|
+
const dotenv = Bun.file(join(path, ".env"));
|
|
179
|
+
if (!(await dotenv.exists())) continue;
|
|
180
|
+
const parsed = parseDotenv(await dotenv.text());
|
|
181
|
+
// Drop keys that are no longer in this worktree's .env.
|
|
182
|
+
for (const [key, byWorktree] of Object.entries(envs)) {
|
|
183
|
+
if (!(key in parsed)) delete byWorktree[name];
|
|
184
|
+
}
|
|
185
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
186
|
+
(envs[key] ??= {})[name] = value;
|
|
187
|
+
}
|
|
188
|
+
ctx.log(`Pulled ${name}`);
|
|
189
|
+
}
|
|
190
|
+
for (const [key, byWorktree] of Object.entries(envs)) {
|
|
191
|
+
if (Object.keys(byWorktree).length === 0) delete envs[key];
|
|
192
|
+
}
|
|
193
|
+
await Bun.write(valuesPath, Bun.YAML.stringify(values, null, 2));
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function edit(ctx: Context): Promise<number> {
|
|
198
|
+
const pulled = await pull(ctx);
|
|
199
|
+
if (pulled !== 0) return pulled;
|
|
200
|
+
const valuesPath = join(await findRoot(ctx.cwd), ".envs/values.yml");
|
|
201
|
+
const code = await ctx.openEditor(valuesPath);
|
|
202
|
+
if (code !== 0) return code;
|
|
203
|
+
return await push(ctx);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Runs a command; resolves with the process exit code. */
|
|
207
|
+
export async function run(
|
|
208
|
+
args: string[],
|
|
209
|
+
ctx: Context = defaultContext(),
|
|
210
|
+
): Promise<number> {
|
|
211
|
+
const [command = "help"] = args;
|
|
212
|
+
switch (command) {
|
|
213
|
+
case "help":
|
|
214
|
+
case "--help":
|
|
215
|
+
case "-h":
|
|
216
|
+
ctx.log(HELP);
|
|
217
|
+
return 0;
|
|
218
|
+
case "init":
|
|
219
|
+
return await init(ctx);
|
|
220
|
+
case "push":
|
|
221
|
+
return await push(ctx);
|
|
222
|
+
case "pull":
|
|
223
|
+
return await pull(ctx);
|
|
224
|
+
case "edit":
|
|
225
|
+
return await edit(ctx);
|
|
226
|
+
default:
|
|
227
|
+
ctx.error(`Unknown command: ${command}\n\n${HELP}`);
|
|
228
|
+
return 1;
|
|
229
|
+
}
|
|
230
|
+
}
|