wsb 0.155.49

Workspace - A tool suite for file operations, version management, and development workflow automation
Documentation
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use anyhow::{Context, Result};
use std::path::Path;

/// A single pattern/substitute pair for batch operations
#[derive(Debug, Clone)]
pub struct PatternPair {
    pub pattern: String,
    pub substitute: String,
}

/// Parse a patterns file into a list of PatternPair entries.
///
/// File format:
/// - One pair per line: PATTERN SUBSTITUTE
/// - Shell-style quoting: single quotes (literal), double quotes (backslash escaping)
/// - Backslash escaping outside quotes
/// - Empty lines and lines starting with # (after trimming) are ignored
/// - Each non-comment, non-empty line must tokenize to exactly 2 tokens
pub fn parse_patterns_file(path: &Path) -> Result<Vec<PatternPair>> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read patterns file: {}", path.display()))?;

    let mut pairs = Vec::new();

    for (line_num, line) in content.lines().enumerate() {
        let trimmed = line.trim();

        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        let tokens = tokenize_shell_line(trimmed).with_context(|| {
            format!(
                "Failed to parse line {} of patterns file: {}",
                line_num + 1,
                path.display()
            )
        })?;

        if tokens.len() != 2 {
            anyhow::bail!(
                "Line {} of patterns file must have exactly 2 tokens (pattern and substitute), found {}: {:?}",
                line_num + 1,
                tokens.len(),
                trimmed
            );
        }

        if tokens[0].is_empty() {
            anyhow::bail!("Line {}: pattern cannot be empty", line_num + 1);
        }

        if tokens[1].is_empty() {
            anyhow::bail!("Line {}: substitute cannot be empty", line_num + 1);
        }

        pairs.push(PatternPair {
            pattern: tokens[0].clone(),
            substitute: tokens[1].clone(),
        });
    }

    if pairs.is_empty() {
        anyhow::bail!(
            "Patterns file is empty or contains only comments: {}",
            path.display()
        );
    }

    Ok(pairs)
}

/// Tokenize a line using shell-style quoting rules:
/// - Single quotes: everything literal until closing single quote
/// - Double quotes: backslash escapes `\\` `\"` `\n` `\t`, everything else literal
/// - Unquoted: whitespace-delimited, backslash escapes next character
fn tokenize_shell_line(line: &str) -> Result<Vec<String>> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut chars = line.chars().peekable();
    let mut in_token = false;

    while let Some(&ch) = chars.peek() {
        match ch {
            '\'' => {
                chars.next();
                in_token = true;
                loop {
                    match chars.next() {
                        Some('\'') => break,
                        Some(c) => current.push(c),
                        None => anyhow::bail!("Unterminated single quote"),
                    }
                }
            }
            '"' => {
                chars.next();
                in_token = true;
                loop {
                    match chars.next() {
                        Some('"') => break,
                        Some('\\') => match chars.next() {
                            Some('\\') => current.push('\\'),
                            Some('"') => current.push('"'),
                            Some('n') => current.push('\n'),
                            Some('t') => current.push('\t'),
                            Some(c) => {
                                current.push('\\');
                                current.push(c);
                            }
                            None => anyhow::bail!("Unterminated escape in double quote"),
                        },
                        Some(c) => current.push(c),
                        None => anyhow::bail!("Unterminated double quote"),
                    }
                }
            }
            '\\' => {
                chars.next();
                in_token = true;
                match chars.next() {
                    Some(c) => current.push(c),
                    None => anyhow::bail!("Trailing backslash"),
                }
            }
            c if c.is_whitespace() => {
                chars.next();
                if in_token {
                    tokens.push(std::mem::take(&mut current));
                    in_token = false;
                }
            }
            c => {
                chars.next();
                current.push(c);
                in_token = true;
            }
        }
    }

    if in_token {
        tokens.push(current);
    }

    Ok(tokens)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // --- Tokenizer unit tests ---

    #[test]
    fn test_tokenize_simple() {
        let tokens = tokenize_shell_line("foo bar").unwrap();
        assert_eq!(tokens, vec!["foo", "bar"]);
    }

    #[test]
    fn test_tokenize_multiple_spaces() {
        let tokens = tokenize_shell_line("foo   bar").unwrap();
        assert_eq!(tokens, vec!["foo", "bar"]);
    }

    #[test]
    fn test_tokenize_tabs_and_spaces() {
        let tokens = tokenize_shell_line("foo\t  bar").unwrap();
        assert_eq!(tokens, vec!["foo", "bar"]);
    }

    #[test]
    fn test_tokenize_single_quotes() {
        let tokens = tokenize_shell_line("'foo bar' baz").unwrap();
        assert_eq!(tokens, vec!["foo bar", "baz"]);
    }

    #[test]
    fn test_tokenize_single_quotes_preserve_backslash() {
        // Inside single quotes, backslashes are literal
        let tokens = tokenize_shell_line(r"'foo\nbar' baz").unwrap();
        assert_eq!(tokens, vec!["foo\\nbar", "baz"]);
    }

    #[test]
    fn test_tokenize_double_quotes() {
        let tokens = tokenize_shell_line(r#""foo bar" baz"#).unwrap();
        assert_eq!(tokens, vec!["foo bar", "baz"]);
    }

    #[test]
    fn test_tokenize_double_quotes_escape_backslash() {
        let tokens = tokenize_shell_line(r#""foo\\bar" baz"#).unwrap();
        assert_eq!(tokens, vec!["foo\\bar", "baz"]);
    }

    #[test]
    fn test_tokenize_double_quotes_escape_quote() {
        let tokens = tokenize_shell_line(r#""foo\"bar" baz"#).unwrap();
        assert_eq!(tokens, vec!["foo\"bar", "baz"]);
    }

    #[test]
    fn test_tokenize_double_quotes_escape_newline() {
        let tokens = tokenize_shell_line(r#""foo\nbar" baz"#).unwrap();
        assert_eq!(tokens, vec!["foo\nbar", "baz"]);
    }

    #[test]
    fn test_tokenize_double_quotes_escape_tab() {
        let tokens = tokenize_shell_line(r#""foo\tbar" baz"#).unwrap();
        assert_eq!(tokens, vec!["foo\tbar", "baz"]);
    }

    #[test]
    fn test_tokenize_double_quotes_unknown_escape_preserved() {
        let tokens = tokenize_shell_line(r#""foo\xbar" baz"#).unwrap();
        assert_eq!(tokens, vec!["foo\\xbar", "baz"]);
    }

    #[test]
    fn test_tokenize_backslash_escape_space() {
        let tokens = tokenize_shell_line(r"foo\ bar baz").unwrap();
        assert_eq!(tokens, vec!["foo bar", "baz"]);
    }

    #[test]
    fn test_tokenize_backslash_escape_backslash() {
        let tokens = tokenize_shell_line(r"foo\\ bar").unwrap();
        assert_eq!(tokens, vec!["foo\\", "bar"]);
    }

    #[test]
    fn test_tokenize_mixed_quoting() {
        let tokens = tokenize_shell_line(r#"'hello world' "goodbye\"cruel" world"#).unwrap();
        assert_eq!(tokens, vec!["hello world", "goodbye\"cruel", "world"]);
    }

    #[test]
    fn test_tokenize_adjacent_quoted_and_unquoted() {
        // foo'bar' should produce "foobar" (adjacent segments merge)
        let tokens = tokenize_shell_line("foo'bar' baz").unwrap();
        assert_eq!(tokens, vec!["foobar", "baz"]);
    }

    #[test]
    fn test_tokenize_empty_string() {
        let tokens = tokenize_shell_line("").unwrap();
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_tokenize_only_whitespace() {
        let tokens = tokenize_shell_line("   \t  ").unwrap();
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_tokenize_single_token() {
        let tokens = tokenize_shell_line("hello").unwrap();
        assert_eq!(tokens, vec!["hello"]);
    }

    #[test]
    fn test_tokenize_three_tokens() {
        let tokens = tokenize_shell_line("a b c").unwrap();
        assert_eq!(tokens, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_unterminated_single_quote() {
        assert!(tokenize_shell_line("'unterminated").is_err());
    }

    #[test]
    fn test_unterminated_double_quote() {
        assert!(tokenize_shell_line(r#""unterminated"#).is_err());
    }

    #[test]
    fn test_trailing_backslash() {
        assert!(tokenize_shell_line(r"foo\").is_err());
    }

    #[test]
    fn test_unterminated_escape_in_double_quote() {
        assert!(tokenize_shell_line(r#""foo\"#).is_err());
    }

    // --- Parser integration tests ---

    #[test]
    fn test_parse_patterns_file_basic() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "foo bar\nbaz qux\n").unwrap();

        let pairs = parse_patterns_file(&file).unwrap();
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0].pattern, "foo");
        assert_eq!(pairs[0].substitute, "bar");
        assert_eq!(pairs[1].pattern, "baz");
        assert_eq!(pairs[1].substitute, "qux");
    }

    #[test]
    fn test_parse_patterns_file_comments_and_blanks() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(
            &file,
            "# comment\n\nfoo bar\n  # indented comment\nbaz qux\n\n",
        )
        .unwrap();

        let pairs = parse_patterns_file(&file).unwrap();
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0].pattern, "foo");
        assert_eq!(pairs[1].pattern, "baz");
    }

    #[test]
    fn test_parse_patterns_file_quoted_values() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "'foo bar' 'baz qux'\n\"hello world\" replacement\n").unwrap();

        let pairs = parse_patterns_file(&file).unwrap();
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0].pattern, "foo bar");
        assert_eq!(pairs[0].substitute, "baz qux");
        assert_eq!(pairs[1].pattern, "hello world");
        assert_eq!(pairs[1].substitute, "replacement");
    }

    #[test]
    fn test_parse_patterns_file_backslash_escaped() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "foo\\ bar baz\n").unwrap();

        let pairs = parse_patterns_file(&file).unwrap();
        assert_eq!(pairs.len(), 1);
        assert_eq!(pairs[0].pattern, "foo bar");
        assert_eq!(pairs[0].substitute, "baz");
    }

    #[test]
    fn test_parse_patterns_file_wrong_token_count_three() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "foo bar baz\n").unwrap();

        let err = parse_patterns_file(&file).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("exactly 2 tokens"), "Error: {}", msg);
    }

    #[test]
    fn test_parse_patterns_file_wrong_token_count_one() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "foo\n").unwrap();

        let err = parse_patterns_file(&file).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("exactly 2 tokens"), "Error: {}", msg);
    }

    #[test]
    fn test_parse_patterns_file_empty() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "# only comments\n\n").unwrap();

        assert!(parse_patterns_file(&file).is_err());
    }

    #[test]
    fn test_parse_patterns_file_nonexistent() {
        assert!(parse_patterns_file(Path::new("/nonexistent/patterns.txt")).is_err());
    }

    #[test]
    fn test_parse_patterns_file_empty_pattern_via_quotes() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "'' bar\n").unwrap();

        let err = parse_patterns_file(&file).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("pattern cannot be empty"), "Error: {}", msg);
    }

    #[test]
    fn test_parse_patterns_file_empty_substitute_via_quotes() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("patterns.txt");
        fs::write(&file, "foo ''\n").unwrap();

        let err = parse_patterns_file(&file).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("substitute cannot be empty"), "Error: {}", msg);
    }
}