diff --git a/README.md b/README.md index 55aa275..3f2d6d2 100644 --- a/README.md +++ b/README.md @@ -151,13 +151,28 @@ Identity: `SHOPWARE_SHOP_ID`, `SHOPWARE_DEPLOY_ENV`, optional ### env init -Does not overwrite the whole `.env`. Does not invent MYSQL passwords or -`APP_URL`. Does not generate `APP_SECRET` (`shopware-cli project create` -already writes it). `--shop-id` is required unless `SHOPWARE_SHOP_ID` is -already set. `--env` defaults to `live`. Uncommented `COMPOSE_PROJECT_NAME` -lines are always commented out (Compose SoT is `SHOPWARE_SHOP_ID` + -`SHOPWARE_DEPLOY_ENV`). `.env` may still be missing; missing keys are -merged from `.env.example`. +Shop-root `.env` is git-committed and shared. This command does not +overwrite the whole file, invent MYSQL passwords or `APP_URL`, or generate +`APP_SECRET` (`shopware-cli project create` already writes it). `--shop-id` +is required unless `SHOPWARE_SHOP_ID` is already set. `--env` writes +`SHOPWARE_DEPLOY_ENV` and `COMPOSE_PROJECT_NAME=-` to +**`.env.local`** (gitignored; created if missing; default `live` when unset +and no host value). Uncommented `COMPOSE_PROJECT_NAME` (create writes +`sw-…`) and leftover `SHOPWARE_DEPLOY_ENV` in shared `.env` are +**commented out** — those keys stay out of the committed file. + +Local Compose uses the same project name as VPS (`-`, not the +folder basename). Compose and `shopware-cli project dev` only auto-read +`COMPOSE_PROJECT_NAME` from project-directory `.env`, so env init also +upserts top-level `name: -` in gitignored +`compose.override.yaml` (create if missing; replace only that key). +shopware-cli regenerates `compose.yaml` and leaves `compose.override.yaml` +for local customization — gitignore it so the env-specific `name:` is not +committed. VPS interpolates `docker compose` `name: ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV}` +from host env files (always `--env-file .env`, then `.env.local` / `.env.prod` +when present). There is no `-p`. +`.env` may still be missing; missing keys are merged from `.env.example` +(not `COMPOSE_PROJECT_NAME` / `SHOPWARE_DEPLOY_ENV`). ```bash fyrst-cli shopware env init --shop-id acme --dry-run @@ -167,7 +182,9 @@ fyrst-cli shopware env init --shop-id acme --env live --image ghcr.io/example/ac ### db import Needs `SHOPWARE_SHOP_ID` and a Compose `mysql` service (preferred) or -`DATABASE_URL` to a real host. +`DATABASE_URL` to a real host. Bundled mysql uses the same Compose naming as +VPS: `name:` interpolating host env files (`--env-file .env`, then +`.env.local` / `.env.prod` when present). There is no `-p`. ```bash fyrst-cli shopware db import --file /tmp/db.sql.gz --dry-run @@ -182,6 +199,10 @@ Needs `IMAGE`, `IMAGE_TAG` (release), `SHOPWARE_SHOP_ID`, and win over `.env` on release. Rollback ignores process-env `IMAGE_TAG` and reads `.previous-tag` only. `--skip-pull` is for same-host / air-gap. +VPS Compose project name is `{shop-id}-{env}`. Source of truth is +`deploy/compose.yaml` `name:` interpolating host env files (`--env-file .env`, +then `.env.local` / `.env.prod` when present). There is no `-p`. + ```bash fyrst-cli shopware deploy release --dry-run fyrst-cli shopware deploy release --skip-pull diff --git a/docs/command-matrix.md b/docs/command-matrix.md index 734667b..8e1c41f 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -110,9 +110,11 @@ Resolves shop root (`COMPOSE_DIR` or walk from cwd), loads `.env` then Compose is always: ```text -docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml +docker compose --env-file .env [--env-file .env.local] [--env-file .env.prod] -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml ``` +Source of truth is `deploy/compose.yaml` `name: "${SHOPWARE_SHOP_ID:?…}-${SHOPWARE_DEPLOY_ENV:?…}"` plus host env files in identity-load order (always `.env`, then `.env.local` / `.env.prod` when those files exist under the shop root). There is no `-p`. Leftover `COMPOSE_PROJECT_NAME` in committed `.env` is ignored (commented out by env init). + Never `--build`. `compose run` uses `--pull never` (not `--no-build`). `compose up` uses `--no-build` (and `--pull never` when skipping registry pull). Theme/asset compile flags stay in the setup helper image. @@ -162,28 +164,47 @@ volumes (`media`, `files`, `thumbnail`, `theme`, `sitemap`) restore from ## `shopware env init` (implemented) -Finish shop-root `.env` after `shopware-cli project create` + Flex. Historically -mapped to overlay `deploy/init-env.sh` (removed). Does **not** overwrite the -whole file, invent `MYSQL_*` passwords, set `APP_URL`, or generate -`APP_SECRET` (`shopware-cli project create` writes that). This is **not** a -dump command. +Finish committed shop-root `.env` after `shopware-cli project create` + Flex, +host `.env.local` for `SHOPWARE_DEPLOY_ENV` and +`COMPOSE_PROJECT_NAME=-`, and gitignored `compose.override.yaml` +(`name: -`) so local `shopware-cli project dev` uses the same +Compose project as VPS. Historically mapped to overlay `deploy/init-env.sh` +(removed). Does **not** overwrite the whole file, invent `MYSQL_*` passwords, +set `APP_URL`, or generate `APP_SECRET` (`shopware-cli project create` writes +that). Shared `.env` must not hold env-specific values. This is **not** a dump +command. Resolves shop root (`COMPOSE_DIR` if set, else walk from cwd for `.env` or `.env.example` + `deploy/`). `.env` is `KEY=VALUE` (quotes stripped, **no shell expansion**), same parser as import (`src/shopware/envfile.rs`). 1. Copy `.env.example` → `.env` when `.env` is missing; merge **missing** keys - from `.env.example` without clobbering existing values. + from `.env.example` without clobbering existing values (skips + `COMPOSE_PROJECT_NAME` and `SHOPWARE_DEPLOY_ENV`). 2. `--shop-id` is required unless `SHOPWARE_SHOP_ID` is already non-empty in `.env`. Slug: lowercase `[a-z0-9]([a-z0-9-]*[a-z0-9])?`. -3. `--env` is `live` | `staging` | `playground` | `dev`. Default `live` when - unset/empty; keep an existing non-empty value. +3. `--env` is `live` | `staging` | `playground` | `dev`. Written to + **`.env.local`** (gitignored; created if missing) together with + `COMPOSE_PROJECT_NAME=-` (same string as VPS, e.g. `acme-dev`). + Default `live` when unset and `.env.local` / `.env.prod` have no value; + leftover uncommented `SHOPWARE_DEPLOY_ENV` in shared `.env` is migrated then + commented out. 4. `--image` sets `IMAGE` (no whitespace). Unset leaves `IMAGE` as-is. -5. Always comments out uncommented `COMPOSE_PROJECT_NAME=…` lines (create - writes `COMPOSE_PROJECT_NAME=sw-…`; Compose SoT is `SHOPWARE_SHOP_ID` + - `SHOPWARE_DEPLOY_ENV`). Does not leave an empty `COMPOSE_PROJECT_NAME=`. -6. `--dry-run` prints the summary and does not write `.env`. -7. After a real write: `chmod 600 .env`. +5. **Comments out** uncommented `COMPOSE_PROJECT_NAME=…` in shared `.env` + (create writes `COMPOSE_PROJECT_NAME=sw-…`). Does **not** write + `COMPOSE_PROJECT_NAME` or `SHOPWARE_DEPLOY_ENV` into committed `.env`. + Already-commented lines are left as-is. +6. Upserts top-level Compose `name: -` in gitignored + `compose.override.yaml` (create if missing; if the file exists, set/replace + only that key). Compose and `shopware-cli project dev` auto-read + `COMPOSE_PROJECT_NAME` only from project-directory `.env`, not `.env.local`, + so the YAML `name:` is what names the local stack. shopware-cli regenerates + `compose.yaml` and leaves `compose.override.yaml` for local customization. + VPS compose interpolates the same `-` from `deploy/compose.yaml` + `name:` plus host env files (no `-p`). +7. `--dry-run` prints the summary and does not write `.env`, `.env.local`, or + `compose.override.yaml`. +8. After a real write: `chmod 600 .env` and `.env.local` (not the override). Does not generate `APP_SECRET` (no dedicated read/write of that key). Refuses a bash xtrace equivalent (`SHELLOPTS=xtrace` / `BASH_XTRACEFD`) so credentials @@ -255,8 +276,10 @@ from the process environment win when non-empty). Requires `SHOPWARE_SHOP_ID`. 1. If a compose `mysql` service is present: on execute, `docker compose … up -d --no-build mysql`, wait until pingable, then - `gzip -dc FILE | docker compose --env-file .env -f … exec -T mysql sh -c - ''` (plain `.sql` is stdin, not gzip). + `gzip -dc FILE | docker compose --env-file .env [--env-file .env.local] [--env-file .env.prod] -f … exec -T mysql sh -c + ''` (plain `.sql` is stdin, not gzip). There is no `-p`; + project name is compose `name:` (VPS `deploy/compose.yaml` or local + `compose.override.yaml`) interpolating host env files. 2. Else `DATABASE_URL` to a real host: `gzip -dc FILE | docker run --rm -i --network host mysql `. Host `mysql` without a bundled service is refused. @@ -350,8 +373,9 @@ Local: rsync (or a tree copy if rsync is missing) from `$SHOPWARE_DATA_ROOT` / derived `$SHOPWARE_DATA_BASE/$SHOPWARE_SHOP_ID/$SHOPWARE_DEPLOY_ENV/` into `--snapshot-dir/data//`. If the bind-mount directory is missing, -named-volume fallback `${COMPOSE_PROJECT_NAME}_` via -`alpine:3.20` writes `--snapshot-dir/volumes/.tar.gz`. +named-volume fallback `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}_` via +`alpine:3.20` writes `--snapshot-dir/volumes/.tar.gz` (identity +project name, matching Compose `name:`). Remote `--from `: SSH + rsync (or tar over SSH) from `SHOPWARE_REMOTE_DATA_ROOT` or derived @@ -491,7 +515,8 @@ shopware-cli. `$SHOPWARE_DATA_ROOT//` (or derived `$SHOPWARE_DATA_BASE/$SHOPWARE_SHOP_ID/$SHOPWARE_DEPLOY_ENV`) into `data//`. Missing bind-mounts fall back to a named-volume tar - (`${COMPOSE_PROJECT_NAME}_`, `alpine:3.20`). Local target writes the + (`{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}_`, `alpine:3.20`; + identity name matching Compose `name:`). Local target writes the timestamped dir in place; SSH target builds under `/var/backup-work/` then rsyncs (`SHOPWARE_SSH_KEY`). 4. If `--data` includes `db`: **do not dump**. `--dry-run` prints @@ -555,7 +580,7 @@ This CLI reads shop identity and secrets from the environment / shop-root | Area | Variables | | --- | --- | -| Shop identity | `COMPOSE_DIR`, `SHOPWARE_SHOP_ID`, `SHOPWARE_DEPLOY_ENV`, `SHOPWARE_DATA_BASE`, `SHOPWARE_DATA_ROOT`, `COMPOSE_PROJECT_NAME` | +| Shop identity | `COMPOSE_DIR`, `SHOPWARE_SHOP_ID` (shared `.env`), `SHOPWARE_DEPLOY_ENV` and `COMPOSE_PROJECT_NAME=-` (`.env.local` / `.env.prod`), `SHOPWARE_DATA_BASE`, `SHOPWARE_DATA_ROOT`. Do not put `COMPOSE_PROJECT_NAME` or `SHOPWARE_DEPLOY_ENV` in committed `.env`. Local Compose project is `-` via host `.env.local` plus gitignored `compose.override.yaml` `name:` (not the folder basename). Compose SoT for VPS, db import, and rewrite is `name:` interpolating host env files (no `-p`). | | Env init | `IMAGE` (`APP_SECRET` is Shopware's; `shopware-cli project create` writes it) | | Import | `MYSQL_DATABASE`, `DATABASE_URL`, `SHOPWARE_ALLOW_LIVE_RESTORE` | | Restore volumes | `SHOPWARE_DATA_ROOT`, `SHOPWARE_DATA_BASE` | diff --git a/src/cli.rs b/src/cli.rs index dcfc5af..39b3ef4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -94,8 +94,10 @@ pub enum Command { deploy (VPS compose), db (SQL import), sync (between environments / workdir), \ backup (off-host disaster recovery).\n\n\ `env init` is implemented: finish shop-root `.env` after create + Flex (merge missing \ -keys from `.env.example`, shop id / deploy env, optional IMAGE; always comments out \ -COMPOSE_PROJECT_NAME). Does not generate APP_SECRET. `--dry-run` prints the \ +keys from `.env.example`, shop id, optional IMAGE). Comments out COMPOSE_PROJECT_NAME \ +and leftover SHOPWARE_DEPLOY_ENV in committed `.env`; writes SHOPWARE_DEPLOY_ENV and \ +COMPOSE_PROJECT_NAME=- to `.env.local` and upserts Compose `name:` in \ +gitignored `compose.override.yaml`. Does not generate APP_SECRET. `--dry-run` prints the \ plan and does not write. Passwords are never printed.\n\n\ `db import` is implemented: MySQL/MariaDB client import (Compose `mysql` exec, else a \ one-shot client image for DATABASE_URL). `sync apply` uses that same import module, \ @@ -183,9 +185,15 @@ impl DeployEnv { #[command( after_help = "Does not overwrite the whole .env. Does not invent MYSQL passwords or APP_URL. \ Does not generate APP_SECRET (shopware-cli project create writes that). \ -Always comments out uncommented COMPOSE_PROJECT_NAME=… lines (create writes \ -COMPOSE_PROJECT_NAME=sw-…; Compose SoT is SHOPWARE_SHOP_ID + SHOPWARE_DEPLOY_ENV). \ -Does not leave an empty COMPOSE_PROJECT_NAME=.\n\n\ +Shared .env is git-committed: comments out uncommented COMPOSE_PROJECT_NAME=… \ +(create writes COMPOSE_PROJECT_NAME=sw-…) and leftover SHOPWARE_DEPLOY_ENV. \ +Does not set COMPOSE_PROJECT_NAME or SHOPWARE_DEPLOY_ENV in shared .env. \ +Writes SHOPWARE_DEPLOY_ENV and COMPOSE_PROJECT_NAME=- to .env.local \ +(gitignored; created if missing). Upserts top-level Compose name: - \ +in gitignored compose.override.yaml so shopware-cli project dev uses that name \ +(Compose reads COMPOSE_PROJECT_NAME only from project-directory .env, not .env.local). \ +VPS compose interpolates the same - from deploy/compose.yaml name: plus host \ +env files (no -p).\n\n\ Environment:\n \ COMPOSE_DIR Shop checkout (default: walk from cwd for .env / .env.example + deploy/)\n\n\ Examples:\n \ @@ -198,7 +206,7 @@ pub struct InitEnvArgs { #[arg(long = "shop-id", value_name = "SLUG")] pub shop_id: Option, - /// live | staging | playground | dev (default live when unset/empty; keep existing non-empty) + /// live | staging | playground | dev (written to .env.local with COMPOSE_PROJECT_NAME; default live when unset and no host value) #[arg(long = "env", value_enum, value_name = "NAME")] pub env: Option, @@ -206,7 +214,7 @@ pub struct InitEnvArgs { #[arg(long = "image", value_name = "REPO")] pub image: Option, - /// Print the summary; do not write .env + /// Print the summary; do not write .env, .env.local, or compose.override.yaml #[arg(long)] pub dry_run: bool, } diff --git a/src/main.rs b/src/main.rs index 83fead0..d2dd61a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,9 @@ //! fyrst.dev global CLI (`fyrst-cli`). //! //! Database dumps are owned by `shopware-cli project dump`. This binary does -//! not wrap dump. `shopware env init` finishes shop-root `.env`. Database +//! not wrap dump. `shopware env init` finishes committed `.env` (shop id / IMAGE) +//! and host `.env.local` (`SHOPWARE_DEPLOY_ENV`, `COMPOSE_PROJECT_NAME`) plus +//! gitignored `compose.override.yaml` (`name: -`). Database //! import is `fyrst-cli shopware db import` (MySQL client via Compose exec or //! a one-shot client image). VPS release is `fyrst-cli shopware deploy release`. //! Rollback is `fyrst-cli shopware deploy rollback` (IMAGE_TAG from diff --git a/src/shopware/app.rs b/src/shopware/app.rs index d5a5aa4..caf3ea3 100644 --- a/src/shopware/app.rs +++ b/src/shopware/app.rs @@ -21,7 +21,7 @@ pub fn stop_app_containers( return Ok(Vec::new()); } require_docker()?; - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); args.extend([ "--profile".into(), "worker".into(), @@ -52,7 +52,7 @@ pub fn stop_app_containers( } println!("==> Stopping {svc} for restore"); if !compose_stop(compose_dir, files, svc) { - let mut with_profile = compose_argv(files); + let mut with_profile = compose_argv(compose_dir, files); with_profile.extend([ "--profile".into(), (*svc).into(), @@ -72,7 +72,7 @@ pub fn stop_app_containers( } fn compose_stop(compose_dir: &Path, files: &[String], svc: &str) -> bool { - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); args.extend(["stop".into(), svc.into()]); Command::new("docker") .args(&args) @@ -99,7 +99,7 @@ pub fn start_stopped_app( continue; } println!("==> Starting {svc}"); - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); match svc.as_str() { "worker" => { args.extend([ @@ -176,7 +176,7 @@ pub fn post_restore_hints( } if env.get("IMAGE").is_some() && !files.is_empty() { println!("==> Trying cache:clear (non-fatal if the image/console is unavailable)"); - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); args.extend([ "run".into(), "--rm".into(), diff --git a/src/shopware/compose.rs b/src/shopware/compose.rs index dbff48a..fddd729 100644 --- a/src/shopware/compose.rs +++ b/src/shopware/compose.rs @@ -1,20 +1,31 @@ //! VPS Compose file list and argv (recipes `deploy/lib/compose.sh`). //! -//! Always invoked from shop-root `COMPOSE_DIR`: -//! `docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml` +//! Always invoked from shop-root `COMPOSE_DIR`. Source of truth for the +//! project name is `deploy/compose.yaml`: +//! `name: "${SHOPWARE_SHOP_ID:?…}-${SHOPWARE_DEPLOY_ENV:?…}"`. +//! That interpolates only if host env is loaded, so argv passes `--env-file` +//! in identity-load order (always `.env`, then `.env.local` / `.env.prod` when +//! those files exist). There is no `-p` / `--project-name`. +//! +//! Example when both host files exist: +//! `docker compose --env-file .env --env-file .env.local --env-file .env.prod -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml` //! //! Never builds images. `compose up` uses `--no-build`. `compose run` uses //! `--pull never` (Compose v5 dropped `--no-build` on `run`). -use super::env::COMPOSE_FILES; +use super::env::{compose_env_file_flags, COMPOSE_FILES}; use super::error::Error; use super::mysql::require_docker; use std::path::Path; use std::process::{Command, Stdio}; -/// The three overlay compose files; all must exist for VPS release/rollback. -pub fn vps_compose_argv() -> Vec { - let mut a = vec!["compose".into(), "--env-file".into(), ".env".into()]; +/// The three overlay compose files plus host env files. +/// +/// Project name comes from `deploy/compose.yaml` `name:` after interpolation. +/// All overlay files must exist for VPS release/rollback. +pub fn vps_compose_argv(compose_dir: &Path) -> Vec { + let mut a = vec!["compose".into()]; + a.extend(compose_env_file_flags(compose_dir)); for f in COMPOSE_FILES { a.push("-f".into()); a.push((*f).to_string()); @@ -88,7 +99,7 @@ pub fn compose_service_names( profile_args: &[String], extra_env: &[(String, String)], ) -> Vec { - let mut args = vps_compose_argv(); + let mut args = vps_compose_argv(compose_dir); args.extend(profile_args.iter().cloned()); args.extend(["config".into(), "--services".into()]); let mut cmd = Command::new("docker"); @@ -112,10 +123,58 @@ pub fn compose_service_names( #[cfg(test)] mod tests { use super::*; + use std::fs; + use std::path::PathBuf; + use std::time::{SystemTime, UNIX_EPOCH}; + + struct TempShop(PathBuf); + + impl TempShop { + fn new(prefix: &str) -> Self { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let p = std::env::temp_dir().join(format!( + "fyrst-cli-compose-{prefix}-{}-{nanos}", + std::process::id() + )); + fs::create_dir_all(&p).unwrap(); + Self(p) + } + } + + impl Drop for TempShop { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn env_files(argv: &[String]) -> Vec<&str> { + argv.windows(2) + .filter(|w| w[0] == "--env-file") + .map(|w| w[1].as_str()) + .collect() + } + + fn compose_files(argv: &[String]) -> Vec<&str> { + argv.windows(2) + .filter(|w| w[0] == "-f") + .map(|w| w[1].as_str()) + .collect() + } + + fn assert_no_project_flag(argv: &[String]) { + assert!( + !argv.iter().any(|s| s == "-p" || s == "--project-name"), + "VPS argv must not pass -p/--project-name: {argv:?}" + ); + } #[test] fn vps_argv_is_the_three_overlay_files() { - let a = vps_compose_argv(); + let shop = TempShop::new("base"); + let a = vps_compose_argv(&shop.0); assert_eq!( a, vec![ @@ -136,5 +195,64 @@ mod tests { "docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml" ); assert!(!args_contain_build(&a)); + assert_eq!(env_files(&a), [".env"]); + assert_eq!( + compose_files(&a), + [ + "deploy/compose.yaml", + "deploy/compose.prod.yaml", + "deploy/compose.vps.yaml" + ] + ); + assert_no_project_flag(&a); + } + + #[test] + fn vps_argv_includes_host_env_files_when_present() { + let shop = TempShop::new("host-env"); + fs::write(shop.0.join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + fs::write(shop.0.join(".env.prod"), "SHOPWARE_DEPLOY_ENV=live\n").unwrap(); + let a = vps_compose_argv(&shop.0); + assert_eq!(env_files(&a), [".env", ".env.local", ".env.prod"]); + assert_eq!( + compose_files(&a), + [ + "deploy/compose.yaml", + "deploy/compose.prod.yaml", + "deploy/compose.vps.yaml" + ] + ); + assert_no_project_flag(&a); + let log = docker_log(&a); + assert_eq!( + log, + "docker compose --env-file .env --env-file .env.local --env-file .env.prod -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml" + ); + let env_idx: Vec = a + .windows(2) + .enumerate() + .filter(|(_, w)| w[0] == "--env-file") + .map(|(i, _)| i) + .collect(); + let dash_f = a.iter().position(|s| s == "-f").unwrap(); + assert!(env_idx.iter().all(|i| *i < dash_f), "{a:?}"); + } + + #[test] + fn vps_argv_omits_missing_host_env_files() { + let shop = TempShop::new("prod-only"); + fs::write(shop.0.join(".env.prod"), "").unwrap(); + let a = vps_compose_argv(&shop.0); + assert_eq!(env_files(&a), [".env", ".env.prod"]); + assert_eq!( + compose_files(&a), + [ + "deploy/compose.yaml", + "deploy/compose.prod.yaml", + "deploy/compose.vps.yaml" + ] + ); + assert!(!a.iter().any(|s| s == ".env.local"), "{a:?}"); + assert_no_project_flag(&a); } } diff --git a/src/shopware/compose_override.rs b/src/shopware/compose_override.rs new file mode 100644 index 0000000..66945f8 --- /dev/null +++ b/src/shopware/compose_override.rs @@ -0,0 +1,148 @@ +//! Upsert top-level Compose `name:` in shop-root `compose.override.yaml`. +//! +//! shopware-cli regenerates `compose.yaml` and leaves `compose.override.yaml` +//! for local customization. Compose (and `shopware-cli project dev`) read +//! `COMPOSE_PROJECT_NAME` only from project-directory `.env`, not `.env.local`, +//! so the YAML `name:` key is what actually names the local stack. + +pub const OVERRIDE_REL: &str = "compose.override.yaml"; + +const EMPTY_FILE_HEADER: &str = + "# Written by fyrst-cli shopware env init. Compose project for shopware-cli project dev.\n"; + +/// Set or replace the top-level `name:` scalar. Nested `name:` keys (indented) +/// and other mappings are left untouched. Returns `(contents, changed)`. +pub fn upsert_top_level_name(contents: &str, project: &str) -> (String, bool) { + let desired = format!("name: {project}"); + if contents.trim().is_empty() { + return (format!("{EMPTY_FILE_HEADER}{desired}\n"), true); + } + + let mut out = String::new(); + let mut found = false; + let mut changed = false; + for line in contents.lines() { + let line = trim_cr(line); + if is_top_level_name_key(line) { + found = true; + if line.trim() == desired { + out.push_str(line); + } else { + out.push_str(&desired); + changed = true; + } + out.push('\n'); + } else { + out.push_str(line); + out.push('\n'); + } + } + if found { + return (out, changed); + } + (insert_after_header(contents, &desired), true) +} + +fn insert_after_header(contents: &str, desired: &str) -> String { + let lines: Vec<&str> = contents.lines().map(trim_cr).collect(); + let mut insert_at = 0; + for (i, line) in lines.iter().enumerate() { + let t = line.trim(); + if t.is_empty() || t.starts_with('#') || t == "---" { + insert_at = i + 1; + continue; + } + break; + } + let mut out = String::new(); + for (i, line) in lines.iter().enumerate() { + if i == insert_at { + out.push_str(desired); + out.push('\n'); + } + out.push_str(line); + out.push('\n'); + } + if insert_at >= lines.len() { + out.push_str(desired); + out.push('\n'); + } + out +} + +fn is_top_level_name_key(line: &str) -> bool { + if line.starts_with(' ') || line.starts_with('\t') { + return false; + } + let t = line.trim(); + if t.is_empty() || t.starts_with('#') { + return false; + } + let Some(after) = t.strip_prefix("name") else { + return false; + }; + after.trim_start().starts_with(':') +} + +fn trim_cr(line: &str) -> &str { + line.trim_end_matches('\r') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn creates_file_with_name() { + let (out, changed) = upsert_top_level_name("", "acme-dev"); + assert!(changed); + assert!(out.contains("name: acme-dev\n")); + assert!(out.contains("fyrst-cli shopware env init")); + assert!(!out.contains("services:")); + } + + #[test] + fn replaces_existing_top_level_name_keeps_services() { + let src = "\ +# keep me +name: old-folder +services: + web: + name: nested-must-stay + ports: + - \"9003:9003\" +"; + let (out, changed) = upsert_top_level_name(src, "acme-dev"); + assert!(changed); + assert!(out.contains("name: acme-dev\n")); + assert!(!out.contains("name: old-folder")); + assert!(out.contains(" name: nested-must-stay")); + assert!(out.contains("# keep me")); + assert!(out.contains(" - \"9003:9003\"")); + } + + #[test] + fn idempotent_when_already_set() { + let src = "name: acme-live\nservices:\n web:\n image: x\n"; + let (out, changed) = upsert_top_level_name(src, "acme-live"); + assert!(!changed); + assert_eq!(out, src); + } + + #[test] + fn inserts_after_document_start_when_missing() { + let src = "\ +--- +services: + web: + image: x +"; + let (out, changed) = upsert_top_level_name(src, "acme-staging"); + assert!(changed); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!(lines[0], "---"); + assert_eq!(lines[1], "name: acme-staging"); + assert!(out.contains("services:")); + assert_eq!(out.matches("name:").count(), 1); + } +} diff --git a/src/shopware/env.rs b/src/shopware/env.rs index db0a612..87643bb 100644 --- a/src/shopware/env.rs +++ b/src/shopware/env.rs @@ -3,8 +3,10 @@ //! One loader for every shopware verb: process env is the base, then //! `.env`, `.env.local` (if present), `.env.prod` (if present). Later files //! win except identity / process-win keys, which a non-empty process value -//! still owns. Leftover `SYNC_*` / `BACKUP_SSH_*` / `BACKUP_ALLOW_*` names -//! fail when the replacement is unset. +//! still owns. Empty `SHOPWARE_DEPLOY_ENV=` / `COMPOSE_PROJECT_NAME=` in a file +//! is ignored so a host file (`.env.local` / `.env.prod`) can own the value +//! over an empty leftover in committed `.env`. Leftover `SYNC_*` / +//! `BACKUP_SSH_*` / `BACKUP_ALLOW_*` names fail when the replacement is unset. use super::envfile::parse_env_file; use super::error::Error; @@ -40,7 +42,21 @@ const PROCESS_WINS: &[&str] = &[ ]; /// Root `.env.*` only. Later file wins. Never `deploy/*.env`. -const ENV_FILES: &[&str] = &[".env", ".env.local", ".env.prod"]; +/// Same order as `docker compose --env-file` flags. +pub const ENV_FILES: &[&str] = &[".env", ".env.local", ".env.prod"]; + +/// `--env-file` flags: always `.env`, then `.env.local` / `.env.prod` if present. +pub fn compose_env_file_flags(compose_dir: &Path) -> Vec { + let mut out = Vec::new(); + for rel in ENV_FILES { + if *rel != ".env" && !compose_dir.join(rel).is_file() { + continue; + } + out.push("--env-file".into()); + out.push((*rel).to_string()); + } + out +} pub const COMPOSE_FILES: &[&str] = &[ "deploy/compose.yaml", @@ -89,6 +105,12 @@ impl ShopEnv { let contents = fs::read_to_string(&path) .map_err(|e| Error::fail(format!("cannot read {}: {e}", path.display())))?; for (k, v) in parse_env_file(&contents) { + if matches!(k.as_str(), "SHOPWARE_DEPLOY_ENV" | "COMPOSE_PROJECT_NAME") + && v.is_empty() + { + // Empty leftover in shared `.env` must not hide a host file. + continue; + } vars.insert(k, v); } } @@ -293,7 +315,7 @@ pub fn require_deploy_env(env: &ShopEnv) -> Result { .map(str::to_string) .ok_or_else(|| { Error::fail( - "SHOPWARE_DEPLOY_ENV is required (live|staging|playground|dev). Set it in shop-root .env.", + "SHOPWARE_DEPLOY_ENV is required (live|staging|playground|dev). Set it in .env.local (host-specific; not committed shared .env).", ) }) } @@ -310,17 +332,40 @@ pub fn allow_live_restore(env: &ShopEnv) -> bool { env_truthy(env.get("SHOPWARE_ALLOW_LIVE_RESTORE")) } +/// Compose project `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. +/// +/// Same string locally (`.env.local` + `compose.override.yaml` `name:`) and +/// on VPS (`deploy/compose.yaml` `name:` interpolating host env files). Do +/// not store this (or `COMPOSE_PROJECT_NAME`) in committed `.env`. +pub fn vps_project_name(shop_id: &str, deploy_env: &str) -> String { + format!("{shop_id}-{deploy_env}") +} + +/// Derived project name when shop id and deploy env are both set. +pub fn vps_project_name_opt(env: &ShopEnv) -> Option { + match (env.get("SHOPWARE_SHOP_ID"), env.get("SHOPWARE_DEPLOY_ENV")) { + (Some(id), Some(deploy_env)) if !id.is_empty() && !deploy_env.is_empty() => { + Some(vps_project_name(id, deploy_env)) + } + _ => None, + } +} + /// `(project_name, derived_from_shop_id_and_env)`. +/// +/// Prefers `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` so named-volume fallback +/// matches compose `name:`. `COMPOSE_PROJECT_NAME` is a last-resort +/// fallback when shop id / deploy env are missing. pub fn derive_project_name(env: &ShopEnv) -> Result<(String, bool), Error> { + if let Some(n) = vps_project_name_opt(env) { + return Ok((n, true)); + } if let Some(n) = env.get("COMPOSE_PROJECT_NAME") { return Ok((n.to_string(), false)); } - match (env.get("SHOPWARE_SHOP_ID"), env.get("SHOPWARE_DEPLOY_ENV")) { - (Some(id), Some(deploy_env)) => Ok((format!("{id}-{deploy_env}"), true)), - _ => Err(Error::fail( - "Set COMPOSE_PROJECT_NAME in .env (must be unique on this Docker host), or set SHOPWARE_SHOP_ID and SHOPWARE_DEPLOY_ENV to derive ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV}.", - )), - } + Err(Error::fail( + "Set SHOPWARE_SHOP_ID in shared .env and SHOPWARE_DEPLOY_ENV in .env.local to derive ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV} for Compose (deploy/compose.yaml name: + host env files).", + )) } /// Work directory for sync capture/apply (`--snapshot-dir`, else `var/runtime-sync`). @@ -716,16 +761,120 @@ COMPOSE_PROFILES=redis } #[test] - fn compose_project_name_wins() { + fn compose_project_name_does_not_override_identity_name() { let mut vars = HashMap::new(); vars.insert("COMPOSE_PROJECT_NAME".into(), "sw-shop-acme".into()); vars.insert("SHOPWARE_SHOP_ID".into(), "acme".into()); vars.insert("SHOPWARE_DEPLOY_ENV".into(), "live".into()); let env = ShopEnv::from_vars(PathBuf::from("/tmp/x"), vars); + assert_eq!( + derive_project_name(&env).unwrap(), + ("acme-live".into(), true) + ); + assert_eq!(vps_project_name_opt(&env).as_deref(), Some("acme-live")); + } + + #[test] + fn compose_project_name_fallback_without_shop_identity() { + let mut vars = HashMap::new(); + vars.insert("COMPOSE_PROJECT_NAME".into(), "sw-shop-acme".into()); + let env = ShopEnv::from_vars(PathBuf::from("/tmp/x"), vars); assert_eq!( derive_project_name(&env).unwrap(), ("sw-shop-acme".into(), false) ); + assert_eq!(vps_project_name_opt(&env), None); + } + + #[test] + fn deploy_env_from_local_wins_over_shared_env() { + let shop = temp_shop("deploy-env-local-wins"); + fs::write( + shop.join(".env"), + "SHOPWARE_SHOP_ID=acme\nSHOPWARE_DEPLOY_ENV=live\n", + ) + .unwrap(); + fs::write(shop.join(".env.local"), "SHOPWARE_DEPLOY_ENV=staging\n").unwrap(); + let env = ShopEnv::load(shop.clone(), &HashMap::new()).unwrap(); + assert_eq!(env.get("SHOPWARE_SHOP_ID"), Some("acme")); + assert_eq!(env.get("SHOPWARE_DEPLOY_ENV"), Some("staging")); + let _ = fs::remove_dir_all(&shop); + } + + #[test] + fn empty_shared_deploy_env_does_not_hide_host_file() { + let shop = temp_shop("deploy-env-empty-shared"); + fs::write( + shop.join(".env"), + "SHOPWARE_SHOP_ID=acme\nSHOPWARE_DEPLOY_ENV=\n", + ) + .unwrap(); + fs::write(shop.join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + let env = ShopEnv::load(shop.clone(), &HashMap::new()).unwrap(); + assert_eq!(env.get("SHOPWARE_DEPLOY_ENV"), Some("dev")); + let _ = fs::remove_dir_all(&shop); + } + + #[test] + fn empty_shared_compose_project_name_does_not_hide_host_file() { + let shop = temp_shop("cpn-empty-shared"); + fs::write( + shop.join(".env"), + "SHOPWARE_SHOP_ID=acme\nCOMPOSE_PROJECT_NAME=\n", + ) + .unwrap(); + fs::write( + shop.join(".env.local"), + "SHOPWARE_DEPLOY_ENV=dev\nCOMPOSE_PROJECT_NAME=acme-dev\n", + ) + .unwrap(); + let env = ShopEnv::load(shop.clone(), &HashMap::new()).unwrap(); + assert_eq!(env.get("COMPOSE_PROJECT_NAME"), Some("acme-dev")); + let _ = fs::remove_dir_all(&shop); + } + + #[test] + fn compose_project_name_from_local_wins_over_shared_leftover() { + let shop = temp_shop("cpn-local-wins"); + fs::write( + shop.join(".env"), + "SHOPWARE_SHOP_ID=acme\nCOMPOSE_PROJECT_NAME=sw-shop-acme\n", + ) + .unwrap(); + fs::write( + shop.join(".env.local"), + "SHOPWARE_DEPLOY_ENV=dev\nCOMPOSE_PROJECT_NAME=acme-dev\n", + ) + .unwrap(); + let env = ShopEnv::load(shop.clone(), &HashMap::new()).unwrap(); + assert_eq!(env.get("COMPOSE_PROJECT_NAME"), Some("acme-dev")); + assert_eq!(vps_project_name_opt(&env).as_deref(), Some("acme-dev")); + let _ = fs::remove_dir_all(&shop); + } + + #[test] + fn empty_local_deploy_env_does_not_wipe_shared_leftover() { + let shop = temp_shop("deploy-env-empty-local"); + fs::write( + shop.join(".env"), + "SHOPWARE_SHOP_ID=acme\nSHOPWARE_DEPLOY_ENV=live\n", + ) + .unwrap(); + fs::write(shop.join(".env.local"), "SHOPWARE_DEPLOY_ENV=\n").unwrap(); + let env = ShopEnv::load(shop.clone(), &HashMap::new()).unwrap(); + assert_eq!(env.get("SHOPWARE_DEPLOY_ENV"), Some("live")); + let _ = fs::remove_dir_all(&shop); + } + + #[test] + fn deploy_env_from_prod_wins_over_local() { + let shop = temp_shop("deploy-env-prod-wins"); + fs::write(shop.join(".env"), "SHOPWARE_SHOP_ID=acme\n").unwrap(); + fs::write(shop.join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + fs::write(shop.join(".env.prod"), "SHOPWARE_DEPLOY_ENV=live\n").unwrap(); + let env = ShopEnv::load(shop.clone(), &HashMap::new()).unwrap(); + assert_eq!(env.get("SHOPWARE_DEPLOY_ENV"), Some("live")); + let _ = fs::remove_dir_all(&shop); } #[test] diff --git a/src/shopware/envfile.rs b/src/shopware/envfile.rs index bd5a500..e0a8bc2 100644 --- a/src/shopware/envfile.rs +++ b/src/shopware/envfile.rs @@ -47,8 +47,14 @@ pub fn has_key(contents: &str, key: &str) -> bool { pub const MERGE_FROM_EXAMPLE_HEADER: &str = "# --- missing keys merged from .env.example by deploy/init-env.sh ---"; +/// Keys that must not be copied from `.env.example` into committed `.env`. +const SKIP_MERGE_INTO_SHARED_ENV: &[&str] = &["COMPOSE_PROJECT_NAME", "SHOPWARE_DEPLOY_ENV"]; + pub const COMPOSE_PROJECT_NAME_COMMENT_SUFFIX: &str = - " # commented by deploy/init-env.sh (restore for local project dev)"; + " # commented by fyrst-cli shopware env init (Compose project is ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV}; host .env.local + compose.override.yaml / VPS compose name:)"; + +pub const SHOPWARE_DEPLOY_ENV_COMMENT_SUFFIX: &str = + " # commented by fyrst-cli shopware env init (host-specific; set in .env.local)"; /// Replace every uncommented `KEY=` line, or append `KEY=value`. /// Preserves an `export` prefix. Does not quote `value` (overlay `env_set_key`). @@ -83,17 +89,17 @@ pub fn set_key(contents: &str, key: &str, value: &str) -> String { out } -/// Comment uncommented `COMPOSE_PROJECT_NAME=` lines (create footgun). -/// Returns the rewritten file and how many lines were commented. -pub fn comment_compose_project_name(contents: &str) -> (String, usize) { +/// Comment uncommented `KEY=` lines. Returns the rewritten file and how many +/// lines were commented. Already-commented lines are left as-is. +pub fn comment_uncommented_key(contents: &str, key: &str, suffix: &str) -> (String, usize) { let mut out = String::new(); let mut n = 0; for line in contents.lines() { let line = trim_cr(line); - if uncommented_assignment(line, "COMPOSE_PROJECT_NAME").is_some() { + if uncommented_assignment(line, key).is_some() { out.push_str("# "); out.push_str(line); - out.push_str(COMPOSE_PROJECT_NAME_COMMENT_SUFFIX); + out.push_str(suffix); out.push('\n'); n += 1; } else { @@ -104,7 +110,24 @@ pub fn comment_compose_project_name(contents: &str) -> (String, usize) { (out, n) } +pub fn comment_compose_project_name(contents: &str) -> (String, usize) { + comment_uncommented_key( + contents, + "COMPOSE_PROJECT_NAME", + COMPOSE_PROJECT_NAME_COMMENT_SUFFIX, + ) +} + +pub fn comment_deploy_env(contents: &str) -> (String, usize) { + comment_uncommented_key( + contents, + "SHOPWARE_DEPLOY_ENV", + SHOPWARE_DEPLOY_ENV_COMMENT_SUFFIX, + ) +} + /// Append assignment lines from `.env.example` whose keys are missing in dest. +/// Skips `COMPOSE_PROJECT_NAME` and `SHOPWARE_DEPLOY_ENV` (not for shared `.env`). pub fn merge_missing_from_example(example: &str, dest: &mut String) -> Vec { let mut added = Vec::new(); let mut header = false; @@ -116,6 +139,9 @@ pub fn merge_missing_from_example(example: &str, dest: &mut String) -> Vec String { let decode = decode_log(self.kind, &self.file); match &self.target { - ImportTarget::Bundled { compose_files, .. } => { + ImportTarget::Bundled { + compose_dir, + compose_files, + } => { format!( "{decode} | {} exec -T mysql sh -c ''", - compose_cli_log(compose_files) + compose_cli_log(compose_dir, compose_files) ) } ImportTarget::External { @@ -366,8 +369,8 @@ pub fn execute(plan: &ImportPlan) -> Result<(), Error> { Ok(()) } -fn bundled_exec_args(files: &[String]) -> Vec { - let mut a = super::mysql::compose_argv(files); +fn bundled_exec_args(compose_dir: &Path, files: &[String]) -> Vec { + let mut a = super::mysql::compose_argv(compose_dir, files); a.extend([ "exec".into(), "-T".into(), @@ -422,7 +425,7 @@ fn external_run_args(target: &ImportTarget) -> Result, Error> { } fn run_bundled(plan: &ImportPlan, compose_dir: &Path, files: &[String]) -> Result<(), Error> { - let args = bundled_exec_args(files); + let args = bundled_exec_args(compose_dir, files); pipe_sql_into_docker(plan, &args, Some(compose_dir), None) } @@ -570,6 +573,7 @@ mod tests { "\ SHOPWARE_SHOP_ID=acme SHOPWARE_DEPLOY_ENV=staging +COMPOSE_PROJECT_NAME=shopware-acme MYSQL_USER=shop MYSQL_PASSWORD=super-secret-pass MYSQL_DATABASE=shopware @@ -592,10 +596,48 @@ MYSQL_DATABASE=shopware assert!(!log.contains("super-secret-pass"), "{log}"); assert!(log.contains("gzip -dc"), "{log}"); assert!(log.contains("exec -T mysql"), "{log}"); + assert!(log.contains("--env-file .env"), "{log}"); assert!(log.contains("-f deploy/compose.yaml"), "{log}"); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); + assert!(!log.contains("shopware-acme"), "{log}"); assert!(matches!(plan.target, ImportTarget::Bundled { .. })); } + #[test] + fn bundled_log_includes_host_env_files() { + let shop = TempShop::new("host-env"); + shop.write_env("SHOPWARE_SHOP_ID=acme\nSHOPWARE_DEPLOY_ENV=staging\nMYSQL_USER=u\n"); + shop.write_compose_mysql(); + fs::write(shop.path().join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + fs::write(shop.path().join(".env.prod"), "").unwrap(); + let dump = shop.dump("db.sql.gz", b"not-a-real-gzip-but-exists"); + let plan = plan_import( + &process(shop.path()), + shop.path(), + &dump, + true, + LivePolicy::DbImport { + allow_live_flag: false, + }, + ) + .unwrap(); + let log = plan.log_line(); + assert!( + log.contains("--env-file .env --env-file .env.local --env-file .env.prod"), + "{log}" + ); + assert!(log.contains("-f deploy/compose.yaml"), "{log}"); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); + } + #[test] fn sql_file_uses_cat_in_plan() { let shop = TempShop::new("sql"); diff --git a/src/shopware/init_env.rs b/src/shopware/init_env.rs index bf42e2a..f758d1a 100644 --- a/src/shopware/init_env.rs +++ b/src/shopware/init_env.rs @@ -1,16 +1,26 @@ //! `fyrst-cli shopware env init` — finish shop-root `.env` after create + Flex. //! -//! Sets fyrst identity (shop id, deploy env, optional IMAGE) and merges -//! missing keys from `.env.example`. Always comments out uncommented -//! `COMPOSE_PROJECT_NAME` lines (create writes `COMPOSE_PROJECT_NAME=sw-…`; -//! Compose SoT is `SHOPWARE_SHOP_ID` + `SHOPWARE_DEPLOY_ENV`). Does not -//! overwrite the whole file, does not invent MYSQL passwords or `APP_URL`, -//! and does not generate or rewrite `APP_SECRET` (`shopware-cli project -//! create` writes that). Never prints secrets. This is not a dump command. - -use super::env::resolve_compose_dir_init; +//! Shared `.env` is git-committed and must not hold env-specific values. +//! This command may set `SHOPWARE_SHOP_ID` (same slug everywhere) and optional +//! `IMAGE`, merge missing keys from `.env.example`, and **comments out** +//! uncommented `COMPOSE_PROJECT_NAME` (create writes `sw-…`) and leftover +//! `SHOPWARE_DEPLOY_ENV` in shared `.env`. Deploy env and +//! `COMPOSE_PROJECT_NAME=-` are written to `.env.local` +//! (gitignored). Top-level Compose `name: -` is upserted in +//! gitignored `compose.override.yaml` so `shopware-cli project dev` uses that +//! name (Compose auto-reads `COMPOSE_PROJECT_NAME` only from project-directory +//! `.env`, not `.env.local`). VPS Compose project is the same +//! `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` via `deploy/compose.yaml` `name:` +//! interpolating host env files. +//! Does not invent MYSQL passwords or `APP_URL`, and does not generate or +//! rewrite `APP_SECRET` (`shopware-cli project create` writes that). Never +//! prints secrets. This is not a dump command. + +use super::compose_override::{upsert_top_level_name, OVERRIDE_REL}; +use super::env::{resolve_compose_dir_init, vps_project_name}; use super::envfile::{ - comment_compose_project_name, last_value, merge_missing_from_example, set_key, + comment_compose_project_name, comment_deploy_env, last_value, merge_missing_from_example, + set_key, }; use super::error::Error; use crate::cli::InitEnvArgs; @@ -22,7 +32,11 @@ use std::path::{Path, PathBuf}; pub(crate) struct Plan { pub compose_dir: PathBuf, pub env_file: PathBuf, + pub local_env_file: PathBuf, + pub override_file: PathBuf, contents: String, + local_contents: String, + override_contents: String, pub dry_run: bool, pub copied: bool, pub merged_keys: Vec, @@ -30,8 +44,14 @@ pub(crate) struct Plan { pub shop_id_changed: bool, pub deploy_env: String, pub deploy_env_changed: bool, + pub local_created: bool, + pub compose_project_name: String, + pub compose_project_name_changed: bool, + pub override_created: bool, + pub override_changed: bool, pub image_set: Option, pub compose_project_name_commented: usize, + pub deploy_env_commented: usize, } impl std::fmt::Debug for Plan { @@ -39,6 +59,8 @@ impl std::fmt::Debug for Plan { f.debug_struct("Plan") .field("compose_dir", &self.compose_dir) .field("env_file", &self.env_file) + .field("local_env_file", &self.local_env_file) + .field("override_file", &self.override_file) .field("dry_run", &self.dry_run) .field("copied", &self.copied) .field("merged_keys", &self.merged_keys) @@ -46,11 +68,20 @@ impl std::fmt::Debug for Plan { .field("shop_id_changed", &self.shop_id_changed) .field("deploy_env", &self.deploy_env) .field("deploy_env_changed", &self.deploy_env_changed) + .field("local_created", &self.local_created) + .field("compose_project_name", &self.compose_project_name) + .field( + "compose_project_name_changed", + &self.compose_project_name_changed, + ) + .field("override_created", &self.override_created) + .field("override_changed", &self.override_changed) .field("image_set", &self.image_set) .field( "compose_project_name_commented", &self.compose_project_name_commented, ) + .field("deploy_env_commented", &self.deploy_env_commented) .finish_non_exhaustive() } } @@ -60,6 +91,16 @@ impl Plan { pub(crate) fn contents(&self) -> &str { &self.contents } + + #[cfg(test)] + pub(crate) fn local_contents(&self) -> &str { + &self.local_contents + } + + #[cfg(test)] + pub(crate) fn override_contents(&self) -> &str { + &self.override_contents + } } pub fn run(args: InitEnvArgs) -> Result<(), Error> { @@ -93,6 +134,8 @@ pub(crate) fn plan( ) -> Result { let compose_dir = resolve_compose_dir_init(process_env, cwd)?; let env_file = compose_dir.join(".env"); + let local_env_file = compose_dir.join(".env.local"); + let override_file = compose_dir.join(OVERRIDE_REL); let example_file = compose_dir.join(".env.example"); let env_exists = env_file.is_file(); @@ -123,9 +166,25 @@ pub(crate) fn plan( merged_keys = merge_missing_from_example(example, &mut contents); } + let local_exists = local_env_file.is_file(); + let mut local_contents = if local_exists { + read_file(&local_env_file)? + } else { + String::new() + }; + let prod_deploy_env = read_optional_key(&compose_dir.join(".env.prod"), "SHOPWARE_DEPLOY_ENV")?; + let existing_shop_id = last_value(&contents, "SHOPWARE_SHOP_ID"); - let existing_deploy_env = last_value(&contents, "SHOPWARE_DEPLOY_ENV"); + let leftover_shared_deploy_env = last_value(&contents, "SHOPWARE_DEPLOY_ENV"); + let existing_host_deploy_env = last_value(&local_contents, "SHOPWARE_DEPLOY_ENV"); + let existing_host_compose_project_name = last_value(&local_contents, "COMPOSE_PROJECT_NAME"); let existing_image = last_value(&contents, "IMAGE"); + let override_exists = override_file.is_file(); + let existing_override = if override_exists { + read_file(&override_file)? + } else { + String::new() + }; let shop_id_flag = nonempty_flag(args.shop_id.as_deref(), "--shop-id")?; let shop_id = match shop_id_flag { @@ -141,7 +200,9 @@ pub(crate) fn plan( let deploy_env = match args.env { Some(e) => e.as_str().to_string(), - None if !existing_deploy_env.is_empty() => existing_deploy_env.clone(), + None if !existing_host_deploy_env.is_empty() => existing_host_deploy_env.clone(), + None if !prod_deploy_env.is_empty() => prod_deploy_env, + None if !leftover_shared_deploy_env.is_empty() => leftover_shared_deploy_env.clone(), None => "live".to_string(), }; validate_deploy_env(&deploy_env)?; @@ -156,7 +217,6 @@ pub(crate) fn plan( } contents = set_key(&contents, "SHOPWARE_SHOP_ID", &shop_id); - contents = set_key(&contents, "SHOPWARE_DEPLOY_ENV", &deploy_env); let mut image_set = None; if let Some(image) = image_flag { if existing_image != image { @@ -166,13 +226,29 @@ pub(crate) fn plan( } let (contents, compose_project_name_commented) = comment_compose_project_name(&contents); + let (contents, deploy_env_commented) = comment_deploy_env(&contents); + + let compose_project_name = vps_project_name(&shop_id, &deploy_env); + local_contents = set_key(&local_contents, "SHOPWARE_DEPLOY_ENV", &deploy_env); + local_contents = set_key( + &local_contents, + "COMPOSE_PROJECT_NAME", + &compose_project_name, + ); + let (override_contents, override_changed) = + upsert_top_level_name(&existing_override, &compose_project_name); let shop_id_changed = existing_shop_id != shop_id; - let deploy_env_changed = existing_deploy_env != deploy_env; + let deploy_env_changed = existing_host_deploy_env != deploy_env; + let compose_project_name_changed = existing_host_compose_project_name != compose_project_name; Ok(Plan { compose_dir, env_file, + local_env_file, + override_file, contents, + local_contents, + override_contents, dry_run: args.dry_run, copied, merged_keys, @@ -180,11 +256,24 @@ pub(crate) fn plan( shop_id_changed, deploy_env, deploy_env_changed, + local_created: !local_exists, + compose_project_name, + compose_project_name_changed, + override_created: !override_exists, + override_changed, image_set, compose_project_name_commented, + deploy_env_commented, }) } +fn read_optional_key(path: &Path, key: &str) -> Result { + if !path.is_file() { + return Ok(String::new()); + } + Ok(last_value(&read_file(path)?, key)) +} + fn nonempty_flag<'a>(value: Option<&'a str>, flag: &str) -> Result, Error> { match value { None => Ok(None), @@ -234,6 +323,19 @@ fn execute(plan: &Plan) -> Result<(), Error> { fs::write(&plan.env_file, &plan.contents) .map_err(|e| Error::fail(format!("cannot write {}: {e}", plan.env_file.display())))?; chmod_600(&plan.env_file)?; + fs::write(&plan.local_env_file, &plan.local_contents).map_err(|e| { + Error::fail(format!( + "cannot write {}: {e}", + plan.local_env_file.display() + )) + })?; + chmod_600(&plan.local_env_file)?; + fs::write(&plan.override_file, &plan.override_contents).map_err(|e| { + Error::fail(format!( + "cannot write {}: {e}", + plan.override_file.display() + )) + })?; } print!("{}", summary_text(plan)); Ok(()) @@ -249,6 +351,8 @@ pub(crate) fn summary_text(plan: &Plan) -> String { ); } else { let _ = writeln!(s, "==> Updated {}", plan.env_file.display()); + let _ = writeln!(s, "==> Updated {}", plan.local_env_file.display()); + let _ = writeln!(s, "==> Updated {}", plan.override_file.display()); } let mut changes = 0u32; @@ -268,10 +372,6 @@ pub(crate) fn summary_text(plan: &Plan) -> String { let _ = writeln!(s, " set SHOPWARE_SHOP_ID={}", plan.shop_id); changes += 1; } - if plan.deploy_env_changed { - let _ = writeln!(s, " set SHOPWARE_DEPLOY_ENV={}", plan.deploy_env); - changes += 1; - } if let Some(image) = &plan.image_set { let _ = writeln!(s, " set IMAGE={image}"); changes += 1; @@ -279,12 +379,72 @@ pub(crate) fn summary_text(plan: &Plan) -> String { if plan.compose_project_name_commented > 0 { let _ = writeln!( s, - " commented {} COMPOSE_PROJECT_NAME=… line(s)", + " commented {} COMPOSE_PROJECT_NAME=… line(s) in shared .env", plan.compose_project_name_commented ); changes += 1; } else { - let _ = writeln!(s, " no uncommented COMPOSE_PROJECT_NAME=… lines"); + let _ = writeln!(s, " no uncommented COMPOSE_PROJECT_NAME=… in shared .env"); + } + if plan.deploy_env_commented > 0 { + let _ = writeln!( + s, + " commented {} SHOPWARE_DEPLOY_ENV=… line(s) in shared .env", + plan.deploy_env_commented + ); + changes += 1; + } else { + let _ = writeln!(s, " no uncommented SHOPWARE_DEPLOY_ENV=… in shared .env"); + } + if plan.local_created { + let _ = writeln!(s, " create .env.local"); + changes += 1; + } + if plan.deploy_env_changed { + let _ = writeln!( + s, + " set SHOPWARE_DEPLOY_ENV={} in .env.local", + plan.deploy_env + ); + changes += 1; + } else { + let _ = writeln!( + s, + " already set SHOPWARE_DEPLOY_ENV={} in .env.local", + plan.deploy_env + ); + } + if plan.compose_project_name_changed { + let _ = writeln!( + s, + " set COMPOSE_PROJECT_NAME={} in .env.local", + plan.compose_project_name + ); + changes += 1; + } else { + let _ = writeln!( + s, + " already set COMPOSE_PROJECT_NAME={} in .env.local", + plan.compose_project_name + ); + } + if plan.override_created { + let _ = writeln!(s, " create {OVERRIDE_REL}"); + changes += 1; + } + if plan.override_changed { + let _ = writeln!( + s, + " set name: {} in {OVERRIDE_REL}", + plan.compose_project_name + ); + changes += 1; + } else { + let _ = writeln!( + s, + " already set name: {} in {OVERRIDE_REL}", + plan.compose_project_name + ); } if changes == 0 { let _ = writeln!(s, " no changes (already up to date)"); @@ -295,6 +455,7 @@ pub(crate) fn summary_text(plan: &Plan) -> String { ); if !plan.dry_run { let _ = writeln!(s, "==> chmod 600 .env"); + let _ = writeln!(s, "==> chmod 600 .env.local"); } s } @@ -316,6 +477,8 @@ mod tests { use super::super::envfile::{has_key, MERGE_FROM_EXAMPLE_HEADER}; use super::*; use crate::cli::DeployEnv; + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; use std::time::{SystemTime, UNIX_EPOCH}; struct TempShop(PathBuf); @@ -342,6 +505,14 @@ mod tests { fs::write(self.0.join(".env"), s).unwrap(); } + fn write_local(&self, s: &str) { + fs::write(self.0.join(".env.local"), s).unwrap(); + } + + fn write_override(&self, s: &str) { + fs::write(self.0.join(OVERRIDE_REL), s).unwrap(); + } + fn write_example(&self, s: &str) { fs::write(self.0.join(".env.example"), s).unwrap(); } @@ -371,6 +542,13 @@ mod tests { const EXISTING_SECRET: &str = "existing-app-secret-do-not-print-0123456789abcdef"; const MYSQL_PASS: &str = "super-secret-pass"; + fn assert_no_uncommented(contents: &str, key: &str) { + assert!( + !has_key(contents, key), + "shared .env still has uncommented {key}:\n{contents}" + ); + } + #[test] fn dry_run_summary_hides_passwords_and_does_not_write() { let shop = TempShop::new("dry"); @@ -389,31 +567,54 @@ COMPOSE_PROJECT_NAME=sw-shop-acme assert!(p.dry_run); assert_eq!(p.shop_id, "acme"); assert_eq!(p.deploy_env, "live"); + assert!(p.local_created); assert_eq!(p.image_set.as_deref(), Some("ghcr.io/example/acme")); - assert_eq!(p.compose_project_name_commented, 1); + assert!(p.compose_project_name_commented >= 1); + assert!(p.deploy_env_commented >= 1); assert_eq!(last_value(p.contents(), "APP_SECRET"), EXISTING_SECRET); - assert!(!has_key(p.contents(), "COMPOSE_PROJECT_NAME")); + assert_no_uncommented(p.contents(), "COMPOSE_PROJECT_NAME"); + assert_no_uncommented(p.contents(), "SHOPWARE_DEPLOY_ENV"); + assert_eq!( + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" + ); + assert_eq!( + last_value(p.local_contents(), "COMPOSE_PROJECT_NAME"), + "acme-live" + ); + assert_eq!(p.compose_project_name, "acme-live"); + assert!(p.override_created); + assert!(p.override_changed); + assert!(p.override_contents().contains("name: acme-live\n")); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=shopware-")); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=acme-")); let text = summary_text(&p); assert!(text.contains("DRY-RUN (no write)")); assert!(text.contains("set SHOPWARE_SHOP_ID=acme")); - assert!(text.contains("set SHOPWARE_DEPLOY_ENV=live")); + assert!(text.contains("set SHOPWARE_DEPLOY_ENV=live in .env.local")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-live in .env.local")); + assert!(text.contains("create compose.override.yaml")); + assert!(text.contains("set name: acme-live in compose.override.yaml")); + assert!(text.contains("commented ")); + assert!(text.contains("COMPOSE_PROJECT_NAME")); + assert!(text.contains("create .env.local")); assert!(text.contains("set IMAGE=ghcr.io/example/acme")); - assert!(text.contains("commented 1 COMPOSE_PROJECT_NAME")); assert!(!text.contains("--vps")); assert!(text.contains("APP_SECRET")); assert!(!text.contains("generate-app-secret")); assert!(!text.contains(MYSQL_PASS)); assert!(!text.contains(EXISTING_SECRET)); + let after = fs::read_to_string(shop.path().join(".env")).unwrap(); assert!( - fs::read_to_string(shop.path().join(".env")) - .unwrap() - .contains("COMPOSE_PROJECT_NAME=sw-shop-acme"), + after.contains("COMPOSE_PROJECT_NAME=sw-shop-acme"), "dry-run must not write .env" ); + assert!(!shop.path().join(".env.local").is_file()); + assert!(!shop.path().join(OVERRIDE_REL).is_file()); } #[test] - fn write_path_sets_keys_merges_example_and_comments_compose_project_name() { + fn write_path_sets_shop_id_comments_shared_keys_and_writes_local() { let shop = TempShop::new("write"); shop.write_env(&format!( "\ @@ -421,6 +622,7 @@ SHOPWARE_SHOP_ID= MYSQL_PASSWORD={MYSQL_PASS} APP_URL= COMPOSE_PROJECT_NAME=sw-shop-acme +SHOPWARE_DEPLOY_ENV=live " )); shop.write_example( @@ -429,6 +631,8 @@ SHOPWARE_SHOP_ID= MYSQL_PASSWORD=from-example APP_URL=http://localhost NEW_FROM_EXAMPLE=1 +COMPOSE_PROJECT_NAME=from-example +SHOPWARE_DEPLOY_ENV=from-example ", ); let mut a = args(); @@ -437,77 +641,154 @@ NEW_FROM_EXAMPLE=1 let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); assert!(p.merged_keys.contains(&"NEW_FROM_EXAMPLE".into())); assert!(!p.merged_keys.contains(&"MYSQL_PASSWORD".into())); + assert!(!p.merged_keys.contains(&"COMPOSE_PROJECT_NAME".into())); + assert!(!p.merged_keys.contains(&"SHOPWARE_DEPLOY_ENV".into())); assert_eq!(last_value(p.contents(), "SHOPWARE_SHOP_ID"), "acme"); - assert_eq!(last_value(p.contents(), "SHOPWARE_DEPLOY_ENV"), "staging"); + assert_no_uncommented(p.contents(), "SHOPWARE_DEPLOY_ENV"); assert_eq!(last_value(p.contents(), "MYSQL_PASSWORD"), MYSQL_PASS); assert!(p.contents().contains(MERGE_FROM_EXAMPLE_HEADER)); assert!(p.contents().contains("NEW_FROM_EXAMPLE=1")); - assert!(!has_key(p.contents(), "COMPOSE_PROJECT_NAME")); + assert_no_uncommented(p.contents(), "COMPOSE_PROJECT_NAME"); assert!(p .contents() - .contains("# COMPOSE_PROJECT_NAME=sw-shop-acme # commented by deploy/init-env.sh")); + .contains("# COMPOSE_PROJECT_NAME=sw-shop-acme # commented by fyrst-cli")); + assert_eq!( + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "staging" + ); + assert_eq!( + last_value(p.local_contents(), "COMPOSE_PROJECT_NAME"), + "acme-staging" + ); + assert!(p.override_contents().contains("name: acme-staging\n")); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=shopware-")); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=acme-")); assert!(!p.contents().contains("--vps")); let text = summary_text(&p); assert!(!text.contains(MYSQL_PASS)); assert!(!text.contains("--vps")); assert!(text.contains("merge missing keys from .env.example: NEW_FROM_EXAMPLE")); - assert!(text.contains("set SHOPWARE_DEPLOY_ENV=staging")); - assert!(text.contains("commented 1 COMPOSE_PROJECT_NAME")); + assert!(text.contains("set SHOPWARE_DEPLOY_ENV=staging in .env.local")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-staging in .env.local")); + assert!(text.contains("set name: acme-staging in compose.override.yaml")); + assert!(text.contains("commented ")); } #[test] - fn reports_none_when_compose_project_name_already_commented() { + fn already_commented_compose_project_name_is_idempotent() { let shop = TempShop::new("already-commented"); shop.write_env( "\ SHOPWARE_SHOP_ID=acme -SHOPWARE_DEPLOY_ENV=live # COMPOSE_PROJECT_NAME=sw-shop-acme ", ); + shop.write_local("SHOPWARE_DEPLOY_ENV=live\nCOMPOSE_PROJECT_NAME=acme-live\n"); + shop.write_override("name: acme-live\n"); let mut a = args(); a.shop_id = None; let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); assert_eq!(p.compose_project_name_commented, 0); + assert!(!p.deploy_env_changed); + assert!(!p.compose_project_name_changed); + assert!(!p.override_changed); + assert!(!p.override_created); + assert!(!p.local_created); assert!(p.contents().contains("# COMPOSE_PROJECT_NAME=sw-shop-acme")); + assert_no_uncommented(p.contents(), "COMPOSE_PROJECT_NAME"); + assert_eq!( + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" + ); + assert_eq!( + last_value(p.local_contents(), "COMPOSE_PROJECT_NAME"), + "acme-live" + ); let text = summary_text(&p); - assert!(text.contains("no uncommented COMPOSE_PROJECT_NAME")); - assert!(!text.contains("commented 0")); + assert!(text.contains("no uncommented COMPOSE_PROJECT_NAME=… in shared .env")); + assert!(text.contains("already set SHOPWARE_DEPLOY_ENV=live in .env.local")); + assert!(text.contains("already set COMPOSE_PROJECT_NAME=acme-live in .env.local")); + assert!(text.contains("already set name: acme-live in compose.override.yaml")); assert!(!text.contains("--vps")); assert!(text.contains("no changes (already up to date)")); } #[test] - fn copy_from_example_comments_compose_project_name() { + fn copy_from_example_comments_compose_project_name_and_writes_local() { let shop = TempShop::new("copy-cpn"); shop.write_example( "\ SHOPWARE_SHOP_ID= COMPOSE_PROJECT_NAME=sw-shop-acme +SHOPWARE_DEPLOY_ENV=live MYSQL_PASSWORD=example-secret ", ); let p = plan(&process(shop.path()), shop.path(), &args()).unwrap(); assert!(p.copied); - assert_eq!(p.compose_project_name_commented, 1); - assert!(!has_key(p.contents(), "COMPOSE_PROJECT_NAME")); - assert!(p - .contents() - .contains("# COMPOSE_PROJECT_NAME=sw-shop-acme # commented by deploy/init-env.sh")); + assert!(p.compose_project_name_commented >= 1); + assert_no_uncommented(p.contents(), "COMPOSE_PROJECT_NAME"); + assert_no_uncommented(p.contents(), "SHOPWARE_DEPLOY_ENV"); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=sw-shop-acme\n")); + assert_eq!( + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" + ); + assert_eq!( + last_value(p.local_contents(), "COMPOSE_PROJECT_NAME"), + "acme-live" + ); + assert!(p.override_contents().contains("name: acme-live\n")); let text = summary_text(&p); assert!(text.contains("copy .env.example → .env")); - assert!(text.contains("commented 1 COMPOSE_PROJECT_NAME")); + assert!(text.contains("commented ")); + assert!(text.contains("create .env.local")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-live in .env.local")); assert!(!text.contains("--vps")); assert!(!text.contains("example-secret")); } + #[test] + fn leftover_shared_deploy_env_migrates_to_local_and_is_commented() { + let shop = TempShop::new("migrate-env"); + shop.write_env( + "\ +SHOPWARE_SHOP_ID=acme +SHOPWARE_DEPLOY_ENV=staging +", + ); + let mut a = args(); + a.shop_id = None; + let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); + assert_eq!(p.deploy_env, "staging"); + assert!(p.local_created); + assert!(p.deploy_env_changed); + assert!(p.deploy_env_commented >= 1); + assert_no_uncommented(p.contents(), "SHOPWARE_DEPLOY_ENV"); + assert!(p + .contents() + .contains("# SHOPWARE_DEPLOY_ENV=staging # commented by fyrst-cli")); + assert_eq!( + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "staging" + ); + assert_eq!( + last_value(p.local_contents(), "COMPOSE_PROJECT_NAME"), + "acme-staging" + ); + let text = summary_text(&p); + assert!(text.contains("set SHOPWARE_DEPLOY_ENV=staging in .env.local")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-staging in .env.local")); + assert!(text.contains("commented ")); + assert!(text.contains("SHOPWARE_DEPLOY_ENV")); + } + #[test] fn leaves_existing_app_secret_unchanged() { let shop = TempShop::new("keep-secret"); shop.write_env(&format!( "\ SHOPWARE_SHOP_ID=acme -SHOPWARE_DEPLOY_ENV=live APP_SECRET={EXISTING_SECRET} MYSQL_PASSWORD={MYSQL_PASS} " @@ -522,7 +803,10 @@ MYSQL_PASSWORD={MYSQL_PASS} assert!(!text.contains(MYSQL_PASS)); assert!(!text.contains("generate-app-secret")); assert!(!p.shop_id_changed); - assert!(!p.deploy_env_changed); + assert_eq!( + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" + ); } #[test] @@ -549,7 +833,7 @@ MYSQL_PASSWORD=super-secret-pass #[test] fn missing_shop_id_is_fail_not_stub() { let shop = TempShop::new("noid"); - shop.write_env("SHOPWARE_DEPLOY_ENV=live\n"); + shop.write_env("MYSQL_PASSWORD=x\n"); let mut a = args(); a.shop_id = None; let err = plan(&process(shop.path()), shop.path(), &a).unwrap_err(); @@ -604,27 +888,130 @@ MYSQL_PASSWORD=example-secret assert!(p.copied); assert!(p.merged_keys.is_empty()); assert_eq!(last_value(p.contents(), "MYSQL_PASSWORD"), "example-secret"); + assert_no_uncommented(p.contents(), "COMPOSE_PROJECT_NAME"); + assert_no_uncommented(p.contents(), "SHOPWARE_DEPLOY_ENV"); + assert!(p.local_created); + assert_eq!( + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" + ); + assert_eq!( + last_value(p.local_contents(), "COMPOSE_PROJECT_NAME"), + "acme-live" + ); let text = summary_text(&p); assert!(text.contains("copy .env.example → .env")); + assert!(text.contains("create .env.local")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-live in .env.local")); assert!(!text.contains("example-secret")); assert!(!shop.path().join(".env").is_file()); } #[test] - fn keep_existing_nonempty_deploy_env() { + fn keep_existing_host_deploy_env() { let shop = TempShop::new("keep-env"); - shop.write_env("SHOPWARE_SHOP_ID=acme\nSHOPWARE_DEPLOY_ENV=playground\n"); + shop.write_env( + "\ +SHOPWARE_SHOP_ID=acme +", + ); + shop.write_local("SHOPWARE_DEPLOY_ENV=playground\nCOMPOSE_PROJECT_NAME=acme-playground\n"); + shop.write_override("name: acme-playground\n"); let mut a = args(); a.shop_id = None; let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); assert_eq!(p.deploy_env, "playground"); assert!(!p.deploy_env_changed); + assert!(!p.compose_project_name_changed); + assert!(!p.override_changed); + assert!(!p.local_created); let text = summary_text(&p); - assert!(text.contains("no uncommented COMPOSE_PROJECT_NAME")); + assert!(text.contains("already set SHOPWARE_DEPLOY_ENV=playground in .env.local")); + assert!(text.contains("already set COMPOSE_PROJECT_NAME=acme-playground in .env.local")); assert!(!text.contains("--vps")); assert!(text.contains("no changes (already up to date)")); } + #[test] + fn env_flag_overwrites_host_file() { + let shop = TempShop::new("flag-wins"); + shop.write_env("SHOPWARE_SHOP_ID=acme\n"); + shop.write_local("SHOPWARE_DEPLOY_ENV=live\nCOMPOSE_PROJECT_NAME=acme-live\n"); + shop.write_override("name: acme-live\nservices:\n web:\n image: x\n"); + let mut a = args(); + a.shop_id = None; + a.env = Some(DeployEnv::Dev); + let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); + assert_eq!(p.deploy_env, "dev"); + assert!(p.deploy_env_changed); + assert!(p.compose_project_name_changed); + assert_eq!(last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), "dev"); + assert_eq!( + last_value(p.local_contents(), "COMPOSE_PROJECT_NAME"), + "acme-dev" + ); + assert!(p.override_contents().contains("name: acme-dev\n")); + assert!(p.override_contents().contains(" image: x")); + assert!(!p.override_contents().contains("name: acme-live")); + let text = summary_text(&p); + assert!(text.contains("set SHOPWARE_DEPLOY_ENV=dev in .env.local")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-dev in .env.local")); + assert!(text.contains("set name: acme-dev in compose.override.yaml")); + } + + #[test] + fn execute_writes_local_project_name_and_keeps_override_services() { + let shop = TempShop::new("exec-override"); + shop.write_env( + "\ +SHOPWARE_SHOP_ID=acme +COMPOSE_PROJECT_NAME=sw-shop-acme +", + ); + shop.write_override( + "\ +# keep me +services: + web: + name: nested-must-stay + ports: + - \"9003:9003\" +", + ); + let mut a = args(); + a.dry_run = false; + a.env = Some(DeployEnv::Dev); + let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); + execute(&p).unwrap(); + + let env = fs::read_to_string(shop.path().join(".env")).unwrap(); + assert_no_uncommented(&env, "COMPOSE_PROJECT_NAME"); + assert!(!env + .lines() + .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); + let local = fs::read_to_string(shop.path().join(".env.local")).unwrap(); + assert_eq!(last_value(&local, "SHOPWARE_DEPLOY_ENV"), "dev"); + assert_eq!(last_value(&local, "COMPOSE_PROJECT_NAME"), "acme-dev"); + let ov = fs::read_to_string(shop.path().join(OVERRIDE_REL)).unwrap(); + assert!(ov.contains("name: acme-dev\n")); + assert!(ov.contains(" name: nested-must-stay")); + assert!(ov.contains("# keep me")); + assert!(ov.contains(" - \"9003:9003\"")); + #[cfg(unix)] + { + let local_mode = fs::metadata(shop.path().join(".env.local")) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(local_mode, 0o600); + } + assert!(!fs::read_to_string(shop.path().join(".env")) + .unwrap() + .lines() + .any(|l| l.trim_start().starts_with("SHOPWARE_DEPLOY_ENV="))); + } + #[test] fn slug_pattern() { assert!(is_shop_slug("a")); diff --git a/src/shopware/mod.rs b/src/shopware/mod.rs index af24fd0..4913cb0 100644 --- a/src/shopware/mod.rs +++ b/src/shopware/mod.rs @@ -22,6 +22,7 @@ mod app; mod backup; mod backup_restore; mod compose; +mod compose_override; mod data; mod env; mod envfile; diff --git a/src/shopware/mysql.rs b/src/shopware/mysql.rs index b89522e..b910642 100644 --- a/src/shopware/mysql.rs +++ b/src/shopware/mysql.rs @@ -3,7 +3,7 @@ //! Used by `shopware db import` (and `sync apply` for the DB). Passwords //! must never appear in log lines. -use super::env::ShopEnv; +use super::env::{compose_env_file_flags, ShopEnv}; use super::envfile::urldecode; use super::error::Error; use std::fmt; @@ -156,8 +156,15 @@ pub fn client_image_for_url(scheme: &str, _env: &ShopEnv) -> String { } } -pub fn compose_argv(files: &[String]) -> Vec { - let mut a = vec!["compose".into(), "--env-file".into(), ".env".into()]; +/// `docker compose --env-file … -f …` for db import / rewrite / restore. +/// +/// Project name comes from compose `name:` (VPS `deploy/compose.yaml` or local +/// `compose.override.yaml`) after host env files load in identity order +/// (always `.env`, then `.env.local` / `.env.prod` when present). There is no +/// `-p` / `--project-name`. +pub fn compose_argv(compose_dir: &Path, files: &[String]) -> Vec { + let mut a = vec!["compose".into()]; + a.extend(compose_env_file_flags(compose_dir)); for f in files { a.push("-f".into()); a.push(f.clone()); @@ -165,11 +172,11 @@ pub fn compose_argv(files: &[String]) -> Vec { a } -pub fn compose_cli_log(files: &[String]) -> String { - let mut s = String::from("docker compose --env-file .env"); - for f in files { - s.push_str(" -f "); - s.push_str(f); +pub fn compose_cli_log(compose_dir: &Path, files: &[String]) -> String { + let mut s = String::from("docker"); + for a in compose_argv(compose_dir, files) { + s.push(' '); + s.push_str(&a); } s } @@ -211,7 +218,7 @@ pub fn compose_up_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Erro "No compose files found under shop root; cannot start service mysql.", )); } - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); args.extend([ "up".into(), "-d".into(), @@ -232,7 +239,7 @@ pub fn compose_up_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Erro } fn wait_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Error> { - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); args.extend([ "exec".into(), "-T".into(), @@ -361,6 +368,63 @@ mod tests { ); } + #[test] + fn compose_argv_loads_host_env_files_without_project_flag() { + let files = vec![ + "deploy/compose.yaml".into(), + "deploy/compose.prod.yaml".into(), + ]; + let dir = std::env::temp_dir().join(format!( + "fyrst-cli-compose-argv-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + let a = compose_argv(&dir, &files); + assert_eq!( + a, + vec![ + "compose", + "--env-file", + ".env", + "-f", + "deploy/compose.yaml", + "-f", + "deploy/compose.prod.yaml", + ] + ); + assert!(!a.iter().any(|s| s == "-p" || s == "--project-name")); + let log = compose_cli_log(&dir, &files); + assert!( + log.starts_with("docker compose --env-file .env -f deploy/compose.yaml"), + "{log}" + ); + assert!(!log.split_whitespace().any(|t| t == "-p"), "{log}"); + + fs::write(dir.join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + fs::write(dir.join(".env.prod"), "").unwrap(); + let with_host = compose_argv(&dir, &files); + assert_eq!( + with_host + .windows(2) + .filter(|w| w[0] == "--env-file") + .count(), + 3 + ); + assert!(with_host.windows(2).any(|w| w == ["--env-file", ".env"])); + assert!(with_host + .windows(2) + .any(|w| w == ["--env-file", ".env.local"])); + assert!(with_host + .windows(2) + .any(|w| w == ["--env-file", ".env.prod"])); + assert!(!with_host.iter().any(|s| s == "-p" || s == "--project-name")); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn secrets_never_include_empty() { let env = env_from(&[("MYSQL_PASSWORD", "s3cret-value")]); diff --git a/src/shopware/restore.rs b/src/shopware/restore.rs index 5fe7496..d322acc 100644 --- a/src/shopware/restore.rs +++ b/src/shopware/restore.rs @@ -322,7 +322,7 @@ fn stop_app_containers( } fn list_running_app_services(compose_dir: &Path, files: &[String]) -> Vec { - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); args.extend([ "--profile".into(), "worker".into(), @@ -350,7 +350,7 @@ fn list_running_app_services(compose_dir: &Path, files: &[String]) -> Vec, svc: &str, ) -> Result<(), Error> { - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); if let Some(p) = profile { args.extend(["--profile".into(), p.to_string()]); } @@ -466,7 +466,7 @@ fn post_restore_hints(plan: &RestorePlan) { } fn cache_clear(compose_dir: &Path, files: &[String]) -> Result<(), Error> { - let mut args = compose_argv(files); + let mut args = compose_argv(compose_dir, files); args.extend([ "run".into(), "--rm".into(), @@ -695,6 +695,14 @@ mod tests { assert!(log_line.contains("--dry-run"), "{log_line}"); assert!(!log_line.contains("s3cret-value"), "{log_line}"); assert!(docker_args.contains(&"fyrst:sales-channel:rewrite-urls".to_string())); + assert!(!docker_args + .iter() + .any(|a| a == "-p" || a == "--project-name")); + assert!(docker_args.windows(2).any(|w| w == ["--env-file", ".env"])); + assert!( + !log_line.split_whitespace().any(|t| t == "-p"), + "{log_line}" + ); assert!(!log_line .to_ascii_lowercase() .contains("update sales_channel")); diff --git a/src/shopware/rewrite.rs b/src/shopware/rewrite.rs index e030a00..ed85088 100644 --- a/src/shopware/rewrite.rs +++ b/src/shopware/rewrite.rs @@ -53,7 +53,7 @@ pub fn console_flag_args(env: &ShopEnv, checkout: &str, dry_run: bool) -> Vec Vec { let files = existing_compose_files(compose_dir); let checkout = super::live::shop_basename(compose_dir); - let mut args = compose_argv(&files); + let mut args = compose_argv(compose_dir, &files); args.extend([ "run".into(), "--rm".into(), @@ -75,7 +75,7 @@ pub fn rewrite_log_line(env: &ShopEnv, compose_dir: &Path, dry_run: bool) -> Str let flags = console_flag_args(env, &checkout, dry_run); format!( "{} run --rm --pull never --entrypoint php web bin/console fyrst:sales-channel:rewrite-urls {}", - compose_cli_log(&files), + compose_cli_log(compose_dir, &files), flags.join(" ") ) } @@ -126,7 +126,7 @@ pub fn maybe_rewrite( } let checkout = super::live::shop_basename(compose_dir); let args = { - let mut a = compose_argv(files); + let mut a = compose_argv(compose_dir, files); a.extend([ "run".into(), "--rm".into(), @@ -219,13 +219,26 @@ mod tests { #[test] fn compose_line_is_console_not_sql() { - let env = env_from(&[("APP_URL", "https://staging.example.com")]); + let env = env_from(&[ + ("APP_URL", "https://staging.example.com"), + ("SHOPWARE_SHOP_ID", "acme"), + ("SHOPWARE_DEPLOY_ENV", "staging"), + ("COMPOSE_PROJECT_NAME", "shopware-acme"), + ]); let line = rewrite_log_line(&env, Path::new("/shops/acme-staging"), true); assert!(line.contains("fyrst:sales-channel:rewrite-urls"), "{line}"); assert!( line.contains("run --rm --pull never --entrypoint php"), "{line}" ); + assert!(line.contains("--env-file .env"), "{line}"); + assert!( + !line + .split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{line}" + ); + assert!(!line.contains("shopware-acme"), "{line}"); assert!(line.contains("--dry-run"), "{line}"); assert!( !line.to_ascii_lowercase().contains("update sales_channel"), @@ -233,9 +246,38 @@ mod tests { ); let args = compose_rewrite_args(&env, Path::new("/shops/acme-staging"), false); assert!(args.contains(&"fyrst:sales-channel:rewrite-urls".to_string())); + assert!(!args.iter().any(|a| a == "-p" || a == "--project-name")); assert!(!args.iter().any(|a| a == "--dry-run")); } + #[test] + fn rewrite_argv_includes_host_env_files() { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("fyrst-cli-rew-env-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(dir.join("deploy")).unwrap(); + std::fs::write( + dir.join("deploy/compose.yaml"), + "services:\n web:\n image: x\n", + ) + .unwrap(); + std::fs::write(dir.join(".env.local"), "SHOPWARE_DEPLOY_ENV=staging\n").unwrap(); + let env = env_from(&[ + ("APP_URL", "https://staging.example.com"), + ("SHOPWARE_SHOP_ID", "acme"), + ("SHOPWARE_DEPLOY_ENV", "staging"), + ]); + let args = compose_rewrite_args(&env, &dir, false); + assert!(args.windows(2).any(|w| w == ["--env-file", ".env"])); + assert!(args.windows(2).any(|w| w == ["--env-file", ".env.local"])); + assert!(args.windows(2).any(|w| w == ["-f", "deploy/compose.yaml"])); + assert!(!args.iter().any(|a| a == "-p" || a == "--project-name")); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn live_skips_rewrite_so_dr_can_continue() { let signals = LiveSignals { diff --git a/src/shopware/rollout.rs b/src/shopware/rollout.rs index 65e1e55..2da3f63 100644 --- a/src/shopware/rollout.rs +++ b/src/shopware/rollout.rs @@ -6,7 +6,7 @@ use super::compose::{ args_contain_build, compose_service_names, docker_log, extend_profiles, require_vps_compose_files, run_compose, vps_compose_argv, }; -use super::env::{derive_project_name, require_shop_id, ShopEnv, DEFAULT_DATA_BASE}; +use super::env::{require_shop_id, vps_project_name, ShopEnv, DEFAULT_DATA_BASE}; use super::error::Error; use super::mysql::log_contains_secret; use std::fs; @@ -150,6 +150,7 @@ pub struct RolloutPlan { impl RolloutPlan { pub fn build( + compose_dir: &Path, skip_pull: bool, pull_policy: String, profiles: Vec, @@ -158,12 +159,12 @@ impl RolloutPlan { let pull = if skip_pull { None } else { - let mut a = vps_compose_argv(); + let mut a = vps_compose_argv(compose_dir); extend_profiles(&mut a, &profiles); a.push("pull".into()); Some(a) }; - let mut setup = vps_compose_argv(); + let mut setup = vps_compose_argv(compose_dir); setup.extend([ "--profile".into(), "setup".into(), @@ -173,14 +174,14 @@ impl RolloutPlan { "never".into(), "setup".into(), ]); - let mut web = vps_compose_argv(); + let mut web = vps_compose_argv(compose_dir); web.extend(["up".into(), "-d".into(), "--no-build".into()]); web.extend(up_pull_args(skip_pull)); web.extend(["--remove-orphans".into(), "web".into()]); let extra = if profiles.is_empty() { None } else { - let mut a = vps_compose_argv(); + let mut a = vps_compose_argv(compose_dir); extend_profiles(&mut a, &profiles); a.extend(["up".into(), "-d".into(), "--no-build".into()]); a.extend(up_pull_args(skip_pull)); @@ -224,7 +225,6 @@ pub struct VpsContext { pub image_tag: String, pub shop_id: String, pub deploy_env: String, - pub compose_project_name: String, pub data_base: String, pub data_root: String, pub profiles: Vec, @@ -255,10 +255,6 @@ impl VpsContext { ), ("SHOPWARE_SHOP_ID".into(), self.shop_id.clone()), ("SHOPWARE_DEPLOY_ENV".into(), self.deploy_env.clone()), - ( - "COMPOSE_PROJECT_NAME".into(), - self.compose_project_name.clone(), - ), ("SHOPWARE_DATA_BASE".into(), self.data_base.clone()), ("SHOPWARE_DATA_ROOT".into(), self.data_root.clone()), ]; @@ -270,6 +266,7 @@ impl VpsContext { pub fn plan(&self) -> RolloutPlan { RolloutPlan::build( + &self.compose_dir, self.skip_pull, self.pull_policy.clone(), self.profiles.clone(), @@ -300,10 +297,10 @@ pub fn bootstrap(env: &ShopEnv, skip_pull_flag: bool, dry_run: bool) -> Result Result Result Result<(), Error if services.iter().any(|s| s == "mysql") { println!("==> Starting mysql"); - let mut a = vps_compose_argv(); + let mut a = vps_compose_argv(&ctx.compose_dir); a.extend(["up".into(), "-d".into(), "--no-build".into()]); a.extend(up_pull_args(plan.skip_pull)); a.push("mysql".into()); @@ -425,7 +413,7 @@ pub fn execute_rollout(ctx: &VpsContext, plan: &RolloutPlan) -> Result<(), Error if services.iter().any(|s| s == "redis") || ctx.profiles_raw.contains("redis") { println!("==> Starting redis"); - let mut a = vps_compose_argv(); + let mut a = vps_compose_argv(&ctx.compose_dir); a.extend([ "--profile".into(), "redis".into(), @@ -520,14 +508,16 @@ mod tests { use std::collections::HashMap; use std::time::{SystemTime, UNIX_EPOCH}; - fn plan(skip: bool, profiles: &str) -> RolloutPlan { + fn plan(skip: bool, profiles: &str) -> (TempShop, RolloutPlan) { + let shop = TempShop::new("plan"); let parsed = parse_profiles(if profiles.is_empty() { None } else { Some(profiles) }) .unwrap(); - RolloutPlan::build( + let p = RolloutPlan::build( + &shop.0, skip, if skip { "never".into() @@ -536,7 +526,8 @@ mod tests { }, parsed, profiles.to_string(), - ) + ); + (shop, p) } #[test] @@ -544,10 +535,11 @@ mod tests { let (policy, skip) = apply_pull_policy(true, Some("always")); assert_eq!(policy, "never"); assert!(skip); - let p = plan(true, ""); + let (_shop, p) = plan(true, ""); assert!(p.pull.is_none()); assert!(p.web.windows(2).any(|w| w == ["--pull", "never"])); assert!(p.web.iter().any(|a| a == "--no-build")); + assert!(!p.web.iter().any(|a| a == "-p" || a == "--project-name")); assert!(!p.setup.iter().any(|a| a == "--no-build")); assert!(p.setup.windows(2).any(|w| w == ["--pull", "never"])); assert!(p.never_builds()); @@ -558,7 +550,7 @@ mod tests { let (policy, skip) = apply_pull_policy(false, Some("never")); assert_eq!(policy, "never"); assert!(skip); - let p = plan(false, "redis,worker"); + let (_shop, p) = plan(false, "redis,worker"); assert!(p.never_builds()); let pull = p.pull.clone().expect("pull"); assert!(pull.ends_with(&["pull".to_string()])); @@ -614,7 +606,7 @@ mod tests { #[test] fn setup_run_never_uses_no_build() { - let p = plan(false, ""); + let (_shop, p) = plan(false, ""); let log = docker_log(&p.setup); assert!( log.contains("--profile setup run --rm --pull never setup"), @@ -626,6 +618,12 @@ mod tests { web.contains("up -d --no-build --remove-orphans web"), "{web}" ); + assert!( + !web.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{web}" + ); + assert!(!web.contains("shopware-acme"), "{web}"); } struct TempShop(PathBuf); @@ -670,6 +668,7 @@ SHOPWARE_SHOP_ID=acme SHOPWARE_DEPLOY_ENV=staging IMAGE=ghcr.io/file/shop IMAGE_TAG=latest +COMPOSE_PROJECT_NAME=shopware-acme MYSQL_PASSWORD=super-secret-pass DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop ", @@ -683,15 +682,52 @@ DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop assert_eq!(ctx.image, "ghcr.io/file/shop"); assert!(ctx.skip_pull); assert_eq!(ctx.pull_policy, "never"); - assert_eq!(ctx.compose_project_name, "acme-staging"); + assert_eq!(ctx.shop_id, "acme"); + assert_eq!(ctx.deploy_env, "staging"); + assert!(ctx.notes.iter().any(|n| n.contains("acme-staging"))); + assert!(ctx + .notes + .iter() + .any(|n| n.contains("COMPOSE_PROJECT_NAME=shopware-acme"))); + assert!(ctx + .notes + .iter() + .any(|n| n.contains("deploy/compose.yaml name:") && n.contains("acme-staging"))); + assert!(!ctx.notes.iter().any(|n| n.contains("-p "))); + assert!(!ctx + .extra_env() + .iter() + .any(|(k, _)| k == "COMPOSE_PROJECT_NAME")); + assert!(!ctx.warnings.iter().any(|w| w.contains("remove or comment"))); let plan = ctx.plan(); assert!(plan.pull.is_none()); + assert!(!plan.web.iter().any(|a| a == "-p" || a == "--project-name")); let web = docker_log_checked(&ctx, &plan.web).unwrap(); assert!(!ctx.log_contains_secret(&web)); assert!(!web.contains("s3cret-value")); assert!(!web.contains("super-secret-pass")); } + #[test] + fn rollout_plan_passes_host_env_files() { + let shop = TempShop::new("host-env"); + write_vps_files(&shop.0); + fs::write(shop.0.join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + fs::write(shop.0.join(".env.prod"), "").unwrap(); + let p = RolloutPlan::build(&shop.0, true, "never".into(), Vec::new(), String::new()); + assert!(p.web.windows(2).any(|w| w == ["--env-file", ".env"])); + assert!(p.web.windows(2).any(|w| w == ["--env-file", ".env.local"])); + assert!(p.web.windows(2).any(|w| w == ["--env-file", ".env.prod"])); + assert!(!p.web.iter().any(|a| a == "-p" || a == "--project-name")); + let log = docker_log(&p.web); + assert!( + log.contains("--env-file .env --env-file .env.local --env-file .env.prod"), + "{log}" + ); + assert!(log.contains("-f deploy/compose.yaml"), "{log}"); + assert!(!log.split_whitespace().any(|t| t == "-p"), "{log}"); + } + #[test] fn missing_vps_file_errors() { let shop = TempShop::new("nofile"); diff --git a/src/shopware/ssh.rs b/src/shopware/ssh.rs index 37cb65a..51a7b0b 100644 --- a/src/shopware/ssh.rs +++ b/src/shopware/ssh.rs @@ -195,19 +195,13 @@ pub fn resolve_remote_data_root( } pub fn resolve_remote_project_name( - src: &SshSource, + _src: &SshSource, env: &ShopEnv, shop_id: &str, ) -> Result { - if src.remote_path.is_some() { - let out = remote_bash(src, r#"printf %s "${COMPOSE_PROJECT_NAME:-}""#)?; - let n = String::from_utf8_lossy(&out.stdout); - let n = n.trim().trim_matches('"').trim(); - if !n.is_empty() { - return Ok(n.to_string()); - } - } let _ = require_shop_id(env); + // Remote live stacks are `{shop_id}-live` from identity. Do not use + // leftover `COMPOSE_PROJECT_NAME` from committed `.env`. Ok(format!("{shop_id}-live")) } diff --git a/src/shopware/sync.rs b/src/shopware/sync.rs index ed4b846..96510d5 100644 --- a/src/shopware/sync.rs +++ b/src/shopware/sync.rs @@ -8,7 +8,7 @@ use super::app; use super::data::normalize_data; use super::env::{ existing_compose_files, is_local_source, local_data_root, remote_data_root, require_shop_id, - resolve_compose_dir, resolve_snapshot_dir, ShopEnv, + resolve_compose_dir, resolve_snapshot_dir, vps_project_name_opt, ShopEnv, }; use super::error::Error; use super::import; @@ -71,14 +71,7 @@ fn run_with( data_root.display() ); } - let project = env - .get("COMPOSE_PROJECT_NAME") - .map(str::to_string) - .or_else(|| { - env.get("SHOPWARE_DEPLOY_ENV") - .map(|d| format!("{shop_id}-{d}")) - }) - .unwrap_or_default(); + let project = vps_project_name_opt(&env).unwrap_or_default(); let compose_files = existing_compose_files(&compose_dir); println!( diff --git a/tests/import.rs b/tests/import.rs index b3a34bc..b5d3fe4 100644 --- a/tests/import.rs +++ b/tests/import.rs @@ -36,6 +36,7 @@ impl TempShop { "\ SHOPWARE_SHOP_ID=acme SHOPWARE_DEPLOY_ENV=staging +COMPOSE_PROJECT_NAME=shopware-acme MYSQL_USER=shop MYSQL_PASSWORD=super-secret-pass MYSQL_DATABASE=shopware @@ -171,6 +172,41 @@ fn dry_run_bundled_mysql_without_password() { assert!(log.contains("exec -T mysql"), "{log}"); assert!(log.contains("docker compose --env-file .env"), "{log}"); assert!(log.contains("-f deploy/compose.yaml"), "{log}"); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); + assert!(!log.contains("-p shopware-acme"), "{log}"); +} + +#[test] +fn dry_run_passes_env_local() { + let shop = TempShop::new("env-local"); + shop.write_min_shop(); + fs::write(shop.path().join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + let dump = shop.dump_gz(); + let out = import( + shop.path(), + &["--dry-run", "--file", dump.to_str().unwrap()], + ); + assert_eq!( + out.status.code(), + Some(0), + "stderr={} stdout={}", + stderr(&out), + stdout(&out) + ); + let log = stdout(&out); + assert!( + log.contains("docker compose --env-file .env --env-file .env.local -f deploy/compose.yaml"), + "{log}" + ); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); } #[test] diff --git a/tests/init_env.rs b/tests/init_env.rs index 48e4283..55dd4fc 100644 --- a/tests/init_env.rs +++ b/tests/init_env.rs @@ -111,13 +111,32 @@ fn init_env_help_lists_flags() { "--dry-run", "COMPOSE_DIR", "COMPOSE_PROJECT_NAME", + ".env.local", + "SHOPWARE_DEPLOY_ENV", + "compose.override.yaml", ] { assert!(help.contains(needle), "missing {needle} in:\n{help}"); } + assert!( + !help.contains("COMPOSE_PROJECT_NAME=shopware-"), + "env init --help must not set COMPOSE_PROJECT_NAME=shopware-…:\n{help}" + ); + assert!( + help.contains("comments out") || help.contains("commented"), + "env init --help should describe commenting COMPOSE_PROJECT_NAME:\n{help}" + ); + assert!( + help.contains(".env.local") && help.contains("compose.override.yaml"), + "env init --help should describe host .env.local + compose.override.yaml:\n{help}" + ); assert!( !help.contains("--vps"), "env init --help must not list --vps:\n{help}" ); + assert!( + !help.contains("--strip"), + "env init --help must not list --strip:\n{help}" + ); assert!( !help.contains("generate-app-secret"), "env init --help must not list --generate-app-secret:\n{help}" @@ -165,9 +184,25 @@ COMPOSE_PROJECT_NAME=sw-shop-acme let log = stdout(&out); assert!(log.contains("DRY-RUN (no write)"), "{log}"); assert!(log.contains("set SHOPWARE_SHOP_ID=acme"), "{log}"); - assert!(log.contains("set SHOPWARE_DEPLOY_ENV=live"), "{log}"); + assert!( + log.contains("set SHOPWARE_DEPLOY_ENV=live in .env.local"), + "{log}" + ); + assert!( + log.contains("set COMPOSE_PROJECT_NAME=acme-live in .env.local"), + "{log}" + ); + assert!( + log.contains("set name: acme-live in compose.override.yaml"), + "{log}" + ); + assert!(log.contains("create compose.override.yaml"), "{log}"); assert!(log.contains("set IMAGE=ghcr.io/example/acme"), "{log}"); - assert!(log.contains("commented 1 COMPOSE_PROJECT_NAME"), "{log}"); + assert!( + log.contains("commented ") && log.contains("COMPOSE_PROJECT_NAME"), + "{log}" + ); + assert!(log.contains("create .env.local"), "{log}"); assert!(!log.contains("--vps"), "{log}"); assert!(!log.contains("generate-app-secret"), "{log}"); assert!(!log.contains("set APP_SECRET"), "{log}"); @@ -179,10 +214,12 @@ COMPOSE_PROJECT_NAME=sw-shop-acme assert_no_secrets(&out, &[]); let after = fs::read_to_string(shop.path().join(".env")).unwrap(); assert_eq!(after, original, "dry-run wrote .env"); + assert!(!shop.path().join(".env.local").is_file()); + assert!(!shop.path().join("compose.override.yaml").is_file()); } #[test] -fn write_merges_example_comments_compose_project_name_and_chmod() { +fn write_merges_example_comments_shared_keys_writes_local_and_chmod() { let shop = TempShop::new("write"); fs::write( shop.path().join(".env"), @@ -192,6 +229,7 @@ SHOPWARE_SHOP_ID= MYSQL_PASSWORD={MYSQL_PASS} APP_URL= COMPOSE_PROJECT_NAME=sw-shop-acme +SHOPWARE_DEPLOY_ENV=live " ), ) @@ -203,6 +241,8 @@ SHOPWARE_SHOP_ID= MYSQL_PASSWORD=from-example APP_URL=http://localhost NEW_FROM_EXAMPLE=1 +COMPOSE_PROJECT_NAME=from-example +SHOPWARE_DEPLOY_ENV=from-example ", ) .unwrap(); @@ -217,33 +257,66 @@ NEW_FROM_EXAMPLE=1 let log = stdout(&out); assert!(log.contains("Updated "), "{log}"); assert!(log.contains("chmod 600 .env"), "{log}"); + assert!(log.contains("chmod 600 .env.local"), "{log}"); assert!( log.contains("merge missing keys from .env.example: NEW_FROM_EXAMPLE"), "{log}" ); assert!(log.contains("set SHOPWARE_SHOP_ID=acme"), "{log}"); - assert!(log.contains("set SHOPWARE_DEPLOY_ENV=staging"), "{log}"); - assert!(log.contains("commented 1 COMPOSE_PROJECT_NAME"), "{log}"); + assert!( + log.contains("set SHOPWARE_DEPLOY_ENV=staging in .env.local"), + "{log}" + ); + assert!( + log.contains("set COMPOSE_PROJECT_NAME=acme-staging in .env.local"), + "{log}" + ); + assert!( + log.contains("set name: acme-staging in compose.override.yaml"), + "{log}" + ); + assert!( + log.contains("commented ") && log.contains("COMPOSE_PROJECT_NAME"), + "{log}" + ); assert!(!log.contains("--vps"), "{log}"); assert_no_secrets(&out, &["from-example"]); let env = fs::read_to_string(shop.path().join(".env")).unwrap(); assert!(env.contains("SHOPWARE_SHOP_ID=acme")); - assert!(env.contains("SHOPWARE_DEPLOY_ENV=staging")); + assert!(!env + .lines() + .any(|l| l.trim_start().starts_with("SHOPWARE_DEPLOY_ENV="))); + assert!(env.contains("# SHOPWARE_DEPLOY_ENV=live")); assert!(env.contains(&format!("MYSQL_PASSWORD={MYSQL_PASS}"))); assert!(!env.contains("MYSQL_PASSWORD=from-example")); assert!(env.contains("NEW_FROM_EXAMPLE=1")); - assert!(env.contains("# COMPOSE_PROJECT_NAME=sw-shop-acme # commented by deploy/init-env.sh")); - assert!(!env.contains("--vps")); + assert!(env.contains("# COMPOSE_PROJECT_NAME=sw-shop-acme")); assert!(!env .lines() .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); + assert!(!env.contains("COMPOSE_PROJECT_NAME=shopware-")); + assert!(!env.contains("--vps")); + let local = fs::read_to_string(shop.path().join(".env.local")).unwrap(); + assert!(local.contains("SHOPWARE_DEPLOY_ENV=staging")); + assert!(local.contains("COMPOSE_PROJECT_NAME=acme-staging")); + let override_yaml = fs::read_to_string(shop.path().join("compose.override.yaml")).unwrap(); + assert!(override_yaml.contains("name: acme-staging\n")); let mode = fs::metadata(shop.path().join(".env")) .unwrap() .permissions() .mode() & 0o777; assert_eq!(mode, 0o600, "expected chmod 600, got {mode:o}"); + let local_mode = fs::metadata(shop.path().join(".env.local")) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!( + local_mode, 0o600, + "expected chmod 600 .env.local, got {local_mode:o}" + ); } #[test] @@ -322,23 +395,47 @@ fn vps_flag_is_rejected() { } #[test] -fn already_commented_compose_project_name_reports_none() { - let shop = TempShop::new("already-cpn"); +fn already_commented_compose_project_name_stays_commented() { + let shop = TempShop::new("commented-cpn"); fs::write( shop.path().join(".env"), "\ SHOPWARE_SHOP_ID=acme -SHOPWARE_DEPLOY_ENV=live # COMPOSE_PROJECT_NAME=sw-shop-acme ", ) .unwrap(); + fs::write( + shop.path().join(".env.local"), + "SHOPWARE_DEPLOY_ENV=live\nCOMPOSE_PROJECT_NAME=acme-live\n", + ) + .unwrap(); + fs::write( + shop.path().join("compose.override.yaml"), + "name: acme-live\n", + ) + .unwrap(); let out = init_env(shop.path(), &[]); assert_eq!(out.status.code(), Some(0), "stderr={}", stderr(&out)); let log = stdout(&out); - assert!(log.contains("no uncommented COMPOSE_PROJECT_NAME"), "{log}"); - assert!(!log.contains("commented 1 COMPOSE_PROJECT_NAME"), "{log}"); + assert!( + log.contains("no uncommented COMPOSE_PROJECT_NAME=… in shared .env"), + "{log}" + ); + assert!( + log.contains("already set SHOPWARE_DEPLOY_ENV=live in .env.local"), + "{log}" + ); + assert!( + log.contains("already set COMPOSE_PROJECT_NAME=acme-live in .env.local"), + "{log}" + ); + assert!( + log.contains("already set name: acme-live in compose.override.yaml"), + "{log}" + ); assert!(!log.contains("--vps"), "{log}"); + assert!(log.contains("no changes (already up to date)"), "{log}"); let env = fs::read_to_string(shop.path().join(".env")).unwrap(); assert!(env.contains("# COMPOSE_PROJECT_NAME=sw-shop-acme")); assert!(!env @@ -346,6 +443,85 @@ SHOPWARE_DEPLOY_ENV=live .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); } +#[test] +fn leftover_compose_project_name_is_commented() { + let shop = TempShop::new("leftover-cpn"); + fs::write( + shop.path().join(".env"), + "\ +SHOPWARE_SHOP_ID=acme +COMPOSE_PROJECT_NAME=shopware-acme +", + ) + .unwrap(); + let out = init_env(shop.path(), &[]); + assert_eq!(out.status.code(), Some(0), "stderr={}", stderr(&out)); + let log = stdout(&out); + assert!( + log.contains("commented ") && log.contains("COMPOSE_PROJECT_NAME"), + "{log}" + ); + assert!( + log.contains("set COMPOSE_PROJECT_NAME=acme-live in .env.local"), + "{log}" + ); + assert!(!log.contains("no changes (already up to date)"), "{log}"); + let env = fs::read_to_string(shop.path().join(".env")).unwrap(); + assert!(env.contains("# COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(!env + .lines() + .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); + let local = fs::read_to_string(shop.path().join(".env.local")).unwrap(); + assert!(local.contains("SHOPWARE_DEPLOY_ENV=live")); + assert!(local.contains("COMPOSE_PROJECT_NAME=acme-live")); + let override_yaml = fs::read_to_string(shop.path().join("compose.override.yaml")).unwrap(); + assert!(override_yaml.contains("name: acme-live\n")); +} + +#[test] +fn existing_override_keeps_services_when_name_is_set() { + let shop = TempShop::new("keep-ov"); + fs::write(shop.path().join(".env"), "SHOPWARE_SHOP_ID=acme\n").unwrap(); + fs::write( + shop.path().join("compose.override.yaml"), + "\ +# xdebug +services: + web: + name: nested-must-stay + ports: + - \"9003:9003\" +", + ) + .unwrap(); + let out = init_env(shop.path(), &["--env", "dev"]); + assert_eq!(out.status.code(), Some(0), "stderr={}", stderr(&out)); + let log = stdout(&out); + assert!( + log.contains("set COMPOSE_PROJECT_NAME=acme-dev in .env.local"), + "{log}" + ); + assert!( + log.contains("set name: acme-dev in compose.override.yaml"), + "{log}" + ); + let env = fs::read_to_string(shop.path().join(".env")).unwrap(); + assert!(!env + .lines() + .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); + assert!(!env + .lines() + .any(|l| l.trim_start().starts_with("SHOPWARE_DEPLOY_ENV="))); + let local = fs::read_to_string(shop.path().join(".env.local")).unwrap(); + assert!(local.contains("COMPOSE_PROJECT_NAME=acme-dev")); + assert!(local.contains("SHOPWARE_DEPLOY_ENV=dev")); + let ov = fs::read_to_string(shop.path().join("compose.override.yaml")).unwrap(); + assert!(ov.contains("name: acme-dev\n")); + assert!(ov.contains(" name: nested-must-stay")); + assert!(ov.contains("# xdebug")); + assert!(ov.contains(" - \"9003:9003\"")); +} + #[test] fn generate_app_secret_flag_is_rejected() { let shop = TempShop::new("gone-flag"); @@ -377,6 +553,8 @@ MYSQL_PASSWORD={MYSQL_PASS} assert!(stdout(&out).contains("copy .env.example → .env")); assert_no_secrets(&out, &[]); assert!(!shop.path().join(".env").is_file()); + assert!(!shop.path().join(".env.local").is_file()); + assert!(!shop.path().join("compose.override.yaml").is_file()); } #[test] diff --git a/tests/release.rs b/tests/release.rs index 9ce29d7..da9992b 100644 --- a/tests/release.rs +++ b/tests/release.rs @@ -134,7 +134,7 @@ fn release_help_documents_flags() { #[test] fn dry_run_prints_compose_sequence_without_passwords() { let shop = TempShop::new("dry"); - shop.write_env("SMOKE_URL=http://127.0.0.1:8000\nCOMPOSE_PROFILES=redis,worker,scheduler\n"); + shop.write_env("SMOKE_URL=http://127.0.0.1:8000\nCOMPOSE_PROFILES=redis,worker,scheduler\nCOMPOSE_PROJECT_NAME=shopware-acme\n"); fs::write(shop.path().join(".deployed-tag"), "oldtag\n").unwrap(); let out = release(shop.path(), &["--dry-run"], &[]); assert_eq!( @@ -157,6 +157,12 @@ fn dry_run_prints_compose_sequence_without_passwords() { log.contains("DRY-RUN docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml"), "{log}" ); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); + assert!(!log.contains("-p shopware-acme"), "{log}"); assert!( log.contains("--profile setup run --rm --pull never setup"), "{log}" @@ -189,6 +195,33 @@ fn dry_run_prints_compose_sequence_without_passwords() { ); } +#[test] +fn dry_run_passes_env_local() { + let shop = TempShop::new("env-local"); + shop.write_env(""); + fs::write(shop.path().join(".env.local"), "SHOPWARE_DEPLOY_ENV=dev\n").unwrap(); + let out = release(shop.path(), &["--dry-run"], &[]); + assert_eq!( + out.status.code(), + Some(0), + "stderr={} stdout={}", + stderr(&out), + stdout(&out) + ); + let log = stdout(&out); + assert!( + log.contains( + "docker compose --env-file .env --env-file .env.local -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml" + ), + "{log}" + ); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); +} + #[test] fn skip_pull_dry_run_sets_pull_policy_never() { let shop = TempShop::new("skip"); diff --git a/tests/restore.rs b/tests/restore.rs index efd19d0..62c11ca 100644 --- a/tests/restore.rs +++ b/tests/restore.rs @@ -295,6 +295,12 @@ fn rewrite_dry_run_is_compose_console() { !log.to_ascii_lowercase().contains("update sales_channel"), "{log}" ); + assert!(log.contains("--env-file .env"), "{log}"); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); } #[test] diff --git a/tests/rollback.rs b/tests/rollback.rs index 7b413bb..5d595ae 100644 --- a/tests/rollback.rs +++ b/tests/rollback.rs @@ -38,6 +38,7 @@ IMAGE=ghcr.io/example/acme IMAGE_TAG=from-env-file SHOPWARE_SHOP_ID=acme SHOPWARE_DEPLOY_ENV=staging +COMPOSE_PROJECT_NAME=shopware-acme MYSQL_PASSWORD=super-secret-pass DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop ", @@ -247,10 +248,15 @@ fn dry_run_prints_same_compose_order_as_release() { let log = stdout(&out); assert!( log.contains( - "docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml" + "docker compose --env-file .env --env-file .env.prod -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml" ), "{log}" ); + assert!( + !log.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{log}" + ); let setup_idx = log .find("--profile setup run --rm --pull never setup") .unwrap_or_else(|| panic!("setup missing:\n{log}"));