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
//! Parse wasmcloud.toml files which specify key information for building and signing
//! WebAssembly modules and native capability provider binaries

use anyhow::{anyhow, bail, Result};
use cargo_toml::{Manifest, Product};
use config::Config;
use semver::Version;
use std::{fs, path::PathBuf};

#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum LanguageConfig {
    Rust(RustConfig),
    TinyGo(TinyGoConfig),
}

#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum TypeConfig {
    Actor(ActorConfig),
    Provider(ProviderConfig),
    Interface(InterfaceConfig),
}

#[derive(serde::Deserialize, Debug, Clone)]
pub struct ProjectConfig {
    /// The language of the project, e.g. rust, tinygo. Contains specific configuration for that language.
    pub language: LanguageConfig,
    /// The type of project, e.g. actor, provider, interface. Contains the specific configuration for that type.
    /// This is renamed to "type" but is named project_type here to avoid clashing with the type keyword in Rust.
    #[serde(rename = "type")]
    pub project_type: TypeConfig,
    /// Configuration common amoung all project types & languages.
    pub common: CommonConfig,
}

#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct ActorConfig {
    /// The list of provider claims that this actor requires. eg. ["wasmcloud:httpserver", "wasmcloud:blobstore"]
    pub claims: Vec<String>,
    /// The registry to push to. eg. "localhost:8080"
    pub registry: Option<String>,
    /// Whether to push to the registry insecurely. Defaults to false.
    pub push_insecure: bool,
    /// The directory to store the private signing keys in.
    pub key_directory: PathBuf,
    /// The filename of the signed wasm actor.
    pub filename: Option<String>,
    /// The target wasm target to build for. Defaults to "wasm32-unknown-unknown".
    pub wasm_target: String,
    /// The call alias of the actor.
    pub call_alias: Option<String>,
}
#[derive(serde::Deserialize, Debug, PartialEq)]
struct RawActorConfig {
    /// The list of provider claims that this actor requires. eg. ["wasmcloud:httpserver", "wasmcloud:blobstore"]
    pub claims: Option<Vec<String>>,
    /// The registry to push to. eg. "localhost:8080"
    pub registry: Option<String>,
    /// Whether to push to the registry insecurely. Defaults to false.
    pub push_insecure: Option<bool>,
    /// The directory to store the private signing keys in. Defaults to "./keys".
    pub key_directory: Option<PathBuf>,
    /// The filename of the signed wasm actor.
    pub filename: Option<String>,
    /// The target wasm target to build for. Defaults to "wasm32-unknown-unknown".
    pub wasm_target: Option<String>,
    /// The call alias of the actor. Defaults to no alias.
    pub call_alias: Option<String>,
}

impl TryFrom<RawActorConfig> for ActorConfig {
    type Error = anyhow::Error;

    fn try_from(raw_config: RawActorConfig) -> Result<Self> {
        Ok(Self {
            claims: raw_config.claims.unwrap_or_default(),
            registry: raw_config.registry,
            push_insecure: raw_config.push_insecure.unwrap_or(false),
            key_directory: raw_config
                .key_directory
                .unwrap_or_else(|| PathBuf::from("./keys")),
            filename: raw_config.filename,
            wasm_target: raw_config
                .wasm_target
                .unwrap_or_else(|| "wasm32-unknown-unknown".to_string()),
            call_alias: raw_config.call_alias,
        })
    }
}
#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct ProviderConfig {
    /// The capability ID of the provider.
    pub capability_id: String,
    /// The vendor name of the provider.
    pub vendor: String,
}
#[derive(serde::Deserialize, Debug, PartialEq)]
struct RawProviderConfig {
    /// The capability ID of the provider.
    pub capability_id: String,
    /// The vendor name of the provider. Optional, defaults to 'NoVendor'.
    pub vendor: Option<String>,
}

impl TryFrom<RawProviderConfig> for ProviderConfig {
    type Error = anyhow::Error;

    fn try_from(raw_config: RawProviderConfig) -> Result<Self> {
        Ok(Self {
            capability_id: raw_config.capability_id,
            vendor: raw_config.vendor.unwrap_or_else(|| "NoVendor".to_string()),
        })
    }
}

#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct InterfaceConfig {
    /// Directory to output HTML.
    pub html_target: PathBuf,
    /// Path to codegen.toml file.
    pub codegen_config: PathBuf,
}
#[derive(serde::Deserialize, Debug, PartialEq)]

struct RawInterfaceConfig {
    /// Directory to output HTML. Defaults to "./html".
    pub html_target: Option<PathBuf>,
    /// Path to codegen.toml file. Optional, defaults to "./codegen.toml".
    pub codegen_config: Option<PathBuf>,
}

impl TryFrom<RawInterfaceConfig> for InterfaceConfig {
    type Error = anyhow::Error;

    fn try_from(raw_config: RawInterfaceConfig) -> Result<Self> {
        Ok(Self {
            html_target: raw_config
                .html_target
                .unwrap_or_else(|| PathBuf::from("./html")),
            codegen_config: raw_config
                .codegen_config
                .unwrap_or_else(|| PathBuf::from("./codegen.toml")),
        })
    }
}

#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct RustConfig {
    /// The path to the cargo binary. Optional, will default to search the user's `PATH` for `cargo` if not specified.
    pub cargo_path: Option<PathBuf>,
    /// Path to cargo/rust's `target` directory. Optional, defaults to `./target`.
    pub target_path: Option<PathBuf>,
}

#[derive(serde::Deserialize, Debug, PartialEq, Default, Clone)]
struct RawRustConfig {
    /// The path to the cargo binary. Optional, will default to search the user's `PATH` for `cargo` if not specified.
    pub cargo_path: Option<PathBuf>,
    /// Path to cargo/rust's `target` directory. Optional, defaults to `./target`.
    pub target_path: Option<PathBuf>,
}

impl TryFrom<RawRustConfig> for RustConfig {
    type Error = anyhow::Error;

    fn try_from(raw_config: RawRustConfig) -> Result<Self> {
        Ok(Self {
            cargo_path: raw_config.cargo_path,
            target_path: raw_config.target_path,
        })
    }
}

/// Configuration common amoung all project types & languages.
#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct CommonConfig {
    /// Name of the project.
    pub name: String,
    /// Semantic version of the project.
    pub version: Version,
    /// Path to the project directory to determine where built and signed artifacts should be
    pub path: PathBuf,
    /// Expected name of the wasm module binary that will be generated
    /// (if not present, name is expected to be used as a fallback)
    pub wasm_bin_name: Option<String>,
}

#[derive(serde::Deserialize, Debug)]
struct RawProjectConfig {
    /// The language of the project, e.g. rust, tinygo. This is used to determine which config to parse.
    pub language: String,
    /// The type of project. This is a string that is used to determine which type of config to parse.
    /// The toml file name is just "type" but is named project_type here to avoid clashing with the type keyword in Rust.
    #[serde(rename = "type")]
    pub project_type: String,
    /// Name of the project.
    pub name: Option<String>,
    /// Semantic version of the project.
    pub version: Option<Version>,
    pub actor: Option<RawActorConfig>,
    pub provider: Option<RawProviderConfig>,
    pub rust: Option<RawRustConfig>,
    pub interface: Option<RawInterfaceConfig>,
    pub tinygo: Option<RawTinyGoConfig>,
}

#[derive(serde::Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct TinyGoConfig {
    /// The path to the tinygo binary. Optional, will default to `tinygo` if not specified.
    pub tinygo_path: Option<PathBuf>,
}

#[derive(serde::Deserialize, Debug, PartialEq, Default)]
struct RawTinyGoConfig {
    /// The path to the tinygo binary. Optional, will default to `tinygo` if not specified.
    pub tinygo_path: Option<PathBuf>,
}

impl TryFrom<RawTinyGoConfig> for TinyGoConfig {
    type Error = anyhow::Error;

    fn try_from(raw_config: RawTinyGoConfig) -> Result<Self> {
        Ok(Self {
            tinygo_path: raw_config.tinygo_path,
        })
    }
}

/// Gets the wasmCloud project (actor, provider, or interface) config.
///
/// The config can come from multiple sources: a specific toml file path, a folder with a `wasmcloud.toml` file inside it, or by default it looks for a `wasmcloud.toml` file in the current directory.
///
/// The user can also override the config file by setting environment variables with the prefix "WASMCLOUD_". This behavior can be disabled by setting `use_env` to false.
/// For example, a user could set the variable `WASMCLOUD_RUST_CARGO_PATH` to override the default `cargo` path.
///
/// # Arguments
/// * `opt_path` - The path to the config file. If None, it will look for a wasmcloud.toml file in the current directory.
/// * `use_env` - Whether to use the environment variables or not. If false, it will not attempt to use environment variables. Defaults to true.
pub fn get_config(opt_path: Option<PathBuf>, use_env: Option<bool>) -> Result<ProjectConfig> {
    let mut path = opt_path.unwrap_or_else(|| PathBuf::from("."));

    if !path.exists() {
        return Err(anyhow!("Path {} does not exist", path.display()));
    }

    path = fs::canonicalize(path)?;
    let (project_path, wasmcloud_path) = if path.is_dir() {
        let wasmcloud_path = path.join("wasmcloud.toml");
        if !wasmcloud_path.is_file() {
            return Err(anyhow!(
                "No wasmcloud.toml file found in {}",
                path.display()
            ));
        }
        (path, wasmcloud_path)
    } else if path.is_file() {
        (
            path.parent()
                .ok_or_else(|| anyhow!("Could not get parent path of wasmcloud.toml file"))?
                .to_path_buf(),
            path,
        )
    } else {
        return Err(anyhow!(
            "No wasmcloud.toml file found in {}",
            path.display()
        ));
    };

    let mut config = Config::builder().add_source(config::File::from(wasmcloud_path.clone()));

    if use_env.unwrap_or(true) {
        config = config.add_source(config::Environment::with_prefix("WASMCLOUD"));
    }

    let json_value = config
        .build()
        .map_err(|e| {
            if e.to_string().contains("is not of a registered file format") {
                return anyhow!("Invalid config file: {}", wasmcloud_path.display());
            }

            anyhow!("{}", e)
        })?
        .try_deserialize::<serde_json::Value>()?;

    let raw_project_config: RawProjectConfig = serde_json::from_value(json_value)?;

    raw_project_config
        .convert(project_path)
        .map_err(|e: anyhow::Error| anyhow!("{} in {}", e, wasmcloud_path.display()))
}

impl RawProjectConfig {
    // Given a path to a valid cargo project, build an common_config enriched with Rust-specific information
    fn build_common_config_from_cargo_project(
        project_path: PathBuf,
        name: Option<String>,
        version: Option<Version>,
    ) -> Result<CommonConfig> {
        let cargo_toml_path = project_path.join("Cargo.toml");
        if !cargo_toml_path.is_file() {
            return Err(anyhow!(
                "missing/invalid Cargo.toml path [{}]",
                cargo_toml_path.display(),
            ));
        }

        // Build the manifest
        let mut cargo_toml = Manifest::from_path(cargo_toml_path)?;

        // Populate Manifest with lib/bin information
        cargo_toml.complete_from_path(&project_path)?;

        let cargo_pkg = cargo_toml
            .package
            .ok_or_else(|| anyhow!("Missing package information in Cargo.toml"))?;

        let version = match version {
            Some(version) => version,
            None => Version::parse(cargo_pkg.version.get()?.as_str())?,
        };

        let name = name.unwrap_or(cargo_pkg.name);

        // Determine the wasm module name from the [lib] section of Cargo.toml
        let wasm_bin_name = match cargo_toml.lib {
            Some(Product {
                name: Some(lib_name),
                ..
            }) => Some(lib_name),
            _ => None,
        };

        Ok(CommonConfig {
            name,
            version,
            path: project_path,
            wasm_bin_name,
        })
    }

    pub fn convert(self, project_path: PathBuf) -> Result<ProjectConfig> {
        let project_type_config = match self.project_type.trim().to_lowercase().as_str() {
            "actor" => {
                let actor_config = self.actor.ok_or_else(|| anyhow!("Missing actor config"))?;
                TypeConfig::Actor(actor_config.try_into()?)
            }

            "provider" => {
                let provider_config = self
                    .provider
                    .ok_or_else(|| anyhow!("Missing provider config"))?;
                TypeConfig::Provider(provider_config.try_into()?)
            }

            "interface" => {
                let interface_config = self
                    .interface
                    .ok_or_else(|| anyhow!("Missing interface config"))?;
                TypeConfig::Interface(interface_config.try_into()?)
            }

            _ => {
                return Err(anyhow!("Unknown project type: {}", self.project_type));
            }
        };

        let language_config = match self.language.trim().to_lowercase().as_str() {
            "rust" => match self.rust {
                Some(rust_config) => LanguageConfig::Rust(rust_config.try_into()?),
                None => LanguageConfig::Rust(RustConfig::default()),
            },
            "tinygo" => match self.tinygo {
                Some(tinygo_config) => LanguageConfig::TinyGo(tinygo_config.try_into()?),
                None => LanguageConfig::TinyGo(TinyGoConfig::default()),
            },
            _ => {
                return Err(anyhow!(
                    "Unknown language in wasmcloud.toml: {}",
                    self.language
                ));
            }
        };

        let common_config_result: Result<CommonConfig> = match language_config {
            LanguageConfig::Rust(_) => {
                match Self::build_common_config_from_cargo_project(
                    project_path.clone(),
                    self.name.clone(),
                    self.version.clone(),
                ) {
                    // Successfully built with cargo information
                    Ok(cfg) => Ok(cfg),

                    // Fallback to non-specific language usage if we at least have a name & version
                    Err(_) if self.name.is_some() && self.version.is_some() => Ok(CommonConfig {
                        name: self.name.unwrap(),
                        version: self.version.unwrap(),
                        path: project_path,
                        wasm_bin_name: None,
                    }),

                    Err(err) => {
                        bail!("No Cargo.toml file found in the current directory, and name/version unspecified: {err}")
                    }
                }
            }

            LanguageConfig::TinyGo(_) => Ok(CommonConfig {
                name: self
                    .name
                    .ok_or_else(|| anyhow!("Missing name in wasmcloud.toml"))?,
                version: self
                    .version
                    .ok_or_else(|| anyhow!("Missing version in wasmcloud.toml"))?,
                path: project_path,
                wasm_bin_name: None,
            }),
        };

        Ok(ProjectConfig {
            language: language_config,
            project_type: project_type_config,
            common: common_config_result?,
        })
    }
}