garden/cmds/
init.rs

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
use anyhow::Result;
use clap::{Parser, ValueHint};
use yaml_rust::{yaml, Yaml};

use crate::{cli, cmds::plant, config, constants, errors, git, model, path};

#[derive(Parser, Clone, Debug)]
#[command(author, about, long_about)]
pub struct InitOptions {
    /// Do not add any trees when initializing
    #[arg(long)]
    pub empty: bool,
    /// Overwrite existing config files
    #[arg(long, short)]
    pub force: bool,
    /// Use the user-wide configuration directory (~/.config/garden/garden.yaml)
    #[arg(long)]
    pub global: bool,
    /// Set the garden root path
    #[arg(long, default_value_t = string!(constants::GARDEN_CONFIG_DIR_EXPR), value_hint = ValueHint::DirPath)]
    pub root: String,
    /// Config filename to write
    #[arg(default_value = constants::GARDEN_CONFIG, value_hint = ValueHint::FilePath)]
    pub filename: std::path::PathBuf,
}

pub fn main(options: &cli::MainOptions, init_options: &mut InitOptions) -> Result<()> {
    let mut dirname = path::current_dir();
    let file_path = &init_options.filename;
    if file_path.is_absolute() {
        if init_options.global {
            return Err(errors::GardenError::Usage(
                "'--global' cannot be used with an absolute path".into(),
            )
            .into());
        }

        dirname = file_path
            .parent()
            .ok_or_else(|| {
                errors::GardenError::AssertionError(format!(
                    "unable to get parent(): {file_path:?}"
                ))
            })?
            .to_path_buf();

        init_options.filename =
            std::path::PathBuf::from(file_path.file_name().ok_or_else(|| {
                errors::GardenError::AssertionError(format!(
                    "unable to get file path: {file_path:?}"
                ))
            })?);
    }
    if init_options.global {
        dirname = config::xdg_dir();
    }

    let mut config_path = dirname.clone();
    config_path.push(&init_options.filename);

    if !init_options.force && config_path.exists() {
        let error_message = format!(
            "{:?} already exists, use \"--force\" to overwrite",
            config_path.to_string_lossy()
        );
        return Err(errors::GardenError::FileExists(error_message).into());
    }

    // Create parent directories as needed
    let parent = config_path
        .parent()
        .ok_or_else(|| {
            errors::GardenError::AssertionError(format!("unable to get parent(): {config_path:?}"))
        })?
        .to_path_buf();

    if !parent.exists() {
        if let Err(err) = std::fs::create_dir_all(&parent) {
            let error_message = format!("unable to create {parent:?}: {err}");
            return Err(errors::GardenError::OSError(error_message).into());
        }
    }

    // Does the config file already exist?
    let exists = config_path.exists();

    // Read or create a new document
    let mut doc = if exists {
        config::reader::read_yaml(&config_path)?
    } else {
        config::reader::empty_doc()
    };

    let mut config = model::Configuration::new();
    config.root = model::Variable::new(init_options.root.clone(), None);
    config.root_path.clone_from(&dirname);
    config.path = Some(config_path.clone());

    let mut done = false;
    if !init_options.empty && init_options.root == constants::GARDEN_CONFIG_DIR_EXPR {
        let git_worktree = git::current_worktree_path(&dirname);
        if let Ok(worktree) = git_worktree {
            config::reader::add_section(constants::TREES, &mut doc)?;
            if let Yaml::Hash(ref mut doc_hash) = doc {
                let trees_key = Yaml::String(constants::TREES.into());
                if let Some(Yaml::Hash(trees)) = doc_hash.get_mut(&trees_key) {
                    if let Ok(tree_name) =
                        plant::plant_path(None, &config, options.verbose, &worktree, trees)
                    {
                        done = true;
                        // If the config path is the same as the tree's worktree path then
                        // set the tree's "path" field to ${GARDEN_CONFIG_DIR}.
                        if config.root_path.to_string_lossy() == worktree {
                            if let Some(Yaml::Hash(tree_entry)) = trees.get_mut(&tree_name) {
                                tree_entry.insert(
                                    Yaml::String(constants::PATH.to_string()),
                                    Yaml::String(constants::GARDEN_CONFIG_DIR_EXPR.to_string()),
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    // Mutable scope
    if !done || init_options.root != constants::GARDEN_CONFIG_DIR_EXPR {
        config::reader::add_section(constants::GARDEN, &mut doc)?;
        if let Yaml::Hash(ref mut doc_hash) = doc {
            let garden_key = Yaml::String(constants::GARDEN.into());
            let garden: &mut yaml::Hash = match doc_hash.get_mut(&garden_key) {
                Some(Yaml::Hash(ref mut hash)) => hash,
                _ => {
                    return Err(errors::GardenError::InvalidConfiguration {
                        msg: "invalid configuration: 'garden' is not a hash".into(),
                    }
                    .into());
                }
            };

            let root_key = Yaml::String(constants::ROOT.into());
            garden.insert(root_key, Yaml::String(init_options.root.clone()));
        }
    }

    config::writer::write_yaml(&doc, &config_path)?;

    if !options.quiet {
        if exists {
            eprintln!("Reinitialized Garden configuration in {config_path:?}");
        } else {
            eprintln!("Initialized Garden configuration in {config_path:?}");
        }
    }

    Ok(())
}