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
use crate::{config::Config, generator::SourceGenerator, metadata, metadata::DEFAULT_WIT_DIR};
use anyhow::{bail, Context, Result};
use cargo_component_core::{
    command::CommonOptions,
    registry::{Dependency, DependencyResolution, DependencyResolver, RegistryResolution},
};
use clap::Args;
use heck::ToKebabCase;
use semver::VersionReq;
use std::{
    borrow::Cow,
    collections::HashMap,
    fs,
    path::{Path, PathBuf},
    process::Command,
};
use toml_edit::{table, value, DocumentMut, Item, Table, Value};
use url::Url;

const WIT_BINDGEN_RT_CRATE: &str = "wit-bindgen-rt";

fn escape_wit(s: &str) -> Cow<str> {
    match s {
        "use" | "type" | "func" | "u8" | "u16" | "u32" | "u64" | "s8" | "s16" | "s32" | "s64"
        | "float32" | "float64" | "char" | "record" | "flags" | "variant" | "enum" | "union"
        | "bool" | "string" | "option" | "result" | "future" | "stream" | "list" | "_" | "as"
        | "from" | "static" | "interface" | "tuple" | "import" | "export" | "world" | "package" => {
            Cow::Owned(format!("%{s}"))
        }
        _ => s.into(),
    }
}

/// Create a new WebAssembly component package at <path>
#[derive(Args)]
#[clap(disable_version_flag = true)]
pub struct NewCommand {
    /// The common command options.
    #[clap(flatten)]
    pub common: CommonOptions,

    /// Initialize a new repository for the given version
    /// control system (git, hg, pijul, or fossil) or do not
    /// initialize any version control at all (none), overriding
    /// a global configuration.
    #[clap(long = "vcs", value_name = "VCS", value_parser = ["git", "hg", "pijul", "fossil", "none"])]
    pub vcs: Option<String>,

    /// Create a CLI command component [default]
    #[clap(long = "bin", alias = "command", conflicts_with = "lib")]
    pub bin: bool,

    /// Create a library (reactor) component
    #[clap(long = "lib", alias = "reactor")]
    pub lib: bool,

    /// Use the built-in `wasi:http/proxy` module adapter
    #[clap(long = "proxy", requires = "lib")]
    pub proxy: bool,

    /// Edition to set for the generated crate
    #[clap(long = "edition", value_name = "YEAR", value_parser = ["2015", "2018", "2021"])]
    pub edition: Option<String>,

    /// The component package namespace to use.
    #[clap(
        long = "namespace",
        value_name = "NAMESPACE",
        default_value = "component"
    )]
    pub namespace: String,

    /// Set the resulting package name, defaults to the directory name
    #[clap(long = "name", value_name = "NAME")]
    pub name: Option<String>,

    /// Code editor to use for rust-analyzer integration, defaults to `vscode`
    #[clap(long = "editor", value_name = "EDITOR", value_parser = ["emacs", "vscode", "none"])]
    pub editor: Option<String>,

    /// Use the specified target world from a WIT package.
    #[clap(long = "target", short = 't', value_name = "TARGET", requires = "lib")]
    pub target: Option<String>,

    /// Use the specified default registry when generating the package.
    #[clap(long = "registry", value_name = "REGISTRY")]
    pub registry: Option<String>,

    /// Disable the use of `rustfmt` when generating source code.
    #[clap(long = "no-rustfmt")]
    pub no_rustfmt: bool,

    /// The path for the generated package.
    #[clap(value_name = "path")]
    pub path: PathBuf,
}

struct PackageName<'a> {
    namespace: String,
    name: String,
    display: Cow<'a, str>,
}

impl<'a> PackageName<'a> {
    fn new(namespace: &str, name: Option<&'a str>, path: &'a Path) -> Result<Self> {
        let (name, display) = match name {
            Some(name) => (name.into(), name.into()),
            None => (
                path.file_name().expect("invalid path").to_string_lossy(),
                // `cargo new` prints the given path to the new package, so
                // use the path for the display value.
                path.as_os_str().to_string_lossy(),
            ),
        };

        let namespace_kebab = namespace.to_kebab_case();
        if namespace_kebab.is_empty() {
            bail!("invalid component namespace `{namespace}`");
        }

        wit_parser::validate_id(&namespace_kebab).with_context(|| {
            format!("component namespace `{namespace}` is not a legal WIT identifier")
        })?;

        let name_kebab = name.to_kebab_case();
        if name_kebab.is_empty() {
            bail!("invalid component name `{name}`");
        }

        wit_parser::validate_id(&name_kebab)
            .with_context(|| format!("component name `{name}` is not a legal WIT identifier"))?;

        Ok(Self {
            namespace: namespace_kebab,
            name: name_kebab,
            display,
        })
    }
}

impl NewCommand {
    /// Executes the command.
    pub async fn exec(self) -> Result<()> {
        log::debug!("executing new command");

        let config = Config::new(self.common.new_terminal())?;

        let name = PackageName::new(&self.namespace, self.name.as_deref(), &self.path)?;

        let out_dir = std::env::current_dir()
            .with_context(|| "couldn't get the current directory of the process")?
            .join(&self.path);
        let registries = self.registries()?;

        let target: Option<metadata::Target> = match self.target.as_deref() {
            Some(s) if s.contains('@') => Some(s.parse()?),
            Some(s) => Some(format!("{s}@{version}", version = VersionReq::STAR).parse()?),
            None => None,
        };

        let target = self
            .resolve_target(&config, &registries, target, true)
            .await?;
        let source = self.generate_source(&target)?;

        let mut command = self.new_command();
        match command.status() {
            Ok(status) => {
                if !status.success() {
                    std::process::exit(status.code().unwrap_or(1));
                }
            }
            Err(e) => {
                bail!("failed to execute `cargo new` command: {e}")
            }
        }

        self.update_manifest(&config, &name, &out_dir, &registries, &target)?;
        self.create_source_file(&config, &out_dir, source.as_ref(), &target)?;
        self.create_targets_file(&name, &out_dir)?;
        self.create_editor_settings_file(&out_dir)?;

        Ok(())
    }

    fn new_command(&self) -> Command {
        let mut command = std::process::Command::new("cargo");
        command.arg("new");

        if let Some(name) = &self.name {
            command.arg("--name").arg(name);
        }

        if let Some(edition) = &self.edition {
            command.arg("--edition").arg(edition);
        }

        if let Some(vcs) = &self.vcs {
            command.arg("--vcs").arg(vcs);
        }

        if self.common.quiet {
            command.arg("-q");
        }

        command.args(std::iter::repeat("-v").take(self.common.verbose as usize));

        if let Some(color) = self.common.color {
            command.arg("--color").arg(color.to_string());
        }

        if !self.is_command() {
            command.arg("--lib");
        }

        command.arg(&self.path);
        command
    }

    fn update_manifest(
        &self,
        config: &Config,
        name: &PackageName,
        out_dir: &Path,
        registries: &HashMap<String, Url>,
        target: &Option<(RegistryResolution, Option<String>)>,
    ) -> Result<()> {
        let manifest_path = out_dir.join("Cargo.toml");
        let manifest = fs::read_to_string(&manifest_path).with_context(|| {
            format!(
                "failed to read manifest file `{path}`",
                path = manifest_path.display()
            )
        })?;

        let mut doc: DocumentMut = manifest.parse().with_context(|| {
            format!(
                "failed to parse manifest file `{path}`",
                path = manifest_path.display()
            )
        })?;

        if !self.is_command() {
            doc["lib"] = table();
            doc["lib"]["crate-type"] = value(Value::from_iter(["cdylib"]));
        }

        // add release profile
        let mut release_profile = table();
        release_profile["codegen-units"] = value(1);
        release_profile["opt-level"] = value("s");
        release_profile["debug"] = value(false);
        release_profile["strip"] = value(true);
        release_profile["lto"] = value(true);
        let mut profile = table();
        profile.as_table_mut().unwrap().set_implicit(true);
        profile["release"] = release_profile;
        doc["profile"] = profile;

        let mut component = Table::new();
        component.set_implicit(true);

        component["package"] = value(format!(
            "{ns}:{name}",
            ns = name.namespace,
            name = name.name
        ));

        if !self.is_command() {
            if let Some((resolution, world)) = target.as_ref() {
                // if specifying exact version, set that exact version in the Cargo.toml
                let version = if !resolution.requirement.comparators.is_empty()
                    && resolution.requirement.comparators[0].op == semver::Op::Exact
                {
                    format!("={}", resolution.version)
                } else {
                    format!("{}", resolution.version)
                };
                component["target"] = match world {
                    Some(world) => {
                        value(format!("{name}/{world}@{version}", name = resolution.name,))
                    }
                    None => value(format!("{name}@{version}", name = resolution.name,)),
                };
            }
        }

        component["dependencies"] = Item::Table(Table::new());

        if !registries.is_empty() {
            let mut table = Table::new();
            for (name, url) in registries {
                table[name] = value(url.as_str());
            }
            component["registries"] = Item::Table(table);
        }

        if self.proxy {
            component["proxy"] = value(true);
        }

        let mut metadata = Table::new();
        metadata.set_implicit(true);
        metadata.set_position(doc.len());
        metadata["component"] = Item::Table(component);
        doc["package"]["metadata"] = Item::Table(metadata);

        fs::write(&manifest_path, doc.to_string()).with_context(|| {
            format!(
                "failed to write manifest file `{path}`",
                path = manifest_path.display()
            )
        })?;

        // Run cargo add for wit-bindgen and bitflags
        let mut cargo_add_command = std::process::Command::new("cargo");
        cargo_add_command.arg("add");
        cargo_add_command.arg("--quiet");
        cargo_add_command.arg(WIT_BINDGEN_RT_CRATE);
        cargo_add_command.arg("--features");
        cargo_add_command.arg("bitflags");
        cargo_add_command.current_dir(out_dir);
        let status = cargo_add_command
            .status()
            .context("failed to execute `cargo add` command")?;
        if !status.success() {
            bail!("`cargo add {WIT_BINDGEN_RT_CRATE} --features bitflags` command exited with non-zero status");
        }

        config.terminal().status(
            "Updated",
            format!("manifest of package `{name}`", name = name.display),
        )?;

        Ok(())
    }

    fn is_command(&self) -> bool {
        self.bin || !self.lib
    }

    fn generate_source(
        &self,
        target: &Option<(RegistryResolution, Option<String>)>,
    ) -> Result<Cow<str>> {
        match target {
            Some((resolution, world)) => {
                let generator =
                    SourceGenerator::new(&resolution.name, &resolution.path, !self.no_rustfmt);
                generator.generate(world.as_deref()).map(Into::into)
            }
            None => {
                if self.is_command() {
                    Ok(r#"#[allow(warnings)]
mod bindings;

fn main() {
    println!("Hello, world!");
}
"#
                    .into())
                } else {
                    Ok(r#"#[allow(warnings)]
mod bindings;

use bindings::Guest;

struct Component;

impl Guest for Component {
    /// Say hello!
    fn hello_world() -> String {
        "Hello, World!".to_string()
    }
}

bindings::export!(Component with_types_in bindings);
"#
                    .into())
                }
            }
        }
    }

    fn create_source_file(
        &self,
        config: &Config,
        out_dir: &Path,
        source: &str,
        target: &Option<(RegistryResolution, Option<String>)>,
    ) -> Result<()> {
        let path = if self.is_command() {
            "src/main.rs"
        } else {
            "src/lib.rs"
        };

        let source_path = out_dir.join(path);
        fs::write(&source_path, source).with_context(|| {
            format!(
                "failed to write source file `{path}`",
                path = source_path.display()
            )
        })?;

        match target {
            Some((resolution, _)) => {
                config.terminal().status(
                    "Generated",
                    format!(
                        "source file `{path}` for target `{name}` v{version}",
                        name = resolution.name,
                        version = resolution.version
                    ),
                )?;
            }
            None => {
                config
                    .terminal()
                    .status("Generated", format!("source file `{path}`"))?;
            }
        }

        Ok(())
    }

    fn create_targets_file(&self, name: &PackageName, out_dir: &Path) -> Result<()> {
        if self.is_command() || self.target.is_some() {
            return Ok(());
        }

        let wit_path = out_dir.join(DEFAULT_WIT_DIR);
        fs::create_dir(&wit_path).with_context(|| {
            format!(
                "failed to create targets directory `{wit_path}`",
                wit_path = wit_path.display()
            )
        })?;

        let path = wit_path.join("world.wit");

        fs::write(
            &path,
            format!(
                r#"package {ns}:{pkg};

/// An example world for the component to target.
world example {{
    export hello-world: func() -> string;
}}
"#,
                ns = escape_wit(&name.namespace),
                pkg = escape_wit(&name.name),
            ),
        )
        .with_context(|| {
            format!(
                "failed to write targets file `{path}`",
                path = path.display()
            )
        })
    }

    fn create_editor_settings_file(&self, out_dir: &Path) -> Result<()> {
        match self.editor.as_deref() {
            Some("vscode") | None => {
                let settings_dir = out_dir.join(".vscode");
                let settings_path = settings_dir.join("settings.json");

                fs::create_dir_all(settings_dir)?;

                fs::write(
                    &settings_path,
                    r#"{
    "rust-analyzer.check.overrideCommand": [
        "cargo",
        "component",
        "check",
        "--workspace",
        "--all-targets",
        "--message-format=json"
    ],
}
"#,
                )
                .with_context(|| {
                    format!(
                        "failed to write editor settings file `{path}`",
                        path = settings_path.display()
                    )
                })
            }
            Some("emacs") => {
                let settings_path = out_dir.join(".dir-locals.el");

                fs::create_dir_all(out_dir)?;

                fs::write(
                    &settings_path,
                    r#";;; Directory Local Variables
;;; For more information see (info "(emacs) Directory Variables")

((lsp-mode . ((lsp-rust-analyzer-cargo-watch-args . ["check"
                                                     (\, "--message-format=json")])
              (lsp-rust-analyzer-cargo-watch-command . "component")
              (lsp-rust-analyzer-cargo-override-command . ["cargo"
                                                           (\, "component")
                                                           (\, "check")
                                                           (\, "--workspace")
                                                           (\, "--all-targets")
                                                           (\, "--message-format=json")]))))
"#,
                )
                .with_context(|| {
                    format!(
                        "failed to write editor settings file `{path}`",
                        path = settings_path.display()
                    )
                })
            }
            Some("none") => Ok(()),
            _ => unreachable!(),
        }
    }

    async fn resolve_target(
        &self,
        config: &Config,
        registries: &HashMap<String, Url>,
        target: Option<metadata::Target>,
        network_allowed: bool,
    ) -> Result<Option<(RegistryResolution, Option<String>)>> {
        match target {
            Some(metadata::Target::Package {
                name,
                package,
                world,
            }) => {
                let mut resolver = DependencyResolver::new(
                    config.warg(),
                    registries,
                    None,
                    config.terminal(),
                    network_allowed,
                )?;
                let dependency = Dependency::Package(package);

                resolver.add_dependency(&name, &dependency).await?;

                let dependencies = resolver.resolve().await?;
                assert_eq!(dependencies.len(), 1);

                match dependencies
                    .into_values()
                    .next()
                    .expect("expected a target resolution")
                {
                    DependencyResolution::Registry(resolution) => Ok(Some((resolution, world))),
                    _ => unreachable!(),
                }
            }
            _ => Ok(None),
        }
    }

    fn registries(&self) -> Result<HashMap<String, Url>> {
        let mut registries = HashMap::new();

        if let Some(url) = self.registry.as_deref() {
            registries.insert(
                "default".to_string(),
                url.parse().context("failed to parse registry URL")?,
            );
        }

        Ok(registries)
    }
}