Open History to see the last commit
1import {
2 executeAtomQuery,
3 runAtomCommand,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import type { EnvironmentId, ProjectCloneSnapshot, ProjectId } from "@t3tools/contracts";
7
8import { stackedThreadToast, toastManager } from "../components/ui/toast";
9import { appAtomRegistry } from "../rpc/atomRegistry";
10import { environmentProjectClonesAtom } from "../state/projectClones";
11import { projectEnvironment } from "../state/projects";
12import { sourceControlEnvironment } from "../state/sourceControl";
13
14export type CloneProtocol = "ssh" | "https";
15
16/** Matches the server's read cap: a larger file would arrive truncated. */
17export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
18
19const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
20const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
21const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
22
23function parseCloneUrl(
24 url: string,
25): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
26 const trimmed = url.trim();
27 const ssh = SSH_URL.exec(trimmed);
28 if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
29 const https = HTTPS_URL.exec(trimmed);
30 if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
31 const scp = SCP_LIKE_URL.exec(trimmed);
32 if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
33 return null;
34}
35
36export function cloneUrlProtocol(url: string): CloneProtocol | null {
37 return parseCloneUrl(url)?.protocol ?? null;
38}
39
40/**
41 * Rewrites a clone URL to the other protocol, because the target machine may
42 * only have SSH keys or only an HTTPS credential helper. Returns null when the
43 * URL cannot be rewritten safely, such as a custom port.
44 */
45export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
46 const parsed = parseCloneUrl(url);
47 if (!parsed) return null;
48 if (parsed.protocol === protocol) return url.trim();
49 if (parsed.customPort) return null;
50 return protocol === "ssh"
51 ? `git@${parsed.host}:${parsed.path}`
52 : `https://${parsed.host}/${parsed.path}`;
53}
54
55const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
56
57/** Env files are the ignored files people almost always want on a new machine. */
58export function isDefaultCopiedFile(path: string): boolean {
59 const name = path.split("/").at(-1) ?? path;
60 return DEFAULT_COPIED_FILE_NAME.test(name);
61}
62
63export interface AddProjectToMachineInput {
64 readonly source: { readonly environmentId: EnvironmentId; readonly cwd: string };
65 /** Where the source project sits below its repository root, or "". */
66 readonly subdirectory: string;
67 readonly target: { readonly environmentId: EnvironmentId; readonly label: string };
68 readonly projectId: ProjectId;
69 readonly title: string;
70 readonly remoteUrl: string;
71 readonly destinationPath: string;
72 readonly files: ReadonlyArray<string>;
73}
74
75function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {
76 const error = squashAtomCommandFailure(result);
77 return error instanceof Error ? error.message : "An error occurred.";
78}
79
80/**
81 * Resolves when the clone finishes, or null once it is removed. A failed or
82 * cancelled clone keeps waiting, since its toast offers a retry.
83 */
84function waitForClone(environmentId: EnvironmentId, projectId: ProjectId) {
85 return new Promise<ProjectCloneSnapshot | null>((resolve) => {
86 const atom = environmentProjectClonesAtom(environmentId);
87 let seen = false;
88 let settled = false;
89 let unsubscribe: (() => void) | null = null;
90 const check = (clones: ReadonlyArray<ProjectCloneSnapshot>) => {
91 if (settled) return;
92 const clone = clones.find((candidate) => candidate.projectId === projectId);
93 if (clone) seen = true;
94 const result = clone?.phase === "done" ? clone : !clone && seen ? null : undefined;
95 if (result === undefined) return;
96 settled = true;
97 unsubscribe?.();
98 resolve(result);
99 };
100 unsubscribe = appAtomRegistry.subscribe(atom, check);
101 check(appAtomRegistry.get(atom));
102 });
103}
104
105/**
106 * Clones a project onto another machine, then copies the chosen ignored files
107 * from the source. The client relays the files because the two servers never
108 * talk to each other. Resolves once the clone starts; the clone toast shows
109 * progress and a second toast reports the copied files.
110 */
111export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<void> {
112 // Read first, so the copy reflects the files as they were when the user asked.
113 const reads = await Promise.all(
114 input.files.map(async (relativePath) => {
115 const result = await executeAtomQuery(
116 appAtomRegistry,
117 projectEnvironment.readFile({
118 environmentId: input.source.environmentId,
119 input: { cwd: input.source.cwd, relativePath },
120 }),
121 { label: "Read file to copy", reportFailure: false, refresh: true },
122 );
123 if (result._tag === "Failure") return { relativePath, error: failureMessage(result) };
124 if (result.value.truncated) return { relativePath, error: "Too large to copy." };
125 return { relativePath, contents: result.value.contents };
126 }),
127 );
128
129 const started = await runAtomCommand(
130 appAtomRegistry,
131 sourceControlEnvironment.startProjectClone,
132 {
133 environmentId: input.target.environmentId,
134 input: {
135 projectId: input.projectId,
136 title: input.title,
137 createdAt: new Date().toISOString(),
138 remoteUrl: input.remoteUrl,
139 destinationPath: input.destinationPath,
140 },
141 },
142 { label: "Add project to machine", reportFailure: false },
143 );
144 if (started._tag === "Failure") throw new Error(failureMessage(started));
145 if (input.files.length === 0) return;
146
147 void (async () => {
148 const clone = await waitForClone(input.target.environmentId, input.projectId);
149 if (!clone) return;
150 const failed: Array<string> = [];
151 let copied = 0;
152 for (const read of reads) {
153 if (!("contents" in read)) {
154 failed.push(`${read.relativePath}: ${read.error}`);
155 continue;
156 }
157 const written = await runAtomCommand(
158 appAtomRegistry,
159 projectEnvironment.writeFile,
160 {
161 environmentId: input.target.environmentId,
162 input: {
163 cwd: started.value.cwd,
164 relativePath: input.subdirectory
165 ? `${input.subdirectory}/${read.relativePath}`
166 : read.relativePath,
167 contents: read.contents,
168 },
169 },
170 { label: "Copy file to machine", reportFailure: false },
171 );
172 if (written._tag === "Failure")
173 failed.push(`${read.relativePath}: ${failureMessage(written)}`);
174 else copied += 1;
175 }
176 const noun = (count: number) => (count === 1 ? "file" : "files");
177 toastManager.add(
178 stackedThreadToast(
179 failed.length === 0
180 ? {
181 type: "success",
182 title: `Copied ${copied} ${noun(copied)} to ${input.target.label}`,
183 description: reads.map((read) => read.relativePath).join(", "),
184 }
185 : {
186 type: "error",
187 title: `Could not copy ${failed.length} ${noun(failed.length)} to ${input.target.label}`,
188 description: failed.join("\n"),
189 },
190 ),
191 );
192 })();
193}