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
//! Log command - show commit history.
//!
//! Reads HEAD to get the current commit CID, then walks the commit chain
//! reading parent commits to display the repository history.

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

use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
use serde::Serialize;
use void_core::{
    cid,
    cid::ToVoidCid,
    crypto::{CommitReader, EncryptedCommit, KeyVault},
    metadata::Commit,
    refs,
    store::{FsStore, ObjectStoreExt},
};

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

/// 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 RESET: &str = "\x1b[0m";

    /// Get yellow color code only if colors are enabled.
    pub fn yellow(use_colors: bool) -> &'static str {
        if use_colors {
            YELLOW
        } else {
            ""
        }
    }

    /// Get green color code only if colors are enabled.
    pub fn green(use_colors: bool) -> &'static str {
        if use_colors {
            GREEN
        } else {
            ""
        }
    }

    /// Get red color code only if colors are enabled.
    pub fn red(use_colors: bool) -> &'static str {
        if use_colors {
            RED
        } else {
            ""
        }
    }

    /// Get reset code only if colors are enabled.
    pub fn reset(use_colors: bool) -> &'static str {
        if use_colors {
            RESET
        } else {
            ""
        }
    }
}

/// 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 single commit entry in the log output.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommitEntry {
    /// CID of the commit object
    pub cid: String,
    /// Commit message
    pub message: String,
    /// ISO 8601 timestamp
    pub timestamp: String,
    /// Parent commit CID (None for initial commit)
    #[serde(rename = "parent")]
    pub parent: Option<String>,
    /// Author public key (hex-encoded ed25519), null if unsigned or not verified
    pub author: Option<String>,
    /// Whether the author signature was verified as valid
    pub author_verified: bool,
    /// Signature verification status
    pub signature_status: SignatureStatus,
}

/// JSON output for the log command.
#[derive(Debug, Clone, Serialize)]
pub struct LogOutput {
    /// List of commits in reverse chronological order
    pub commits: Vec<CommitEntry>,
}

/// Format a timestamp (in milliseconds) as an ISO 8601 date string.
fn format_timestamp_iso(timestamp_ms: u64) -> String {
    // Commit timestamps are stored in milliseconds, convert to seconds
    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.
/// Handles both envelope format (VD01) and legacy format commits.
fn read_commit(store: &FsStore, vault: &KeyVault, cid_bytes: &[u8]) -> Result<Commit, CliError> {
    let cid_obj =
        cid::from_bytes(cid_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_bytes, _reader) = CommitReader::open_with_vault(vault, &encrypted)
        .map_err(|e| CliError::internal(format!("failed to open commit: {e}")))?;
    let commit = commit_bytes.parse()
        .map_err(|e| CliError::internal(format!("failed to parse commit: {e}")))?;

    Ok(commit)
}

/// Run the log command.
///
/// Reads HEAD to get the current commit CID, then walks the commit chain
/// reading parent commits up to the specified limit.
///
/// # Arguments
/// * `cwd` - Current working directory
/// * `number` - Maximum number of commits to show
/// * `opts` - CLI options
/// * `verify` - Whether to verify commit signatures
pub fn run(cwd: &Path, number: usize, opts: &CliOptions, verify: bool) -> Result<(), CliError> {
    run_command("log", opts, |ctx| {
        ctx.progress("Loading commit history...");
        ctx.verbose("Reading repository context...");

        let void_ctx = build_void_context(cwd)?;
        let void_dir = void_ctx.paths.void_dir.clone();

        ctx.verbose("Resolving HEAD...");

        // Read HEAD to get current commit CID
        let head_cid = refs::resolve_head(&void_dir)
            .map_err(|e| CliError::internal(format!("failed to read HEAD: {e}")))?;

        // If no commits exist, return NOT_FOUND error (matches TS behavior)
        let head_cid = match head_cid {
            Some(cid) => cid,
            None => {
                return Err(CliError::not_found(
                    "No commits found. Run 'void commit' first.",
                ));
            }
        };

        // Create object store to read commits
        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}")))?;

        ctx.verbose("Walking commit history...");

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

        // Walk the commit chain
        let mut commits = Vec::new();
        let mut current_cid: Option<Vec<u8>> = Some(head_cid.into_bytes());

        while let Some(cid_bytes) = current_cid.take() {
            if commits.len() >= number {
                break;
            }

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

            ctx.verbose(format!(
                "Reading commit {}",
                &cid_str[..12.min(cid_str.len())]
            ));

            let commit = match read_commit(&store, &void_ctx.crypto.vault, &cid_bytes) {
                Ok(c) => c,
                Err(_) if !commits.is_empty() => {
                    // Parent commit is unreadable (foreign repo key, missing object, etc.)
                    // This is the natural boundary — e.g., a fork's source commit.
                    if !ctx.use_json() {
                        ctx.info(format!(
                            "  (parent {} from foreign repository)",
                            cid_str
                        ));
                    }
                    break;
                }
                Err(e) => return Err(e),
            };

            // Determine author and verification status
            let (author, author_verified, signature_status) = if verify {
                match commit.verify() {
                    Ok(true) => (
                        commit.author.map(|a| a.to_hex()),
                        true,
                        SignatureStatus::Verified,
                    ),
                    Ok(false) => (None, false, SignatureStatus::Unsigned),
                    Err(_) => (
                        commit.author.map(|a| a.to_hex()),
                        false,
                        SignatureStatus::Invalid,
                    ),
                }
            } else {
                // Skip verification - set author to null (matches TS behavior)
                // When verification is disabled, we don't expose the author key
                (None, false, SignatureStatus::Unsigned)
            };

            // Get parent CID for linking
            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()))
            });

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

                // Author line with verification badge (only when verifying)
                if verify {
                    let author_display = match &author {
                        Some(hex_key) => format!("ed25519:{}...", &hex_key[..8]),
                        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));
                }

                // ISO 8601 date with timezone
                ctx.info(format!(
                    "Date:   {}",
                    format_timestamp_iso(commit.timestamp)
                ));

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

            // Add to result list
            commits.push(CommitEntry {
                cid: cid_str,
                message: commit.message.clone(),
                timestamp: format_timestamp_iso(commit.timestamp),
                parent: parent_cid.clone(),
                author: author.clone(),
                author_verified,
                signature_status: signature_status.clone(),
            });

            // Move to parent commit
            current_cid = commit.first_parent().map(|p| p.as_bytes().to_vec());
        }

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

        Ok(LogOutput { commits })
    })
}

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

    #[test]
    fn test_format_timestamp_iso() {
        // Test a known timestamp (in milliseconds)
        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_commit_entry_serialization() {
        let entry = CommitEntry {
            cid: "bafytest123".to_string(),
            message: "test commit".to_string(),
            timestamp: "2024-01-01T00:00:00Z".to_string(),
            parent: Some("bafyparent456".to_string()),
            author: Some("abcd1234abcd1234".to_string()),
            author_verified: true,
            signature_status: SignatureStatus::Verified,
        };

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

    #[test]
    fn test_commit_entry_without_parent() {
        let entry = CommitEntry {
            cid: "bafytest123".to_string(),
            message: "initial commit".to_string(),
            timestamp: "2024-01-01T00:00:00Z".to_string(),
            parent: None,
            author: None,
            author_verified: false,
            signature_status: SignatureStatus::Unsigned,
        };

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"parent\":null")); // parent is always serialized, even as null
        assert!(json.contains("\"author\":null")); // author is always serialized (matches TS behavior)
        assert!(json.contains("\"signatureStatus\":\"unsigned\""));
    }

    #[test]
    fn test_log_output_serialization() {
        let output = LogOutput {
            commits: vec![CommitEntry {
                cid: "bafytest123".to_string(),
                message: "test".to_string(),
                timestamp: "2024-01-01T00:00:00Z".to_string(),
                parent: None,
                author: None,
                author_verified: false,
                signature_status: SignatureStatus::Unsigned,
            }],
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commits\""));
    }

    #[test]
    fn test_signature_status_serialization() {
        // Test that all signature statuses serialize correctly
        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_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::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::reset(false), "");
    }
}