holochain_scaffolding_cli 0.1.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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
use crate::error::{ScaffoldError, ScaffoldResult};
use crate::file_tree::{
    dir_content, file_content, insert_file, load_directory_into_memory, FileTree,
};
use crate::scaffold::app::cargo::exec_metadata;
use crate::scaffold::app::AppFileTree;
use crate::scaffold::collection::{scaffold_collection, CollectionType};
use crate::scaffold::dna::{scaffold_dna, DnaFileTree};
use crate::scaffold::entry_type::crud::{parse_crud, Crud};
use crate::scaffold::entry_type::definitions::{
    parse_entry_type_reference, parse_referenceable, Cardinality, EntryTypeReference,
    FieldDefinition, FieldType, Referenceable,
};
use crate::scaffold::entry_type::{fields::parse_fields, scaffold_entry_type};
use crate::scaffold::example::{choose_example, Example};
use crate::scaffold::link_type::scaffold_link_type;
use crate::scaffold::web_app::scaffold_web_app;
use crate::scaffold::web_app::uis::{
    choose_non_vanilla_ui_framework, choose_ui_framework, template_for_ui_framework, UiFramework,
};
use crate::scaffold::zome::utils::select_integrity_zomes;
use crate::scaffold::zome::{
    integrity_zome_name, scaffold_coordinator_zome, scaffold_coordinator_zome_in_path,
    scaffold_integrity_zome, scaffold_integrity_zome_with_path, ZomeFileTree,
};
use crate::templates::example::scaffold_example;
use crate::templates::get::get_template;
use crate::templates::{
    choose_or_get_template, choose_or_get_template_file_tree, templates_path, ScaffoldedTemplate,
};
use crate::utils::{
    check_no_whitespace, check_snake_case, input_no_whitespace, input_snake_case, input_yes_or_no,
};

use build_fs_tree::{dir, Build, MergeableFileSystemTree};
use dialoguer::Input;
use dialoguer::{theme::ColorfulTheme, Select};
use std::process::Stdio;
use std::str::FromStr;
use std::{ffi::OsString, path::PathBuf, process::Command};
use structopt::StructOpt;

/// The list of subcommands for `hc scaffold`
#[derive(Debug, StructOpt)]
#[structopt(setting = structopt::clap::AppSettings::InferSubcommands)]
pub enum HcScaffold {
    /// Scaffold a new, empty web app
    WebApp {
        /// Name of the app to scaffold
        name: Option<String>,

        /// Description of the app to scaffold
        description: Option<String>,

        #[structopt(long)]
        /// Whether to setup the holonix development environment for this web-app
        setup_nix: Option<bool>,

        #[structopt(short = "u", long)]
        /// The git repository URL from which to download the template, incompatible with --templates-path
        templates_url: Option<String>,

        #[structopt(short = "p", long)]
        /// The local folder path in which to look for the given template, incompatible with --templates-url
        templates_path: Option<PathBuf>,

        #[structopt(short, long)]
        /// The template to scaffold the web-app from
        /// If "--templates-url" is given, the template must be located at the ".templates/<TEMPLATE NAME>" folder of the repository
        /// If not, the template must be an option from the built-in templates: "vanilla", "vue", "lit", "svelte"
        template: Option<String>,
    },
    /// Set up the template used in this project
    Template(HcScaffoldTemplate),
    /// Scaffold a DNA into an existing app
    Dna {
        #[structopt(long)]
        /// Name of the app in which you want to scaffold the DNA
        app: Option<String>,

        /// Name of the DNA being scaffolded
        name: Option<String>,

        #[structopt(short, long)]
        /// The template to scaffold the dna from
        /// The template must be located at the ".templates/<TEMPLATE NAME>" folder of the repository
        template: Option<String>,
    },
    /// Scaffold one or multiple zomes into an existing DNA
    Zome {
        #[structopt(long)]
        /// Name of the dna in which you want to scaffold the zome
        dna: Option<String>,

        /// Name of the zome being scaffolded
        name: Option<String>,

        #[structopt(long)]
        /// Scaffold an integrity zome at the given path
        integrity: Option<PathBuf>,

        #[structopt(long)]
        /// Scaffold a coordinator zome at the given path
        coordinator: Option<PathBuf>,

        #[structopt(short, long)]
        /// The template to scaffold the dna from
        /// The template must be located at the ".templates/<TEMPLATE NAME>" folder of the repository
        template: Option<String>,
    },
    /// Scaffold an entry type and CRUD functions into an existing zome
    EntryType {
        #[structopt(long)]
        /// Name of the dna in which you want to scaffold the zome
        dna: Option<String>,

        #[structopt(long)]
        /// Name of the integrity zome in which you want to scaffold the entry definition
        zome: Option<String>,

        /// Name of the entry type being scaffolded
        name: Option<String>,

        #[structopt(long)]
        /// Whether this entry type should be refereced with its "EntryHash" or its "ActionHash"
        /// If referred to by "EntryHash", the entries can't be updated or deleted
        reference_entry_hash: Option<bool>,

        #[structopt(long, parse(try_from_str = parse_crud))]
        /// The Create, "Read", "Update", and "Delete" zome call functions that should be scaffolded for this entry type
        /// If "--reference-entry-hash" is "true", only "Create" and "Read" will be scaffolded
        crud: Option<Crud>,

        #[structopt(long)]
        /// Whether to create a link from the original entry to each update action
        /// Only applies if update is selected in the "crud" argument
        link_from_original_to_each_update: Option<bool>,

        #[structopt(long, value_delimiter = ",", parse(try_from_str = parse_fields))]
        /// The fields that the entry type struct should contain
        /// Grammar: <FIELD_NAME>:<FIELD_TYPE>:<WIDGET>:<LINKED_FROM> , (widget and linked_from are optional)
        /// Eg. "title:String:TextField" , "posts_hashes:Vec\<ActionHash\>::Post"
        fields: Option<Vec<FieldDefinition>>,

        #[structopt(short, long)]
        /// The template to scaffold the dna from
        /// The template must be located at the ".templates/<TEMPLATE NAME>" folder of the repository
        template: Option<String>,
    },
    /// Scaffold a link type and its appropriate zome functions into an existing zome
    LinkType {
        #[structopt(long)]
        /// Name of the dna in which you want to scaffold the zome
        dna: Option<String>,

        #[structopt(long)]
        /// Name of the integrity zome in which you want to scaffold the link type
        zome: Option<String>,

        #[structopt(parse(try_from_str = parse_referenceable))]
        /// Entry type (or agent role) used as the base for the links
        from_referenceable: Option<Referenceable>,

        #[structopt(parse(try_from_str = parse_referenceable))]
        /// Entry type (or agent role) used as the target for the links
        to_referenceable: Option<Referenceable>,

        #[structopt(long)]
        /// Whether to create the inverse link, from the "--to-referenceable" entry type to the "--from-referenceable" entry type
        bidireccional: Option<bool>,

        #[structopt(long)]
        /// Whether this link type can be deleted
        delete: Option<bool>,

        #[structopt(short, long)]
        /// The template to scaffold the dna from
        /// The template must be located at the ".templates/<TEMPLATE NAME>" folder of the repository
        template: Option<String>,
    },
    /// Scaffold a collection of entries in an existing zome
    Collection {
        #[structopt(long)]
        /// Name of the dna in which you want to scaffold the zome
        dna: Option<String>,

        #[structopt(long)]
        /// Name of the integrity zome in which you want to scaffold the link type
        zome: Option<String>,

        /// Collection type: "global" or "by-author"
        collection_type: Option<CollectionType>,

        /// Collection name, just to differentiate it from other collections
        collection_name: Option<String>,

        #[structopt(parse(try_from_str = parse_entry_type_reference))]
        /// Entry type that is going to be added to the collection
        entry_type: Option<EntryTypeReference>,

        #[structopt(short, long)]
        /// The template to scaffold the dna from
        /// The template must be located at the ".templates/<TEMPLATE NAME>" folder of the repository
        template: Option<String>,
    },

    Example {
        /// Name of the example to scaffold. One of ['hello-world', 'forum'].
        example: Option<Example>,

        #[structopt(short, long)]
        /// The template to scaffold the example for
        /// Must be an option from the built-in templates: "vanilla", "vue", "lit", "svelte"
        template: Option<String>,
    },
}

impl HcScaffold {
    pub async fn run(self) -> anyhow::Result<()> {
        match self {
            HcScaffold::WebApp {
                name,
                description,
                setup_nix,
                template,
                templates_url,
                templates_path,
            } => {
                let prompt = String::from("App name (no whitespaces):");
                let name: String = match name {
                    Some(n) => {
                        check_no_whitespace(&n, "app name")?;
                        n
                    }
                    None => input_no_whitespace(&prompt)?,
                };

                let current_dir = std::env::current_dir()?;
                let app_folder = current_dir.join(&name);
                if app_folder.as_path().exists() {
                    return Err(ScaffoldError::FolderAlreadyExists(app_folder.clone()))?;
                }

                let (template_name, template_file_tree, scaffold_template) =
                    match (templates_url, templates_path) {
                        (Some(_), Some(_)) => Err(ScaffoldError::InvalidArguments(String::from(
                            "cannot use --templates-path and --templates-url together",
                        )))?,
                        (Some(u), None) => {
                            let (name, file_tree) = get_template(&u, &template)?;
                            (name, file_tree, true)
                        }
                        (None, Some(p)) => {
                            let templates_dir = current_dir.join(p);
                            let templates_file_tree = load_directory_into_memory(&templates_dir)?;
                            let name = choose_or_get_template(
                                &dir! {".templates"=>templates_file_tree},
                                &template,
                            )?;
                            let template_file_tree =
                                load_directory_into_memory(&templates_dir.join(&name))?;
                            (name, template_file_tree, true)
                        }
                        (None, None) => {
                            let ui_framework = match template {
                                Some(t) => UiFramework::from_str(t.as_str())?,
                                None => choose_ui_framework()?,
                            };

                            (
                                format!("{:?}", ui_framework),
                                template_for_ui_framework(&ui_framework)?,
                                false,
                            )
                        }
                    };

                if file_content(&template_file_tree, &PathBuf::from("web-app/README.md.hbs"))
                    .is_err()
                {
                    return Err(ScaffoldError::MalformedTemplate(
                        "Template does not contain a README.md.hbs file in its \"web-app\" directory"
                            .to_string(),
                    ))?;
                }

                let setup_nix = match setup_nix {
                    Some(s) => s,
                    None => {
                        let holonix_prompt = String::from("Do you want to set up the holonix development environment for this project?");
                        input_yes_or_no(&holonix_prompt, Some(true))?
                    }
                };

                let ScaffoldedTemplate {
                    file_tree,
                    next_instructions,
                } = scaffold_web_app(
                    name.clone(),
                    description,
                    !setup_nix,
                    &template_file_tree,
                    template_name,
                    scaffold_template,
                )?;

                let file_tree = MergeableFileSystemTree::<OsString, String>::from(dir! {
                    name.clone() => file_tree
                });

                file_tree.build(&".".into())?;

                let mut maybe_nix = "";

                if setup_nix {
                    if cfg!(target_os = "windows") {
                        return Err(anyhow::anyhow!("Windows doesn't support nix"));
                    } else {
                        let output = Command::new("nix-shell")
                        .stdout(Stdio::inherit())
                        .current_dir(std::env::current_dir()?.join(&name))
                        .args(["-I", "nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-21.11.tar.gz", "-p", "niv", "--run", "niv init && niv drop nixpkgs && niv drop niv && niv add -b main holochain/holonix"])
                        .output()?;

                        if !output.status.success() {
                            return Err(ScaffoldError::NixSetupError)?;
                        }

                        maybe_nix = "\n  nix-shell";
                    };
                }

                println!(
                    r#"
Web hApp "{}" scaffolded!
"#,
                    name
                );

                if let Some(i) = next_instructions {
                    println!("{}", i);
                } else {
                    println!(
                        r#"
Notice that this is an empty skeleton for a Holochain web-app, so:

- It won't compile until you add a DNA to it, and then add a zome to that DNA.
- The UI is empty, you'll need to import the appropriate components to the top level app component.

Set up your development environment with:

  cd {}{}
  npm install

Then, at any point in time you can start your application with:

  npm start

To continue scaffolding your application, add new DNAs to your app with:

  hc scaffold dna
"#,
                        name, maybe_nix
                    );
                }
            }
            HcScaffold::Template(template) => template.run()?,
            HcScaffold::Dna {
                app,
                name,
                template,
            } => {
                let prompt = String::from("DNA name (snake_case):");
                let name: String = match name {
                    Some(n) => {
                        check_snake_case(&n, "dna name")?;
                        n
                    }
                    None => input_snake_case(&prompt)?,
                };

                let current_dir = std::env::current_dir()?;

                let file_tree = load_directory_into_memory(&current_dir)?;
                let template_file_tree = choose_or_get_template_file_tree(&file_tree, &template)?;

                let app_file_tree = AppFileTree::get_or_choose(file_tree, &app)?;

                let ScaffoldedTemplate {
                    file_tree,
                    next_instructions,
                } = scaffold_dna(app_file_tree, &template_file_tree, &name)?;

                let file_tree = MergeableFileSystemTree::<OsString, String>::from(file_tree);

                file_tree.build(&".".into())?;

                println!(
                    r#"
DNA "{}" scaffolded!"#,
                    name
                );

                if let Some(i) = next_instructions {
                    println!("{}", i);
                } else {
                    println!(
                        r#"
Add new zomes to your DNA with:

  hc scaffold zome
"#,
                    );
                }
            }
            HcScaffold::Zome {
                dna,
                name,
                integrity,
                coordinator,
                template,
            } => {
                let current_dir = std::env::current_dir()?;
                let file_tree = load_directory_into_memory(&current_dir)?;
                let template_file_tree = choose_or_get_template_file_tree(&file_tree, &template)?;

                if let Some(n) = name.clone() {
                    check_snake_case(&n, "zome name")?;
                }

                let (scaffold_integrity, scaffold_coordinator) =
                    match (integrity.clone(), coordinator.clone()) {
                        (None, None) => {
                            let option = Select::with_theme(&ColorfulTheme::default())
                                .with_prompt("What do you want to scaffold?")
                                .default(0)
                                .items(&[
                                    "Integrity/coordinator zome-pair (recommended)",
                                    "Only an integrity zome",
                                    "Only a coordinator zome",
                                ])
                                .interact()?;

                            match option {
                                0 => (true, true),
                                1 => (true, false),
                                _ => (false, true),
                            }
                        }
                        _ => (integrity.is_some(), coordinator.is_some()),
                    };

                let name_prompt = match (scaffold_integrity, scaffold_coordinator) {
                    (true, true) => String::from("Enter coordinator zome name (snake_case):\n (The integrity zome will automatically be named '{name of coordinator zome}_integrity')\n"),
                    _ => String::from("Enter zome name (snake_case):"),
                };

                let name: String = match name {
                    Some(n) => n,
                    None => input_snake_case(&name_prompt)?,
                };

                let mut dna_file_tree = DnaFileTree::get_or_choose(file_tree, &dna)?;
                let dna_manifest_path = dna_file_tree.dna_manifest_path.clone();

                let mut zome_next_instructions: (Option<String>, Option<String>) = (None, None);

                if scaffold_integrity {
                    let integrity_zome_name = match scaffold_coordinator {
                        true => integrity_zome_name(&name),
                        false => name.clone(),
                    };
                    let ScaffoldedTemplate {
                        file_tree,
                        next_instructions,
                    } = scaffold_integrity_zome(
                        dna_file_tree,
                        &template_file_tree,
                        &integrity_zome_name,
                        &integrity,
                    )?;

                    zome_next_instructions.0 = next_instructions;

                    println!(r#"Integrity zome "{}" scaffolded!"#, integrity_zome_name);

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

                if scaffold_coordinator {
                    let dependencies = match scaffold_integrity {
                        true => Some(vec![integrity_zome_name(&name)]),
                        false => {
                            let integrity_zomes = select_integrity_zomes(&dna_file_tree.dna_manifest, Some(&String::from(
                              "Select integrity zome(s) this coordinator zome depends on (SPACE to select/unselect, ENTER to continue):"
                            )))?;
                            Some(integrity_zomes)
                        }
                    };
                    let ScaffoldedTemplate {
                        file_tree,
                        next_instructions,
                    } = scaffold_coordinator_zome(
                        dna_file_tree,
                        &template_file_tree,
                        &name,
                        &dependencies,
                        &coordinator,
                    )?;
                    zome_next_instructions.1 = next_instructions;

                    println!(r#"Coordinator zome "{}" scaffolded!"#, name);

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

                // TODO: implement scaffold_zome_template

                let file_tree =
                    MergeableFileSystemTree::<OsString, String>::from(dna_file_tree.file_tree());

                let f = file_tree.clone();

                file_tree.build(&".".into())?;

                // Execute cargo metadata to set up the cargo workspace in case this zome is the first crate
                exec_metadata(&f)?;

                match zome_next_instructions {
                    (Some(ii), Some(ci)) => {
                        println!("{}", ii);
                        println!("{}", ci);
                    }
                    (None, Some(i)) => println!("{}", i),
                    (Some(i), None) => println!("{}", i),
                    _ => println!(
                        r#"
Add new entry definitions to your zome with:

  hc scaffold entry-type
"#,
                    ),
                }
            }
            HcScaffold::EntryType {
                dna,
                zome,
                name,
                crud,
                reference_entry_hash,
                link_from_original_to_each_update,
                fields,
                template,
            } => {
                let current_dir = std::env::current_dir()?;
                let file_tree = load_directory_into_memory(&current_dir)?;
                let template_file_tree = choose_or_get_template_file_tree(&file_tree, &template)?;

                let name: String = match name {
                    Some(n) => {
                        check_snake_case(&n, "entry type name")?;
                        n
                    }
                    None => input_snake_case(&String::from("Entry type name (snake_case):"))?,
                };

                let dna_file_tree = DnaFileTree::get_or_choose(file_tree, &dna)?;

                let zome_file_tree = ZomeFileTree::get_or_choose_integrity(dna_file_tree, &zome)?;

                let ScaffoldedTemplate {
                    file_tree,
                    next_instructions,
                } = scaffold_entry_type(
                    zome_file_tree,
                    &template_file_tree,
                    &name,
                    &crud,
                    &reference_entry_hash,
                    &link_from_original_to_each_update,
                    &fields,
                )?;

                let file_tree = MergeableFileSystemTree::<OsString, String>::from(file_tree);

                file_tree.build(&".".into())?;

                println!(
                    r#"
Entry type "{}" scaffolded!"#,
                    name
                );

                if let Some(i) = next_instructions {
                    println!("{}", i);
                } else {
                    println!(
                        r#"
Add new collections for that entry type with:

  hc scaffold collection
"#,
                    );
                }
            }
            HcScaffold::LinkType {
                dna,
                zome,
                from_referenceable,
                to_referenceable,
                delete,
                bidireccional,
                template,
            } => {
                let current_dir = std::env::current_dir()?;
                let file_tree = load_directory_into_memory(&current_dir)?;
                let template_file_tree = choose_or_get_template_file_tree(&file_tree, &template)?;

                let dna_file_tree = DnaFileTree::get_or_choose(file_tree, &dna)?;

                let zome_file_tree = ZomeFileTree::get_or_choose_integrity(dna_file_tree, &zome)?;

                let ScaffoldedTemplate {
                    file_tree,
                    next_instructions,
                } = scaffold_link_type(
                    zome_file_tree,
                    &template_file_tree,
                    &from_referenceable,
                    &to_referenceable,
                    &delete,
                    &bidireccional,
                )?;

                let file_tree = MergeableFileSystemTree::<OsString, String>::from(file_tree);

                file_tree.build(&".".into())?;

                println!(
                    r#"
Link type scaffolded!
"#,
                );
                if let Some(i) = next_instructions {
                    println!("{}", i);
                }
            }
            HcScaffold::Collection {
                dna,
                zome,
                collection_name,
                collection_type,
                entry_type,
                template,
            } => {
                let current_dir = std::env::current_dir()?;
                let file_tree = load_directory_into_memory(&current_dir)?;
                let template_file_tree = choose_or_get_template_file_tree(&file_tree, &template)?;

                let dna_file_tree = DnaFileTree::get_or_choose(file_tree, &dna)?;

                let zome_file_tree = ZomeFileTree::get_or_choose_integrity(dna_file_tree, &zome)?;

                let prompt = String::from("Collection name (snake_case, eg. \"all_posts\"):");
                let name: String = match collection_name {
                    Some(n) => {
                        check_snake_case(&n, "collection name")?;
                        n
                    }
                    None => input_snake_case(&prompt)?,
                };

                let ScaffoldedTemplate {
                    file_tree,
                    next_instructions,
                } = scaffold_collection(
                    zome_file_tree,
                    &template_file_tree,
                    &name,
                    &collection_type,
                    &entry_type,
                )?;

                let file_tree = MergeableFileSystemTree::<OsString, String>::from(file_tree);

                file_tree.build(&".".into())?;

                println!(
                    r#"
Collection "{}" scaffolded!
"#,
                    name
                );

                if let Some(i) = next_instructions {
                    println!("{}", i);
                }
            }
            HcScaffold::Example { example, template } => {
                let example = match example {
                    Some(e) => e,
                    None => choose_example()?,
                };
                let name = example.to_string();

                let app_dir = std::env::current_dir()?.join(&name);
                if app_dir.as_path().exists() {
                    return Err(ScaffoldError::FolderAlreadyExists(app_dir.clone()))?;
                }

                let ui_framework = match example {
                    Example::HelloWorld => UiFramework::Vanilla,
                    Example::Forum => match template {
                        Some(t) => UiFramework::from_str(t.as_str())?,
                        None => choose_non_vanilla_ui_framework()?,
                    },
                };

                let template_file_tree = template_for_ui_framework(&ui_framework)?;
                let template_name = format!("{:?}", ui_framework);

                // Match on example types
                let file_tree = match example {
                    Example::HelloWorld => {
                        // scaffold web-app
                        let ScaffoldedTemplate { file_tree, .. } = scaffold_web_app(
                            name.clone(),
                            Some(String::from("A simple 'hello world' application.")),
                            false,
                            &template_file_tree,
                            template_name.clone(),
                            false,
                        )?;

                        // scaffold dna hello_world
                        let dna_name = String::from("hello_world");

                        let app_file_tree =
                            AppFileTree::get_or_choose(file_tree, &Some(name.clone()))?;
                        let ScaffoldedTemplate { file_tree, .. } =
                            scaffold_dna(app_file_tree, &template_file_tree, &dna_name)?;

                        // scaffold integrity zome hello_world
                        let dna_file_tree =
                            DnaFileTree::get_or_choose(file_tree, &Some(dna_name.clone()))?;
                        let dna_manifest_path = dna_file_tree.dna_manifest_path.clone();

                        let integrity_zome_name = String::from("hello_world_integrity");
                        let integrity_zome_path = PathBuf::new()
                            .join("dnas")
                            .join(&dna_name)
                            .join("zomes")
                            .join("integrity");
                        let ScaffoldedTemplate { file_tree, .. } =
                            scaffold_integrity_zome_with_path(
                                dna_file_tree,
                                &template_file_tree,
                                &integrity_zome_name,
                                &integrity_zome_path,
                            )?;

                        // scaffold integrity zome hello_world
                        let dna_file_tree =
                            DnaFileTree::from_dna_manifest_path(file_tree, &dna_manifest_path)?;

                        let coordinator_zome_name = String::from("hello_world");
                        let coordinator_zome_path = PathBuf::new()
                            .join("dnas")
                            .join(dna_name)
                            .join("zomes")
                            .join("coordinator");
                        let ScaffoldedTemplate { mut file_tree, .. } =
                            scaffold_coordinator_zome_in_path(
                                dna_file_tree,
                                &template_file_tree,
                                &coordinator_zome_name,
                                &Some(vec![integrity_zome_name]),
                                &coordinator_zome_path,
                            )?;

                        // Add "hello_world" function to coordinator
                        let hello_world_zome = format!(
                            r#"use hdk::prelude::*;

#[hdk_extern]
pub fn hello_world(_: ()) -> ExternResult<String> {{
    Ok(String::from("hello world from a Holochain app!"))
}}
"#
                        );

                        insert_file(
                            &mut file_tree,
                            &coordinator_zome_path.join("hello_world/src/lib.rs"),
                            &hello_world_zome,
                        )?;

                        file_tree
                    }
                    Example::Forum => {
                        // scaffold web-app
                        let ScaffoldedTemplate { file_tree, .. } = scaffold_web_app(
                            name.clone(),
                            Some(String::from("A simple 'forum' application.")),
                            false,
                            &template_file_tree,
                            template_name.clone(),
                            false,
                        )?;

                        // scaffold dna hello_world
                        let dna_name = String::from("forum");

                        let app_file_tree =
                            AppFileTree::get_or_choose(file_tree, &Some(name.clone()))?;
                        let ScaffoldedTemplate { file_tree, .. } =
                            scaffold_dna(app_file_tree, &template_file_tree, &dna_name)?;

                        // scaffold integrity zome posts
                        let dna_file_tree =
                            DnaFileTree::get_or_choose(file_tree, &Some(dna_name.clone()))?;
                        let dna_manifest_path = dna_file_tree.dna_manifest_path.clone();

                        let integrity_zome_name = String::from("posts_integrity");
                        let integrity_zome_path = PathBuf::new()
                            .join("dnas")
                            .join(&dna_name)
                            .join("zomes")
                            .join("integrity");
                        let ScaffoldedTemplate { file_tree, .. } =
                            scaffold_integrity_zome_with_path(
                                dna_file_tree,
                                &template_file_tree,
                                &integrity_zome_name,
                                &integrity_zome_path,
                            )?;

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

                        let coordinator_zome_name = String::from("posts");
                        let coordinator_zome_path = PathBuf::new()
                            .join("dnas")
                            .join(dna_name)
                            .join("zomes")
                            .join("coordinator");
                        let ScaffoldedTemplate { file_tree, .. } =
                            scaffold_coordinator_zome_in_path(
                                dna_file_tree,
                                &template_file_tree,
                                &coordinator_zome_name,
                                &Some(vec![integrity_zome_name.clone()]),
                                &coordinator_zome_path,
                            )?;

                        // Scaffold the app here to enable ZomeFileTree::from_manifest(), which calls `cargo metadata`
                        MergeableFileSystemTree::<OsString, String>::from(file_tree.clone())
                            .build(&app_dir)?;

                        std::env::set_current_dir(&app_dir)?;

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

                        let zome_file_tree = ZomeFileTree::get_or_choose_integrity(
                            dna_file_tree,
                            &Some(integrity_zome_name.clone()),
                        )?;

                        let ScaffoldedTemplate { file_tree, .. } = scaffold_entry_type(
                            zome_file_tree,
                            &template_file_tree,
                            &String::from("post"),
                            &Some(Crud {
                                update: true,
                                delete: true,
                            }),
                            &Some(false),
                            &Some(true),
                            &Some(vec![
                                FieldDefinition {
                                    field_name: String::from("title"),
                                    field_type: FieldType::String,
                                    widget: Some(String::from("TextField")),
                                    cardinality: Cardinality::Single,
                                    linked_from: None,
                                },
                                FieldDefinition {
                                    field_name: String::from("content"),
                                    field_type: FieldType::String,
                                    widget: Some(String::from("TextArea")),
                                    cardinality: Cardinality::Single,
                                    linked_from: None,
                                },
                            ]),
                        )?;

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

                        let zome_file_tree = ZomeFileTree::get_or_choose_integrity(
                            dna_file_tree,
                            &Some(String::from("posts_integrity")),
                        )?;

                        let ScaffoldedTemplate { file_tree, .. } = scaffold_entry_type(
                            zome_file_tree,
                            &template_file_tree,
                            &String::from("comment"),
                            &Some(Crud {
                                update: false,
                                delete: true,
                            }),
                            &Some(false),
                            &Some(true),
                            &Some(vec![
                                FieldDefinition {
                                    field_name: String::from("comment"),
                                    field_type: FieldType::String,
                                    widget: Some(String::from("TextArea")),
                                    cardinality: Cardinality::Single,
                                    linked_from: None,
                                },
                                FieldDefinition {
                                    field_name: String::from("post_hash"),
                                    field_type: FieldType::ActionHash,
                                    widget: None,
                                    cardinality: Cardinality::Single,
                                    linked_from: Some(Referenceable::EntryType(
                                        EntryTypeReference {
                                            entry_type: String::from("post"),
                                            reference_entry_hash: false,
                                        },
                                    )),
                                },
                            ]),
                        )?;

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

                        let zome_file_tree = ZomeFileTree::get_or_choose_integrity(
                            dna_file_tree,
                            &Some(String::from("posts_integrity")),
                        )?;

                        let ScaffoldedTemplate { file_tree, .. } = scaffold_collection(
                            zome_file_tree,
                            &template_file_tree,
                            &String::from("all_posts"),
                            &Some(CollectionType::Global),
                            &Some(EntryTypeReference {
                                entry_type: String::from("post"),
                                reference_entry_hash: false,
                            }),
                        )?;

                        file_tree
                    }
                };

                let ScaffoldedTemplate {
                    file_tree,
                    next_instructions,
                } = scaffold_example(file_tree, &template_file_tree, &example)?;

                let file_tree = MergeableFileSystemTree::<OsString, String>::from(file_tree);

                file_tree.build(&app_dir)?;

                // set up nix
                println!("Setting up nix-shell...");
                if cfg!(target_os = "windows") {
                    return Err(anyhow::anyhow!("Windows doesn't support nix"));
                } else {
                    let output = Command::new("nix-shell")
                            .stdout(Stdio::inherit())
                            .current_dir(&app_dir)
                            .args(["-I", "nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-21.11.tar.gz", "-p", "niv", "--run", "niv init && niv drop nixpkgs && niv drop niv && niv add -b main holochain/holonix"])
                            .output()?;

                    if !output.status.success() {
                        return Err(ScaffoldError::NixSetupError)?;
                    }
                };

                println!(
                    r#"
Example "{}" scaffolded!
"#,
                    example.to_string()
                );

                if let Some(i) = next_instructions {
                    println!("{}", i);
                }
            }
        }

        Ok(())
    }
}

#[derive(Debug, StructOpt)]
#[structopt(setting = structopt::clap::AppSettings::InferSubcommands)]
pub enum HcScaffoldTemplate {
    /// Download a custom template from a remote repository to this folder
    Get {
        /// The git repository URL from which to download the template
        template_url: String,

        #[structopt(long)]
        /// The template to get from the given repository (located at ".templates/<FROM TEMPLATE>")
        from_template: Option<String>,

        #[structopt(long)]
        /// The folder to download the template to, will end up at ".templates/<TO TEMPLATE>"
        to_template: Option<String>,
    },
    /// Initialize a new custom template from a built-in one
    Init {
        /// The UI framework to use as the template for this web-app
        template: Option<UiFramework>,

        #[structopt(long)]
        /// The folder to download the template to, will end up at ".templates/<TO TEMPLATE>"
        to_template: Option<String>,
    },
}

fn existing_templates_names(file_tree: &FileTree) -> ScaffoldResult<Vec<String>> {
    let templates_path = PathBuf::new().join(templates_path());

    match dir_content(file_tree, &templates_path) {
        Ok(templates_dir_content) => {
            let templates: Vec<String> = templates_dir_content
                .into_keys()
                .map(|k| k.to_str().unwrap().to_string())
                .collect();
            Ok(templates)
        }
        _ => Ok(vec![]),
    }
}

fn choose_existing_template(file_tree: &FileTree) -> ScaffoldResult<String> {
    let templates = existing_templates_names(file_tree)?;
    match templates.len() {
        0 => Err(ScaffoldError::NoTemplatesFound),
        1 => Ok(templates[0].clone()),
        _ => {
            let option = Select::with_theme(&ColorfulTheme::default())
                .with_prompt("Which existing template should the new template be merged into?")
                .default(0)
                .items(&templates[..])
                .interact()?;

            Ok(templates[option].clone())
        }
    }
}

impl HcScaffoldTemplate {
    pub fn run(self) -> anyhow::Result<()> {
        let (template_name, template_file_tree) = self.get_template_file_tree()?;

        let target_template = match self.target_template() {
            Some(t) => t,
            None => {
                let current_dir = std::env::current_dir()?;

                let file_tree = load_directory_into_memory(&current_dir)?;

                let mut create = true;
                // If existing templates
                if existing_templates_names(&file_tree)?.len() != 0 {
                    // Merge or create?

                    let selection = Select::with_theme(&ColorfulTheme::default())
                        .with_prompt("Do you want to create a new template in this repository?")
                        .default(0)
                        .item("Merge with an existing template")
                        .item("Create a new template")
                        .interact()?;

                    if selection == 0 {
                        create = false;
                    }
                }

                if create {
                    // Enter template name
                    let template_name = Input::with_theme(&ColorfulTheme::default())
                        .with_prompt("Enter new template name:")
                        .with_initial_text(template_name)
                        .interact()?;
                    template_name
                } else {
                    let existing_template = choose_existing_template(&file_tree)?;
                    existing_template
                }
            }
        };

        let template_file_tree = dir! {
            templates_path().join(&target_template) => template_file_tree
        };

        let file_tree = MergeableFileSystemTree::<OsString, String>::from(template_file_tree);

        file_tree.build(&".".into())?;

        match self {
            HcScaffoldTemplate::Get { .. } => {
                println!(
                    r#"Template downloaded to folder {:?}
"#,
                    templates_path().join(target_template)
                );
            }
            HcScaffoldTemplate::Init { .. } => {
                println!(
                    r#"Template initialized to folder {:?}
"#,
                    templates_path().join(target_template)
                );
            }
        }
        Ok(())
    }

    pub fn target_template(&self) -> Option<String> {
        match self {
            HcScaffoldTemplate::Get {
                to_template: target_template,
                ..
            } => target_template.clone(),
            HcScaffoldTemplate::Init {
                to_template: target_template,
                ..
            } => target_template.clone(),
        }
    }

    pub fn get_template_file_tree(&self) -> ScaffoldResult<(String, FileTree)> {
        match self {
            HcScaffoldTemplate::Get {
                template_url,
                from_template: template,
                ..
            } => get_template(template_url, template),

            HcScaffoldTemplate::Init { template, .. } => {
                let ui_framework = match template {
                    Some(t) => t.clone(),
                    None => choose_ui_framework()?,
                };
                Ok((
                    format!("{}", ui_framework.to_string()),
                    template_for_ui_framework(&ui_framework)?,
                ))
            }
        }
    }
}