1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//! # converter
//!
//! The module which converts the shell script to windows batch script.
//!

#[cfg(test)]
#[path = "./converter_test.rs"]
mod converter_test;

use regex::Regex;

fn replace_flags(arguments: &str, flags_mappings: Vec<(&str, &str)>) -> String {
    let mut windows_arguments = arguments.clone().to_string();

    for flags in flags_mappings {
        let (shell_flag, windows_flag) = flags;

        windows_arguments = match Regex::new(shell_flag) {
            Ok(shell_regex) => {
                let str_value = &shell_regex.replace_all(&windows_arguments, windows_flag);
                str_value.to_string()
            }
            Err(_) => windows_arguments,
        };
    }

    windows_arguments
}

fn replace_full_vars(arguments: &str) -> String {
    let mut parts: Vec<&str> = arguments.split("${").collect();
    let mut buffer = vec![];

    buffer.push(parts.remove(0));

    for part in parts {
        let (before, after, found) = match part.find("}") {
            None => (part, "", false),
            Some(index) => {
                let values = part.split_at(index);

                (values.0, &values.1[1..values.1.len()], true)
            }
        };

        if found {
            buffer.push("%");
        }
        buffer.push(before);

        if found {
            buffer.push("%")
        }

        if after.len() > 0 {
            buffer.push(after);
        }
    }

    buffer.join("").to_string()
}

fn replace_partial_vars(arguments: &str) -> String {
    let mut parts: Vec<&str> = arguments.split('$').collect();
    let mut buffer = vec![];

    buffer.push(parts.remove(0));

    for part in parts {
        let (before, after) = match part.find(" ") {
            None => (part, ""),
            Some(index) => part.split_at(index),
        };

        buffer.push("%");
        buffer.push(before);
        buffer.push("%");

        if after.len() > 0 {
            buffer.push(after);
        }
    }

    buffer.join("").to_string()
}

fn replace_vars(arguments: &str) -> String {
    let mut updated_arguments = replace_full_vars(arguments);
    updated_arguments = replace_partial_vars(&updated_arguments);

    updated_arguments
}

fn add_arguments(arguments: &str, additional_arguments: Vec<(&str)>) -> String {
    let mut windows_arguments = arguments.clone().to_string();

    for additional_argument in additional_arguments {
        windows_arguments.push_str(additional_argument);
    }

    windows_arguments.to_string()
}

fn convert_line(line: &str) -> String {
    if line.starts_with("#") {
        let mut windows_command = String::from(line);
        windows_command.remove(0);
        windows_command.insert_str(0, "@REM ");

        windows_command
    } else {
        // assume first word is the command
        let (shell_command, mut arguments) = match line.find(" ") {
            None => (line, ""),
            Some(index) => line.split_at(index),
        };

        arguments = arguments.trim();

        let (mut windows_command, flags_mappings, additional_arguments) = match shell_command {
            "cp" => ("xcopy".to_string(), vec![("-[rR]", "/E")], vec![]),
            "mv" => ("move".to_string(), vec![], vec![]),
            "ls" => ("dir".to_string(), vec![], vec![]),
            "rm" => {
                let win_cmd = match Regex::new("-[^ ]*[rR]") {
                    Ok(regex_instance) => {
                        if regex_instance.is_match(arguments) {
                            "rmdir".to_string()
                        } else {
                            "del".to_string()
                        }
                    }
                    Err(_) => "del".to_string(),
                };

                let flags_mappings = if win_cmd == "rmdir".to_string() {
                    vec![("-([rR][fF]|[fF][rR]) ", "/S /Q "), ("-[rR]+ ", "/S ")]
                } else {
                    vec![("-[fF] ", "/Q ")]
                };

                (win_cmd, flags_mappings, vec![])
            }
            "mkdir" => ("mkdir".to_string(), vec![("-[pP]", "")], vec![]),
            "clear" => ("cls".to_string(), vec![], vec![]),
            "grep" => ("find".to_string(), vec![], vec![]),
            "pwd" => ("chdir".to_string(), vec![], vec![]),
            "export" => ("set".to_string(), vec![], vec![]),
            "unset" => ("set".to_string(), vec![], vec!["="]),
            _ => (shell_command.to_string(), vec![], vec![]),
        };

        // replace flags
        let mut windows_arguments = if flags_mappings.len() > 0 {
            replace_flags(arguments, flags_mappings)
        } else {
            arguments.to_string()
        };

        // replace vars
        windows_arguments = if windows_arguments.len() > 0 {
            replace_vars(&windows_arguments)
        } else {
            windows_arguments
        };

        // add additional arguments
        windows_arguments = if additional_arguments.len() > 0 {
            add_arguments(&windows_arguments, additional_arguments)
        } else {
            windows_arguments
        };

        if windows_arguments.len() > 0 {
            windows_command.push_str(" ");
            windows_command.push_str(&windows_arguments);
        }

        windows_command
    }
}

/// Converts the provided shell script and returns the windows batch script text.
pub(crate) fn run(script: &str) -> String {
    let lines: Vec<&str> = script.split('\n').collect();
    let mut windows_batch = vec![];

    for mut line in lines {
        line = line.trim();
        let mut line_string = line.to_string();

        // convert line
        let converted_line = if line_string.len() == 0 {
            line_string
        } else {
            convert_line(&mut line_string)
        };

        windows_batch.push(converted_line);
    }

    windows_batch.join("\n")
}