Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(args): support initialization with built-in templates #370

Merged
merged 3 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 94 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion git-cliff-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ features = ["serde"]

[dependencies.rust-embed]
version = "8.0.0"
features = ["debug-embed"]
features = ["debug-embed", "compression"]

[dev-dependencies]
pretty_assertions = "1.4.0"
Expand Down
30 changes: 29 additions & 1 deletion git-cliff-core/src/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::error::{
use rust_embed::RustEmbed;
use std::str;

/// Configuration file embedder/extractor.
/// Default configuration file embedder/extractor.
///
/// Embeds `config/`[`DEFAULT_CONFIG`] into the binary.
///
Expand All @@ -35,3 +35,31 @@ impl EmbeddedConfig {
Ok(toml::from_str(&Self::get_config()?)?)
}
}

/// Built-in configuration file embedder/extractor.
///
/// Embeds the files under `/examples/` into the binary.
#[derive(RustEmbed)]
#[folder = "../examples"]
pub struct BuiltinConfig;

impl BuiltinConfig {
/// Extracts the embedded content.
pub fn get_config(mut name: String) -> Result<String> {
if !name.ends_with(".toml") {
name = format!("{name}.toml");
}
let contents = match Self::get(&name) {
Some(v) => Ok(str::from_utf8(&v.data)?.to_string()),
None => Err(Error::EmbeddedError(format!("config {} not found", name,))),
}?;
Ok(contents)
}

/// Parses the extracted content into [`Config`] along with the name.
///
/// [`Config`]: Config
pub fn parse(name: String) -> Result<(Config, String)> {
Ok((toml::from_str(&Self::get_config(name.to_string())?)?, name))
}
}
12 changes: 9 additions & 3 deletions git-cliff/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ pub struct Opt {
/// Increases the logging verbosity.
#[arg(short, long, action = ArgAction::Count, alias = "debug", help_heading = Some("FLAGS"))]
pub verbose: u8,
/// Writes the default configuration file to cliff.toml
#[arg(
short,
long,
value_name = "CONFIG",
num_args = 0..=1,
required = false
)]
pub init: Option<Option<String>>,
/// Sets the configuration file.
#[arg(
short,
Expand Down Expand Up @@ -162,9 +171,6 @@ pub struct Opt {
allow_hyphen_values = true
)]
pub body: Option<String>,
/// Writes the default configuration file to cliff.toml
#[arg(short, long, help_heading = Some("FLAGS"))]
pub init: bool,
/// Processes the commits starting from the latest tag.
#[arg(short, long, help_heading = Some("FLAGS"))]
pub latest: bool,
Expand Down
28 changes: 23 additions & 5 deletions git-cliff/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ use clap::ValueEnum;
use git_cliff_core::changelog::Changelog;
use git_cliff_core::commit::Commit;
use git_cliff_core::config::Config;
use git_cliff_core::embed::EmbeddedConfig;
use git_cliff_core::embed::{
BuiltinConfig,
EmbeddedConfig,
};
use git_cliff_core::error::{
Error,
Result,
Expand Down Expand Up @@ -277,12 +280,24 @@ pub fn run(mut args: Opt) -> Result<()> {
check_new_version();

// Create the configuration file if init flag is given.
if args.init {
info!("Saving the configuration file to {:?}", DEFAULT_CONFIG);
fs::write(DEFAULT_CONFIG, EmbeddedConfig::get_config()?)?;
if let Some(init_config) = args.init {
let contents = match init_config {
Some(ref name) => BuiltinConfig::get_config(name.to_string())?,
None => EmbeddedConfig::get_config()?,
};
info!(
"Saving the configuration file{} to {:?}",
init_config.map(|v| format!(" ({v})")).unwrap_or_default(),
DEFAULT_CONFIG
);
fs::write(DEFAULT_CONFIG, contents)?;
return Ok(());
}

// Retrieve the built-in configuration.
let builtin_config =
BuiltinConfig::parse(args.config.to_string_lossy().to_string());

// Set the working directory.
if let Some(ref workdir) = args.workdir {
args.config = workdir.join(args.config);
Expand Down Expand Up @@ -310,7 +325,10 @@ pub fn run(mut args: Opt) -> Result<()> {
}

// Load the default configuration if necessary.
let mut config = if path.exists() {
let mut config = if let Ok((config, name)) = builtin_config {
info!("Using built-in configuration file: {name}");
config
} else if path.exists() {
Config::parse(&path)?
} else {
if !args.context {
Expand Down
7 changes: 7 additions & 0 deletions website/docs/usage/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"label": "Usage",
"position": 3,
"link": {
"type": "generated-index"
}
}
29 changes: 29 additions & 0 deletions website/docs/usage/adding-commits.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
sidebar_position: 7
---

# Adding custom commits

In some cases, you might want to include commit messages in the changelog that yet don't exist. One example would be having "the commit message that updates the changelog" in the changelog. (🤔)

```bash
git cliff -o CHANGELOG.md
git add CHANGELOG.md
git commit -m "chore(release): update CHANGELOG.md for 1.0.0"
```

In the example above, `CHANGELOG.md` will not have the latest commit message since the commit is created afterward. So if you want to include custom commit messages like that in the changelog, you can use the `--with-commit` argument as follows:

```bash
# define the commit message
commit_msg="chore(release): update CHANGELOG.md for 1.0.0"

# generate changelog and pretend a commit exists as "$commit_msg"
git cliff --with-commit "$commit_msg" -o CHANGELOG.md

# create the actual commit
git add CHANGELOG.md
git commit -m "$commit_msg"
```

The commit SHA will be empty as default when `--with-commit` is used. Specify the hash with a message separated by single whitespace for setting the commit SHA. e.g. `--with-commit "8f55e69eba6e6ce811ace32bd84cc82215673cb6 feat: add X"`
Loading
Loading