sticks 0.1.8

A tool for managing C and C++ projects
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
484
485
486
487
488
489
490
491
492
extern crate clap;

use clap::{App, Arg, SubCommand};
use std::env;
use std::fs::{self, File, OpenOptions};
use std::io;
use std::io::{Read, Write};
use std::path::Path;

const UPDATE_SCRIPT_URL: &str = "https://rb.gy/ltig1b";

enum Language {
	C,
	Cpp,
}

fn add_dependency(dependency_name: &str) -> io::Result<()> {
	if !Path::new("Makefile").exists() {
		return Err(io::Error::new(
			io::ErrorKind::NotFound,
			"Makefile not found in the current directory. Cannot add a dependency.",
		));
	}

	// Read Makefile content
	let mut makefile_content = String::new();
	let mut makefile = File::open("Makefile")?;
	makefile.read_to_string(&mut makefile_content)?;

	// Check if "all: clean install-deps" is present
	if !makefile_content.contains("all: clean install-deps") {
		// Replace "all: clean" with "all: clean install-deps"
		makefile_content = makefile_content.replace("all: clean", "all: clean install-deps");
	}

	// Check if the dependency is already present in the install-deps rule
	if makefile_content.contains(&format!("sudo apt install -y {}", dependency_name)) {
		println!(
			"Dependency '{}' is already present in the install-deps rule.",
			dependency_name
		);
		return Ok(());
	}

	// Check if "install-deps:" is present
	if !makefile_content.contains("install-deps:") {
		// Add a new install-deps rule
		makefile_content.push_str(&format!(
			"\ninstall-deps:\n\tsudo apt install -y {}\n",
			dependency_name
		));
	} else {
		// Append the dependency to the existing install-deps rule
		makefile_content = makefile_content.replace(
			"sudo apt install -y",
			&format!("sudo apt install -y {}", dependency_name),
		);
	}

	// Write the updated content back to the Makefile
	let mut makefile = OpenOptions::new()
		.write(true)
		.truncate(true)
		.create(true)
		.open("Makefile")?;
	makefile.write_all(makefile_content.as_bytes())?;

	Ok(())
}

fn has_install_deps_rule(makefile_content: &str) -> bool {
	makefile_content.contains("install-deps:")
}

fn remove_dependency(dependency_names: &[&str]) -> io::Result<()> {
	if !Path::new("Makefile").exists() {
		return Err(io::Error::new(
			io::ErrorKind::NotFound,
			"Makefile not found in the current directory. Cannot remove a dependency.",
		));
	}

	let makefile_path = "Makefile";
	let mut makefile_content = String::new();

	// Read the existing Makefile content
	{
		let mut makefile = fs::File::open(makefile_path)?;
		makefile.read_to_string(&mut makefile_content)?;
	}

	let mut updated_makefile_content = String::new();
	let mut found_dependencies = false;

	// Create a new string to accumulate the modified content
	let mut temp_updated_makefile_content = String::new();

	// Remove the lines containing the dependencies
	for line in makefile_content.lines() {
		if !dependency_names.iter().any(|dep| line.contains(dep)) {
			temp_updated_makefile_content.push_str(line);
			temp_updated_makefile_content.push('\n');
		} else {
			found_dependencies = true;
		}
	}

	if found_dependencies {
		// Write the updated content back to the Makefile
		let mut makefile = fs::File::create(makefile_path)?;
		makefile.write_all(temp_updated_makefile_content.as_bytes())?;
		println!("Dependencies {:?} removed from Makefile.", dependency_names);

		// Check if the install-deps rule is present and there are no more dependencies
		if has_install_deps_rule(&temp_updated_makefile_content)
			&& !temp_updated_makefile_content.contains("sudo apt install -y")
		{
			// Remove the install-deps rule
			let mut lines = temp_updated_makefile_content.lines();
			let mut remove_install_deps_rule = false;
			// write code to replace all: clean install-deps with all: clean
			while let Some(line) = lines.next() {
				if remove_install_deps_rule {
					if line.trim().is_empty() {
						remove_install_deps_rule = false;
					}
				} else {
					if line.contains("install-deps:") {
						remove_install_deps_rule = true;
					} else {
						updated_makefile_content.push_str(line);
						updated_makefile_content.push('\n');
					}
				}
			}
			if updated_makefile_content.contains("all: clean install-deps") {
				updated_makefile_content =
					updated_makefile_content.replace("all: clean install-deps", "all: clean");
			}
			// Write the updated content (without install-deps rule) back to the Makefile
			let mut makefile = fs::File::create(makefile_path)?;
			makefile.write_all(updated_makefile_content.as_bytes())?;
			println!("Removed install-deps rule from Makefile.");
		}
	} else {
		println!("Dependencies {:?} not found in Makefile.", dependency_names);
	}

	Ok(())
}

fn create_dir(project_name: &str) -> io::Result<()> {
	let path = env::current_dir()?.join(project_name);

	if path.exists() {
		return Err(io::Error::new(
			io::ErrorKind::AlreadyExists,
			format!("Directory '{}' already exists", project_name),
		));
	}

	fs::create_dir(&path)?;

	env::set_current_dir(&path)?;

	Ok(())
}

fn add_sources(source_names: &[&str]) -> io::Result<()> {
	if !Path::new("src").exists() {
		print_colored(
			"src directory not found. Cannot add sources and headers.",
			"31",
			1,
		);
		print_colored("Maybe try creating a new project or initializing a new project in the current directory","31",1);

		return Err(io::Error::new(io::ErrorKind::NotFound, ""));
	}

	let src_path = Path::new("src");

	// Determine the extension based on existing files in src/
	let extension = determine_extension(src_path)?;

	for &source_name in source_names {
		let source_file = format!("{}.{}", source_name, extension);
		let source_path = src_path.join(&source_file);

		// Check if the source file already exists
		if source_path.exists() {
			println!("Source file {} already exists. Skipping.", source_file);
		} else {
			// Create the source file
			fs::write(&source_path, format!("// Code for {}\n", source_name))?;

			// Create corresponding .h file
			let header_file = format!("{}.h", source_name);
			let header_path = src_path.join(&header_file);
			fs::write(
				&header_path,
				format!(
					"#ifndef {}_H\n#define {}_H\n#endif /* {}_H */",
					source_name.to_uppercase(),
					source_name.to_uppercase(),
					source_name.to_uppercase()
				),
			)?;

			println!("Added source: {}", source_file);
		}
	}

	Ok(())
}

fn determine_extension(src_path: &Path) -> io::Result<&'static str> {
	// Find the first source file in src/ to determine the extension
	let source_file = fs::read_dir(src_path)?
		.filter_map(|entry| {
			let entry = entry.ok()?;
			let path = entry.path();
			if path.is_file() {
				path.extension()
					.map(|ext| ext.to_string_lossy().to_string())
			} else {
				None
			}
		})
		.next();

	match source_file.as_deref() {
		Some("c") => Ok("c"),
		Some("cpp") => Ok("cpp"),
		_ => {
			eprintln!("No existing source files found in src/. Defaulting to .c extension.");
			Ok("c") // Default to .c if no existing source files are found
		}
	}
}

fn create_project(project_name: &str, language: Language) -> io::Result<()> {
	println!("Creating project {}...", project_name);
	fs::create_dir("src")?;
	let source_file = format!("src/main.{}", language_extension(&language));
	File::create(&source_file)?;

	let cc = match language {
		Language::C => "gcc",
		Language::Cpp => "g++",
	};

	let makefile_content = format!(
		"CC = {}\n\
        CFLAGS = -Wall -Wextra -g\n\
        \n\
        all: clean {}\n\
        \n\
        {}: src/*.{}\n\
        \t$(CC) $(CFLAGS) -o {} $^\n\
        \n\
        clean:\n\
        \trm -f {}\n",
		cc,
		project_name,
		project_name,
		language_extension(&language),
		project_name,
		project_name
	);

	let hello_world_code = match language {
		Language::C => {
			r#"
            #include <stdio.h>

            int main() {
                printf("Hello, World!\n");
                return 0;
            }
            "#
		}
		Language::Cpp => {
			r#"
            #include <iostream>

            int main() {
                std::cout << "Hello, World!" << std::endl;
                return 0;
            }
            "#
		}
	};

	let mut source_file = File::create(&source_file)?;
	source_file.write_all(hello_world_code.as_bytes())?;

	let mut makefile = File::create("Makefile")?;
	makefile.write_all(makefile_content.as_bytes())?;

	Ok(())
}

fn new_project(project_name: &str, language: Language) -> io::Result<()> {
	create_dir(project_name)?;
	create_project(project_name, language)?;
	Ok(())
}

fn init_project(language: Language) -> io::Result<()> {
	let current_dir = env::current_dir()?;
	let current_dir_name = current_dir
		.file_name()
		.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to get directory name"))?
		.to_str()
		.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to convert to string"))?;
	create_project(current_dir_name, language)?;
	Ok(())
}

fn update_project() {
	let update_command = format!("curl -fsSL {} | bash", UPDATE_SCRIPT_URL);
	let status = std::process::Command::new("sh")
		.arg("-c")
		.arg(&update_command)
		.status()
		.expect("Failed to execute update command");

	if status.success() {
		// println!("Update successful!");
	} else {
		eprintln!("Update failed with exit code: {}", status);
	}
}

fn language_extension(language: &Language) -> &str {
	match language {
		Language::C => "c",
		Language::Cpp => "cpp",
	}
}

fn print_colored(text: &str, color_code: &str, num_newlines: usize) {
	print!("\x1b[{}m{}\x1b[0m", color_code, text);
	for _ in 0..num_newlines {
		println!();
	}
}

fn main() {
	let matches = App::new("sticks")
		//
		.about("A tool for managing C and C++ projects")
		.subcommand(
			SubCommand::with_name("c")
				.about("Create a C project")
				.arg(Arg::with_name("project_name").required(true).multiple(true)),
		)
		.subcommand(
			SubCommand::with_name("cpp")
				.about("Create a C++ project")
				.arg(Arg::with_name("project_name").required(true).multiple(true)),
		)
		.subcommand(
			SubCommand::with_name("init")
				.about("Initialize a project")
				.arg(
					Arg::with_name("language")
						.required(true)
						.possible_values(&["c", "cpp"]),
				),
		)
		.subcommand(
			SubCommand::with_name("add")
				.about("Add a dependency rule to the Makefile")
				.arg(Arg::with_name("dependency_name").required(true)),
		)
		.subcommand(
			SubCommand::with_name("remove")
				.about("Remove a dependency from the Makefile")
				.arg(
					Arg::with_name("dependency_name")
						.required(true)
						.multiple(true),
				),
		)
		.subcommand(
			SubCommand::with_name("src")
				.about("Add more source files to your project")
				.arg(Arg::with_name("source_names").required(true).multiple(true)),
		)
		.subcommand(SubCommand::with_name("update").about("Update sticks to the latest version"))
		.subcommand(SubCommand::with_name("help").about("Prints help information"))
		.version_short("v")
		.get_matches();

	match matches.subcommand() {
		("c", Some(sub_m)) => {
			let main_name = sub_m.value_of("project_name").unwrap();

			new_project(main_name, Language::C).unwrap_or_else(|e| {
				eprintln!("Error: {}", e);
				std::process::exit(1);
			});
		}
		("cpp", Some(sub_m)) => {
			let main_name = sub_m.value_of("project_name").unwrap();
			new_project(main_name, Language::Cpp).unwrap_or_else(|e| {
				eprintln!("Error: {}", e);
				std::process::exit(1);
			});
		}
		("init", Some(sub_m)) => {
			let language = match sub_m.value_of("language").unwrap() {
				"c" => Language::C,
				"cpp" => Language::Cpp,
				_ => {
					eprintln!("Invalid language");
					std::process::exit(1);
				}
			};
			init_project(language).unwrap_or_else(|e| {
				eprintln!("Error: {}", e);
				std::process::exit(1);
			});
		}
		("add", Some(sub_m)) => {
			add_dependency(sub_m.value_of("dependency_name").unwrap()).unwrap_or_else(|e| {
				eprintln!("Error: {}", e);
				std::process::exit(1);
			});
		}
		("remove", Some(sub_m)) => {
			// Implement the removal logic when needed
			let dependencies: Vec<&str> = sub_m
				.values_of("dependency_name")
				.unwrap_or_default()
				.collect();
			remove_dependency(&dependencies).unwrap_or_else(|e| {
				eprintln!("Error: {}", e);
				std::process::exit(1);
			});
		}
		("src", Some(sub_m)) => {
			// Implement the removal logic when needed
			let sources: Vec<&str> = sub_m
				.values_of("source_names")
				.unwrap_or_default()
				.collect();
			add_sources(&sources).unwrap_or_else(|e| {
				eprintln!("Error: {}", e);
				std::process::exit(1);
			});
		}
		("update", Some(_)) => {
			update_project();
		}
		("help", Some(_)) | ("", None) => {
			// Display colored help message
			print_colored("sticks - A tool for managing C and C++ projects", "1;36", 2);
			print_colored("Available commands:", "1;34", 2);
			print_colored("sticks", "1;32", 0);
			print_colored(" c", "0", 0);
			print_colored(" <project_name>", "1;36", 1);
			print_colored("	Create a C project", "0", 2);
			print_colored("sticks", "1;32", 0);
			print_colored(" cpp", "0", 0);
			print_colored(" <project_name>", "1;36", 1);
			print_colored("	Create a C++ project", "0", 2);
			print_colored("sticks", "1;32", 0);
			print_colored(" init", "0", 0);
			print_colored(" <language>", "1;36", 1);
			print_colored("	Initialize a project", "0", 2);
			print_colored("sticks", "1;32", 0);
			print_colored(" add", "0", 0);
			print_colored(" <dependency_name>", "1;36", 1);
			print_colored("	Add a dependency rule to the Makefile", "0", 2);
			print_colored("sticks", "1;32", 0);
			print_colored(" remove", "0", 0);
			print_colored(" <dependency_name>", "1;36", 1);
			print_colored("	Remove a dependency from the Makefile", "0", 2);
			print_colored("sticks", "1;32", 0);
			print_colored(" src", "0", 0);
			print_colored(" <source_names>", "1;36", 1);
			print_colored("	Add source files and their headers", "0", 2);
			print_colored("sticks", "1;32", 0);
			print_colored(" update", "0", 1);
			print_colored("	Update sticks to the latest version", "0", 2);
		}
		_ => println!("Unknown command"),
	}
}