Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
ZIO Config
https://github.com/zio/zio-config
Admin
Easily use and document any config from anywhere in ZIO apps
Tokens:
7,546
Snippets:
56
Trust Score:
7.7
License:
Apache-2.0
Update:
1 year ago
Context
Chat
Benchmark
76.14
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Add ZIO Config Quick Start Modules (Scala) Source: https://github.com/zio/zio-config/blob/series/4.x/docs/index.md This Scala build.sbt snippet includes multiple ZIO Config modules for a quick start, covering core functionality, automatic derivation (magnolia), Typesafe Config integration, and refined types support. These dependencies are essential for exploring various features of ZIO Config. Ensure to substitute `<version>` with the appropriate library version. ```scala libraryDependencies += "dev.zio" %% "zio-config" % "<version>" libraryDependencies += "dev.zio" %% "zio-config-magnolia" % "<version>" libraryDependencies += "dev.zio" %% "zio-config-typesafe" % "<version>" libraryDependencies += "dev.zio" %% "zio-config-refined" % "<version>" ``` -------------------------------- ### Add ZIO Config Module Dependencies for Quick Start (Scala) Source: https://github.com/zio/zio-config/blob/series/4.x/README.md This snippet shows how to include multiple ZIO Config modules (`zio-config`, `zio-config-magnolia`, `zio-config-typesafe`, `zio-config-refined`) in a Scala `build.sbt` file. These modules are commonly used together for quick start examples, providing extended functionality for configuration management. Remember to replace `<version>` with the appropriate library version for each module. ```scala libraryDependencies += "dev.zio" %% "zio-config" % "<version>" libraryDependencies += "dev.zio" %% "zio-config-magnolia" % "<version>" libraryDependencies += "dev.zio" %% "zio-config-typesafe" % "<version>" libraryDependencies += "dev.zio" %% "zio-config-refined" % "<version>" ``` -------------------------------- ### Build ZIO Config Website Locally Source: https://github.com/zio/zio-config/blob/series/4.x/contributing.md Instructions to navigate to the ZIO Config project directory and then execute the SBT command to build the project's documentation website locally. ```Shell cd zio-config ./sbt docs/buildWebsite ``` -------------------------------- ### Build and Test ZIO Config with SBT Source: https://github.com/zio/zio-config/blob/series/4.x/contributing.md Provides a sequence of shell commands to navigate to the project directory and then use SBT for formatting, fixing, checking, compiling all modules, running all examples, and executing all tests within the ZIO Config project. ```Shell cd zio-config sbt fmt fix check sbt compileAll sbt runAllExamples sbt testAll ``` -------------------------------- ### Add ZIO Config Core Dependency (Scala) Source: https://github.com/zio/zio-config/blob/series/4.x/docs/index.md This Scala build.sbt snippet adds the core ZIO Config library as a project dependency. It's the fundamental step to start using ZIO Config in your Scala application. Remember to replace `<version>` with the specific ZIO Config release you intend to use. ```scala libraryDependencies += "dev.zio" %% "zio-config" % "<version>" ``` -------------------------------- ### Build and Test ZIO Config with BLOOP Source: https://github.com/zio/zio-config/blob/series/4.x/contributing.md Outlines shell commands to navigate to the project directory and then use BLOOP for listing available projects, compiling the 'zio-config' module, and running tests for the 'zio-config' module. ```Shell cd zio-config bloop projects bloop compile zio-config bloop test zio-config ``` -------------------------------- ### Define AppConfig Case Class for `to` Method Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet defines a simple `AppConfig` case class, which is used in the subsequent example to demonstrate the `to` method for easy manual configuration mapping. It contains basic fields for port and URL. ```scala final case class AppConfig(port: Int, url: String) ``` -------------------------------- ### Load Configuration from JSON String in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This example demonstrates reading configuration from a JSON formatted string. It shows how to define a JSON string and then use `ConfigProvider.fromHoconString` (which also handles JSON) to parse it into a configuration. ```Scala val jsonString = """ { "port" : "123" "url" : "bla" "region": "useast" } """ ConfigProvider.fromHoconString(jsonString) ``` -------------------------------- ### Load Configuration from a Map Source Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This example demonstrates loading a configuration from a simple Scala `Map`. It creates a `ConfigProvider` from the map and then uses `source.load(myConfig)` to attempt to load the previously defined `myConfig` descriptor, simulating reading from an in-memory source. ```scala val map = Map( "LDAP" -> "xyz", "PORT" -> "8888", "DB_URL" -> "postgres" ) val source = ConfigProvider.fromMap(map) source.load(myConfig) ``` -------------------------------- ### Use `to` Method for Easy Manual Configuration Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet demonstrates the convenient `to` method on a zipped `Config` descriptor. It allows direct mapping of a tupled configuration description (e.g., `Config.int("PORT").zip(Config.string("URL"))`) to a case class like `AppConfig`, simplifying manual configuration setup. ```scala val config = Config.int("PORT").zip(Config.string("URL")).to[AppConfig] ``` -------------------------------- ### Load Configuration from HOCON File in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This snippet provides a concise example of how to load configuration directly from a HOCON file using `ConfigProvider.fromHoconFile`. It requires specifying the file path as a `java.io.File` object. ```Scala ConfigProvider.fromHoconFile(new java.io.File("fileapth")) ``` -------------------------------- ### Load Configuration from HOCON String in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This example illustrates how to read configuration from a HOCON formatted string. It defines a `SimpleConfig` case class and uses `ConfigProvider.fromHoconString` to parse the HOCON content, demonstrating both object-style and key-value pair HOCON syntax. ```Scala import zio.config.typesafe._ import zio.config.magnolia._ ``` ```Scala case class SimpleConfig(port: Int, url: String, region: Option[String]) val automaticDescription = deriveConfig[SimpleConfig] val hoconSource = ConfigProvider.fromHoconString( """ { port : 123 url : bla region: useast } """ ) val anotherHoconSource = ConfigProvider.fromHoconString( """ port=123 url=bla region=useast """ ) hoconSource.load(deriveConfig[SimpleConfig]) // yielding SimpleConfig(123,bla,Some(useast)) ``` -------------------------------- ### Map Configuration Keys with `mapKey` Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet demonstrates how to transform configuration keys using the `mapKey` function available on a `Config` descriptor. It shows an example of converting all derived configuration keys to uppercase, providing flexibility in matching configuration sources. ```scala // mapKey is just a function in `Config` that pre-existed val config = deriveConfig[Config].mapKey(_.toUpperCase) ``` -------------------------------- ### Handle Alternative Configurations with ZIO Config orElseEither and Constant Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This example illustrates the use of `Config.constant` to define fixed configuration values and `Config.orElseEither` to provide fallback options. It shows how to define a sealed trait `Greeting` and use `orElseEither` to merge two constant configurations, effectively choosing between 'Hello' and 'Bye' based on the configuration source. ```scala import zio.config._ sealed trait Greeting case object Hello extends Greeting case object Bye extends Greeting val configSource = ConfigProvider.fromMap(Map("greeting" -> "Hello")) val config: Config[Greeting] = Config.constant("Hello").orElseEither(Config.constant("Bye")).map(_.merge) ``` -------------------------------- ### ZIO Config ReadError Structure Example Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This section describes the structure of `ReadError` in ZIO Config, which accumulates misconfigurations. It explains how `AndErrors` are represented in parallel lines and `OrErrors` sequentially, providing a visual example of a complex `ReadError` output. ```APIDOC ReadError: ╥ ╠══╦══╗ ║ ║ ║ ║ ║ ╠─MissingValue ║ ║ ║ path: var2 ║ ║ ║ Details: value of type string ║ ║ ║ ║ ║ ╠─MissingValue path: envvar3 ║ ║ ║ path: var3 ║ ║ ║ Details: value of type string ║ ║ ║ ║ ║ ▼ ║ ║ ║ ╠─FormatError ║ ║ cause: Provided value is wrong, expecting the type int ║ ║ path: var1 ║ ▼ ▼ ``` -------------------------------- ### Document ZIO Config Case Classes with @describe Annotation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This example illustrates using the `@describe` annotation from `zio.config.magnolia` to add a description to an entire case class. This description is then automatically associated with the configuration, similar to manually adding documentation using `??`. ```scala import zio.config.magnolia.describe @describe("This config is about aws") case class Aws(region: String, dburl: DbUrl) case class DbUrl(value: String) ``` -------------------------------- ### Load Configuration from XML String in Scala (Experimental) Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This example illustrates how to read configuration from an XML string using the experimental `zio-config-xml` module. It defines nested case classes for the configuration structure and then parses an XML string using `ConfigProvider.fromYamlString` (note: this might be a typo in the original source, as `fromXmlString` would be expected). It highlights the current limitations of the XML parser. ```Scala import zio.config.xml.experimental._ import zio.Config final case class Configuration(aws: Aws, database: Database) object Configuration { val config: Config[Configuration] = Aws.config.nested("aws").zip(Database.config.nested("database")).to[Configuration].nested("config") final case class Aws(region: String, account: String) object Aws { val config: Config[Aws> = Config.string("region").zip(Config.string("account")).to[Aws] } final case class Database(port: Int, url: String) object Database { val config: Config[Database] = Config.int("port").zip(Config.string("url")).to[Database] } } val config = s""" |<config> | <aws region="us-east" account="personal"></aws> | <database port="123" url="some url"></database> |</config> | |""".stripMargin val parsed = ConfigProvider.fromYamlString(config).load(Configuration.config) ``` -------------------------------- ### Defining Config with Refined Types for Basic Validation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-validations.md This example shows how to define a `Config` for a `Jdbc` case class where `username` and `password` are `NonEmptyString` types from `eu.timepit.refined`. It demonstrates using `refineType` to apply validations and loading the configuration with `ConfigProvider`. ```scala import eu.timepit.refined.types.string.NonEmptyString case class Jdbc(username: NonEmptyString, password: NonEmptyString) val jdbc: Config[Jdbc] = (refineType[NonEmptyString]("username") zip refineType[NonEmptyString]("password")).to[Jdbc] ConfigProvider.fromMap(Map("username" -> "", "password" -> "")).load(jdbc) ``` -------------------------------- ### Apply Scalaz/Cats Typeclasses with ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/integrations.md Illustrates how `zio-config` provides instances for `Config` to work seamlessly with typeclasses like `Applicative` and `Monoid` from `Scalaz` (or `Cats`). This example shows a generic `add` function that operates on any effect type `F[_]` and monoidal type `A`, demonstrating how `Config` can participate in such polymorphic operations, simplifying configuration value aggregation. ```scala import _root_.scalaz._, Scalaz._ import zio.config.scalaz.instances._ // Across the application, there can be various effect types, but there is only one addition! def add[F[_]: Applicative, A: Monoid](primary: F[A], secondary: F[A]): F[A] = primary.<*>(Applicative[F].map(secondary)(secondary => (primary: A) => primary.mappend(secondary))) // Now even `Config` can take part in this addition given the values of config parameters should be Monoid, // instead of using native `zip` and separately implementing addition for various types val configResult = add(Config.int("marks1"), Config.int("marks2"))) ConfigProvider.fromMap(Map("marks1" -> "10", "marks2" -> "20")).load(configResult) // returns 30 ``` -------------------------------- ### Deriving Refined Config from Existing ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-validations.md This example demonstrates the composable nature of `zio-config` by showing how to apply a `Refined` validation to an already derived `Config`. It specifically applies a `Size` predicate to a `List[MyConfig]` to ensure the list contains more than two elements. ```scala import eu.timepit.refined._, api._, numeric._, collection._ import zio.config.magnolia.deriveConfig case class MyConfig(url: String, port: Int) val configs: Config[List[MyConfig]] = Config.listOf("databases", deriveConfig[MyConfig]) // A list of database configs, such that size should be greater than 2. val databaseList: Config[Refined[List[MyConfig], Size[Greater[W.`2`.T]]]] = refine[Size[Greater[W.`2`.T]]](configs) ``` -------------------------------- ### Integrate PureConfig with HOCON and Sealed Traits Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This example illustrates ZIO Config's built-in support for PureConfig, specifically for handling HOCON files with `type` labels for sealed traits (coproducts). It defines a sealed trait `X` with case classes `A` and `B`, and shows how to load an `AppConfig` containing `X` from a HOCON string using `ConfigProvider.fromHoconString` and `deriveConfig` with `@nameWithLabel("type")`. ```scala import zio.config._, typesafe._, magnolia._ @nameWithLabel("type") sealed trait X case class A(name: String) extends X case class B(age: Int) extends X case class AppConfig(x: X) val str = s""" x : { type = A name = jon } """ ConfigProvider.fromHoconString(str).load(deriveConfig[AppConfig]) ``` -------------------------------- ### Customize Field Names in ZIO Config Derivation with @name Annotation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This example demonstrates how to use the `@name` annotation from `zio.config.derivation.name` to specify a custom name for a case class or field. This allows the HOCON key to differ from the Scala identifier, providing flexibility in configuration naming. ```scala import zio.config.derivation.name @name("detailsWrapped") case class DetailsWrapped(detail: Detail) extends X ``` -------------------------------- ### Provide Custom `DeriveConfig` Instance for External Types in ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This example shows how to provide an implicit `DeriveConfig` instance for types that `zio-config-magnolia` cannot automatically derive (e.g., `AwsRegion` from an external library). This custom instance allows `deriveConfig` to successfully compile and work with case classes containing such types by mapping them from a known derivable type (like `String`). ```scala import zio.config.magnolia._ implicit val awsRegionConfig: DeriveConfig[Aws.Region] = DeriveConfig[String].map(string => AwsRegion.from(string)) ``` -------------------------------- ### Generate Configuration Documentation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet illustrates how to generate documentation for a `Config` descriptor. `generateDocs(myConfig)` creates automatic documentation, while adding `??` operators to fields allows for custom descriptions, which can then be formatted into a GitHub Flavoured Markdown table. ```scala generateDocs(myConfig) //Creates documentation (automatic) val betterConfig = (string("LDAP") ?? "Related to auth" zip int("PORT") ?? "Database port" zip string("DB_URL") ?? "url of database" ).to[MyConfig] generateDocs(betterConfig).toTable.toGithubFlavouredMarkdown ``` -------------------------------- ### Define Basic Configuration Structure in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This snippet demonstrates how to define a simple case class to represent application configuration and how to create a `Config` object from it using `zio-config`'s combinators. It also shows the necessary imports for `zio-config` and `magnolia`. ```Scala import zio._, Config._, ConfigProvider._ import zio.config._, magnolia._ ``` ```Scala case class MyConfig(ldap: String, port: Int, dburl: String) ``` ```Scala val myConfig = (string("LDAP") zip int("PORT") zip string("DB_URL")).to[MyConfig] // val automatedConfig = deriveConfig[MyConfig]; using zio-config-magnolia ``` -------------------------------- ### Import ZIO Config Core Dependencies Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet imports necessary classes and objects from the `zio.IO`, `zio.config`, and `zio.ConfigProvider` packages. These imports are fundamental for defining and loading configurations in ZIO applications. ```scala import zio.IO import zio.config._ import zio.ConfigProvider import zio.Config, Config._ ``` -------------------------------- ### Manually Describe MyConfig Configuration Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet demonstrates how to manually create a `Config` descriptor for the `MyConfig` case class. It uses `string` and `int` combinators to define how each field maps to environment variables or configuration sources, and then uses `.to[MyConfig]` to map them to the case class. ```scala val myConfig: Config[MyConfig] = (string("LDAP") zip int("PORT") zip string("DB_URL")).to[MyConfig] ``` -------------------------------- ### Manually Describe Tupled Configuration Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet shows how to create a `Config` descriptor that results in a tuple instead of a case class. It uses the same `string` and `int` combinators, demonstrating flexibility in how configuration values can be aggregated. ```scala val myConfigTupled: Config[(String, Int, String)] = (string("LDAP") zip int("PORT") zip string("DB_URL")) ``` -------------------------------- ### Define MyConfig Case Class Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This defines a simple Scala case class `MyConfig` which represents the structure of the application's configuration. It includes fields for LDAP, port, and database URL, demonstrating a typical configuration data model. ```scala case class MyConfig(ldap: String, port: Int, dburl: String) ``` -------------------------------- ### Load Configuration from YAML String in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This snippet shows the necessary import for YAML support and indicates the use of `ConfigProvider.fromYamlString` for loading configurations from YAML formatted strings. ```Scala import zio.config.yaml._ ConfigProvider.fromYamlString ``` -------------------------------- ### Load Configuration with Automatic Derivation using ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This snippet shows how to load the `MyConfig` using the `deriveConfig` macro provided by `zio-config-magnolia` with the previously defined HOCON sources. It demonstrates that the automatic derivation successfully parses and maps the HOCON values to the corresponding Scala case class instances. ```scala // Let's try automatic derivation aHoconSource.load(deriveConfig[MyConfig]) // res0: Right(MyConfig(A)) bHoconSource.load(deriveConfig[MyConfig]) // res0: Right(MyConfig(B)) cHoconSource.load(deriveConfig[MyConfig]) // res0: Right(MyConfig(C)) dHoconSource.load(deriveConfig[MyConfig]) // res0: Right(MyConfig(DetailsWrapped(Detail("ff", "ll", Region("strath", "syd"))))) ``` -------------------------------- ### Manual ZIO Config Definition Equivalent to @describe Annotation (Class) Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This code provides the manual ZIO Config definition that achieves the same documentation effect as applying the `@describe` annotation to a case class. It explicitly zips string configurations for `region` and `dburl`, maps `dburl` to `DbUrl`, and then adds a description to the entire `Aws` configuration. ```scala string("region").zip(string("dburl").to[DbUrl]).to[Aws] ?? "This config is about aws" ``` -------------------------------- ### Load Configuration from Indexed Map in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This snippet demonstrates how to load a complex configuration, including lists and nested objects, from a flat `Map` using indexed keys. It defines `Department`, `Employee`, and `Config` case classes and shows how `ConfigProvider.fromMap` can handle such structures, including representing empty lists with `<nil>`. ```Scala import zio.config._, magnolia._ final case class Department(name: String, block: Int) final case class Employee(departments: List[Department], name: String) final case class Config(employees: List[Employee]) val map = Map( "employees[0].name" -> "jon", "employees[0].departments[0].name" -> "science", "employees[0].departments[0].block" -> "10", "employees[0].departments[1].name" -> "maths", "employees[0].departments[2].block" -> "11", "employees[1].name" -> "foo", "employees[1].departments" -> "<nil>" ) ConfigProvider.fromMap(map).load(derivedConfig[Config]) ``` -------------------------------- ### Apply Kebab Case Mapping to ZIO Config Derived Keys Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This snippet shows how to apply a global key mapping, specifically `toKebabCase`, to the automatically derived configuration. This transforms field names (e.g., `firstName`) into their kebab-case equivalents (e.g., `first-name`) when parsing HOCON, aligning with common configuration conventions. ```scala import zio.config._ deriveConfig[MyConfig].mapKey(toKebabCase) ``` -------------------------------- ### Define and Load Indexed Employee Configuration in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/read-from-various-sources.md This Scala code snippet demonstrates how to define a configuration for a list of `Employee` objects from a flat `Map` where keys represent nested and indexed paths. It uses `zio-config`'s `ConfigProvider.fromMap` to create a provider and `Config.listOf` with `deriveConfig` to parse the indexed data into a strongly-typed list. ```scala import zio.config._, magnolia._ final case class Employee(age: Int, name: String) val map = Map( "department.employees[0].age" -> "10", "department.employees[0].name" -> "foo", "department.employees[1].age" -> "11", "department.employees[1].name" -> "bar", "department.employees[2].age" -> "12", "department.employees[2].name" -> "baz" ) val provider = ConfigProvider.fromMap(map) val config = Config.listOf("employees", deriveConfig[Employee]).nested("department") val result = provider.load(config) ``` -------------------------------- ### Combine Multiple Configurations with ZIO Config collectAll Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet demonstrates how to use `Config.collectAll` to combine a list of individual configurations into a single configuration that yields a list of parsed values. It defines a `Variables` case class and constructs configurations for multiple groups, then collects them into a single configuration for a list of `Variables`. ```scala import zio.config._ final case class Variables(variable1: Int, variable2: Option[Int]) val listOfConfig: List[Config[Variables]] = List("GROUP1", "GROUP2", "GROUP3", "GROUP4") .map(group => (Config.int(s"${group}_VARIABLE1") zip Config.int(s"${group}_VARIABLE2").optional).to[Variables]) val configOfList: Config[List[Variables]] = Config.collectAll(listOfConfig.head, listOfConfig.tail: _*) ``` -------------------------------- ### Importing ZIO Config Refined Modules Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-validations.md This snippet demonstrates the necessary imports to use `zio-config` with the `zio-config-refined` module, enabling automatic validations for configuration parameters. ```scala import zio.Config import zio.ConfigProvider import zio.config._, refined._ ``` -------------------------------- ### Import ZIO Config and Magnolia for Automatic Derivation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This snippet imports the required ZIO Config modules, including `zio.config.magnolia`, which provides the automatic derivation capabilities. It also imports `X._` to make the previously defined configuration types easily accessible. ```scala // Setting up imports import zio._ import zio.config._, import zio.config.typesafe._ import zio.config.magnolia._ import X._ ``` -------------------------------- ### Load Enumeratum Enum with ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/integrations.md Demonstrates how to integrate `zio-config` with `enumeratum` to load enum values directly from a configuration source. It defines a `Greeting` enum and shows how to use `ConfigProvider` and `zio.config.enumeratum._` to load a `Greeting` value from a map-based configuration. ```scala sealed trait Greeting extends EnumEntry object Greeting extends Enum[Greeting] { val values = findValues case object Hello extends Greeting case object GoodBye extends Greeting case object Hi extends Greeting case object Bye extends Greeting } // Load using zio-config import zio.config.enumeratum._ val mapProvider = ConfigProvider.fromMap(Map( "greeting" -> "Hello" )) val config = `enum`(Greeting).nested("greeting") val pgm: IO[Error, Greeting] = mapProvider.load(config) // Returns Hello ``` -------------------------------- ### Document ZIO Config Case Class Fields with @describe Annotation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This snippet demonstrates how to apply the `@describe` annotation to individual fields within a case class. This allows for field-specific documentation, providing more granular descriptions for each configuration parameter. ```scala case class Aws(@describe("AWS region") region: String, dburl: DbUrl) ``` -------------------------------- ### Add ZIO Config Core Dependency (Scala) Source: https://github.com/zio/zio-config/blob/series/4.x/README.md This snippet demonstrates how to add the core `zio-config` library as a dependency in a Scala `build.sbt` file. Replace `<version>` with the desired library version to include it in your project. ```scala libraryDependencies += "dev.zio" %% "zio-config" % "<version>" ``` -------------------------------- ### Define HOCON Configuration Sources for ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md These code blocks demonstrate how to create `ConfigProvider` instances from various HOCON string configurations. Each `val` represents a different configuration scenario (simple values A, B, C, and a complex nested structure for `DetailsWrapped`), which will be used to test the automatic derivation. ```scala // Defining different possibility of HOCON source val aHoconSource = ConfigProvider .fromHoconString("x = A") ``` ```scala val bHoconSource = ConfigProvider .fromHoconString("x = B") ``` ```scala val cHoconSource = ConfigProvider .fromHoconString("x = C") ``` ```scala val dHoconSource = ConfigProvider .fromHoconString( s""" | x { | DetailsWrapped { | detail { | firstName : ff | lastName : ll | region { | city : syd | suburb : strath | } | } | } |} |""".stripMargin ) ``` -------------------------------- ### Scala 3 Config Derivation using `derives` Keyword Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md Explains how to leverage Scala 3's `derives` keyword to automatically derive `zio.Config` typeclasses. This simplifies the process by removing the need for explicit implicit or given declarations, requiring an import from `zio.config.magnolia.*`. ```scala import zio.config.magnolia.* import zio.{Config, ZIO} sealed trait A case class B(x: String) extends A case class C(y: String) extends A case class MyConfig(a: A) derives Config // And then simply summon the `Config[MyConfig]` instance as you would normally: val cfg = ZIO.config[MyConfig] ``` -------------------------------- ### Implicit Derivation for Owned Types in Scala Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md Demonstrates the recommended placement for implicit instances when dealing with types owned by the user. The best practice is to place the implicit definition within the companion object of the type. ```scala final case class MyAwsRegion(value: AwsRegion) object MyAwsRegion { implicit val awsRegionDescriptor: DeriveConfig[MyAwsRegion] = DeriveConfig[String] .map( string => MyAwsRegion(AwsRegion.from(string)) ) ?? "value of type AWS.Region" } ``` -------------------------------- ### Automatically Derive Configuration with Magnolia Source: https://github.com/zio/zio-config/blob/series/4.x/docs/dive-into-zio-config.md This snippet showcases the automatic configuration derivation feature using `zio-config-magnolia`. By importing `zio.config.magnolia._`, the `deriveConfig` macro can automatically generate a `Config` descriptor for `MyConfig` based on its field names and types, reducing boilerplate. ```scala import zio.config._ import zio.config.magnolia._ val myConfigAutomatic = deriveConfig[MyConfig] ``` -------------------------------- ### Manual ZIO Config Definition Equivalent to @describe Annotation (Field) Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This code provides the manual ZIO Config definition that achieves the same field-level documentation effect as applying the `@describe` annotation to a case class field. It explicitly adds a description to the `region` string configuration before zipping it with `dburl`. ```scala (string("region") ?? "AWS region" zip string("dburl").to[DbUrl]).to[Aws] ?? "This config is about aws" ``` -------------------------------- ### Load Scalaz/Cats Specific Datatypes with ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/integrations.md Demonstrates `zio-config`'s capability to load specific datatypes from `Scalaz` (and `Cats`) libraries. This snippet shows how to define a `Config` for `Scalaz.Maybe[Int]`, allowing optional integer values to be parsed from configuration. ```scala import zio.config.scalaz._ import _root_.scalaz.Maybe val config: Config[Maybe[Int]] = maybe(Config.int("age")) ``` -------------------------------- ### Pure-Config Integration with @nameWithLabel Annotation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md Demonstrates `zio-config`'s inbuilt support for `pure-config`'s convention of using a `type` label in HOCON files to annotate coproducts. By using `@nameWithLabel("type")` on a sealed trait, `zio-config` can correctly parse such configurations. ```scala import zio.config._, typesafe._, magnolia._ @nameWithLabel("type") sealed trait X case class A(name: String) extends X case class B(age: Int) extends X case class AppConfig(x: X) val str = s""" x : { type = A name = jon } """ read(deriveConfig[AppConfig] from ConfigProvider.fromHoconString(str)) ``` -------------------------------- ### Automatic Derivation of Refined ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-validations.md This snippet showcases how `zio-config` can automatically derive configurations for case classes containing `Refined` types. It defines a `RefinedProd` case class with various refined fields and demonstrates loading configuration values from a map using `ConfigProvider` and `deriveConfig`. ```scala import zio.ConfigProvider import eu.timepit.refined.W import eu.timepit.refined.api.Refined import eu.timepit.refined.collection.{ NonEmpty, Size } import zio.config.magnolia.deriveConfig object RefinedReadConfig extends App { case class RefinedProd( ldap: Refined[String, NonEmpty], port: Refined[Int, GreaterEqual[W.`1024`.T]], dbUrl: Option[Refined[String, NonEmpty]] ) val configMap = Map( "LDAP" -> "ldap", "PORT" -> "1999", "DBURL" -> "ddd" ) val result = ConfigProvider.fromMap(configMap).load(deriveConfig[RefinedProd].mapKey(_.toUpperCase)) // RefinedProd(ldap,1999,Some(ddd)) } ``` -------------------------------- ### Customizing Configuration Keys with mapKey Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md Shows how to modify keys in a derived configuration using the `mapKey` function. This function, available on `Config` instances, allows transforming key names, such as converting them to uppercase. ```scala // mapKey is just a function in `Config` that pre-existed val config = deriveConfig[Config].mapKey(_.toUpperCase) ``` -------------------------------- ### Define ZIO Config Data Structures for Automatic Derivation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This Scala code defines the necessary data structures (`sealed trait X`, `case objects`, `case classes`, and `MyConfig`) that `zio-config-magnolia` uses to automatically derive configuration readers. These structures represent the shape of the configuration expected from sources like HOCON. ```scala sealed trait X object X { case object A extends X case object B extends X case object C extends X case class DetailsWrapped(detail: Detail) extends X case class Detail(firstName: String, lastName: String, region: Region) case class Region(suburb: String, city: String) } case class MyConfig(x: X) ``` -------------------------------- ### Scala 3 Autoderivation: Case Class with @name Annotation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md Demonstrates how to use the `@name` annotation on a case class within a sealed trait hierarchy in Scala 3. This allows customizing the key name for that specific case class in the configuration source. ```scala sealed trait A @name("b") case class B(x: String) extends A case class C(y: String) extends A case class Config(a: A) ``` ```json { "a" : { "b" : { "x" : "abc" } } } } ``` -------------------------------- ### Directly Applying Refined Predicates to ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-validations.md This snippet illustrates two ways to apply `Refined` predicates directly to `zio.Config` types. It shows using `refineType` with a pre-defined refined type alias and `refine` to specify the base type and predicate separately, offering flexibility in validation definition. ```scala import eu.timepit.refined._, api._, string._, collection._ type NonEmptyString = String Refined NonEmpty val refinedConfig: Config[NonEmptyString] = refineType[NonEmptyString]("USERNAME") // Another way of doing it is val urlConfig: Config[Refined[String, Url]] = refine[String, Url]("URL") // refineType takes a fully formed type (String Refined NonEmpty) where as refine allows you to play with the predicate directly (NonEmpty) ``` -------------------------------- ### Scala 3 Autoderivation: Sealed Trait with @name Annotation Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md Shows how applying a `@name` annotation to a sealed trait in Scala 3 autoderivation includes the sealed trait's name as part of the configuration source. This is rarely used but provides explicit control over the hierarchy. ```scala @name("aaaaa") sealed trait A case class B(x: String) extends A case class C(y: String) extends A case class Config(a: A) ``` ```json { "a" : { "aaaaa" : "B" : { "x" : "abc" } } } } ``` -------------------------------- ### Provide Custom `DeriveConfig` Instance for Value Classes in ZIO Config Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md This snippet demonstrates how to define an implicit `DeriveConfig` instance for a custom value class (`AwsRegion`). This ensures that value classes are correctly handled during automatic configuration derivation, allowing them to be used seamlessly within automatically derived configurations. ```scala import zio.config.magnolia._ final case class AwsRegion(value: String) extends AnyVal { override def toString: String = value } object AwsRegion { implicit val descriptor: DeriveConfig[AwsRegion] = DeriveConfig[String].map(AwsRegion(_)) } ``` -------------------------------- ### Scala 3 Autoderivation: Sealed Trait Default Behavior Source: https://github.com/zio/zio-config/blob/series/4.x/docs/automatic-derivation-of-config.md Illustrates the default behavior of Scala 3 autoderivation for sealed traits. By default, the sealed trait's name is skipped in the configuration source, and only the case class name and its fields are included. ```scala sealed trait A case class B(x: String) extends A case class C(y: String) extends A case class Config(a: A) ``` ```json { "a" : { "B" : { "x" : "abc" } } } } // or a.B.x="abc", if your source is just property file ```