simplification
Download
173 lines 6.2 KiBMoonScriptModified 2026-11-08 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
-- Some file utilities for searching for files recursively and using package.nomsupath
lpeg = require 'lpeg'
re = require 're'
Files = {}

-- Run a shell command, and return the lines it prints, or nil if it fails. The command
-- prints its exit status last, since in Lua 5.1 and LuaJIT, closing the pipe doesn't
-- say whether it failed.
run_cmd = (cmd)->
    f = io.popen(cmd..' 2>/dev/null; echo "$?"')
    lines = [line for line in f\lines!]
    f\close!
    return nil unless table.remove(lines) == "0"
    return lines

-- Quote text so the shell passes it to a command as a single argument
shell_quote = (text)-> "'"..text\gsub("'", "'\\''").."'"
        
_BROWSE_CACHE = {}

-- Source code that isn't on disk (like code that was run from text, or modules from a
-- custom loader) is kept in tables of sources, which map filenames to contents. Each
-- Nomsu instance has its own table of sources, which it registers here. The keys are
-- weak, so a table of sources is freed along with its instance.
_SPOOFED_FILES = {}
_SOURCES = setmetatable({[_SPOOFED_FILES]: true}, {__mode:'k'})
Files.add_sources = (sources)-> _SOURCES[sources] = true
find_source = (filename)->
    for sources in pairs(_SOURCES)
        if contents = sources[filename]
            return contents
Files.find_source = find_source

-- A new filename for code that doesn't come from a file
_anon_number = 0
Files.anonymous_filename = ->
    filename = "<anonymous file ##{_anon_number}>"
    _anon_number += 1
    return filename

-- Create a fake file (which lasts as long as the program)
Files.spoof = (filename, contents)->
    if not contents
        filename, contents = Files.anonymous_filename!, filename
    _SPOOFED_FILES[filename] = contents
    return filename

-- Read a file's contents
Files.read = (filename)->
    if contents = find_source(filename)
        return contents
    if filename == 'stdin' or filename == '-'
        contents = io.read('*a')
        Files.spoof('stdin', contents)
        Files.spoof('-', contents)
        return contents
    file = io.open(filename)
    return nil unless file
    contents = file\read("*a")
    file\close!
    return contents or nil

{:match, :gsub} = string

Files.exists = (path)->
    return true if find_source(path)
    return true if path == 'stdin' or path == '-'
    return true if run_cmd("test -e #{shell_quote(path)}")
    return false

Files.list = (path)->
    unless _BROWSE_CACHE[path]
        local files
        _BROWSE_CACHE[path] = if find_source(path) or path == 'stdin' or path == '-'
            {path}
        else run_cmd("find -L #{shell_quote(path)} -not -path '*/.*' -type f") or false
    return _BROWSE_CACHE[path]

Files.make_directory = (path)->
    run_cmd("mkdir #{shell_quote(path)}")

-- A quick (not cryptographic) hash of some text, used to tell whether a precompiled
-- .lua file is out of date with its .nom source
-- (Each byte is mixed in separately, so edits can't cancel each other out the way they
-- can with a weighted sum. Every step stays under 2^53, so it's the same on every Lua.)
Files.hash = (text)->
    {:byte} = string
    h = #text
    for i=1,#text
        h = (h * 31 + byte(text, i)) % 4294967291
    return ("%08x")\format(h)

ok, lfs = pcall(require, "lfs")
if ok
    raw_file_exists = (filename)->
        mode = lfs.attributes(filename, 'mode')
        return if mode == 'file' or mode == 'directory' or mode == 'link' then true else false
    Files.exists = (path)->
        return true if find_source(path)
        return true if path == 'stdin' or path == '-' or raw_file_exists(path)
        return false

    Files.list = (path)->
        unless _BROWSE_CACHE[path]
            _BROWSE_CACHE[path] = if find_source(path) or path == 'stdin' or path == '-'
                {path}
            else
                file_type, err = lfs.attributes(path, 'mode')
                switch file_type
                    when "file", "char device"
                        {path}
                    when "directory", "link"
                        files = {}
                        for subfile in lfs.dir(path)
                            continue if subfile == "." or subfile == ".."
                            for f in *(Files.list(path.."/"..subfile) or {})
                                files[#files+1] = f
                        files
                    else false
            -- Filter out any "./" prefix to standardize
            if _BROWSE_CACHE[path]
                for i,f in ipairs(_BROWSE_CACHE[path])
                    if f\match("^%./") then _BROWSE_CACHE[path][i] = f\sub(3)
        return _BROWSE_CACHE[path]

    Files.make_directory = lfs.mkdir
else
    unless run_cmd('find . -maxdepth 0')
        url = if jit
            'https://github.com/spacewander/luafilesystem'
        else 'https://github.com/keplerproject/luafilesystem'
        error "Could not find 'luafilesystem' module and couldn't run system command `find` (this might happen on Windows). Please install `luafilesystem` (which can be found at: #{url} or `luarocks install luafilesystem`)\n#{lfs}\npackage.cpath: #{package.cpath}", 0

line_counter = re.compile([[
    lines <- {| line (%nl line)* |}
    line <- {} (!%nl .)*
]], nl:lpeg.P("\r")^-1 * lpeg.P("\n"))

-- LINE_STARTS is a mapping from strings to a table that maps line number to character positions.
-- Lua never frees strings from weak tables, so this is emptied when it gets big.
_LINE_STARTS, _num_line_starts = {}, 0
Files.get_line_starts = (str)->
    if type(str) != 'string'
        str = tostring(str)
    if starts = _LINE_STARTS[str]
        return starts
    line_starts = line_counter\match(str)
    if _num_line_starts >= 100
        _LINE_STARTS, _num_line_starts = {}, 0
    _LINE_STARTS[str] = line_starts
    _num_line_starts += 1
    return line_starts

Files.get_line_number = (str, pos)->
    line_starts = Files.get_line_starts(str)
    -- Binary search for line number of position
    lo, hi = 1, #line_starts
    while lo <= hi
        mid = math.floor((lo+hi)/2)
        if line_starts[mid] > pos
            hi = mid-1
        else lo = mid+1
    return hi

Files.get_line = (str, line_no)->
    line_starts = Files.get_line_starts(str)
    start = line_starts[line_no]
    return unless start
    stop = line_starts[line_no+1]
    return unless stop
    return (str\sub(start, stop - 2))

return Files