cuenv 0.40.6

Event-driven CLI with inline TUI for cuenv
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! Command handler traits and implementations for lifecycle event management.
//!
//! This module provides the `CommandHandler` trait that standardizes command
//! execution with automatic event emission (start, complete), eliminating
//! boilerplate in individual command implementations.

use async_trait::async_trait;
use cuenv_core::Result;
use cuenv_events::{emit_stderr, emit_stdout};

use crate::cli::{ShellType, StatusFormat};
use crate::events::Event;

use super::{CommandExecutor, ci, env, exec, export, hooks, sync, task};

/// Trait for commands with lifecycle events.
///
/// Commands implementing this trait get automatic event emission
/// (`CommandStart`, `CommandComplete`) when executed through `CommandRunner`.
#[async_trait]
pub trait CommandHandler: Send + Sync {
    /// The unique name of this command for event tracking (e.g., "env print").
    fn command_name(&self) -> &'static str;

    /// Execute the command and return output string.
    async fn execute(&self, executor: &CommandExecutor) -> Result<String>;

    /// Whether to print output to stdout (default: true for non-empty output).
    fn should_print_output(&self) -> bool {
        true
    }
}

/// Extension trait for running commands with event lifecycle.
#[async_trait]
pub trait CommandRunner {
    /// Run a command with automatic event lifecycle management.
    async fn run_command<C: CommandHandler>(&self, cmd: C) -> Result<()>;
}

#[async_trait]
impl CommandRunner for CommandExecutor {
    async fn run_command<C: CommandHandler>(&self, cmd: C) -> Result<()> {
        let name = cmd.command_name();

        self.send_event(Event::CommandStart {
            command: name.to_string(),
        });

        match cmd.execute(self).await {
            Ok(output) => {
                if cmd.should_print_output() && !output.is_empty() {
                    emit_stdout!(&output);
                }
                self.send_event(Event::CommandComplete {
                    command: name.to_string(),
                    success: true,
                    output,
                });
                Ok(())
            }
            Err(e) => {
                emit_stderr!(format!("Error: {e}"));
                self.send_event(Event::CommandComplete {
                    command: name.to_string(),
                    success: false,
                    output: format!("Error: {e}"),
                });
                Err(e)
            }
        }
    }
}

// ============================================================================
// Command Handler Implementations
// ============================================================================

/// Handler for `env print` command.
pub struct EnvPrintHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Output format (e.g., "json", "yaml", "table").
    pub format: String,
    /// Optional environment name to use for evaluation.
    pub environment: Option<String>,
}

#[async_trait]
impl CommandHandler for EnvPrintHandler {
    fn command_name(&self) -> &'static str {
        "env print"
    }

    fn should_print_output(&self) -> bool {
        false // env::execute_env_print handles printing
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        env::execute_env_print(
            &self.path,
            &self.format,
            self.environment.as_deref(),
            executor,
        )
        .await
    }
}

/// Handler for `env list` command.
pub struct EnvListHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Output format (e.g., "json", "yaml", "table").
    pub format: String,
}

#[async_trait]
impl CommandHandler for EnvListHandler {
    fn command_name(&self) -> &'static str {
        "env list"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        env::execute_env_list(&self.path, &self.format, executor).await
    }
}

/// Handler for `env load` command.
pub struct EnvLoadHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
}

#[async_trait]
impl CommandHandler for EnvLoadHandler {
    fn command_name(&self) -> &'static str {
        "env load"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        hooks::execute_env_load(&self.path, &self.package, Some(executor)).await
    }
}

/// Handler for `env status` command.
pub struct EnvStatusHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Whether to wait for the environment to become ready.
    pub wait: bool,
    /// Maximum time in seconds to wait for environment readiness.
    pub timeout: u64,
    /// Output format for the status information.
    pub format: StatusFormat,
}

#[async_trait]
impl CommandHandler for EnvStatusHandler {
    fn command_name(&self) -> &'static str {
        "env status"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        hooks::execute_env_status(
            &self.path,
            &self.package,
            self.wait,
            self.timeout,
            self.format,
            Some(executor),
        )
        .await
    }
}

/// Handler for `env check` command.
pub struct EnvCheckHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Shell type to check compatibility with.
    pub shell: ShellType,
}

#[async_trait]
impl CommandHandler for EnvCheckHandler {
    fn command_name(&self) -> &'static str {
        "env check"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        hooks::execute_env_check(&self.path, &self.package, self.shell, Some(executor)).await
    }
}

/// Handler for `env inspect` command.
pub struct EnvInspectHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
}

#[async_trait]
impl CommandHandler for EnvInspectHandler {
    fn command_name(&self) -> &'static str {
        "env inspect"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        hooks::execute_env_inspect(&self.path, &self.package, Some(executor)).await
    }
}

/// Handler for `allow` command.
pub struct AllowHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Optional note explaining why this project is allowed.
    pub note: Option<String>,
    /// Skip confirmation prompt and automatically approve.
    pub yes: bool,
}

#[async_trait]
impl CommandHandler for AllowHandler {
    fn command_name(&self) -> &'static str {
        "allow"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        hooks::execute_allow(
            &self.path,
            &self.package,
            self.note.clone(),
            self.yes,
            Some(executor),
        )
        .await
    }
}

/// Handler for `deny` command.
pub struct DenyHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
}

#[async_trait]
impl CommandHandler for DenyHandler {
    fn command_name(&self) -> &'static str {
        "deny"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, _executor: &CommandExecutor) -> Result<String> {
        hooks::execute_deny(&self.path, &self.package).await
    }
}

/// Handler for `export` command.
pub struct ExportHandler {
    /// Optional shell type override for export format.
    pub shell: Option<String>,
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
}

#[async_trait]
impl CommandHandler for ExportHandler {
    fn command_name(&self) -> &'static str {
        "export"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        export::execute_export(
            self.shell.as_deref(),
            &self.path,
            &self.package,
            Some(executor),
        )
        .await
    }
}

/// Handler for `exec` command.
pub struct ExecHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Command to execute within the environment.
    pub command: String,
    /// Arguments to pass to the command.
    pub args: Vec<String>,
    /// Optional environment name to use for execution.
    pub environment: Option<String>,
}

#[async_trait]
impl CommandHandler for ExecHandler {
    fn command_name(&self) -> &'static str {
        "exec"
    }

    fn should_print_output(&self) -> bool {
        false
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        let request = exec::ExecRequest {
            path: &self.path,
            package: &self.package,
            command: &self.command,
            args: &self.args,
            environment_override: self.environment.as_deref(),
        };
        let exit_code = exec::execute_exec(request, executor).await?;

        if exit_code == 0 {
            Ok(format!("Command exited with code {exit_code}"))
        } else {
            Err(cuenv_core::Error::configuration(format!(
                "Command failed with exit code {exit_code}"
            )))
        }
    }
}

/// Handler for `task` command.
#[allow(clippy::struct_excessive_bools)]
pub struct TaskHandler {
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Optional specific task name to execute.
    pub name: Option<String>,
    /// Labels to filter tasks by.
    pub labels: Vec<String>,
    /// Optional environment name to use for task execution.
    pub environment: Option<String>,
    /// Output format (e.g., "json", "yaml", "table").
    pub format: String,
    /// Optional path to materialize task outputs to.
    pub materialize_outputs: Option<String>,
    /// Whether to display cache paths for tasks.
    pub show_cache_path: bool,
    /// Optional execution backend override (e.g., "dagger").
    pub backend: Option<String>,
    /// Whether to use the TUI interface.
    pub tui: bool,
    /// Whether to run in interactive mode for task selection.
    pub interactive: bool,
    /// Whether to show help for the specified task.
    pub help: bool,
    /// Whether to skip task dependencies.
    pub skip_dependencies: bool,
    /// Dry run mode: export DAG without executing.
    pub dry_run: cuenv_core::DryRun,
    /// Additional arguments to pass to the task.
    pub task_args: Vec<String>,
}

#[async_trait]
impl CommandHandler for TaskHandler {
    fn command_name(&self) -> &'static str {
        "task"
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        // Validate conflicting selection modes before constructing the request
        if !self.labels.is_empty() && self.name.is_some() {
            return Err(cuenv_core::Error::configuration(
                "Cannot specify both a task name and --label",
            ));
        }
        if !self.labels.is_empty() && !self.task_args.is_empty() {
            return Err(cuenv_core::Error::configuration(
                "Task arguments are not supported when selecting tasks by label",
            ));
        }

        // Build request using the builder pattern
        let mut request = match (&self.name, &self.labels, self.interactive) {
            (Some(name), _, _) => {
                task::TaskExecutionRequest::named(&self.path, &self.package, name, executor)
                    .with_args(self.task_args.clone())
            }
            (None, labels, _) if !labels.is_empty() => task::TaskExecutionRequest::labels(
                &self.path,
                &self.package,
                labels.clone(),
                executor,
            ),
            (None, _, true) => {
                task::TaskExecutionRequest::interactive(&self.path, &self.package, executor)
            }
            (None, _, _) => task::TaskExecutionRequest::list(&self.path, &self.package, executor),
        };

        // Apply optional settings
        if let Some(env) = &self.environment {
            request = request.with_environment(env);
        }
        request = request.with_format(&self.format);
        if let Some(path) = &self.materialize_outputs {
            request = request.with_materialize_outputs(path);
        }
        if self.show_cache_path {
            request = request.with_show_cache_path();
        }
        if let Some(backend) = &self.backend {
            request = request.with_backend(backend);
        }
        if self.tui {
            request = request.with_tui();
        }
        if self.help {
            request = request.with_help();
        }
        if self.skip_dependencies {
            request = request.with_skip_dependencies();
        }
        if self.dry_run.is_dry_run() {
            request = request.with_dry_run();
        }

        task::execute(request).await
    }
}

/// Handler for `ci` command.
pub struct CiHandler {
    /// CI command arguments.
    pub args: ci::CiArgs,
}

#[async_trait]
impl CommandHandler for CiHandler {
    fn command_name(&self) -> &'static str {
        "ci"
    }

    fn should_print_output(&self) -> bool {
        false // CI handles its own output
    }

    async fn execute(&self, _executor: &CommandExecutor) -> Result<String> {
        ci::execute_ci(self.args.clone()).await?;
        Ok("CI execution completed".to_string())
    }
}

/// Scope of sync operation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum SyncScope {
    /// Sync single path.
    #[default]
    Path,
    /// Sync all projects in workspace.
    Workspace,
}

/// Handler for `sync` command using provider registry.
pub struct SyncHandler {
    /// Specific provider name (None = sync all providers).
    pub subcommand: Option<String>,
    /// Path to the cuenv project directory.
    pub path: String,
    /// Name of the CUE package to evaluate.
    pub package: String,
    /// Operation mode (write, dry-run, check).
    pub mode: sync::SyncMode,
    /// Scope (single path or entire workspace).
    pub scope: SyncScope,
    /// Show diff for codegen (codegen-specific).
    pub show_diff: bool,
    /// CI provider filter (github, buildkite).
    pub ci_provider: Option<String>,
    /// Tools to force re-resolution for (lock-specific).
    pub update_tools: Option<Vec<String>>,
}

struct SelectedSyncProvidersRequest<'a> {
    registry: &'a sync::SyncRegistry,
    provider_names: &'a [&'a str],
    path: &'a std::path::Path,
    package: &'a str,
    options: &'a sync::SyncOptions,
    scope: &'a SyncScope,
    executor: &'a CommandExecutor,
}

async fn run_selected_sync_providers(request: SelectedSyncProvidersRequest<'_>) -> Result<String> {
    let mut outputs = Vec::new();
    let mut had_error = false;
    let sync_all = request.scope == &SyncScope::Workspace;

    for name in request.provider_names {
        let result = request
            .registry
            .sync_provider(
                name,
                request.path,
                request.package,
                request.options,
                sync_all,
                request.executor,
            )
            .await;

        match result {
            Ok(r) => {
                if !r.output.is_empty() {
                    outputs.push(format!("[{name}]\n{}", r.output));
                }
                had_error |= r.had_error;
            }
            Err(e) => {
                outputs.push(format!("[{name}] Error: {e}"));
                had_error = true;
            }
        }
    }

    let combined = outputs.join("\n\n");
    if had_error {
        Err(cuenv_core::Error::configuration(combined))
    } else if combined.is_empty() {
        Ok("No sync operations performed.".to_string())
    } else {
        Ok(combined)
    }
}

#[async_trait]
impl CommandHandler for SyncHandler {
    fn command_name(&self) -> &'static str {
        "sync"
    }

    async fn execute(&self, executor: &CommandExecutor) -> Result<String> {
        use sync::{SyncOptions, default_registry};

        let registry = default_registry();
        let options = SyncOptions {
            mode: self.mode.clone(),
            show_diff: self.show_diff,
            ci_provider: self.ci_provider.clone(),
            update_tools: self.update_tools.clone(),
        };

        let path = std::path::Path::new(&self.path);
        let sync_all = self.scope == SyncScope::Workspace;
        let project_error = |path: &std::path::Path| {
            cuenv_core::Error::configuration(format!(
                "No cuenv project found at path: {}. Run 'cuenv info' to inspect project layout or use 'cuenv sync -A' to sync all projects.",
                path.display()
            ))
        };

        if self.subcommand.is_none() && !sync_all {
            let target_path = path.canonicalize().map_err(|e| cuenv_core::Error::Io {
                source: e,
                path: Some(path.to_path_buf().into_boxed_path()),
                operation: "canonicalize path".to_string(),
            })?;
            let (is_project, is_root) = {
                let module = executor.get_module(&target_path)?;
                let is_root = module.root == target_path;
                let is_project = module.projects().any(|instance| {
                    // instance.path is the relative path to the project directory
                    module
                        .root
                        .join(&instance.path)
                        .canonicalize()
                        .ok()
                        .is_some_and(|path| path == target_path)
                });
                (is_project, is_root)
            };

            if !is_project {
                if !is_root {
                    return Err(project_error(path));
                }

                return run_selected_sync_providers(SelectedSyncProvidersRequest {
                    registry: &registry,
                    provider_names: &["rules"],
                    path,
                    package: &self.package,
                    options: &options,
                    scope: &self.scope,
                    executor,
                })
                .await;
            }
        }

        if let Some(name) = &self.subcommand {
            // Special-case: `cuenv sync ci` from the module root should behave like `-A`
            // to avoid requiring the root to be a Project. This mirrors CI usage.
            let mut use_workspace = sync_all;
            if !use_workspace && *name == "ci" && self.path == "." {
                tracing::info!("sync ci: switching to workspace mode at module root");
                use_workspace = true;
            }

            let result = registry
                .sync_provider(name, path, &self.package, &options, use_workspace, executor)
                .await?;
            return Ok(result.output);
        }

        run_selected_sync_providers(SelectedSyncProvidersRequest {
            registry: &registry,
            provider_names: &["lock", "codegen", "ci", "rules", "git-hooks"],
            path,
            package: &self.package,
            options: &options,
            scope: &self.scope,
            executor,
        })
        .await
    }
}

/// Handler for `shell init` command (synchronous).
pub struct ShellInitHandler {
    /// Shell type to generate initialization script for.
    pub shell: ShellType,
}

impl ShellInitHandler {
    /// Execute shell init synchronously (doesn't use async trait)
    pub fn execute_sync(&self, executor: &CommandExecutor) {
        let name = "shell init";
        executor.send_event(Event::CommandStart {
            command: name.to_string(),
        });

        let output = hooks::execute_shell_init(self.shell);

        executor.send_event(Event::CommandComplete {
            command: name.to_string(),
            success: true,
            output,
        });
    }
}