holochain_scaffolding_cli 0.4000.4

CLI to easily generate and modify holochain apps
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
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::path::Path;
use std::process::Command;
use std::{ffi::OsString, path::PathBuf};

use anyhow::Context;
use colored::Colorize;
use convert_case::{Case, Casing};
use dialoguer::{theme::ColorfulTheme, Input, Select};
use dprint_plugin_typescript::configuration::ConfigurationBuilder;

use crate::error::{ScaffoldError, ScaffoldResult};
use crate::file_tree::{dir_content, FileTree};

pub fn choose_directory_path(prompt: &str, app_file_tree: &FileTree) -> ScaffoldResult<PathBuf> {
    let mut chosen_directory: Option<PathBuf> = None;
    let mut current_path = PathBuf::new();

    while chosen_directory.is_none() {
        let mut folders = get_folder_names(&dir_content(app_file_tree, &current_path)?);

        folders = folders
            .clone()
            .into_iter()
            .map(|s| format!("{}/", s))
            .collect();
        let mut default = 0;

        let path_is_empty = current_path.as_os_str().is_empty();

        if !path_is_empty {
            default = 1;
            folders.insert(0, String::from(".."));
        }

        let selection = Select::with_theme(&ColorfulTheme::default())
            .with_prompt(format!("{} Current path: {:?}", prompt, current_path))
            .default(default)
            .items(&folders[..])
            .item("[Select this folder]")
            .report(false)
            .clear(true)
            .interact()?;

        if selection == folders.len() {
            chosen_directory = Some(current_path.clone());
        } else if !path_is_empty && selection == 0 {
            current_path.pop();
        } else {
            let mut folder_name = folders[selection].clone();
            folder_name.pop();
            current_path = current_path.join(folder_name);
        }
    }

    let dir = chosen_directory.context("Couldn't choose directory")?;

    println!("{prompt} Selected path: {current_path:?}");

    Ok(dir)
}

fn get_folder_names(folder: &BTreeMap<OsString, FileTree>) -> Vec<String> {
    folder
        .iter()
        .filter_map(|(key, val)| {
            if val.dir_content().is_some() {
                return key.to_str().map(|s| s.to_owned());
            }
            None
        })
        .collect()
}

#[inline]
/// "yes" or "no" input dialog, with the option to specify a recommended answer (yes = true, no = false)
pub fn input_yes_or_no(prompt: &str, recommended: Option<bool>) -> ScaffoldResult<bool> {
    let yes_recommended = (recommended == Some(true))
        .then_some("(recommended)")
        .unwrap_or_default();
    let no_recommended = (recommended == Some(false))
        .then_some("(recommended)")
        .unwrap_or_default();

    let items = [
        format!("Yes {}", yes_recommended),
        format!("No {}", no_recommended),
    ];

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .default(0)
        .items(&items)
        .interact()?;

    Ok(selection == 0)
}

#[inline]
pub fn input_with_custom_validation<V>(
    prompt: &str,
    initial_text: Option<&str>,
    validator: V,
) -> ScaffoldResult<String>
where
    V: Fn(String) -> Result<(), String>,
{
    let mut input: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .with_initial_text(initial_text.unwrap_or_default())
        .interact_text()?;

    while let Err(e) = validator(input.clone()) {
        println!("{}", e.red());
        input = Input::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt)
            .with_initial_text(initial_text.unwrap_or_default())
            .interact_text()?;
    }

    Ok(input)
}

#[inline]
pub fn input_with_case(
    prompt: &str,
    initial_text: Option<&str>,
    case: Case,
) -> ScaffoldResult<String> {
    let mut input: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .with_initial_text(initial_text.unwrap_or_default())
        .interact_text()?;

    while let Err(e) = check_case(&input, "Input", case) {
        println!("{}", e.to_string().red());
        input = Input::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt)
            .interact_text()?;
    }

    Ok(input)
}

#[inline]
pub fn input_no_whitespace(prompt: &str) -> ScaffoldResult<String> {
    let mut input: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .interact_text()?;

    while let Err(e) = validate_input(&input, "Input") {
        println!("{}", e.to_string().red());
        input = Input::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt)
            .interact_text()?;
    }

    Ok(input)
}

#[inline]
/// Raises an error if input is not of the appropriate_case
pub fn check_case(input: &str, identifier: &str, case: Case) -> ScaffoldResult<()> {
    if !input.is_case(case) {
        return Err(ScaffoldError::InvalidStringFormat(format!(
            "{identifier} must be {case:?} Case",
        )));
    }
    if input.chars().next().map_or(false, char::is_numeric) {
        return Err(ScaffoldError::InvalidStringFormat(format!(
            "{identifier} must not start with a number"
        )));
    }
    Ok(())
}

#[inline]
/// Raises an error if input is contains white spaces or starts with a numeric
pub fn validate_input(input: &str, identifier: &str) -> ScaffoldResult<()> {
    if input.contains(char::is_whitespace) {
        return Err(ScaffoldError::InvalidStringFormat(format!(
            "{identifier} must *not* contain whitespaces.",
        )));
    }
    if input.chars().next().map_or(false, char::is_numeric) {
        return Err(ScaffoldError::InvalidStringFormat(format!(
            "{identifier} must not start with a numeric"
        )));
    }
    Ok(())
}

/// Inserts new lines that are stripped out by `syn` during programmatic
/// manipulation of Rust code. Newlines and white spaces are not considered
/// tokens by `syn`, so this function restores them to improve code readability.
pub fn unparse_pretty(code: &syn::File) -> String {
    // replace previously converted line comment to doc comments back to line comments
    let formatted = prettyplease::unparse(code).replace("///", "//");
    let lines = formatted.lines().collect::<Vec<&str>>();
    let mut result = String::new();

    let mut last_line_was_import = false;
    let mut last_line_was_comment = false;
    let mut in_attribute = false;
    let mut in_struct = false;
    let mut in_function = false;
    let mut brace_count = 0;

    // Iterate through the lines, adding extra newlines where needed
    for (i, line) in lines.iter().enumerate() {
        let trimmed_line = line.trim();

        // Check if this line is an import
        let is_import = trimmed_line.starts_with("use ");
        let next_line_is_comment = lines.get(i + 1).unwrap_or(&"").starts_with("//");
        let is_comment = trimmed_line.starts_with("//");

        // Check if we're entering or exiting an attribute
        if trimmed_line.starts_with("#[") {
            in_attribute = true;
        } else if in_attribute && !trimmed_line.ends_with(']') {
            in_attribute = false;
        }

        // Check if we're entering or exiting a struct or function
        if trimmed_line.starts_with("pub struct ") || trimmed_line.starts_with("struct ") {
            in_struct = true;
        } else if trimmed_line.starts_with("pub fn ") || trimmed_line.starts_with("fn ") {
            in_function = true;
        }

        // Count braces to determine when we exit a struct or function
        brace_count += trimmed_line.chars().filter(|&c| c == '{').count() as i32;
        brace_count -= trimmed_line.chars().filter(|&c| c == '}').count() as i32;

        if brace_count == 0 {
            in_struct = false;
            in_function = false;
        }

        // Add an extra newline after the imports section
        if last_line_was_import && !is_import && !in_attribute {
            result.push('\n');
        }

        // Add the current line
        result.push_str(line);
        result.push('\n');

        // Add an extra newline between major items, but not after attributes or within structs/functions
        if !in_attribute
            && !in_struct
            && !in_function
            && !is_comment
            && i + 1 < lines.len()
            && should_add_newline(trimmed_line, lines[i + 1].trim())
        {
            result.push('\n');
        }

        if next_line_is_comment && !last_line_was_comment && !is_comment {
            result.push('\n');
        }

        last_line_was_import = is_import;
        last_line_was_comment = is_comment;
    }

    // Final cleanup: remove any triple (or more) newlines
    while result.contains("\n\n\n") {
        result = result.replace("\n\n\n", "\n\n");
    }

    result
}

fn should_add_newline(current: &str, next: &str) -> bool {
    let major_items = [
        "pub struct ",
        "struct ",
        "pub enum ",
        "enum ",
        "pub fn ",
        "fn ",
        "#[",
    ];

    major_items
        .iter()
        .any(|&item| current.starts_with(item) || next.starts_with(item))
}

/// Tries to progrmatically format generated ui code if the file extension matches
/// - ts/js/tsx/jsx
/// - svelte
/// - vue
pub fn format_code<P: Into<PathBuf>>(code: &str, file_name: P) -> ScaffoldResult<String> {
    let file_path: PathBuf = file_name.into();
    let ts_format_config = ConfigurationBuilder::new()
        .line_width(120)
        .indent_width(2)
        .build();

    if let Some(extension) = file_path.extension().and_then(|ext| ext.to_str()) {
        match extension {
            "ts" | "js" | "tsx" | "jsx" => {
                let formatted_code = dprint_plugin_typescript::format_text(
                    &file_path,
                    None,
                    code.to_owned(),
                    &ts_format_config,
                )
                .map_err(|e| anyhow::anyhow!("Failed to format source code: {e:?}"))?;

                if let Some(value) = formatted_code {
                    return Ok(value);
                }
            }
            "svelte" => {
                let formatted_code = markup_fmt::format_text(
                    code,
                    markup_fmt::Language::Svelte,
                    &Default::default(),
                    |path, raw, _| format_nested(path, extension, raw, &ts_format_config),
                )
                .map_err(|e| anyhow::anyhow!("Failed to format Svelte source code: {e:?}"))?;

                return Ok(formatted_code);
            }
            "vue" => {
                let formatted_code = markup_fmt::format_text(
                    code,
                    markup_fmt::Language::Vue,
                    &Default::default(),
                    |path, raw, _| format_nested(path, extension, raw, &ts_format_config),
                )
                .map_err(|e| anyhow::anyhow!("Failed to format Vue source code: {e:?}"))?;

                return Ok(formatted_code);
            }
            _ => {}
        }
    }

    Ok(code.to_owned())
}

/// Formats ts/js code nested in markup
fn format_nested<'a>(
    path: &Path,
    root_extension: &str,
    raw: &'a str,
    ts_format_config: &dprint_plugin_typescript::configuration::Configuration,
) -> ScaffoldResult<Cow<'a, str>> {
    if let Some(nested_extension) = path.extension().and_then(|ext| ext.to_str()) {
        match (root_extension, nested_extension) {
            ("vue", "ts" | "js") => {
                let formatted_code = dprint_plugin_typescript::format_text(
                    path,
                    None,
                    raw.to_owned(),
                    ts_format_config,
                )
                .map_err(|e| anyhow::anyhow!("Failed to format source code: {e:?}"))?;

                if let Some(value) = formatted_code {
                    return Ok(Cow::Owned(value));
                }
            }
            ("svelte", "ts" | "js" | "tsx" | "jsx") => {
                let formatted_code = dprint_plugin_typescript::format_text(
                    path,
                    None,
                    raw.to_owned(),
                    ts_format_config,
                )
                .map_err(|e| anyhow::anyhow!("Failed to format source code: {e:?}"))?;

                if let Some(value) = formatted_code {
                    return Ok(Cow::Owned(value));
                }
            }
            // Provision to format other nested code i.e css
            _ => {}
        }
    }
    Ok(Cow::Borrowed(raw))
}

/// Runs `cargo fmt` if it's available in the current Rust toolchain otherwise will exit
/// gracefully
pub fn run_cargo_fmt_if_available() -> ScaffoldResult<()> {
    let cargo_fmt_available = Command::new("cargo").arg("fmt").arg("--version").output();

    match cargo_fmt_available {
        Ok(output) if output.status.success() => {
            Command::new("cargo").arg("fmt").status()?;
        }
        _ => {}
    }
    Ok(())
}

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

    #[test]
    fn test_format_typescript_code() {
        let code = "function foo() { console.log('Hello, world!'); }";
        let file_name = "test.ts";
        let result = format_code(code, file_name);
        assert!(result.is_ok());
        let formatted_code = result.unwrap();
        assert_eq!(
            formatted_code,
            "function foo() {\n  console.log(\"Hello, world!\");\n}\n"
        );
    }

    #[test]
    fn test_format_javascript_code() {
        let code = "function foo() { console.log('Hello, world!'); }";
        let file_name = "test.js";
        let result = format_code(code, file_name);
        assert!(result.is_ok());
        let formatted_code = result.unwrap();
        assert_eq!(
            formatted_code,
            "function foo() {\n  console.log(\"Hello, world!\");\n}\n"
        );
    }

    #[test]
    fn test_format_tsx_code() {
        let code = "const foo = () => (<div>Hello, world!</div>);";
        let file_name = "test.tsx";
        let result = format_code(code, file_name);
        assert!(result.is_ok());
        let formatted_code = result.unwrap();
        assert_eq!(
            formatted_code,
            "const foo = () => <div>Hello, world!</div>;\n"
        );
    }

    #[test]
    fn test_format_jsx_code() {
        let code = "const foo = () => (<div>Hello, world!</div>);";
        let file_name = "test.jsx";
        let result = format_code(code, file_name);
        assert!(result.is_ok());
        let formatted_code = result.unwrap();
        assert_eq!(
            formatted_code,
            "const foo = () => <div>Hello, world!</div>;\n"
        );
    }

    #[test]
    fn test_format_vue_code() {
        let code = r#"<template>
<div>{{ message }}</div>
<button>click me</button>
</template>

<script lang="ts">
export default {
  data() {
    return {message: 'Hello, world!'}
  }
};
</script>
"#;
        let file_name = "test.vue";
        let result = format_code(code, file_name);
        assert!(result.is_ok());
        let formatted_code = result.unwrap();
        let expected_output = r#"<template>
  <div>{{ message }}</div>
  <button>click me</button>
</template>

<script lang="ts">
export default {
  data() {
    return { message: "Hello, world!" };
  },
};
</script>
"#;
        assert_eq!(formatted_code, expected_output);
    }

    #[test]
    fn test_format_svelte_code() {
        let code = r#"<script lang="ts">
  let greeting = {message: 'Hello, world!'}
</script>

<div>
<div>{greeting.message}</div>
<button>click me</button>
</div>
"#;
        let file_name = "test.svelte";
        let result = format_code(code, file_name);
        assert!(result.is_ok());
        let formatted_code = result.unwrap();
        let expected_output = r#"<script lang="ts">
let greeting = { message: "Hello, world!" };
</script>

<div>
  <div>{greeting.message}</div>
  <button>click me</button>
</div>
"#;
        assert_eq!(formatted_code, expected_output);
    }
}