-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcli.rs
379 lines (333 loc) · 10.9 KB
/
cli.rs
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
use std::env::set_current_dir;
use std::path::PathBuf;
use clap::{builder::PossibleValue, Parser, Subcommand};
use eyre::{bail, Result};
use crate::cmd;
use crate::net;
#[cfg(test)]
use mockall::{automock, predicate::*};
#[cfg(test)]
use tokio::{fs::canonicalize, fs::remove_dir_all};
#[derive(Parser)]
#[command(
author = "NTBBloodbath",
version,
disable_version_flag = true,
about = "The monolithic Norg static site generator"
)]
struct Cli {
/// Print version
#[arg(short = 'v', long, action = clap::builder::ArgAction::Version)]
version: (),
/// Operate on the project in the given directory.
#[arg(short = 'd', long = "dir", global = true)]
project_dir: Option<PathBuf>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Clone)]
enum Commands {
/// Initialize a new Norgolith site
Init {
#[arg(
long,
default_value_t = true,
overrides_with = "_no_prompt",
help = "Whether to prompt for site info"
)]
prompt: bool,
#[arg(long = "no-prompt")]
_no_prompt: bool,
/// Site name
name: Option<String>,
},
/// Theme management
Theme {
#[command(subcommand)]
subcommand: cmd::ThemeCommands,
},
/// Build a site for development
Serve {
#[arg(short = 'p', long, default_value_t = 3030, help = "Port to be used")]
port: u16,
#[arg(
long,
default_value_t = true,
overrides_with = "_no_drafts",
help = "Whether to serve draft content"
)]
drafts: bool,
#[arg(long = "no-drafts")]
_no_drafts: bool,
// TODO: add SocketAddr parsing if host is a String, similar to Vite
#[arg(
short = 'e',
long,
default_value_t = false,
help = "Expose site to LAN network"
)]
host: bool,
#[arg(
short = 'o',
long,
default_value_t = false,
help = "Open the development server in your browser"
)]
open: bool,
},
/// Create a new asset in the site and optionally open it using your preferred system editor.
/// e.g. 'new -k norg post1.norg' -> 'content/post1.norg'
New {
#[arg(
short = 'o',
long,
default_value_t = false,
help = "Open the new file using your preferred system editor"
)]
open: bool,
#[arg(
short = 'k',
long,
default_value = "norg",
help = "type of asset",
value_parser = [
PossibleValue::new("norg").help("New norg file"),
PossibleValue::new("css").help("New CSS stylesheet"),
PossibleValue::new("js").help("New JS script")
]
)]
kind: Option<String>,
/// Asset name, e.g. 'post1.norg' or 'hello.js'
name: Option<String>,
},
/// Build a site for production
Build {
#[arg(
short = 'm',
long,
default_value_t = true,
overrides_with = "_no_minify",
help = "Minify the produced assets"
)]
minify: bool,
#[arg(long = "no-minify")]
_no_minify: bool,
},
}
/// Asynchronously parse the command-line arguments and executes the corresponding subcommand
///
/// # Returns:
/// A `Result<()>` indicating success or error. On error, the context message will provide information on why the subcommand failed.
pub async fn start() -> Result<()> {
let cli = Cli::parse();
if let Some(dir) = cli.project_dir {
set_current_dir(dir)?;
}
match &cli.command {
Commands::Init {
name,
prompt: _,
_no_prompt,
} => init_site(name.as_ref(), !_no_prompt).await?,
Commands::Theme { subcommand } => theme_handle(subcommand).await?,
Commands::Serve {
port,
drafts: _,
_no_drafts,
host,
open,
} => check_and_serve(*port, !_no_drafts, *open, *host).await?,
Commands::Build { minify: _, _no_minify } => build_site(!_no_minify).await?,
Commands::New { kind, name, open } => {
new_asset(kind.as_ref(), name.as_ref(), *open).await?
} // _ => bail!("Unsupported command"),
}
Ok(())
}
/// Initializes a new Norgolith site.
///
/// # Arguments:
/// * name: An optional name for the site. If `None` is provided, an error will be returned.
///
/// # Returns:
/// A `Result<()>` indicating success or error. On error, the context message will provide information on why the site could not be initialized.
async fn init_site(name: Option<&String>, prompt: bool) -> Result<()> {
if let Some(name) = name {
cmd::init(name, prompt).await?;
} else {
bail!("Missing name for the site: could not initialize the new Norgolith site");
}
Ok(())
}
/// Builds a Norgolith site for production.
///
/// # Arguments:
/// * minify: Whether to minify the produced artifacts. Defaults to `true`.
///
/// # Returns:
/// A `Result<()>` indicating success or error.
async fn build_site(minify: bool) -> Result<()> {
let build_config = match crate::fs::find_config_file().await? {
Some(config_path) => {
let config_content = tokio::fs::read_to_string(config_path).await?;
toml::from_str(&config_content)?
}
None => crate::config::SiteConfig::default(),
}
.build
.unwrap_or_default();
// Merge CLI and config values
// CLI options have higher priority than config
// config has higher priority than defaults
let minify = minify || build_config.minify;
cmd::build(minify).await
}
/// Checks port availability and starts the development server.
///
/// # Arguments:
/// * port: The port number to use for the server.
/// * drafts: Whether to serve draft content.
/// * open: Whether to open the development server in the system web browser.
/// * host: Whether to expose local server to LAN network.
///
/// # Returns:
/// A `Result<()>` indicating success or error. On error, the context message
/// will provide information on why the development server could not be initialized.
async fn check_and_serve(port: u16, drafts: bool, open: bool, host: bool) -> Result<()> {
let serve_config = match crate::fs::find_config_file().await? {
Some(config_path) => {
let config_content = tokio::fs::read_to_string(config_path).await?;
toml::from_str(&config_content)?
}
None => crate::config::SiteConfig::default(),
}
.serve
.unwrap_or_default();
// Merge CLI and config values
// CLI options have higher priority than config
// config has higher priority than defaults
let port = if port != 3030 {
port
} else if serve_config.port == 0 {
3030
} else {
serve_config.port
};
let drafts = drafts || serve_config.drafts;
let host = host || serve_config.host;
let open = open || serve_config.open;
if !net::is_port_available(port) {
let port_msg = if port == 3030 {
"default Norgolith port (3030)".to_string()
} else {
format!("requested port ({})", port)
};
bail!("Could not initialize the development server: failed to open listener, perhaps the {} is busy?", port_msg);
}
cmd::serve(port, drafts, open, host).await
}
async fn theme_handle(subcommand: &cmd::ThemeCommands) -> Result<()> {
cmd::theme(subcommand).await
}
/// Creates a new asset with the given kind and name.
///
/// # Arguments
///
/// * `kind`: Optional asset type. Defaults to "content". Valid values are "content", "css", and "js".
/// * `name`: Required asset name including the extension.
///
/// # Errors
///
/// Returns an error if the asset name is missing.
///
/// # Example
///
/// ```rust
/// use crate::new_asset;
///
/// async fn main() -> Result<()> {
/// new_asset(Some(&String::from("css")), Some(&String::from("style.css"))).await?;
/// Ok(())
/// }
/// ```
async fn new_asset(kind: Option<&String>, name: Option<&String>, open: bool) -> Result<()> {
let asset_type = kind.unwrap_or(&String::from("content")).to_owned();
if ![
String::from("js"),
String::from("css"),
String::from("norg"),
]
.contains(&asset_type)
{
bail!("Unable to create site asset: unknown asset type provided");
}
match name {
Some(name) => cmd::new(&asset_type, name, open).await,
None => bail!("Unable to create site asset: missing name for the asset"),
}
}
#[cfg(test)]
mod tests {
use super::*;
// init_site tests
#[tokio::test]
async fn test_init_site_with_name() {
let test_name = String::from("my-site");
let result = init_site(Some(&test_name), false).await;
assert!(result.is_ok());
// Cleanup
remove_dir_all(test_name).await.unwrap();
}
#[tokio::test]
async fn test_init_site_without_name() {
let result = init_site(None, false).await;
assert!(result.is_err());
assert!(result
.unwrap_err()
.root_cause()
.to_string()
.contains("Missing name for the site"));
}
#[cfg_attr(test, automock)]
trait NetTrait {
fn is_port_available(&self, port: u16) -> bool;
}
// check_and_serve tests
#[tokio::test]
#[cfg_attr(feature = "ci", ignore)]
async fn test_check_and_serve_available_port() {
let mut mock_net = MockNetTrait::new();
mock_net
.expect_is_port_available()
.with(eq(8080))
.times(1)
.returning(|_| true);
assert!(mock_net.is_port_available(8080));
}
#[tokio::test]
#[cfg_attr(feature = "ci", ignore)]
async fn test_check_and_serve_unavailable_port() -> Result<()> {
// Bind port
let temp_listener = std::net::TcpListener::bind(("127.0.0.1", 3030))?;
let port = temp_listener.local_addr()?.port();
// Create temporal site
let test_site_dir = String::from("my-unavailable-site");
init_site(Some(&test_site_dir), false).await?;
// Save current directory as the previous directory to restore it later
let previous_dir = std::env::current_dir()?;
// Enter the test directory
std::env::set_current_dir(canonicalize(test_site_dir.clone()).await?)?;
let result = check_and_serve(port, false, false, false).await;
assert!(result.is_err());
assert!(result
.unwrap_err()
.root_cause()
.to_string()
.contains("failed to open listener"));
// Restore previous directory
std::env::set_current_dir(previous_dir)?;
// Cleanup test directory and test file
remove_dir_all(test_site_dir).await?;
Ok(())
}
}