Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/liancheng/scalafix-organize-imports
A CI-friendly Scalafix semantic rule for organizing imports
https://github.com/liancheng/scalafix-organize-imports
scala scalafix scalafix-plugin
Last synced: about 2 months ago
JSON representation
A CI-friendly Scalafix semantic rule for organizing imports
- Host: GitHub
- URL: https://github.com/liancheng/scalafix-organize-imports
- Owner: liancheng
- License: mit
- Archived: true
- Created: 2020-04-06T21:11:47.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2023-07-14T15:46:42.000Z (over 1 year ago)
- Last Synced: 2024-08-03T01:39:18.210Z (5 months ago)
- Topics: scala, scalafix, scalafix-plugin
- Language: Scala
- Homepage:
- Size: 461 KB
- Stars: 193
- Watchers: 10
- Forks: 22
- Open Issues: 22
-
Metadata Files:
- Readme: README.adoc
- License: LICENSE
Awesome Lists containing this project
README
:latest-release: 0.6.0
ifdef::env-github[]
:caution-caption: :construction:
:important-caption: :exclamation:
:warning-caption: :warning:
:tip-caption: :bulb:
:note-caption: :notebook:
endif::[]IMPORTANT: This rule is included in Scalafix as https://github.com/scalacenter/scalafix/blob/v0.11.0/docs/rules/OrganizeImports.md[a built-in rule] since https://github.com/scalacenter/scalafix/releases/tag/v0.11.0[Scalafix v0.11.0]. Please refer to the https://github.com/scalacenter/scalafix/[Scalafix GitHub repository] for bug reports and feature requests.
= OrganizeImports
:icons: font
:sectnums:
:toc-placement!:
:toc-title:
:toc:
:toclevels: 2image:https://github.com/liancheng/scalafix-organize-imports/workflows/CI/badge.svg[]
https://github.com/liancheng/scalafix-organize-imports/releases/latest[image:https://img.shields.io/github/v/tag/liancheng/scalafix-organize-imports[]]
https://github.com/liancheng/scalafix-organize-imports/blob/master/LICENSE[image:https://img.shields.io/github/license/liancheng/scalafix-organize-imports[]]
https://scala-steward.org[image:https://img.shields.io/badge/Scala_Steward-helping-blue.svg[]]
https://codecov.io/gh/liancheng/scalafix-organize-imports[image:https://img.shields.io/codecov/c/github/liancheng/scalafix-organize-imports[]]toc::[]
`OrganizeImports` is a CI-friendly https://scalacenter.github.io/scalafix[Scalafix] semantic rule that helps you organize Scala import statements.
https://scalameta.org/metals/[Metals], the Scala language server, also uses `OrganizeImports` to power its "organize imports" code action starting from version https://scalameta.org/metals/blog/2020/11/10/lithium.html#organize-imports-code-action[v0.9.5].
image:https://i.imgur.com/8YBdjjC.gif[]
== Getting started
=== sbt
Please refer to https://scalacenter.github.io/scalafix/docs/users/installation.html[the Scalafix documentation] for how to install Scalafix and invoking it in your sbt build.
To try this rule in the sbt console without adding this rule to your sbt build:
[source,subs="attributes+"]
----
sbt> scalafix dependency:[email protected]:organize-imports:{latest-release}
----To include this rule in your sbt build:
[source,scala,subs="attributes+"]
----
ThisBuild / scalafixDependencies += "com.github.liancheng" %% "organize-imports" % "{latest-release}"
----=== Mill
You can also include this rule in your http://www.lihaoyi.com/mill/[Mill] build using https://github.com/joan38/mill-scalafix[mill-scalafix]:
[source,scala,subs="attributes+"]
----
def scalafixIvyDeps = Agg(ivy"com.github.liancheng::organize-imports:{latest-release}")
----=== For IntelliJ Scala plugin users
`OrganizeImports` allows you to specify a preset style via the <>. To make it easier to add `OrganizeImports` into existing Scala projects built using the IntelliJ Scala plugin, `OrganizeImports` provides a preset style compatible with the default configuration of the IntelliJ Scala import optimizer. Please check the <> preset style for more details.
=== Source formatting tools
The `OrganizeImports` rule respects source-formatting tools like https://scalameta.org/scalafmt/[Scalafmt]. If an import statement is already organized according to the configuration, its original source level format is preserved. Therefore, in an sbt project, if you run the following command sequence:
[source]
----
sbt> scalafixAll
...
sbt> scalafmtAll
...
sbt> scalafixAll --check
...
----Assuming that the first two commands run successfully, the last `scalafixAll --check` command should not fail even if some import statements are reformatted by the `scalafmtAll` command.
However, you should make sure that the source-formatting tools you use do not rewrite import statements in ways that conflict with `OrganizeImports`. For example, when using Scalafmt together with `OrganizeImports`, the `ExpandImportSelectors`, `SortImports`, and `AsciiSortImports` rewriting rules should not be used.
=== Scala 3
Available since v0.6.0.
Running the rule on source files compiled with Scala 3 is still experimental.
Known limitations:
. You must use Scalafix 0.9.28 or later
. The <> option must be explicitly set to `false` - the rule currently doesn't remove unused imports as it's currently not supported by the compiler.
. Usage of http://dotty.epfl.ch/docs/reference/dropped-features/package-objects.html[deprecated package objects] may result in incorrect imports
. The <> option has no effect== Configuration
=== Default Configuration values
[source,hocon,subs=+macros]
----
OrganizeImports {
<> = Auto
<> = null
<> = false
<> = false
<> = Explode
<> = [
"*"
"re:(javax?|scala)\\."
]
<> = Ascii
<> = Ascii
<> = DEFAULT
<> = true
}
----[[remove-unused-warning]]
[WARNING]
====
Please do NOT use the Scalafix built-in https://scalacenter.github.io/scalafix/docs/rules/RemoveUnused.html[`RemoveUnused.imports`] together with `OrganizeImports` to remove unused imports. You may end up with broken code! It is still safe to use `RemoveUnused` to remove unused private members or local definitions, though.Scalafix rewrites source files by applying patches generated by invoked rules. Each rule generates a patch based on the _original_ text of the source files. When two patches generated by different rules conflict with each other, Scalafix is not able to reconcile the conflicts, and may produce broken code. It is very likely to happen when `RemoveUnused` and `OrganizeImports` are used together, since both rules rewrite import statements.
By default, `OrganizeImports` already removes unused imports for you (see the <> option). It locates unused imports via compilation diagnostics, which is exactly how `RemoveUnused` does it. This mechanism works well in most cases, unless there are new unused imports generated while organizing imports, which is possible when the <> option is set to true. For now, the only reliable workaround for this edge case is to run Scalafix with `OrganizeImports` twice.
====[[blankLines]]
=== `blankLines`Available since v0.5.0-alpha.1.
Configures whether blank lines between adjacent import groups are automatically or manually inserted. This option is used together with the <>.
==== Value type
Enum: `Auto | Manual`
Auto:: A blank line is automatically inserted between adjacent import groups. All blank line markers (`---`) configured in the <> are ignored.
Manual:: A blank line is inserted at all the positions where blank line markers appear in the <>.
The following two configurations are equivalent:
[source,hocon]
----
OrganizeImports {
blankLines = Auto
groups = [
"re:javax?\\."
"scala."
"*"
]
}OrganizeImports {
blankLines = Manual
groups = [
"re:javax?\\."
"---"
"scala."
"---"
"*"
]
}
----==== Default value
`Auto`
==== Examples
`Auto`::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
blankLines = Auto
groups = [
"re:javax?\\."
"scala."
"*"
]
}
----Before:
[source,scala]
----
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import javax.annotation.Generated
import scala.concurrent.ExecutionContext
----After:
[source,scala]
----
import java.time.Clock
import javax.annotation.Generatedimport scala.collection.JavaConverters._
import scala.concurrent.ExecutionContextimport sun.misc.BASE64Encoder
----
--`Manual`::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
blankLines = Manual
groups = [
"re:javax?\\."
"scala."
"---"
"*"
]
}
----Before:
[source,scala]
----
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import javax.annotation.Generated
import scala.concurrent.ExecutionContext
----After:
[source,scala]
----
import java.time.Clock
import javax.annotation.Generated
import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContextimport sun.misc.BASE64Encoder
----
--[[coalesceToWildcardImportThreshold]]
=== `coalesceToWildcardImportThreshold`When the number of imported names exceeds a certain threshold, coalesce them into a wildcard import. Renames and unimports are left untouched.
[CAUTION]
====
Having this feature in `OrganizeImports` is mostly for feature parity with the IntelliJ IDEA Scala import optimizer, but coalescing grouped import selectors into a wildcard import may introduce _compilation errors_!Here is an example to illustrate the risk. The following snippet compiles successfully:
[source,scala]
----
import scala.collection.immutable._
import scala.collection.mutable.{ArrayBuffer, Map, Set}object Example {
val m: Map[Int, Int] = ???
}
----
The type of `Example.m` above is not ambiguous because the mutable `Map` explicitly imported in the second import takes higher precedence than the immutable `Map` imported via wildcard in the first import.However, if we coalesce the grouped imports in the second import statement into a wildcard, there will be a compilation error:
[source,scala]
----
import scala.collection.immutable._
import scala.collection.mutable._object Example {
val m: Map[Int, Int] = ???
}
----
This is because the type of `Example.m` becomes ambiguous now since both the mutable and immutable `Map` are imported via a wildcard and have the same precedence.
======== Value type
Integer. Not setting it or setting it to `null` disables this feature.
==== Default value
`null`
==== Examples
Configuration:
[source,scala]
----
OrganizeImports {
groupedImports = Keep
coalesceToWildcardImportThreshold = 3
}
----Before:
[source,scala]
----
import scala.collection.immutable.{Seq, Map, Vector, Set}
import scala.collection.immutable.{Seq, Map, Vector}
import scala.collection.immutable.{Seq, Map, Vector => Vec, Set, Stream}
import scala.collection.immutable.{Seq, Map, Vector => _, Set, Stream}
----After:
[source,scala]
----
import scala.collection.immutable._
import scala.collection.immutable.{Map, Seq, Vector}
import scala.collection.immutable.{Vector => Vec, _}
import scala.collection.immutable.{Vector => _, _}
----[[expandRelative]]
=== `expandRelative`Expand relative imports into fully-qualified one.
[CAUTION]
====
Expanding relative imports may introduce new unused imports. For instance, relative imports in the following snippet[source,scala]
----
import scala.util
import util.control
import control.NonFatal
----are expanded into
[source,scala]
----
import scala.util
import scala.util.control
import scala.util.control.NonFatal
----If neither `scala.util` nor `scala.util.control` is referenced anywhere after the expansion, they become unused imports.
Unfortunately, these newly introduced unused imports cannot be removed by setting `removeUnused` to `true`. Please refer to the <> option for more details.
======== Value type
Boolean
==== Default value
`false`
==== Examples
Configuration:
[source,hocon]
----
OrganizeImports {
expandRelative = true
groups = ["re:javax?\\.", "scala.", "*"]
}
----Before:
[source,scala]
----
import scala.util
import util.control
import control.NonFatal
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import javax.annotation.Generated
import scala.concurrent.ExecutionContext
----After:
[source,scala]
----
import java.time.Clock
import javax.annotation.Generatedimport scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext
import scala.util
import scala.util.control
import scala.util.control.NonFatalimport sun.misc.BASE64Encoder
----[[groupExplicitlyImportedImplicitsSeparately]]
=== `groupExplicitlyImportedImplicitsSeparately`This option provides a workaround to a subtle and rarely seen correctness issue related to explicitly imported implicit names.
The following snippet helps illustrate the problem:
[source,scala]
----
package aimport c._
import b.iobject b { implicit def i: Int = 1 }
object c { implicit def i: Int = 2 }object Imports {
def f()(implicit i: Int) = println(1)
def main() = f()
}
----The above snippet compiles successfully and outputs `1`, because the explicitly imported implicit value `b.i` overrides `c.i`, which is made available via a wildcard import. However, if we reorder the two imports into:
[source,scala]
----
import b.i
import c._
----The Scala compiler starts complaining:
----
error: could not find implicit value for parameter i: Int
def main() = f()
^
----This behavior could be due to a Scala compiler bug since https://scala-lang.org/files/archive/spec/2.13/02-identifiers-names-and-scopes.html[the Scala language specification] requires that explicitly imported names should have higher precedence than names made available via a wildcard.
Unfortunately, Scalafix is not able to surgically identify conflicting implicit values behind a wildcard import. In order to guarantee correctness in all cases, when the `groupExplicitlyImportedImplicitsSeparately` option is set to `true`, all explicitly imported implicit names are moved into the trailing order-preserving import group together with relative imports, if any (see the <> section for more details).
CAUTION: In general, order-sensitive imports are fragile, and can easily be broken by either human collaborators or tools (e.g., the IntelliJ IDEA Scala import optimizer does not handle this case correctly). They should be eliminated whenever possible. This option is mostly useful when you are dealing with a large trunk of legacy codebase, and you want to minimize manual intervention and guarantee correctness in all cases.
[IMPORTANT]
====
The `groupExplicitlyImportedImplicitsSeparately` option has currently no effect on source files compiled with Scala 3, as the https://github.com/lampepfl/dotty/issues/12766[compiler does not expose full signature information], preventing the rule to identify imported implicits.
======== Value type
Boolean
==== Default value
`false`
Rationale::
+
--
This option defaults to `false` due to the following reasons:. Although setting it to `true` avoids the aforementioned correctness issue, the result is unintuitive and confusing for many users since it looks like the `groups` option is not respected.
+
E.g., why my `scala.concurrent.ExecutionContext.Implicits.global` import is moved to a separate group even if I have a `scala.` group defined in the `groups` option?. The concerned correctness issue is rarely seen in real life. When it really happens, it is usually a sign of bad coding style, and you may want to tweak your imports to eliminate the root cause.
--==== Examples
Configuration:
[source,hocon]
----
OrganizeImports {
groups = ["scala.", "*"]
groupExplicitlyImportedImplicitsSeparately = true // not supported in Scala 3
}
----Before:
[source,scala]
----
import org.apache.spark.SparkContext
import org.apache.spark.RDD
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Buffer
import scala.concurrent.ExecutionContext.Implicits.global
import scala.sys.process.stringToProcess
----After:
[source,scala]
----
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Bufferimport org.apache.spark.RDD
import org.apache.spark.SparkContextimport scala.concurrent.ExecutionContext.Implicits.global
import scala.sys.process.stringToProcess
----[[groupedImports]]
=== `groupedImports`Configure how to handle grouped imports.
==== Value type
Enum: `Explode | Merge | AggressiveMerge | Keep`
`Explode`:: Explode grouped imports into separate import statements.
`Merge`::
+
--
Merge imports sharing the same prefix into a single grouped import statement.[TIP]
====
You may want to check the <> option for more concise results despite a relatively low risk of introducing compilation errors.
====[IMPORTANT]
====
`OrganizeImports` does not support cases where one name is renamed to multiple aliases within the same source file when `groupedImports` is set to `Merge`. (The IntelliJ IDEA Scala import optimizer does not support this either.)Scala allows a name to be renamed to multiple aliases within a single source file, which makes merging import statements tricky. For example:
[source,scala]
----
import java.lang.{Double => JDouble}
import java.lang.{Double => JavaDouble}
import java.lang.Integer
----The above three imports can be merged into:
[source,scala]
----
import java.lang.{Double => JDouble}
import java.lang.{Double => JavaDouble, Integer}
----but not:
[source,scala]
----
import java.lang.{Double => JDouble, Double => JavaDouble, Integer}
----because Scala disallow a name (in this case, `Double`) to appear in one import multiple times.
Here's a more complicated example:
[source,scala]
----
import p.{A => A1}
import p.{A => A2}
import p.{A => A3}import p.{B => B1}
import p.{B => B2}import p.{C => C1}
import p.{C => C2}
import p.{C => C3}
import p.{C => C4}
----While merging these imports, we may want to "bin-pack" them to minimize the number of the result import statements:
[source,scala]
----
import p.{A => A1, B => B1, C => C1}
import p.{A => A2, B => B2, C => C2}
import p.{A => A3, C3 => C3}
import p.{C => C4}
----However, in reality, renaming aliasing a name multiple times in the same source file is rarely a practical need. Therefore, `OrganizeImports` does not support this when `groupedImports` is set to `Merge` to avoid the extra complexity.
====
--[[aggressive-merge]]
`AggressiveMerge`::
+
--
Similar to `Merge`, but merges imports more aggressively and produces more concise results, despite a relatively low risk of introducing compilation errors.The `OrganizeImports` rule tries hard to guarantee correctness in all cases. This forces it to be more conservative when merging imports, and may sometimes produce suboptimal output. Here is a concrete example about correctness:
[source,scala]
----
import scala.collection.immutable._
import scala.collection.mutable.Map
import scala.collection.mutable._object Example {
val m: Map[Int, Int] = ???
}
----At a first glance, it seems feasible to simply drop the second import since `mutable._` already covers `mutble.Map`. However, similar to the example illustrated in the section about the <>, the type of `Example.m` above is `mutable.Map`, because the mutable `Map` explicitly imported in the second import takes higher precedence than the immutable `Map` imported via wildcard in the first import. If we merge the last two imports naively, we'll get:
[source,scala]
----
import scala.collection.immutable._
import scala.collection.mutable._
----This triggers in a compilation error, because both `immutable.Map` and `mutable.Map` are now imported via wildcards with the same precedence. This makes the type of `Example.m` ambiguous. The correct result should be:
[source,scala]
----
import scala.collection.immutable._
import scala.collection.mutable.{Map, _}
----On the other hand, the case discussed above is rarely seen in practice. A more commonly seen case is something like:
[source,scala]
----
import scala.collection.mutable.Map
import scala.collection.mutable._
----Instead of being conservative and produce a suboptimal output like:
[source,scala]
----
import scala.collection.mutable.{Map, _}
----setting `groupedImports` to `AggressiveMerge` produces
[source,scala]
----
import scala.collection.mutable._
----
--`Keep`:: Leave grouped imports and imports sharing the same prefix untouched.
==== Default value
`Explode`
Rationale:: Despite making the import section lengthier, exploding grouped imports into separate import statements is made the default behavior because it is more friendly to version control and less likely to create annoying merge conflicts caused by trivial import changes.
==== Examples
`Explode`::
+
--
Configuration:[source,hocon]
----
OrganizeImports.groupedImports = Explode
----Before:
[source,scala]
----
import scala.collection.mutable.{ArrayBuffer, Buffer, StringBuilder}
----After:
[source,scala]
----
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Buffer
import scala.collection.mutable.StringBuilder
----
--`Merge`::
+
--
Configuration:[source,hocon]
----
OrganizeImports.groupedImports = Merge
----Before:
[source,scala]
----
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Buffer
import scala.collection.mutable.StringBuilder
import scala.collection.immutable.Set
import scala.collection.immutable._
----After:
[source,scala]
----
import scala.collection.mutable.{ArrayBuffer, Buffer, StringBuilder}
import scala.collection.immutable.{Set, _}
----
--`AggressiveMerge`::
+
--
Configuration:[source,hocon]
----
OrganizeImports.groupedImports = AggressiveMerge
----Before:
[source,scala]
----
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Buffer
import scala.collection.mutable.StringBuilder
import scala.collection.immutable.Set
import scala.collection.immutable._
----After:
[source,scala]
----
import scala.collection.mutable.{ArrayBuffer, Buffer, StringBuilder}
import scala.collection.immutable._
----
--[[groups]]
=== `groups`Defines import groups by prefix patterns. Only global imports are processed.
All the imports matching the same prefix pattern are gathered into the same group and sorted by the order defined by the <> option.
CAUTION: Comments living _between_ imports being processed will be _removed_.
[TIP]
====
`OrganizeImports` tries to match the longest prefix while grouping imports. For instance, the following configuration groups `scala.meta.` and `scala.` imports into different two groups properly:[source,hocon]
----
OrganizeImports.groups = [
"re:javax?\\."
"scala."
"scala.meta."
"*"
]
----
====[[trailing-order-preserving-import-group]]
[IMPORTANT]
====
No matter how the `groups` option is configured, a special order-preserving import group may appear after all the configured import groups when:. The `expandRelative` option is set to `false` and there are relative imports.
. The `groupExplicitlyImportedImplicitsSeparately` option is set to `true` and there are implicit names explicitly imported.This special import group is necessary because the above two kinds of imports are order sensitive:
Relative imports::
+
--
For instance, sorting the following imports in alphabetical order introduces compilation errors:[source,scala]
----
import scala.util
import util.control
import control.NonFatal
----
--Explicitly imported implicit names:: Please refer to the <> option for more details.
======== Value type
An ordered list of import prefix pattern strings. A prefix pattern can be one of the following:
A plain-text pattern:: For instance, `"scala."` is a plain-text pattern that matches imports referring the `scala` package. Please note that the trailing dot is necessary, otherwise you may have `scalafix` and `scala` imports in the same group, which is not what you want in most cases.
A regular expression pattern:: A regular expression pattern starts with `re:`. For instance, `"re:javax?\\."` is such a pattern that matches both the `java` and the `javax` packages. Please refer to the https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html[`java.util.regex.Pattern`] Javadoc page for the regular expression syntax. Note that special characters like backslashes must be escaped.
The wildcard pattern::
+
--
The wildcard pattern, `"*"`, defines the wildcard group, which matches all fully-qualified imports not belonging to any other groups. It can be omitted when it's the last group. So the following two configurations are equivalent:[source,hocon]
----
OrganizeImports.groups = ["re:javax?\\.", "scala.", "*"]
OrganizeImports.groups = ["re:javax?\\.", "scala."]
----
--[[blank-line-marker]]
A blank line marker::
+
--
Available since v0.5.0-alpha.1.A blank line marker, `"---"`, defines a blank line between two adjacent import groups when <> is set to `Manual`. It is ignored when `blankLines` is `Auto`. Leading and trailing blank line markers are always ignored. Multiple consecutive blank line markers are treated as a single one. So the following three configurations are all equivalent:
[source,hocon]
----
OrganizeImports {
blankLines = Manual
groups = [
"---"
"re:javax?\\."
"---"
"scala."
"---"
"---"
"*"
"---"
]
}OrganizeImports {
blankLines = Manual
groups = [
"re:javax?\\."
"---"
"scala."
"---"
"*"
]
}OrganizeImports {
blankLines = Auto
groups = [
"re:javax?\\."
"scala."
"*"
]
}
----
--==== Default value
[source,hocon]
----
[
"*"
"re:(javax?|scala)\\."
]
----Rationale:: This aligns with the default configuration of the IntelliJ Scala plugin version 2020.3.
==== Examples
Fully-qualified imports only::
+
--
Configuration:[source,hocon]
----
OrganizeImports.groups = ["re:javax?\\.", "scala.", "*"]
----Before:
[source,scala]
----
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import javax.annotation.Generated
import scala.concurrent.ExecutionContext
----After:
[source,scala]
----
import java.time.Clock
import javax.annotation.Generatedimport scala.collection.JavaConverters._
import scala.concurrent.ExecutionContextimport sun.misc.BASE64Encoder
----
--With relative imports::
+
--
Configuration:[source,hocon]
----
OrganizeImports.groups = ["re:javax?\\.", "scala.", "*"]
----Before:
[source,scala]
----
import scala.util
import util.control
import control.NonFatal
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import javax.annotation.Generated
import scala.concurrent.ExecutionContext
----After:
[source,scala]
----
import java.time.Clock
import javax.annotation.Generatedimport scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext
import scala.utilimport sun.misc.BASE64Encoder
import util.control
import control.NonFatal
----
--With relative imports and an explicitly imported implicit name::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
groups = ["re:javax?\\.", "scala.", "*"]
groupExplicitlyImportedImplicitsSeparately = true
}
----Before:
[source,scala]
----
import scala.util
import util.control
import control.NonFatal
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import javax.annotation.Generated
import scala.concurrent.ExecutionContext.Implicits.global
----After:
[source,scala]
----
import java.time.Clock
import javax.annotation.Generatedimport scala.collection.JavaConverters._
import scala.utilimport sun.misc.BASE64Encoder
import util.control
import control.NonFatal
import scala.concurrent.ExecutionContext.Implicits.global
----
--Regular expression::
+
--
Defining import groups using regular expressions can be quite flexible. For instance, the `scala.meta` package is not part of the Scala standard library, but the default groups defined in the `OrganizeImports.groups` option move imports from this package into the `scala.` group. The following example illustrates how to move them into the wildcard group using regular expression.Configuration:
[source,hocon]
----
OrganizeImports.groups = [
"re:javax?\\."
"re:scala.(?!meta\\.)"
"*"
]
----Before:
[source,scala]
----
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import scala.meta.Tree
import javax.annotation.Generated
import scala.concurrent.ExecutionContext
import scala.meta.Import
import scala.meta.Pkg
----After:
[source,scala]
----
import java.time.Clock
import javax.annotation.Generatedimport scala.collection.JavaConverters._
import scala.concurrent.ExecutionContextimport scala.meta.Import
import scala.meta.Pkg
import scala.meta.Tree
import sun.misc.BASE64Encoder
----
--With manually configured blank lines::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
blankLines = Manual
groups = [
"*"
"---"
"re:javax?\\."
"scala."
]
}
----Before:
[source,scala]
----
import scala.collection.JavaConverters._
import java.time.Clock
import sun.misc.BASE64Encoder
import javax.annotation.Generated
import scala.concurrent.ExecutionContext
----After:
[source,scala]
----
import sun.misc.BASE64Encoderimport java.time.Clock
import javax.annotation.Generated
import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext
----
--[[importSelectorsOrder]]
=== `importSelectorsOrder`Specifies the order of grouped import selectors within a single import expression.
==== Value type
Enum: `Ascii | SymbolsFirst | Keep`
`Ascii`:: Sort import selectors by ASCII codes, equivalent to the https://scalameta.org/scalafmt/docs/configuration.html#asciisortimports[`AsciiSortImports`] rewriting rule in Scalafmt.
`SymbolsFirst`:: Sort import selectors by the groups: symbols, lower-case, upper-case, equivalent to the https://scalameta.org/scalafmt/docs/configuration.html#sortimports[`SortImports`] rewriting rule in Scalafmt.
`Keep`:: Keep the original order.
==== Default value
`Ascii`
==== Examples
`Ascii`::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
groupedImports = Keep
importSelectorsOrder = Ascii
}
----Before:
[source,scala]
----
import foo.{~>, `symbol`, bar, Random}
----After:
[source,scala]
----
import foo.{Random, `symbol`, bar, ~>}
----
--`SymbolsFirst`::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
groupedImports = Keep
importSelectorsOrder = SymbolsFirst
}
----Before:
[source,scala]
----
import foo.{Random, `symbol`, bar, ~>}
----After:
[source,scala]
----
import foo.{~>, `symbol`, bar, Random}
----
--[[importsOrder]]
=== `importsOrder`Specifies the order of import statements within import groups defined by the <> option.
==== Value type
Enum: `Ascii | SymbolsFirst | Keep`
`Ascii`:: Sort import statements by ASCII codes. This is the default sorting order that the IntelliJ IDEA Scala import optimizer picks ("lexicographically" option).
`SymbolsFirst`:: Put wildcard imports and grouped imports with braces first, otherwise same as `Ascii`. This replicates IntelliJ IDEA Scala's "scalastyle consistent" option.
`Keep`:: Keep the original order.
==== Default value
`Ascii`
==== Examples
`Ascii`::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
groupedImports = Keep
importsOrder = Ascii
}
----Before:
[source,scala]
----
import scala.concurrent._
import scala.concurrent.{Future, Promise}
import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.duration
----After:
[source,scala]
----
import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent._
import scala.concurrent.duration
import scala.concurrent.{Promise, Future}
----
--`SymbolsFirst`::
+
--
Configuration:[source,hocon]
----
OrganizeImports {
groupedImports = Keep
importsOrder = SymbolsFirst
}
----Before:
[source,scala]
----
import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent._
import scala.concurrent.duration
import scala.concurrent.{Promise, Future}
----After:
[source,scala]
----
import scala.concurrent._
import scala.concurrent.{Future, Promise}
import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.duration
----
--[[preset]]
=== `preset`Available since v0.5.0.
Specify a preset style.
==== Value type
Enum: `DEFAULT | INTELLIJ_2020_3`
`DEFAULT`::
+
--
An opinionated style recommended for new projects. The `OrganizeImports` rule tries its best to ensure correctness in all cases when possible. This default style aligns with this principal. In addition, by setting `groupedImports` to `Explode`, this style is also more friendly to version control and less likely to create annoying merge conflicts caused by trivial import changes.[source,hocon]
----
OrganizeImports {
blankLines = Auto
coalesceToWildcardImportThreshold = null
expandRelative = false
groupExplicitlyImportedImplicitsSeparately = false
groupedImports = Explode
groups = [
"*"
"re:(javax?|scala)\\."
]
importSelectorsOrder = Ascii
importsOrder = Ascii
preset = DEFAULT
removeUnused = true
}
----
--[[intellij-2020-3]]
`INTELLIJ_2020_3`::
+
--
A style that is compatible with the default configuration of the IntelliJ Scala 2020.3 import optimizer. It is mostly useful for adding `OrganizeImports` to existing projects developed using the IntelliJ Scala plugin. However, the configuration of this style may introduce subtle correctness issues (so does the default configuration of the IntelliJ Scala plugin). Please see the <> for more details.[source,hocon]
----
OrganizeImports {
blankLines = Auto
coalesceToWildcardImportThreshold = 5
expandRelative = false
groupExplicitlyImportedImplicitsSeparately = false
groupedImports = Merge
groups = [
"*"
"re:(javax?|scala)\\."
]
importSelectorsOrder = Ascii
importsOrder = Ascii
preset = INTELLIJ_2020_3
removeUnused = true
}
----
--==== Default value
`DEFAULT`
[[removeUnused]]
=== `removeUnused`Remove unused imports.
[CAUTION]
====
As mentioned in <>, the `removeUnused` option doesn't play perfectly with the `expandRelative` option. Setting `expandRelative` to `true` might introduce new unused imports (see <>). These newly introduced unused imports cannot be removed by setting `removeUnused` to `true`. This is because unused imports are identified using Scala compilation diagnostics information, and the compilation phase happens before Scalafix rules get applied.
====[IMPORTANT]
====
The `removeUnused` option is currently not supported for source files compiled with Scala 3, as the https://docs.scala-lang.org/scala3/guides/migration/options-lookup.html#warning-settings[compiler cannot issue warnings for unused imports yet]. As a result, you must set `removeUnused` to `false` when running the rule on source files compiled with Scala 3.
======== Value type
Boolean
==== Default value
`true`
==== Examples
Configuration:
[source,hocon]
----
OrganizeImports {
groups = ["javax?\\.", "scala.", "*"]
removeUnused = true // not supported in Scala 3
}
----Before:
[source,scala]
----
import scala.collection.mutable.{Buffer, ArrayBuffer}
import java.time.Clock
import java.lang.{Long => JLong, Double => JDouble}object RemoveUnused {
val buffer: ArrayBuffer[Int] = ArrayBuffer.empty[Int]
val long: JLong = JLong.parseLong("0")
}
----After:
[source,scala]
----
import java.lang.{Long => JLong}import scala.collection.mutable.ArrayBuffer
object RemoveUnused {
val buffer: ArrayBuffer[Int] = ArrayBuffer.empty[Int]
val long: JLong = JLong.parseLong("0")
}
----