Quellcode durchsuchen

refactor: moved things around to easy up the tree implementation

I am still having trouble to implement json tree with the current data
If I can't find anything I might refactor a bit of the code to have
a different type of data structure saved to then be printed at once
MartinFillon vor 2 Jahren
Ursprung
Commit
b337360b52
4 geänderte Dateien mit 181 neuen und 26 gelöschten Zeilen
  1. 93 22
      src/output/details.rs
  2. 2 0
      src/output/table.rs
  3. 7 4
      src/output/tree.rs
  4. 79 0
      test.json

+ 93 - 22
src/output/details.rs

@@ -222,24 +222,14 @@ impl<'a> Render<'a> {
         Ok(())
     }
 
-    fn print_row<W: Write>(
+    fn print_row_contents(
         &self,
-        w: &mut W,
+        w: &mut impl Write,
         row: &TextCell,
         header: &Option<TextCell>,
         file_num: usize,
     ) -> io::Result<()> {
-        let last = if file_num == self.files.len() - 1 {
-            "\n}"
-        } else {
-            "\n},"
-        };
-        if self.opts.header {
-            writeln!(w, "{{")?;
-        } else {
-            writeln!(w, "[")?;
-        }
-        let mut header_idx = 0usize;
+        let mut j: usize = 0;
         for (i, cell) in row.contents.iter().enumerate() {
             if cell.is_empty() || cell.trim().is_empty() {
                 continue;
@@ -253,11 +243,27 @@ impl<'a> Render<'a> {
                 writeln!(w, ", ")?;
             }
         }
-        if self.opts.header {
-            writeln!(w, "{last}")
-        } else {
-            writeln!(w, "]")
+        Ok(())
+    }
+
+    fn print_row<W: Write>(
+        &self,
+        w: &mut W,
+        header: &Option<TextCell>,
+        iter: &mut JsonTableIter<'_>,
+        current_depth: i32,
+        idx: &mut usize,
+    ) -> io::Result<()> {
+        let (row, depth) = iter.next().unwrap();
+        self.print_row_contents(w, &row, header)?;
+        writeln!(w, ", \"depth\": {}", depth.depth.0)?;
+        writeln!(w, ", \"current\": {}", current_depth)?;
+        if depth.depth.0 as i32 > current_depth {
+            writeln!(w, ", \"children\": [{{")?;
+            writeln!(w, "}}]")?;
         }
+        *idx += 1;
+        Ok(())
     }
 
     pub fn render_json<W: Write>(self, w: &mut W) -> io::Result<()> {
@@ -290,16 +296,35 @@ impl<'a> Render<'a> {
             );
 
             writeln!(w, "{{")?;
-            let mut row_iter = self.iterate_with_table(table.unwrap(), rows);
+            let mut row_iter = self.iterate_with_table_json(table.unwrap(), rows);
             let header = if self.opts.header {
-                let header = row_iter.next().unwrap().clean_content();
-                Some(header)
+                let (header, _) = row_iter.next().unwrap();
+                Some(header.clean_content())
             } else {
                 None
             };
+            let mut i = 0;
+            let len = row_iter.len();
             writeln!(w, "\"files\":[")?;
-            for (i, row) in row_iter.enumerate() {
-                self.print_row(w, &row, &(header.clone()), i)?;
+
+            let current_depth: i32 = 0;
+
+            while row_iter.len() > 0 {
+                if self.opts.header {
+                    writeln!(w, "{{")?;
+                } else {
+                    writeln!(w, "[")?;
+                }
+                writeln!(w, "\"index\": {},", i)?;
+                self.print_row(w, &(header.clone()), &mut row_iter, current_depth, &mut i)?;
+                if self.opts.header {
+                    writeln!(w, "}}")?;
+                } else {
+                    writeln!(w, "]")?;
+                }
+                if i < len {
+                    writeln!(w, ",")?;
+                }
             }
             writeln!(w, "]\n}}")?;
         } else {
@@ -541,6 +566,18 @@ impl<'a> Render<'a> {
         }
     }
 
+    pub fn iterate_with_table_json(
+        &'a self,
+        table: Table<'a>,
+        rows: Vec<Row>,
+    ) -> JsonTableIter<'a> {
+        JsonTableIter {
+            total_width: table.widths().total(),
+            table,
+            inner: rows.into_iter(),
+        }
+    }
+
     pub fn iterate(&'a self, rows: Vec<Row>) -> Iter {
         Iter {
             tree_trunk: TreeTrunk::default(),
@@ -550,6 +587,7 @@ impl<'a> Render<'a> {
     }
 }
 
+#[derive(Clone)]
 pub struct Row {
     /// Vector of cells to display.
     ///
@@ -606,6 +644,39 @@ impl<'a> Iterator for TableIter<'a> {
     }
 }
 
+#[derive(Clone)]
+pub struct JsonTableIter<'a> {
+    inner: VecIntoIter<Row>,
+    table: Table<'a>,
+
+    total_width: usize,
+}
+
+impl<'a> Iterator for JsonTableIter<'a> {
+    type Item = (TextCell, TreeParams);
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.inner.next().map(|row| {
+            let mut cell = if let Some(cells) = row.cells {
+                self.table.render(cells)
+            } else {
+                let mut cell = TextCell::default();
+                cell.add_spaces(self.total_width);
+                cell
+            };
+
+            cell.append(row.name.concat_content());
+            (cell, row.tree)
+        })
+    }
+}
+
+impl JsonTableIter<'_> {
+    pub fn len(&self) -> usize {
+        self.inner.len()
+    }
+}
+
 pub struct Iter {
     tree_trunk: TreeTrunk,
     tree_style: Style,

+ 2 - 0
src/output/table.rs

@@ -394,6 +394,7 @@ impl Environment {
 
 static ENVIRONMENT: Lazy<Environment> = Lazy::new(Environment::load_all);
 
+#[derive(Clone)]
 pub struct Table<'a> {
     columns: Vec<Column>,
     theme: &'a Theme,
@@ -632,6 +633,7 @@ impl<'a> Table<'a> {
     }
 }
 
+#[derive(Clone)]
 pub struct TableWidths(Vec<usize>);
 
 impl Deref for TableWidths {

+ 7 - 4
src/output/tree.rs

@@ -83,13 +83,13 @@ pub struct TreeTrunk {
 pub struct TreeParams {
     /// How many directories deep into the tree structure this is. Directories
     /// on top have depth 0.
-    depth: TreeDepth,
+    pub depth: TreeDepth,
 
     /// Whether this is the last entry in the directory.
-    last: bool,
+    pub last: bool,
 }
 
-#[derive(Debug, Copy, Clone)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
 pub struct TreeDepth(pub usize);
 
 impl TreeTrunk {
@@ -141,7 +141,10 @@ impl TreeTrunk {
 
 impl TreeParams {
     pub fn new(depth: TreeDepth, last: bool) -> Self {
-        Self { depth, last }
+        Self {
+            depth,
+            last,
+        }
     }
 
     pub fn is_at_root(&self) -> bool {

+ 79 - 0
test.json

@@ -0,0 +1,79 @@
+{
+    "files": [
+        {
+            "index": 0,
+            "Permissions": "drwxr-xr-x",
+            "Size": "-",
+            "User": "fexkoser",
+            "Date Modified": "22 Jan 14:29",
+            "Name": "/home/fexkoser/dev/eza-test",
+            "depth": 0,
+            "current": 0
+        },
+        {
+            "index": 1,
+            "Permissions": "drwxr-xr-x",
+            "Size": "-",
+            "User": "fexkoser",
+            "Date Modified": "22 Jan 14:29",
+            "Name": "caca",
+            "depth": 1,
+            "current": 0,
+            "children": [
+                {}
+            ]
+        },
+        {
+            "index": 2,
+            "Permissions": ".rw-r--r--",
+            "Size": "0",
+            "User": "fexkoser",
+            "Date Modified": "22 Jan 14:29",
+            "Name": "FruitBox.cpp",
+            "depth": 2,
+            "current": 0,
+            "children": [
+                {}
+            ]
+        },
+        {
+            "index": 3,
+            "Permissions": ".rw-r--r--",
+            "Size": "0",
+            "User": "fexkoser",
+            "Date Modified": "22 Jan 14:29",
+            "Name": "FruitBox.hpp",
+            "depth": 2,
+            "current": 0,
+            "children": [
+                {}
+            ]
+        },
+        {
+            "index": 4,
+            "Permissions": ".rw-r--r--",
+            "Size": "0",
+            "User": "fexkoser",
+            "Date Modified": "22 Jan 14:29",
+            "Name": "FruitBoxs.hpp",
+            "depth": 2,
+            "current": 0,
+            "children": [
+                {}
+            ]
+        },
+        {
+            "index": 5,
+            "Permissions": ".rw-r--r--",
+            "Size": "534",
+            "User": "fexkoser",
+            "Date Modified": "22 Jan 14:29",
+            "Name": "test.json",
+            "depth": 1,
+            "current": 0,
+            "children": [
+                {}
+            ]
+        }
+    ]
+}