Repository navigation
Preserve local environments during concurrent setup #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| { | ||
| "name": "cove", | ||
| "version": "1.0.0", | ||
| "version": "1.0.1", | ||
| "private": true, | ||
| "license": "MIT", | ||
| "type": "module", | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,47 @@ | ||
| import { existsSync, readFileSync, writeFileSync } from "node:fs"; | ||
| import { | ||
| closeSync, | ||
| fsyncSync, | ||
| lstatSync, | ||
| openSync, | ||
| readFileSync, | ||
| writeFileSync, | ||
| } from "node:fs"; | ||
| import { randomBytes } from "node:crypto"; | ||
| if (existsSync(".env")) console.log("Existing .env preserved."); | ||
| else { | ||
| writeFileSync( | ||
| ".env", | ||
| readFileSync(".env.example", "utf8").replace( | ||
| "replace-with-at-least-32-random-characters", | ||
| randomBytes(48).toString("base64url"), | ||
| ), | ||
| { mode: 0o600 }, | ||
| function createEnvironment() { | ||
| // Preserve existing entries, including dangling links, without opening them. | ||
| try { | ||
| lstatSync(".env"); | ||
| return false; | ||
| } catch (error) { | ||
| if (error.code !== "ENOENT") throw error; | ||
| } | ||
| const content = readFileSync(".env.example", "utf8").replace( | ||
| "replace-with-at-least-32-random-characters", | ||
| randomBytes(48).toString("base64url"), | ||
| ); | ||
| let descriptor; | ||
| try { | ||
| descriptor = openSync(".env", "wx", 0o600); | ||
| } catch (error) { | ||
| if (error.code === "EEXIST") return false; | ||
| throw error; | ||
| } | ||
| try { | ||
| writeFileSync(descriptor, content); | ||
| fsyncSync(descriptor); | ||
| } catch { | ||
| // A failed file stays available for inspection. Never unlink a shared name | ||
| // that another process might have replaced after this handle was opened. | ||
| throw Error( | ||
| "Could not finish .env. Inspect the local file before running setup again.", | ||
| ); | ||
| } finally { | ||
| closeSync(descriptor); | ||
| } | ||
| return true; | ||
| } | ||
| if (createEnvironment()) { | ||
| console.log( | ||
| "Created local .env with a random session secret. Do not commit it.", | ||
| ); | ||
| } | ||
| } else console.log("Existing .env preserved."); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| import { afterEach, expect, it } from "vitest"; | ||
| import fs from "node:fs"; | ||
| import os from "node:os"; | ||
| import path from "node:path"; | ||
| import { spawn, spawnSync } from "node:child_process"; | ||
| import { fileURLToPath, pathToFileURL } from "node:url"; | ||
|
|
||
| const script = fileURLToPath( | ||
| new URL("../scripts/setup-env.mjs", import.meta.url), | ||
| ); | ||
| const directories: string[] = []; | ||
| afterEach(() => { | ||
| for (const directory of directories.splice(0)) | ||
| fs.rmSync(directory, { recursive: true, force: true }); | ||
| }); | ||
| function fixture(template = true) { | ||
| const directory = fs.mkdtempSync(path.join(os.tmpdir(), "cove-env-")); | ||
| directories.push(directory); | ||
| if (template) | ||
| fs.writeFileSync( | ||
| path.join(directory, ".env.example"), | ||
| "SESSION_SECRET=replace-with-at-least-32-random-characters\nKEEP=value\n", | ||
| ); | ||
| return directory; | ||
| } | ||
| function run(directory: string, preload?: string) { | ||
| const args = preload | ||
| ? ["--import", pathToFileURL(preload).href, script] | ||
| : [script]; | ||
| return spawnSync(process.execPath, args, { | ||
| cwd: directory, | ||
| encoding: "utf8", | ||
| timeout: 5000, | ||
| }); | ||
| } | ||
|
|
||
| it("creates a secret once and preserves an existing environment without its template", () => { | ||
| const directory = fixture(); | ||
| const first = run(directory); | ||
| expect(first.status, first.stderr).toBe(0); | ||
| const file = path.join(directory, ".env"); | ||
| const bytes = fs.readFileSync(file, "utf8"); | ||
| expect(bytes).toMatch(/^SESSION_SECRET=[A-Za-z0-9_-]{64}\nKEEP=value\n$/); | ||
| expect(first.stdout).not.toContain(bytes.split("\n")[0].split("=")[1]); | ||
| if (process.platform !== "win32") | ||
| expect(fs.statSync(file).mode & 0o777).toBe(0o600); | ||
| fs.unlinkSync(path.join(directory, ".env.example")); | ||
| expect(run(directory).stdout).toContain("Existing .env preserved."); | ||
| expect(fs.readFileSync(file, "utf8")).toBe(bytes); | ||
| }); | ||
|
|
||
| it("preserves a file created between the initial check and exclusive creation", () => { | ||
| const directory = fixture(); | ||
| const preload = path.join(directory, "competing-writer.mjs"); | ||
| fs.writeFileSync( | ||
| preload, | ||
| ` | ||
| import fs from 'node:fs'; | ||
| import crypto from 'node:crypto'; | ||
| import { syncBuiltinESMExports } from 'node:module'; | ||
| const original = crypto.randomBytes; | ||
| crypto.randomBytes = (...args) => { fs.writeFileSync('.env', 'competing environment\\n'); return original(...args); }; | ||
| syncBuiltinESMExports(); | ||
| `, | ||
| ); | ||
| const result = run(directory, preload); | ||
| expect(result.status, result.stderr).toBe(0); | ||
| expect(result.stdout).toContain("Existing .env preserved."); | ||
| expect(fs.readFileSync(path.join(directory, ".env"), "utf8")).toBe( | ||
| "competing environment\n", | ||
| ); | ||
| }); | ||
|
|
||
| it("preserves linked and dangling entries without opening or changing their targets", (context) => { | ||
| const directory = fixture(false); | ||
| const target = path.join(directory, "target"); | ||
| const file = path.join(directory, ".env"); | ||
| try { | ||
| fs.symlinkSync(target, file, "file"); | ||
| } catch (error) { | ||
| if ((error as NodeJS.ErrnoException).code === "EPERM") { | ||
| context.skip(); | ||
| return; | ||
| } | ||
| throw error; | ||
| } | ||
| expect(run(directory).status).toBe(0); | ||
| expect(fs.lstatSync(file).isSymbolicLink()).toBe(true); | ||
| expect(fs.existsSync(target)).toBe(false); | ||
| fs.writeFileSync(target, "keep linked target"); | ||
|
agammann marked this conversation as resolved.
Dismissed
|
||
| expect(run(directory).status).toBe(0); | ||
| expect(fs.readFileSync(target, "utf8")).toBe("keep linked target"); | ||
| }); | ||
|
|
||
| it("does not create an empty environment when its template is missing", () => { | ||
| const directory = fixture(false); | ||
| expect(run(directory).status).toBe(1); | ||
| expect(fs.existsSync(path.join(directory, ".env"))).toBe(false); | ||
| }); | ||
|
|
||
| it("preserves an existing directory or junction at the environment name", () => { | ||
| const directory = fixture(false); | ||
| const target = path.join(directory, "linked-directory"); | ||
| fs.mkdirSync(target); | ||
| fs.writeFileSync(path.join(target, "keep.txt"), "keep directory contents"); | ||
| fs.symlinkSync( | ||
| target, | ||
| path.join(directory, ".env"), | ||
| process.platform === "win32" ? "junction" : "dir", | ||
| ); | ||
| expect(run(directory).status).toBe(0); | ||
| expect(fs.readFileSync(path.join(target, "keep.txt"), "utf8")).toBe( | ||
| "keep directory contents", | ||
| ); | ||
| }); | ||
|
|
||
| it("concurrent setup invocations produce one complete environment", async () => { | ||
| const directory = fixture(); | ||
| const results = await Promise.all( | ||
| Array.from( | ||
| { length: 8 }, | ||
| () => | ||
| new Promise<number | null>((resolve, reject) => { | ||
| const child = spawn(process.execPath, [script], { | ||
| cwd: directory, | ||
| stdio: "ignore", | ||
| }); | ||
| child.once("error", reject); | ||
| child.once("exit", resolve); | ||
| }), | ||
| ), | ||
| ); | ||
| expect(results).toEqual(Array(8).fill(0)); | ||
| expect(fs.readFileSync(path.join(directory, ".env"), "utf8")).toMatch( | ||
| /^SESSION_SECRET=[A-Za-z0-9_-]{64}\nKEEP=value\n$/, | ||
| ); | ||
| }); | ||
|
|
||
| it("a failed descriptor write never removes another writer's replacement", () => { | ||
| const directory = fixture(); | ||
| const preload = path.join(directory, "failed-writer.mjs"); | ||
| fs.writeFileSync( | ||
| preload, | ||
| ` | ||
| import fs from 'node:fs'; | ||
| import { syncBuiltinESMExports } from 'node:module'; | ||
| const write = fs.writeFileSync; | ||
| fs.writeFileSync = (target, ...args) => { | ||
| if (typeof target === 'number') { | ||
| fs.renameSync('.env', '.failed-creation'); | ||
| write('.env', 'replacement environment\\n'); | ||
| throw Error('Controlled write failure'); | ||
| } | ||
| return write(target, ...args); | ||
| }; | ||
| syncBuiltinESMExports(); | ||
| `, | ||
| ); | ||
| const result = run(directory, preload); | ||
| expect(result.status).toBe(1); | ||
| expect(result.stderr).toContain("Could not finish .env"); | ||
| expect(fs.readFileSync(path.join(directory, ".env"), "utf8")).toBe( | ||
| "replacement environment\n", | ||
| ); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.