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
/* Copyright 2016 Joshua Gentry
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;

use toml::{Parser, Value};
use config::{Issues, Priority};

use FlexiConfig;

//*************************************************************************************************
// Holds the various methods used to create an instance of FlexiConfig from a cargo file.
impl FlexiConfig
{
    //*********************************************************************************************
    /// Construct a new instance from a Cargo.toml file located on disk.  This can be used during
    /// development to create the initial configuration file to ship with the application.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexi_config::FlexiConfig;
    ///
    /// let config = FlexiConfig::from_cargo_file("Cargo.toml").unwrap();
    ///
    /// config.to_toml_file("log.toml").unwrap();
    /// ```
    ///
    /// You can also change some of the default values to values that work better for your
    /// application.
    ///
    /// ```
    /// use flexi_config::{FlexiConfig, Target};
    ///
    /// let mut config = FlexiConfig::from_cargo_file("Cargo.toml").unwrap();
    ///
    /// config.target   = Target::Disk;
    /// config.disk_dir = Some(String::from("logs"));
    ///
    /// config.to_toml_file("log.toml").unwrap();
    /// ```
    pub fn from_cargo_file<P : AsRef<Path>>(
        file : P
        ) -> Result<FlexiConfig, Issues>
    {
        match load_cargo(file)
        {
            Ok(cargo)   => FlexiConfig::from_cargo(&cargo),
            Err(issues) => Err(issues)
        }
    }

    //*********************************************************************************************
    /// Construct a new object from a Cargo.toml file that has already been loaded.  Use this
    /// method if you want to load the Cargo.toml file yourself.  Or you could provide a static
    /// string for the Cargo file instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexi_config::FlexiConfig;
    ///
    /// let mut config = FlexiConfig::from_cargo(r#"
    ///     [package]
    ///     name="foo"
    ///     [dependencies]
    ///     rand = "*"
    ///     time = "*"
    ///     "#).unwrap();
    ///
    /// config.to_toml_file("log.toml").unwrap();
    /// ```
    pub fn from_cargo(
        file : &str
    ) -> Result<FlexiConfig, Issues>
    {
        match parse_cargo(file)
        {
            //-------------------------------------------------------------------------------------
            // Cargo file loaded and verified, grab the important information and build the object.
            Ok(cargo) => {
                let     app     = String::from(cargo.lookup("package.name").unwrap().as_str().unwrap());
                let mut depends = BTreeMap::new();

                if let Some(dependencies) = cargo.lookup("dependencies")
                {
                    for name in dependencies.as_table().unwrap().keys()
                    {
                        depends.insert(name.clone(), Some(Priority::Error));
                    }
                }

                Ok(FlexiConfig::new(&app, depends))
            },
            //-------------------------------------------------------------------------------------
            // The cargo file could not be parsed.
            Err(issues) => Err(issues)
        }
    }
}

//*************************************************************************************************
/// Loads a TOML file from disk into a string.
pub fn load_cargo<P : AsRef<Path>>(
    file : P
) -> Result<String, Issues>
{
    match File::open(file)
    {
        //-------------------------------------------------------------------------------------
        // The file was opened.
        Ok(mut file) => {
            let mut buf = String::with_capacity(8192);

            //---------------------------------------------------------------------------------
            // Read the file and extract the information.
            match file.read_to_string(&mut buf)
            {
                Ok(_)    => Ok(buf),
                Err(err) => Err(Issues::single(format!( "Could not read cargo file: {}", err)))
            }
        },
        //-------------------------------------------------------------------------------------
        // Error opening the file.
        Err(err) => Err(Issues::single(format!("Could not open cargo file: {}", err)))
    }
}

//*************************************************************************************************
/// Parse the cargo.toml file into a TOML data structure.
pub fn parse_cargo(
    cargo : &str
    ) ->  Result<Value, Issues>
{
    let mut parser = Parser::new(cargo);

    //---------------------------------------------------------------------------------------------
    // The cargo file was parsed, verify it's contents.
    if let Some(table) = parser.parse()
    {
        let result = Value::Table(table);

        if let Some(err) = verify_cargo(&result)
        {
            Err(err)
        }
        else
        {
            Ok(result)
        }
    }
    //---------------------------------------------------------------------------------------------
    // The cargo file could not be parsed, report the problems.
    else if parser.errors.len() > 0
    {
        let mut issues = Issues::new();

        for err in parser.errors.iter()
        {
            let (line, col) = parser.to_linecol(err.lo);
            issues.errors.push(format!("line {:>3} : col {:>3} | {}", line, col, err.desc));
        }

        Err(issues)
    }
    else
    {
        Err(Issues::single(String::from(("Error parsing cargo file."))))
    }
}

//*************************************************************************************************
/// Verify that the cargo file has what we need.  If it doesn't returns the error message.
fn verify_cargo(
    cargo : &Value
    ) -> Option<Issues>
{
    let name    = cargo.lookup("package.name");
    let depends = cargo.lookup("dependencies");

    if name.is_none() || name.unwrap().as_str().is_none()
    {
        Some(Issues::single(String::from("Could not determine the name of the package.")))
    }
    else if depends.is_some() && depends.unwrap().as_table().is_none()
    {
        Some(Issues::single(String::from("Could not read the dependencies.")))
    }
    else
    {
        None
    }
}