### Clone and Run Scalafix Example Project Source: https://scalacenter.github.io/scalafix/docs/users/installation Demonstrates how to clone a minimal example project that uses sbt-scalafix and run a Scalafix rule. This involves cloning the repository, navigating into the directory, and executing a specific Scalafix command. The expected outcome is a git diff showing the code changes. ```shell git clone https://github.com/scalacenter/sbt-scalafix-example cd sbt-scalafix-example sbt "scalafix RemoveUnused" git diff // should produce a diff ``` -------------------------------- ### Start Docusaurus Live Reload Server Source: https://scalacenter.github.io/scalafix/docs/developers/contributing Starts the Docusaurus live reload server to view the Scalafix documentation website locally. This requires navigating to the `website` directory and installing dependencies using yarn. ```bash cd website yarn install yarn start ``` -------------------------------- ### Cloning Scalafix Project and Starting SBT Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial Instructions for cloning the `scalafix-named-literal-arguments` repository and starting an sbt shell session. This sets up the development environment for working with Scalafix rules. ```bash git clone https://github.com/scalacenter/scalafix-named-literal-arguments.git cd scalafix-named-literal-arguments/scalafix sbt ... [info] sbt server started at local://$HOME/.sbt/1.0/server/93fc24de3bb97dec3e5b/sock sbt:scalafix> ``` -------------------------------- ### Scalafix CLI Configuration Source: https://scalacenter.github.io/scalafix/docs/users/cross-building Demonstrates how to specify a Scalafix configuration file when using the Scalafix command-line interface. ```bash scalafix --config .scalafix-scala2.conf scalafix --config .scalafix-scala3.conf ``` -------------------------------- ### Scalafix Bash Tab Completion Installation Source: https://scalacenter.github.io/scalafix/docs/users/installation Instructions for installing Scalafix tab completions for the bash shell on macOS and Linux. This enhances command-line usability by providing suggestions for Scalafix commands and options. ```bash # macOS, requires "brew install bash-completion" scalafix --bash > /usr/local/etc/bash_completion.d/scalafix # Linux scalafix --bash > /etc/bash_completion.d/scalafix ``` -------------------------------- ### Scalafix Zsh Tab Completion Installation Source: https://scalacenter.github.io/scalafix/docs/users/installation Instructions for installing Scalafix tab completions for the zsh shell. This improves command-line efficiency by offering relevant suggestions for Scalafix commands and arguments. ```zsh scalafix --zsh > /usr/local/share/zsh/site-functions/_scalafix unfunction _scalafix autoload -U _scalafix ``` -------------------------------- ### Configure Rule-Specific Settings Source: https://scalacenter.github.io/scalafix/docs/users/configuration Allows for custom configuration of individual Scalafix rules. This example shows how to enable a specific option for the DisableSyntax rule. ```HOCON // .scalafix.conf rules = [ DisableSyntax ] DisableSyntax.noFinalize = true ``` -------------------------------- ### OrganizeImports Example: Fully-qualified Imports Source: https://scalacenter.github.io/scalafix/docs/rules/OrganizeImports Demonstrates how `OrganizeImports.groups` with patterns like `"re:javax?\."` and `"scala."` organizes fully-qualified imports. The example shows imports before and after applying the configuration, highlighting the grouping and separation. ```scala OrganizeImports.groups = ["re:javax?\.", "scala.", "*"] Before: ``` import scala.collection.JavaConverters._ import java.time.Clock import sun.misc.BASE64Encoder import javax.annotation.Generated import scala.concurrent.ExecutionContext ``` After: ``` import java.time.Clock import javax.annotation.Generated import scala.collection.JavaConverters._ import scala.concurrent.ExecutionContext import sun.misc.BASE64Encoder ``` ``` -------------------------------- ### Define and call methods Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial Defines two simple methods, `complete` and `finish`, and demonstrates their invocation. This serves as a basic example for subsequent rule development. ```Scala def complete(isSuccess: Boolean): Unit = () def finish(isError: Boolean): Unit = () complete(true) finish(true) ``` -------------------------------- ### Install and Verify Scalafix CLI Versions with Coursier Source: https://scalacenter.github.io/scalafix/docs/users/installation Provides commands to install and verify different versions of the Scalafix command-line interface using Coursier. This allows users to manage and test specific Scalafix releases. The `--version` flag is used to confirm the installed version. ```shell cs install scalafix scalafix --version # Should say 0.14.5 cs install scalafix:0.14.0 scalafix --version # Should say 0.14.0 cs launch scalafix:0.13.0 -- --version # Should say 0.13.0 ``` -------------------------------- ### Compile Documentation with sbt Source: https://scalacenter.github.io/scalafix/docs/developers/contributing Compiles the markdown documentation using sbt. This process is necessary for generating the Scalafix documentation website, which is built with Docusaurus and mdoc. ```bash > ci-docs ``` -------------------------------- ### OrganizeImports Example: With Relative Imports Source: https://scalacenter.github.io/scalafix/docs/rules/OrganizeImports Illustrates the effect of `OrganizeImports.groups` on code containing both fully-qualified and relative imports. The example shows how relative imports are handled separately to maintain correct compilation order, as demonstrated in the 'Before' and 'After' states. ```scala OrganizeImports.groups = ["re:javax?\.", "scala.", "*"] Before: ``` import scala.utilRationale 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: ``` import java.time.Clock import javax.annotation.Generated import scala.collection.JavaConverters._ import scala.concurrent.ExecutionContext import scala.util import sun.misc.BASE64Encoder import util.control import control.NonFatal ``` ``` -------------------------------- ### Scalafix Rule Implementation Example (Scala) Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial An example of a Scalafix rule implementation in Scala. This rule, likely a syntactic rule, collects and processes `Term.Apply` nodes, specifically looking for `Lit` arguments that are disabled according to a configuration. It then generates a `Patch.lint` for each such argument. ```scala override def fix(implicit doc: SyntacticDocument): Patch = { doc.tree .collect { case Term.Apply(_, args) => args.collect { case t: Lit if config.isDisabled(t) => Patch.lint(LiteralArgument(t)) } } .flatten .asPatch } ``` -------------------------------- ### Configure Scalafix Rules Source: https://scalacenter.github.io/scalafix/docs/users/configuration Defines the list of Scalafix rules to be executed. This is a basic configuration for enabling specific rules. ```HOCON // .scalafix.conf rules = [ DisableSyntax ] ``` -------------------------------- ### Run Windows-Compatible Tests with sbt Source: https://scalacenter.github.io/scalafix/docs/developers/contributing Executes tests that are expected to succeed on Windows environments. This command is used to ensure cross-platform compatibility for Scalafix components. ```bash > unit3_3_6 / testWindows > integration3_3_6 / testWindows ``` -------------------------------- ### Run Scalafix ProcedureSyntax Rule Source: https://scalacenter.github.io/scalafix/docs/users/installation This command demonstrates how to run the `ProcedureSyntax` rule in Scalafix from the sbt shell. This rule typically refactors procedures to explicitly return Unit. ```sbt > myproject / scalafix ProcedureSyntax ``` -------------------------------- ### Add Rule Dependency to build.sbt Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial To permanently install a published rule for a build, add its dependency to the `build.sbt` file under `ThisBuild / scalafixDependencies`. Replace `VERSION` with the correct version. ```scala // build.sbt ThisBuild / scalafixDependencies += "ch.epfl.scala" %% "named-literal-arguments" % "VERSION" ``` -------------------------------- ### Add scalafix-testkit Dependency Source: https://scalacenter.github.io/scalafix/docs/developers/setup This command adds the `scalafix-testkit` artifact to your project, enabling direct testing of custom Scalafix rules. Ensure you use the correct version for your Scala build. ```shell cs fetch ch.epfl.scala:scalafix-testkit_2.12.21:0.14.5 ``` -------------------------------- ### Create Scalafix Project Template (sbt) Source: https://scalacenter.github.io/scalafix/docs/developers/setup Use the `scalafix.g8` project template to quickly set up a new project for writing custom Scalafix rules. This command initializes a new sbt project with the necessary structure for defining and testing rules. ```bash cd repo-name sbt new scalacenter/scalafix.g8 --repo="Repository Name" cd scalafix sbt tests / test ``` -------------------------------- ### Inspect Syntax Tree Structure (Scalameta) Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial This example shows how to use the `.structure` and `.structureWidth` extension methods on Scalameta trees to inspect their abstract syntax tree representation. The output can be used to understand the structure of code elements and aid in writing pattern matches. ```scala import scalafix.v1._ import scala.meta._ println(q"complete(true)".structure) // line wrap at 80th column // Term.Apply(Term.Name("complete"), Term.ArgClause(List(Lit.Boolean(true)), None)) println(q"complete(true)".structureWidth(30)) // line wrap at 30th column // Term.Apply( // Term.Name("complete"), // Term.ArgClause( // List(Lit.Boolean(true)), // None // ) // ) ``` -------------------------------- ### Override Linting Behavior with List of Regex Source: https://scalacenter.github.io/scalafix/docs/users/configuration An alternative way to override linting behavior using a list of regular expressions. This configuration achieves the same result as the single regex example. ```HOCON // .scalafix.conf lint.error = [ "^((?!UnusedScalafixSuppression).)*$" ] ``` -------------------------------- ### Override Linting Behavior with Regex Source: https://scalacenter.github.io/scalafix/docs/users/configuration Configures which linter diagnostics should result in a non-zero exit code. This example forces all linter reports to be treated as errors, except for unused suppressions. ```HOCON // .scalafix.conf lint.error = "^((?!UnusedScalafixSuppression).)*$" ``` -------------------------------- ### Publish Rule Online with sbt Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial These sbt commands are executed after setting up GPG and Sonatype. `publishSigned` signs the artifacts, and `sonatypeRelease` handles the release to the Sonatype repository. ```bash > rules/publishSigned > sonatypeRelease ``` -------------------------------- ### SBT Command Sequence for Scalafix and Scalafmt Source: https://scalacenter.github.io/scalafix/docs/rules/OrganizeImports This sequence of SBT commands demonstrates how to integrate Scalafix and Scalafmt in a project. It includes running `scalafixAll` to organize imports, `scalafmtAll` to format code, and then `scalafixAll --check` to verify that no conflicts arise, especially when Scalafmt might reformat imports. ```bash sbt> scalafixAll ... sbt> scalafmtAll ... sbt> scalafixAll --check ... ``` -------------------------------- ### Scalafix CLI Usage and Options Source: https://scalacenter.github.io/scalafix/docs/users/installation This section describes the general usage of the Scalafix CLI and its common options. It covers how to specify rules, files, configuration files, and control the fixing process (e.g., check mode, stdout output, diff mode). ```bash Scalafix 0.14.5+48-38dd7ac5-SNAPSHOT Usage: scalafix [options] [ ...] Scalafix is a refactoring and linting tool. Scalafix supports both syntactic and semantic linter and rewrite rules. Syntactic rules can run on source code without compilation. Semantic rules can run on source code that has been compiled with the SemanticDB compiler plugin. Common options: --rules | -r [String ...] (default: []) Scalafix rules to run, for example ExplicitResultTypes. The syntax for rules is documented in https://scalacenter.github.io/scalafix/docs/users/configuration#rules --files | -f [ ...] (default: []) Files or directories (recursively visited) to fix. --config (default: null) File path to a .scalafix.conf configuration file. Defaults to .scalafix.conf in the current working directory, if any. --check Check that all files have been fixed with scalafix, exiting with non-zero code on violations. Won't write to files. --stdout Print fixed output to stdout instead of writing in-place. --diff If set, only apply scalafix to added and edited files in git diff against the master branch. --diff-base String (default: null) If set, only apply scalafix to added and edited files in git diff against a provided branch, commit or tag. --scala-version ScalaVersion (default: "2.13.18") The major or binary Scala version that the provided files are targeting, or the full version that was used to compile them when a classpath is provided. --syntactic Run only syntactic rules, ignore semantic rules even if they are explicitly configured in .scalafix.conf or via --rules --triggered Overlay the default rules & rule settings in .scalafix.conf with the `triggered` section --verbose Print out additional diagnostics while running scalafix. --help | -h Print out this help message and exit --version | -v Print out version number and exit Semantic options: --classpath Classpath (default: "") Full classpath of the files to fix, required for semantic rules. The source files that should be fixed must be compiled with semanticdb-scalac. Dependencies are required by rules like ExplicitResultTypes, but the dependencies do not need to be compiled with semanticdb-scalac. --sourceroot (default: null) Absolute path passed to semanticdb with -P:semanticdb:sourceroot:. Relative filenames persisted in the Semantic DB are absolutized by the sourceroot. Defaults to current working directory if not provided. --semanticdb-targetroots [ ...] (default: []) Absolute paths passed to semanticdb with -P:semanticdb:targetroot:. Used to locate semanticdb files. By default, Scalafix will try to locate semanticdb files in the classpath --auto-classpath If set, automatically infer the --classpath flag by scanning for directories with META-INF/semanticdb --auto-classpath-roots [ ...] (default: []) Additional directories to scan for --auto-classpath --scalac-options [String ...] (default: []) The scala compiler options used to compile this --classpath, for example -Ywarn-unused-import Tab completions: --bash Print out bash tab completions. To install: ``` # macOS, requires "brew install bash-completion" scalafix --bash > /usr/local/etc/bash_completion.d/scalafix # Linux scalafix --bash > /etc/bash_completion.d/scalafix ``` --zsh Print out zsh tab completions. To install: ``` scalafix --zsh > /usr/local/share/zsh/site-functions/_scalafix unfunction _scalafix autoload -U _scalafix ``` Less common options: --exclude [ ...] (default: []) Unix-style glob for files to exclude from fixing. The glob syntax is defined by `nio.FileSystem.getPathMatcher`. --tool-classpath URLClassLoader (default: "") Additional classpath for compiling and classloading custom rules, as a set of filesystem paths, separated by ':' on Unix or ';' on Windows. --charset Charset (default: "UTF-8") The encoding to use for reading/writing files --no-sys-exit If set, throw exception in the end instead of System.exit --no-stale-semanticdb Don't error on stale semanticdb files. --settings ScalafixConfig (default: {}) Custom settings to override .scalafix.conf --out-from String (default: null) Write fixed output to custom location instead of in-place. Regex is passed as first argument to file.replaceAll(--out-from, --out-to), requires --out-to. --out-to String (default: null) Companion of --out-from, string that is passed as second argument to fileToFix.replaceAll(--out-from, --out-to) --auto-suppress-linter-errors Insert /* scalafix:ok */ suppressions instead of reporting linter errors. ``` -------------------------------- ### Example Configuration for ExplicitResultTypes (Scala) Source: https://scalacenter.github.io/scalafix/docs/rules/ExplicitResultTypes This code snippet provides an example of how to configure the ExplicitResultTypes Scalafix rule in Scala. It demonstrates setting specific values for member kind, visibility, and simple definitions. ```scala ExplicitResultTypes.memberKind = [Def, Val, Var] ExplicitResultTypes.memberVisibility = [Public, Protected] ExplicitResultTypes.skipSimpleDefinitions = ['Lit', 'Term.New'] ``` -------------------------------- ### Configure build.sbt for Online Publishing Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial These settings in `build.sbt` are essential for publishing a rule online. They define the organization, project details, homepage, license, and developer information. ```scala // build.sbt inThisBuild(List( organization := "ch.epfl.scala", homepage := Some(url("https://github.com/scalacenter/scalafix")), licenses := List("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")), developers := List( Developer( "olafurpg", "Ólafur Páll Geirsson", "olafurpg@gmail.com", url("https://geirsson.com") ) ) )) ``` -------------------------------- ### Inherited Method Overloads Example in Scala Source: https://scalacenter.github.io/scalafix/docs/developers/symbol-information Demonstrates how the `getMethodOverloads` function can identify overloaded methods that are inherited from supertypes. This example shows a custom class `Main` with an overloaded `toString` method, and how Scalafix can distinguish it from the inherited `toString` from `scala.Any`. ```Scala // Main.scala package example class Main { def toString(width: Int): String = ??? } getMethodOverloads(Symbol("example/Main#"), "toString") // res49: Set[SymbolInformation] = Set( // example/Main#toString(). => method toString(width: Int): String, // scala/Any#toString(). => abstract method toString(): String // ) ``` -------------------------------- ### Running Scalafix Tests and Applying Rules via SBT Source: https://scalacenter.github.io/scalafix/docs/developers/local-rules These SBT commands demonstrate how to execute unit tests for Scalafix rules using `scalafixTests / test` and how to apply specific rules (e.g., MyRule1, MyRule2) to a project (e.g., service1) using the `scalafix` command. ```shell $ sbt > scalafixTests / test > service1 / scalafix MyRule1 MyRule2 ``` -------------------------------- ### Directory Structure for Scalafix Input and Output Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial This illustrates the typical directory structure for Scalafix rules, separating the input code that needs rewriting from the expected output code after the rewrite is applied. This structure is crucial for writing and testing rewrite rules. ```tree input/src └── main └── scala └── fix └── NamedLiteralArguments.scala output/src └── main └── scala └── fix └── NamedLiteralArguments.scala ``` -------------------------------- ### Scalafix DisableSyntax: Example of Disallowed Exception Throw Source: https://scalacenter.github.io/scalafix/docs/rules/DisableSyntax This example demonstrates the output of the Scalafix DisableSyntax rule when an exception is thrown. The rule identifies the usage of 'throw' and reports an error, suggesting alternative approaches like encoding errors in the return type. This is a syntactic rule and does not require compilation. ```Scala MyCode.scala:10: error: [DisableSyntax.throw] exceptions should be avoided, consider encoding the error in the return type instead throw new IllegalArgumentException ^^^^^ ``` -------------------------------- ### Publish Rule Locally with sbt Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial This command publishes a Scalafix rule locally using sbt. It's a prerequisite for online publishing and useful for testing within the same codebase. ```bash > rules/publishLocal ``` -------------------------------- ### Prevent Implicit Class Val Leakage with Private Modifier (Scala) Source: https://scalacenter.github.io/scalafix/docs/rules/LeakingImplicitClassVal This Scala code snippet demonstrates how the LeakingImplicitClassVal rule in Scalafix modifies implicit classes. It adds the 'private' access modifier to 'val' fields within implicit classes to prevent them from being accessed as public extension methods. The 'before' example shows the vulnerability, while the 'after' example illustrates the fix. ```Scala // before implicit class XtensionVal(val str: String) extends AnyVal { def doubled: String = str + str } "message".str // compiles // after implicit class XtensionValFixed(private val str: String) extends AnyVal { def doubled: String = str + str } "message".str // does not compile ``` -------------------------------- ### Run Scalafix Custom Rule Tests (sbt) Source: https://scalacenter.github.io/scalafix/docs/developers/setup Execute unit tests for your custom Scalafix rules using the `tests / test` command within the sbt shell. For continuous testing during development, use `~tests / test`. ```bash sbt > ~tests / test ``` -------------------------------- ### Add sbt-ci-release Plugin Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial This snippet shows how to add the `sbt-ci-release` plugin to your project by including it in `project/plugins.sbt`. This plugin facilitates the release process. ```scala // project/plugins.sbt addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.10") ``` -------------------------------- ### Scalafix CLI: Snapshot Release Launch Command Source: https://scalacenter.github.io/scalafix/docs/users/installation Launches the Scalafix CLI using a snapshot release from a specified Maven repository. This command uses `cs launch` to execute the `scalafix.cli.Cli` main class with the `--help` argument, targeting the snapshot version. ```bash cs launch ch.epfl.scala:scalafix-cli_2.13.18:0.14.5+48-38dd7ac5-SNAPSHOT -r https://central.sonatype.com/repository/maven-snapshots --main scalafix.cli.Cli -- --help ``` -------------------------------- ### Scalafix Common Configuration Source: https://scalacenter.github.io/scalafix/docs/users/cross-building Defines shared Scalafix rules and their configurations, intended to be included by version-specific configuration files. ```hocon rules = [ DisableSyntax, OrganizeImports ] DisableSyntax { noFinalize = true } ``` -------------------------------- ### Pass Configuration via CLI Arguments Source: https://scalacenter.github.io/scalafix/docs/users/configuration Demonstrates how to override configuration values set in .scalafix.conf by passing them as command-line arguments. Values are prefixed with `--settings.` and require escaping special characters like wildcards. ```Shell $ scalafix ... \ --settings.DisableSyntax.noFinalize=true \ --settings.lint.error.includes=.\* \ --settings.lint.error.excludes=UnusedScalafixSuppression ``` -------------------------------- ### sbt Configuration for Scalafix Source: https://scalacenter.github.io/scalafix/docs/users/cross-building Dynamically sets the Scalafix configuration file based on the Scala version being used in an sbt build. ```scala import scalafix.sbt.ScalafixPlugin.autoImport._ lazy val commonSettings = Seq( scalafixConfig := { val base = (ThisBuild / baseDirectory).value val file = CrossVersion.partialVersion(scalaVersion.value) match { case Some((3, _)) => base / ".scalafix-scala3.conf" case _ => base / ".scalafix-scala2.conf" } Some(file) } ) lazy val core = project .settings(commonSettings) .settings( scalaVersion := "3.3.3", crossScalaVersions := Seq("2.13.14", "3.3.3") ) ``` -------------------------------- ### Scalafix Scala 3 Configuration Source: https://scalacenter.github.io/scalafix/docs/users/cross-building Extends the common Scalafix configuration for Scala 3 projects, adding Scala 3-specific rules and options. ```hocon include ".scalafix-common.conf" rules += LeakingImplicitClassVal OrganizeImports { groupedImports = Keep } ``` -------------------------------- ### Run Scalafix Rule from Local File Path Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial Executes a Scalafix rule defined in a local Scala file. This method is straightforward for rules residing on your machine. Ensure the file path is correctly specified using the 'file:/' URI scheme. On Windows, use 'file:///'. ```bash scalafix --rules=file:/path/to/NamedLiteralArguments.scala ``` -------------------------------- ### Scalafix Scala 2 Configuration Source: https://scalacenter.github.io/scalafix/docs/users/cross-building Extends the common Scalafix configuration for Scala 2 projects, adding Scala 2-specific rules and options. ```hocon include ".scalafix-common.conf" rules += RemoveUnused RemoveUnused { imports = true } ``` -------------------------------- ### Remove Single Token (Scala) Source: https://scalacenter.github.io/scalafix/docs/developers/patch The removeToken() patch replaces a specified token with an empty string. This example removes the string literal 'Hello world!'. ```Scala doc.tokens.collect { case helloWorld @ Token.Constant.String("Hello world!") => Patch.removeToken(helloWorld) }.showDiff() // - println("Hello world!") // + println() ``` -------------------------------- ### Run Scalafix Rule from HTTP URL Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial Runs a Scalafix rule hosted at a public HTTP URL, such as a GitHub Gist. This allows sharing and running rules without local file access. The provided URL should point directly to the raw Scala source file of the rule. ```bash scalafix --rules=https://gist.githubusercontent.com/olafurpg/eeccf32f035d13f0728bc94d8ec0a776/raw/78c81bb7f390eb98178dd26ea03c42bd5a998666/NamedLiteralArguments.scala ``` -------------------------------- ### Scalafix OrganizeImports BlankLines Configuration Examples Source: https://scalacenter.github.io/scalafix/docs/rules/OrganizeImports Demonstrates the 'blankLines' configuration for OrganizeImports, showing how to use 'Auto' and 'Manual' modes for inserting blank lines between import groups. The 'Auto' mode ignores manual markers, while 'Manual' inserts blank lines based on specified markers in the 'groups' configuration. ```scala OrganizeImports { blankLines = Auto groups = [ "re:javax?\." "scala." "*" ] } ``` ```scala OrganizeImports { blankLines = Manual groups = [ "re:javax?\." "---" "scala." "---" "*" ] } ``` ```scala OrganizeImports { blankLines = Auto groups = [ "re:javax?\." "scala." "*" ] } ``` -------------------------------- ### Query method information using Tree.symbol.info Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial Demonstrates how to use `fun.symbol.info` to retrieve `SymbolInformation` for the called method. This provides metadata about the symbol, including its signature. ```Scala case Lit.Boolean(_) => + fun.symbol.info match { + case Some(info) => // ... + case None => + // Do nothing, no information about this symbol. + Patch.empty + } ``` -------------------------------- ### Scalafix OrganizeImports Configuration (Scala) Source: https://scalacenter.github.io/scalafix/docs/rules/OrganizeImports This example shows how to configure Scalafix's OrganizeImports feature, specifically enabling the groupExplicitlyImportedImplicitsSeparately option and defining import groups. ```scala OrganizeImports { groups = ["scala.", "*"] groupExplicitlyImportedImplicitsSeparately = true // not supported in Scala 3 } ``` -------------------------------- ### Run Scalafix Rule from GitHub Repository Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial Executes a Scalafix rule directly from a GitHub repository. This method simplifies running rules from shared projects. The format 'github:org/repo' defaults to the 'master' branch and a specific rule path, but can be customized with branch names or commit SHAs. ```bash scalafix --rules=github:scalacenter/named-literal-arguments ``` -------------------------------- ### Run Specific Rule Tests with sbt Source: https://scalacenter.github.io/scalafix/docs/developers/contributing Focuses on running tests for built-in rules using the scalafix-testkit. This allows for isolated testing of individual rules, such as ProcedureSyntax. ```bash > expect3_3_6Target3_3_6 / test > expect3_3_6Target3_3_6 / testOnly -- -z ProcedureSyntax ``` -------------------------------- ### Disable Scalafix for a Specific Project Source: https://scalacenter.github.io/scalafix/docs/users/installation This snippet demonstrates how to disable the Scalafix plugin for an individual project within a multi-project build. It uses the `.disablePlugins(ScalafixPlugin)` method. ```scala lazy val myproject = project .settings(...) + .disablePlugins(ScalafixPlugin) ``` -------------------------------- ### Generate GPG Key Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial This command is used to generate a GPG key, which is required for signing your releases when publishing to Maven Central. Ensure GPG is set up on your machine before running. ```bash gpg --gen-key ``` -------------------------------- ### Run a Single Scalafix Test Case (sbt) Source: https://scalacenter.github.io/scalafix/docs/developers/setup To run a specific test case or a subset of test cases, use the `testOnly` command with a suite name and a regular expression to filter tests. This is useful for targeted debugging. ```bash tests / testOnly *MySuite -- -z MyRegex ``` -------------------------------- ### Add Scalafix sbt Plugin Source: https://scalacenter.github.io/scalafix/docs/users/installation This snippet shows how to add the Scalafix sbt plugin to your project by including it in the `project/plugins.sbt` file. It specifies the artifact coordinates and version. ```sbt // project/plugins.sbt addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.14.5") ``` -------------------------------- ### Auto Import for project/*.scala Builds Source: https://scalacenter.github.io/scalafix/docs/developers/tutorial For projects using `project/*.scala` files, this import statement is necessary to enable Scalafix functionality, including the use of `scalafixDependencies`. ```scala import scalafix.sbt.ScalafixPlugin.autoImport._ ``` -------------------------------- ### Add String to Right of Token (Scala) Source: https://scalacenter.github.io/scalafix/docs/developers/patch This patch inserts a string to the right of a specific token. The example demonstrates adding a comment after the left parenthesis of the 'println' method. ```Scala doc.tokens.collect { case brace @ Token.LeftParen() => Patch.addRight(brace, " /* <= */ ") }.showDiff() // - println("Hello world!") // + println( /* <= */ "Hello world!") ``` -------------------------------- ### Add Library Dependencies to Input Project (sbt) Source: https://scalacenter.github.io/scalafix/docs/developers/setup Customize the input project by adding library dependencies using standard sbt settings. This allows your custom rules to operate within a specific dependency context. ```scala lazy val input = project.settings( libraryDependencies += "org" %% "name" % "version" ) ``` -------------------------------- ### Testing Release Artifacts Source: https://scalacenter.github.io/scalafix/docs/developers/contributing This script is used to test the release artifacts after a CI build. It takes the version number as an argument to verify the successful completion of the release process. ```shell ./bin/test-release.sh $VERSION ``` -------------------------------- ### Check Binary Compatibility with sbt Source: https://scalacenter.github.io/scalafix/docs/developers/contributing Checks for any binary compatibility issues using `sbt-version-policy`. This is crucial for maintaining stable releases, as anything under `scalafix.internal._` is exempt from compatibility restrictions. ```bash sbt versionPolicyCheck ```