Current section

Files

Jump to
oaspec src oaspec internal util string_extra.gleam
Raw

src/oaspec/internal/util/string_extra.gleam

import gleam/list
import gleam/string
import gleam/string_tree.{type StringTree}
/// Type alias for StringTree used as a mutable string builder throughout codegen.
pub type StringBuilder =
StringTree
/// Create a new empty string builder.
pub fn new() -> StringTree {
string_tree.new()
}
/// Append a line to the string builder.
pub fn line(sb: StringTree, text: String) -> StringTree {
sb
|> string_tree.append(text)
|> string_tree.append("\n")
}
/// Append an indented line to the string builder.
pub fn indent(sb: StringTree, level: Int, text: String) -> StringTree {
let spaces = string.repeat(" ", level)
sb
|> string_tree.append(spaces)
|> string_tree.append(text)
|> string_tree.append("\n")
}
/// Append a blank line.
pub fn blank_line(sb: StringTree) -> StringTree {
sb
|> string_tree.append("\n")
}
/// Generate a file header with auto-generation notice.
pub fn file_header(version: String) -> StringTree {
new()
|> line("// Code generated by oaspec v" <> version <> ". DO NOT EDIT.")
|> blank_line()
}
/// Generate import statements.
pub fn imports(sb: StringTree, modules: List(String)) -> StringTree {
let sb =
list.fold(modules, sb, fn(sb, module) { sb |> line("import " <> module) })
sb |> blank_line()
}
/// Convert the string builder to a final string.
pub fn to_string(sb: StringTree) -> String {
string_tree.to_string(sb)
}
/// Join a list of strings with a separator.
pub fn join_with(items: List(String), separator: String) -> String {
string.join(items, separator)
}
/// Wrap a string in Gleam doc comment style.
pub fn doc_comment(sb: StringTree, text: String) -> StringTree {
case text {
"" -> sb
_ -> {
let lines = string.split(text, "\n")
list.fold(lines, sb, fn(sb, l) { sb |> line("/// " <> l) })
}
}
}