cpkg 0.6.5

A dead simple C package manager.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use clap::{Parser, Subcommand};
use indoc::indoc;
use colored::Colorize;

mod compiler;
mod docgen;
mod format;

/// Dead simple C package manager
#[derive(Parser)]
#[command(version, about, long_about = None)]
#[command(arg_required_else_help = true)]
struct Cli {
	#[command(subcommand)]
	command: Commands,
}

#[derive(Subcommand)]
enum Commands {
	#[command(about = "Creates a template project at a given directory.")]
	New {
		/// Name of folder to create new project inside of.
		name: String
	},
	#[command(about = "Initializes a template project at the cwd.\n\x1b[31m")]
	Init,

	#[command(about = "Builds the project to the target directory using gcc or clang, if available.\x1b[31m")]
	Build,

	#[command(about = "Runs the project's main file, or a standalone c file.\x1b[31m")]
	Run {
		path: Option<String>
	},

	#[command(about = "Runs the project's test suite.\n\x1b[33m")]
	Test {
		#[arg(short, long)]
		print: bool
	},

	#[command(about = "Removes compiled programs from the project.\x1b[33m")]
	Clean,

	#[command(about = "Generates documentation for the project using doxygen, if available.\x1b[33m")]
	Doc {
		#[arg(short, long)]
		open: bool
	},

	#[command(about = "Formats the project's code using clang-format, if available.\n\x1b[36m")]
	Format,

	#[command(about = "Creates a REPL with gcc or clang, if available.\x1b[36m")]
	Repl,

	#[command(about = "Updates to the latest version of cpkg.\n\x1b[35m")]
	Upgrade
}

fn init_project(proj: &std::path::Path) -> std::io::Result<()> {
	let src = proj.join("src");
	std::fs::create_dir(&src)?;

	let main = src.join("main.c");
	std::fs::write(&main, indoc! {r#"
		#include <stdio.h>

		int main() {
			printf("Hello, world!\n");
			return 0;
		}
	"#})?;

	let tests = proj.join("tests");
	std::fs::create_dir(&tests)?;

	let main_test = tests.join("main.test.c");
	std::fs::write(main_test, indoc!{r#"
		#include <assert.h>

		int main() {
			assert( (1 + 2 == 3) && "C is broken" );
		}
	"#})?;

	let config = proj.join("cpkg.toml");
	let name = proj.file_name().unwrap().to_string_lossy();
	std::fs::write(config, indoc::formatdoc! {r#"
		[package]
		name = "{name}"

		[dependencies]
	"#})?;

	if which::which("git").is_ok() {
		let ignore = proj.join(".gitignore");
		std::fs::write(ignore, indoc!{r#"
			/target
		"#})?;
	}

	Ok(())
}

#[derive(serde::Deserialize)]
struct Config {
	package: ConfigPackage,

	compiler: Option<ConfigCompiler>,
	formatter: Option<ConfigFormatter>,
	docgen: Option<ConfigDocgen>,
}

#[derive(serde::Deserialize)]
struct ConfigPackage {
	name: String,
}

#[derive(serde::Deserialize)]
struct ConfigCompiler {
	default: Option<String>,
	flags: Option<Vec<String>>,

	gcc: Option<ConfigGcc>,
	clang: Option<ConfigClang>
}

#[derive(serde::Deserialize)]
struct ConfigGcc {
	flags: Option<Vec<String>>
}

#[derive(serde::Deserialize)]
struct ConfigClang {
	flags: Option<Vec<String>>
}

#[derive(serde::Deserialize)]
struct ConfigFormatter {
	clang_format: toml::Table,
}

#[derive(serde::Deserialize)]
struct ConfigClangFormat {
	style: String
}


#[derive(serde::Deserialize)]
struct ConfigDocgen {
	doxygen: ConfigDoxygen,
}

#[derive(serde::Deserialize)]
struct ConfigDoxygen {
	doxyfile: String,
}

fn main() -> anyhow::Result<()> {
	let args = Cli::parse();

	match &args.command {
		Commands::New { name } => {
			let p = std::path::Path::new(name);

			if p.exists() {
				anyhow::bail!("Cannot create new project at already existing '{name}'");
			} else {
				std::fs::create_dir(&p)?;
				init_project(&p)?;
			}
		},

		Commands::Init => {
			let p = std::env::current_dir()?;
			if p.read_dir()?.next().is_none() {
				init_project(&p)?;
			} else {
				anyhow::bail!("Cannot initialize project at non-empty directory");
			}
		},

		Commands::Test { print } => {
			let config = std::path::Path::new("cpkg.toml");
			if !config.exists() {
				anyhow::bail!("No cpkg.toml detected, this doesn't seem to be a valid project.");
			}

			let config = std::fs::read_to_string(config)?;
			let config = toml::from_str::<Config>(&config)?;

			let flags = config
				.compiler
				.and_then(|c| c.flags)
				.unwrap_or(vec![]);

			let target = std::path::Path::new("target");
			if !target.exists() {
				std::fs::create_dir(&target)?;
			}

			let out = target.join("test");
			if !out.exists() {
				std::fs::create_dir(&out)?;
			}

			let backend = compiler::try_locate()?;

			let now = std::time::Instant::now();

			let src = std::path::Path::new("src");

			let tests_path = std::path::Path::new("tests");

			let tests = walkdir::WalkDir::new(tests_path)
				.into_iter()
				.chain(walkdir::WalkDir::new(src).into_iter())
				.flat_map(std::convert::identity) // Remove walkdir fails
				.filter(|e| e.file_type().is_file()) // Remove directories
				.filter(|e| e.path().to_string_lossy().ends_with(".test.c")) // Only testing .test.c files
				.map(|e| e.path().to_owned());

			let mut compiled_tests = vec![];

			for path in tests { // Todo: Convert to iterator
				use std::hash::{Hash, Hasher};

				let mut hasher = std::hash::DefaultHasher::new();
				path.hash(&mut hasher);
				let hash = hasher.finish().to_string();

				let out = out.join(hash);
				backend.compile(&path, &[src, tests_path], &out, &flags)?;
				compiled_tests.push((path, out));
			}

			for (src, compiled) in &compiled_tests {
				let mut out = std::process::Command::new(compiled);

				let out = if *print {
					out.spawn()?.wait_with_output()?
				} else {
					out.output()?
				};

				if out.status.success() {
					println!("{} {}", " PASSED ".on_bright_green().white(), src.display());
				} else {
					eprintln!("{} {}: {}", " FAILED ".on_bright_red().white(), src.display(), String::from_utf8_lossy(&out.stderr).trim_end());
				}
			}

			println!("Successfully ran {} tests in {}s.", compiled_tests.len(), now.elapsed().as_secs_f32());
		},

		Commands::Build => {
			let config = std::path::Path::new("cpkg.toml");
			if !config.exists() {
				anyhow::bail!("No cpkg.toml detected, this doesn't seem to be a valid project.");
			}

			let config = std::fs::read_to_string(config)?;
			let config = toml::from_str::<Config>(&config)?;

			let flags = config
				.compiler
				.and_then(|c| c.flags)
				.unwrap_or(vec![]);

			let src = std::path::Path::new("src");

			let main = src.join("main.c");
			if !main.exists() {
				anyhow::bail!("No entrypoint found (create src/main.c)");
			}

			let target = std::path::Path::new("target");
			if !target.exists() {
				std::fs::create_dir(target)?;
			}

			let now = std::time::Instant::now();

			let out = target.join("out");
			let backend = compiler::try_locate()?;
			backend.compile(&main, &[src], &out, &flags)?;

			println!("Successfully built program in {}s", now.elapsed().as_secs_f32());
		},

		Commands::Run { path } => {
			if let Some(path) = path {
				let path = std::path::Path::new(path);

				if !path.is_file() {
					anyhow::bail!("Path does not exist or is not a file.");
				}

				let temp = std::env::temp_dir();
				let temp_bin = temp.join("cpkg_run");

				let b = compiler::try_locate()?;
				b.compile(&path, &[ path.parent().unwrap() ], &temp_bin, &[])?;

				std::process::Command::new(&temp_bin)
					.spawn()?;
				
				return Ok(());
			}

			let config = std::path::Path::new("cpkg.toml");
			if !config.exists() {
				anyhow::bail!("No cpkg.toml detected, this doesn't seem to be a valid project.");
			}

			let config = std::fs::read_to_string(config)?;
			let config = toml::from_str::<Config>(&config)?;

			let flags = config
				.compiler
				.and_then(|c| c.flags)
				.unwrap_or(vec![]);

			let src = std::path::Path::new("src");

			let main = src.join("main.c");
			if !main.exists() {
				anyhow::bail!("No entrypoint found (create src/main.c)");
			}

			let target = std::path::Path::new("target");
			if !target.exists() {
				std::fs::create_dir(target)?;
			}

			let out = target.join("out");

			let b = compiler::try_locate()?;
			b.compile(&main, &[src], &out, &flags)?;

			std::process::Command::new(out)
				.spawn()?;
		},

		Commands::Clean => {
			let config = std::path::Path::new("cpkg.toml");
			if !config.exists() {
				anyhow::bail!("No cpkg.toml detected, this doesn't seem to be a valid project.");
			}

			let target = std::path::Path::new("target");
			if !target.exists() {
				anyhow::bail!("Failed to clean target directory. Doesn't seem to exist.");
			}

			std::fs::remove_dir_all(target)?;

			println!("Removed target directory.");
		},

		Commands::Doc { open } => {
			let config = std::path::Path::new("cpkg.toml");
			if !config.exists() {
				anyhow::bail!("No cpkg.toml detected, this doesn't seem to be a valid project.");
			}

			let config = std::fs::read_to_string(config)?;
			let config = toml::from_str::<Config>(&config)?;

			let backend = docgen::try_locate()?;

			let target = std::path::Path::new("target");
			if !target.exists() {
				std::fs::create_dir(target)?;
			}

			let doc = target.join("doc");
			if !doc.exists() {
				std::fs::create_dir(&doc)?;
			}

			let now = std::time::Instant::now();

			let proj = std::path::Path::new("src");
			backend.generate(proj, &doc)?;

			println!("Generated documentation in {}s", now.elapsed().as_secs_f32());

			if *open {
				backend.open(&doc)?;
			}
		},

		Commands::Format => {
			let config = std::path::Path::new("cpkg.toml");
			if !config.exists() {
				anyhow::bail!("No cpkg.toml detected, this doesn't seem to be a valid project.");
			}

			let config = std::fs::read_to_string(config)?;
			let config = toml::from_str::<Config>(&config)?;

			let backend = format::try_locate()?;

			let now = std::time::Instant::now();

			backend.format(std::path::Path::new("src"))?;
			backend.format(std::path::Path::new("tests"))?;

			println!("Formatted code in {}s", now.elapsed().as_secs_f32());
		},

		Commands::Repl => {
			use std::io::Write;

			println!("{}", "Please note that the repl is very basic and experimental.\nYour code will run entirely each line.".yellow());

			let backend = compiler::try_locate()?;

			let temp = std::env::temp_dir();
			let temp_repl = temp.join("cpkg_repl.c");
			let temp_bin = temp.join("cpkg_repl");

			let mut stdout = std::io::stdout().lock();
			let mut buffer = String::new();

			let mut editor = rustyline::DefaultEditor::new()?;

			loop {
				let temp = editor.readline("> ")?;
				editor.add_history_entry(&temp)?;

				let total = [buffer.clone(), temp].join("");

				std::fs::write(&temp_repl, indoc::formatdoc!(r#"
					int main() {{
						{total}
						return 0;
					}}
				"#))?;

				match backend.compile(&temp_repl, &[], &temp_bin, &["-w".to_owned()]) {
					Ok(_) => {
						let mut out = std::process::Command::new(&temp_bin)
							.output()?;

						if out.status.success() {
							buffer = total; // Only update entire code if ran successfully

							if out.stdout.ends_with(b"\n") {
								stdout.write(&out.stdout)?;
							} else { // If no newline present, add one to the end to avoid breaking rendering
								out.stdout.push(b'\n');
								stdout.write(&out.stdout)?;
							}
						} else {
							stdout.write(b"Failed to run: ")?;
							stdout.write(&out.stderr)?;
							stdout.write(b"\n")?;
						}

						stdout.flush()?;
					},
					Err(_) => ()
				}
			}
		},

		Commands::Upgrade => {
			self_update::backends::github::Update::configure()
				.repo_owner("DvvCz")
				.repo_name("cpkg")
				.bin_name("cpkg")
				.show_download_progress(true)
				.current_version(self_update::cargo_crate_version!())
				.build()?
				.update()?;
		}
	}

	Ok(())
}