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
use crate::model::{Example, ExampleMetadata, ExampleName, ExampleParameters, GuestLanguage};
use include_dir::{include_dir, Dir, DirEntry};
use std::collections::HashSet;
use std::convert::identity;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{fs, io};

#[cfg(feature = "cli")]
pub mod cli;
pub mod model;

pub trait Examples {
    fn list_all_examples() -> Vec<Example>;
    fn instantiate(example: &Example, parameters: &ExampleParameters) -> io::Result<String>;
    fn instructions(example: &Example, parameters: &ExampleParameters) -> String;
}

pub struct GolemExamples {}

static EXAMPLES: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/examples");
static ADAPTERS: Dir<'_> = include_dir!("$OUT_DIR/golem-wit/adapters");
static WIT: Dir<'_> = include_dir!("$OUT_DIR/golem-wit/wit/deps");

impl Examples for GolemExamples {
    fn list_all_examples() -> Vec<Example> {
        let mut result: Vec<Example> = vec![];
        for entry in EXAMPLES.entries() {
            if let Some(lang_dir) = entry.as_dir() {
                let lang_dir_name = lang_dir.path().file_name().unwrap().to_str().unwrap();
                if let Some(lang) = GuestLanguage::from_string(lang_dir_name) {
                    let adapters_path =
                        Path::new(lang.tier().name()).join("wasi_snapshot_preview1.wasm");

                    for sub_entry in lang_dir.entries() {
                        if let Some(example_dir) = sub_entry.as_dir() {
                            let example_dir_name =
                                example_dir.path().file_name().unwrap().to_str().unwrap();
                            if example_dir_name != "INSTRUCTIONS"
                                && !example_dir_name.starts_with('.')
                            {
                                let example = parse_example(
                                    &lang,
                                    lang_dir.path(),
                                    Path::new("INSTRUCTIONS"),
                                    &adapters_path,
                                    example_dir.path(),
                                );
                                result.push(example);
                            }
                        }
                    }
                } else {
                    panic!("Invalid guest language name: {lang_dir_name}");
                }
            }
        }
        result
    }

    fn instantiate(example: &Example, parameters: &ExampleParameters) -> io::Result<String> {
        instantiate_directory(
            &EXAMPLES,
            &example.example_path,
            &parameters
                .target_path
                .join(parameters.component_name.as_string()),
            parameters,
            &example.exclude,
            &example.transform_exclude,
            true,
        )?;
        if let Some(adapter_path) = &example.adapter {
            copy(
                &ADAPTERS,
                adapter_path,
                &parameters
                    .target_path
                    .join(parameters.component_name.as_string())
                    .join("adapters")
                    .join(example.language.tier().name())
                    .join(adapter_path.file_name().unwrap().to_str().unwrap()),
            )?;
        }
        let wit_deps_targets = {
            match &example.wit_deps_targets {
                Some(paths) => paths
                    .iter()
                    .map(|path| {
                        parameters
                            .target_path
                            .join(parameters.component_name.as_string())
                            .join(path)
                    })
                    .collect(),
                None => vec![parameters
                    .target_path
                    .join(parameters.component_name.as_string())
                    .join("wit")
                    .join("deps")],
            }
        };
        for wit_dep in &example.wit_deps {
            for target_wit_deps in &wit_deps_targets {
                let target = target_wit_deps.join(wit_dep.file_name().unwrap().to_str().unwrap());
                copy_all(&WIT, wit_dep, &target)?;
            }
        }
        Ok(Self::instructions(example, parameters))
    }

    fn instructions(example: &Example, parameters: &ExampleParameters) -> String {
        transform(&example.instructions, parameters)
    }
}

fn instantiate_directory(
    catalog: &Dir<'_>,
    source: &Path,
    target: &Path,
    parameters: &ExampleParameters,
    excludes: &HashSet<String>,
    transform_excludes: &HashSet<String>,
    filter_metadata: bool,
) -> io::Result<()> {
    fs::create_dir_all(target)?;
    for entry in catalog
        .get_dir(source)
        .unwrap_or_else(|| panic!("Could not find entry {source:?}"))
        .entries()
    {
        let name = entry.path().file_name().unwrap().to_str().unwrap();
        if !excludes.contains(name) && (!filter_metadata || name != "metadata.json") {
            let name = file_name_transform(name, parameters);
            match entry {
                DirEntry::Dir(dir) => {
                    instantiate_directory(
                        catalog,
                        dir.path(),
                        &target.join(&name),
                        parameters,
                        excludes,
                        transform_excludes,
                        false,
                    )?;
                }
                DirEntry::File(file) => {
                    instantiate_file(
                        catalog,
                        file.path(),
                        &target.join(&name),
                        parameters,
                        !transform_excludes.contains(&name),
                    )?;
                }
            }
        }
    }
    Ok(())
}

fn instantiate_file(
    catalog: &Dir<'_>,
    source: &Path,
    target: &Path,
    parameters: &ExampleParameters,
    transform_contents: bool,
) -> io::Result<()> {
    let raw_contents = catalog
        .get_file(source)
        .unwrap_or_else(|| panic!("Could not find entry {source:?}"))
        .contents();
    let mut file = File::create(target)?;

    let transformed_contents = transform_contents
        .then(|| String::from_utf8(raw_contents.to_vec()).ok())
        .and_then(identity)
        .map(|contents| transform(contents, parameters));

    if let Some(transformed_contents) = transformed_contents {
        file.write_all(transformed_contents.as_bytes())?;
    } else {
        file.write_all(raw_contents)?;
    }

    Ok(())
}

fn copy(catalog: &Dir<'_>, source: &Path, target: &Path) -> io::Result<()> {
    let contents = catalog
        .get_file(source)
        .unwrap_or_else(|| panic!("Could not find entry {source:?}"))
        .contents();

    if let Some(parent) = target.parent() {
        fs::create_dir_all(parent)?;
    }
    let mut file = File::create(target)?;
    file.write_all(contents)?;
    Ok(())
}

fn copy_all(catalog: &Dir<'_>, source_path: &Path, target_path: &Path) -> io::Result<()> {
    fs::create_dir_all(target_path)?;

    let source_dir = catalog
        .get_dir(source_path)
        .unwrap_or_else(|| panic!("Could not find entry {source_path:?}"));
    for file in source_dir.files() {
        let contents = file.contents();
        let mut file =
            File::create(target_path.join(file.path().file_name().unwrap().to_str().unwrap()))?;
        file.write_all(contents)?;
    }

    Ok(())
}

fn transform(str: impl AsRef<str>, parameters: &ExampleParameters) -> String {
    str.as_ref()
        .replace("component-name", &parameters.component_name.to_kebab_case())
        .replace("ComponentName", &parameters.component_name.to_pascal_case())
        .replace("component_name", &parameters.component_name.to_snake_case())
        .replace(
            "pack::name",
            &parameters.package_name.to_string_with_double_colon(),
        )
        .replace("pack:name", &parameters.package_name.to_string_with_colon())
        .replace("pack_name", &parameters.package_name.to_snake_case())
        .replace("pack-name", &parameters.package_name.to_kebab_case())
        .replace("pack/name", &parameters.package_name.to_string_with_slash())
        .replace("PackName", &parameters.package_name.to_pascal_case())
        .replace("pack-ns", &parameters.package_name.namespace())
        .replace("PackNs", &parameters.package_name.namespace_title_case())
}

fn file_name_transform(str: impl AsRef<str>, parameters: &ExampleParameters) -> String {
    transform(str, parameters).replace("Cargo.toml._", "Cargo.toml") // HACK because cargo package ignores every subdirectory containing a Cargo.toml
}

fn parse_example(
    lang: &GuestLanguage,
    lang_path: &Path,
    default_instructions_file_name: &Path,
    adapters_path: &Path,
    example_root: &Path,
) -> Example {
    let raw_metadata = EXAMPLES
        .get_file(example_root.join("metadata.json"))
        .expect("Failed to read metadata JSON")
        .contents();
    let metadata = serde_json::from_slice::<ExampleMetadata>(raw_metadata)
        .expect("Failed to parse metadata JSON");
    let instructions_path = match metadata.instructions {
        Some(instructions_file_name) => lang_path.join(instructions_file_name),
        None => lang_path.join(default_instructions_file_name),
    };
    let raw_instructions = EXAMPLES
        .get_file(instructions_path)
        .expect("Failed to read instructions")
        .contents();
    let instructions =
        String::from_utf8(raw_instructions.to_vec()).expect("Failed to decode instructions");
    let name = ExampleName::from_string(example_root.file_name().unwrap().to_str().unwrap());

    let mut wit_deps: Vec<PathBuf> = vec![];
    if metadata.requires_golem_host_wit.unwrap_or(false) {
        wit_deps.push(Path::new("golem").to_path_buf());
        wit_deps.push(Path::new("wasm-rpc").to_path_buf());
    }
    if metadata.requires_wasi.unwrap_or(false) {
        wit_deps.push(Path::new("blobstore").to_path_buf());
        wit_deps.push(Path::new("cli").to_path_buf());
        wit_deps.push(Path::new("clocks").to_path_buf());
        wit_deps.push(Path::new("filesystem").to_path_buf());
        wit_deps.push(Path::new("http").to_path_buf());
        wit_deps.push(Path::new("io").to_path_buf());
        wit_deps.push(Path::new("keyvalue").to_path_buf());
        wit_deps.push(Path::new("logging").to_path_buf());
        wit_deps.push(Path::new("random").to_path_buf());
        wit_deps.push(Path::new("sockets").to_path_buf());
    }

    Example {
        name,
        language: lang.clone(),
        description: metadata.description,
        example_path: example_root.to_path_buf(),
        instructions,
        adapter: if metadata.requires_adapter.unwrap_or(true) {
            Some(adapters_path.to_path_buf())
        } else {
            None
        },
        wit_deps,
        wit_deps_targets: metadata
            .wit_deps_paths
            .map(|dirs| dirs.iter().map(PathBuf::from).collect()),
        exclude: metadata.exclude.iter().cloned().collect(),
        transform_exclude: metadata
            .transform_exclude
            .map(|te| te.iter().cloned().collect())
            .unwrap_or_default(),
    }
}