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
use std::ffi::OsString;

use convert_case::{Case, Casing};
use dialoguer::{theme::ColorfulTheme, Select};
use holochain_types::prelude::ZomeManifest;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::parse_quote;

use crate::{
    error::{ScaffoldError, ScaffoldResult},
    file_tree::{insert_file, map_file, map_rust_files},
    scaffold::{
        dna::DnaFileTree,
        entry_type::definitions::EntryTypeReference,
        zome::{
            coordinator::{find_extern_function_in_zomes, find_extern_function_or_choose},
            utils::get_coordinator_zomes_for_integrity,
            ZomeFileTree,
        },
    },
    utils::unparse_pretty,
};

use super::CollectionType;

pub fn add_collection_to_coordinators(
    integrity_zome_file_tree: ZomeFileTree,
    collection_name: &str,
    link_type_name: &str,
    collection_type: &CollectionType,
    entry_type: &EntryTypeReference,
) -> ScaffoldResult<(DnaFileTree, ZomeManifest, bool)> {
    let integrity_zome_name = integrity_zome_file_tree.zome_manifest.name.0.to_string();
    let dna_manifest_path = integrity_zome_file_tree
        .dna_file_tree
        .dna_manifest_path
        .clone();

    let coordinator_zomes_for_integrity = get_coordinator_zomes_for_integrity(
        &integrity_zome_file_tree.dna_file_tree.dna_manifest,
        &integrity_zome_name,
    );

    let coordinator_zome = match coordinator_zomes_for_integrity.len() {
        0 => Err(ScaffoldError::NoCoordinatorZomesFoundForIntegrityZome(
            integrity_zome_file_tree.dna_file_tree.dna_manifest.name(),
            integrity_zome_file_tree.zome_manifest.name.0.to_string(),
        )),
        1 => Ok(coordinator_zomes_for_integrity[0].clone()),
        _ => {
            let names: Vec<String> = coordinator_zomes_for_integrity
                .iter()
                .map(|z| z.name.0.to_string())
                .collect();
            let selection = Select::with_theme(&ColorfulTheme::default())
                .with_prompt(
                    "Which coordinator zome should the collection getter functions be scaffolded in?",
                )
                .default(0)
                .items(&names[..])
                .interact()?;

            Ok(coordinator_zomes_for_integrity[selection].clone())
        }
    }?;

    // 1. Create an INDEX_NAME.rs in "src/", with the appropriate zome functions
    let zome_file_tree = ZomeFileTree::from_zome_manifest(
        integrity_zome_file_tree.dna_file_tree,
        coordinator_zome.clone(),
    )?;

    let snake_link_type_name = collection_name.to_case(Case::Snake);

    let getter = match collection_type {
        CollectionType::Global => {
            global_collection_getter(&integrity_zome_name, collection_name, link_type_name)
        }
        CollectionType::ByAuthor => {
            by_author_collection_getter(&integrity_zome_name, collection_name, link_type_name)
        }
    };

    let mut file_tree = zome_file_tree.dna_file_tree.file_tree();

    let crate_src_path = zome_file_tree.zome_crate_path.join("src");
    let collection_path = crate_src_path.join(format!("{}.rs", snake_link_type_name.clone()));

    let file = unparse_pretty(&syn::parse_quote! { #getter });

    insert_file(&mut file_tree, &collection_path, &file)?;

    // 2. Add this file as a module in the entry point for the crate
    let lib_rs_path = crate_src_path.join("lib.rs");

    map_file(&mut file_tree, &lib_rs_path, |contents| {
        Ok(format!(
            r#"pub mod {snake_link_type_name};
{contents}"#,
        ))
    })?;

    let mut dna_file_tree = DnaFileTree::from_dna_manifest_path(file_tree, &dna_manifest_path)?;

    dna_file_tree = add_create_link_in_create_function(
        dna_file_tree,
        &coordinator_zomes_for_integrity,
        collection_name,
        link_type_name,
        collection_type,
        entry_type,
    )?;

    let (dna_file_tree, deletable) = add_delete_link_in_delete_function(
        dna_file_tree,
        &coordinator_zomes_for_integrity,
        collection_name,
        link_type_name,
        collection_type,
        entry_type,
    )?;

    Ok((dna_file_tree, coordinator_zome, deletable))
}

fn global_collection_getter(
    integrity_zome_name: &str,
    collection_name: &str,
    link_type_name: &str,
) -> TokenStream {
    let get_collection_function_name =
        format_ident!("get_{}", collection_name.to_case(Case::Snake));
    let link_type_name = format_ident!("{link_type_name}");
    let integrity_zome_name = format_ident!("{integrity_zome_name}");
    let snake_collection_name = collection_name.to_case(Case::Snake);

    quote! {
        use hdk::prelude::*;
        use #integrity_zome_name::*;

        #[hdk_extern]
        pub fn #get_collection_function_name() -> ExternResult<Vec<Link>> {
            let path = Path::from(#snake_collection_name);
            get_links(GetLinksInputBuilder::try_new(path.path_entry_hash()?, LinkTypes::#link_type_name)?.build())
        }
    }
}

fn by_author_collection_getter(
    integrity_zome_name: &str,
    collection_name: &str,
    link_type_name: &str,
) -> TokenStream {
    let get_collection_function_name =
        format_ident!("get_{}", collection_name.to_case(Case::Snake));
    let link_type_name = format_ident!("{link_type_name}");
    let integrity_zome_name = format_ident!("{integrity_zome_name}");

    quote! {
        use hdk::prelude::*;
        use #integrity_zome_name::*;

        #[hdk_extern]
        pub fn #get_collection_function_name(author: AgentPubKey) -> ExternResult<Vec<Link>> {
            get_links(GetLinksInputBuilder::try_new(author, LinkTypes::#link_type_name)?.build())
        }
    }
}

fn add_create_link_in_create_function(
    dna_file_tree: DnaFileTree,
    coordinator_zomes_for_integrity: &Vec<ZomeManifest>,
    collection_name: &str,
    link_type_name: &str,
    collection_type: &CollectionType,
    entry_type_reference: &EntryTypeReference,
) -> ScaffoldResult<DnaFileTree> {
    let dna_manifest_path = dna_file_tree.dna_manifest_path.clone();

    let (chosen_coordinator_zome, fn_name) = find_extern_function_or_choose(
        &dna_file_tree,
        coordinator_zomes_for_integrity,
        &format!(
            "create_{}",
            entry_type_reference.entry_type.to_case(Case::Snake)
        ),
        &format!(
            "At the end of which function should the {} entries be collected?",
            entry_type_reference.entry_type.to_case(Case::Pascal)
        ),
    )?;

    let zome_file_tree = ZomeFileTree::from_zome_manifest(dna_file_tree, chosen_coordinator_zome)?;

    let snake_case_entry_type = entry_type_reference.entry_type.to_case(Case::Snake);

    let mut create_link_stmts: Vec<syn::Stmt> = if entry_type_reference.reference_entry_hash {
        let entry_hash_variable_name = format_ident!("{snake_case_entry_type}_entry_hash");
        let snake_case_entry_type = format_ident!("{snake_case_entry_type}");
        vec![parse_quote! {
            let #entry_hash_variable_name = hash_entry(&#snake_case_entry_type)?;
        }]
    } else {
        vec![]
    };

    let link_to_variable = if entry_type_reference.reference_entry_hash {
        format_ident!("{snake_case_entry_type}_entry_hash")
    } else {
        format_ident!("{snake_case_entry_type}_hash")
    };
    let link_type_name = format_ident!("{link_type_name}");

    match collection_type {
        CollectionType::Global => {
            create_link_stmts.push(parse_quote! {let path = Path::from(#collection_name);});
            create_link_stmts.push(parse_quote! {
                create_link(path.path_entry_hash()?, #link_to_variable.clone(), LinkTypes::#link_type_name, ())?;
            });
        }
        CollectionType::ByAuthor => {
            create_link_stmts.push(parse_quote! {
                let my_agent_pub_key = agent_info()?.agent_latest_pubkey;
            });
            create_link_stmts.push(parse_quote! {
                create_link(my_agent_pub_key, #link_to_variable.clone(), LinkTypes::#link_type_name, ())?;
            });
        }
    };

    let crate_src_path = zome_file_tree.zome_crate_path.join("src");

    let mut file_tree = zome_file_tree.dna_file_tree.file_tree();

    let v: Vec<OsString> = crate_src_path.iter().map(|s| s.to_os_string()).collect();
    map_rust_files(
        file_tree
            .path_mut(&mut v.iter())
            .ok_or(ScaffoldError::PathNotFound(crate_src_path.clone()))?,
        |_, mut file| {
            file.items = file
                .items
                .into_iter()
                .map(|item| {
                    if let syn::Item::Fn(mut item_fn) = item.clone() {
                        if item_fn
                            .attrs
                            .iter()
                            .any(|a| a.path().segments.iter().any(|s| s.ident == "hdk_extern"))
                            && item_fn.sig.ident == fn_name.sig.ident
                        {
                            if let Some(return_stmt) = item_fn.block.stmts.pop() {
                                item_fn
                                    .block
                                    .stmts
                                    .extend(create_link_stmts.clone().into_iter());
                                item_fn.block.stmts.push(return_stmt);
                            }
                            return syn::Item::Fn(item_fn);
                        }
                    }
                    item
                })
                .collect();
            Ok(file)
        },
    )
    .map_err(|e| match e {
        ScaffoldError::MalformedFile(path, error) => {
            ScaffoldError::MalformedFile(crate_src_path.join(path), error)
        }
        _ => e,
    })?;

    let dna_file_tree = DnaFileTree::from_dna_manifest_path(file_tree, &dna_manifest_path)?;

    Ok(dna_file_tree)
}

fn add_delete_link_in_delete_function(
    dna_file_tree: DnaFileTree,
    coordinator_zomes_for_integrity: &Vec<ZomeManifest>,
    collection_name: &str,
    link_type_name: &str,
    collection_type: &CollectionType,
    entry_type_reference: &EntryTypeReference,
) -> ScaffoldResult<(DnaFileTree, bool)> {
    let dna_manifest_path = dna_file_tree.dna_manifest_path.clone();

    let Some((chosen_coordinator_zome, fn_name)) = find_extern_function_in_zomes(
        &dna_file_tree,
        coordinator_zomes_for_integrity,
        &format!(
            "delete_{}",
            entry_type_reference.entry_type.to_case(Case::Snake)
        ),
    )?
    else {
        return Ok((dna_file_tree, false));
    };

    let zome_file_tree = ZomeFileTree::from_zome_manifest(dna_file_tree, chosen_coordinator_zome)?;

    let snake_case_entry_type = entry_type_reference.entry_type.to_case(Case::Snake);
    let pascal_entry_def_name = entry_type_reference.entry_type.to_case(Case::Pascal);

    let target_hash_variable = if entry_type_reference.reference_entry_hash {
        quote! {
            record
                .action()
                .entry_hash()
                .ok_or(wasm_error!(WasmErrorInner::Guest("Record does not have an entry".to_string())))?
                .clone()
        }
    } else {
        let original_hash = format_ident!("original_{snake_case_entry_type}_hash");
        quote! {#original_hash}
    };

    let into_hash_fn = if entry_type_reference.reference_entry_hash {
        format_ident!("into_entry_hash")
    } else {
        format_ident!("into_action_hash")
    };

    let delete_link_stmts: Vec<syn::Stmt> = match collection_type {
        CollectionType::Global => {
            let link_type_name = format_ident!("{link_type_name}");
            vec![
                parse_quote! {let path = Path::from(#collection_name);},
                parse_quote! {
                    let links = get_links(
                        GetLinksInputBuilder::try_new(path.path_entry_hash()?, LinkTypes::#link_type_name)?.build(),
                    )?;
                },
                parse_quote! {
                    for link in links {
                        if let Some(hash) = link.target.#into_hash_fn() {
                           if hash == #target_hash_variable {
                                delete_link(link.create_link_hash)?;
                            }
                        }
                    }
                },
            ]
        }
        CollectionType::ByAuthor => {
            let original_hash = format_ident!("original_{snake_case_entry_type}_hash");
            let error_message = format!("{pascal_entry_def_name} not found");
            let link_type_name = format_ident!("{link_type_name}");
            vec![
                parse_quote! {
                    let details = get_details(#original_hash.clone(), GetOptions::default())?
                    .ok_or(
                        wasm_error!(WasmErrorInner::Guest(#error_message.to_string()))
                    )?;
                },
                parse_quote! {
                    let record = match details {
                        Details::Record(details) => Ok(details.record),
                        _ => Err(wasm_error!(WasmErrorInner::Guest("Malformed get details response".to_string()))),
                    }?;
                },
                parse_quote! {
                    let links = get_links(
                        GetLinksInputBuilder::try_new(record.action().author().clone(), LinkTypes::#link_type_name)?.build()
                    )?;
                },
                parse_quote! {
                    for link in links {
                        if let Some(hash) = link.target.#into_hash_fn() {
                           if hash == #target_hash_variable {
                                delete_link(link.create_link_hash)?;
                            }
                        }
                    }
                },
            ]
        }
    };

    let crate_src_path = zome_file_tree.zome_crate_path.join("src");

    let mut file_tree = zome_file_tree.dna_file_tree.file_tree();

    let v: Vec<OsString> = crate_src_path.iter().map(|s| s.to_os_string()).collect();
    map_rust_files(
        file_tree
            .path_mut(&mut v.iter())
            .ok_or(ScaffoldError::PathNotFound(crate_src_path.clone()))?,
        |_, mut file| {
            file.items = file
                .items
                .into_iter()
                .map(|item| {
                    if let syn::Item::Fn(mut item_fn) = item.clone() {
                        if item_fn
                            .attrs
                            .iter()
                            .any(|a| a.path().segments.iter().any(|s| s.ident == "hdk_extern"))
                            && item_fn.sig.ident == fn_name.sig.ident
                        {
                            if let Some(delete_stmt) = item_fn.block.stmts.pop() {
                                item_fn
                                    .block
                                    .stmts
                                    .extend(delete_link_stmts.clone().into_iter());
                                item_fn.block.stmts.push(delete_stmt);
                            }
                            return syn::Item::Fn(item_fn);
                        }
                    }
                    item
                })
                .collect();
            Ok(file)
        },
    )
    .map_err(|e| match e {
        ScaffoldError::MalformedFile(path, error) => {
            ScaffoldError::MalformedFile(crate_src_path.join(path), error)
        }
        _ => e,
    })?;

    let dna_file_tree = DnaFileTree::from_dna_manifest_path(file_tree, &dna_manifest_path)?;

    Ok((dna_file_tree, true))
}