smv 0.4.0

Smart Move - An enhanced mv command with transformation capabilities
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use std::error::Error;
use std::fmt;

/// CNP Grammar Parser for SMV
/// Implements the full CNP grammar specification with filters, routes, and semantic groups

#[derive(Debug, Clone)]
pub struct CnpCommand {
    pub path: String,
    pub filters: Vec<Filter>,
    pub routes: Vec<Route>,
    pub flags: String,
    pub transform_command: Option<TransformCommand>,
    pub remove_command: Option<RemoveCommand>,
    pub case_insensitive: bool,
}

#[derive(Debug, Clone)]
pub struct TransformCommand {
    pub command_type: String,
    pub old_value: Option<String>,
    pub new_value: Option<String>,
}

#[derive(Debug, Clone)]
pub struct RemoveCommand {
    pub command_type: String, // "rm"
    pub preview: bool,
}

#[derive(Debug, Clone)]
pub enum Filter {
    Name(String),
    Type(FileType),
    Extension(String),
    SizeGreater(String),
    SizeLess(String),
    DepthGreater(usize),
    DepthLess(usize),
    ModifiedAfter(String),
    ModifiedBefore(String),
    AccessedAfter(String),
    AccessedBefore(String),
    Tag(String),
    Hash(String),
    Where(Vec<Filter>),
    For(SemanticGroup),
}

#[derive(Debug, Clone)]
pub enum FileType {
    File,
    Folder,
    Symlink,
    Other,
}

#[derive(Debug, Clone)]
pub enum SemanticGroup {
    Notes,    // EXT:md + TYPE:file + common note paths
    Media,    // EXT:jpg/png/gif/webm/mp4 + TYPE:file
    Scripts,  // EXT:sh/py/rb/pl/rs + TYPE:file
    Projects, // TYPE:folder + NAME:src/build/docs
    Configs,  // EXT:conf/ini/yaml/toml/json + TYPE:file
}

#[derive(Debug, Clone)]
pub enum Route {
    To { tool: String, args: Vec<String> }, // TO:tool[:arg1,arg2] - delegate to another CNP tool with optional args
    Into(String),                           // INTO:file - write output to file
    Format(OutputFormat),                   // FORMAT:type - change output format
}

#[derive(Debug, Clone)]
pub enum OutputFormat {
    Json,
    Csv,
    Text,
    Yaml,
}

#[derive(Debug)]
pub struct GrammarParseError {
    pub message: String,
}

impl fmt::Display for GrammarParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "CNP Grammar Parse Error: {}", self.message)
    }
}

impl Error for GrammarParseError {}

pub struct CnpGrammarParser;

impl CnpGrammarParser {
    pub fn parse(args: &[String]) -> Result<CnpCommand, Box<dyn Error>> {
        println!("Debug CNP: parsing args: {:?}", args);
        let mut command = CnpCommand {
            path: ".".to_string(),
            filters: Vec::new(),
            routes: Vec::new(),
            flags: String::new(),
            transform_command: None,
            remove_command: None,
            case_insensitive: false,
        };

        let mut i = 0;
        while i < args.len() {
            let arg = &args[i];

            // Parse CNP filters (UPPERCASE keywords)
            if let Some(filter) = Self::parse_filter(arg)? {
                command.filters.push(filter);
                i += 1;
                continue;
            }

            // Parse CNP routes
            if let Some(route) = Self::parse_route(arg)? {
                command.routes.push(route);
                i += 1;
                continue;
            }

            // Parse SMV remove commands FIRST (before transform commands)
            if let Some(remove) = Self::parse_remove_command(args, &mut i)? {
                command.remove_command = Some(remove);
                continue;
            }

            // Parse SMV transform commands
            if let Some(transform) = Self::parse_transform_command(args, &mut i)? {
                command.transform_command = Some(transform);
                continue;
            }

            // Parse flags (starting with -)
            if let Some(flags) = arg.strip_prefix('-') {
                println!("Debug CNP: parsing flag '{}', current flags: '{}'", flags, command.flags);
                command.flags.push_str(flags);
                println!("Debug CNP: after push, flags: '{}'", command.flags);
                // Check for case-insensitive flag (both CNP standard 'ic' and SMV-specific 'i')
                if flags.contains("ic") || flags.contains('i') {
                    command.case_insensitive = true;
                }
                i += 1;
                continue;
            }

            // Parse path (first non-keyword, non-command argument)
            if command.path == "." && !arg.contains(':') && !arg.starts_with('-') && arg != "rm" {
                command.path = arg.clone();
                i += 1;
                continue;
            }

            i += 1;
        }

        Ok(command)
    }

    fn parse_filter(arg: &str) -> Result<Option<Filter>, Box<dyn Error>> {
        if !arg.contains(':')
            && !arg.starts_with("SIZE")
            && !arg.starts_with("DEPTH")
            && !arg.starts_with("MODIFIED")
            && !arg.starts_with("ACCESSED")
        {
            return Ok(None);
        }

        // Handle SIZE comparisons
        if arg.starts_with("SIZE>") {
            return Ok(Some(Filter::SizeGreater(arg[5..].to_string())));
        }
        if arg.starts_with("SIZE<") {
            return Ok(Some(Filter::SizeLess(arg[5..].to_string())));
        }

        // Handle DEPTH comparisons
        if arg.starts_with("DEPTH>") {
            let value = arg[6..].parse::<usize>().map_err(|_| GrammarParseError {
                message: format!("Invalid depth value: {}", &arg[6..]),
            })?;
            return Ok(Some(Filter::DepthGreater(value)));
        }
        if arg.starts_with("DEPTH<") {
            let value = arg[6..].parse::<usize>().map_err(|_| GrammarParseError {
                message: format!("Invalid depth value: {}", &arg[6..]),
            })?;
            return Ok(Some(Filter::DepthLess(value)));
        }

        // Handle timestamp comparisons
        if arg.starts_with("MODIFIED>") {
            return Ok(Some(Filter::ModifiedAfter(arg[9..].to_string())));
        }
        if arg.starts_with("MODIFIED<") {
            return Ok(Some(Filter::ModifiedBefore(arg[9..].to_string())));
        }
        if arg.starts_with("ACCESSED>") {
            return Ok(Some(Filter::AccessedAfter(arg[9..].to_string())));
        }
        if arg.starts_with("ACCESSED<") {
            return Ok(Some(Filter::AccessedBefore(arg[9..].to_string())));
        }

        // Handle colon-separated filters
        if let Some(colon_pos) = arg.find(':') {
            let key = &arg[..colon_pos];
            let value = &arg[colon_pos + 1..];

            match key {
                "NAME" => Ok(Some(Filter::Name(value.to_string()))),
                "TYPE" => {
                    let file_type = match value.to_lowercase().as_str() {
                        "file" => FileType::File,
                        "folder" | "dir" | "directory" => FileType::Folder,
                        "symlink" | "link" => FileType::Symlink,
                        "other" => FileType::Other,
                        _ => {
                            return Err(Box::new(GrammarParseError {
                                message: format!("Invalid file type: {value}"),
                            }))
                        }
                    };
                    Ok(Some(Filter::Type(file_type)))
                }
                "EXT" => Ok(Some(Filter::Extension(value.to_string()))),
                "TAG" => Ok(Some(Filter::Tag(value.to_string()))),
                "HASH" => Ok(Some(Filter::Hash(value.to_string()))),
                "FOR" => {
                    let semantic_group = match value.to_lowercase().as_str() {
                        "notes" => SemanticGroup::Notes,
                        "media" => SemanticGroup::Media,
                        "scripts" => SemanticGroup::Scripts,
                        "projects" => SemanticGroup::Projects,
                        "configs" => SemanticGroup::Configs,
                        _ => {
                            return Err(Box::new(GrammarParseError {
                                message: format!("Invalid semantic group: {value}"),
                            }))
                        }
                    };
                    Ok(Some(Filter::For(semantic_group)))
                }
                _ => Ok(None), // Unknown filter, ignore
            }
        } else {
            Ok(None)
        }
    }

    fn parse_route(arg: &str) -> Result<Option<Route>, Box<dyn Error>> {
        if !arg.contains(':') {
            return Ok(None);
        }

        if let Some(colon_pos) = arg.find(':') {
            let key = &arg[..colon_pos];
            let value = &arg[colon_pos + 1..];

            match key {
                "TO" => {
                    // Parse TO:tool or TO:tool:arg1,arg2 syntax
                    if let Some(tool_args_pos) = value.find(':') {
                        // Extended syntax: TO:tool:arg1,arg2
                        let tool = value[..tool_args_pos].to_string();
                        let args_str = &value[tool_args_pos + 1..];
                        let args: Vec<String> = args_str
                            .split(',')
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .collect();
                        Ok(Some(Route::To { tool, args }))
                    } else {
                        // Basic syntax: TO:tool
                        Ok(Some(Route::To {
                            tool: value.to_string(),
                            args: Vec::new(),
                        }))
                    }
                }
                "INTO" => Ok(Some(Route::Into(value.to_string()))),
                "FORMAT" => {
                    let format = match value.to_lowercase().as_str() {
                        "json" => OutputFormat::Json,
                        "csv" => OutputFormat::Csv,
                        "text" | "txt" => OutputFormat::Text,
                        "yaml" | "yml" => OutputFormat::Yaml,
                        _ => {
                            return Err(Box::new(GrammarParseError {
                                message: format!("Invalid output format: {value}"),
                            }))
                        }
                    };
                    Ok(Some(Route::Format(format)))
                }
                _ => Ok(None), // Unknown route, ignore
            }
        } else {
            Ok(None)
        }
    }

    fn parse_transform_command(
        args: &[String],
        i: &mut usize,
    ) -> Result<Option<TransformCommand>, Box<dyn Error>> {
        if *i >= args.len() {
            return Ok(None);
        }

        let arg = &args[*i];

        // Check for SMV transform commands
        match arg.to_lowercase().as_str() {
            "change" => {
                if *i + 3 < args.len() && args[*i + 2] == "INTO" {
                    let old_value = args[*i + 1].clone();
                    let new_value = args[*i + 3].clone();
                    *i += 4;
                    return Ok(Some(TransformCommand {
                        command_type: "change".to_string(),
                        old_value: Some(old_value),
                        new_value: Some(new_value),
                    }));
                }
            }
            "regex" => {
                if *i + 3 < args.len() && args[*i + 2] == "INTO" {
                    let pattern = args[*i + 1].clone();
                    let replacement = args[*i + 3].clone();
                    *i += 4;
                    return Ok(Some(TransformCommand {
                        command_type: "regex".to_string(),
                        old_value: Some(pattern),
                        new_value: Some(replacement),
                    }));
                }
            }
            "snake" | "kebab" | "pascal" | "camel" | "title" | "lower" | "upper" | "clean" => {
                *i += 1;
                return Ok(Some(TransformCommand {
                    command_type: arg.clone(),
                    old_value: None,
                    new_value: None,
                }));
            }
            _ => {}
        }

        Ok(None)
    }

    /// Expand semantic groups into concrete filters
    pub fn expand_semantic_groups(filters: &[Filter]) -> Vec<Filter> {
        let mut expanded = Vec::new();

        for filter in filters {
            match filter {
                Filter::For(group) => match group {
                    SemanticGroup::Notes => {
                        expanded.push(Filter::Extension("md".to_string()));
                        expanded.push(Filter::Type(FileType::File));
                    }
                    SemanticGroup::Media => {
                        for ext in ["jpg", "png", "gif", "webm", "mp4", "jpeg", "webp", "svg"] {
                            expanded.push(Filter::Extension(ext.to_string()));
                        }
                        expanded.push(Filter::Type(FileType::File));
                    }
                    SemanticGroup::Scripts => {
                        for ext in ["sh", "py", "rb", "pl", "rs", "js", "ts", "bash", "zsh"] {
                            expanded.push(Filter::Extension(ext.to_string()));
                        }
                        expanded.push(Filter::Type(FileType::File));
                    }
                    SemanticGroup::Projects => {
                        expanded.push(Filter::Type(FileType::Folder));
                        for name in ["src", "build", "docs", "target", "dist", "bin"] {
                            expanded.push(Filter::Name(name.to_string()));
                        }
                    }
                    SemanticGroup::Configs => {
                        for ext in [
                            "conf", "ini", "yaml", "yml", "toml", "json", "config", "cfg",
                        ] {
                            expanded.push(Filter::Extension(ext.to_string()));
                        }
                        expanded.push(Filter::Type(FileType::File));
                    }
                },
                _ => expanded.push(filter.clone()),
            }
        }

        expanded
    }

    fn parse_remove_command(
        args: &[String],
        i: &mut usize,
    ) -> Result<Option<RemoveCommand>, Box<dyn Error>> {
        if *i >= args.len() {
            return Ok(None);
        }

        let arg = &args[*i];

        // Check for rm command
        if arg.to_lowercase() == "rm" {
            *i += 1;
            return Ok(Some(RemoveCommand {
                command_type: "rm".to_string(),
                preview: false, // Will be set based on flags later
            }));
        }

        Ok(None)
    }
}