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
374
//! This crate is a library for generating structs based on a config file at build
//! time. It is intended for use in a `build.rs` file so should be included in your
//! `[build-dependencies]`.
//!
//! ```toml
//! [build-dependencies.config_struct]
//! version = "~0.2.0"
//! features = ["toml-parsing"]
//! ```
//!
//! By default, `config_struct` is markup-language-agnostic, so include the relevant feature for whatever language your config file is written in. Choices are:
//!
//! 1.  `json-parsing`
//! 2.  `ron-parsing`
//! 3.  `toml-parsing`
//! 4.  `yaml-parsing`
//!
//! Only `toml-parsing` is included by default, so be sure to specify the features
//! you need in your `Cargo.toml` file.
//!
//! # Examples
//!
//! ```rust,ignore
//! // build.rs
//! extern crate config_struct;
//!
//! fn main() {
//!     config_struct::create_config("config.toml", "src/config.rs", &Default::default());
//! }
//! ```
//!
//! The above build script will take the following `config.toml` file and generate
//! a `config.rs` like the following:
//!
//! ```toml
//! // config.toml
//! name = "Application"
//! version = 5
//! features = [
//!     "one",
//!     "two",
//!     "three"
//! ]
//! ```
//!
//! ```rust,ignore
//! // config.rs
//! // ...
//! use std::borrow::Cow;
//!
//! #[derive(Debug, Clone, Serialize, Deserialize)]
//! #[allow(non_camel_case_types)]
//! pub struct Config {
//!     pub features: Cow<'static, [Cow<'static, str>]>,
//!     pub name: Cow<'static, str>,
//!     pub version: i64,
//! }
//!
//! pub const CONFIG: Config = Config {
//!     features: Cow::Borrowed(&[Cow::Borrowed("one"), Cow::Borrowed("two"), Cow::Borrowed("three")]),
//!     name: Cow::Borrowed("Application"),
//!     version: 5,
//! };
//! // ...
//! ```
//!
//! Strings and arrays are represented by `Cow` types, which allows the entire
//! Config struct to be either heap allocated at runtime, or a compile time
//! constant, as shown above.
//!
//! **Note:** By default, config structs derive `Serialize` and
//! `Deserialize`. This will only work in your application if you include the
//! `serde_derive` and `serde` crates. You can disable deriving those traits in
//! [`Options`](struct.Options.html) if you wish.
//!
//! Similarly, the loading functions generated by default will require the same
//! serialization crate used in generation. For example, `extern crate toml` will
//! be required if you generate using `"config.toml"`. These loading functions can
//! also be disabled however.

#![allow(unknown_lints)]

#[cfg(feature = "json-parsing")]
extern crate serde_json;

#[cfg(feature = "ron-parsing")]
extern crate ron;

#[cfg(feature = "toml-parsing")]
extern crate toml;

#[cfg(feature = "yaml-parsing")]
extern crate serde_yaml;

#[macro_use]
extern crate failure;

#[cfg(feature = "json-parsing")]
mod json_parsing;

#[cfg(feature = "ron-parsing")]
mod ron_parsing;

#[cfg(feature = "toml-parsing")]
mod toml_parsing;

#[cfg(feature = "yaml-parsing")]
mod yaml_parsing;

mod error;
mod format;
mod generation;
mod load_fns;
mod options;
mod parsing;
mod validation;
mod value;

#[cfg(
    not(
        any(
            feature = "json-parsing",
            feature = "ron-parsing",
            feature = "toml-parsing",
            feature = "yaml-parsing"
        )
    )
)]
compile_error!("The config_struct crate requires at least one parsing feature to be enabled:\n {json-parsing, ron-parsing, toml-parsing, yaml-parsing}");

use std::path::Path;
use value::GenericStruct;

pub use error::{Error, GenerationError, OptionsError};
pub use format::Format;
pub use options::{DynamicLoading, FloatSize, IntSize, Options};

/// Generate Rust source code defining structs based on a config file.
///
/// The format of
/// the config file will be auto-detected from its extension.
///
/// # Examples
/// ```rust,ignore
/// let code = config_struct::generate_config("config.toml", &Default::default())?;
/// assert!(code.contains("pub struct Config"));
/// ```
pub fn generate_config<P: AsRef<Path>>(filepath: P, options: &Options) -> Result<String, Error> {
    let format = Format::from_filename(filepath.as_ref())?;

    generate_config_with_format(format, filepath, options)
}

/// Generate Rust source code defining structs based on a config file of an explicit
/// format.
///
/// # Examples
/// ```rust,ignore
/// use config_struct::Format;
///
/// let code = config_struct::generate_config_with_format(
///     Format::Toml,
///     "config.toml",
///     &Default::default())?;
///
/// assert!(code.contains("pub struct Config"));
/// ```
pub fn generate_config_with_format<P: AsRef<Path>>(
    format: Format,
    filepath: P,
    options: &Options,
) -> Result<String, Error> {
    let path = filepath.as_ref();
    let source = std::fs::read_to_string(path)?;
    let output = generate_config_from_source_with_filepath(format, &source, options, Some(path))?;

    Ok(output)
}

/// Generate Rust source code defining structs from a config string in some
/// specified format.
///
/// # Examples
/// ```rust
/// use config_struct::{Options, Format};
///
/// let code = config_struct::generate_config_from_source(
///     Format::Toml,
///     "number = 100  # This is valid TOML.",
///     &Options {
///         generate_load_fns: false,
///         ..Default::default()
///     }).unwrap();
///
/// assert!(code.contains("pub struct Config"));
/// assert!(code.contains("pub number: i64"));
/// assert!(code.contains("number: 100"));
/// ```
pub fn generate_config_from_source<S: AsRef<str>>(
    format: Format,
    source: S,
    options: &Options,
) -> Result<String, GenerationError> {
    generate_config_from_source_with_filepath(format, source.as_ref(), options, None)
}

fn generate_config_from_source_with_filepath(
    format: Format,
    source: &str,
    options: &Options,
    filepath: Option<&Path>,
) -> Result<String, GenerationError> {
    options.validate()?;

    let config = {
        let mut root_struct: GenericStruct = match format {
            #[cfg(feature = "json-parsing")]
            Format::Json => json_parsing::parse_json(source, options)?,

            #[cfg(feature = "ron-parsing")]
            Format::Ron => ron_parsing::parse_ron(source, options)?,

            #[cfg(feature = "toml-parsing")]
            Format::Toml => toml_parsing::parse_toml(source, options)?,

            #[cfg(feature = "yaml-parsing")]
            Format::Yaml => yaml_parsing::parse_yaml(source, options)?,
        };
        root_struct.struct_name = options.struct_name.clone();
        root_struct
    };

    validation::validate_struct(&config)?;

    let mut code = String::new();

    const HEADER: &str = "#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(dead_code)]

use std::borrow::Cow;\n\n";
    code.push_str(HEADER);

    let structs = generation::generate_structs(&config, options);
    code.push_str(&structs);

    let requires_const =
        options.generate_load_fns && options.dynamic_loading != DynamicLoading::Always;

    let struct_name = &options.struct_name;
    let const_name = &options.real_const_name();

    if options.generate_const || requires_const {
        code.push_str(&format!(
            "pub const {}: {} = {};\n",
            const_name,
            struct_name,
            generation::struct_value_string(&config, 0, options.max_array_size)
        ));
    }

    if options.generate_load_fns {
        let filepath = filepath.ok_or(GenerationError::MissingFilePath);

        let dynamic_impl =
            filepath.map(|path| load_fns::dynamic_load_impl(format, struct_name, path));

        let static_impl = load_fns::static_load_impl(struct_name, const_name);

        let impl_string = match options.dynamic_loading {
            DynamicLoading::Always => dynamic_impl?,
            DynamicLoading::Never => static_impl,
            DynamicLoading::DebugOnly => format!(
                "
#[cfg(debug_assertions)]
{}

#[cfg(not(debug_assertions))]
{}
",
                dynamic_impl?, static_impl,
            ),
        };

        code.push_str(&impl_string);
    }

    Ok(code)
}

/// Generate a Rust module containing struct definitions based on a given config
/// file.
///
/// The format of the config is auto-detected from its filename extension.
///
/// # Examples
///
/// ```rust,ignore
/// config_struct::create_config("config.toml", "src/config.rs", &Default::default())?;
/// ```
pub fn create_config<SrcPath: AsRef<Path>, DstPath: AsRef<Path>>(
    filepath: SrcPath,
    destination: DstPath,
    options: &Options,
) -> Result<(), Error> {
    let output = generate_config(filepath, options)?;
    ensure_destination(destination.as_ref(), options)?;
    std::fs::write(destination, output)?;

    Ok(())
}

/// Generate a Rust module containing struct definitions based on a given config
/// file with an explicitly specified format.
///
/// # Examples
///
/// ```rust,ignore
/// use config_struct::Format;
///
/// config_struct::create_config_with_format(
///     Format::Toml,
///     "config.toml",
///     "src/config.rs",
///     &Default::default())?;
/// ```
pub fn create_config_with_format<SrcPath: AsRef<Path>, DstPath: AsRef<Path>>(
    format: Format,
    filepath: SrcPath,
    destination: DstPath,
    options: &Options,
) -> Result<(), Error> {
    let output = generate_config_with_format(format, filepath, options)?;
    ensure_destination(destination.as_ref(), options)?;
    std::fs::write(destination, output)?;

    Ok(())
}

/// Generate a Rust module containing struct definitions from a config string in
/// some specified format.
///
/// # Examples
///
/// ```rust,ignore
/// use config_struct::Format;
///
/// config_struct::create_config_from_source(
///     Format::Toml,
///     "number = 100  # This is valid TOML.",
///     "src/config.rs",
///     &Default::default())?;
/// ```
pub fn create_config_from_source<S: AsRef<str>, P: AsRef<Path>>(
    format: Format,
    source: S,
    destination: P,
    options: &Options,
) -> Result<(), Error> {
    let output = generate_config_from_source(format, source, options)?;
    ensure_destination(destination.as_ref(), options)?;
    std::fs::write(destination, output)?;

    Ok(())
}

fn ensure_destination(path: &Path, options: &Options) -> Result<(), Error> {
    if options.create_dirs {
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir)?;
        }
    }

    Ok(())
}