Skip to main content

src/internal/config.gleam

import filepath
import gleam/dict
import gleam/result
import simplifile
import tom

pub type Configuration {
  Configuration(root: String, iconset: String, module: String)
}

pub type ConfigurationError {
  FileError(simplifile.FileError)
  TomlError(tom.ParseError)
}

pub fn get(
  default_iconset: String,
  default_module: String,
) -> Result(Configuration, ConfigurationError) {
  let root = find_root("./")

  filepath.join(root, "gleam.toml")
  |> fn(file) { simplifile.read(file) |> result.map_error(FileError) }
  |> result.try(fn(content) {
    tom.parse(content) |> result.map_error(TomlError)
  })
  |> result.map(fn(toml) {
    tom.get_table(toml, ["tools", "iconify_lustre"])
    |> result.unwrap(dict.new())
  })
  |> result.map(fn(table) {
    Configuration(
      root:,
      iconset: get_string(table, "iconset", default_iconset),
      module: get_string(table, "module", default_module),
    )
  })
}

fn find_root(path: String) -> String {
  case simplifile.is_file(filepath.join(path, "gleam.toml")) {
    Ok(True) -> path
    Ok(False) | Error(_) -> find_root(filepath.join(path, "../"))
  }
}

fn get_string(
  toml: dict.Dict(String, tom.Toml),
  key: String,
  default: String,
) -> String {
  tom.get_string(toml, [key]) |> result.unwrap(default)
}