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
mod error;
/// Providers of reading/writing semver functionality.
pub mod plugins {
// ADDING A PLUGIN: Add the module to this list
pub mod file;
pub mod git;
pub mod npm;
pub mod rust;
}
use jacklog::instrument;
use log::{debug, info};
use semver::Version;
use std::{
collections::HashMap,
fmt::Debug,
path::{Path, PathBuf},
str,
};
// Re-exported modules.
pub use error::VertoError as Error;
/// Result type alias used in the library.
///
/// This is just shorthand for returning a Result type with a verto Error type.
pub type Result<T> = std::result::Result<T, Error>;
/// Trait implemented by plugins which can read and write version information.
///
/// Pluggable must be implemented for all plugins, and contains basic
/// functionality for working with the plugin, lifecycle hooks, and providing a
/// name in order to enable/disable the plugin.
pub trait Plugable {
fn name(&self) -> String;
/// check is run first to determine whether a give plugin should be enabled
/// for use.
///
/// # Errors
///
/// When an error may be returned is determined by the specific
/// implementation.
fn check(&self) -> Result<bool>;
/// Determine whether or not a prefix was detected.
fn prefix(&self) -> &str;
// TODO: Figure out how to make this return itself in the builder pattern
fn enable(&mut self);
fn disable(&mut self);
fn enabled(&self) -> bool;
/// Run any required initialization code.
///
/// # Errors
///
/// Will never return an error by default; depends on the implementation in
/// the implementing struct.
fn init(&mut self, _branch: &Option<String>) -> Result<()> {
Ok(())
}
// Add the prefix to the semver string
fn add_prefix(&self, version: &dyn std::fmt::Display) -> String {
format!("{}{}", self.prefix(), version)
}
/// Strip the prefix from the semver string.
fn remove_prefix(&self, version: &str) -> String {
version.replace(&self.prefix(), "")
}
/// Calculate what the current version is.
///
/// # Errors
///
/// Will never return an error by default; depends on the implementation in
/// the implementing struct.
fn current_version(&self) -> Result<Option<Version>> {
Ok(None)
}
/// Calculate what the next version should be.
///
/// # Errors
///
/// Will never return an error by default; depends on the implementation in
/// the implementing struct.
fn next_version(&self, _: &Version) -> Result<Option<Version>> {
Ok(None)
}
/// Write the version to file(s).
///
/// # Errors
///
/// May return an error depending on the particular plugin. See each plugin's
/// documentation for details.
fn write(&self, _version: &str) -> Result<Vec<PathBuf>> {
Ok(vec![])
}
/// Called after all plugins have written.
///
/// # Errors
///
/// Will never return an error by default; depends on the implementation in
/// the implementing struct.
fn done(&self, _version: &str, _changed_files: &[&Path]) -> Result<()> {
Ok(())
}
}
/// Entrypoint and configuration for verto.
///
/// This is a container that stores configuration options like `dry_run` and a
/// list of plugins.
pub struct Verto {
dry_run: bool,
plugins: Vec<Box<dyn Plugable>>,
}
impl Verto {
#[instrument]
pub fn new<T: AsRef<Path> + Debug>(
path: &T,
prefix: &str,
suffix: &str,
dry_run: bool,
) -> Self {
// Create a canonical path, which will normalize the path and make it absolute.
// This avoids issues later with path manipulation in plugins.
let path = path
.as_ref()
.canonicalize()
.expect("error getting canonical path");
Self {
dry_run,
// ADDING A PLUGIN: Add an entry here to push your plugin onto the `plugins` vec
plugins: vec![
Box::new(plugins::file::Plugin::new(&path, prefix)),
Box::new(plugins::rust::Plugin::new(&path, prefix)),
Box::new(plugins::npm::Plugin::new(&path, prefix)),
// It's important the git plugin go last, so all the other
// plugin output gets committed
Box::new(plugins::git::Plugin::new(&path, prefix)),
],
}
}
/// Get a list of string names of plugins that are available.
#[must_use]
pub fn plugin_names(&self) -> Vec<String> {
self.plugins
.iter()
.map(|x| x.name())
.collect::<Vec<String>>()
}
/// # Errors
///
/// Will return an error if plugin initialization fails for a plugin.
pub fn initialize(
&mut self,
branch: &Option<String>,
disabled_plugins: &[String],
) -> Result<()> {
debug!("plugins disabled: {:?}", disabled_plugins);
// Go through all the available plugins, and filter them based on
// whether they're explicitly enabled/disabled, and whether the plugin
// _thinks_ it should be enabled, based on whatever detection heuristics
// it implements.
for plugin in &mut self.plugins {
// If the plugin has not detected that it's relevant for this project, disable it and
// continue
if !plugin.check()? {
debug!("==> {} not detected; disabling", &plugin.name());
plugin.disable();
continue;
}
// Check to see whether we find the plugin name in the list of disabled plugins
let mut found = false;
for dp in disabled_plugins.iter() {
if plugin.name() == *dp {
found = true;
break;
}
}
// If we found the plugin name in the list of disabled plugins, disable the plugin and
// continue
if found {
debug!("==> {} disabled", &plugin.name());
plugin.disable();
continue;
}
// Otherwise, it wasn't disabled and checked as valid
debug!("==> {} detected; enabling", &plugin.name());
plugin.enable();
}
info!(
"==> plugins enabled: {}",
self.plugins
.iter()
.filter_map(|p| {
if !p.enabled() {
return None;
}
Some(p.name())
})
.collect::<Vec<String>>()
.join(", ")
);
// Initialize all the plugins
for plugin in &mut self.plugins {
if !plugin.enabled() {
continue;
}
plugin.init(branch)?;
}
Ok(())
}
/// # Errors
///
/// Will return an error if enabled plugins detect different current versions.
/// This probably means that various files on disk and git history have gotten
/// out of sync.
pub fn current_version(&self, plugin_name: &Option<String>) -> Result<Version> {
if let Some(name) = plugin_name {
info!("==> only incrementing version using plugin: {}", &name);
}
// Calculate the current version
let mut current_versions = HashMap::new();
for plugin in &self.plugins {
if !plugin.enabled() {
continue;
}
if let Some(name) = plugin_name {
if name != &plugin.name() {
continue;
}
}
if let Some(v) = plugin.current_version()? {
info!("{} at version {}", plugin.name(), v);
current_versions.insert(plugin.name(), v);
}
}
debug!("found current versions: {:#?}", ¤t_versions);
// Now that we have a set of current_versions from the plugins, confirm that they're all indicating the
// same version
let mut current_versions: Vec<&Version> = current_versions.values().collect();
if current_versions.is_empty() {
return Ok(Version::parse("0.0.0").expect("unable to parse default version"));
}
current_versions.sort();
current_versions.dedup();
if current_versions.is_empty() {
return Err(Error::Error(
"different current versions detected by different plugins;
check that all tags have been pushed, and that you've pulled the latest tags.
If they still don't match, make sure that you ran a build to update any
lockfiles if you bumped the version by hand somewhere"
.to_string(),
));
}
let current_version = current_versions[0];
info!("==> current version: {}", ¤t_version.to_string());
Ok(current_version.clone())
}
/// # Errors
///
/// Will return an error if no enabled plugin returned a next version or
/// different next versions were returned by different plugins.
pub fn next_version(
&self,
current_version: &Version,
plugin_name: &Option<String>,
) -> Result<Version> {
if let Some(name) = plugin_name {
info!("==> only using version from plugin: {}", &name);
}
// Calculate the next version
let mut next_versions = HashMap::new();
for plugin in &self.plugins {
if !plugin.enabled() {
continue;
}
if let Some(name) = plugin_name {
if name != &plugin.name() {
continue;
}
}
if let Some(v) = plugin.next_version(current_version)? {
next_versions.insert(plugin.name(), v);
}
}
debug!("calculated next versions: {:?}", &next_versions);
// Now that we have a set of next_versions from the plugins, confirm that they're all indicating the
// same version
let mut next_versions: Vec<&Version> = next_versions.values().collect();
if next_versions.is_empty() {
return Err(Error::Error(
"no enabled plugin returned a next version".to_string(),
));
}
next_versions.sort();
next_versions.dedup();
if next_versions.len() > 1 {
return Err(Error::Error(
"different next version returned by different plugins".to_string(),
));
}
let next_version = next_versions[0];
info!("==> next version: {}", &next_version.to_string());
Ok(next_version.clone())
}
/// Go through each plugin and have it write the version. What this means
/// will vary depending on which plugins are enabled, and how they work internally.
///
/// # Errors
///
/// Will return an error if any of the plugins returns an error. See
/// documentation for each plugin for details.
pub fn write(&mut self, next_version: &Version) -> Result<Vec<PathBuf>> {
// Set up a vec of files that we'll use to collect the files to be updated by the
// various plugins (and that will therefore need to be committed with the new version)
let mut files: Vec<PathBuf> = Vec::new();
// Write the version out to various places
for plugin in &self.plugins {
if !plugin.enabled() {
continue;
}
debug!("==> running next_version for {}", &plugin.name());
// Don't do anything if this is a dry-run
if self.dry_run {
continue;
}
// The `write` method should return a list of files that were updated by
// the plugin. We need to keep track of them so we can commit them at the
// end.
files.append(&mut plugin.write(&next_version.to_string())?);
}
Ok(files)
}
/// Commit any versioning changes.
///
/// # Errors
///
/// Returns an error if any of the plugins return an error when their `commit`
/// method is called.
pub fn commit<T: AsRef<Path>>(&mut self, next_version: &Version, files: &[T]) -> Result<()> {
// If we're running in dry-run mode, just exit here
if self.dry_run {
return Ok(());
}
let mut f: Vec<&Path> = Vec::new();
for file in files {
f.push(file.as_ref());
}
// Don't do anything if this is a dry-run
for plugin in &self.plugins {
if !plugin.enabled() {
continue;
}
// After all the plugins have done their thing, we call a done hook to allow cleanup or
// final actions like the git plugin committing changes
plugin.done(&next_version.to_string(), &f)?;
}
Ok(())
}
}