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
// Copyright 2017-2018 by Aldrin J D'Souza.
// Licensed under the MIT License <https://opensource.org/licenses/MIT>

use std::fs::File;
use super::Result;
use std::io::prelude::*;
use serde_yaml::from_str;
use std::env::current_dir;

/// The YAML configuration file name (`.changelog.yml`).
///
/// The library looks for a file with this name in the current directory and all its ancestors (up to root). If
/// one is found, it is used to initialize configuration, if not the default configuration is used.
pub const CONFIG_FILE: &str = ".changelog.yml";

/// The embedded configuration used when none is provided by the user.
const CONFIG_DEFAULT: &str = include_str!("assets/changelog.yml");

/// The Handlebars template file name (`.changelog.hbs`).
///
/// The library looks for a file with this name (`.changelog.hbs`) in the current directory and all its ancestors
/// (up to root). If one is found, it is used to render the changelog, if not the default template is used.
pub const TEMPLATE_FILE: &str = ".changelog.hbs";

/// The embedded template that is used when none is provided by the user.
const TEMPLATE_DEFAULT: &str = include_str!("assets/changelog.hbs");

/// The tool configuration.
///
/// The configuration defines the repository conventions and output preferences.
#[serde(default)]
#[derive(Debug, Default, Deserialize)]
pub struct Configuration {
    /// The project conventions
    pub conventions: Conventions,

    /// The output preferences
    pub output: OutputPreferences,
}

/// The change categorization conventions used by a repository/project.
#[serde(default)]
#[derive(Debug, Default, Deserialize, Eq, PartialEq)]
pub struct Conventions {
    /// The scope keywords
    pub scopes: Vec<Keyword>,

    /// The category keywords
    pub categories: Vec<Keyword>,
}

/// A keyword used to categorize commit message lines.
#[serde(default)]
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct Keyword {
    /// The identifying tag used in commit messages.
    pub tag: String,

    /// The presentation title that shows up in the final change log.
    pub title: String,
}

/// The output preferences
#[serde(default)]
#[derive(Debug, Default, Deserialize, Eq, PartialEq)]
pub struct OutputPreferences {
    /// Output as JSON
    pub json: bool,

    /// Output Handlebar template
    pub template: Option<String>,

    /// The remote url
    pub remote: Option<String>,

    /// Output line post-processors
    pub post_processors: Vec<PostProcessor>,
}

/// A post-processor definition.
#[serde(default)]
#[derive(Debug, Default, Deserialize, Eq, PartialEq)]
pub struct PostProcessor {
    /// The lookup pattern
    pub lookup: String,

    /// The replace pattern
    pub replace: String,
}

impl Configuration {
    /// Default constructor
    pub fn new() -> Self {
        Self::from_file(None).unwrap_or_else(|_| Self::default())
    }

    /// Construct from the given YAML file
    pub fn from_file(file: Option<&str>) -> Result<Self> {
        file.map(str::to_owned)
            .or_else(|| find_file(CONFIG_FILE))
            .map_or_else(|| Ok(String::from(CONFIG_DEFAULT)), |f| read_file(&f))
            .and_then(|yml| Self::from_yaml(&yml))
    }

    /// Construct from the given YAML string
    pub fn from_yaml(yml: &str) -> Result<Self> {
        from_str(yml).map_err(|e| format_err!("Configuration contains invalid YAML: {}", e))
    }
}

impl Conventions {
    /// Get the title for the given scope
    pub fn scope_title(&self, scope: Option<String>) -> Option<&str> {
        self.title(&self.scopes, scope)
    }

    /// Get the title for the given category
    pub fn category_title(&self, category: Option<String>) -> Option<&str> {
        self.title(&self.categories, category)
    }

    /// Get the titles for all the categories defined
    pub fn category_titles(&self) -> Vec<&str> {
        Self::titles(&self.categories)
    }

    /// Get the titles for all the scopes defined
    pub fn scope_titles(&self) -> Vec<&str> {
        Self::titles(&self.scopes)
    }

    /// Given the available keywords, get the title for the given tag
    fn title<'a>(&'a self, keywords: &'a [Keyword], tag: Option<String>) -> Option<&'a str> {
        // The least we have is a "blank" one.
        if keywords.is_empty() && tag.is_none() {
            return Some("");
        }

        // Look in the list for one that matches the given tag
        let given = tag.unwrap_or_default();
        for kw in keywords {
            if kw.tag == given {
                return Some(&kw.title);
            }
        }

        None
    }

    /// Given the available keywords, get a iterable list of the titles
    fn titles(keywords: &[Keyword]) -> Vec<&str> {
        if keywords.is_empty() {
            vec![""]
        } else {
            keywords.iter().map(|k| k.title.as_ref()).collect()
        }
    }
}

impl Keyword {
    /// Construct a keyword from the tag and title
    pub fn new<T: AsRef<str>>(tag: T, title: T) -> Self {
        Keyword {
            tag: tag.as_ref().to_owned(),
            title: title.as_ref().to_owned(),
        }
    }
}

impl OutputPreferences {
    /// Default constructor
    pub fn new() -> Self {
        Self::default()
    }

    /// Get the template definition
    pub fn get_template(&self) -> Result<String> {
        self.template
            .clone()
            .or_else(|| find_file(TEMPLATE_FILE))
            .map_or_else(|| Ok(String::from(TEMPLATE_DEFAULT)), |f| read_file(&f))
    }
}

/// Read the given file to a String (with logging)
fn read_file(name: &str) -> Result<String> {
    // Return the data
    info!("Reading file '{}'", name);
    let mut contents = String::new();

    File::open(name)
        .map_err(|e| format_err!("Cannot open file '{}' (Reason: {})", name, e))?
        .read_to_string(&mut contents)
        .map_err(|e| format_err!("Cannot read file '{}' (Reason: {})", name, e))?;

    Ok(contents)
}

/// Identify the closest configuration file that should be used for this run
fn find_file(file: &str) -> Option<String> {
    // Start at the current directory
    let mut cwd = current_dir().expect("Current directory is invalid");

    // While we have hope
    while cwd.exists() {
        // Set the filename we're looking for
        cwd.push(file);

        // If we find it
        if cwd.is_file() {
            // return it
            return Some(cwd.to_string_lossy().to_string());
        }

        // If not, remove the filename
        cwd.pop();

        // If we have room to go up
        if cwd.parent().is_some() {
            // Go up the path
            cwd.pop();
        } else {
            // Get out
            break;
        }
    }

    // No file found
    None
}

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

    #[test]
    fn configuration_from_yaml() {
        let project = include_str!("../.changelog.yml");
        let no_category = r#"
        conventions:
          scopes: [{keyword:"a", title: "A"}]
        "#;
        let no_scope = r#"
        conventions:
          categories: [{keyword:"a", title: "A"}]
        "#;
        assert!(Configuration::from_yaml("").is_err());
        assert!(Configuration::from_yaml(project).is_ok());
        assert!(Configuration::from_yaml(no_scope).is_ok());
        assert!(Configuration::from_yaml(no_category).is_ok());
    }

    #[test]
    fn find_file() {
        use super::find_file;
        assert!(find_file("unknown").is_none());
        assert!(find_file("Cargo.toml").is_some());
    }
}