ui-cli 0.3.4

A CLI to add components to your app.
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
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;

use serde::{Deserialize, Serialize};
use toml_edit::{DocumentMut, Item, Value};

use crate::command_init::crates::{Crate, INIT_CRATES};
use crate::command_init::workspace_utils::{WorkspaceInfo, analyze_workspace, check_leptos_dependency};
use crate::shared::cli_error::{CliError, CliResult};
use crate::shared::task_spinner::TaskSpinner;

///
/// UiConfig - Minimal configuration stored in ui_config.toml
/// Workspace detection is done dynamically via analyze_workspace()
///
#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd)]
pub struct UiConfig {
    pub base_color: String,
    pub base_path_components: String,
    pub tailwind_input_file: String,
}

impl UiConfig {
    pub fn try_reading_ui_config(toml_path: &str) -> CliResult<UiConfig> {
        if !Path::new(toml_path).exists() {
            return Err(CliError::project_not_initialized());
        }
        let contents = fs::read_to_string(toml_path)?;
        let ui_config: UiConfig = toml::from_str(&contents)?;
        Ok(ui_config)
    }
}

impl Default for UiConfig {
    fn default() -> Self {
        // Detect workspace and set appropriate component path
        let base_path_components = match analyze_workspace() {
            Ok(info) => info.components_base_path,
            Err(_) => "src/components".to_string(),
        };

        UiConfig {
            base_color: "neutral".to_string(),
            base_path_components,
            tailwind_input_file: "style/tailwind.css".to_string(),
        }
    }
}

/* ========================================================== */
/*                     ✨ FUNCTIONS ✨                        */
/* ========================================================== */

pub async fn add_init_crates() -> CliResult<()> {
    let workspace_info = analyze_workspace().ok();
    let workspace_crates = get_workspace_dependencies(&workspace_info);

    for my_crate in INIT_CRATES {
        if my_crate.name == "leptos" && check_leptos_dependency()? {
            continue;
        }

        let spinner = TaskSpinner::new(&format!("Adding {} crate...", my_crate.name));

        if add_crate_to_workspace(&my_crate, &workspace_info, &workspace_crates)? {
            spinner.finish_success(&format!("{} (workspace) added.", my_crate.name));
            continue;
        }

        add_crate_with_cargo(&my_crate, &workspace_info)?;
        spinner.finish_success(&format!("{} added.", my_crate.name));
    }
    Ok(())
}

fn add_crate_to_workspace(
    my_crate: &Crate,
    workspace_info: &Option<WorkspaceInfo>,
    workspace_crates: &HashSet<String>,
) -> CliResult<bool> {
    let Some(info) = workspace_info.as_ref().filter(|i| i.is_workspace) else {
        return Ok(false);
    };
    let Some(workspace_root) = &info.workspace_root else {
        return Ok(false);
    };
    let Some(member_path) = &info.target_crate_path else {
        return Ok(false);
    };

    let root_cargo_toml = workspace_root.join("Cargo.toml");
    let member_cargo_toml = member_path.join("Cargo.toml");

    if workspace_crates.contains(my_crate.name) {
        add_workspace_ref_to_member(&member_cargo_toml, my_crate.name)?;
        return Ok(true);
    }

    if !has_workspace_dependencies_section(workspace_info) {
        return Ok(false);
    }

    let version = fetch_latest_version(my_crate.name)?;
    add_to_workspace_dependencies(&root_cargo_toml, my_crate.name, &version, my_crate.features)?;
    add_workspace_ref_to_member(&member_cargo_toml, my_crate.name)?;
    Ok(true)
}

fn add_crate_with_cargo(my_crate: &Crate, workspace_info: &Option<WorkspaceInfo>) -> CliResult<()> {
    let mut args = vec!["add".to_owned(), my_crate.name.to_owned()];

    if let Some(info) = workspace_info.as_ref().filter(|i| i.is_workspace)
        && let Some(crate_name) = &info.target_crate
    {
        args.extend(["--package".to_owned(), crate_name.clone()]);
    }

    if let Some(features) = my_crate.features.filter(|f| !f.is_empty()) {
        args.extend(["--features".to_owned(), features.join(",")]);
    }

    let output = Command::new("cargo").args(&args).output().map_err(|e| {
        CliError::cargo_operation(&format!("Failed to execute cargo add {}: {e}", my_crate.name))
    })?;

    if !output.status.success() {
        return Err(CliError::cargo_operation(&format!(
            "Failed to add crate '{}': {}",
            my_crate.name,
            String::from_utf8_lossy(&output.stderr)
        )));
    }
    Ok(())
}

/* ========================================================== */
/*                     ✨ HELPERS ✨                          */
/* ========================================================== */

fn parse_workspace_cargo_toml(workspace_info: &Option<WorkspaceInfo>) -> Option<DocumentMut> {
    let info = workspace_info.as_ref().filter(|i| i.is_workspace)?;
    let root = info.workspace_root.as_ref()?;
    let contents = fs::read_to_string(root.join("Cargo.toml")).ok()?;
    contents.parse().ok()
}

fn has_workspace_dependencies_section(workspace_info: &Option<WorkspaceInfo>) -> bool {
    parse_workspace_cargo_toml(workspace_info)
        .and_then(|doc| doc.get("workspace")?.get("dependencies").cloned())
        .is_some()
}

fn get_workspace_dependencies(workspace_info: &Option<WorkspaceInfo>) -> HashSet<String> {
    parse_workspace_cargo_toml(workspace_info)
        .and_then(|doc| {
            doc.get("workspace")?
                .get("dependencies")?
                .as_table()
                .map(|t| t.iter().map(|(k, _)| k.to_string()).collect())
        })
        .unwrap_or_default()
}

fn add_workspace_ref_to_member(cargo_toml_path: &Path, dep: &str) -> CliResult<()> {
    let contents = fs::read_to_string(cargo_toml_path)?;
    let mut doc: DocumentMut = contents
        .parse()
        .map_err(|e| CliError::cargo_operation(&format!("Failed to parse member Cargo.toml: {e}")))?;

    let deps = doc.entry("dependencies").or_insert(Item::Table(toml_edit::Table::new()));

    let deps_table =
        deps.as_table_mut().ok_or_else(|| CliError::cargo_operation("[dependencies] is not a table"))?;

    if deps_table.contains_key(dep) {
        return Ok(());
    }

    let mut dep_table = toml_edit::Table::new();
    dep_table.set_dotted(true);
    dep_table.insert("workspace", Item::Value(Value::Boolean(toml_edit::Formatted::new(true))));
    deps_table.insert(dep, Item::Table(dep_table));

    fs::write(cargo_toml_path, doc.to_string())?;
    Ok(())
}

fn add_to_workspace_dependencies(
    cargo_toml_path: &Path,
    dep: &str,
    version: &str,
    features: Option<&[&str]>,
) -> CliResult<()> {
    let contents = fs::read_to_string(cargo_toml_path)?;
    let mut doc: DocumentMut = contents
        .parse()
        .map_err(|e| CliError::cargo_operation(&format!("Failed to parse Cargo.toml: {e}")))?;

    let workspace = doc.entry("workspace").or_insert(Item::Table(toml_edit::Table::new()));

    let workspace_table =
        workspace.as_table_mut().ok_or_else(|| CliError::cargo_operation("[workspace] is not a table"))?;

    let deps = workspace_table.entry("dependencies").or_insert(Item::Table(toml_edit::Table::new()));

    let deps_table = deps
        .as_table_mut()
        .ok_or_else(|| CliError::cargo_operation("[workspace.dependencies] is not a table"))?;

    if deps_table.contains_key(dep) {
        return Ok(());
    }

    if let Some(feats) = features
        && !feats.is_empty()
    {
        let mut inline = toml_edit::InlineTable::new();
        inline.insert("version", version.into());
        let features_array: toml_edit::Array = feats.iter().map(|f| Value::from(*f)).collect();
        inline.insert("features", Value::Array(features_array));
        deps_table.insert(dep, Item::Value(Value::InlineTable(inline)));
    } else {
        deps_table.insert(dep, Item::Value(Value::String(toml_edit::Formatted::new(version.to_string()))));
    }

    fs::write(cargo_toml_path, doc.to_string())?;
    Ok(())
}

fn fetch_latest_version(crate_name: &str) -> CliResult<String> {
    let output = Command::new("cargo")
        .args(["search", crate_name, "--limit", "1"])
        .output()
        .map_err(|_| CliError::cargo_operation("Failed to execute cargo search"))?;

    if !output.status.success() {
        return Ok("*".to_string());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        if line.starts_with(crate_name)
            && let Some(version_part) = line.split('=').nth(1)
        {
            let version = version_part
                .trim()
                .trim_matches('"')
                .split_whitespace()
                .next()
                .unwrap_or("")
                .trim_matches('"');
            if !version.is_empty() {
                return Ok(version.to_string());
            }
        }
    }

    Ok("*".to_string())
}

/* ========================================================== */
/*                        🧪 TESTS 🧪                         */
/* ========================================================== */

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_get_workspace_dependencies_returns_crates() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create workspace Cargo.toml with dependencies
        fs::write(
            root.join("Cargo.toml"),
            r#"[workspace]
members = ["app"]

[workspace.dependencies]
leptos = "0.7"
tw_merge = { version = "0.1", features = ["variant"] }
serde = "1.0"
"#,
        )
        .unwrap();

        let info = WorkspaceInfo {
            is_workspace: true,
            workspace_root: Some(root.to_path_buf()),
            target_crate: Some("app".to_string()),
            target_crate_path: Some(root.join("app")),
            components_base_path: "app/src/components".to_string(),
        };

        let deps = get_workspace_dependencies(&Some(info));

        assert!(deps.contains(&"leptos".to_string()));
        assert!(deps.contains(&"tw_merge".to_string()));
        assert!(deps.contains(&"serde".to_string()));
        assert_eq!(deps.len(), 3);
    }

    #[test]
    fn test_get_workspace_dependencies_empty_when_no_workspace() {
        let deps = get_workspace_dependencies(&None);
        assert!(deps.is_empty());
    }

    #[test]
    fn test_get_workspace_dependencies_empty_when_not_workspace() {
        let info = WorkspaceInfo {
            is_workspace: false,
            workspace_root: None,
            target_crate: Some("app".to_string()),
            target_crate_path: None,
            components_base_path: "src/components".to_string(),
        };

        let deps = get_workspace_dependencies(&Some(info));
        assert!(deps.is_empty());
    }

    #[test]
    fn test_get_workspace_dependencies_empty_when_no_workspace_deps_section() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create workspace Cargo.toml WITHOUT [workspace.dependencies]
        fs::write(
            root.join("Cargo.toml"),
            r#"[workspace]
members = ["app"]
"#,
        )
        .unwrap();

        let info = WorkspaceInfo {
            is_workspace: true,
            workspace_root: Some(root.to_path_buf()),
            target_crate: Some("app".to_string()),
            target_crate_path: Some(root.join("app")),
            components_base_path: "app/src/components".to_string(),
        };

        let deps = get_workspace_dependencies(&Some(info));
        assert!(deps.is_empty());
    }

    #[test]
    fn test_add_workspace_ref_to_member_uses_dotted_format() {
        let temp = TempDir::new().unwrap();
        let cargo_toml = temp.path().join("Cargo.toml");

        fs::write(
            &cargo_toml,
            r#"[package]
name = "app"
version = "0.1.0"

[dependencies]
leptos.workspace = true
"#,
        )
        .unwrap();

        add_workspace_ref_to_member(&cargo_toml, "tw_merge").unwrap();

        let contents = fs::read_to_string(&cargo_toml).unwrap();
        assert!(contents.contains("tw_merge.workspace = true"), "Should use dotted format, got: {contents}");
    }

    #[test]
    fn test_add_workspace_ref_skips_existing_dep() {
        let temp = TempDir::new().unwrap();
        let cargo_toml = temp.path().join("Cargo.toml");

        let original = r#"[package]
name = "app"
version = "0.1.0"

[dependencies]
tw_merge.workspace = true
"#;
        fs::write(&cargo_toml, original).unwrap();

        // Should not error or modify when dep already exists
        add_workspace_ref_to_member(&cargo_toml, "tw_merge").unwrap();

        let contents = fs::read_to_string(&cargo_toml).unwrap();
        // Count occurrences - should still be just one
        assert_eq!(contents.matches("tw_merge").count(), 1, "Should not duplicate: {contents}");
    }

    #[test]
    fn test_workspace_crate_detection_for_init() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create workspace with tw_merge already in workspace.dependencies
        fs::write(
            root.join("Cargo.toml"),
            r#"[workspace]
members = ["app"]

[workspace.dependencies]
tw_merge = { version = "0.1", features = ["variant"] }
leptos_ui = "0.3"
"#,
        )
        .unwrap();

        let info = WorkspaceInfo {
            is_workspace: true,
            workspace_root: Some(root.to_path_buf()),
            target_crate: Some("app".to_string()),
            target_crate_path: Some(root.join("app")),
            components_base_path: "app/src/components".to_string(),
        };

        let workspace_crates = get_workspace_dependencies(&Some(info));

        // These should be detected as workspace crates
        assert!(workspace_crates.contains(&"tw_merge".to_string()));
        assert!(workspace_crates.contains(&"leptos_ui".to_string()));

        // These should NOT be in workspace crates (not defined)
        assert!(!workspace_crates.contains(&"icons".to_string()));
    }

    #[test]
    fn test_has_workspace_dependencies_section_true() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        fs::write(
            root.join("Cargo.toml"),
            r#"[workspace]
members = ["app"]

[workspace.dependencies]
leptos = "0.7"
"#,
        )
        .unwrap();

        let info = WorkspaceInfo {
            is_workspace: true,
            workspace_root: Some(root.to_path_buf()),
            target_crate: Some("app".to_string()),
            target_crate_path: Some(root.join("app")),
            components_base_path: "app/src/components".to_string(),
        };

        assert!(has_workspace_dependencies_section(&Some(info)));
    }

    #[test]
    fn test_has_workspace_dependencies_section_false() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        fs::write(
            root.join("Cargo.toml"),
            r#"[workspace]
members = ["app"]
"#,
        )
        .unwrap();

        let info = WorkspaceInfo {
            is_workspace: true,
            workspace_root: Some(root.to_path_buf()),
            target_crate: Some("app".to_string()),
            target_crate_path: Some(root.join("app")),
            components_base_path: "app/src/components".to_string(),
        };

        assert!(!has_workspace_dependencies_section(&Some(info)));
    }

    #[test]
    fn test_add_to_workspace_dependencies_simple() {
        let temp = TempDir::new().unwrap();
        let cargo_toml = temp.path().join("Cargo.toml");

        fs::write(
            &cargo_toml,
            r#"[workspace]
members = ["app"]

[workspace.dependencies]
leptos = "0.7"
"#,
        )
        .unwrap();

        add_to_workspace_dependencies(&cargo_toml, "serde", "1.0", None).unwrap();

        let contents = fs::read_to_string(&cargo_toml).unwrap();
        assert!(contents.contains(r#"serde = "1.0""#), "got: {contents}");
        assert!(contents.contains(r#"leptos = "0.7""#), "should preserve existing: {contents}");
    }

    #[test]
    fn test_add_to_workspace_dependencies_with_features() {
        let temp = TempDir::new().unwrap();
        let cargo_toml = temp.path().join("Cargo.toml");

        fs::write(
            &cargo_toml,
            r#"[workspace]
members = ["app"]

[workspace.dependencies]
"#,
        )
        .unwrap();

        add_to_workspace_dependencies(&cargo_toml, "icons", "0.3", Some(&["leptos"])).unwrap();

        let contents = fs::read_to_string(&cargo_toml).unwrap();
        assert!(contents.contains("icons"), "got: {contents}");
        assert!(contents.contains("leptos"), "should have features: {contents}");
    }

    #[test]
    fn test_add_to_workspace_dependencies_skips_existing() {
        let temp = TempDir::new().unwrap();
        let cargo_toml = temp.path().join("Cargo.toml");

        fs::write(
            &cargo_toml,
            r#"[workspace]
members = ["app"]

[workspace.dependencies]
icons = { version = "0.2", features = ["leptos"] }
"#,
        )
        .unwrap();

        add_to_workspace_dependencies(&cargo_toml, "icons", "0.3", Some(&["leptos"])).unwrap();

        let contents = fs::read_to_string(&cargo_toml).unwrap();
        assert!(contents.contains(r#"version = "0.2""#), "should keep original version: {contents}");
        assert_eq!(contents.matches("icons").count(), 1, "should not duplicate: {contents}");
    }
}