From 9d673adb871b20e9c6e505933f8877ae15462f7f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 06:58:17 +0000 Subject: [PATCH 1/9] feat: set COMPOSE_PROJECT_NAME=shopware- in env init MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit env init now writes COMPOSE_PROJECT_NAME=shopware- (no deploy-env suffix) so local shopware-cli project dev and Compose share a stable name, instead of commenting out create's COMPOSE_PROJECT_NAME=sw-… line. Co-authored-by: ROBJkE --- README.md | 9 +-- docs/command-matrix.md | 8 ++- src/cli.rs | 10 +-- src/shopware/envfile.rs | 60 ++++++----------- src/shopware/init_env.rs | 141 ++++++++++++++++++++++++++++----------- tests/init_env.rs | 77 +++++++++++++++++---- 6 files changed, 201 insertions(+), 104 deletions(-) diff --git a/README.md b/README.md index 55aa275..6272bc5 100644 --- a/README.md +++ b/README.md @@ -154,10 +154,11 @@ Identity: `SHOPWARE_SHOP_ID`, `SHOPWARE_DEPLOY_ENV`, optional 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`. +already set. `--env` defaults to `live`. Sets +`COMPOSE_PROJECT_NAME=shopware-` so local `shopware-cli project +dev` and Compose share a stable name (create writes +`COMPOSE_PROJECT_NAME=sw-…`; no env suffix). `.env` may still be missing; +missing keys are merged from `.env.example`. ```bash fyrst-cli shopware env init --shop-id acme --dry-run diff --git a/docs/command-matrix.md b/docs/command-matrix.md index 734667b..1e4500d 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -179,9 +179,11 @@ shell expansion**), same parser as import (`src/shopware/envfile.rs`). 3. `--env` is `live` | `staging` | `playground` | `dev`. Default `live` when unset/empty; keep an existing non-empty value. 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=`. +5. Sets `COMPOSE_PROJECT_NAME=shopware-` so local + `shopware-cli project dev` and Compose share a stable name (create writes + `COMPOSE_PROJECT_NAME=sw-…`). Pattern is exactly `shopware-` — + no `SHOPWARE_DEPLOY_ENV` suffix. If the file only has a commented + `# COMPOSE_PROJECT_NAME=…` line, an uncommented assignment is appended. 6. `--dry-run` prints the summary and does not write `.env`. 7. After a real write: `chmod 600 .env`. diff --git a/src/cli.rs b/src/cli.rs index dcfc5af..b7ba76c 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -94,8 +94,8 @@ 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 / deploy env, optional IMAGE; sets \ +COMPOSE_PROJECT_NAME=shopware-). 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 +183,9 @@ 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\ +Sets COMPOSE_PROJECT_NAME=shopware- so local shopware-cli project dev and \ +Compose share a stable name (create writes COMPOSE_PROJECT_NAME=sw-…). \ +Does not append SHOPWARE_DEPLOY_ENV.\n\n\ Environment:\n \ COMPOSE_DIR Shop checkout (default: walk from cwd for .env / .env.example + deploy/)\n\n\ Examples:\n \ diff --git a/src/shopware/envfile.rs b/src/shopware/envfile.rs index bd5a500..9cf8e9b 100644 --- a/src/shopware/envfile.rs +++ b/src/shopware/envfile.rs @@ -47,9 +47,6 @@ 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 ---"; -pub const COMPOSE_PROJECT_NAME_COMMENT_SUFFIX: &str = - " # commented by deploy/init-env.sh (restore for local project dev)"; - /// Replace every uncommented `KEY=` line, or append `KEY=value`. /// Preserves an `export` prefix. Does not quote `value` (overlay `env_set_key`). pub fn set_key(contents: &str, key: &str, value: &str) -> String { @@ -83,27 +80,6 @@ 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) { - 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() { - out.push_str("# "); - out.push_str(line); - out.push_str(COMPOSE_PROJECT_NAME_COMMENT_SUFFIX); - out.push('\n'); - n += 1; - } else { - out.push_str(line); - out.push('\n'); - } - } - (out, n) -} - /// Append assignment lines from `.env.example` whose keys are missing in dest. pub fn merge_missing_from_example(example: &str, dest: &mut String) -> Vec { let mut added = Vec::new(); @@ -318,29 +294,35 @@ MYSQL_PASSWORD=pa$$word } #[test] - fn comment_compose_project_name_skips_already_commented() { + fn set_key_rewrites_uncommented_compose_project_name_and_appends_if_only_commented() { let src = "\ COMPOSE_PROJECT_NAME=sw-shop-acme export COMPOSE_PROJECT_NAME=other # COMPOSE_PROJECT_NAME=keep-commented MYSQL_PASSWORD=s3cret "; - let (out, n) = comment_compose_project_name(src); - assert_eq!(n, 2); - assert!(!has_key(&out, "COMPOSE_PROJECT_NAME")); - assert!(!out - .lines() - .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); - assert!( - out.contains("# COMPOSE_PROJECT_NAME=sw-shop-acme # commented by deploy/init-env.sh") - ); - assert!( - out.contains("# export COMPOSE_PROJECT_NAME=other # commented by deploy/init-env.sh") - ); - assert!(!out.contains("--vps")); + let out = set_key(src, "COMPOSE_PROJECT_NAME", "shopware-acme"); + assert_eq!(last_value(&out, "COMPOSE_PROJECT_NAME"), "shopware-acme"); + assert!(out.contains("COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(out.contains("export COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(!out.contains("COMPOSE_PROJECT_NAME=sw-shop-acme")); + assert!(!out.contains("COMPOSE_PROJECT_NAME=other")); assert!(out.contains("# COMPOSE_PROJECT_NAME=keep-commented")); assert!(out.contains("MYSQL_PASSWORD=s3cret")); - assert!(!out.contains("COMPOSE_PROJECT_NAME=\n")); + + let commented_only = "\ +# COMPOSE_PROJECT_NAME=sw-shop-acme +MYSQL_PASSWORD=s3cret +"; + let appended = set_key(commented_only, "COMPOSE_PROJECT_NAME", "shopware-acme"); + assert!(appended.contains("# COMPOSE_PROJECT_NAME=sw-shop-acme")); + assert!(appended.lines().any(|l| l + .trim_start() + .starts_with("COMPOSE_PROJECT_NAME=shopware-acme"))); + assert_eq!( + last_value(&appended, "COMPOSE_PROJECT_NAME"), + "shopware-acme" + ); } #[test] diff --git a/src/shopware/init_env.rs b/src/shopware/init_env.rs index bf42e2a..a61c700 100644 --- a/src/shopware/init_env.rs +++ b/src/shopware/init_env.rs @@ -1,17 +1,15 @@ //! `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`, +//! missing keys from `.env.example`. Sets `COMPOSE_PROJECT_NAME=shopware-` +//! so local `shopware-cli project dev` and Compose share a stable name (create +//! writes `COMPOSE_PROJECT_NAME=sw-…`; no `SHOPWARE_DEPLOY_ENV` suffix). 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; -use super::envfile::{ - comment_compose_project_name, last_value, merge_missing_from_example, set_key, -}; +use super::envfile::{last_value, merge_missing_from_example, set_key}; use super::error::Error; use crate::cli::InitEnvArgs; use std::collections::HashMap; @@ -31,7 +29,8 @@ pub(crate) struct Plan { pub deploy_env: String, pub deploy_env_changed: bool, pub image_set: Option, - pub compose_project_name_commented: usize, + pub compose_project_name: String, + pub compose_project_name_changed: bool, } impl std::fmt::Debug for Plan { @@ -47,9 +46,10 @@ impl std::fmt::Debug for Plan { .field("deploy_env", &self.deploy_env) .field("deploy_env_changed", &self.deploy_env_changed) .field("image_set", &self.image_set) + .field("compose_project_name", &self.compose_project_name) .field( - "compose_project_name_commented", - &self.compose_project_name_commented, + "compose_project_name_changed", + &self.compose_project_name_changed, ) .finish_non_exhaustive() } @@ -165,7 +165,10 @@ pub(crate) fn plan( contents = set_key(&contents, "IMAGE", image); } - let (contents, compose_project_name_commented) = comment_compose_project_name(&contents); + let compose_project_name = format!("shopware-{shop_id}"); + let compose_project_name_changed = + last_value(&contents, "COMPOSE_PROJECT_NAME") != compose_project_name; + contents = set_key(&contents, "COMPOSE_PROJECT_NAME", &compose_project_name); let shop_id_changed = existing_shop_id != shop_id; let deploy_env_changed = existing_deploy_env != deploy_env; @@ -181,7 +184,8 @@ pub(crate) fn plan( deploy_env, deploy_env_changed, image_set, - compose_project_name_commented, + compose_project_name, + compose_project_name_changed, }) } @@ -276,15 +280,19 @@ pub(crate) fn summary_text(plan: &Plan) -> String { let _ = writeln!(s, " set IMAGE={image}"); changes += 1; } - if plan.compose_project_name_commented > 0 { + if plan.compose_project_name_changed { let _ = writeln!( s, - " commented {} COMPOSE_PROJECT_NAME=… line(s)", - plan.compose_project_name_commented + " set COMPOSE_PROJECT_NAME={}", + plan.compose_project_name ); changes += 1; } else { - let _ = writeln!(s, " no uncommented COMPOSE_PROJECT_NAME=… lines"); + let _ = writeln!( + s, + " already set COMPOSE_PROJECT_NAME={}", + plan.compose_project_name + ); } if changes == 0 { let _ = writeln!(s, " no changes (already up to date)"); @@ -313,7 +321,7 @@ fn chmod_600(_path: &Path) -> Result<(), Error> { #[cfg(test)] mod tests { - use super::super::envfile::{has_key, MERGE_FROM_EXAMPLE_HEADER}; + use super::super::envfile::MERGE_FROM_EXAMPLE_HEADER; use super::*; use crate::cli::DeployEnv; use std::time::{SystemTime, UNIX_EPOCH}; @@ -390,15 +398,20 @@ COMPOSE_PROJECT_NAME=sw-shop-acme assert_eq!(p.shop_id, "acme"); assert_eq!(p.deploy_env, "live"); 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_changed); + assert_eq!(p.compose_project_name, "shopware-acme"); assert_eq!(last_value(p.contents(), "APP_SECRET"), EXISTING_SECRET); - assert!(!has_key(p.contents(), "COMPOSE_PROJECT_NAME")); + assert_eq!( + last_value(p.contents(), "COMPOSE_PROJECT_NAME"), + "shopware-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 IMAGE=ghcr.io/example/acme")); - assert!(text.contains("commented 1 COMPOSE_PROJECT_NAME")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(!text.contains("shopware-acme-live")); assert!(!text.contains("--vps")); assert!(text.contains("APP_SECRET")); assert!(!text.contains("generate-app-secret")); @@ -413,7 +426,7 @@ COMPOSE_PROJECT_NAME=sw-shop-acme } #[test] - fn write_path_sets_keys_merges_example_and_comments_compose_project_name() { + fn write_path_sets_keys_merges_example_and_sets_compose_project_name() { let shop = TempShop::new("write"); shop.write_env(&format!( "\ @@ -442,21 +455,24 @@ NEW_FROM_EXAMPLE=1 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!(p - .contents() - .contains("# COMPOSE_PROJECT_NAME=sw-shop-acme # commented by deploy/init-env.sh")); + assert_eq!( + last_value(p.contents(), "COMPOSE_PROJECT_NAME"), + "shopware-acme" + ); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=sw-shop-acme")); + assert!(!p.contents().contains("shopware-acme-staging")); 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 COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(!text.contains("shopware-acme-staging")); } #[test] - fn reports_none_when_compose_project_name_already_commented() { + fn commented_only_compose_project_name_appends_uncommented() { let shop = TempShop::new("already-commented"); shop.write_env( "\ @@ -468,17 +484,22 @@ SHOPWARE_DEPLOY_ENV=live 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.compose_project_name_changed); + assert_eq!(p.compose_project_name, "shopware-acme"); assert!(p.contents().contains("# COMPOSE_PROJECT_NAME=sw-shop-acme")); + assert_eq!( + last_value(p.contents(), "COMPOSE_PROJECT_NAME"), + "shopware-acme" + ); let text = summary_text(&p); - assert!(text.contains("no uncommented COMPOSE_PROJECT_NAME")); - assert!(!text.contains("commented 0")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(!text.contains("already set COMPOSE_PROJECT_NAME")); assert!(!text.contains("--vps")); - assert!(text.contains("no changes (already up to date)")); + assert!(!text.contains("no changes (already up to date)")); } #[test] - fn copy_from_example_comments_compose_project_name() { + fn copy_from_example_sets_compose_project_name() { let shop = TempShop::new("copy-cpn"); shop.write_example( "\ @@ -489,18 +510,45 @@ 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_changed); + assert_eq!( + last_value(p.contents(), "COMPOSE_PROJECT_NAME"), + "shopware-acme" + ); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=sw-shop-acme")); let text = summary_text(&p); assert!(text.contains("copy .env.example → .env")); - assert!(text.contains("commented 1 COMPOSE_PROJECT_NAME")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=shopware-acme")); assert!(!text.contains("--vps")); assert!(!text.contains("example-secret")); } + #[test] + fn already_set_compose_project_name_is_idempotent() { + let shop = TempShop::new("already-cpn"); + shop.write_env( + "\ +SHOPWARE_SHOP_ID=acme +SHOPWARE_DEPLOY_ENV=live +COMPOSE_PROJECT_NAME=shopware-acme +", + ); + let mut a = args(); + a.shop_id = None; + let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); + assert!(!p.compose_project_name_changed); + assert_eq!(p.compose_project_name, "shopware-acme"); + assert_eq!( + last_value(p.contents(), "COMPOSE_PROJECT_NAME"), + "shopware-acme" + ); + let text = summary_text(&p); + assert!(text.contains("already set COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(!text.contains(" set COMPOSE_PROJECT_NAME=")); + assert!(!text.contains("--vps")); + assert!(text.contains("no changes (already up to date)")); + } + #[test] fn leaves_existing_app_secret_unchanged() { let shop = TempShop::new("keep-secret"); @@ -604,8 +652,14 @@ MYSQL_PASSWORD=example-secret assert!(p.copied); assert!(p.merged_keys.is_empty()); assert_eq!(last_value(p.contents(), "MYSQL_PASSWORD"), "example-secret"); + assert_eq!( + last_value(p.contents(), "COMPOSE_PROJECT_NAME"), + "shopware-acme" + ); + assert!(p.compose_project_name_changed); let text = summary_text(&p); assert!(text.contains("copy .env.example → .env")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=shopware-acme")); assert!(!text.contains("example-secret")); assert!(!shop.path().join(".env").is_file()); } @@ -613,14 +667,21 @@ MYSQL_PASSWORD=example-secret #[test] fn keep_existing_nonempty_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 +SHOPWARE_DEPLOY_ENV=playground +COMPOSE_PROJECT_NAME=shopware-acme +", + ); 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); let text = summary_text(&p); - assert!(text.contains("no uncommented COMPOSE_PROJECT_NAME")); + assert!(text.contains("already set COMPOSE_PROJECT_NAME=shopware-acme")); assert!(!text.contains("--vps")); assert!(text.contains("no changes (already up to date)")); } diff --git a/tests/init_env.rs b/tests/init_env.rs index 48e4283..04a256f 100644 --- a/tests/init_env.rs +++ b/tests/init_env.rs @@ -111,6 +111,7 @@ fn init_env_help_lists_flags() { "--dry-run", "COMPOSE_DIR", "COMPOSE_PROJECT_NAME", + "COMPOSE_PROJECT_NAME=shopware-", ] { assert!(help.contains(needle), "missing {needle} in:\n{help}"); } @@ -118,6 +119,14 @@ fn init_env_help_lists_flags() { !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("always comments"), + "env init --help must not describe commenting COMPOSE_PROJECT_NAME:\n{help}" + ); assert!( !help.contains("generate-app-secret"), "env init --help must not list --generate-app-secret:\n{help}" @@ -167,7 +176,11 @@ COMPOSE_PROJECT_NAME=sw-shop-acme assert!(log.contains("set SHOPWARE_SHOP_ID=acme"), "{log}"); assert!(log.contains("set SHOPWARE_DEPLOY_ENV=live"), "{log}"); assert!(log.contains("set IMAGE=ghcr.io/example/acme"), "{log}"); - assert!(log.contains("commented 1 COMPOSE_PROJECT_NAME"), "{log}"); + assert!( + log.contains("set COMPOSE_PROJECT_NAME=shopware-acme"), + "{log}" + ); + assert!(!log.contains("shopware-acme-live"), "{log}"); assert!(!log.contains("--vps"), "{log}"); assert!(!log.contains("generate-app-secret"), "{log}"); assert!(!log.contains("set APP_SECRET"), "{log}"); @@ -182,7 +195,7 @@ COMPOSE_PROJECT_NAME=sw-shop-acme } #[test] -fn write_merges_example_comments_compose_project_name_and_chmod() { +fn write_merges_example_sets_compose_project_name_and_chmod() { let shop = TempShop::new("write"); fs::write( shop.path().join(".env"), @@ -223,7 +236,11 @@ NEW_FROM_EXAMPLE=1 ); 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 COMPOSE_PROJECT_NAME=shopware-acme"), + "{log}" + ); + assert!(!log.contains("shopware-acme-staging"), "{log}"); assert!(!log.contains("--vps"), "{log}"); assert_no_secrets(&out, &["from-example"]); @@ -233,11 +250,10 @@ NEW_FROM_EXAMPLE=1 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("COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(!env.contains("COMPOSE_PROJECT_NAME=sw-shop-acme")); + assert!(!env.contains("shopware-acme-staging")); assert!(!env.contains("--vps")); - assert!(!env - .lines() - .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); let mode = fs::metadata(shop.path().join(".env")) .unwrap() .permissions() @@ -322,8 +338,8 @@ fn vps_flag_is_rejected() { } #[test] -fn already_commented_compose_project_name_reports_none() { - let shop = TempShop::new("already-cpn"); +fn commented_only_compose_project_name_appends_uncommented() { + let shop = TempShop::new("commented-cpn"); fs::write( shop.path().join(".env"), "\ @@ -336,14 +352,49 @@ SHOPWARE_DEPLOY_ENV=live 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("set COMPOSE_PROJECT_NAME=shopware-acme"), + "{log}" + ); + assert!(!log.contains("already set COMPOSE_PROJECT_NAME"), "{log}"); assert!(!log.contains("--vps"), "{log}"); let env = fs::read_to_string(shop.path().join(".env")).unwrap(); assert!(env.contains("# COMPOSE_PROJECT_NAME=sw-shop-acme")); - assert!(!env + assert!(env .lines() - .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); + .any(|l| l.trim_start() == "COMPOSE_PROJECT_NAME=shopware-acme")); +} + +#[test] +fn already_set_compose_project_name_is_idempotent() { + let shop = TempShop::new("already-cpn"); + fs::write( + shop.path().join(".env"), + "\ +SHOPWARE_SHOP_ID=acme +SHOPWARE_DEPLOY_ENV=live +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("already set COMPOSE_PROJECT_NAME=shopware-acme"), + "{log}" + ); + assert!(!log.contains(" set COMPOSE_PROJECT_NAME="), "{log}"); + assert!(log.contains("no changes (already up to date)"), "{log}"); + assert!(!log.contains("--vps"), "{log}"); + let env = fs::read_to_string(shop.path().join(".env")).unwrap(); + assert!(env.contains("COMPOSE_PROJECT_NAME=shopware-acme")); + assert_eq!( + env.lines() + .filter(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME=")) + .count(), + 1 + ); } #[test] From 956c9af5e0d637e64423511b115b480f59c123df Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 07:09:25 +0000 Subject: [PATCH 2/9] feat: pin VPS compose -p - over .env COMPOSE_PROJECT_NAME env init still writes COMPOSE_PROJECT_NAME=shopware- for local shopware-cli project dev. VPS compose argv now passes -p - so that local name cannot collide live/staging on one Docker host. Co-authored-by: ROBJkE --- README.md | 8 ++--- docs/command-matrix.md | 25 +++++++++------ src/cli.rs | 9 +++--- src/shopware/app.rs | 19 ++++++----- src/shopware/compose.rs | 34 +++++++++++++------- src/shopware/env.rs | 53 ++++++++++++++++++++++++------ src/shopware/import.rs | 31 +++++++++++++----- src/shopware/init_env.rs | 5 +-- src/shopware/mysql.rs | 69 +++++++++++++++++++++++++++++++++------- src/shopware/restore.rs | 53 ++++++++++++++++++++---------- src/shopware/rewrite.rs | 18 ++++++++--- src/shopware/rollout.rs | 61 ++++++++++++++++++++--------------- src/shopware/ssh.rs | 12 ++----- src/shopware/sync.rs | 41 ++++++++++++++++-------- tests/import.rs | 3 ++ tests/release.rs | 4 ++- tests/rollback.rs | 3 ++ 17 files changed, 312 insertions(+), 136 deletions(-) diff --git a/README.md b/README.md index 6272bc5..54094bd 100644 --- a/README.md +++ b/README.md @@ -155,10 +155,10 @@ 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`. Sets -`COMPOSE_PROJECT_NAME=shopware-` so local `shopware-cli project -dev` and Compose share a stable name (create writes -`COMPOSE_PROJECT_NAME=sw-…`; no env suffix). `.env` may still be missing; -missing keys are merged from `.env.example`. +`COMPOSE_PROJECT_NAME=shopware-` for **local** `shopware-cli project +dev` / root `compose.yaml` (create writes `COMPOSE_PROJECT_NAME=sw-…`; no +env suffix). VPS stacks stay `-` (`docker compose -p`). `.env` +may still be missing; missing keys are merged from `.env.example`. ```bash fyrst-cli shopware env init --shop-id acme --dry-run diff --git a/docs/command-matrix.md b/docs/command-matrix.md index 1e4500d..e0ef9bf 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -110,9 +110,12 @@ 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 -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml -p - ``` +`-p` wins over `.env` `COMPOSE_PROJECT_NAME` (that key is for local +`shopware-cli project dev` only). VPS stacks stay `-`. + 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. @@ -179,11 +182,13 @@ shell expansion**), same parser as import (`src/shopware/envfile.rs`). 3. `--env` is `live` | `staging` | `playground` | `dev`. Default `live` when unset/empty; keep an existing non-empty value. 4. `--image` sets `IMAGE` (no whitespace). Unset leaves `IMAGE` as-is. -5. Sets `COMPOSE_PROJECT_NAME=shopware-` so local - `shopware-cli project dev` and Compose share a stable name (create writes +5. Sets `COMPOSE_PROJECT_NAME=shopware-` for **local** + `shopware-cli project dev` / root `compose.yaml` (create writes `COMPOSE_PROJECT_NAME=sw-…`). Pattern is exactly `shopware-` — - no `SHOPWARE_DEPLOY_ENV` suffix. If the file only has a commented - `# COMPOSE_PROJECT_NAME=…` line, an uncommented assignment is appended. + no `SHOPWARE_DEPLOY_ENV` suffix. This does **not** rename VPS stacks. + VPS compose pins `-p -` so live and staging stay distinct + on one host. If the file only has a commented `# COMPOSE_PROJECT_NAME=…` + line, an uncommented assignment is appended. 6. `--dry-run` prints the summary and does not write `.env`. 7. After a real write: `chmod 600 .env`. @@ -257,7 +262,7 @@ 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 + `gzip -dc FILE | docker compose --env-file .env -f … -p - exec -T mysql sh -c ''` (plain `.sql` is stdin, not gzip). 2. Else `DATABASE_URL` to a real host: `gzip -dc FILE | docker run --rm -i --network host mysql `. Host `mysql` @@ -352,8 +357,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` (VPS project +name, not local `COMPOSE_PROJECT_NAME`). Remote `--from `: SSH + rsync (or tar over SSH) from `SHOPWARE_REMOTE_DATA_ROOT` or derived @@ -493,7 +499,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`; not + local `COMPOSE_PROJECT_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 diff --git a/src/cli.rs b/src/cli.rs index b7ba76c..be962b3 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -95,7 +95,7 @@ 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; sets \ -COMPOSE_PROJECT_NAME=shopware-). Does not generate APP_SECRET. `--dry-run` prints the \ +COMPOSE_PROJECT_NAME=shopware- for local project-dev). 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 +183,10 @@ 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). \ -Sets COMPOSE_PROJECT_NAME=shopware- so local shopware-cli project dev and \ -Compose share a stable name (create writes COMPOSE_PROJECT_NAME=sw-…). \ -Does not append SHOPWARE_DEPLOY_ENV.\n\n\ +Sets COMPOSE_PROJECT_NAME=shopware- for local shopware-cli project dev / \ +root compose.yaml (create writes COMPOSE_PROJECT_NAME=sw-…). \ +Does not append SHOPWARE_DEPLOY_ENV. VPS stacks stay - \ +(docker compose -p).\n\n\ Environment:\n \ COMPOSE_DIR Shop checkout (default: walk from cwd for .env / .env.example + deploy/)\n\n\ Examples:\n \ diff --git a/src/shopware/app.rs b/src/shopware/app.rs index d5a5aa4..707f713 100644 --- a/src/shopware/app.rs +++ b/src/shopware/app.rs @@ -1,6 +1,6 @@ //! App container pause/resume and post-restore hints (recipes `lib/sync-app.sh`). -use super::env::ShopEnv; +use super::env::{vps_project_name_opt, ShopEnv}; use super::error::Error; use super::mysql::{compose_argv, require_docker}; use std::path::Path; @@ -11,6 +11,7 @@ const APP_SERVICES: &[&str] = &["web", "worker", "scheduler"]; pub fn stop_app_containers( compose_dir: &Path, files: &[String], + project: Option<&str>, dry_run: bool, ) -> Result, Error> { if dry_run { @@ -21,7 +22,7 @@ pub fn stop_app_containers( return Ok(Vec::new()); } require_docker()?; - let mut args = compose_argv(files); + let mut args = compose_argv(files, project); args.extend([ "--profile".into(), "worker".into(), @@ -51,8 +52,8 @@ pub fn stop_app_containers( continue; } println!("==> Stopping {svc} for restore"); - if !compose_stop(compose_dir, files, svc) { - let mut with_profile = compose_argv(files); + if !compose_stop(compose_dir, files, project, svc) { + let mut with_profile = compose_argv(files, project); with_profile.extend([ "--profile".into(), (*svc).into(), @@ -71,8 +72,8 @@ pub fn stop_app_containers( Ok(stopped) } -fn compose_stop(compose_dir: &Path, files: &[String], svc: &str) -> bool { - let mut args = compose_argv(files); +fn compose_stop(compose_dir: &Path, files: &[String], project: Option<&str>, svc: &str) -> bool { + let mut args = compose_argv(files, project); args.extend(["stop".into(), svc.into()]); Command::new("docker") .args(&args) @@ -87,6 +88,7 @@ fn compose_stop(compose_dir: &Path, files: &[String], svc: &str) -> bool { pub fn start_stopped_app( compose_dir: &Path, files: &[String], + project: Option<&str>, stopped: &[String], dry_run: bool, ) -> Result<(), Error> { @@ -99,7 +101,7 @@ pub fn start_stopped_app( continue; } println!("==> Starting {svc}"); - let mut args = compose_argv(files); + let mut args = compose_argv(files, project); match svc.as_str() { "worker" => { args.extend([ @@ -176,7 +178,8 @@ 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 project = vps_project_name_opt(env); + let mut args = compose_argv(files, project.as_deref()); args.extend([ "run".into(), "--rm".into(), diff --git a/src/shopware/compose.rs b/src/shopware/compose.rs index dbff48a..d1ee827 100644 --- a/src/shopware/compose.rs +++ b/src/shopware/compose.rs @@ -1,7 +1,10 @@ //! 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` +//! `docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml -p -` +//! +//! `-p` pins the VPS project name so `.env` `COMPOSE_PROJECT_NAME` (local +//! `shopware-cli project dev`) cannot collide live/staging on one host. //! //! Never builds images. `compose up` uses `--no-build`. `compose run` uses //! `--pull never` (Compose v5 dropped `--no-build` on `run`). @@ -12,14 +15,11 @@ 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()]; - for f in COMPOSE_FILES { - a.push("-f".into()); - a.push((*f).to_string()); - } - a +/// The three overlay compose files plus `-p `; all files must exist +/// for VPS release/rollback. `project` is `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. +pub fn vps_compose_argv(project: &str) -> Vec { + let files: Vec = COMPOSE_FILES.iter().map(|s| (*s).to_string()).collect(); + super::mysql::compose_argv(&files, Some(project)) } pub fn docker_log(compose_args: &[String]) -> String { @@ -87,8 +87,9 @@ pub fn compose_service_names( compose_dir: &Path, profile_args: &[String], extra_env: &[(String, String)], + project: &str, ) -> Vec { - let mut args = vps_compose_argv(); + let mut args = vps_compose_argv(project); args.extend(profile_args.iter().cloned()); args.extend(["config".into(), "--services".into()]); let mut cmd = Command::new("docker"); @@ -115,7 +116,7 @@ mod tests { #[test] fn vps_argv_is_the_three_overlay_files() { - let a = vps_compose_argv(); + let a = vps_compose_argv("acme-staging"); assert_eq!( a, vec![ @@ -128,13 +129,22 @@ mod tests { "deploy/compose.prod.yaml", "-f", "deploy/compose.vps.yaml", + "-p", + "acme-staging", ] ); let log = docker_log(&a); assert_eq!( log, - "docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml" + "docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml -p acme-staging" ); assert!(!args_contain_build(&a)); } + + #[test] + fn vps_argv_pins_derived_name_not_local_compose_project_name() { + let a = vps_compose_argv("acme-live"); + assert!(a.windows(2).any(|w| w == ["-p", "acme-live"]), "{a:?}"); + assert!(!a.iter().any(|s| s.contains("shopware-"))); + } } diff --git a/src/shopware/env.rs b/src/shopware/env.rs index db0a612..2af6c36 100644 --- a/src/shopware/env.rs +++ b/src/shopware/env.rs @@ -310,17 +310,39 @@ pub fn allow_live_restore(env: &ShopEnv) -> bool { env_truthy(env.get("SHOPWARE_ALLOW_LIVE_RESTORE")) } +/// VPS Compose project `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. +/// +/// `COMPOSE_PROJECT_NAME` is for local `shopware-cli project dev` / root +/// `compose.yaml` only and must not name VPS stacks. +pub fn vps_project_name(shop_id: &str, deploy_env: &str) -> String { + format!("{shop_id}-{deploy_env}") +} + +/// Derived VPS 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 VPS named-volume +/// fallback matches `docker compose -p`. `COMPOSE_PROJECT_NAME` is used only +/// when shop id / deploy env are missing (local project-dev). 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 and SHOPWARE_DEPLOY_ENV to derive ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV} for VPS Compose. COMPOSE_PROJECT_NAME is for local shopware-cli project dev only.", + )) } /// Work directory for sync capture/apply (`--snapshot-dir`, else `var/runtime-sync`). @@ -716,16 +738,29 @@ COMPOSE_PROFILES=redis } #[test] - fn compose_project_name_wins() { + fn compose_project_name_does_not_override_vps_name() { let mut vars = HashMap::new(); - vars.insert("COMPOSE_PROJECT_NAME".into(), "sw-shop-acme".into()); + vars.insert("COMPOSE_PROJECT_NAME".into(), "shopware-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(), - ("sw-shop-acme".into(), false) + ("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(), "shopware-acme".into()); + let env = ShopEnv::from_vars(PathBuf::from("/tmp/x"), vars); + assert_eq!( + derive_project_name(&env).unwrap(), + ("shopware-acme".into(), false) ); + assert_eq!(vps_project_name_opt(&env), None); } #[test] diff --git a/src/shopware/import.rs b/src/shopware/import.rs index 1b05615..278e05f 100644 --- a/src/shopware/import.rs +++ b/src/shopware/import.rs @@ -6,7 +6,7 @@ use super::env::{ compose_mentions_mysql_service, existing_compose_files, require_shop_id, resolve_compose_dir, - ShopEnv, + vps_project_name, ShopEnv, }; use super::error::Error; use super::live::{assert_not_live, LivePolicy, LiveSignals}; @@ -133,7 +133,7 @@ impl ImportPlan { ImportTarget::Bundled { compose_files, .. } => { format!( "{decode} | {} exec -T mysql sh -c ''", - compose_cli_log(compose_files) + compose_cli_log(compose_files, self.compose_project().as_deref()) ) } ImportTarget::External { @@ -147,6 +147,12 @@ impl ImportPlan { pub fn log_contains_secret(&self, text: &str) -> bool { log_contains_secret(text, &self.secrets) } + + fn compose_project(&self) -> Option { + self.deploy_env + .as_ref() + .map(|e| vps_project_name(&self.shop_id, e)) + } } pub fn run(args: DbImportArgs) -> Result<(), Error> { @@ -357,8 +363,9 @@ pub fn execute(plan: &ImportPlan) -> Result<(), Error> { compose_dir, compose_files, } => { - compose_up_mysql(compose_dir, compose_files)?; - run_bundled(plan, compose_dir, compose_files)?; + let project = plan.compose_project(); + compose_up_mysql(compose_dir, compose_files, project.as_deref())?; + run_bundled(plan, compose_dir, compose_files, project.as_deref())?; } ImportTarget::External { .. } => run_external(plan)?, } @@ -366,8 +373,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(files: &[String], project: Option<&str>) -> Vec { + let mut a = super::mysql::compose_argv(files, project); a.extend([ "exec".into(), "-T".into(), @@ -421,8 +428,13 @@ fn external_run_args(target: &ImportTarget) -> Result, Error> { Ok(a) } -fn run_bundled(plan: &ImportPlan, compose_dir: &Path, files: &[String]) -> Result<(), Error> { - let args = bundled_exec_args(files); +fn run_bundled( + plan: &ImportPlan, + compose_dir: &Path, + files: &[String], + project: Option<&str>, +) -> Result<(), Error> { + let args = bundled_exec_args(files, project); pipe_sql_into_docker(plan, &args, Some(compose_dir), None) } @@ -570,6 +582,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 @@ -593,6 +606,8 @@ MYSQL_DATABASE=shopware assert!(log.contains("gzip -dc"), "{log}"); assert!(log.contains("exec -T mysql"), "{log}"); assert!(log.contains("-f deploy/compose.yaml"), "{log}"); + assert!(log.contains("-p acme-staging"), "{log}"); + assert!(!log.contains("shopware-acme"), "{log}"); assert!(matches!(plan.target, ImportTarget::Bundled { .. })); } diff --git a/src/shopware/init_env.rs b/src/shopware/init_env.rs index a61c700..5ee30bb 100644 --- a/src/shopware/init_env.rs +++ b/src/shopware/init_env.rs @@ -2,8 +2,9 @@ //! //! Sets fyrst identity (shop id, deploy env, optional IMAGE) and merges //! missing keys from `.env.example`. Sets `COMPOSE_PROJECT_NAME=shopware-` -//! so local `shopware-cli project dev` and Compose share a stable name (create -//! writes `COMPOSE_PROJECT_NAME=sw-…`; no `SHOPWARE_DEPLOY_ENV` suffix). Does +//! for local `shopware-cli project dev` / root `compose.yaml` (create writes +//! `COMPOSE_PROJECT_NAME=sw-…`; no `SHOPWARE_DEPLOY_ENV` suffix). Does not +//! rename VPS stacks (`-` via `docker compose -p`). 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. diff --git a/src/shopware/mysql.rs b/src/shopware/mysql.rs index b89522e..8142831 100644 --- a/src/shopware/mysql.rs +++ b/src/shopware/mysql.rs @@ -156,24 +156,36 @@ pub fn client_image_for_url(scheme: &str, _env: &ShopEnv) -> String { } } -pub fn compose_argv(files: &[String]) -> Vec { +/// `docker compose --env-file .env -f …` plus `-p ` when set. +/// +/// `-p` is Compose's highest-precedence project name and wins over +/// `COMPOSE_PROJECT_NAME` in `.env` (that key is for local project-dev). +pub fn compose_argv(files: &[String], project: Option<&str>) -> Vec { let mut a = vec!["compose".into(), "--env-file".into(), ".env".into()]; for f in files { a.push("-f".into()); a.push(f.clone()); } + pin_compose_project(&mut a, project); 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(files: &[String], project: Option<&str>) -> String { + let mut s = String::from("docker"); + for a in compose_argv(files, project) { + s.push(' '); + s.push_str(&a); } s } +fn pin_compose_project(args: &mut Vec, project: Option<&str>) { + if let Some(p) = project.map(str::trim).filter(|s| !s.is_empty()) { + args.push("-p".into()); + args.push(p.to_string()); + } +} + pub fn require_docker() -> Result<(), Error> { match Command::new("docker") .arg("info") @@ -205,13 +217,17 @@ pub fn require_gzip() -> Result<(), Error> { } } -pub fn compose_up_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Error> { +pub fn compose_up_mysql( + compose_dir: &Path, + files: &[String], + project: Option<&str>, +) -> Result<(), Error> { if files.is_empty() { return Err(Error::fail( "No compose files found under shop root; cannot start service mysql.", )); } - let mut args = compose_argv(files); + let mut args = compose_argv(files, project); args.extend([ "up".into(), "-d".into(), @@ -228,11 +244,11 @@ pub fn compose_up_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Erro "docker compose up mysql failed. Is Docker running, and is the mysql service defined?", )); } - wait_mysql(compose_dir, files) + wait_mysql(compose_dir, files, project) } -fn wait_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Error> { - let mut args = compose_argv(files); +fn wait_mysql(compose_dir: &Path, files: &[String], project: Option<&str>) -> Result<(), Error> { + let mut args = compose_argv(files, project); args.extend([ "exec".into(), "-T".into(), @@ -361,6 +377,37 @@ mod tests { ); } + #[test] + fn compose_argv_pins_vps_project_after_files() { + let files = vec![ + "deploy/compose.yaml".into(), + "deploy/compose.prod.yaml".into(), + ]; + let a = compose_argv(&files, Some("acme-staging")); + assert_eq!( + a, + vec![ + "compose", + "--env-file", + ".env", + "-f", + "deploy/compose.yaml", + "-f", + "deploy/compose.prod.yaml", + "-p", + "acme-staging", + ] + ); + let log = compose_cli_log(&files, Some("acme-live")); + assert!(log.contains("-p acme-live"), "{log}"); + assert!( + log.starts_with("docker compose --env-file .env -f deploy/compose.yaml"), + "{log}" + ); + let plain = compose_argv(&files, None); + assert!(!plain.iter().any(|s| s == "-p")); + } + #[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..ad8b448 100644 --- a/src/shopware/restore.rs +++ b/src/shopware/restore.rs @@ -7,7 +7,7 @@ use super::data::{normalize_data, DataSelection}; use super::env::{ existing_compose_files, require_shop_id, resolve_compose_dir, resolve_data_root, - resolve_snapshot_dir, ShopEnv, + resolve_snapshot_dir, vps_project_name_opt, ShopEnv, }; use super::error::Error; use super::import::{self, ImportPlan}; @@ -41,6 +41,7 @@ pub enum RewriteAction { pub struct RestorePlan { pub compose_dir: PathBuf, pub compose_files: Vec, + pub compose_project: Option, pub shop_id: String, pub deploy_env: Option, pub snapshot_dir: PathBuf, @@ -182,6 +183,7 @@ pub fn plan_with_env( Ok(RestorePlan { compose_dir, compose_files, + compose_project: vps_project_name_opt(env), shop_id, deploy_env: env.get("SHOPWARE_DEPLOY_ENV").map(str::to_string), snapshot_dir, @@ -219,7 +221,12 @@ pub fn execute(plan: &RestorePlan) -> Result<(), Error> { if plan.dry_run { 1 } else { 0 }, ); - let stopped = stop_app_containers(&plan.compose_dir, &plan.compose_files, plan.dry_run)?; + let stopped = stop_app_containers( + &plan.compose_dir, + &plan.compose_files, + plan.compose_project.as_deref(), + plan.dry_run, + )?; if let Some(imp) = &plan.import { import::execute(imp)?; @@ -266,6 +273,7 @@ pub fn execute(plan: &RestorePlan) -> Result<(), Error> { start_stopped_app( &plan.compose_dir, &plan.compose_files, + plan.compose_project.as_deref(), &stopped, plan.dry_run, )?; @@ -300,6 +308,7 @@ fn run_rewrite(compose_dir: &Path, docker_args: &[String]) -> Result<(), Error> fn stop_app_containers( compose_dir: &Path, files: &[String], + project: Option<&str>, dry_run: bool, ) -> Result, Error> { if dry_run { @@ -309,20 +318,24 @@ fn stop_app_containers( if files.is_empty() { return Ok(Vec::new()); } - let running = list_running_app_services(compose_dir, files); + let running = list_running_app_services(compose_dir, files, project); let mut stopped = Vec::new(); for svc in ["web", "worker", "scheduler"] { if running.iter().any(|s| s == svc) { println!("==> Stopping {svc} for restore"); - compose_stop(compose_dir, files, svc); + compose_stop(compose_dir, files, project, svc); stopped.push(svc.to_string()); } } Ok(stopped) } -fn list_running_app_services(compose_dir: &Path, files: &[String]) -> Vec { - let mut args = compose_argv(files); +fn list_running_app_services( + compose_dir: &Path, + files: &[String], + project: Option<&str>, +) -> Vec { + let mut args = compose_argv(files, project); args.extend([ "--profile".into(), "worker".into(), @@ -349,8 +362,8 @@ fn list_running_app_services(compose_dir: &Path, files: &[String]) -> Vec, svc: &str) { + let mut args = compose_argv(files, project); args.extend(["stop".into(), svc.to_string()]); let ok = Command::new("docker") .args(&args) @@ -363,7 +376,7 @@ fn compose_stop(compose_dir: &Path, files: &[String], svc: &str) { if ok { return; } - let mut args = compose_argv(files); + let mut args = compose_argv(files, project); args.extend([ "--profile".into(), svc.to_string(), @@ -381,6 +394,7 @@ fn compose_stop(compose_dir: &Path, files: &[String], svc: &str) { fn start_stopped_app( compose_dir: &Path, files: &[String], + project: Option<&str>, stopped: &[String], dry_run: bool, ) -> Result<(), Error> { @@ -391,12 +405,12 @@ fn start_stopped_app( } println!("==> Starting {svc}"); match svc.as_str() { - "web" => compose_up(compose_dir, files, None, "web")?, + "web" => compose_up(compose_dir, files, project, None, "web")?, "worker" => { - let _ = compose_up(compose_dir, files, Some("worker"), "worker"); + let _ = compose_up(compose_dir, files, project, Some("worker"), "worker"); } "scheduler" => { - let _ = compose_up(compose_dir, files, Some("scheduler"), "scheduler"); + let _ = compose_up(compose_dir, files, project, Some("scheduler"), "scheduler"); } _ => {} } @@ -407,10 +421,11 @@ fn start_stopped_app( fn compose_up( compose_dir: &Path, files: &[String], + project: Option<&str>, profile: Option<&str>, svc: &str, ) -> Result<(), Error> { - let mut args = compose_argv(files); + let mut args = compose_argv(files, project); if let Some(p) = profile { args.extend(["--profile".into(), p.to_string()]); } @@ -459,14 +474,20 @@ fn post_restore_hints(plan: &RestorePlan) { } if plan.image.is_some() { println!("==> Trying cache:clear (non-fatal if the image/console is unavailable)"); - if cache_clear(&plan.compose_dir, &plan.compose_files).is_err() { + if cache_clear( + &plan.compose_dir, + &plan.compose_files, + plan.compose_project.as_deref(), + ) + .is_err() + { println!("==> cache:clear skipped or failed — not fatal"); } } } -fn cache_clear(compose_dir: &Path, files: &[String]) -> Result<(), Error> { - let mut args = compose_argv(files); +fn cache_clear(compose_dir: &Path, files: &[String], project: Option<&str>) -> Result<(), Error> { + let mut args = compose_argv(files, project); args.extend([ "run".into(), "--rm".into(), diff --git a/src/shopware/rewrite.rs b/src/shopware/rewrite.rs index e030a00..b5b038c 100644 --- a/src/shopware/rewrite.rs +++ b/src/shopware/rewrite.rs @@ -3,7 +3,7 @@ //! Target URL is `APP_URL`. On live, rewrite is skipped (APP_URL is a shop //! runtime var, not a restore opt-in — refusing it would block live DR). -use super::env::{existing_compose_files, ShopEnv}; +use super::env::{existing_compose_files, vps_project_name_opt, ShopEnv}; use super::error::Error; use super::live::LiveSignals; use super::mysql::{compose_argv, compose_cli_log, require_docker}; @@ -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(&files, vps_project_name_opt(env).as_deref()); 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(&files, vps_project_name_opt(env).as_deref()), 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(files, vps_project_name_opt(env).as_deref()); a.extend([ "run".into(), "--rm".into(), @@ -219,13 +219,20 @@ 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("-p acme-staging"), "{line}"); + assert!(!line.contains("-p shopware-acme"), "{line}"); assert!(line.contains("--dry-run"), "{line}"); assert!( !line.to_ascii_lowercase().contains("update sales_channel"), @@ -233,6 +240,7 @@ 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.windows(2).any(|w| w == ["-p", "acme-staging"])); assert!(!args.iter().any(|a| a == "--dry-run")); } diff --git a/src/shopware/rollout.rs b/src/shopware/rollout.rs index 65e1e55..806dbe7 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; @@ -146,6 +146,7 @@ pub struct RolloutPlan { pub setup: Vec, pub web: Vec, pub extra: Option>, + pub project: String, } impl RolloutPlan { @@ -154,16 +155,17 @@ impl RolloutPlan { pull_policy: String, profiles: Vec, profiles_raw: String, + project: String, ) -> Self { let pull = if skip_pull { None } else { - let mut a = vps_compose_argv(); + let mut a = vps_compose_argv(&project); extend_profiles(&mut a, &profiles); a.push("pull".into()); Some(a) }; - let mut setup = vps_compose_argv(); + let mut setup = vps_compose_argv(&project); setup.extend([ "--profile".into(), "setup".into(), @@ -173,14 +175,14 @@ impl RolloutPlan { "never".into(), "setup".into(), ]); - let mut web = vps_compose_argv(); + let mut web = vps_compose_argv(&project); 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(&project); extend_profiles(&mut a, &profiles); a.extend(["up".into(), "-d".into(), "--no-build".into()]); a.extend(up_pull_args(skip_pull)); @@ -195,6 +197,7 @@ impl RolloutPlan { setup, web, extra, + project, } } @@ -274,6 +277,7 @@ impl VpsContext { self.pull_policy.clone(), self.profiles.clone(), self.profiles_raw.clone(), + self.compose_project_name.clone(), ) } @@ -303,7 +307,7 @@ pub fn bootstrap(env: &ShopEnv, skip_pull_flag: bool, dry_run: bool) -> Result Result Result<(), Error let mut profile_args = Vec::new(); extend_profiles(&mut profile_args, &plan.profiles); - let services = compose_service_names(&ctx.compose_dir, &profile_args, &env); + let services = compose_service_names( + &ctx.compose_dir, + &profile_args, + &env, + &ctx.compose_project_name, + ); if services.iter().any(|s| s == "mysql") { println!("==> Starting mysql"); - let mut a = vps_compose_argv(); + let mut a = vps_compose_argv(&ctx.compose_project_name); a.extend(["up".into(), "-d".into(), "--no-build".into()]); a.extend(up_pull_args(plan.skip_pull)); a.push("mysql".into()); @@ -425,7 +424,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_project_name); a.extend([ "--profile".into(), "redis".into(), @@ -536,6 +535,7 @@ mod tests { }, parsed, profiles.to_string(), + "acme-staging".into(), ) } @@ -548,6 +548,7 @@ mod tests { 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.windows(2).any(|w| w == ["-p", "acme-staging"])); assert!(!p.setup.iter().any(|a| a == "--no-build")); assert!(p.setup.windows(2).any(|w| w == ["--pull", "never"])); assert!(p.never_builds()); @@ -626,6 +627,8 @@ mod tests { web.contains("up -d --no-build --remove-orphans web"), "{web}" ); + assert!(web.contains("-p acme-staging"), "{web}"); + assert!(!web.contains("shopware-acme"), "{web}"); } struct TempShop(PathBuf); @@ -670,6 +673,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 ", @@ -684,8 +688,15 @@ DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop assert!(ctx.skip_pull); assert_eq!(ctx.pull_policy, "never"); assert_eq!(ctx.compose_project_name, "acme-staging"); + assert!(ctx.notes.iter().any(|n| n.contains("-p acme-staging"))); + assert!(ctx + .notes + .iter() + .any(|n| n.contains("COMPOSE_PROJECT_NAME=shopware-acme"))); + assert!(!ctx.warnings.iter().any(|w| w.contains("remove or comment"))); let plan = ctx.plan(); assert!(plan.pull.is_none()); + assert!(plan.web.windows(2).any(|w| w == ["-p", "acme-staging"])); let web = docker_log_checked(&ctx, &plan.web).unwrap(); assert!(!ctx.log_contains_secret(&web)); assert!(!web.contains("s3cret-value")); diff --git a/src/shopware/ssh.rs b/src/shopware/ssh.rs index 37cb65a..cc99d16 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 VPS stacks are `{shop_id}-live`. COMPOSE_PROJECT_NAME is local + // `shopware-cli project dev` only and must not name the live project. Ok(format!("{shop_id}-live")) } diff --git a/src/shopware/sync.rs b/src/shopware/sync.rs index ed4b846..97a9de8 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!( @@ -146,13 +139,24 @@ fn run_local( return Err(Error::fail(dump_operator_instructions(snapshot_dir))); } - let stopped = app::stop_app_containers(compose_dir, compose_files, dry_run)?; + let stopped = app::stop_app_containers( + compose_dir, + compose_files, + vps_project_name_opt(env).as_deref(), + dry_run, + )?; let imported = import_db_if_present(env, cwd, selection, snapshot_dir, dry_run)?; rewrite::maybe_rewrite(env, signals, compose_dir, compose_files, imported, dry_run)?; for logical in &selection.volumes { volumes::sync_bind_local_roundtrip(env, data_root, snapshot_dir, logical, dry_run)?; } - app::start_stopped_app(compose_dir, compose_files, &stopped, dry_run)?; + app::start_stopped_app( + compose_dir, + compose_files, + vps_project_name_opt(env).as_deref(), + &stopped, + dry_run, + )?; app::post_restore_hints( env, rewrite::requested(env), @@ -198,7 +202,12 @@ fn run_remote( return Err(Error::fail(dump_operator_instructions(snapshot_dir))); } - let stopped = app::stop_app_containers(compose_dir, compose_files, dry_run)?; + let stopped = app::stop_app_containers( + compose_dir, + compose_files, + vps_project_name_opt(env).as_deref(), + dry_run, + )?; let imported = import_db_if_present(env, cwd, selection, snapshot_dir, dry_run)?; rewrite::maybe_rewrite(env, signals, compose_dir, compose_files, imported, dry_run)?; for logical in &selection.volumes { @@ -212,7 +221,13 @@ fn run_remote( dry_run, )?; } - app::start_stopped_app(compose_dir, compose_files, &stopped, dry_run)?; + app::start_stopped_app( + compose_dir, + compose_files, + vps_project_name_opt(env).as_deref(), + &stopped, + dry_run, + )?; app::post_restore_hints( env, rewrite::requested(env), diff --git a/tests/import.rs b/tests/import.rs index b3a34bc..fb8a33a 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,8 @@ 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.contains("-p acme-staging"), "{log}"); + assert!(!log.contains("-p shopware-acme"), "{log}"); } #[test] diff --git a/tests/release.rs b/tests/release.rs index 9ce29d7..41d4e17 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,8 @@ 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.contains("-p acme-staging"), "{log}"); + assert!(!log.contains("-p shopware-acme"), "{log}"); assert!( log.contains("--profile setup run --rm --pull never setup"), "{log}" diff --git a/tests/rollback.rs b/tests/rollback.rs index 7b413bb..dc02524 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 ", @@ -251,6 +252,8 @@ fn dry_run_prints_same_compose_order_as_release() { ), "{log}" ); + assert!(log.contains("-p acme-staging"), "{log}"); + assert!(!log.contains("-p shopware-"), "{log}"); let setup_idx = log .find("--profile setup run --rm --pull never setup") .unwrap_or_else(|| panic!("setup missing:\n{log}")); From cc54335d96d8f3279ebdb843924278bc8609e787 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 08:39:55 +0000 Subject: [PATCH 3/9] feat: env init comments COMPOSE_PROJECT_NAME; deploy env in .env.local Shared .env is git-committed and must not hold env-specific values. env init comments out uncommented COMPOSE_PROJECT_NAME and leftover SHOPWARE_DEPLOY_ENV in .env, and writes SHOPWARE_DEPLOY_ENV to gitignored .env.local. Loader skips empty SHOPWARE_DEPLOY_ENV so host files win. VPS compose still pins -p - from identity. Co-authored-by: ROBJkE --- README.md | 20 ++- docs/command-matrix.md | 51 ++++--- src/cli.rs | 18 ++- src/main.rs | 3 +- src/shopware/compose.rs | 7 +- src/shopware/env.rs | 90 ++++++++++-- src/shopware/envfile.rs | 120 ++++++++++++--- src/shopware/init_env.rs | 307 +++++++++++++++++++++++++++------------ src/shopware/mysql.rs | 4 +- src/shopware/rollout.rs | 10 +- src/shopware/ssh.rs | 4 +- tests/init_env.rs | 108 +++++++++----- 12 files changed, 528 insertions(+), 214 deletions(-) diff --git a/README.md b/README.md index 54094bd..c498453 100644 --- a/README.md +++ b/README.md @@ -151,14 +151,18 @@ 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`. Sets -`COMPOSE_PROJECT_NAME=shopware-` for **local** `shopware-cli project -dev` / root `compose.yaml` (create writes `COMPOSE_PROJECT_NAME=sw-…`; no -env suffix). VPS stacks stay `-` (`docker compose -p`). `.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` 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**. Compose +project name is `-` from identity, pinned with +`docker compose -p` on VPS. `.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 diff --git a/docs/command-matrix.md b/docs/command-matrix.md index e0ef9bf..986566e 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -113,8 +113,9 @@ Compose is always: docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml -p - ``` -`-p` wins over `.env` `COMPOSE_PROJECT_NAME` (that key is for local -`shopware-cli project dev` only). VPS stacks stay `-`. +`-p` pins `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` from loaded identity +(`.env` shop id + `.env.local` / `.env.prod` deploy env). Leftover +`COMPOSE_PROJECT_NAME` in committed `.env` is ignored. Never `--build`. `compose run` uses `--pull never` (not `--no-build`). `compose up` uses `--no-build` (and `--pull never` when skipping registry pull). Theme/asset @@ -165,32 +166,34 @@ 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, +and host `.env.local` for `SHOPWARE_DEPLOY_ENV`. 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). 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. Sets `COMPOSE_PROJECT_NAME=shopware-` for **local** - `shopware-cli project dev` / root `compose.yaml` (create writes - `COMPOSE_PROJECT_NAME=sw-…`). Pattern is exactly `shopware-` — - no `SHOPWARE_DEPLOY_ENV` suffix. This does **not** rename VPS stacks. - VPS compose pins `-p -` so live and staging stay distinct - on one host. If the file only has a commented `# COMPOSE_PROJECT_NAME=…` - line, an uncommented assignment is appended. -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** set + `COMPOSE_PROJECT_NAME` to `shopware-…` or `-`. VPS compose + derives `-` from identity and pins `-p`. Already-commented + lines are left as-is. +6. `--dry-run` prints the summary and does not write `.env` or `.env.local`. +7. After a real write: `chmod 600 .env` and `.env.local`. Does not generate `APP_SECRET` (no dedicated read/write of that key). Refuses a bash xtrace equivalent (`SHELLOPTS=xtrace` / `BASH_XTRACEFD`) so credentials @@ -358,8 +361,8 @@ Local: rsync (or a tree copy if rsync is missing) from `$SHOPWARE_DATA_BASE/$SHOPWARE_SHOP_ID/$SHOPWARE_DEPLOY_ENV/` into `--snapshot-dir/data//`. If the bind-mount directory is missing, named-volume fallback `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}_` via -`alpine:3.20` writes `--snapshot-dir/volumes/.tar.gz` (VPS project -name, not local `COMPOSE_PROJECT_NAME`). +`alpine:3.20` writes `--snapshot-dir/volumes/.tar.gz` (identity +project name, matching `docker compose -p`). Remote `--from `: SSH + rsync (or tar over SSH) from `SHOPWARE_REMOTE_DATA_ROOT` or derived @@ -499,8 +502,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 - (`{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}_`, `alpine:3.20`; not - local `COMPOSE_PROJECT_NAME`). Local target writes the + (`{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}_`, `alpine:3.20`; + identity name matching `docker compose -p`). 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 @@ -564,7 +567,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` (`.env.local` / `.env.prod`), `SHOPWARE_DATA_BASE`, `SHOPWARE_DATA_ROOT`. Do not put `COMPOSE_PROJECT_NAME` or `SHOPWARE_DEPLOY_ENV` in committed `.env`; VPS compose uses `-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 be962b3..50b6296 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -94,8 +94,9 @@ 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; sets \ -COMPOSE_PROJECT_NAME=shopware- for local project-dev). 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 to \ +`.env.local`. 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,10 +184,11 @@ 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). \ -Sets COMPOSE_PROJECT_NAME=shopware- for local shopware-cli project dev / \ -root compose.yaml (create writes COMPOSE_PROJECT_NAME=sw-…). \ -Does not append SHOPWARE_DEPLOY_ENV. VPS stacks stay - \ -(docker compose -p).\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. Writes SHOPWARE_DEPLOY_ENV to .env.local \ +(gitignored; created if missing). Compose project is - via identity \ +and docker compose -p.\n\n\ Environment:\n \ COMPOSE_DIR Shop checkout (default: walk from cwd for .env / .env.example + deploy/)\n\n\ Examples:\n \ @@ -199,7 +201,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; default live when unset and no host value) #[arg(long = "env", value_enum, value_name = "NAME")] pub env: Option, @@ -207,7 +209,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 or .env.local #[arg(long)] pub dry_run: bool, } diff --git a/src/main.rs b/src/main.rs index 83fead0..dde1d80 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,8 @@ //! 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`). 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/compose.rs b/src/shopware/compose.rs index d1ee827..cd9b3c4 100644 --- a/src/shopware/compose.rs +++ b/src/shopware/compose.rs @@ -3,8 +3,8 @@ //! 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 -p -` //! -//! `-p` pins the VPS project name so `.env` `COMPOSE_PROJECT_NAME` (local -//! `shopware-cli project dev`) cannot collide live/staging on one host. +//! `-p` pins `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` so leftover +//! `COMPOSE_PROJECT_NAME` in committed `.env` cannot collapse live/staging. //! //! Never builds images. `compose up` uses `--no-build`. `compose run` uses //! `--pull never` (Compose v5 dropped `--no-build` on `run`). @@ -142,9 +142,8 @@ mod tests { } #[test] - fn vps_argv_pins_derived_name_not_local_compose_project_name() { + fn vps_argv_pins_identity_name() { let a = vps_compose_argv("acme-live"); assert!(a.windows(2).any(|w| w == ["-p", "acme-live"]), "{a:?}"); - assert!(!a.iter().any(|s| s.contains("shopware-"))); } } diff --git a/src/shopware/env.rs b/src/shopware/env.rs index 2af6c36..c813595 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=` 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; @@ -89,6 +91,10 @@ 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 k == "SHOPWARE_DEPLOY_ENV" && v.is_empty() { + // Empty leftover in shared `.env` must not hide a host file. + continue; + } vars.insert(k, v); } } @@ -293,7 +299,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,15 +316,15 @@ pub fn allow_live_restore(env: &ShopEnv) -> bool { env_truthy(env.get("SHOPWARE_ALLOW_LIVE_RESTORE")) } -/// VPS Compose project `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. +/// Compose project `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. /// -/// `COMPOSE_PROJECT_NAME` is for local `shopware-cli project dev` / root -/// `compose.yaml` only and must not name VPS stacks. +/// Derived at runtime from loaded identity. Do not store this (or +/// `COMPOSE_PROJECT_NAME`) in committed `.env`; VPS compose pins `-p`. pub fn vps_project_name(shop_id: &str, deploy_env: &str) -> String { format!("{shop_id}-{deploy_env}") } -/// Derived VPS project name when shop id and deploy env are both set. +/// 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() => { @@ -330,9 +336,9 @@ pub fn vps_project_name_opt(env: &ShopEnv) -> Option { /// `(project_name, derived_from_shop_id_and_env)`. /// -/// Prefers `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` so VPS named-volume -/// fallback matches `docker compose -p`. `COMPOSE_PROJECT_NAME` is used only -/// when shop id / deploy env are missing (local project-dev). +/// Prefers `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` so named-volume fallback +/// matches `docker compose -p`. `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)); @@ -341,7 +347,7 @@ pub fn derive_project_name(env: &ShopEnv) -> Result<(String, bool), Error> { return Ok((n.to_string(), false)); } Err(Error::fail( - "Set SHOPWARE_SHOP_ID and SHOPWARE_DEPLOY_ENV to derive ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV} for VPS Compose. COMPOSE_PROJECT_NAME is for local shopware-cli project dev only.", + "Set SHOPWARE_SHOP_ID in shared .env and SHOPWARE_DEPLOY_ENV in .env.local to derive ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV} for Compose (-p).", )) } @@ -738,9 +744,9 @@ COMPOSE_PROFILES=redis } #[test] - fn compose_project_name_does_not_override_vps_name() { + fn compose_project_name_does_not_override_identity_name() { let mut vars = HashMap::new(); - vars.insert("COMPOSE_PROJECT_NAME".into(), "shopware-acme".into()); + 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); @@ -754,15 +760,69 @@ COMPOSE_PROFILES=redis #[test] fn compose_project_name_fallback_without_shop_identity() { let mut vars = HashMap::new(); - vars.insert("COMPOSE_PROJECT_NAME".into(), "shopware-acme".into()); + 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(), - ("shopware-acme".into(), false) + ("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_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] fn local_from_aliases() { assert!(is_local_source(None)); diff --git a/src/shopware/envfile.rs b/src/shopware/envfile.rs index 9cf8e9b..bd545d0 100644 --- a/src/shopware/envfile.rs +++ b/src/shopware/envfile.rs @@ -47,6 +47,15 @@ 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 fyrst-cli shopware env init (Compose project is ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV} via docker compose -p)"; + +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`). pub fn set_key(contents: &str, key: &str, value: &str) -> String { @@ -80,7 +89,45 @@ pub fn set_key(contents: &str, key: &str, value: &str) -> String { out } +/// 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, key).is_some() { + out.push_str("# "); + out.push_str(line); + out.push_str(suffix); + out.push('\n'); + n += 1; + } else { + out.push_str(line); + out.push('\n'); + } + } + (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; @@ -92,6 +139,9 @@ pub fn merge_missing_from_example(example: &str, dest: &mut String) -> Vec` -//! for local `shopware-cli project dev` / root `compose.yaml` (create writes -//! `COMPOSE_PROJECT_NAME=sw-…`; no `SHOPWARE_DEPLOY_ENV` suffix). Does not -//! rename VPS stacks (`-` via `docker compose -p`). 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. +//! 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 is written to +//! `.env.local` (gitignored). VPS Compose project is +//! `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` via identity + `docker compose -p`. +//! 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; -use super::envfile::{last_value, merge_missing_from_example, set_key}; +use super::envfile::{ + comment_compose_project_name, comment_deploy_env, last_value, merge_missing_from_example, + set_key, +}; use super::error::Error; use crate::cli::InitEnvArgs; use std::collections::HashMap; @@ -21,7 +26,9 @@ use std::path::{Path, PathBuf}; pub(crate) struct Plan { pub compose_dir: PathBuf, pub env_file: PathBuf, + pub local_env_file: PathBuf, contents: String, + local_contents: String, pub dry_run: bool, pub copied: bool, pub merged_keys: Vec, @@ -29,9 +36,10 @@ pub(crate) struct Plan { pub shop_id_changed: bool, pub deploy_env: String, pub deploy_env_changed: bool, + pub local_created: bool, pub image_set: Option, - pub compose_project_name: String, - pub compose_project_name_changed: bool, + pub compose_project_name_commented: usize, + pub deploy_env_commented: usize, } impl std::fmt::Debug for Plan { @@ -39,6 +47,7 @@ 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("dry_run", &self.dry_run) .field("copied", &self.copied) .field("merged_keys", &self.merged_keys) @@ -46,12 +55,13 @@ 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("image_set", &self.image_set) - .field("compose_project_name", &self.compose_project_name) .field( - "compose_project_name_changed", - &self.compose_project_name_changed, + "compose_project_name_commented", + &self.compose_project_name_commented, ) + .field("deploy_env_commented", &self.deploy_env_commented) .finish_non_exhaustive() } } @@ -61,6 +71,11 @@ impl Plan { pub(crate) fn contents(&self) -> &str { &self.contents } + + #[cfg(test)] + pub(crate) fn local_contents(&self) -> &str { + &self.local_contents + } } pub fn run(args: InitEnvArgs) -> Result<(), Error> { @@ -94,6 +109,7 @@ 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 example_file = compose_dir.join(".env.example"); let env_exists = env_file.is_file(); @@ -124,8 +140,17 @@ 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_image = last_value(&contents, "IMAGE"); let shop_id_flag = nonempty_flag(args.shop_id.as_deref(), "--shop-id")?; @@ -142,7 +167,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)?; @@ -157,7 +184,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,17 +192,19 @@ pub(crate) fn plan( contents = set_key(&contents, "IMAGE", image); } - let compose_project_name = format!("shopware-{shop_id}"); - let compose_project_name_changed = - last_value(&contents, "COMPOSE_PROJECT_NAME") != compose_project_name; - contents = set_key(&contents, "COMPOSE_PROJECT_NAME", &compose_project_name); + let (contents, compose_project_name_commented) = comment_compose_project_name(&contents); + let (contents, deploy_env_commented) = comment_deploy_env(&contents); + + local_contents = set_key(&local_contents, "SHOPWARE_DEPLOY_ENV", &deploy_env); 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; Ok(Plan { compose_dir, env_file, + local_env_file, contents, + local_contents, dry_run: args.dry_run, copied, merged_keys, @@ -184,12 +212,20 @@ pub(crate) fn plan( shop_id_changed, deploy_env, deploy_env_changed, + local_created: !local_exists, image_set, - compose_project_name, - compose_project_name_changed, + 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), @@ -239,6 +275,13 @@ 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)?; } print!("{}", summary_text(plan)); Ok(()) @@ -254,6 +297,7 @@ 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 mut changes = 0u32; @@ -273,26 +317,46 @@ 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; } - if plan.compose_project_name_changed { + if plan.compose_project_name_commented > 0 { + let _ = writeln!( + 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=… 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 COMPOSE_PROJECT_NAME={}", - plan.compose_project_name + " set SHOPWARE_DEPLOY_ENV={} in .env.local", + plan.deploy_env ); changes += 1; } else { let _ = writeln!( s, - " already set COMPOSE_PROJECT_NAME={}", - plan.compose_project_name + " already set SHOPWARE_DEPLOY_ENV={} in .env.local", + plan.deploy_env ); } if changes == 0 { @@ -304,6 +368,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 } @@ -322,7 +387,7 @@ fn chmod_600(_path: &Path) -> Result<(), Error> { #[cfg(test)] mod tests { - use super::super::envfile::MERGE_FROM_EXAMPLE_HEADER; + use super::super::envfile::{has_key, MERGE_FROM_EXAMPLE_HEADER}; use super::*; use crate::cli::DeployEnv; use std::time::{SystemTime, UNIX_EPOCH}; @@ -351,6 +416,10 @@ 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_example(&self, s: &str) { fs::write(self.0.join(".env.example"), s).unwrap(); } @@ -380,6 +449,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"); @@ -398,36 +474,43 @@ 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!(p.compose_project_name_changed); - assert_eq!(p.compose_project_name, "shopware-acme"); + assert!(p.compose_project_name_commented >= 1); + assert!(p.deploy_env_commented >= 1); assert_eq!(last_value(p.contents(), "APP_SECRET"), EXISTING_SECRET); + assert_no_uncommented(p.contents(), "COMPOSE_PROJECT_NAME"); + assert_no_uncommented(p.contents(), "SHOPWARE_DEPLOY_ENV"); assert_eq!( - last_value(p.contents(), "COMPOSE_PROJECT_NAME"), - "shopware-acme" + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" ); + 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("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("set COMPOSE_PROJECT_NAME=shopware-acme")); - assert!(!text.contains("shopware-acme-live")); + assert!(!text.contains("set 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()); } #[test] - fn write_path_sets_keys_merges_example_and_sets_compose_project_name() { + fn write_path_sets_shop_id_comments_shared_keys_and_writes_local() { let shop = TempShop::new("write"); shop.write_env(&format!( "\ @@ -435,6 +518,7 @@ SHOPWARE_SHOP_ID= MYSQL_PASSWORD={MYSQL_PASS} APP_URL= COMPOSE_PROJECT_NAME=sw-shop-acme +SHOPWARE_DEPLOY_ENV=live " )); shop.write_example( @@ -443,6 +527,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(); @@ -451,103 +537,120 @@ 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_no_uncommented(p.contents(), "COMPOSE_PROJECT_NAME"); + assert!(p + .contents() + .contains("# COMPOSE_PROJECT_NAME=sw-shop-acme # commented by fyrst-cli")); assert_eq!( - last_value(p.contents(), "COMPOSE_PROJECT_NAME"), - "shopware-acme" + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "staging" ); - assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=sw-shop-acme")); - assert!(!p.contents().contains("shopware-acme-staging")); + assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=shopware-")); 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("set COMPOSE_PROJECT_NAME=shopware-acme")); - assert!(!text.contains("shopware-acme-staging")); + assert!(text.contains("set SHOPWARE_DEPLOY_ENV=staging in .env.local")); + assert!(text.contains("commented ")); + assert!(!text.contains("set COMPOSE_PROJECT_NAME=")); } #[test] - fn commented_only_compose_project_name_appends_uncommented() { + 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\n"); let mut a = args(); a.shop_id = None; let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); - assert!(p.compose_project_name_changed); - assert_eq!(p.compose_project_name, "shopware-acme"); + assert_eq!(p.compose_project_name_commented, 0); + assert!(!p.deploy_env_changed); + 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.contents(), "COMPOSE_PROJECT_NAME"), - "shopware-acme" + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" ); let text = summary_text(&p); - assert!(text.contains("set COMPOSE_PROJECT_NAME=shopware-acme")); - assert!(!text.contains("already set COMPOSE_PROJECT_NAME")); + 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("set COMPOSE_PROJECT_NAME=")); assert!(!text.contains("--vps")); - assert!(!text.contains("no changes (already up to date)")); + assert!(text.contains("no changes (already up to date)")); } #[test] - fn copy_from_example_sets_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!(p.compose_project_name_changed); + 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.contents(), "COMPOSE_PROJECT_NAME"), - "shopware-acme" + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" ); - assert!(!p.contents().contains("COMPOSE_PROJECT_NAME=sw-shop-acme")); let text = summary_text(&p); assert!(text.contains("copy .env.example → .env")); - assert!(text.contains("set COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(text.contains("commented ")); + assert!(text.contains("create .env.local")); + assert!(!text.contains("set COMPOSE_PROJECT_NAME=")); assert!(!text.contains("--vps")); assert!(!text.contains("example-secret")); } #[test] - fn already_set_compose_project_name_is_idempotent() { - let shop = TempShop::new("already-cpn"); + 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=live -COMPOSE_PROJECT_NAME=shopware-acme +SHOPWARE_DEPLOY_ENV=staging ", ); let mut a = args(); a.shop_id = None; let p = plan(&process(shop.path()), shop.path(), &a).unwrap(); - assert!(!p.compose_project_name_changed); - assert_eq!(p.compose_project_name, "shopware-acme"); + 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.contents(), "COMPOSE_PROJECT_NAME"), - "shopware-acme" + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "staging" ); let text = summary_text(&p); - assert!(text.contains("already set COMPOSE_PROJECT_NAME=shopware-acme")); - assert!(!text.contains(" set COMPOSE_PROJECT_NAME=")); - assert!(!text.contains("--vps")); - assert!(text.contains("no changes (already up to date)")); + assert!(text.contains("set SHOPWARE_DEPLOY_ENV=staging in .env.local")); + assert!(text.contains("commented ")); + assert!(text.contains("SHOPWARE_DEPLOY_ENV")); } #[test] @@ -556,7 +659,6 @@ COMPOSE_PROJECT_NAME=shopware-acme shop.write_env(&format!( "\ SHOPWARE_SHOP_ID=acme -SHOPWARE_DEPLOY_ENV=live APP_SECRET={EXISTING_SECRET} MYSQL_PASSWORD={MYSQL_PASS} " @@ -571,7 +673,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] @@ -598,7 +703,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(); @@ -653,40 +758,58 @@ 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.contents(), "COMPOSE_PROJECT_NAME"), - "shopware-acme" + last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), + "live" ); - assert!(p.compose_project_name_changed); let text = summary_text(&p); assert!(text.contains("copy .env.example → .env")); - assert!(text.contains("set COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(text.contains("create .env.local")); + assert!(!text.contains("set COMPOSE_PROJECT_NAME=")); 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 -SHOPWARE_DEPLOY_ENV=playground -COMPOSE_PROJECT_NAME=shopware-acme ", ); + shop.write_local("SHOPWARE_DEPLOY_ENV=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.local_created); let text = summary_text(&p); - assert!(text.contains("already set COMPOSE_PROJECT_NAME=shopware-acme")); + assert!(text.contains("already set SHOPWARE_DEPLOY_ENV=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\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_eq!(last_value(p.local_contents(), "SHOPWARE_DEPLOY_ENV"), "dev"); + let text = summary_text(&p); + assert!(text.contains("set SHOPWARE_DEPLOY_ENV=dev in .env.local")); + } + #[test] fn slug_pattern() { assert!(is_shop_slug("a")); diff --git a/src/shopware/mysql.rs b/src/shopware/mysql.rs index 8142831..02c226a 100644 --- a/src/shopware/mysql.rs +++ b/src/shopware/mysql.rs @@ -158,8 +158,8 @@ pub fn client_image_for_url(scheme: &str, _env: &ShopEnv) -> String { /// `docker compose --env-file .env -f …` plus `-p ` when set. /// -/// `-p` is Compose's highest-precedence project name and wins over -/// `COMPOSE_PROJECT_NAME` in `.env` (that key is for local project-dev). +/// `-p` is Compose's highest-precedence project name and wins over leftover +/// `COMPOSE_PROJECT_NAME` in `.env`. pub fn compose_argv(files: &[String], project: Option<&str>) -> Vec { let mut a = vec!["compose".into(), "--env-file".into(), ".env".into()]; for f in files { diff --git a/src/shopware/rollout.rs b/src/shopware/rollout.rs index 806dbe7..f8fdfae 100644 --- a/src/shopware/rollout.rs +++ b/src/shopware/rollout.rs @@ -304,7 +304,7 @@ pub fn bootstrap(env: &ShopEnv, skip_pull_flag: bool, dry_run: bool) -> Result Result Result { let _ = require_shop_id(env); - // Remote VPS stacks are `{shop_id}-live`. COMPOSE_PROJECT_NAME is local - // `shopware-cli project dev` only and must not name the live project. + // 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/tests/init_env.rs b/tests/init_env.rs index 04a256f..5ba802b 100644 --- a/tests/init_env.rs +++ b/tests/init_env.rs @@ -111,10 +111,19 @@ fn init_env_help_lists_flags() { "--dry-run", "COMPOSE_DIR", "COMPOSE_PROJECT_NAME", - "COMPOSE_PROJECT_NAME=shopware-", + ".env.local", + "SHOPWARE_DEPLOY_ENV", ] { 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("--vps"), "env init --help must not list --vps:\n{help}" @@ -123,10 +132,6 @@ fn init_env_help_lists_flags() { !help.contains("--strip"), "env init --help must not list --strip:\n{help}" ); - assert!( - !help.contains("always comments"), - "env init --help must not describe commenting COMPOSE_PROJECT_NAME:\n{help}" - ); assert!( !help.contains("generate-app-secret"), "env init --help must not list --generate-app-secret:\n{help}" @@ -174,13 +179,17 @@ 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 IMAGE=ghcr.io/example/acme"), "{log}"); assert!( - log.contains("set COMPOSE_PROJECT_NAME=shopware-acme"), + log.contains("commented ") && log.contains("COMPOSE_PROJECT_NAME"), "{log}" ); - assert!(!log.contains("shopware-acme-live"), "{log}"); + assert!(log.contains("create .env.local"), "{log}"); + assert!(!log.contains("set COMPOSE_PROJECT_NAME="), "{log}"); assert!(!log.contains("--vps"), "{log}"); assert!(!log.contains("generate-app-secret"), "{log}"); assert!(!log.contains("set APP_SECRET"), "{log}"); @@ -192,10 +201,11 @@ 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()); } #[test] -fn write_merges_example_sets_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"), @@ -205,6 +215,7 @@ SHOPWARE_SHOP_ID= MYSQL_PASSWORD={MYSQL_PASS} APP_URL= COMPOSE_PROJECT_NAME=sw-shop-acme +SHOPWARE_DEPLOY_ENV=live " ), ) @@ -216,6 +227,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(); @@ -230,36 +243,56 @@ 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("set COMPOSE_PROJECT_NAME=shopware-acme"), + log.contains("set SHOPWARE_DEPLOY_ENV=staging in .env.local"), + "{log}" + ); + assert!( + log.contains("commented ") && log.contains("COMPOSE_PROJECT_NAME"), "{log}" ); - assert!(!log.contains("shopware-acme-staging"), "{log}"); + assert!(!log.contains("set 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=shopware-acme")); - assert!(!env.contains("COMPOSE_PROJECT_NAME=sw-shop-acme")); - assert!(!env.contains("shopware-acme-staging")); + 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")); 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] @@ -338,41 +371,45 @@ fn vps_flag_is_rejected() { } #[test] -fn commented_only_compose_project_name_appends_uncommented() { +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\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("set COMPOSE_PROJECT_NAME=shopware-acme"), + 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"), "{log}"); + assert!(!log.contains("set COMPOSE_PROJECT_NAME="), "{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 + assert!(!env .lines() - .any(|l| l.trim_start() == "COMPOSE_PROJECT_NAME=shopware-acme")); + .any(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME="))); } #[test] -fn already_set_compose_project_name_is_idempotent() { - let shop = TempShop::new("already-cpn"); +fn leftover_compose_project_name_is_commented() { + let shop = TempShop::new("leftover-cpn"); fs::write( shop.path().join(".env"), "\ SHOPWARE_SHOP_ID=acme -SHOPWARE_DEPLOY_ENV=live COMPOSE_PROJECT_NAME=shopware-acme ", ) @@ -381,20 +418,18 @@ COMPOSE_PROJECT_NAME=shopware-acme assert_eq!(out.status.code(), Some(0), "stderr={}", stderr(&out)); let log = stdout(&out); assert!( - log.contains("already set COMPOSE_PROJECT_NAME=shopware-acme"), + log.contains("commented ") && log.contains("COMPOSE_PROJECT_NAME"), "{log}" ); - assert!(!log.contains(" set COMPOSE_PROJECT_NAME="), "{log}"); - assert!(log.contains("no changes (already up to date)"), "{log}"); - assert!(!log.contains("--vps"), "{log}"); + assert!(!log.contains("set COMPOSE_PROJECT_NAME="), "{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_eq!( - env.lines() - .filter(|l| l.trim_start().starts_with("COMPOSE_PROJECT_NAME=")) - .count(), - 1 - ); + 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")); } #[test] @@ -428,6 +463,7 @@ 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()); } #[test] From 0da9422e23c44b94ae990c18394850cb02e0d3b5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 08:59:23 +0000 Subject: [PATCH 4/9] feat: local Compose project name - via host files env init writes COMPOSE_PROJECT_NAME=- to gitignored .env.local and upserts top-level Compose name: in gitignored compose.override.yaml so shopware-cli project dev matches VPS. Shared .env still does not get COMPOSE_PROJECT_NAME or SHOPWARE_DEPLOY_ENV. Co-authored-by: ROBJkE --- README.md | 24 ++-- docs/command-matrix.md | 42 +++--- src/cli.rs | 18 ++- src/main.rs | 3 +- src/shopware/compose_override.rs | 148 ++++++++++++++++++++ src/shopware/env.rs | 54 +++++++- src/shopware/envfile.rs | 2 +- src/shopware/init_env.rs | 223 +++++++++++++++++++++++++++++-- src/shopware/mod.rs | 1 + tests/init_env.rs | 101 +++++++++++++- 10 files changed, 561 insertions(+), 55 deletions(-) create mode 100644 src/shopware/compose_override.rs diff --git a/README.md b/README.md index c498453..c82bee8 100644 --- a/README.md +++ b/README.md @@ -155,14 +155,22 @@ 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` 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**. Compose -project name is `-` from identity, pinned with -`docker compose -p` on VPS. `.env` may still be missing; missing keys are -merged from `.env.example` (not `COMPOSE_PROJECT_NAME` / -`SHOPWARE_DEPLOY_ENV`). +`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 still pins `docker compose -p -` from identity. +`.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 diff --git a/docs/command-matrix.md b/docs/command-matrix.md index 986566e..bcada2e 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -167,11 +167,14 @@ volumes (`media`, `files`, `thumbnail`, `theme`, `sitemap`) restore from ## `shopware env init` (implemented) Finish committed shop-root `.env` after `shopware-cli project create` + Flex, -and host `.env.local` for `SHOPWARE_DEPLOY_ENV`. 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. +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 @@ -183,17 +186,26 @@ shell expansion**), same parser as import (`src/shopware/envfile.rs`). 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`. Written to - **`.env.local`** (gitignored; created if missing). 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. + **`.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. **Comments out** uncommented `COMPOSE_PROJECT_NAME=…` in shared `.env` - (create writes `COMPOSE_PROJECT_NAME=sw-…`). Does **not** set - `COMPOSE_PROJECT_NAME` to `shopware-…` or `-`. VPS compose - derives `-` from identity and pins `-p`. Already-commented - lines are left as-is. -6. `--dry-run` prints the summary and does not write `.env` or `.env.local`. -7. After a real write: `chmod 600 .env` and `.env.local`. + (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 still derives `-` from identity and pins `-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 @@ -567,7 +579,7 @@ This CLI reads shop identity and secrets from the environment / shop-root | Area | Variables | | --- | --- | -| Shop identity | `COMPOSE_DIR`, `SHOPWARE_SHOP_ID` (shared `.env`), `SHOPWARE_DEPLOY_ENV` (`.env.local` / `.env.prod`), `SHOPWARE_DATA_BASE`, `SHOPWARE_DATA_ROOT`. Do not put `COMPOSE_PROJECT_NAME` or `SHOPWARE_DEPLOY_ENV` in committed `.env`; VPS compose uses `-p -`. | +| 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). VPS compose uses `-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 50b6296..5297fe4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -95,8 +95,9 @@ 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, optional IMAGE). Comments out COMPOSE_PROJECT_NAME \ -and leftover SHOPWARE_DEPLOY_ENV in committed `.env`; writes SHOPWARE_DEPLOY_ENV to \ -`.env.local`. Does not generate APP_SECRET. `--dry-run` prints the \ +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, \ @@ -186,9 +187,12 @@ impl DeployEnv { Does not generate APP_SECRET (shopware-cli project create writes that). \ 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. Writes SHOPWARE_DEPLOY_ENV to .env.local \ -(gitignored; created if missing). Compose project is - via identity \ -and docker compose -p.\n\n\ +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 pins the same - via identity and docker compose -p.\n\n\ Environment:\n \ COMPOSE_DIR Shop checkout (default: walk from cwd for .env / .env.example + deploy/)\n\n\ Examples:\n \ @@ -201,7 +205,7 @@ pub struct InitEnvArgs { #[arg(long = "shop-id", value_name = "SLUG")] pub shop_id: Option, - /// live | staging | playground | dev (written to .env.local; default live when unset and no host value) + /// 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, @@ -209,7 +213,7 @@ pub struct InitEnvArgs { #[arg(long = "image", value_name = "REPO")] pub image: Option, - /// Print the summary; do not write .env or .env.local + /// 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 dde1d80..d2dd61a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,8 @@ //! //! Database dumps are owned by `shopware-cli project dump`. This binary does //! not wrap dump. `shopware env init` finishes committed `.env` (shop id / IMAGE) -//! and host `.env.local` (`SHOPWARE_DEPLOY_ENV`). Database +//! 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/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 c813595..82bc252 100644 --- a/src/shopware/env.rs +++ b/src/shopware/env.rs @@ -3,10 +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. Empty `SHOPWARE_DEPLOY_ENV=` 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. +//! 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; @@ -91,7 +91,9 @@ 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 k == "SHOPWARE_DEPLOY_ENV" && v.is_empty() { + 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; } @@ -318,8 +320,9 @@ pub fn allow_live_restore(env: &ShopEnv) -> bool { /// Compose project `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. /// -/// Derived at runtime from loaded identity. Do not store this (or -/// `COMPOSE_PROJECT_NAME`) in committed `.env`; VPS compose pins `-p`. +/// Same string locally (`.env.local` + `compose.override.yaml` `name:`) and +/// on VPS (`docker compose -p`). 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}") } @@ -798,6 +801,43 @@ COMPOSE_PROFILES=redis 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"); diff --git a/src/shopware/envfile.rs b/src/shopware/envfile.rs index bd545d0..e99b03d 100644 --- a/src/shopware/envfile.rs +++ b/src/shopware/envfile.rs @@ -51,7 +51,7 @@ pub const MERGE_FROM_EXAMPLE_HEADER: &str = const SKIP_MERGE_INTO_SHARED_ENV: &[&str] = &["COMPOSE_PROJECT_NAME", "SHOPWARE_DEPLOY_ENV"]; pub const COMPOSE_PROJECT_NAME_COMMENT_SUFFIX: &str = - " # commented by fyrst-cli shopware env init (Compose project is ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV} via docker compose -p)"; + " # commented by fyrst-cli shopware env init (Compose project is ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV}; host .env.local + compose.override.yaml / VPS docker compose -p)"; pub const SHOPWARE_DEPLOY_ENV_COMMENT_SUFFIX: &str = " # commented by fyrst-cli shopware env init (host-specific; set in .env.local)"; diff --git a/src/shopware/init_env.rs b/src/shopware/init_env.rs index 313366f..c9d4c54 100644 --- a/src/shopware/init_env.rs +++ b/src/shopware/init_env.rs @@ -4,14 +4,19 @@ //! 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 is written to -//! `.env.local` (gitignored). VPS Compose project is +//! `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 identity + `docker compose -p`. //! 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; +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, comment_deploy_env, last_value, merge_missing_from_example, set_key, @@ -27,8 +32,10 @@ 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, @@ -37,6 +44,10 @@ pub(crate) struct Plan { 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, @@ -48,6 +59,7 @@ impl std::fmt::Debug for 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) @@ -56,6 +68,13 @@ impl std::fmt::Debug for Plan { .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", @@ -76,6 +95,11 @@ impl Plan { 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> { @@ -110,6 +134,7 @@ pub(crate) fn plan( 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(); @@ -151,7 +176,14 @@ pub(crate) fn plan( let existing_shop_id = last_value(&contents, "SHOPWARE_SHOP_ID"); 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 { @@ -195,16 +227,27 @@ 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_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, @@ -213,6 +256,10 @@ pub(crate) fn plan( 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, @@ -282,6 +329,12 @@ fn execute(plan: &Plan) -> Result<(), Error> { )) })?; 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(()) @@ -298,6 +351,7 @@ 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; @@ -359,6 +413,38 @@ pub(crate) fn summary_text(plan: &Plan) -> String { 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)"); } @@ -390,6 +476,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); @@ -420,6 +508,10 @@ mod tests { 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(); } @@ -485,17 +577,27 @@ COMPOSE_PROJECT_NAME=sw-shop-acme 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 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("set COMPOSE_PROJECT_NAME=")); assert!(!text.contains("--vps")); assert!(text.contains("APP_SECRET")); assert!(!text.contains("generate-app-secret")); @@ -507,6 +609,7 @@ 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] @@ -552,15 +655,22 @@ SHOPWARE_DEPLOY_ENV=from-example 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 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 ")); - assert!(!text.contains("set COMPOSE_PROJECT_NAME=")); } #[test] @@ -572,12 +682,16 @@ SHOPWARE_SHOP_ID=acme # COMPOSE_PROJECT_NAME=sw-shop-acme ", ); - shop.write_local("SHOPWARE_DEPLOY_ENV=live\n"); + 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"); @@ -585,10 +699,15 @@ SHOPWARE_SHOP_ID=acme 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=… in shared .env")); assert!(text.contains("already set SHOPWARE_DEPLOY_ENV=live in .env.local")); - assert!(!text.contains("set COMPOSE_PROJECT_NAME=")); + 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)")); } @@ -614,11 +733,16 @@ MYSQL_PASSWORD=example-secret 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 ")); assert!(text.contains("create .env.local")); - assert!(!text.contains("set COMPOSE_PROJECT_NAME=")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-live in .env.local")); assert!(!text.contains("--vps")); assert!(!text.contains("example-secret")); } @@ -647,8 +771,13 @@ SHOPWARE_DEPLOY_ENV=staging 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")); } @@ -765,10 +894,14 @@ MYSQL_PASSWORD=example-secret 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=")); + assert!(text.contains("set COMPOSE_PROJECT_NAME=acme-live in .env.local")); assert!(!text.contains("example-secret")); assert!(!shop.path().join(".env").is_file()); } @@ -781,15 +914,19 @@ MYSQL_PASSWORD=example-secret SHOPWARE_SHOP_ID=acme ", ); - shop.write_local("SHOPWARE_DEPLOY_ENV=playground\n"); + 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("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)")); } @@ -798,16 +935,80 @@ SHOPWARE_SHOP_ID=acme 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\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] 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/tests/init_env.rs b/tests/init_env.rs index 5ba802b..55dd4fc 100644 --- a/tests/init_env.rs +++ b/tests/init_env.rs @@ -113,6 +113,7 @@ fn init_env_help_lists_flags() { "COMPOSE_PROJECT_NAME", ".env.local", "SHOPWARE_DEPLOY_ENV", + "compose.override.yaml", ] { assert!(help.contains(needle), "missing {needle} in:\n{help}"); } @@ -124,6 +125,10 @@ fn init_env_help_lists_flags() { 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}" @@ -183,13 +188,21 @@ COMPOSE_PROJECT_NAME=sw-shop-acme 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 ") && log.contains("COMPOSE_PROJECT_NAME"), "{log}" ); assert!(log.contains("create .env.local"), "{log}"); - assert!(!log.contains("set COMPOSE_PROJECT_NAME="), "{log}"); assert!(!log.contains("--vps"), "{log}"); assert!(!log.contains("generate-app-secret"), "{log}"); assert!(!log.contains("set APP_SECRET"), "{log}"); @@ -202,6 +215,7 @@ COMPOSE_PROJECT_NAME=sw-shop-acme 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] @@ -253,11 +267,18 @@ SHOPWARE_DEPLOY_ENV=from-example 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("set COMPOSE_PROJECT_NAME="), "{log}"); assert!(!log.contains("--vps"), "{log}"); assert_no_secrets(&out, &["from-example"]); @@ -278,6 +299,9 @@ SHOPWARE_DEPLOY_ENV=from-example 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() @@ -381,7 +405,16 @@ SHOPWARE_SHOP_ID=acme ", ) .unwrap(); - fs::write(shop.path().join(".env.local"), "SHOPWARE_DEPLOY_ENV=live\n").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); @@ -393,7 +426,14 @@ SHOPWARE_SHOP_ID=acme log.contains("already set SHOPWARE_DEPLOY_ENV=live in .env.local"), "{log}" ); - assert!(!log.contains("set COMPOSE_PROJECT_NAME="), "{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(); @@ -421,7 +461,10 @@ COMPOSE_PROJECT_NAME=shopware-acme log.contains("commented ") && log.contains("COMPOSE_PROJECT_NAME"), "{log}" ); - assert!(!log.contains("set 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")); @@ -430,6 +473,53 @@ COMPOSE_PROJECT_NAME=shopware-acme .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] @@ -464,6 +554,7 @@ MYSQL_PASSWORD={MYSQL_PASS} 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] From c1fe4a0a16a9f5dd0d7b2a94fd4e01b0b5f29ca8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 09:16:28 +0000 Subject: [PATCH 5/9] feat: pass host env files to VPS compose argv VPS docker compose loads .env, then .env.local/.env.prod when present, so deploy/compose.yaml name: interpolates SHOPWARE_DEPLOY_ENV. Keep -p - as a matching pin. Co-authored-by: ROBJkE --- README.md | 8 ++- docs/command-matrix.md | 11 ++-- src/cli.rs | 3 +- src/shopware/compose.rs | 131 ++++++++++++++++++++++++++++++++++++---- src/shopware/env.rs | 12 ++-- src/shopware/rollout.rs | 63 ++++++++++++++----- tests/release.rs | 25 ++++++++ tests/rollback.rs | 2 +- 8 files changed, 213 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index c82bee8..af6e0b8 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,9 @@ 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 still pins `docker compose -p -` from identity. +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) and still pins `-p -` as a matching pin. `.env` may still be missing; missing keys are merged from `.env.example` (not `COMPOSE_PROJECT_NAME` / `SHOPWARE_DEPLOY_ENV`). @@ -195,6 +197,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). `-p` is a matching pin. + ```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 bcada2e..2693b83 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -110,12 +110,10 @@ 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 -p - +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 -p - ``` -`-p` pins `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` from loaded identity -(`.env` shop id + `.env.local` / `.env.prod` deploy env). Leftover -`COMPOSE_PROJECT_NAME` in committed `.env` is ignored. +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). `-p -` is a matching pin from loaded identity (`.env` shop id + `.env.local` / `.env.prod` deploy env). Leftover `COMPOSE_PROJECT_NAME` in committed `.env` is ignored. Never `--build`. `compose run` uses `--pull never` (not `--no-build`). `compose up` uses `--no-build` (and `--pull never` when skipping registry pull). Theme/asset @@ -202,7 +200,8 @@ shell expansion**), same parser as import (`src/shopware/envfile.rs`). `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 still derives `-` from identity and pins `-p`. + VPS compose interpolates the same `-` from `deploy/compose.yaml` + `name:` plus host env files; `-p` is a matching pin. 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). @@ -579,7 +578,7 @@ This CLI reads shop identity and secrets from the environment / shop-root | Area | Variables | | --- | --- | -| 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). VPS compose uses `-p -`. | +| 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). VPS compose SoT is `deploy/compose.yaml` `name:` interpolating host env files; `-p -` is a matching pin. | | 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 5297fe4..87fb902 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -192,7 +192,8 @@ Writes SHOPWARE_DEPLOY_ENV and COMPOSE_PROJECT_NAME=- to .env.loca (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 pins the same - via identity and docker compose -p.\n\n\ +VPS compose interpolates the same - from deploy/compose.yaml name: plus host \ +env files; docker compose -p is a matching pin.\n\n\ Environment:\n \ COMPOSE_DIR Shop checkout (default: walk from cwd for .env / .env.example + deploy/)\n\n\ Examples:\n \ diff --git a/src/shopware/compose.rs b/src/shopware/compose.rs index cd9b3c4..3d92d46 100644 --- a/src/shopware/compose.rs +++ b/src/shopware/compose.rs @@ -1,25 +1,53 @@ //! 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 -p -` +//! 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). `-p -` is a matching pin (defense in +//! depth), not the only naming mechanism. //! -//! `-p` pins `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` so leftover -//! `COMPOSE_PROJECT_NAME` in committed `.env` cannot collapse live/staging. +//! 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 -p -` //! //! 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_FILES, ENV_FILES}; use super::error::Error; use super::mysql::require_docker; use std::path::Path; use std::process::{Command, Stdio}; -/// The three overlay compose files plus `-p `; all files must exist -/// for VPS release/rollback. `project` is `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. -pub fn vps_compose_argv(project: &str) -> Vec { - let files: Vec = COMPOSE_FILES.iter().map(|s| (*s).to_string()).collect(); - super::mysql::compose_argv(&files, Some(project)) +/// `--env-file` flags: always `.env`, then `.env.local` / `.env.prod` if present. +pub fn vps_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 +} + +/// The three overlay compose files, host env files, plus `-p `. +/// +/// `project` is `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` and must match +/// compose `name:` after interpolation. All overlay files must exist for VPS +/// release/rollback. +pub fn vps_compose_argv(compose_dir: &Path, project: &str) -> Vec { + let mut a = vec!["compose".into()]; + a.extend(vps_env_file_flags(compose_dir)); + for f in COMPOSE_FILES { + a.push("-f".into()); + a.push((*f).to_string()); + } + a.push("-p".into()); + a.push(project.to_string()); + a } pub fn docker_log(compose_args: &[String]) -> String { @@ -89,7 +117,7 @@ pub fn compose_service_names( extra_env: &[(String, String)], project: &str, ) -> Vec { - let mut args = vps_compose_argv(project); + let mut args = vps_compose_argv(compose_dir, project); args.extend(profile_args.iter().cloned()); args.extend(["config".into(), "--services".into()]); let mut cmd = Command::new("docker"); @@ -113,10 +141,44 @@ 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() + } #[test] fn vps_argv_is_the_three_overlay_files() { - let a = vps_compose_argv("acme-staging"); + let shop = TempShop::new("base"); + let a = vps_compose_argv(&shop.0, "acme-staging"); assert_eq!( a, vec![ @@ -139,11 +201,54 @@ mod tests { "docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml -p acme-staging" ); assert!(!args_contain_build(&a)); + assert_eq!(env_files(&a), [".env"]); } #[test] fn vps_argv_pins_identity_name() { - let a = vps_compose_argv("acme-live"); + let shop = TempShop::new("pin"); + let a = vps_compose_argv(&shop.0, "acme-live"); assert!(a.windows(2).any(|w| w == ["-p", "acme-live"]), "{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, "acme-dev"); + assert_eq!(env_files(&a), [".env", ".env.local", ".env.prod"]); + assert!( + a.windows(2).any(|w| w == ["-p", "acme-dev"]), + "matching pin missing: {a:?}" + ); + let log = docker_log(&a); + assert!( + log.contains( + "docker compose --env-file .env --env-file .env.local --env-file .env.prod -f deploy/compose.yaml" + ), + "{log}" + ); + assert!(log.contains("-p acme-dev"), "{log}"); + 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(); + let dash_p = a.iter().position(|s| s == "-p").unwrap(); + assert!(env_idx.iter().all(|i| *i < dash_f), "{a:?}"); + assert!(dash_f < dash_p, "{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, "acme-staging"); + assert_eq!(env_files(&a), [".env", ".env.prod"]); + assert!(!a.iter().any(|s| s == ".env.local"), "{a:?}"); + assert!(a.windows(2).any(|w| w == ["-p", "acme-staging"]), "{a:?}"); + } } diff --git a/src/shopware/env.rs b/src/shopware/env.rs index 82bc252..1287ca8 100644 --- a/src/shopware/env.rs +++ b/src/shopware/env.rs @@ -42,7 +42,8 @@ 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 VPS `docker compose --env-file` flags. +pub const ENV_FILES: &[&str] = &[".env", ".env.local", ".env.prod"]; pub const COMPOSE_FILES: &[&str] = &[ "deploy/compose.yaml", @@ -321,8 +322,9 @@ pub fn allow_live_restore(env: &ShopEnv) -> bool { /// Compose project `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}`. /// /// Same string locally (`.env.local` + `compose.override.yaml` `name:`) and -/// on VPS (`docker compose -p`). Do not store this (or `COMPOSE_PROJECT_NAME`) -/// in committed `.env`. +/// on VPS (`deploy/compose.yaml` `name:` interpolating host env files, with +/// `docker compose -p` as a matching pin). 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}") } @@ -340,7 +342,7 @@ pub fn vps_project_name_opt(env: &ShopEnv) -> Option { /// `(project_name, derived_from_shop_id_and_env)`. /// /// Prefers `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` so named-volume fallback -/// matches `docker compose -p`. `COMPOSE_PROJECT_NAME` is a last-resort +/// matches compose `name:` / `-p`. `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) { @@ -350,7 +352,7 @@ pub fn derive_project_name(env: &ShopEnv) -> Result<(String, bool), Error> { return Ok((n.to_string(), false)); } 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 (-p).", + "Set SHOPWARE_SHOP_ID in shared .env and SHOPWARE_DEPLOY_ENV in .env.local to derive ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV} for Compose (name: + host env files; -p matching pin).", )) } diff --git a/src/shopware/rollout.rs b/src/shopware/rollout.rs index f8fdfae..460cc33 100644 --- a/src/shopware/rollout.rs +++ b/src/shopware/rollout.rs @@ -151,6 +151,7 @@ pub struct RolloutPlan { impl RolloutPlan { pub fn build( + compose_dir: &Path, skip_pull: bool, pull_policy: String, profiles: Vec, @@ -160,12 +161,12 @@ impl RolloutPlan { let pull = if skip_pull { None } else { - let mut a = vps_compose_argv(&project); + let mut a = vps_compose_argv(compose_dir, &project); extend_profiles(&mut a, &profiles); a.push("pull".into()); Some(a) }; - let mut setup = vps_compose_argv(&project); + let mut setup = vps_compose_argv(compose_dir, &project); setup.extend([ "--profile".into(), "setup".into(), @@ -175,14 +176,14 @@ impl RolloutPlan { "never".into(), "setup".into(), ]); - let mut web = vps_compose_argv(&project); + let mut web = vps_compose_argv(compose_dir, &project); 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(&project); + let mut a = vps_compose_argv(compose_dir, &project); extend_profiles(&mut a, &profiles); a.extend(["up".into(), "-d".into(), "--no-build".into()]); a.extend(up_pull_args(skip_pull)); @@ -273,6 +274,7 @@ impl VpsContext { pub fn plan(&self) -> RolloutPlan { RolloutPlan::build( + &self.compose_dir, self.skip_pull, self.pull_policy.clone(), self.profiles.clone(), @@ -334,11 +336,13 @@ pub fn bootstrap(env: &ShopEnv, skip_pull_flag: bool, dry_run: bool) -> Result Result<(), Error if services.iter().any(|s| s == "mysql") { println!("==> Starting mysql"); - let mut a = vps_compose_argv(&ctx.compose_project_name); + let mut a = vps_compose_argv(&ctx.compose_dir, &ctx.compose_project_name); a.extend(["up".into(), "-d".into(), "--no-build".into()]); a.extend(up_pull_args(plan.skip_pull)); a.push("mysql".into()); @@ -424,7 +428,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(&ctx.compose_project_name); + let mut a = vps_compose_argv(&ctx.compose_dir, &ctx.compose_project_name); a.extend([ "--profile".into(), "redis".into(), @@ -519,14 +523,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 +542,8 @@ mod tests { parsed, profiles.to_string(), "acme-staging".into(), - ) + ); + (shop, p) } #[test] @@ -544,7 +551,7 @@ 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")); @@ -559,7 +566,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()])); @@ -615,7 +622,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"), @@ -696,7 +703,7 @@ DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop assert!(ctx .notes .iter() - .any(|n| n.contains("ignored; compose uses -p acme-staging"))); + .any(|n| n.contains("matching pin") && n.contains("acme-staging"))); assert!(!ctx.warnings.iter().any(|w| w.contains("remove or comment"))); let plan = ctx.plan(); assert!(plan.pull.is_none()); @@ -707,6 +714,32 @@ DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop assert!(!web.contains("super-secret-pass")); } + #[test] + fn rollout_plan_passes_host_env_files_and_pins_identity() { + 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(), + "acme-dev".into(), + ); + 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.windows(2).any(|w| w == ["-p", "acme-dev"])); + let log = docker_log(&p.web); + assert!( + log.contains("--env-file .env --env-file .env.local --env-file .env.prod"), + "{log}" + ); + assert!(log.contains("-p acme-dev"), "{log}"); + } + #[test] fn missing_vps_file_errors() { let shop = TempShop::new("nofile"); diff --git a/tests/release.rs b/tests/release.rs index 41d4e17..2596a03 100644 --- a/tests/release.rs +++ b/tests/release.rs @@ -191,6 +191,31 @@ fn dry_run_prints_compose_sequence_without_passwords() { ); } +#[test] +fn dry_run_passes_env_local_and_pins_identity_name() { + 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.contains("-p acme-dev"), "{log}"); + assert!(!log.contains("-p acme-staging"), "{log}"); + assert!(!log.contains("-p shopware-"), "{log}"); +} + #[test] fn skip_pull_dry_run_sets_pull_policy_never() { let shop = TempShop::new("skip"); diff --git a/tests/rollback.rs b/tests/rollback.rs index dc02524..dc82441 100644 --- a/tests/rollback.rs +++ b/tests/rollback.rs @@ -248,7 +248,7 @@ 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}" ); From f47f967815a2d2d98e2da37443773285424845e4 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 09:22:11 +0000 Subject: [PATCH 6/9] feat: drop -p from VPS compose argv VPS project name comes only from deploy/compose.yaml name: interpolating host env files (.env, then .env.local/.env.prod when present). Co-authored-by: ROBJkE --- README.md | 4 +- docs/command-matrix.md | 12 +++--- src/cli.rs | 2 +- src/shopware/compose.rs | 91 ++++++++++++++++++++++++---------------- src/shopware/env.rs | 9 ++-- src/shopware/envfile.rs | 2 +- src/shopware/init_env.rs | 3 +- src/shopware/rollout.rs | 67 +++++++++++++---------------- tests/release.rs | 16 ++++--- tests/rollback.rs | 7 +++- 10 files changed, 114 insertions(+), 99 deletions(-) diff --git a/README.md b/README.md index af6e0b8..c10053b 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ 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) and still pins `-p -` as a matching pin. +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`). @@ -199,7 +199,7 @@ win over `.env` on release. Rollback ignores process-env `IMAGE_TAG` and reads 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). `-p` is a matching pin. +then `.env.local` / `.env.prod` when present). There is no `-p`. ```bash fyrst-cli shopware deploy release --dry-run diff --git a/docs/command-matrix.md b/docs/command-matrix.md index 2693b83..baf341f 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -110,10 +110,10 @@ Resolves shop root (`COMPOSE_DIR` or walk from cwd), loads `.env` then Compose is always: ```text -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 -p - +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). `-p -` is a matching pin from loaded identity (`.env` shop id + `.env.local` / `.env.prod` deploy env). Leftover `COMPOSE_PROJECT_NAME` in committed `.env` is ignored. +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 @@ -201,7 +201,7 @@ shell expansion**), same parser as import (`src/shopware/envfile.rs`). 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; `-p` is a matching pin. + `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). @@ -373,7 +373,7 @@ Local: rsync (or a tree copy if rsync is missing) from into `--snapshot-dir/data//`. If the bind-mount directory is missing, named-volume fallback `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}_` via `alpine:3.20` writes `--snapshot-dir/volumes/.tar.gz` (identity -project name, matching `docker compose -p`). +project name, matching Compose `name:`). Remote `--from `: SSH + rsync (or tar over SSH) from `SHOPWARE_REMOTE_DATA_ROOT` or derived @@ -514,7 +514,7 @@ shopware-cli. `$SHOPWARE_DATA_BASE/$SHOPWARE_SHOP_ID/$SHOPWARE_DEPLOY_ENV`) into `data//`. Missing bind-mounts fall back to a named-volume tar (`{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}_`, `alpine:3.20`; - identity name matching `docker compose -p`). Local target writes the + 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 @@ -578,7 +578,7 @@ This CLI reads shop identity and secrets from the environment / shop-root | Area | Variables | | --- | --- | -| 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). VPS compose SoT is `deploy/compose.yaml` `name:` interpolating host env files; `-p -` is a matching pin. | +| 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). VPS compose SoT is `deploy/compose.yaml` `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 87fb902..39b3ef4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -193,7 +193,7 @@ Writes SHOPWARE_DEPLOY_ENV and COMPOSE_PROJECT_NAME=- to .env.loca 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; docker compose -p is a matching pin.\n\n\ +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 \ diff --git a/src/shopware/compose.rs b/src/shopware/compose.rs index 3d92d46..d98a3e8 100644 --- a/src/shopware/compose.rs +++ b/src/shopware/compose.rs @@ -5,11 +5,10 @@ //! `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). `-p -` is a matching pin (defense in -//! depth), not the only naming mechanism. +//! 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 -p -` +//! `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`). @@ -33,20 +32,17 @@ pub fn vps_env_file_flags(compose_dir: &Path) -> Vec { out } -/// The three overlay compose files, host env files, plus `-p `. +/// The three overlay compose files plus host env files. /// -/// `project` is `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` and must match -/// compose `name:` after interpolation. All overlay files must exist for VPS -/// release/rollback. -pub fn vps_compose_argv(compose_dir: &Path, project: &str) -> Vec { +/// 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(vps_env_file_flags(compose_dir)); for f in COMPOSE_FILES { a.push("-f".into()); a.push((*f).to_string()); } - a.push("-p".into()); - a.push(project.to_string()); a } @@ -115,9 +111,8 @@ pub fn compose_service_names( compose_dir: &Path, profile_args: &[String], extra_env: &[(String, String)], - project: &str, ) -> Vec { - let mut args = vps_compose_argv(compose_dir, project); + 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"); @@ -175,10 +170,24 @@ mod tests { .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 shop = TempShop::new("base"); - let a = vps_compose_argv(&shop.0, "acme-staging"); + let a = vps_compose_argv(&shop.0); assert_eq!( a, vec![ @@ -191,24 +200,24 @@ mod tests { "deploy/compose.prod.yaml", "-f", "deploy/compose.vps.yaml", - "-p", - "acme-staging", ] ); let log = docker_log(&a); assert_eq!( log, - "docker compose --env-file .env -f deploy/compose.yaml -f deploy/compose.prod.yaml -f deploy/compose.vps.yaml -p acme-staging" + "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"]); - } - - #[test] - fn vps_argv_pins_identity_name() { - let shop = TempShop::new("pin"); - let a = vps_compose_argv(&shop.0, "acme-live"); - assert!(a.windows(2).any(|w| w == ["-p", "acme-live"]), "{a:?}"); + assert_eq!( + compose_files(&a), + [ + "deploy/compose.yaml", + "deploy/compose.prod.yaml", + "deploy/compose.vps.yaml" + ] + ); + assert_no_project_flag(&a); } #[test] @@ -216,20 +225,22 @@ mod tests { 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, "acme-dev"); + let a = vps_compose_argv(&shop.0); assert_eq!(env_files(&a), [".env", ".env.local", ".env.prod"]); - assert!( - a.windows(2).any(|w| w == ["-p", "acme-dev"]), - "matching pin missing: {a:?}" + 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!( - log.contains( - "docker compose --env-file .env --env-file .env.local --env-file .env.prod -f deploy/compose.yaml" - ), - "{log}" + 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" ); - assert!(log.contains("-p acme-dev"), "{log}"); let env_idx: Vec = a .windows(2) .enumerate() @@ -237,18 +248,24 @@ mod tests { .map(|(i, _)| i) .collect(); let dash_f = a.iter().position(|s| s == "-f").unwrap(); - let dash_p = a.iter().position(|s| s == "-p").unwrap(); assert!(env_idx.iter().all(|i| *i < dash_f), "{a:?}"); - assert!(dash_f < dash_p, "{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, "acme-staging"); + 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!(a.windows(2).any(|w| w == ["-p", "acme-staging"]), "{a:?}"); + assert_no_project_flag(&a); } } diff --git a/src/shopware/env.rs b/src/shopware/env.rs index 1287ca8..514f5f9 100644 --- a/src/shopware/env.rs +++ b/src/shopware/env.rs @@ -322,9 +322,8 @@ pub fn allow_live_restore(env: &ShopEnv) -> bool { /// 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, with -/// `docker compose -p` as a matching pin). Do not store this (or -/// `COMPOSE_PROJECT_NAME`) in committed `.env`. +/// 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}") } @@ -342,7 +341,7 @@ pub fn vps_project_name_opt(env: &ShopEnv) -> Option { /// `(project_name, derived_from_shop_id_and_env)`. /// /// Prefers `{SHOPWARE_SHOP_ID}-{SHOPWARE_DEPLOY_ENV}` so named-volume fallback -/// matches compose `name:` / `-p`. `COMPOSE_PROJECT_NAME` is a last-resort +/// 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) { @@ -352,7 +351,7 @@ pub fn derive_project_name(env: &ShopEnv) -> Result<(String, bool), Error> { return Ok((n.to_string(), false)); } 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 (name: + host env files; -p matching pin).", + "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).", )) } diff --git a/src/shopware/envfile.rs b/src/shopware/envfile.rs index e99b03d..e0a8bc2 100644 --- a/src/shopware/envfile.rs +++ b/src/shopware/envfile.rs @@ -51,7 +51,7 @@ pub const MERGE_FROM_EXAMPLE_HEADER: &str = const SKIP_MERGE_INTO_SHARED_ENV: &[&str] = &["COMPOSE_PROJECT_NAME", "SHOPWARE_DEPLOY_ENV"]; pub const COMPOSE_PROJECT_NAME_COMMENT_SUFFIX: &str = - " # commented by fyrst-cli shopware env init (Compose project is ${SHOPWARE_SHOP_ID}-${SHOPWARE_DEPLOY_ENV}; host .env.local + compose.override.yaml / VPS docker compose -p)"; + " # 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)"; diff --git a/src/shopware/init_env.rs b/src/shopware/init_env.rs index c9d4c54..f758d1a 100644 --- a/src/shopware/init_env.rs +++ b/src/shopware/init_env.rs @@ -10,7 +10,8 @@ //! 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 identity + `docker compose -p`. +//! `{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. diff --git a/src/shopware/rollout.rs b/src/shopware/rollout.rs index 460cc33..dadf711 100644 --- a/src/shopware/rollout.rs +++ b/src/shopware/rollout.rs @@ -146,7 +146,6 @@ pub struct RolloutPlan { pub setup: Vec, pub web: Vec, pub extra: Option>, - pub project: String, } impl RolloutPlan { @@ -156,17 +155,16 @@ impl RolloutPlan { pull_policy: String, profiles: Vec, profiles_raw: String, - project: String, ) -> Self { let pull = if skip_pull { None } else { - let mut a = vps_compose_argv(compose_dir, &project); + 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(compose_dir, &project); + let mut setup = vps_compose_argv(compose_dir); setup.extend([ "--profile".into(), "setup".into(), @@ -176,14 +174,14 @@ impl RolloutPlan { "never".into(), "setup".into(), ]); - let mut web = vps_compose_argv(compose_dir, &project); + 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(compose_dir, &project); + 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)); @@ -198,7 +196,6 @@ impl RolloutPlan { setup, web, extra, - project, } } @@ -259,10 +256,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()), ]; @@ -279,7 +272,6 @@ impl VpsContext { self.pull_policy.clone(), self.profiles.clone(), self.profiles_raw.clone(), - self.compose_project_name.clone(), ) } @@ -336,12 +328,12 @@ pub fn bootstrap(env: &ShopEnv, skip_pull_flag: bool, dry_run: bool) -> Result Result<(), Error let mut profile_args = Vec::new(); extend_profiles(&mut profile_args, &plan.profiles); - let services = compose_service_names( - &ctx.compose_dir, - &profile_args, - &env, - &ctx.compose_project_name, - ); + let services = compose_service_names(&ctx.compose_dir, &profile_args, &env); if services.iter().any(|s| s == "mysql") { println!("==> Starting mysql"); - let mut a = vps_compose_argv(&ctx.compose_dir, &ctx.compose_project_name); + 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()); @@ -428,7 +415,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(&ctx.compose_dir, &ctx.compose_project_name); + let mut a = vps_compose_argv(&ctx.compose_dir); a.extend([ "--profile".into(), "redis".into(), @@ -541,7 +528,6 @@ mod tests { }, parsed, profiles.to_string(), - "acme-staging".into(), ); (shop, p) } @@ -555,7 +541,7 @@ mod tests { 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.windows(2).any(|w| w == ["-p", "acme-staging"])); + 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()); @@ -634,7 +620,11 @@ mod tests { web.contains("up -d --no-build --remove-orphans web"), "{web}" ); - assert!(web.contains("-p acme-staging"), "{web}"); + assert!( + !web.split_whitespace() + .any(|t| t == "-p" || t == "--project-name"), + "{web}" + ); assert!(!web.contains("shopware-acme"), "{web}"); } @@ -695,7 +685,7 @@ DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop assert!(ctx.skip_pull); assert_eq!(ctx.pull_policy, "never"); assert_eq!(ctx.compose_project_name, "acme-staging"); - assert!(ctx.notes.iter().any(|n| n.contains("-p acme-staging"))); + assert!(ctx.notes.iter().any(|n| n.contains("acme-staging"))); assert!(ctx .notes .iter() @@ -703,11 +693,16 @@ DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop assert!(ctx .notes .iter() - .any(|n| n.contains("matching pin") && n.contains("acme-staging"))); + .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.windows(2).any(|w| w == ["-p", "acme-staging"])); + 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")); @@ -715,29 +710,23 @@ DATABASE_URL=mysql://alice:s3cret-value@db.example.com/shop } #[test] - fn rollout_plan_passes_host_env_files_and_pins_identity() { + 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(), - "acme-dev".into(), - ); + 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.windows(2).any(|w| w == ["-p", "acme-dev"])); + 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("-p acme-dev"), "{log}"); + assert!(log.contains("-f deploy/compose.yaml"), "{log}"); + assert!(!log.split_whitespace().any(|t| t == "-p"), "{log}"); } #[test] diff --git a/tests/release.rs b/tests/release.rs index 2596a03..da9992b 100644 --- a/tests/release.rs +++ b/tests/release.rs @@ -157,7 +157,11 @@ 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.contains("-p acme-staging"), "{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"), @@ -192,7 +196,7 @@ fn dry_run_prints_compose_sequence_without_passwords() { } #[test] -fn dry_run_passes_env_local_and_pins_identity_name() { +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(); @@ -211,9 +215,11 @@ fn dry_run_passes_env_local_and_pins_identity_name() { ), "{log}" ); - assert!(log.contains("-p acme-dev"), "{log}"); - assert!(!log.contains("-p acme-staging"), "{log}"); - assert!(!log.contains("-p shopware-"), "{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 dc82441..5d595ae 100644 --- a/tests/rollback.rs +++ b/tests/rollback.rs @@ -252,8 +252,11 @@ fn dry_run_prints_same_compose_order_as_release() { ), "{log}" ); - assert!(log.contains("-p acme-staging"), "{log}"); - assert!(!log.contains("-p shopware-"), "{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}")); From 9e569f7dc97dd2c52fc14a06a30d73b18e095a08 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 09:25:20 +0000 Subject: [PATCH 7/9] fix: drop unused VPS compose project field after removing -p VpsContext no longer stores a project name used only for docker compose -p. Bootstrap still derives {shop-id}-{env} for operator notes. Co-authored-by: ROBJkE --- src/shopware/rollout.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/shopware/rollout.rs b/src/shopware/rollout.rs index dadf711..2da3f63 100644 --- a/src/shopware/rollout.rs +++ b/src/shopware/rollout.rs @@ -225,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, @@ -328,7 +327,7 @@ pub fn bootstrap(env: &ShopEnv, skip_pull_flag: bool, dry_run: bool) -> Result Result Date: Thu, 17 Sep 2026 09:31:10 +0000 Subject: [PATCH 8/9] feat: drop -p from db import and rewrite compose Import, rewrite, restore, and sync compose argv use the same naming SoT as VPS: compose name: interpolating host env files in identity-load order. compose_argv no longer takes a project name or emits -p. Co-authored-by: ROBJkE --- README.md | 4 +- docs/command-matrix.md | 8 ++-- src/shopware/app.rs | 19 ++++------ src/shopware/compose.rs | 17 +-------- src/shopware/env.rs | 15 +++++++- src/shopware/import.rs | 71 ++++++++++++++++++++++++----------- src/shopware/mysql.rs | 83 +++++++++++++++++++++++++---------------- src/shopware/restore.rs | 61 ++++++++++++------------------ src/shopware/rewrite.rs | 48 ++++++++++++++++++++---- src/shopware/sync.rs | 32 +++------------- tests/import.rs | 35 ++++++++++++++++- tests/restore.rs | 6 +++ 12 files changed, 241 insertions(+), 158 deletions(-) diff --git a/README.md b/README.md index c10053b..3f2d6d2 100644 --- a/README.md +++ b/README.md @@ -182,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 diff --git a/docs/command-matrix.md b/docs/command-matrix.md index baf341f..8e1c41f 100644 --- a/docs/command-matrix.md +++ b/docs/command-matrix.md @@ -276,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 … -p - 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. @@ -578,7 +580,7 @@ This CLI reads shop identity and secrets from the environment / shop-root | Area | Variables | | --- | --- | -| 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). VPS compose SoT is `deploy/compose.yaml` `name:` interpolating host env files (no `-p`). | +| 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/shopware/app.rs b/src/shopware/app.rs index 707f713..caf3ea3 100644 --- a/src/shopware/app.rs +++ b/src/shopware/app.rs @@ -1,6 +1,6 @@ //! App container pause/resume and post-restore hints (recipes `lib/sync-app.sh`). -use super::env::{vps_project_name_opt, ShopEnv}; +use super::env::ShopEnv; use super::error::Error; use super::mysql::{compose_argv, require_docker}; use std::path::Path; @@ -11,7 +11,6 @@ const APP_SERVICES: &[&str] = &["web", "worker", "scheduler"]; pub fn stop_app_containers( compose_dir: &Path, files: &[String], - project: Option<&str>, dry_run: bool, ) -> Result, Error> { if dry_run { @@ -22,7 +21,7 @@ pub fn stop_app_containers( return Ok(Vec::new()); } require_docker()?; - let mut args = compose_argv(files, project); + let mut args = compose_argv(compose_dir, files); args.extend([ "--profile".into(), "worker".into(), @@ -52,8 +51,8 @@ pub fn stop_app_containers( continue; } println!("==> Stopping {svc} for restore"); - if !compose_stop(compose_dir, files, project, svc) { - let mut with_profile = compose_argv(files, project); + if !compose_stop(compose_dir, files, svc) { + let mut with_profile = compose_argv(compose_dir, files); with_profile.extend([ "--profile".into(), (*svc).into(), @@ -72,8 +71,8 @@ pub fn stop_app_containers( Ok(stopped) } -fn compose_stop(compose_dir: &Path, files: &[String], project: Option<&str>, svc: &str) -> bool { - let mut args = compose_argv(files, project); +fn compose_stop(compose_dir: &Path, files: &[String], svc: &str) -> bool { + let mut args = compose_argv(compose_dir, files); args.extend(["stop".into(), svc.into()]); Command::new("docker") .args(&args) @@ -88,7 +87,6 @@ fn compose_stop(compose_dir: &Path, files: &[String], project: Option<&str>, svc pub fn start_stopped_app( compose_dir: &Path, files: &[String], - project: Option<&str>, stopped: &[String], dry_run: bool, ) -> Result<(), Error> { @@ -101,7 +99,7 @@ pub fn start_stopped_app( continue; } println!("==> Starting {svc}"); - let mut args = compose_argv(files, project); + let mut args = compose_argv(compose_dir, files); match svc.as_str() { "worker" => { args.extend([ @@ -178,8 +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 project = vps_project_name_opt(env); - let mut args = compose_argv(files, project.as_deref()); + 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 d98a3e8..fddd729 100644 --- a/src/shopware/compose.rs +++ b/src/shopware/compose.rs @@ -13,32 +13,19 @@ //! 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, ENV_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}; -/// `--env-file` flags: always `.env`, then `.env.local` / `.env.prod` if present. -pub fn vps_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 -} - /// 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(vps_env_file_flags(compose_dir)); + a.extend(compose_env_file_flags(compose_dir)); for f in COMPOSE_FILES { a.push("-f".into()); a.push((*f).to_string()); diff --git a/src/shopware/env.rs b/src/shopware/env.rs index 514f5f9..87643bb 100644 --- a/src/shopware/env.rs +++ b/src/shopware/env.rs @@ -42,9 +42,22 @@ const PROCESS_WINS: &[&str] = &[ ]; /// Root `.env.*` only. Later file wins. Never `deploy/*.env`. -/// Same order as VPS `docker compose --env-file` flags. +/// 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", "deploy/compose.prod.yaml", diff --git a/src/shopware/import.rs b/src/shopware/import.rs index 278e05f..8faead6 100644 --- a/src/shopware/import.rs +++ b/src/shopware/import.rs @@ -6,7 +6,7 @@ use super::env::{ compose_mentions_mysql_service, existing_compose_files, require_shop_id, resolve_compose_dir, - vps_project_name, ShopEnv, + ShopEnv, }; use super::error::Error; use super::live::{assert_not_live, LivePolicy, LiveSignals}; @@ -130,10 +130,13 @@ impl ImportPlan { pub fn log_line(&self) -> 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, self.compose_project().as_deref()) + compose_cli_log(compose_dir, compose_files) ) } ImportTarget::External { @@ -147,12 +150,6 @@ impl ImportPlan { pub fn log_contains_secret(&self, text: &str) -> bool { log_contains_secret(text, &self.secrets) } - - fn compose_project(&self) -> Option { - self.deploy_env - .as_ref() - .map(|e| vps_project_name(&self.shop_id, e)) - } } pub fn run(args: DbImportArgs) -> Result<(), Error> { @@ -363,9 +360,8 @@ pub fn execute(plan: &ImportPlan) -> Result<(), Error> { compose_dir, compose_files, } => { - let project = plan.compose_project(); - compose_up_mysql(compose_dir, compose_files, project.as_deref())?; - run_bundled(plan, compose_dir, compose_files, project.as_deref())?; + compose_up_mysql(compose_dir, compose_files)?; + run_bundled(plan, compose_dir, compose_files)?; } ImportTarget::External { .. } => run_external(plan)?, } @@ -373,8 +369,8 @@ pub fn execute(plan: &ImportPlan) -> Result<(), Error> { Ok(()) } -fn bundled_exec_args(files: &[String], project: Option<&str>) -> Vec { - let mut a = super::mysql::compose_argv(files, project); +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(), @@ -428,13 +424,8 @@ fn external_run_args(target: &ImportTarget) -> Result, Error> { Ok(a) } -fn run_bundled( - plan: &ImportPlan, - compose_dir: &Path, - files: &[String], - project: Option<&str>, -) -> Result<(), Error> { - let args = bundled_exec_args(files, project); +fn run_bundled(plan: &ImportPlan, compose_dir: &Path, files: &[String]) -> Result<(), Error> { + let args = bundled_exec_args(compose_dir, files); pipe_sql_into_docker(plan, &args, Some(compose_dir), None) } @@ -605,12 +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.contains("-p acme-staging"), "{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/mysql.rs b/src/shopware/mysql.rs index 02c226a..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,36 +156,31 @@ pub fn client_image_for_url(scheme: &str, _env: &ShopEnv) -> String { } } -/// `docker compose --env-file .env -f …` plus `-p ` when set. +/// `docker compose --env-file … -f …` for db import / rewrite / restore. /// -/// `-p` is Compose's highest-precedence project name and wins over leftover -/// `COMPOSE_PROJECT_NAME` in `.env`. -pub fn compose_argv(files: &[String], project: Option<&str>) -> Vec { - let mut a = vec!["compose".into(), "--env-file".into(), ".env".into()]; +/// 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()); } - pin_compose_project(&mut a, project); a } -pub fn compose_cli_log(files: &[String], project: Option<&str>) -> String { +pub fn compose_cli_log(compose_dir: &Path, files: &[String]) -> String { let mut s = String::from("docker"); - for a in compose_argv(files, project) { + for a in compose_argv(compose_dir, files) { s.push(' '); s.push_str(&a); } s } -fn pin_compose_project(args: &mut Vec, project: Option<&str>) { - if let Some(p) = project.map(str::trim).filter(|s| !s.is_empty()) { - args.push("-p".into()); - args.push(p.to_string()); - } -} - pub fn require_docker() -> Result<(), Error> { match Command::new("docker") .arg("info") @@ -217,17 +212,13 @@ pub fn require_gzip() -> Result<(), Error> { } } -pub fn compose_up_mysql( - compose_dir: &Path, - files: &[String], - project: Option<&str>, -) -> Result<(), Error> { +pub fn compose_up_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Error> { if files.is_empty() { return Err(Error::fail( "No compose files found under shop root; cannot start service mysql.", )); } - let mut args = compose_argv(files, project); + let mut args = compose_argv(compose_dir, files); args.extend([ "up".into(), "-d".into(), @@ -244,11 +235,11 @@ pub fn compose_up_mysql( "docker compose up mysql failed. Is Docker running, and is the mysql service defined?", )); } - wait_mysql(compose_dir, files, project) + wait_mysql(compose_dir, files) } -fn wait_mysql(compose_dir: &Path, files: &[String], project: Option<&str>) -> Result<(), Error> { - let mut args = compose_argv(files, project); +fn wait_mysql(compose_dir: &Path, files: &[String]) -> Result<(), Error> { + let mut args = compose_argv(compose_dir, files); args.extend([ "exec".into(), "-T".into(), @@ -378,12 +369,21 @@ mod tests { } #[test] - fn compose_argv_pins_vps_project_after_files() { + fn compose_argv_loads_host_env_files_without_project_flag() { let files = vec![ "deploy/compose.yaml".into(), "deploy/compose.prod.yaml".into(), ]; - let a = compose_argv(&files, Some("acme-staging")); + 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![ @@ -394,18 +394,35 @@ mod tests { "deploy/compose.yaml", "-f", "deploy/compose.prod.yaml", - "-p", - "acme-staging", ] ); - let log = compose_cli_log(&files, Some("acme-live")); - assert!(log.contains("-p acme-live"), "{log}"); + 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}" ); - let plain = compose_argv(&files, None); - assert!(!plain.iter().any(|s| s == "-p")); + 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] diff --git a/src/shopware/restore.rs b/src/shopware/restore.rs index ad8b448..d322acc 100644 --- a/src/shopware/restore.rs +++ b/src/shopware/restore.rs @@ -7,7 +7,7 @@ use super::data::{normalize_data, DataSelection}; use super::env::{ existing_compose_files, require_shop_id, resolve_compose_dir, resolve_data_root, - resolve_snapshot_dir, vps_project_name_opt, ShopEnv, + resolve_snapshot_dir, ShopEnv, }; use super::error::Error; use super::import::{self, ImportPlan}; @@ -41,7 +41,6 @@ pub enum RewriteAction { pub struct RestorePlan { pub compose_dir: PathBuf, pub compose_files: Vec, - pub compose_project: Option, pub shop_id: String, pub deploy_env: Option, pub snapshot_dir: PathBuf, @@ -183,7 +182,6 @@ pub fn plan_with_env( Ok(RestorePlan { compose_dir, compose_files, - compose_project: vps_project_name_opt(env), shop_id, deploy_env: env.get("SHOPWARE_DEPLOY_ENV").map(str::to_string), snapshot_dir, @@ -221,12 +219,7 @@ pub fn execute(plan: &RestorePlan) -> Result<(), Error> { if plan.dry_run { 1 } else { 0 }, ); - let stopped = stop_app_containers( - &plan.compose_dir, - &plan.compose_files, - plan.compose_project.as_deref(), - plan.dry_run, - )?; + let stopped = stop_app_containers(&plan.compose_dir, &plan.compose_files, plan.dry_run)?; if let Some(imp) = &plan.import { import::execute(imp)?; @@ -273,7 +266,6 @@ pub fn execute(plan: &RestorePlan) -> Result<(), Error> { start_stopped_app( &plan.compose_dir, &plan.compose_files, - plan.compose_project.as_deref(), &stopped, plan.dry_run, )?; @@ -308,7 +300,6 @@ fn run_rewrite(compose_dir: &Path, docker_args: &[String]) -> Result<(), Error> fn stop_app_containers( compose_dir: &Path, files: &[String], - project: Option<&str>, dry_run: bool, ) -> Result, Error> { if dry_run { @@ -318,24 +309,20 @@ fn stop_app_containers( if files.is_empty() { return Ok(Vec::new()); } - let running = list_running_app_services(compose_dir, files, project); + let running = list_running_app_services(compose_dir, files); let mut stopped = Vec::new(); for svc in ["web", "worker", "scheduler"] { if running.iter().any(|s| s == svc) { println!("==> Stopping {svc} for restore"); - compose_stop(compose_dir, files, project, svc); + compose_stop(compose_dir, files, svc); stopped.push(svc.to_string()); } } Ok(stopped) } -fn list_running_app_services( - compose_dir: &Path, - files: &[String], - project: Option<&str>, -) -> Vec { - let mut args = compose_argv(files, project); +fn list_running_app_services(compose_dir: &Path, files: &[String]) -> Vec { + let mut args = compose_argv(compose_dir, files); args.extend([ "--profile".into(), "worker".into(), @@ -362,8 +349,8 @@ fn list_running_app_services( .collect() } -fn compose_stop(compose_dir: &Path, files: &[String], project: Option<&str>, svc: &str) { - let mut args = compose_argv(files, project); +fn compose_stop(compose_dir: &Path, files: &[String], svc: &str) { + let mut args = compose_argv(compose_dir, files); args.extend(["stop".into(), svc.to_string()]); let ok = Command::new("docker") .args(&args) @@ -376,7 +363,7 @@ fn compose_stop(compose_dir: &Path, files: &[String], project: Option<&str>, svc if ok { return; } - let mut args = compose_argv(files, project); + let mut args = compose_argv(compose_dir, files); args.extend([ "--profile".into(), svc.to_string(), @@ -394,7 +381,6 @@ fn compose_stop(compose_dir: &Path, files: &[String], project: Option<&str>, svc fn start_stopped_app( compose_dir: &Path, files: &[String], - project: Option<&str>, stopped: &[String], dry_run: bool, ) -> Result<(), Error> { @@ -405,12 +391,12 @@ fn start_stopped_app( } println!("==> Starting {svc}"); match svc.as_str() { - "web" => compose_up(compose_dir, files, project, None, "web")?, + "web" => compose_up(compose_dir, files, None, "web")?, "worker" => { - let _ = compose_up(compose_dir, files, project, Some("worker"), "worker"); + let _ = compose_up(compose_dir, files, Some("worker"), "worker"); } "scheduler" => { - let _ = compose_up(compose_dir, files, project, Some("scheduler"), "scheduler"); + let _ = compose_up(compose_dir, files, Some("scheduler"), "scheduler"); } _ => {} } @@ -421,11 +407,10 @@ fn start_stopped_app( fn compose_up( compose_dir: &Path, files: &[String], - project: Option<&str>, profile: Option<&str>, svc: &str, ) -> Result<(), Error> { - let mut args = compose_argv(files, project); + let mut args = compose_argv(compose_dir, files); if let Some(p) = profile { args.extend(["--profile".into(), p.to_string()]); } @@ -474,20 +459,14 @@ fn post_restore_hints(plan: &RestorePlan) { } if plan.image.is_some() { println!("==> Trying cache:clear (non-fatal if the image/console is unavailable)"); - if cache_clear( - &plan.compose_dir, - &plan.compose_files, - plan.compose_project.as_deref(), - ) - .is_err() - { + if cache_clear(&plan.compose_dir, &plan.compose_files).is_err() { println!("==> cache:clear skipped or failed — not fatal"); } } } -fn cache_clear(compose_dir: &Path, files: &[String], project: Option<&str>) -> Result<(), Error> { - let mut args = compose_argv(files, project); +fn cache_clear(compose_dir: &Path, files: &[String]) -> Result<(), Error> { + let mut args = compose_argv(compose_dir, files); args.extend([ "run".into(), "--rm".into(), @@ -716,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 b5b038c..ed85088 100644 --- a/src/shopware/rewrite.rs +++ b/src/shopware/rewrite.rs @@ -3,7 +3,7 @@ //! Target URL is `APP_URL`. On live, rewrite is skipped (APP_URL is a shop //! runtime var, not a restore opt-in — refusing it would block live DR). -use super::env::{existing_compose_files, vps_project_name_opt, ShopEnv}; +use super::env::{existing_compose_files, ShopEnv}; use super::error::Error; use super::live::LiveSignals; use super::mysql::{compose_argv, compose_cli_log, require_docker}; @@ -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, vps_project_name_opt(env).as_deref()); + 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, vps_project_name_opt(env).as_deref()), + 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, vps_project_name_opt(env).as_deref()); + let mut a = compose_argv(compose_dir, files); a.extend([ "run".into(), "--rm".into(), @@ -231,8 +231,14 @@ mod tests { line.contains("run --rm --pull never --entrypoint php"), "{line}" ); - assert!(line.contains("-p acme-staging"), "{line}"); - assert!(!line.contains("-p shopware-acme"), "{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"), @@ -240,10 +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.windows(2).any(|w| w == ["-p", "acme-staging"])); + 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/sync.rs b/src/shopware/sync.rs index 97a9de8..9fcb5fd 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, vps_project_name_opt, ShopEnv, + resolve_compose_dir, resolve_snapshot_dir, ShopEnv, }; use super::error::Error; use super::import; @@ -139,24 +139,13 @@ fn run_local( return Err(Error::fail(dump_operator_instructions(snapshot_dir))); } - let stopped = app::stop_app_containers( - compose_dir, - compose_files, - vps_project_name_opt(env).as_deref(), - dry_run, - )?; + let stopped = app::stop_app_containers(compose_dir, compose_files, dry_run)?; let imported = import_db_if_present(env, cwd, selection, snapshot_dir, dry_run)?; rewrite::maybe_rewrite(env, signals, compose_dir, compose_files, imported, dry_run)?; for logical in &selection.volumes { volumes::sync_bind_local_roundtrip(env, data_root, snapshot_dir, logical, dry_run)?; } - app::start_stopped_app( - compose_dir, - compose_files, - vps_project_name_opt(env).as_deref(), - &stopped, - dry_run, - )?; + app::start_stopped_app(compose_dir, compose_files, &stopped, dry_run)?; app::post_restore_hints( env, rewrite::requested(env), @@ -202,12 +191,7 @@ fn run_remote( return Err(Error::fail(dump_operator_instructions(snapshot_dir))); } - let stopped = app::stop_app_containers( - compose_dir, - compose_files, - vps_project_name_opt(env).as_deref(), - dry_run, - )?; + let stopped = app::stop_app_containers(compose_dir, compose_files, dry_run)?; let imported = import_db_if_present(env, cwd, selection, snapshot_dir, dry_run)?; rewrite::maybe_rewrite(env, signals, compose_dir, compose_files, imported, dry_run)?; for logical in &selection.volumes { @@ -221,13 +205,7 @@ fn run_remote( dry_run, )?; } - app::start_stopped_app( - compose_dir, - compose_files, - vps_project_name_opt(env).as_deref(), - &stopped, - dry_run, - )?; + app::start_stopped_app(compose_dir, compose_files, &stopped, dry_run)?; app::post_restore_hints( env, rewrite::requested(env), diff --git a/tests/import.rs b/tests/import.rs index fb8a33a..b5d3fe4 100644 --- a/tests/import.rs +++ b/tests/import.rs @@ -172,10 +172,43 @@ 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.contains("-p acme-staging"), "{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] fn dry_run_sql_uses_cat() { let shop = TempShop::new("sql"); 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] From fe6b881a0ac885217dba408210bbd35bffee10e9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 17 Sep 2026 09:31:42 +0000 Subject: [PATCH 9/9] fix: restore sync log import of vps_project_name_opt Named-volume / operator log still prints {shop-id}-{env}; compose argv does not take -p. Co-authored-by: ROBJkE --- src/shopware/sync.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shopware/sync.rs b/src/shopware/sync.rs index 9fcb5fd..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;