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
//! Resolve command for marking merge conflicts as resolved.
//!
//! During a merge, when conflicts occur, the user can resolve them by:
//! 1. Manually editing the file and staging it with `void add`
//! 2. Using `void resolve --ours/--theirs <path>` to pick one version
//!
//! This command implements option 2 by checking out the chosen version
//! and staging the resolved file.

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

use camino::Utf8PathBuf;
use serde::Serialize;
use void_core::ops::merge_state::{is_merge_in_progress, read_merge_state};
use void_core::store::FsStore;
use void_core::workspace::checkout::{checkout_tree, CheckoutOptions};
use void_core::workspace::stage::{stage_paths, StageOptions};
use void_core::cid;

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

/// Command-line arguments for resolve.
#[derive(Debug)]
pub struct ResolveArgs {
    /// Paths to resolve.
    pub paths: Vec<String>,
    /// Use our version (HEAD).
    pub ours: bool,
    /// Use their version (merge head).
    pub theirs: bool,
    /// Resolve all conflicts.
    pub all: bool,
}

/// JSON output for the resolve command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveOutput {
    /// List of resolved paths.
    pub resolved: Vec<String>,
    /// Count of unresolved conflicts remaining.
    pub remaining: usize,
    /// True if all conflicts are resolved.
    pub merge_complete: bool,
}

/// Run the resolve command.
///
/// # Arguments
///
/// * `cwd` - Current working directory
/// * `args` - Resolve arguments
/// * `opts` - CLI options
///
/// # Operations
///
/// * Validates a merge is in progress
/// * Validates exactly one of --ours/--theirs is specified
/// * For each path, checks out the chosen version and stages it
pub fn run(cwd: &Path, args: ResolveArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("resolve", opts, |ctx| {
        let void_dir = find_void_dir(cwd)?;

        // Get workspace root (parent of .void)
        let workspace = void_dir
            .parent()
            .ok_or_else(|| CliError::internal("void_dir has no parent"))?;

        let repo = open_repo(workspace)?;
        let vault = repo.vault().clone();

        // Validate flags: must specify exactly one of --ours or --theirs
        if args.ours && args.theirs {
            return Err(CliError::invalid_args(
                "cannot specify both --ours and --theirs",
            ));
        }
        if !args.ours && !args.theirs {
            return Err(CliError::invalid_args(
                "must specify either --ours or --theirs",
            ));
        }

        // Check that a merge is in progress
        if !is_merge_in_progress(&void_dir) {
            return Err(CliError::conflict("no merge in progress"));
        }

        // Read merge state to get conflict list and refs
        let merge_state = read_merge_state(&void_dir)
            .map_err(void_err_to_cli)?
            .ok_or_else(|| CliError::conflict("no merge in progress"))?;

        // Validate --all vs paths
        if args.all && !args.paths.is_empty() {
            return Err(CliError::invalid_args(
                "cannot specify both --all and paths",
            ));
        }

        // Determine which paths to resolve
        let paths_to_resolve = if args.all {
            merge_state.conflicts.clone()
        } else {
            // Validate paths are provided
            if args.paths.is_empty() {
                return Err(CliError::invalid_args("no paths specified"));
            }

            // Validate that specified paths are in the conflict list
            for path in &args.paths {
                if !merge_state.conflicts.contains(path) {
                    return Err(CliError::not_found(format!(
                        "path '{}' is not in the conflict list",
                        path
                    )));
                }
            }
            args.paths.clone()
        };

        let total_conflicts = merge_state.conflicts.len();

        let strategy = if args.ours { "ours" } else { "theirs" };
        ctx.progress(format!(
            "Resolving {} file(s) using {}...",
            paths_to_resolve.len(),
            strategy
        ));

        // Determine which commit to checkout from
        let commit_cid_bytes = if args.ours {
            // Use HEAD (orig_head from merge state)
            merge_state.orig_head.clone()
        } else {
            // Use MERGE_HEAD (theirs)
            merge_state.merge_head.clone()
        };

        let commit_cid = cid::from_bytes(commit_cid_bytes.as_bytes())
            .map_err(|e| CliError::internal(format!("invalid commit CID: {}", e)))?;

        // Build object store
        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(void_err_to_cli)?;

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

        // Checkout the specified paths from the chosen commit
        let checkout_opts = CheckoutOptions {
            paths: Some(paths_to_resolve.clone()),
            force: true, // Force overwrite since we're resolving conflicts
            observer: Some(observer.clone()),
            workspace_dir: None,
            include_large: false,
        };

        checkout_tree(&store, &*vault, &commit_cid, workspace, &checkout_opts)
            .map_err(void_err_to_cli)?;

        observer.finish();

        // Stage the resolved files

        // Create observer for staging
        let stage_observer: Arc<ProgressObserver> = if ctx.use_json() {
            Arc::new(ProgressObserver::new_hidden())
        } else {
            Arc::new(ProgressObserver::new("Staging resolved files..."))
        };

        let stage_opts = StageOptions {
            ctx: repo.context().clone(),
            patterns: paths_to_resolve.clone(),
            observer: Some(stage_observer.clone()),
        };

        stage_paths(stage_opts).map_err(void_err_to_cli)?;

        stage_observer.finish();

        // Calculate remaining conflicts
        let remaining = total_conflicts - paths_to_resolve.len();
        let merge_complete = remaining == 0;

        // Human-readable output
        if !ctx.use_json() {
            for path in &paths_to_resolve {
                ctx.info(format!("Resolved '{}' using {}", path, strategy));
            }
            if merge_complete {
                ctx.info(
                    "All conflicts resolved. Run 'void merge --continue' to complete the merge."
                        .to_string(),
                );
            } else {
                ctx.info(format!("{} conflict(s) remaining", remaining));
            }
        }

        Ok(ResolveOutput {
            resolved: paths_to_resolve,
            remaining,
            merge_complete,
        })
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::CliOptions;
    use std::fs;
    use tempfile::tempdir;
    use void_core::crypto::{self, CommitCid};
    use void_core::ops::merge_state::{write_merge_state, MergeState};

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

        (dir, void_dir, home, guard)
    }

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

        let args = ResolveArgs {
            paths: vec!["src/main.rs".to_string()],
            ours: true,
            theirs: false,
            all: false,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
        // Error message should mention no merge in progress
    }

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

        // Create a merge state
        let state = MergeState {
            merge_head: CommitCid::from_bytes(vec![0x01, 0x02, 0x03]),
            merge_base: None,
            orig_head: CommitCid::from_bytes(vec![0x04, 0x05, 0x06]),
            conflicts: vec!["src/main.rs".to_string()],
            message: "Merge".to_string(),
        };
        write_merge_state(&void_dir, &state).unwrap();

        let args = ResolveArgs {
            paths: vec!["src/main.rs".to_string()],
            ours: true,
            theirs: true,
            all: false,
        };

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

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

        // Create a merge state
        let state = MergeState {
            merge_head: CommitCid::from_bytes(vec![0x01, 0x02, 0x03]),
            merge_base: None,
            orig_head: CommitCid::from_bytes(vec![0x04, 0x05, 0x06]),
            conflicts: vec!["src/main.rs".to_string()],
            message: "Merge".to_string(),
        };
        write_merge_state(&void_dir, &state).unwrap();

        let args = ResolveArgs {
            paths: vec!["src/main.rs".to_string()],
            ours: false,
            theirs: false,
            all: false,
        };

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

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

        // Create a merge state
        let state = MergeState {
            merge_head: CommitCid::from_bytes(vec![0x01, 0x02, 0x03]),
            merge_base: None,
            orig_head: CommitCid::from_bytes(vec![0x04, 0x05, 0x06]),
            conflicts: vec!["src/main.rs".to_string()],
            message: "Merge".to_string(),
        };
        write_merge_state(&void_dir, &state).unwrap();

        let args = ResolveArgs {
            paths: vec![],
            ours: true,
            theirs: false,
            all: false,
        };

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

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

        // Create a merge state with different conflicts
        let state = MergeState {
            merge_head: CommitCid::from_bytes(vec![0x01, 0x02, 0x03]),
            merge_base: None,
            orig_head: CommitCid::from_bytes(vec![0x04, 0x05, 0x06]),
            conflicts: vec!["other/file.rs".to_string()],
            message: "Merge".to_string(),
        };
        write_merge_state(&void_dir, &state).unwrap();

        let args = ResolveArgs {
            paths: vec!["src/main.rs".to_string()],
            ours: true,
            theirs: false,
            all: false,
        };

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

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

        // Create a merge state
        let state = MergeState {
            merge_head: CommitCid::from_bytes(vec![0x01, 0x02, 0x03]),
            merge_base: None,
            orig_head: CommitCid::from_bytes(vec![0x04, 0x05, 0x06]),
            conflicts: vec!["src/main.rs".to_string()],
            message: "Merge".to_string(),
        };
        write_merge_state(&void_dir, &state).unwrap();

        let args = ResolveArgs {
            paths: vec!["src/main.rs".to_string()],
            ours: true,
            theirs: false,
            all: true,
        };

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

    #[test]
    fn test_resolve_output_serialization() {
        let output = ResolveOutput {
            resolved: vec!["src/main.rs".to_string(), "lib/utils.rs".to_string()],
            remaining: 1,
            merge_complete: false,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"resolved\""));
        assert!(json.contains("\"src/main.rs\""));
        assert!(json.contains("\"lib/utils.rs\""));
        assert!(json.contains("\"remaining\":1"));
        assert!(json.contains("\"mergeComplete\":false"));
    }

    #[test]
    fn test_resolve_output_serialization_complete() {
        let output = ResolveOutput {
            resolved: vec!["README.md".to_string()],
            remaining: 0,
            merge_complete: true,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"remaining\":0"));
        assert!(json.contains("\"mergeComplete\":true"));
    }
}