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
//! Changelog

use std::path::Path;

use gitcc_changelog::{Changelog, Release, Section};
use gitcc_git::{discover_repo, get_origin_url};
use indexmap::{indexmap, IndexMap};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

use crate::{Commit, CommitHistory, Config, Error};

/// Changelog configuration
#[derive(Debug, Serialize, Deserialize)]
pub struct ChangelogConfig {
    /// Release sections
    ///
    /// The key is the group label, and the value is a list of commit types
    ///
    /// # Notes
    ///
    /// [IndexMap] is used to maintain an order of groups
    pub sections: IndexMap<String, Vec<String>>,
}

impl Default for ChangelogConfig {
    fn default() -> Self {
        let sections = indexmap! {
            "New features".to_string() => vec!["feat".to_string()],
            "Bug fixes".to_string() => vec!["fix".to_string()],
            "Documentation".to_string() => vec!["docs".to_string()],
            "Performance improvements".to_string() => vec!["perf".to_string()],
            "Tooling".to_string() => vec![
                "build".to_string(),
                "ci".to_string(),
                "cd".to_string()
            ],
        };
        Self { sections }
    }
}

impl ChangelogConfig {
    /// Returns the section label for a specific commit type
    fn find_section_for_commit_type(&self, r#type: &str) -> Option<String> {
        for (section_label, commit_types) in &self.sections {
            if commit_types.contains(&r#type.to_string()) {
                return Some(section_label.clone());
            }
        }
        None
    }
}

/// Changelog build options
#[derive(Debug, Clone, Default)]
pub struct ChangelogBuildOptions {
    /// Origin name (`origin` by default)
    pub origin_name: Option<String>,
    /// Includes all commits
    pub all: bool,
}

/// Builds the changelog
///
/// # Arguments
/// - the `origin` is the origin name (`origin` by default)
pub fn build_changelog(
    cwd: &Path,
    cfg: &Config,
    history: &CommitHistory,
    opts: Option<ChangelogBuildOptions>,
) -> Result<Changelog, Error> {
    let opts = opts.unwrap_or_default();
    let repo = discover_repo(cwd)?;

    let origin_name = opts.origin_name.unwrap_or("origin".to_owned());
    let origin_url = get_origin_url(&repo, &origin_name)?.ok_or(Error::msg(
        format!("remote origin '{origin_name}' not found").as_str(),
    ))?;

    let mut releases = vec![];
    for (release_tag, release_commits) in history
        .commits
        .iter()
        .group_by(|c| c.version_tag.clone())
        .into_iter()
    {
        // eprintln!(
        //     "RELEASE: {}",
        //     release_tag
        //         .as_ref()
        //         .map(|t| t.name.to_string())
        //         .unwrap_or("unreleased".to_string())
        // );

        let mut sections: IndexMap<String, Section> = IndexMap::new();
        for (s_label, _) in &cfg.changelog.sections {
            sections.insert(s_label.to_string(), Section::new(s_label));
        }
        const UNCATEGORIZED: &str = "Uncategorized"; // commits with no type
        const HIDDEN: &str = "__Hidden__"; // ignored commits (types not included)
        sections.insert(UNCATEGORIZED.to_string(), Section::new(UNCATEGORIZED));
        sections.insert(HIDDEN.to_string(), Section::new(HIDDEN));

        for c in release_commits {
            // eprintln!("{}", c.subject());
            let c_sect_label = match &c.conv_message {
                Some(m) => {
                    // eprint!("=> is conventional: {}", m.r#type);
                    match cfg.changelog.find_section_for_commit_type(&m.r#type) {
                        Some(label) => {
                            // eprintln!("=> section: {}", label);
                            label
                        }
                        None => {
                            // eprintln!("=> HIDDEN");
                            HIDDEN.to_string()
                        }
                    }
                }
                None => UNCATEGORIZED.to_string(),
            };

            if c_sect_label == HIDDEN && !opts.all {
                continue;
            }

            let section = sections.get_mut(&c_sect_label).unwrap();
            section.items.push(commit_oneliner(&origin_url, c));
        }

        // remove empty sections
        let sections: Vec<_> = sections
            .into_iter()
            .filter_map(|(_, v)| if v.items.is_empty() { None } else { Some(v) })
            .collect();

        let release_version = release_tag
            .as_ref()
            .map(|t| t.name.to_string())
            .unwrap_or("Unreleased".to_string());
        let release_date = release_tag
            .as_ref()
            .map(|t| t.date)
            .unwrap_or(OffsetDateTime::now_utc());
        let release_url = release_tag
            .as_ref()
            .map(|t| build_release_url(&origin_url, &t.name));

        let release = Release {
            version: release_version,
            date: release_date,
            url: release_url,
            sections,
        };
        releases.push(release);
    }

    Ok(Changelog { releases })
}

/// Builds the release URL
///
/// eg. https://github.com/nlargueze/gitcc/releases/tag/v0.0.15
/// eg. https://github.com/nlargueze/repo/compare/v0.1.1...v0.1.2
fn build_release_url(origin_url: &str, version: &str) -> String {
    format!("{origin_url}/releases/tag/{version}")
}

/// Builders the commit
///
/// eg: chore!: refactoring [#e88da](https://github.com/nlargueze/repo/commit/e88dae6d48fd85b094f58eab029a883969436101)
fn commit_oneliner(origin_url: &str, commit: &Commit) -> String {
    format!(
        "{} [{}]({}/commit/{})",
        commit.subject(),
        commit.short_id(),
        origin_url,
        commit.id
    )
}

#[cfg(test)]
mod tests {
    use crate::commit_history;

    use super::*;

    #[test]
    fn test_changelog() {
        let cwd = std::env::current_dir().unwrap();
        let cfg = Config::load_from_fs(&cwd).unwrap().unwrap_or_default();
        let history = commit_history(&cwd, &cfg).unwrap();
        let _changelog = build_changelog(&cwd, &cfg, &history, None).unwrap();
        // eprintln!("{:#?}", changelog);
        // let changelog_str = changelog.generate(TEMPLATE_CHANGELOG_STD).unwrap();
        // eprintln!("{}", changelog_str);
    }
}