Scalafix: Ban Environment Variable Access
Overview
- Purpose: Prevent direct access to environment variables to encourage centralized configuration via
ConfigReader. - Enforced APIs:
sys.envandjava.lang.System.getenv(...). - Message: Violations emit the error “use ConfigReader”.
What’s Included
- Plugin:
sbt-scalafix(seeproject/plugins.sbt). - Rule: Uses
DisableSyntaxwith regex to flag:sys.envSystem.getenvThis approach is syntactic and does not require SemanticDB.
Running Scalafix
- Lint on compile: Enabled per-project.
- Enabled:
root,samples,shared - Disabled:
workspaceRunner - Violations are warnings and do not fail the build.
- Enabled:
- Manual run:
sbt scalafixAllto check all modules.sbt Test/scalafixto check only test sources.
Violation Examples
val v = sys.env("API_KEY")→ warning: use ConfigReaderval v = System.getenv("API_KEY")→ warning: use ConfigReader
Suppressing a Finding (discouraged)
- Next line only: add
// scalafix:ok NoSysEnvor// scalafix:ok NoSystemGetenv. - Block scope: wrap with
// scalafix:offand// scalafix:on. Use sparingly and document why the exception is necessary.
Migration Guidance
- Replace env access with a typed configuration layer, for example:
- Define a
ConfigReaderthat validates and loads values (e.g., from Typesafe Config, system properties, or injected config), and use it where needed. - Avoid hard dependencies on the process environment in library code; prefer dependency injection.
- Define a
Files Changed
.scalafix.conf: AddsDisableSyntaxregex rules with custom messages.project/plugins.sbt: Adds thesbt-scalafixplugin.build.sbt: EnablesscalafixOnCompileonly onrootandsamples.
Notes
- The rule is syntactic and works for both Scala 2.13 and Scala 3 without SemanticDB.
- If you see false negatives for unusual code paths, please open an issue with a minimal repro so we can extend the rule.