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
// Copyright (c) 2017 repomon-config developers
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Configuration management for repomon.
//!
//! # Examples
//!
//! ## Read from TOML string
//!
//! ```
//! # use repomon_config::error::Result;
//! # use repomon_config::{read_toml, Branches};
//! # use std::io::Cursor;
//! #
//! # fn read() -> Result<()> {
//!     let test_toml = r#"[[branch.blah]]
//!     name = "origin/master"
//!     interval = "1m"
//!
//!     [[branch.repomon]]
//!     name = "origin/master"
//!     interval = "1m"
//!
//!     [[branch.repomon]]
//!     name = "origin/feature/testing"
//!     interval = "1m"
//!
//!     [[branch.repomon-config]]
//!     name = "origin/master"
//!     interval = "1m"
//!     "#;
//!
//!     // Serialize the TOML above into a `Branches` struct.
//!     let mut reader = Cursor::new(test_toml);
//!     let branches = read_toml(&mut reader)?;
//!
//!     // Check the `Branches` struct.
//!     let branch_map = branches.branch_map();
//!     assert_eq!(branch_map.keys().len(), 3);
//!     assert!(branch_map.contains_key("repomon"));
//!     assert!(branch_map.contains_key("repomon-config"));
//!     assert!(branch_map.contains_key("blah"));
//!
//!     // Check we have the right number of branch definitions per repo.
//!     let mut branches = branch_map.get("repomon").ok_or("invalid key")?;
//!     assert_eq!(branches.len(), 2);
//!     branches = branch_map.get("repomon-config").ok_or("invalid key")?;
//!     assert_eq!(branches.len(), 1);
//!     branches = branch_map.get("blah").ok_or("invalid key")?;
//!     assert_eq!(branches.len(), 1);
//! #   Ok(())
//! # }
//! ```
//!
//! ## Write to TOML string
//!
//! ```
//! # use repomon_config::error::Result;
//! # use repomon_config::{write_toml, Branch, Branches};
//! # use std::collections::BTreeMap;
//! # use std::io::{Cursor, Write};
//! #
//! # const TEST_TOML: &str = r#"[[branch.blah]]
//! # name = "origin/master"
//! # interval = "1m"
//! #
//! # [[branch.repomon]]
//! # name = "origin/master"
//! # interval = "1m"
//! #
//! # [[branch.repomon]]
//! # name = "origin/feature/testing"
//! # interval = "1m"
//! #
//! # [[branch.repomon-config]]
//! # name = "origin/master"
//! # interval = "1m"
//! # "#;
//! #
//! # fn write() -> Result<()> {
//!       // Setup the `Branches` struct.
//!       let mut master: Branch = Default::default();
//!       master.set_name("origin/master".to_string());
//!       master.set_interval("1m".to_string());
//!
//!       let mut feature_testing: Branch = Default::default();
//!       feature_testing.set_name("origin/feature/testing".to_string());
//!       feature_testing.set_interval("1m".to_string());
//!
//!       let repomon_branches = vec![master.clone(), feature_testing];
//!       let blah_branches = vec![master.clone()];
//!       let repomon_config_branches = vec![master];
//!
//!       let mut branch_map = BTreeMap::new();
//!       branch_map.insert("repomon".to_string(), repomon_branches);
//!       branch_map.insert("repomon-config".to_string(), repomon_config_branches);
//!       branch_map.insert("blah".to_string(), blah_branches);
//!
//!       let mut branches: Branches = Default::default();
//!       branches.set_branch_map(branch_map);
//!
//!       // Write the TOML to the given buf.
//!       let mut buf = [0; 5000];
//!
//!       // Wrapped to drop mutable borrow.
//!       {
//!         let mut writer = Cursor::new(&mut buf[..]);
//!         write_toml(&branches, &mut writer)?;
//!       }
//!
//!       // Check that the result is the same as the TOML above.
//!       assert_eq!(TEST_TOML, String::from_utf8_lossy(&buf));
//! #   Ok(())
//! # }
//! ```
//!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate getset;
#[macro_use]
extern crate serde_derive;

extern crate toml;

use error::Result;
use std::collections::BTreeMap;
use std::io::{Read, Write};

pub mod error;

/// A map of repo name to branch definitions.
#[derive(Clone, Debug, Default, Deserialize, Getters, Serialize, Setters)]
pub struct Branches {
    /// A map of repo name to a vector branches to monitor.
    #[get = "pub"]
    #[set = "pub"]
    #[serde(rename = "branch")]
    branch_map: BTreeMap<String, Vec<Branch>>,
}

/// A branch to monitor for changes.
#[derive(Clone, Debug, Default, Deserialize, Getters, Serialize, Setters)]
pub struct Branch {
    /// The fully qualified branch name, e.g. `origin/master` for the remote
    /// or `master` for the local.
    #[get = "pub"]
    #[set = "pub"]
    name: String,
    /// The interval to check the branch for changes.
    #[get = "pub"]
    #[set = "pub"]
    interval: String,
}

/// Read TOML from the given `reader` and deserialize into a `Repos` struct.
pub fn read_toml<R>(reader: &mut R) -> Result<Branches>
where
    R: Read,
{
    let mut toml_str = String::new();
    let bytes_read = reader.read_to_string(&mut toml_str)?;

    if bytes_read > 0 {
        Ok(toml::from_str(&toml_str)?)
    } else {
        Err("Unable to read any bytes from the reader".into())
    }
}

/// Write TOML serialized from the `repos` struct to the given writer.
pub fn write_toml<W>(repos: &Branches, writer: &mut W) -> Result<()>
where
    W: Write,
{
    let toml = toml::to_string(&repos)?;
    Ok(writer.write_all(toml.as_bytes())?)
}

#[cfg(test)]
mod tests {
    use super::{Branch, Branches};
    use std::collections::BTreeMap;
    use std::io::Cursor;
    use toml;

    const TEST_TOML: &str = r#"[[branch.blah]]
name = "origin/master"
interval = "1m"

[[branch.repomon]]
name = "origin/master"
interval = "1m"

[[branch.repomon]]
name = "origin/feature/testing"
interval = "1m"

[[branch.repomon-config]]
name = "origin/master"
interval = "1m"
"#;

    fn setup_branches() -> Branches {
        let master = Branch {
            name: "origin/master".to_string(),
            interval: "1m".to_string(),
        };

        let feature_testing = Branch {
            name: "origin/feature/testing".to_string(),
            interval: "1m".to_string(),
        };

        let repomon_branches = vec![master.clone(), feature_testing];
        let blah_branches = vec![master.clone()];
        let repomon_config_branches = vec![master];

        let mut branch_map = BTreeMap::new();
        branch_map.insert("repomon".to_string(), repomon_branches);
        branch_map.insert("repomon-config".to_string(), repomon_config_branches);
        branch_map.insert("blah".to_string(), blah_branches);

        Branches {
            branch_map: branch_map,
        }
    }

    fn test_branches(branches: &Branches) {
        let branch_map = branches.branch_map();
        assert_eq!(branch_map.keys().len(), 3);
        assert!(branch_map.contains_key("repomon"));
        assert!(branch_map.contains_key("repomon-config"));
        assert!(branch_map.contains_key("blah"));

        let mut branches = branch_map
            .get("repomon")
            .ok_or("invalid key")
            .expect("Unable to lookup repomon repo");
        assert_eq!(branches.len(), 2);
        branches = branch_map
            .get("repomon-config")
            .ok_or("invalid key")
            .expect("Unable to lookup repomon repo");
        assert_eq!(branches.len(), 1);
        branches = branch_map
            .get("blah")
            .ok_or("invalid key")
            .expect("Unable to lookup repomon repo");
        assert_eq!(branches.len(), 1);
    }

    #[test]
    fn serialize() {
        let branches = setup_branches();
        let toml = toml::to_string(&branches).expect("Unable to serialize to TOML");
        assert_eq!(TEST_TOML, toml);
    }

    #[test]
    fn deserialize() {
        let branches: Branches = toml::from_str(TEST_TOML).expect("Unable to deserialize TOML");
        test_branches(&branches);
    }

    #[test]
    fn empty_reader() {
        let mut cursor = Cursor::new(vec![]);
        match super::read_toml(&mut cursor) {
            Ok(_) => assert!(false, "0 bytes read should error"),
            Err(_) => assert!(true),
        }
    }

    #[test]
    fn read_toml() {
        let mut reader = Cursor::new(TEST_TOML);

        match super::read_toml(&mut reader) {
            Ok(branches) => test_branches(&branches),
            Err(_) => assert!(false, "Unable to parse TOML"),
        }
    }

    #[test]
    fn write_toml() {
        let mut buf = [0; 5000];
        let branches = setup_branches();
        {
            let mut writer = Cursor::new(&mut buf[..]);
            match super::write_toml(&branches, &mut writer) {
                Ok(_) => {}
                Err(_) => assert!(false, "Unable to write TOML"),
            }
        }

        let filtered = buf.iter().filter(|x| **x > 0).cloned().collect::<Vec<u8>>();
        assert_eq!(
            TEST_TOML,
            String::from_utf8(filtered).expect("Invalid UTF-8 in result")
        );
    }
}