homeboy 0.40.1

CLI for multi-component deployment and development workflow automation
Documentation
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
use clap::{Args, Subcommand};
use serde::Serialize;
use serde_json::Value;

use homeboy::defaults::{self, Defaults, HomeboyConfig};

use super::CmdResult;

#[derive(Args)]
pub struct ConfigArgs {
    #[command(subcommand)]
    command: ConfigCommand,
}

#[derive(Subcommand)]
enum ConfigCommand {
    /// Display configuration (merged defaults + file)
    Show {
        /// Show only built-in defaults (ignore homeboy.json)
        #[arg(long)]
        builtin: bool,
    },
    /// Set a configuration value at a JSON pointer path
    Set {
        /// JSON pointer path (e.g., /defaults/deploy/scp_flags)
        pointer: String,
        /// Value to set (JSON)
        value: String,
    },
    /// Remove a configuration value at a JSON pointer path
    Remove {
        /// JSON pointer path (e.g., /defaults/deploy/scp_flags)
        pointer: String,
    },
    /// Reset configuration to built-in defaults (deletes homeboy.json)
    Reset,
    /// Show the path to homeboy.json
    Path,
}

#[derive(Debug, Serialize)]
pub struct ConfigOutput {
    command: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    config: Option<HomeboyConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    defaults: Option<Defaults>,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    exists: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pointer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    value: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    deleted: Option<bool>,
}

pub fn run(args: ConfigArgs, _global: &crate::commands::GlobalArgs) -> CmdResult<ConfigOutput> {
    match args.command {
        ConfigCommand::Show { builtin } => show(builtin),
        ConfigCommand::Set { pointer, value } => set(&pointer, &value),
        ConfigCommand::Remove { pointer } => remove(&pointer),
        ConfigCommand::Reset => reset(),
        ConfigCommand::Path => path(),
    }
}

fn show(builtin: bool) -> CmdResult<ConfigOutput> {
    if builtin {
        Ok((
            ConfigOutput {
                command: "config.show".to_string(),
                defaults: Some(defaults::builtin_defaults()),
                config: None,
                path: None,
                exists: None,
                pointer: None,
                value: None,
                deleted: None,
            },
            0,
        ))
    } else {
        let config = defaults::load_config();
        Ok((
            ConfigOutput {
                command: "config.show".to_string(),
                config: Some(config),
                defaults: None,
                path: None,
                exists: None,
                pointer: None,
                value: None,
                deleted: None,
            },
            0,
        ))
    }
}

fn set(pointer: &str, value_str: &str) -> CmdResult<ConfigOutput> {
    // Validate pointer format
    if !pointer.starts_with('/') {
        return Err(homeboy::Error::validation_invalid_argument(
            "pointer",
            "JSON pointer must start with '/'",
            None,
            None,
        ));
    }

    // Parse the value as JSON
    let value: Value = serde_json::from_str(value_str).map_err(|e| {
        homeboy::Error::validation_invalid_json(
            e,
            Some("parse value".to_string()),
            Some(value_str.chars().take(200).collect::<String>()),
        )
    })?;

    // Load current config (or create default)
    let mut config = defaults::load_config();

    // Convert to JSON, set the value, convert back
    let mut config_json = serde_json::to_value(&config).map_err(|e| {
        homeboy::Error::internal_unexpected(format!("Failed to serialize config: {}", e))
    })?;

    // Navigate to the pointer location and set the value
    set_json_pointer(&mut config_json, pointer, value.clone())?;

    // Convert back to HomeboyConfig
    config = serde_json::from_value(config_json).map_err(|e| {
        homeboy::Error::validation_invalid_json(e, Some("deserialize config".to_string()), None)
    })?;

    // Save the config
    defaults::save_config(&config)?;

    Ok((
        ConfigOutput {
            command: "config.set".to_string(),
            config: Some(config),
            defaults: None,
            path: None,
            exists: None,
            pointer: Some(pointer.to_string()),
            value: Some(value),
            deleted: None,
        },
        0,
    ))
}

fn remove(pointer: &str) -> CmdResult<ConfigOutput> {
    // Validate pointer format
    if !pointer.starts_with('/') {
        return Err(homeboy::Error::validation_invalid_argument(
            "pointer",
            "JSON pointer must start with '/'",
            None,
            None,
        ));
    }

    // Load current config
    let mut config = defaults::load_config();

    // Convert to JSON
    let mut config_json = serde_json::to_value(&config).map_err(|e| {
        homeboy::Error::internal_unexpected(format!("Failed to serialize config: {}", e))
    })?;

    // Remove the value at the pointer
    remove_json_pointer(&mut config_json, pointer)?;

    // Convert back to HomeboyConfig
    config = serde_json::from_value(config_json).map_err(|e| {
        homeboy::Error::validation_invalid_json(e, Some("deserialize config".to_string()), None)
    })?;

    // Save the config
    defaults::save_config(&config)?;

    Ok((
        ConfigOutput {
            command: "config.remove".to_string(),
            config: Some(config),
            defaults: None,
            path: None,
            exists: None,
            pointer: Some(pointer.to_string()),
            value: None,
            deleted: None,
        },
        0,
    ))
}

fn reset() -> CmdResult<ConfigOutput> {
    let deleted = defaults::reset_config()?;

    Ok((
        ConfigOutput {
            command: "config.reset".to_string(),
            config: None,
            defaults: Some(defaults::builtin_defaults()),
            path: Some(defaults::config_path()?),
            exists: None,
            pointer: None,
            value: None,
            deleted: Some(deleted),
        },
        0,
    ))
}

fn path() -> CmdResult<ConfigOutput> {
    let path = defaults::config_path()?;
    let exists = defaults::config_exists();

    Ok((
        ConfigOutput {
            command: "config.path".to_string(),
            config: None,
            defaults: None,
            path: Some(path),
            exists: Some(exists),
            pointer: None,
            value: None,
            deleted: None,
        },
        0,
    ))
}

/// Set a value at a JSON pointer path, creating intermediate objects as needed.
fn set_json_pointer(root: &mut Value, pointer: &str, value: Value) -> homeboy::Result<()> {
    let parts: Vec<&str> = pointer[1..].split('/').collect();

    if parts.is_empty() {
        *root = value;
        return Ok(());
    }

    let mut current = root;

    for (i, part) in parts.iter().enumerate() {
        let key = unescape_json_pointer(part);

        if i == parts.len() - 1 {
            // Last part: set the value
            match current {
                Value::Object(map) => {
                    map.insert(key, value);
                    return Ok(());
                }
                Value::Array(arr) => {
                    let index: usize = key.parse().map_err(|_| {
                        homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Invalid array index: {}", key),
                            None,
                            None,
                        )
                    })?;
                    if index < arr.len() {
                        arr[index] = value;
                    } else if index == arr.len() {
                        arr.push(value);
                    } else {
                        return Err(homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Array index {} out of bounds (length {})", index, arr.len()),
                            None,
                            None,
                        ));
                    }
                    return Ok(());
                }
                _ => {
                    return Err(homeboy::Error::validation_invalid_argument(
                        "pointer",
                        format!("Cannot set property on non-object at path: {}", pointer),
                        None,
                        None,
                    ));
                }
            }
        } else {
            // Intermediate part: navigate or create
            match current {
                Value::Object(map) => {
                    if !map.contains_key(&key) {
                        map.insert(key.clone(), Value::Object(serde_json::Map::new()));
                    }
                    current = map.get_mut(&key).expect("key just inserted or already exists");
                }
                Value::Array(arr) => {
                    let index: usize = key.parse().map_err(|_| {
                        homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Invalid array index: {}", key),
                            None,
                            None,
                        )
                    })?;
                    if index >= arr.len() {
                        return Err(homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Array index {} out of bounds (length {})", index, arr.len()),
                            None,
                            None,
                        ));
                    }
                    current = &mut arr[index];
                }
                _ => {
                    return Err(homeboy::Error::validation_invalid_argument(
                        "pointer",
                        format!("Cannot navigate through non-object at path: {}", pointer),
                        None,
                        None,
                    ));
                }
            }
        }
    }

    Ok(())
}

/// Remove a value at a JSON pointer path.
fn remove_json_pointer(root: &mut Value, pointer: &str) -> homeboy::Result<()> {
    let parts: Vec<&str> = pointer[1..].split('/').collect();

    if parts.is_empty() {
        return Err(homeboy::Error::validation_invalid_argument(
            "pointer",
            "Cannot remove root element",
            None,
            None,
        ));
    }

    let mut current = root;

    for (i, part) in parts.iter().enumerate() {
        let key = unescape_json_pointer(part);

        if i == parts.len() - 1 {
            // Last part: remove the value
            match current {
                Value::Object(map) => {
                    if map.remove(&key).is_none() {
                        return Err(homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Key '{}' not found", key),
                            None,
                            None,
                        ));
                    }
                    return Ok(());
                }
                Value::Array(arr) => {
                    let index: usize = key.parse().map_err(|_| {
                        homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Invalid array index: {}", key),
                            None,
                            None,
                        )
                    })?;
                    if index >= arr.len() {
                        return Err(homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Array index {} out of bounds (length {})", index, arr.len()),
                            None,
                            None,
                        ));
                    }
                    arr.remove(index);
                    return Ok(());
                }
                _ => {
                    return Err(homeboy::Error::validation_invalid_argument(
                        "pointer",
                        format!("Cannot remove from non-object at path: {}", pointer),
                        None,
                        None,
                    ));
                }
            }
        } else {
            // Intermediate part: navigate
            match current {
                Value::Object(map) => {
                    current = map.get_mut(&key).ok_or_else(|| {
                        homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Key '{}' not found", key),
                            None,
                            None,
                        )
                    })?;
                }
                Value::Array(arr) => {
                    let index: usize = key.parse().map_err(|_| {
                        homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Invalid array index: {}", key),
                            None,
                            None,
                        )
                    })?;
                    if index >= arr.len() {
                        return Err(homeboy::Error::validation_invalid_argument(
                            "pointer",
                            format!("Array index {} out of bounds (length {})", index, arr.len()),
                            None,
                            None,
                        ));
                    }
                    current = &mut arr[index];
                }
                _ => {
                    return Err(homeboy::Error::validation_invalid_argument(
                        "pointer",
                        format!("Cannot navigate through non-object at path: {}", pointer),
                        None,
                        None,
                    ));
                }
            }
        }
    }

    Ok(())
}

/// Unescape JSON pointer special characters (~0 = ~, ~1 = /)
fn unescape_json_pointer(s: &str) -> String {
    s.replace("~1", "/").replace("~0", "~")
}