cargo-leptos 0.2.19

Build tool for Leptos.
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
use crate::config::hash_file::HashFile;
use crate::{
    config::lib_package::LibPackage,
    ext::{
        anyhow::{bail, ensure, Result},
        PackageExt, PathBufExt, PathExt,
    },
    logger::GRAY,
    service::site::Site,
};
use camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::{Metadata, Package};
use serde::Deserialize;
use std::{fmt::Debug, net::SocketAddr, sync::Arc};

use super::{
    assets::AssetsConfig,
    bin_package::BinPackage,
    cli::Opts,
    dotenvs::{load_dotenvs, overlay_env},
    end2end::End2EndConfig,
    style::StyleConfig,
};

/// If the site root path starts with this marker, the marker should be replaced with the Cargo target directory
const CARGO_TARGET_DIR_MARKER: &str = "CARGO_TARGET_DIR";
/// If the site root path starts with this marker, the marker should be replaced with the Cargo target directory
const CARGO_BUILD_TARGET_DIR_MARKER: &str = "CARGO_BUILD_TARGET_DIR";

pub struct Project {
    /// absolute path to the working dir
    pub working_dir: Utf8PathBuf,
    pub name: String,
    pub lib: LibPackage,
    pub bin: BinPackage,
    pub style: StyleConfig,
    pub watch: bool,
    pub release: bool,
    pub precompress: bool,
    pub hot_reload: bool,
    pub wasm_debug: bool,
    pub site: Arc<Site>,
    pub end2end: Option<End2EndConfig>,
    pub assets: Option<AssetsConfig>,
    pub js_dir: Utf8PathBuf,
    pub watch_additional_files: Vec<Utf8PathBuf>,
    pub hash_file: HashFile,
    pub hash_files: bool,
    pub js_minify: bool,
}

impl Debug for Project {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Project")
            .field("name", &self.name)
            .field("lib", &self.lib)
            .field("bin", &self.bin)
            .field("style", &self.style)
            .field("watch", &self.watch)
            .field("release", &self.release)
            .field("precompress", &self.precompress)
            .field("js_minify", &self.js_minify)
            .field("hot_reload", &self.hot_reload)
            .field("site", &self.site)
            .field("end2end", &self.end2end)
            .field("assets", &self.assets)
            .finish_non_exhaustive()
    }
}

impl Project {
    pub fn resolve(
        cli: &Opts,
        cwd: &Utf8Path,
        metadata: &Metadata,
        watch: bool,
        bin_args: Option<&[String]>,
    ) -> Result<Vec<Arc<Project>>> {
        let projects = ProjectDefinition::parse(metadata)?;

        let mut resolved = Vec::new();
        for (project, mut config) in projects {
            if config.output_name.is_empty() {
                config.output_name = project.name.to_string();
            }

            let lib = LibPackage::resolve(cli, metadata, &project, &config)?;

            let js_dir = config
                .js_dir
                .clone()
                .unwrap_or_else(|| Utf8PathBuf::from("src"));

            let watch_additional_files = config.watch_additional_files.clone().unwrap_or_default();

            let bin = BinPackage::resolve(cli, metadata, &project, &config, bin_args)?;

            let hash_file = HashFile::new(
                &metadata.workspace_root,
                config.hash_file_name.as_ref(),
            );

            let proj = Project {
                working_dir: metadata.workspace_root.clone(),
                name: project.name.clone(),
                lib,
                bin,
                style: StyleConfig::new(&config)?,
                watch,
                release: cli.release,
                precompress: cli.precompress,
                hot_reload: cli.hot_reload,
                wasm_debug: cli.wasm_debug,
                site: Arc::new(Site::new(&config)),
                end2end: End2EndConfig::resolve(&config),
                assets: AssetsConfig::resolve(&config),
                js_dir,
                watch_additional_files,
                hash_file,
                hash_files: config.hash_files,
                js_minify: cli.release && cli.js_minify && config.js_minify,
            };
            resolved.push(Arc::new(proj));
        }

        let projects_in_cwd = resolved
            .iter()
            .filter(|p| p.bin.abs_dir.starts_with(cwd) || p.lib.abs_dir.starts_with(cwd))
            .collect::<Vec<_>>();

        if projects_in_cwd.len() == 1 {
            Ok(vec![projects_in_cwd[0].clone()])
        } else {
            Ok(resolved)
        }
    }

    /// env vars to use when running external command
    pub fn to_envs(&self) -> Vec<(&'static str, String)> {
        let mut vec = vec![
            ("LEPTOS_OUTPUT_NAME", self.lib.output_name.to_string()),
            ("LEPTOS_SITE_ROOT", self.site.root_dir.to_string()),
            ("LEPTOS_SITE_PKG_DIR", self.site.pkg_dir.to_string()),
            ("LEPTOS_SITE_ADDR", self.site.addr.to_string()),
            ("LEPTOS_RELOAD_PORT", self.site.reload.port().to_string()),
            ("LEPTOS_LIB_DIR", self.lib.rel_dir.to_string()),
            ("LEPTOS_BIN_DIR", self.bin.rel_dir.to_string()),
            ("LEPTOS_JS_MINIFY", self.js_minify.to_string()),
            ("LEPTOS_HASH_FILES", self.hash_files.to_string()),
        ];
        if self.hash_files {
            vec.push(("LEPTOS_HASH_FILE_NAME", self.hash_file.rel.to_string()));
        }
        if self.watch {
            vec.push(("LEPTOS_WATCH", "true".to_string()))
        }
        vec
    }
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct ProjectConfig {
    #[serde(default)]
    pub output_name: String,
    #[serde(default = "default_site_addr")]
    pub site_addr: SocketAddr,
    #[serde(default = "default_site_root")]
    pub site_root: Utf8PathBuf,
    #[serde(default = "default_pkg_dir")]
    pub site_pkg_dir: Utf8PathBuf,
    pub style_file: Option<Utf8PathBuf>,
    /// text file where the hashes of the frontend files are stored
    pub hash_file_name: Option<Utf8PathBuf>,
    /// whether to hash the frontend files content and add them to the file names
    #[serde(default = "default_hash_files")]
    pub hash_files: bool,
    pub tailwind_input_file: Option<Utf8PathBuf>,
    pub tailwind_config_file: Option<Utf8PathBuf>,
    /// assets dir. content will be copied to the target/site dir
    pub assets_dir: Option<Utf8PathBuf>,
    /// js dir. changes triggers rebuilds.
    pub js_dir: Option<Utf8PathBuf>,
    #[serde(default = "default_js_minify")]
    pub js_minify: bool,
    /// additional files to watch. changes triggers rebuilds.
    pub watch_additional_files: Option<Vec<Utf8PathBuf>>,
    #[serde(default = "default_reload_port")]
    pub reload_port: u16,
    /// command for launching end-2-end integration tests
    pub end2end_cmd: Option<String>,
    /// the dir used when launching end-2-end integration tests
    pub end2end_dir: Option<Utf8PathBuf>,
    #[serde(default = "default_browserquery")]
    pub browserquery: String,
    /// the bin target to use for building the server
    #[serde(default)]
    pub bin_target: String,
    /// the bin output target triple to use for building the server
    pub bin_target_triple: Option<String>,
    /// the directory to put the generated server artifacts
    pub bin_target_dir: Option<String>,
    /// the command to run instead of "cargo" when building the server
    pub bin_cargo_command: Option<String>,
    /// cargo flags to pass to cargo when running the server. Overriden by bin_cargo_command
    pub bin_cargo_args: Option<Vec<String>>,
    /// An optional override, if you've changed the name of your bin file in your project you'll need to set it here as well.
    pub bin_exe_name: Option<String>,
    #[serde(default)]
    pub features: Vec<String>,
    #[serde(default)]
    pub lib_features: Vec<String>,
    #[serde(default)]
    pub lib_default_features: bool,
    /// cargo flags to pass to cargo when building the WASM frontend
    pub lib_cargo_args: Option<Vec<String>>,
    #[serde(default)]
    pub bin_features: Vec<String>,
    #[serde(default)]
    pub bin_default_features: bool,

    #[serde(skip)]
    pub config_dir: Utf8PathBuf,
    #[serde(skip)]
    pub tmp_dir: Utf8PathBuf,

    /// Deprecated. Keeping this here to warn users to remove it in case they have it in their config.
    #[deprecated = "This option is deprecated since cargo-leptos 0.2.3 (when it became unconditionally enabled). You may remove it from your config."]
    pub separate_front_target_dir: Option<bool>,

    // Profiles
    pub lib_profile_dev: Option<String>,
    pub lib_profile_release: Option<String>,
    pub bin_profile_dev: Option<String>,
    pub bin_profile_release: Option<String>,
}

impl ProjectConfig {
    fn parse(
        dir: &Utf8Path,
        metadata: &serde_json::Value,
        cargo_metadata: &Metadata,
    ) -> Result<Self> {
        let mut conf: ProjectConfig = serde_json::from_value(metadata.clone())?;
        conf.config_dir = dir.to_path_buf();
        conf.tmp_dir = cargo_metadata.target_directory.join("tmp");
        let dotenvs = load_dotenvs(dir)?;
        overlay_env(&mut conf, dotenvs)?;
        if conf.site_root == "/"
            || conf.site_root == "."
            || conf.site_root == CARGO_TARGET_DIR_MARKER
            || conf.site_root == CARGO_BUILD_TARGET_DIR_MARKER
        {
            bail!(
                "site-root cannot be '{}'. All the content is erased when building the site.",
                conf.site_root
            );
        }
        if conf.site_root.starts_with(CARGO_TARGET_DIR_MARKER) {
            conf.site_root = {
                let mut path = cargo_metadata.target_directory.clone();
                // unwrap() should be safe because we just checked
                let sub = conf
                    .site_root
                    .unbase(CARGO_TARGET_DIR_MARKER.into())
                    .unwrap();
                path.push(sub);
                path
            };
        }
        if conf.site_root.starts_with(CARGO_BUILD_TARGET_DIR_MARKER) {
            conf.site_root = {
                let mut path = cargo_metadata.target_directory.clone();
                // unwrap() should be safe because we just checked
                let sub = conf
                    .site_root
                    .unbase(CARGO_BUILD_TARGET_DIR_MARKER.into())
                    .unwrap();
                path.push(sub);
                path
            };
        }
        if conf.site_addr.port() == conf.reload_port {
            bail!(
                "The site-addr port and reload-port cannot be the same: {}",
                conf.reload_port
            );
        }

        #[allow(deprecated)]
        if conf.separate_front_target_dir.is_some() {
            log::warn!("Deprecated: the `separate-front-target-dir` option is deprecated since cargo-leptos 0.2.3");
            log::warn!("It is now unconditionally enabled; you can remove it from your Cargo.toml")
        }

        Ok(conf)
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct ProjectDefinition {
    name: String,
    pub bin_package: String,
    pub lib_package: String,
}
impl ProjectDefinition {
    fn from_workspace(
        metadata: &serde_json::Value,
        dir: &Utf8Path,
        cargo_metadata: &Metadata,
    ) -> Result<Vec<(Self, ProjectConfig)>> {
        let mut found = Vec::new();
        if let Some(arr) = metadata.as_array() {
            for section in arr {
                let conf = ProjectConfig::parse(dir, section, cargo_metadata)?;
                let def: Self = serde_json::from_value(section.clone())?;
                found.push((def, conf))
            }
        }
        Ok(found)
    }

    fn from_project(
        package: &Package,
        metadata: &serde_json::Value,
        dir: &Utf8Path,
        cargo_metadata: &Metadata,
    ) -> Result<(Self, ProjectConfig)> {
        let conf = ProjectConfig::parse(dir, metadata, cargo_metadata)?;

        ensure!(
            package.cdylib_target().is_some(),
            "Cargo.toml has leptos metadata but is missing a cdylib library target. {}",
            GRAY.paint(package.manifest_path.as_str())
        );
        ensure!(
            package.has_bin_target(),
            "Cargo.toml has leptos metadata but is missing a bin target. {}",
            GRAY.paint(package.manifest_path.as_str())
        );

        Ok((
            ProjectDefinition {
                name: package.name.to_string(),
                bin_package: package.name.to_string(),
                lib_package: package.name.to_string(),
            },
            conf,
        ))
    }

    fn parse(metadata: &Metadata) -> Result<Vec<(Self, ProjectConfig)>> {
        let workspace_dir = &metadata.workspace_root;
        let mut found: Vec<(Self, ProjectConfig)> =
            if let Some(md) = leptos_metadata(&metadata.workspace_metadata) {
                Self::from_workspace(md, &Utf8PathBuf::default(), metadata)?
            } else {
                Default::default()
            };

        for package in metadata.workspace_packages() {
            let dir = package.manifest_path.unbase(workspace_dir)?.without_last();

            if let Some(leptos_metadata) = leptos_metadata(&package.metadata) {
                found.push(Self::from_project(
                    package,
                    leptos_metadata,
                    &dir,
                    metadata,
                )?);
            }
        }
        Ok(found)
    }
}

fn leptos_metadata(metadata: &serde_json::Value) -> Option<&serde_json::Value> {
    metadata.as_object().and_then(|o| o.get("leptos"))
}

fn default_site_addr() -> SocketAddr {
    SocketAddr::new([127, 0, 0, 1].into(), 3000)
}

fn default_pkg_dir() -> Utf8PathBuf {
    Utf8PathBuf::from("pkg")
}

fn default_site_root() -> Utf8PathBuf {
    Utf8PathBuf::from(CARGO_TARGET_DIR_MARKER).join("site")
}

fn default_reload_port() -> u16 {
    3001
}

fn default_browserquery() -> String {
    "defaults".to_string()
}

fn default_hash_files() -> bool {
    false
}

fn default_js_minify() -> bool {
    true
}