Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

174 lines · 6.5 KiB · Rust

Last changed by

Relicense under MIT/Apache-2.0Antti Keränenbefore adoption701b8f2

History of this file

Take it

Relicense under MIT/Apache-2.0Antti Keränenbefore adoption701b8f2

lines 1–8why, one step back
1// Copyright (c) 2017 fd developers
2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.8

Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07

lines 9–12why, one step back
9// TODO: Possible optimization could avoid pushing characters on a buffer.
10mod ticket;11mod token;12mod job;

Escape exec InputsMichael Aaron Murphybefore adoption6a01faf

line 13why, one step back
13mod input;

Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07

lines 14–17why, one step back
14
15use std::path::Path;16use std::sync::{Arc, Mutex};17

Escape exec InputsMichael Aaron Murphybefore adoption6a01faf

lines 18–19why, one step back
18// use self::paths::{basename, dirname, remove_extension};
19use self::input::Input;

Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07

lines 20–120why, one step back
20use self::ticket::CommandTicket;
21use self::token::Token;22pub use self::job::job;2324/// Signifies that a placeholder token was found25const PLACE: u8 = 1;2627/// Signifies that the '{' character was found.28const OPEN: u8 = 2;2930/// Contains a collection of `Token`'s that are utilized to generate command strings.31///32/// The tokens are a represntation of the supplied command template, and are meant to be coupled33/// with an input in order to generate a command. The `generate()` method will be used to34/// generate a command and obtain a ticket for executing that command.35#[derive(Debug, Clone, PartialEq)]36pub struct TokenizedCommand {37 pub tokens: Vec<Token>,38}3940impl TokenizedCommand {41 pub fn new(input: &str) -> TokenizedCommand {42 let mut tokens = Vec::new();43 let mut start = 0;44 let mut flags = 0;45 let mut chars = input.char_indices();46 let mut text = String::new();4748 while let Some((id, character)) = chars.next() {49 match character {50 // Backslashes are useful in cases where we want to use the '{' character51 // without having all occurrences of it to collect placeholder tokens.52 '\\' => {53 if let Some((_, nchar)) = chars.next() {54 if nchar != '{' {55 text.push(character);56 }57 text.push(nchar);58 }59 }60 // When a raw '{' is discovered, we will note it's position, and use that for a61 // later comparison against valid placeholder tokens.62 '{' if flags & OPEN == 0 => {63 flags |= OPEN;64 start = id;65 if !text.is_empty() {66 append(&mut tokens, &text);67 text.clear();68 }69 }70 // If the `OPEN` bit is set, we will compare the contents between the discovered71 // '{' and '}' characters against a list of valid tokens, then pushing the72 // corresponding token onto the `tokens` vector.73 '}' if flags & OPEN != 0 => {74 flags ^= OPEN;75 match &input[start + 1..id] {76 "" => tokens.push(Token::Placeholder),77 "." => tokens.push(Token::NoExt),78 "/" => tokens.push(Token::Basename),79 "//" => tokens.push(Token::Parent),80 "/." => tokens.push(Token::BasenameNoExt),81 _ => {82 append(&mut tokens, &input[start..id + 1]);83 continue;84 }85 }86 flags |= PLACE;87 }88 // We aren't collecting characters for a text string if the `OPEN` bit is set.89 _ if flags & OPEN != 0 => (),90 // Push the character onto the text buffer91 _ => text.push(character),92 }93 }9495 // Take care of any stragglers left behind.96 if !text.is_empty() {97 append(&mut tokens, &text);98 }99100 // If a placeholder token was not supplied, append one at the end of the command.101 if flags & PLACE == 0 {102 append(&mut tokens, " ");103 tokens.push(Token::Placeholder)104 }105106 TokenizedCommand { tokens: tokens }107 }108109 /// Generates a ticket that is required to execute the generated command.110 ///111 /// Using the internal `tokens` field, and a supplied `input` variable, commands will be112 /// written into the `command` buffer. Once all tokens have been processed, the mutable113 /// reference of the `command` will be wrapped within a `CommandTicket`, which will be114 /// responsible for executing the command and clearing the buffer.115 pub fn generate<'a>(116 &self,117 command: &'a mut String,118 input: &Path,119 out_perm: Arc<Mutex<()>>,120 ) -> CommandTicket<'a> {

Escape exec InputsMichael Aaron Murphybefore adoption6a01faf

lines 121–122why, one step back
121 use self::Token::*;
122 let input = input.strip_prefix(".").unwrap_or(input).to_string_lossy();

Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07

lines 123–124why, one step back
123 for token in &self.tokens {
124 match *token {

Escape exec InputsMichael Aaron Murphybefore adoption6a01faf

lines 125–127why, one step back
125 Basename => *command += &Input::new(&input).basename().get(),
126 BasenameNoExt => {127 *command += &Input::new(&input).basename().remove_extension().get()

Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07

line 128why, one step back
128 }

Escape exec InputsMichael Aaron Murphybefore adoption6a01faf

lines 129–132why, one step back
129 NoExt => *command += &Input::new(&input).remove_extension().get(),
130 Parent => *command += &Input::new(&input).dirname().get(),131 Placeholder => *command += &Input::new(&input).get(),132 Text(ref string) => *command += string,

Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07

lines 133–174why, one step back
133 }
134 }135136 CommandTicket::new(command, out_perm)137 }138}139140/// If the last token is a text token, append to that token. Otherwise, create a new token.141fn append(tokens: &mut Vec<Token>, elem: &str) {142 // Useful to avoid a borrowing issue with the tokens vector.143 let mut append_text = false;144145 // If the last token is a `Text` token, simply the `elem` at the end.146 match tokens.last_mut() {147 Some(&mut Token::Text(ref mut string)) => *string += elem,148 _ => append_text = true,149 };150151 // Otherwise, we will need to add a new `Text` token that contains the `elem`152 if append_text {153 tokens.push(Token::Text(String::from(elem)));154 }155}156157#[cfg(test)]158mod tests {159 use super::{TokenizedCommand, Token};160161 #[test]162 fn tokens() {163 let expected = TokenizedCommand {164 tokens: vec![Token::Text("echo ${SHELL}: ".into()), Token::Placeholder],165 };166167 assert_eq!(TokenizedCommand::new("echo $\\{SHELL}: {}"), expected);168 assert_eq!(TokenizedCommand::new("echo ${SHELL}:"), expected);169 assert_eq!(170 TokenizedCommand::new("echo {.}"),171 TokenizedCommand { tokens: vec![Token::Text("echo ".into()), Token::NoExt] }172 );173 }174}