unclog 0.7.3

unclog allows you to build your changelog from a collection of independent files. This helps prevent annoying and unnecessary merge conflicts when collaborating on shared codebases.
Documentation
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! `unclog` helps you build your changelog.

use clap::{Parser, Subcommand, ValueEnum};
use log::error;
use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
use std::path::{Path, PathBuf};
use unclog::{Changelog, Config, Error, PlatformId, Result};

const RELEASE_SUMMARY_TEMPLATE: &str = r#"<!--
    Add a summary for the release here.

    If you don't change this message, or if this file is empty, the release
    will not be created. -->
"#;

const ADD_CHANGE_TEMPLATE: &str = r#"<!--
    Add your entry's details here (in Markdown format).

    If you don't change this message, or if this file is empty, the entry will
    not be created. -->
"#;

const DEFAULT_CHANGELOG_DIR: &str = ".changelog";
const DEFAULT_CONFIG_FILENAME: &str = "config.toml";

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Opt {
    /// The path to the changelog folder.
    #[arg(short, long, default_value = DEFAULT_CHANGELOG_DIR)]
    path: PathBuf,

    /// The path to the changelog configuration file. If a relative path is
    /// provided, it is assumed this is relative to the `path` parameter. If no
    /// configuration file exists, defaults will be used for all parameters.
    #[arg(short, long, default_value = DEFAULT_CONFIG_FILENAME)]
    config_file: PathBuf,

    /// Increase output logging verbosity to DEBUG level.
    #[arg(short, long)]
    verbose: bool,

    /// Suppress all output logging (overrides `--verbose`).
    #[arg(short, long)]
    quiet: bool,

    #[command(subcommand)]
    cmd: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Create and initialize a fresh .changelog folder.
    Init {
        /// The path to a prologue to optionally prepend to the changelog.
        #[arg(name = "prologue", short, long)]
        maybe_prologue_path: Option<PathBuf>,

        /// The path to an epilogue to optionally append to the new changelog.
        #[arg(name = "epilogue", short, long)]
        maybe_epilogue_path: Option<PathBuf>,

        /// Automatically generate a `config.toml` file for your changelog,
        /// inferring parameters from your environment. This is the same as
        /// running `unclog generate-config` after `unclog init`.
        #[arg(short, long)]
        gen_config: bool,

        /// If automatically generating configuration, the Git remote from which
        /// to infer the project URL.
        #[arg(short, long, default_value = "origin")]
        remote: String,
    },
    /// Automatically generate a configuration file, attempting to infer as many
    /// parameters as possible from your project's environment.
    GenerateConfig {
        /// The Git remote from which to infer the project URL.
        #[arg(short, long, default_value = "origin")]
        remote: String,

        /// Overwrite any existing configuration file.
        #[arg(short, long)]
        force: bool,
    },
    /// Add a change to the unreleased set of changes.
    Add {
        /// The path to the editor to use to edit the details of the change.
        #[arg(long, env = "EDITOR")]
        editor: PathBuf,

        /// The component to which this entry should be added.
        #[arg(name = "component", short, long)]
        maybe_component: Option<String>,

        /// The ID of the section to which the change must be added (e.g.
        /// "breaking-changes").
        #[arg(short, long)]
        section: String,

        /// The ID of the change to add, which should include the number of the
        /// issue or PR to which the change applies (e.g. "820-change-api").
        #[arg(short, long)]
        id: String,

        /// The issue number associated with this change, if any. Only relevant
        /// if the `--message` flag is also provided. Only one of the
        /// `--issue-no` or `--pull-request` flags can be specified at a time.
        #[arg(name = "issue_no", short = 'n', long = "issue-no")]
        maybe_issue_no: Option<u32>,

        /// The number of the pull request associated with this change, if any.
        /// Only relevant if the `--message` flag is also provided. Only one of
        /// the `--issue-no` or `--pull-request` flags can be specified at a
        /// time.
        #[arg(name = "pull_request", short, long = "pull-request")]
        maybe_pull_request: Option<u32>,

        /// If specified, the change will automatically be generated from the
        /// default change template. Requires a project URL to be specified in
        /// the changelog configuration file.
        #[arg(name = "message", short, long)]
        maybe_message: Option<String>,
    },
    /// Searches for duplicate entries across releases in this changelog.
    FindDuplicates {
        /// Include the changelog path (usually ".changelog") in entry paths
        /// when listing them.
        #[arg(long)]
        include_changelog_path: bool,

        /// The format to use when writing the duplicates to stdout.
        #[arg(value_enum, short, long, default_value = "simple")]
        format: DuplicatesOutputFormat,
    },
    /// Build the changelog from the input path and write the output to stdout.
    Build {
        /// Render all changes, including released and unreleased ones.
        #[arg(short, long)]
        all: bool,
        /// Only render unreleased changes.
        #[arg(short, long)]
        unreleased_only: bool,
    },
    /// Release any unreleased features.
    Release {
        /// The path to the editor to use to edit the release summary.
        #[arg(long, env = "EDITOR")]
        editor: PathBuf,

        /// The version string to use for the new release (e.g. "v0.1.0").
        version: String,
    },
}

#[derive(Debug, Clone, Default, Copy, ValueEnum)]
enum DuplicatesOutputFormat {
    /// A simple table with no borders.
    #[default]
    Simple,
    /// A table with borders made of ASCII characters.
    AsciiTable,
}

fn main() {
    let opt: Opt = Opt::parse();
    TermLogger::init(
        if opt.quiet {
            LevelFilter::Off
        } else if opt.verbose {
            LevelFilter::Debug
        } else {
            LevelFilter::Info
        },
        Default::default(),
        TerminalMode::Stderr,
        ColorChoice::Auto,
    )
    .unwrap();

    let config_path = if opt.config_file.is_relative() {
        opt.path.join(opt.config_file)
    } else {
        opt.config_file
    };
    let config = Config::read_from_file(&config_path).unwrap();

    let result = match opt.cmd {
        Command::Init {
            maybe_prologue_path,
            maybe_epilogue_path,
            gen_config,
            remote,
        } => init_changelog(
            &config,
            &opt.path,
            &config_path,
            maybe_prologue_path,
            maybe_epilogue_path,
            gen_config,
            &remote,
        ),
        Command::GenerateConfig { remote, force } => {
            Changelog::generate_config(&config_path, opt.path, remote, force)
        }
        Command::Build {
            all,
            unreleased_only,
        } => build_changelog(&config, &opt.path, all, unreleased_only),
        Command::Add {
            editor,
            maybe_component,
            section,
            id,
            maybe_issue_no,
            maybe_pull_request,
            maybe_message,
        } => match maybe_message {
            Some(message) => match maybe_issue_no {
                Some(issue_no) => match maybe_pull_request {
                    Some(_) => Err(Error::EitherIssueNoOrPullRequest),
                    None => Changelog::add_unreleased_entry_from_template(
                        &config,
                        &opt.path,
                        &section,
                        maybe_component,
                        &id,
                        PlatformId::Issue(issue_no),
                        &message,
                    ),
                },
                None => match maybe_pull_request {
                    Some(pull_request) => Changelog::add_unreleased_entry_from_template(
                        &config,
                        &opt.path,
                        &section,
                        maybe_component,
                        &id,
                        PlatformId::PullRequest(pull_request),
                        &message,
                    ),
                    None => Err(Error::MissingIssueNoOrPullRequest),
                },
            },
            None => add_unreleased_entry_with_editor(
                &config,
                &editor,
                &opt.path,
                &section,
                maybe_component,
                &id,
            ),
        },
        Command::FindDuplicates {
            include_changelog_path,
            format,
        } => find_duplicates(&config, &opt.path, include_changelog_path, format),
        Command::Release { editor, version } => {
            prepare_release(&config, &editor, &opt.path, &version)
        }
    };
    if let Err(e) = result {
        error!("Failed: {}", e);
        std::process::exit(1);
    }
}

fn init_changelog(
    config: &Config,
    path: &Path,
    config_path: &Path,
    maybe_prologue_path: Option<PathBuf>,
    maybe_epilogue_path: Option<PathBuf>,
    gen_config: bool,
    remote: &str,
) -> Result<()> {
    Changelog::init_dir(config, path, maybe_prologue_path, maybe_epilogue_path)?;
    if gen_config {
        Changelog::generate_config(config_path, path, remote, true)
    } else {
        Ok(())
    }
}

fn build_changelog(config: &Config, path: &Path, all: bool, unreleased_only: bool) -> Result<()> {
    if all && unreleased_only {
        return Err(Error::CommandLine(
            "cannot combine --all and --unreleased-only flags when building the changelog"
                .to_string(),
        ));
    }
    let changelog = Changelog::read_from_dir(config, path)?;
    log::info!("Success!");
    if unreleased_only {
        println!("{}", changelog.render_unreleased(config)?);
    } else if all {
        println!("{}", changelog.render_all(config));
    } else {
        println!("{}", changelog.render_released(config));
    }
    Ok(())
}

fn add_unreleased_entry_with_editor(
    config: &Config,
    editor: &Path,
    path: &Path,
    section: &str,
    component: Option<String>,
    id: &str,
) -> Result<()> {
    let entry_path = Changelog::get_entry_path(
        config,
        path,
        &config.unreleased.folder,
        section,
        component.clone(),
        id,
    );
    if std::fs::metadata(&entry_path).is_ok() {
        return Err(Error::FileExists(entry_path.display().to_string()));
    }

    let tmpdir =
        tempfile::tempdir().map_err(|e| Error::Io(Path::new("tempdir").to_path_buf(), e))?;
    let tmpfile_path = tmpdir.path().join("entry.md");
    std::fs::write(&tmpfile_path, ADD_CHANGE_TEMPLATE)
        .map_err(|e| Error::Io(tmpfile_path.clone(), e))?;

    // Run the user's editor and wait for the process to exit
    let _ = std::process::Command::new(editor)
        .arg(&tmpfile_path)
        .status()
        .map_err(|e| Error::Subprocess(editor.to_str().unwrap().to_string(), e))?;

    // Check if the temporary file's content's changed, and that it's not empty
    let tmpfile_content = std::fs::read_to_string(&tmpfile_path)
        .map_err(|e| Error::Io(tmpfile_path.to_path_buf(), e))?;
    if tmpfile_content.is_empty() || tmpfile_content == ADD_CHANGE_TEMPLATE {
        log::info!("No changes to entry - not adding new entry to changelog");
        return Ok(());
    }

    Changelog::add_unreleased_entry(config, path, section, component, id, &tmpfile_content)
}

fn find_duplicates(
    config: &Config,
    path: &Path,
    include_changelog_path: bool,
    output_format: DuplicatesOutputFormat,
) -> Result<()> {
    let changelog = Changelog::read_from_dir(config, path)?;
    let dups = changelog.find_duplicates_across_releases();
    if dups.is_empty() {
        log::info!("No duplicates found");
        return Ok(());
    }
    log::info!("Found {} duplicate(s)", dups.len());

    let mut table = comfy_table::Table::new();
    table.load_preset(match output_format {
        DuplicatesOutputFormat::Simple => comfy_table::presets::NOTHING,
        DuplicatesOutputFormat::AsciiTable => comfy_table::presets::ASCII_FULL,
    });

    for (entry_path_a, entry_path_b) in dups {
        let base_path = if include_changelog_path {
            path.to_owned()
        } else {
            PathBuf::new()
        };
        table.add_row(vec![
            base_path.join(entry_path_a.as_path(config)).display(),
            base_path.join(entry_path_b.as_path(config)).display(),
        ]);
    }
    println!("{table}");
    Ok(())
}

fn prepare_release(config: &Config, editor: &Path, path: &Path, version: &str) -> Result<()> {
    // Add the summary to the unreleased folder, since we'll be moving it to
    // the new release folder
    let summary_path = path
        .join(&config.unreleased.folder)
        .join(&config.change_sets.summary_filename);
    // If the summary doesn't exist, try to create it
    if std::fs::metadata(&summary_path).is_err() {
        std::fs::write(&summary_path, RELEASE_SUMMARY_TEMPLATE)
            .map_err(|e| Error::Io(summary_path.clone(), e))?;
    }

    // Run the user's editor and wait for the process to exit
    let _ = std::process::Command::new(editor)
        .arg(&summary_path)
        .status()
        .map_err(|e| Error::Subprocess(editor.to_str().unwrap().to_string(), e))?;

    // Check if the file's contents have changed - if not, don't continue with
    // the release
    let summary_content =
        std::fs::read_to_string(&summary_path).map_err(|e| Error::Io(summary_path.clone(), e))?;
    if summary_content.is_empty() || summary_content == RELEASE_SUMMARY_TEMPLATE {
        log::info!("No changes to release summary - not creating a new release");
        return Ok(());
    }

    Changelog::prepare_release_dir(config, path, version)
}