dfxmon-cli 0.1.4

CLI tool for interacting with dfxmon canister on the Internet Computer
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
use anyhow::{Context, Result};
use candid::{CandidType, Deserialize, Principal};
use clap::{Parser, Subcommand};
use ic_agent::Agent;
use ic_utils::call::SyncCall;
use ic_utils::canister::Canister;
use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use serde::Serialize;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;
use tracing::{debug, error, info, warn};

mod constants;
use constants::{get_default_canister_id, resolve_network_url};

#[derive(Parser)]
#[command(name = "dfxmon")]
#[command(about = "CLI tool for interacting with dfxmon canister on the Internet Computer")]
#[command(version)]
struct Cli {
    /// dfxmon canister ID
    #[arg(long)]
    canister_id: Option<String>,

    /// IC network URL (local or mainnet). Use 'local' for localhost:4943, 'mainnet' for IC mainnet
    #[arg(long, default_value = "local")]
    network: String,

    /// Enable verbose logging
    #[arg(short, long)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a new project in dfxmon
    Create {
        /// Project name
        name: String,
        /// Path to dfx.json file
        #[arg(long, default_value = "./dfx.json")]
        dfx_json: PathBuf,
        /// Enable auto-deployment
        #[arg(long)]
        auto_deploy: bool,
        /// Debounce delay in milliseconds
        #[arg(long, default_value = "1000")]
        debounce_ms: u64,
    },
    /// Start watching files and send changes to dfxmon canister
    Watch {
        /// Project name
        project: String,
        /// Watch specific canister types: all, backend, frontend, or canister name
        #[arg(long, default_value = "all")]
        filter: String,
    },
    /// Deploy a project or specific canister
    Deploy {
        /// Project name
        project: String,
        /// Specific canister to deploy (optional)
        #[arg(long)]
        canister: Option<String>,
        /// Force deployment even if no changes detected
        #[arg(long)]
        force: bool,
    },
    /// Get project status
    Status {
        /// Project name
        project: String,
    },
    /// List all projects
    List,
    /// Get deployment history
    History {
        /// Project name (optional, shows all if not specified)
        project: Option<String>,
        /// Limit number of results
        #[arg(long, default_value = "10")]
        limit: u32,
    },
    /// Get dfxmon canister statistics
    Stats,
    /// Health check of dfxmon canister
    Health,
}

#[derive(CandidType, Serialize, Deserialize, Debug)]
struct CreateProjectRequest {
    name: String,
    dfx_json_content: String,
    auto_deploy: bool,
    debounce_ms: Option<u64>,
    ignore_patterns: Option<Vec<String>>,
}

#[derive(CandidType, Serialize, Deserialize, Debug)]
struct WatchRequest {
    project_name: String,
    canister_filter: Option<String>,
}

#[derive(CandidType, Serialize, Deserialize, Debug)]
struct DeployRequest {
    project_name: String,
    canister_name: Option<String>,
    force: bool,
}

#[derive(CandidType, Serialize, Deserialize, Debug)]
struct FileChangeEvent {
    file_path: String,
    change_type: ChangeType,
    timestamp: u64,
    project_name: String,
}

#[derive(CandidType, Serialize, Deserialize, Debug)]
enum ChangeType {
    Created,
    Modified,
    Deleted,
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize tracing
    let log_level = if cli.verbose { "debug" } else { "info" };
    tracing_subscriber::fmt()
        .with_env_filter(format!("dfxmon={}", log_level))
        .init();

    info!("Starting dfxmon CLI v{}", env!("CARGO_PKG_VERSION"));

    // Resolve network URL
    let network_url = resolve_network_url(&cli.network);
    info!("Connecting to network: {}", network_url);

    // Get canister ID with automatic network detection
    let canister_id = cli.canister_id
        .or_else(|| std::env::var("DFXMON_CANISTER_ID").ok())
        .unwrap_or_else(|| {
            let default_id = get_default_canister_id(&network_url);
            info!("Using default dfxmon canister ID for network {}: {}", network_url, default_id);
            debug!("Network URL: {}, Selected canister ID: {}", network_url, default_id);
            default_id.to_string()
        });

    let canister_principal =
        Principal::from_text(&canister_id).context("Invalid canister ID format")?;

    // Create IC agent
    let agent = Agent::builder()
        .with_url(&network_url)
        .build()
        .context("Failed to create IC agent")?;

    // For local development, fetch root key
    if network_url.contains("localhost") || network_url.contains("127.0.0.1") {
        agent
            .fetch_root_key()
            .await
            .context("Failed to fetch root key for local development")?;
    }

    let canister = Canister::builder()
        .with_agent(&agent)
        .with_canister_id(canister_principal)
        .build()
        .context("Failed to create canister interface")?;

    match cli.command {
        Commands::Create {
            name,
            dfx_json,
            auto_deploy,
            debounce_ms,
        } => {
            create_project(&canister, name, dfx_json, auto_deploy, debounce_ms).await?;
        }
        Commands::Watch { project, filter } => {
            start_watching(&canister, project, filter).await?;
        }
        Commands::Deploy {
            project,
            canister: canister_name,
            force,
        } => {
            deploy_project(&canister, project, canister_name, force).await?;
        }
        Commands::Status { project } => {
            get_project_status(&canister, project).await?;
        }
        Commands::List => {
            list_projects(&canister).await?;
        }
        Commands::History { project, limit } => {
            get_deployment_history(&canister, project, limit).await?;
        }
        Commands::Stats => {
            get_statistics(&canister).await?;
        }
        Commands::Health => {
            health_check(&canister).await?;
        }
    }

    Ok(())
}

async fn create_project(
    canister: &Canister<'_>,
    name: String,
    dfx_json_path: PathBuf,
    auto_deploy: bool,
    debounce_ms: u64,
) -> Result<()> {
    info!("Creating project: {}", name);

    // Read dfx.json content
    let dfx_json_content = fs::read_to_string(&dfx_json_path)
        .with_context(|| format!("Failed to read dfx.json from {}", dfx_json_path.display()))?;

    let request = CreateProjectRequest {
        name: name.clone(),
        dfx_json_content,
        auto_deploy,
        debounce_ms: Some(debounce_ms),
        ignore_patterns: None,
    };

    let response: (Result<String, String>,) = canister
        .update("create_project")
        .with_arg(request)
        .build()
        .call_and_wait()
        .await
        .context("Failed to call create_project")?;

    match response.0 {
        Ok(msg) => {
            info!("✅ Project created successfully: {}", msg);
        }
        Err(e) => {
            error!("❌ Failed to create project: {}", e);
            return Err(anyhow::anyhow!("{}", e));
        }
    }

    Ok(())
}

async fn start_watching(
    canister: &Canister<'_>,
    project_name: String,
    filter: String,
) -> Result<()> {
    info!("Starting file watcher for project: {}", project_name);

    // Start watching on the canister
    let watch_request = WatchRequest {
        project_name: project_name.clone(),
        canister_filter: if filter == "all" { None } else { Some(filter) },
    };

    let response: (Result<String, String>,) = canister
        .update("start_watching")
        .with_arg(watch_request)
        .build()
        .call_and_wait()
        .await
        .context("Failed to call start_watching")?;

    match response.0 {
        Ok(msg) => {
            info!("✅ Started watching: {}", msg);
        }
        Err(e) => {
            error!("❌ Failed to start watching: {}", e);
            return Err(anyhow::anyhow!("{}", e));
        }
    }

    // Start local file watcher
    start_local_file_watcher(canister, project_name).await?;

    Ok(())
}

async fn start_local_file_watcher(canister: &Canister<'_>, project_name: String) -> Result<()> {
    info!("🔍 Starting local file watcher...");

    let (tx, rx) = channel();
    let mut watcher = RecommendedWatcher::new(
        move |res: Result<Event, notify::Error>| {
            if let Err(e) = tx.send(res) {
                error!("Failed to send file event: {}", e);
            }
        },
        notify::Config::default(),
    )?;

    // Watch current directory recursively
    watcher
        .watch(Path::new("."), RecursiveMode::Recursive)
        .context("Failed to start watching current directory")?;

    info!("👀 Watching current directory for file changes...");

    // Process file events
    loop {
        match rx.recv() {
            Ok(Ok(event)) => {
                if let Err(e) = handle_file_event(canister, &project_name, event).await {
                    error!("Error handling file event: {}", e);
                }
            }
            Ok(Err(e)) => {
                error!("File watcher error: {}", e);
            }
            Err(e) => {
                error!("Channel error: {}", e);
                break;
            }
        }
    }

    Ok(())
}

async fn handle_file_event(
    canister: &Canister<'_>,
    project_name: &str,
    event: Event,
) -> Result<()> {
    // Filter out events we don't care about
    match event.kind {
        EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) => {}
        _ => return Ok(()),
    }

    for path in event.paths {
        if should_process_path(&path) {
            let change_type = match event.kind {
                EventKind::Create(_) => ChangeType::Created,
                EventKind::Modify(_) => ChangeType::Modified,
                EventKind::Remove(_) => ChangeType::Deleted,
                _ => continue,
            };

            let file_event = FileChangeEvent {
                file_path: path.to_string_lossy().to_string(),
                change_type,
                timestamp: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos() as u64,
                project_name: project_name.to_string(),
            };

            debug!("📝 File change: {:?}", file_event);

            // Send to canister
            let response: (Result<String, String>,) = canister
                .update("notify_file_change")
                .with_arg(file_event)
                .build()
                .call_and_wait()
                .await
                .context("Failed to notify file change")?;

            match response.0 {
                Ok(msg) => {
                    debug!("File change processed: {}", msg);
                }
                Err(e) => {
                    warn!("Failed to process file change: {}", e);
                }
            }
        }
    }

    Ok(())
}

fn should_process_path(path: &std::path::Path) -> bool {
    let path_str = path.to_string_lossy();

    // Ignore common directories and files
    let ignore_patterns = [
        ".dfx/",
        "target/",
        "node_modules/",
        ".git/",
        "dist/",
        "build/",
        ".DS_Store",
    ];

    for pattern in &ignore_patterns {
        if path_str.contains(pattern) {
            return false;
        }
    }

    // Check for specific file patterns
    if path_str.ends_with(".log")
        || path_str.ends_with(".tmp")
        || path_str.ends_with(".swp")
        || path_str.ends_with("~")
    {
        return false;
    }

    // Check file extensions we care about
    if let Some(extension) = path.extension() {
        matches!(
            extension.to_str(),
            Some("rs")
                | Some("mo")
                | Some("js")
                | Some("ts")
                | Some("jsx")
                | Some("tsx")
                | Some("html")
                | Some("css")
                | Some("scss")
                | Some("json")
                | Some("toml")
                | Some("did")
                | Some("md")
        )
    } else {
        // Files without extensions might be important
        true
    }
}

async fn deploy_project(
    canister: &Canister<'_>,
    project_name: String,
    canister_name: Option<String>,
    force: bool,
) -> Result<()> {
    info!("Deploying project: {}", project_name);

    let request = DeployRequest {
        project_name,
        canister_name,
        force,
    };

    let response: (Result<String, String>,) = canister
        .update("deploy")
        .with_arg(request)
        .build()
        .call_and_wait()
        .await
        .context("Failed to call deploy")?;

    match response.0 {
        Ok(msg) => {
            info!("✅ Deployment successful: {}", msg);
        }
        Err(e) => {
            error!("❌ Deployment failed: {}", e);
            return Err(anyhow::anyhow!("{}", e));
        }
    }

    Ok(())
}

async fn get_project_status(canister: &Canister<'_>, project_name: String) -> Result<()> {
    info!("Getting status for project: {}", project_name);

    let response: (Result<String, String>,) = canister
        .query("get_project_status")
        .with_arg(project_name)
        .build()
        .call()
        .await
        .context("Failed to call get_project_status")?;

    match response.0 {
        Ok(status_json) => {
            println!("📊 Project Status:");
            // Parse the JSON string and pretty print it
            match serde_json::from_str::<serde_json::Value>(&status_json) {
                Ok(status) => println!("{}", serde_json::to_string_pretty(&status)?),
                Err(_) => println!("{}", status_json), // Fallback to raw string
            }
        }
        Err(e) => {
            error!("❌ Failed to get project status: {}", e);
            return Err(anyhow::anyhow!("{}", e));
        }
    }

    Ok(())
}

async fn list_projects(canister: &Canister<'_>) -> Result<()> {
    info!("Listing all projects...");

    let projects: (Vec<String>,) = canister
        .query("list_projects")
        .build()
        .call()
        .await
        .context("Failed to call list_projects")?;

    println!("📋 Projects:");
    for project in projects.0 {
        println!("  - {}", project);
    }

    Ok(())
}

async fn get_deployment_history(
    canister: &Canister<'_>,
    project: Option<String>,
    limit: u32,
) -> Result<()> {
    info!("Getting deployment history...");

    let history: (String,) = canister
        .query("get_deployment_history")
        .with_arg((project, Some(limit)))
        .build()
        .call()
        .await
        .context("Failed to call get_deployment_history")?;

    println!("📈 Deployment History:");
    // Parse the JSON string and pretty print it
    match serde_json::from_str::<serde_json::Value>(&history.0) {
        Ok(parsed) => println!("{}", serde_json::to_string_pretty(&parsed)?),
        Err(_) => println!("{}", history.0), // Fallback to raw string
    }

    Ok(())
}

async fn get_statistics(canister: &Canister<'_>) -> Result<()> {
    info!("Getting dfxmon statistics...");

    let stats: (Vec<(String, u32)>,) = canister
        .query("get_statistics")
        .build()
        .call()
        .await
        .context("Failed to call get_statistics")?;

    println!("📊 dfxmon Statistics:");
    for (key, value) in stats.0 {
        println!("  {}: {}", key, value);
    }

    Ok(())
}

async fn health_check(canister: &Canister<'_>) -> Result<()> {
    info!("Performing health check...");

    let health: (String,) = canister
        .query("health_check")
        .build()
        .call()
        .await
        .context("Failed to call health_check")?;

    println!("🏥 Health Check: {}", health.0);

    Ok(())
}

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

    #[test]
    fn test_should_process_path_rust_files() {
        assert!(should_process_path(Path::new("src/lib.rs")));
        assert!(should_process_path(Path::new("src/main.rs")));
        assert!(should_process_path(Path::new("backend/src/lib.rs")));
    }

    #[test]
    fn test_should_process_path_motoko_files() {
        assert!(should_process_path(Path::new("src/main.mo")));
        assert!(should_process_path(Path::new("backend/main.mo")));
    }

    #[test]
    fn test_should_process_path_frontend_files() {
        assert!(should_process_path(Path::new("src/index.js")));
        assert!(should_process_path(Path::new("src/App.tsx")));
        assert!(should_process_path(Path::new("src/style.css")));
        assert!(should_process_path(Path::new("public/index.html")));
    }

    #[test]
    fn test_should_process_path_config_files() {
        assert!(should_process_path(Path::new("dfx.json")));
        assert!(should_process_path(Path::new("Cargo.toml")));
        assert!(should_process_path(Path::new("package.json")));
    }

    #[test]
    fn test_should_ignore_build_directories() {
        assert!(!should_process_path(Path::new(
            ".dfx/local/canister_ids.json"
        )));
        assert!(!should_process_path(Path::new(
            "target/debug/deps/lib.rlib"
        )));
        assert!(!should_process_path(Path::new(
            "node_modules/react/index.js"
        )));
        assert!(!should_process_path(Path::new("dist/bundle.js")));
        assert!(!should_process_path(Path::new("build/static/js/main.js")));
    }

    #[test]
    fn test_should_ignore_system_files() {
        assert!(!should_process_path(Path::new(".DS_Store")));
        assert!(!should_process_path(Path::new("file.log")));
        assert!(!should_process_path(Path::new("temp.tmp")));
        assert!(!should_process_path(Path::new("file.swp")));
        assert!(!should_process_path(Path::new("backup~")));
    }

    #[test]
    fn test_should_ignore_git_directory() {
        assert!(!should_process_path(Path::new(".git/config")));
        assert!(!should_process_path(Path::new(".git/hooks/pre-commit")));
    }
}