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
use clap::Subcommand;
use std::{fs, process::Command, path::Path};
use tera::{Tera, Context};

#[derive(Subcommand)]
pub enum CompileCmd {
    Repository,
    // Package
}

#[derive(serde::Deserialize, serde::Serialize)]
struct RepositoryManifest {
    name: String,
    author: String,
    description: Option<String>,
}

#[derive(serde::Deserialize)]
struct ModuleCargo {
    package: ModulePackageCargo,
}

#[derive(serde::Deserialize)]
struct ModulePackageCargo {
    name: String,
    description: Option<String>,
    version: String,
    icon: Option<String>,
}

#[derive(serde::Serialize)]
struct ModuleManifest {
    id: String,
    name: String,
    description: Option<String>,
    file: String,
    version: String,
    meta: Vec<MetaType>,
    icon: Option<String>,
}

#[derive(serde::Serialize)]
struct RepositoryReleaseManifest {
    repository: RepositoryManifest,
    modules: Vec<ModuleManifest>,
}

#[derive(serde::Serialize)]
#[allow(dead_code)]
enum MetaType {
    Video,
    Image,
    Text,
}

pub fn handle(cmd: CompileCmd) {
    match cmd {
        CompileCmd::Repository => compile_repository()
    }
}

fn compile_repository() {
    Command::new("cargo")
        .arg("build")
        .arg("--release")
        .arg("--target")
        .arg("wasm32-unknown-unknown")
        .output()
        .expect("failed to build modules");

    let cwd = std::env::current_dir().expect("failed to get current working directory");
    let target_releases_path = cwd
        .join("target")
        .join("wasm32-unknown-unknown")
        .join("release");

    let repo_manifest_path = cwd.join("Manifest").with_extension("toml");
    let repo_manifest = toml::from_str::<RepositoryManifest>(
        &fs::read_to_string(repo_manifest_path).expect("No `Manifest.toml` found in directory."),
    )
    .unwrap();

    // Iterate every module and store in dist directory.

    let dist_path = cwd.join("dist");
    let dist_modules_path = dist_path.join("modules");

    // delete dist if present
    _ = fs::remove_dir_all(&dist_path);

    fs::create_dir_all(&dist_modules_path).expect("failed to create `dist/modules` folder.");

    let modules_dir = cwd.join("modules");

    let normalized_author = normalize_string(&repo_manifest.author).to_lowercase();
    assert!(normalized_author.len() > 0);

    let mut releases = RepositoryReleaseManifest {
        modules: vec![],
        repository: repo_manifest,
    };

    for entry in fs::read_dir(modules_dir).expect("failed to retrieve modules") {
        let module_cargo_path = entry
            .expect("failed to retrieve module")
            .path()
            .join("Cargo")
            .with_extension("toml");

        if !module_cargo_path.exists() {
            continue;
        }

        let module_cargo_str =
            fs::read_to_string(&module_cargo_path).expect("failed to retrieve module's cargo");
        let module_cargo: ModuleCargo =
            toml::from_str(&module_cargo_str).expect("failed to unpack module");

        let module_id = format!(
            "com.{}.{}",
            normalized_author,
            module_cargo.package.name.to_lowercase()
        );
        let module_display_name = module_cargo
            .package
            .name
            .replace("-", " ")
            .replace("_", " ")
            .trim()
            .into();

        // TODO: Zip Modules with their resources

        fs::copy(
            target_releases_path
                .join(&module_cargo.package.name)
                .with_extension("wasm"),
            dist_modules_path
                .join(format!("{}.stub", &module_id))
                .with_extension("wasm"),
        )
        .expect(
            format!(
                "failed to copy wasm file to dist for {}",
                &module_cargo.package.name
            )
            .as_str(),
        );

        let module_manifest = ModuleManifest {
            id: module_id.clone(),
            name: module_display_name,
            description: module_cargo.package.description.map(|f| f.trim().into()),
            file: format!("/modules/{}.wasm", &module_id),
            version: module_cargo.package.version,
            meta: vec![],
            icon: module_cargo.package.icon,
        };
        releases.modules.push(module_manifest);
    }

    geerate_html_template(&releases, &dist_path);

    fs::write(
        dist_path.join("Manifest").with_extension("json"),
        serde_json::to_string_pretty(&releases).expect("failed to create `Manifest.json`"),
    )
    .unwrap();

    println!("Successfully packaged server!")
}

fn geerate_html_template(manifest: &RepositoryReleaseManifest, output_path: &Path) {
    let index_bytes = include_str!("../../templates/site/index.html");

    let mut tera = Tera::default();
    tera.add_raw_template("index.html", index_bytes)
    .expect("failed to create index.html template.");

    let mut context = Context::new();
    context.insert("repository", &manifest.repository);
    context.insert("modules", &manifest.modules);
    let rendered = tera.render("index.html", &context).expect("failed to create template for index.html");

    fs::write(
        output_path.join("index").with_extension("html"),
        rendered,
    )
    .unwrap();
}

fn normalize_string(value: &String) -> String {
    return value
        .trim()
        .chars()
        .filter(|c| c.is_alphanumeric() || c.is_whitespace())
        .collect::<String>()
        .replace(" ", "-");
}