Skip to content

Commit

Permalink
Merge pull request #243 from godenji/0.2.0
Browse files Browse the repository at this point in the history
0.2.0
  • Loading branch information
godenji authored Jul 11, 2017
2 parents f53978c + 60d0d98 commit 8380d17
Show file tree
Hide file tree
Showing 29 changed files with 232 additions and 115 deletions.
40 changes: 19 additions & 21 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ sbt will build one jar with all the dependencies and put it in ::

You can copy this to a location in your path and execute it as follows: ::

java -jar /home/me/bin/cli-assembly-$scalariform_version.jar -f -q +compactControlReadability +alignParameters +alignSingleLineCaseStatements +doubleIndentClassDeclaration +rewriteArrowSymbols +preserveSpaceBeforeArguments --stdout ~/myproject/src/main/scala/Stuff.scala > Stuff.scala
java -jar /home/me/bin/cli-assembly-$scalariform_version.jar -f -q +compactControlReadability +alignParameters +alignSingleLineCaseStatements +doubleIndentConstructorArguments +rewriteArrowSymbols +preserveSpaceBeforeArguments --stdout ~/myproject/src/main/scala/Stuff.scala > Stuff.scala

Integration with sbt
--------------------
Expand All @@ -52,7 +52,7 @@ Usage within a project

Have a use for the scalariform source code directly? You can use it as a build dependency: ::

"org.scalariform" %% "scalariform" % "0.1.8"
"org.scalariform" %% "scalariform" % "0.2.0"

Integration with Eclipse
------------------------
Expand Down Expand Up @@ -155,8 +155,8 @@ While there is no specific Vim integration at present, you can use
Scalariform as an external formatter for the ``gg=G`` command by adding
the following to ``.vimrc`` ::
au BufEnter *.scala setl formatprg=java\ -jar\ /home/me/bin/scalariform.jar\ -f\ -q\ +compactControlReadability\ +alignParameters\ +alignSingleLineCaseStatements\ +doubleIndentClassDeclaration\ +rewriteArrowSymbols\ +preserveSpaceBeforeArguments\ --stdin\ --stdout
au BufEnter *.scala setl equalprg=java\ -jar\ /home/me/bin/scalariform.jar\ -f\ -q\ +compactControlReadability\ +alignParameters\ +alignSingleLineCaseStatements\ +doubleIndentClassDeclaration\ +rewriteArrowSymbols\ +preserveSpaceBeforeArguments\ --stdin\ --stdout
au BufEnter *.scala setl formatprg=java\ -jar\ /home/me/bin/scalariform.jar\ -f\ -q\ +compactControlReadability\ +alignParameters\ +alignSingleLineCaseStatements\ +doubleIndentConstructorArguments\ +rewriteArrowSymbols\ +preserveSpaceBeforeArguments\ --stdin\ --stdout
au BufEnter *.scala setl equalprg=java\ -jar\ /home/me/bin/scalariform.jar\ -f\ -q\ +compactControlReadability\ +alignParameters\ +alignSingleLineCaseStatements\ +doubleIndentConstructorArguments\ +rewriteArrowSymbols\ +preserveSpaceBeforeArguments\ --stdin\ --stdout


You can create your own executable scalariform.jar by following the instructions at the top of this file, in "Packaging an executable JAR."
Expand Down Expand Up @@ -450,32 +450,30 @@ invoked using infix notation with spaces separated the target".

.. _recommends: http://docs.scala-lang.org/style/method-invocation.html#symbolic-methodsoperators

doubleIndentClassDeclaration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
doubleIndentConstructorArguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Default: ``false``

With this set to ``true``, class (and trait / object) declarations
will be formatted as recommended_ by the Scala Style Guide. That is,
if the declaration section spans multiple lines, it will be formatted
so that either the parameter section or the inheritance section is
doubly indented. This provides a visual distinction from the members
of the class. For example:
so that the parameter section is doubly indented. This provides a visual
distinction between the constructor arguments & the extensions. For example:

.. code:: scala
class Person(
name: String,
age: Int,
birthdate: Date,
astrologicalSign: String,
shoeSize: Int,
favoriteColor: java.awt.Color)
extends Entity
with Logging
with Identifiable
with Serializable {
def firstMethod = ...
name: String,
age: Int,
birthdate: Date,
astrologicalSign: String,
shoeSize: Int,
favoriteColor: java.awt.Color)
extends Entity
with Logging
with Identifiable
with Serializable {
}
Or:
Expand Down Expand Up @@ -836,7 +834,7 @@ Preference Value Default?
=========================================== ========= =========
alignParameters ``false``
compactStringConcatenation ``false``
doubleIndentClassDeclaration ``true`` No
doubleIndentConstructorArguments ``true`` No
indentSpaces ``2``
placeScaladocAsterisksBeneathSecondAsterisk ``true`` No
preserveSpaceBeforeArguments ``false``
Expand Down
20 changes: 16 additions & 4 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ lazy val commonSettings = inConfig(Test)(Defaults.testSettings) ++
sonatypeProfileName := organization.value,
scalaVersion := crossScalaVersions.value.head,
crossScalaVersions := Seq(
"2.11.8",
"2.12.2",
"2.11.11",
"2.10.6"
),
exportJars := true, // Needed for cli oneJar
scalacOptions ++= (CrossVersion.partialVersion(scalaVersion.value) match {
case Some((2, 12)) => Seq(
"-Xlint:-unused,_", "-Ywarn-unused:imports",
"-language:postfixOps", "-language:implicitConversions",
"-deprecation", "-feature"
)
case Some((2, major)) if major >= 11 =>
scalac2_10Options ++ scalac2_11Options
case _ =>
Expand Down Expand Up @@ -68,8 +74,8 @@ lazy val subprojectSettings = commonSettings :+ (
def scala2_11Dependencies = Def.setting {
CrossVersion.partialVersion(scalaVersion.value) match {
case Some((2, major)) if major >= 11 => Seq(
"org.scala-lang.modules" %% "scala-xml" % "1.0.5",
"org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.4"
"org.scala-lang.modules" %% "scala-xml" % "1.0.6",
"org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.6"
)
case _ => Nil
}
Expand All @@ -81,7 +87,7 @@ lazy val scalariform = (project
settings(publishSettings("scalariform"))
settings(
libraryDependencies ++= scala2_11Dependencies.value,
libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.6" % "test",
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test",
// sbt doesn't automatically load the content of the MANIFST.MF file, therefore
// we have to do it here by ourselves Furthermore, the version format in the
// MANIFEST.MF is `x.y.z.qualifier` but we need to replace the `qualifier` part
Expand Down Expand Up @@ -123,6 +129,7 @@ lazy val cli = (project
)

lazy val root = (project in file(".")
settings(publishSettings("root"))
settings(commonSettings)
aggregate(scalariform, cli)
)
Expand Down Expand Up @@ -157,4 +164,9 @@ def pomExtraXml =
<name>Daniel Trinh</name>
<url>https://github.com/daniel-trinh/</url>
</developer>
<developer>
<id>machaval</id>
<name>Mariano de Achaval</name>
<url>https://github.com/machaval/</url>
</developer>
</developers>
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package scalariform.commandline

import java.io.File
import java.util.{ ArrayList, Collection }
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._

import org.apache.commons.io._
import org.apache.commons.io.filefilter._
Expand All @@ -14,7 +14,7 @@ object ScalaFileWalker extends DirectoryWalker(TrueFileFilter.INSTANCE, FileFilt
def findScalaFiles(path: File): List[File] = {
val results = new ArrayList[File]
walk(path, results)
results.toList
results.asScala.toList
}

override protected def handleFile(file: File, depth: Int, results: Collection[_]) {
Expand Down
2 changes: 1 addition & 1 deletion formatterPreferences.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ compactStringConcatenation=false
indentPackageBlocks=true
formatXml=true
preserveSpaceBeforeArguments=false
doubleIndentClassDeclaration=false
doubleIndentConstructorArguments=false
doubleIndentMethodDeclaration=false
rewriteArrowSymbols=false
alignSingleLineCaseStatements=true
Expand Down
2 changes: 1 addition & 1 deletion project/build.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
sbt.version=0.13.11
sbt.version=0.13.15
2 changes: 1 addition & 1 deletion project/plugins.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.6.1")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "1.1")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ trait ExprFormatter { self: HasFormattingPreferences with AnnotationFormatter wi
for ((previousElementOption, element, nextElementOption) Utils.withPreviousAndNext(exprElements)) {
previousElementOption match {
case Some(previousElement)
val instructionOption = condOpt(previousElement, element) {
val instructionOption = condOpt((previousElement, element)) {
case (PrefixExprElement(_), _) if (Chars.isOperatorPart(element.firstToken.text(0))) CompactEnsuringGap else Compact
case (Argument(_), _) Compact
case (_, _: ArgumentExprs) if formattingPreferences(PreserveSpaceBeforeArguments) CompactPreservingGap // TODO: Probably not needed now with CallExpr
Expand Down
12 changes: 8 additions & 4 deletions scalariform/src/main/scala/scalariform/formatter/ScalaFormatter.scala
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,14 @@ abstract class ScalaFormatter extends HasFormattingPreferences with TypeFormatte
val commentIndentLevel = if (nextTokenUnindents) indentLevel + 1 else indentLevel
for ((previousOpt, hiddenToken, nextOpt) Utils.withPreviousAndNext(hiddenTokens)) {
hiddenToken match {
case ScalaDocComment(_)
builder.ensureAtBeginningOfLine()
builder.indent(commentIndentLevel, baseIndentOption)
builder.append(formatScaladocComment(hiddenToken, commentIndentLevel))
case ScalaDocComment(token)
if (token.rawText.startsWith("/***")) {
builder.append(token.rawText)
} else {
builder.ensureAtBeginningOfLine()
builder.indent(commentIndentLevel, baseIndentOption)
builder.append(formatScaladocComment(hiddenToken, commentIndentLevel))
}
case SingleLineComment(_) | MultiLineComment(_)
if (builder.atBeginningOfLine)
builder.indent(commentIndentLevel, baseIndentOption)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ trait TemplateFormatter { self: HasFormattingPreferences with AnnotationFormatte
} {
if (annotations.size > 0)
formatResult = formatResult.formatNewlineOrOrdinary(firstToken, CompactEnsuringGap)
val doubleIndentParams = formattingPreferences(DoubleIndentClassDeclaration) &&
!templateInheritanceSectionOpt.exists { section containsNewline(section) || hiddenPredecessors(section.firstToken).containsNewline } &&
templateBodyOption.exists(containsNewline(_))
val doubleIndentParams = (formattingPreferences(DoubleIndentConstructorArguments) &&
!templateInheritanceSectionOpt.exists { section
containsNewline(section) || hiddenPredecessors(section.firstToken).containsNewline
} &&
templateBodyOption.exists(containsNewline(_))) || formattingPreferences(DoubleIndentConstructorArguments)
formatResult ++= formatParamClauses(paramClauses, doubleIndentParams)
}
for (TemplateInheritanceSection(extendsOrSubtype, earlyDefsOpt, templateParentsOpt) templateInheritanceSectionOpt) {
val doubleIndentTemplateInheritance = formattingPreferences(DoubleIndentClassDeclaration) &&
val doubleIndentTemplateInheritance = !formattingPreferences(DoubleIndentConstructorArguments) &&
(templateBodyOption.exists(containsNewline(_)) || paramClausesOpt.exists(containsNewline(_)))
val inheritanceIndent = if (doubleIndentTemplateInheritance) 2 else 1
var currentFormatterState = formatterState
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ object AllPreferences {
val preferences: List[PreferenceDescriptor[_]] = List(
RewriteArrowSymbols, IndentSpaces, SpaceBeforeColon, SpaceBeforeContextColon, CompactStringConcatenation,
PreserveSpaceBeforeArguments, AlignParameters, FirstParameterOnNewline, AlignArguments, FirstArgumentOnNewline,
DoubleIndentClassDeclaration, FormatXml, IndentPackageBlocks, AlignSingleLineCaseStatements,
AlignSingleLineCaseStatements.MaxArrowIndent, IndentLocalDefs, PreserveDanglingCloseParenthesis, DanglingCloseParenthesis,
DoubleIndentConstructorArguments, FormatXml, IndentPackageBlocks, AlignSingleLineCaseStatements,
AlignSingleLineCaseStatements.MaxArrowIndent, IndentLocalDefs, DanglingCloseParenthesis,
SpaceInsideParentheses, SpaceInsideBrackets, SpacesWithinPatternBinders, MultilineScaladocCommentsStartOnFirstLine, IndentWithTabs,
CompactControlReadability, PlaceScaladocAsterisksBeneathSecondAsterisk, DoubleIndentMethodDeclaration, SpacesAroundMultiImports,
NewlineAtEndOfFile
Expand Down Expand Up @@ -166,9 +166,9 @@ case object FirstArgumentOnNewline extends IntentPreferenceDescriptor {
val defaultValue = Force
}

case object DoubleIndentClassDeclaration extends BooleanPreferenceDescriptor {
val key = "doubleIndentClassDeclaration"
val description = "Double indent either a class's parameters or its inheritance list"
case object DoubleIndentConstructorArguments extends BooleanPreferenceDescriptor {
val key = "doubleIndentConstructorArguments"
val description = "Class (and trait / object) declarations will be formatted as recommended by the Scala Style Guide"
val defaultValue = false
}

Expand Down Expand Up @@ -210,13 +210,6 @@ case object IndentLocalDefs extends BooleanPreferenceDescriptor {
val defaultValue = false
}

@deprecated("This has been dropped in favor of DanglingCloseParenthesis.", since = "0.1.5")
case object PreserveDanglingCloseParenthesis extends BooleanPreferenceDescriptor {
val key = "preserveDanglingCloseParenthesis"
val description = "Allow a newline before a ')' in an argument expression"
val defaultValue = false
}

case object DanglingCloseParenthesis extends IntentPreferenceDescriptor {
val key = "danglingCloseParenthesis"
val description = "Put a newline before a ')' in an argument expression"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package scalariform.formatter.preferences

import java.util.Properties
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scalariform.utils.Utils._
import java.io.IOException

Expand All @@ -22,7 +22,7 @@ object PreferencesImporterExporter {
}

for {
key @ (dummy: String) properties.propertyNames
key @ (dummy: String) properties.propertyNames.asScala
descriptor AllPreferences.preferencesByKey.get(key)
valueString = properties.getProperty(key)
} setPreference(descriptor, valueString)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ private[lexer] trait ScalaOnlyLexer { self: ScalaLexer ⇒
case '\''
nextChar()
if (isIdentifierStart(ch))
charLitOr(getIdentRest)
charLitOr(() => getIdentRest)
else if (isOperatorPart(ch) && (ch != '\\'))
charLitOr(getOperatorRest)
charLitOr(() => getOperatorRest)
else {
getLitChar()
if (ch == '\'' || forgiveErrors) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1461,6 +1461,8 @@ class InferredSemicolonScalaParser(tokens: Array[Token]) {
nextToken()
case LBRACE
xmlEmbeddedScala(isPattern)
case _
throw new ScalaParserException("Expected XML attribute name or left brace: " + currentToken)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1810,6 +1810,8 @@ class ScalaParser(tokens: Array[Token]) {
Left(nextToken())
case LBRACE
Right(xmlEmbeddedScala(isPattern))
case _
throw new ScalaParserException("Expected XML attribute name or left brace: " + currentToken)
}
XmlAttribute(name, whitespaceOption, equals, whitespaceOption2, valueOrEmbeddedScala)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package scalariform.astselect

import org.scalatest._
import org.scalatest.matchers._
import scalariform.utils.Range
import scalariform.ScalaVersions

// format: OFF
class AstSelectorTest extends FlatSpec with ShouldMatchers {
class AstSelectorTest extends FlatSpec with Matchers {

// Legend:
//
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package scalariform.formatter

import org.scalatest.exceptions.{TestFailedException, TestPendingException}

import scalariform.lexer._
import scalariform.formatter.preferences._
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.TestFailedException
import org.scalatest.TestPendingException
import org.scalatest.{FlatSpec, Matchers}

import scalariform.ScalaVersions

abstract class AbstractFormatterTest extends FlatSpec with ShouldMatchers with SpecificFormatter {
abstract class AbstractFormatterTest extends FlatSpec with Matchers with SpecificFormatter {

def prettyPrint(s: String): String =
//s.replaceAll("\n", "↵\n").replaceAll("\t", "↦" ).replaceAll(" ", "▵")
Expand Down
23 changes: 23 additions & 0 deletions scalariform/src/test/scala/scalariform/formatter/CommentFormatterTest.scala
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -262,4 +262,27 @@ class CommentFormatterTest extends AbstractFormatterTest {
| */
|"""
}

{
"""object Main {
|/***
|scalaVersion := "ololo"
|
|libraryDependencies ++= Seq(
| "net.databinder" % "dispatch-twitter_2.9.0-1" % "0.8.3",
| "net.databinder" % "dispatch-http_2.9.0-1" % "0.8.3"
|)
|*/
|}""" ==>
"""object Main {
|/***
|scalaVersion := "ololo"
|
|libraryDependencies ++= Seq(
| "net.databinder" % "dispatch-twitter_2.9.0-1" % "0.8.3",
| "net.databinder" % "dispatch-http_2.9.0-1" % "0.8.3"
|)
|*/
|}"""
}
}
Loading

0 comments on commit 8380d17

Please sign in to comment.