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
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
//! Branch management for void repositories.
//!
//! Lists, creates, and deletes branches. Branches are lightweight refs
//! stored in `.void/refs/heads/<name>`.

use camino::Utf8PathBuf;
use serde::Serialize;
use std::path::Path;
use void_core::{cid, refs};

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

/// Command-line arguments for branch.
#[derive(Debug)]
pub struct BranchArgs {
    /// Branch name (for create/delete operations).
    pub name: Option<String>,
    /// Target commit CID for new branch (default: HEAD).
    pub target: Option<String>,
    /// Delete the specified branch.
    pub delete: bool,
    /// Overwrite existing branch when creating.
    pub force: bool,
}

/// HEAD reference output for JSON.
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct HeadRefOutput {
    /// Kind of HEAD reference: "symbolic" or "detached".
    pub kind: String,
    /// Value: branch name for symbolic, CID for detached.
    pub value: String,
}

/// JSON output for the branch command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BranchOutput {
    /// The action performed: "list", "create", or "delete".
    pub action: String,
    /// The current branch name (if on a branch).
    pub current: Option<String>,
    /// HEAD reference info (for list action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub head: Option<HeadRefOutput>,
    /// List of all branches (for list action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches: Option<Vec<String>>,
    /// Branch name (for create action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Deleted branch name (for delete action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted: Option<String>,
    /// Target commit CID (for create action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
}

/// Run the branch command.
///
/// # Arguments
///
/// * `cwd` - Current working directory
/// * `args` - Branch arguments
/// * `opts` - CLI options
///
/// # Operations
///
/// * No args: List all branches with current branch marked
/// * `<name>`: Create branch at HEAD
/// * `<name> <commit>`: Create branch at specified commit
/// * `-d <name>`: Delete branch
pub fn run(cwd: &Path, args: BranchArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("branch", opts, |ctx| {
        let void_dir = find_void_dir(cwd)?;
        let void_dir_utf8 = Utf8PathBuf::try_from(void_dir.clone())
            .map_err(|e| CliError::internal(format!("invalid void_dir path: {}", e)))?;

        // Get current branch from HEAD
        let current_branch = get_current_branch(&void_dir_utf8)?;

        // Get HEAD ref for list output
        let head_ref = get_head_ref(&void_dir_utf8)?;

        // Dispatch based on arguments
        if args.delete {
            // Delete branch
            let name = args
                .name
                .ok_or_else(|| CliError::invalid_args("branch name required for delete"))?;
            delete_branch_cmd(ctx, &void_dir_utf8, &name, current_branch.as_deref())
        } else if let Some(name) = args.name {
            // Create branch
            create_branch_cmd(
                ctx,
                &void_dir,
                &void_dir_utf8,
                &name,
                args.target,
                args.force,
                current_branch,
            )
        } else {
            // List branches
            list_branches_cmd(ctx, &void_dir_utf8, current_branch, head_ref)
        }
    })
}

/// Get the current branch name from HEAD (if symbolic ref).
fn get_current_branch(void_dir: &Utf8PathBuf) -> Result<Option<String>, CliError> {
    match refs::read_head(void_dir).map_err(void_err_to_cli)? {
        Some(refs::HeadRef::Symbolic(branch)) => Ok(Some(branch)),
        _ => Ok(None),
    }
}

/// Get the full HEAD reference info.
fn get_head_ref(void_dir: &Utf8PathBuf) -> Result<Option<HeadRefOutput>, CliError> {
    match refs::read_head(void_dir).map_err(void_err_to_cli)? {
        Some(refs::HeadRef::Symbolic(branch)) => Ok(Some(HeadRefOutput {
            kind: "symbolic".to_string(),
            value: branch,
        })),
        Some(refs::HeadRef::Detached(commit_cid)) => {
            let cid_str = cid::from_bytes(commit_cid.as_bytes())
                .map(|c| c.to_string())
                .map_err(|e| CliError::internal(format!("invalid CID: {}", e)))?;
            Ok(Some(HeadRefOutput {
                kind: "detached".to_string(),
                value: cid_str,
            }))
        }
        None => Ok(None),
    }
}

/// List all branches.
fn list_branches_cmd(
    ctx: &mut crate::output::CommandContext,
    void_dir: &Utf8PathBuf,
    current_branch: Option<String>,
    head_ref: Option<HeadRefOutput>,
) -> Result<BranchOutput, CliError> {
    ctx.progress("Listing branches...");

    let branches = refs::list_branches(void_dir).map_err(void_err_to_cli)?;

    // Human-readable output
    if !ctx.use_json() {
        if branches.is_empty() {
            ctx.info("No branches found.");
        } else {
            for branch in &branches {
                if current_branch.as_ref() == Some(branch) {
                    ctx.info(format!("* {}", branch));
                } else {
                    ctx.info(format!("  {}", branch));
                }
            }
        }
    }

    Ok(BranchOutput {
        action: "list".to_string(),
        current: current_branch,
        head: head_ref,
        branches: Some(branches),
        name: None,
        deleted: None,
        target: None,
    })
}

/// Create a new branch.
fn create_branch_cmd(
    ctx: &mut crate::output::CommandContext,
    void_dir: &std::path::PathBuf,
    void_dir_utf8: &Utf8PathBuf,
    name: &str,
    target: Option<String>,
    force: bool,
    current_branch: Option<String>,
) -> Result<BranchOutput, CliError> {
    ctx.progress(format!("Creating branch '{}'...", name));

    // Check if branch already exists (unless force is set)
    if !force
        && refs::read_branch(void_dir_utf8, name)
            .map_err(void_err_to_cli)?
            .is_some()
    {
        return Err(CliError::conflict(format!(
            "branch '{}' already exists",
            name
        )));
    }

    // Resolve target commit
    let target_ref = target.as_deref().unwrap_or("HEAD");
    let target_cid_bytes = resolve_ref(void_dir, target_ref)?;

    // Convert to CID string for output
    let target_cid_str = cid::from_bytes(target_cid_bytes.as_bytes())
        .map(|c| c.to_string())
        .map_err(|e| CliError::internal(format!("invalid CID: {}", e)))?;

    // Create the branch
    refs::write_branch(void_dir_utf8, name, &target_cid_bytes).map_err(void_err_to_cli)?;

    // Human-readable output
    if !ctx.use_json() {
        let short_cid = if target_cid_str.len() > 12 {
            &target_cid_str[..12]
        } else {
            &target_cid_str
        };
        ctx.info(format!("Created branch '{}' at {}...", name, short_cid));
    }

    Ok(BranchOutput {
        action: "create".to_string(),
        current: current_branch,
        head: None,
        branches: None,
        name: Some(name.to_string()),
        deleted: None,
        target: Some(target_cid_str),
    })
}

/// Delete a branch.
fn delete_branch_cmd(
    ctx: &mut crate::output::CommandContext,
    void_dir: &Utf8PathBuf,
    name: &str,
    current_branch: Option<&str>,
) -> Result<BranchOutput, CliError> {
    ctx.progress(format!("Deleting branch '{}'...", name));

    // Cannot delete current branch
    if current_branch == Some(name) {
        return Err(CliError::conflict(format!(
            "cannot delete branch '{}' which is currently checked out",
            name
        )));
    }

    // Check if branch exists
    if refs::read_branch(void_dir, name)
        .map_err(void_err_to_cli)?
        .is_none()
    {
        return Err(CliError::not_found(format!("branch '{}' not found", name)));
    }

    // Delete the branch
    refs::delete_branch(void_dir, name).map_err(void_err_to_cli)?;

    // Human-readable output
    if !ctx.use_json() {
        ctx.info(format!("Deleted branch '{}'", name));
    }

    Ok(BranchOutput {
        action: "delete".to_string(),
        current: current_branch.map(|s| s.to_string()),
        head: None,
        branches: None,
        name: None,
        deleted: Some(name.to_string()),
        target: None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::CliOptions;
    use std::fs;
    use tempfile::tempdir;
    use void_core::crypto;

    fn default_opts() -> CliOptions {
        CliOptions {
            human: true,
            ..Default::default()
        }
    }

    fn setup_test_repo() -> (tempfile::TempDir, std::path::PathBuf, tempfile::TempDir, crate::context::VoidHomeGuard) {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir_all(void_dir.join("objects")).unwrap();
        fs::create_dir_all(void_dir.join("refs/heads")).unwrap();

        // Set up manifest-based key
        let key = crypto::generate_key();
        let home = tempdir().unwrap();
        let guard = crate::context::setup_test_manifest(&void_dir, &key, home.path());

        // Create config file with repoSecret
        let repo_secret = hex::encode(crypto::generate_key());
        fs::write(
            void_dir.join("config.json"),
            format!(r#"{{"repoSecret": "{}"}}"#, repo_secret),
        )
        .unwrap();

        // Create initial commit (a valid CID)
        let cid_obj = cid::create(b"test commit");
        let cid_str = cid_obj.to_string();

        // Create trunk branch with initial commit
        fs::write(void_dir.join("refs/heads/trunk"), format!("{}\n", cid_str)).unwrap();

        // Set HEAD to trunk
        fs::write(void_dir.join("HEAD"), "ref: refs/heads/trunk\n").unwrap();

        (dir, void_dir, home, guard)
    }

    #[test]
    fn test_list_branches_empty() {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir_all(void_dir.join("refs/heads")).unwrap();

        // Set up manifest-based key
        let key = crypto::generate_key();
        let home = tempdir().unwrap();
        let _guard = crate::context::setup_test_manifest(&void_dir, &key, home.path());
        fs::write(void_dir.join("config.json"), "{}").unwrap();

        let args = BranchArgs {
            name: None,
            target: None,
            delete: false,
            force: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_branches_with_branches() {
        let (dir, void_dir, _home, _guard) = setup_test_repo();

        // Create another branch
        let cid_obj = cid::create(b"test");
        let cid_str = cid_obj.to_string();
        fs::write(
            void_dir.join("refs/heads/develop"),
            format!("{}\n", cid_str),
        )
        .unwrap();

        let args = BranchArgs {
            name: None,
            target: None,
            delete: false,
            force: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_branch() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        let args = BranchArgs {
            name: Some("feature/test".to_string()),
            target: None,
            delete: false,
            force: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_branch_already_exists() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        // Try to create trunk which already exists
        let args = BranchArgs {
            name: Some("trunk".to_string()),
            target: None,
            delete: false,
            force: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }

    #[test]
    fn test_create_branch_force_overwrites() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        // Create trunk with force=true should succeed
        let args = BranchArgs {
            name: Some("trunk".to_string()),
            target: None,
            delete: false,
            force: true,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_ok());
    }

    #[test]
    fn test_delete_branch() {
        let (dir, void_dir, _home, _guard) = setup_test_repo();

        // Create a branch to delete
        let cid_obj = cid::create(b"test");
        let cid_str = cid_obj.to_string();
        fs::write(
            void_dir.join("refs/heads/to-delete"),
            format!("{}\n", cid_str),
        )
        .unwrap();

        let args = BranchArgs {
            name: Some("to-delete".to_string()),
            target: None,
            delete: true,
            force: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_ok());

        // Verify branch is deleted
        assert!(!void_dir.join("refs/heads/to-delete").exists());
    }

    #[test]
    fn test_delete_current_branch_fails() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        // Try to delete trunk (current branch)
        let args = BranchArgs {
            name: Some("trunk".to_string()),
            target: None,
            delete: true,
            force: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }

    #[test]
    fn test_delete_nonexistent_branch() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        let args = BranchArgs {
            name: Some("nonexistent".to_string()),
            target: None,
            delete: true,
            force: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }

    #[test]
    fn test_branch_output_serialization() {
        let output = BranchOutput {
            action: "list".to_string(),
            current: Some("trunk".to_string()),
            head: Some(HeadRefOutput {
                kind: "symbolic".to_string(),
                value: "trunk".to_string(),
            }),
            branches: Some(vec!["develop".to_string(), "trunk".to_string()]),
            name: None,
            deleted: None,
            target: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"list\""));
        assert!(json.contains("\"current\":\"trunk\""));
        assert!(json.contains("\"branches\""));
        assert!(json.contains("\"head\""));
        assert!(json.contains("\"kind\":\"symbolic\""));
        assert!(!json.contains("\"name\""));
        assert!(!json.contains("\"target\""));
        assert!(!json.contains("\"deleted\""));
    }

    #[test]
    fn test_create_output_serialization() {
        let output = BranchOutput {
            action: "create".to_string(),
            current: Some("trunk".to_string()),
            head: None,
            branches: None,
            name: Some("feature".to_string()),
            deleted: None,
            target: Some("bafytest123".to_string()),
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"create\""));
        assert!(json.contains("\"name\":\"feature\""));
        assert!(json.contains("\"target\":\"bafytest123\""));
        assert!(!json.contains("\"branches\""));
        assert!(!json.contains("\"head\""));
        assert!(!json.contains("\"deleted\""));
    }

    #[test]
    fn test_delete_output_serialization() {
        let output = BranchOutput {
            action: "delete".to_string(),
            current: Some("trunk".to_string()),
            head: None,
            branches: None,
            name: None,
            deleted: Some("feature".to_string()),
            target: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"delete\""));
        assert!(json.contains("\"deleted\":\"feature\""));
        assert!(!json.contains("\"name\""));
        assert!(!json.contains("\"target\""));
        assert!(!json.contains("\"branches\""));
        assert!(!json.contains("\"head\""));
    }
}