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
//! Tag command - manage lightweight tags for commits.
//!
//! Tags are human-readable references to specific commits. Unlike branches,
//! tags don't move when new commits are created.

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 tag.
#[derive(Debug)]
pub struct TagArgs {
    /// Tag name to create or delete (None for listing)
    pub name: Option<String>,
    /// List all tags
    pub list: bool,
    /// Target commit (defaults to HEAD)
    pub target: Option<String>,
    /// Delete the tag instead of creating it
    pub delete: bool,
    /// Overwrite existing tag
    pub force: bool,
}

/// JSON output for the tag command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TagOutput {
    /// Action performed: "list", "create", or "delete"
    pub action: String,
    /// List of all tags (for list action)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    /// Tag name (for create action)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Deleted tag 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 tag command.
///
/// # Operations
///
/// - **List tags** (`--list` or no name): Show all tags in the repository
/// - **Create tag** (`tag <name>` or `tag <name> --target <commit>`): Create a tag at HEAD or specified commit
/// - **Delete tag** (`tag -d <name>`): Delete a tag
///
/// # Arguments
///
/// * `cwd` - Current working directory
/// * `args` - Tag arguments
/// * `opts` - CLI options
///
/// # Errors
///
/// Returns an error if:
/// - Not in a void repository
/// - Tag already exists (for create, unless --force)
/// - Tag not found (for delete)
/// - Invalid tag name
pub fn run(cwd: &Path, args: TagArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("tag", 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)))?;

        // Determine operation based on arguments
        // List tags: --list flag or no name provided (and not deleting)
        if args.list || (args.name.is_none() && !args.delete) {
            ctx.progress("Listing tags...");

            let tags = refs::list_tags(&void_dir_utf8).map_err(void_err_to_cli)?;

            // Human-readable output
            if !ctx.use_json() {
                if tags.is_empty() {
                    ctx.info("No tags found.");
                } else {
                    for tag in &tags {
                        ctx.info(tag.clone());
                    }
                }
            }

            return Ok(TagOutput {
                action: "list".to_string(),
                tags: Some(tags),
                name: None,
                deleted: None,
                target: None,
            });
        }

        // Delete tag: -d flag with name
        if args.delete {
            let name = args
                .name
                .as_ref()
                .ok_or_else(|| CliError::invalid_args("tag name required for delete"))?;

            ctx.progress(format!("Deleting tag '{}'...", name));

            // Check if tag exists
            let existing = refs::read_tag(&void_dir_utf8, name).map_err(void_err_to_cli)?;
            if existing.is_none() {
                return Err(CliError::not_found(format!("tag '{}' not found", name)));
            }

            refs::delete_tag(&void_dir_utf8, name).map_err(void_err_to_cli)?;

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

            return Ok(TagOutput {
                action: "delete".to_string(),
                tags: None,
                name: None,
                deleted: Some(name.clone()),
                target: None,
            });
        }

        // Create tag: name provided without -d flag
        let name = args
            .name
            .as_ref()
            .ok_or_else(|| CliError::invalid_args("tag name required"))?;

        ctx.progress(format!("Creating tag '{}'...", name));

        // Check if tag already exists
        let existing = refs::read_tag(&void_dir_utf8, name).map_err(void_err_to_cli)?;
        if existing.is_some() && !args.force {
            return Err(CliError::conflict(format!(
                "tag '{}' already exists (use --force to overwrite)",
                name
            )));
        }

        // Resolve target to commit CID
        let target_ref = args.target.as_deref().unwrap_or("HEAD");
        let cid_bytes = resolve_ref(&void_dir, target_ref)?;

        // Convert CID bytes to string for output
        let cid_str = cid::from_bytes(cid_bytes.as_bytes())
            .map(|c| c.to_string())
            .unwrap_or_else(|_| hex::encode(cid_bytes.as_bytes()));

        refs::write_tag(&void_dir_utf8, name, &cid_bytes).map_err(void_err_to_cli)?;

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

        Ok(TagOutput {
            action: "create".to_string(),
            tags: None,
            name: Some(name.clone()),
            deleted: None,
            target: Some(cid_str),
        })
    })
}

#[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/tags")).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_list_tags_empty() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

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

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

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

        // Create some tag files manually
        let tags_dir = void_dir.join("refs/tags");
        // Use a valid CID format (bafk... is a valid CIDv1 prefix)
        fs::write(
            tags_dir.join("v1.0.0"),
            "bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku\n",
        )
        .unwrap();
        fs::write(
            tags_dir.join("v2.0.0"),
            "bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku\n",
        )
        .unwrap();

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

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

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

        // Even with a name, --list should list tags
        let args = TagArgs {
            name: Some("v1.0.0".to_string()),
            list: true,
            target: None,
            delete: false,
            force: false,
        };

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

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

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

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

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

        let args = TagArgs {
            name: None,
            list: false,
            target: None,
            delete: true,
            force: false,
        };

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

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

        // No HEAD set, so creating a tag at HEAD should fail
        let args = TagArgs {
            name: Some("v1.0.0".to_string()),
            list: false,
            target: None,
            delete: false,
            force: false,
        };

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

    #[test]
    fn test_tag_not_initialized() {
        let dir = tempdir().unwrap();
        // Don't create .void directory

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

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

    #[test]
    fn test_tag_output_serialization() {
        let output = TagOutput {
            action: "list".to_string(),
            tags: Some(vec!["v1.0.0".to_string(), "v2.0.0".to_string()]),
            name: None,
            deleted: None,
            target: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"list\""));
        assert!(json.contains("\"tags\":[\"v1.0.0\",\"v2.0.0\"]"));
        // name, deleted, and target should be omitted due to skip_serializing_if
        assert!(!json.contains("\"name\""));
        assert!(!json.contains("\"deleted\""));
        assert!(!json.contains("\"target\""));
    }

    #[test]
    fn test_tag_output_create_serialization() {
        let output = TagOutput {
            action: "create".to_string(),
            tags: None,
            name: Some("v1.0.0".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\":\"v1.0.0\""));
        assert!(json.contains("\"target\":\"bafytest123\""));
        // tags and deleted should be omitted
        assert!(!json.contains("\"tags\""));
        assert!(!json.contains("\"deleted\""));
    }

    #[test]
    fn test_tag_output_delete_serialization() {
        let output = TagOutput {
            action: "delete".to_string(),
            tags: None,
            name: None,
            deleted: Some("v1.0.0".to_string()),
            target: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"delete\""));
        assert!(json.contains("\"deleted\":\"v1.0.0\""));
        // tags, name, and target should be omitted
        assert!(!json.contains("\"tags\""));
        assert!(!json.contains("\"name\""));
        assert!(!json.contains("\"target\""));
    }
}