fake-tty-0.3.1/Cargo.toml0000644000000016470000000000100105670ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "fake-tty" version = "0.3.1" authors = ["Ludwig Stecher "] description = "Run command with bash pretending to be a tty" homepage = "https://github.com/Aloso/to-html/tree/master/crates/fake-tty" documentation = "https://docs.rs/fake-tty" readme = "README.md" keywords = [ "cli", "terminal", ] categories = [] license = "MIT" repository = "https://github.com/Aloso/to-html" resolver = "2" [dependencies] fake-tty-0.3.1/Cargo.toml.orig000064400000000000000000000010341046102023000142360ustar 00000000000000[package] name = "fake-tty" version = "0.3.1" authors = ["Ludwig Stecher "] description = "Run command with bash pretending to be a tty" categories = [] repository = "https://github.com/Aloso/to-html" documentation = "https://docs.rs/fake-tty" homepage = "https://github.com/Aloso/to-html/tree/master/crates/fake-tty" readme = "README.md" edition = "2021" keywords = ["cli", "terminal"] license = "MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] fake-tty-0.3.1/LICENSE000064400000000000000000000020571046102023000123620ustar 00000000000000MIT License Copyright (c) 2020 Ludwig Stecher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fake-tty-0.3.1/README.md000064400000000000000000000020221046102023000126240ustar 00000000000000# fake-tty [Documentation](https://docs.rs/crate/fake-tty) Rust library to run a command in bash, pretending to be a tty. This means that the command will assume that terminal colors and other terminal features are available. This is done by executing the [script](https://man7.org/linux/man-pages/man1/script.1.html) command. Note that some programs might still behave differently than they would in a real terminal. For example, on my system, `ls` always displays colors in the terminal, but requires `--color=auto` when executed in fake-tty. ## Example ```rust let output = fake_tty::bash_command("ls --color=auto").output().unwrap(); assert!(output.status.success()); let _stdout: String = String::from_utf8(output.stdout).unwrap(); ``` ## Platform support As of now, fake-tty supports Linux, macOS and FreeBSD. Adding support other platforms should be easy, if they support bash and the `script` command. On Windows, it might be possible to use cmd or PowerShell instead; please send a pull request if you need Windows support. fake-tty-0.3.1/src/lib.rs000064400000000000000000000111321046102023000132520ustar 00000000000000//! Run a command in bash, pretending to be a tty. //! //! This means that the command will assume that terminal colors and //! other terminal features are available. //! //! ## Example //! //! ``` //! let output = fake_tty::bash_command("ls").unwrap() //! .output().unwrap(); //! assert!(output.status.success()); //! //! let _stdout: String = fake_tty::get_stdout(output.stdout).unwrap(); //! ``` use std::{ io, process::{Command, Stdio}, string::FromUtf8Error, }; /// Creates a command that is executed by bash, pretending to be a tty. /// /// This means that the command will assume that terminal colors and /// other terminal features are available. pub fn bash_command(command: &str) -> io::Result { let mut command = make_script_command(command, Some("bash"))?; command.stdout(Stdio::piped()).stderr(Stdio::piped()); Ok(command) } /// Creates a command that is executed by a shell, pretending to be a tty. /// /// This means that the command will assume that terminal colors and /// other terminal features are available. pub fn command(command: &str, shell: Option<&str>) -> io::Result { let mut command = make_script_command(command, shell)?; command.stdout(Stdio::piped()).stderr(Stdio::piped()); Ok(command) } /// Wraps the command in the `script` command that can execute it /// pretending to be a tty. /// /// - [Linux docs](https://man7.org/linux/man-pages/man1/script.1.html) /// - [FreeBSD docs](https://www.freebsd.org/cgi/man.cgi?query=script&sektion=0&manpath=FreeBSD+12.2-RELEASE+and+Ports&arch=default&format=html) /// - [Apple docs](https://opensource.apple.com/source/shell_cmds/shell_cmds-170/script/script.1.auto.html) /// /// ## Examples /// /// ``` /// use std::process::{Command, Stdio}; /// use fake_tty::make_script_command; /// /// let output = make_script_command("ls", Some("bash")).unwrap() /// .stdout(Stdio::piped()) /// .stderr(Stdio::piped()) /// .output().unwrap(); /// /// assert!(output.status.success()); /// ``` pub fn make_script_command(c: &str, shell: Option<&str>) -> io::Result { let shell = which_shell(shell.unwrap_or("bash"))?; #[cfg(any(target_os = "linux", target_os = "android"))] { let mut command = Command::new("script"); command.args(&["-qec", c, "/dev/null"]); command.env("SHELL", shell.trim()); Ok(command) } #[cfg(any(target_os = "macos", target_os = "freebsd"))] { let mut command = Command::new("script"); command.args(&["-q", "/dev/null", shell.trim(), "-c", c]); Ok(command) } #[cfg(not(any( target_os = "android", target_os = "linux", target_os = "macos", target_os = "freebsd" )))] compile_error!("This platform is not supported. See https://github.com/Aloso/to-html/issues/3") } /// Returns the standard output of the command. pub fn get_stdout(stdout: Vec) -> Result { let out = String::from_utf8(stdout)?; #[cfg(any(target_os = "linux", target_os = "android"))] { Ok(out.replace("\r\n", "\n")) } #[cfg(any(target_os = "macos", target_os = "freebsd"))] { let mut out = out.replace("\r\n", "\n"); if out.starts_with("^D\u{8}\u{8}") { out = out["^D\u{8}\u{8}".len()..].to_string() } Ok(out) } } fn which_shell(shell: &str) -> io::Result { let which = Command::new("which") .arg(shell) .stdout(Stdio::piped()) .output()?; if which.status.success() { Ok(String::from_utf8(which.stdout).unwrap()) } else { Err(io::Error::new( io::ErrorKind::Other, String::from_utf8(which.stderr).unwrap(), )) } } #[cfg(test)] mod tests { fn run(s: &str) -> String { let output = crate::bash_command(s).unwrap().output().unwrap(); let s1 = crate::get_stdout(output.stdout).unwrap(); if crate::which_shell("zsh").is_ok() { let output = crate::command(s, Some("zsh")).unwrap().output().unwrap(); let s2 = crate::get_stdout(output.stdout).unwrap(); assert_eq!(s1, s2); } s1 } #[test] fn echo() { assert_eq!(run("echo hello world"), "hello world\n"); } #[test] fn seq() { assert_eq!(run("seq 3"), "1\n2\n3\n"); } #[test] fn echo_quotes() { assert_eq!(run(r#"echo "Hello \$\`' world!""#), "Hello $`' world!\n"); } #[test] fn echo_and_cat() { assert_eq!( run("echo 'look, bash support!' | cat"), "look, bash support!\n" ); } }