Skip to content
718 linesCodeBlameRaw
1//! Projects that deploy as a container: their own `Dockerfile` (or
2//! `Containerfile`, or the path the project chose), or, for a server g1t
3//! recognises without one, a Dockerfile g1t writes, as `fly launch` does.
4//! What is built here runs on Cloudflare Containers behind the app's
5//! Worker (the deployments service's containers.ts). Nothing here runs
6//! anything: it reads the project and says what to build.
7
8use std::path::Path;
9
10use anyhow::{Result, bail};
11use serde_json::Value;
12
13/// The port a container listens on when its Dockerfile names none, and
14/// what every Dockerfile g1t writes listens on. `PORT` says it, too.
15pub(crate) const DEFAULT_PORT: u16 = 8080;
16
17/// What the project's **Build as** setting says it is.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19pub(crate) enum BuildAs {
20 /// Found from its files: see `detect` in deploy.rs.
21 #[default]
22 Auto,
23 /// Built and served as a static site, whatever else it has.
24 Static,
25 /// A Workers project: its Wrangler config, or a framework's adapter.
26 Workers,
27 /// A container, from its Dockerfile or one g1t writes.
28 Docker,
29}
30
31impl BuildAs {
32 /// `BUILD_AS`, as the deployments service sends the setting: `auto`,
33 /// `static`, `workers` or `docker`; anything else is `auto`.
34 pub(crate) fn parse(value: &str) -> BuildAs {
35 match value.trim().to_ascii_lowercase().as_str() {
36 "static" => BuildAs::Static,
37 "workers" => BuildAs::Workers,
38 "docker" | "container" => BuildAs::Docker,
39 _ => BuildAs::Auto,
40 }
41 }
42}
43
44/// The names a project's own Dockerfile is found by, in order.
45const DOCKERFILES: [&str; 3] = ["Dockerfile", "Containerfile", "dockerfile"];
46
47/// The project's own Dockerfile, relative to the project: the path it
48/// chose (which must exist), else the first of `DOCKERFILES`.
49pub(crate) fn own_dockerfile(dir: &Path, chosen: Option<&str>) -> Result<Option<String>> {
50 if let Some(chosen) = chosen.map(|c| c.trim().trim_start_matches("./")).filter(|c| !c.is_empty()) {
51 if chosen.split('/').any(|part| part == "..") || chosen.starts_with('/') {
52 bail!("the Dockerfile path `{chosen}` must be inside the project");
53 }
54 if !dir.join(chosen).is_file() {
55 bail!("the Dockerfile `{chosen}` set in the project's settings does not exist");
56 }
57 return Ok(Some(chosen.to_owned()));
58 }
59 Ok(DOCKERFILES.iter().find(|name| dir.join(name).is_file()).map(|name| (*name).to_owned()))
60}
61
62/// The instructions of a Dockerfile's last stage, the one that runs: each
63/// as its keyword in capitals and the rest of its line. Lines continued
64/// with `\` are joined, and comments dropped.
65fn last_stage(dockerfile: &str) -> Vec<(String, String)> {
66 let mut joined = Vec::new();
67 let mut current = String::new();
68 for line in dockerfile.lines() {
69 let trimmed = line.trim();
70 if current.is_empty() && (trimmed.is_empty() || trimmed.starts_with('#')) {
71 continue;
72 }
73 match trimmed.strip_suffix('\\') {
74 Some(start) => {
75 current.push_str(start);
76 current.push(' ');
77 }
78 None => {
79 current.push_str(trimmed);
80 joined.push(std::mem::take(&mut current));
81 }
82 }
83 }
84 if !current.is_empty() {
85 joined.push(current);
86 }
87 let mut stage = Vec::new();
88 for line in joined {
89 let (word, rest) = line.split_once(char::is_whitespace).unwrap_or((line.as_str(), ""));
90 let word = word.to_ascii_uppercase();
91 if word == "FROM" {
92 // Each stage starts afresh: only the last one's is what runs.
93 stage.clear();
94 }
95 stage.push((word, rest.trim().to_owned()));
96 }
97 stage
98}
99
100/// The port a Dockerfile's last stage says it listens on: its first
101/// `EXPOSE` there, else the `PORT` it sets with `ENV`, if it says.
102pub(crate) fn exposed_port(dockerfile: &str) -> Option<u16> {
103 let stage = last_stage(dockerfile);
104 let port = |text: &str| text.split('/').next().and_then(|p| p.trim_matches('"').parse::<u16>().ok()).filter(|p| *p > 0);
105 let exposed = stage.iter().filter(|(word, _)| word == "EXPOSE").find_map(|(_, rest)| rest.split_whitespace().next().and_then(port));
106 exposed.or_else(|| {
107 stage.iter().rev().filter(|(word, _)| word == "ENV").find_map(|(_, rest)| {
108 // `ENV PORT=3000 OTHER=x`, or the old `ENV PORT 3000`.
109 if let Some(value) = rest.split_whitespace().find_map(|pair| pair.strip_prefix("PORT=")) {
110 return port(value);
111 }
112 let mut words = rest.split_whitespace();
113 (words.next() == Some("PORT")).then(|| words.next().and_then(port)).flatten()
114 })
115 })
116}
117
118/// A server g1t can write a Dockerfile for.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub(crate) struct Server {
121 /// As `g1t-runner detect` prints it when no framework names it:
122 /// `node`, `django`, `flask`, `fastapi`, `python`, `go`, `rails`,
123 /// `rack`, `laravel`, `php`, `rust`.
124 pub id: &'static str,
125 /// For the build's log: `Node.js`, `Django`…
126 pub name: &'static str,
127 /// The Dockerfile, whole.
128 pub dockerfile: String,
129}
130
131/// What a generated Dockerfile leaves out of the image.
132pub(crate) const DOCKERIGNORE: &str = ".git\nnode_modules\n.venv\n__pycache__\n.wrangler\n.g1t\n";
133
134fn header(name: &str) -> String {
135 format!(
136 "# Written by g1t for this {name} project, which has no Dockerfile of its own.\n\
137 # To change how it is built or run, commit this file as `Dockerfile` and edit it.\n"
138 )
139}
140
141/// `package.json`, as read.
142fn package(dir: &Path) -> Option<Value> {
143 serde_json::from_str(&std::fs::read_to_string(dir.join("package.json")).ok()?).ok()
144}
145
146fn has_dependency(package: &Value, name: &str) -> bool {
147 ["dependencies", "devDependencies"].iter().any(|field| package[field].get(name).is_some())
148}
149
150/// Packages that make a Node.js project a server of its own.
151const NODE_SERVERS: [&str; 15] = [
152 "express",
153 "fastify",
154 "koa",
155 "@hapi/hapi",
156 "@nestjs/core",
157 "@hono/node-server",
158 "hono",
159 "restify",
160 "polka",
161 "@adonisjs/core",
162 "sails",
163 "socket.io",
164 "@remix-run/serve",
165 "@react-router/serve",
166 "@feathersjs/feathers",
167];
168
169/// The Node.js version to build with: `.nvmrc` or `.node-version` when it
170/// names a major release g1t can pull, else 22.
171fn node_major(dir: &Path) -> u32 {
172 [".nvmrc", ".node-version"]
173 .iter()
174 .find_map(|name| std::fs::read_to_string(dir.join(name)).ok())
175 .and_then(|text| {
176 let digits: String = text.trim().trim_start_matches('v').chars().take_while(char::is_ascii_digit).collect();
177 digits.parse::<u32>().ok()
178 })
179 .filter(|major| (18..=30).contains(major))
180 .unwrap_or(22)
181}
182
183/// How a Node.js project installs, in the image.
184fn node_install(dir: &Path) -> &'static str {
185 if dir.join("pnpm-lock.yaml").exists() {
186 "corepack enable && pnpm install --frozen-lockfile --prod=false"
187 } else if dir.join("yarn.lock").exists() {
188 "corepack enable && yarn install"
189 } else if dir.join("bun.lockb").exists() || dir.join("bun.lock").exists() {
190 "npx --yes bun install"
191 } else if dir.join("package-lock.json").exists() {
192 "npm ci --include=dev"
193 } else {
194 "npm install --include=dev"
195 }
196}
197
198/// A Node.js server's Dockerfile: installed, built if it has a `build`
199/// script, then started with `start`.
200fn node_dockerfile(dir: &Path, name: &str, start: &str, build: Option<&str>) -> String {
201 let build = build.map(|command| format!("RUN {command}\n")).unwrap_or_default();
202 format!(
203 "{header}FROM node:{major}-slim\n\
204 WORKDIR /app\n\
205 COPY . .\n\
206 RUN {install}\n\
207 {build}\
208 ENV NODE_ENV=production HOST=0.0.0.0 HOSTNAME=0.0.0.0 PORT={DEFAULT_PORT}\n\
209 EXPOSE {DEFAULT_PORT}\n\
210 CMD {start}\n",
211 header = header(name),
212 major = node_major(dir),
213 install = node_install(dir),
214 )
215}
216
217/// Whether a Next.js app builds a standalone server (`output:
218/// 'standalone'`), which `next start` does not run.
219fn next_standalone(dir: &Path) -> bool {
220 ["next.config.js", "next.config.mjs", "next.config.ts", "next.config.cjs"].iter().any(|name| {
221 std::fs::read_to_string(dir.join(name)).is_ok_and(|text| {
222 let text: String = text.chars().filter(|c| !c.is_whitespace()).collect();
223 ["output:\"standalone\"", "output:'standalone'", "output:`standalone`"].iter().any(|form| text.contains(form))
224 })
225 })
226}
227
228/// The command a Node.js server starts with, as a Dockerfile's exec form.
229fn exec(words: &[&str]) -> String {
230 let quoted: Vec<String> = words.iter().map(|w| format!("\"{w}\"")).collect();
231 format!("[{}]", quoted.join(", "))
232}
233
234/// A shell command as a Dockerfile's `CMD`, so `$PORT` is read when it starts.
235fn shell(command: &str) -> String {
236 exec(&["sh", "-c", &format!("exec {command}")])
237}
238
239/// A Dockerfile for a framework that needs a server (`framework`, from
240/// frameworks.rs), when g1t knows how to run it: Next.js with `next
241/// start`, Astro with `@astrojs/node`, SvelteKit with `adapter-node`,
242/// React Router and Remix with their own server.
243pub(crate) fn for_framework(dir: &Path, framework: &str) -> Option<Server> {
244 let package = package(dir)?;
245 let scripts = &package["scripts"];
246 let script = |name: &str| scripts[name].as_str();
247 let has_build = script("build").is_some();
248 let start = |fallback: &[&str]| if script("start").is_some() { exec(&["npm", "start"]) } else { exec(fallback) };
249 let (name, command, own_build) = match framework {
250 // A standalone build is its own server, with the static files it
251 // serves copied beside it, as Next.js's guide does.
252 "nextjs" if next_standalone(dir) => {
253 let build = if has_build { "npm run build" } else { "npx next build" };
254 let build = format!(
255 "{build} && cp -r .next/static .next/standalone/.next/static && if [ -d public ]; then cp -r public .next/standalone/public; fi"
256 );
257 return Some(Server {
258 id: "node",
259 name: "Next.js",
260 dockerfile: node_dockerfile(dir, "Next.js", &exec(&["node", ".next/standalone/server.js"]), Some(&build)),
261 });
262 }
263 "nextjs" => ("Next.js", start(&["npx", "next", "start"]), "npx next build"),
264 // `astro dev` is a common `start` script, so Astro's node adapter's
265 // own server is run instead.
266 "astro" if has_dependency(&package, "@astrojs/node") => ("Astro", exec(&["node", "./dist/server/entry.mjs"]), "npx astro build"),
267 "sveltekit" if has_dependency(&package, "@sveltejs/adapter-node") => ("SvelteKit", exec(&["node", "build"]), "npx vite build"),
268 "react-router" => ("React Router", start(&["npx", "react-router-serve", "./build/server/index.js"]), "npx react-router build"),
269 "remix" => ("Remix", start(&["npx", "remix-serve", "./build/server/index.js"]), "npx remix vite:build"),
270 _ => return None,
271 };
272 // Its own `build` script, else the framework's command.
273 let build = if has_build { "npm run build" } else { own_build };
274 Some(Server { id: "node", name, dockerfile: node_dockerfile(dir, name, &command, Some(build)) })
275}
276
277/// A server g1t recognises in a project with no framework it knows, and
278/// the Dockerfile it writes for it.
279pub(crate) fn server(dir: &Path) -> Option<Server> {
280 node_server(dir)
281 .or_else(|| python(dir))
282 .or_else(|| go(dir))
283 .or_else(|| ruby(dir))
284 .or_else(|| php(dir))
285 .or_else(|| rust(dir))
286}
287
288/// Crates that make a Rust program a web server.
289const RUST_SERVERS: [&str; 7] = ["axum", "actix-web", "rocket", "warp", "poem", "salvo", "tide"];
290
291/// A Rust web server: a `Cargo.toml` with one program, depending on a web
292/// framework.
293fn rust(dir: &Path) -> Option<Server> {
294 let manifest: toml::Value = toml::from_str(&std::fs::read_to_string(dir.join("Cargo.toml")).ok()?).ok()?;
295 let package = manifest.get("package")?.get("name")?.as_str()?;
296 let dependencies = manifest.get("dependencies")?.as_table()?;
297 if !RUST_SERVERS.iter().any(|name| dependencies.contains_key(*name)) {
298 return None;
299 }
300 // Its one `[[bin]]`, else the package's own program.
301 let bins: Vec<&str> = manifest
302 .get("bin")
303 .and_then(|bins| bins.as_array())
304 .map(|bins| bins.iter().filter_map(|bin| bin.get("name")?.as_str()).collect())
305 .unwrap_or_default();
306 let program = match bins.as_slice() {
307 [] if dir.join("src/main.rs").is_file() => package,
308 [one] => one,
309 // None, or more than one: which to run is the project's to say.
310 _ => return None,
311 };
312 if !program.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
313 return None;
314 }
315 let dockerfile = format!(
316 "{header}FROM rust:1-bookworm AS build\n\
317 WORKDIR /src\n\
318 COPY . .\n\
319 RUN cargo build --release --locked --bin {program} || cargo build --release --bin {program}\n\
320 RUN cp target/release/{program} /app\n\
321 \n\
322 FROM debian:bookworm-slim\n\
323 RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*\n\
324 COPY --from=build /app /app\n\
325 ENV PORT={DEFAULT_PORT}\n\
326 EXPOSE {DEFAULT_PORT}\n\
327 ENTRYPOINT [\"/app\"]\n",
328 header = header("Rust"),
329 );
330 Some(Server { id: "rust", name: "Rust", dockerfile })
331}
332
333/// A Node.js server: a `start` script, with a server package or nothing
334/// that looks like a static site (no `build` script and no `index.html`).
335pub(crate) fn node_server(dir: &Path) -> Option<Server> {
336 let package = package(dir)?;
337 let scripts = &package["scripts"];
338 let server_package = NODE_SERVERS.iter().any(|name| has_dependency(&package, name));
339 let has_build = scripts["build"].is_string();
340 let start = if scripts["start"].is_string() {
341 exec(&["npm", "start"])
342 } else if server_package {
343 let main = package["main"].as_str().map(str::to_owned).or_else(|| {
344 ["server.js", "index.js", "app.js", "server.mjs", "index.mjs"].iter().find(|f| dir.join(f).is_file()).map(|f| (*f).to_owned())
345 })?;
346 exec(&["node", &main])
347 } else {
348 return None;
349 };
350 if !server_package && (has_build || dir.join("index.html").exists()) {
351 return None;
352 }
353 Some(Server { id: "node", name: "Node.js", dockerfile: node_dockerfile(dir, "Node.js", &start, has_build.then_some("npm run build")) })
354}
355
356/// A Python web app: its requirements, and the file that starts it.
357fn python(dir: &Path) -> Option<Server> {
358 let requirements = ["requirements.txt", "pyproject.toml", "Pipfile"].iter().find(|f| dir.join(f).is_file())?;
359 let text = ["requirements.txt", "pyproject.toml", "Pipfile"]
360 .iter()
361 .filter_map(|f| std::fs::read_to_string(dir.join(f)).ok())
362 .collect::<Vec<_>>()
363 .join("\n")
364 .to_ascii_lowercase();
365 let uses = |name: &str| {
366 text.lines().any(|line| {
367 let line = line.trim().trim_start_matches(['"', '\'']);
368 line.starts_with(name) && !line[name.len()..].starts_with(|c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
369 })
370 };
371 let install = match *requirements {
372 "requirements.txt" => "pip install --no-cache-dir -r requirements.txt",
373 "Pipfile" => "pip install --no-cache-dir pipenv && pipenv install --system --deploy",
374 _ => "pip install --no-cache-dir .",
375 };
376 let module = ["app", "main", "server", "wsgi", "asgi"].iter().find(|m| dir.join(format!("{m}.py")).is_file()).copied();
377 let (id, name, extra, command) = if dir.join("manage.py").is_file() {
378 // Django: the project's package is the folder with its `wsgi.py`.
379 let project = std::fs::read_dir(dir)
380 .ok()?
381 .flatten()
382 .find(|entry| entry.path().join("wsgi.py").is_file())?
383 .file_name()
384 .to_string_lossy()
385 .into_owned();
386 ("django", "Django", "gunicorn", format!("gunicorn --bind 0.0.0.0:$PORT {project}.wsgi"))
387 } else if uses("fastapi") || uses("starlette") {
388 let module = module?;
389 ("fastapi", "FastAPI", "uvicorn", format!("uvicorn {module}:app --host 0.0.0.0 --port $PORT"))
390 } else if uses("flask") {
391 let module = module?;
392 ("flask", "Flask", "gunicorn", format!("gunicorn --bind 0.0.0.0:$PORT {module}:app"))
393 } else {
394 let module = module?;
395 ("python", "Python", "", format!("python {module}.py"))
396 };
397 let extra = if extra.is_empty() || uses(extra) { String::new() } else { format!(" && pip install --no-cache-dir {extra}") };
398 let dockerfile = format!(
399 "{header}FROM python:3.12-slim\n\
400 WORKDIR /app\n\
401 ENV PYTHONUNBUFFERED=1 PORT={DEFAULT_PORT}\n\
402 COPY . .\n\
403 RUN {install}{extra}\n\
404 EXPOSE {DEFAULT_PORT}\n\
405 CMD {cmd}\n",
406 header = header(name),
407 cmd = shell(&command),
408 );
409 Some(Server { id, name, dockerfile })
410}
411
412/// Whether a Go file is `package main`.
413fn is_main(path: &Path) -> bool {
414 std::fs::read_to_string(path).is_ok_and(|text| {
415 text.lines().map(str::trim).find(|line| line.starts_with("package ")).is_some_and(|line| line == "package main")
416 })
417}
418
419fn has_main(dir: &Path) -> bool {
420 std::fs::read_dir(dir).is_ok_and(|entries| {
421 entries.flatten().any(|entry| {
422 let path = entry.path();
423 path.extension().is_some_and(|e| e == "go") && !path.to_string_lossy().ends_with("_test.go") && is_main(&path)
424 })
425 })
426}
427
428/// A Go program: `go.mod`, and a `package main` at the top or in one
429/// folder of `cmd/`.
430fn go(dir: &Path) -> Option<Server> {
431 if !dir.join("go.mod").is_file() {
432 return None;
433 }
434 let target = if has_main(dir) {
435 ".".to_owned()
436 } else {
437 let mut commands: Vec<String> = std::fs::read_dir(dir.join("cmd"))
438 .ok()?
439 .flatten()
440 .filter(|entry| has_main(&entry.path()))
441 .map(|entry| format!("./cmd/{}", entry.file_name().to_string_lossy()))
442 .collect();
443 commands.sort();
444 // More than one program: which to run is the project's to say.
445 if commands.len() != 1 {
446 return None;
447 }
448 commands.remove(0)
449 };
450 let dockerfile = format!(
451 "{header}FROM golang:1.25 AS build\n\
452 WORKDIR /src\n\
453 COPY . .\n\
454 RUN go mod download && CGO_ENABLED=0 go build -trimpath -ldflags=-s -o /out/app {target}\n\
455 \n\
456 FROM scratch\n\
457 COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\n\
458 COPY --from=build /out/app /app\n\
459 ENV PORT={DEFAULT_PORT}\n\
460 EXPOSE {DEFAULT_PORT}\n\
461 ENTRYPOINT [\"/app\"]\n",
462 header = header("Go"),
463 );
464 Some(Server { id: "go", name: "Go", dockerfile })
465}
466
467/// A Ruby web app: Rails, or any Rack app with a `config.ru`.
468fn ruby(dir: &Path) -> Option<Server> {
469 let gemfile = std::fs::read_to_string(dir.join("Gemfile")).ok()?;
470 let rails = gemfile.lines().any(|line| {
471 let line = line.trim();
472 line.starts_with("gem \"rails\"") || line.starts_with("gem 'rails'")
473 });
474 let (id, name, setup, command) = if rails {
475 (
476 "rails",
477 "Rails",
478 "RUN if bundle exec rails -T assets:precompile 2>/dev/null | grep -q assets:precompile; then SECRET_KEY_BASE_DUMMY=1 bundle exec rails assets:precompile; fi\n",
479 "bundle exec rails server -b 0.0.0.0 -p $PORT",
480 )
481 } else if dir.join("config.ru").is_file() {
482 ("rack", "Rack", "", "bundle exec rackup -o 0.0.0.0 -p $PORT")
483 } else {
484 return None;
485 };
486 let dockerfile = format!(
487 "{header}FROM ruby:3.3-slim\n\
488 RUN apt-get update && apt-get install -y --no-install-recommends build-essential git libpq-dev libyaml-dev pkg-config && rm -rf /var/lib/apt/lists/*\n\
489 WORKDIR /app\n\
490 ENV RAILS_ENV=production RACK_ENV=production BUNDLE_WITHOUT=development:test RAILS_LOG_TO_STDOUT=1 RAILS_SERVE_STATIC_FILES=1 PORT={DEFAULT_PORT}\n\
491 COPY . .\n\
492 RUN bundle install\n\
493 {setup}\
494 EXPOSE {DEFAULT_PORT}\n\
495 CMD {cmd}\n",
496 header = header(name),
497 cmd = shell(command),
498 );
499 Some(Server { id, name, dockerfile })
500}
501
502/// A PHP app with Composer: Laravel, or any app with an `index.php`.
503fn php(dir: &Path) -> Option<Server> {
504 if !dir.join("composer.json").is_file() {
505 return None;
506 }
507 let (id, name) = if dir.join("artisan").is_file() { ("laravel", "Laravel") } else { ("php", "PHP") };
508 let root = if dir.join("public/index.php").is_file() {
509 "/var/www/html/public"
510 } else if dir.join("index.php").is_file() {
511 "/var/www/html"
512 } else {
513 return None;
514 };
515 let dockerfile = format!(
516 "{header}FROM composer:2 AS vendor\n\
517 WORKDIR /app\n\
518 COPY . .\n\
519 RUN composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader --ignore-platform-reqs\n\
520 \n\
521 FROM php:8.3-apache\n\
522 ENV PORT={DEFAULT_PORT} APACHE_DOCUMENT_ROOT={root}\n\
523 RUN sed -ri -e 's!/var/www/html!${{APACHE_DOCUMENT_ROOT}}!g' /etc/apache2/sites-available/*.conf /etc/apache2/apache2.conf \\\n \
524 && sed -ri -e 's/^Listen 80$/Listen ${{PORT}}/' /etc/apache2/ports.conf \\\n \
525 && sed -ri -e 's/:80>/:${{PORT}}>/' /etc/apache2/sites-available/000-default.conf \\\n \
526 && a2enmod rewrite\n\
527 COPY --from=vendor --chown=www-data:www-data /app /var/www/html\n\
528 EXPOSE {DEFAULT_PORT}\n",
529 header = header(name),
530 );
531 Some(Server { id, name, dockerfile })
532}
533
534#[cfg(test)]
535mod tests {
536 use super::*;
537
538 fn project(name: &str, files: &[(&str, &str)]) -> std::path::PathBuf {
539 let dir = std::env::temp_dir().join(format!("g1t-container-{name}-{}", std::process::id()));
540 let _ = std::fs::remove_dir_all(&dir);
541 std::fs::create_dir_all(&dir).unwrap();
542 for (path, text) in files {
543 let path = dir.join(path);
544 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
545 std::fs::write(path, text).unwrap();
546 }
547 dir
548 }
549
550 #[test]
551 fn build_as_is_read_from_the_setting() {
552 assert_eq!(BuildAs::parse("docker"), BuildAs::Docker);
553 assert_eq!(BuildAs::parse(" Static "), BuildAs::Static);
554 assert_eq!(BuildAs::parse("workers"), BuildAs::Workers);
555 assert_eq!(BuildAs::parse(""), BuildAs::Auto);
556 assert_eq!(BuildAs::parse("something"), BuildAs::Auto);
557 }
558
559 #[test]
560 fn a_dockerfile_is_found_by_its_names_or_the_chosen_path() {
561 let dir = project("own", &[("Containerfile", "FROM scratch"), ("deploy/web.Dockerfile", "FROM scratch")]);
562 assert_eq!(own_dockerfile(&dir, None).unwrap().as_deref(), Some("Containerfile"));
563 assert_eq!(own_dockerfile(&dir, Some("./deploy/web.Dockerfile")).unwrap().as_deref(), Some("deploy/web.Dockerfile"));
564 assert!(own_dockerfile(&dir, Some("missing/Dockerfile")).unwrap_err().to_string().contains("does not exist"));
565 assert!(own_dockerfile(&dir, Some("../etc/passwd")).is_err());
566 assert_eq!(own_dockerfile(&project("none", &[]), None).unwrap(), None);
567 }
568
569 #[test]
570 fn the_port_is_the_last_stages_first_expose() {
571 assert_eq!(exposed_port("FROM node\nEXPOSE 3000\nEXPOSE 9229"), Some(3000));
572 assert_eq!(exposed_port("FROM golang AS build\nEXPOSE 9000\nFROM scratch\nexpose 8000/tcp"), Some(8000));
573 assert_eq!(exposed_port("FROM golang AS build\nEXPOSE 9000\nFROM scratch\n"), None);
574 assert_eq!(exposed_port("FROM x\nEXPOSE $PORT"), None);
575 // Without an `EXPOSE`, the `PORT` it sets.
576 assert_eq!(exposed_port("FROM node\nENV NODE_ENV=production PORT=3000\nCMD node ."), Some(3000));
577 assert_eq!(exposed_port("FROM node\nENV PORT 4000"), Some(4000));
578 assert_eq!(exposed_port("FROM node\nENV PORT=1\nFROM node\nENV PORT=5000\nEXPOSE 7000"), Some(7000));
579 // Continued lines and comments.
580 assert_eq!(exposed_port("FROM node\n# EXPOSE 1\nRUN a \\\n && b\nEXPOSE \\\n 9000"), Some(9000));
581 }
582
583 #[test]
584 fn rust_servers_are_recognised() {
585 let axum = project("axum", &[("Cargo.toml", "[package]\nname = \"todo-api\"\n\n[dependencies]\naxum = \"0.8\"\n"), ("src/main.rs", "fn main() {}")]);
586 let found = server(&axum).unwrap();
587 assert_eq!((found.id, found.name), ("rust", "Rust"));
588 assert!(found.dockerfile.contains("--bin todo-api"));
589 assert!(found.dockerfile.contains("ENTRYPOINT [\"/app\"]"));
590 let lib = project("rust-lib", &[("Cargo.toml", "[package]\nname = \"x\"\n[dependencies]\nserde = \"1\"\n"), ("src/main.rs", "")]);
591 assert_eq!(server(&lib), None, "not a web server");
592 let two = project("rust-two", &[("Cargo.toml", "[package]\nname = \"x\"\n[dependencies]\naxum = \"0.8\"\n[[bin]]\nname = \"a\"\n[[bin]]\nname = \"b\"\n")]);
593 assert_eq!(server(&two), None, "which program runs is the project's to say");
594 }
595
596 #[test]
597 fn every_dockerfile_g1t_writes_listens_on_its_port() {
598 let projects = [
599 project("w-node", &[("package.json", r#"{ "scripts": { "start": "node i.js" }, "dependencies": { "express": "5" } }"#)]),
600 project("w-flask", &[("requirements.txt", "flask\n"), ("app.py", "")]),
601 project("w-go", &[("go.mod", "module x\n"), ("main.go", "package main")]),
602 project("w-rack", &[("Gemfile", "gem 'sinatra'\n"), ("config.ru", "")]),
603 project("w-php", &[("composer.json", "{}"), ("index.php", "")]),
604 ];
605 for dir in &projects {
606 let found = server(dir).unwrap();
607 assert_eq!(exposed_port(&found.dockerfile), Some(DEFAULT_PORT), "{}", found.id);
608 }
609 }
610
611 #[test]
612 fn a_standalone_next_app_runs_its_own_server() {
613 let next = project(
614 "next-standalone",
615 &[
616 ("package.json", r#"{ "scripts": { "build": "next build", "start": "next start" }, "dependencies": { "next": "16" } }"#),
617 ("next.config.mjs", "export default {\n output: \"standalone\",\n};\n"),
618 ],
619 );
620 let found = for_framework(&next, "nextjs").unwrap();
621 assert!(found.dockerfile.contains("RUN npm run build && cp -r .next/static .next/standalone/.next/static"));
622 assert!(found.dockerfile.contains("CMD [\"node\", \".next/standalone/server.js\"]"));
623 assert!(found.dockerfile.contains("HOSTNAME=0.0.0.0"));
624 }
625
626 #[test]
627 fn node_servers_are_recognised_and_static_sites_are_not() {
628 let express = project("express", &[("package.json", r#"{ "scripts": { "start": "node server.js" }, "dependencies": { "express": "5" } }"#), ("package-lock.json", "{}")]);
629 let found = server(&express).unwrap();
630 assert_eq!((found.id, found.name), ("node", "Node.js"));
631 assert!(found.dockerfile.contains("FROM node:22-slim"));
632 assert!(found.dockerfile.contains("RUN npm ci --include=dev"));
633 assert!(found.dockerfile.contains("CMD [\"npm\", \"start\"]"));
634 assert!(found.dockerfile.contains("EXPOSE 8080"));
635 assert!(!found.dockerfile.contains("npm run build"));
636 // A server package without a start script runs its main file.
637 let main = project("main", &[("package.json", r#"{ "main": "src/app.js", "dependencies": { "fastify": "5" } }"#), (".nvmrc", "v20.11\n")]);
638 let found = server(&main).unwrap();
639 assert!(found.dockerfile.contains("CMD [\"node\", \"src/app.js\"]"));
640 assert!(found.dockerfile.contains("FROM node:20-slim"));
641 // A start script beside a build script and no server package is a
642 // static site's preview server, not an app.
643 let site = project("site", &[("package.json", r#"{ "scripts": { "build": "x", "start": "serve dist" } }"#)]);
644 assert_eq!(server(&site), None);
645 assert_eq!(server(&project("bare", &[("package.json", "{}")])), None);
646 }
647
648 #[test]
649 fn python_apps_get_the_server_their_framework_runs_on() {
650 let flask = project("flask", &[("requirements.txt", "Flask==3.1\n"), ("app.py", "")]);
651 let found = server(&flask).unwrap();
652 assert_eq!(found.id, "flask");
653 assert!(found.dockerfile.contains("pip install --no-cache-dir -r requirements.txt && pip install --no-cache-dir gunicorn"));
654 assert!(found.dockerfile.contains(r#"CMD ["sh", "-c", "exec gunicorn --bind 0.0.0.0:$PORT app:app"]"#));
655 let fastapi = project("fastapi", &[("requirements.txt", "fastapi\nuvicorn[standard]\n"), ("main.py", "")]);
656 let found = server(&fastapi).unwrap();
657 assert_eq!(found.id, "fastapi");
658 assert!(!found.dockerfile.contains("pip install --no-cache-dir uvicorn"), "already required");
659 assert!(found.dockerfile.contains("uvicorn main:app --host 0.0.0.0 --port $PORT"));
660 let django = project("django", &[("requirements.txt", "Django>=5\ngunicorn\n"), ("manage.py", ""), ("shop/wsgi.py", "")]);
661 let found = server(&django).unwrap();
662 assert_eq!(found.id, "django");
663 assert!(found.dockerfile.contains("gunicorn --bind 0.0.0.0:$PORT shop.wsgi"));
664 // Requirements without an app to start (a docs site's) are not one.
665 assert_eq!(server(&project("mkdocs", &[("requirements.txt", "mkdocs\n"), ("mkdocs.yml", "")])), None);
666 // flask-cors is not Flask.
667 let cors = project("cors", &[("requirements.txt", "flask-cors\n"), ("app.py", "")]);
668 assert_eq!(server(&cors).unwrap().id, "python");
669 }
670
671 #[test]
672 fn go_ruby_and_php_apps_are_recognised() {
673 let go_root = project("go", &[("go.mod", "module x\n"), ("main.go", "// x\npackage main\n"), ("main_test.go", "package main")]);
674 let found = server(&go_root).unwrap();
675 assert_eq!(found.id, "go");
676 assert!(found.dockerfile.contains("go build -trimpath -ldflags=-s -o /out/app .\n"));
677 assert!(found.dockerfile.contains("FROM scratch"));
678 let go_cmd = project("gocmd", &[("go.mod", "module x\n"), ("lib.go", "package x"), ("cmd/api/main.go", "package main")]);
679 assert!(server(&go_cmd).unwrap().dockerfile.contains("-o /out/app ./cmd/api\n"));
680 let go_two = project("gotwo", &[("go.mod", "module x\n"), ("cmd/a/main.go", "package main"), ("cmd/b/main.go", "package main")]);
681 assert_eq!(server(&go_two), None, "which program runs is the project's to say");
682
683 let rails = project("rails", &[("Gemfile", "source 'https://rubygems.org'\ngem \"rails\", \"~> 8.0\"\n"), ("config.ru", "")]);
684 let found = server(&rails).unwrap();
685 assert_eq!(found.id, "rails");
686 assert!(found.dockerfile.contains("bundle exec rails server -b 0.0.0.0 -p $PORT"));
687 let rack = project("rack", &[("Gemfile", "gem 'sinatra'\n"), ("config.ru", "run App")]);
688 assert_eq!(server(&rack).unwrap().id, "rack");
689 assert_eq!(server(&project("gems", &[("Gemfile", "gem 'rake'\n")])), None);
690
691 let laravel = project("laravel", &[("composer.json", "{}"), ("artisan", ""), ("public/index.php", "")]);
692 let found = server(&laravel).unwrap();
693 assert_eq!(found.id, "laravel");
694 assert!(found.dockerfile.contains("APACHE_DOCUMENT_ROOT=/var/www/html/public"));
695 assert!(found.dockerfile.contains("Listen ${PORT}"));
696 assert_eq!(server(&project("composer", &[("composer.json", "{}")])), None);
697 }
698
699 #[test]
700 fn frameworks_that_need_a_server_get_one() {
701 let next = project("next", &[("package.json", r#"{ "scripts": { "build": "next build", "start": "next start" }, "dependencies": { "next": "16" } }"#)]);
702 let found = for_framework(&next, "nextjs").unwrap();
703 assert!(found.dockerfile.contains("RUN npm run build\n"));
704 assert!(found.dockerfile.contains("CMD [\"npm\", \"start\"]"));
705 let bare = project("next-bare", &[("package.json", r#"{ "dependencies": { "next": "16" } }"#)]);
706 let found = for_framework(&bare, "nextjs").unwrap();
707 assert!(found.dockerfile.contains("RUN npx next build\n"));
708 assert!(found.dockerfile.contains("CMD [\"npx\", \"next\", \"start\"]"));
709 let astro = project("astro-node", &[("package.json", r#"{ "scripts": { "build": "astro build", "start": "astro dev" }, "dependencies": { "astro": "5", "@astrojs/node": "9" } }"#)]);
710 assert!(for_framework(&astro, "astro").unwrap().dockerfile.contains("CMD [\"node\", \"./dist/server/entry.mjs\"]"));
711 let kit = project("kit-auto", &[("package.json", r#"{ "devDependencies": { "@sveltejs/kit": "2", "@sveltejs/adapter-auto": "6" } }"#)]);
712 assert_eq!(for_framework(&kit, "sveltekit"), None, "adapter-auto has no server to run");
713 let rr = project("rr", &[("package.json", r#"{ "devDependencies": { "@react-router/dev": "7" } }"#)]);
714 let found = for_framework(&rr, "react-router").unwrap();
715 assert!(found.dockerfile.contains("RUN npx react-router build\n"));
716 assert!(found.dockerfile.contains("react-router-serve"));
717 }
718}