Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
2,254 linesCodeBlameRaw
1//! Builds one commit of a repository and hands the result to Cloudflare, as
2//! a preview of a pull request or as the repository's production.
3//!
4//! The sandbox never holds a Cloudflare credential that could touch anything
5//! else. The deployments service opens an upload for exactly the files
6//! this build produced and gives back a key that can only upload those;
7//! the sandbox uploads them with it, and sends the Worker's code to the
8//! service, which puts the app in place.
9//!
10//! What gets built:
11//!
12//! - A Workers project (a `wrangler.jsonc`, `wrangler.json` or
13//! `wrangler.toml`): bundled by `wrangler deploy --dry-run`, with its
14//! static assets, compatibility settings and `vars`. Other bindings (D1,
15//! KV, R2, Durable Objects…) are not provisioned yet; the deployment says
16//! which were left out.
17//! - A framework g1t knows (deploy/frameworks.rs: Vite, Astro, Next.js,
18//! SvelteKit, Nuxt, Hugo, Jekyll and the rest), found by the package's
19//! dependencies and config files: built with its own command and served
20//! from the folder it writes. A Cloudflare adapter's Worker (Astro's
21//! `dist/_worker.js`, SvelteKit's `.svelte-kit/cloudflare/_worker.js`) is
22//! bundled as a Workers project's is, without a Wrangler config of its
23//! own. A framework set up to need a server fails before anything is
24//! installed, saying what to change.
25//! - A container (deploy/container.rs): a project with a `Dockerfile` (or
26//! `Containerfile`, or the path it chose) and no framework that builds a
27//! static site or a Worker, a framework set up to need a server, or a
28//! Node.js, Python, Go, Ruby or PHP server, for which g1t writes a
29//! Dockerfile and shows it in the log. The image is built with Docker
30//! and pushed to Cloudflare's registry with a push-only login the
31//! deployments service gives this build alone, for minutes (the
32//! `registry` step); the service runs it.
33//! - Anything else: a static site. Its `build` script runs, and the first
34//! of `dist`, `build`, `out`, `public`, `_site` or `.output/public` that
35//! exists is served, or the repository itself if it has an `index.html`.
36//!
37//! The project's own **Build as** (`BUILD_AS`: auto, static, workers or
38//! docker), **Dockerfile** (`DOCKERFILE`), **Build command** and **Output
39//! directory** win over what is detected.
40//!
41//! Configuration comes from the environment:
42//!
43//! - `G1T_API`, `DEPLOY_ID`, `DEPLOY_TOKEN`: where and how to report.
44//! - `GIT_REMOTE`, `GIT_COMMIT`, `G1T_USER`, `G1T_TOKEN`: what to check out.
45//! - `ROOT_DIR`: where in the repository the project lives; empty for all
46//! of it. Everything below is relative to it.
47//! - `BUILD_COMMAND`, `OUTPUT_DIR`: the project's own choices, if any.
48//! - `BUILD_ENV`, `BUILD_SECRETS`: JSON objects of the repository's
49//! variables and secrets for deploy builds. Both are set for the build;
50//! secrets' values are redacted from its log.
51//!
52//! From a workflow step, `g1t-runner deploy` runs the same build in the
53//! job's own checkout: without `GIT_REMOTE` nothing is cloned, and the
54//! project is the current directory (`ROOT_DIR` below it). The build's id
55//! and token come from `POST /repos/{owner}/{repo}/deployments/builds`,
56//! which the `g1t/deploy` action calls (actions/deploy). Its output goes
57//! to the step's log as well as the deployment's. `g1t-runner detect`
58//! says what the build would find, as `key=value` lines for
59//! `$GITHUB_OUTPUT`, without building anything.
60
61use std::collections::{BTreeMap, BTreeSet};
62use std::path::{Path, PathBuf};
63use std::time::Instant;
64
65use anyhow::{Context, Result, bail};
66use base64::Engine;
67use base64::engine::general_purpose::STANDARD;
68use serde::{Deserialize, Serialize};
69use serde_json::{Value, json};
70use sha2::{Digest, Sha256};
71
72use crate::checks::{redact, run_command};
73use crate::{WORKDIR, auth_option, env, git};
74
75mod container;
76mod frameworks;
77
78use container::BuildAs;
79use frameworks::{Adapter, Framework};
80
81/// Where `wrangler deploy --dry-run` writes the bundle in a sandbox.
82const BUNDLE_DIR: &str = "/work/g1t-bundle";
83/// Cloudflare's limits on a Worker's static assets.
84const MAX_FILES: usize = 20_000;
85const MAX_FILE_BYTES: u64 = 25 * 1024 * 1024;
86/// How much of the build's output is kept for the deployment's log.
87const MAX_LOG_CHARS: usize = 20_000;
88/// Directories a static build usually writes to, in the order they are tried.
89const OUTPUT_DIRS: [&str; 6] = ["dist", "build", "out", "public", "_site", ".output/public"];
90/// Bindings a Workers project may declare that are not provisioned yet.
91const UNSUPPORTED_BINDINGS: [&str; 10] = [
92 "kv_namespaces",
93 "d1_databases",
94 "r2_buckets",
95 "durable_objects",
96 "services",
97 "queues",
98 "vectorize",
99 "hyperdrive",
100 "ai",
101 "workflows",
102];
103
104struct Reporter {
105 base: String,
106 token: String,
107}
108
109impl Reporter {
110 fn send(&self, step: &str, mut body: Value) -> Result<Value> {
111 body["token"] = self.token.clone().into();
112 match ureq::post(&format!("{}/{step}", self.base)).send_json(body) {
113 Ok(response) => Ok(response.into_json().unwrap_or(Value::Null)),
114 // A refusal (409 `not_enabled`, say) still says why in its
115 // body, which the step reads: ureq makes any status over 399
116 // an error.
117 Err(ureq::Error::Status(status, response)) => match response.into_json::<Value>() {
118 Ok(answer) if answer.get("ok").is_some() => Ok(answer),
119 _ => bail!("could not report `{step}` to g1t: status code {status}"),
120 },
121 Err(error) => Err(error).with_context(|| format!("could not report `{step}` to g1t")),
122 }
123 }
124}
125
126/// The build's log, kept to its end; also printed, in a workflow step.
127#[derive(Default)]
128struct Log {
129 text: String,
130 /// Each line to standard output as well, redacted.
131 echo: Option<Vec<String>>,
132}
133
134impl Log {
135 fn line(&mut self, line: &str) {
136 self.text.push_str(line);
137 self.text.push('\n');
138 if let Some(secrets) = &self.echo {
139 println!("{}", redact(line, secrets));
140 }
141 }
142
143 fn tail(&self) -> String {
144 let length = self.text.chars().count();
145 if length <= MAX_LOG_CHARS {
146 return self.text.clone();
147 }
148 let kept: String = self.text.chars().skip(length - MAX_LOG_CHARS).collect();
149 format!("… (earlier output not shown)\n{kept}")
150 }
151}
152
153/// Runs a command in the checkout, logging it; fails if it fails.
154fn step(log: &mut Log, command: &str, secrets: &[String]) -> Result<()> {
155 log.line(&format!("$ {command}"));
156 let result = run_command(command, &project_dir(), secrets);
157 if !result.output_text().is_empty() {
158 log.line(result.output_text());
159 }
160 if !result.passed {
161 bail!("`{command}` failed");
162 }
163 Ok(())
164}
165
166/// A Workers project's settings, from whichever config file it has.
167#[derive(Debug, Default, Deserialize)]
168struct WranglerConfig {
169 main: Option<String>,
170 compatibility_date: Option<String>,
171 #[serde(default)]
172 compatibility_flags: Vec<String>,
173 assets: Option<AssetsConfig>,
174 #[serde(default)]
175 vars: BTreeMap<String, Value>,
176 #[serde(flatten)]
177 rest: BTreeMap<String, Value>,
178}
179
180#[derive(Debug, Default, Deserialize)]
181struct AssetsConfig {
182 directory: Option<String>,
183 binding: Option<String>,
184 html_handling: Option<String>,
185 not_found_handling: Option<String>,
186}
187
188/// JSON with comments and trailing commas, as `wrangler.jsonc` allows.
189fn strip_jsonc(text: &str) -> String {
190 let mut out = String::with_capacity(text.len());
191 let mut chars = text.chars().peekable();
192 let mut in_string = false;
193 while let Some(c) = chars.next() {
194 if in_string {
195 out.push(c);
196 if c == '\\' {
197 if let Some(next) = chars.next() {
198 out.push(next);
199 }
200 } else if c == '"' {
201 in_string = false;
202 }
203 continue;
204 }
205 match (c, chars.peek()) {
206 ('"', _) => {
207 in_string = true;
208 out.push(c);
209 }
210 ('/', Some('/')) => {
211 for c in chars.by_ref() {
212 if c == '\n' {
213 out.push('\n');
214 break;
215 }
216 }
217 }
218 ('/', Some('*')) => {
219 chars.next();
220 let mut last = ' ';
221 for c in chars.by_ref() {
222 if last == '*' && c == '/' {
223 break;
224 }
225 last = c;
226 }
227 }
228 _ => out.push(c),
229 }
230 }
231 // Trailing commas before a closing bracket.
232 let mut cleaned = String::with_capacity(out.len());
233 let chars: Vec<char> = out.chars().collect();
234 let mut in_string = false;
235 let mut i = 0;
236 while i < chars.len() {
237 let c = chars[i];
238 if c == '"' && (i == 0 || chars[i - 1] != '\\') {
239 in_string = !in_string;
240 }
241 if c == ',' && !in_string {
242 let next = chars[i + 1..].iter().find(|c| !c.is_whitespace());
243 if matches!(next, Some('}') | Some(']')) {
244 i += 1;
245 continue;
246 }
247 }
248 cleaned.push(c);
249 i += 1;
250 }
251 cleaned
252}
253
254fn read_wrangler(dir: &Path) -> Result<Option<WranglerConfig>> {
255 for name in ["wrangler.jsonc", "wrangler.json"] {
256 let path = dir.join(name);
257 if path.exists() {
258 let text = std::fs::read_to_string(&path)?;
259 return Ok(Some(
260 serde_json::from_str(&strip_jsonc(&text)).with_context(|| format!("could not read {name}"))?,
261 ));
262 }
263 }
264 let path = dir.join("wrangler.toml");
265 if path.exists() {
266 let text = std::fs::read_to_string(&path)?;
267 return Ok(Some(toml::from_str(&text).context("could not read wrangler.toml")?));
268 }
269 Ok(None)
270}
271
272/// How to install the project's dependencies, judged by its lockfile.
273fn install_command(dir: &Path) -> Option<&'static str> {
274 if !dir.join("package.json").exists() {
275 return None;
276 }
277 Some(if dir.join("pnpm-lock.yaml").exists() {
278 "corepack enable && pnpm install --frozen-lockfile"
279 } else if dir.join("yarn.lock").exists() {
280 "corepack enable && yarn install"
281 } else if dir.join("bun.lockb").exists() || dir.join("bun.lock").exists() {
282 "npx --yes bun install"
283 } else if dir.join("package-lock.json").exists() {
284 "npm ci"
285 } else {
286 "npm install"
287 })
288}
289
290fn has_build_script(dir: &Path) -> bool {
291 std::fs::read_to_string(dir.join("package.json"))
292 .ok()
293 .and_then(|text| serde_json::from_str::<Value>(&text).ok())
294 .is_some_and(|package| package["scripts"]["build"].is_string())
295}
296
297/// One file of the site, as Cloudflare's asset upload names it.
298struct Asset {
299 path: String,
300 hash: String,
301 size: u64,
302 file: PathBuf,
303}
304
305fn content_type(path: &str) -> &'static str {
306 let extension = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
307 match extension.as_str() {
308 "html" | "htm" => "text/html",
309 "css" => "text/css",
310 "js" | "mjs" => "application/javascript",
311 "json" | "map" => "application/json",
312 "svg" => "image/svg+xml",
313 "png" => "image/png",
314 "jpg" | "jpeg" => "image/jpeg",
315 "gif" => "image/gif",
316 "webp" => "image/webp",
317 "avif" => "image/avif",
318 "ico" => "image/x-icon",
319 "woff" => "font/woff",
320 "woff2" => "font/woff2",
321 "ttf" => "font/ttf",
322 "txt" => "text/plain",
323 "xml" => "application/xml",
324 "wasm" => "application/wasm",
325 "pdf" => "application/pdf",
326 "mp4" => "video/mp4",
327 "webm" => "video/webm",
328 _ => "application/octet-stream",
329 }
330}
331
332/// What is never served from the top of a site: a Pages-style Worker
333/// (`_worker.js`, its server code, which a Cloudflare adapter writes beside
334/// the site's files), `_routes.json`, and `.assetsignore`, with each name
335/// that `.assetsignore` lists, as wrangler leaves them out.
336fn ignored_at_root(root: &Path) -> BTreeSet<String> {
337 let mut ignored: BTreeSet<String> = ["_worker.js", "_routes.json", ".assetsignore"].map(str::to_owned).into();
338 if let Ok(text) = std::fs::read_to_string(root.join(".assetsignore")) {
339 ignored.extend(
340 text.lines()
341 .map(|line| line.trim().trim_matches('/'))
342 .filter(|line| !line.is_empty() && !line.starts_with('#') && !line.contains(['*', '/', '!']))
343 .map(str::to_owned),
344 );
345 }
346 ignored
347}
348
349/// Every file of the site at `root`, but for what never belongs in one.
350fn collect_site(root: &Path, skip_project: bool) -> Result<Vec<Asset>> {
351 let mut assets = Vec::new();
352 collect(root, root, skip_project, &ignored_at_root(root), &mut assets)?;
353 Ok(assets)
354}
355
356fn collect(root: &Path, dir: &Path, skip_project: bool, ignored: &BTreeSet<String>, out: &mut Vec<Asset>) -> Result<()> {
357 for entry in std::fs::read_dir(dir)? {
358 let entry = entry?;
359 let name = entry.file_name().to_string_lossy().into_owned();
360 let path = entry.path();
361 let kind = entry.file_type()?;
362 if name == ".git" || (skip_project && (name == "node_modules" || name.starts_with(".g1t"))) {
363 continue;
364 }
365 if dir == root && ignored.contains(&name) {
366 continue;
367 }
368 if kind.is_dir() {
369 collect(root, &path, skip_project, ignored, out)?;
370 continue;
371 }
372 if !kind.is_file() || name == "_headers" || name == "_redirects" {
373 continue;
374 }
375 let size = entry.metadata()?.len();
376 let relative = path
377 .strip_prefix(root)?
378 .to_string_lossy()
379 .replace('\\', "/");
380 if size > MAX_FILE_BYTES {
381 bail!("{relative} is larger than Cloudflare's 25 MiB limit for one file");
382 }
383 let bytes = std::fs::read(&path)?;
384 let digest = hex::encode(Sha256::digest(&bytes));
385 out.push(Asset {
386 path: format!("/{relative}"),
387 hash: digest[..32].to_owned(),
388 size,
389 file: path,
390 });
391 if out.len() > MAX_FILES {
392 bail!("the site has more than {MAX_FILES} files, Cloudflare's limit");
393 }
394 }
395 Ok(())
396}
397
398/// The upload, as the API sends it: `snake_case`, or `uploadUrl` from
399/// before its bodies were.
400#[derive(Deserialize)]
401struct UploadSession {
402 jwt: String,
403 #[serde(default)]
404 buckets: Vec<Vec<String>>,
405 #[serde(alias = "uploadUrl")]
406 upload_url: String,
407}
408
409/// Sends one bucket of files with the upload's key. The last bucket's
410/// answer carries the key that completes the upload.
411fn upload_bucket(session: &UploadSession, bucket: &[String], by_hash: &BTreeMap<&str, &Asset>) -> Result<Option<String>> {
412 let boundary = format!("g1t-{}", hex::encode(Sha256::digest(bucket.join(",").as_bytes()))[..24].to_owned());
413 let mut body: Vec<u8> = Vec::new();
414 for hash in bucket {
415 let asset = by_hash
416 .get(hash.as_str())
417 .with_context(|| format!("Cloudflare asked for a file this build does not have ({hash})"))?;
418 let bytes = std::fs::read(&asset.file)?;
419 body.extend_from_slice(
420 format!(
421 "--{boundary}\r\nContent-Disposition: form-data; name=\"{hash}\"; filename=\"{hash}\"\r\nContent-Type: {}\r\n\r\n",
422 content_type(&asset.path)
423 )
424 .as_bytes(),
425 );
426 body.extend_from_slice(STANDARD.encode(bytes).as_bytes());
427 body.extend_from_slice(b"\r\n");
428 }
429 body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
430 let response = ureq::post(&session.upload_url)
431 .set("authorization", &format!("Bearer {}", session.jwt))
432 .set("content-type", &format!("multipart/form-data; boundary={boundary}"))
433 .send_bytes(&body);
434 let response = match response {
435 Ok(response) => response,
436 Err(ureq::Error::Status(code, response)) => {
437 bail!("Cloudflare refused the upload ({code}): {}", response.into_string().unwrap_or_default())
438 }
439 Err(error) => bail!("could not upload to Cloudflare: {error}"),
440 };
441 let answer: Value = response.into_json().unwrap_or(Value::Null);
442 Ok(answer["result"]["jwt"].as_str().map(str::to_owned))
443}
444
445#[derive(Serialize)]
446#[serde(rename_all = "camelCase")]
447struct Module {
448 name: String,
449 content_base64: String,
450 content_type: String,
451}
452
453/// The bundle `wrangler deploy --dry-run` wrote, main module first.
454fn bundle_modules(main: &str, bundle: &Path) -> Result<(String, Vec<Module>)> {
455 let stem = Path::new(main)
456 .file_stem()
457 .map(|stem| stem.to_string_lossy().into_owned())
458 .unwrap_or_else(|| "index".to_owned());
459 let mut modules = Vec::new();
460 let mut files = Vec::new();
461 collect_files(bundle, &mut files)?;
462 for file in files {
463 let name = file
464 .strip_prefix(bundle)?
465 .to_string_lossy()
466 .replace('\\', "/");
467 let kind = match name.rsplit('.').next().unwrap_or("") {
468 "js" | "mjs" => "application/javascript+module",
469 "wasm" => "application/wasm",
470 "map" | "md" => continue,
471 _ => "text/plain",
472 };
473 modules.push(Module {
474 content_base64: STANDARD.encode(std::fs::read(&file)?),
475 content_type: kind.to_owned(),
476 name,
477 });
478 }
479 let main_name = modules
480 .iter()
481 .map(|module| module.name.clone())
482 .find(|name| *name == format!("{stem}.js") || *name == format!("{stem}.mjs"))
483 .or_else(|| {
484 modules
485 .iter()
486 .find(|module| module.content_type == "application/javascript+module")
487 .map(|module| module.name.clone())
488 })
489 .context("wrangler wrote no JavaScript module")?;
490 Ok((main_name, modules))
491}
492
493fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
494 for entry in std::fs::read_dir(dir)? {
495 let entry = entry?;
496 if entry.file_type()?.is_dir() {
497 collect_files(&entry.path(), out)?;
498 } else {
499 out.push(entry.path());
500 }
501 }
502 Ok(())
503}
504
505/// What a Workers config asks for that g1t.page does not provision, said
506/// as the deployment's warnings: bindings it runs without, and scheduled
507/// (`triggers.crons`) runs that never fire.
508fn config_warnings(config: &WranglerConfig) -> Vec<String> {
509 // An empty list, as a config a framework's build writes has for each
510 // kind of binding (`"d1_databases": []`), declares nothing.
511 fn declares(value: &Value) -> bool {
512 match value {
513 Value::Null => false,
514 Value::Array(items) => !items.is_empty(),
515 Value::Object(fields) => fields.values().any(declares),
516 _ => true,
517 }
518 }
519 let mut warnings = Vec::new();
520 for binding in UNSUPPORTED_BINDINGS {
521 if config.rest.get(binding).is_some_and(declares) {
522 warnings.push(format!("`{binding}` is not provisioned on g1t.page yet, so the app runs without it."));
523 }
524 }
525 let crons = config
526 .rest
527 .get("triggers")
528 .and_then(|triggers| triggers.get("crons"))
529 .and_then(Value::as_array)
530 .map_or(0, |crons| crons.iter().filter(|cron| cron.as_str().is_some_and(|c| !c.trim().is_empty())).count());
531 if crons > 0 {
532 let schedules = if crons == 1 { "schedule" } else { "schedules" };
533 warnings.push(format!(
534 "`triggers.crons` ({crons} {schedules}) is not set up on g1t.page yet, so the Worker's `scheduled` handler never runs."
535 ));
536 }
537 warnings
538}
539
540/// What was built: the Worker's code and settings, and where its site is.
541struct Built {
542 worker: Value,
543 assets_dir: Option<PathBuf>,
544 warnings: Vec<String>,
545 /// What kind of project it was found to be, for its settings page:
546 /// `workers`, `static` (a build's output), `html` (the files as they
547 /// are) or `container`.
548 detected: &'static str,
549 /// The framework it was found to be built with, if any (`astro`…), or
550 /// for a container what it was built from (`dockerfile`, `flask`…).
551 framework: Option<&'static str>,
552 /// For a container: the image pushed, its digest, port and size.
553 container: Option<Value>,
554}
555
556/// What a project without a Workers config is: a site it built, or its own
557/// files served as they are.
558fn static_kind(project: &Path, assets_dir: &Path, built: bool) -> &'static str {
559 if !built && assets_dir == project { "html" } else { "static" }
560}
561
562/// The command that bundles a Workers project, without deploying it,
563/// into `bundle` when given, by the config at `config` when given.
564fn wrangler_build(bundle: Option<&Path>, config: Option<&Path>) -> String {
565 let mut command = "npx --yes wrangler@4 deploy --dry-run".to_owned();
566 if let Some(config) = config {
567 command.push_str(&format!(" --config {}", config.display()));
568 }
569 if let Some(bundle) = bundle {
570 command.push_str(&format!(" --outdir {}", bundle.display()));
571 }
572 command
573}
574
575/// The config a framework's build wrote for wrangler, which wrangler reads
576/// in place of the project's own (`.wrangler/deploy/config.json`, as
577/// `@cloudflare/vite-plugin` writes it), with the folder its paths are
578/// relative to.
579fn redirected_config(dir: &Path) -> Result<Option<(WranglerConfig, PathBuf)>> {
580 let pointer = dir.join(".wrangler/deploy/config.json");
581 let Ok(text) = std::fs::read_to_string(&pointer) else { return Ok(None) };
582 let Some(path) = serde_json::from_str::<Value>(&text).ok().and_then(|v| v["configPath"].as_str().map(str::to_owned)) else {
583 return Ok(None);
584 };
585 let path = dir.join(".wrangler/deploy").join(path);
586 let path = canonical(&path).unwrap_or(path);
587 let text = std::fs::read_to_string(&path).with_context(|| format!("could not read {}", path.display()))?;
588 let config = serde_json::from_str(&strip_jsonc(&text)).with_context(|| format!("could not read {}", path.display()))?;
589 Ok(Some((config, path.parent().map_or_else(|| dir.to_path_buf(), Path::to_path_buf))))
590}
591
592/// The path, resolved, as a plain path. On Windows, `canonicalize` gives a
593/// verbatim one (`\\?\C:\…`), in which `/` and `..` are not read as
594/// separators or as the folder above: a config's `"directory": "../client"`
595/// joined to it would name no folder. A drive path loses the prefix; a
596/// network path keeps it, as it cannot do without.
597fn canonical(path: &Path) -> std::io::Result<PathBuf> {
598 let path = path.canonicalize()?;
599 #[cfg(windows)]
600 {
601 let text = path.to_string_lossy();
602 if let Some(rest) = text.strip_prefix(r"\\?\") {
603 if !rest.starts_with(r"UNC\") {
604 return Ok(PathBuf::from(rest));
605 }
606 }
607 }
608 Ok(path)
609}
610
611/// The entry of the Worker a framework's adapter wrote, once it has built:
612/// the file, or a directory's `index.js`.
613fn adapter_entry(dir: &Path, adapter: &Adapter) -> Option<PathBuf> {
614 let entry = dir.join(adapter.entry);
615 if entry.is_file() {
616 return Some(entry);
617 }
618 ["index.js", "index.mjs"].iter().map(|name| entry.join(name)).find(|index| index.is_file())
619}
620
621/// The first of the usual output directories a static build wrote (or the
622/// project's own `index.html`), relative to the project: `.` for itself.
623fn find_output(dir: &Path) -> Option<String> {
624 OUTPUT_DIRS
625 .iter()
626 .find(|name| {
627 let path = dir.join(name);
628 path.join("index.html").exists() || (path.is_dir() && **name != "public")
629 })
630 .map(|name| (*name).to_owned())
631 .or_else(|| dir.join("index.html").exists().then(|| ".".to_owned()))
632}
633
634/// What a build of the project at `dir` does, found before anything runs:
635/// what it is, how its dependencies are installed, what builds it, and
636/// where what it serves is. For a site with a build of its own, the output
637/// directory may only exist once it has run; then `output_dir` is `None`
638/// unless one was chosen or the framework says where it writes.
639#[derive(Debug, PartialEq, Eq)]
640pub(crate) struct Detected {
641 /// `workers`, `static`, `html`, `container`, or `none` when there is
642 /// nothing to serve.
643 pub kind: &'static str,
644 /// The framework it is built with, if g1t knows it.
645 pub framework: Option<Framework>,
646 pub install: Option<String>,
647 pub build: Option<String>,
648 pub output_dir: Option<String>,
649 /// Why it cannot be served as it is set up, and what to change: the
650 /// kind is then `none`.
651 pub problem: Option<String>,
652 /// What runs before wrangler bundles a Workers project; for anything
653 /// else, `build`.
654 pre_build: Option<String>,
655 /// For a container: its Dockerfile, or the one g1t writes.
656 pub container: Option<ContainerBuild>,
657 /// What it would be served as without its Dockerfile, when it is a
658 /// container only for having one: built so while g1t.page runs no
659 /// containers (`not_enabled` from the registry step).
660 fallback: Option<Box<Detected>>,
661}
662
663/// How a container is built.
664#[derive(Debug, Clone, PartialEq, Eq)]
665pub(crate) struct ContainerBuild {
666 /// The project's own Dockerfile, relative to the project; none when
667 /// g1t writes one.
668 pub dockerfile: Option<String>,
669 /// The Dockerfile g1t writes, for a server it recognises.
670 pub generated: Option<container::Server>,
671 /// What it listens on: its Dockerfile's `EXPOSE`, else 8080. `PORT`
672 /// is set to it.
673 pub port: u16,
674}
675
676impl Detected {
677 fn nothing(framework: Option<Framework>, install: Option<String>, problem: String) -> Detected {
678 Detected {
679 kind: "none",
680 framework,
681 install,
682 build: None,
683 output_dir: None,
684 problem: Some(problem),
685 pre_build: None,
686 container: None,
687 fallback: None,
688 }
689 }
690
691 /// The `framework` `g1t-runner detect` prints: the framework, else for
692 /// a container the server g1t wrote a Dockerfile for (`flask`…) or
693 /// `dockerfile`.
694 pub(crate) fn framework_id(&self) -> Option<&'static str> {
695 self.framework.as_ref().map(|f| f.id).or_else(|| {
696 self.container.as_ref().map(|c| c.generated.as_ref().map_or("dockerfile", |server| server.id))
697 })
698 }
699}
700
701/// Why nothing could be found to serve, and what to add.
702const NOTHING_TO_SERVE: &str = "found nothing to serve: no Workers config, no Dockerfile, no index.html, and none of dist, build, out, \
703 public, _site or .output/public. Add a `Dockerfile` to deploy it as a container, or set **Build command** and \
704 **Output directory** for a static site.";
705
706/// The project as a container: its own Dockerfile, else one g1t writes
707/// for `framework` or for a server it recognises. None when it has neither.
708fn as_container(dir: &Path, framework: Option<Framework>, own: Option<String>) -> Option<Detected> {
709 let build = match own {
710 Some(path) => {
711 let text = std::fs::read_to_string(dir.join(&path)).unwrap_or_default();
712 ContainerBuild { port: container::exposed_port(&text).unwrap_or(container::DEFAULT_PORT), dockerfile: Some(path), generated: None }
713 }
714 None => {
715 let server = match &framework {
716 // One set up for Workers (OpenNext's adapter) is not run as a server.
717 Some(framework) if framework.workers => None,
718 Some(framework) => container::for_framework(dir, framework.id),
719 None => container::server(dir),
720 }?;
721 ContainerBuild { dockerfile: None, generated: Some(server), port: container::DEFAULT_PORT }
722 }
723 };
724 let file = build.dockerfile.clone().unwrap_or_else(|| "Dockerfile (written by g1t)".to_owned());
725 Some(Detected {
726 kind: "container",
727 framework,
728 // The image installs what it needs: nothing runs before its build.
729 install: None,
730 build: Some(format!("docker build -f {file} .")),
731 output_dir: None,
732 problem: None,
733 pre_build: None,
734 container: Some(build),
735 fallback: None,
736 })
737}
738
739#[cfg(test)]
740pub(crate) fn detect(dir: &Path, custom_build: Option<&str>, chosen_output: Option<&str>) -> Result<Detected> {
741 detect_as(dir, custom_build, chosen_output, BuildAs::Auto, None)
742}
743
744/// What the project is, by its **Build as** setting (`build_as`) and its
745/// Dockerfile's path (`dockerfile`, when it chose one):
746///
747/// - **Docker**: a container, from its Dockerfile or one g1t writes.
748/// - **Static site**: built and served as files, whatever else it has.
749/// - **Workers**: its Wrangler config or a framework adapter's Worker.
750/// - **Auto**: a Wrangler config is a Workers project; a framework that
751/// builds a static site or a Worker is that, which costs nothing while
752/// no one visits; a framework set up to need a server is a container
753/// when it has a Dockerfile, or when g1t can write one; a project with
754/// no framework g1t knows is a container when it has a Dockerfile or is
755/// a server g1t recognises (a Node.js, Python, Go, Ruby or PHP app),
756/// else a static site, else nothing, saying to add a Dockerfile.
757pub(crate) fn detect_as(
758 dir: &Path,
759 custom_build: Option<&str>,
760 chosen_output: Option<&str>,
761 build_as: BuildAs,
762 dockerfile: Option<&str>,
763) -> Result<Detected> {
764 let own = container::own_dockerfile(dir, dockerfile)?;
765 match build_as {
766 BuildAs::Docker => {
767 let framework = frameworks::detect(dir, read_wrangler(dir)?.is_some());
768 Ok(as_container(dir, framework.clone(), own).unwrap_or_else(|| {
769 Detected::nothing(
770 framework,
771 None,
772 "**Build as** is Docker, but this project has no Dockerfile and g1t doesn't recognise a server it can write \
773 one for. Add a `Dockerfile` (or set its path under Settings, Deployments)."
774 .to_owned(),
775 )
776 }))
777 }
778 BuildAs::Static => detect_site(dir, custom_build, chosen_output, true),
779 BuildAs::Workers => {
780 let site = detect_site(dir, custom_build, chosen_output, false)?;
781 if site.kind == "workers" {
782 return Ok(site);
783 }
784 Ok(Detected::nothing(
785 site.framework,
786 site.install,
787 "**Build as** is Workers, but this project has no Wrangler config (`wrangler.jsonc`, `wrangler.json` or \
788 `wrangler.toml`) and no framework adapter that writes a Worker."
789 .to_owned(),
790 ))
791 }
792 BuildAs::Auto => {
793 let site = detect_site(dir, custom_build, chosen_output, false)?;
794 if site.kind == "workers" || (site.framework.is_some() && site.problem.is_none()) {
795 return Ok(site);
796 }
797 if let Some(problem) = site.problem.clone() {
798 // A framework set up to need a server.
799 let found = as_container(dir, site.framework.clone(), own);
800 return Ok(found.unwrap_or_else(|| {
801 Detected::nothing(site.framework, site.install, format!("{problem} Or add a `Dockerfile` to run it as a container."))
802 }));
803 }
804 let has_own = own.is_some();
805 if let Some(mut found) = as_container(dir, None, own) {
806 // A Dockerfile beside a site that could be served as it is.
807 if has_own && (site.kind == "static" || site.kind == "html") {
808 found.fallback = Some(Box::new(site));
809 }
810 return Ok(found);
811 }
812 if site.kind == "none" {
813 return Ok(Detected::nothing(site.framework, site.install, NOTHING_TO_SERVE.to_owned()));
814 }
815 Ok(site)
816 }
817 }
818}
819
820/// What the project is as a static site or Workers project: `as_static`
821/// ignores its Wrangler config and any framework adapter, and builds it
822/// even when its framework is set up to need a server.
823fn detect_site(dir: &Path, custom_build: Option<&str>, chosen_output: Option<&str>, as_static: bool) -> Result<Detected> {
824 let custom_build = custom_build.map(str::trim).filter(|c| !c.is_empty());
825 let chosen_output = chosen_output.map(|d| d.trim().trim_matches('/')).filter(|d| !d.is_empty());
826 let config = if as_static { None } else { read_wrangler(dir)? };
827 let framework = frameworks::detect(dir, config.is_some());
828 let installs: Vec<&str> = [install_command(dir), framework.as_ref().and_then(|f| f.install)].into_iter().flatten().collect();
829 let install = (!installs.is_empty()).then(|| installs.join(" && "));
830 let framework_build = framework.as_ref().and_then(|f| f.build.clone());
831 if let Some(config) = config {
832 // A framework built for Workers builds before wrangler bundles what
833 // it wrote; any other project's config builds it, as it always has.
834 let pre_build = custom_build
835 .map(str::to_owned)
836 .or_else(|| framework.as_ref().filter(|f| f.workers).and(framework_build));
837 let mut steps: Vec<String> = pre_build.clone().into_iter().collect();
838 if config.main.is_some() {
839 steps.push(wrangler_build(None, None));
840 }
841 return Ok(Detected {
842 kind: "workers",
843 framework,
844 install,
845 build: (!steps.is_empty()).then(|| steps.join(" && ")),
846 output_dir: config.assets.and_then(|assets| assets.directory),
847 problem: None,
848 pre_build,
849 container: None,
850 fallback: None,
851 });
852 }
853 let build = custom_build
854 .map(str::to_owned)
855 .or(framework_build)
856 .or_else(|| has_build_script(dir).then(|| "npm run build".to_owned()));
857 // An adapter's Worker, unless the project chose a folder to serve.
858 if !as_static && chosen_output.is_none() && framework.as_ref().is_some_and(|f| f.adapter.is_some()) {
859 // Where its files are is known once it has built: the adapter's
860 // own folder, or where the config it writes says.
861 return Ok(Detected {
862 kind: "workers",
863 output_dir: None,
864 framework,
865 install,
866 pre_build: build.clone(),
867 build,
868 problem: None,
869 container: None,
870 fallback: None,
871 });
872 }
873 // A command or a folder of the project's own says it knows better, as
874 // does **Build as** set to Static site.
875 let problem = framework
876 .as_ref()
877 .and_then(|f| f.problem.clone())
878 .filter(|_| !as_static && custom_build.is_none() && chosen_output.is_none());
879 if let Some(problem) = problem {
880 return Ok(Detected::nothing(framework, install, problem));
881 }
882 let output_dir = chosen_output
883 .map(str::to_owned)
884 .or_else(|| framework.as_ref().and_then(|f| f.output.clone()))
885 .or_else(|| find_output(dir));
886 // `.` is the project itself: its own files, served as they are.
887 let kind = match (&build, output_dir.as_deref()) {
888 (None, Some(".")) => "html",
889 (None, None) => "none",
890 _ => "static",
891 };
892 Ok(Detected { kind, framework, install, pre_build: build.clone(), build, output_dir, problem: None, container: None, fallback: None })
893}
894
895/// The compatibility date a Worker gets when its config names none.
896const COMPATIBILITY_DATE: &str = "2026-09-26";
897
898/// A Workers project bundled by wrangler: `config` with its paths relative
899/// to `base`, read by wrangler from `config_file` when given (else the
900/// project's own, or the one its build wrote).
901fn build_worker(
902 log: &mut Log,
903 secrets: &[String],
904 config: WranglerConfig,
905 base: &Path,
906 config_file: Option<&Path>,
907) -> Result<(Value, Option<PathBuf>, Vec<String>)> {
908 let bundle = bundle_dir();
909 let warnings = config_warnings(&config);
910 let mut worker = json!({
911 "compatibilityDate": config.compatibility_date.clone().unwrap_or_else(|| COMPATIBILITY_DATE.to_owned()),
912 "compatibilityFlags": config.compatibility_flags,
913 "vars": config.vars,
914 });
915 if let Some(main) = &config.main {
916 // `--dry-run` runs the config's own build and bundles it, without
917 // deploying anywhere.
918 let _ = std::fs::remove_dir_all(&bundle);
919 step(log, &wrangler_build(Some(&bundle), config_file), secrets)?;
920 let (main_module, modules) = bundle_modules(main, &bundle)?;
921 worker["mainModule"] = main_module.into();
922 worker["modules"] = serde_json::to_value(modules)?;
923 }
924 let assets = config.assets.unwrap_or_default();
925 let assets_dir = assets.directory.as_ref().map(|directory| base.join(directory));
926 worker["assetsBinding"] = assets.binding.into();
927 worker["htmlHandling"] = assets.html_handling.into();
928 worker["notFoundHandling"] = assets.not_found_handling.into();
929 Ok((worker, assets_dir, warnings))
930}
931
932/// Where the config for an adapter's Worker is written: beside the
933/// bundle, never in the checkout.
934fn adapter_config_path() -> PathBuf {
935 let bundle = bundle_dir();
936 bundle.with_file_name(format!("{}.wrangler.json", bundle.file_name().unwrap_or_default().to_string_lossy()))
937}
938
939/// What a container build says when g1t.page runs no containers.
940const CONTAINERS_OFF: &str = "This project deploys as a container, and Docker deployments are not switched on for g1t.page yet. \
941 Set **Build as** to Static site or Workers under Settings, Deployments if it can be built as one.";
942
943/// Where a container's registry login is kept for the build: its own
944/// folder, never the job's `~/.docker`.
945fn docker_config_dir() -> PathBuf {
946 bundle_dir().with_file_name(format!("{}.docker", bundle_dir().file_name().unwrap_or_default().to_string_lossy()))
947}
948
949/// Where the Dockerfile g1t writes for a project without one goes: beside
950/// the bundle, never in the checkout.
951fn generated_dockerfile_path() -> PathBuf {
952 bundle_dir().with_file_name(format!("{}.Dockerfile", bundle_dir().file_name().unwrap_or_default().to_string_lossy()))
953}
954
955/// What the deployments service answers the `registry` step with: where
956/// to push the app's image, with a login good for pushing only and only
957/// for minutes, and the largest image the app's instance can run.
958#[derive(Debug, Deserialize)]
959struct RegistryGrant {
960 registry: String,
961 repository: String,
962 tag: String,
963 username: String,
964 password: String,
965 #[serde(alias = "maxImageBytes")]
966 max_image_bytes: u64,
967 #[serde(default, alias = "instanceType")]
968 instance_type: Option<String>,
969}
970
971/// `name@sha256:…` for `repository` among an image's repository digests,
972/// as `docker image inspect` lists them, one a line.
973fn pushed_digest(repo_digests: &str, registry: &str, repository: &str) -> Option<String> {
974 let prefix = format!("{registry}/{repository}@sha256:");
975 repo_digests
976 .lines()
977 .map(str::trim)
978 .find(|line| line.starts_with(&prefix) && line.len() == prefix.len() + 64)
979 .map(str::to_owned)
980}
981
982/// Bytes, as a person reads them: `1.4 GB`.
983fn size_text(bytes: u64) -> String {
984 format!("{:.1} GB", bytes as f64 / 1_000_000_000.0)
985}
986
987/// Runs `docker` with `args`, signed in through `config`; its output, or
988/// why it failed, redacted.
989fn docker(args: &[&str], config: &Path, input: Option<&str>, secrets: &[String]) -> Result<String> {
990 use std::io::Write;
991 use std::process::{Command, Stdio};
992 let mut command = Command::new("docker");
993 command.args(args).env("DOCKER_CONFIG", config).stdout(Stdio::piped()).stderr(Stdio::piped());
994 command.stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() });
995 let mut child = command.spawn().context("could not run docker")?;
996 if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
997 stdin.write_all(input.as_bytes())?;
998 }
999 let output = child.wait_with_output()?;
1000 let text = redact(&format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)), secrets);
1001 if !output.status.success() {
1002 bail!("`docker {}` failed: {}", args.first().copied().unwrap_or_default(), text.trim());
1003 }
1004 Ok(text)
1005}
1006
1007/// Builds the project's container image with Docker and pushes it to
1008/// Cloudflare's registry, at the place and with the short-lived push-only
1009/// login the deployments service gives for this build (`registry`). The
1010/// sandbox never holds g1t's own Cloudflare token. None when g1t.page runs
1011/// no containers (the service answers `not_enabled`).
1012fn container_build(reporter: &Reporter, log: &mut Log, secrets: &[String], dir: &Path, plan: &Detected) -> Result<Option<Value>> {
1013 let build = plan.container.as_ref().context("not a container")?;
1014 // Asked first: a build that could not be pushed is not run.
1015 let answer = reporter.send("registry", json!({}))?;
1016 if answer["ok"] == false {
1017 if answer["error"]["code"] == "not_enabled" {
1018 return Ok(None);
1019 }
1020 bail!("{}", answer["error"]["message"].as_str().unwrap_or("g1t refused the image's upload"));
1021 }
1022 let grant: RegistryGrant =
1023 serde_json::from_value(answer["value"].clone()).context("g1t's answer to the image's upload was not understood")?;
1024 let mut secrets = secrets.to_vec();
1025 secrets.push(grant.password.clone());
1026 let dockerfile = match (&build.dockerfile, &build.generated) {
1027 (Some(own), _) => {
1028 log.line(&format!("Building a container from {own}, listening on port {}.", build.port));
1029 dir.join(own)
1030 }
1031 (None, Some(server)) => {
1032 // Shown whole, so it can be committed and changed.
1033 log.line(&format!("This {} project has no Dockerfile, so g1t wrote this one (commit it as `Dockerfile` to change it):", server.name));
1034 for line in server.dockerfile.lines() {
1035 log.line(&format!(" {line}"));
1036 }
1037 let path = generated_dockerfile_path();
1038 std::fs::write(&path, &server.dockerfile)?;
1039 // BuildKit reads `<Dockerfile>.dockerignore` beside it.
1040 std::fs::write(path.with_file_name(format!("{}.dockerignore", path.file_name().unwrap_or_default().to_string_lossy())), container::DOCKERIGNORE)?;
1041 path
1042 }
1043 (None, None) => bail!("nothing to build the container from"),
1044 };
1045 if std::env::var("BUILD_COMMAND").is_ok_and(|c| !c.trim().is_empty()) {
1046 log.line("Build command is not used for a container: its Dockerfile builds it.");
1047 }
1048 // A sandbox's own Docker Engine, started for the build; in a workflow
1049 // step, the job's.
1050 if clones() {
1051 if std::env::var("G1T_DOCKER").as_deref() != Ok("on") {
1052 bail!("Docker is turned off for g1t's sandboxes here, so a container cannot be built.");
1053 }
1054 crate::docker::engine::enable(crate::docker::engine::Options::default())
1055 .map_err(|problem| anyhow::anyhow!("Docker is not available in this sandbox: {problem}"))?;
1056 let started = crate::docker::engine::ensure_started();
1057 for note in crate::docker::take_notes() {
1058 log.line(&note);
1059 }
1060 started.map_err(|problem| anyhow::anyhow!("Docker could not start: {problem}"))?;
1061 }
1062 let config = docker_config_dir();
1063 std::fs::create_dir_all(&config)?;
1064 let image = format!("{}/{}:{}", grant.registry, grant.repository, grant.tag);
1065 let quote = |path: &Path| format!("'{}'", path.display().to_string().replace('\'', r"'\''"));
1066 let built = step(
1067 log,
1068 &format!("docker build --platform linux/amd64 --pull -f {} -t {image} .", quote(&dockerfile)),
1069 &secrets,
1070 );
1071 let pushed = built.and_then(|()| {
1072 let size: u64 = docker(&["image", "inspect", "--format", "{{.Size}}", &image], &config, None, &secrets)?.trim().parse().unwrap_or(0);
1073 log.line(&format!("The image is {}.", size_text(size)));
1074 if size > grant.max_image_bytes {
1075 bail!(
1076 "The image is {}, more than the {} an app of its size ({}) can hold. Make it smaller (a slim base image, a multi-stage build), or choose a larger instance under Settings, Deployments.",
1077 size_text(size),
1078 size_text(grant.max_image_bytes),
1079 grant.instance_type.as_deref().unwrap_or("its instance type"),
1080 );
1081 }
1082 docker(&["login", &grant.registry, "--username", &grant.username, "--password-stdin"], &config, Some(&grant.password), &secrets)?;
1083 log.line(&format!("$ docker push {image}"));
1084 let output = docker(&["push", &image], &config, None, &secrets)?;
1085 log.line(output.trim_end());
1086 let digests = docker(&["image", "inspect", "--format", "{{join .RepoDigests \"\\n\"}}", &image], &config, None, &secrets)?;
1087 let reference = pushed_digest(&digests, &grant.registry, &grant.repository).context("the pushed image's digest was not found")?;
1088 Ok(json!({
1089 "image": reference,
1090 "port": build.port,
1091 "sizeBytes": size,
1092 "dockerfile": build.dockerfile,
1093 "generated": build.generated.as_ref().map(|server| server.id),
1094 }))
1095 });
1096 let _ = std::fs::remove_dir_all(&config);
1097 let _ = std::fs::remove_file(generated_dockerfile_path());
1098 pushed.map(Some)
1099}
1100
1101fn build(reporter: &Reporter, log: &mut Log, secrets: &[String]) -> Result<Built> {
1102 let project = project_dir();
1103 let dir = project.as_path();
1104 let custom_build = std::env::var("BUILD_COMMAND").ok();
1105 let chosen = std::env::var("OUTPUT_DIR").ok().filter(|d| !d.trim().is_empty());
1106 let build_as = BuildAs::parse(&std::env::var("BUILD_AS").unwrap_or_default());
1107 let dockerfile = std::env::var("DOCKERFILE").ok();
1108 let mut plan = detect_as(dir, custom_build.as_deref(), chosen.as_deref(), build_as, dockerfile.as_deref())?;
1109 if let Some(framework) = &plan.framework {
1110 log.line(&format!("Detected {}: framework={}.", framework.name, framework.id));
1111 }
1112 // Said before anything is installed: it would fail after, less clearly.
1113 if let Some(problem) = &plan.problem {
1114 bail!("{problem}");
1115 }
1116 if plan.container.is_some() {
1117 match container_build(reporter, log, secrets, dir, &plan)? {
1118 Some(image) => {
1119 return Ok(Built {
1120 worker: json!({}),
1121 assets_dir: None,
1122 warnings: Vec::new(),
1123 detected: "container",
1124 framework: plan.framework_id(),
1125 container: Some(image),
1126 });
1127 }
1128 // g1t.page runs no containers yet: the site it is without its
1129 // Dockerfile, as it was built before.
1130 None => match plan.fallback.take() {
1131 Some(site) => {
1132 log.line(&format!("Building it as a {} site instead, as it is without its Dockerfile.", if site.kind == "html" { "plain HTML" } else { "static" }));
1133 plan = *site;
1134 }
1135 None => bail!("{CONTAINERS_OFF}"),
1136 },
1137 }
1138 }
1139 let framework_id = plan.framework.as_ref().map(|f| f.id);
1140 if let Some(install) = &plan.install {
1141 step(log, install, secrets)?;
1142 }
1143 if let Some(command) = &plan.pre_build {
1144 step(log, command, secrets)?;
1145 }
1146 // A static site (by **Build as**, or found to be one) never reads a
1147 // Workers config.
1148 let workers = plan.kind == "workers";
1149 let own_config = if workers { read_wrangler(dir)? } else { None };
1150 // A framework built for Workers may write the config wrangler reads
1151 // (`@cloudflare/vite-plugin` does, and Astro's adapter with it), with
1152 // or without one of the project's own.
1153 let written = if own_config.is_some() || (workers && plan.framework.as_ref().is_some_and(|f| f.workers)) {
1154 redirected_config(dir)?
1155 } else {
1156 None
1157 };
1158 if let Some((config, base)) = written {
1159 log.line(&format!("Using the Workers config the build wrote, in {}.", base.display()));
1160 let (worker, assets_dir, warnings) = build_worker(log, secrets, config, &base, None)?;
1161 return Ok(Built { worker, assets_dir, warnings, detected: "workers", framework: framework_id, container: None });
1162 }
1163 if let Some(config) = own_config {
1164 let (worker, assets_dir, warnings) = build_worker(log, secrets, config, dir, None)?;
1165 return Ok(Built { worker, assets_dir, warnings, detected: "workers", framework: framework_id, container: None });
1166 }
1167 let adapter = plan.framework.as_ref().and_then(|f| f.adapter.as_ref()).filter(|_| workers && chosen.is_none());
1168 if let Some(adapter) = adapter
1169 && let Some(entry) = adapter_entry(dir, adapter)
1170 {
1171 // The adapter's Worker, bundled as a Workers project's is. Its
1172 // static files are uploaded by g1t, so wrangler is given none.
1173 let file = adapter_config_path();
1174 let flags = vec!["nodejs_compat".to_owned()];
1175 std::fs::write(
1176 &file,
1177 serde_json::to_string_pretty(&json!({
1178 "name": "g1t-app",
1179 "main": entry,
1180 "compatibility_date": COMPATIBILITY_DATE,
1181 "compatibility_flags": flags,
1182 }))?,
1183 )?;
1184 log.line(&format!("Bundling the Worker the adapter wrote, {}.", adapter.entry));
1185 let config = WranglerConfig {
1186 main: Some(entry.to_string_lossy().into_owned()),
1187 compatibility_flags: flags,
1188 assets: Some(AssetsConfig {
1189 directory: Some(adapter.assets.to_owned()),
1190 binding: Some("ASSETS".to_owned()),
1191 ..AssetsConfig::default()
1192 }),
1193 ..WranglerConfig::default()
1194 };
1195 let built = build_worker(log, secrets, config, dir, Some(&file));
1196 let _ = std::fs::remove_file(&file);
1197 let (worker, assets_dir, warnings) = built?;
1198 return Ok(Built { worker, assets_dir, warnings, detected: "workers", framework: framework_id, container: None });
1199 }
1200 if let (Some(adapter), Some(framework)) = (adapter, &plan.framework)
1201 && framework.output.is_none()
1202 {
1203 bail!("{}'s build did not write its Worker, `{}`", framework.name, adapter.entry);
1204 }
1205 let assets_dir = match &chosen {
1206 Some(chosen) => {
1207 let path = dir.join(chosen.trim().trim_matches('/'));
1208 if !path.is_dir() {
1209 bail!("the output directory `{chosen}` does not exist after the build");
1210 }
1211 path
1212 }
1213 None => {
1214 let expected = plan.framework.as_ref().and_then(|f| f.output.as_deref());
1215 match expected.filter(|output| dir.join(output).is_dir()) {
1216 Some(output) => dir.join(output),
1217 None => {
1218 let found = find_output(dir).with_context(|| match (&plan.framework, expected) {
1219 (Some(framework), Some(expected)) => format!(
1220 "found nothing to serve: {} writes its site to `{expected}`, which the build did not write. \
1221 Set **Output directory** if it writes somewhere else.",
1222 framework.name
1223 ),
1224 (Some(framework), None) if framework.problem.is_some() => {
1225 format!("found nothing to serve. {}", framework.problem.as_deref().unwrap_or_default())
1226 }
1227 _ => "found nothing to serve: no Workers config, no index.html, and none of dist, build, out, public, _site or .output/public".to_owned(),
1228 })?;
1229 if let Some(expected) = expected {
1230 log.line(&format!("`{expected}` was not written; serving `{found}`."));
1231 }
1232 if found == "." { dir.to_path_buf() } else { dir.join(found) }
1233 }
1234 }
1235 }
1236 };
1237 let spa = !assets_dir.join("404.html").exists();
1238 Ok(Built {
1239 worker: json!({
1240 "compatibilityDate": COMPATIBILITY_DATE,
1241 "compatibilityFlags": [],
1242 "vars": {},
1243 "notFoundHandling": if spa { "single-page-application" } else { "404-page" },
1244 }),
1245 detected: static_kind(dir, &assets_dir, plan.build.is_some()),
1246 assets_dir: Some(assets_dir),
1247 warnings: Vec::new(),
1248 framework: framework_id,
1249 container: None,
1250 })
1251}
1252
1253/// Whether the build checks out its own commit (a sandbox, given
1254/// `GIT_REMOTE`) rather than building the checkout it runs in.
1255fn clones() -> bool {
1256 std::env::var("GIT_REMOTE").is_ok_and(|remote| !remote.trim().is_empty())
1257}
1258
1259/// The checkout the build runs in: the sandbox's clone, or, from a
1260/// workflow step, the current directory.
1261fn checkout_dir() -> PathBuf {
1262 if clones() {
1263 PathBuf::from(WORKDIR)
1264 } else {
1265 std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
1266 }
1267}
1268
1269/// Where `wrangler deploy --dry-run` writes the bundle: in a workflow
1270/// step, a directory of the job's temporary space, never the checkout.
1271fn bundle_dir() -> PathBuf {
1272 if clones() {
1273 return PathBuf::from(BUNDLE_DIR);
1274 }
1275 let base = std::env::var_os("RUNNER_TEMP").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
1276 base.join(format!("g1t-bundle-{}", std::process::id()))
1277}
1278
1279/// Where the project lives in the checkout `base`: its root directory,
1280/// never above the checkout.
1281fn project_dir_in(base: &Path, root: &str) -> PathBuf {
1282 let root = root.trim().trim_matches('/');
1283 if root.is_empty() || root == "." || root.split('/').any(|part| part == "..") {
1284 base.to_path_buf()
1285 } else {
1286 base.join(root)
1287 }
1288}
1289
1290/// Where the project lives: `ROOT_DIR` in the checkout.
1291fn project_dir() -> PathBuf {
1292 project_dir_in(&checkout_dir(), &std::env::var("ROOT_DIR").unwrap_or_default())
1293}
1294
1295fn check_out(secrets: &[String]) -> Result<()> {
1296 let remote = env("GIT_REMOTE")?;
1297 let commit = env("GIT_COMMIT")?;
1298 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
1299 std::fs::create_dir_all("/work")?;
1300 let workdir = Path::new(WORKDIR);
1301 // The clone is shallow and of the default branch; a preview's commit is
1302 // often on another one, so it is fetched before checking out.
1303 let cloned = crate::clone::clone(Path::new("/work"), &auth, &[], &remote, WORKDIR)
1304 .and_then(|_| git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"]))
1305 .and_then(|branch| crate::clone::ensure(workdir, &auth, "origin", &branch, &commit))
1306 .and_then(|_| git(workdir, &["-c", "advice.detachedHead=false", "checkout", "--quiet", &commit]));
1307 if let Err(error) = cloned {
1308 bail!("{}", redact(&format!("{error:#}"), secrets));
1309 }
1310 Ok(())
1311}
1312
1313fn deploy(reporter: &Reporter, log: &mut Log, secrets: &[String]) -> Result<Value> {
1314 if clones() {
1315 check_out(secrets).context("the commit could not be checked out")?;
1316 } else {
1317 let dir = project_dir();
1318 if !dir.is_dir() {
1319 bail!("the project's directory {} does not exist in this checkout", dir.display());
1320 }
1321 log.line(&format!("Building {} as it is checked out.", dir.display()));
1322 }
1323 // The repository's variables and secrets for deploy builds.
1324 for source in ["BUILD_ENV", "BUILD_SECRETS"] {
1325 if let Ok(vars) = std::env::var(source)
1326 && let Ok(Value::Object(vars)) = serde_json::from_str::<Value>(&vars)
1327 {
1328 for (name, value) in vars {
1329 if let Some(value) = value.as_str() {
1330 // SAFETY: single-threaded; set before any command runs.
1331 unsafe { std::env::set_var(name, value) };
1332 }
1333 }
1334 }
1335 }
1336 let built = build(reporter, log, secrets)?;
1337 let mut finish = json!({
1338 "worker": built.worker,
1339 "warnings": built.warnings,
1340 "detected": built.detected,
1341 // What it is built with, shown beside `detected` on its settings.
1342 "framework": built.framework,
1343 });
1344 if let Some(image) = built.container {
1345 finish["container"] = image;
1346 }
1347 for warning in &built.warnings {
1348 log.line(&format!("Warning: {warning}"));
1349 }
1350 if let Some(dir) = &built.assets_dir {
1351 let skip_project = *dir == project_dir();
1352 let assets = collect_site(dir, skip_project)?;
1353 if assets.is_empty() {
1354 bail!("the site to serve is empty");
1355 }
1356 log.line(&format!("Uploading {} files.", assets.len()));
1357 for special in ["_headers", "_redirects"] {
1358 if let Ok(text) = std::fs::read_to_string(dir.join(special)) {
1359 finish["worker"][special] = text.into();
1360 }
1361 }
1362 let manifest: BTreeMap<&str, Value> = assets
1363 .iter()
1364 .map(|asset| (asset.path.as_str(), json!({ "hash": asset.hash, "size": asset.size })))
1365 .collect();
1366 let answer = reporter.send("session", json!({ "manifest": manifest }))?;
1367 if answer["ok"] == false {
1368 bail!("{}", answer["error"]["message"].as_str().unwrap_or("g1t refused the upload"));
1369 }
1370 let session: UploadSession =
1371 serde_json::from_value(answer["value"].clone()).context("g1t's answer to the upload was not understood")?;
1372 let by_hash: BTreeMap<&str, &Asset> = assets.iter().map(|asset| (asset.hash.as_str(), asset)).collect();
1373 let mut completion = session.jwt.clone();
1374 for bucket in &session.buckets {
1375 if let Some(jwt) = upload_bucket(&session, bucket, &by_hash)? {
1376 completion = jwt;
1377 }
1378 }
1379 finish["completionJwt"] = completion.into();
1380 }
1381 Ok(finish)
1382}
1383
1384/// A sandbox's build (`MODE=deploy`).
1385pub fn main() -> i32 {
1386 run(false)
1387}
1388
1389/// `g1t-runner deploy`, from a workflow step: the build in the job's own
1390/// checkout, its log in the step's as well. Exits 1 when the build fails,
1391/// after reporting it, so the step fails too.
1392pub fn cli(args: &[String]) -> i32 {
1393 if args.iter().any(|arg| arg == "--help" || arg == "-h") {
1394 println!("{CLI_HELP}");
1395 return 0;
1396 }
1397 run(true)
1398}
1399
1400const CLI_HELP: &str = "g1t-runner deploy: builds the project in this checkout and puts it on g1t.page.
1401
1402Reads DEPLOY_ID and DEPLOY_TOKEN (from POST /repos/{owner}/{repo}/deployments/builds),
1403G1T_API (https://api.g1t.sh), and optionally ROOT_DIR, BUILD_COMMAND, OUTPUT_DIR,
1404BUILD_AS (auto, static, workers or docker), DOCKERFILE, and BUILD_ENV and
1405BUILD_SECRETS (JSON objects). The g1t/deploy action sets them all. A container
1406is built with the docker on PATH.
1407
1408g1t-runner detect prints what the build would find, as key=value lines.";
1409
1410fn run(step_log: bool) -> i32 {
1411 let reporter = match (env("G1T_API"), env("DEPLOY_ID"), env("DEPLOY_TOKEN")) {
1412 (Ok(api), Ok(id), Ok(token)) => Reporter {
1413 base: format!("{}/deployments/jobs/{id}", api.trim_end_matches('/')),
1414 token,
1415 },
1416 _ => {
1417 eprintln!("g1t-runner: G1T_API, DEPLOY_ID and DEPLOY_TOKEN must be set");
1418 return 2;
1419 }
1420 };
1421 let mut secrets: Vec<String> = ["G1T_TOKEN", "DEPLOY_TOKEN"]
1422 .iter()
1423 .filter_map(|name| std::env::var(name).ok())
1424 .filter(|secret| !secret.is_empty())
1425 .collect();
1426 // The repository's build secrets never appear in the log.
1427 if let Ok(Value::Object(build)) = serde_json::from_str::<Value>(&std::env::var("BUILD_SECRETS").unwrap_or_default()) {
1428 secrets.extend(build.values().filter_map(Value::as_str).filter(|v| v.len() >= 4).map(str::to_owned));
1429 }
1430 if let Err(error) = reporter.send("started", json!({})) {
1431 eprintln!("g1t-runner: {error:#}");
1432 return 1;
1433 }
1434 let started = Instant::now();
1435 let mut log = Log { echo: step_log.then(|| secrets.clone()), ..Log::default() };
1436 let outcome = deploy(&reporter, &mut log, &secrets);
1437 let seconds = started.elapsed().as_secs();
1438 if step_log {
1439 let _ = std::fs::remove_dir_all(bundle_dir());
1440 let _ = std::fs::remove_file(adapter_config_path());
1441 let _ = std::fs::remove_dir_all(docker_config_dir());
1442 }
1443 let (sent, failed) = match outcome {
1444 Ok(mut finish) => {
1445 finish["log"] = redact(&log.tail(), &secrets).into();
1446 finish["buildSeconds"] = seconds.into();
1447 (reporter.send("finish", finish), false)
1448 }
1449 Err(error) => {
1450 let message = redact(&format!("{error:#}"), &secrets);
1451 log.line(&format!("The build failed: {message}"));
1452 let sent = reporter.send(
1453 "fail",
1454 json!({ "message": message, "log": redact(&log.tail(), &secrets), "buildSeconds": seconds }),
1455 );
1456 (sent, true)
1457 }
1458 };
1459 match sent {
1460 // A sandbox's build has said how it ended; a step fails with its build.
1461 Ok(answer) if step_log && (failed || answer["ok"] == false || answer["value"] == false) => {
1462 if !failed {
1463 eprintln!("g1t-runner: g1t did not take the build; its deployment says why");
1464 }
1465 1
1466 }
1467 Ok(_) => 0,
1468 Err(error) => {
1469 eprintln!("g1t-runner: {error:#}");
1470 1
1471 }
1472 }
1473}
1474
1475/// `g1t-runner detect`: what a build of the project would find, as
1476/// `key=value` lines for `$GITHUB_OUTPUT`: `kind`, `install`, `build`,
1477/// `output-dir`, and `framework` when one is found. Reads `ROOT_DIR`,
1478/// `BUILD_COMMAND` and `OUTPUT_DIR` as the build does; `--root-dir DIR` is
1479/// the same as `ROOT_DIR`. A framework set up to need a server is `none`,
1480/// with what to change on standard error.
1481pub fn detect_cli(args: &[String]) -> i32 {
1482 let mut root = std::env::var("ROOT_DIR").unwrap_or_default();
1483 let mut rest = args.iter();
1484 while let Some(arg) = rest.next() {
1485 match arg.as_str() {
1486 "--root-dir" => root = rest.next().cloned().unwrap_or_default(),
1487 "--help" | "-h" => {
1488 println!(
1489 "g1t-runner detect [--root-dir DIR]: prints kind, install, build, output-dir and framework (when one is found), and for a container dockerfile and port, as key=value lines. Reads ROOT_DIR, BUILD_COMMAND, OUTPUT_DIR, BUILD_AS (auto, static, workers or docker) and DOCKERFILE as a build does."
1490 );
1491 return 0;
1492 }
1493 other => {
1494 eprintln!("g1t-runner detect: unknown argument {other}");
1495 return 2;
1496 }
1497 }
1498 }
1499 let dir = project_dir_in(&checkout_dir(), &root);
1500 let custom = std::env::var("BUILD_COMMAND").ok();
1501 let output = std::env::var("OUTPUT_DIR").ok();
1502 let build_as = BuildAs::parse(&std::env::var("BUILD_AS").unwrap_or_default());
1503 let dockerfile = std::env::var("DOCKERFILE").ok();
1504 match detect_as(&dir, custom.as_deref(), output.as_deref(), build_as, dockerfile.as_deref()) {
1505 Ok(found) => {
1506 print!("{}", output_lines(&found));
1507 if let Some(problem) = &found.problem {
1508 eprintln!("g1t-runner detect: {problem}");
1509 }
1510 0
1511 }
1512 Err(error) => {
1513 eprintln!("g1t-runner detect: {error:#}");
1514 1
1515 }
1516 }
1517}
1518
1519/// `Detected` as `$GITHUB_OUTPUT` lines; a value on one line, empty when
1520/// there is none. `framework` is left out when none was found, which a
1521/// step's outputs read as empty all the same.
1522fn output_lines(found: &Detected) -> String {
1523 let one_line = |value: Option<&str>| value.unwrap_or_default().replace(['\r', '\n'], " ");
1524 let mut lines = format!(
1525 "kind={}\ninstall={}\nbuild={}\noutput-dir={}\n",
1526 found.kind,
1527 one_line(found.install.as_deref()),
1528 one_line(found.build.as_deref()),
1529 one_line(found.output_dir.as_deref()),
1530 );
1531 if let Some(framework) = found.framework_id() {
1532 lines.push_str(&format!("framework={framework}\n"));
1533 }
1534 // A container's Dockerfile (empty when g1t writes one) and its port.
1535 if let Some(container) = &found.container {
1536 lines.push_str(&format!("dockerfile={}\nport={}\n", one_line(container.dockerfile.as_deref()), container.port));
1537 }
1538 lines
1539}
1540
1541#[cfg(test)]
1542mod tests {
1543 use super::*;
1544
1545 /// A server that answers one request with `status` and `body`.
1546 fn answering(status: &str, body: &'static str) -> String {
1547 use std::io::{Read, Write};
1548 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1549 let base = format!("http://{}", listener.local_addr().unwrap());
1550 let status = status.to_owned();
1551 std::thread::spawn(move || {
1552 let (mut stream, _) = listener.accept().unwrap();
1553 // The whole request first (its headers, then its body by
1554 // length), or the client may still be writing when the answer
1555 // closes the connection.
1556 let mut seen = Vec::new();
1557 let mut buf = [0; 4096];
1558 loop {
1559 let n = stream.read(&mut buf).unwrap_or(0);
1560 if n == 0 {
1561 break;
1562 }
1563 seen.extend_from_slice(&buf[..n]);
1564 let text = String::from_utf8_lossy(&seen);
1565 if let Some(end) = text.find("\r\n\r\n") {
1566 let length = text[..end]
1567 .lines()
1568 .find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0)))
1569 .unwrap_or(0);
1570 if seen.len() >= end + 4 + length {
1571 break;
1572 }
1573 }
1574 }
1575 let reply = format!("HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
1576 stream.write_all(reply.as_bytes()).unwrap();
1577 });
1578 base
1579 }
1580
1581 #[test]
1582 fn a_refusal_reaches_the_step_with_its_reason() {
1583 let base = answering("409 Conflict", r#"{"ok":false,"error":{"code":"not_enabled","message":"Docker deployments are not switched on for g1t.page yet."}}"#);
1584 let answer = Reporter { base, token: "t".into() }.send("registry", json!({})).unwrap();
1585 assert_eq!(answer["ok"], false);
1586 assert_eq!(answer["error"]["code"], "not_enabled");
1587 }
1588
1589 #[test]
1590 fn a_failure_without_an_answer_says_its_status() {
1591 let base = answering("502 Bad Gateway", "upstream down");
1592 let error = Reporter { base, token: "t".into() }.send("registry", json!({})).unwrap_err();
1593 assert!(format!("{error:#}").contains("status code 502"), "{error:#}");
1594 }
1595
1596 #[test]
1597 fn the_upload_session_is_read_in_either_spelling() {
1598 for answer in [
1599 json!({ "jwt": "j", "buckets": [["a"]], "upload_url": "https://u" }),
1600 json!({ "jwt": "j", "uploadUrl": "https://u" }),
1601 ] {
1602 let session: UploadSession = serde_json::from_value(answer).unwrap();
1603 assert_eq!(session.upload_url, "https://u");
1604 }
1605 }
1606
1607 #[test]
1608 fn jsonc_comments_and_trailing_commas_are_dropped() {
1609 let text = r#"{
1610 // a comment
1611 "main": "src/index.ts", /* another */
1612 "vars": { "URL": "https://x.dev//not-a-comment", },
1613 }"#;
1614 let config: WranglerConfig = serde_json::from_str(&strip_jsonc(text)).unwrap();
1615 assert_eq!(config.main.as_deref(), Some("src/index.ts"));
1616 assert_eq!(config.vars["URL"], "https://x.dev//not-a-comment");
1617 }
1618
1619 #[test]
1620 fn unsupported_bindings_are_noticed() {
1621 let config: WranglerConfig =
1622 serde_json::from_str(r#"{ "main": "a.js", "d1_databases": [{ "binding": "DB" }] }"#).unwrap();
1623 assert!(config.rest.contains_key("d1_databases"));
1624 }
1625
1626 #[test]
1627 fn crons_g1t_does_not_run_are_warned_about() {
1628 let config: WranglerConfig =
1629 serde_json::from_str(r#"{ "main": "a.js", "triggers": { "crons": ["*/5 * * * *", "0 3 * * *"] }, "kv_namespaces": [{ "binding": "KV" }] }"#)
1630 .unwrap();
1631 let warnings = config_warnings(&config);
1632 assert_eq!(warnings.len(), 2);
1633 assert!(warnings.iter().any(|w| w.contains("kv_namespaces")));
1634 assert!(warnings.iter().any(|w| w.contains("triggers.crons") && w.contains("2 schedules")));
1635 let none: WranglerConfig = serde_json::from_str(r#"{ "main": "a.js", "triggers": { "crons": [] } }"#).unwrap();
1636 assert!(config_warnings(&none).is_empty());
1637 let toml: WranglerConfig = toml::from_str("main = \"a.js\"
1638[triggers]
1639crons = [\"0 * * * *\"]
1640").unwrap();
1641 assert!(config_warnings(&toml)[0].contains("1 schedule)"));
1642 // A config a build wrote lists every kind of binding, mostly empty.
1643 let written: WranglerConfig = serde_json::from_str(
1644 r#"{ "main": "entry.mjs", "d1_databases": [], "durable_objects": { "bindings": [] }, "triggers": {}, "kv_namespaces": [{ "binding": "SESSION" }] }"#,
1645 )
1646 .unwrap();
1647 assert_eq!(config_warnings(&written).len(), 1);
1648 }
1649
1650 #[test]
1651 fn a_site_is_plain_html_only_when_its_own_files_are_served_unbuilt() {
1652 let project = Path::new("/w/site");
1653 assert_eq!(static_kind(project, project, false), "html");
1654 assert_eq!(static_kind(project, project, true), "static");
1655 assert_eq!(static_kind(project, &project.join("dist"), false), "static");
1656 }
1657
1658 #[test]
1659 fn files_are_typed_by_extension() {
1660 assert_eq!(content_type("/index.HTML"), "text/html");
1661 assert_eq!(content_type("/a/b.woff2"), "font/woff2");
1662 assert_eq!(content_type("/LICENSE"), "application/octet-stream");
1663 }
1664
1665 /// A fresh directory with `files` (path, contents) in it.
1666 fn project(name: &str, files: &[(&str, &str)]) -> PathBuf {
1667 let dir = std::env::temp_dir().join(format!("g1t-detect-{name}-{}", std::process::id()));
1668 let _ = std::fs::remove_dir_all(&dir);
1669 for (path, text) in files {
1670 let path = dir.join(path);
1671 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1672 std::fs::write(path, text).unwrap();
1673 }
1674 std::fs::create_dir_all(&dir).unwrap();
1675 dir
1676 }
1677
1678 #[test]
1679 fn detect_finds_a_workers_project_and_how_it_builds() {
1680 let dir = project(
1681 "workers",
1682 &[
1683 ("wrangler.jsonc", r#"{ "main": "src/index.ts", "assets": { "directory": "./public" }, }"#),
1684 ("package.json", "{}"),
1685 ("pnpm-lock.yaml", ""),
1686 ],
1687 );
1688 let found = detect(&dir, None, None).unwrap();
1689 assert_eq!(found.kind, "workers");
1690 assert_eq!(found.install.as_deref(), Some("corepack enable && pnpm install --frozen-lockfile"));
1691 assert_eq!(found.framework, None);
1692 assert_eq!(found.build.as_deref(), Some("npx --yes wrangler@4 deploy --dry-run"));
1693 assert_eq!(found.output_dir.as_deref(), Some("./public"));
1694 // The project's own build command runs first.
1695 let custom = detect(&dir, Some("npm run codegen"), None).unwrap();
1696 assert_eq!(custom.build.as_deref(), Some("npm run codegen && npx --yes wrangler@4 deploy --dry-run"));
1697 }
1698
1699 #[test]
1700 fn detect_finds_a_static_build_and_a_plain_site() {
1701 let built = project("static", &[("package.json", r#"{ "scripts": { "build": "vite build" } }"#), ("package-lock.json", "{}")]);
1702 let found = detect(&built, None, None).unwrap();
1703 assert_eq!(found.kind, "static");
1704 assert_eq!(found.install.as_deref(), Some("npm ci"));
1705 assert_eq!(found.build.as_deref(), Some("npm run build"));
1706 assert_eq!(found.output_dir, None, "its output is found once it has built");
1707 assert_eq!(found.framework, None, "a build script alone names no framework");
1708 std::fs::create_dir_all(built.join("dist")).unwrap();
1709 std::fs::write(built.join("dist/index.html"), "<h1>hi</h1>").unwrap();
1710 assert_eq!(detect(&built, None, None).unwrap().output_dir.as_deref(), Some("dist"));
1711 assert_eq!(detect(&built, None, Some("/site/")).unwrap().output_dir.as_deref(), Some("site"));
1712
1713 let html = project("html", &[("index.html", "<h1>hi</h1>")]);
1714 let found = detect(&html, None, None).unwrap();
1715 assert_eq!((found.kind, found.install, found.build, found.output_dir.as_deref()), ("html", None, None, Some(".")));
1716 // A `public` folder alone, without an index.html, is not a site.
1717 let empty = project("empty", &[("public/robots.txt", ""), ("README.md", "")]);
1718 assert_eq!(detect(&empty, None, None).unwrap().kind, "none");
1719 }
1720
1721 #[test]
1722 fn detect_prints_lines_for_github_output() {
1723 let mut found = Detected {
1724 kind: "static",
1725 framework: None,
1726 install: Some("npm ci".into()),
1727 build: Some("a\nb".into()),
1728 output_dir: None,
1729 problem: None,
1730 pre_build: None,
1731 container: None,
1732 fallback: None,
1733 };
1734 assert_eq!(output_lines(&found), "kind=static\ninstall=npm ci\nbuild=a b\noutput-dir=\n");
1735 let vite = project("lines", &[("package.json", r#"{ "devDependencies": { "vite": "7" } }"#)]);
1736 found.framework = frameworks::detect(&vite, false);
1737 assert!(output_lines(&found).ends_with("output-dir=\nframework=vite\n"));
1738 }
1739
1740 /// One project of the table below: its files, the project's own
1741 /// settings, and what detect should say.
1742 struct Case {
1743 name: &'static str,
1744 files: &'static [(&'static str, &'static str)],
1745 custom_build: Option<&'static str>,
1746 chosen_output: Option<&'static str>,
1747 kind: &'static str,
1748 framework: Option<&'static str>,
1749 build: Option<&'static str>,
1750 output_dir: Option<&'static str>,
1751 /// A phrase the problem says, if there is one.
1752 problem: Option<&'static str>,
1753 }
1754
1755 const CASE: Case = Case {
1756 name: "",
1757 files: &[],
1758 custom_build: None,
1759 chosen_output: None,
1760 kind: "static",
1761 framework: None,
1762 build: Some("npm run build"),
1763 output_dir: None,
1764 problem: None,
1765 };
1766
1767 #[test]
1768 fn detect_knows_each_framework() {
1769 let cases = [
1770 Case {
1771 name: "vite",
1772 files: &[("package.json", r#"{ "devDependencies": { "vite": "7" } }"#)],
1773 framework: Some("vite"),
1774 build: Some("npx vite build"),
1775 output_dir: Some("dist"),
1776 ..CASE
1777 },
1778 Case {
1779 name: "vite-react",
1780 files: &[
1781 ("package.json", r#"{ "scripts": { "build": "tsc && vite build" }, "dependencies": { "react": "19" }, "devDependencies": { "vite": "7", "@vitejs/plugin-react": "5" } }"#),
1782 ("vite.config.ts", "export default defineConfig({ plugins: [react()], build: { outDir: 'site' } })"),
1783 ],
1784 framework: Some("vite-react"),
1785 output_dir: Some("site"),
1786 ..CASE
1787 },
1788 Case {
1789 name: "vite-vue",
1790 files: &[("package.json", r#"{ "scripts": { "build": "vite build" }, "devDependencies": { "vite": "7", "@vitejs/plugin-vue": "6" } }"#)],
1791 framework: Some("vite-vue"),
1792 output_dir: Some("dist"),
1793 ..CASE
1794 },
1795 Case {
1796 name: "vite-svelte",
1797 files: &[("package.json", r#"{ "devDependencies": { "vite": "7", "@sveltejs/vite-plugin-svelte": "6" } }"#)],
1798 framework: Some("vite-svelte"),
1799 build: Some("npx vite build"),
1800 output_dir: Some("dist"),
1801 ..CASE
1802 },
1803 Case {
1804 name: "vite-solid",
1805 files: &[("package.json", r#"{ "devDependencies": { "vite": "7", "vite-plugin-solid": "2" } }"#)],
1806 framework: Some("vite-solid"),
1807 build: Some("npx vite build"),
1808 output_dir: Some("dist"),
1809 ..CASE
1810 },
1811 Case {
1812 name: "vite-cloudflare",
1813 files: &[
1814 ("package.json", r#"{ "scripts": { "build": "vite build" }, "devDependencies": { "vite": "7", "@cloudflare/vite-plugin": "1" } }"#),
1815 ("wrangler.jsonc", r#"{ "main": "worker/index.ts" }"#),
1816 ],
1817 kind: "workers",
1818 framework: Some("vite"),
1819 build: Some("npm run build && npx --yes wrangler@4 deploy --dry-run"),
1820 ..CASE
1821 },
1822 Case {
1823 name: "astro",
1824 files: &[("package.json", r#"{ "scripts": { "build": "astro build" }, "dependencies": { "astro": "5" } }"#), ("astro.config.mjs", "export default defineConfig({ site: 'https://x.dev' })")],
1825 framework: Some("astro"),
1826 output_dir: Some("dist"),
1827 ..CASE
1828 },
1829 Case {
1830 name: "astro-server",
1831 files: &[("package.json", r#"{ "dependencies": { "astro": "5", "@astrojs/node": "9" } }"#), ("astro.config.mjs", "export default { output: \"server\" }")],
1832 kind: "container",
1833 framework: Some("astro"),
1834 build: Some(GENERATED),
1835 ..CASE
1836 },
1837 Case {
1838 name: "astro-cloudflare",
1839 files: &[("package.json", r#"{ "scripts": { "build": "astro build" }, "dependencies": { "astro": "5", "@astrojs/cloudflare": "12" } }"#)],
1840 kind: "workers",
1841 framework: Some("astro"),
1842 ..CASE
1843 },
1844 Case {
1845 name: "astro-cloudflare-folder",
1846 files: &[("package.json", r#"{ "scripts": { "build": "astro build" }, "dependencies": { "astro": "5", "@astrojs/cloudflare": "12" } }"#)],
1847 chosen_output: Some("dist"),
1848 framework: Some("astro"),
1849 output_dir: Some("dist"),
1850 ..CASE
1851 },
1852 Case {
1853 name: "next-export",
1854 files: &[("package.json", r#"{ "scripts": { "build": "next build" }, "dependencies": { "next": "16" } }"#), ("next.config.ts", "const config: NextConfig = {\n output: 'export',\n};")],
1855 framework: Some("nextjs"),
1856 output_dir: Some("out"),
1857 ..CASE
1858 },
1859 Case {
1860 name: "next-server",
1861 files: &[("package.json", r#"{ "scripts": { "build": "next build" }, "dependencies": { "next": "16" } }"#), ("next.config.mjs", "export default {}")],
1862 kind: "container",
1863 framework: Some("nextjs"),
1864 build: Some(GENERATED),
1865 ..CASE
1866 },
1867 Case {
1868 name: "next-server-own-folder",
1869 files: &[("package.json", r#"{ "scripts": { "build": "next build" }, "dependencies": { "next": "16" } }"#)],
1870 chosen_output: Some("out"),
1871 framework: Some("nextjs"),
1872 output_dir: Some("out"),
1873 ..CASE
1874 },
1875 Case {
1876 name: "opennext",
1877 files: &[
1878 ("package.json", r#"{ "scripts": { "build": "next build" }, "dependencies": { "next": "16", "@opennextjs/cloudflare": "1" } }"#),
1879 ("wrangler.jsonc", r#"{ "main": ".open-next/worker.js", "assets": { "directory": ".open-next/assets", "binding": "ASSETS" } }"#),
1880 ],
1881 kind: "workers",
1882 framework: Some("nextjs"),
1883 build: Some("npx opennextjs-cloudflare build && npx --yes wrangler@4 deploy --dry-run"),
1884 output_dir: Some(".open-next/assets"),
1885 ..CASE
1886 },
1887 Case {
1888 name: "opennext-no-config",
1889 files: &[("package.json", r#"{ "dependencies": { "next": "16", "@opennextjs/cloudflare": "1" } }"#)],
1890 kind: "none",
1891 framework: Some("nextjs"),
1892 build: None,
1893 problem: Some("`.open-next/worker.js`"),
1894 ..CASE
1895 },
1896 Case {
1897 name: "sveltekit-static",
1898 files: &[
1899 ("package.json", r#"{ "scripts": { "build": "vite build" }, "devDependencies": { "@sveltejs/kit": "2", "@sveltejs/adapter-static": "3", "vite": "7" } }"#),
1900 ("svelte.config.js", "import adapter from '@sveltejs/adapter-static';\nexport default { kit: { adapter: adapter() } };"),
1901 ],
1902 framework: Some("sveltekit"),
1903 output_dir: Some("build"),
1904 ..CASE
1905 },
1906 Case {
1907 name: "sveltekit-3-static",
1908 files: &[
1909 ("package.json", r#"{ "scripts": { "build": "vite build" }, "devDependencies": { "@sveltejs/kit": "3", "@sveltejs/adapter-static": "4", "@sveltejs/adapter-cloudflare": "8" } }"#),
1910 ("vite.config.js", "import adapter from '@sveltejs/adapter-static';\nexport default defineConfig({ plugins: [sveltekit({ adapter: adapter({ pages: 'www' }) })] });"),
1911 ],
1912 framework: Some("sveltekit"),
1913 output_dir: Some("www"),
1914 ..CASE
1915 },
1916 Case {
1917 name: "sveltekit-cloudflare",
1918 files: &[("package.json", r#"{ "scripts": { "build": "vite build" }, "devDependencies": { "@sveltejs/kit": "2", "@sveltejs/adapter-cloudflare": "7" } }"#)],
1919 kind: "workers",
1920 framework: Some("sveltekit"),
1921 ..CASE
1922 },
1923 Case {
1924 name: "sveltekit-auto",
1925 files: &[("package.json", r#"{ "scripts": { "build": "vite build" }, "devDependencies": { "@sveltejs/kit": "2", "@sveltejs/adapter-auto": "6" } }"#)],
1926 kind: "none",
1927 framework: Some("sveltekit"),
1928 build: None,
1929 problem: Some("Or add a `Dockerfile`"),
1930 ..CASE
1931 },
1932 Case {
1933 name: "nuxt",
1934 files: &[("package.json", r#"{ "scripts": { "build": "nuxt build", "generate": "nuxt generate" }, "dependencies": { "nuxt": "4" } }"#)],
1935 framework: Some("nuxt"),
1936 build: Some("npm run generate"),
1937 output_dir: Some(".output/public"),
1938 ..CASE
1939 },
1940 Case {
1941 name: "nuxt-no-generate",
1942 files: &[("package.json", r#"{ "scripts": { "build": "nuxt build" }, "dependencies": { "nuxt": "4" } }"#)],
1943 framework: Some("nuxt"),
1944 build: Some("npx nuxi generate"),
1945 output_dir: Some(".output/public"),
1946 ..CASE
1947 },
1948 Case {
1949 name: "react-router-spa",
1950 files: &[
1951 ("package.json", r#"{ "scripts": { "build": "react-router build" }, "devDependencies": { "@react-router/dev": "7", "vite": "7" } }"#),
1952 ("react-router.config.ts", "export default {\n // Server-side render by default\n ssr: false,\n} satisfies Config;"),
1953 ],
1954 framework: Some("react-router"),
1955 output_dir: Some("build/client"),
1956 ..CASE
1957 },
1958 Case {
1959 name: "react-router-ssr",
1960 files: &[("package.json", r#"{ "devDependencies": { "@react-router/dev": "7" } }"#), ("react-router.config.ts", "export default { ssr: true }")],
1961 kind: "container",
1962 framework: Some("react-router"),
1963 build: Some(GENERATED),
1964 ..CASE
1965 },
1966 Case {
1967 name: "remix-spa",
1968 files: &[
1969 ("package.json", r#"{ "scripts": { "build": "remix vite:build" }, "devDependencies": { "@remix-run/dev": "2", "vite": "5" } }"#),
1970 ("vite.config.ts", "export default defineConfig({ plugins: [remix({ ssr: false })] })"),
1971 ],
1972 framework: Some("remix"),
1973 output_dir: Some("build/client"),
1974 ..CASE
1975 },
1976 Case {
1977 name: "gatsby",
1978 files: &[("package.json", r#"{ "scripts": { "build": "gatsby build" }, "dependencies": { "gatsby": "5" } }"#)],
1979 framework: Some("gatsby"),
1980 output_dir: Some("public"),
1981 ..CASE
1982 },
1983 Case {
1984 name: "docusaurus",
1985 files: &[("package.json", r#"{ "scripts": { "build": "docusaurus build" }, "dependencies": { "@docusaurus/core": "3" } }"#)],
1986 framework: Some("docusaurus"),
1987 output_dir: Some("build"),
1988 ..CASE
1989 },
1990 Case {
1991 name: "eleventy",
1992 files: &[("package.json", r#"{ "devDependencies": { "@11ty/eleventy": "3" } }"#)],
1993 framework: Some("eleventy"),
1994 build: Some("npx @11ty/eleventy"),
1995 output_dir: Some("_site"),
1996 ..CASE
1997 },
1998 Case {
1999 name: "angular",
2000 files: &[
2001 ("package.json", r#"{ "scripts": { "build": "ng build" }, "dependencies": { "@angular/core": "20" } }"#),
2002 ("angular.json", r#"{ "projects": { "shop": { "projectType": "application", "architect": { "build": { "builder": "@angular/build:application", "options": { "outputPath": "dist/shop" } } } } } }"#),
2003 ],
2004 framework: Some("angular"),
2005 output_dir: Some("dist/shop/browser"),
2006 ..CASE
2007 },
2008 Case {
2009 name: "angular-default",
2010 files: &[
2011 ("package.json", r#"{ "dependencies": { "@angular/core": "20" } }"#),
2012 ("angular.json", r#"{ "projects": { "app": { "projectType": "application", "architect": { "build": { "builder": "@angular/build:application", "options": {} } } } } }"#),
2013 ],
2014 framework: Some("angular"),
2015 build: Some("npx ng build"),
2016 output_dir: Some("dist/app/browser"),
2017 ..CASE
2018 },
2019 Case {
2020 name: "hugo",
2021 files: &[("hugo.toml", "baseURL = 'https://example.org/'\ntitle = 'Site'\n")],
2022 framework: Some("hugo"),
2023 build: Some(frameworks_hugo()),
2024 output_dir: Some("public"),
2025 ..CASE
2026 },
2027 Case {
2028 name: "hugo-config-toml",
2029 files: &[("config.toml", "baseURL = \"https://example.org/\"\npublishDir = \"site\"\n")],
2030 framework: Some("hugo"),
2031 build: Some(frameworks_hugo()),
2032 output_dir: Some("site"),
2033 ..CASE
2034 },
2035 Case {
2036 name: "not-hugo",
2037 files: &[("config.toml", "base_url = \"https://example.org\"\n"), ("index.html", "")],
2038 kind: "html",
2039 build: None,
2040 output_dir: Some("."),
2041 ..CASE
2042 },
2043 Case {
2044 name: "jekyll",
2045 files: &[("_config.yml", "title: Blog\n"), ("Gemfile", "gem 'jekyll'\n")],
2046 framework: Some("jekyll"),
2047 build: Some("bundle exec jekyll build"),
2048 output_dir: Some("_site"),
2049 ..CASE
2050 },
2051 Case {
2052 name: "mdbook",
2053 files: &[("book.toml", "[book]\ntitle = \"Guide\"\n")],
2054 framework: Some("mdbook"),
2055 build: Some(frameworks_mdbook()),
2056 output_dir: Some("book"),
2057 ..CASE
2058 },
2059 Case {
2060 name: "mdbook-build-dir",
2061 files: &[("book.toml", "[book]\ntitle = \"Guide\"\n[build]\nbuild-dir = \"site\"\n")],
2062 framework: Some("mdbook"),
2063 build: Some(frameworks_mdbook()),
2064 output_dir: Some("site"),
2065 ..CASE
2066 },
2067 // The project's own settings win.
2068 Case {
2069 name: "own-settings",
2070 files: &[("package.json", r#"{ "scripts": { "build": "vite build" }, "devDependencies": { "vite": "7" } }"#)],
2071 custom_build: Some("make site"),
2072 chosen_output: Some("www"),
2073 framework: Some("vite"),
2074 build: Some("make site"),
2075 output_dir: Some("www"),
2076 ..CASE
2077 },
2078 ];
2079 for case in cases {
2080 let dir = project(&format!("fw-{}", case.name), case.files);
2081 let found = detect(&dir, case.custom_build, case.chosen_output).unwrap();
2082 let name = case.name;
2083 assert_eq!(found.kind, case.kind, "{name}: kind");
2084 assert_eq!(found.framework.as_ref().map(|f| f.id), case.framework, "{name}: framework");
2085 assert_eq!(found.build.as_deref(), case.build, "{name}: build");
2086 assert_eq!(found.output_dir.as_deref(), case.output_dir, "{name}: output-dir");
2087 match case.problem {
2088 Some(phrase) => assert!(found.problem.as_deref().is_some_and(|p| p.contains(phrase)), "{name}: {:?}", found.problem),
2089 None => assert_eq!(found.problem, None, "{name}: problem"),
2090 }
2091 let _ = std::fs::remove_dir_all(&dir);
2092 }
2093 }
2094
2095 #[test]
2096 fn build_as_and_dockerfiles_decide_in_order() {
2097 let detect_with = |dir: &Path, build_as: BuildAs, dockerfile: Option<&str>| detect_as(dir, None, None, build_as, dockerfile).unwrap();
2098 // A framework that builds a static site stays one beside a
2099 // Dockerfile: it costs nothing while no one visits.
2100 let vite = project("p-vite", &[("package.json", r#"{ "devDependencies": { "vite": "7" } }"#), ("Dockerfile", "FROM nginx\nEXPOSE 80\n")]);
2101 assert_eq!(detect_with(&vite, BuildAs::Auto, None).kind, "static");
2102 // Unless the project says Docker.
2103 let found = detect_with(&vite, BuildAs::Docker, None);
2104 assert_eq!((found.kind, found.framework_id()), ("container", Some("vite")));
2105 let container = found.container.unwrap();
2106 assert_eq!((container.dockerfile.as_deref(), container.port), (Some("Dockerfile"), 80));
2107 // A Wrangler config wins in Auto, and not when it says Static site.
2108 let workers = project("p-workers", &[("wrangler.jsonc", r#"{ "assets": { "directory": "public" } }"#), ("index.html", "")]);
2109 assert_eq!(detect_with(&workers, BuildAs::Auto, None).kind, "workers");
2110 assert_eq!(detect_with(&workers, BuildAs::Static, None).kind, "html");
2111 // Workers, without a config or adapter, says what is missing.
2112 let html = project("p-html", &[("index.html", "<h1>hi</h1>")]);
2113 let found = detect_with(&html, BuildAs::Workers, None);
2114 assert_eq!(found.kind, "none");
2115 assert!(found.problem.unwrap().contains("no Wrangler config"));
2116 // No framework and a Dockerfile: a container, built as the site it
2117 // is without one while g1t.page runs no containers.
2118 let both = project("p-both", &[("index.html", ""), ("Containerfile", "FROM nginx")]);
2119 let found = detect_with(&both, BuildAs::Auto, None);
2120 assert_eq!((found.kind, found.framework_id()), ("container", Some("dockerfile")));
2121 assert_eq!(found.container.as_ref().unwrap().port, 8080);
2122 assert_eq!(found.fallback.as_ref().map(|site| site.kind), Some("html"));
2123 // A Dockerfile at a path of the project's choosing.
2124 let chosen = project("p-chosen", &[("ops/web.Dockerfile", "FROM node\nEXPOSE 3000")]);
2125 assert_eq!(detect_with(&chosen, BuildAs::Auto, None).kind, "none");
2126 let found = detect_with(&chosen, BuildAs::Auto, Some("ops/web.Dockerfile"));
2127 assert_eq!((found.kind, found.container.unwrap().port), ("container", 3000));
2128 assert!(detect_as(&chosen, None, None, BuildAs::Auto, Some("nope")).is_err());
2129 // A server g1t recognises gets a Dockerfile written for it.
2130 let express = project("p-express", &[("package.json", r#"{ "scripts": { "start": "node index.js" }, "dependencies": { "express": "5" } }"#)]);
2131 let found = detect_with(&express, BuildAs::Auto, None);
2132 assert_eq!((found.kind, found.framework_id(), found.install.as_deref()), ("container", Some("node"), None));
2133 assert!(found.fallback.is_none());
2134 assert!(output_lines(&found).ends_with("framework=node\ndockerfile=\nport=8080\n"));
2135 // Nothing at all says to add a Dockerfile.
2136 let nothing = project("p-nothing", &[("README.md", "")]);
2137 let found = detect_with(&nothing, BuildAs::Auto, None);
2138 assert_eq!(found.kind, "none");
2139 assert!(found.problem.as_deref().unwrap().starts_with("found nothing to serve"));
2140 assert!(found.problem.unwrap().contains("Add a `Dockerfile`"));
2141 let found = detect_with(&nothing, BuildAs::Docker, None);
2142 assert!(found.problem.unwrap().contains("**Build as** is Docker"));
2143 // A framework set up for a server, with a Dockerfile of its own.
2144 let next = project("p-next", &[("package.json", r#"{ "dependencies": { "next": "16" } }"#), ("Dockerfile", "FROM node")]);
2145 let found = detect_with(&next, BuildAs::Auto, None);
2146 assert_eq!((found.kind, found.framework_id()), ("container", Some("nextjs")));
2147 assert_eq!(found.container.unwrap().dockerfile.as_deref(), Some("Dockerfile"));
2148 // OpenNext's adapter means Workers: it is not run as a server.
2149 let opennext = project("p-opennext", &[("package.json", r#"{ "dependencies": { "next": "16", "@opennextjs/cloudflare": "1" } }"#)]);
2150 assert_eq!(detect_with(&opennext, BuildAs::Auto, None).kind, "none");
2151 for dir in [vite, workers, html, both, chosen, express, nothing, next, opennext] {
2152 let _ = std::fs::remove_dir_all(dir);
2153 }
2154 }
2155
2156 #[test]
2157 fn the_pushed_digest_is_the_one_in_the_apps_repository() {
2158 let digest = "a".repeat(64);
2159 let lines = format!("docker.io/x@sha256:{digest}\nregistry.cloudflare.com/acc/other@sha256:{digest}\nregistry.cloudflare.com/acc/g1t-web@sha256:{digest}\n");
2160 assert_eq!(
2161 pushed_digest(&lines, "registry.cloudflare.com", "acc/g1t-web"),
2162 Some(format!("registry.cloudflare.com/acc/g1t-web@sha256:{digest}"))
2163 );
2164 assert_eq!(pushed_digest("registry.cloudflare.com/acc/g1t-web@sha256:short", "registry.cloudflare.com", "acc/g1t-web"), None);
2165 let grant: RegistryGrant = serde_json::from_value(json!({
2166 "registry": "registry.cloudflare.com", "repository": "acc/g1t-web", "tag": "dpl_1",
2167 "username": "u", "password": "p", "max_image_bytes": 2_000_000_000u64, "instance_type": "lite"
2168 }))
2169 .unwrap();
2170 assert_eq!((grant.max_image_bytes, grant.instance_type.as_deref()), (2_000_000_000, Some("lite")));
2171 assert_eq!(size_text(1_450_000_000), "1.4 GB");
2172 }
2173
2174 /// What a container g1t writes the Dockerfile for is built with.
2175 const GENERATED: &str = "docker build -f Dockerfile (written by g1t) .";
2176
2177 fn frameworks_hugo() -> &'static str {
2178 "if command -v hugo >/dev/null 2>&1; then hugo --minify; else npx --yes hugo-extended@0.166.0 --minify; fi"
2179 }
2180
2181 fn frameworks_mdbook() -> &'static str {
2182 "if ! command -v mdbook >/dev/null 2>&1; then cargo install mdbook --version 0.5.4 --locked --quiet; fi && mdbook build"
2183 }
2184
2185 #[test]
2186 fn jekyll_installs_its_gems_after_the_packages() {
2187 let dir = project("jekyll-install", &[("_config.yml", ""), ("Gemfile", ""), ("package.json", "{}")]);
2188 let found = detect(&dir, None, None).unwrap();
2189 assert_eq!(found.install.as_deref(), Some("npm install && bundle config set --local path vendor/bundle && bundle install"));
2190 }
2191
2192 #[test]
2193 fn an_adapters_worker_is_found_once_built_and_never_served() {
2194 let dir = project(
2195 "adapter",
2196 &[
2197 ("dist/_worker.js/index.js", "export default {}"),
2198 ("dist/_routes.json", "{}"),
2199 ("dist/.assetsignore", "_worker.js\nsecret.txt\n"),
2200 ("dist/secret.txt", "no"),
2201 ("dist/index.html", "<h1>hi</h1>"),
2202 ("dist/about/_worker.js", "a page's own file"),
2203 ("kit/.svelte-kit/cloudflare/_worker.js", "export default {}"),
2204 ],
2205 );
2206 let astro = Adapter { entry: "dist/_worker.js", assets: "dist" };
2207 assert_eq!(adapter_entry(&dir, &astro), Some(dir.join("dist/_worker.js/index.js")));
2208 let kit = Adapter { entry: ".svelte-kit/cloudflare/_worker.js", assets: ".svelte-kit/cloudflare" };
2209 assert_eq!(adapter_entry(&dir.join("kit"), &kit), Some(dir.join("kit/.svelte-kit/cloudflare/_worker.js")));
2210 assert_eq!(adapter_entry(&dir.join("missing"), &kit), None);
2211 let mut served: Vec<String> = collect_site(&dir.join("dist"), false).unwrap().into_iter().map(|a| a.path).collect();
2212 served.sort();
2213 assert_eq!(served, ["/about/_worker.js", "/index.html"]);
2214 }
2215
2216 #[test]
2217 fn a_config_the_build_wrote_is_read_in_place_of_the_projects() {
2218 let dir = project(
2219 "redirected",
2220 &[
2221 ("wrangler.jsonc", r#"{ "main": "worker/index.ts" }"#),
2222 (".wrangler/deploy/config.json", r#"{ "configPath": "../../dist/app/wrangler.json" }"#),
2223 ("dist/app/wrangler.json", r#"{ "main": "index.js", "assets": { "directory": "../client" } }"#),
2224 ],
2225 );
2226 let (config, base) = redirected_config(&dir).unwrap().unwrap();
2227 assert_eq!(config.main.as_deref(), Some("index.js"));
2228 assert_eq!(base, canonical(&dir.join("dist/app")).unwrap());
2229 assert!(base.join(config.assets.unwrap().directory.unwrap()).ends_with("dist/app/../client"));
2230 assert!(redirected_config(&project("not-redirected", &[])).unwrap().is_none());
2231 }
2232
2233 #[test]
2234 fn the_root_directory_stays_inside_the_checkout() {
2235 let base = Path::new("/w/repo");
2236 assert_eq!(project_dir_in(base, ""), base);
2237 assert_eq!(project_dir_in(base, "."), base);
2238 assert_eq!(project_dir_in(base, "/apps/site/"), base.join("apps/site"));
2239 assert_eq!(project_dir_in(base, "../etc"), base);
2240 assert_eq!(project_dir_in(base, "apps/../../x"), base);
2241 }
2242
2243 #[test]
2244 fn a_step_prints_the_log_redacted() {
2245 let mut log = Log { echo: Some(vec!["hunter22".to_owned()]), ..Log::default() };
2246 log.line("token hunter22 used");
2247 assert!(log.text.contains("hunter22"), "the deployment's log is redacted when it is sent");
2248 assert_eq!(wrangler_build(Some(Path::new("/tmp/b")), None), "npx --yes wrangler@4 deploy --dry-run --outdir /tmp/b");
2249 assert_eq!(
2250 wrangler_build(Some(Path::new("/tmp/b")), Some(Path::new("/tmp/w.json"))),
2251 "npx --yes wrangler@4 deploy --dry-run --config /tmp/w.json --outdir /tmp/b"
2252 );
2253 }
2254}