void-cli 0.0.4

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
//! Unseal command - restore files from sealed shards.
//!
//! This is a low-level command for restoring files from encrypted shards.
//! For regular file restoration, use the `restore` command instead.

use std::path::Path;
use std::sync::Arc;

use serde::Serialize;
use void_core::cid::ToVoidCid;
use void_core::pipeline::unseal::{unseal_commit, UnsealOptions};
use void_core::transport::IpfsBackend;
use void_core::{
    cid,
    crypto::{CommitReader, EncryptedCommit},

    store::{FsStore, ObjectStoreExt},
};

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

/// A file entry for list mode output.
#[derive(Debug, Clone, Serialize)]
pub struct FileEntry {
    /// File path.
    pub path: String,
    /// File size in bytes.
    pub size: u64,
}

/// Statistics from the unseal operation.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UnsealStats {
    /// Total number of shards.
    pub shards_total: usize,
    /// Number of shards read from local store.
    pub shards_read: usize,
    /// Number of shards fetched from IPFS.
    pub shards_fetched: usize,
    /// Number of bytes written.
    pub bytes_written: usize,
}

/// JSON output for normal unseal mode.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UnsealOutput {
    /// CID of the commit.
    pub commit: String,
    /// Commit message.
    pub message: String,
    /// Number of files restored.
    pub files: usize,
    /// Unseal statistics.
    pub stats: UnsealStats,
}

/// JSON output for list mode.
#[derive(Debug, Clone, Serialize)]
pub struct UnsealListOutput {
    /// CID of the commit.
    pub commit: String,
    /// List of files in the commit.
    pub files: Vec<FileEntry>,
}

/// Arguments for the unseal command.
pub struct UnsealArgs {
    /// Output directory (default: current working directory).
    pub output: Option<String>,
    /// Specific commit CID (default: HEAD).
    pub commit: Option<String>,
    /// List files only, don't extract.
    pub list: bool,
    /// Don't fetch missing shards from IPFS.
    pub offline: bool,
    /// Skip hash verification.
    pub no_verify: bool,
    /// Backend type: kubo or gateway.
    pub backend: Option<String>,
    /// Kubo API URL.
    pub kubo: Option<String>,
    /// Gateway URL (required if backend is gateway).
    pub gateway: Option<String>,
    /// Request timeout in milliseconds.
    pub timeout: Option<u64>,
}

/// Collect all file entries from the commit's manifest.
fn collect_all_files(
    store: &FsStore,
    commit: &void_core::metadata::Commit,
    reader: &CommitReader,
) -> Result<Vec<FileEntry>, 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<FileEntry> = manifest
        .iter()
        .map(|me| {
            let me = me.map_err(void_err_to_cli)?;
            Ok(FileEntry {
                path: me.path.clone(),
                size: me.length,
            })
        })
        .collect::<Result<_, CliError>>()?;

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

/// Run the unseal command in list mode.
fn run_list_mode(
    cwd: &Path,
    args: &UnsealArgs,
    ctx: &mut crate::output::CommandContext,
) -> Result<UnsealListOutput, CliError> {
    ctx.progress("Loading commit...");

    let repo = open_repo(cwd)?;
    let void_dir = repo.void_dir();
    let vault = repo.vault().clone();

    // Resolve commit reference
    let commit_ref = args.commit.as_deref().unwrap_or("HEAD");
    let commit_cid_typed = resolve_ref(void_dir.as_std_path(), commit_ref)?;
    let commit_cid =
        cid::from_bytes(commit_cid_typed.as_bytes()).map_err(|e| CliError::internal(e.to_string()))?;
    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 objects_dir = void_dir.join("objects");
    let store = FsStore::new(&objects_dir)
        .map_err(|e| CliError::internal(format!("failed to open object store: {e}")))?;
    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(&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.progress("Collecting file entries...");

    let files = collect_all_files(&store, &commit, &reader)?;

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

    // Print human-readable output
    if !ctx.use_json() {
        ctx.info(format!("commit {}", commit_cid_str));
        ctx.info("");
        for file in &files {
            ctx.info(format!("{:>10}  {}", file.size, file.path));
        }
        ctx.info("");
        ctx.info(format!("{} file(s)", files.len()));
    }

    Ok(UnsealListOutput {
        commit: commit_cid_str,
        files,
    })
}

/// Run the unseal command in normal (extract) mode.
fn run_extract_mode(
    cwd: &Path,
    args: &UnsealArgs,
    ctx: &mut crate::output::CommandContext,
) -> Result<UnsealOutput, CliError> {
    ctx.progress("Preparing unseal...");

    let repo = open_repo(cwd)?;
    let void_dir = repo.void_dir().to_owned();

    // Determine output directory
    let output_dir = match &args.output {
        Some(dir) => {
            let path = Path::new(dir);
            if path.is_absolute() {
                path.to_path_buf()
            } else {
                cwd.join(path)
            }
        }
        None => cwd.to_path_buf(),
    };

    // Resolve commit CID if provided
    let commit_cid = match &args.commit {
        Some(ref_str) => {
            Some(resolve_ref(void_dir.as_std_path(), ref_str)?)
        }
        None => None,
    };

    ctx.verbose(format!("Output directory: {}", output_dir.display()));
    if let Some(ref cid) = commit_cid {
        let cid_str = cid.to_cid_string();
        ctx.verbose(format!("Commit: {}", &cid_str[..12.min(cid_str.len())]));
    } else {
        ctx.verbose("Commit: HEAD");
    }

    // Create observer for progress reporting
    let observer: Arc<ProgressObserver> = if ctx.use_json() {
        Arc::new(ProgressObserver::new_hidden())
    } else {
        Arc::new(ProgressObserver::new("Unsealing..."))
    };

    // Build IPFS backend from flags
    let ipfs_backend = match args.backend.as_deref() {
        Some("gateway") => {
            let gateway_url = args.gateway.as_ref().ok_or_else(|| {
                CliError::invalid_args("--gateway URL is required when using gateway backend")
            })?;
            Some(IpfsBackend::Gateway {
                base: gateway_url.clone(),
            })
        }
        Some("kubo") | Some(_) => {
            let kubo_url = args.kubo.as_deref().unwrap_or("http://127.0.0.1:5001");
            Some(IpfsBackend::Kubo {
                api: kubo_url.to_string(),
            })
        }
        None => None,
    };

    let timeout_ms = args.timeout.unwrap_or(30000);

    let output_dir_utf8 = camino::Utf8PathBuf::try_from(output_dir.clone())
        .map_err(|e| CliError::internal(format!("output path is not valid UTF-8: {e}")))?;

    let unseal_opts = UnsealOptions {
        ctx: repo.context().clone(),
        output_dir: output_dir_utf8,
        commit_cid,
        backend: ipfs_backend,
        timeout: std::time::Duration::from_millis(timeout_ms),
        offline: args.offline,
        verify_content_hashes: !args.no_verify,
    };

    let result = unseal_commit(unseal_opts).map_err(void_err_to_cli)?;

    // Finish progress bar
    observer.finish();

    // Print human-readable summary
    if !ctx.use_json() {
        ctx.info(format!("commit {}", result.commit_cid.to_cid_string()));
        if !result.message.is_empty() {
            ctx.info(format!("  {}", result.message));
        }
        ctx.info("");
        ctx.info(format!(
            "Unsealed {} file(s) to {}",
            result.stats.files_restored,
            output_dir.display()
        ));
        ctx.info(format!(
            "  {} shard(s) read, {} fetched, {} bytes written",
            result.stats.shards_read, result.stats.shards_fetched, result.stats.bytes_written
        ));
    }

    Ok(UnsealOutput {
        commit: result.commit_cid.to_cid_string(),
        message: result.message,
        files: result.stats.files_restored,
        stats: UnsealStats {
            shards_total: result.stats.shards_total,
            shards_read: result.stats.shards_read,
            shards_fetched: result.stats.shards_fetched,
            bytes_written: result.stats.bytes_written,
        },
    })
}

/// Unified output enum for serde serialization.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum UnsealResultOutput {
    /// Normal extraction mode output.
    Extract(UnsealOutput),
    /// List mode output.
    List(UnsealListOutput),
}

/// Run the unseal command.
///
/// Restores files from sealed shards to the specified output directory.
///
/// # Arguments
///
/// * `cwd` - Working directory to operate in.
/// * `args` - Unseal arguments.
/// * `opts` - CLI options.
pub fn run(cwd: &Path, args: UnsealArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("unseal", opts, |ctx| {
        if args.list {
            let result = run_list_mode(cwd, &args, ctx)?;
            Ok(UnsealResultOutput::List(result))
        } else {
            let result = run_extract_mode(cwd, &args, ctx)?;
            Ok(UnsealResultOutput::Extract(result))
        }
    })
}

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

    #[test]
    fn test_unseal_output_serialization() {
        let output = UnsealOutput {
            commit: "bafytest123".to_string(),
            message: "test commit".to_string(),
            files: 42,
            stats: UnsealStats {
                shards_total: 5,
                shards_read: 5,
                shards_fetched: 0,
                bytes_written: 500000,
            },
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commit\":\"bafytest123\""));
        assert!(json.contains("\"message\":\"test commit\""));
        assert!(json.contains("\"files\":42"));
        assert!(json.contains("\"shardsTotal\":5"));
        assert!(json.contains("\"shardsRead\":5"));
        assert!(json.contains("\"shardsFetched\":0"));
        assert!(json.contains("\"bytesWritten\":500000"));
    }

    #[test]
    fn test_unseal_list_output_serialization() {
        let output = UnsealListOutput {
            commit: "bafytest456".to_string(),
            files: vec![
                FileEntry {
                    path: "src/main.rs".to_string(),
                    size: 1234,
                },
                FileEntry {
                    path: "README.md".to_string(),
                    size: 567,
                },
            ],
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commit\":\"bafytest456\""));
        assert!(json.contains("\"path\":\"src/main.rs\""));
        assert!(json.contains("\"size\":1234"));
        assert!(json.contains("\"path\":\"README.md\""));
        assert!(json.contains("\"size\":567"));
    }

    #[test]
    fn test_file_entry_serialization() {
        let entry = FileEntry {
            path: "test/file.txt".to_string(),
            size: 42,
        };

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"path\":\"test/file.txt\""));
        assert!(json.contains("\"size\":42"));
    }

    #[test]
    fn test_unseal_result_output_extract_variant() {
        let output = UnsealResultOutput::Extract(UnsealOutput {
            commit: "bafy123".to_string(),
            message: "msg".to_string(),
            files: 1,
            stats: UnsealStats {
                shards_total: 1,
                shards_read: 1,
                shards_fetched: 0,
                bytes_written: 100,
            },
        });

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commit\":\"bafy123\""));
        assert!(json.contains("\"message\":\"msg\""));
    }

    #[test]
    fn test_unseal_result_output_list_variant() {
        let output = UnsealResultOutput::List(UnsealListOutput {
            commit: "bafy456".to_string(),
            files: vec![],
        });

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commit\":\"bafy456\""));
        assert!(json.contains("\"files\":[]"));
    }
}