• Stars
    star
    294
  • Rank 135,717 (Top 3 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An sbt plugin to dynamically set your version from git

sbt-dynver

sbt-dynver is an sbt plugin to dynamically set your version from git.

Inspired by:

Features:

  • Dynamically set your version by looking at the closest tag to the current commit
  • Detect the previous version

Setup

Add this to your sbt build plugins, in either project/plugins.sbt or project/dynver.sbt:

addSbtPlugin("com.github.sbt" % "sbt-dynver" % "x.y.z")
// Until version 4.1.1:
addSbtPlugin("com.dwijnand" % "sbt-dynver" % "4.1.1")

The latest release is: dynver Scala version support

Then make sure to NOT set the version setting, otherwise you will override sbt-dynver.

In CI, if you're using GitHub Actions and actions/checkout you may need to use fetch-depth: 0 to avoid situations where a shallow clone will result in the last tag not being fetched.

  - uses: actions/checkout@v3
    with:
      fetch-depth: 0

If you're manually running git commands then you may need to run git fetch --unshallow (or, sometimes, git fetch --depth=10000). Additionally git fetch --tags if the repo is cloned with --no-tags.

Other than that, as sbt-dynver is an AutoPlugin that is all that is required.

Detail

ThisBuild / version, ThisBuild / isSnapshot and ThisBuild / isVersionStable will be automatically set to:

| tag    | dist | HEAD sha | dirty | version                        | isSnapshot | isVersionStable |
| ------ | ---- | -------- | ----- | ------------------------------ | ---------- | --------------- |
| v1.0.0 | 0    | -        | No    | 1.0.0                          | false      | true            |
| v1.0.0 | 0    | 1234abcd | Yes   | 1.0.0+0-1234abcd+20140707-1030 | true       | false           |
| v1.0.0 | 3    | 1234abcd | No    | 1.0.0+3-1234abcd               | true       | true            |
| v1.0.0 | 3    | 1234abcd | Yes   | 1.0.0+3-1234abcd+20140707-1030 | true       | false           |
| <none> | 3    | 1234abcd | No    | 0.0.0+3-1234abcd               | true       | true            |
| <none> | 3    | 1234abcd | Yes   | 0.0.0+3-1234abcd+20140707-1030 | true       | false           |
| no commits or no git repo at all | HEAD+20140707-1030             | true       | false           |

Where:

  • tag means what is the latest tag (relative to HEAD)
  • dist means the distance of the HEAD commit from the tag
  • dirty refers to whether there are local changes in the git repo

Previous Version Detection

Given the following git history, here's what previousStableVersion returns when at each commit:

*   (tagged: v1.1.0)       --> Some("1.0.0")
*   (untagged)             --> Some("1.0.0")
| * (tagged: v2.1.0)       --> Some("2.0.0")
| * (tagged: v2.0.0)       --> Some("1.0.0")
|/
*   (tagged: v1.0.0)       --> None
*   (untagged)             --> None

Previous version is detected by looking at the closest tag of the parent commit of HEAD.

If the current commit has multiple parents, the first parent will be used. In git, the first parent comes from the branch you merged into (e.g. master in git checkout master && git merge my-feature-branch)

To use this feature with the Migration Manager MiMa sbt plugin, add

mimaPreviousArtifacts := previousStableVersion.value.map(organization.value %% moduleName.value % _).toSet

Tag Requirements

In order to be recognized by sbt-dynver, by default tags must begin with the lowercase letter 'v' followed by a digit.

If you're not seeing what you expect, then either start with this:

git tag -a v0.0.1 -m "Initial version tag for sbt-dynver"

or change the value of ThisBuild / dynverVTagPrefix to remove the requirement for the v-prefix:

ThisBuild / dynverVTagPrefix := false

or, more generally, use ThisBuild / dynverTagPrefix to fully customising tag prefixes, for example:

ThisBuild / dynverTagPrefix := "foo-" // our tags have the format foo-<version>, e.g. foo-1.2.3

Tasks

  • dynver: Returns the dynamic version of your project, inferred from the git metadata
  • dynverCurrentDate: Returns the captured current date. Used for (a) the dirty suffix of dynverGitDescribeOutput and (b) the fallback version (e.g if not a git repo).
  • dynverGitDescribeOutput: Returns the captured git describe out, in a structured form. Useful to define a custom version string.
  • dynverCheckVersion: Checks if version and dynver match
  • dynverAssertVersion: Asserts if version and dynver match

Publishing to Sonatype's snapshots repository (aka "Sonatype mode")

If you're publishing to Sonatype sonashots then enable ThisBuild / dynverSonatypeSnapshots := true to append "-SNAPSHOT" to the version if isSnapshot is true (which it is unless building on a tag with no local changes). This opt-in exists because the Sonatype's snapshots repository requires all versions to end with -SNAPSHOT.

Portable version strings

The default version string format includes + characters, which is an escape character in URL and is not compatible with docker tags. This character can be overridden by setting:

ThisBuild / dynverSeparator := "-"

Custom version string

Sometimes you want to customise the version string. It might be for personal preference, or for compatibility with another tool or spec.

For simple cases you can customise a version by simply post-processing the value of ThisBuild / version (and optionally ThisBuild / dynver), for example by replacing '+' with '-' (emulating the docker support mentioned above):

ThisBuild / version ~= (_.replace('+', '-'))
ThisBuild / dynver  ~= (_.replace('+', '-'))

To completely customise the string format you can use dynverGitDescribeOutput, dynverCurrentDate and sbtdynver.DynVer, like so:

def versionFmt(out: sbtdynver.GitDescribeOutput): String = {
  val dirtySuffix = out.dirtySuffix.dropPlus.mkString("-", "")
  if (out.isCleanAfterTag) out.ref.dropPrefix + dirtySuffix // no commit info if clean after tag
  else out.ref.dropPrefix + out.commitSuffix.mkString("-", "-", "") + dirtySuffix
}

def fallbackVersion(d: java.util.Date): String = s"HEAD-${sbtdynver.DynVer timestamp d}"

inThisBuild(List(
  version := dynverGitDescribeOutput.value.mkVersion(versionFmt, fallbackVersion(dynverCurrentDate.value)),
   dynver := {
     val d = new java.util.Date
     sbtdynver.DynVer.getGitDescribeOutput(d).mkVersion(versionFmt, fallbackVersion(d))
   }
))

Essentially this:

  1. defines how to transform the structured output of git describe's into a string, with versionFmt
  2. defines the fallback version string, with fallbackVersion, and
  3. wires everything back together

Sanity checking the version

As a sanity check, you can stop the build from loading by running a check during sbt's onLoad. For instance, to make sure that the version is derived from tags you can use:

Global / onLoad := (Global / onLoad).value.andThen { s =>
  dynverAssertTagVersion.value
  s
}

This will return an error message like the following:

[error] Failed to derive version from git tags. Maybe run `git fetch --unshallow`? Version: 3-d9489763

Or, using sbt-dynver v1.1.0 to v4.0.0:

Global / onLoad := (Global / onLoad).value.andThen { s =>
  val v = version.value
  if (dynverGitDescribeOutput.value.hasNoTags)
    throw new MessageOnlyException(
      s"Failed to derive version from git tags. Maybe run `git fetch --unshallow`? Version: $v"
    )
  s
}

Dependencies

  • git, on the PATH

Library Usage

sbt-dynver also publishes a standalone library, dynver.

dynver Scala version support

"com.github.sbt" % "dynver" % "x.y.z")

The easiest way to use this library is to use the methods that exist on DynVer to which you can query with questions like:

  • The current version
  • The sonatype version
  • If this a snapshot?
  • What the previous version was
import java.util.Date
import sbtdynver.DynVer

DynVer.version(Date())
// res0: String = 0.2.0+0-3d78911a+20230427-1401
DynVer.isSnapshot()
// res1: Boolean = true
DynVer.isDirty()
// res2: Boolean = true
DynVer.previousVersion
// res3: Option[String] = None

You can get a full idea of what exists on DynVer by looking at it here.

FAQ

How do I make previousStableVersion return None for major version branches?

Deciding whether going from one version to another is a "breaking change" is out of scope for this project. If you have binary compatibility check setup using previousStableVersion in CI and want to skip the check for major version branches (e.g. 1.x vs 2.x), see #70 (comment) for the recommended solution.

More Repositories

1

sbt

sbt, the interactive build tool
Scala
4,685
star
2

sbt-native-packager

sbt Native Packager
Scala
1,582
star
3

sbt-dependency-graph

sbt plugin to create a dependency graph for your project
Scala
1,240
star
4

sbt-jmh

"Trust no one, bench everything." - sbt plugin for JMH (Java Microbenchmark Harness)
Scala
781
star
5

sbt-eclipse

Plugin for sbt to create Eclipse project definitions
Scala
721
star
6

sbt-release

A release plugin for sbt
Scala
638
star
7

sbt-buildinfo

I know this because build.sbt knows this.
Scala
545
star
8

sbt-web

Library for building sbt plugins for the web
Scala
365
star
9

sbt-git

A git plugin for sbt
Scala
343
star
10

zinc

Scala incremental compiler library, used by sbt and other build tools
Scala
324
star
11

docker-sbt

Official sbt docker images
Dockerfile
308
star
12

sbt-ci-release

sbt plugin to automate Sonatype releases from GitHub Actions
Scala
274
star
13

sbt-onejar

Packages your project using One-JARβ„’
Scala
268
star
14

sbt-scalariform

sbt plugin adding support for source code formatting using Scalariform
Scala
259
star
15

sbt-fresh

sbt-plugin to create an opinionated fresh sbt project
Scala
235
star
16

sbt-github-actions

An sbt plugin which makes it easier to build with GitHub Actions
Scala
192
star
17

sbt-header

sbt-header is an sbt plugin for creating file headers, e.g. copyright headers
Scala
190
star
18

sbt-bintray

fresh packages delivered from your sbt console
Scala
180
star
19

sbt-site

Site generation for sbt
Scala
175
star
20

sbt-protobuf

sbt plugin for compiling protobuf files
Scala
173
star
21

sbt-start-script

SBT Plugin to create a "start" script to run the program
Scala
144
star
22

sbt-pgp

PGP plugin for sbt
Scala
141
star
23

sbt-groll

sbt plugin to roll the Git history
Scala
134
star
24

junit-interface

Implementation of sbt's test interface for JUnit
Java
132
star
25

sbt-unidoc

sbt plugin to create a unified Scaladoc or Javadoc API document across multiple subprojects.
Scala
127
star
26

sbt-jacoco

an sbt plugin for JaCoCo Code Coverage
Scala
123
star
27

sbt-jni

SBT Plugin to ease working with JNI
Scala
122
star
28

sbt-projectmatrix

Scala
116
star
29

sbt-boilerplate

sbt plugin for generating scala.Tuple/Function related boilerplate code
Scala
110
star
30

sbt-proguard

Proguard sbt plugin
Scala
99
star
31

sbt-atmos

sbt plugin for running Typesafe Console in development
Scala
98
star
32

sbt-launcher-package

Packaging for sbt so you can run it.
Scala
90
star
33

sbt-dirty-money

clean Ivy2 cache
Scala
88
star
34

sbt-license-report

Report on licenses used in an sbt project.
Scala
85
star
35

sbt-doge

sbt plugin to aggregate tasks across subprojects and their crossScalaVersions
Scala
78
star
36

website

The source for scala-sbt.org
Scala
75
star
37

sbt-pom-reader

Translates xml -> awesome. Maven-ish support for sbt.
Scala
75
star
38

sbt-remote-control

Create and manage sbt process using unicorns and forks
Scala
74
star
39

sbt-aspectj

AspectJ sbt plugin
Scala
73
star
40

sbt-scalabuff

SBT plugin which generate case classes and support for serialization from Google Protocol Buffer definitions using ScalaBuff
Scala
72
star
41

contraband

http://www.scala-sbt.org/contraband/
Scala
68
star
42

sbt-s3

sbt-s3 is a simple sbt plugin to manipulate objects on Amazon S3
Scala
62
star
43

sbt-multi-jvm

Multi-JVM testing in sbt
Scala
56
star
44

sbt-javaagent

sbt plugin for adding java agents to projects
Scala
54
star
45

sbt-paradox-material-theme

Material Design theme for Paradox
StringTemplate
51
star
46

sbt-cpd

Copy & Paste Detector plugin using PMD for sbt.
Scala
49
star
47

sbt-osgi

sbt plugin for creating OSGi bundles
Scala
47
star
48

sbt-findbugs

FindBugs static analysis plugin for sbt.
Scala
47
star
49

sbt-man

Looks up scaladoc.
Scala
46
star
50

librarymanagement

librarymanagement module for sbt
Scala
46
star
51

sbt-less

Scala
42
star
52

ipcsocket

IPC: Unix Domain Socket and Windows Named Pipes for Java
Java
42
star
53

io

IO module for sbt
Scala
41
star
54

sbt-js-engine

Support for sbt plugins that use JavaScript
Scala
40
star
55

launcher

The sbt launcher as its own project. Can launch any ivy/maven published project with a main class, with some fancy features.
Scala
40
star
56

sbt-autoversion

Scala
35
star
57

sbt-digest

sbt-web plugin for checksum files
Scala
31
star
58

sbt-jupiter-interface

Implementation of SBT's test interface for JUnit Jupiter
Java
30
star
59

sbt-avro

sbt plugin for compiling Avro schemas, similar to sbt-protobuf
Scala
29
star
60

sbt-slash

unified slash syntax for both shell and build.sbt
Scala
29
star
61

sbt-java-formatter

An sbt plugin for formating Java code
Scala
27
star
62

sbt-gzip

sbt-web plugin for gzipping assets
Scala
25
star
63

sbt-unique-version

emulates Maven's uniqueVersion snapshots
Scala
24
star
64

sbt-pull-request-validator

Plugin that optimizes pull request validation to only validate sub projects that have changed
Scala
23
star
65

sbt.github.com

See https://github.com/sbt/website for the source
HTML
22
star
66

sbt-duplicates-finder

Find classes and resources conflicts in your build
Scala
22
star
67

sbt-autoplugin.g8

giter8 template for sbt 0.13.5+ AutoPlugin
Scala
20
star
68

sbt-cucumber

Cucumber plugin for SBT.
Scala
20
star
69

sbt-jcstress

Trust no-one, and especially not memory visibility.
HTML
19
star
70

sbt-sriracha

Scala
18
star
71

adept

adept helps you find, declare, and download dependencies. http://groups.google.com/group/adept-dev/
18
star
72

sbt-mocha

SBT plugin for running mocha JavaScript unit tests on node
Scala
17
star
73

sbt-multi-release-jar

Support for JDK9's Multi Release JAR Files (JEP 238)
Scala
17
star
74

sbt-xjc

SBT plugin to compile an XML Schema with XJC
Scala
15
star
75

util

util modules for sbt
Scala
15
star
76

sbt-export-repo

exports your dependency graph to a preloaded local repository
Scala
15
star
77

sbt-nocomma

sbt-nocomma reduces commas from your build.sbt.
Scala
13
star
78

serialization

serialization facility for sbt
Scala
13
star
79

sbt-maven-resolver

An sbt plugin to resolve dependencies using Aether
Scala
12
star
80

sbt-core-next

sbt APIs targeted for eventual inclusion in sbt core
Scala
12
star
81

sbt-houserules

House rules for sbt modules.
Scala
12
star
82

sbt-pamflet

sbt plugin to run Pamflet (and Pamflet plugin to run sbt)
Scala
11
star
83

sbt-sdlc

Scaladoc link checker for sbt
Scala
11
star
84

sbt-appbundle

A plugin for the simple-build-tool to create an OS X application bundle.
Scala
10
star
85

bintry

your packages, delivered fresh
Scala
10
star
86

sbt-fmpp

FreeMarker Scala/Java Templating Plugin for SBT
Scala
9
star
87

sbt-ynolub

Scala
9
star
88

sbt-testng

Implementation of the sbt testing interface for TestNG, bundled with an sbt plug-in for convenience.
Scala
9
star
89

sbt-concat

sbt-web plugin for concatenating web assets
Scala
8
star
90

sbt-ant

SBT plug-in to call Ant targets from within SBT builds
Scala
7
star
91

sbtn-dist

Shell
6
star
92

sbt-community-plugins

All community plugins that opt into an uber-build
Scala
6
star
93

sbt-vimquit

an sbt plugin that adds :q command.
Scala
5
star
94

helloworld-one

An example build for sbt 1.0.0.
Scala
5
star
95

sbt-giter8-resolver

Scala
5
star
96

sbt-sequential

adds sequential tasks to sbt
Scala
4
star
97

sbt-scalashim

generates sys.error.
Scala
4
star
98

sbt-experimental

Experimental APIs to fix rough edges in sbt
Scala
3
star
99

sbt-web-build-base

Scala
3
star
100

sbt-validator

Builds sbt 1.0.x against recent versions of the sbt modules
Shell
3
star