Skip to main content

phoenix_cli/
release.rs

1#![allow(
2    clippy::missing_errors_doc,
3    clippy::needless_pass_by_value,
4    clippy::too_many_lines,
5    clippy::map_unwrap_or
6)]
7
8use std::{
9    env,
10    ffi::OsString,
11    fs,
12    path::{Path, PathBuf},
13    process::Command,
14};
15
16use phoenix_release::{
17    DeployStatus, InstallOptions, InstallSource, PackOptions, ReleaseError, RollbackOptions,
18    StagingSources, create_tarball, extract_tarball, install, rollback, status, write_staging,
19};
20
21use crate::ProjectGenerator;
22
23pub fn release_build(args: Vec<String>) -> Result<(), String> {
24    let options = parse_build_args(args)?;
25    let generator = ProjectGenerator::discover(env::current_dir().map_err(|e| e.to_string())?)
26        .map_err(|e| e.to_string())?;
27    let root = generator.root();
28
29    let package = read_cargo_package(root)?;
30    let version = options
31        .version
32        .clone()
33        .unwrap_or_else(|| package.version.clone());
34    let binary_name = options
35        .bin
36        .clone()
37        .unwrap_or_else(|| package.default_run.unwrap_or(package.name.clone()));
38    let target_triple = options.target.clone().unwrap_or_else(host_triple);
39    let output = options
40        .output
41        .clone()
42        .unwrap_or_else(|| root.join("dist/releases").join(&version));
43    let staging_dir = output.join("staging");
44
45    if !options.skip_types && root.join("node_modules").is_dir() {
46        run_command("npm", &["run", "types"], root, "npm run types")?;
47    }
48    if !options.skip_npm && root.join("node_modules").is_dir() {
49        run_command("npm", &["run", "build"], root, "npm run build")?;
50    }
51
52    // Database-less scaffolds omit `src/bin/phoenix-manage.rs`; only build it when present.
53    let has_manage = root.join("src/bin/phoenix-manage.rs").is_file();
54
55    let mut cargo_args = vec!["build".to_owned(), "--release".to_owned()];
56    if let Some(target) = &options.target {
57        cargo_args.push("--target".to_owned());
58        cargo_args.push(target.clone());
59    }
60    cargo_args.push("--bin".to_owned());
61    cargo_args.push(binary_name.clone());
62    if has_manage {
63        cargo_args.push("--bin".to_owned());
64        cargo_args.push("phoenix-manage".to_owned());
65    }
66
67    let cargo = env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo"));
68    run_command_strings(
69        &cargo.to_string_lossy(),
70        &cargo_args,
71        root,
72        "cargo build --release",
73    )?;
74
75    let release_dir = release_profile_dir(root, options.target.as_deref());
76    let binary_path = release_dir.join(&binary_name);
77    if !binary_path.is_file() {
78        return Err(format!(
79            "release binary missing at {}",
80            binary_path.display()
81        ));
82    }
83    let manage_path = if has_manage {
84        let path = release_dir.join("phoenix-manage");
85        if !path.is_file() {
86            return Err(format!(
87                "phoenix-manage binary missing at {}",
88                path.display()
89            ));
90        }
91        Some(path)
92    } else {
93        None
94    };
95
96    let public_assets = ensure_dir(root.join("public/assets"))?;
97    let public_ssr = ensure_dir(root.join("public/ssr"))?;
98    let public_static_dirs = list_public_static_dirs(&root.join("public"))?;
99    let config = ensure_dir(root.join("config"))?;
100    let migrations = ensure_dir(root.join("database/migrations"))?;
101
102    let client_manifest = root.join("public/assets/phoenix-manifest.json");
103    let ssr_manifest = root.join("public/ssr/phoenix-renderer.json");
104    let contract_hash = read_json_str_field(&client_manifest, "contract_hash")
105        .or_else(|| read_json_str_field(&ssr_manifest, "contract_hash"));
106
107    let manifest = write_staging(
108        &PackOptions {
109            version: version.clone(),
110            app_name: package.name.clone(),
111            binary_name: binary_name.clone(),
112            target_triple: target_triple.clone(),
113            staging_dir: staging_dir.clone(),
114            git_revision: git_revision(root),
115            client_manifest: read_json_str_field(&client_manifest, "version")
116                .map(|_| "public/assets/phoenix-manifest.json".to_owned()),
117            ssr_manifest: read_json_str_field(&ssr_manifest, "version")
118                .map(|_| "public/ssr/phoenix-renderer.json".to_owned()),
119            contract_hash,
120            rustc_version: rustc_version(),
121            profile: Some("release".to_owned()),
122            npm_build: if options.skip_npm {
123                None
124            } else {
125                Some("npm run build".to_owned())
126            },
127        },
128        &StagingSources {
129            binary: binary_path,
130            phoenix_manage: manage_path,
131            public_assets,
132            public_ssr,
133            public_static_dirs,
134            config,
135            migrations,
136        },
137    )
138    // manage_path is already Option<PathBuf>
139    .map_err(release_err)?;
140
141    println!("STAGING {}", staging_dir.display());
142    println!("MANIFEST {}", staging_dir.join("manifest.toml").display());
143    println!("VERSION {}", manifest.version);
144
145    if options.tarball {
146        fs::create_dir_all(&output).map_err(|e| e.to_string())?;
147        let tarball = output.join(format!("{}-{}.tar.gz", package.name, version));
148        let digest = create_tarball(&staging_dir, &tarball).map_err(release_err)?;
149        println!("TARBALL {}", tarball.display());
150        println!("SHA256 {digest}");
151    }
152
153    Ok(())
154}
155
156pub fn release_install(args: Vec<String>) -> Result<(), String> {
157    let options = parse_install_args(args)?;
158    let deploy_root = resolve_deploy_root(options.deploy_root)?;
159    let version = resolve_install_version(options.version.as_deref(), &options.source)?;
160    let source = match options.source {
161        InstallSourceKind::Tarball(path) => InstallSource::Tarball(path),
162        InstallSourceKind::Path(path) => InstallSource::Path(path),
163    };
164
165    let report = install(InstallOptions {
166        deploy_root: deploy_root.clone(),
167        version: version.clone(),
168        source,
169        skip_migrate: options.skip_migrate,
170        no_switch: options.no_switch,
171        restart_cmd: options.restart_cmd.clone(),
172        dry_run: options.dry_run,
173    })
174    .map_err(release_err)?;
175
176    if options.dry_run {
177        println!("DRY RUN install {version} into {}", deploy_root.display());
178    }
179    println!("INSTALLED {}", report.version);
180    println!("RELEASE_DIR {}", report.release_dir.display());
181    if let Some(previous) = report.previous_version {
182        println!("PREVIOUS {previous}");
183    }
184    println!(
185        "SWITCHED={} MIGRATED={} RESTARTED={}",
186        report.switched, report.migrated, report.restarted
187    );
188    Ok(())
189}
190
191pub fn release_rollback(args: Vec<String>) -> Result<(), String> {
192    let options = parse_rollback_args(args)?;
193    let deploy_root = resolve_deploy_root(options.deploy_root)?;
194
195    let report = rollback(RollbackOptions {
196        deploy_root: deploy_root.clone(),
197        to: options.to,
198        steps: options.steps,
199        restart_cmd: options.restart_cmd,
200        skip_restart: options.skip_restart,
201        dry_run: options.dry_run,
202    })
203    .map_err(release_err)?;
204
205    if options.dry_run {
206        println!("DRY RUN rollback on {}", deploy_root.display());
207    }
208    if let Some(from) = report.from {
209        println!("FROM {from}");
210    }
211    println!("TO {}", report.to);
212    println!("RESTARTED={}", report.restarted);
213    Ok(())
214}
215
216pub fn release_status(args: Vec<String>) -> Result<(), String> {
217    let options = parse_status_args(args)?;
218    let deploy_root = resolve_deploy_root(options.deploy_root)?;
219    let snapshot = status(&deploy_root).map_err(release_err)?;
220
221    if options.json {
222        print_status_json(&snapshot);
223    } else {
224        print_status_human(&deploy_root, &snapshot);
225    }
226    Ok(())
227}
228
229struct CargoPackage {
230    name: String,
231    version: String,
232    default_run: Option<String>,
233}
234
235struct BuildOptions {
236    version: Option<String>,
237    output: Option<PathBuf>,
238    tarball: bool,
239    bin: Option<String>,
240    skip_npm: bool,
241    skip_types: bool,
242    target: Option<String>,
243}
244
245enum InstallSourceKind {
246    Tarball(PathBuf),
247    Path(PathBuf),
248}
249
250struct InstallOptionsParsed {
251    deploy_root: Option<PathBuf>,
252    source: InstallSourceKind,
253    version: Option<String>,
254    skip_migrate: bool,
255    no_switch: bool,
256    restart_cmd: Option<String>,
257    dry_run: bool,
258}
259
260struct RollbackOptionsParsed {
261    deploy_root: Option<PathBuf>,
262    to: Option<String>,
263    steps: usize,
264    restart_cmd: Option<String>,
265    skip_restart: bool,
266    dry_run: bool,
267}
268
269struct StatusOptions {
270    deploy_root: Option<PathBuf>,
271    json: bool,
272}
273
274fn parse_build_args(args: Vec<String>) -> Result<BuildOptions, String> {
275    let mut options = BuildOptions {
276        version: None,
277        output: None,
278        tarball: false,
279        bin: None,
280        skip_npm: false,
281        skip_types: false,
282        target: None,
283    };
284    let mut index = 0;
285    while index < args.len() {
286        match args[index].as_str() {
287            "--version" => {
288                index += 1;
289                options.version = Some(next_value(&args, index, "--version")?);
290            }
291            "--output" => {
292                index += 1;
293                options.output = Some(PathBuf::from(next_value(&args, index, "--output")?));
294            }
295            "--tarball" => options.tarball = true,
296            "--bin" => {
297                index += 1;
298                options.bin = Some(next_value(&args, index, "--bin")?);
299            }
300            "--skip-npm" => options.skip_npm = true,
301            "--skip-types" => options.skip_types = true,
302            "--target" => {
303                index += 1;
304                options.target = Some(next_value(&args, index, "--target")?);
305            }
306            flag if flag.starts_with("--version=") => {
307                options.version = Some(flag["--version=".len()..].to_owned());
308            }
309            flag if flag.starts_with("--output=") => {
310                options.output = Some(PathBuf::from(flag["--output=".len()..].to_owned()));
311            }
312            flag if flag.starts_with("--bin=") => {
313                options.bin = Some(flag["--bin=".len()..].to_owned());
314            }
315            flag if flag.starts_with("--target=") => {
316                options.target = Some(flag["--target=".len()..].to_owned());
317            }
318            flag => return Err(format!("unknown release option `{flag}`")),
319        }
320        index += 1;
321    }
322    Ok(options)
323}
324
325fn parse_install_args(args: Vec<String>) -> Result<InstallOptionsParsed, String> {
326    let mut options = InstallOptionsParsed {
327        deploy_root: None,
328        source: InstallSourceKind::Path(PathBuf::from(".")),
329        version: None,
330        skip_migrate: false,
331        no_switch: false,
332        restart_cmd: None,
333        dry_run: false,
334    };
335    let mut has_source = false;
336    let mut index = 0;
337    while index < args.len() {
338        match args[index].as_str() {
339            "--deploy-root" => {
340                index += 1;
341                options.deploy_root =
342                    Some(PathBuf::from(next_value(&args, index, "--deploy-root")?));
343            }
344            "--tarball" => {
345                index += 1;
346                let path = PathBuf::from(next_value(&args, index, "--tarball")?);
347                options.source = InstallSourceKind::Tarball(path);
348                has_source = true;
349            }
350            "--path" => {
351                index += 1;
352                let path = PathBuf::from(next_value(&args, index, "--path")?);
353                options.source = InstallSourceKind::Path(path);
354                has_source = true;
355            }
356            "--version" => {
357                index += 1;
358                options.version = Some(next_value(&args, index, "--version")?);
359            }
360            "--skip-migrate" => options.skip_migrate = true,
361            "--no-switch" => options.no_switch = true,
362            "--restart-cmd" => {
363                index += 1;
364                options.restart_cmd = Some(next_value(&args, index, "--restart-cmd")?);
365            }
366            "--dry-run" => options.dry_run = true,
367            flag if flag.starts_with("--deploy-root=") => {
368                options.deploy_root =
369                    Some(PathBuf::from(flag["--deploy-root=".len()..].to_owned()));
370            }
371            flag if flag.starts_with("--tarball=") => {
372                options.source = InstallSourceKind::Tarball(PathBuf::from(
373                    flag["--tarball=".len()..].to_owned(),
374                ));
375                has_source = true;
376            }
377            flag if flag.starts_with("--path=") => {
378                options.source =
379                    InstallSourceKind::Path(PathBuf::from(flag["--path=".len()..].to_owned()));
380                has_source = true;
381            }
382            flag if flag.starts_with("--version=") => {
383                options.version = Some(flag["--version=".len()..].to_owned());
384            }
385            flag if flag.starts_with("--restart-cmd=") => {
386                options.restart_cmd = Some(flag["--restart-cmd=".len()..].to_owned());
387            }
388            flag => return Err(format!("unknown release:install option `{flag}`")),
389        }
390        index += 1;
391    }
392    if !has_source {
393        return Err("release:install requires --tarball <path> or --path <dir>".to_owned());
394    }
395    Ok(options)
396}
397
398fn parse_rollback_args(args: Vec<String>) -> Result<RollbackOptionsParsed, String> {
399    let mut options = RollbackOptionsParsed {
400        deploy_root: None,
401        to: None,
402        steps: 1,
403        restart_cmd: None,
404        skip_restart: false,
405        dry_run: false,
406    };
407    let mut index = 0;
408    while index < args.len() {
409        match args[index].as_str() {
410            "--deploy-root" => {
411                index += 1;
412                options.deploy_root =
413                    Some(PathBuf::from(next_value(&args, index, "--deploy-root")?));
414            }
415            "--to" => {
416                index += 1;
417                options.to = Some(next_value(&args, index, "--to")?);
418            }
419            "--steps" => {
420                index += 1;
421                options.steps = parse_steps(&next_value(&args, index, "--steps")?)?;
422            }
423            "--restart-cmd" => {
424                index += 1;
425                options.restart_cmd = Some(next_value(&args, index, "--restart-cmd")?);
426            }
427            "--skip-restart" => options.skip_restart = true,
428            "--dry-run" => options.dry_run = true,
429            flag if flag.starts_with("--deploy-root=") => {
430                options.deploy_root =
431                    Some(PathBuf::from(flag["--deploy-root=".len()..].to_owned()));
432            }
433            flag if flag.starts_with("--to=") => {
434                options.to = Some(flag["--to=".len()..].to_owned());
435            }
436            flag if flag.starts_with("--steps=") => {
437                options.steps = parse_steps(&flag["--steps=".len()..])?;
438            }
439            flag if flag.starts_with("--restart-cmd=") => {
440                options.restart_cmd = Some(flag["--restart-cmd=".len()..].to_owned());
441            }
442            flag => return Err(format!("unknown release:rollback option `{flag}`")),
443        }
444        index += 1;
445    }
446    Ok(options)
447}
448
449fn parse_status_args(args: Vec<String>) -> Result<StatusOptions, String> {
450    let mut options = StatusOptions {
451        deploy_root: None,
452        json: false,
453    };
454    let mut index = 0;
455    while index < args.len() {
456        match args[index].as_str() {
457            "--deploy-root" => {
458                index += 1;
459                options.deploy_root =
460                    Some(PathBuf::from(next_value(&args, index, "--deploy-root")?));
461            }
462            "--json" => options.json = true,
463            flag if flag.starts_with("--deploy-root=") => {
464                options.deploy_root =
465                    Some(PathBuf::from(flag["--deploy-root=".len()..].to_owned()));
466            }
467            flag => return Err(format!("unknown release:status option `{flag}`")),
468        }
469        index += 1;
470    }
471    Ok(options)
472}
473
474fn next_value(args: &[String], index: usize, flag: &str) -> Result<String, String> {
475    args.get(index)
476        .cloned()
477        .ok_or_else(|| format!("{flag} requires a value"))
478}
479
480fn parse_steps(value: &str) -> Result<usize, String> {
481    value
482        .parse::<usize>()
483        .ok()
484        .filter(|steps| *steps > 0)
485        .ok_or_else(|| "rollback steps must be a positive integer".to_owned())
486}
487
488fn resolve_deploy_root(explicit: Option<PathBuf>) -> Result<PathBuf, String> {
489    if let Some(path) = explicit {
490        return Ok(path);
491    }
492    env::var("PHOENIX_DEPLOY_ROOT")
493        .map(PathBuf::from)
494        .map_err(|_| {
495            "deploy root is required; pass --deploy-root or set PHOENIX_DEPLOY_ROOT".to_owned()
496        })
497}
498
499fn resolve_install_version(
500    explicit: Option<&str>,
501    source: &InstallSourceKind,
502) -> Result<String, String> {
503    if let Some(version) = explicit {
504        return Ok(version.to_owned());
505    }
506    match source {
507        InstallSourceKind::Path(path) => manifest_version_at(path),
508        InstallSourceKind::Tarball(path) => {
509            let temp = env::temp_dir().join(format!(
510                "px-release-install-{}-{}",
511                std::process::id(),
512                path.file_name()
513                    .and_then(|name| name.to_str())
514                    .unwrap_or("tarball")
515            ));
516            if temp.exists() {
517                fs::remove_dir_all(&temp).map_err(|e| e.to_string())?;
518            }
519            extract_tarball(path, &temp).map_err(release_err)?;
520            let version = manifest_version_at(&temp)?;
521            let _ = fs::remove_dir_all(&temp);
522            Ok(version)
523        }
524    }
525}
526
527fn manifest_version_at(path: &Path) -> Result<String, String> {
528    let manifest_path = path.join("manifest.toml");
529    if !manifest_path.is_file() {
530        return Err(format!(
531            "manifest missing at {}; pass --version explicitly",
532            manifest_path.display()
533        ));
534    }
535    let text = fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?;
536    for line in text.lines() {
537        let line = line.trim();
538        if line.starts_with("version = ") {
539            return parse_toml_string_value(line.strip_prefix("version = ").unwrap_or(line));
540        }
541    }
542    Err(format!(
543        "could not read version from {}; pass --version explicitly",
544        manifest_path.display()
545    ))
546}
547
548fn read_cargo_package(root: &Path) -> Result<CargoPackage, String> {
549    let cargo_toml = root.join("Cargo.toml");
550    let text = fs::read_to_string(&cargo_toml)
551        .map_err(|error| format!("failed to read {}: {error}", cargo_toml.display()))?;
552    let mut in_package = false;
553    let mut name = None;
554    let mut version = None;
555    let mut default_run = None;
556    for line in text.lines() {
557        let trimmed = line.trim();
558        if trimmed.starts_with('[') && trimmed.ends_with(']') {
559            in_package = trimmed == "[package]";
560            continue;
561        }
562        if !in_package {
563            continue;
564        }
565        if let Some(value) = trimmed.strip_prefix("name = ") {
566            name = Some(parse_toml_string_value(value)?);
567        } else if let Some(value) = trimmed.strip_prefix("version = ") {
568            version = Some(parse_toml_string_value(value)?);
569        } else if let Some(value) = trimmed.strip_prefix("default-run = ") {
570            default_run = Some(parse_toml_string_value(value)?);
571        }
572    }
573    Ok(CargoPackage {
574        name: name.ok_or("Cargo.toml [package] name is missing")?,
575        version: version.ok_or("Cargo.toml [package] version is missing")?,
576        default_run,
577    })
578}
579
580fn parse_toml_string_value(raw: &str) -> Result<String, String> {
581    let raw = raw.trim();
582    if raw.starts_with('"') && raw.ends_with('"') && raw.len() >= 2 {
583        Ok(raw[1..raw.len() - 1].to_owned())
584    } else {
585        Err(format!("expected quoted TOML string, got `{raw}`"))
586    }
587}
588
589fn release_profile_dir(root: &Path, target: Option<&str>) -> PathBuf {
590    match target {
591        Some(triple) => root.join("target").join(triple).join("release"),
592        None => root.join("target/release"),
593    }
594}
595
596fn ensure_dir(path: PathBuf) -> Result<PathBuf, String> {
597    if !path.exists() {
598        fs::create_dir_all(&path)
599            .map_err(|error| format!("failed to create directory {}: {error}", path.display()))?;
600    }
601    Ok(path)
602}
603
604/// Collect `public/*` directories that are not Vite build outputs (`assets` / `ssr`).
605fn list_public_static_dirs(public_root: &Path) -> Result<Vec<PathBuf>, String> {
606    if !public_root.is_dir() {
607        return Ok(Vec::new());
608    }
609    let mut dirs = Vec::new();
610    let entries = fs::read_dir(public_root).map_err(|error| {
611        format!(
612            "failed to read public directory {}: {error}",
613            public_root.display()
614        )
615    })?;
616    for entry in entries {
617        let entry = entry.map_err(|error| {
618            format!(
619                "failed to read public directory entry under {}: {error}",
620                public_root.display()
621            )
622        })?;
623        let path = entry.path();
624        if !path.is_dir() {
625            continue;
626        }
627        let name = entry.file_name();
628        if name == "assets" || name == "ssr" {
629            continue;
630        }
631        dirs.push(path);
632    }
633    dirs.sort();
634    Ok(dirs)
635}
636
637fn run_command(program: &str, args: &[&str], cwd: &Path, label: &str) -> Result<(), String> {
638    let status = Command::new(program)
639        .args(args)
640        .current_dir(cwd)
641        .status()
642        .map_err(|error| format!("failed to start `{label}`: {error}"))?;
643    if status.success() {
644        Ok(())
645    } else {
646        Err(format!("`{label}` exited with {status}"))
647    }
648}
649
650fn run_command_strings(
651    program: &str,
652    args: &[String],
653    cwd: &Path,
654    label: &str,
655) -> Result<(), String> {
656    let status = Command::new(program)
657        .args(args)
658        .current_dir(cwd)
659        .status()
660        .map_err(|error| format!("failed to start `{label}`: {error}"))?;
661    if status.success() {
662        Ok(())
663    } else {
664        Err(format!("`{label}` exited with {status}"))
665    }
666}
667
668fn host_triple() -> String {
669    rustc_metadata()
670        .and_then(|text| {
671            text.lines()
672                .find(|line| line.starts_with("host: "))
673                .map(|line| line["host: ".len()..].trim().to_owned())
674        })
675        .unwrap_or_else(|| "unknown".to_owned())
676}
677
678fn rustc_version() -> Option<String> {
679    rustc_metadata().and_then(|text| {
680        text.lines()
681            .find(|line| line.starts_with("release: "))
682            .map(|line| line["release: ".len()..].trim().to_owned())
683    })
684}
685
686fn rustc_metadata() -> Option<String> {
687    Command::new("rustc")
688        .arg("-vV")
689        .output()
690        .ok()
691        .filter(|output| output.status.success())
692        .and_then(|output| String::from_utf8(output.stdout).ok())
693}
694
695fn git_revision(root: &Path) -> Option<String> {
696    Command::new("git")
697        .args(["rev-parse", "HEAD"])
698        .current_dir(root)
699        .output()
700        .ok()
701        .filter(|output| output.status.success())
702        .and_then(|output| String::from_utf8(output.stdout).ok())
703        .map(|text| text.trim().to_owned())
704        .filter(|text| !text.is_empty())
705}
706
707fn read_json_str_field(path: &Path, field: &str) -> Option<String> {
708    if !path.is_file() {
709        return None;
710    }
711    let text = fs::read_to_string(path).ok()?;
712    let value: serde_json::Value = serde_json::from_str(&text).ok()?;
713    value
714        .get(field)
715        .and_then(|entry| entry.as_str())
716        .map(ToOwned::to_owned)
717}
718
719fn print_status_human(deploy_root: &Path, snapshot: &DeployStatus) {
720    println!("DEPLOY_ROOT {}", deploy_root.display());
721    println!(
722        "CURRENT {}",
723        snapshot.current_version.as_deref().unwrap_or("(none)")
724    );
725    println!(
726        "PREVIOUS {}",
727        snapshot.previous_version.as_deref().unwrap_or("(none)")
728    );
729    println!("LOCKED={}", snapshot.locked);
730    if snapshot.releases.is_empty() {
731        println!("RELEASES (none)");
732        return;
733    }
734    println!("RELEASES");
735    for release in &snapshot.releases {
736        println!(
737            "  {} application={} migrations={} created_at={}",
738            release.version,
739            release.application.as_deref().unwrap_or("-"),
740            release
741                .migration_count
742                .map(|count| count.to_string())
743                .unwrap_or_else(|| "-".to_owned()),
744            release.created_at.as_deref().unwrap_or("-"),
745        );
746    }
747}
748
749fn print_status_json(snapshot: &DeployStatus) {
750    let releases: Vec<serde_json::Value> = snapshot
751        .releases
752        .iter()
753        .map(|release| {
754            serde_json::json!({
755                "version": release.version,
756                "application": release.application,
757                "migration_count": release.migration_count,
758                "created_at": release.created_at,
759            })
760        })
761        .collect();
762    let value = serde_json::json!({
763        "current_version": snapshot.current_version,
764        "previous_version": snapshot.previous_version,
765        "locked": snapshot.locked,
766        "releases": releases,
767    });
768    println!(
769        "{}",
770        serde_json::to_string_pretty(&value).unwrap_or_default()
771    );
772}
773
774fn release_err(error: ReleaseError) -> String {
775    error.to_string()
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781
782    #[test]
783    fn parse_build_flags() {
784        let options = parse_build_args(vec![
785            "--version".into(),
786            "1.2.3".into(),
787            "--tarball".into(),
788            "--skip-npm".into(),
789        ])
790        .unwrap();
791        assert_eq!(options.version.as_deref(), Some("1.2.3"));
792        assert!(options.tarball);
793        assert!(options.skip_npm);
794    }
795
796    #[test]
797    fn parse_install_requires_source() {
798        assert!(parse_install_args(vec![]).is_err());
799    }
800
801    #[test]
802    fn parse_toml_string() {
803        assert_eq!(parse_toml_string_value("\"demo\"").unwrap(), "demo");
804    }
805}