void-cli 0.0.3

CLI for void — anonymous encrypted source control
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
//! ls-tree command - list contents of a tree at a given commit.
//!
//! Lists files and directories in a commit's tree, similar to git ls-tree.
//! Supports filtering by path prefix and recursive listing.

use std::collections::BTreeSet;
use std::path::Path;

use serde::Serialize;
use void_core::{
    cid,
    crypto::{CommitReader, EncryptedCommit},

    store::ObjectStoreExt,
};

use crate::context::{open_repo, resolve_ref, void_err_to_cli};
use crate::output::{run_command, CliError, CliOptions};

/// A single entry in the ls-tree output.
#[derive(Debug, Clone, Serialize)]
pub struct TreeEntry {
    /// File mode (040000 for tree, 100644 for blob)
    pub mode: String,
    /// Entry type (tree or blob)
    #[serde(rename = "type")]
    pub entry_type: String,
    /// Full path of the entry
    pub path: String,
    /// Size in bytes (0 for directories)
    pub size: u64,
}

/// JSON output for the ls-tree command.
#[derive(Debug, Clone, Serialize)]
pub struct LsTreeOutput {
    /// CID of the commit
    pub commit: String,
    /// Path prefix filter (if any)
    pub path: String,
    /// List of entries
    pub entries: Vec<TreeEntry>,
}

/// Collect all file entries from the commit's manifest.
fn collect_all_entries(
    store: &impl ObjectStoreExt,
    commit: &void_core::metadata::Commit,
    reader: &CommitReader,
) -> Result<Vec<(String, u64)>, CliError> {
    let manifest = void_core::metadata::manifest_tree::TreeManifest::from_commit(store, commit, reader)
        .map_err(void_err_to_cli)?
        .ok_or_else(|| CliError::internal("commit has no manifest_cid"))?;

    let mut entries: Vec<(String, u64)> = manifest
        .iter()
        .map(|me| {
            let me = me.map_err(void_err_to_cli)?;
            Ok((me.path.clone(), me.length))
        })
        .collect::<Result<_, CliError>>()?;

    entries.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(entries)
}

/// Filter entries to only those under the given path prefix.
fn filter_by_path(entries: Vec<(String, u64)>, path_prefix: &str) -> Vec<(String, u64)> {
    if path_prefix.is_empty() {
        return entries;
    }

    let prefix = if path_prefix.ends_with('/') {
        path_prefix.to_string()
    } else {
        format!("{}/", path_prefix)
    };

    entries
        .into_iter()
        .filter(|(p, _)| p.starts_with(&prefix) || p == path_prefix.trim_end_matches('/'))
        .collect()
}

/// Get the immediate parent directory of a path.
fn parent_dir(path: &str) -> Option<&str> {
    path.rfind('/').map(|idx| &path[..idx])
}

/// Collapse entries to immediate children of the given path prefix (non-recursive mode).
/// Returns both files and inferred directories.
fn collapse_to_immediate_children(
    entries: Vec<(String, u64)>,
    path_prefix: &str,
) -> Vec<TreeEntry> {
    let prefix = if path_prefix.is_empty() {
        String::new()
    } else if path_prefix.ends_with('/') {
        path_prefix.to_string()
    } else {
        format!("{}/", path_prefix)
    };

    // Track directories we've already added
    let mut seen_dirs: BTreeSet<String> = BTreeSet::new();
    let mut result: Vec<TreeEntry> = Vec::new();

    for (path, size) in entries {
        // Skip if path doesn't start with prefix (but handle root case)
        if !prefix.is_empty() && !path.starts_with(&prefix) {
            continue;
        }

        // Get the relative path after the prefix
        let relative = if prefix.is_empty() {
            path.as_str()
        } else {
            &path[prefix.len()..]
        };

        // Check if this is an immediate child or needs directory inference
        if let Some(slash_idx) = relative.find('/') {
            // This file is in a subdirectory
            let dir_name = &relative[..slash_idx];
            let full_dir_path = if prefix.is_empty() {
                format!("{}/", dir_name)
            } else {
                format!("{}{}/", prefix, dir_name)
            };

            if !seen_dirs.contains(&full_dir_path) {
                seen_dirs.insert(full_dir_path.clone());
                result.push(TreeEntry {
                    mode: "040000".to_string(),
                    entry_type: "tree".to_string(),
                    path: full_dir_path,
                    size: 0,
                });
            }
        } else {
            // This is an immediate child file
            result.push(TreeEntry {
                mode: "100644".to_string(),
                entry_type: "blob".to_string(),
                path,
                size,
            });
        }
    }

    // Sort by path
    result.sort_by(|a, b| a.path.cmp(&b.path));
    result
}

/// Expand all entries (recursive mode) - include files and their parent directories.
fn expand_recursive(entries: Vec<(String, u64)>, path_prefix: &str) -> Vec<TreeEntry> {
    let prefix = if path_prefix.is_empty() {
        String::new()
    } else if path_prefix.ends_with('/') {
        path_prefix.to_string()
    } else {
        format!("{}/", path_prefix)
    };

    // Track directories we've seen
    let mut seen_dirs: BTreeSet<String> = BTreeSet::new();
    let mut result: Vec<TreeEntry> = Vec::new();

    for (path, size) in entries {
        // Skip if path doesn't start with prefix (but handle root case)
        if !prefix.is_empty() && !path.starts_with(&prefix) {
            continue;
        }

        // Add all parent directories
        let mut current = path.as_str();
        while let Some(parent) = parent_dir(current) {
            if !parent.is_empty() {
                let dir_path = format!("{}/", parent);
                // Only add if within the path prefix
                if prefix.is_empty()
                    || dir_path.starts_with(&prefix)
                    || prefix.starts_with(&dir_path)
                {
                    if !seen_dirs.contains(&dir_path) {
                        seen_dirs.insert(dir_path.clone());
                    }
                }
            }
            current = parent;
        }

        // Add the file entry
        result.push(TreeEntry {
            mode: "100644".to_string(),
            entry_type: "blob".to_string(),
            path,
            size,
        });
    }

    // Add directory entries
    for dir in seen_dirs {
        // Only include directories that are within or descendants of the prefix
        if prefix.is_empty() || dir.starts_with(&prefix) {
            result.push(TreeEntry {
                mode: "040000".to_string(),
                entry_type: "tree".to_string(),
                path: dir,
                size: 0,
            });
        }
    }

    // Sort by path
    result.sort_by(|a, b| a.path.cmp(&b.path));
    result
}

/// Run the ls-tree command.
///
/// Lists files and directories in a commit's tree.
///
/// # Arguments
/// * `cwd` - Current working directory
/// * `commit_ref` - Commit reference (HEAD, branch, tag, or CID)
/// * `path_filter` - Optional path prefix to filter
/// * `name_only` - Show only filenames (no mode/type/size)
/// * `recursive` - Recurse into subdirectories
/// * `opts` - CLI options
pub fn run(
    cwd: &Path,
    commit_ref: &str,
    path_filter: Option<&str>,
    name_only: bool,
    recursive: bool,
    opts: &CliOptions,
) -> Result<(), CliError> {
    run_command("ls-tree", opts, |ctx| {
        ctx.progress("Loading tree...");
        ctx.verbose("Reading repository context...");

        let repo = open_repo(cwd)?;

        ctx.verbose(format!("Resolving ref: {}", commit_ref));

        // Resolve the commit reference
        let commit_cid_typed = resolve_ref(repo.void_dir().as_std_path(), commit_ref)?;
        let commit_cid = cid::from_bytes(commit_cid_typed.as_bytes())
            .map_err(|e| CliError::internal(format!("invalid commit CID: {e}")))?;
        let commit_cid_str = commit_cid.to_string();

        ctx.verbose(format!(
            "Commit: {}",
            &commit_cid_str[..12.min(commit_cid_str.len())]
        ));

        // Create object store
        let store = repo.store().map_err(void_err_to_cli)?;

        // Read commit using CommitReader (handles VD01 format)
        let commit_encrypted: EncryptedCommit = store
            .get_blob(&commit_cid)
            .map_err(|e| CliError::not_found(format!("commit not found: {e}")))?;
        let (commit_bytes, reader) = CommitReader::open_with_vault(repo.vault(), &commit_encrypted)
            .map_err(|e| CliError::internal(format!("commit decryption failed: {e}")))?;
        let commit = commit_bytes.parse()
            .map_err(|e| CliError::internal(format!("failed to parse commit: {e}")))?;

        ctx.verbose("Collecting file entries...");

        let all_entries = collect_all_entries(&store, &commit, &reader)?;

        let path_prefix = path_filter.unwrap_or("");

        // Filter by path if specified
        let filtered_entries = filter_by_path(all_entries, path_prefix);

        // Build tree entries based on recursive flag
        let tree_entries = if recursive {
            expand_recursive(filtered_entries, path_prefix)
        } else {
            collapse_to_immediate_children(filtered_entries, path_prefix)
        };

        ctx.progress(format!("Found {} entries", tree_entries.len()));

        // Format human-readable output
        if !ctx.use_json() {
            for entry in &tree_entries {
                if name_only {
                    ctx.info(&entry.path);
                } else {
                    // git-like format: mode type cid\tpath
                    // Since we don't have a separate CID for each file, we show "-"
                    ctx.info(format!(
                        "{} {} -\t{}",
                        entry.mode, entry.entry_type, entry.path
                    ));
                }
            }
        }

        Ok(LsTreeOutput {
            commit: commit_cid_str,
            path: path_prefix.to_string(),
            entries: tree_entries,
        })
    })
}

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

    #[test]
    fn test_parent_dir() {
        assert_eq!(parent_dir("file.txt"), None);
        assert_eq!(parent_dir("src/main.rs"), Some("src"));
        assert_eq!(parent_dir("a/b/c.txt"), Some("a/b"));
    }

    #[test]
    fn test_filter_by_path_empty() {
        let entries = vec![
            ("src/main.rs".to_string(), 100),
            ("README.md".to_string(), 50),
        ];
        let filtered = filter_by_path(entries.clone(), "");
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn test_filter_by_path_prefix() {
        let entries = vec![
            ("src/main.rs".to_string(), 100),
            ("src/lib.rs".to_string(), 80),
            ("README.md".to_string(), 50),
        ];
        let filtered = filter_by_path(entries, "src");
        assert_eq!(filtered.len(), 2);
        assert!(filtered.iter().all(|(p, _)| p.starts_with("src/")));
    }

    #[test]
    fn test_collapse_to_immediate_children_root() {
        let entries = vec![
            ("README.md".to_string(), 50),
            ("src/main.rs".to_string(), 100),
            ("src/lib.rs".to_string(), 80),
            ("tests/test.rs".to_string(), 60),
        ];

        let result = collapse_to_immediate_children(entries, "");

        // Should have: README.md (blob), src/ (tree), tests/ (tree)
        assert_eq!(result.len(), 3);

        let readme = result.iter().find(|e| e.path == "README.md").unwrap();
        assert_eq!(readme.entry_type, "blob");

        let src = result.iter().find(|e| e.path == "src/").unwrap();
        assert_eq!(src.entry_type, "tree");
    }

    #[test]
    fn test_collapse_to_immediate_children_subdir() {
        let entries = vec![
            ("src/main.rs".to_string(), 100),
            ("src/lib.rs".to_string(), 80),
            ("src/utils/helper.rs".to_string(), 40),
        ];

        let result = collapse_to_immediate_children(entries, "src");

        // Should have: main.rs, lib.rs (blobs), utils/ (tree)
        assert_eq!(result.len(), 3);

        let main_rs = result.iter().find(|e| e.path == "src/main.rs").unwrap();
        assert_eq!(main_rs.entry_type, "blob");

        let utils = result.iter().find(|e| e.path == "src/utils/").unwrap();
        assert_eq!(utils.entry_type, "tree");
    }

    #[test]
    fn test_expand_recursive() {
        let entries = vec![
            ("src/main.rs".to_string(), 100),
            ("src/utils/helper.rs".to_string(), 40),
        ];

        let result = expand_recursive(entries, "");

        // Should include: src/ (tree), src/utils/ (tree), src/main.rs (blob), src/utils/helper.rs (blob)
        assert_eq!(result.len(), 4);

        let trees: Vec<_> = result.iter().filter(|e| e.entry_type == "tree").collect();
        let blobs: Vec<_> = result.iter().filter(|e| e.entry_type == "blob").collect();

        assert_eq!(trees.len(), 2);
        assert_eq!(blobs.len(), 2);
    }

    #[test]
    fn test_tree_entry_serialization() {
        let entry = TreeEntry {
            mode: "100644".to_string(),
            entry_type: "blob".to_string(),
            path: "src/main.rs".to_string(),
            size: 1234,
        };

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"mode\":\"100644\""));
        assert!(json.contains("\"type\":\"blob\""));
        assert!(json.contains("\"path\":\"src/main.rs\""));
        assert!(json.contains("\"size\":1234"));
    }

    #[test]
    fn test_ls_tree_output_serialization() {
        let output = LsTreeOutput {
            commit: "bafytest123".to_string(),
            path: "src/".to_string(),
            entries: vec![TreeEntry {
                mode: "100644".to_string(),
                entry_type: "blob".to_string(),
                path: "src/main.rs".to_string(),
                size: 100,
            }],
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commit\":\"bafytest123\""));
        assert!(json.contains("\"path\":\"src/\""));
        assert!(json.contains("\"entries\""));
    }
}