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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Switch branch or restore working tree files.
//!
//! Switches between branches or commits, updating the working tree.
//! Can also create a new branch and switch to it in one operation.

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

use camino::Utf8PathBuf;
use serde::Serialize;
use void_core::crypto::{CommitCid, KeyVault};
use void_core::store::FsStore;
use void_core::workspace::checkout::{checkout_tree, CheckoutOptions, CheckoutStats};
use void_core::workspace::stage::{status_workspace, StatusOptions};
use void_core::{cid, refs};

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

/// Command-line arguments for switch.
#[derive(Debug)]
pub struct SwitchArgs {
    /// Branch name to switch to.
    pub target: Option<String>,
    /// Create a new branch and switch to it.
    pub create: bool,
    /// Detach HEAD at the given commit CID.
    pub detach: Option<String>,
    /// Force switch even with uncommitted changes.
    pub force: bool,
}

/// JSON output for the switch command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SwitchOutput {
    /// The new HEAD state.
    pub head: HeadRefOutput,
}

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

/// Run the switch command.
///
/// # Arguments
///
/// * `cwd` - Current working directory
/// * `args` - Switch arguments
/// * `opts` - CLI options
///
/// # Operations
///
/// * `switch <branch>`: Switch HEAD to existing branch
/// * `switch -c <name>`: Create new branch and switch
/// * `switch --detach <cid>`: Detached HEAD mode at given CID
pub fn run(cwd: &Path, args: SwitchArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("switch", 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 workspace root (parent of .void)
        let workspace = void_dir
            .parent()
            .ok_or_else(|| CliError::internal("void_dir has no parent"))?;

        // Open repo via SDK to get vault and for status checks
        let repo = open_repo(cwd)?;
        let vault = repo.vault().clone();

        // Check for uncommitted changes unless --force
        if !args.force {
            ctx.progress("Checking for uncommitted changes...");
            check_clean_workspace_with_ctx(repo.context().clone())?;
        }

        // Handle --detach <cid> mode
        if let Some(ref detach_cid) = args.detach {
            ctx.progress("Checking out files...");

            // Resolve the CID
            let target_cid_bytes = resolve_ref(&void_dir, detach_cid)?;

            // Checkout the tree
            let _stats = checkout_commit(
                &void_dir,
                &*vault,
                &target_cid_bytes,
                workspace,
                args.force,
                ctx.use_json(),
            )?;

            // Set HEAD to detached
            refs::write_head(&void_dir_utf8, &refs::HeadRef::Detached(target_cid_bytes))
                .map_err(void_err_to_cli)?;

            // Human-readable output
            if !ctx.use_json() {
                ctx.info(format!(
                    "Note: switching to detached HEAD at '{}'",
                    detach_cid
                ));
                ctx.info("");
                ctx.info(
                    "You are in 'detached HEAD' state. You can look around, make experimental",
                );
                ctx.info(
                    "changes and commit them, and you can discard any commits you make in this",
                );
                ctx.info("state without impacting any branches by switching back to a branch.");
            }

            return Ok(SwitchOutput {
                head: HeadRefOutput {
                    kind: "detached".to_string(),
                    value: detach_cid.clone(),
                },
            });
        }

        // Require target for non-detach mode
        let target = args
            .target
            .as_ref()
            .ok_or_else(|| CliError::invalid_args("Branch name is required"))?;

        // Handle branch creation if requested
        if args.create {
            ctx.progress(format!("Creating branch '{}'...", target));
            create_branch(&void_dir, &void_dir_utf8, target)?;
        }

        // Resolve the target to a commit CID
        let (target_cid_bytes, _is_branch) = if args.create {
            // If we created the branch, it now exists, so resolve it
            let cid_bytes = resolve_ref(&void_dir, target)?;
            (cid_bytes, true)
        } else {
            // Normal switch: check if target is a branch
            let is_branch = refs::read_branch(&void_dir_utf8, target)
                .map_err(void_err_to_cli)?
                .is_some();

            if !is_branch {
                // Target is not a branch
                return Err(CliError::not_found(format!("Branch not found: {}", target)));
            }

            let cid_bytes = resolve_ref(&void_dir, target)?;
            (cid_bytes, is_branch)
        };

        // Checkout the tree from the target commit
        ctx.progress("Checking out files...");
        let _stats = checkout_commit(
            &void_dir,
            &*vault,
            &target_cid_bytes,
            workspace,
            args.force,
            ctx.use_json(),
        )?;

        // Update HEAD to symbolic ref
        refs::write_head(&void_dir_utf8, &refs::HeadRef::Symbolic(target.clone()))
            .map_err(void_err_to_cli)?;

        // Human-readable output
        if !ctx.use_json() {
            if args.create {
                ctx.info(format!("Switched to branch '{}' (newly created)", target));
            } else {
                ctx.info(format!("Switched to branch '{}'", target));
            }
        }

        Ok(SwitchOutput {
            head: HeadRefOutput {
                kind: "symbolic".to_string(),
                value: target.clone(),
            },
        })
    })
}

/// Get the current HEAD name (branch name or "detached").
#[allow(dead_code)] // Used by tests and kept for future switch improvements
fn get_current_head_name(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)),
        Some(refs::HeadRef::Detached(commit_cid)) => {
            // Return short CID for detached HEAD
            let cid_obj = cid::from_bytes(commit_cid.as_bytes())
                .map_err(|e| CliError::internal(format!("invalid CID: {}", e)))?;
            let cid_str = cid_obj.to_string();
            let short = if cid_str.len() > 12 {
                &cid_str[..12]
            } else {
                &cid_str
            };
            Ok(Some(format!("detached:{}", short)))
        }
        None => Ok(None),
    }
}

/// Check that the workspace has no uncommitted changes using an existing VoidContext.
fn check_clean_workspace_with_ctx(void_ctx: void_core::VoidContext) -> Result<(), CliError> {
    let status_opts = StatusOptions {
        ctx: void_ctx,
        patterns: vec![],
        observer: None,
    };

    let result = status_workspace(status_opts).map_err(void_err_to_cli)?;

    let has_changes = !result.staged_added.is_empty()
        || !result.staged_modified.is_empty()
        || !result.staged_deleted.is_empty()
        || !result.unstaged_modified.is_empty()
        || !result.unstaged_deleted.is_empty();

    if has_changes {
        return Err(CliError::conflict(
            "You have uncommitted changes. Commit or stash them before switching, or use --force to discard them.",
        ));
    }

    Ok(())
}

/// Create a new branch at HEAD.
fn create_branch(void_dir: &Path, void_dir_utf8: &Utf8PathBuf, name: &str) -> Result<(), CliError> {
    // Check if branch already exists
    if 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 HEAD to get the commit CID
    let head_cid_bytes = resolve_ref(void_dir, "HEAD")?;

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

    Ok(())
}

/// Checkout files from a commit.
fn checkout_commit(
    void_dir: &Path,
    vault: &KeyVault,
    commit_cid: &CommitCid,
    workspace: &Path,
    force: bool,
    use_json: bool,
) -> Result<CheckoutStats, CliError> {
    let commit_cid =
        cid::from_bytes(commit_cid.as_bytes()).map_err(|e| CliError::internal(e.to_string()))?;
    let objects_dir = Utf8PathBuf::try_from(void_dir.join("objects"))
        .map_err(|e| CliError::internal(format!("invalid objects path: {}", e)))?;

    let store = FsStore::new(objects_dir)
        .map_err(|e| CliError::internal(format!("failed to open store: {}", e)))?;

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

    let checkout_opts = CheckoutOptions {
        paths: None, // Full tree checkout
        force,
        observer: Some(observer.clone()),
        workspace_dir: None,
        include_large: false,
    };

    let stats = checkout_tree(&store, vault, &commit_cid, workspace, &checkout_opts)
        .map_err(void_err_to_cli)?;

    observer.finish();

    Ok(stats)
}

#[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();

        // Create key and manifest
        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 = void_core::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_get_current_head_name_symbolic() {
        let (dir, void_dir, _home, _guard) = setup_test_repo();
        let void_dir_utf8 = Utf8PathBuf::try_from(void_dir).unwrap();

        let name = get_current_head_name(&void_dir_utf8).unwrap();
        assert_eq!(name, Some("trunk".to_string()));

        drop(dir);
    }

    #[test]
    fn test_get_current_head_name_detached() {
        let (dir, void_dir, _home, _guard) = setup_test_repo();
        let void_dir_utf8 = Utf8PathBuf::try_from(void_dir.clone()).unwrap();

        // Set HEAD to detached
        let cid_obj = void_core::cid::create(b"test");
        let cid_str = cid_obj.to_string();
        fs::write(void_dir.join("HEAD"), format!("{}\n", cid_str)).unwrap();

        let name = get_current_head_name(&void_dir_utf8).unwrap();
        assert!(name.is_some());
        assert!(name.unwrap().starts_with("detached:"));

        drop(dir);
    }

    #[test]
    fn test_switch_output_serialization_symbolic() {
        let output = SwitchOutput {
            head: HeadRefOutput {
                kind: "symbolic".to_string(),
                value: "feature".to_string(),
            },
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"kind\":\"symbolic\""));
        assert!(json.contains("\"value\":\"feature\""));
    }

    #[test]
    fn test_switch_output_serialization_detached() {
        let output = SwitchOutput {
            head: HeadRefOutput {
                kind: "detached".to_string(),
                value: "bafkreiabc123".to_string(),
            },
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"kind\":\"detached\""));
        assert!(json.contains("\"value\":\"bafkreiabc123\""));
    }

    #[test]
    fn test_create_branch_already_exists() {
        let (dir, void_dir, _home, _guard) = setup_test_repo();
        let void_dir_utf8 = Utf8PathBuf::try_from(void_dir.clone()).unwrap();

        let result = create_branch(&void_dir, &void_dir_utf8, "trunk");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("already exists"));

        drop(dir);
    }

    #[test]
    fn test_create_branch_new() {
        let (dir, void_dir, _home, _guard) = setup_test_repo();
        let void_dir_utf8 = Utf8PathBuf::try_from(void_dir.clone()).unwrap();

        let result = create_branch(&void_dir, &void_dir_utf8, "new-branch");
        assert!(result.is_ok());

        // Verify branch was created
        assert!(void_dir.join("refs/heads/new-branch").exists());

        drop(dir);
    }

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

        let args = SwitchArgs {
            target: Some("nonexistent".to_string()),
            create: false,
            detach: None,
            force: true, // Skip workspace check
        };

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

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

        let args = SwitchArgs {
            target: None,
            create: false,
            detach: None,
            force: true,
        };

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