Skip to content

Commit

Permalink
Add option to specify custom location of .scalafmt.conf for fmt command.
Browse files Browse the repository at this point in the history
  • Loading branch information
wleczny committed Aug 2, 2022
1 parent 5df5f47 commit 7ea4544
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ final case class FmtOptions(
scalafmtArg: List[String] = Nil,

@Group("Format")
@HelpMessage("Custom path to the scalafmt configuration file.")
@Name("scalafmtConfig")
scalafmtConf: Option[String] = None,
@Group("Format")
@HelpMessage("Pass a global dialect for scalafmt. This overrides whatever value is configured in the .scalafmt.conf file.")
@Name("dialect")
scalafmtDialect: Option[String] = None,
Expand Down
7 changes: 4 additions & 3 deletions modules/cli/src/main/scala/scala/cli/commands/Fmt.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,10 @@ object Fmt extends ScalaCommand[FmtOptions] {
(s, i.workspace, Some(i))
}
CurrentParams.workspaceOpt = Some(workspace)
val (versionMaybe, dialectMaybe, pathMaybe) = readVersionAndDialectFromFile(workspace, logger)
val cache = options.shared.buildOptions().archiveCache
val buildOptions = options.buildOptions
val (versionMaybe, dialectMaybe, pathMaybe) =
readVersionAndDialectFromFile(workspace, options.scalafmtConf, logger)
val cache = options.shared.buildOptions().archiveCache
val buildOptions = options.buildOptions

if (sourceFiles.isEmpty)
logger.debug("No source files, not formatting anything")
Expand Down
29 changes: 19 additions & 10 deletions modules/cli/src/main/scala/scala/cli/commands/util/FmtUtil.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ object FmtUtil {
*/
def readVersionAndDialectFromFile(
workspace: os.Path,
customConfPath: Option[String],
logger: Logger
): (Option[String], Option[String], Option[os.Path]) = {
case class RunnerMetaconfig(dialect: String = "")
Expand All @@ -58,17 +59,25 @@ object FmtUtil {
}

val confName = ".scalafmt.conf"
val pathMaybe = {
logger.debug(s"Checking for $confName in cwd.")
val confInCwd = workspace / confName
if (os.exists(confInCwd)) Some(confInCwd)
else {
logger.debug(s"Checking for $confName in git root.")
val gitRootMaybe = getGitRoot(workspace, logger)
val confInGitRootMaybe = gitRootMaybe.map(os.Path(_) / confName)
confInGitRootMaybe.find(os.exists(_))
val pathMaybe =
customConfPath.flatMap { p =>
val confPath = os.Path(p, os.pwd)
logger.debug(s"Checking for $confPath.")
if (os.exists(confPath)) Some(confPath)
else
logger.message(s"WARNING: provided file doesn't exist $confPath")
None
}.orElse {
logger.debug(s"Checking for $confName in cwd.")
val confInCwd = workspace / confName
if (os.exists(confInCwd)) Some(confInCwd)
else {
logger.debug(s"Checking for $confName in git root.")
val gitRootMaybe = getGitRoot(workspace, logger)
val confInGitRootMaybe = gitRootMaybe.map(os.Path(_) / confName)
confInGitRootMaybe.find(os.exists(_))
}
}
}

val confContentMaybe = pathMaybe.flatMap { path =>
val either = metaconfig.Hocon.parseInput[ScalafmtMetaconfig](
Expand Down
4 changes: 2 additions & 2 deletions modules/cli/src/test/scala/cli/tests/ScalafmtTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ class ScalafmtTests extends munit.FunSuite {
os.write(confFilePath, confFile)

val readVersionAndDialect =
FmtUtil.readVersionAndDialectFromFile(workspace = dirPath, TestLogger())
FmtUtil.readVersionAndDialectFromFile(workspace = dirPath, None, TestLogger())
expect(readVersionAndDialect == (Some("3.1.2"), Some("scala213"), Some(confFilePath)))
}
}

test("readVersionFromFile with missing .scalafmt.conf file") {
TestInputs.withTmpDir("temp-dir") { dirPath =>
val readVersionAndDialect =
FmtUtil.readVersionAndDialectFromFile(workspace = dirPath, TestLogger())
FmtUtil.readVersionAndDialectFromFile(workspace = dirPath, None, TestLogger())
expect(readVersionAndDialect == (None, None, None))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ class FmtTests extends ScalaCliSuite {
)
)

// val simpleInputsWithCustomConfLocation: TestInputs = TestInputs(
// Seq(
// os.rel / "custom-dir" / "custom.conf" ->
// s"""|version = "3.5.5"
// |runner.dialect = scala213
// |""".stripMargin,
// os.rel / "Foo.scala" -> simpleInputsUnformattedContent
// )
// )

private def noCrLf(input: String): String =
input.replaceAll("\r\n", "\n")

Expand Down Expand Up @@ -147,6 +157,21 @@ class FmtTests extends ScalaCliSuite {
}
}

// test("--scalafmt-conf") {
// simpleInputsWithCustomConfLocation.fromRoot { root =>
// os.proc(TestUtil.cli, "fmt", ".", "--scalafmt-conf", "custom-dir/custom.conf").call(cwd =
// root
// )
// val confLines = os.read.lines(root / Constants.workspaceDirName / confFileName)
// val versionInConf = confLines(0).stripPrefix("version = ").trim
// val dialectInConf = confLines(1).stripPrefix("runner.dialect = ").trim
// val updatedContent = noCrLf(os.read(root / "Foo.scala"))
// expect(versionInConf == "\"3.5.5\"")
// expect(dialectInConf == "scala213")
// expect(updatedContent == expectedSimpleInputsFormattedContent)
// }
// }

test("creating workspace conf file") {
simpleInputsWithDialectOnly.fromRoot { root =>
val workspaceConfPath = root / Constants.workspaceDirName / confFileName
Expand Down
2 changes: 1 addition & 1 deletion website/docs/commands/fmt.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ scala-cli fmt . --check --respect-project-filters=false

The Scala CLI `fmt` command runs `scalafmt` under the hood, which *normally* requires `.scalafmt.conf` configuration file with explicitly specified **version** and **dialect** fields. The way it is handled by Scala CLI is as follows:

At the beginning `fmt` looks for existing `.scalafmt.conf` file inside **current workspace** directory and if it doesn't find it - inside **git root** directory. There are 3 possible cases:
At the beginning `fmt` looks for the configuration inside the file specified in the `--scalafmt-conf` option. If the option is not passed or the file doesn't exist, `fmt` looks for the existing configuration file inside **current workspace** directory. If the file is still not found, `fmt` looks for it inside **git root** directory. There are 3 possible cases:

1. Configuration file with the specified version and dialect is found.
2. Configuration file is found, but it doesn't have specified version or dialect.
Expand Down
6 changes: 6 additions & 0 deletions website/docs/reference/cli-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,12 @@ Show help for scalafmt. This is an alias for --scalafmt-arg -help

Aliases: `-F`

#### `--scalafmt-conf`

Aliases: `--scalafmt-config`

Custom path to the scalafmt configuration file.

#### `--scalafmt-dialect`

Aliases: `--dialect`
Expand Down

0 comments on commit 7ea4544

Please sign in to comment.