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
use camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::{Metadata, Package};
use serde::Deserialize;
use std::{fmt::Debug, net::SocketAddr, sync::Arc};

use crate::{
    config::lib_package::LibPackage,
    ext::{
        anyhow::{bail, Result},
        PathBufExt, PathExt,
    },
    service::site::Site,
};

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

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 hot_reload: bool,
    pub site: Arc<Site>,
    pub end2end: Option<End2EndConfig>,
    pub assets: Option<AssetsConfig>,
    pub js_dir: Utf8PathBuf,
}

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("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) -> 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 proj = Project {
                working_dir: metadata.workspace_root.clone(),
                name: project.name.clone(),
                lib,
                bin: BinPackage::resolve(cli, metadata, &project, &config)?,
                style: StyleConfig::new(&config)?,
                watch,
                release: cli.release,
                hot_reload: cli.hot_reload,
                site: Arc::new(Site::new(&config)),
                end2end: End2EndConfig::resolve(&config),
                assets: AssetsConfig::resolve(&config),
                js_dir,
            };
            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![
            ("GLORY_OUTPUT_NAME", self.lib.output_name.to_string()),
            ("GLORY_SITE_ROOT", self.site.root_dir.to_string()),
            ("GLORY_SITE_PKG_DIR", self.site.pkg_dir.to_string()),
            ("GLORY_SITE_ADDR", self.site.addr.to_string()),
            ("GLORY_RELOAD_PORT", self.site.reload.port().to_string()),
            ("GLORY_LIB_DIR", self.lib.rel_dir.to_string()),
            ("GLORY_BIN_DIR", self.bin.rel_dir.to_string()),
        ];
        if self.watch {
            vec.push(("GLORY_WATCH", "ON".to_string()))
        }
        vec
    }
}

#[derive(Deserialize, Debug)]
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>,
    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_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_browser_query")]
    pub browser_query: 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>,
    #[serde(default)]
    pub features: Vec<String>,
    #[serde(default)]
    pub lib_features: Vec<String>,
    #[serde(default)]
    pub lib_default_features: bool,
    #[serde(default)]
    pub bin_features: Vec<String>,
    #[serde(default)]
    pub bin_default_features: bool,

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

    // 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) -> Result<Self> {
        let mut conf: ProjectConfig = serde_json::from_value(metadata.clone())?;
        conf.config_dir = dir.to_path_buf();
        let dotenvs = load_dotenvs(dir)?;
        overlay_env(&mut conf, dotenvs)?;
        if conf.site_root == "/" || conf.site_root == "." {
            bail!(
                "site-root cannot be '{}'. All the content is erased when building the site.",
                conf.site_root
            );
        }
        if conf.site_addr.port() == conf.reload_port {
            bail!("The site-addr port and reload-port cannot be the same: {}", conf.reload_port);
        }
        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) -> 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)?;
                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) -> Result<(Self, ProjectConfig)> {
        let conf = ProjectConfig::parse(dir, metadata)?;

        // ensure!(
        //     package.cdylib_target().is_some(),
        //     "Cargo.toml has glory metadata but is missing a cdylib library target. {}",
        //     GRAY.paint(package.manifest_path.as_str())
        // );
        // ensure!(
        //     package.has_bin_target(),
        //     "Cargo.toml has glory 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) = glory_metadata(&metadata.workspace_metadata) {
            Self::from_workspace(md, &Utf8PathBuf::default())?
        } else {
            Default::default()
        };

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

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

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

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("target").join("site")
}

fn default_reload_port() -> u16 {
    3001
}

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