Open History to see the last commit
1/**
2 * Copy a `localSource` folder into a new container, so the agent works on the
3 * same files and the same git branch as on the host.
4 *
5 * The copy holds the files that git lists: tracked files with their
6 * uncommitted changes, and untracked files that `.gitignore` keeps. The
7 * history of the current branch goes in as a git bundle, so git works in the
8 * container, also when the folder is a git worktree (where `.git` is a file).
9 * The copy goes one way, once, when the container is created.
10 */
11import { randomUUID } from 'node:crypto'
12import { lstat, readFile, readlink, rm, stat } from 'node:fs/promises'
13import { tmpdir } from 'node:os'
14import path from 'node:path'
15import { hasGitDir, probeGit, runGit } from './sbx/materialize'
16import { tarStream } from './tar'
17import type { Stats } from 'node:fs'
18import type Dockerode from 'dockerode'
19import type { DockerHandle, DockerLogger } from './handle'
20
21/** File modes in the git index (`git ls-files -s`). */
22const EXECUTABLE = '100755'
23const SYMLINK = '120000'
24
25/**
26 * Where the history bundle waits in the container, relative to the work dir.
27 * It is in `.git`, so it never shows as an untracked file.
28 */
29const BUNDLE = '.git/tanstack-local-source.bundle'
30
31const GIT_NOT_ON_PATH =
32 'dockerSandbox: git is not on PATH. Install git to copy a localSource folder into the container.'
33
34const NO_GIT_IN_IMAGE =
35 'dockerSandbox: the container image has no git, so it cannot hold the history of a localSource folder. Use an image with git, such as node:24.'
36
37/** What {@link readLocalSource} found in the folder. */
38export type LocalSource = Awaited<ReturnType<typeof readLocalSource>>
39
40/**
41 * Check a localSource folder and list what to copy. This runs on the host
42 * before any container work, so a bad folder fails fast.
43 */
44export async function readLocalSource(sourcePath: string) {
45 // A relative path is relative to the process cwd, as in sbxSandbox.
46 const dir = path.resolve(sourcePath)
47 const isFolder = await stat(dir).then(
48 (info) => info.isDirectory(),
49 () => false,
50 )
51 if (!isFolder) {
52 throw new Error(
53 `dockerSandbox: the localSource path ${dir} is not a folder.`,
54 )
55 }
56 if (!(await hasGitDir(dir))) {
57 throw new Error(
58 `dockerSandbox: the localSource folder ${dir} is not a Git repository. dockerSandbox copies the files that git lists and the history of the current branch, so the folder must contain .git. Run \`git init\` in it, or pass the root folder of the repository.`,
59 )
60 }
61 // No output cap: a big repository lists many MiB of paths.
62 const listFiles = async (...args: Array<string>) => {
63 const output = await runGit(['ls-files', '-z', ...args], {
64 cwd: dir,
65 maxBuffer: Infinity,
66 })
67 return output.split('\0').filter(Boolean)
68 }
69 try {
70 const tracked = await listFiles('-s')
71 const untracked = await listFiles('--others', '--exclude-standard')
72 // Each path, with its mode in the git index. An untracked file has none.
73 const files: Map<string, string | undefined> = new Map()
74 for (const record of tracked) {
75 // A `-s` record is `<mode> <object> <stage>\t<path>`.
76 files.set(record.slice(record.indexOf('\t') + 1), record.slice(0, 6))
77 }
78 for (const file of untracked) files.set(file, undefined)
79 const [ref, head, autocrlf, shallow] = await Promise.all([
80 // No branch when HEAD is detached.
81 probeGit(['symbolic-ref', '-q', 'HEAD'], dir),
82 // No commit on an unborn branch.
83 probeGit(['rev-parse', '-q', '--verify', 'HEAD'], dir),
84 probeGit(['config', 'core.autocrlf'], dir),
85 probeGit(['rev-parse', '--is-shallow-repository'], dir),
86 ])
87 if (shallow === 'true') {
88 throw new Error(
89 `dockerSandbox: the localSource folder ${dir} is a shallow clone. dockerSandbox sends the history of the current branch as a git bundle, and a bundle needs the full history. Run \`git fetch --unshallow\` in it.`,
90 )
91 }
92 return { dir, files, ref, head, autocrlf }
93 } catch (error) {
94 if (isMissing(error)) throw new Error(GIT_NOT_ON_PATH)
95 throw error
96 }
97}
98
99/**
100 * Copy the folder into the container work dir and set up git there: the same
101 * branch at the same commit, so `git status` shows the uncommitted changes of
102 * the host. Staged changes show as unstaged. Call it for a new container only.
103 */
104export async function copyLocalSource(
105 source: LocalSource,
106 target: {
107 container: Dockerode.Container
108 handle: DockerHandle
109 logger?: DockerLogger
110 signal?: AbortSignal
111 },
112) {
113 const { container, handle, logger, signal } = target
114 const { ref, head } = source
115 const upload = (bundleFile?: string) =>
116 container.putArchive(
117 tarStream(archiveEntries(source, bundleFile, logger)),
118 {
119 path: handle.workspaceRoot,
120 ...(signal ? { abortSignal: signal } : {}),
121 },
122 )
123 // git init runs first, so an image without git fails before the upload.
124 await runInContainer(handle, initCommand(source))
125 // An unborn branch has no commits, so there is no history to send.
126 if (head === undefined) {
127 await upload()
128 return
129 }
130 // A temp file, not stdout, so the history never goes through a string.
131 const bundleFile = path.join(
132 tmpdir(),
133 `tanstack-local-source-${randomUUID()}.bundle`,
134 )
135 try {
136 await runGit(['bundle', 'create', bundleFile, ref ?? 'HEAD'], {
137 cwd: source.dir,
138 })
139 await upload(bundleFile)
140 await runInContainer(handle, historyCommand(ref, head))
141 } finally {
142 // A failed copy removes the container, and the bundle in it, so only the
143 // host file needs removing here.
144 await rm(bundleFile, { force: true })
145 }
146}
147
148/** `git init`, plus the line-ending setting and the branch of the host. */
149function initCommand(source: LocalSource) {
150 const steps = ['git init -q']
151 // core.autocrlf made the line endings of the copied files (Git for Windows
152 // sets it), so git in the container must read them the same way.
153 if (source.autocrlf !== undefined) {
154 steps.push(`git config core.autocrlf ${q(source.autocrlf)}`)
155 }
156 // HEAD names the branch from now on. An unborn branch stays unborn.
157 if (source.ref !== undefined) {
158 steps.push(`git symbolic-ref HEAD ${q(source.ref)}`)
159 }
160 return steps.join(' && ')
161}
162
163/**
164 * Fetch the bundle and point HEAD at the commit of the host. A mixed reset
165 * makes the index match HEAD and keeps the copied files as they are.
166 */
167function historyCommand(ref: string | undefined, head: string) {
168 // HEAD already names the branch (see initCommand), so the reset creates
169 // that branch at the commit.
170 if (ref !== undefined) {
171 return `git fetch -q ${BUNDLE} ${q(ref)} && git reset -q ${head} && rm -f ${BUNDLE}`
172 }
173 // A detached HEAD: the bundle holds HEAD only.
174 return `git fetch -q ${BUNDLE} HEAD && git update-ref --no-deref HEAD ${head} && git reset -q && rm -f ${BUNDLE}`
175}
176
177/** Run a command in the container work dir, and throw when it fails. */
178async function runInContainer(handle: DockerHandle, command: string) {
179 const result = await handle.process.exec(command)
180 // sh exits 127 when it cannot find a program, and that program is git here.
181 if (result.exitCode === 127) throw new Error(NO_GIT_IN_IMAGE)
182 if (result.exitCode !== 0) {
183 throw new Error(
184 `dockerSandbox: \`${command}\` failed in the container (exit ${result.exitCode}): ${result.stderr.trim()}`,
185 )
186 }
187}
188
189/**
190 * The archive: the bundle when there is one, then each listed file as it is
191 * on disk now. It reads one file at a time, so the repository is never all in
192 * memory.
193 */
194async function* archiveEntries(
195 source: LocalSource,
196 bundleFile: string | undefined,
197 logger: DockerLogger | undefined,
198) {
199 // ponytail: each file, and the bundle, is in memory whole while it streams,
200 // because tarStream takes Buffers. Stream from disk if huge files matter.
201 if (bundleFile !== undefined) {
202 yield { path: BUNDLE, mode: 0o644, data: await readFile(bundleFile) }
203 }
204 for (const [file, indexMode] of source.files) {
205 const fullPath = path.join(source.dir, file)
206 const stats = await lstat(fullPath).catch((error: unknown) => {
207 // git still lists a tracked file that is deleted in the working tree.
208 if (isMissing(error)) return undefined
209 throw error
210 })
211 if (stats === undefined) continue
212 if (stats.isDirectory()) {
213 // git lists a submodule, or a nested repository, as one folder.
214 logger?.warn(
215 `docker: localSource did not copy ${file}: submodules and nested repositories are not copied`,
216 { path: file },
217 )
218 continue
219 }
220 if (stats.isSymbolicLink()) {
221 const linkTarget = await readlink(fullPath)
222 // Git for Windows writes link targets with `\`. The container needs `/`.
223 yield {
224 path: file,
225 linkTarget:
226 process.platform === 'win32'
227 ? linkTarget.replaceAll('\\', '/')
228 : linkTarget,
229 }
230 continue
231 }
232 const data = await readFile(fullPath)
233 // Without symlink support (the Windows default), git checks a link out as
234 // a plain file that holds the link target.
235 if (indexMode === SYMLINK) yield { path: file, linkTarget: data.toString() }
236 else yield { path: file, mode: fileMode(indexMode, stats), data }
237 }
238}
239
240/**
241 * A tracked file gets its mode from the git index, so only the exec bit
242 * counts. An untracked file keeps its disk mode, except on Windows, where the
243 * disk has no exec bit.
244 */
245function fileMode(indexMode: string | undefined, stats: Stats) {
246 if (indexMode === EXECUTABLE) return 0o755
247 if (indexMode !== undefined || process.platform === 'win32') return 0o644
248 return stats.mode
249}
250
251/** POSIX single-quote escape, for a branch name or a config value in `sh -c`. */
252function q(value: string) {
253 return `'${value.replaceAll("'", `'\\''`)}'`
254}
255
256/** ENOENT: a program that is not on PATH, or a path that is not there. */
257function isMissing(error: unknown) {
258 return error instanceof Error && 'code' in error && error.code === 'ENOENT'
259}