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
|
use std::{
io::Write,
path::{Path, PathBuf},
};
use clap::Parser;
use color_eyre::{owo_colors::OwoColorize, Result};
mod error;
mod luax;
mod server;
#[derive(Debug, Clone, clap::Parser)]
#[clap(about = "⛱️ A LuaX web framework")]
enum Args {
#[clap(
name = "serve",
about = "Serve a directory of LuaX files in production mode"
)]
Serve {
#[clap(
short = 'C',
long = "change-dir",
default_value = ".",
help = "The directory to serve LuaX files from"
)]
change_dir: std::path::PathBuf,
#[clap(
short = 'p',
long = "port",
default_value = "4310",
help = "The port to serve on"
)]
port: u16,
#[clap(
short = 'l',
long = "local",
default_value = "false",
help = "Do not use a temporary directory for preprocessing"
)]
local: bool,
},
#[clap(name = "build", about = "Build a directory of LuaX files")]
Build {
#[clap(
short = 'C',
long = "change-dir",
default_value = ".",
help = "The directory to build LuaX files from"
)]
change_dir: std::path::PathBuf,
#[clap(
short = 'o',
long = "output",
default_value = ".",
help = "The directory to output the built files to"
)]
output_dir: std::path::PathBuf,
},
#[clap(
name = "dev",
about = "Serve a directory of LuaX files in development mode"
)]
Dev {
#[clap(
short = 'C',
long = "change-dir",
default_value = ".",
help = "The directory to serve LuaX files from"
)]
change_dir: std::path::PathBuf,
#[clap(
short = 'P',
long = "public-dir",
default_value = ".",
help = "The static files directory to serve"
)]
public_dir: std::path::PathBuf,
#[clap(
short = 'p',
long = "port",
default_value = "4310",
help = "The port to serve on"
)]
port: u16,
#[clap(
short = 'l',
long = "local",
default_value = "false",
help = "Do not use a temporary directory for preprocessing"
)]
local: bool,
},
#[clap(name = "new", about = "Create a new project")]
New {
#[clap(help = "The name of the project")]
name: String,
},
#[clap(
name = "init",
about = "Initialize a new project in the current directory"
)]
Init,
}
#[tokio::main]
async fn main() -> color_eyre::Result<()> {
color_eyre::install().unwrap();
let args = Args::parse();
match args {
Args::Serve {
change_dir,
port,
local,
} => {
if !change_dir.is_dir() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{} is not a directory", change_dir.display()),
)
.into());
}
println!("🌴 Project root: {}", change_dir.display().bright_yellow());
if local {
serve_locally(change_dir, false, port, None).await
} else {
serve_from_temp(change_dir, false, port, None).await
}
}
Args::Build {
change_dir,
output_dir,
} => build(change_dir, output_dir),
Args::Dev {
change_dir,
public_dir,
port,
local,
} => {
if !change_dir.is_dir() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{} is not a directory", change_dir.display()),
)
.into());
}
println!("🌴 Project root: {}", change_dir.display().bright_yellow());
if !public_dir.is_dir() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{} is not a directory", public_dir.display()),
)
.into());
}
println!(
"🌴 Public directory: {}",
public_dir.display().bright_yellow()
);
let public_dir = Some(public_dir.canonicalize()?);
if local {
serve_locally(change_dir, true, port, public_dir).await
} else {
serve_from_temp(change_dir, true, port, public_dir).await
}
}
Args::New { name } => create_project(&name),
Args::Init => init_project(),
}
}
async fn serve_locally(
change_dir: PathBuf,
dev_mode: bool,
port: u16,
public_dir: Option<PathBuf>,
) -> Result<()> {
println!("🌴 Running in local mode");
std::env::set_current_dir(&change_dir)?;
preprocess_current_dir().await?;
ensure_entry_point().await?;
serve(dev_mode, port, public_dir).await
}
async fn serve_from_temp(
change_dir: PathBuf,
dev_mode: bool,
port: u16,
public_dir: Option<PathBuf>,
) -> Result<()> {
// Create a /tmp/reluax-XXXXXX directory for the server to pre-process files in.
let tmp_dir = tempfile::Builder::new()
.prefix("reluax-")
.tempdir()
.unwrap();
if !tmp_dir.path().is_dir() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{} is not a directory", tmp_dir.path().display()),
)
.into());
}
println!(
"⏲️ Created temporary directory {}",
tmp_dir.path().display().bright_blue()
);
println!(
"⏲️ Will serve Lua from {}",
tmp_dir.path().display().bright_blue()
);
// copy all files from the current directory to the temporary directory recursively.
let copied = recurse_copy(&change_dir, tmp_dir.path())?;
println!("⏲️ {} files copied", copied.bright_green());
std::env::set_current_dir(tmp_dir.path())?;
preprocess_current_dir().await?;
ensure_entry_point().await?;
serve(dev_mode, port, public_dir).await
}
async fn preprocess_current_dir() -> Result<()> {
let current_dir = std::env::current_dir()?;
let preprocessed = luax::preprocess_dir(current_dir.as_path(), current_dir.as_path())?;
println!(
"⛱️ {} Reluax files preprocessed!",
preprocessed.bright_green()
);
Ok(())
}
async fn ensure_entry_point() -> Result<()> {
let entry = PathBuf::from("reluax.lua");
if !entry.is_file() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{} is not a file", entry.display()),
)
.into());
}
Ok(())
}
async fn serve(dev_mode: bool, port: u16, public_dir: Option<PathBuf>) -> Result<()> {
println!("📦 Building Lua state...");
let lua = luax::prepare_lua(dev_mode)?;
println!("🛫 Starting server on port {}...", port);
server::Server::serve(lua, port, public_dir).await
}
fn recurse_copy(from: &Path, to: &Path) -> Result<usize> {
let mut copied = 0;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let path = entry.path();
let file_name = path.file_name().unwrap();
let to = to.join(file_name);
if path.is_dir() {
std::fs::create_dir(&to)?;
copied += recurse_copy(&path, &to)?;
} else {
std::fs::copy(&path, &to)?;
copied += 1;
}
}
Ok(copied)
}
fn create_project(name: &str) -> Result<()> {
let dir = PathBuf::from(name);
if dir.is_dir() {
println!("🛑 Directory {} already exists", dir.display().bright_red());
return Ok(());
}
std::fs::create_dir(&dir)?;
std::env::set_current_dir(&dir)?;
write_templates(name)?;
println!("🌴 Created project {}", name.bright_yellow());
println!(
"🛠️ To start a development server, change to the {} directory and run {}.",
name.bright_yellow(),
"reluax dev".bright_green()
);
Ok(())
}
fn init_project() -> Result<()> {
let dir = std::env::current_dir()?;
if !dir.is_dir() {
println!("🛑 Directory {} does not exist", dir.display().bright_red());
return Ok(());
}
let name = dir.file_name().unwrap().to_str().unwrap();
write_templates(name)?;
println!("🌴 Initialized project {}", name.bright_yellow());
println!(
"🛠️ To start a development server, run {}.",
"reluax dev".bright_green()
);
Ok(())
}
fn write_templates(name: &str) -> Result<()> {
let mut file = std::fs::File::create("reluax.luax")?;
file.write_all(
include_str!("../templates/reluax.luax")
.replace("PROJECT_NAME", name)
.as_bytes(),
)?;
let mut file = std::fs::File::create("index.luax")?;
file.write_all(
include_str!("../templates/index.luax")
.replace("PROJECT_NAME", name)
.as_bytes(),
)?;
let mut file = std::fs::File::create("style.css")?;
file.write_all(include_str!("../templates/style.css").as_bytes())?;
Ok(())
}
fn build(change_dir: PathBuf, output_dir: PathBuf) -> Result<()> {
if !change_dir.is_dir() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{} is not a directory", change_dir.display()),
)
.into());
}
println!("🌴 Project root: {}", change_dir.display().bright_yellow());
if !output_dir.is_dir() {
std::fs::create_dir(&output_dir)?;
}
println!(
"🌴 Output directory: {}",
output_dir.display().bright_yellow()
);
std::env::set_current_dir(&change_dir)?;
println!("📦 Preprocessing LuaX files...");
let built = luax::preprocess_dir(&change_dir, &output_dir)?;
println!("📦 {} LuaX files preprocessed!", built.bright_green());
Ok(())
}
|