Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

597 lines · 19.4 KiB · Rust

Last changed by

Merge pull request #1333 from tmccombs/rust-170Thayne McCombsbefore adoptiona0370aa

History of this file

Take it

The walk stopped after 200 commits: lines older than cbf3f11 point at it.

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 1–7why, one step back
1mod command;
2mod input;3mod job;4mod token;56use std::borrow::Cow;7use std::ffi::{OsStr, OsString};

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 8–9why, one step back
8use std::io;
9use std::iter;

Make -u idempotentJackson Theelbefore adoptioncbf3f11

line 10why, one step back
10use std::path::{Component, Path, PathBuf, Prefix};

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

line 11why, one step back
11use std::process::Stdio;

Merge pull request #1333 from tmccombs/rust-170Thayne McCombsbefore adoptiona0370aa

line 12why, one step back
12use std::sync::{Mutex, OnceLock};

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 13–14why, one step back
13
14use anyhow::{bail, Result};

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

line 15why, one step back
15use argmax::Command;

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 16–17why, one step back
16use regex::Regex;
17

Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11

line 18why, one step back
18use crate::exit_codes::{merge_exitcodes, ExitCode};

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 19–25why, one step back
19
20use self::command::{execute_commands, handle_cmd_error};21use self::input::{basename, dirname, remove_extension};22pub use self::job::{batch, job};23use self::token::Token;2425/// Execution mode of the command

Fix clippy suggestionsDavid Peterbefore adoption9ea882d

line 26why, one step back
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 27–40why, one step back
27pub enum ExecutionMode {
28 /// Command is executed for each search result29 OneByOne,30 /// Command is run for a batch of results at once31 Batch,32}3334#[derive(Debug, Clone, PartialEq)]35pub struct CommandSet {36 mode: ExecutionMode,37 commands: Vec<CommandTemplate>,38}3940impl CommandSet {

Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e

line 41why, one step back
41 pub fn new<I, T, S>(input: I) -> Result<CommandSet>

Make -u idempotentJackson Theelbefore adoptioncbf3f11

line 42why, one step back
42 where

Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e

lines 43–44why, one step back
43 I: IntoIterator<Item = T>,
44 T: IntoIterator<Item = S>,

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 45–55why, one step back
45 S: AsRef<str>,
46 {47 Ok(CommandSet {48 mode: ExecutionMode::OneByOne,49 commands: input50 .into_iter()51 .map(CommandTemplate::new)52 .collect::<Result<_>>()?,53 })54 }55

Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e

line 56why, one step back
56 pub fn new_batch<I, T, S>(input: I) -> Result<CommandSet>

Make -u idempotentJackson Theelbefore adoptioncbf3f11

line 57why, one step back
57 where

Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e

lines 58–59why, one step back
58 I: IntoIterator<Item = T>,
59 T: IntoIterator<Item = S>,

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 60–83why, one step back
60 S: AsRef<str>,
61 {62 Ok(CommandSet {63 mode: ExecutionMode::Batch,64 commands: input65 .into_iter()66 .map(|args| {67 let cmd = CommandTemplate::new(args)?;68 if cmd.number_of_tokens() > 1 {69 bail!("Only one placeholder allowed for batch commands");70 }71 if cmd.args[0].has_tokens() {72 bail!("First argument of exec-batch is expected to be a fixed executable");73 }74 Ok(cmd)75 })76 .collect::<Result<Vec<_>>>()?,77 })78 }7980 pub fn in_batch_mode(&self) -> bool {81 self.mode == ExecutionMode::Batch82 }83

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 84–87why, one step back
84 pub fn execute(
85 &self,86 input: &Path,87 path_separator: Option<&str>,

Merge pull request #1283 from tmccombs/new-rust-versionTavian Barnesbefore adoptione4bca10

line 88why, one step back
88 out_perm: &Mutex<()>,

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 89–90why, one step back
89 buffer_output: bool,
90 ) -> ExitCode {

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 91–94why, one step back
91 let commands = self
92 .commands93 .iter()94 .map(|c| c.generate(input, path_separator));

Merge pull request #1283 from tmccombs/new-rust-versionTavian Barnesbefore adoptione4bca10

line 95why, one step back
95 execute_commands(commands, out_perm, buffer_output)

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 96–97why, one step back
96 }
97

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 98why, one step back
98 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 99–101why, one step back
99 where
100 I: Iterator<Item = PathBuf>,101 {

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 102–123why, one step back
102 let builders: io::Result<Vec<_>> = self
103 .commands104 .iter()105 .map(|c| CommandBuilder::new(c, limit))106 .collect();107108 match builders {109 Ok(mut builders) => {110 for path in paths {111 for builder in &mut builders {112 if let Err(e) = builder.push(&path, path_separator) {113 return handle_cmd_error(Some(&builder.cmd), e);114 }115 }116 }117118 for builder in &mut builders {119 if let Err(e) = builder.finish() {120 return handle_cmd_error(Some(&builder.cmd), e);121 }122 }123

Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11

line 124why, one step back
124 merge_exitcodes(builders.iter().map(|b| b.exit_code()))

Make -u idempotentJackson Theelbefore adoptioncbf3f11

line 125why, one step back
125 }

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

line 126why, one step back
126 Err(e) => handle_cmd_error(None, e),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 127–130why, one step back
127 }
128 }129}130

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 131–139why, one step back
131/// Represents a multi-exec command as it is built.
132#[derive(Debug)]133struct CommandBuilder {134 pre_args: Vec<OsString>,135 path_arg: ArgumentTemplate,136 post_args: Vec<OsString>,137 cmd: Command,138 count: usize,139 limit: usize,

Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11

line 140why, one step back
140 exit_code: ExitCode,

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 141–151why, one step back
141}
142143impl CommandBuilder {144 fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {145 let mut pre_args = vec![];146 let mut path_arg = None;147 let mut post_args = vec![];148149 for arg in &template.args {150 if arg.has_tokens() {151 path_arg = Some(arg.clone());

Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91

line 152why, one step back
152 } else if path_arg.is_none() {

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 153–167why, one step back
153 pre_args.push(arg.generate("", None));
154 } else {155 post_args.push(arg.generate("", None));156 }157 }158159 let cmd = Self::new_command(&pre_args)?;160161 Ok(Self {162 pre_args,163 path_arg: path_arg.unwrap(),164 post_args,165 cmd,166 count: 0,167 limit,

Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11

line 168why, one step back
168 exit_code: ExitCode::Success,

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 169–201why, one step back
169 })
170 }171172 fn new_command(pre_args: &[OsString]) -> io::Result<Command> {173 let mut cmd = Command::new(&pre_args[0]);174 cmd.stdin(Stdio::inherit());175 cmd.stdout(Stdio::inherit());176 cmd.stderr(Stdio::inherit());177 cmd.try_args(&pre_args[1..])?;178 Ok(cmd)179 }180181 fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {182 if self.limit > 0 && self.count >= self.limit {183 self.finish()?;184 }185186 let arg = self.path_arg.generate(path, separator);187 if !self188 .cmd189 .args_would_fit(iter::once(&arg).chain(&self.post_args))190 {191 self.finish()?;192 }193194 self.cmd.try_arg(arg)?;195 self.count += 1;196 Ok(())197 }198199 fn finish(&mut self) -> io::Result<()> {200 if self.count > 0 {201 self.cmd.try_args(&self.post_args)?;

Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11

lines 202–204why, one step back
202 if !self.cmd.status()?.success() {
203 self.exit_code = ExitCode::GeneralError;204 }

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 205–210why, one step back
205
206 self.cmd = Self::new_command(&self.pre_args)?;207 self.count = 0;208 }209210 Ok(())

Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11

lines 211–214why, one step back
211 }
212213 fn exit_code(&self) -> ExitCode {214 self.exit_code

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

lines 215–217why, one step back
215 }
216}217

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 218–232why, one step back
218/// Represents a template that is utilized to generate command strings.
219///220/// The template is meant to be coupled with an input in order to generate a command. The221/// `generate_and_execute()` method will be used to generate a command and execute it.222#[derive(Debug, Clone, PartialEq)]223struct CommandTemplate {224 args: Vec<ArgumentTemplate>,225}226227impl CommandTemplate {228 fn new<I, S>(input: I) -> Result<CommandTemplate>229 where230 I: IntoIterator<Item = S>,231 S: AsRef<str>,232 {

Merge pull request #1333 from tmccombs/rust-170Thayne McCombsbefore adoptiona0370aa

line 233why, one step back
233 static PLACEHOLDER_PATTERN: OnceLock<Regex> = OnceLock::new();

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 234–243why, one step back
234
235 let mut args = Vec::new();236 let mut has_placeholder = false;237238 for arg in input {239 let arg = arg.as_ref();240241 let mut tokens = Vec::new();242 let mut start = 0;243

Merge pull request #1333 from tmccombs/rust-170Thayne McCombsbefore adoptiona0370aa

lines 244–247why, one step back
244 let pattern =
245 PLACEHOLDER_PATTERN.get_or_init(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());246247 for placeholder in pattern.find_iter(arg) {

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 248–305why, one step back
248 // Leading text before the placeholder.
249 if placeholder.start() > start {250 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));251 }252253 start = placeholder.end();254255 match placeholder.as_str() {256 "{}" => tokens.push(Token::Placeholder),257 "{.}" => tokens.push(Token::NoExt),258 "{/}" => tokens.push(Token::Basename),259 "{//}" => tokens.push(Token::Parent),260 "{/.}" => tokens.push(Token::BasenameNoExt),261 _ => unreachable!("Unhandled placeholder"),262 }263264 has_placeholder = true;265 }266267 // Without a placeholder, the argument is just fixed text.268 if tokens.is_empty() {269 args.push(ArgumentTemplate::Text(arg.to_owned()));270 continue;271 }272273 if start < arg.len() {274 // Trailing text after last placeholder.275 tokens.push(Token::Text(arg[start..].to_owned()));276 }277278 args.push(ArgumentTemplate::Tokens(tokens));279 }280281 // We need to check that we have at least one argument, because if not282 // it will try to execute each file and directory it finds.283 //284 // Sadly, clap can't currently handle this for us, see285 // https://github.com/clap-rs/clap/issues/3542286 if args.is_empty() {287 bail!("No executable provided for --exec or --exec-batch");288 }289290 // If a placeholder token was not supplied, append one at the end of the command.291 if !has_placeholder {292 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));293 }294295 Ok(CommandTemplate { args })296 }297298 fn number_of_tokens(&self) -> usize {299 self.args.iter().filter(|arg| arg.has_tokens()).count()300 }301302 /// Generates and executes a command.303 ///304 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be305 /// build.

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

line 306why, one step back
306 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {

Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91

line 307why, one step back
307 let mut cmd = Command::new(self.args[0].generate(input, path_separator));

Make -u idempotentJackson Theelbefore adoptioncbf3f11

line 308why, one step back
308 for arg in &self.args[1..] {

Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91

line 309why, one step back
309 cmd.try_arg(arg.generate(input, path_separator))?;

Make -u idempotentJackson Theelbefore adoptioncbf3f11

line 310why, one step back
310 }

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

line 311why, one step back
311 Ok(cmd)

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 312–426why, one step back
312 }
313}314315/// Represents a template for a single command argument.316///317/// The argument is either a collection of `Token`s including at least one placeholder variant, or318/// a fixed text.319#[derive(Clone, Debug, PartialEq)]320enum ArgumentTemplate {321 Tokens(Vec<Token>),322 Text(String),323}324325impl ArgumentTemplate {326 pub fn has_tokens(&self) -> bool {327 matches!(self, ArgumentTemplate::Tokens(_))328 }329330 /// Generate an argument from this template. If path_separator is Some, then it will replace331 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by332 /// path separator substitution.333 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {334 use self::Token::*;335 let path = path.as_ref();336337 match *self {338 ArgumentTemplate::Tokens(ref tokens) => {339 let mut s = OsString::new();340 for token in tokens {341 match *token {342 Basename => s.push(Self::replace_separator(basename(path), path_separator)),343 BasenameNoExt => s.push(Self::replace_separator(344 &remove_extension(basename(path).as_ref()),345 path_separator,346 )),347 NoExt => s.push(Self::replace_separator(348 &remove_extension(path),349 path_separator,350 )),351 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),352 Placeholder => {353 s.push(Self::replace_separator(path.as_ref(), path_separator))354 }355 Text(ref string) => s.push(string),356 }357 }358 s359 }360 ArgumentTemplate::Text(ref text) => OsString::from(text),361 }362 }363364 /// Replace the path separator in the input with the custom separator string. If path_separator365 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is366 /// interpreted as a Path and its components are iterated through and re-joined into a new367 /// OsString.368 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {369 // fast-path - no replacement necessary370 if path_separator.is_none() {371 return Cow::Borrowed(path);372 }373374 let path_separator = path_separator.unwrap();375 let mut out = OsString::with_capacity(path.len());376 let mut components = Path::new(path).components().peekable();377378 while let Some(comp) = components.next() {379 match comp {380 // Absolute paths on Windows are tricky. A Prefix component is usually a drive381 // letter or UNC path, and is usually followed by RootDir. There are also382 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to383 // ignore verbatim path prefixes here because they're very rare, might be384 // impossible to reach here, and there's no good way to deal with them. If users385 // are doing something advanced involving verbatim windows paths, they can do their386 // own output filtering with a tool like sed.387 Component::Prefix(prefix) => {388 if let Prefix::UNC(server, share) = prefix.kind() {389 // Prefix::UNC is a parsed version of '\\server\share'390 out.push(path_separator);391 out.push(path_separator);392 out.push(server);393 out.push(path_separator);394 out.push(share);395 } else {396 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for397 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,398 // but they're not returned by directories fd can search anyway so we don't worry399 // about them.400 out.push(comp.as_os_str());401 }402 }403404 // Root directory is always replaced with the custom separator.405 Component::RootDir => out.push(path_separator),406407 // Everything else is joined normally, with a trailing separator if we're not last408 _ => {409 out.push(comp.as_os_str());410 if components.peek().is_some() {411 out.push(path_separator);412 }413 }414 }415 }416 Cow::Owned(out)417 }418}419420#[cfg(test)]421mod tests {422 use super::*;423424 #[test]425 fn tokens_with_placeholder() {426 assert_eq!(

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 427why, one step back
427 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 428–443why, one step back
428 CommandSet {
429 commands: vec![CommandTemplate {430 args: vec![431 ArgumentTemplate::Text("echo".into()),432 ArgumentTemplate::Text("${SHELL}:".into()),433 ArgumentTemplate::Tokens(vec![Token::Placeholder]),434 ]435 }],436 mode: ExecutionMode::OneByOne,437 }438 );439 }440441 #[test]442 fn tokens_with_no_extension() {443 assert_eq!(

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 444why, one step back
444 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 445–459why, one step back
445 CommandSet {
446 commands: vec![CommandTemplate {447 args: vec![448 ArgumentTemplate::Text("echo".into()),449 ArgumentTemplate::Tokens(vec![Token::NoExt]),450 ],451 }],452 mode: ExecutionMode::OneByOne,453 }454 );455 }456457 #[test]458 fn tokens_with_basename() {459 assert_eq!(

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 460why, one step back
460 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 461–475why, one step back
461 CommandSet {
462 commands: vec![CommandTemplate {463 args: vec![464 ArgumentTemplate::Text("echo".into()),465 ArgumentTemplate::Tokens(vec![Token::Basename]),466 ],467 }],468 mode: ExecutionMode::OneByOne,469 }470 );471 }472473 #[test]474 fn tokens_with_parent() {475 assert_eq!(

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 476why, one step back
476 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 477–491why, one step back
477 CommandSet {
478 commands: vec![CommandTemplate {479 args: vec![480 ArgumentTemplate::Text("echo".into()),481 ArgumentTemplate::Tokens(vec![Token::Parent]),482 ],483 }],484 mode: ExecutionMode::OneByOne,485 }486 );487 }488489 #[test]490 fn tokens_with_basename_no_extension() {491 assert_eq!(

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 492why, one step back
492 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 493–507why, one step back
493 CommandSet {
494 commands: vec![CommandTemplate {495 args: vec![496 ArgumentTemplate::Text("echo".into()),497 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),498 ],499 }],500 mode: ExecutionMode::OneByOne,501 }502 );503 }504505 #[test]506 fn tokens_multiple() {507 assert_eq!(

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 508why, one step back
508 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 509–527why, one step back
509 CommandSet {
510 commands: vec![CommandTemplate {511 args: vec![512 ArgumentTemplate::Text("cp".into()),513 ArgumentTemplate::Tokens(vec![Token::Placeholder]),514 ArgumentTemplate::Tokens(vec![515 Token::BasenameNoExt,516 Token::Text(".ext".into())517 ]),518 ],519 }],520 mode: ExecutionMode::OneByOne,521 }522 );523 }524525 #[test]526 fn tokens_single_batch() {527 assert_eq!(

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 528why, one step back
528 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 529–542why, one step back
529 CommandSet {
530 commands: vec![CommandTemplate {531 args: vec![532 ArgumentTemplate::Text("echo".into()),533 ArgumentTemplate::Tokens(vec![Token::NoExt]),534 ],535 }],536 mode: ExecutionMode::Batch,537 }538 );539 }540541 #[test]542 fn tokens_multiple_batch() {

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 543why, one step back
543 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 544–552why, one step back
544 }
545546 #[test]547 fn template_no_args() {548 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());549 }550551 #[test]552 fn command_set_no_args() {

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 553why, one step back
553 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());

Make -u idempotentJackson Theelbefore adoptioncbf3f11

lines 554–597why, one step back
554 }
555556 #[test]557 fn generate_custom_path_separator() {558 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);559 macro_rules! check {560 ($input:expr, $expected:expr) => {561 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));562 };563 }564565 check!("foo", "foo");566 check!("foo/bar", "foo#bar");567 check!("/foo/bar/baz", "#foo#bar#baz");568 }569570 #[cfg(windows)]571 #[test]572 fn generate_custom_path_separator_windows() {573 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);574 macro_rules! check {575 ($input:expr, $expected:expr) => {576 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));577 };578 }579580 // path starting with a drive letter581 check!(r"C:\foo\bar", "C:#foo#bar");582 // UNC path583 check!(r"\\server\share\path", "##server#share#path");584 // Drive Relative path - no separator after the colon omits the RootDir path component.585 // This is uncommon, but valid586 check!(r"C:foo\bar", "C:foo#bar");587588 // forward slashes should get normalized and interpreted as separators589 check!("C:/foo/bar", "C:#foo#bar");590 check!("C:foo/bar", "C:foo#bar");591592 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal593 // absolute path that begins with RootDir, and the two slashes get combined together as594 // a single path separator during normalization.595 //check!("//server/share/path", "##server#share#path");596 }597}