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