#! @file command.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains `std::process`, which starts other programs, and `command`, a #! program to start with its arguments, directory, variables, and standard #! streams, which starts it as a `child` to talk to, runs it to its end, or #! captures everything it writes. #! #! `std::process` is written once over `system`, which starts a program the #! way each system does, so it is the same everywhere. import std::io; import system; module std::process; # Bytes read from a child's output at a time, while capturing it. const capture_bytes: u64 = 16384; #! Where one of a started program's standard streams goes. pub enum stdio: u8 { inherit, #! The program's own. piped, #! A pipe, whose other end the child gives the program. none, #! Nothing: reading it ends at once, and writing goes nowhere. } #! A program to start, and what it is given, which can start any number of #! children, each the same way. #! #! The program is found as it is started: a name without a `/` in the #! directories of the `PATH` the child will have, as a shell finds it, and one #! with a `/` where it says, from where the child runs. Its first argument is #! the name as it is given here, and the arguments added follow. #! #! On Windows, a name holding a `\` too, or beginning with a drive, as `C:`, is #! where it says. The directories of `PATH` are split at `;`, and a name ending #! in none of the endings `PATHEXT` lists, as `.EXE` and `.CMD`, is tried with #! each of them in turn, as the system's shell tries it. The names of variables #! are the same whatever the case of their letters, as `Path` is `PATH`. #! #! A command owns all it gives a child. A file given to it, as by `output_to`, #! goes to the first child it starts, and starting that child closes the #! program's copy, so the child alone holds it. pub struct command { var _program: string; var _arguments: vector; var _directory: string; var _variables: vector; var _cleared: bool; var _streams: stdio[3]; var _set_input: bool; var _files: io::file[3]; } # A variable a command sets, or removes where `value` is `nothing`. struct setting { var name: string; var value: maybe; } #! Makes a command to start a program, with no arguments, in the program's own #! directory, with the program's own variables and standard streams. #! @param program The program's name, as `cc`, or its path, as `./build.sh`. #! @returns The command. pub def command::new(program: strview): command { return command { _program = string::from(program, nothing{}), _arguments = vector::::new(), _directory = string::new(nothing{}), _variables = vector::::new() }; } #! Adds an argument, after those added before. #! @param this The command. #! @param text The argument, which the program is given as it is, without #! being split or quoted. pub def command::argument(&mut this, text: strview): void { this._arguments.append(string::from(text, nothing{})); } #! Adds arguments, after those added before. #! @param this The command. #! @param texts The arguments, in order. pub def command::arguments(&mut this, texts: span): void { for text in texts { this._arguments.append(string::from(text, nothing{})); } } #! Sets the directory the program runs in, which is the program's own unless #! this is set. #! @param this The command. #! @param at The directory. pub def command::directory(&mut this, at: &path): void { this._directory.clear(); this._directory.append(at.span); } #! Gives the program a variable, in place of any of the name it would have. #! @param this The command. #! @param name The name of the variable, which holds no `=`. #! @param value Its value. pub def command::set_variable(&mut this, name: strview, value: strview): void { this.change(name, string::from(value, nothing{})); } #! Starts the program without a variable it would have. #! @param this The command. #! @param name The name of the variable. pub def command::remove_variable(&mut this, name: strview): void { this.change(name, nothing{}); } #! Starts the program with none of the program's variables, and only those set #! after this. #! @param this The command. pub def command::clear_variables(&mut this): void { this._variables.clear(); this._cleared = true; } #! Sets where the program's standard input comes from, which is the program's #! own unless this is set. #! @param this The command. #! @param how Where it comes from. pub def command::input(&mut this, how: stdio): void { this.stream(0, how); this._set_input = true; } #! Sets where the program's standard output goes, which is the program's own #! unless this is set. #! @param this The command. #! @param how Where it goes. pub def command::output(&mut this, how: stdio): void { this.stream(1, how); } #! Sets where the program's standard error goes, which is the program's own #! unless this is set. #! @param this The command. #! @param how Where it goes. pub def command::error(&mut this, how: stdio): void { this.stream(2, how); } #! Gives the program a file to read as its standard input, taking it over. #! @param this The command. #! @param file The file, which goes to the first child started. pub def command::input_from(&mut this, file: io::file): void { this._files[0] = move(file); this._set_input = true; } #! Gives the program a file to write its standard output to, taking it over. #! @param this The command. #! @param file The file, which goes to the first child started. pub def command::output_to(&mut this, file: io::file): void { this._files[1] = move(file); } #! Gives the program a file to write its standard error to, taking it over. #! @param this The command. #! @param file The file, which goes to the first child started. pub def command::error_to(&mut this, file: io::file): void { this._files[2] = move(file); } #! Starts the program, which runs beside this one. #! #! What the program has written to `io::output()` and `io::error_output()` is #! flushed first, where the child writes to the same place, so it comes before #! what the child writes. A child that reads the program's input does not see #! what `io::input()` has already read. #! @param this The command. #! @returns The child, running, or why it could not be started: #! `io_error::not_found` where the program is not found, which is #! known before anything starts, `io_error::permission_denied` where it #! may not be run, and `io_error::invalid` where a text the command #! holds has a zero in it, or a variable's name is empty or holds `=`. pub def command::spawn(&mut this): result { return this.start(false); } #! Starts the program, and waits for it to stop. #! @param this The command. #! @returns How it stopped, or why it could not be started, as `spawn` says. pub def command::run(&mut this): result { var started := this.start(false) else (why) { return why; }; return started.wait(); } #! Starts the program, and keeps everything it writes to its standard output #! and error until it stops. Both are read as they arrive, so a program that #! fills one while this waits on the other cannot stop both. The program is #! given nothing to read, unless its input was set. #! @param this The command. #! @returns How the program stopped, with what it wrote, which is what it gives #! for a program that failed too, or why it could not be started, as #! `spawn` says, or read. pub def command::capture(&mut this): result { var started := this.start(true) else (why) { return why; }; started._input.close(); var output := string::new(nothing{}); var error := string::new(nothing{}); val buffer := raw_allocate(capture_bytes); val read := read_both(&mut started, &mut output, &mut error, buffer); raw_release(buffer); if read is some(why) { return why; } val stopped := started.wait() else (why) { return why; }; return captured { status = stopped, output = move(output), error = move(error) }; } # Reads both outputs of a child as they arrive, until both end, giving why where # reading failed. def read_both(started: &mut child, output: &mut string, error: &mut string, buffer: *mut u8): maybe { var handles: system::fd[2]; var ready: bool[2]; while started._output.is_open || started._error.is_open { handles[0] = started._output.is_open ? started._output.handle : -1; handles[1] = started._error.is_open ? started._error.handle : -1; val polled := system::poll(span::::over((&handles) as *system::fd, 2), slice::::over((&mut ready) as *mut bool, 2)); if polled < 0 { return system::error_of(polled); } if ready[0] && read_into(&mut started._output, output, buffer) is some(why) { return why; } if ready[1] && read_into(&mut started._error, error, buffer) is some(why) { return why; } } return nothing{}; } # Reads what has arrived on a pipe into text, closing the pipe where it has # ended, and giving why where reading failed. def read_into(from: &mut io::file, into: &mut string, buffer: *mut u8): maybe { val count := from.read(slice::::over(buffer, capture_bytes)) else (why) { return why; }; if count == 0 { from.close(); return nothing{}; } into.append(span::::over(buffer as *u8, count)); return nothing{}; } # Sets where a stream goes, giving up a file given for it before. def command::stream(&mut this, which: u64, how: stdio): void { this._files[which].close(); this._streams[which] = how; } # Records a variable set, or removed where `value` is `nothing`, in place of # what was recorded of the name before. def command::change(&mut this, name: strview, value: maybe): void { for &mut each in this._variables { if same_name(each.name.span, name) { each.value = move(value); return; } } this._variables.append(setting { name = string::from(name, nothing{}), value = move(value) }); } # What the command records of a variable, where it records anything. def command::setting_of(&this, name: strview): maybe<&setting> { for &each in this._variables { if same_name(each.name.span, name) { return each; } } return nothing{}; } # Starts the program, with its streams as they are set, or with its output and # error piped and its input empty unless set, where `capturing`. def command::start(&mut this, capturing: bool): result { var found := this.find() else (why) { return why; }; var variables := this.environment() else (why) { return why; }; var arguments := vector::::new(); arguments.append(this._program.span); for &each in this._arguments { arguments.append(each.span); } var views := vector::::new(); for &each in variables { views.append(each.span); } # What the program has written comes first, where the child writes there too. if this.inherits(1, capturing) || this.inherits(2, capturing) { _ = io::output().flush(); _ = io::error_output().flush(); } # Each stream is the child's end of a pipe, the device that holds nothing, or # a file given, which all close once the child has started, as each of its # own; or it is the program's own, which is no file. var made := child {}; var given: io::file[3]; for which in 0u..3u { if this.connect(which, capturing, &mut given[which], &mut made) is error(why) { return why; } } val request := system::spawn_request { program = found.span, arguments = arguments.span, environment = views.span, directory = this._directory.span, input = given[0].is_open ? given[0].handle : 0, output = given[1].is_open ? given[1].handle : 1, error = given[2].is_open ? given[2].handle : 2 }; val id := system::spawn(&request); if id < 0 { return system::error_of(id); } made._id = id; made._running = true; return move(made); } # Whether a stream goes where the program's own does. def command::inherits(&this, which: u64, capturing: bool): bool { return !this.uses_file(which, capturing) && this.choice(which, capturing) == stdio::inherit; } # Whether a stream goes to the file given for it, which capturing passes over # for the outputs. def command::uses_file(&this, which: u64, capturing: bool): bool { return this._files[which].is_open && !(capturing && which != 0); } # Where a stream goes, where it goes to no file: capturing pipes both outputs, # and gives the child nothing to read unless its input was set. def command::choice(&this, which: u64, capturing: bool): stdio { if capturing && which != 0 { return stdio::piped; } if capturing && !this._set_input { return stdio::none; } return this._streams[which]; } # Gives the child what a stream goes to, as a file, which is not open where the # stream is the program's own, keeping the program's end of a pipe in the child. def command::connect( &mut this, which: u64, capturing: bool, given: &mut io::file, made: &mut child ): result { if this.uses_file(which, capturing) { given = move(this._files[which]); return; } val how := this.choice(which, capturing); if how == stdio::inherit { return; } if how == stdio::none { var device := path::parse(system::null_device) else (_) { return io_error::invalid; }; val flags := which == 0 ? open_flags::read : open_flags::write; given = io::file::open(&device, flags) else (why) { return why; }; return; } var ends := io::pipe::open() else (why) { return why; }; if which == 0 { given = move(ends.reading); made._input = move(ends.writing); return; } given = move(ends.writing); if which == 1 { made._output = move(ends.reading); return; } made._error = move(ends.reading); return; } # The variables the child gets, each as `NAME=value`: the program's, with the # command's changes, or only those set where the command cleared them. def command::environment(&this): result, io_error> { var made := vector::::new(); if !this._cleared { for each in system::environment() { var name_length := 0u; while name_length < each.length && each[name_length] != '=' { name_length++; } if this.setting_of(each.substr(0, name_length)) is some(_) { continue; } made.append(string::from(each, nothing{})); } } for &each in this._variables { if each.name.length == 0 || contains(each.name.span, '=') { return io_error::invalid; } if each.value is some(&value) { var text := string::copy_of(&each.name); text.append("="); text.append(value.span); made.append(move(text)); } } return move(made); } # The path of the program to start: as given, where the name holds a `/`, and # otherwise the first in the directories of the `PATH` the child will have that # is a file anyone may run. Windows finds it as `found` says. def command::find(&this): result { val name := this._program.span; if name.length == 0 { return io_error::invalid; } when os == windows { return this.found(name); } if contains(name, '/') { return string::from(name, nothing{}); } val search := this.search_path(); for directory in search.split(':') { var candidate := string::from(directory.length == 0 ? "." : directory, nothing{}); candidate.append("/"); candidate.append(name); if this.runnable(candidate.span) { return move(candidate); } } return io_error::not_found; } # The `PATH` the child will have, which is the command's own where it set one, # and otherwise the program's. def command::search_path(&this): strview { if this.setting_of("PATH") is some(&set) && set.value is some(&value) { return value.span; } return variable("PATH") else { return "/usr/local/bin:/usr/bin:/bin"; }; } # Whether a path, from where the child runs, is a file anyone may run. def command::runnable(&this, candidate: strview): bool { var at := string::new(nothing{}); var rooted := candidate.starts_with("/"); when os == windows { rooted = rooted || candidate.starts_with("\\") || (candidate.length > 1 && candidate[1] == ':'); } if this._directory.length != 0 && !rooted { at.append(this._directory.span); at.append("/"); } at.append(candidate); var info: file_info; return system::stat(at.span, &mut info) == 0 && info.kind == file_kind::regular && (info.permissions & 0o111) != 0; } when os == windows { # The path of the program to start, as Windows finds it: as given, where the # name holds a `/` or `\`, or begins with a drive, and otherwise the first in # the directories of the `PATH` the child will have that is a program. A name # ending in none of the endings `PATHEXT` lists is tried with each in turn, # where it is given as a path too, since the system adds none itself. def command::found(&this, name: strview): result { val endings := this.endings(); val ended := this.has_ending(name, &endings); if contains(name, '/') || contains(name, '\\') || (name.length > 1 && name[1] == ':') { for ending in endings.split(';') { if !ended && ending.length != 0 { var candidate := string::from(name, nothing{}); candidate.append(ending); if this.runnable(candidate.span) { return move(candidate); } } } return string::from(name, nothing{}); } val search := this.directories(); for listed in search.split(';') { # A directory may be written within quotes, as one holding a `;` must be. var directory := listed.trim(); if directory.length >= 2 && directory[0] == '"' && directory[directory.length - 1] == '"' { directory = directory.substr(1, directory.length - 2); } if directory.length == 0 { continue; } var at := string::from(directory, nothing{}); if !directory.ends_with("\\") && !directory.ends_with("/") { at.append("\\"); } at.append(name); if ended && this.runnable(at.span) { return move(at); } for ending in endings.split(';') { if !ended && ending.length != 0 { var candidate := string::copy_of(&at); candidate.append(ending); if this.runnable(candidate.span) { return move(candidate); } } } } return io_error::not_found; } # The endings that make a name a program's, as the `PATHEXT` the child will # have lists them, between `;`, or those the system's shell takes where it # lists none. def command::endings(&this): string { if this.setting_of("PATHEXT") is some(&set) && set.value is some(&value) { return string::copy_of(value); } val listed := variable("PATHEXT") else { return string::from(".COM;.EXE;.BAT;.CMD", nothing{}); }; return string::from(listed, nothing{}); } # Whether a name ends in one of the endings, compared whatever their case. def command::has_ending(&this, name: strview, endings: &string): bool { for ending in endings.split(';') { if ending.length != 0 && name.length > ending.length && same_name(name.substr(name.length - ending.length, ending.length), ending) { return true; } } return false; } # The directories the child will have in its `PATH`, which is the command's # own where it set one, and otherwise the program's, or, where neither has # one, those of the system, where the program has `SystemRoot`. def command::directories(&this): string { if this.setting_of("PATH") is some(&set) && set.value is some(&value) { return string::copy_of(value); } if variable("PATH") is some(listed) { return string::from(listed, nothing{}); } val root := variable("SystemRoot") else { return string::new(nothing{}); }; var made := string::from(root, nothing{}); made.append("\\System32;"); made.append(root); return made; } # Whether two names of variables are the same, as Windows has them: whatever # the case of their letters. def same_name(a: strview, b: strview): bool { if a.length != b.length { return false; } for i in 0..a.length { if a[i].to_upper != b[i].to_upper { return false; } } return true; } } else { # Whether two names of variables are the same. def same_name(a: strview, b: strview): bool { return a == b; } } # Whether text holds a byte. def contains(text: strview, wanted: u8): bool { for i in 0..text.length { if text[i] == wanted { return true; } } return false; }