Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NewProject.ts

179 lines6.2 KB

1/**
2 * NewProject - makes the folder for a project started from just a name:
3 * `<projects root>/<slug>` with a README, an icon, and a first commit.
4 *
5 * The icon lives at `assets/icon.svg`, a path ProjectFaviconResolver already
6 * checks after the usual web app icons. It travels with the repository, so
7 * every machine that clones the project shows the same icon.
8 *
9 * @module NewProject
10 */
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import * as PlatformError from "effect/PlatformError";
15​
16import { newProjectFolderName } from "@t3tools/shared/path";
17import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
18​
19// Tailwind 600 shades: dark enough for white initials on every hue.
20const ICON_BACKGROUNDS = [
21 "#dc2626",
22 "#ea580c",
23 "#d97706",
24 "#16a34a",
25 "#059669",
26 "#0d9488",
27 "#0891b2",
28 "#0284c7",
29 "#2563eb",
30 "#4f46e5",
31 "#7c3aed",
32 "#9333ea",
33 "#c026d3",
34 "#db2777",
35 "#e11d48",
36] as const;
37​
38const MAX_FOLDER_ATTEMPTS = 100;
39​
40function escapeXml(value: string): string {
41 return value
42 .replaceAll("&", "&amp;")
43 .replaceAll("<", "&lt;")
44 .replaceAll(">", "&gt;")
45 .replaceAll('"', "&quot;");
47​
48/** A rounded square with the name's initials, colored by a hash of the name. */
49function newProjectIconSvg(name: string): string {
50 const words = name.split(/[^\p{L}\p{N}]+/u).filter(Boolean);
51 const initials =
52 words
53 .slice(0, 2)
54 .map((word) => Array.from(word)[0] ?? "")
55 .join("")
56 .toUpperCase() ||
57 Array.from(name.trim())[0] ||
58 "?";
59 let hash = 0;
60 for (const char of name) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) >>> 0;
61 const background = ICON_BACKGROUNDS[hash % ICON_BACKGROUNDS.length];
62 return [
63 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">`,
64 ` <rect width="64" height="64" rx="14" fill="${background}"/>`,
65 ` <text x="32" y="32" dy="0.35em" text-anchor="middle" font-family="ui-sans-serif, system-ui, -apple-system, sans-serif" font-size="${initials.length > 1 ? 26 : 32}" font-weight="600" fill="#ffffff">${escapeXml(initials)}</text>`,
66 `</svg>`,
67 "",
68 ].join("\n");
70​
71function newProjectReadme(name: string): string {
72 return [
73 `<img src="assets/icon.svg" width="64" height="64" alt="">`,
74 "",
75 `# ${name}`,
76 "",
77 "Created in [T3 Code](https://t3.codes).",
78 "",
79 ].join("\n");
81​
82// Git's own identity message runs several lines; say what to do instead.
83// Otherwise its last line ("error: gpg failed to sign the data") says enough.
84function describeCommitFailure(stderr: string): string {
85 if (/identity unknown|tell me who you are|no (name|email) was given/i.test(stderr)) {
86 return "Git has no name or email on this machine. Set user.name and user.email, then commit.";
87 }
88 const lines = stderr
89 .split("\n")
90 .map((line) => line.trim())
91 .filter(Boolean);
92 return lines.at(-1) ?? "Git could not make the first commit.";
94​
95/**
96 * Claims a fresh folder for `name` under `root` (adding `-2`, `-3`, ... when
97 * the name is taken), writes the starter files, and makes the first commit.
98 * A failed commit (no Git identity, a signing prompt) keeps the folder and
99 * returns why, so the project still opens. Any other failure removes the
100 * folder it claimed.
101 */
102export const createNewProjectFolder = Effect.fn("NewProject.createNewProjectFolder")(
103 function* (input: { readonly root: string; readonly name: string }) {
104 const fileSystem = yield* FileSystem.FileSystem;
105 const path = yield* Path.Path;
106 const git = yield* GitVcsDriver.GitVcsDriver;
107​
108 yield* fileSystem.makeDirectory(input.root, { recursive: true });
109 // Created without `recursive`, so the create itself claims the folder and
110 // two requests for the same name never share one.
111 const folderName = newProjectFolderName(input.name);
112 let workspaceRoot: string | null = null;
113 for (let attempt = 1; workspaceRoot === null && attempt <= MAX_FOLDER_ATTEMPTS; attempt++) {
114 const candidate = path.join(
115 input.root,
116 attempt === 1 ? folderName : `${folderName}-${attempt}`,
117 );
118 const claimed = yield* fileSystem.makeDirectory(candidate).pipe(
119 Effect.as(true),
120 Effect.catchIf(
121 (error) => error.reason._tag === "AlreadyExists",
122 () => Effect.succeed(false),
123 ),
124 );
125 if (claimed) workspaceRoot = candidate;
126 }
127 if (workspaceRoot === null) {
128 return yield* PlatformError.systemError({
129 _tag: "AlreadyExists",
130 module: "FileSystem",
131 method: "makeDirectory",
132 description: `Every folder name for "${folderName}" is taken.`,
133 pathOrDescriptor: input.root,
134 });
135 }
136 const cwd = workspaceRoot;
137​
138 return yield* Effect.gen(function* () {
139 const branch =
140 (yield* git
141 .readConfigValue(cwd, "init.defaultBranch")
142 .pipe(Effect.orElseSucceed(() => null))) ?? "main";
143 yield* git.execute({
144 operation: "NewProject.init",
145 cwd,
146 args: ["init", `--initial-branch=${branch}`],
147 timeoutMs: 10_000,
148 });
149 yield* fileSystem.writeFileString(path.join(cwd, "README.md"), newProjectReadme(input.name));
150 yield* fileSystem.makeDirectory(path.join(cwd, "assets"));
151 yield* fileSystem.writeFileString(
152 path.join(cwd, "assets", "icon.svg"),
153 newProjectIconSvg(input.name),
154 );
155 // Named and forced so a global ignore rule (say `*.svg`) cannot drop one.
156 yield* git.execute({
157 operation: "NewProject.add",
158 cwd,
159 args: ["add", "--force", "--", "README.md", "assets/icon.svg"],
160 timeoutMs: 10_000,
161 });
162 const commitError = yield* git
163 .execute({
164 operation: "NewProject.commit",
165 cwd,
166 args: ["commit", "--message", "Initial commit"],
167 allowNonZeroExit: true,
168 timeoutMs: 30_000,
169 })
170 .pipe(
171 Effect.map((result) =>
172 result.exitCode === 0 ? undefined : describeCommitFailure(result.stderr),
173 ),
174 Effect.catch((error) => Effect.succeed(error.message)),
175 );
176 return { workspaceRoot: cwd, commitError };
177 }).pipe(Effect.onError(() => fileSystem.remove(cwd, { recursive: true }).pipe(Effect.ignore)));
178 },
179);