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
use crate::{properties::Properties, Error, Result};
use fs::File;
use lazy_static::lazy_static;
use regex::Regex;
use std::{cmp::Ordering, collections::HashMap, fs, io::BufReader, path::PathBuf};

lazy_static! {
    static ref NAME_REGEX: Regex = Regex::new("^[a-z][-a-z0-9]*$").unwrap();
}

#[derive(Debug, Clone)]
/// Represents a gcloud named configuration
pub struct Configuration {
    /// Name of the configuration
    name: String,

    /// Path to the configuration file
    path: PathBuf,
}

impl Configuration {
    /// Name of the configuration
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Is the given name a valid configuration name?
    ///
    /// Names must start with a lowercase ASCII character
    /// then zero or more ASCII alphanumerics and hyphens
    pub fn is_valid_name(name: &str) -> bool {
        NAME_REGEX.is_match(name)
    }
}

impl Ord for Configuration {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.name.cmp(&other.name)
    }
}

impl PartialOrd for Configuration {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Configuration {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl Eq for Configuration {}

/// Action to perform when a naming conflict occurs
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ConflictAction {
    /// Abort the operation
    Abort,

    /// Overwrite the existing configuration
    Overwrite,
}

impl From<bool> for ConflictAction {
    fn from(value: bool) -> Self {
        if value {
            ConflictAction::Overwrite
        } else {
            ConflictAction::Abort
        }
    }
}

#[derive(Debug)]
/// Represents the store of gcloud configurations
pub struct ConfigurationStore {
    /// Location of the configuration store on disk
    location: PathBuf,

    /// Path to the configurations sub-folder
    configurations_path: PathBuf,

    /// Available configurations
    configurations: HashMap<String, Configuration>,

    /// Name of the active configuration
    active: String,
}

impl ConfigurationStore {
    /// Opens the configuration store using the OS-specific defaults
    ///
    /// If the `CLOUDSDK_CONFIG` environment variable is set then this will be used, otherwise an
    /// OS-specific default location will be used, as defined by the [dirs] crate, e.g.:
    ///
    /// - Windows: `%APPDATA%\gcloud`
    /// - Linux: `~/.config/gcloud`
    /// - Mac: `~/.config/gcloud` - note that this does not follow the Apple Developer Guidelines
    ///
    /// [dirs]: https://crates.io/crates/dirs
    pub fn with_default_location() -> Result<Self> {
        let gcloud_path: PathBuf = if let Ok(value) = std::env::var("CLOUDSDK_CONFIG") {
            value.into()
        } else {
            let gcloud_path = if cfg!(target_os = "macos") {
                dirs::home_dir()
                    .ok_or(Error::ConfigurationDirectoryNotFound)?
                    .join(".config")
            } else {
                dirs::config_dir().ok_or(Error::ConfigurationDirectoryNotFound)?
            };

            gcloud_path.join("gcloud")
        };

        Self::with_location(gcloud_path)
    }

    /// Opens a configuration store at the given path
    pub fn with_location(gcloud_path: PathBuf) -> Result<Self> {
        if !gcloud_path.is_dir() {
            return Err(Error::ConfigurationStoreNotFound(gcloud_path));
        }

        let configurations_path = gcloud_path.join("configurations");

        if !configurations_path.is_dir() {
            return Err(Error::ConfigurationStoreNotFound(configurations_path));
        }

        let mut configurations: HashMap<String, Configuration> = HashMap::new();

        for file in fs::read_dir(&configurations_path)? {
            if file.is_err() {
                // ignore files we're unable to read - e.g. permissions errors
                continue;
            }

            let file = file.unwrap();
            let name = file.file_name();
            let name = match name.to_str() {
                Some(name) => name,
                None => continue, // ignore files that aren't valid utf8
            };
            let name = name.trim_start_matches("config_");

            if !Configuration::is_valid_name(name) {
                continue;
            }

            configurations.insert(
                name.to_owned(),
                Configuration {
                    name: name.to_owned(),
                    path: file.path(),
                },
            );
        }

        if configurations.is_empty() {
            return Err(Error::NoConfigurationsFound(configurations_path));
        }

        let active = gcloud_path.join("active_config");
        let active = fs::read_to_string(active)?;

        Ok(ConfigurationStore {
            location: gcloud_path,
            configurations_path,
            configurations,
            active,
        })
    }

    /// Get the name of the currently active configuration
    pub fn active(&self) -> &str {
        &self.active
    }

    /// Get the collection of currently available configurations
    pub fn configurations(&self) -> Vec<&Configuration> {
        let mut value: Vec<&Configuration> = self.configurations.values().collect();
        value.sort();
        value
    }

    /// Check if the given configuration is active
    pub fn is_active(&self, configuration: &Configuration) -> bool {
        configuration.name == self.active
    }

    /// Activate a configuration by name
    pub fn activate(&mut self, name: &str) -> Result<()> {
        let configuration = self
            .find_by_name(name)
            .ok_or_else(|| Error::UnknownConfiguration(name.to_owned()))?;

        let path = self.location.join("active_config");
        std::fs::write(path, &configuration.name)?;

        self.active = configuration.name.to_owned();

        Ok(())
    }

    /// Copy an existing configuration, preserving all properties
    pub fn copy(&mut self, src_name: &str, dest_name: &str, conflict: ConflictAction) -> Result<()> {
        let src = self
            .configurations
            .get(src_name)
            .ok_or_else(|| Error::UnknownConfiguration(src_name.to_owned()))?;

        if !Configuration::is_valid_name(dest_name) {
            return Err(Error::InvalidName(dest_name.to_owned()));
        }

        if conflict == ConflictAction::Abort && self.configurations.contains_key(dest_name) {
            return Err(Error::ExistingConfiguration(dest_name.to_owned()));
        }

        // just copy the file on disk so that any properties which aren't directly supported are maintained
        let filename = self.configurations_path.join(format!("config_{}", dest_name));
        fs::copy(&src.path, &filename)?;

        let dest = Configuration {
            name: dest_name.to_owned(),
            path: filename,
        };

        self.configurations.insert(dest_name.to_owned(), dest);

        Ok(())
    }

    /// Create a new configuration
    pub fn create(&mut self, name: &str, properties: &Properties, conflict: ConflictAction) -> Result<()> {
        if !Configuration::is_valid_name(name) {
            return Err(Error::InvalidName(name.to_owned()));
        }

        if conflict == ConflictAction::Abort && self.configurations.contains_key(name) {
            return Err(Error::ExistingConfiguration(name.to_owned()));
        }

        let filename = self.configurations_path.join(format!("config_{}", name));
        let file = File::create(&filename)?;
        properties.to_writer(file)?;

        self.configurations.insert(
            name.to_owned(),
            Configuration {
                name: name.to_owned(),
                path: filename,
            },
        );

        Ok(())
    }

    /// Delete a configuration
    pub fn delete(&mut self, name: &str) -> Result<()> {
        let configuration = self
            .find_by_name(name)
            .ok_or_else(|| Error::UnknownConfiguration(name.to_owned()))?;

        if self.is_active(configuration) {
            return Err(Error::DeleteActiveConfiguration);
        }

        let path = &configuration.path;
        fs::remove_file(&path)?;

        self.configurations.remove(name);

        Ok(())
    }

    /// Describe the properties in the given configuration
    pub fn describe(&self, name: &str) -> Result<Properties> {
        let configuration = self
            .find_by_name(name)
            .ok_or_else(|| Error::UnknownConfiguration(name.to_owned()))?;

        let path = &configuration.path;
        let handle = File::open(path)?;
        let reader = BufReader::new(handle);

        let properties = Properties::from_reader(reader)?;

        Ok(properties)
    }

    /// Rename a configuration
    pub fn rename(&mut self, old_name: &str, new_name: &str, conflict: ConflictAction) -> Result<()> {
        let src = self
            .configurations
            .get(old_name)
            .ok_or_else(|| Error::UnknownConfiguration(old_name.to_owned()))?;

        let active = self.is_active(src);

        if !Configuration::is_valid_name(new_name) {
            return Err(Error::InvalidName(new_name.to_owned()));
        }

        if conflict == ConflictAction::Abort && self.configurations.contains_key(new_name) {
            return Err(Error::ExistingConfiguration(new_name.to_owned()));
        }

        let new_value = Configuration {
            name: new_name.to_owned(),
            path: src.path.with_file_name(format!("config_{}", new_name)),
        };

        std::fs::rename(&src.path, &new_value.path)?;

        self.configurations.remove(old_name);
        self.configurations.insert(new_name.to_owned(), new_value);

        // check if the active configuration is the one being renamed
        if active {
            self.activate(new_name)?;
        }

        Ok(())
    }

    /// Find a configuration by name
    pub fn find_by_name(&self, name: &str) -> Option<&Configuration> {
        self.configurations.get(&name.to_owned())
    }
}

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

    #[test]
    pub fn test_is_valid_name_with_valid_name() {
        assert!(Configuration::is_valid_name("foo"));
        assert!(Configuration::is_valid_name("f"));
        assert!(Configuration::is_valid_name("f123"));
        assert!(Configuration::is_valid_name("foo-bar"));
        assert!(Configuration::is_valid_name("foo-123"));
        assert!(Configuration::is_valid_name("foo-a1b2c3"));
    }

    #[test]
    pub fn test_is_valid_name_with_invalid_name() {
        // too short
        assert!(!Configuration::is_valid_name(""));

        // doesn't start with lowercase ASCII
        assert!(!Configuration::is_valid_name("F"));
        assert!(!Configuration::is_valid_name("1"));
        assert!(!Configuration::is_valid_name("-"));

        // doesn't contain only alphanumerics and ASCII
        assert!(!Configuration::is_valid_name("foo_bar"));
        assert!(!Configuration::is_valid_name("foo.bar"));
        assert!(!Configuration::is_valid_name("foo|bar"));
        assert!(!Configuration::is_valid_name("foo$bar"));
        assert!(!Configuration::is_valid_name("foo#bar"));
        assert!(!Configuration::is_valid_name("foo@bar"));
        assert!(!Configuration::is_valid_name("foo;bar"));
        assert!(!Configuration::is_valid_name("foo?bar"));

        // doesn't contain only lowercase
        assert!(!Configuration::is_valid_name("camelCase"));
    }
}