holochain_scaffolding_cli 0.600.1

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
use anyhow::Context;
use build_fs_tree::{dir, file, Build, FileSystemTree, MergeableFileSystemTree};
use ignore::WalkBuilder;
use include_dir::Dir;
use regex::Regex;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};

use crate::error::{ScaffoldError, ScaffoldResult};
use crate::utils::unparse_pretty;

pub type FileTree = FileSystemTree<OsString, String>;

// Loads the directory tree in the given path into memory recursively
pub fn load_directory_into_memory(path: &Path) -> ScaffoldResult<FileTree> {
    let mut file_tree: FileTree = dir! {};

    for result in WalkBuilder::new(path).hidden(false).build() {
        let dir_entry = result?
            .path()
            .iter()
            .skip(path.components().count())
            .collect::<PathBuf>();

        if fs::metadata(path.join(&dir_entry))?.is_dir() {
            create_dir_all(&mut file_tree, &dir_entry)?;
        } else if let Ok(contents) = fs::read_to_string(path.join(&dir_entry)) {
            insert_file(&mut file_tree, &dir_entry, &contents)?;
        }
    }

    Ok(file_tree)
}

pub fn dir_content(
    file_tree: &FileTree,
    folder_path: &Path,
) -> ScaffoldResult<BTreeMap<OsString, FileTree>> {
    let v: Vec<OsString> = folder_path.iter().map(|s| s.to_os_string()).collect();
    file_tree
        .path(&mut v.iter())
        .ok_or(ScaffoldError::PathNotFound(folder_path.to_path_buf()))?
        .dir_content()
        .ok_or(ScaffoldError::PathNotFound(folder_path.to_path_buf()))
        .cloned()
}

pub fn dir_exists(app_file_tree: &FileTree, dir_path: &Path) -> bool {
    dir_content(app_file_tree, dir_path).is_ok()
}

pub fn file_exists(app_file_tree: &FileTree, file_path: &Path) -> bool {
    file_content(app_file_tree, file_path).is_ok()
}

pub fn file_content(file_tree: &FileTree, file_path: &Path) -> ScaffoldResult<String> {
    let v: Vec<OsString> = file_path.iter().map(|s| s.to_os_string()).collect();
    file_tree
        .path(&mut v.iter())
        .ok_or(ScaffoldError::PathNotFound(file_path.to_path_buf()))?
        .file_content()
        .ok_or(ScaffoldError::PathNotFound(file_path.to_path_buf()))
        .cloned()
}

pub fn map_file<F: Fn(String) -> Result<String, ScaffoldError>>(
    file_tree: &mut FileTree,
    file_path: &Path,
    map_fn: F,
) -> ScaffoldResult<()> {
    let contents = file_content(file_tree, file_path)?;
    insert_file(file_tree, file_path, &map_fn(contents)?)
}

pub fn insert_file(
    file_tree: &mut FileTree,
    file_path: &Path,
    content: &str,
) -> ScaffoldResult<()> {
    let mut folder_path = file_path.to_path_buf();
    folder_path.pop();

    insert_file_tree_in_dir(
        file_tree,
        &folder_path,
        (
            file_path.file_name().unwrap().to_os_string(),
            file!(content),
        ),
    )
}

pub fn insert_file_tree_in_dir(
    file_tree: &mut FileTree,
    folder_path: &Path,
    file_tree_to_insert: (OsString, FileTree),
) -> ScaffoldResult<()> {
    let v: Vec<OsString> = folder_path.iter().map(|s| s.to_os_string()).collect();
    file_tree
        .path_mut(&mut v.iter())
        .ok_or(ScaffoldError::PathNotFound(folder_path.to_path_buf()))?
        .dir_content_mut()
        .ok_or(ScaffoldError::PathNotFound(folder_path.to_path_buf()))?
        .insert(file_tree_to_insert.0, file_tree_to_insert.1);
    Ok(())
}

pub fn find_files_by_name(file_tree: &FileTree, file_name: &str) -> BTreeMap<PathBuf, String> {
    find_files(file_tree, &|file_path, _file_contents| {
        file_path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.eq(file_name))
    })
}

pub fn find_files<F: Fn(&PathBuf, &String) -> bool>(
    file_tree: &FileTree,
    find_by_path_and_contents: &F,
) -> BTreeMap<PathBuf, String> {
    find_map_files(file_tree, &|file_name, file_contents| {
        if find_by_path_and_contents(file_name, file_contents) {
            Some(file_contents.clone())
        } else {
            None
        }
    })
}

pub fn find_map_rust_files<T, F: Fn(&PathBuf, &syn::File) -> Option<T>>(
    file_tree: &FileTree,
    find_fn: &F,
) -> BTreeMap<PathBuf, T> {
    find_map_files(file_tree, &|file_path, file_contents| {
        if let Some(extension) = file_path.extension() {
            if extension == "rs" {
                let result: Result<syn::File, _> = syn::parse_str(file_contents.as_str());

                if let Ok(file) = result {
                    if let Some(t) = find_fn(file_path, &file) {
                        return Some(t);
                    }
                }
            }
        }

        None
    })
}

pub fn find_map_files<T, F: Fn(&PathBuf, &String) -> Option<T>>(
    file_tree: &FileTree,
    find_by_path_and_contents: &F,
) -> BTreeMap<PathBuf, T> {
    find_map_files_rec(file_tree, find_by_path_and_contents, &PathBuf::new())
}

fn find_map_files_rec<T, F: Fn(&PathBuf, &String) -> Option<T>>(
    file_tree: &FileTree,
    find_by_path_and_contents: &F,
    current_path: &Path,
) -> BTreeMap<PathBuf, T> {
    let mut found_files: BTreeMap<PathBuf, T> = BTreeMap::new();

    match file_tree {
        FileTree::File(_) => {}
        FileTree::Directory(directory_contents) => {
            for (file_name, child_file_tree) in directory_contents {
                let child_path = current_path.join(file_name);

                if let FileTree::File(contents) = child_file_tree {
                    if let Some(t) = find_by_path_and_contents(&child_path, contents) {
                        found_files.insert(child_path, t);
                    }
                } else {
                    let sub_paths =
                        find_map_files_rec(child_file_tree, find_by_path_and_contents, &child_path);
                    for (grandchild_path, contents) in sub_paths {
                        found_files.insert(grandchild_path, contents);
                    }
                }
            }
        }
    }

    found_files
}

pub fn map_rust_files<F: Fn(PathBuf, syn::File) -> ScaffoldResult<syn::File> + Copy>(
    file_tree: &mut FileTree,
    map_fn: F,
) -> ScaffoldResult<()> {
    map_all_files(file_tree, |file_path, contents| {
        if let Some(extension) = file_path.extension() {
            if extension == "rs" {
                let original_file: syn::File =
                    syn::parse_str(&convert_rust_line_to_doc_comments(&file_path, &contents))
                        .map_err(|e| {
                            ScaffoldError::MalformedFile(file_path.clone(), e.to_string())
                        })?;
                let new_file = map_fn(file_path, original_file.clone())?;
                // Only reformat the file via unparse_pretty if the contents of the newly modified
                // file are different from the original
                if new_file != original_file {
                    return Ok(unparse_pretty(&new_file));
                }
            }
        }
        Ok(contents)
    })
}

/// Converts line comments to doc comments in Rust files
///
/// This function is a workaround for a limitation in the `prettyplease::unparse` function,
/// which is used to pretty-print Rust syntax trees. The `unparse` function discards line
/// comments but preserves doc comments. To maintain all comments in the code, this function
/// converts line comments to doc comments before parsing, allowing them to be preserved
/// during the pretty-printing process.
///
/// After pretty-printing, these doc comments can be converted back to line comments if needed.
///
/// # Arguments
///
/// * `file_path` - A reference to the Path of the file being processed
/// * `content` - A string slice containing the content of the file
///
/// # Returns
///
/// A String with line comments converted to doc comments if the file is a Rust file,
/// otherwise returns the original content unchanged.
fn convert_rust_line_to_doc_comments(file_path: &Path, content: &str) -> String {
    if file_path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
        let re = Regex::new(r"(?:^|[^:])/(/[^/])").expect("Failed to create regex");
        content
            .lines()
            .map(|line| re.replace_all(line, "/// ").into_owned() + "\n")
            .collect()
    } else {
        content.to_string()
    }
}

pub fn flatten_file_tree(file_tree: &FileTree) -> BTreeMap<PathBuf, Option<String>> {
    walk_file_tree_rec(file_tree, &PathBuf::new())
}

pub fn unflatten_file_tree(
    flattened_tree: &BTreeMap<PathBuf, Option<String>>,
) -> ScaffoldResult<FileTree> {
    let mut file_tree: FileTree = FileTree::Directory(BTreeMap::new());

    for (path, maybe_contents) in flattened_tree.iter() {
        if let Some(contents) = maybe_contents {
            let mut folder_path = path.clone();
            folder_path.pop();

            create_dir_all(&mut file_tree, &folder_path)?;

            let v: Vec<OsString> = folder_path
                .clone()
                .iter()
                .map(|s| s.to_os_string())
                .collect();
            file_tree
                .path_mut(&mut v.iter())
                .ok_or(ScaffoldError::PathNotFound(folder_path.clone()))?
                .dir_content_mut()
                .ok_or(ScaffoldError::PathNotFound(folder_path.clone()))?
                .insert(path.file_name().unwrap().to_os_string(), file!(contents));
        } else {
            create_dir_all(&mut file_tree, path)?;
        }
    }

    Ok(file_tree)
}

pub fn map_all_files<F: Fn(PathBuf, String) -> ScaffoldResult<String> + Copy>(
    file_tree: &mut FileTree,
    map_fn: F,
) -> ScaffoldResult<()> {
    map_all_files_rec(file_tree, PathBuf::new(), map_fn)?;
    Ok(())
}

fn map_all_files_rec<F: Fn(PathBuf, String) -> ScaffoldResult<String> + Copy>(
    file_tree: &mut FileTree,
    current_path: PathBuf,
    map_fn: F,
) -> ScaffoldResult<()> {
    if let Some(dir) = file_tree.dir_content_mut() {
        for (key, mut tree) in dir.clone().into_iter() {
            let child_path = current_path.join(&key);
            match &tree {
                FileTree::Directory(_) => {
                    map_all_files_rec(&mut tree, child_path, map_fn)?;
                }
                FileTree::File(file_contents) => {
                    *tree
                        .file_content_mut()
                        .context("Failed to get mutable reference of file tree")? =
                        map_fn(child_path, file_contents.to_owned())?;
                }
            }
            dir.insert(key, tree);
        }
    }

    Ok(())
}

pub fn create_dir_all(file_tree: &mut FileTree, path: &Path) -> ScaffoldResult<()> {
    let mut current_path = PathBuf::new();

    for c in path.components() {
        let v: Vec<OsString> = current_path
            .clone()
            .iter()
            .map(|s| s.to_os_string())
            .collect();
        if let Some(contents) = file_tree
            .path_mut(&mut v.iter())
            .ok_or(ScaffoldError::PathNotFound(current_path.clone()))?
            .dir_content_mut()
        {
            let component_key = c.as_os_str().to_os_string();
            contents
                .entry(component_key)
                .or_insert_with(|| FileTree::Directory(BTreeMap::new()));
        } else {
            return Err(ScaffoldError::InvalidPath(
                path.to_path_buf(),
                String::from("given path is a file, and we expected it to be a directory"),
            ));
        }

        current_path.push(c);
    }

    Ok(())
}

pub fn template_dirs_to_file_tree(
    ui_framework_template_dir: &Dir<'_>,
    generic_template_dir: &Dir<'_>,
) -> ScaffoldResult<FileTree> {
    let mut flattened = walk_dir(ui_framework_template_dir);
    flattened.extend(walk_dir(generic_template_dir));
    unflatten_file_tree(&flattened)
}

fn walk_dir(dir: &Dir<'_>) -> BTreeMap<PathBuf, Option<String>> {
    let mut contents: BTreeMap<PathBuf, Option<String>> = BTreeMap::new();

    for f in dir.files() {
        if let Some(s) = f.contents_utf8() {
            contents.insert(f.path().to_path_buf(), Some(s.to_string()));
        }
    }
    for d in dir.dirs() {
        contents.insert(d.path().to_path_buf(), None);
        contents.extend(walk_dir(d));
    }

    contents
}

fn walk_file_tree_rec(
    file_tree: &FileTree,
    current_path: &Path,
) -> BTreeMap<PathBuf, Option<String>> {
    let mut found_files: BTreeMap<PathBuf, Option<String>> = BTreeMap::new();

    match file_tree {
        FileTree::File(_) => {}
        FileTree::Directory(directory_contents) => {
            for (file_name, child_file_tree) in directory_contents {
                let child_path = current_path.join(file_name);

                if let FileTree::File(contents) = child_file_tree {
                    found_files.insert(child_path, Some(contents.clone()));
                } else {
                    found_files.insert(child_path.clone(), None);
                    let sub_paths = walk_file_tree_rec(child_file_tree, &child_path);
                    for (grandchild_path, contents) in sub_paths {
                        found_files.insert(grandchild_path, contents);
                    }
                }
            }
        }
    }

    found_files
}

pub fn build_file_tree(file_tree: FileTree, path: impl Into<PathBuf>) -> Result<(), ScaffoldError> {
    let mergeable_tree = MergeableFileSystemTree::from(file_tree);
    mergeable_tree.build(&path.into())?;
    Ok(())
}