Repository: lucidsoftware/neo-sbt-scalafmt
Branch: master
Commit: e236a97fefd6
Files: 44
Total size: 47.4 KB
Directory structure:
gitextract_d3zy9f9d/
├── .gitignore
├── .scalafmt.conf
├── .travis.yml
├── LICENSE
├── README.md
├── build.sbt
├── project/
│ ├── build.properties
│ └── build.sbt
├── sbt-scalafmt/
│ ├── build.sbt
│ └── src/
│ ├── main/
│ │ ├── scala/
│ │ │ └── com/
│ │ │ └── lucidchart/
│ │ │ └── sbt/
│ │ │ └── scalafmt/
│ │ │ ├── BridgeClassLoader.scala
│ │ │ ├── SbtUtil.scala
│ │ │ ├── ScalafmtCheckFailure.scala
│ │ │ ├── ScalafmtCorePlugin.scala
│ │ │ ├── ScalafmtFileFilter.scala
│ │ │ ├── ScalafmtPlugin.scala
│ │ │ └── ScalafmtSbtPlugin.scala
│ │ ├── scala-2.10/
│ │ │ ├── com.lucidchart.sbt.scalafmt/
│ │ │ │ └── Platform.scala
│ │ │ └── sbt/
│ │ │ └── ProjectDefinitionUtil.scala
│ │ └── scala-2.12/
│ │ ├── com/
│ │ │ └── lucidchart/
│ │ │ └── sbt/
│ │ │ └── scalafmt/
│ │ │ └── Platform.scala
│ │ └── sbt/
│ │ └── ProjectDefinitionUtil.scala
│ └── sbt-test/
│ └── sbt-scalafmt/
│ ├── oncompile/
│ │ ├── build.sbt
│ │ ├── project/
│ │ │ ├── build.properties
│ │ │ └── build.sbt
│ │ ├── src/
│ │ │ └── main/
│ │ │ └── scala/
│ │ │ └── Main.scala
│ │ └── test
│ └── simple/
│ ├── build.sbt
│ ├── project/
│ │ ├── build.properties
│ │ └── build.sbt
│ ├── src/
│ │ └── main/
│ │ └── scala/
│ │ └── Main.scala
│ └── test
├── sbt-scalafmt-coursier/
│ ├── build.sbt
│ └── src/
│ └── main/
│ └── scala/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── coursier/
│ └── ScalafmtCoursierPlugin.scala
├── scalafmt-api/
│ ├── build.sbt
│ └── src/
│ └── main/
│ └── java/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── api/
│ ├── Dialect.java
│ ├── ScalafmtFactory.java
│ └── Scalafmtter.java
└── scalafmt-impl/
├── build.sbt
└── src/
├── scalafmt-1.5/
│ └── main/
│ └── scala/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── impl/
│ ├── ScalafmtConfigUtil.scala
│ ├── ScalafmtFactory.scala
│ └── ScalametaUtil.scala
├── scalafmt-2.0/
│ └── main/
│ └── scala/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── impl/
│ ├── ScalafmtConfigUtil.scala
│ ├── ScalafmtFactory.scala
│ └── ScalametaUtil.scala
└── shared/
└── main/
└── scala/
└── com/
└── lucidchart/
└── scalafmt/
└── impl/
└── Scalafmtter.scala
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.idea/
target/
================================================
FILE: .scalafmt.conf
================================================
align.openParenCallSite = false
align.openParenDefnSite = false
continuationIndent.defnSite = 2
danglingParentheses = true
docstrings = JavaDoc
importSelectors = singleLine
maxColumn = 120
newlines.afterImplicitKWInVerticalMultiline = true
rewrite.redundantBraces.stringInterpolation = true
rewrite.rules = [
RedundantBraces,
RedundantParens,
PreferCurlyFors,
SortImports
]
unindentTopLevelOperators = true
================================================
FILE: .travis.yml
================================================
cache:
directories:
- $HOME/.ivy2
- $HOME/.sbt
deploy:
api_key: $GITHUB_AUTH
file: '*/target/**/*.jar'
file_glob: true
on:
tags: true
provider: releases
skip_cleanup: true
git:
depth: 1
jdk:
- openjdk8
dist: bionic
language: scala
script:
- '[ "$TRAVIS_PULL_REQUEST" != false ] || export SBT_OPTS="-Dbuild.version=${TRAVIS_TAG:-$TRAVIS_BRANCH-SNAPSHOT} -DscalafmtOnCompile=false"'
- sbt 'all compile doc:compile sbt:scalafmt::test scalafmt::test' scripted
- |
if [ "$TRAVIS_SECURE_ENV_VARS" == true ]; then
echo "$PGP_SECRET" | base64 --decode | gpg --import
if [ -z "$TRAVIS_TAG" ]; then
sbt publishSigned
else
sbt "sonatypeOpen sbt-scalafmt-$TRAVIS_TAG" publishSigned sonatypeReleaseAll
fi
fi
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# neo-sbt-scalafmt
[](https://travis-ci.com/lucidsoftware/neo-sbt-scalafmt)
[](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.lucidchart%22%20AND%20a%3A%22scalafmt-api%22)
An sbt plugin for [Scalafmt](http://scalameta.org/scalafmt/) that
* formats .sbt and .scala files
* supports sbt 0.13 and 1.0.0-RC3
* supports Scalafmt 0.6 and 1.0
* runs in-process
* uses sbt's ivy2 for dependency resolution
## Usage
In `project/plugins.sbt`,
```scala
// see the Maven badge at the top of this README for the latest version
addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % "<version>")
// if you use coursier, you must use sbt-scalafmt-coursier
// addSbtPlugin("com.lucidchart" % "sbt-scalafmt-coursier" % "<version>")
```
then
```
> scalafmt # format compile sources
> test:scalafmt # format test sources
> sbt:scalafmt # format .sbt source
```
To ensure everything is formatted, and fail if it is not (e.g. as a CI step),
```
> scalafmt::test # check compile sources
> test:scalafmt::test # check test sources
> sbt:scalafmt::test # check .sbt sources
```
## Scalafmt configuration
By default, `.scalafmt.conf` in the root project is used for Scalafmt configuration. If the file does not exist, the
Scalafmt defaults are used. To choose another config file,
```scala
scalafmtConfig in ThisBuild := file("other.scalafmt.conf") // all projects
scalafmtConfig := file("other.scalafmt.conf") // current project
scalafmtConfig in Compile := file("other.scalafmt.conf") // current project, specific configuration
```
To change the Scalafmt version,
```scala
scalafmtVersion in ThisBuild := "1.0.0-RC2" // all projects
scalafmtVersion := "1.0.0-RC2" // current project
```
## Task configuration
To run `scalafmt` automatically before compiling (or before loading, in the case of sbt).
```scala
scalafmtOnCompile in ThisBuild := true // all projects
scalafmtOnCompile := true // current project
scalafmtOnCompile in Compile := true // current project, specific configuration
```
To run `scalafmt::test` automatically before compiling (or before loading, in the case of sbt).
```scala
scalafmtTestOnCompile in ThisBuild := true // all projects
scalafmtTestOnCompile := true // current project
scalafmtTestOnCompile in Compile := true // current project, specific configuration
```
By default, `scalafmt::test` fails if sources are unformatted. If you'd prefer warnings instead:
```scala
scalafmtFailTest in ThisBuild := false // all projects
scalafmtFailTest := false // current project
scalafmtFailTest in Compile := false // current project, specific configuration
```
At the time of writing, Scalafmt fails on some valid inputs. By default, errors in Scalafmt itself do not fail the
`scalafmt` task. To fail instead,
```scala
ignoreErrors in (ThisBuild, scalafmt) := false // all projects
ignoreErrors in scalafmt := false // current project
ignoreErrors in (Compile, scalafmt) := false // current project, specific configuration
```
By default, scalafmt just lists the files that have differences. You can configure it to show the actual diff like this:
```scala
scalafmtShowDiff in (ThisBuild, scalafmt) := true // all projects
scalafmtShowDiff in scalafmt := true // current project
scalafmtShowDiff in (Compile, scalafmt) := true // current project, specific configuration
```
## Additional configuration
The scalafmt task is defined by default for the compile and test configurations. To define it for additional
configurations, e.g. `Integration`,
```scala
inConfig(Integration)(scalafmtSettings)
```
To disable this plugin for a project
```scala
disablePlugins(ScalafmtCorePlugin)
```
## Formatting build files
If you wish to format project/*.scala files, configure the meta-build by adding sbt-scalafmt to
project/project/plugins.sbt, and configuring it in project/plugins.sbt. See
[sbt documentation](http://www.scala-sbt.org/0.13/docs/Organizing-Build.html) on meta-builds.
## Implementation details
Scalafmt artifacts are downloaded with a scalafmt Ivy configuration added to each project. Scalafmt classes are loaded
in a separate classloader, allowing them work regardless of the Scala version of sbt.
* `ScalafmtCorePlugin` adds the Ivy configuration and scalafmt dependency.
* `ScalafmtCoursierPlugin` replaces the sbt ivy configuration with coursier.
* `ScalafmtSbtPlugin` create scalafmt tasks for .sbt sources.
* `ScalafmtPlugin` creates the scalafmt task for compile and test configurations.
Scalafmt requires Java 8+.
================================================
FILE: build.sbt
================================================
import com.lucidchart.sbtcross.{CrossableProject, DefaultAxis, LibraryVersionAxis}
import sbt.CrossVersion.binaryScalaVersion
inScope(Global)(
Seq(
credentials += Credentials(
"Sonatype Nexus Repository Manager",
"oss.sonatype.org",
sys.env.getOrElse("SONATYPE_USERNAME", ""),
sys.env.getOrElse("SONATYPE_PASSWORD", "")
),
developers ++= List(
Developer("pauldraper", "Paul Draper", "", url("https://github.com/pauldraper"))
),
homepage := Some(url("https://github.com/lucidsoftware/neo-sbt-scalafmt")),
licenses += "Apache License 2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0"),
organization := "com.lucidchart",
PgpKeys.pgpPassphrase := Some(Array.emptyCharArray),
scmInfo := Some(
ScmInfo(
url("https://github.com/lucidsoftware/neo-sbt-scalafmt"),
"scm:git:git@github.com:lucidsoftware/neo-sbt-scalafmt.git"
)
),
startYear := Some(2017),
version := sys.props.getOrElse("build.version", "0-SNAPSHOT")
)
)
inThisBuild(
Seq(
scalafmtOnCompile := sys.props.get("scalafmtOnCompile") != Some("false"),
scalafmtVersion := "1.3.0"
)
)
lazy val `scalafmt-api` = project
lazy val localScalafmtVersion = settingKey[String]("Scalafmt version")
lazy val `scalafmt-impl` = project
.dependsOn(`scalafmt-api` % Provided.name)
.cross(new LibraryVersionAxis("scalafmt", localScalafmtVersion, _.split("\\.").take(2).mkString(".")))
lazy val `scalafmt-impl-1.5` = `scalafmt-impl`("1.5.1").settings(
scalaVersion := "2.12.6"
)
lazy val `scalafmt-impl-2.0` = `scalafmt-impl`("2.0.0-RC2").settings(
scalaVersion := "2.12.6"
)
lazy val sbtVersionAxis = new DefaultAxis {
protected[this] val name = "sbt"
protected[this] def major(version: String) = CrossVersion.binarySbtVersion(version)
override def apply[A <: CrossableProject[A]](delegate: A, version: String) = {
val newDelegate = super.apply(delegate, version)
newDelegate.withProject(
newDelegate.project.settings(
Keys.name := Keys.name.value.dropRight(major(version).size + 1),
sbtVersion := version,
scalaCompilerBridgeSource :=
xsbti.ArtifactInfo.SbtOrganization % "compiler-interface" % (sbtVersion in ThisBuild).value % "component" sources (),
sbtBinaryVersion := CrossVersion.binarySbtVersion(sbtVersion.value),
sbtDependency := {
val app = appConfiguration.value
val id = app.provider.id
val scalaVersion = app.provider.scalaProvider.version
val binVersion = binaryScalaVersion(scalaVersion)
val cross = if (id.crossVersioned) CrossVersion.binary else CrossVersion.Disabled
val base = ModuleID(id.groupID, id.name, sbtVersion.value, crossVersion = cross)
CrossVersion(scalaVersion, binVersion)(base).copy(crossVersion = CrossVersion.Disabled)
},
scalaVersion := (sbtVersion.value match {
case version if version.startsWith("0.13.") => "2.10.6"
case version if version.startsWith("1.") => "2.12.6"
})
)
)
}
}
lazy val `sbt-scalafmt` = project.dependsOn(`scalafmt-api`).cross(sbtVersionAxis)
lazy val `sbt-scalafmt_0.13` = `sbt-scalafmt`("0.13.16")
.settings(scriptedSettings)
.settings(
scriptedDependencies := {
(publishLocal in `scalafmt-api`).value
(publishLocal in `scalafmt-impl-1.5`).value
(publishLocal in `scalafmt-impl-2.0`).value
scriptedDependencies.value
},
scriptedLaunchOpts += s"-Dplugin.version=${version.value}"
)
lazy val `sbt-scalafmt_1.0` = `sbt-scalafmt`("1.0.2")
lazy val `sbt-scalafmt-coursier` = project.cross(sbtVersionAxis).dependsOn(`sbt-scalafmt`)
lazy val `sbt-scalafmt-coursier_0.13` = `sbt-scalafmt-coursier`("0.13.16")
lazy val `sbt-scalafmt-coursier_1.0` = `sbt-scalafmt-coursier`("1.0.2")
================================================
FILE: project/build.properties
================================================
sbt.version=0.13.16
================================================
FILE: project/build.sbt
================================================
libraryDependencies += "org.scala-sbt" % "scripted-plugin" % sbtVersion.value
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.7.0")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.0.1")
addSbtPlugin("com.lucidchart" % "sbt-cross" % "3.2")
addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % "1.14")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "1.1")
================================================
FILE: sbt-scalafmt/build.sbt
================================================
enablePlugins(BuildInfoPlugin, ScalafmtPlugin)
buildInfoKeys := Seq[BuildInfoKey.Entry[_]](version)
buildInfoPackage := "com.lucidchart.sbt.scalafmt"
description := "SBT plugin for scalafmt"
libraryDependencies ++= Seq(
"com.google.code.findbugs" % "jsr305" % "3.0.2" % Provided, // fixes warnings about javax annotations
"com.google.guava" % "guava" % "19.0",
"com.michaelpollmeier" %% "colordiff" % "0.8"
)
sbtPlugin := true
scalacOptions ++= Seq(
"-deprecation",
"-feature"
)
================================================
FILE: sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/BridgeClassLoader.scala
================================================
package com.lucidchart.sbt.scalafmt
import java.net.{URL, URLClassLoader}
class BridgeClassLoader(classpath: Seq[URL])(include: String => Boolean)
extends URLClassLoader(classpath.toArray, null) {
private[this] val otherClassLoader = getClass.getClassLoader
override def findClass(name: String) =
if (include(name)) super.findClass(name) else otherClassLoader.loadClass(name)
}
================================================
FILE: sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/SbtUtil.scala
================================================
package com.lucidchart.sbt.scalafmt
import sbt.{file, Configuration, ProjectRef}
object SbtUtil {
def display(project: ProjectRef, configuration: Configuration) = {
val ProjectRef(uri, id) = project
val build = if (uri == file("").toURI) "" else s"{$uri}/"
s"$build$id:$configuration"
}
}
================================================
FILE: sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtCheckFailure.scala
================================================
package com.lucidchart.sbt.scalafmt
class ScalafmtCheckFailure(message: String) extends Exception(message)
================================================
FILE: sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtCorePlugin.scala
================================================
package com.lucidchart.sbt.scalafmt
import colordiff.ColorDiff
import com.google.common.cache._
import com.lucidchart.scalafmt.api.{Dialect, ScalafmtFactory, Scalafmtter}
import java.io.FileNotFoundException
import java.util.Arrays
import sbt.KeyRanks._
import sbt.Keys._
import sbt._
import sbt.plugins.{IvyPlugin, JvmPlugin}
import scala.collection.breakOut
import scala.io.Source
import scala.util.control.NonFatal
import scala.util.control.Exception.catching
object ScalafmtCorePlugin extends AutoPlugin {
object autoImport {
case object UseScalafmtConfigFilter extends FileFilter {
def accept(file: File) = ???
}
val Scalafmt = config("scalafmt").hide
val ignoreErrors = TaskKey[Boolean]("ignore-errors", "Ignore errors for a task", BTask)
val scalafmt = TaskKey[Unit]("scalafmt", "Format Scala sources", ATask)
val scalafmtCache =
SettingKey[Seq[File] => String => Scalafmtter]("scalafmtCache", "Cache of Scalafmtter instances", DSetting)
val scalafmtCacheBuilder = SettingKey[CacheBuilder[Seq[File], String => Scalafmtter]](
"scalafmt-cache-builder",
"CacheBuilder for Scalafmtter cache",
CSetting
)
val scalafmtConfig = TaskKey[File]("scalafmt-config", "Scalafmtter config file", BTask)
val scalafmtDialect = SettingKey[Dialect]("scalafmt-dialect", "Dialect of Scala sources", BSetting)
val scalafmtOnCompile = SettingKey[Boolean]("scalafmt-on-compile", "Format source when compiling", BTask)
val scalafmtTestOnCompile =
SettingKey[Boolean]("scalafmt-test-on-compile", "Check source format when compiling", BTask)
// A better way is to put things in a sbt-scalafmt-ivy plugin, but this stuff is currently in flux.
val scalafmtUseIvy = SettingKey[Boolean]("scalafmt-use-ivy", "Use sbt's Ivy resolution", CSetting)
val scalafmtVersion = SettingKey[String]("scalafmt-version", "Scalafmtter version", AMinusSetting)
val scalafmtter = TaskKey[Scalafmtter]("scalafmtter", "Scalafmt API")
val scalafmtFailTest = SettingKey[Boolean](
"scalafmt-Fail-Test",
"Fail build when one or more style issues are found",
CSetting
)
val scalafmtShowDiff = SettingKey[Boolean](
"scalafmt-show-diff",
"show differences between original and formatted version",
CSetting
)
private[this] val scalafmtFn = Def.task {
val ignoreErrors = this.ignoreErrors.value
val logger = streams.value.log
val scalafmtter = autoImport.scalafmtter.value.formatter(scalafmtDialect.value)
(name: String, input: String) =>
{
try scalafmtter(input)
catch {
case NonFatal(e) =>
val exceptionMesssage = e.getLocalizedMessage
val message = if (exceptionMesssage.contains("<input>")) {
exceptionMesssage.replace("<input>", name)
} else {
s"$name:\n$exceptionMesssage"
}
if (ignoreErrors) {
logger.warn(message)
input
} else {
throw new Exception(message, e)
}
}
}
}
val scalafmtCoreSettings: Seq[Def.Setting[_]] =
Seq(
externalDependencyClasspath in scalafmt := (externalDependencyClasspath in Scalafmt).value,
scalafmt := (scalafmt in scalafmt).value
) ++ inTask(scalafmt)(
Seq(
clean := IO.delete(streams.value.cacheDirectory),
scalafmt := {
val logger = streams.value.log
val display = SbtUtil.display(thisProjectRef.value, configuration.value)
val classpath = externalDependencyClasspath.value.map(_.data)
val extraModified = (scalafmtConfig.value +: classpath).map(_.lastModified).max
lazy val extraHash = Hash(
classpath.toArray.flatMap(Hash(_)) ++
catching(classOf[FileNotFoundException])
.opt(Hash(scalafmtConfig.value))
.getOrElse(Array.emptyByteArray)
)
// It would be simpler to use SBT's built-in FileFunction or similar, but this offers better performance and
// doesn't take that much more work.
// We first check timestamps, and only then check hashes.
val cacheFile = streams.value.cacheDirectory / "scalafmt"
val oldInfo: Map[File, HashModifiedFileInfo] = CachePlatform
.readFileInfo(cacheFile)
.map(info => info.file -> info)(breakOut)
val updatedInfo = sources.value.map {
source =>
val old = oldInfo.getOrElse(source, CachePlatform.fileInfo(source, Nil, Long.MinValue))
val updatedLastModified = extraModified max old.file.lastModified
if (old.lastModified < updatedLastModified) {
val updatedHash = Hash(IO.readBytes(old.file) ++ extraHash)
val updatedInfo = CachePlatform.fileInfo(old.file, updatedHash.toList, updatedLastModified)
Either.cond(Arrays.equals(old.hash.toArray, updatedHash), updatedInfo, updatedInfo)
} else {
Right(CachePlatform.fileInfo(old.file, old.hash, updatedLastModified))
}
}
AnalysisPlatform.counted("Scala source", "", "s", updatedInfo.count(_.isLeft)).foreach { message =>
logger.info(s"Formatting $message in $display ...")
}
val scalafmtter = scalafmtFn.value
val newInfo = updatedInfo.map(_.left.flatMap { updatedInfo =>
val input = IO.read(updatedInfo.file)
val output = scalafmtter(updatedInfo.file.toString, input)
Either.cond(
input == output,
updatedInfo, {
IO.write(updatedInfo.file, output)
CachePlatform.fileInfo(updatedInfo.file, Hash(output).toList, updatedInfo.file.lastModified)
}
)
})
AnalysisPlatform.counted("Scala source", "", "s", newInfo.count(_.isLeft)).foreach { message =>
logger.info(s"Reformatted $message in $display")
}
CachePlatform.writeFileInfo(cacheFile, newInfo.map(_.merge)(breakOut))
},
scalafmtter := {
val file = scalafmtConfig.value
val logger = streams.value.log
val configString = try IO.read(file)
catch {
case _: FileNotFoundException =>
logger.debug(s"$file does not exist")
""
}
scalafmtCache.value(externalDependencyClasspath.value.map(_.data))(configString)
},
sources := Def.taskDyn {
includeFilter.value match {
case UseScalafmtConfigFilter =>
val directories = sourceDirectories.value
scalafmtter.map(scalafmtter => (directories ** new ScalafmtFileFilter(scalafmtter)).get)
case _ => Defaults.collectFiles(sourceDirectories, includeFilter, excludeFilter)
}
}.value
)
) ++ inTask(scalafmt)(
Seq(
test := {
// Nothing is currently cached. This is probably okay since it is run for CI builds.
val logger = streams.value.log
val display = SbtUtil.display(thisProjectRef.value, configuration.value)
AnalysisPlatform.counted("Scala source", "", "s", sources.value.size).foreach { message =>
logger.info(s"Checking formatting for $message in $display ...")
}
val scalafmtter = scalafmtFn.value
val failForStyleIssues = scalafmtFailTest.value
val showDiff = scalafmtShowDiff.value
val differentCount = sources.value.count {
file =>
val original = IO.read(file)
val formatted = scalafmtter(file.toString, original)
val hasChanges = original != formatted
if (hasChanges) {
val msg = if (showDiff) {
val diff = ColorDiff(original.split('\n').toList, formatted.split('\n').toList)
s"$file has changes after scalafmt:\n$diff"
} else s"$file has changes after scalafmt"
if (failForStyleIssues) logger.error(msg)
else logger.warn(msg)
}
hasChanges
}
AnalysisPlatform.counted("Scala source", "", "s", differentCount).foreach { message =>
val msg = s"$message not formatted in $display"
if (failForStyleIssues) throw new ScalafmtCheckFailure(s"$message not formatted in $display")
else logger.warn(msg)
}
}
)
)
val scalafmtSettings = scalafmtCoreSettings ++
Seq(
compileInputs in compile := Def.taskDyn {
val task =
if (scalafmtOnCompile.value) scalafmt in resolvedScoped.value.scope
else if (scalafmtTestOnCompile.value) test in (resolvedScoped.value.scope in scalafmt.key)
else Def.task(())
val previousInputs = (compileInputs in compile).value
task.map(_ => previousInputs)
}.value
) ++
inTask(scalafmt)(
Seq(
scalafmtDialect := Dialect.SCALA,
sourceDirectories := Seq(scalaSource.value)
)
)
}
import autoImport._
override val buildSettings = Seq(
ignoreErrors := true,
includeFilter in scalafmt := UseScalafmtConfigFilter,
scalafmtCache := {
val cache = scalafmtCacheBuilder.value.build(new CacheLoader[Seq[File], String => Scalafmtter] {
def load(classpath: Seq[File]): String => Scalafmtter = {
val factory =
new BridgeClassLoader(classpath.map(_.toURI.toURL))(!_.startsWith("com.lucidchart.scalafmt.api."))
.loadClass("com.lucidchart.scalafmt.impl.ScalafmtFactory")
.asInstanceOf[Class[_ <: ScalafmtFactory]]
.newInstance
val cache = CacheBuilder.newBuilder
.maximumSize(5)
.build(new CacheLoader[String, Scalafmtter] {
def load(configString: String) = factory.fromConfig(configString)
})
cache.get
}
})
cache.get
},
scalafmtCacheBuilder := CacheBuilder.newBuilder
.asInstanceOf[CacheBuilder[Seq[File], String => Scalafmtter]]
.maximumSize(3),
scalafmtConfig := (baseDirectory in ThisBuild).value / ".scalafmt.conf",
scalafmtOnCompile := false,
scalafmtTestOnCompile := false,
scalafmtVersion := "1.5.1",
scalafmtFailTest := true,
scalafmtShowDiff := false
)
override val projectSettings = Seq(
externalDependencyClasspath in Scalafmt := Classpaths.managedJars(Scalafmt, classpathTypes.value, update.value),
ivyConfigurations ++= (if (scalafmtUseIvy.value) Seq(Scalafmt) else Seq.empty),
libraryDependencies ++=
(if (scalafmtUseIvy.value) (libraryDependencies in Scalafmt).value.map(_ % Scalafmt) else Seq.empty),
libraryDependencies in Scalafmt := {
val (scalaBinaryVersion, fmtVersion, fmtOrg) = "(\\d+.){0,1}\\d+".r
.findPrefixOf(scalafmtVersion.value)
.flatMap { prefix =>
scalafmtMetadata.get(prefix)
}
.getOrElse {
println(s"Warning: Unknown Scalafmt version ${scalafmtVersion.value}; using 1.5 interface")
scalafmtMetadata("1.5")
}
val version = if (BuildInfo.version.endsWith("-SNAPSHOT")) {
s"${BuildInfo.version.stripSuffix("-SNAPSHOT")}-$fmtVersion-SNAPSHOT"
} else {
s"${BuildInfo.version}-$fmtVersion"
}
Seq(
fmtOrg % s"scalafmt-core_$scalaBinaryVersion" % scalafmtVersion.value,
"com.lucidchart" % s"scalafmt-impl_$scalaBinaryVersion" % version
)
},
scalafmtUseIvy := true
) :+ LibraryPlatform.moduleInfo(scalafmtUseIvy)
private val scalafmtMetadata = Map(
"1.5" -> ("2.12", "1.5", "com.geirsson"),
"2.0" -> ("2.12", "2.0", "org.scalameta")
)
override val requires = IvyPlugin && JvmPlugin
override val trigger = allRequirements
}
================================================
FILE: sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtFileFilter.scala
================================================
package com.lucidchart.sbt.scalafmt
import com.lucidchart.scalafmt.api.Scalafmtter
import java.io.File
import sbt.FileFilter
class ScalafmtFileFilter(scalafmtter: Scalafmtter) extends FileFilter {
def accept(file: File) = file.isFile && scalafmtter.includeFile(file.toPath)
}
================================================
FILE: sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtPlugin.scala
================================================
package com.lucidchart.sbt.scalafmt
import com.lucidchart.sbt.scalafmt.ScalafmtCorePlugin.autoImport._
import sbt._
import sbt.Keys._
object ScalafmtPlugin extends AutoPlugin {
override val projectSettings = Seq(Compile, Test).flatMap(inConfig(_)(scalafmtSettings)) ++
inConfig(Compile)(
inTask(scalafmt)(
Seq(
sources ++= Def
.taskDyn[Seq[File]] {
if (!sourcesInBase.value) {
Def.task(Seq.empty[File])
} else if (includeFilter.value == UseScalafmtConfigFilter) {
Def.task((baseDirectory.value * (new ScalafmtFileFilter(scalafmtter.value) && "*.scala")).get)
} else {
Def.task((baseDirectory.value * includeFilter.value --- baseDirectory.value * excludeFilter.value).get)
}
}
.value
)
)
)
override val requires = ScalafmtCorePlugin
override val trigger = allRequirements
}
================================================
FILE: sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtSbtPlugin.scala
================================================
package com.lucidchart.sbt.scalafmt
import com.lucidchart.sbt.scalafmt.ScalafmtCorePlugin.autoImport._
import com.lucidchart.scalafmt.api.Dialect
import sbt.Keys._
import sbt._
object ScalafmtSbtPlugin extends AutoPlugin {
object autoImport {
val Sbt = config("sbt")
}
import autoImport._
override val globalSettings = Seq(
onLoad := { state =>
onLoad.value {
val projects = Def
.settingDyn(Def.Initialize.join(loadedBuild.value.allProjectRefs.map(_._1).map { project =>
(scalafmtOnCompile in (project, Sbt))(if (_) Some(project) else None)
}))
.value
.flatten
if (projects.isEmpty) {
state
} else {
val command = CommandPlatform.CommandStrings.MultiTaskCommand +:
projects.map(project => s"${Reference.display(project)}/$Sbt:${scalafmt.key}")
command.mkString(" ") :: state
}
}
}
)
override val projectSettings = inConfig(Sbt)(
scalafmtCoreSettings ++
Seq(
scalafmtDialect := Dialect.SBT,
sources in scalafmt := new ProjectDefinitionUtil(thisProject.value).sbtFiles.toSeq
)
)
override val requires = ScalafmtCorePlugin
override val trigger = allRequirements
}
================================================
FILE: sbt-scalafmt/src/main/scala-2.10/com.lucidchart.sbt.scalafmt/Platform.scala
================================================
package com.lucidchart.sbt.scalafmt
import sbinary.DefaultProtocol._
import sbt.Keys._
import sbt._
import sbt.FileInfo.full.{format => hashModifiedFormat}
import sbt.inc.Analysis
object AnalysisPlatform {
def counted(prefix: String, single: String, plural: String, count: Int) =
Analysis.counted(prefix, single, plural, count)
}
object CachePlatform {
def fileInfo(file: File, hash: List[Byte], lastModified: Long) = FileInfo.full.make(file, hash, lastModified)
def readFileInfo(cache: File) = CacheIO.fromFile[Set[HashModifiedFileInfo]](cache).getOrElse(Set.empty)
def writeFileInfo(cache: File, value: Set[HashModifiedFileInfo]) = CacheIO.toFile(value)(cache)
}
object CommandPlatform {
val CommandStrings = sbt.CommandStrings
}
object LibraryPlatform {
def moduleInfo(useIvy: SettingKey[Boolean]) =
ivyScala := {
if (useIvy.value) {
// otherwise scala-library conflicts
ivyScala.value.map(_.copy(overrideScalaVersion = false))
} else {
ivyScala.value
}
}
}
================================================
FILE: sbt-scalafmt/src/main/scala-2.10/sbt/ProjectDefinitionUtil.scala
================================================
package sbt
import scala.collection.breakOut
/**
* Defined in sbt packaged because of private[sbt] restrictions.
*/
class ProjectDefinitionUtil(project: ProjectDefinition[_]) {
def sbtFiles = {
def sbtFiles(addSettings: AddSettings): Set[File] = addSettings match {
case addSettings: AddSettings.SbtFiles =>
addSettings.files.map(IO.resolve(project.base, _)).filterNot(_.isHidden).toSet
case addSettings: AddSettings.DefaultSbtFiles =>
BuildPaths.configurationSources(project.base).filter(addSettings.include).filterNot(_.isHidden).toSet
case addSettings: AddSettings.Sequence =>
addSettings.sequence.flatMap(sbtFiles)(breakOut)
case _ => Set.empty
}
sbtFiles(project.auto)
}
}
================================================
FILE: sbt-scalafmt/src/main/scala-2.12/com/lucidchart/sbt/scalafmt/Platform.scala
================================================
package com.lucidchart.sbt.scalafmt
import sbt.Keys._
import sbt._
import sbt.internal.inc.Analysis
import sbt.util.CacheImplicits._
import sbt.util.CacheStore
import scala.reflect.runtime.universe
object AnalysisPlatform {
def counted(prefix: String, single: String, plural: String, count: Int) =
Analysis.counted(prefix, single, plural, count)
}
object CachePlatform {
private[this] val mirror = universe.runtimeMirror(getClass.getClassLoader)
private[this] val fileHashModified = {
val module = mirror.reflectModule(mirror.staticModule("sbt.util.FileHashModified"))
mirror.reflect(module.instance).reflectMethod(module.symbol.info.decl(universe.TermName("apply")).asMethod)
}
def fileInfo(file: File, hash: List[Byte], lastModified: Long) =
fileHashModified(file, hash, lastModified.asInstanceOf[AnyRef]).asInstanceOf[HashModifiedFileInfo]
def readFileInfo(cache: File) = CacheStore(cache).read(Set.empty[HashModifiedFileInfo])
def writeFileInfo(cache: File, value: Set[HashModifiedFileInfo]) = CacheStore(cache).write(value)
}
object CommandPlatform {
val CommandStrings = sbt.internal.CommandStrings
}
object LibraryPlatform {
def moduleInfo(useIvy: SettingKey[Boolean]) =
scalaModuleInfo := {
if (useIvy.value) {
// otherwise scala-library conflicts
scalaModuleInfo.value.map(_.withOverrideScalaVersion(false))
} else {
scalaModuleInfo.value
}
}
}
================================================
FILE: sbt-scalafmt/src/main/scala-2.12/sbt/ProjectDefinitionUtil.scala
================================================
package sbt
import sbt.internal.AddSettings
import scala.collection.breakOut
/**
* Defined in sbt packaged because of private[sbt] restrictions.
*/
class ProjectDefinitionUtil(project: ProjectDefinition[_]) {
def sbtFiles = {
def sbtFiles(addSettings: AddSettings): Set[File] = addSettings match {
case addSettings: AddSettings.SbtFiles =>
addSettings.files.map(IO.resolve(project.base, _)).filterNot(_.isHidden).toSet
case addSettings: AddSettings.DefaultSbtFiles =>
BuildPaths.configurationSources(project.base).filter(addSettings.include).filterNot(_.isHidden).toSet
case addSettings: AddSettings.Sequence =>
addSettings.sequence.flatMap(sbtFiles)(breakOut)
case _ => Set.empty
}
sbtFiles(AddSettings.defaultSbtFiles)
}
}
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/build.sbt
================================================
scalafmtOnCompile := true
ignoreErrors in scalafmt := false
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/project/build.properties
================================================
sbt.version=0.13.16
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/project/build.sbt
================================================
addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % sys.props("plugin.version"))
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/src/main/scala/Main.scala
================================================
object Main extends App {
println( "hello" )
}
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/test
================================================
-> scalafmt::test
> compile
> scalafmt::test
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/build.sbt
================================================
ignoreErrors in scalafmt := false
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/project/build.properties
================================================
sbt.version=0.13.16
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/project/build.sbt
================================================
addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % sys.props("plugin.version"))
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/src/main/scala/Main.scala
================================================
object Main extends App {
println( "hello" )
}
================================================
FILE: sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/test
================================================
-> scalafmt::test
> scalafmt
> scalafmt::test
================================================
FILE: sbt-scalafmt-coursier/build.sbt
================================================
description := "Replaces ivy2 resolution for sbt-scalafmt with coursier"
libraryDependencies ++= Seq(
"io.get-coursier" %% "coursier" % "1.0.1",
"io.get-coursier" %% "coursier-cache" % "1.0.1"
)
sbtPlugin := true
================================================
FILE: sbt-scalafmt-coursier/src/main/scala/com/lucidchart/scalafmt/coursier/ScalafmtCoursierPlugin.scala
================================================
package com.lucidchart.scalafmt.coursier
import com.lucidchart.sbt.scalafmt.ScalafmtCorePlugin
import com.lucidchart.sbt.scalafmt.ScalafmtCorePlugin.autoImport._
import coursier._
import java.io.{FileNotFoundException, IOException}
import sbt.KeyRanks._
import sbt.Keys._
import sbt._
import scala.util.control.NonFatal
import scalaz.concurrent.Task
/**
* This does not pull from sbt settings like sbt-coursier. It is a quickish fix to some issues like
* https://github.com/lucidsoftware/neo-sbt-scalafmt/issues/1 .
*/
object ScalafmtCoursierPlugin extends AutoPlugin {
object autoImport {
val scalafmtCoursierRepositories =
SettingKey[Seq[Repository]]("scalafmt-coursier-repositories", "Coursier respositories for scalafmt", BTask)
}
import autoImport._
override val projectSettings = Seq(
externalDependencyClasspath in Scalafmt := {
val dependencies = (libraryDependencies in Scalafmt).value
.map(module => Dependency(Module(module.organization, module.name), module.revision))
.toSet
val cacheFile = streams.value.cacheDirectory / "dependencies"
val newHash = dependencies.hashCode
val cached = try {
IO.readLines(cacheFile) match {
case hash +: fileStrings =>
val files = fileStrings.map(file)
if (hash.toInt == newHash && files.forall(_.exists)) Some(files) else None
}
} catch {
case _: FileNotFoundException => None
case NonFatal(e) =>
streams.value.log.error(e.getLocalizedMessage)
None
}
Attributed.blankSeq(cached.getOrElse {
synchronized {
val fetch = Fetch.from(scalafmtCoursierRepositories.value, coursier.Cache.fetch())
streams.value.log.info(s"Fetching scalafmt for ${Reference.display(thisProjectRef.value)}")
val resolution = Resolution(dependencies).process.run(fetch).unsafePerformSync
val result = Task
.gatherUnordered(resolution.artifacts.map(coursier.Cache.file(_).run))
.unsafePerformSync
.map(_.valueOr(error => throw new IOException(error.describe)))
.filter(_.ext == "jar")
.sorted
streams.value.log.info(s"Fetched ${result.size} artifacts for scalafmt")
IO.writeLines(cacheFile, newHash.toString +: result.map(_.toString))
result
}
})
},
scalafmtUseIvy := false
)
override val buildSettings = Seq(
scalafmtCoursierRepositories := Seq(
coursier.Cache.ivy2Local,
coursier.MavenRepository("https://repo1.maven.org/maven2")
)
)
override val requires = ScalafmtCorePlugin
override val trigger = allRequirements
}
================================================
FILE: scalafmt-api/build.sbt
================================================
disablePlugins(ScalafmtCorePlugin)
autoScalaLibrary := false
crossPaths := false
description := "Bridge for scalafmt API"
================================================
FILE: scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/Dialect.java
================================================
package com.lucidchart.scalafmt.api;
public enum Dialect {
SCALA,
SBT
}
================================================
FILE: scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/ScalafmtFactory.java
================================================
package com.lucidchart.scalafmt.api;
public interface ScalafmtFactory {
Scalafmtter fromConfig(String configString);
}
================================================
FILE: scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/Scalafmtter.java
================================================
package com.lucidchart.scalafmt.api;
import java.nio.file.Path;
import java.util.function.Function;
public interface Scalafmtter {
Function<String, String> formatter(Dialect dialect);
boolean includeFile(Path file);
}
================================================
FILE: scalafmt-impl/build.sbt
================================================
disablePlugins(ScalafmtCorePlugin)
description := "Implementation for scalafmt-api"
def scalafmtOrg(scalafmtVersion: String): String = {
if (scalafmtVersion.startsWith("2")) {
"org.scalameta"
} else {
"com.geirsson"
}
}
libraryDependencies += scalafmtOrg(SettingKey[String]("local-scalafmt-version").value) %% s"scalafmt-core" % SettingKey[String]("local-scalafmt-version").value % Provided
================================================
FILE: scalafmt-impl/src/scalafmt-1.5/main/scala/com/lucidchart/scalafmt/impl/ScalafmtConfigUtil.scala
================================================
package com.lucidchart.scalafmt.impl
import org.scalafmt.Scalafmt
import org.scalafmt.config.ScalafmtConfig
import scala.meta.Dialect
object ScalafmtConfigUtil {
def setDialect(config: ScalafmtConfig, dialect: Dialect) =
Scalafmt.configWithDialect(config, dialect)
}
================================================
FILE: scalafmt-impl/src/scalafmt-1.5/main/scala/com/lucidchart/scalafmt/impl/ScalafmtFactory.scala
================================================
package com.lucidchart.scalafmt.impl
import com.lucidchart.scalafmt.api
import java.util.function
import org.scalafmt.config.Config
import scala.meta.dialects
final class ScalafmtFactory extends api.ScalafmtFactory {
def fromConfig(configString: String) = new Scalafmtter(Config.fromHoconString(configString, Option.empty).get)
}
================================================
FILE: scalafmt-impl/src/scalafmt-1.5/main/scala/com/lucidchart/scalafmt/impl/ScalametaUtil.scala
================================================
package com.lucidchart.scalafmt.impl
import scala.meta.internal.tokenizers.PlatformTokenizerCache
object ScalametaUtil {
def clearCache() = PlatformTokenizerCache.megaCache.clear()
}
================================================
FILE: scalafmt-impl/src/scalafmt-2.0/main/scala/com/lucidchart/scalafmt/impl/ScalafmtConfigUtil.scala
================================================
package com.lucidchart.scalafmt.impl
import org.scalafmt.Scalafmt
import org.scalafmt.config.ScalafmtConfig
import scala.meta.Dialect
object ScalafmtConfigUtil {
def setDialect(config: ScalafmtConfig, dialect: Dialect) =
Scalafmt.configWithDialect(config, dialect)
}
================================================
FILE: scalafmt-impl/src/scalafmt-2.0/main/scala/com/lucidchart/scalafmt/impl/ScalafmtFactory.scala
================================================
package com.lucidchart.scalafmt.impl
import com.lucidchart.scalafmt.api
import java.util.function
import org.scalafmt.config.Config
import scala.meta.dialects
final class ScalafmtFactory extends api.ScalafmtFactory {
def fromConfig(configString: String) = new Scalafmtter(Config.fromHoconString(configString, Option.empty).get)
}
================================================
FILE: scalafmt-impl/src/scalafmt-2.0/main/scala/com/lucidchart/scalafmt/impl/ScalametaUtil.scala
================================================
package com.lucidchart.scalafmt.impl
import scala.meta.internal.tokenizers.PlatformTokenizerCache
object ScalametaUtil {
def clearCache() = PlatformTokenizerCache.megaCache.clear()
}
================================================
FILE: scalafmt-impl/src/shared/main/scala/com/lucidchart/scalafmt/impl/Scalafmtter.scala
================================================
package com.lucidchart.scalafmt.impl
import com.lucidchart.scalafmt.api
import com.lucidchart.scalafmt.api.Dialect
import java.nio.file.Path
import java.util.function
import org.scalafmt
import org.scalafmt.config.ScalafmtConfig
import scala.meta.dialects
class Scalafmtter(config: ScalafmtConfig) extends api.Scalafmtter {
self =>
def formatter(dialect: Dialect) = new function.Function[String, String] {
private[this] val config = dialect match {
case Dialect.SBT => ScalafmtConfigUtil.setDialect(self.config, dialects.Sbt0137)
case Dialect.SCALA => self.config
}
def apply(code: String) = scalafmt.Scalafmt.format(code, config).get
}
def includeFile(file: Path) = config.project.matcher.matches(file.toString)
// Otherwise, this cache hangs on to a lot
override protected def finalize() = try ScalametaUtil.clearCache() finally super.finalize()
}
gitextract_d3zy9f9d/
├── .gitignore
├── .scalafmt.conf
├── .travis.yml
├── LICENSE
├── README.md
├── build.sbt
├── project/
│ ├── build.properties
│ └── build.sbt
├── sbt-scalafmt/
│ ├── build.sbt
│ └── src/
│ ├── main/
│ │ ├── scala/
│ │ │ └── com/
│ │ │ └── lucidchart/
│ │ │ └── sbt/
│ │ │ └── scalafmt/
│ │ │ ├── BridgeClassLoader.scala
│ │ │ ├── SbtUtil.scala
│ │ │ ├── ScalafmtCheckFailure.scala
│ │ │ ├── ScalafmtCorePlugin.scala
│ │ │ ├── ScalafmtFileFilter.scala
│ │ │ ├── ScalafmtPlugin.scala
│ │ │ └── ScalafmtSbtPlugin.scala
│ │ ├── scala-2.10/
│ │ │ ├── com.lucidchart.sbt.scalafmt/
│ │ │ │ └── Platform.scala
│ │ │ └── sbt/
│ │ │ └── ProjectDefinitionUtil.scala
│ │ └── scala-2.12/
│ │ ├── com/
│ │ │ └── lucidchart/
│ │ │ └── sbt/
│ │ │ └── scalafmt/
│ │ │ └── Platform.scala
│ │ └── sbt/
│ │ └── ProjectDefinitionUtil.scala
│ └── sbt-test/
│ └── sbt-scalafmt/
│ ├── oncompile/
│ │ ├── build.sbt
│ │ ├── project/
│ │ │ ├── build.properties
│ │ │ └── build.sbt
│ │ ├── src/
│ │ │ └── main/
│ │ │ └── scala/
│ │ │ └── Main.scala
│ │ └── test
│ └── simple/
│ ├── build.sbt
│ ├── project/
│ │ ├── build.properties
│ │ └── build.sbt
│ ├── src/
│ │ └── main/
│ │ └── scala/
│ │ └── Main.scala
│ └── test
├── sbt-scalafmt-coursier/
│ ├── build.sbt
│ └── src/
│ └── main/
│ └── scala/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── coursier/
│ └── ScalafmtCoursierPlugin.scala
├── scalafmt-api/
│ ├── build.sbt
│ └── src/
│ └── main/
│ └── java/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── api/
│ ├── Dialect.java
│ ├── ScalafmtFactory.java
│ └── Scalafmtter.java
└── scalafmt-impl/
├── build.sbt
└── src/
├── scalafmt-1.5/
│ └── main/
│ └── scala/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── impl/
│ ├── ScalafmtConfigUtil.scala
│ ├── ScalafmtFactory.scala
│ └── ScalametaUtil.scala
├── scalafmt-2.0/
│ └── main/
│ └── scala/
│ └── com/
│ └── lucidchart/
│ └── scalafmt/
│ └── impl/
│ ├── ScalafmtConfigUtil.scala
│ ├── ScalafmtFactory.scala
│ └── ScalametaUtil.scala
└── shared/
└── main/
└── scala/
└── com/
└── lucidchart/
└── scalafmt/
└── impl/
└── Scalafmtter.scala
SYMBOL INDEX (6 symbols across 3 files)
FILE: scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/Dialect.java
type Dialect (line 3) | public enum Dialect {
FILE: scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/ScalafmtFactory.java
type ScalafmtFactory (line 3) | public interface ScalafmtFactory {
method fromConfig (line 5) | Scalafmtter fromConfig(String configString);
FILE: scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/Scalafmtter.java
type Scalafmtter (line 6) | public interface Scalafmtter {
method formatter (line 8) | Function<String, String> formatter(Dialect dialect);
method includeFile (line 10) | boolean includeFile(Path file);
Condensed preview — 44 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (54K chars).
[
{
"path": ".gitignore",
"chars": 15,
"preview": ".idea/\ntarget/\n"
},
{
"path": ".scalafmt.conf",
"chars": 415,
"preview": "align.openParenCallSite = false\nalign.openParenDefnSite = false\ncontinuationIndent.defnSite = 2\ndanglingParentheses = tr"
},
{
"path": ".travis.yml",
"chars": 783,
"preview": "cache:\n directories:\n - $HOME/.ivy2\n - $HOME/.sbt\ndeploy:\n api_key: $GITHUB_AUTH\n file: '*/target/**/*.jar'\n f"
},
{
"path": "LICENSE",
"chars": 11358,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 4750,
"preview": "# neo-sbt-scalafmt\n\n[](https://travis-ci.com/lu"
},
{
"path": "build.sbt",
"chars": 3856,
"preview": "import com.lucidchart.sbtcross.{CrossableProject, DefaultAxis, LibraryVersionAxis}\nimport sbt.CrossVersion.binaryScalaVe"
},
{
"path": "project/build.properties",
"chars": 20,
"preview": "sbt.version=0.13.16\n"
},
{
"path": "project/build.sbt",
"chars": 357,
"preview": "libraryDependencies += \"org.scala-sbt\" % \"scripted-plugin\" % sbtVersion.value\n\naddSbtPlugin(\"com.eed3si9n\" % \"sbt-buildi"
},
{
"path": "sbt-scalafmt/build.sbt",
"chars": 495,
"preview": "enablePlugins(BuildInfoPlugin, ScalafmtPlugin)\n\nbuildInfoKeys := Seq[BuildInfoKey.Entry[_]](version)\n\nbuildInfoPackage :"
},
{
"path": "sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/BridgeClassLoader.scala",
"chars": 395,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport java.net.{URL, URLClassLoader}\n\nclass BridgeClassLoader(classpath: Seq[URL])"
},
{
"path": "sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/SbtUtil.scala",
"chars": 309,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport sbt.{file, Configuration, ProjectRef}\n\nobject SbtUtil {\n\n def display(proje"
},
{
"path": "sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtCheckFailure.scala",
"chars": 108,
"preview": "package com.lucidchart.sbt.scalafmt\n\nclass ScalafmtCheckFailure(message: String) extends Exception(message)\n"
},
{
"path": "sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtCorePlugin.scala",
"chars": 12274,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport colordiff.ColorDiff\nimport com.google.common.cache._\nimport com.lucidchart.s"
},
{
"path": "sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtFileFilter.scala",
"chars": 280,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport com.lucidchart.scalafmt.api.Scalafmtter\nimport java.io.File\nimport sbt.FileF"
},
{
"path": "sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtPlugin.scala",
"chars": 971,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport com.lucidchart.sbt.scalafmt.ScalafmtCorePlugin.autoImport._\nimport sbt._\nimp"
},
{
"path": "sbt-scalafmt/src/main/scala/com/lucidchart/sbt/scalafmt/ScalafmtSbtPlugin.scala",
"chars": 1269,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport com.lucidchart.sbt.scalafmt.ScalafmtCorePlugin.autoImport._\nimport com.lucid"
},
{
"path": "sbt-scalafmt/src/main/scala-2.10/com.lucidchart.sbt.scalafmt/Platform.scala",
"chars": 1036,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport sbinary.DefaultProtocol._\nimport sbt.Keys._\nimport sbt._\nimport sbt.FileInfo"
},
{
"path": "sbt-scalafmt/src/main/scala-2.10/sbt/ProjectDefinitionUtil.scala",
"chars": 748,
"preview": "package sbt\n\nimport scala.collection.breakOut\n\n/**\n * Defined in sbt packaged because of private[sbt] restrictions.\n */\n"
},
{
"path": "sbt-scalafmt/src/main/scala-2.12/com/lucidchart/sbt/scalafmt/Platform.scala",
"chars": 1449,
"preview": "package com.lucidchart.sbt.scalafmt\n\nimport sbt.Keys._\nimport sbt._\nimport sbt.internal.inc.Analysis\nimport sbt.util.Cac"
},
{
"path": "sbt-scalafmt/src/main/scala-2.12/sbt/ProjectDefinitionUtil.scala",
"chars": 795,
"preview": "package sbt\n\nimport sbt.internal.AddSettings\nimport scala.collection.breakOut\n\n/**\n * Defined in sbt packaged because of"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/build.sbt",
"chars": 60,
"preview": "scalafmtOnCompile := true\nignoreErrors in scalafmt := false\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/project/build.properties",
"chars": 20,
"preview": "sbt.version=0.13.16\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/project/build.sbt",
"chars": 78,
"preview": "addSbtPlugin(\"com.lucidchart\" % \"sbt-scalafmt\" % sys.props(\"plugin.version\"))\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/src/main/scala/Main.scala",
"chars": 49,
"preview": "object Main extends App {\n println( \"hello\" )\n}\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/oncompile/test",
"chars": 45,
"preview": "-> scalafmt::test\n> compile\n> scalafmt::test\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/build.sbt",
"chars": 34,
"preview": "ignoreErrors in scalafmt := false\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/project/build.properties",
"chars": 20,
"preview": "sbt.version=0.13.16\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/project/build.sbt",
"chars": 77,
"preview": "addSbtPlugin(\"com.lucidchart\" % \"sbt-scalafmt\" % sys.props(\"plugin.version\"))"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/src/main/scala/Main.scala",
"chars": 49,
"preview": "object Main extends App {\n println( \"hello\" )\n}\n"
},
{
"path": "sbt-scalafmt/src/sbt-test/sbt-scalafmt/simple/test",
"chars": 46,
"preview": "-> scalafmt::test\n> scalafmt\n> scalafmt::test\n"
},
{
"path": "sbt-scalafmt-coursier/build.sbt",
"chars": 219,
"preview": "description := \"Replaces ivy2 resolution for sbt-scalafmt with coursier\"\n\nlibraryDependencies ++= Seq(\n \"io.get-coursie"
},
{
"path": "sbt-scalafmt-coursier/src/main/scala/com/lucidchart/scalafmt/coursier/ScalafmtCoursierPlugin.scala",
"chars": 2704,
"preview": "package com.lucidchart.scalafmt.coursier\n\nimport com.lucidchart.sbt.scalafmt.ScalafmtCorePlugin\nimport com.lucidchart.sb"
},
{
"path": "scalafmt-api/build.sbt",
"chars": 125,
"preview": "disablePlugins(ScalafmtCorePlugin)\n\nautoScalaLibrary := false\n\ncrossPaths := false\n\ndescription := \"Bridge for scalafmt "
},
{
"path": "scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/Dialect.java",
"chars": 81,
"preview": "package com.lucidchart.scalafmt.api;\n\npublic enum Dialect {\n SCALA,\n SBT\n}\n"
},
{
"path": "scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/ScalafmtFactory.java",
"chars": 126,
"preview": "package com.lucidchart.scalafmt.api;\n\npublic interface ScalafmtFactory {\n\n Scalafmtter fromConfig(String configString"
},
{
"path": "scalafmt-api/src/main/java/com/lucidchart/scalafmt/api/Scalafmtter.java",
"chars": 231,
"preview": "package com.lucidchart.scalafmt.api;\n\nimport java.nio.file.Path;\nimport java.util.function.Function;\n\npublic interface S"
},
{
"path": "scalafmt-impl/build.sbt",
"chars": 408,
"preview": "disablePlugins(ScalafmtCorePlugin)\n\ndescription := \"Implementation for scalafmt-api\"\n\ndef scalafmtOrg(scalafmtVersion: S"
},
{
"path": "scalafmt-impl/src/scalafmt-1.5/main/scala/com/lucidchart/scalafmt/impl/ScalafmtConfigUtil.scala",
"chars": 278,
"preview": "package com.lucidchart.scalafmt.impl\n\nimport org.scalafmt.Scalafmt\nimport org.scalafmt.config.ScalafmtConfig\nimport scal"
},
{
"path": "scalafmt-impl/src/scalafmt-1.5/main/scala/com/lucidchart/scalafmt/impl/ScalafmtFactory.scala",
"chars": 336,
"preview": "package com.lucidchart.scalafmt.impl\n\nimport com.lucidchart.scalafmt.api\nimport java.util.function\nimport org.scalafmt.c"
},
{
"path": "scalafmt-impl/src/scalafmt-1.5/main/scala/com/lucidchart/scalafmt/impl/ScalametaUtil.scala",
"chars": 189,
"preview": "package com.lucidchart.scalafmt.impl\n\nimport scala.meta.internal.tokenizers.PlatformTokenizerCache\n\nobject ScalametaUtil"
},
{
"path": "scalafmt-impl/src/scalafmt-2.0/main/scala/com/lucidchart/scalafmt/impl/ScalafmtConfigUtil.scala",
"chars": 277,
"preview": "package com.lucidchart.scalafmt.impl\n\nimport org.scalafmt.Scalafmt\nimport org.scalafmt.config.ScalafmtConfig\nimport scal"
},
{
"path": "scalafmt-impl/src/scalafmt-2.0/main/scala/com/lucidchart/scalafmt/impl/ScalafmtFactory.scala",
"chars": 336,
"preview": "package com.lucidchart.scalafmt.impl\n\nimport com.lucidchart.scalafmt.api\nimport java.util.function\nimport org.scalafmt.c"
},
{
"path": "scalafmt-impl/src/scalafmt-2.0/main/scala/com/lucidchart/scalafmt/impl/ScalametaUtil.scala",
"chars": 189,
"preview": "package com.lucidchart.scalafmt.impl\n\nimport scala.meta.internal.tokenizers.PlatformTokenizerCache\n\nobject ScalametaUtil"
},
{
"path": "scalafmt-impl/src/shared/main/scala/com/lucidchart/scalafmt/impl/Scalafmtter.scala",
"chars": 892,
"preview": "package com.lucidchart.scalafmt.impl\n\nimport com.lucidchart.scalafmt.api\nimport com.lucidchart.scalafmt.api.Dialect\nimpo"
}
]
About this extraction
This page contains the full source code of the lucidsoftware/neo-sbt-scalafmt GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 44 files (47.4 KB), approximately 14.1k tokens, and a symbol index with 6 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.