Skip to content
556 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Merge GitHub pull request #8 (claude/cool-newton-7nm8r9): Docker deployments on g1t.page behind a switch that stays off until Cloudflare's container APIs are checked live, workflows a workspace manages in its repositories, tarball and zipball downloads, refs/pull/* kept to g1t alone, framework detection for g1t.page builds, and a workflow's event payload matching GitHub's.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 port a Dockerfile's last stage says it listens on (its first
63/// `EXPOSE` there), if it says.
64pub(crate) fn exposed_port(dockerfile: &str) -> Option<u16> {
65 let mut port = None;
66 for line in dockerfile.lines() {
67 let line = line.trim();
68 let mut words = line.split_whitespace();
69 let Some(word) = words.next() else { continue };
70 if word.eq_ignore_ascii_case("FROM") {
71 // Each stage starts afresh: only the last one's is what runs.
72 port = None;
73 } else if word.eq_ignore_ascii_case("EXPOSE") && port.is_none() {
74 port = words.next().and_then(|p| p.split('/').next()).and_then(|p| p.parse::<u16>().ok()).filter(|p| *p > 0);
75 }
76 }
77 port
78}
79
80/// A server g1t can write a Dockerfile for.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub(crate) struct Server {
83 /// As `g1t-runner detect` prints it when no framework names it:
84 /// `node`, `django`, `flask`, `fastapi`, `python`, `go`, `rails`,
85 /// `rack`, `laravel`, `php`.
86 pub id: &'static str,
87 /// For the build's log: `Node.js`, `Django`…
88 pub name: &'static str,
89 /// The Dockerfile, whole.
90 pub dockerfile: String,
91}
92
93/// What a generated Dockerfile leaves out of the image.
94pub(crate) const DOCKERIGNORE: &str = ".git\nnode_modules\n.venv\n__pycache__\n.wrangler\n.g1t\n";
95
96fn header(name: &str) -> String {
97 format!(
98 "# Written by g1t for this {name} project, which has no Dockerfile of its own.\n\
99 # To change how it is built or run, commit this file as `Dockerfile` and edit it.\n"
100 )
101}
102
103/// `package.json`, as read.
104fn package(dir: &Path) -> Option<Value> {
105 serde_json::from_str(&std::fs::read_to_string(dir.join("package.json")).ok()?).ok()
106}
107
108fn has_dependency(package: &Value, name: &str) -> bool {
109 ["dependencies", "devDependencies"].iter().any(|field| package[field].get(name).is_some())
110}
111
112/// Packages that make a Node.js project a server of its own.
113const NODE_SERVERS: [&str; 14] = [
114 "express",
115 "fastify",
116 "koa",
117 "@hapi/hapi",
118 "@nestjs/core",
119 "@hono/node-server",
120 "restify",
121 "polka",
122 "@adonisjs/core",
123 "sails",
124 "socket.io",
125 "@remix-run/serve",
126 "@react-router/serve",
127 "@feathersjs/feathers",
128];
129
130/// The Node.js version to build with: `.nvmrc` or `.node-version` when it
131/// names a major release g1t can pull, else 22.
132fn node_major(dir: &Path) -> u32 {
133 [".nvmrc", ".node-version"]
134 .iter()
135 .find_map(|name| std::fs::read_to_string(dir.join(name)).ok())
136 .and_then(|text| {
137 let digits: String = text.trim().trim_start_matches('v').chars().take_while(char::is_ascii_digit).collect();
138 digits.parse::<u32>().ok()
139 })
140 .filter(|major| (18..=30).contains(major))
141 .unwrap_or(22)
142}
143
144/// How a Node.js project installs, in the image.
145fn node_install(dir: &Path) -> &'static str {
146 if dir.join("pnpm-lock.yaml").exists() {
147 "corepack enable && pnpm install --frozen-lockfile --prod=false"
148 } else if dir.join("yarn.lock").exists() {
149 "corepack enable && yarn install"
150 } else if dir.join("bun.lockb").exists() || dir.join("bun.lock").exists() {
151 "npx --yes bun install"
152 } else if dir.join("package-lock.json").exists() {
153 "npm ci --include=dev"
154 } else {
155 "npm install --include=dev"
156 }
157}
158
159/// A Node.js server's Dockerfile: installed, built if it has a `build`
160/// script, then started with `start`.
161fn node_dockerfile(dir: &Path, name: &str, start: &str, build: Option<&str>) -> String {
162 let build = build.map(|command| format!("RUN {command}\n")).unwrap_or_default();
163 format!(
164 "{header}FROM node:{major}-slim\n\
165 WORKDIR /app\n\
166 COPY . .\n\
167 RUN {install}\n\
168 {build}\
169 ENV NODE_ENV=production HOST=0.0.0.0 PORT={DEFAULT_PORT}\n\
170 EXPOSE {DEFAULT_PORT}\n\
171 CMD {start}\n",
172 header = header(name),
173 major = node_major(dir),
174 install = node_install(dir),
175 )
176}
177
178/// The command a Node.js server starts with, as a Dockerfile's exec form.
179fn exec(words: &[&str]) -> String {
180 let quoted: Vec<String> = words.iter().map(|w| format!("\"{w}\"")).collect();
181 format!("[{}]", quoted.join(", "))
182}
183
184/// A shell command as a Dockerfile's `CMD`, so `$PORT` is read when it starts.
185fn shell(command: &str) -> String {
186 exec(&["sh", "-c", &format!("exec {command}")])
187}
188
189/// A Dockerfile for a framework that needs a server (`framework`, from
190/// frameworks.rs), when g1t knows how to run it: Next.js with `next
191/// start`, Astro with `@astrojs/node`, SvelteKit with `adapter-node`,
192/// React Router and Remix with their own server.
193pub(crate) fn for_framework(dir: &Path, framework: &str) -> Option<Server> {
194 let package = package(dir)?;
195 let scripts = &package["scripts"];
196 let script = |name: &str| scripts[name].as_str();
197 let has_build = script("build").is_some();
198 let start = |fallback: &[&str]| if script("start").is_some() { exec(&["npm", "start"]) } else { exec(fallback) };
199 let (name, command, own_build) = match framework {
200 "nextjs" => ("Next.js", start(&["npx", "next", "start"]), "npx next build"),
201 // `astro dev` is a common `start` script, so Astro's node adapter's
202 // own server is run instead.
203 "astro" if has_dependency(&package, "@astrojs/node") => ("Astro", exec(&["node", "./dist/server/entry.mjs"]), "npx astro build"),
204 "sveltekit" if has_dependency(&package, "@sveltejs/adapter-node") => ("SvelteKit", exec(&["node", "build"]), "npx vite build"),
205 "react-router" => ("React Router", start(&["npx", "react-router-serve", "./build/server/index.js"]), "npx react-router build"),
206 "remix" => ("Remix", start(&["npx", "remix-serve", "./build/server/index.js"]), "npx remix vite:build"),
207 _ => return None,
208 };
209 // Its own `build` script, else the framework's command.
210 let build = if has_build { "npm run build" } else { own_build };
211 Some(Server { id: "node", name, dockerfile: node_dockerfile(dir, name, &command, Some(build)) })
212}
213
214/// A server g1t recognises in a project with no framework it knows, and
215/// the Dockerfile it writes for it.
216pub(crate) fn server(dir: &Path) -> Option<Server> {
217 node_server(dir).or_else(|| python(dir)).or_else(|| go(dir)).or_else(|| ruby(dir)).or_else(|| php(dir))
218}
219
220/// A Node.js server: a `start` script, with a server package or nothing
221/// that looks like a static site (no `build` script and no `index.html`).
222fn node_server(dir: &Path) -> Option<Server> {
223 let package = package(dir)?;
224 let scripts = &package["scripts"];
225 let server_package = NODE_SERVERS.iter().any(|name| has_dependency(&package, name));
226 let has_build = scripts["build"].is_string();
227 let start = if scripts["start"].is_string() {
228 exec(&["npm", "start"])
229 } else if server_package {
230 let main = package["main"].as_str().map(str::to_owned).or_else(|| {
231 ["server.js", "index.js", "app.js", "server.mjs", "index.mjs"].iter().find(|f| dir.join(f).is_file()).map(|f| (*f).to_owned())
232 })?;
233 exec(&["node", &main])
234 } else {
235 return None;
236 };
237 if !server_package && (has_build || dir.join("index.html").exists()) {
238 return None;
239 }
240 Some(Server { id: "node", name: "Node.js", dockerfile: node_dockerfile(dir, "Node.js", &start, has_build.then_some("npm run build")) })
241}
242
243/// A Python web app: its requirements, and the file that starts it.
244fn python(dir: &Path) -> Option<Server> {
245 let requirements = ["requirements.txt", "pyproject.toml", "Pipfile"].iter().find(|f| dir.join(f).is_file())?;
246 let text = ["requirements.txt", "pyproject.toml", "Pipfile"]
247 .iter()
248 .filter_map(|f| std::fs::read_to_string(dir.join(f)).ok())
249 .collect::<Vec<_>>()
250 .join("\n")
251 .to_ascii_lowercase();
252 let uses = |name: &str| {
253 text.lines().any(|line| {
254 let line = line.trim().trim_start_matches(['"', '\'']);
255 line.starts_with(name) && !line[name.len()..].starts_with(|c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
256 })
257 };
258 let install = match *requirements {
259 "requirements.txt" => "pip install --no-cache-dir -r requirements.txt",
260 "Pipfile" => "pip install --no-cache-dir pipenv && pipenv install --system --deploy",
261 _ => "pip install --no-cache-dir .",
262 };
263 let module = ["app", "main", "server", "wsgi", "asgi"].iter().find(|m| dir.join(format!("{m}.py")).is_file()).copied();
264 let (id, name, extra, command) = if dir.join("manage.py").is_file() {
265 // Django: the project's package is the folder with its `wsgi.py`.
266 let project = std::fs::read_dir(dir)
267 .ok()?
268 .flatten()
269 .find(|entry| entry.path().join("wsgi.py").is_file())?
270 .file_name()
271 .to_string_lossy()
272 .into_owned();
273 ("django", "Django", "gunicorn", format!("gunicorn --bind 0.0.0.0:$PORT {project}.wsgi"))
274 } else if uses("fastapi") || uses("starlette") {
275 let module = module?;
276 ("fastapi", "FastAPI", "uvicorn", format!("uvicorn {module}:app --host 0.0.0.0 --port $PORT"))
277 } else if uses("flask") {
278 let module = module?;
279 ("flask", "Flask", "gunicorn", format!("gunicorn --bind 0.0.0.0:$PORT {module}:app"))
280 } else {
281 let module = module?;
282 ("python", "Python", "", format!("python {module}.py"))
283 };
284 let extra = if extra.is_empty() || uses(extra) { String::new() } else { format!(" && pip install --no-cache-dir {extra}") };
285 let dockerfile = format!(
286 "{header}FROM python:3.12-slim\n\
287 WORKDIR /app\n\
288 ENV PYTHONUNBUFFERED=1 PORT={DEFAULT_PORT}\n\
289 COPY . .\n\
290 RUN {install}{extra}\n\
291 EXPOSE {DEFAULT_PORT}\n\
292 CMD {cmd}\n",
293 header = header(name),
294 cmd = shell(&command),
295 );
296 Some(Server { id, name, dockerfile })
297}
298
299/// Whether a Go file is `package main`.
300fn is_main(path: &Path) -> bool {
301 std::fs::read_to_string(path).is_ok_and(|text| {
302 text.lines().map(str::trim).find(|line| line.starts_with("package ")).is_some_and(|line| line == "package main")
303 })
304}
305
306fn has_main(dir: &Path) -> bool {
307 std::fs::read_dir(dir).is_ok_and(|entries| {
308 entries.flatten().any(|entry| {
309 let path = entry.path();
310 path.extension().is_some_and(|e| e == "go") && !path.to_string_lossy().ends_with("_test.go") && is_main(&path)
311 })
312 })
313}
314
315/// A Go program: `go.mod`, and a `package main` at the top or in one
316/// folder of `cmd/`.
317fn go(dir: &Path) -> Option<Server> {
318 if !dir.join("go.mod").is_file() {
319 return None;
320 }
321 let target = if has_main(dir) {
322 ".".to_owned()
323 } else {
324 let mut commands: Vec<String> = std::fs::read_dir(dir.join("cmd"))
325 .ok()?
326 .flatten()
327 .filter(|entry| has_main(&entry.path()))
328 .map(|entry| format!("./cmd/{}", entry.file_name().to_string_lossy()))
329 .collect();
330 commands.sort();
331 // More than one program: which to run is the project's to say.
332 if commands.len() != 1 {
333 return None;
334 }
335 commands.remove(0)
336 };
337 let dockerfile = format!(
338 "{header}FROM golang:1.25 AS build\n\
339 WORKDIR /src\n\
340 COPY . .\n\
341 RUN go mod download && CGO_ENABLED=0 go build -trimpath -ldflags=-s -o /out/app {target}\n\
342 \n\
343 FROM scratch\n\
344 COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\n\
345 COPY --from=build /out/app /app\n\
346 ENV PORT={DEFAULT_PORT}\n\
347 EXPOSE {DEFAULT_PORT}\n\
348 ENTRYPOINT [\"/app\"]\n",
349 header = header("Go"),
350 );
351 Some(Server { id: "go", name: "Go", dockerfile })
352}
353
354/// A Ruby web app: Rails, or any Rack app with a `config.ru`.
355fn ruby(dir: &Path) -> Option<Server> {
356 let gemfile = std::fs::read_to_string(dir.join("Gemfile")).ok()?;
357 let rails = gemfile.lines().any(|line| {
358 let line = line.trim();
359 line.starts_with("gem \"rails\"") || line.starts_with("gem 'rails'")
360 });
361 let (id, name, setup, command) = if rails {
362 (
363 "rails",
364 "Rails",
365 "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",
366 "bundle exec rails server -b 0.0.0.0 -p $PORT",
367 )
368 } else if dir.join("config.ru").is_file() {
369 ("rack", "Rack", "", "bundle exec rackup -o 0.0.0.0 -p $PORT")
370 } else {
371 return None;
372 };
373 let dockerfile = format!(
374 "{header}FROM ruby:3.3-slim\n\
375 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\
376 WORKDIR /app\n\
377 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\
378 COPY . .\n\
379 RUN bundle install\n\
380 {setup}\
381 EXPOSE {DEFAULT_PORT}\n\
382 CMD {cmd}\n",
383 header = header(name),
384 cmd = shell(command),
385 );
386 Some(Server { id, name, dockerfile })
387}
388
389/// A PHP app with Composer: Laravel, or any app with an `index.php`.
390fn php(dir: &Path) -> Option<Server> {
391 if !dir.join("composer.json").is_file() {
392 return None;
393 }
394 let (id, name) = if dir.join("artisan").is_file() { ("laravel", "Laravel") } else { ("php", "PHP") };
395 let root = if dir.join("public/index.php").is_file() {
396 "/var/www/html/public"
397 } else if dir.join("index.php").is_file() {
398 "/var/www/html"
399 } else {
400 return None;
401 };
402 let dockerfile = format!(
403 "{header}FROM composer:2 AS vendor\n\
404 WORKDIR /app\n\
405 COPY . .\n\
406 RUN composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader --ignore-platform-reqs\n\
407 \n\
408 FROM php:8.3-apache\n\
409 ENV PORT={DEFAULT_PORT} APACHE_DOCUMENT_ROOT={root}\n\
410 RUN sed -ri -e 's!/var/www/html!${{APACHE_DOCUMENT_ROOT}}!g' /etc/apache2/sites-available/*.conf /etc/apache2/apache2.conf \\\n \
411 && sed -ri -e 's/^Listen 80$/Listen ${{PORT}}/' /etc/apache2/ports.conf \\\n \
412 && sed -ri -e 's/:80>/:${{PORT}}>/' /etc/apache2/sites-available/000-default.conf \\\n \
413 && a2enmod rewrite\n\
414 COPY --from=vendor --chown=www-data:www-data /app /var/www/html\n\
415 EXPOSE {DEFAULT_PORT}\n",
416 header = header(name),
417 );
418 Some(Server { id, name, dockerfile })
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424
425 fn project(name: &str, files: &[(&str, &str)]) -> std::path::PathBuf {
426 let dir = std::env::temp_dir().join(format!("g1t-container-{name}-{}", std::process::id()));
427 let _ = std::fs::remove_dir_all(&dir);
428 std::fs::create_dir_all(&dir).unwrap();
429 for (path, text) in files {
430 let path = dir.join(path);
431 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
432 std::fs::write(path, text).unwrap();
433 }
434 dir
435 }
436
437 #[test]
438 fn build_as_is_read_from_the_setting() {
439 assert_eq!(BuildAs::parse("docker"), BuildAs::Docker);
440 assert_eq!(BuildAs::parse(" Static "), BuildAs::Static);
441 assert_eq!(BuildAs::parse("workers"), BuildAs::Workers);
442 assert_eq!(BuildAs::parse(""), BuildAs::Auto);
443 assert_eq!(BuildAs::parse("something"), BuildAs::Auto);
444 }
445
446 #[test]
447 fn a_dockerfile_is_found_by_its_names_or_the_chosen_path() {
448 let dir = project("own", &[("Containerfile", "FROM scratch"), ("deploy/web.Dockerfile", "FROM scratch")]);
449 assert_eq!(own_dockerfile(&dir, None).unwrap().as_deref(), Some("Containerfile"));
450 assert_eq!(own_dockerfile(&dir, Some("./deploy/web.Dockerfile")).unwrap().as_deref(), Some("deploy/web.Dockerfile"));
451 assert!(own_dockerfile(&dir, Some("missing/Dockerfile")).unwrap_err().to_string().contains("does not exist"));
452 assert!(own_dockerfile(&dir, Some("../etc/passwd")).is_err());
453 assert_eq!(own_dockerfile(&project("none", &[]), None).unwrap(), None);
454 }
455
456 #[test]
457 fn the_port_is_the_last_stages_first_expose() {
458 assert_eq!(exposed_port("FROM node\nEXPOSE 3000\nEXPOSE 9229"), Some(3000));
459 assert_eq!(exposed_port("FROM golang AS build\nEXPOSE 9000\nFROM scratch\nexpose 8000/tcp"), Some(8000));
460 assert_eq!(exposed_port("FROM golang AS build\nEXPOSE 9000\nFROM scratch\n"), None);
461 assert_eq!(exposed_port("FROM x\nEXPOSE $PORT"), None);
462 }
463
464 #[test]
465 fn node_servers_are_recognised_and_static_sites_are_not() {
466 let express = project("express", &[("package.json", r#"{ "scripts": { "start": "node server.js" }, "dependencies": { "express": "5" } }"#), ("package-lock.json", "{}")]);
467 let found = server(&express).unwrap();
468 assert_eq!((found.id, found.name), ("node", "Node.js"));
469 assert!(found.dockerfile.contains("FROM node:22-slim"));
470 assert!(found.dockerfile.contains("RUN npm ci --include=dev"));
471 assert!(found.dockerfile.contains("CMD [\"npm\", \"start\"]"));
472 assert!(found.dockerfile.contains("EXPOSE 8080"));
473 assert!(!found.dockerfile.contains("npm run build"));
474 // A server package without a start script runs its main file.
475 let main = project("main", &[("package.json", r#"{ "main": "src/app.js", "dependencies": { "fastify": "5" } }"#), (".nvmrc", "v20.11\n")]);
476 let found = server(&main).unwrap();
477 assert!(found.dockerfile.contains("CMD [\"node\", \"src/app.js\"]"));
478 assert!(found.dockerfile.contains("FROM node:20-slim"));
479 // A start script beside a build script and no server package is a
480 // static site's preview server, not an app.
481 let site = project("site", &[("package.json", r#"{ "scripts": { "build": "x", "start": "serve dist" } }"#)]);
482 assert_eq!(server(&site), None);
483 assert_eq!(server(&project("bare", &[("package.json", "{}")])), None);
484 }
485
486 #[test]
487 fn python_apps_get_the_server_their_framework_runs_on() {
488 let flask = project("flask", &[("requirements.txt", "Flask==3.1\n"), ("app.py", "")]);
489 let found = server(&flask).unwrap();
490 assert_eq!(found.id, "flask");
491 assert!(found.dockerfile.contains("pip install --no-cache-dir -r requirements.txt && pip install --no-cache-dir gunicorn"));
492 assert!(found.dockerfile.contains(r#"CMD ["sh", "-c", "exec gunicorn --bind 0.0.0.0:$PORT app:app"]"#));
493 let fastapi = project("fastapi", &[("requirements.txt", "fastapi\nuvicorn[standard]\n"), ("main.py", "")]);
494 let found = server(&fastapi).unwrap();
495 assert_eq!(found.id, "fastapi");
496 assert!(!found.dockerfile.contains("pip install --no-cache-dir uvicorn"), "already required");
497 assert!(found.dockerfile.contains("uvicorn main:app --host 0.0.0.0 --port $PORT"));
498 let django = project("django", &[("requirements.txt", "Django>=5\ngunicorn\n"), ("manage.py", ""), ("shop/wsgi.py", "")]);
499 let found = server(&django).unwrap();
500 assert_eq!(found.id, "django");
501 assert!(found.dockerfile.contains("gunicorn --bind 0.0.0.0:$PORT shop.wsgi"));
502 // Requirements without an app to start (a docs site's) are not one.
503 assert_eq!(server(&project("mkdocs", &[("requirements.txt", "mkdocs\n"), ("mkdocs.yml", "")])), None);
504 // flask-cors is not Flask.
505 let cors = project("cors", &[("requirements.txt", "flask-cors\n"), ("app.py", "")]);
506 assert_eq!(server(&cors).unwrap().id, "python");
507 }
508
509 #[test]
510 fn go_ruby_and_php_apps_are_recognised() {
511 let go_root = project("go", &[("go.mod", "module x\n"), ("main.go", "// x\npackage main\n"), ("main_test.go", "package main")]);
512 let found = server(&go_root).unwrap();
513 assert_eq!(found.id, "go");
514 assert!(found.dockerfile.contains("go build -trimpath -ldflags=-s -o /out/app .\n"));
515 assert!(found.dockerfile.contains("FROM scratch"));
516 let go_cmd = project("gocmd", &[("go.mod", "module x\n"), ("lib.go", "package x"), ("cmd/api/main.go", "package main")]);
517 assert!(server(&go_cmd).unwrap().dockerfile.contains("-o /out/app ./cmd/api\n"));
518 let go_two = project("gotwo", &[("go.mod", "module x\n"), ("cmd/a/main.go", "package main"), ("cmd/b/main.go", "package main")]);
519 assert_eq!(server(&go_two), None, "which program runs is the project's to say");
520
521 let rails = project("rails", &[("Gemfile", "source 'https://rubygems.org'\ngem \"rails\", \"~> 8.0\"\n"), ("config.ru", "")]);
522 let found = server(&rails).unwrap();
523 assert_eq!(found.id, "rails");
524 assert!(found.dockerfile.contains("bundle exec rails server -b 0.0.0.0 -p $PORT"));
525 let rack = project("rack", &[("Gemfile", "gem 'sinatra'\n"), ("config.ru", "run App")]);
526 assert_eq!(server(&rack).unwrap().id, "rack");
527 assert_eq!(server(&project("gems", &[("Gemfile", "gem 'rake'\n")])), None);
528
529 let laravel = project("laravel", &[("composer.json", "{}"), ("artisan", ""), ("public/index.php", "")]);
530 let found = server(&laravel).unwrap();
531 assert_eq!(found.id, "laravel");
532 assert!(found.dockerfile.contains("APACHE_DOCUMENT_ROOT=/var/www/html/public"));
533 assert!(found.dockerfile.contains("Listen ${PORT}"));
534 assert_eq!(server(&project("composer", &[("composer.json", "{}")])), None);
535 }
536
537 #[test]
538 fn frameworks_that_need_a_server_get_one() {
539 let next = project("next", &[("package.json", r#"{ "scripts": { "build": "next build", "start": "next start" }, "dependencies": { "next": "16" } }"#)]);
540 let found = for_framework(&next, "nextjs").unwrap();
541 assert!(found.dockerfile.contains("RUN npm run build\n"));
542 assert!(found.dockerfile.contains("CMD [\"npm\", \"start\"]"));
543 let bare = project("next-bare", &[("package.json", r#"{ "dependencies": { "next": "16" } }"#)]);
544 let found = for_framework(&bare, "nextjs").unwrap();
545 assert!(found.dockerfile.contains("RUN npx next build\n"));
546 assert!(found.dockerfile.contains("CMD [\"npx\", \"next\", \"start\"]"));
547 let astro = project("astro-node", &[("package.json", r#"{ "scripts": { "build": "astro build", "start": "astro dev" }, "dependencies": { "astro": "5", "@astrojs/node": "9" } }"#)]);
548 assert!(for_framework(&astro, "astro").unwrap().dockerfile.contains("CMD [\"node\", \"./dist/server/entry.mjs\"]"));
549 let kit = project("kit-auto", &[("package.json", r#"{ "devDependencies": { "@sveltejs/kit": "2", "@sveltejs/adapter-auto": "6" } }"#)]);
550 assert_eq!(for_framework(&kit, "sveltekit"), None, "adapter-auto has no server to run");
551 let rr = project("rr", &[("package.json", r#"{ "devDependencies": { "@react-router/dev": "7" } }"#)]);
552 let found = for_framework(&rr, "react-router").unwrap();
553 assert!(found.dockerfile.contains("RUN npx react-router build\n"));
554 assert!(found.dockerfile.contains("react-router-serve"));
555 }
556}

This file's history is long; its oldest lines are credited to the oldest commit read.