Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-environment

Environment files for Pudu: load .env variables safely with layered files, discovery, expansion, typed reads, and secrets kept out of every message

0.1.0Apache-2.01

InstallClose

Source.pudu

Pudu48 lines1.6 KB

GitHub ↗
1/** @Environment.Source.Module — where one environment file comes from */2module PuduLangEnvironment.Source34import Std.Io as Io5import PuduLangEnvironment.Domain.Encoding as Encoding6import PuduLangEnvironment.Domain.Parser as Parser7import PuduLangEnvironment as Environment89/** @Environment.Source.Source — a file path, text, or bytes */10export type Source11  = File(Str)12  | Text(Str, Str)13  | Data(Str, Bytes)1415/// The name a problem gives the source: its path, or the label it was given.16export fn label(source: &Source) -> Str {17  match source {18    case File(path) => path19    case Text(named, _) => named20    case Data(named, _) => named21  }22}2324/// The source's lines, split on `\n` or `\r\n`, after decoding its bytes in `encoding` unless a25/// byte-order mark says otherwise.26export fn lines(source: &Source, encoding: Encoding.Encoding) -> Result[Array[Str], Environment.Problem] {27  match source {28    case File(path) => {29      if path.trim().isEmpty() { return Err(Environment.BlankPath) }30      if !Io.exists(path) { return Err(Environment.MissingFile(path)) }31      match Io.readAllBytes(path) {32        case Ok(data) => decoded(path, &data, encoding)33        case Err(reason) => Err(Environment.Unreadable(path, show(reason)))34      }35    }36    case Text(_, text) => Ok(Parser.lines(text))37    case Data(named, data) => decoded(named, &data, encoding)38  }39}4041/// The decoded lines of bytes, or the encoding they failed.42fn decoded(named: Str, data: &Bytes, encoding: Encoding.Encoding) -> Result[Array[Str], Environment.Problem] {43  match Encoding.decode(data, encoding) {44    case Some(text) => Ok(Parser.lines(text))45    case None => Err(Environment.Undecodable(named, Encoding.name(&encoding)))46  }47}48