about summary refs log tree commit diff stats
path: root/sys/nixpkgs/pkgs/lf-make-map/src
diff options
context:
space:
mode:
authorBenedikt Peetz <benedikt.peetz@b-peetz.de>2024-05-09 13:20:13 +0200
committerBenedikt Peetz <benedikt.peetz@b-peetz.de>2024-05-09 13:20:13 +0200
commit16c7608bcfb876866abd62b65276951ee2a81b54 (patch)
tree8cf0cbb52c8212747e0c3a90df0ffb844fb91f7e /sys/nixpkgs/pkgs/lf-make-map/src
parentfeat(pkgs/lf-make-map): Support depths > 2 (diff)
downloadnixos-config-16c7608bcfb876866abd62b65276951ee2a81b54.tar.gz
nixos-config-16c7608bcfb876866abd62b65276951ee2a81b54.zip
feat(pkgs/lf-make-map): Add de-serialization to lf mappings
Diffstat (limited to 'sys/nixpkgs/pkgs/lf-make-map/src')
-rw-r--r--sys/nixpkgs/pkgs/lf-make-map/src/cli.rs29
-rw-r--r--sys/nixpkgs/pkgs/lf-make-map/src/main.rs18
-rw-r--r--sys/nixpkgs/pkgs/lf-make-map/src/mapping/error.rs9
-rw-r--r--sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/iterator.rs20
-rw-r--r--sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/lf_mapping.rs19
-rw-r--r--sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/mod.rs38
-rw-r--r--sys/nixpkgs/pkgs/lf-make-map/src/mapping/mod.rs17
7 files changed, 91 insertions, 59 deletions
diff --git a/sys/nixpkgs/pkgs/lf-make-map/src/cli.rs b/sys/nixpkgs/pkgs/lf-make-map/src/cli.rs
index 7650b39b..a398e451 100644
--- a/sys/nixpkgs/pkgs/lf-make-map/src/cli.rs
+++ b/sys/nixpkgs/pkgs/lf-make-map/src/cli.rs
@@ -1,6 +1,6 @@
 use std::path::PathBuf;
 
-use clap::{ArgAction, Parser};
+use clap::{ArgAction, Parser, Subcommand};
 
 /// An automatic lf cd mapping generator
 #[derive(Parser, Debug)]
@@ -11,9 +11,6 @@ pub struct Args {
     #[arg(long, short = 'n', env = "HOME")]
     pub home_name: PathBuf,
 
-    /// The directories to generate mappings for
-    pub relevant_directories: Vec<PathBuf>,
-
     /// The number of directories to generate mappings for, starting from each `relevant_directory`
     #[arg(long, short, default_value = "2")]
     pub depth: usize,
@@ -25,4 +22,28 @@ pub struct Args {
     /// Silence all output
     #[arg(long, short = 'q')]
     pub quiet: bool,
+
+    #[command(subcommand)]
+    pub command: Command,
+}
+
+#[derive(Subcommand, Debug)]
+pub enum Command {
+    /// Visualize the generated mappings in a tree
+    Visualize {
+        #[command(flatten)]
+        options: CommandOptions,
+    },
+
+    /// Output the generated mappings in a format suitable for the lf config file
+    Generate {
+        #[command(flatten)]
+        options: CommandOptions,
+    },
+}
+
+#[derive(Debug, Parser)]
+pub struct CommandOptions {
+    /// The directories to generate mappings for
+    pub relevant_directories: Vec<PathBuf>,
 }
diff --git a/sys/nixpkgs/pkgs/lf-make-map/src/main.rs b/sys/nixpkgs/pkgs/lf-make-map/src/main.rs
index ccda1f14..aaf79b20 100644
--- a/sys/nixpkgs/pkgs/lf-make-map/src/main.rs
+++ b/sys/nixpkgs/pkgs/lf-make-map/src/main.rs
@@ -2,8 +2,8 @@ use std::path::{Path, PathBuf};
 
 use anyhow::{Context, Result};
 use clap::Parser;
-use cli::Args;
-use log::{debug, trace};
+use cli::{Args, Command};
+use log::trace;
 use mapping::map_tree::MappingTree;
 use walkdir::{DirEntry, WalkDir};
 
@@ -26,7 +26,12 @@ fn main() -> anyhow::Result<()> {
 
     let mut mappings = MappingTree::new();
 
-    for dir in args.relevant_directories {
+    let relevant_directories = match &args.command {
+        Command::Visualize { options } => &options.relevant_directories,
+        Command::Generate { options } => &options.relevant_directories,
+    };
+
+    for dir in relevant_directories {
         trace!("Processing '{}'..", dir.display());
         let path = strip_path(&dir, &args.home_name)?;
 
@@ -39,7 +44,7 @@ fn main() -> anyhow::Result<()> {
 
     let mut current_depth = 1;
     while current_depth != args.depth {
-        for (key, value) in mappings.iter() {
+        for (key, value) in mappings.iter(false) {
             trace!(
                 "Adding to child ('{}' -> '{}')",
                 MapKey::display(&key),
@@ -87,7 +92,10 @@ fn main() -> anyhow::Result<()> {
         current_depth += 1;
     }
 
-    println!("{}", mappings);
+    match args.command {
+        Command::Visualize { .. } => println!("{}", mappings),
+        Command::Generate { .. } => println!("{}", mappings.to_lf_mappings(args.home_name)),
+    }
 
     Ok(())
 }
diff --git a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/error.rs b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/error.rs
deleted file mode 100644
index ac772430..00000000
--- a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/error.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-use thiserror::Error;
-
-use super::MapKey;
-
-#[derive(Error, Debug)]
-pub enum Error {
-    #[error("The node at key '{}' already exists!", MapKey::display(&.0))]
-    NodeExits(Vec<MapKey>),
-}
diff --git a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/iterator.rs b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/iterator.rs
index 33c27540..4364bb2b 100644
--- a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/iterator.rs
+++ b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/iterator.rs
@@ -7,14 +7,18 @@ pub struct MappingTreeIterator {
 }
 
 impl MappingTreeIterator {
-    pub fn new(tree: &MappingTree) -> Self {
-        let children = extract_child(vec![], &tree.root);
+    pub fn new(tree: &MappingTree, ignore_extendable: bool) -> Self {
+        let children = extract_child(vec![], &tree.root, ignore_extendable);
 
         Self { children }
     }
 }
 
-fn extract_child(current_key: Vec<MapKey>, node: &Node) -> Vec<(Vec<MapKey>, String)> {
+fn extract_child(
+    current_key: Vec<MapKey>,
+    node: &Node,
+    ignore_extendable: bool,
+) -> Vec<(Vec<MapKey>, String)> {
     match &node.value {
         NodeValue::Parent { children } => children
             .iter()
@@ -22,15 +26,19 @@ fn extract_child(current_key: Vec<MapKey>, node: &Node) -> Vec<(Vec<MapKey>, Str
                 let mut new_key = current_key.clone();
                 new_key.push(key.to_owned());
 
-                extract_child(new_key, value)
+                extract_child(new_key, value, ignore_extendable)
             })
             .flatten()
             .collect(),
         NodeValue::Child { path, extandable } => {
-            if *extandable {
+            if ignore_extendable {
                 vec![(current_key, path.to_string())]
             } else {
-                vec![]
+                if *extandable {
+                    vec![(current_key, path.to_string())]
+                } else {
+                    vec![]
+                }
             }
         }
     }
diff --git a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/lf_mapping.rs b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/lf_mapping.rs
new file mode 100644
index 00000000..6d9c7a0d
--- /dev/null
+++ b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/lf_mapping.rs
@@ -0,0 +1,19 @@
+use std::path::PathBuf;
+
+use crate::mapping::MapKey;
+
+use super::MappingTree;
+
+impl MappingTree {
+    pub fn to_lf_mappings(self, home_path: PathBuf) -> String {
+        self.iter(true)
+            .map(|(key, value)| {
+                format!(
+                    "map g{} cd \"{}\"\n",
+                    MapKey::display(&key),
+                    home_path.join(&value).display()
+                )
+            })
+            .collect()
+    }
+}
diff --git a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/mod.rs b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/mod.rs
index 44adc483..35e6d91d 100644
--- a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/mod.rs
+++ b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/map_tree/mod.rs
@@ -9,6 +9,7 @@ use super::MapKey;
 
 pub mod display;
 pub mod iterator;
+pub mod lf_mapping;
 
 /// A prefix tree
 #[derive(Debug)]
@@ -38,22 +39,8 @@ impl MappingTree {
         &self.root
     }
 
-    pub fn iter(&self) -> MappingTreeIterator {
-        MappingTreeIterator::new(&self)
-    }
-
-    /// Returns the node at the key, otherwise None
-    pub fn get(&self, key: &[MapKey]) -> Option<&Node> {
-        let mut current_node = &self.root;
-        for ch in key.iter() {
-            if let NodeValue::Parent { children } = &current_node.value {
-                current_node = children.get(&ch)?
-            } else {
-                return None;
-            }
-        }
-
-        Some(current_node)
+    pub fn iter(&self, ignore_extendable: bool) -> MappingTreeIterator {
+        MappingTreeIterator::new(&self, ignore_extendable)
     }
 
     /// Returns the node at the key, otherwise None. The node can be changed
@@ -126,7 +113,11 @@ impl MappingTree {
             }
         ));
 
-        let child_value = if let NodeValue::Child { path, extandable } = child_value {
+        let child_value = if let NodeValue::Child {
+            path,
+            extandable: _,
+        } = child_value
+        {
             NodeValue::Child {
                 path,
                 extandable: false,
@@ -147,18 +138,6 @@ impl MappingTree {
         Ok(())
     }
 
-    pub fn replace_node(&mut self, key: &[MapKey], node: Node) -> Node {
-        let parent = self.get_mut(&key[..key.len() - 1]).expect("Must be some");
-
-        if let NodeValue::Parent { children } = &mut parent.value {
-            children
-                .insert(key[key.len() - 1].clone(), node)
-                .expect("This must exist, otherwise insert would have been used")
-        } else {
-            unreachable!("All parent nodes should be parent nodes");
-        }
-    }
-
     pub fn insert_node(&mut self, key: &[MapKey], node: Node) -> Result<()> {
         let (_node, found_key) = self.try_get(key).clone();
 
@@ -348,7 +327,6 @@ Please rename the paths to fix this.
                     foreign_key[0].part_path,
                 );
             }
-            assert_eq!(our_key.len(), foreign_key.len());
 
             debug!(
                 "Found a better one: '{}' ('{}') and '{}' ('{}')",
diff --git a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/mod.rs b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/mod.rs
index 129e9673..114fdca0 100644
--- a/sys/nixpkgs/pkgs/lf-make-map/src/mapping/mod.rs
+++ b/sys/nixpkgs/pkgs/lf-make-map/src/mapping/mod.rs
@@ -5,7 +5,6 @@ use std::{
 
 use log::debug;
 
-pub mod error;
 pub mod map_tree;
 
 #[derive(Clone, Debug, Eq)]
@@ -77,7 +76,6 @@ impl MapKey {
 
             generated_chars
         };
-        assert_eq!(added_chars.len(), new_resolution,);
 
         let part_path = self.part_path.clone();
         let output: Vec<Self> = added_chars
@@ -101,6 +99,15 @@ impl MapKey {
         fn make(pat: char, part: &str, number_of_chars: usize) -> String {
             let mut acc = String::new();
 
+            if !part.split(pat).all(|part| part.len() > 0) {
+                panic!(
+                    "\
+Can't turn this path '{}' to a mapping.
+This should not happen, please report the bug!",
+                    part
+                )
+            }
+
             let mut last_working = None;
             for i in 0..number_of_chars {
                 for str in part.split(pat) {
@@ -123,9 +130,9 @@ impl MapKey {
             acc
         }
 
-        let value = if part.contains('_') {
+        let value = if part.contains('_') && !part.starts_with('_') && !part.ends_with('_') {
             make('_', part, number_of_chars)
-        } else if part.contains('-') {
+        } else if part.contains('-') && !part.starts_with('-') && !part.ends_with('-') {
             make('-', part, number_of_chars)
         } else {
             part.chars().take(number_of_chars).collect::<String>()
@@ -134,7 +141,7 @@ impl MapKey {
         assert_eq!(
             value.len(),
             number_of_chars,
-            "'{}' is not {}",
+            "'{}' does not have expected length of: {}",
             value,
             number_of_chars
         );