ocd 0.8.0

Organize current dotfiles
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
// SPDX-FileCopyrightText: 2025 Jason Pena <jasonpena@awkless.com>
// SPDX-License-Identifier: MIT

//! Command set implementation.
//!
//! This module is the forward facing API of internal library. It is meant to be used in `main` of
//! the OCD binary. The entire OCD command set is implemented right there!.

use crate::{
    model::{
        cluster::{Cluster, NodeEntry, RootEntry},
        config_dir, data_dir,
        hook::{HookAction, HookKind, HookRunner},
    },
    store::{DeployAction, MultiNodeClone, Node, Root, TablizeCluster},
};

use anyhow::{anyhow, Context, Result};
use clap::{Parser, Subcommand};
use inquire::prompt_confirmation;
use std::{ffi::OsString, fs::remove_dir_all};
use tracing::{info, instrument, warn};

/// OCD public command set CLI.
#[derive(Debug, Clone, Parser)]
#[command(
    about,
    override_usage = "\n  ocd [options] <ocd-command>\n  ocd [options] [target]... <git-command>",
    subcommand_help_heading = "Commands",
    version
)]
pub struct Ocd {
    #[arg(default_value_t = HookAction::default(), long, short, value_enum, value_name = "action")]
    pub run_hook: HookAction,

    /// Command-set interfaces.
    #[command(subcommand)]
    pub command: Command,
}

impl Ocd {
    /// Run OCD command based on given arguments.
    ///
    /// # Panics
    ///
    /// May panic if given command implementation also panics.
    ///
    /// # Errors
    ///
    /// Will fail if given command implementation fails.
    pub async fn run(self) -> Result<()> {
        match self.command {
            Command::Clone(opts) => run_clone(self.run_hook, opts).await,
            Command::Init(opts) => run_init(self.run_hook, opts),
            Command::Deploy(opts) => run_deploy(self.run_hook, opts),
            Command::Undeploy(opts) => run_undeploy(self.run_hook, opts),
            Command::Remove(opts) => run_remove(self.run_hook, opts),
            Command::List(opts) => run_list(self.run_hook, opts),
            Command::Git(opts) => run_git(opts),
        }
    }
}

/// Full command-set of OCD.
#[derive(Debug, Clone, Subcommand)]
pub enum Command {
    /// Clone existing cluster from root repository.
    #[command(override_usage = "ocd clone [options] <url>")]
    Clone(CloneOptions),

    /// Initialize new entries.
    #[command(override_usage = "ocd init [options] <node_name>")]
    Init(InitOptions),

    /// Deploy target entries in cluster.
    #[command(override_usage = "ocd deploy [options] [target]...")]
    Deploy(DeployOptions),

    /// Undeploy target entries in cluster.
    #[command(override_usage = "ocd undeploy [options] [target]...")]
    Undeploy(UndeployOptions),

    /// Remove target entries from cluster.
    #[command(name = "rm", override_usage = "ocd rm [options] [target]...")]
    Remove(RemoveOptions),

    /// List current entries in cluster.
    #[command(name = "ls", override_usage = "ocd list [options]")]
    List(ListOptions),

    /// Git binary shortcut.
    #[command(external_subcommand)]
    Git(Vec<OsString>),
}

/// Clone existing cluster.
#[derive(Parser, Clone, Debug)]
#[command(author, about, long_about)]
pub struct CloneOptions {
    /// URL to root repository to clone from.
    #[arg(value_name = "url")]
    pub url: String,

    /// Number of threads to use per node clone.
    #[arg(short, long, value_name = "limit")]
    pub jobs: Option<usize>,
}

/// Initialize new entry in repository store, based on cluster configuration entry.
#[derive(Parser, Clone, Debug)]
#[command(author, about, long_about)]
pub struct InitOptions {
    /// Name of new repository to initialize.
    #[arg(value_name = "entry_name")]
    pub entry_name: String,
}

/// Deploy node of cluster.
#[derive(Parser, Clone, Debug)]
#[command(author, about, long_about)]
pub struct DeployOptions {
    /// List of nodes to deploy ("root" is always deployed).
    #[arg(value_parser, num_args = 1.., value_delimiter = ',', value_name = "pattern")]
    pub patterns: Vec<String>,

    /// Do not deploy dependencies of target nodes.
    #[arg(short, long)]
    pub only: bool,

    /// Deploy excluded files as well.
    #[arg(short, long)]
    pub with_excluded: bool,
}

/// Undeploy nodes of cluster.
#[derive(Parser, Clone, Debug)]
#[command(author, about, long_about)]
pub struct UndeployOptions {
    /// List of nodes to undeploy ("root" cannot be undeployed).
    #[arg(value_parser, num_args = 1.., value_delimiter = ',', value_name = "pattern")]
    pub patterns: Vec<String>,

    /// Do not undeploy dependencies of target nodes.
    #[arg(short, long)]
    pub only: bool,

    /// Undeploy excluded files only.
    #[arg(short, long)]
    pub excluded_only: bool,
}

/// Remove target node from cluster.
#[derive(Parser, Clone, Debug)]
#[command(author, about, long_about)]
pub struct RemoveOptions {
    /// List of nodes to remove ("root" will nuke cluster).
    #[arg(value_parser, num_args = 1.., value_delimiter = ',', value_name = "pattern")]
    pub patterns: Vec<String>,
}

/// List current entries in cluster.
#[derive(Parser, Clone, Debug)]
#[command(author, about, long_about)]
pub struct ListOptions {
    /// Only list names of each entry only.
    #[arg(short, long)]
    pub names_only: bool,
}

#[instrument(skip(opts), level = "debug")]
async fn run_clone(action: HookAction, opts: CloneOptions) -> Result<()> {
    // INVARIANT: Wipe out cluster if root cannot be cloned or deployed.
    if let Err(error) = Root::new_clone(&opts.url) {
        warn!("Root clone failure, clearing broken cluster");
        let config_dir = config_dir()?;
        if config_dir.exists() {
            remove_dir_all(&config_dir)
                .with_context(|| format!("Failed to remove {config_dir:?}"))?;
        }

        let data_dir = data_dir()?;
        if data_dir.exists() {
            remove_dir_all(&data_dir).with_context(|| format!("Failed to remove {data_dir:?}"))?;
        }

        return Err(error);
    }

    let cluster = Cluster::new()?;
    let mut hooks = HookRunner::new()?;
    hooks.set_action(action);

    hooks.run("clone", HookKind::Pre, None)?;
    let multi_clone = MultiNodeClone::new(&cluster, opts.jobs)?;
    multi_clone.clone_all().await?;
    hooks.run("clone", HookKind::Post, None)?;

    Ok(())
}

pub fn run_init(action: HookAction, opts: InitOptions) -> Result<()> {
    let mut hooks = HookRunner::new()?;
    hooks.set_action(action);

    hooks.run("init", HookKind::Pre, Some(&vec![opts.entry_name.clone()]))?;

    match opts.entry_name.as_str() {
        "root" => {
            let path = config_dir()?.join(format!("{}.toml", opts.entry_name));
            if !path.exists() {
                return Err(anyhow!("No root entry to initialize! Define {path:?} first!"));
            }

            let data = std::fs::read_to_string(path)?;
            let root: RootEntry = toml::de::from_str(&data)?;
            let _ = Root::new_init(&root)?;
        }
        &_ => {
            let cluster = Cluster::new()?;
            let _ = Root::new_open(&cluster.root)
                .with_context(|| "Root may not have been properly initialized")?;

            let path = config_dir()?.join("nodes").join(format!("{}.toml", opts.entry_name));
            if !path.exists() {
                return Err(anyhow!("No node entry to initialize! Define {path:?} first!"));
            }

            let data = std::fs::read_to_string(path)?;
            let node: NodeEntry = toml::de::from_str(&data)?;
            let _ = Node::new_init(&opts.entry_name, &node)?;
        }
    }

    hooks.run("init", HookKind::Post, Some(&vec![opts.entry_name.clone()]))?;

    Ok(())
}

#[instrument(skip(opts), level = "debug")]
pub fn run_deploy(run_hook: HookAction, opts: DeployOptions) -> Result<()> {
    let cluster = Cluster::new()?;
    let root = Root::new_open(&cluster.root)?;
    let action = if opts.with_excluded { DeployAction::DeployAll } else { DeployAction::Deploy };

    let targets = cluster.match_targets(opts.patterns)?;
    let mut hooks = HookRunner::new()?;
    hooks.set_action(run_hook);
    hooks.run("deploy", HookKind::Pre, Some(&targets))?;

    let mut nodes = Vec::new();
    if opts.only {
        for target in &targets {
            if target == "root" {
                root.deploy(action)?;
                continue;
            }

            let entry = cluster.nodes.get(target).ok_or(anyhow!("Node {target:?} not defined"))?;
            let node = Node::new_open(target, entry)?;
            nodes.push(node);
        }
    } else {
        for target in &targets {
            if target == "root" {
                root.deploy(action)?;
                continue;
            }

            for (name, entry) in cluster.dependency_iter(target) {
                let node = Node::new_open(name, entry)?;
                nodes.push(node);
            }
        }
    }

    for node in nodes {
        node.deploy(action)?;
    }

    hooks.run("deploy", HookKind::Post, Some(&targets))?;

    Ok(())
}

fn run_undeploy(run_hook: HookAction, opts: UndeployOptions) -> Result<()> {
    let cluster = Cluster::new()?;
    let root = Root::new_open(&cluster.root)?;
    let action =
        if opts.excluded_only { DeployAction::UndeployExcludes } else { DeployAction::Undeploy };

    let targets = cluster.match_targets(opts.patterns)?;
    let mut hooks = HookRunner::new()?;
    hooks.set_action(run_hook);
    hooks.run("undeploy", HookKind::Pre, Some(&targets))?;

    let mut nodes = Vec::new();
    if opts.only {
        for target in &targets {
            if target == "root" {
                root.deploy(action)?;
                continue;
            }

            let entry = cluster.nodes.get(target).ok_or(anyhow!("Node {target:?} not defined"))?;
            let node = Node::new_open(target, entry)?;
            nodes.push(node);
        }
    } else {
        for target in &targets {
            if target == "root" {
                root.deploy(action)?;
                continue;
            }

            for (name, entry) in cluster.dependency_iter(target) {
                let node = Node::new_open(name, entry)?;
                nodes.push(node);
            }
        }
    }

    for node in nodes {
        node.deploy(action)?;
    }

    hooks.run("undeploy", HookKind::Post, Some(&targets))?;

    Ok(())
}

#[instrument(skip(opts), level = "debug")]
fn run_remove(run_hook: HookAction, opts: RemoveOptions) -> Result<()> {
    let cluster = Cluster::new()?;

    let targets = cluster.match_targets(opts.patterns)?;
    let mut hooks = HookRunner::new()?;
    hooks.set_action(run_hook);
    hooks.run("rm", HookKind::Pre, Some(&targets))?;

    if targets.contains(&"root".into()) {
        warn!("Removing root will nuke your entire cluster");
        if prompt_confirmation("Do you want to send your cluster to the gallows? [y/n]")? {
            nuke_cluster(&cluster)?;
        }
    } else {
        for target in &targets {
            let node = cluster.nodes.get(target).ok_or(anyhow!("Node {target:?} not defined"))?;
            let repo = Node::new_open(target, node)?;
            repo.nuke()?;
        }
    }

    hooks.run("rm", HookKind::Post, Some(&targets))?;

    Ok(())
}

fn nuke_cluster(cluster: &Cluster) -> Result<()> {
    let root = Root::new_open(&cluster.root)?;
    root.nuke()?;

    for (name, node) in &cluster.nodes {
        if !data_dir()?.join(name).exists() {
            warn!("Node {name:?} not found in repository store");
            continue;
        }

        let repo = Node::new_open(name, node)?;
        repo.nuke()?;
    }

    remove_dir_all(config_dir()?)?;
    info!("Configuration directory removed");

    remove_dir_all(data_dir()?)?;
    info!("Data directory removed");

    Ok(())
}

fn run_list(run_hook: HookAction, opts: ListOptions) -> Result<()> {
    let cluster = Cluster::new()?;
    let root = Root::new_open(&cluster.root)?;

    let mut hooks = HookRunner::new()?;
    hooks.set_action(run_hook);

    hooks.run("ls", HookKind::Pre, None)?;

    let tablize = TablizeCluster::new(&root, &cluster);
    if opts.names_only {
        tablize.names_only()?;
    } else {
        tablize.fancy()?;
    }

    hooks.run("ls", HookKind::Post, None)?;

    Ok(())
}

fn run_git(opts: Vec<OsString>) -> Result<()> {
    let cluster = Cluster::new()?;
    let root = Root::new_open(&cluster.root)?;
    let patterns = opts[0].to_string_lossy().into_owned();
    let patterns: Vec<String> = patterns.split(',').map(Into::into).collect();
    let targets = cluster.match_targets(patterns)?;

    for target in &targets {
        if target == "root" {
            root.gitcall(opts[1..].to_vec())?;
            continue;
        }

        let node = cluster.nodes.get(target).ok_or(anyhow!("{target} not found"))?;
        let node = Node::new_open(target, node)?;
        node.gitcall(opts[1..].to_vec())?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    use clap::CommandFactory;

    #[test]
    fn cli_verify_structure() {
        Ocd::command().debug_assert();
    }
}