Appearance
A script with files and programs
weft run runs a file as a program: build steps, data clean-ups, command-line tools. std/fs reads and writes files, std/process reads the arguments, standard input and environment, and runs other programs.
Count lines, write a report
tools/report.weft
weft
import { list, readText, writeText, stat, join, extname } from "std/fs"
import { args, stderr, exit } from "std/process"
import { log } from "std/log"
let dir = args()[0] ?? "."
if (try await stat(dir)) == null {
stderr(`${dir}: no such directory\n`)
exit(2)
}
let mut rows: string[] = []
for entry of try await list(dir) {
if entry.kind != "file" || extname(entry.name) != ".md" { continue }
let text = try await readText(join(dir, entry.name))
rows.push(`${entry.name}\t${text.split("\n").length}`)
}
try await writeText(join(dir, "report.tsv"), rows.join("\n") + "\n")
log(`${rows.length} files`)sh
weft run tools/report.weft docsEvery operation is async and fails with an FsError naming the path (code is NotFound, PermissionDenied, …). At a script's top level try passes it on, which ends the script with the error and exit code 1; try … else or two bindings (let text, err = try await readText(p)) handle it instead.
Run other programs
tools/release.weft
weft
import { run, spawn, stdin } from "std/process"
import { log } from "std/log"
// `run` waits for the end and gives the output; arguments go as they are (no shell).
let status = try await run("git", ["status", "--porcelain"])
if status.stdout.trim() != "" {
log("commit first:")
log(status.stdout)
}
// `spawn` gives the output as it comes, and the program's input.
let sort = try await spawn("sort", ["-r"])
for word of ["pear", "apple", "fig"] {
try await sort.write(`${word}\n`)
}
sort.closeStdin()
let mut out = ""
let mut piece = await sort.stdout()
while piece != null {
out += piece.toUtf8()
piece = await sort.stdout()
}
let exit = await sort.wait()
log(`${out.trim()} (exit ${exit.code})`)
// Lines typed (or piped) in, until the end of input.
let input = stdin()
let mut line = try await input.line()
while line != null {
log(line.toUpperCase())
line = try await input.line()
}Programs start without a shell, so a file name with spaces or ; in it is just an argument. run's options take a working directory, environment variables, input and a timeout. Both modules are capabilities: a package that uses them says so, and user code in std/sandbox can't import them. The reference: std/fs, std/process.