Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.43.0

0.43.0 / src / support / host_tools.lucb

#==============================================================================================
#
#   host_tools - Running host tools inside an owned workspace
#
#   DESCRIPTION:
#       Host tools run with private child state. Generated filenames stay relative ASCII names
#       even when the output directory is Unicode. Storage belongs to the compiler command
#       arena; close releases filesystem state.
#
#==============================================================================================

import c
import interop
import luce_std.files
import luce_std.paths
import platform
import luce_std.process
import strings
import support.in_arena
import thread

## A temporary directory a host tool runs in, removed when closed.
pub struct Workspace:
    let directory: str

    ## Create the workspace beside `output`'s directory.
    pub func init(output: str) -> !:
        let parent = try strings.copy(paths.directory(output))
        let absolute = try in_arena.canonical((c.str)parent)
        self.directory = try in_arena.temporary_directory((c.str)absolute)

    ## The workspace directory.
    pub func path() -> str:
        return self.directory

    ## Remove the workspace and everything in it.
    pub func close() -> !:
        try files.remove_tree((c.str)self.directory)

    ## Remove the workspace, ignoring failure.
    pub func destroy():
        self.close() catch failure:
            _ = failure

## Move a produced file out of the workspace to `destination`. On Windows a file that
## was just written or run is often held open for a moment by another process (a virus
## scan, the indexer, the previous program still closing), and replacing it fails until
## that handle closes: the move is tried again every 25 ms for two and a half seconds
## before its failure stands.
pub func publish(source: str, destination: str) -> !:
    let target = try strings.copy(destination)
    var tries = 0
    while true:
        files.rename((c.str)source, (c.str)target, true) catch failure:
            if platform.windows and tries < 100:
                tries += 1
                thread.sleep(25)
                continue
            error(failure.code, failure.message)
        return

## Rebase only filesystem operands. Flags, library names and framework names are
## preserved. Existing external inputs become absolute before changing child cwd.
func operand(text: str, directory: str) -> str!:
    if text == directory:
        return "."
    if strings.starts_with(text, directory) and text.length > directory.length and paths.separator(text.bytes[directory.length]):
        return try strings.copy((str)text.bytes[directory.length + 1..])
    let terminated = try strings.copy(text)
    if not paths.is_absolute(text) and files.exists((c.str)terminated):
        return try in_arena.canonical((c.str)terminated)
    return terminated

## GCC's Windows temporary-path API expands even "." through the ANSI code page.
## Keep its intermediates beside the relative output instead, including collect2's
## constructor files. The workspace owner removes all of them after publication.
pub func run_compiler(program: c.str, arguments: const c.str[], directory: str) -> interop.Owned[process.Completed]!:
    if platform.windows:
        let selected = try new c.str[arguments.length + 1] ---
        for index in 0..<arguments.length:
            selected[index] = arguments[index]
        selected[arguments.length] = "-save-temps=obj"
        return try run(program, selected, directory)
    return try run(program, arguments, directory)

## Run `program` with `directory` as its working directory, rebasing filesystem operands
## and confining its temporaries there; what it left behind, which the caller releases
## (`process.run`).
pub func run(program: c.str, arguments: const c.str[], directory: str = "") -> interop.Owned[process.Completed]!:
    if directory.length == 0:
        return try process.run(program, arguments)
    let converted = try new c.str[arguments.length] ---
    for index in 0..<arguments.length:
        let text = (str)arguments[index]
        if strings.starts_with(text, "-I") or strings.starts_with(text, "-L"):
            let path = try operand((str)text.bytes[2..], directory)
            let buffer = try new u8[path.length + 3] ---
            converted[index] = (c.str)try strings.format(buffer, f"{(str)text.bytes[..<2]}{path}")
        elif text.length > 0 and text.bytes[0] == '-':
            converted[index] = arguments[index]
        else:
            converted[index] = (c.str)try operand(text, directory)
    let overrides: c.str[3] = ["TMPDIR=.", "TEMP=.", "TMP=."]
    # A bare tool name is resolved through PATH. Explicit relative executables
    # refer to the caller's directory, just like input files.
    let executable = try operand((str)program, directory) if paths.directory((str)program) != "." else (str)program
    let environment: const c.str[] = overrides
    return try process.run((c.str)executable, converted, (c.str)directory, environment)