diff options
author | Valentin Popov <valentin@popov.link> | 2024-01-08 00:21:28 +0300 |
---|---|---|
committer | Valentin Popov <valentin@popov.link> | 2024-01-08 00:21:28 +0300 |
commit | 1b6a04ca5504955c571d1c97504fb45ea0befee4 (patch) | |
tree | 7579f518b23313e8a9748a88ab6173d5e030b227 /vendor/shell-words | |
parent | 5ecd8cf2cba827454317368b68571df0d13d7842 (diff) | |
download | fparkan-1b6a04ca5504955c571d1c97504fb45ea0befee4.tar.xz fparkan-1b6a04ca5504955c571d1c97504fb45ea0befee4.zip |
Initial vendor packages
Signed-off-by: Valentin Popov <valentin@popov.link>
Diffstat (limited to 'vendor/shell-words')
-rw-r--r-- | vendor/shell-words/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | vendor/shell-words/Cargo.toml | 30 | ||||
-rw-r--r-- | vendor/shell-words/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | vendor/shell-words/LICENSE-MIT | 25 | ||||
-rw-r--r-- | vendor/shell-words/README.md | 90 | ||||
-rw-r--r-- | vendor/shell-words/rustfmt.toml | 1 | ||||
-rw-r--r-- | vendor/shell-words/src/lib.rs | 507 |
7 files changed, 855 insertions, 0 deletions
diff --git a/vendor/shell-words/.cargo-checksum.json b/vendor/shell-words/.cargo-checksum.json new file mode 100644 index 0000000..851eba5 --- /dev/null +++ b/vendor/shell-words/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"93a9e03b9ff9da01305caf81ce6d2d452b9d43d8247e5122437cb2804c2c6dc8","LICENSE-APACHE":"848d7bf14c618c39f1e29fcac2318a2fcc4254045ba7e2f6f5fa799e057225cb","LICENSE-MIT":"f76b7831ee8f42d3ac38919101e4ceb9f56aeb7796cdfe8a5ef52e26acedcbbf","README.md":"9afd45a0555ac08318b35b569d439e9aa3e9b15323622648bce72e9663e12453","rustfmt.toml":"aeffdf96c9207bb6b1cb14c082f2f7c702653664c2f23d705b6a6b3de055c9d4","src/lib.rs":"be96845d39315fc620e12abd42e29a593ec5d267b9a40462a15cf5be234d3149"},"package":"24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"}
\ No newline at end of file diff --git a/vendor/shell-words/Cargo.toml b/vendor/shell-words/Cargo.toml new file mode 100644 index 0000000..2040d9d --- /dev/null +++ b/vendor/shell-words/Cargo.toml @@ -0,0 +1,30 @@ +# 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] +name = "shell-words" +version = "1.1.0" +authors = ["Tomasz Miąsko <tomasz.miasko@gmail.com>"] +description = "Process command line according to parsing rules of UNIX shell" +readme = "README.md" +keywords = [ + "quote", + "shell", + "split", + "unix", + "words", +] +license = "MIT/Apache-2.0" +repository = "https://github.com/tmiasko/shell-words" + +[features] +default = ["std"] +std = [] diff --git a/vendor/shell-words/LICENSE-APACHE b/vendor/shell-words/LICENSE-APACHE new file mode 100644 index 0000000..356ea6f --- /dev/null +++ b/vendor/shell-words/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/shell-words/LICENSE-MIT b/vendor/shell-words/LICENSE-MIT new file mode 100644 index 0000000..eac305d --- /dev/null +++ b/vendor/shell-words/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Tomasz Miąsko + +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. diff --git a/vendor/shell-words/README.md b/vendor/shell-words/README.md new file mode 100644 index 0000000..9b9e563 --- /dev/null +++ b/vendor/shell-words/README.md @@ -0,0 +1,90 @@ +# shell-words + +Process command line according to parsing rules of Unix shell. + +## Usage + +Add this to Cargo.toml: +```toml +[dependencies] +shell-words = "1.0.0" +``` + +Add this to your crate: +```rust +extern crate shell_words; +``` + +## Examples + +### Split + +Compiling C source code into an executable as in default build rule found in GNU Make: + +```rust +extern crate shell_words; + +use std::env::var; +use std::process::Command; + +fn main() { + let cc = var("CC").unwrap_or_else(|_| "cc".to_owned()); + + let cflags = var("CFLAGS").unwrap_or_else(|_| String::new()); + let cflags = shell_words::split(&cflags).expect("failed to parse CFLAGS"); + + let cppflags = var("CPPFLAGS").unwrap_or_else(|_| String::new()); + let cppflags = shell_words::split(&cppflags).expect("failed to parse CPPFLAGS"); + + Command::new(cc) + .args(cflags) + .args(cppflags) + .args(&["-c", "a.c", "-o", "a.out"]) + .spawn() + .expect("failed to start subprocess") + .wait() + .expect("failed to wait for subprocess"); +} +``` + +### Join + +Logging executed commands in format that can be readily copied and pasted to a shell: + +```rust +extern crate shell_words; + +fn main() { + let argv = &["python", "-c", "print('Hello world!')"]; + + println!("Executing: {}", shell_words::join(argv)); + + std::process::Command::new(&argv[0]) + .args(&argv[1..]) + .spawn() + .expect("failed to start subprocess") + .wait() + .expect("failed to wait for subprocess"); +} +``` + +## Bugs + +Please report any issues at https://github.com/tmiasko/shell-words/issues. + +## License + +Licensed under either of + + * Apache License, Version 2.0 + ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license + ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +## Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/vendor/shell-words/rustfmt.toml b/vendor/shell-words/rustfmt.toml new file mode 100644 index 0000000..b2715b2 --- /dev/null +++ b/vendor/shell-words/rustfmt.toml @@ -0,0 +1 @@ +wrap_comments = true diff --git a/vendor/shell-words/src/lib.rs b/vendor/shell-words/src/lib.rs new file mode 100644 index 0000000..b93001f --- /dev/null +++ b/vendor/shell-words/src/lib.rs @@ -0,0 +1,507 @@ +// Copyright 2018 Tomasz Miąsko +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE> +// or the MIT license <LICENSE-MIT>, at your option. +// +//! Process command line according to parsing rules of Unix shell as specified +//! in [Shell Command Language in POSIX.1-2008][posix-shell]. +//! +//! [posix-shell]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html + +#![cfg_attr(not(feature = "std"), no_std)] +#![forbid(unsafe_code)] + +#[cfg(feature = "std")] +extern crate core; + +use core::fmt; +use core::mem; + +#[cfg(not(feature = "std"))] +#[macro_use] +extern crate alloc; + +#[cfg(not(feature = "std"))] +use alloc::string::String; +#[cfg(not(feature = "std"))] +use alloc::vec::Vec; + +#[cfg(not(feature = "std"))] +use alloc::borrow::Cow; +#[cfg(feature = "std")] +use std::borrow::Cow; + +/// An error returned when shell parsing fails. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ParseError; + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("missing closing quote") + } +} + +#[cfg(feature = "std")] +impl std::error::Error for ParseError {} + +enum State { + /// Within a delimiter. + Delimiter, + /// After backslash, but before starting word. + Backslash, + /// Within an unquoted word. + Unquoted, + /// After backslash in an unquoted word. + UnquotedBackslash, + /// Within a single quoted word. + SingleQuoted, + /// Within a double quoted word. + DoubleQuoted, + /// After backslash inside a double quoted word. + DoubleQuotedBackslash, + /// Inside a comment. + Comment, +} + +/// Splits command line into separate arguments, in much the same way Unix shell +/// would, but without many of expansion the shell would perform. +/// +/// The split functionality is compatible with behaviour of Unix shell, but with +/// word expansions limited to quote removal, and without special token +/// recognition rules for operators. +/// +/// The result is exactly the same as one obtained from Unix shell as long as +/// those unsupported features are not present in input: no operators, no +/// variable assignments, no tilde expansion, no parameter expansion, no command +/// substitution, no arithmetic expansion, no pathname expansion. +/// +/// In case those unsupported shell features are present, the syntax that +/// introduce them is interpreted literally. +/// +/// # Errors +/// +/// When input contains unmatched quote, an error is returned. +/// +/// # Compatibility with other implementations +/// +/// It should be fully compatible with g_shell_parse_argv from GLib, except that +/// in GLib it is an error not to have any words after tokenization. +/// +/// It is also very close to shlex.split available in Python standard library, +/// when used in POSIX mode with support for comments. Though, shlex +/// implementation diverges from POSIX, and from implementation contained herein +/// in three aspects. First, it doesn't support line continuations. +/// Second, inside double quotes, the backslash characters retains its special +/// meaning as an escape character only when followed by \\ or \", whereas POSIX +/// specifies that it should retain its special meaning when followed by: $, \`, +/// \", \\, or a newline. Third, it treats carriage return as one of delimiters. +/// +/// # Examples +/// +/// Building an executable using compiler obtained from CC environment variable +/// and compiler flags from both CFLAGS and CPPFLAGS. Similar to default build +/// rule for C used in GNU Make: +/// +/// ```rust,no_run +/// use std::env::var; +/// use std::process::Command; +/// +/// let cc = var("CC").unwrap_or_else(|_| "cc".to_owned()); +/// +/// let cflags_str = var("CFLAGS").unwrap_or_else(|_| String::new()); +/// let cflags = shell_words::split(&cflags_str).expect("failed to parse CFLAGS"); +/// +/// let cppflags_str = var("CPPFLAGS").unwrap_or_else(|_| String::new()); +/// let cppflags = shell_words::split(&cppflags_str).expect("failed to parse CPPFLAGS"); +/// +/// Command::new(cc) +/// .args(cflags) +/// .args(cppflags) +/// .args(&["-c", "a.c", "-o", "a.out"]) +/// .spawn() +/// .expect("failed to start subprocess") +/// .wait() +/// .expect("failed to wait for subprocess"); +/// ``` +pub fn split(s: &str) -> Result<Vec<String>, ParseError> { + use State::*; + + let mut words = Vec::new(); + let mut word = String::new(); + let mut chars = s.chars(); + let mut state = Delimiter; + + loop { + let c = chars.next(); + state = match state { + Delimiter => match c { + None => break, + Some('\'') => SingleQuoted, + Some('\"') => DoubleQuoted, + Some('\\') => Backslash, + Some('\t') | Some(' ') | Some('\n') => Delimiter, + Some('#') => Comment, + Some(c) => { + word.push(c); + Unquoted + } + }, + Backslash => match c { + None => { + word.push('\\'); + words.push(mem::replace(&mut word, String::new())); + break; + } + Some('\n') => Delimiter, + Some(c) => { + word.push(c); + Unquoted + } + }, + Unquoted => match c { + None => { + words.push(mem::replace(&mut word, String::new())); + break; + } + Some('\'') => SingleQuoted, + Some('\"') => DoubleQuoted, + Some('\\') => UnquotedBackslash, + Some('\t') | Some(' ') | Some('\n') => { + words.push(mem::replace(&mut word, String::new())); + Delimiter + } + Some(c) => { + word.push(c); + Unquoted + } + }, + UnquotedBackslash => match c { + None => { + word.push('\\'); + words.push(mem::replace(&mut word, String::new())); + break; + } + Some('\n') => Unquoted, + Some(c) => { + word.push(c); + Unquoted + } + }, + SingleQuoted => match c { + None => return Err(ParseError), + Some('\'') => Unquoted, + Some(c) => { + word.push(c); + SingleQuoted + } + }, + DoubleQuoted => match c { + None => return Err(ParseError), + Some('\"') => Unquoted, + Some('\\') => DoubleQuotedBackslash, + Some(c) => { + word.push(c); + DoubleQuoted + } + }, + DoubleQuotedBackslash => match c { + None => return Err(ParseError), + Some('\n') => DoubleQuoted, + Some(c @ '$') | Some(c @ '`') | Some(c @ '"') | Some(c @ '\\') => { + word.push(c); + DoubleQuoted + } + Some(c) => { + word.push('\\'); + word.push(c); + DoubleQuoted + } + }, + Comment => match c { + None => break, + Some('\n') => Delimiter, + Some(_) => Comment, + }, + } + } + + Ok(words) +} + +enum EscapeStyle { + /// No escaping. + None, + /// Wrap in single quotes. + SingleQuoted, + /// Single quotes combined with backslash. + Mixed, +} + +/// Determines escaping style to use. +fn escape_style(s: &str) -> EscapeStyle { + if s.is_empty() { + return EscapeStyle::SingleQuoted; + } + + let mut special = false; + let mut newline = false; + let mut single_quote = false; + + for c in s.chars() { + match c { + '\n' => { + newline = true; + special = true; + } + '\'' => { + single_quote = true; + special = true; + } + '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '\\' | '"' | ' ' | '\t' | '*' + | '?' | '[' | '#' | '˜' | '=' | '%' => { + special = true; + } + _ => continue, + } + } + + if !special { + EscapeStyle::None + } else if newline && !single_quote { + EscapeStyle::SingleQuoted + } else { + EscapeStyle::Mixed + } +} + +/// Escapes special characters in a string, so that it will retain its literal +/// meaning when used as a part of command in Unix shell. +/// +/// It tries to avoid introducing any unnecessary quotes or escape characters, +/// but specifics regarding quoting style are left unspecified. +pub fn quote(s: &str) -> Cow<str> { + // We are going somewhat out of the way to provide + // minimal amount of quoting in typical cases. + match escape_style(s) { + EscapeStyle::None => s.into(), + EscapeStyle::SingleQuoted => format!("'{}'", s).into(), + EscapeStyle::Mixed => { + let mut quoted = String::new(); + quoted.push('\''); + for c in s.chars() { + if c == '\'' { + quoted.push_str("'\\''"); + } else { + quoted.push(c); + } + } + quoted.push('\''); + quoted.into() + } + } +} + +/// Joins arguments into a single command line suitable for execution in Unix +/// shell. +/// +/// Each argument is quoted using [`quote`] to preserve its literal meaning when +/// parsed by Unix shell. +/// +/// Note: This function is essentially an inverse of [`split`]. +/// +/// # Examples +/// +/// Logging executed commands in format that can be easily copied and pasted +/// into an actual shell: +/// +/// ```rust,no_run +/// fn execute(args: &[&str]) { +/// use std::process::Command; +/// println!("Executing: {}", shell_words::join(args)); +/// Command::new(&args[0]) +/// .args(&args[1..]) +/// .spawn() +/// .expect("failed to start subprocess") +/// .wait() +/// .expect("failed to wait for subprocess"); +/// } +/// +/// execute(&["python", "-c", "print('Hello world!')"]); +/// ``` +/// +/// [`quote`]: fn.quote.html +/// [`split`]: fn.split.html +pub fn join<I, S>(words: I) -> String +where + I: IntoIterator<Item = S>, + S: AsRef<str>, +{ + let mut line = words.into_iter().fold(String::new(), |mut line, word| { + let quoted = quote(word.as_ref()); + line.push_str(quoted.as_ref()); + line.push(' '); + line + }); + line.pop(); + line +} + +#[cfg(test)] +mod tests { + use super::*; + + fn split_ok(cases: &[(&str, &[&str])]) { + for &(input, expected) in cases { + match split(input) { + Err(actual) => { + panic!( + "After split({:?})\nexpected: Ok({:?})\n actual: Err({:?})\n", + input, expected, actual + ); + } + Ok(actual) => { + assert!( + expected == actual.as_slice(), + "After split({:?}).unwrap()\nexpected: {:?}\n actual: {:?}\n", + input, + expected, + actual + ); + } + } + } + } + + #[test] + fn split_empty() { + split_ok(&[("", &[])]); + } + + #[test] + fn split_initial_whitespace_is_removed() { + split_ok(&[ + (" a", &["a"]), + ("\t\t\t\tbar", &["bar"]), + ("\t \nc", &["c"]), + ]); + } + + #[test] + fn split_trailing_whitespace_is_removed() { + split_ok(&[ + ("a ", &["a"]), + ("b\t", &["b"]), + ("c\t \n \n \n", &["c"]), + ("d\n\n", &["d"]), + ]); + } + + #[test] + fn split_carriage_return_is_not_special() { + split_ok(&[("c\ra\r'\r'\r", &["c\ra\r\r\r"])]); + } + + #[test] + fn split_single_quotes() { + split_ok(&[ + (r#"''"#, &[r#""#]), + (r#"'a'"#, &[r#"a"#]), + (r#"'\'"#, &[r#"\"#]), + (r#"' \ '"#, &[r#" \ "#]), + (r#"'#'"#, &[r#"#"#]), + ]); + } + + #[test] + fn split_double_quotes() { + split_ok(&[ + (r#""""#, &[""]), + (r#""""""#, &[""]), + (r#""a b c' d""#, &["a b c' d"]), + (r#""\a""#, &["\\a"]), + (r#""$""#, &["$"]), + (r#""\$""#, &["$"]), + (r#""`""#, &["`"]), + (r#""\`""#, &["`"]), + (r#""\"""#, &["\""]), + (r#""\\""#, &["\\"]), + ("\"\n\"", &["\n"]), + ("\"\\\n\"", &[""]), + ]); + } + + #[test] + fn split_unquoted() { + split_ok(&[ + (r#"\|\&\;"#, &[r#"|&;"#]), + (r#"\<\>"#, &[r#"<>"#]), + (r#"\(\)"#, &[r#"()"#]), + (r#"\$"#, &[r#"$"#]), + (r#"\`"#, &[r#"`"#]), + (r#"\""#, &[r#"""#]), + (r#"\'"#, &[r#"'"#]), + ("\\\n", &[]), + (" \\\n \n", &[]), + ("a\nb\nc", &["a", "b", "c"]), + ("a\\\nb\\\nc", &["abc"]), + ("foo bar baz", &["foo", "bar", "baz"]), + (r#"\🦉"#, &[r"🦉"]), + ]); + } + + #[test] + fn split_trailing_backslash() { + split_ok(&[("\\", &["\\"]), (" \\", &["\\"]), ("a\\", &["a\\"])]); + } + + #[test] + fn split_errors() { + assert_eq!(split("'abc"), Err(ParseError)); + assert_eq!(split("\""), Err(ParseError)); + assert_eq!(split("'\\"), Err(ParseError)); + assert_eq!(split("'\\"), Err(ParseError)); + } + + #[test] + fn split_comments() { + split_ok(&[ + (r#" x # comment "#, &["x"]), + (r#" w1#w2 "#, &["w1#w2"]), + (r#"'not really a # comment'"#, &["not really a # comment"]), + (" a # very long comment \n b # another comment", &["a", "b"]), + ]); + } + + #[test] + fn test_quote() { + assert_eq!(quote(""), "''"); + assert_eq!(quote("'"), "''\\'''"); + assert_eq!(quote("abc"), "abc"); + assert_eq!(quote("a \n b"), "'a \n b'"); + assert_eq!(quote("X'\nY"), "'X'\\''\nY'"); + } + + #[test] + fn test_join() { + assert_eq!(join(&["a", "b", "c"]), "a b c"); + assert_eq!(join(&[" ", "$", "\n"]), "' ' '$' '\n'"); + } + + #[test] + fn join_followed_by_split_is_identity() { + let cases: Vec<&[&str]> = vec![ + &["a"], + &["python", "-c", "print('Hello world!')"], + &["echo", " arg with spaces ", "arg \' with \" quotes"], + &["even newlines are quoted correctly\n", "\n", "\n\n\t "], + &["$", "`test`"], + &["cat", "~user/log*"], + &["test", "'a \"b", "\"X'"], + &["empty", "", "", ""], + ]; + for argv in cases { + let args = join(argv); + assert_eq!(split(&args).unwrap(), argv); + } + } +} |