Skip to content

Commit

Permalink
add scalafmt
Browse files Browse the repository at this point in the history
  • Loading branch information
xuwei-k committed Oct 10, 2024
1 parent 60bc07a commit df8301f
Show file tree
Hide file tree
Showing 10 changed files with 149 additions and 107 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ jobs:
shell: bash
run: |
gpg --import test-key.gpg
sbt -v ++2.12.x clean test scripted
sbt -v ++2.12.x clean scalafmtSbtCheck scalafmtCheckAll test scripted
- name: Build and test (sbt 2.x)
if: ${{ matrix.sbt == 2 }}
shell: bash
run: |
gpg --import test-key.gpg
sbt -v ++3.x clean test scripted
sbt -v ++3.x clean scalafmtCheckAll test scripted
10 changes: 10 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version = "3.8.3"
maxColumn = 150
align.tokens = []
docstrings.wrap = keep
docstrings.oneline = keep
docstrings.style = keep
docstrings.forceBlankLineBefore = false
runner.dialect = Scala212Source3
rewrite.scala3.convertToNewSyntax = true
rewrite.scala3.newSyntax.control = false
2 changes: 2 additions & 0 deletions project/plugins.sbt
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
libraryDependencies += "org.scala-sbt" %% "scripted-plugin" % sbtVersion.value

addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.7.0")

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.2")
12 changes: 6 additions & 6 deletions src/main/scala/com/github/sbt/git/ConsoleGitRunner.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ object ConsoleGitRunner extends GitRunner {
val isWindows = System.getProperty("os.name", "").toLowerCase.contains("windows")
isWindows && !isCygwin
}
private lazy val cmd = if(isWindowsShell) Seq("cmd", "/c", "git") else Seq("git")
private lazy val cmd = if (isWindowsShell) Seq("cmd", "/c", "git") else Seq("git")

// in order to enable colors we trick git into thinking we're a pager, because it already knows we're not a tty
val colorSupport: Seq[(String, String)] =
Try{
if(Terminal.console.isAnsiSupported)
Try {
if (Terminal.console.isAnsiSupported)
Seq("GIT_PAGER_IN_USE" -> "1")
else
Seq.empty
Expand All @@ -31,9 +31,9 @@ object ConsoleGitRunner extends GitRunner {
IO.createDirectory(cwd)
val full = cmd ++ args
log.debug(cwd.toString + "$ " + full.mkString(" "))
val code = Process(full, cwd, colorSupport *) ! gitLogger
val code = Process(full, cwd, colorSupport*) ! gitLogger
val result = gitLogger.flush(code)
if(code != 0)
if (code != 0)
throw new MessageOnlyException("Nonzero exit code (" + code + ") running git.")
else
result
Expand All @@ -43,7 +43,7 @@ object ConsoleGitRunner extends GitRunner {
// reduce log level for git process
private class GitLogger(log: Logger) extends ProcessLogger {
import scala.collection.mutable.ListBuffer
import Level.{ Debug, Info, Error, Value as LogLevel }
import Level.{Debug, Info, Error, Value as LogLevel}

private val msgs: ListBuffer[(LogLevel, String)] = new ListBuffer()

Expand Down
103 changes: 57 additions & 46 deletions src/main/scala/com/github/sbt/git/GitPlugin.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.github.sbt.git

import sbt._
import Keys._
import sbt.*
import Keys.*

/** This plugin has all the basic 'git' functionality for other plugins. */
object SbtGit {
Expand All @@ -15,7 +15,8 @@ object SbtGit {
val gitCurrentTags = SettingKey[Seq[String]]("git-current-tags", "The tags associated with this commit.")
val gitHeadCommit = SettingKey[Option[String]]("git-head-commit", "The commit sha for the top commit of this project.")
val gitHeadMessage = SettingKey[Option[String]]("git-head-message", "The message for the top commit of this project.")
val gitHeadCommitDate = SettingKey[Option[String]]("git-head-commit-date", "The commit date for the top commit of this project in ISO-8601 format.")
val gitHeadCommitDate =
SettingKey[Option[String]]("git-head-commit-date", "The commit date for the top commit of this project in ISO-8601 format.")
val gitDescribedVersion = SettingKey[Option[String]]("git-described-version", "Version as returned by `git describe --tags`.")
val gitUncommittedChanges = SettingKey[Boolean]("git-uncommitted-changes", "Whether there are uncommitted changes.")

Expand All @@ -28,12 +29,15 @@ object SbtGit {
val gitTagToVersionNumber = SettingKey[String => Option[String]]("git-tag-to-version-number", "Converts a git tag string to a version number.")

// Component version strings. We use these when determining the actual version.
val formattedShaVersion = settingKey[Option[String]]("Completely formatted version string which will use the git SHA. Override this to change how the SHA version is formatted.")
val formattedShaVersion = settingKey[Option[String]](
"Completely formatted version string which will use the git SHA. Override this to change how the SHA version is formatted."
)
val formattedDateVersion = settingKey[String]("Completely formatted version string which does not rely on git. Used as a fallback.")

// Helper suffix/prefix information for generated default version strings.
val baseVersion = SettingKey[String]("base-version", "The base version number which we will append the git version to.")
val versionProperty = SettingKey[String]("version-property", "The system property that can be used to override the version number. Defaults to `project.version`.")
val versionProperty =
SettingKey[String]("version-property", "The system property that can be used to override the version number. Defaults to `project.version`.")
val uncommittedSignifier = SettingKey[Option[String]]("uncommitted-signifier", "Optional additional signifier to signify uncommitted changes")

// The remote repository we're using.
Expand All @@ -44,19 +48,19 @@ object SbtGit {
}

object GitCommand {
import complete._
import complete.DefaultParsers._
import complete.*
import complete.DefaultParsers.*

val action: (State, Seq[String]) => State = { (state, args) =>
val extracted = Project.extract(state)
val (state2, runner) = extracted.runTask(GitKeys.gitRunner, state)
val dir = extracted.get(baseDirectory)
runner(args:_*)(dir, state2.log)
runner(args*)(dir, state2.log)
state2
}

// the git command we expose to the user
val command: Command = Command("git")(s => fullCommand(s)){ (state, arg) =>
val command: Command = Command("git")(s => fullCommand(s)) { (state, arg) =>
val (command, args) = arg
action(state, command +: args)
}
Expand Down Expand Up @@ -109,17 +113,22 @@ object SbtGit {
}

// Build settings.
import GitKeys._
import GitKeys.*
def buildSettings = Seq(
useConsoleForROGit := false,
gitReader := new DefaultReadableGit(baseDirectory.value, if (useConsoleForROGit.value) Some(new ConsoleGitReadableOnly(ConsoleGitRunner, file("."), sLog.value)) else None),
gitReader := new DefaultReadableGit(
baseDirectory.value,
if (useConsoleForROGit.value) Some(new ConsoleGitReadableOnly(ConsoleGitRunner, file("."), sLog.value)) else None
),
gitRunner := ConsoleGitRunner,
gitHeadCommit := gitReader.value.withGit(_.headCommitSha),
gitHeadMessage := gitReader.value.withGit(_.headCommitMessage),
gitHeadCommitDate := gitReader.value.withGit(_.headCommitDate),
gitTagToVersionNumber := git.defaultTagByVersionStrategy,
gitDescribePatterns := Seq.empty[String],
gitDescribedVersion := gitReader.value.withGit(_.describedVersion(git.gitDescribePatterns.value)).map(v => git.gitTagToVersionNumber.value(v).getOrElse(v)),
gitDescribedVersion := gitReader.value
.withGit(_.describedVersion(git.gitDescribePatterns.value))
.map(v => git.gitTagToVersionNumber.value(v).getOrElse(v)),
gitCurrentTags := gitReader.value.withGit(_.currentTags),
gitCurrentBranch := Option(gitReader.value.withGit(_.branch)).getOrElse(""),
ThisBuild / gitUncommittedChanges := gitReader.value.withGit(_.hasUncommittedChanges),
Expand All @@ -142,9 +151,9 @@ object SbtGit {
)

remoteOrigin match {
case unauthenticated(domain, repo) => buildScmInfo(domain,repo)
case ssh(domain, repo) => buildScmInfo(domain,repo)
case headlessSSH(domain, repo) => buildScmInfo(domain,repo)
case unauthenticated(domain, repo) => buildScmInfo(domain, repo)
case ssh(domain, repo) => buildScmInfo(domain, repo)
case headlessSSH(domain, repo) => buildScmInfo(domain, repo)
case _ => None
}
}
Expand All @@ -162,20 +171,19 @@ object SbtGit {
if (projectPatterns == buildPatterns && projectTagToVersionNumber == buildTagToVersionNumber)
(ThisBuild / gitDescribedVersion).value
else gitReader.value.withGit(_.describedVersion(projectPatterns)).map(v => projectTagToVersionNumber(v).getOrElse(v))
},
}
)

/** A Predefined setting to use JGit runner for git. */
def useJGit: Setting[_] = ThisBuild / gitRunner := JGitRunner
def useJGit: Setting[?] = ThisBuild / gitRunner := JGitRunner

/** Setting to use console git for readable ops, to allow working with git worktrees */
def useReadableConsoleGit: Setting[_] = ThisBuild / useConsoleForROGit := true
def useReadableConsoleGit: Setting[?] = ThisBuild / useConsoleForROGit := true

/** Adapts the project prompt to show the current project name *and* the current git branch. */
def showCurrentGitBranch: Setting[_] =
def showCurrentGitBranch: Setting[?] =
shellPrompt := GitCommand.prompt


/** Uses git to control versioning.
*
* Versioning runs through the following:
Expand All @@ -185,7 +193,7 @@ object SbtGit {
* 3. if we have a head commit, we attach this to the base version setting "<base-version>.<git commit sha>"
* 4. We append the current timestamp to the base version: "<base-version>.<timestamp>"
*/
def versionWithGit: Seq[Setting[_]] =
def versionWithGit: Seq[Setting[?]] =
Seq(
ThisBuild / versionProperty := "project.version",
ThisBuild / uncommittedSignifier := Some("SNAPSHOT"),
Expand Down Expand Up @@ -216,17 +224,19 @@ object SbtGit {
git.flaggedOptional(git.useGitDescribe.value, git.describeVersion((ThisBuild / gitDescribedVersion).value, uncommittedSuffix))
val datedVersion = formattedDateVersion.value
val commitVersion = formattedShaVersion.value
//Now we fall through the potential version numbers...
git.makeVersion(Seq(
overrideVersion,
releaseVersion,
describedVersion,
commitVersion
)) getOrElse datedVersion // For when git isn't there at all.
// Now we fall through the potential version numbers...
git.makeVersion(
Seq(
overrideVersion,
releaseVersion,
describedVersion,
commitVersion
)
) getOrElse datedVersion // For when git isn't there at all.
}
)

def versionProjectWithGit: Seq[Setting[_]] =
def versionProjectWithGit: Seq[Setting[?]] =
Seq(
ThisProject / useGitDescribe := false,
ThisProject / version := {
Expand All @@ -240,13 +250,15 @@ object SbtGit {
git.flaggedOptional(git.useGitDescribe.value, git.describeVersion((ThisProject / gitDescribedVersion).value, uncommittedSuffix))
val datedVersion = formattedDateVersion.value
val commitVersion = formattedShaVersion.value
//Now we fall through the potential version numbers...
git.makeVersion(Seq(
overrideVersion,
releaseVersion,
describedVersion,
commitVersion
)) getOrElse datedVersion // For when git isn't there at all.
// Now we fall through the potential version numbers...
git.makeVersion(
Seq(
overrideVersion,
releaseVersion,
describedVersion,
commitVersion
)
) getOrElse datedVersion // For when git isn't there at all.
}
)

Expand All @@ -271,24 +283,23 @@ object SbtGit {
val formattedShaVersion = ThisBuild / GitKeys.formattedShaVersion
val formattedDateVersion = ThisBuild / GitKeys.formattedDateVersion


val defaultTagByVersionStrategy: String => Option[String] = { tag =>
if(tag matches "v[0-9].*") Some(tag drop 1)
if (tag matches "v[0-9].*") Some(tag drop 1)
else None
}

def defaultFormatShaVersion(baseVersion: Option[String], sha:String, suffix: String):String = {
baseVersion.map(_ +"-").getOrElse("") + sha + suffix
def defaultFormatShaVersion(baseVersion: Option[String], sha: String, suffix: String): String = {
baseVersion.map(_ + "-").getOrElse("") + sha + suffix
}

def defaultFormatDateVersion(baseVersion:Option[String], date:java.util.Date):String = {
def defaultFormatDateVersion(baseVersion: Option[String], date: java.util.Date): String = {
val df = new java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss")
df setTimeZone java.util.TimeZone.getTimeZone("GMT")
baseVersion.map(_ +"-").getOrElse("") + (df format (new java.util.Date))
baseVersion.map(_ + "-").getOrElse("") + (df format (new java.util.Date))
}

def flaggedOptional(flag: Boolean, value: Option[String]): Option[String] =
if(flag) value
if (flag) value
else None

def makeUncommittedSignifierSuffix(hasUncommittedChanges: Boolean, uncommittedSignifier: Option[String]): String =
Expand Down Expand Up @@ -339,8 +350,8 @@ object GitPlugin extends AutoPlugin {
def useReadableConsoleGit = SbtGit.useReadableConsoleGit
def showCurrentGitBranch = SbtGit.showCurrentGitBranch
}
override def buildSettings: Seq[Setting[_]] = SbtGit.buildSettings
override def projectSettings: Seq[Setting[_]] = SbtGit.projectSettings
override def buildSettings: Seq[Setting[?]] = SbtGit.buildSettings
override def projectSettings: Seq[Setting[?]] = SbtGit.projectSettings
}

/** Adapter to auto-enable git versioning. i.e. the sbt 0.13.5+ mechanism of turning it on. */
Expand All @@ -352,5 +363,5 @@ object GitVersioning extends AutoPlugin {
/** Adapter to enable the git prompt. i.e. rich prompt based on git info. */
object GitBranchPrompt extends AutoPlugin {
override def requires = GitPlugin
override def projectSettings = SbtGit.showCurrentGitBranch
override def projectSettings = SbtGit.showCurrentGitBranch
}
9 changes: 5 additions & 4 deletions src/main/scala/com/github/sbt/git/GitRunner.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.github.sbt.git

import sbt._
import sbt.*

/** An interface to run git commands. */
trait GitRunner {
Expand All @@ -12,7 +12,7 @@ trait GitRunner {
def commitAndPush(msg: String, tag: Option[String] = None)(repo: File, log: Logger): Unit = {
apply("add", ".")(repo, log)
apply("commit", "-m", msg, "--allow-empty")(repo, log)
for(tagString <- tag) apply("tag", tagString)(repo, log)
for (tagString <- tag) apply("tag", tagString)(repo, log)
push(repo, log)
}
/** Pushes local commits to the remote branch. */
Expand All @@ -21,8 +21,9 @@ trait GitRunner {
def pull(cwd: File, log: Logger) = apply("pull")(cwd, log)
/** Updates the cwd from a remote branch. If the local git repo doesn't exist, will clone it into existence. */
def updated(remote: String, branch: Option[String], cwd: File, log: Logger): Unit =
if(cwd.exists) pull(cwd, log)
else branch match {
if (cwd.exists) pull(cwd, log)
else
branch match {
case None => apply("clone", remote, ".")(cwd, log)
case Some(b) => apply("clone", "-b", b, remote, ".")(cwd, log)
}
Expand Down
Loading

0 comments on commit df8301f

Please sign in to comment.