iforgor 0.3.0

The CLI tool for all those commands you forget about
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use {
    serde::{Deserialize, Serialize},
    sha3::{Digest, Sha3_256},
    std::path::{Path, PathBuf},
};

pub type CommandId = String;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CommandsSource {
    /// Optional metadata about this source file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceMeta>,

    pub entries: Vec<UserCommand>,
}

/// Optional metadata at the top of a domain TOML file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceMeta {
    pub name: Option<String>,
    pub description: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserCommand {
    /// Optional stable ID. If present, used as CommandId instead of content hash.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    pub name: String,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    pub script: String,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<ArgDef>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,

    /// Platform filter. Matches against `std::env::consts::OS` (e.g., "linux", "macos", "windows").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub only_on: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shell: Option<Shell>,

    /// Glob patterns restricting where this command is visible.
    /// Command only shown when CWD matches at least one pattern (OR semantics).
    /// Empty = visible everywhere.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub only_in_dir: Vec<String>,

    #[serde(default)]
    pub risky: bool,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after_run: Option<AfterRun>,

    /// Working directory for script execution, relative to the project root
    /// (parent of the `.iforgor/` folder). If not set, scripts run from the user's CWD.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub working_dir: Option<String>,

    /// Source file this command was loaded from (set at load time, not serialized in source).
    #[serde(skip)]
    pub source_path: Option<PathBuf>,

    /// Project root directory (parent of `.iforgor/`). Set at load time.
    #[serde(skip)]
    pub project_dir: Option<PathBuf>,

    /// Domain name derived from the source file (e.g., "docker" from "docker.toml").
    #[serde(skip)]
    pub domain: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum AfterRun {
    /// Return to menu immediately.
    #[default]
    #[serde(alias = "auto")]
    Auto,
    /// Wait for Enter key.
    #[serde(alias = "wait")]
    Wait,
    /// Wait N seconds with visible countdown, then auto-return.
    #[serde(alias = "delay")]
    Delay(u64),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArgDef {
    /// Variable name used in the script (e.g., "BRANCHES").
    pub name: String,

    /// Prompt shown to the user. Falls back to `name` if not set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,

    /// Argument type. Defaults to text.
    #[serde(default, rename = "type")]
    pub arg_type: ArgType,

    /// Default value for text args.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Fixed list of choices (for select/multi-select).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<String>,

    /// Shell command whose stdout lines provide dynamic choices (for select/multi-select).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,

    /// Shell command to post-process the collected value.
    /// Raw value piped to stdin, stdout becomes the final arg value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_transform: Option<String>,

    /// Mask input with ***** (for passwords/tokens).
    #[serde(default)]
    pub secret: bool,

    /// Whether to remember the last used value across runs.
    /// Defaults to true, but forced to false when `secret` is true.
    /// History is stored in the user's ~/.iforgor/ folder, not in source files.
    #[serde(default = "default_true")]
    pub remember: bool,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum ArgType {
    /// Plain text input.
    #[default]
    #[serde(alias = "text")]
    Text,
    /// Single selection from choices/source.
    #[serde(alias = "select")]
    Select,
    /// Multiple selection from choices/source.
    #[serde(alias = "multi-select", alias = "multi_select")]
    MultiSelect,
}

impl UserCommand {
    /// Returns the explicit id if set, otherwise generates one from script content hash.
    pub fn resolve_id(&self) -> CommandId {
        if let Some(ref id) = self.id {
            return id.clone();
        }
        self.generate_hash_id()
    }

    fn generate_hash_id(&self) -> CommandId {
        let mut hasher = Sha3_256::new();
        hasher.update(self.script.as_bytes());
        let hash = hasher.finalize();
        base16ct::lower::encode_string(&hash)
    }
}

/// Shell configuration. Common shells have shortcuts; custom shells
/// can specify arbitrary command/shebang/extension.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Shell {
    /// A well-known shell by name.
    Predefined(PredefinedShell),
    /// A custom shell with explicit configuration.
    Custom {
        command: String,
        #[serde(default = "default_sh_extension")]
        extension: String,
        #[serde(default)]
        shebang: Option<String>,
    },
}

fn default_sh_extension() -> String {
    ".sh".to_string()
}

impl Default for Shell {
    #[cfg(unix)]
    fn default() -> Self {
        Self::Predefined(PredefinedShell::Sh)
    }

    #[cfg(target_os = "windows")]
    fn default() -> Self {
        Self::Predefined(PredefinedShell::Cmd)
    }
}

impl std::fmt::Display for Shell {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Shell::Predefined(p) => write!(f, "{p}"),
            Shell::Custom { command, .. } => write!(f, "{command}"),
        }
    }
}

impl std::fmt::Display for PredefinedShell {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PredefinedShell::Sh => write!(f, "sh"),
            PredefinedShell::Bash => write!(f, "bash"),
            PredefinedShell::Zsh => write!(f, "zsh"),
            PredefinedShell::Fish => write!(f, "fish"),
            PredefinedShell::Cmd => write!(f, "cmd"),
            PredefinedShell::Powershell => write!(f, "powershell"),
        }
    }
}

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub enum PredefinedShell {
    #[serde(alias = "sh")]
    Sh,
    #[serde(alias = "bash")]
    Bash,
    #[serde(alias = "zsh")]
    Zsh,
    #[serde(alias = "fish")]
    Fish,
    #[serde(alias = "cmd")]
    Cmd,
    #[serde(alias = "powershell")]
    Powershell,
}

/// Returns true if the command should be visible given the current working directory.
/// Commands with an empty `only_in_dir` are always visible.
/// Otherwise, returns true if `current_dir` matches at least one of the glob patterns.
pub fn filter_only_in_dir(current_dir: &Path, command: &UserCommand) -> bool {
    if command.only_in_dir.is_empty() {
        return true;
    }

    command
        .only_in_dir
        .iter()
        .any(|dir_glob| match glob::Pattern::new(dir_glob) {
            Ok(p) => p.matches_path(current_dir),
            Err(e) => {
                eprintln!(
                    "Warning: \"{}\" has invalid `only_in_dir` glob \"{dir_glob}\": {e}",
                    command.name
                );
                false
            }
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cmd_with(only_in_dir: Vec<&str>) -> UserCommand {
        UserCommand {
            id: None,
            name: "test".into(),
            description: None,
            script: "echo hi".into(),
            args: vec![],
            tags: vec![],
            only_on: None,
            shell: None,
            only_in_dir: only_in_dir.into_iter().map(String::from).collect(),
            risky: false,
            after_run: None,
            working_dir: None,
            source_path: None,
            project_dir: None,
            domain: None,
        }
    }

    // -- filter_only_in_dir --

    #[test]
    fn filter_empty_matches_everything() {
        let cmd = cmd_with(vec![]);
        assert!(filter_only_in_dir(Path::new("/anywhere"), &cmd));
    }

    #[test]
    fn filter_single_matching_glob() {
        let cmd = cmd_with(vec!["/home/user/project*"]);
        assert!(filter_only_in_dir(Path::new("/home/user/project"), &cmd));
    }

    #[test]
    fn filter_single_non_matching_glob() {
        let cmd = cmd_with(vec!["/home/user/project*"]);
        assert!(!filter_only_in_dir(Path::new("/other/path"), &cmd));
    }

    #[test]
    fn filter_multiple_globs_or_semantics() {
        let cmd = cmd_with(vec!["/a/*", "/b/*"]);
        assert!(filter_only_in_dir(Path::new("/b/foo"), &cmd));
    }

    #[test]
    fn filter_multiple_globs_none_match() {
        let cmd = cmd_with(vec!["/a/*", "/b/*"]);
        assert!(!filter_only_in_dir(Path::new("/c/foo"), &cmd));
    }

    #[test]
    fn filter_invalid_glob_no_panic() {
        let cmd = cmd_with(vec!["[invalid"]);
        assert!(!filter_only_in_dir(Path::new("/any"), &cmd));
    }

    // -- resolve_id --

    #[test]
    fn resolve_id_explicit() {
        let mut cmd = cmd_with(vec![]);
        cmd.id = Some("my-custom-id".into());
        assert_eq!(cmd.resolve_id(), "my-custom-id");
    }

    #[test]
    fn resolve_id_hash_fallback() {
        let cmd = cmd_with(vec![]);
        let id = cmd.resolve_id();
        assert!(!id.is_empty());
        // Should be hex
        assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn resolve_id_same_script_same_hash() {
        let a = cmd_with(vec![]);
        let mut b = cmd_with(vec![]);
        b.name = "different name".into();
        assert_eq!(a.resolve_id(), b.resolve_id());
    }

    #[test]
    fn resolve_id_different_script_different_hash() {
        let a = cmd_with(vec![]);
        let mut b = cmd_with(vec![]);
        b.script = "echo bye".into();
        assert_ne!(a.resolve_id(), b.resolve_id());
    }

    // -- Shell deserialization --
    // TOML can't deserialize bare values; wrap in a struct.

    #[derive(Deserialize)]
    struct ShellWrap {
        shell: Shell,
    }

    #[derive(Deserialize)]
    struct AfterRunWrap {
        after_run: AfterRun,
    }

    #[test]
    fn shell_predefined() {
        let w: ShellWrap = toml::from_str(r#"shell = "Sh""#).unwrap();
        assert!(matches!(w.shell, Shell::Predefined(PredefinedShell::Sh)));
    }

    #[test]
    fn shell_alias() {
        let w: ShellWrap = toml::from_str(r#"shell = "bash""#).unwrap();
        assert!(matches!(w.shell, Shell::Predefined(PredefinedShell::Bash)));
    }

    #[test]
    fn shell_custom() {
        let w: ShellWrap =
            toml::from_str(r#"shell = { command = "nushell", extension = ".nu" }"#).unwrap();
        match w.shell {
            Shell::Custom {
                command,
                extension,
                shebang,
            } => {
                assert_eq!(command, "nushell");
                assert_eq!(extension, ".nu");
                assert!(shebang.is_none());
            }
            _ => panic!("expected Custom"),
        }
    }

    #[test]
    fn shell_custom_with_shebang() {
        let w: ShellWrap =
            toml::from_str(r##"shell = { command = "x", shebang = "#!/usr/bin/env x" }"##).unwrap();
        match w.shell {
            Shell::Custom { shebang, .. } => {
                assert_eq!(shebang.as_deref(), Some("#!/usr/bin/env x"));
            }
            _ => panic!("expected Custom"),
        }
    }

    // -- AfterRun deserialization --

    #[test]
    fn after_run_auto() {
        let w: AfterRunWrap = toml::from_str(r#"after_run = "auto""#).unwrap();
        assert!(matches!(w.after_run, AfterRun::Auto));
    }

    #[test]
    fn after_run_wait() {
        let w: AfterRunWrap = toml::from_str(r#"after_run = "wait""#).unwrap();
        assert!(matches!(w.after_run, AfterRun::Wait));
    }

    #[test]
    fn after_run_delay() {
        let w: AfterRunWrap = toml::from_str(r#"after_run = { Delay = 5 }"#).unwrap();
        assert!(matches!(w.after_run, AfterRun::Delay(5)));
    }

    // -- ArgDef deserialization --

    #[test]
    fn argdef_text_defaults() {
        let a: ArgDef = toml::from_str(r#"name = "MSG""#).unwrap();
        assert_eq!(a.name, "MSG");
        assert!(matches!(a.arg_type, ArgType::Text));
        assert!(a.remember);
        assert!(!a.secret);
        assert!(a.post_transform.is_none());
    }

    #[test]
    fn argdef_select_with_choices() {
        let a: ArgDef = toml::from_str(
            r#"
            name = "ENV"
            type = "select"
            choices = ["dev", "prod"]
            "#,
        )
        .unwrap();
        assert!(matches!(a.arg_type, ArgType::Select));
        assert_eq!(a.choices, vec!["dev", "prod"]);
    }

    #[test]
    fn argdef_multi_select_with_source() {
        let a: ArgDef = toml::from_str(
            r#"
            name = "BRANCHES"
            type = "multi-select"
            source = "git branch"
            post_transform = "tr '\n' ' '"
            "#,
        )
        .unwrap();
        assert!(matches!(a.arg_type, ArgType::MultiSelect));
        assert_eq!(a.source.as_deref(), Some("git branch"));
        assert!(a.post_transform.is_some());
    }
}