rise-deploy 0.15.10

A simple and powerful CLI for deploying containerized applications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

/// The container runtime engine behind the CLI command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContainerRuntime {
    Docker,
    Podman,
}

/// Container CLI identity, carrying the command to invoke and the detected runtime.
///
/// Handles the case where `docker` is a Podman alias (e.g. podman-docker package)
/// by inspecting version command output during construction.
#[derive(Debug, Clone)]
pub struct ContainerCli {
    command: String,
    runtime: ContainerRuntime,
    buildx_supports_push: bool,
}

impl ContainerCli {
    /// Build a `ContainerCli` from an explicitly provided command name.
    ///
    /// Detects the runtime by inspecting the binary name first, then falling
    /// back to checking version command output (handles `docker` → Podman aliases).
    pub fn from_command(command: impl Into<String>) -> Self {
        let command = command.into();
        let runtime = detect_runtime(&command);
        let buildx_supports_push = detect_buildx_push_support(&command);
        Self {
            command,
            runtime,
            buildx_supports_push,
        }
    }

    /// The CLI command to invoke (e.g. `"docker"` or `"podman"`).
    pub fn command(&self) -> &str {
        &self.command
    }

    /// The detected container runtime engine.
    pub fn runtime(&self) -> ContainerRuntime {
        self.runtime
    }

    /// Whether this CLI frontend likely supports `buildx build --push`.
    pub fn buildx_supports_push(&self) -> bool {
        self.buildx_supports_push
    }
}

/// Detect which container runtime a CLI command is backed by.
fn detect_runtime(command: &str) -> ContainerRuntime {
    // Fast path: binary name is literally "podman"
    if command_file_name(command) == Some("podman") {
        return ContainerRuntime::Podman;
    }

    // Slow path: e.g. `docker` might be a Podman alias (podman-docker package)
    probe_runtime(command).unwrap_or(ContainerRuntime::Docker)
}

/// Return the file name component of a command path.
fn command_file_name(command: &str) -> Option<&str> {
    use std::path::Path;
    Path::new(command)
        .file_name()
        .and_then(|name| name.to_str())
}

/// Heuristic for buildx `--push` support:
/// treat Podman frontends as unsupported, everything else as supported.
fn detect_buildx_push_support(command: &str) -> bool {
    !command.to_lowercase().contains("podman")
}

/// Parse runtime from version command output.
///
/// Combines stdout and stderr because wrappers may emit identifying text to either stream.
fn runtime_from_version_output(stdout: &[u8], stderr: &[u8]) -> ContainerRuntime {
    let combined = format!(
        "{}\n{}",
        String::from_utf8_lossy(stdout),
        String::from_utf8_lossy(stderr)
    );
    if combined.to_lowercase().contains("podman") {
        ContainerRuntime::Podman
    } else {
        ContainerRuntime::Docker
    }
}

/// Probe runtime by executing `<command> version` and falling back to `<command> --version`.
///
/// `version` can include both client and server info, which detects the case
/// where the Docker CLI talks to a Podman server (e.g. Docker CLI connected to
/// a Podman backend in a VM). If that probe fails (for example because Docker
/// daemon is down), we fall back to `--version` so CLI presence is still
/// detected.
///
/// Returns `None` if command execution fails or exits non-zero.
fn probe_runtime(command: &str) -> Option<ContainerRuntime> {
    use std::process::Command;

    for args in &[&["version"][..], &["--version"][..]] {
        let output = Command::new(command).args(*args).output().ok()?;
        if output.status.success() {
            return Some(runtime_from_version_output(&output.stdout, &output.stderr));
        }
    }

    None
}

// TODO: Use keyring crate for secure token storage instead of plain JSON
// This would store tokens in the system's secure credential storage:
// - macOS: Keychain
// - Linux: Secret Service API / libsecret
// - Windows: Credential Manager

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Config {
    pub token: Option<String>,
    pub backend_url: Option<String>,
    pub container_cli: Option<String>,
    pub managed_buildkit: Option<bool>,
    pub railpack_embed_ssl_cert: Option<bool>,
}

impl Config {
    /// Get the path to the config file
    pub fn config_path() -> Result<PathBuf> {
        let home = dirs::home_dir().context("Failed to get home directory")?;

        let config_dir = home.join(".config").join("rise");

        // Create directory if it doesn't exist
        if !config_dir.exists() {
            fs::create_dir_all(&config_dir).context("Failed to create config directory")?;
        }

        Ok(config_dir.join("config.json"))
    }

    /// Load configuration from disk
    pub fn load() -> Result<Self> {
        let config_path = Self::config_path()?;

        if !config_path.exists() {
            return Ok(Config::default());
        }

        let contents = fs::read_to_string(&config_path).context("Failed to read config file")?;

        let config: Config =
            serde_json::from_str(&contents).context("Failed to parse config file")?;

        Ok(config)
    }

    /// Save configuration to disk
    pub fn save(&self) -> Result<()> {
        let config_path = Self::config_path()?;

        let json = serde_json::to_string_pretty(self).context("Failed to serialize config")?;

        fs::write(&config_path, json).context("Failed to write config file")?;

        Ok(())
    }

    /// Set the authentication token
    pub fn set_token(&mut self, token: String) -> Result<()> {
        self.token = Some(token);
        self.save()
    }

    /// Get the authentication token
    /// Checks RISE_TOKEN environment variable first, then falls back to config file
    pub fn get_token(&self) -> Option<String> {
        #[cfg(not(test))]
        if let Ok(token) = std::env::var("RISE_TOKEN") {
            return Some(token);
        }
        self.token.clone()
    }

    /// Set the backend URL
    pub fn set_backend_url(&mut self, url: String) -> Result<()> {
        self.backend_url = Some(url);
        self.save()
    }

    /// Get the backend URL (with default fallback)
    /// Checks RISE_URL environment variable first, then falls back to config file, then to default
    pub fn get_backend_url(&self) -> String {
        #[cfg(not(test))]
        if let Ok(url) = std::env::var("RISE_URL") {
            return url;
        }
        self.backend_url
            .clone()
            .unwrap_or_else(|| "http://localhost:3000".to_string())
    }

    /// Set the container CLI
    #[allow(dead_code)]
    pub fn set_container_cli(&mut self, cli: String) -> Result<()> {
        self.container_cli = Some(cli);
        self.save()
    }

    /// Get the container CLI to use (docker or podman)
    /// Checks RISE_CONTAINER_CLI environment variable first, then falls back to config file,
    /// then to auto-detection (podman if available, docker otherwise)
    pub fn get_container_cli(&self) -> ContainerCli {
        #[cfg(not(test))]
        if let Ok(cli) = std::env::var("RISE_CONTAINER_CLI") {
            return ContainerCli::from_command(cli);
        }
        if let Some(ref cli) = self.container_cli {
            return ContainerCli::from_command(cli.clone());
        }
        detect_container_cli()
    }

    /// Get whether to use managed BuildKit daemon
    /// Checks RISE_MANAGED_BUILDKIT environment variable first, then falls back to config file
    /// Returns false by default (opt-in feature)
    #[allow(dead_code)]
    pub fn get_managed_buildkit(&self) -> bool {
        #[cfg(not(test))]
        if let Some(val) = crate::build::parse_bool_env_var("RISE_MANAGED_BUILDKIT") {
            return val;
        }
        self.managed_buildkit.unwrap_or(false)
    }

    /// Set whether to use managed BuildKit daemon
    #[allow(dead_code)]
    pub fn set_managed_buildkit(&mut self, enabled: bool) -> Result<()> {
        self.managed_buildkit = Some(enabled);
        self.save()
    }

    /// Get whether to embed SSL certificate in Railpack builds
    /// Checks RISE_RAILPACK_EMBED_SSL_CERT environment variable first, then falls back to config file
    /// Defaults to true if SSL_CERT_FILE is set in the environment
    #[allow(dead_code)]
    pub fn get_railpack_embed_ssl_cert(&self) -> bool {
        #[cfg(not(test))]
        if let Some(val) = crate::build::parse_bool_env_var("RISE_RAILPACK_EMBED_SSL_CERT") {
            return val;
        }
        if let Some(enabled) = self.railpack_embed_ssl_cert {
            return enabled;
        }
        #[cfg(not(test))]
        return crate::build::env_var_non_empty("SSL_CERT_FILE").is_some();
        #[cfg(test)]
        false
    }

    /// Set whether to embed SSL certificate in Railpack builds
    #[allow(dead_code)]
    pub fn set_railpack_embed_ssl_cert(&mut self, enabled: bool) -> Result<()> {
        self.railpack_embed_ssl_cert = Some(enabled);
        self.save()
    }
}

/// Auto-detect which container CLI is available.
///
/// Checks `docker` first, then `podman`. Also detects the case where
/// `docker` is a Podman alias (e.g. podman-docker package) by inspecting
/// version command output — the same probe that checks availability.
fn detect_container_cli() -> ContainerCli {
    // Check if docker is available (and whether it's secretly Podman)
    if let Some(runtime) = probe_runtime("docker") {
        return ContainerCli {
            command: "docker".to_string(),
            runtime,
            buildx_supports_push: detect_buildx_push_support("docker"),
        };
    }

    // Check if podman is available
    if probe_runtime("podman").is_some() {
        return ContainerCli {
            command: "podman".to_string(),
            runtime: ContainerRuntime::Podman,
            buildx_supports_push: detect_buildx_push_support("podman"),
        };
    }

    // Default to docker if neither is detected
    ContainerCli {
        command: "docker".to_string(),
        runtime: ContainerRuntime::Docker,
        buildx_supports_push: detect_buildx_push_support("docker"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config(overrides: impl FnOnce(&mut Config)) -> Config {
        let mut c = Config::default();
        overrides(&mut c);
        c
    }

    #[test]
    fn test_backend_url_default() {
        assert_eq!(Config::default().get_backend_url(), "http://localhost:3000");
    }

    #[test]
    fn test_backend_url_from_config() {
        let c = config(|c| c.backend_url = Some("https://api.example.com".to_string()));
        assert_eq!(c.get_backend_url(), "https://api.example.com");
    }

    #[test]
    fn test_token_none_by_default() {
        assert_eq!(Config::default().get_token(), None);
    }

    #[test]
    fn test_token_from_config() {
        let c = config(|c| c.token = Some("config-token".to_string()));
        assert_eq!(c.get_token(), Some("config-token".to_string()));
    }

    #[test]
    fn test_managed_buildkit_default_false() {
        assert!(!Config::default().get_managed_buildkit());
    }

    #[test]
    fn test_managed_buildkit_from_config() {
        let c = config(|c| c.managed_buildkit = Some(true));
        assert!(c.get_managed_buildkit());

        let c = config(|c| c.managed_buildkit = Some(false));
        assert!(!c.get_managed_buildkit());
    }

    #[test]
    fn test_railpack_embed_ssl_cert_default_false() {
        // In tests, env vars are ignored, so default is always false
        assert!(!Config::default().get_railpack_embed_ssl_cert());
    }

    #[test]
    fn test_railpack_embed_ssl_cert_from_config() {
        let c = config(|c| c.railpack_embed_ssl_cert = Some(true));
        assert!(c.get_railpack_embed_ssl_cert());

        let c = config(|c| c.railpack_embed_ssl_cert = Some(false));
        assert!(!c.get_railpack_embed_ssl_cert());
    }

    #[test]
    fn test_runtime_from_version_output_docker_sample() {
        // Sample Docker output:
        // Docker version 27.3.1, build ce12230
        let runtime = runtime_from_version_output(b"Docker version 27.3.1, build ce12230\n", b"");
        assert_eq!(runtime, ContainerRuntime::Docker);
    }

    #[test]
    fn test_runtime_from_version_output_podman_sample_stdout() {
        // Sample Podman output:
        // podman version 5.0.2
        let runtime = runtime_from_version_output(b"podman version 5.0.2\n", b"");
        assert_eq!(runtime, ContainerRuntime::Podman);
    }

    #[test]
    fn test_runtime_from_version_output_podman_sample_stderr() {
        // Sample podman-docker wrapper behavior (identity text on stderr):
        // Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        let runtime = runtime_from_version_output(
            b"Docker version 5.0.2\n",
            b"Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.\n",
        );
        assert_eq!(runtime, ContainerRuntime::Podman);
    }

    #[test]
    fn test_runtime_from_version_output_docker_cli_podman_server() {
        // Docker CLI connected to a Podman server (e.g. via VM).
        // `docker version` output contains "Podman Engine:" in server section.
        let stdout = b"Client:\n Version: 29.2.1\n\nServer: linux/arm64/fedora-43\n Podman Engine:\n  Version: 5.7.1\n";
        let runtime = runtime_from_version_output(stdout, b"");
        assert_eq!(runtime, ContainerRuntime::Podman);
    }

    #[test]
    fn test_command_file_name_extracts_binary_name() {
        assert_eq!(command_file_name("podman"), Some("podman"));
        assert_eq!(command_file_name("/usr/bin/podman"), Some("podman"));
        assert_eq!(command_file_name("/usr/local/bin/docker"), Some("docker"));
    }
}