magg 0.4.4

Opinionated tools for Rust devs
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use crate::code_of_conduct::get_code_of_conduct;
use crate::config::load_config;
use crate::errors::*;
use crate::licenses::{get_apache_license, get_apache_notice, get_mit_license};
use crate::project_report::get_project_report;
use crate::utils::SEPARATOR_LINE;
use crate::{changelog, crate_list, utils};
use crate::{readme, workflows};
use antex::{StyledText, Text, auto};
use clap::{Arg, ArgAction, ArgMatches, Command, command, crate_version};

enum Action {
    /// Generate README file for regular crate.
    ReadmeForRegularCrate(
        /// Name of the file containing the body text of README file.
        String,
        /// Scaffolded README file name.
        String,
    ),
    /// Generate README file for crate in ÐecisionToolkit project.
    ReadmeForDecisionToolkitCrate(
        /// Name of the file containing the body text of README file.
        String,
        /// Scaffolded README file name.
        String,
    ),
    /// Generate license files.
    Licenses,
    /// Generate code of conduct file.
    CodeOfConduct,
    /// Generate workflows files.
    Workflows,
    /// Generate changelog.
    Changelog(
        /// Start revision.
        String,
        /// End revision.
        String,
        /// Milestone.
        String,
        /// Organization/Repository name.
        String,
        /// Current directory.
        String,
        /// Verbose flag.
        bool,
        /// String patterns for excluding commits by subject.
        Vec<String>,
        /// String patterns for excluding pull requests by title.
        Vec<String>,
    ),
    ProjectReport(
        /// Owner name of the project.
        String,
        /// Project name.
        String,
    ),
    /// Generate a list of owned crates.
    Crates,
    /// Do nothing.
    Nothing,
}

/// Parses CLI argument matches.
fn get_matches() -> ArgMatches {
    command!()
        // disable the built-in version flag
        .disable_version_flag(true)
        // handle the version flag in a custom way
        .arg(Arg::new("version").short('V').long("version").help("Print version").action(ArgAction::SetTrue))
        // Generate README file for regular crate.
        .subcommand(
            Command::new("readme")
                .about("Generates README file for regular crate")
                .display_order(1)
                .arg(
                    Arg::new("input-file")
                        .short('f')
                        .long("input-file")
                        .help("File containing the body of the scaffolded README")
                        .action(ArgAction::Set)
                        .default_value("docs/prelude.md")
                        .display_order(1),
                )
                .arg(
                    Arg::new("output-file")
                        .short('o')
                        .long("output-file")
                        .help("Scaffolded README file name")
                        .action(ArgAction::Set)
                        .default_value("README.md")
                        .display_order(1),
                ),
        )
        // Generate README file for a crate in ÐecisionToolkit project.
        .subcommand(
            Command::new("readme-dt")
                .about("Generates README file for crate in ÐecisionToolkit project")
                .display_order(2)
                .arg(
                    Arg::new("input-file")
                        .short('f')
                        .long("input-file")
                        .help("File containing the body of the scaffolded README")
                        .action(ArgAction::Set)
                        .default_value("docs/prelude.md")
                        .display_order(1),
                )
                .arg(
                    Arg::new("output-file")
                        .short('o')
                        .long("output-file")
                        .help("Scaffolded README file name")
                        .action(ArgAction::Set)
                        .default_value("README.md")
                        .display_order(1),
                ),
        )
        .subcommand(Command::new("licenses").about("Generates MIT and Apache 2.0 license files").display_order(3))
        .subcommand(Command::new("code-of-conduct").about("Generates code of conduct file").display_order(4))
        .subcommand(Command::new("workflows").about("Generates GitHub workflows").display_order(5))

        .subcommand(
            Command::new("changelog")
                .about("Generates changelog")
                .display_order(6)
                .arg(
                    Arg::new("start-revision")
                        .short('s')
                        .long("start")
                        .help("Start revision for searching commits")
                        .action(ArgAction::Set)
                        .required(true)
                        .display_order(1),
                )
                .arg(
                    Arg::new("end-revision")
                        .short('e')
                        .long("end")
                        .help("End revision for searching commits")
                        .action(ArgAction::Set)
                        .required(true)
                        .display_order(2),
                )
                .arg(
                    Arg::new("milestone")
                        .short('m')
                        .long("milestone")
                        .help("GitHub milestone name for searching issues and pull requests")
                        .action(ArgAction::Set)
                        .required(true)
                        .display_order(3),
                )
                .arg(
                    Arg::new("repository")
                        .short('r')
                        .long("repo")
                        .help("GitHub organization/repository name for searching issues and pull requests")
                        .action(ArgAction::Set)
                        .required(true)
                        .display_order(4),
                )
                .arg(
                    Arg::new("directory")
                        .short('d')
                        .long("dir")
                        .help("Directory of a Git repository for searching commits")
                        .action(ArgAction::Set)
                        .default_value(".")
                        .default_missing_value(".")
                        .num_args(0..=1)
                        .display_order(5),
                )
                .arg(
                    Arg::new("verbose")
                        .long("verbose")
                        .help("Set this flag to display more detailed report")
                        .action(ArgAction::SetTrue)
                        .default_value("false")
                        .default_missing_value("true")
                        .display_order(6),
                )
                .arg(
                    Arg::new("exclude-commit")
                        .long("exclude-commit")
                        .help("Exclude commits that contain this text in subject")
                        .action(ArgAction::Append)
                        .display_order(7),
                )
                .arg(
                    Arg::new("exclude-pr")
                        .long("exclude-pr")
                        .help("Exclude pull requests that contain this text in title")
                        .action(ArgAction::Append)
                        .display_order(8),
                ),
        )
        .subcommand(
            Command::new("project-report")
                .about("Generates project report")
                .display_order(7)
                .arg(
                    Arg::new("owner")
                        .short('o')
                        .long("owner")
                        .help("Project owner")
                        .action(ArgAction::Set)
                        .required(true)
                        .display_order(1),
                )
                .arg(
                    Arg::new("name")
                        .short('n')
                        .long("name")
                        .help("Project name")
                        .action(ArgAction::Set)
                        .required(true)
                        .display_order(2),
                ),
        )
        .subcommand(Command::new("crates").about("Generates list of owned crates").display_order(8))
        .get_matches()
}

/// Checks the list of arguments passed from the command line
/// and returns an action related to a valid argument.
fn get_cli_action() -> Action {
    let matches = get_matches();
    // Replaces the built-in version flag with the custom handler.
    if matches.get_flag("version") {
        // Displays only the version number, without the name of the crate.
        println!("{}", crate_version!());
        return Action::Nothing;
    }
    match matches.subcommand() {
        Some(("readme", matches)) => {
            let input_file = match_string(matches, "input-file");
            let output_file = match_string(matches, "output-file");
            return Action::ReadmeForRegularCrate(input_file, output_file);
        }
        Some(("readme-dt", matches)) => {
            let input_file = match_string(matches, "input-file");
            let output_file = match_string(matches, "output-file");
            return Action::ReadmeForDecisionToolkitCrate(input_file, output_file);
        }
        Some(("licenses", _matches)) => {
            return Action::Licenses;
        }
        Some(("code-of-conduct", _matches)) => {
            return Action::CodeOfConduct;
        }
        Some(("workflows", _matches)) => {
            return Action::Workflows;
        }
        Some(("changelog", matches)) => {
            let start_revision = match_string(matches, "start-revision");
            let end_revision = match_string(matches, "end-revision");
            let milestone = match_string(matches, "milestone");
            let repository = match_string(matches, "repository");
            let dir = match_string(matches, "directory");
            let verbose = match_boolean(matches, "verbose");
            let exclude_commit = match_strings(matches, "exclude-commit");
            let exclude_pr = match_strings(matches, "exclude-pr");
            return Action::Changelog(
                start_revision,
                end_revision,
                milestone,
                repository,
                dir,
                verbose,
                exclude_commit,
                exclude_pr,
            );
        }
        Some(("project-report", matches)) => {
            let project_owner = match_string(matches, "owner");
            let project_name = match_string(matches, "name");
            return Action::ProjectReport(project_owner, project_name);
        }
        Some(("crates", _matches)) => {
            return Action::Crates;
        }
        _ => {}
    }
    Action::Nothing
}

pub fn do_action() {
    // Utility function for building an error message.
    fn error_message(reason: MaggError) -> Text {
        auto()
            .bold()
            .red()
            .s("error")
            .reset()
            .s(": ")
            .s(reason.to_string())
    }

    // Load configuration from file.
    let config = load_config();

    match get_cli_action() {
        Action::ReadmeForRegularCrate(input_file, output_file) => {
            match readme::get_readme_for_regular_crate(input_file) {
                Ok(contents) => {
                    utils::write_file(output_file, &contents).unwrap();
                }
                Err(reason) => {
                    eprintln!("{}", error_message(reason));
                    std::process::exit(1);
                }
            }
        }
        Action::ReadmeForDecisionToolkitCrate(input_file, output_file) => {
            match readme::get_readme_for_decision_toolkit_crate(input_file) {
                Ok(contents) => {
                    utils::write_file(output_file, &contents).unwrap();
                }
                Err(reason) => {
                    eprintln!("{}", error_message(reason));
                    std::process::exit(1);
                }
            }
        }
        Action::Licenses => {
            let copyright_owner = &config.licenses.copyright_owner;
            utils::write_file("LICENSE-APACHE", &get_apache_license()).unwrap();
            utils::write_file("NOTICE", &get_apache_notice(copyright_owner)).unwrap();
            utils::write_file("LICENSE-MIT", &get_mit_license(copyright_owner)).unwrap();
        }
        Action::CodeOfConduct => {
            utils::write_file(
                "CODE_OF_CONDUCT.md",
                &get_code_of_conduct(&config.emails.code_of_conduct),
            )
            .unwrap();
        }
        Action::Workflows => {
            utils::write_file(
                ".github/workflows/build-linux-gnu.yml",
                &workflows::get_build_linux_gnu(),
            )
            .unwrap();
            utils::write_file(
                ".github/workflows/build-linux-musl.yml",
                &workflows::get_build_linux_musl(),
            )
            .unwrap();
            utils::write_file(
                ".github/workflows/build-macos.yml",
                &workflows::get_build_macos(),
            )
            .unwrap();
            utils::write_file(
                ".github/workflows/build-macos-aarch64.yml",
                &workflows::get_build_macos_aarch64(),
            )
            .unwrap();
            utils::write_file(
                ".github/workflows/build-windows.yml",
                &workflows::get_build_windows(),
            )
            .unwrap();
        }
        Action::Changelog(
            start_revision,
            end_revision,
            milestone,
            repository,
            dir,
            verbose,
            exclude_commit,
            exclude_pr,
        ) => {
            match changelog::get_changelog(
                verbose,
                &start_revision,
                &end_revision,
                &milestone,
                &repository,
                &dir,
                exclude_commit,
                exclude_pr,
            ) {
                Ok(changelog) => {
                    println!("\nCHANGELOG");
                    println!("{SEPARATOR_LINE}");
                    println!("{changelog}")
                }
                Err(reason) => {
                    eprintln!("\n{}", error_message(reason));
                    std::process::exit(1);
                }
            }
        }
        Action::ProjectReport(project_owner, project_name) => {
            // Generates a report of the project.
            match get_project_report(&project_owner, &project_name) {
                Ok(report) => {
                    println!("\n{report}")
                }
                Err(reason) => {
                    eprintln!("\n{}", error_message(reason));
                    std::process::exit(1);
                }
            }
        }
        Action::Crates => {
            let crates = crate_list::get_crates(&config.crates_io.id);
            for c in crates {
                println!(
                    "{} | v{} | {} | {}",
                    c.name, c.max_version, c.description, c.repository
                );
            }
        }
        Action::Nothing => {
            // No action was requested.
        }
    }
}

/// Matches a mandatory string argument.
fn match_string(matches: &ArgMatches, name: &str) -> String {
    matches.get_one::<String>(name).unwrap().trim().to_string()
}

/// Matches a mandatory boolean argument.
fn match_boolean(matches: &ArgMatches, name: &str) -> bool {
    matches.get_flag(name)
}

/// Matches an optional repeatable string argument.
fn match_strings(matches: &ArgMatches, name: &str) -> Vec<String> {
    matches
        .get_many(name)
        .unwrap_or_default()
        .cloned()
        .collect()
}