mekle 0.2.0

Fast project discovery tool for developers
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! The command line, the configuration file, and how they layer.
//!
//! Settings come from four sources, each overriding the one before it: the
//! defaults embedded at compile time, the system configuration file, the
//! user's configuration file, and the command line.

use crate::{
    completions::CompletionShell,
    error::{Error, Result},
    fs, paths,
};
use clap::{Args, CommandFactory, Parser, Subcommand};
use serde::Deserialize;
use std::{
    num::NonZeroUsize,
    path::{Path, PathBuf},
};

const DEFAULT_CONFIG: &str = include_str!("../config/config.toml");
const SYSTEM_CONFIG_PATH: &str = "/etc/xdg/mekle/config.toml";

#[derive(Debug, Parser, Clone)]
#[command(
    author,
    version,
    about = "Find coding projects in specified directories"
)]
struct Cli {
    #[command(subcommand)]
    command: Option<CliCommand>,

    #[command(flatten)]
    search: SearchArgs,
}

/// The options that shape a search, shared by the bare invocation and `add`.
#[derive(Debug, Args, Clone)]
struct SearchArgs {
    #[arg(help = "Directories to search")]
    paths: Vec<PathBuf>,

    #[arg(short, long, help = "Maximum search depth")]
    depth: Option<usize>,

    #[arg(short, long, help = "Print search progress")]
    verbose: bool,

    #[arg(short = 'n', long, help = "Maximum number of results")]
    max_results: Option<NonZeroUsize>,

    #[arg(long, conflicts_with = "null", help = "Print newline-delimited JSON")]
    json: bool,

    #[arg(
        short = '0',
        long,
        conflicts_with = "json",
        help = "Print uncontracted paths separated by NUL bytes"
    )]
    null: bool,

    #[arg(
        long,
        value_name = "PATTERN",
        help = "Exclude entries matching a gitignore-style pattern, relative to each search directory"
    )]
    exclude: Vec<String>,
}

#[derive(Debug, Subcommand, Clone)]
enum CliCommand {
    /// Generates shell completions.
    Completions { shell: CompletionShell },
    /// Generates a shell integration that defines `m`.
    Init { shell: CompletionShell },
    /// Records a visit to a project directory.
    Add {
        #[arg(help = "Project directory to record")]
        path: PathBuf,
    },
    /// Holds a project above the frecency ranking.
    Pin {
        #[arg(help = "Project directory to pin")]
        path: PathBuf,
    },
    /// Returns a project to the frecency ranking.
    Unpin {
        #[arg(help = "Project directory to unpin")]
        path: PathBuf,
    },

    /// Inspects or changes project history.
    History {
        #[command(subcommand)]
        command: HistoryCommand,
    },
}

/// What the user asked mekle to do.
#[derive(Debug)]
pub enum Invocation {
    Find(Config),
    Completions(CompletionShell),
    Init(CompletionShell),
    Add { path: PathBuf, config: Config },
    Pin { path: PathBuf, config: Config },
    Unpin { path: PathBuf, config: Config },
    History(HistoryCommand),
}

/// How discovered projects are printed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum OutputFormat {
    #[default]
    Path,
    Json,
    Null,
}

#[derive(Debug, Subcommand, Clone)]
pub enum HistoryCommand {
    /// Lists every recorded project.
    List,
    /// Shows one recorded project.
    Show {
        #[arg(help = "Project directory to inspect")]
        path: PathBuf,
    },
    /// Sets a project's raw score.
    Set {
        #[arg(help = "Project directory to change")]
        path: PathBuf,
        #[arg(help = "New raw score")]
        score: f64,
    },
    /// Adds a positive or negative amount to a project's raw score.
    Adjust {
        #[arg(help = "Project directory to change")]
        path: PathBuf,
        #[arg(allow_hyphen_values = true, help = "Amount to add to the raw score")]
        delta: f64,
    },
    /// Removes one project from history.
    Remove {
        #[arg(help = "Project directory to remove")]
        path: PathBuf,
    },
    /// Removes projects whose paths no longer exist.
    Prune,
    /// Removes every project from history.
    Clear,
}

/// The configuration file, where every setting is optional.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct FileConfig {
    search_dirs: Option<Vec<PathBuf>>,
    marker_files: Option<Vec<String>>,
    workspace_files: Option<Vec<String>>,
    exclude: Option<Vec<String>>,
    depth: Option<usize>,
    verbose: Option<bool>,
    max_results: Option<NonZeroUsize>,
}

/// The effective settings for one run.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(rename = "search_dirs")]
    pub paths: Vec<PathBuf>,
    pub marker_files: Vec<String>,
    pub workspace_files: Vec<String>,
    #[serde(default)]
    pub exclude: Vec<String>,
    pub depth: usize,
    pub verbose: bool,
    #[serde(default)]
    pub max_results: Option<NonZeroUsize>,
    #[serde(skip)]
    pub output: OutputFormat,
}

impl Invocation {
    /// Loads the requested command and its effective configuration.
    ///
    /// # Errors
    ///
    /// Returns an error when the configuration file cannot be read or parsed.
    pub fn load() -> Result<Self> {
        let user_config_path = paths::config_file();
        Self::from_cli(
            Cli::parse(),
            Some(Path::new(SYSTEM_CONFIG_PATH)),
            user_config_path.as_deref(),
        )
    }

    fn from_cli(
        cli: Cli,
        system_config_path: Option<&Path>,
        user_config_path: Option<&Path>,
    ) -> Result<Self> {
        let home = paths::home();
        let Cli { command, search } = cli;

        match command {
            Some(CliCommand::Completions { shell }) => Ok(Self::Completions(shell)),
            Some(CliCommand::Init { shell }) => Ok(Self::Init(shell)),
            Some(CliCommand::Add { path }) => Ok(Self::Add {
                path: paths::expand_tilde(&path, home.as_deref()),
                config: Config::from_sources(search, system_config_path, user_config_path)?,
            }),
            Some(CliCommand::Pin { path }) => Ok(Self::Pin {
                path: paths::expand_tilde(&path, home.as_deref()),
                config: Config::from_sources(search, system_config_path, user_config_path)?,
            }),
            Some(CliCommand::Unpin { path }) => Ok(Self::Unpin {
                path: paths::expand_tilde(&path, home.as_deref()),
                config: Config::from_sources(search, system_config_path, user_config_path)?,
            }),
            Some(CliCommand::History { command }) => {
                Ok(Self::History(command.expand_path(home.as_deref())))
            }
            None => {
                Config::from_sources(search, system_config_path, user_config_path).map(Self::Find)
            }
        }
    }
}

/// Builds the complete command definition.
#[must_use]
pub fn cli_command() -> clap::Command {
    Cli::command()
}

impl HistoryCommand {
    fn expand_path(self, home: Option<&Path>) -> Self {
        match self {
            Self::Show { path } => Self::Show {
                path: paths::expand_tilde(&path, home),
            },
            Self::Set { path, score } => Self::Set {
                path: paths::expand_tilde(&path, home),
                score,
            },
            Self::Adjust { path, delta } => Self::Adjust {
                path: paths::expand_tilde(&path, home),
                delta,
            },
            Self::Remove { path } => Self::Remove {
                path: paths::expand_tilde(&path, home),
            },
            command @ (Self::List | Self::Prune | Self::Clear) => command,
        }
    }
}

impl Config {
    /// Returns the embedded defaults.
    ///
    /// # Errors
    ///
    /// Returns an error if the embedded TOML is invalid.
    pub fn defaults() -> Result<Self> {
        toml::from_str(DEFAULT_CONFIG).map_err(|source| Error::ParseDefaultConfig { source })
    }

    fn from_sources(
        cli: SearchArgs,
        system_config_path: Option<&Path>,
        user_config_path: Option<&Path>,
    ) -> Result<Self> {
        let mut config = Self::defaults()?;

        for path in [system_config_path, user_config_path].into_iter().flatten() {
            if let Some(file) = read_config_file(path)? {
                file.apply_to(&mut config);
            }
        }

        cli.apply_to(&mut config);
        let home = paths::home();
        for path in &mut config.paths {
            *path = paths::expand_tilde(path, home.as_deref());
        }

        Ok(config)
    }
}

/// Overwrites `target` when the layer above supplied a value.
fn overlay<T>(target: &mut T, value: Option<T>) {
    if let Some(value) = value {
        *target = value;
    }
}

impl FileConfig {
    fn apply_to(self, config: &mut Config) {
        overlay(&mut config.paths, self.search_dirs);
        overlay(&mut config.marker_files, self.marker_files);
        overlay(&mut config.workspace_files, self.workspace_files);
        overlay(&mut config.exclude, self.exclude);
        overlay(&mut config.depth, self.depth);
        overlay(&mut config.verbose, self.verbose);
        config.max_results = self.max_results.or(config.max_results);
    }
}

impl SearchArgs {
    fn apply_to(self, config: &mut Config) {
        config.output = self.output_format();
        config.max_results = self.max_results.or(config.max_results);
        overlay(&mut config.depth, self.depth);
        if self.verbose {
            config.verbose = true;
        }
        if !self.paths.is_empty() {
            config.paths = self.paths;
        }
        // Exclusions accumulate: the command line narrows a configured search
        // rather than replacing it.
        config.exclude.extend(self.exclude);
    }

    const fn output_format(&self) -> OutputFormat {
        if self.json {
            OutputFormat::Json
        } else if self.null {
            OutputFormat::Null
        } else {
            OutputFormat::Path
        }
    }
}

fn read_config_file(path: &Path) -> Result<Option<FileConfig>> {
    fs::read(path)?
        .map(|contents| {
            toml::from_str(&contents).map_err(|source| Error::ParseConfig {
                path: path.to_path_buf(),
                source,
            })
        })
        .transpose()
}

#[cfg(test)]
mod tests {
    use super::*;
    use claims::{assert_none, assert_ok, assert_some};
    use std::fs::write;
    use tempfile::TempDir;

    /// Parses `args` and layers it over `path`, the way a run would.
    fn config_from(args: &[&str], path: Option<&Path>) -> Result<Config> {
        let cli = Cli::try_parse_from(args).expect("the arguments parse");
        Config::from_sources(cli.search, None, path)
    }

    /// Writes a configuration file holding `contents` and returns its path.
    fn config_file(temp: &TempDir, contents: &str) -> PathBuf {
        let path = temp.path().join("config.toml");
        write(&path, contents).expect("write the configuration file");
        path
    }

    #[test]
    fn defaults_are_used_without_a_config_file() -> Result<()> {
        let config = config_from(&["mekle"], None)?;

        assert_eq!(config.paths, [PathBuf::from(".")]);
        assert_eq!(config.depth, 5);
        assert!(config.exclude.is_empty());
        assert!(config.marker_files.iter().any(|file| file == "Cargo.toml"));
        assert!(
            config
                .workspace_files
                .iter()
                .any(|file| file == "pnpm-workspace.yaml")
        );
        assert_none!(config.max_results);
        assert_eq!(config.output, OutputFormat::Path);
        Ok(())
    }

    #[test]
    fn file_values_replace_built_in_defaults() -> Result<()> {
        let temp = TempDir::new().expect("create temp dir");
        let path = config_file(
            &temp,
            r#"
search_dirs = ["/projects"]
marker_files = ["project.toml"]
workspace_files = ["workspace.toml"]
depth = 12
verbose = true
max_results = 20
"#,
        );

        let config = config_from(&["mekle"], Some(&path))?;

        assert_eq!(config.paths, [PathBuf::from("/projects")]);
        assert_eq!(config.marker_files, ["project.toml"]);
        assert_eq!(config.workspace_files, ["workspace.toml"]);
        assert_eq!(config.depth, 12);
        assert!(config.verbose);
        assert_eq!(config.max_results.map(NonZeroUsize::get), Some(20));
        Ok(())
    }

    #[test]
    fn user_config_overrides_system_config() -> Result<()> {
        let temp = TempDir::new().expect("create temp dir");
        let system = temp.path().join("system.toml");
        let user = temp.path().join("user.toml");
        write(&system, "search_dirs = [\"/system\"]\ndepth = 8\n").expect("write system config");
        write(&user, "search_dirs = [\"/user\"]\n").expect("write user config");
        let cli = Cli::try_parse_from(["mekle"]).expect("arguments parse");

        let system_only = Config::from_sources(cli.search.clone(), Some(&system), None)?;
        assert_eq!(system_only.paths, [PathBuf::from("/system")]);
        assert_eq!(system_only.depth, 8);

        let config = Config::from_sources(cli.search, Some(&system), Some(&user))?;

        assert_eq!(config.paths, [PathBuf::from("/user")]);
        assert_eq!(config.depth, 8);
        Ok(())
    }

    #[test]
    fn command_line_values_override_the_file() -> Result<()> {
        let temp = TempDir::new().expect("create temp dir");
        let path = config_file(
            &temp,
            "search_dirs = [\"/from-file\"]\ndepth = 12\nmax_results = 20\n",
        );

        let config = config_from(
            &["mekle", "--depth", "3", "--max-results", "2", "/from-cli"],
            Some(&path),
        )?;

        assert_eq!(config.paths, [PathBuf::from("/from-cli")]);
        assert_eq!(config.depth, 3);
        assert_eq!(config.max_results.map(NonZeroUsize::get), Some(2));
        Ok(())
    }

    #[test]
    fn missing_config_file_is_ignored() {
        let temp = TempDir::new().expect("create temp dir");

        assert_ok!(config_from(
            &["mekle"],
            Some(&temp.path().join("missing.toml"))
        ));
    }

    #[test]
    fn configured_search_dirs_are_expanded() -> Result<()> {
        let temp = TempDir::new().expect("create temp dir");
        let path = config_file(&temp, "search_dirs = [\"~/repos\", \"/absolute\"]\n");
        let home = assert_some!(paths::home());

        let config = config_from(&["mekle"], Some(&path))?;

        assert_eq!(
            config.paths,
            [home.join("repos"), PathBuf::from("/absolute")]
        );
        Ok(())
    }

    #[test]
    fn exclusions_are_loaded_from_the_file() -> Result<()> {
        let temp = TempDir::new().expect("create temp dir");
        let path = config_file(
            &temp,
            "exclude = [\"target/\", \"**/vendor/\", \"/archive/\"]\n",
        );

        let config = config_from(&["mekle"], Some(&path))?;

        assert_eq!(config.exclude, ["target/", "**/vendor/", "/archive/"]);
        Ok(())
    }

    #[test]
    fn repeated_cli_exclusions_are_collected() -> Result<()> {
        let config = config_from(
            &[
                "mekle",
                "--exclude",
                "target/",
                "--exclude",
                "node_modules/",
            ],
            None,
        )?;

        assert_eq!(config.exclude, ["target/", "node_modules/"]);
        Ok(())
    }

    #[test]
    fn cli_exclusions_append_to_configured_ones() -> Result<()> {
        let temp = TempDir::new().expect("create temp dir");
        let path = config_file(&temp, "exclude = [\"target/\"]\n");

        let config = config_from(&["mekle", "--exclude", "dist/"], Some(&path))?;

        assert_eq!(config.exclude, ["target/", "dist/"]);
        Ok(())
    }

    #[test]
    fn add_carries_the_search_configuration() -> Result<()> {
        let cli = Cli::try_parse_from(["mekle", "add", "/projects/one"]).expect("arguments parse");

        let invocation = Invocation::from_cli(cli, None, None)?;

        match invocation {
            Invocation::Add { path, config } => {
                assert_eq!(path, PathBuf::from("/projects/one"));
                assert_eq!(config.depth, 5);
            }
            other => panic!("expected an add invocation, got {other:?}"),
        }
        Ok(())
    }

    #[test]
    fn pin_and_unpin_resolve_a_project_the_way_add_does() -> Result<()> {
        let home = assert_some!(paths::home());

        for args in [["mekle", "pin", "~/one"], ["mekle", "unpin", "~/one"]] {
            let cli = Cli::try_parse_from(args).expect("arguments parse");

            match Invocation::from_cli(cli, None, None)? {
                Invocation::Pin { path, config } | Invocation::Unpin { path, config } => {
                    assert_eq!(path, home.join("one"));
                    assert_eq!(config.depth, 5);
                }
                other => panic!("expected a pin invocation, got {other:?}"),
            }
        }
        Ok(())
    }

    #[test]
    fn a_bare_invocation_searches() -> Result<()> {
        let cli = Cli::try_parse_from(["mekle", "--json"]).expect("arguments parse");

        match Invocation::from_cli(cli, None, None)? {
            Invocation::Find(config) => assert_eq!(config.output, OutputFormat::Json),
            other => panic!("expected a find invocation, got {other:?}"),
        }
        Ok(())
    }
}