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
/* 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::fs::File;
use std::io::{Read};
use std::path::Path;

use toml::{Parser, Table};

use FlexiConfig;
use config::{Issues, TomlFile};

impl FlexiConfig
{
    //*********************************************************************************************
    /// Construct an instance of FlexiConfig by parsing a TOML data structure.
    fn from_toml(
        toml : Table
        ) -> Result<FlexiConfig, Issues>
    {
        match TomlFile::from(toml)
        {
            Ok(mut config) => {
                Ok(FlexiConfig {
                    project              : config.common().application(),
                    dependencies         : config.depends().priority(),
                    target               : config.common().target(),
                    stderr_format        : config.common().stderr(),
                    disk_format          : config.common().disk(),
                    disk_dir             : config.disk().dir(),
                    disk_dup_err         : config.disk().dup_err(),
                    disk_dup_info        : config.disk().dup_info(),
                    disk_filename_ext    : config.disk().extension(),
                    disk_filename_time   : config.disk().timestamp(),
                    disk_file_size       : config.disk().max_size(),
                    disk_filename_suffix : config.disk().name_suffix(),
                    app_priority         : config.common().priority(),
                    issues               : config.issues()
                })
            },
            Err(issues) => {
                Err(issues)
            }
        }
    }

    //*********************************************************************************************
    /// Creates an instance of the object by loading a configuration file that has been previously
    /// created.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexi_config::FlexiConfig;
    ///
    /// let mut config = FlexiConfig::from_toml_file("log.toml").unwrap();
    ///
    /// config.apply().unwrap()
    /// ```
    pub fn from_toml_file<P : AsRef<Path>>(
        file : P
        ) -> Result<FlexiConfig, 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(_)    => FlexiConfig::from_toml_string(&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)))
        }
    }

    //*********************************************************************************************
    /// Creates an instance from a file already loaded into memory.  Use this method if you want
    /// to load the configuration file yourself and pass it to FlexiConfig.  Or you could use it
    /// to contruct from a static string.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexi_config::FlexiConfig;
    ///
    /// let config = FlexiConfig::from_toml_string(r#"
    ///     [common]
    ///     application="foo"
    ///     priority="warn"
    ///     target="stderr"
    ///     stderr_format="detailed"
    ///     [depends]
    ///     rand = "warn"
    ///     time = "trace"
    ///     "#).unwrap();
    ///
    /// config.apply().unwrap();
    /// ```
    pub fn from_toml_string(
        input : &str
        ) -> Result<FlexiConfig, Issues>
    {
        let mut parser = Parser::new(&input);

        //-----------------------------------------------------------------------------------------
        // Parse the string into a TOML value.
        if let Some(table) = parser.parse()
        {
            FlexiConfig::from_toml(table)
        }
        //-----------------------------------------------------------------------------------------
        // 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.")))
        }
    }
}