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