syncable_cli/
cli.rs

1use clap::{Parser, Subcommand, ValueEnum};
2use std::path::PathBuf;
3
4#[derive(Parser)]
5#[command(name = "sync-ctl")]
6#[command(version = env!("CARGO_PKG_VERSION"))]
7#[command(about = "Generate Infrastructure as Code from your codebase")]
8#[command(
9    long_about = "A powerful CLI tool that analyzes your codebase and automatically generates optimized Infrastructure as Code configurations including Dockerfiles, Docker Compose files, and Terraform configurations"
10)]
11pub struct Cli {
12    #[command(subcommand)]
13    pub command: Commands,
14
15    /// Path to configuration file
16    #[arg(short, long, global = true, value_name = "FILE")]
17    pub config: Option<PathBuf>,
18
19    /// Enable verbose logging (-v for info, -vv for debug, -vvv for trace)
20    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
21    pub verbose: u8,
22
23    /// Suppress all output except errors
24    #[arg(short, long, global = true)]
25    pub quiet: bool,
26
27    /// Output in JSON format where applicable
28    #[arg(long, global = true)]
29    pub json: bool,
30
31    /// Clear the update check cache and force a new check
32    #[arg(long, global = true)]
33    pub clear_update_cache: bool,
34
35    /// Disable telemetry data collection
36    #[arg(long, global = true)]
37    pub disable_telemetry: bool,
38}
39
40#[derive(Subcommand)]
41pub enum Commands {
42    /// Analyze a project and display detected components
43    Analyze {
44        /// Path to the project directory to analyze
45        #[arg(value_name = "PROJECT_PATH")]
46        path: PathBuf,
47
48        /// Output analysis results in JSON format
49        #[arg(short, long)]
50        json: bool,
51
52        /// Show detailed analysis information (legacy format)
53        #[arg(short, long, conflicts_with = "display")]
54        detailed: bool,
55
56        /// Display format for analysis results
57        #[arg(long, value_enum, default_value = "matrix")]
58        display: Option<DisplayFormat>,
59
60        /// Only analyze specific aspects (languages, frameworks, dependencies)
61        #[arg(long, value_delimiter = ',')]
62        only: Option<Vec<String>>,
63
64        /// Color scheme for terminal output (auto-detect, dark, light)
65        #[arg(long, value_enum, default_value = "auto")]
66        color_scheme: Option<ColorScheme>,
67    },
68
69    /// Generate IaC files for a project
70    Generate {
71        /// Path to the project directory to analyze
72        #[arg(value_name = "PROJECT_PATH")]
73        path: PathBuf,
74
75        /// Output directory for generated files
76        #[arg(short, long, value_name = "OUTPUT_DIR")]
77        output: Option<PathBuf>,
78
79        /// Generate Dockerfile
80        #[arg(long)]
81        dockerfile: bool,
82
83        /// Generate Docker Compose file
84        #[arg(long)]
85        compose: bool,
86
87        /// Generate Terraform configuration
88        #[arg(long)]
89        terraform: bool,
90
91        /// Generate all supported IaC files
92        #[arg(long, conflicts_with_all = ["dockerfile", "compose", "terraform"])]
93        all: bool,
94
95        /// Perform a dry run without creating files
96        #[arg(long)]
97        dry_run: bool,
98
99        /// Overwrite existing files
100        #[arg(long)]
101        force: bool,
102    },
103
104    /// Validate existing IaC files against best practices
105    Validate {
106        /// Path to the directory containing IaC files
107        #[arg(value_name = "PATH")]
108        path: PathBuf,
109
110        /// Types of files to validate
111        #[arg(long, value_delimiter = ',')]
112        types: Option<Vec<String>>,
113
114        /// Fix issues automatically where possible
115        #[arg(long)]
116        fix: bool,
117    },
118
119    /// Show supported languages and frameworks
120    Support {
121        /// Show only languages
122        #[arg(long)]
123        languages: bool,
124
125        /// Show only frameworks
126        #[arg(long)]
127        frameworks: bool,
128
129        /// Show detailed information
130        #[arg(short, long)]
131        detailed: bool,
132    },
133
134    /// Analyze project dependencies in detail
135    Dependencies {
136        /// Path to the project directory to analyze
137        #[arg(value_name = "PROJECT_PATH")]
138        path: PathBuf,
139
140        /// Show license information for dependencies
141        #[arg(long)]
142        licenses: bool,
143
144        /// Check for known vulnerabilities
145        #[arg(long)]
146        vulnerabilities: bool,
147
148        /// Show only production dependencies
149        #[arg(long, conflicts_with = "dev_only")]
150        prod_only: bool,
151
152        /// Show only development dependencies
153        #[arg(long, conflicts_with = "prod_only")]
154        dev_only: bool,
155
156        /// Output format
157        #[arg(long, value_enum, default_value = "table")]
158        format: OutputFormat,
159    },
160
161    /// Check dependencies for known vulnerabilities
162    Vulnerabilities {
163        /// Check vulnerabilities in a specific path
164        #[arg(default_value = ".")]
165        path: PathBuf,
166
167        /// Show only vulnerabilities with severity >= threshold
168        #[arg(long, value_enum)]
169        severity: Option<SeverityThreshold>,
170
171        /// Output format
172        #[arg(long, value_enum, default_value = "table")]
173        format: OutputFormat,
174
175        /// Export report to file
176        #[arg(long)]
177        output: Option<PathBuf>,
178    },
179
180    /// Perform comprehensive security analysis
181    Security {
182        /// Path to the project directory to analyze
183        #[arg(value_name = "PROJECT_PATH", default_value = ".")]
184        path: PathBuf,
185
186        /// Security scan mode (lightning, fast, balanced, thorough, paranoid)
187        #[arg(long, value_enum, default_value = "thorough")]
188        mode: SecurityScanMode,
189
190        /// Include low severity findings
191        #[arg(long)]
192        include_low: bool,
193
194        /// Skip secrets detection
195        #[arg(long)]
196        no_secrets: bool,
197
198        /// Skip code pattern analysis
199        #[arg(long)]
200        no_code_patterns: bool,
201
202        /// Skip infrastructure analysis (not implemented yet)
203        #[arg(long, hide = true)]
204        no_infrastructure: bool,
205
206        /// Skip compliance checks (not implemented yet)
207        #[arg(long, hide = true)]
208        no_compliance: bool,
209
210        /// Compliance frameworks to check (not implemented yet)
211        #[arg(long, value_delimiter = ',', hide = true)]
212        frameworks: Vec<String>,
213
214        /// Output format
215        #[arg(long, value_enum, default_value = "table")]
216        format: OutputFormat,
217
218        /// Export report to file
219        #[arg(long)]
220        output: Option<PathBuf>,
221
222        /// Exit with error code on security findings
223        #[arg(long)]
224        fail_on_findings: bool,
225    },
226
227    /// Manage vulnerability scanning tools
228    Tools {
229        #[command(subcommand)]
230        command: ToolsCommand,
231    },
232
233    /// Analyze Kubernetes manifests for resource optimization opportunities
234    Optimize {
235        /// Path to Kubernetes manifests (file or directory)
236        #[arg(value_name = "PATH", default_value = ".")]
237        path: PathBuf,
238
239        /// Connect to a live Kubernetes cluster for metrics-based recommendations
240        /// Uses current kubeconfig context, or specify a context name
241        #[arg(long, short = 'k', value_name = "CONTEXT", default_missing_value = "current", num_args = 0..=1)]
242        cluster: Option<String>,
243
244        /// Prometheus URL for historical metrics (e.g., http://localhost:9090)
245        #[arg(long, value_name = "URL")]
246        prometheus: Option<String>,
247
248        /// Target namespace(s) for cluster analysis (comma-separated, or * for all)
249        #[arg(long, short = 'n', value_name = "NAMESPACE")]
250        namespace: Option<String>,
251
252        /// Analysis period for historical metrics (e.g., 7d, 30d)
253        #[arg(long, short = 'p', default_value = "7d")]
254        period: String,
255
256        /// Minimum severity to report (critical, warning, info)
257        #[arg(long, short = 's')]
258        severity: Option<String>,
259
260        /// Minimum waste percentage threshold (0-100)
261        #[arg(long, short = 't')]
262        threshold: Option<u8>,
263
264        /// Safety margin percentage for recommendations (default: 20)
265        #[arg(long)]
266        safety_margin: Option<u8>,
267
268        /// Include info-level suggestions
269        #[arg(long)]
270        include_info: bool,
271
272        /// Include system namespaces (kube-system, etc.)
273        #[arg(long)]
274        include_system: bool,
275
276        /// Output format (table, json, yaml)
277        #[arg(long, value_enum, default_value = "table")]
278        format: OutputFormat,
279
280        /// Write report to file
281        #[arg(long, short = 'o')]
282        output: Option<PathBuf>,
283
284        /// Generate fix suggestions
285        #[arg(long)]
286        fix: bool,
287
288        /// Apply fixes to manifest files (requires --fix or --full with live cluster)
289        #[arg(long, requires = "fix")]
290        apply: bool,
291
292        /// Preview changes without applying (dry-run mode)
293        #[arg(long)]
294        dry_run: bool,
295
296        /// Backup directory for original files before applying fixes
297        #[arg(long, value_name = "DIR")]
298        backup_dir: Option<PathBuf>,
299
300        /// Minimum confidence threshold for auto-apply (0-100, default: 70)
301        #[arg(long, default_value = "70")]
302        min_confidence: u8,
303
304        /// Cloud provider for cost estimation (aws, gcp, azure, onprem)
305        #[arg(long, value_name = "PROVIDER")]
306        cloud_provider: Option<String>,
307
308        /// Region for cloud pricing (e.g., us-east-1, us-central1)
309        #[arg(long, value_name = "REGION", default_value = "us-east-1")]
310        region: String,
311
312        /// Run comprehensive analysis (includes kubelint security checks and helmlint validation)
313        #[arg(long, short = 'f')]
314        full: bool,
315    },
316
317    /// Start an interactive AI chat session to analyze and understand your project
318    Chat {
319        /// Path to the project directory (default: current directory)
320        #[arg(value_name = "PROJECT_PATH", default_value = ".")]
321        path: PathBuf,
322
323        /// LLM provider to use (uses saved preference by default)
324        #[arg(long, value_enum, default_value = "auto")]
325        provider: ChatProvider,
326
327        /// Model to use (e.g., gpt-4o, claude-3-5-sonnet-latest, llama3.2)
328        #[arg(long)]
329        model: Option<String>,
330
331        /// Run a single query instead of interactive mode
332        #[arg(long)]
333        query: Option<String>,
334
335        /// Resume a previous session (accepts: "latest", session number, or UUID)
336        #[arg(long, short = 'r')]
337        resume: Option<String>,
338
339        /// List available sessions for this project and exit
340        #[arg(long)]
341        list_sessions: bool,
342    },
343
344    /// Authenticate with the Syncable platform
345    Auth {
346        #[command(subcommand)]
347        command: AuthCommand,
348    },
349
350    /// Manage Syncable projects
351    Project {
352        #[command(subcommand)]
353        command: ProjectCommand,
354    },
355
356    /// Manage Syncable organizations
357    Org {
358        #[command(subcommand)]
359        command: OrgCommand,
360    },
361
362    /// Manage environments within a project
363    Env {
364        #[command(subcommand)]
365        command: EnvCommand,
366    },
367
368    /// Deploy services to the Syncable platform (launches wizard by default)
369    Deploy {
370        /// Path to the project directory (default: current directory)
371        #[arg(value_name = "PROJECT_PATH", default_value = ".")]
372        path: PathBuf,
373
374        #[command(subcommand)]
375        command: Option<DeployCommand>,
376    },
377}
378
379#[derive(Subcommand)]
380pub enum ToolsCommand {
381    /// Check which vulnerability scanning tools are installed
382    Status {
383        /// Output format
384        #[arg(long, value_enum, default_value = "table")]
385        format: OutputFormat,
386
387        /// Check tools for specific languages only
388        #[arg(long, value_delimiter = ',')]
389        languages: Option<Vec<String>>,
390    },
391
392    /// Install missing vulnerability scanning tools
393    Install {
394        /// Install tools for specific languages only
395        #[arg(long, value_delimiter = ',')]
396        languages: Option<Vec<String>>,
397
398        /// Also install OWASP Dependency Check (large download)
399        #[arg(long)]
400        include_owasp: bool,
401
402        /// Perform a dry run to show what would be installed
403        #[arg(long)]
404        dry_run: bool,
405
406        /// Skip confirmation prompts
407        #[arg(short, long)]
408        yes: bool,
409    },
410
411    /// Verify that installed tools are working correctly
412    Verify {
413        /// Test tools for specific languages only
414        #[arg(long, value_delimiter = ',')]
415        languages: Option<Vec<String>>,
416
417        /// Show detailed verification output
418        #[arg(short, long)]
419        detailed: bool,
420    },
421
422    /// Show tool installation guides for manual setup
423    Guide {
424        /// Show guide for specific languages only
425        #[arg(long, value_delimiter = ',')]
426        languages: Option<Vec<String>>,
427
428        /// Show platform-specific instructions
429        #[arg(long)]
430        platform: Option<String>,
431    },
432}
433
434/// Authentication subcommands for the Syncable platform
435#[derive(Subcommand)]
436pub enum AuthCommand {
437    /// Log in to Syncable (opens browser for authentication)
438    Login {
439        /// Don't open browser automatically
440        #[arg(long)]
441        no_browser: bool,
442    },
443
444    /// Log out and clear stored credentials
445    Logout,
446
447    /// Show current authentication status
448    Status,
449
450    /// Print current access token (for scripting)
451    Token {
452        /// Print raw token without formatting
453        #[arg(long)]
454        raw: bool,
455    },
456}
457
458/// Project management subcommands
459#[derive(Subcommand)]
460pub enum ProjectCommand {
461    /// List projects in the current organization
462    List {
463        /// Organization ID to list projects from (uses current org if not specified)
464        #[arg(long)]
465        org_id: Option<String>,
466
467        /// Output format
468        #[arg(long, value_enum, default_value = "table")]
469        format: OutputFormat,
470    },
471
472    /// Select a project to work with
473    Select {
474        /// Project ID to select
475        id: String,
476    },
477
478    /// Show current organization and project context
479    Current,
480
481    /// Show details of a project
482    Info {
483        /// Project ID (uses current project if not specified)
484        id: Option<String>,
485    },
486}
487
488/// Organization management subcommands
489#[derive(Subcommand)]
490pub enum OrgCommand {
491    /// List organizations you belong to
492    List {
493        /// Output format
494        #[arg(long, value_enum, default_value = "table")]
495        format: OutputFormat,
496    },
497
498    /// Select an organization to work with
499    Select {
500        /// Organization ID to select
501        id: String,
502    },
503}
504
505/// Environment management subcommands
506#[derive(Subcommand)]
507pub enum EnvCommand {
508    /// List environments in the current project
509    List {
510        /// Output format
511        #[arg(long, value_enum, default_value = "table")]
512        format: OutputFormat,
513    },
514
515    /// Select an environment to work with
516    Select {
517        /// Environment ID to select
518        id: String,
519    },
520}
521
522/// Deployment subcommands
523#[derive(Subcommand)]
524pub enum DeployCommand {
525    /// Launch interactive deployment wizard
526    Wizard {
527        /// Path to the project directory (default: current directory)
528        #[arg(value_name = "PROJECT_PATH", default_value = ".")]
529        path: PathBuf,
530    },
531
532    /// Create a new environment for the current project
533    NewEnv,
534
535    /// Check deployment status
536    Status {
537        /// The deployment task ID (from deploy command output)
538        task_id: String,
539
540        /// Watch for status updates (poll until complete)
541        #[arg(short, long)]
542        watch: bool,
543    },
544}
545
546#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
547pub enum OutputFormat {
548    Table,
549    Json,
550}
551
552#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
553pub enum DisplayFormat {
554    /// Compact matrix/dashboard view (modern, easy to scan)
555    Matrix,
556    /// Detailed vertical view (legacy format with all details)
557    Detailed,
558    /// Brief summary only
559    Summary,
560}
561
562#[derive(Clone, Copy, Debug, ValueEnum)]
563pub enum ColorScheme {
564    /// Auto-detect terminal background (default)
565    Auto,
566    /// Dark background terminal colors
567    Dark,
568    /// Light background terminal colors
569    Light,
570}
571
572#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
573pub enum SeverityThreshold {
574    Low,
575    Medium,
576    High,
577    Critical,
578}
579
580#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
581pub enum SecurityScanMode {
582    /// Lightning fast scan - critical files only (.env, configs)
583    Lightning,
584    /// Fast scan - smart sampling with priority patterns
585    Fast,
586    /// Balanced scan - good coverage with performance optimizations (recommended)
587    Balanced,
588    /// Thorough scan - comprehensive analysis of all files
589    Thorough,
590    /// Paranoid scan - most comprehensive including low-severity findings
591    Paranoid,
592}
593
594#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
595pub enum ChatProvider {
596    /// OpenAI (GPT-4o, GPT-4, etc.)
597    Openai,
598    /// Anthropic (Claude 3)
599    Anthropic,
600    /// AWS Bedrock (Claude via AWS)
601    Bedrock,
602    /// Ollama (local LLM, no API key needed)
603    Ollama,
604    /// Use saved default from config file
605    #[default]
606    Auto,
607}
608
609impl Cli {
610    /// Initialize logging based on verbosity level
611    pub fn init_logging(&self) {
612        if self.quiet {
613            return;
614        }
615
616        let level = match self.verbose {
617            0 => log::LevelFilter::Warn,
618            1 => log::LevelFilter::Info,
619            2 => log::LevelFilter::Debug,
620            _ => log::LevelFilter::Trace,
621        };
622
623        env_logger::Builder::from_default_env()
624            .filter_level(level)
625            .init();
626    }
627}