Skip to content

Commit

Permalink
feat(cli): Added get-version feature (#248)
Browse files Browse the repository at this point in the history
* feat(cli): Added get-version feature

Added the read-only feature "get-version", that will output the latest version

* feat(cli): Added monorepo-support to get-version command

* feat(cli): Removed disable_fallback option from get-version command and adjusted tests accordingly

* refactor: Made use of transitive matching for NoTag-error

Co-authored-by: Marcin Puc <tranzystorek.io@protonmail.com>

* style: Make clippy happy

* style(cli): Corrected import order

---------

Co-authored-by: André Dörscheln <ad@itesign.de>
Co-authored-by: Marcin Puc <tranzystorek.io@protonmail.com>
  • Loading branch information
3 people committed Feb 18, 2023
1 parent c2e7ab0 commit 5670cd8
Show file tree
Hide file tree
Showing 22 changed files with 348 additions and 62 deletions.
7 changes: 3 additions & 4 deletions src/bin/cog/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ fn prepare_header(typ: &str, message: &str, scope: Option<&str>) -> String {
let mut header = typ.to_string();

if let Some(scope) = scope {
write!(&mut header, "({})", scope).unwrap();
write!(&mut header, "({scope})").unwrap();
}

write!(&mut header, ": {}", message).unwrap();
write!(&mut header, ": {message}").unwrap();

header
}
Expand All @@ -93,8 +93,7 @@ fn prepare_edit_template(typ: &str, message: &str, scope: Option<&str>, breaking

write!(
&mut template,
"{}\n\n# Message body\n\n\n# Message footer\n# For example, foo: bar\n\n\n",
header
"{header}\n\n# Message body\n\n\n# Message footer\n# For example, foo: bar\n\n\n"
)
.unwrap();

Expand Down
17 changes: 16 additions & 1 deletion src/bin/cog/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,17 @@ enum Command {
repository: Option<String>,
},

/// Get current version
GetVersion {
/// Fallback version. Has to be semver compliant.
#[arg(short, long)]
fallback: Option<String>,

/// Specify which package to get the version for in a monorepo.
#[arg(long, value_parser = packages())]
package: Option<String>,
},

/// Commit changelog from latest tag to HEAD and create new tag
#[command(group = ArgGroup::new("bump-spec").required(true))]
Bump {
Expand Down Expand Up @@ -306,6 +317,10 @@ fn main() -> Result<()> {
init_logs(cli.verbose, cli.quiet);

match cli.command {
Command::GetVersion { fallback, package } => {
let cocogitto = CocoGitto::get()?;
cocogitto.get_latest_version(fallback, package)?
}
Command::Bump {
version,
auto,
Expand Down Expand Up @@ -474,7 +489,7 @@ fn main() -> Result<()> {
changelog.into_markdown(template)?
}
};
println!("{}", result);
println!("{result}");
}
Command::Init { path } => {
cocogitto::command::init::init(&path)?;
Expand Down
17 changes: 6 additions & 11 deletions src/command/bump/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,9 @@ mod standard;

fn ensure_tag_is_greater_than_previous(current: &Tag, next: &Tag) -> Result<()> {
if next <= current {
let comparison = format!("{} <= {}", current, next).red();
let comparison = format!("{current} <= {next}").red();
let cause_key = "cause:".red();
let cause = format!(
"{} version MUST be greater than current one: {}",
cause_key, comparison
);
let cause = format!("{cause_key} version MUST be greater than current one: {comparison}");

bail!("{}:\n\t{}\n", "SemVer Error".red().to_string(), cause);
};
Expand Down Expand Up @@ -170,8 +167,7 @@ impl CocoGitto {
.enumerate()
.map(|(idx, result)| {
result.context(format!(
"Cannot parse bump profile {} hook at index {}",
profile, idx
"Cannot parse bump profile {profile} hook at index {idx}"
))
})
.try_collect()?,
Expand All @@ -185,8 +181,7 @@ impl CocoGitto {
.enumerate()
.map(|(idx, result)| {
result.context(format!(
"Cannot parse bump profile {} hook at index {}",
profile, idx
"Cannot parse bump profile {profile} hook at index {idx}"
))
})
.try_collect()?
Expand All @@ -196,14 +191,14 @@ impl CocoGitto {
.iter()
.map(|s| s.parse())
.enumerate()
.map(|(idx, result)| result.context(format!("Cannot parse hook at index {}", idx)))
.map(|(idx, result)| result.context(format!("Cannot parse hook at index {idx}")))
.try_collect()?,
(None, None) => settings
.get_hooks(hook_type)
.iter()
.map(|s| s.parse())
.enumerate()
.map(|(idx, result)| result.context(format!("Cannot parse hook at index {}", idx)))
.map(|(idx, result)| result.context(format!("Cannot parse hook at index {idx}")))
.try_collect()?,
};

Expand Down
4 changes: 2 additions & 2 deletions src/command/bump/monorepo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ impl CocoGitto {
for bump in bumps {
println!("{}", bump.new_version.prefixed_tag)
}
print!("{}", tag);
print!("{tag}");
return Ok(());
}

Expand Down Expand Up @@ -231,7 +231,7 @@ impl CocoGitto {
let tag = Tag::create(tag.version, None);

if dry_run {
print!("{}", tag);
print!("{tag}");
return Ok(());
}

Expand Down
4 changes: 2 additions & 2 deletions src/command/bump/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl CocoGitto {
let tag = Tag::create(next_version.version.clone(), Some(package_name.to_string()));

if dry_run {
print!("{}", tag);
print!("{tag}");
return Ok(());
}

Expand Down Expand Up @@ -76,7 +76,7 @@ impl CocoGitto {

let sign = self.repository.gpg_sign();
self.repository
.commit(&format!("chore(version): {}", tag), sign)?;
.commit(&format!("chore(version): {tag}"), sign)?;

if let Some(msg_tmpl) = annotated {
let mut context = tera::Context::new();
Expand Down
2 changes: 1 addition & 1 deletion src/command/bump/standard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl CocoGitto {
let tag = Tag::create(tag.version, None);

if dry_run {
print!("{}", tag);
print!("{tag}");
return Ok(());
}

Expand Down
2 changes: 1 addition & 1 deletion src/command/changelog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl CocoGitto {
}

pub fn get_changelog_at_tag(&self, tag: &str, template: Template) -> Result<String> {
let pattern = format!("..{}", tag);
let pattern = format!("..{tag}");
let pattern = RevspecPattern::from(pattern.as_str());
let changelog = self.get_changelog(pattern, false)?;

Expand Down
44 changes: 44 additions & 0 deletions src/command/get_version.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use anyhow::bail;
use anyhow::Result;
use log::warn;
use semver::Version;

use crate::git::error::TagError;
use crate::CocoGitto;

impl CocoGitto {
pub fn get_latest_version(
&self,
fallback: Option<String>,
package: Option<String>,
) -> Result<()> {
let fallback = match fallback {
Some(input) => match Version::parse(&input) {
Ok(version) => Some(version),
Err(err) => {
warn!("Invalid fallback: {}", input);
bail!("{}", err)
}
},
None => None,
};

let current_tag = match package {
Some(pkg) => self.repository.get_latest_package_tag(&pkg),
None => self.repository.get_latest_tag(),
};

let current_version = match current_tag {
Ok(tag) => tag.version,
Err(TagError::NoTag) => match fallback {
Some(input) => input,
None => bail!("No version yet"),
},
Err(err) => bail!("{}", err),
};

warn!("Current version:");
print!("{current_version}");
Ok(())
}
}
4 changes: 2 additions & 2 deletions src/command/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ impl CocoGitto {
let mut repo_tag_name = repo_path.to_str()?.to_string();

if let Some(branch_shorthand) = self.repository.get_branch_shorthand() {
write!(&mut repo_tag_name, " on {}", branch_shorthand).unwrap();
write!(&mut repo_tag_name, " on {branch_shorthand}").unwrap();
}

if let Ok(latest_tag) = self.repository.get_latest_tag() {
write!(&mut repo_tag_name, " {}", latest_tag).unwrap();
write!(&mut repo_tag_name, " {latest_tag}").unwrap();
};

Some(repo_tag_name)
Expand Down
1 change: 1 addition & 0 deletions src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ pub mod changelog;
pub mod check;
pub mod commit;
pub mod edit;
pub mod get_version;
pub mod init;
pub mod log;
6 changes: 3 additions & 3 deletions src/conventional/bump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl Tag {
let changelog_start_oid = Some(changelog_start_oid.as_str());

let pattern = changelog_start_oid
.map(|oid| format!("{}..", oid))
.map(|oid| format!("{oid}.."))
.unwrap_or_else(|| "..".to_string());
let pattern = pattern.as_str();
let pattern = RevspecPattern::from(pattern);
Expand Down Expand Up @@ -178,7 +178,7 @@ impl Tag {
let changelog_start_oid = Some(changelog_start_oid.as_str());

let pattern = changelog_start_oid
.map(|oid| format!("{}..", oid))
.map(|oid| format!("{oid}.."))
.unwrap_or_else(|| "..".to_string());
let pattern = pattern.as_str();
let pattern = RevspecPattern::from(pattern);
Expand Down Expand Up @@ -217,7 +217,7 @@ impl Tag {
let changelog_start_oid = Some(changelog_start_oid.as_str());

let pattern = changelog_start_oid
.map(|oid| format!("{}..", oid))
.map(|oid| format!("{oid}.."))
.unwrap_or_else(|| "..".to_string());
let pattern = pattern.as_str();
let pattern = RevspecPattern::from(pattern);
Expand Down
6 changes: 3 additions & 3 deletions src/conventional/changelog/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ impl Display for ChangelogError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ChangelogError::TemplateNotFound(path) => {
writeln!(f, "changelog template not found in {:?}", path)
writeln!(f, "changelog template not found in {path:?}")
}
ChangelogError::TeraError(err) => {
writeln!(f, "failed to render changelog: \n\t{:?}", err)
writeln!(f, "failed to render changelog: \n\t{err:?}")
}
ChangelogError::WriteError(err) => {
writeln!(f, "failed to write changelog: \n\t{}", err)
writeln!(f, "failed to write changelog: \n\t{err}")
}
ChangelogError::SeparatorNotFound(path) => writeln!(
f,
Expand Down
16 changes: 8 additions & 8 deletions src/conventional/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ impl Display for BumpError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "failed to bump version\n")?;
match self {
BumpError::Git2Error(err) => writeln!(f, "\t{}", err),
BumpError::TagError(err) => writeln!(f, "\t{}", err),
BumpError::SemVerError(err) => writeln!(f, "\t{}", err),
BumpError::FmtError(err) => writeln!(f, "\t{}", err),
BumpError::Git2Error(err) => writeln!(f, "\t{err}"),
BumpError::TagError(err) => writeln!(f, "\t{err}"),
BumpError::SemVerError(err) => writeln!(f, "\t{err}"),
BumpError::FmtError(err) => writeln!(f, "\t{err}"),
BumpError::NoCommitFound => writeln!(
f,
r#"cause: No conventional commit found to bump current version.
Expand Down Expand Up @@ -87,9 +87,9 @@ impl Display for ConventionalCommitError {
cause,
} => {
let error_header = "Errored commit: ".bold().red();
let author = format!("<{}>", author).blue();
let author = format!("<{author}>").blue();
let cause = anyhow!(cause.clone());
let cause = format!("{:?}", cause)
let cause = format!("{cause:?}")
.lines()
.collect::<Vec<&str>>()
.join("\n\t");
Expand All @@ -113,7 +113,7 @@ impl Display for ConventionalCommitError {
author,
} => {
let error_header = "Errored commit: ".bold().red();
let author = format!("<{}>", author).blue();
let author = format!("<{author}>").blue();
writeln!(
f,
"{}{} {}\n\t{message}'{summary}'\n\t{cause}Commit type `{commit_type}` not allowed",
Expand All @@ -128,7 +128,7 @@ impl Display for ConventionalCommitError {
}
ConventionalCommitError::ParseError(err) => {
let err = anyhow!(err.clone());
writeln!(f, "{:?}", err)
writeln!(f, "{err:?}")
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ impl Display for CogCheckReport {
.red()
.bold();

writeln!(f, "{}", header)?;
writeln!(f, "{header}")?;

for err in &self.errors {
let underline = format!("{:>57}", " ").underline();
writeln!(f, "{:>5}\n", underline)?;
write!(f, "{}", err)?;
writeln!(f, "{underline:>5}\n")?;
write!(f, "{err}")?;
}
Ok(())
}
Expand Down Expand Up @@ -54,6 +54,6 @@ impl Display for BumpError {
\tyou can run `git stash apply stash@{}` to restore these changes.",
stash_ref, self.stash_number
);
write!(f, "{}\n{}", header, suggestion)
write!(f, "{header}\n{suggestion}")
}
}

0 comments on commit 5670cd8

Please sign in to comment.