forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.rs
More file actions
296 lines (275 loc) · 10.1 KB
/
Copy pathcommands.rs
File metadata and controls
296 lines (275 loc) · 10.1 KB
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
//! `nula` CLI subcommands: `new`, `build`, `test`, `run`.
//!
//! All commands operate on the package rooted at the current directory
//! (except `new`, which creates one). Compiling and running is delegated to
//! the current `nulang` executable — the package manager only resolves
//! dependencies and picks the entry point.
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::package::manifest::{Manifest, MANIFEST_FILE};
use crate::package::resolver::resolve;
use crate::types::{NuError, NuResult, Span};
/// Dispatch a `nula` invocation (`args` excludes the leading `nula`).
pub fn run(args: &[String]) -> NuResult<()> {
match args.first().map(String::as_str) {
Some("new") => cmd_new(args.get(1).map(String::as_str)),
Some("build") => cmd_build(),
Some("build-wasm") => cmd_build_wasm(),
Some("test") => cmd_test(),
Some("run") => cmd_run(),
Some("--help") | Some("-h") => {
print_usage();
Ok(())
}
Some(other) => Err(NuError::PackageError {
msg: format!(
"unknown nula subcommand '{}' (expected new, build, build-wasm, test, or run)",
other
),
span: Span::default(),
}),
None => {
print_usage();
Ok(())
}
}
}
fn print_usage() {
println!("nula — the Nulang package manager");
println!();
println!("Usage: nulang nula <COMMAND>");
println!();
println!("Commands:");
println!(" new Scaffold a new package directory");
println!(" build Resolve dependencies and type-check the package");
println!(" build-wasm Build package to .wasm + .cwasm (AOT, requires wasmtime)");
println!(" test Run every .nula file in the package's tests/ directory");
println!(" run Build and run the package entry point");
}
/// `nula new <name>`: scaffold a package directory.
fn cmd_new(path_arg: Option<&str>) -> NuResult<()> {
let path_str = path_arg.ok_or_else(|| NuError::PackageError {
msg: "nula new requires a package name or path".to_string(),
span: Span::default(),
})?;
let dir = PathBuf::from(path_str);
let name = dir
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| NuError::PackageError {
msg: format!("invalid path '{}' — cannot extract package name", path_str),
span: Span::default(),
})?;
if name.is_empty()
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return Err(NuError::PackageError {
msg: format!(
"invalid package name '{}' (use letters, digits, '-' or '_')",
name
),
span: Span::default(),
});
}
if dir.exists() {
return Err(NuError::PackageError {
msg: format!("directory '{}' already exists", dir.display()),
span: Span::default(),
});
}
scaffold_package(&dir, name)?;
println!("Created package '{}' at '{}'", name, dir.display());
Ok(())
}
/// Write the `Nulang.toml` + `src/main.nula` scaffold for a new package.
fn scaffold_package(dir: &Path, name: &str) -> NuResult<()> {
let src_dir = dir.join("src");
std::fs::create_dir_all(&src_dir).map_err(|e| NuError::PackageError {
msg: format!("cannot create {}: {}", src_dir.display(), e),
span: Span::default(),
})?;
std::fs::write(
dir.join(MANIFEST_FILE),
format!(
"[package]\nname = \"{}\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
name
),
)
.map_err(|e| NuError::PackageError {
msg: format!("cannot write {}: {}", MANIFEST_FILE, e),
span: Span::default(),
})?;
std::fs::write(
src_dir.join("main.nula"),
"// Run with: nulang nula run\n\nperform IO.print(\"Hello from Nulang!\")\n",
)
.map_err(|e| NuError::PackageError {
msg: format!("cannot write main.nula: {}", e),
span: Span::default(),
})?;
Ok(())
}
/// Resolve the package in the current directory, write `Nulang.lock`, and
/// return the entry point path.
fn prepare_package() -> NuResult<PathBuf> {
let root = std::env::current_dir().map_err(|e| NuError::PackageError {
msg: format!("cannot read current directory: {}", e),
span: Span::default(),
})?;
let manifest = Manifest::load(&root)?;
let resolution = resolve(&root, &manifest)?;
resolution.to_lockfile().save(&root)?;
let entry = root.join(&manifest.package.entry);
if !entry.exists() {
return Err(NuError::PackageError {
msg: format!("entry point {} not found", entry.display()),
span: Span::default(),
});
}
Ok(entry)
}
/// Run the current `nulang` executable with `args`, inheriting stdio.
fn nulang_exe(args: &[&str]) -> NuResult<()> {
let exe = std::env::current_exe().map_err(|e| NuError::PackageError {
msg: format!("cannot locate nulang executable: {}", e),
span: Span::default(),
})?;
let status = Command::new(exe)
.args(args)
.status()
.map_err(|e| NuError::PackageError {
msg: format!("failed to run nulang: {}", e),
span: Span::default(),
})?;
if !status.success() {
return Err(NuError::PackageError {
msg: format!("nulang {} failed with status {}", args.join(" "), status),
span: Span::default(),
});
}
Ok(())
}
/// `nula build`: resolve dependencies, write the lockfile, type-check entry.
fn cmd_build() -> NuResult<()> {
let entry = prepare_package()?;
let entry_str = entry.to_string_lossy().into_owned();
nulang_exe(&["--check", &entry_str])?;
println!("Build finished.");
Ok(())
}
/// `nula build-wasm`: compile package to .wasm + AOT .cwasm.
fn cmd_build_wasm() -> NuResult<()> {
let entry = prepare_package()?;
let entry_str = entry.to_string_lossy().into_owned();
nulang_exe(&["--backend", "wasm-aot", &entry_str])?;
println!("WASM AOT build finished.");
Ok(())
}
/// `nula run`: build, then execute the entry point.
fn cmd_run() -> NuResult<()> {
let entry = prepare_package()?;
let entry_str = entry.to_string_lossy().into_owned();
nulang_exe(&[&entry_str])
}
/// `nula test`: run every `.nula` file under the package's `tests/` directory.
fn cmd_test() -> NuResult<()> {
let _entry = prepare_package()?;
let tests_dir = std::env::current_dir()
.map_err(|e| NuError::PackageError {
msg: format!("cannot read current directory: {}", e),
span: Span::default(),
})?
.join("tests");
let mut test_files: Vec<PathBuf> = match std::fs::read_dir(&tests_dir) {
Ok(entries) => entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|ext| ext == "nula"))
.collect(),
Err(_) => Vec::new(),
};
test_files.sort();
if test_files.is_empty() {
println!(
"No tests found ({} does not exist or has no .nula files).",
tests_dir.display()
);
return Ok(());
}
let mut failed = 0;
for file in &test_files {
let file_str = file.to_string_lossy().into_owned();
match nulang_exe(&[&file_str]) {
Ok(()) => println!("ok {}", file.display()),
Err(e) => {
failed += 1;
println!("FAIL {} ({})", file.display(), e);
}
}
}
println!("{} passed, {} failed", test_files.len() - failed, failed);
if failed > 0 {
return Err(NuError::PackageError {
msg: format!("{} test(s) failed", failed),
span: Span::default(),
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::package::manifest::DEFAULT_ENTRY;
#[test]
fn test_scaffold_package_creates_valid_manifest() {
let dir = std::env::temp_dir().join(format!("nulang_nula_new_test_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
scaffold_package(&dir, "my-app").expect("scaffold should succeed");
let manifest = Manifest::load(&dir).expect("scaffolded manifest should parse");
assert_eq!(manifest.package.name, "my-app");
assert_eq!(manifest.package.version, "0.1.0");
assert_eq!(manifest.package.entry, DEFAULT_ENTRY);
assert!(dir.join(DEFAULT_ENTRY).exists());
let resolution = resolve(&dir, &manifest).expect("scaffold should resolve");
assert_eq!(resolution.root().name, "my-app");
assert!(resolution.to_lockfile().package.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_cmd_new_rejects_invalid_name() {
// Path with invalid package name (contains '.')
let err = cmd_new(Some("./my.app")).expect_err("dots in name are rejected");
assert!(matches!(err, NuError::PackageError { msg: _, span: _ }));
let err = cmd_new(None).expect_err("missing name is rejected");
assert!(matches!(err, NuError::PackageError { msg: _, span: _ }));
}
#[test]
fn test_cmd_new_accepts_path() {
let dir = std::env::temp_dir().join(format!("nulang_new_path_test_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path_str = dir.to_str().expect("temp dir should be valid UTF-8");
let result = cmd_new(Some(path_str));
assert!(
result.is_ok(),
"path with valid basename should succeed: {:?}",
result.err()
);
assert!(dir.join("Nulang.toml").exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_print_usage_does_not_panic() {
print_usage();
}
#[test]
fn test_nulang_exe_rejects_invalid_args() {
let result = nulang_exe(&["--nonexistent-flag"]);
assert!(result.is_err(), "unknown flags should fail");
}
#[test]
fn test_cmd_test_fails_in_non_package_dir() {
let result = cmd_test();
assert!(result.is_err(), "test outside package should fail");
}
}