void-cli 0.0.2

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
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
//! Show command - display commit details or file contents.
//!
//! Usage: `void show <target>` where target is:
//! - `commit` - CID or ref to show commit details
//! - `commit:path` - show file contents at specific path in commit
//! - `HEAD` - show HEAD commit
//! - branch name - show branch tip commit

use std::io::IsTerminal;
use std::path::Path;

use base64::prelude::*;
use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
use serde::Serialize;
use void_core::{
    cid,
    crypto::{CommitReader, EncryptedCommit, KeyVault},
    diff::{diff_commits, DiffKind},
    metadata::Commit,

    store::{FsStore, ObjectStoreExt},
};
use void_core::support::ToVoidCid;
use void_core::VoidContext;

use void_core::crypto::CommitCid;

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

/// Signature verification status for a commit.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SignatureStatus {
    /// Signature is present and valid
    Verified,
    /// Commit has no signature
    Unsigned,
    /// Signature is present but invalid
    Invalid,
}

/// A file change in a commit (for commit mode output).
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileChange {
    /// Status of the change: A (added), M (modified), D (deleted), R (renamed)
    pub status: String,
    /// Path of the file (new path for renames)
    pub path: String,
    /// Original path for renamed files
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Similarity percentage for renamed files
    #[serde(skip_serializing_if = "Option::is_none")]
    pub similarity: Option<u8>,
}

/// JSON output for commit mode (no path specified).
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommitShowOutput {
    /// CID of the commit object
    pub cid: String,
    /// Parent commit CID (None for initial commit)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent: Option<String>,
    /// ISO 8601 date string
    pub date: String,
    /// Commit message
    pub message: String,
    /// List of file changes in this commit
    pub files: Vec<FileChange>,
    /// Author public key (ed25519:hex format), None if unsigned
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// Signature verification status
    pub signature_status: SignatureStatus,
}

/// JSON output for file mode (commit:path specified).
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileShowOutput {
    /// CID of the commit
    pub commit: String,
    /// Path of the file
    pub path: String,
    /// Base64-encoded file content
    pub content: String,
    /// File size in bytes
    pub size: u64,
}

/// Unified output enum for show command.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ShowOutput {
    Commit(CommitShowOutput),
    File(FileShowOutput),
}

/// Format a timestamp (in milliseconds) as an ISO 8601 date string.
fn format_timestamp_iso(timestamp_ms: u64) -> String {
    let secs = (timestamp_ms / 1000) as i64;
    let datetime: DateTime<Utc> = Utc.timestamp_opt(secs, 0).single().unwrap_or_else(Utc::now);
    datetime.to_rfc3339_opts(SecondsFormat::Secs, true)
}

/// Read and decrypt a commit from the object store.
fn read_commit(store: &FsStore, vault: &KeyVault, commit_cid: &CommitCid) -> Result<Commit, CliError> {
    let cid_obj =
        cid::from_bytes(commit_cid.as_bytes()).map_err(|e| CliError::internal(format!("invalid CID: {e}")))?;

    let encrypted: EncryptedCommit = store
        .get_blob(&cid_obj)
        .map_err(|e| CliError::not_found(format!("commit not found: {e}")))?;

    let (commit_plaintext, _reader) = CommitReader::open_with_vault(vault, &encrypted)
        .map_err(|e| CliError::internal(format!("failed to open commit: {e}")))?;
    let commit = commit_plaintext.parse()
        .map_err(|e| CliError::internal(format!("failed to parse commit: {e}")))?;

    Ok(commit)
}

/// Read file content from a commit at the specified path using manifest-driven lookup.
fn show_file_from_commit(
    void_ctx: &VoidContext,
    store: &FsStore,
    commit_cid: &CommitCid,
    file_path: &str,
) -> Result<Vec<u8>, CliError> {
    let cid_obj = cid::from_bytes(commit_cid.as_bytes())
        .map_err(|e| CliError::internal(format!("invalid CID: {e}")))?;
    let (commit, reader) = void_ctx.load_commit(store, &cid_obj)
        .map_err(void_err_to_cli)?;

    let ancestor_keys =
        void_core::crypto::collect_ancestor_content_keys_vault(&void_ctx.crypto.vault, store, &commit);

    void_ctx
        .read_file_from_commit(store, &commit, &reader, &ancestor_keys, file_path)
        .map(Into::into)
        .map_err(void_err_to_cli)
}

/// ANSI color codes for terminal output.
mod colors {
    pub const YELLOW: &str = "\x1b[33m";
    pub const GREEN: &str = "\x1b[32m";
    pub const RED: &str = "\x1b[31m";
    pub const CYAN: &str = "\x1b[36m";
    pub const RESET: &str = "\x1b[0m";

    pub fn yellow(use_colors: bool) -> &'static str {
        if use_colors {
            YELLOW
        } else {
            ""
        }
    }

    pub fn green(use_colors: bool) -> &'static str {
        if use_colors {
            GREEN
        } else {
            ""
        }
    }

    pub fn red(use_colors: bool) -> &'static str {
        if use_colors {
            RED
        } else {
            ""
        }
    }

    pub fn cyan(use_colors: bool) -> &'static str {
        if use_colors {
            CYAN
        } else {
            ""
        }
    }

    pub fn reset(use_colors: bool) -> &'static str {
        if use_colors {
            RESET
        } else {
            ""
        }
    }
}

/// Run the show command.
///
/// # Arguments
/// * `cwd` - Current working directory
/// * `target` - Target to show (commit ref, commit:path, HEAD, or branch name)
/// * `verify` - Whether to verify commit signatures
/// * `opts` - CLI options
pub fn run(cwd: &Path, target: &str, verify: bool, opts: &CliOptions) -> Result<(), CliError> {
    run_command("show", opts, |ctx| {
        ctx.progress("Loading repository...");

        let void_ctx = build_void_context(cwd)?;

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

        // Parse target: check if it contains `:` for file mode
        let (commit_ref, file_path) = if let Some(colon_pos) = target.find(':') {
            let commit_part = &target[..colon_pos];
            let path_part = &target[colon_pos + 1..];
            if path_part.is_empty() {
                return Err(CliError::invalid_args(
                    "file path cannot be empty after ':'",
                ));
            }
            (commit_part, Some(path_part))
        } else {
            (target, None)
        };

        // Resolve the commit reference
        ctx.verbose(format!("Resolving reference: {}", commit_ref));
        let cid_bytes = resolve_ref(&void_ctx.paths.void_dir, commit_ref)?;

        let cid_str = cid::from_bytes(cid_bytes.as_bytes())
            .map(|c| c.to_string())
            .unwrap_or_else(|_| hex::encode(cid_bytes.as_bytes()));

        // Load the commit
        ctx.verbose(format!(
            "Loading commit: {}",
            &cid_str[..12.min(cid_str.len())]
        ));
        let commit = read_commit(&store, &void_ctx.crypto.vault, &cid_bytes)?;

        // Check if stderr is a TTY for color output
        let use_colors = std::io::stderr().is_terminal();

        if let Some(path) = file_path {
            // File mode: show file contents
            ctx.progress(format!("Reading file: {}", path));

            let content = show_file_from_commit(&void_ctx, &store, &cid_bytes, path)?;
            let size = content.len() as u64;
            let encoded = BASE64_STANDARD.encode(&content);

            // Human-readable output
            if !ctx.use_json() {
                ctx.info(format!("commit {}", cid_str));
                ctx.info(format!("path   {}", path));
                ctx.info(format!("size   {} bytes", size));
                ctx.info("");

                // Try to display as text if valid UTF-8
                if let Ok(text) = String::from_utf8(content.clone()) {
                    for line in text.lines() {
                        ctx.info(line);
                    }
                } else {
                    ctx.info("(binary content, use --json for base64 output)");
                }
            }

            Ok(ShowOutput::File(FileShowOutput {
                commit: cid_str,
                path: path.to_string(),
                content: encoded,
                size,
            }))
        } else {
            // Commit mode: show commit details
            ctx.progress("Loading commit details...");

            // Get parent CID string
            let parent_cid = commit.first_parent().map(|p| {
                p.to_void_cid()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|_| hex::encode(p.as_bytes()))
            });

            // Verify signature if requested
            let (author, signature_status) = if verify {
                match commit.verify() {
                    Ok(true) => (
                        commit.author.map(|a| format!("ed25519:{}", a.to_hex())),
                        SignatureStatus::Verified,
                    ),
                    Ok(false) => (None, SignatureStatus::Unsigned),
                    Err(_) => (
                        commit.author.map(|a| format!("ed25519:{}", a.to_hex())),
                        SignatureStatus::Invalid,
                    ),
                }
            } else {
                (
                    commit.author.map(|a| format!("ed25519:{}", a.to_hex())),
                    if commit.signature.is_some() {
                        SignatureStatus::Verified // Assume valid when not verifying
                    } else {
                        SignatureStatus::Unsigned
                    },
                )
            };

            // Compute file changes by diffing against parent
            ctx.verbose("Computing file changes...");
            let cid_obj = cid::from_bytes(cid_bytes.as_bytes())
                .map_err(|e| CliError::internal(format!("invalid CID: {e}")))?;

            let parent_cid_obj = match commit.first_parent() {
                Some(p) => Some(
                    p.to_void_cid()
                        .map_err(|e| CliError::internal(format!("invalid parent CID: {e}")))?,
                ),
                None => None,
            };

            let diff = diff_commits(&store, &void_ctx.crypto.vault, parent_cid_obj.as_ref(), &cid_obj)
                .map_err(void_err_to_cli)?;

            let files: Vec<FileChange> = diff
                .files
                .into_iter()
                .map(|f| {
                    let (status, from, similarity) = match &f.kind {
                        DiffKind::Added => ("A".to_string(), None, None),
                        DiffKind::Modified => ("M".to_string(), None, None),
                        DiffKind::Deleted => ("D".to_string(), None, None),
                        DiffKind::Renamed { from, similarity } => {
                            ("R".to_string(), Some(from.clone()), Some(*similarity))
                        }
                    };
                    FileChange {
                        status,
                        path: f.path,
                        from,
                        similarity,
                    }
                })
                .collect();

            // Human-readable output
            if !ctx.use_json() {
                // Yellow commit CID
                ctx.info(format!(
                    "{}commit {}{}",
                    colors::yellow(use_colors),
                    cid_str,
                    colors::reset(use_colors)
                ));

                // Parent
                if let Some(ref p) = parent_cid {
                    ctx.info(format!("Parent: {}", p));
                }

                // Author line with verification badge
                if verify {
                    let author_display = match &author {
                        Some(key) => key.clone(),
                        None => "(unsigned)".to_string(),
                    };
                    let badge = match signature_status {
                        SignatureStatus::Verified => format!(
                            "{}[verified]{}",
                            colors::green(use_colors),
                            colors::reset(use_colors)
                        ),
                        SignatureStatus::Unsigned => format!(
                            "{}[no signature]{}",
                            colors::yellow(use_colors),
                            colors::reset(use_colors)
                        ),
                        SignatureStatus::Invalid => format!(
                            "{}[invalid]{}",
                            colors::red(use_colors),
                            colors::reset(use_colors)
                        ),
                    };
                    ctx.info(format!("Author: {} {}", author_display, badge));
                }

                // Date
                ctx.info(format!(
                    "Date:   {}",
                    format_timestamp_iso(commit.timestamp)
                ));

                // Message
                ctx.info("");
                for line in commit.message.lines() {
                    ctx.info(format!("    {}", line));
                }
                ctx.info("");

                // File changes
                if !files.is_empty() {
                    ctx.info("Files:");
                    for file in &files {
                        let color = match file.status.as_str() {
                            "A" => colors::green(use_colors),
                            "D" => colors::red(use_colors),
                            "M" => colors::cyan(use_colors),
                            "R" => colors::yellow(use_colors),
                            _ => "",
                        };
                        if let Some(ref from) = file.from {
                            ctx.info(format!(
                                "  {}{}{} {} (from {})",
                                color,
                                file.status,
                                colors::reset(use_colors),
                                file.path,
                                from
                            ));
                        } else {
                            ctx.info(format!(
                                "  {}{}{} {}",
                                color,
                                file.status,
                                colors::reset(use_colors),
                                file.path
                            ));
                        }
                    }
                }
            }

            Ok(ShowOutput::Commit(CommitShowOutput {
                cid: cid_str,
                parent: parent_cid,
                date: format_timestamp_iso(commit.timestamp),
                message: commit.message.clone(),
                files,
                author,
                signature_status,
            }))
        }
    })
}

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

    #[test]
    fn test_format_timestamp_iso() {
        let ts_ms = 1704067200000; // 2024-01-01 00:00:00 UTC in milliseconds
        let formatted = format_timestamp_iso(ts_ms);
        assert_eq!(formatted, "2024-01-01T00:00:00Z");
    }

    #[test]
    fn test_signature_status_serialization() {
        let verified = serde_json::to_string(&SignatureStatus::Verified).unwrap();
        let unsigned = serde_json::to_string(&SignatureStatus::Unsigned).unwrap();
        let invalid = serde_json::to_string(&SignatureStatus::Invalid).unwrap();

        assert_eq!(verified, "\"verified\"");
        assert_eq!(unsigned, "\"unsigned\"");
        assert_eq!(invalid, "\"invalid\"");
    }

    #[test]
    fn test_file_change_serialization() {
        let change = FileChange {
            status: "A".to_string(),
            path: "src/main.rs".to_string(),
            from: None,
            similarity: None,
        };

        let json = serde_json::to_string(&change).unwrap();
        assert!(json.contains("\"status\":\"A\""));
        assert!(json.contains("\"path\":\"src/main.rs\""));
        assert!(!json.contains("\"from\"")); // Should be skipped
    }

    #[test]
    fn test_file_change_renamed_serialization() {
        let change = FileChange {
            status: "R".to_string(),
            path: "new_name.rs".to_string(),
            from: Some("old_name.rs".to_string()),
            similarity: Some(95),
        };

        let json = serde_json::to_string(&change).unwrap();
        assert!(json.contains("\"status\":\"R\""));
        assert!(json.contains("\"path\":\"new_name.rs\""));
        assert!(json.contains("\"from\":\"old_name.rs\""));
        assert!(json.contains("\"similarity\":95"));
    }

    #[test]
    fn test_commit_show_output_serialization() {
        let output = CommitShowOutput {
            cid: "bafytest123".to_string(),
            parent: Some("bafyparent456".to_string()),
            date: "2024-01-01T00:00:00Z".to_string(),
            message: "test commit".to_string(),
            files: vec![FileChange {
                status: "A".to_string(),
                path: "README.md".to_string(),
                from: None,
                similarity: None,
            }],
            author: Some("ed25519:abcd1234".to_string()),
            signature_status: SignatureStatus::Verified,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"cid\":\"bafytest123\""));
        assert!(json.contains("\"parent\":\"bafyparent456\""));
        assert!(json.contains("\"date\":\"2024-01-01T00:00:00Z\""));
        assert!(json.contains("\"message\":\"test commit\""));
        assert!(json.contains("\"signatureStatus\":\"verified\""));
    }

    #[test]
    fn test_file_show_output_serialization() {
        let output = FileShowOutput {
            commit: "bafytest123".to_string(),
            path: "src/main.rs".to_string(),
            content: "SGVsbG8gV29ybGQ=".to_string(), // "Hello World" in base64
            size: 11,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commit\":\"bafytest123\""));
        assert!(json.contains("\"path\":\"src/main.rs\""));
        assert!(json.contains("\"content\":\"SGVsbG8gV29ybGQ=\""));
        assert!(json.contains("\"size\":11"));
    }

    #[test]
    fn test_colors_with_tty() {
        assert_eq!(colors::yellow(true), "\x1b[33m");
        assert_eq!(colors::green(true), "\x1b[32m");
        assert_eq!(colors::red(true), "\x1b[31m");
        assert_eq!(colors::cyan(true), "\x1b[36m");
        assert_eq!(colors::reset(true), "\x1b[0m");
    }

    #[test]
    fn test_colors_without_tty() {
        assert_eq!(colors::yellow(false), "");
        assert_eq!(colors::green(false), "");
        assert_eq!(colors::red(false), "");
        assert_eq!(colors::cyan(false), "");
        assert_eq!(colors::reset(false), "");
    }
}