PageRenderTime 23ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/src/utils.rs

https://gitlab.com/vitalii.dr/starship
Rust | 718 lines | 638 code | 58 blank | 22 comment | 27 complexity | 2896017372f5c92c08a739c8a7673170 MD5 | raw file
  1. use process_control::{ChildExt, Control};
  2. use std::ffi::OsStr;
  3. use std::fmt::Debug;
  4. use std::fs::read_to_string;
  5. use std::io::{Error, ErrorKind, Result};
  6. use std::path::{Path, PathBuf};
  7. use std::process::{Command, Stdio};
  8. use std::time::{Duration, Instant};
  9. use crate::context::Context;
  10. use crate::context::Shell;
  11. /// Create a `PathBuf` from an absolute path, where the root directory will be mocked in test
  12. #[cfg(not(test))]
  13. #[inline]
  14. #[allow(dead_code)]
  15. pub fn context_path<S: AsRef<OsStr> + ?Sized>(_context: &Context, s: &S) -> PathBuf {
  16. PathBuf::from(s)
  17. }
  18. /// Create a `PathBuf` from an absolute path, where the root directory will be mocked in test
  19. #[cfg(test)]
  20. #[allow(dead_code)]
  21. pub fn context_path<S: AsRef<OsStr> + ?Sized>(context: &Context, s: &S) -> PathBuf {
  22. let requested_path = PathBuf::from(s);
  23. if requested_path.is_absolute() {
  24. let mut path = PathBuf::from(context.root_dir.path());
  25. path.extend(requested_path.components().skip(1));
  26. path
  27. } else {
  28. requested_path
  29. }
  30. }
  31. /// Return the string contents of a file
  32. pub fn read_file<P: AsRef<Path> + Debug>(file_name: P) -> Result<String> {
  33. log::trace!("Trying to read from {:?}", file_name);
  34. let result = read_to_string(file_name);
  35. if result.is_err() {
  36. log::debug!("Error reading file: {:?}", result);
  37. } else {
  38. log::trace!("File read successfully");
  39. };
  40. result
  41. }
  42. /// Reads command output from stderr or stdout depending on to which stream program streamed it's output
  43. pub fn get_command_string_output(command: CommandOutput) -> String {
  44. if command.stdout.is_empty() {
  45. command.stderr
  46. } else {
  47. command.stdout
  48. }
  49. }
  50. /// Attempt to resolve `binary_name` from and creates a new `Command` pointing at it
  51. /// This allows executing cmd files on Windows and prevents running executable from cwd on Windows
  52. /// This function also initialises std{err,out,in} to protect against processes changing the console mode
  53. pub fn create_command<T: AsRef<OsStr>>(binary_name: T) -> Result<Command> {
  54. let binary_name = binary_name.as_ref();
  55. log::trace!("Creating Command for binary {:?}", binary_name);
  56. let full_path = match which::which(binary_name) {
  57. Ok(full_path) => {
  58. log::trace!("Using {:?} as {:?}", full_path, binary_name);
  59. full_path
  60. }
  61. Err(error) => {
  62. log::trace!("Unable to find {:?} in PATH, {:?}", binary_name, error);
  63. return Err(Error::new(ErrorKind::NotFound, error));
  64. }
  65. };
  66. #[allow(clippy::disallowed_methods)]
  67. let mut cmd = Command::new(full_path);
  68. cmd.stderr(Stdio::piped())
  69. .stdout(Stdio::piped())
  70. .stdin(Stdio::null());
  71. Ok(cmd)
  72. }
  73. #[derive(Debug, Clone)]
  74. pub struct CommandOutput {
  75. pub stdout: String,
  76. pub stderr: String,
  77. }
  78. impl PartialEq for CommandOutput {
  79. fn eq(&self, other: &Self) -> bool {
  80. self.stdout == other.stdout && self.stderr == other.stderr
  81. }
  82. }
  83. #[cfg(test)]
  84. pub fn display_command<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
  85. cmd: T,
  86. args: &[U],
  87. ) -> String {
  88. std::iter::once(cmd.as_ref())
  89. .chain(args.iter().map(|i| i.as_ref()))
  90. .map(|i| i.to_string_lossy().into_owned())
  91. .collect::<Vec<String>>()
  92. .join(" ")
  93. }
  94. /// Execute a command and return the output on stdout and stderr if successful
  95. pub fn exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
  96. cmd: T,
  97. args: &[U],
  98. time_limit: Duration,
  99. ) -> Option<CommandOutput> {
  100. log::trace!("Executing command {:?} with args {:?}", cmd, args);
  101. #[cfg(test)]
  102. if let Some(o) = mock_cmd(&cmd, args) {
  103. return o;
  104. }
  105. internal_exec_cmd(cmd, args, time_limit)
  106. }
  107. #[cfg(test)]
  108. pub fn mock_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
  109. cmd: T,
  110. args: &[U],
  111. ) -> Option<Option<CommandOutput>> {
  112. let command = display_command(&cmd, args);
  113. let out = match command.as_str() {
  114. "buf --version" => Some(CommandOutput {
  115. stdout: String::from("1.0.0"),
  116. stderr: String::default(),
  117. }),
  118. "cobc -version" => Some(CommandOutput {
  119. stdout: String::from("\
  120. cobc (GnuCOBOL) 3.1.2.0
  121. Copyright (C) 2020 Free Software Foundation, Inc.
  122. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
  123. This is free software; see the source for copying conditions. There is NO
  124. warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  125. Written by Keisuke Nishida, Roger While, Ron Norman, Simon Sobisch, Edward Hart
  126. Built Dec 24 2020 19:08:58
  127. Packaged Dec 23 2020 12:04:58 UTC
  128. C version \"10.2.0\""),
  129. stderr: String::default(),
  130. }),
  131. "crystal --version" => Some(CommandOutput {
  132. stdout: String::from(
  133. "\
  134. Crystal 0.35.1 (2020-06-19)
  135. LLVM: 10.0.0
  136. Default target: x86_64-apple-macosx\n",
  137. ),
  138. stderr: String::default(),
  139. }),
  140. "dart --version" => Some(CommandOutput {
  141. stdout: String::default(),
  142. stderr: String::from(
  143. "Dart VM version: 2.8.4 (stable) (Wed Jun 3 12:26:04 2020 +0200) on \"macos_x64\"",
  144. ),
  145. }),
  146. "deno -V" => Some(CommandOutput {
  147. stdout: String::from("deno 1.8.3\n"),
  148. stderr: String::default()
  149. }),
  150. "dummy_command" => Some(CommandOutput {
  151. stdout: String::from("stdout ok!\n"),
  152. stderr: String::from("stderr ok!\n"),
  153. }),
  154. "elixir --version" => Some(CommandOutput {
  155. stdout: String::from(
  156. "\
  157. Erlang/OTP 22 [erts-10.6.4] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]
  158. Elixir 1.10 (compiled with Erlang/OTP 22)\n",
  159. ),
  160. stderr: String::default(),
  161. }),
  162. "elm --version" => Some(CommandOutput {
  163. stdout: String::from("0.19.1\n"),
  164. stderr: String::default(),
  165. }),
  166. "go version" => Some(CommandOutput {
  167. stdout: String::from("go version go1.12.1 linux/amd64\n"),
  168. stderr: String::default(),
  169. }),
  170. "ghc --numeric-version" => Some(CommandOutput {
  171. stdout: String::from("9.2.1\n"),
  172. stderr: String::default(),
  173. }),
  174. "helm version --short --client" => Some(CommandOutput {
  175. stdout: String::from("v3.1.1+gafe7058\n"),
  176. stderr: String::default(),
  177. }),
  178. s if s.ends_with("java -Xinternalversion") => Some(CommandOutput {
  179. stdout: String::from("OpenJDK 64-Bit Server VM (13.0.2+8) for bsd-amd64 JRE (13.0.2+8), built on Feb 6 2020 02:07:52 by \"brew\" with clang 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.17)"),
  180. stderr: String::default(),
  181. }),
  182. "scalac -version" => Some(CommandOutput {
  183. stdout: String::from("Scala compiler version 2.13.5 -- Copyright 2002-2020, LAMP/EPFL and Lightbend, Inc."),
  184. stderr: String::default(),
  185. }),
  186. "julia --version" => Some(CommandOutput {
  187. stdout: String::from("julia version 1.4.0\n"),
  188. stderr: String::default(),
  189. }),
  190. "kotlin -version" => Some(CommandOutput {
  191. stdout: String::from("Kotlin version 1.4.21-release-411 (JRE 14.0.1+7)\n"),
  192. stderr: String::default(),
  193. }),
  194. "kotlinc -version" => Some(CommandOutput {
  195. stdout: String::from("info: kotlinc-jvm 1.4.21 (JRE 14.0.1+7)\n"),
  196. stderr: String::default(),
  197. }),
  198. "lua -v" => Some(CommandOutput{
  199. stdout: String::from("Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio\n"),
  200. stderr: String::default(),
  201. }),
  202. "luajit -v" => Some(CommandOutput{
  203. stdout: String::from("LuaJIT 2.0.5 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/\n"),
  204. stderr: String::default(),
  205. }),
  206. "nim --version" => Some(CommandOutput {
  207. stdout: String::from(
  208. "\
  209. Nim Compiler Version 1.2.0 [Linux: amd64]
  210. Compiled at 2020-04-03
  211. Copyright (c) 2006-2020 by Andreas Rumpf
  212. git hash: 7e83adff84be5d0c401a213eccb61e321a3fb1ff
  213. active boot switches: -d:release\n",
  214. ),
  215. stderr: String::default(),
  216. }),
  217. "node --version" => Some(CommandOutput {
  218. stdout: String::from("v12.0.0\n"),
  219. stderr: String::default(),
  220. }),
  221. "ocaml -vnum" => Some(CommandOutput {
  222. stdout: String::from("4.10.0\n"),
  223. stderr: String::default(),
  224. }),
  225. "opam switch show --safe" => Some(CommandOutput {
  226. stdout: String::from("default\n"),
  227. stderr: String::default(),
  228. }),
  229. "esy ocaml -vnum" => Some(CommandOutput {
  230. stdout: String::from("4.08.1\n"),
  231. stderr: String::default(),
  232. }),
  233. "perl -e printf q#%vd#,$^V;" => Some(CommandOutput {
  234. stdout: String::from("5.26.1"),
  235. stderr: String::default(),
  236. }),
  237. "php -nr echo PHP_MAJOR_VERSION.\".\".PHP_MINOR_VERSION.\".\".PHP_RELEASE_VERSION;" => {
  238. Some(CommandOutput {
  239. stdout: String::from("7.3.8"),
  240. stderr: String::default(),
  241. })
  242. },
  243. "pulumi version" => Some(CommandOutput{
  244. stdout: String::from("1.2.3-ver.1631311768+e696fb6c"),
  245. stderr: String::default(),
  246. }),
  247. "purs --version" => Some(CommandOutput {
  248. stdout: String::from("0.13.5\n"),
  249. stderr: String::default(),
  250. }),
  251. "pyenv version-name" => Some(CommandOutput {
  252. stdout: String::from("system\n"),
  253. stderr: String::default(),
  254. }),
  255. "python --version" => None,
  256. "python2 --version" => Some(CommandOutput {
  257. stdout: String::default(),
  258. stderr: String::from("Python 2.7.17\n"),
  259. }),
  260. "python3 --version" => Some(CommandOutput {
  261. stdout: String::from("Python 3.8.0\n"),
  262. stderr: String::default(),
  263. }),
  264. "R --version" => Some(CommandOutput {
  265. stdout: String::default(),
  266. stderr: String::from(
  267. r#"R version 4.1.0 (2021-05-18) -- "Camp Pontanezen"
  268. Copyright (C) 2021 The R Foundation for Statistical Computing
  269. Platform: x86_64-w64-mingw32/x64 (64-bit)\n
  270. R is free software and comes with ABSOLUTELY NO WARRANTY.
  271. You are welcome to redistribute it under the terms of the
  272. GNU General Public License versions 2 or 3.
  273. For more information about these matters see
  274. https://www.gnu.org/licenses/."#
  275. ),
  276. }),
  277. "red --version" => Some(CommandOutput {
  278. stdout: String::from("0.6.4\n"),
  279. stderr: String::default()
  280. }),
  281. "ruby -v" => Some(CommandOutput {
  282. stdout: String::from("ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]\n"),
  283. stderr: String::default(),
  284. }),
  285. "swift --version" => Some(CommandOutput {
  286. stdout: String::from(
  287. "\
  288. Apple Swift version 5.2.2 (swiftlang-1103.0.32.6 clang-1103.0.32.51)
  289. Target: x86_64-apple-darwin19.4.0\n",
  290. ),
  291. stderr: String::default(),
  292. }),
  293. "vagrant --version" => Some(CommandOutput {
  294. stdout: String::from("Vagrant 2.2.10\n"),
  295. stderr: String::default(),
  296. }),
  297. "v version" => Some(CommandOutput {
  298. stdout: String::from("V 0.2 30c0659"),
  299. stderr: String::default()
  300. }),
  301. "zig version" => Some(CommandOutput {
  302. stdout: String::from("0.6.0\n"),
  303. stderr: String::default(),
  304. }),
  305. "cmake --version" => Some(CommandOutput {
  306. stdout: String::from(
  307. "\
  308. cmake version 3.17.3
  309. CMake suite maintained and supported by Kitware (kitware.com/cmake).\n",
  310. ),
  311. stderr: String::default(),
  312. }),
  313. "dotnet --version" => Some(CommandOutput {
  314. stdout: String::from("3.1.103"),
  315. stderr: String::default(),
  316. }),
  317. "dotnet --list-sdks" => Some(CommandOutput {
  318. stdout: String::from("3.1.103 [/usr/share/dotnet/sdk]"),
  319. stderr: String::default(),
  320. }),
  321. "terraform version" => Some(CommandOutput {
  322. stdout: String::from("Terraform v0.12.14\n"),
  323. stderr: String::default(),
  324. }),
  325. s if s.starts_with("erl -noshell -eval") => Some(CommandOutput {
  326. stdout: String::from("22.1.3\n"),
  327. stderr: String::default(),
  328. }),
  329. _ => return None,
  330. };
  331. Some(out)
  332. }
  333. /// Wraps ANSI color escape sequences in the shell-appropriate wrappers.
  334. pub fn wrap_colorseq_for_shell(ansi: String, shell: Shell) -> String {
  335. const ESCAPE_BEGIN: char = '\u{1b}';
  336. const ESCAPE_END: char = 'm';
  337. wrap_seq_for_shell(ansi, shell, ESCAPE_BEGIN, ESCAPE_END)
  338. }
  339. /// Many shells cannot deal with raw unprintable characters and miscompute the cursor position,
  340. /// leading to strange visual bugs like duplicated/missing chars. This function wraps a specified
  341. /// sequence in shell-specific escapes to avoid these problems.
  342. pub fn wrap_seq_for_shell(
  343. ansi: String,
  344. shell: Shell,
  345. escape_begin: char,
  346. escape_end: char,
  347. ) -> String {
  348. const BASH_BEG: &str = "\u{5c}\u{5b}"; // \[
  349. const BASH_END: &str = "\u{5c}\u{5d}"; // \]
  350. const ZSH_BEG: &str = "\u{25}\u{7b}"; // %{
  351. const ZSH_END: &str = "\u{25}\u{7d}"; // %}
  352. const TCSH_BEG: &str = "\u{25}\u{7b}"; // %{
  353. const TCSH_END: &str = "\u{25}\u{7d}"; // %}
  354. // ANSI escape codes cannot be nested, so we can keep track of whether we're
  355. // in an escape or not with a single boolean variable
  356. let mut escaped = false;
  357. let final_string: String = ansi
  358. .chars()
  359. .map(|x| {
  360. if x == escape_begin && !escaped {
  361. escaped = true;
  362. match shell {
  363. Shell::Bash => format!("{}{}", BASH_BEG, escape_begin),
  364. Shell::Zsh => format!("{}{}", ZSH_BEG, escape_begin),
  365. Shell::Tcsh => format!("{}{}", TCSH_BEG, escape_begin),
  366. _ => x.to_string(),
  367. }
  368. } else if x == escape_end && escaped {
  369. escaped = false;
  370. match shell {
  371. Shell::Bash => format!("{}{}", escape_end, BASH_END),
  372. Shell::Zsh => format!("{}{}", escape_end, ZSH_END),
  373. Shell::Tcsh => format!("{}{}", escape_end, TCSH_END),
  374. _ => x.to_string(),
  375. }
  376. } else {
  377. x.to_string()
  378. }
  379. })
  380. .collect();
  381. final_string
  382. }
  383. fn internal_exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
  384. cmd: T,
  385. args: &[U],
  386. time_limit: Duration,
  387. ) -> Option<CommandOutput> {
  388. let mut cmd = create_command(cmd).ok()?;
  389. cmd.args(args);
  390. exec_timeout(&mut cmd, time_limit)
  391. }
  392. pub fn exec_timeout(cmd: &mut Command, time_limit: Duration) -> Option<CommandOutput> {
  393. let start = Instant::now();
  394. let process = match cmd.spawn() {
  395. Ok(process) => process,
  396. Err(error) => {
  397. log::info!("Unable to run {:?}, {:?}", cmd.get_program(), error);
  398. return None;
  399. }
  400. };
  401. match process
  402. .controlled_with_output()
  403. .time_limit(time_limit)
  404. .terminate_for_timeout()
  405. .wait()
  406. {
  407. Ok(Some(output)) => {
  408. let stdout_string = match String::from_utf8(output.stdout) {
  409. Ok(stdout) => stdout,
  410. Err(error) => {
  411. log::warn!("Unable to decode stdout: {:?}", error);
  412. return None;
  413. }
  414. };
  415. let stderr_string = match String::from_utf8(output.stderr) {
  416. Ok(stderr) => stderr,
  417. Err(error) => {
  418. log::warn!("Unable to decode stderr: {:?}", error);
  419. return None;
  420. }
  421. };
  422. log::trace!(
  423. "stdout: {:?}, stderr: {:?}, exit code: \"{:?}\", took {:?}",
  424. stdout_string,
  425. stderr_string,
  426. output.status.code(),
  427. start.elapsed()
  428. );
  429. if !output.status.success() {
  430. return None;
  431. }
  432. Some(CommandOutput {
  433. stdout: stdout_string,
  434. stderr: stderr_string,
  435. })
  436. }
  437. Ok(None) => {
  438. log::warn!("Executing command {:?} timed out.", cmd.get_program());
  439. log::warn!("You can set command_timeout in your config to a higher value to allow longer-running commands to keep executing.");
  440. None
  441. }
  442. Err(error) => {
  443. log::info!(
  444. "Executing command {:?} failed by: {:?}",
  445. cmd.get_program(),
  446. error
  447. );
  448. None
  449. }
  450. }
  451. }
  452. // Render the time into a nice human-readable string
  453. pub fn render_time(raw_millis: u128, show_millis: bool) -> String {
  454. // Make sure it renders something if the time equals zero instead of an empty string
  455. if raw_millis == 0 {
  456. return "0ms".into();
  457. }
  458. // Calculate a simple breakdown into days/hours/minutes/seconds/milliseconds
  459. let (millis, raw_seconds) = (raw_millis % 1000, raw_millis / 1000);
  460. let (seconds, raw_minutes) = (raw_seconds % 60, raw_seconds / 60);
  461. let (minutes, raw_hours) = (raw_minutes % 60, raw_minutes / 60);
  462. let (hours, days) = (raw_hours % 24, raw_hours / 24);
  463. let components = [days, hours, minutes, seconds];
  464. let suffixes = ["d", "h", "m", "s"];
  465. let mut rendered_components: Vec<String> = components
  466. .iter()
  467. .zip(&suffixes)
  468. .map(render_time_component)
  469. .collect();
  470. if show_millis || raw_millis < 1000 {
  471. rendered_components.push(render_time_component((&millis, &"ms")));
  472. }
  473. rendered_components.join("")
  474. }
  475. /// Render a single component of the time string, giving an empty string if component is zero
  476. fn render_time_component((component, suffix): (&u128, &&str)) -> String {
  477. match component {
  478. 0 => String::new(),
  479. n => format!("{}{}", n, suffix),
  480. }
  481. }
  482. pub fn home_dir() -> Option<PathBuf> {
  483. directories_next::BaseDirs::new().map(|base_dirs| base_dirs.home_dir().to_owned())
  484. }
  485. const HEXTABLE: &[char] = &[
  486. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
  487. ];
  488. /// Encode a u8 slice into a hexadecimal string.
  489. pub fn encode_to_hex(slice: &[u8]) -> String {
  490. // let mut j = 0;
  491. let mut dst = Vec::with_capacity(slice.len() * 2);
  492. for &v in slice {
  493. dst.push(HEXTABLE[(v >> 4) as usize] as u8);
  494. dst.push(HEXTABLE[(v & 0x0f) as usize] as u8);
  495. }
  496. String::from_utf8(dst).unwrap()
  497. }
  498. #[cfg(test)]
  499. mod tests {
  500. use super::*;
  501. #[test]
  502. fn test_0ms() {
  503. assert_eq!(render_time(0_u128, true), "0ms")
  504. }
  505. #[test]
  506. fn test_500ms() {
  507. assert_eq!(render_time(500_u128, true), "500ms")
  508. }
  509. #[test]
  510. fn test_10s() {
  511. assert_eq!(render_time(10_000_u128, true), "10s")
  512. }
  513. #[test]
  514. fn test_90s() {
  515. assert_eq!(render_time(90_000_u128, true), "1m30s")
  516. }
  517. #[test]
  518. fn test_10110s() {
  519. assert_eq!(render_time(10_110_000_u128, true), "2h48m30s")
  520. }
  521. #[test]
  522. fn test_1d() {
  523. assert_eq!(render_time(86_400_000_u128, true), "1d")
  524. }
  525. #[test]
  526. fn exec_mocked_command() {
  527. let result = exec_cmd(
  528. "dummy_command",
  529. &[] as &[&OsStr],
  530. Duration::from_millis(500),
  531. );
  532. let expected = Some(CommandOutput {
  533. stdout: String::from("stdout ok!\n"),
  534. stderr: String::from("stderr ok!\n"),
  535. });
  536. assert_eq!(result, expected)
  537. }
  538. // While the exec_cmd should work on Windows some of these tests assume a Unix-like
  539. // environment.
  540. #[test]
  541. #[cfg(not(windows))]
  542. fn exec_no_output() {
  543. let result = internal_exec_cmd("true", &[] as &[&OsStr], Duration::from_millis(500));
  544. let expected = Some(CommandOutput {
  545. stdout: String::from(""),
  546. stderr: String::from(""),
  547. });
  548. assert_eq!(result, expected)
  549. }
  550. #[test]
  551. #[cfg(not(windows))]
  552. fn exec_with_output_stdout() {
  553. let result =
  554. internal_exec_cmd("/bin/sh", &["-c", "echo hello"], Duration::from_millis(500));
  555. let expected = Some(CommandOutput {
  556. stdout: String::from("hello\n"),
  557. stderr: String::from(""),
  558. });
  559. assert_eq!(result, expected)
  560. }
  561. #[test]
  562. #[cfg(not(windows))]
  563. fn exec_with_output_stderr() {
  564. let result = internal_exec_cmd(
  565. "/bin/sh",
  566. &["-c", "echo hello >&2"],
  567. Duration::from_millis(500),
  568. );
  569. let expected = Some(CommandOutput {
  570. stdout: String::from(""),
  571. stderr: String::from("hello\n"),
  572. });
  573. assert_eq!(result, expected)
  574. }
  575. #[test]
  576. #[cfg(not(windows))]
  577. fn exec_with_output_both() {
  578. let result = internal_exec_cmd(
  579. "/bin/sh",
  580. &["-c", "echo hello; echo world >&2"],
  581. Duration::from_millis(500),
  582. );
  583. let expected = Some(CommandOutput {
  584. stdout: String::from("hello\n"),
  585. stderr: String::from("world\n"),
  586. });
  587. assert_eq!(result, expected)
  588. }
  589. #[test]
  590. #[cfg(not(windows))]
  591. fn exec_with_non_zero_exit_code() {
  592. let result = internal_exec_cmd("false", &[] as &[&OsStr], Duration::from_millis(500));
  593. let expected = None;
  594. assert_eq!(result, expected)
  595. }
  596. #[test]
  597. #[cfg(not(windows))]
  598. fn exec_slow_command() {
  599. let result = internal_exec_cmd("sleep", &["500"], Duration::from_millis(500));
  600. let expected = None;
  601. assert_eq!(result, expected)
  602. }
  603. #[test]
  604. fn test_color_sequence_wrappers() {
  605. let test0 = "\x1b2mhellomynamekeyes\x1b2m"; // BEGIN: \x1b END: m
  606. let test1 = "\x1b]330;mlol\x1b]0m"; // BEGIN: \x1b END: m
  607. let test2 = "\u{1b}J"; // BEGIN: \x1b END: J
  608. let test3 = "OH NO"; // BEGIN: O END: O
  609. let test4 = "herpaderp";
  610. let test5 = "";
  611. let zresult0 = wrap_seq_for_shell(test0.to_string(), Shell::Zsh, '\x1b', 'm');
  612. let zresult1 = wrap_seq_for_shell(test1.to_string(), Shell::Zsh, '\x1b', 'm');
  613. let zresult2 = wrap_seq_for_shell(test2.to_string(), Shell::Zsh, '\x1b', 'J');
  614. let zresult3 = wrap_seq_for_shell(test3.to_string(), Shell::Zsh, 'O', 'O');
  615. let zresult4 = wrap_seq_for_shell(test4.to_string(), Shell::Zsh, '\x1b', 'm');
  616. let zresult5 = wrap_seq_for_shell(test5.to_string(), Shell::Zsh, '\x1b', 'm');
  617. assert_eq!(&zresult0, "%{\x1b2m%}hellomynamekeyes%{\x1b2m%}");
  618. assert_eq!(&zresult1, "%{\x1b]330;m%}lol%{\x1b]0m%}");
  619. assert_eq!(&zresult2, "%{\x1bJ%}");
  620. assert_eq!(&zresult3, "%{OH NO%}");
  621. assert_eq!(&zresult4, "herpaderp");
  622. assert_eq!(&zresult5, "");
  623. let bresult0 = wrap_seq_for_shell(test0.to_string(), Shell::Bash, '\x1b', 'm');
  624. let bresult1 = wrap_seq_for_shell(test1.to_string(), Shell::Bash, '\x1b', 'm');
  625. let bresult2 = wrap_seq_for_shell(test2.to_string(), Shell::Bash, '\x1b', 'J');
  626. let bresult3 = wrap_seq_for_shell(test3.to_string(), Shell::Bash, 'O', 'O');
  627. let bresult4 = wrap_seq_for_shell(test4.to_string(), Shell::Bash, '\x1b', 'm');
  628. let bresult5 = wrap_seq_for_shell(test5.to_string(), Shell::Bash, '\x1b', 'm');
  629. assert_eq!(&bresult0, "\\[\x1b2m\\]hellomynamekeyes\\[\x1b2m\\]");
  630. assert_eq!(&bresult1, "\\[\x1b]330;m\\]lol\\[\x1b]0m\\]");
  631. assert_eq!(&bresult2, "\\[\x1bJ\\]");
  632. assert_eq!(&bresult3, "\\[OH NO\\]");
  633. assert_eq!(&bresult4, "herpaderp");
  634. assert_eq!(&bresult5, "");
  635. }
  636. #[test]
  637. fn test_get_command_string_output() {
  638. let case1 = CommandOutput {
  639. stdout: String::from("stdout"),
  640. stderr: String::from("stderr"),
  641. };
  642. assert_eq!(get_command_string_output(case1), "stdout");
  643. let case2 = CommandOutput {
  644. stdout: String::from(""),
  645. stderr: String::from("stderr"),
  646. };
  647. assert_eq!(get_command_string_output(case2), "stderr");
  648. }
  649. #[test]
  650. fn sha1_hex() {
  651. assert_eq!(
  652. encode_to_hex(&[8, 13, 9, 189, 129, 94]),
  653. "080d09bd815e".to_string()
  654. );
  655. }
  656. }