#!/usr/bin/env nomsu -V2.5.5.5
#
    This file defines some actions that interact with the operating system and filesystem.

test:
    path of Nomsu file "lib/os.nom"
action [path of Nomsu file %filename]:
    lua> "for i,f in Files.walk(\%filename) do return f end"
    barf "Could not find file: \%filename"

action [sh> %cmd]:
    lua> ".."
        local result = io.popen(\%cmd)
        local contents = result:read("*a")
        result:close()
        return contents

test:
    read file "lib/os.nom"
action [read file %filename] (=lua "Files.read(\%filename)")

test:
    for file %f in "core": do nothing
compile [for file %f in %path %body] to (..)
    Lua ".."
        for i,\(%f as lua expr) in Files.walk(\(%path as lua expr)) do
            \(%body as lua statements)
            \(compile as (===next %f ===))
        end
        \(compile as (===stop %f ===))

compile [%expr for file %f in %path] to (..)
    Lua value ".."
        (function()
            local ret = list{}
            for i,\(%f as lua expr) in Files.walk(\(%path as lua expr)) do
                ret[#ret+1] = \(%expr as lua statements)
            end
            return ret
        end)()

action [..]
    write to file %filename %text, to file %filename write %text
    write %text to file %filename
..:
    assume (%filename != "stdin") or barf "Cannot write to stdin"
    lua> ".."
        local file = io.open(\%filename, 'w')
        file:write(\%text)
        file:close()

test:
    assume ((line number of 3 in "x\ny") == 2)
action [line number of %pos in %str] (=lua "Files.get_line_number(\%str, \%pos)")

test:
    assume ((line 2 in "one\ntwo\nthree") == "two")
action [line %line_num in %str] (=lua "Files.get_line(\%str, \%line_num)")

test:
    assume (source lines of \(this))
action [source lines of %tree]:
    %source = (%tree.source if (%tree is syntax tree) else %tree)
    %file = (read file %source.filename)
    return (..)
        (..)
            (line % in %file) for % in (line number of %source.start in %file) to (..)
                line number of %source.stop in %file
        ..joined with "\n"