Skip to main content

docsrs_cli/config/load/
init.rs

1//! `config init`: atomic creation of the default `config.toml`.
2
3use std::fs;
4use std::io::Write;
5use std::path::PathBuf;
6
7use serde::{Deserialize, Serialize};
8
9use crate::config::constants::{APP_NAME, CONFIG_FILE_NAME};
10use crate::config::path_source::{PathSource, resolve_config_dir_with_source};
11use crate::error::{AppError, AppResult, ErrorDetail, IoOp, io_at};
12use crate::platform::{restrict_private_dir, restrict_private_file};
13
14use super::template::default_config_toml;
15
16/// Result of `config init`.
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18pub struct ConfigInitResult {
19    /// Absolute path written (or already present when not forced).
20    pub path: String,
21    /// Directory that holds the file.
22    pub config_dir: String,
23    /// Layer that resolved the directory this call wrote into.
24    ///
25    /// Named `target_source` to match `cache-clear`, the other verb that
26    /// destroys. It carried the same value under the name `source` while its
27    /// sibling said `target_source`, and two names for one concept across two
28    /// destructive verbs is the drift this repository keeps finding.
29    pub target_source: PathSource,
30    /// True when the file was created or overwritten in this call.
31    pub created: bool,
32    /// True when an existing file was replaced (`--force`).
33    pub overwritten: bool,
34}
35
36/// Create default `config.toml` under the resolved config directory.
37///
38/// # Errors
39///
40/// - [`crate::error::ErrorKind::Config`] when the directory cannot be resolved or created,
41///   when the file already exists without `force`, or on I/O failure.
42pub fn init_config_toml(
43    config_dir_override: Option<PathBuf>,
44    force: bool,
45) -> AppResult<ConfigInitResult> {
46    let (dir, source) = resolve_config_dir_with_source(config_dir_override);
47    let dir = dir.ok_or_else(|| AppError::of(ErrorDetail::ConfigDirUnresolved))?;
48    fs::create_dir_all(&dir).map_err(io_at(IoOp::CreateDir, &dir))?;
49    restrict_private_dir(&dir);
50
51    let path = dir.join(CONFIG_FILE_NAME);
52    let existed = path.is_file();
53    if existed && !force {
54        return Err(AppError::of(ErrorDetail::ConfigAlreadyExists {
55            path: path.display().to_string(),
56        }));
57    }
58
59    // Atomic-ish write: tempfile in same dir then rename.
60    let tmp = dir.join(format!("{CONFIG_FILE_NAME}.{APP_NAME}.tmp"));
61    let template = default_config_toml();
62    {
63        let mut f = fs::File::create(&tmp).map_err(io_at(IoOp::CreateTemp, &tmp))?;
64        f.write_all(template.as_bytes())
65            .map_err(io_at(IoOp::Write, &tmp))?;
66        f.sync_all().map_err(io_at(IoOp::Sync, &tmp))?;
67    }
68    restrict_private_file(&tmp);
69    fs::rename(&tmp, &path).map_err(|e| {
70        let _ = fs::remove_file(&tmp);
71        io_at(IoOp::Install, &path)(e)
72    })?;
73    restrict_private_file(&path);
74
75    Ok(ConfigInitResult {
76        path: path.display().to_string(),
77        config_dir: dir.display().to_string(),
78        target_source: source,
79        created: true,
80        overwritten: existed,
81    })
82}