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
use anyhow::Result;
use yaml_rust::yaml::Hash as YamlHash;
use yaml_rust::yaml::Yaml;

use super::super::cmd;
use super::super::config;
use super::super::errors;
use super::super::model;
use super::super::path;

struct InitOptions {
    pub dirname: std::path::PathBuf,
    pub filename: String,
    pub force: bool,
    pub global: bool,
    pub root: String,
}

impl std::default::Default for InitOptions {
    fn default() -> Self {
        InitOptions {
            dirname: path::current_dir(),
            filename: "garden.yaml".to_string(),
            force: false,
            global: false,
            root: "${GARDEN_CONFIG_DIR}".to_string(),
        }
    }
}

pub fn main(options: &mut model::CommandOptions) -> Result<()> {
    let mut init_options = InitOptions::default();
    {
        let mut ap = argparse::ArgumentParser::new();
        ap.set_description("garden init - create an empty garden.yaml");

        ap.refer(&mut init_options.global).add_option(
            &["--global"],
            argparse::StoreTrue,
            "use the user-wide configuration directory
                        (~/.config/garden/garden.yaml)",
        );

        ap.refer(&mut init_options.force).add_option(
            &["-f", "--force"],
            argparse::StoreTrue,
            "overwrite existing config files",
        );

        ap.refer(&mut init_options.root).add_option(
            &["-r", "--root"],
            argparse::Store,
            "specify the garden root
                        (default: ${GARDEN_CONFIG_DIR}",
        );

        ap.refer(&mut init_options.filename).add_argument(
            "filename",
            argparse::Store,
            "config file to write (default: garden.yaml)",
        );

        options.args.insert(0, "garden init".into());
        cmd::parse_args(ap, options.args.to_vec());
    }

    init(options, &mut init_options)
}

fn init(options: &model::CommandOptions, init_options: &mut InitOptions) -> Result<()> {
    let file_path = std::path::PathBuf::from(&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());
        }

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

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

    let mut config_path = init_options.dirname.to_path_buf();
    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()
        .as_ref()
        .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 {
        doc = config::reader::read_yaml(&config_path)?;
    } else {
        doc = config::reader::empty_doc();
    }

    // Mutable scope
    {
        if let Yaml::Hash(ref mut doc_hash) = doc {
            let garden_key = Yaml::String("garden".into());
            let garden: &mut YamlHash = 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("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 empty Garden configuration in {:?}",
                config_path
            );
        }
    }

    Ok(())
}