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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
use crate::builder::tgt::Target;
use crate::global_config::GlobalConfig;
use crate::utils::{
    self,
    configs::{BuildConfig, TargetConfig},
    log::{log, LogLevel},
    package::Package,
};
use std::fs;
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};

///Cleans the local targets
/// # Arguments
/// * `targets` - A vector of targets to clean
pub fn clean(targets: &Vec<TargetConfig>) {
    if Path::new(".bld_cpp").exists() {
        fs::create_dir_all(".bld_cpp").unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not remove binary directory: {}", why),
            );
        });
    }
    if Path::new(Target::obj_dir()).exists() {
        fs::remove_dir_all(Target::obj_dir()).unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not remove object directory: {}", why),
            );
        });
        log(LogLevel::Info, &format!("Cleaning: {}", Target::obj_dir()));
    }
    for target in targets {
        //remove hashes
        #[cfg(target_os = "windows")]
        let hash_path = format!(".bld_cpp/{}.win32.hash", &target.name);
        #[cfg(target_os = "linux")]
        let hash_path = format!(".bld_cpp/{}.linux.hash", &target.name);
        #[cfg(target_os = "android")]
        let hash_path = format!(".bld_cpp/{}.linux.hash", &target.name);

        if Path::new(&hash_path).exists() {
            fs::remove_file(&hash_path).unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not remove hash file: {}", why),
                );
            });
            log(LogLevel::Info, &format!("Cleaning: {}", &hash_path));
        }
        if Path::new(Target::build_dir()).exists() {
            let mut bin_name = String::new();
            bin_name.push_str(Target::build_dir());
            bin_name.push('/');
            bin_name.push_str(&target.name);
            #[cfg(target_os = "windows")]
            if target.typ == "exe" {
                bin_name.push_str(".exe");
            } else if target.typ == "dll" {
                bin_name.push_str(".dll");
            }
            #[cfg(target_os = "linux")]
            if target.typ == "exe" {
                bin_name.push_str("");
            } else if target.typ == "dll" {
                bin_name.push_str(".so");
            }
            #[cfg(target_os = "android")]
            if target.typ == "exe" {
                bin_name.push_str("");
            } else if target.typ == "dll" {
                bin_name.push_str(".so");
            }
            if Path::new(&bin_name).exists() {
                fs::remove_file(&bin_name).unwrap_or_else(|why| {
                    log(
                        LogLevel::Error,
                        &format!("Could not remove binary file: {}", why),
                    );
                });
                log(LogLevel::Log, &format!("Cleaning: {}", &bin_name));
            } else {
                log(
                    LogLevel::Log,
                    &format!("Binary file does not exist: {}", &bin_name),
                );
            }
        }
    }
}

///Cleans the downloaded packages
/// # Arguments
/// * `packages` - A vector of packages to clean
pub fn clean_packages(packages: &Vec<Package>) {
    for pack in packages {
        for target in &pack.target_configs {
            #[cfg(target_os = "windows")]
            let pack_bin_path = format!("{}/{}.dll", Target::build_dir(), &target.name);
            #[cfg(target_os = "linux")]
            let pack_bin_path = format!("{}/{}.so", Target::build_dir(), &target.name);
            #[cfg(target_os = "android")]
            let pack_bin_path = format!("{}/{}.so", Target::build_dir(), &target.name);

            if !Path::new(&pack_bin_path).exists() {
                log(
                    LogLevel::Log,
                    &format!("Package binary does not exist: {}", &pack_bin_path),
                );
                continue;
            }
            let cmd_str = format!("rm {}", &pack_bin_path);
            log(LogLevel::Debug, cmd_str.as_str());
            let output = Command::new("sh")
                .arg("-c")
                .arg(&cmd_str)
                .output()
                .expect("failed to execute process");
            if output.status.success() {
                log(
                    LogLevel::Log,
                    &format!("Cleaned package: {} of {}", &pack.name, &pack.repo),
                );
            } else {
                log(
                    LogLevel::Error,
                    &format!("Could not clean package: {} of {}", &pack.name, &pack.repo),
                );
            }
        }
    }
}

///Builds all targets
/// # Arguments
/// * `build_config` - The local build configuration
/// * `targets` - A vector of targets to build
/// * `gen_cc` - Whether to generate a compile_commands.json file
pub fn build(
    build_config: &BuildConfig,
    targets: &Vec<TargetConfig>,
    gen_cc: bool,
    gen_vsc: bool,
    packages: &Vec<Package>,
) {
    if !Path::new("./.bld_cpp").exists() {
        fs::create_dir(".bld_cpp").unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not create bld_cpp directory: {}", why),
            );
            std::process::exit(1);
        });
    }
    if gen_cc {
        let mut cc_file = fs::OpenOptions::new()
            .write(true)
            .append(true)
            .open("compile_commands.json")
            .unwrap_or_else(|why| {
                log(LogLevel::Error, &format!("Could not open cc file: {}", why));
                std::process::exit(1);
            });
        cc_file.write_all(b"[").unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not write to cc file: {}", why),
            );
            std::process::exit(1);
        });
    }

    if gen_vsc {
        let mut vsc_file = fs::OpenOptions::new()
            .write(true)
            .append(true)
            .open(".vscode/c_cpp_properties.json")
            .unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not open vsc file: {}", why),
                );
                std::process::exit(1);
            });

        let mut inc_dirs: Vec<String> = targets.iter().map(|t| t.include_dir.clone()).collect();
        for package in packages {
            for target in &package.target_configs {
                inc_dirs.push(target.include_dir.clone());
            }
        }
        let compiler_path: String = build_config.compiler.clone();
        let mut intellimode: String = String::new();
        if compiler_path == "gcc" || compiler_path == "g++" {
            intellimode = "gcc-x64".to_string();
        } else if compiler_path == "clang" || compiler_path == "clang++" {
            intellimode = "clang-x64".to_string();
        } else {
            log(
                LogLevel::Error,
                &format!("Unsupported compiler: {}", compiler_path),
            );
        }

        #[cfg(target_os = "windows")]
        let compiler_path = Command::new("sh")
            .arg("-c")
            .arg(&format!("where {}", &compiler_path))
            .output()
            .expect("failed to execute process")
            .stdout;

        #[cfg(target_os = "windows")]
        //Pick the first compiler path
        let compiler_path = String::from_utf8(compiler_path)
            .unwrap()
            .split('\n')
            .collect::<Vec<&str>>()[0]
            .to_string()
            .replace('\r', "")
            .replace('\\', "/");

        #[cfg(target_os = "windows")]
        let vsc_json = format!(
            r#"{{
    "configurations": [
        {{
            "name": "Win32",
            "includePath": [
                "{}"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "{}",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-{}"
        }}
    ],
    "version": 4
}}"#,
            inc_dirs.join("\",\n\t\t\t\t\""),
            compiler_path,
            intellimode
        );

        #[cfg(target_os = "linux")]
        let compiler_path = Command::new("sh")
            .arg("-c")
            .arg(&format!("which {}", &compiler_path))
            .output()
            .expect("failed to execute process")
            .stdout;

        #[cfg(target_os = "linux")]
        let compiler_path = String::from_utf8(compiler_path).unwrap().replace('\n', "");

        #[cfg(target_os = "linux")]
        let vsc_json = format!(
            r#"{{
    "configurations": [
        {{
            "name": "Linux",
            "includePath": [
                "{}"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "{}",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "linux-{}"
        }}
    ],
    "version": 4
}}"#,
            inc_dirs.join("\",\n\t\t\t\t\""),
            compiler_path,
            intellimode
        );
        #[cfg(target_os = "android")]
        let compiler_path = Command::new("sh")
            .arg("-c")
            .arg(&format!("which {}", &compiler_path))
            .output()
            .expect("failed to execute process")
            .stdout;

        #[cfg(target_os = "android")]
        let compiler_path = String::from_utf8(compiler_path).unwrap().replace('\n', "");

        #[cfg(target_os = "android")]
        let vsc_json = format!(
            r#"{{
    "configurations": [
        {{
            "name": "Linux",
            "includePath": [
                "{}"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "{}",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "linux-{}"
        }}
    ],
    "version": 4
}}"#,
            inc_dirs.join("\",\n\t\t\t\t\""),
            compiler_path,
            intellimode
        );

        //Write to file
        vsc_file
            .write_all(vsc_json.as_bytes())
            .unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not write to vsc file: {}", why),
                );
                std::process::exit(1);
            });
    }

    for target in targets {
        let mut tgt = Target::new(build_config, target, targets, packages);
        tgt.build(gen_cc);
    }
    if gen_cc {
        let mut cc_file = fs::OpenOptions::new()
            .write(true)
            .read(true)
            .append(true)
            .open("compile_commands.json")
            .unwrap_or_else(|why| {
                log(LogLevel::Error, &format!("Could not open cc file: {}", why));
                std::process::exit(1);
            });
        cc_file.write_all(b"]").unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not write to cc file: {}", why),
            );
            std::process::exit(1);
        });
    }
    log(LogLevel::Info, "Build complete");
}

///Runs the exe target
/// # Arguments
/// * `build_config` - The local build configuration
/// * `exe_target` - The exe target to run
/// * `targets` - A vector of targets
/// * `packages` - A vector of packages
pub fn run(
    bin_args: Option<Vec<&str>>,
    build_config: &BuildConfig,
    exe_target: &TargetConfig,
    targets: &Vec<TargetConfig>,
    packages: &Vec<Package>,
) {
    let trgt = Target::new(build_config, exe_target, targets, packages);
    if !Path::new(&trgt.bin_path).exists() {
        log(
            LogLevel::Error,
            &format!("Could not find binary: {}", &trgt.bin_path),
        );
        std::process::exit(1);
    }
    if build_config.pre_build.is_some() {
        log(LogLevel::Log, "Running pre-build script...");
        let mut cmd = std::process::Command::new(build_config.pre_build.clone().unwrap());
        cmd.stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit());
        let output = cmd.output();
        if output.is_ok() {
            log(LogLevel::Info, "  Success");
        } else {
            log(LogLevel::Error, "  Error");
            std::process::exit(1);
        }
    }
    log(LogLevel::Log, &format!("Running: {}", &trgt.bin_path));
    let mut cmd = std::process::Command::new(&trgt.bin_path);
    if let Some(bin_args) = bin_args {
        for arg in bin_args {
            cmd.arg(arg);
        }
    }
    cmd.stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit());
    let output = cmd.output();
    if output.is_ok() {
        log(LogLevel::Info, &format!("  Success: {}", &trgt.bin_path));
    } else {
        log(LogLevel::Error, &format!("  Error: {}", &trgt.bin_path));
        std::process::exit(1);
    }

    if build_config.post_build.is_some() {
        log(LogLevel::Log, "Running post-build script...");
        let mut cmd = std::process::Command::new(build_config.post_build.clone().unwrap());
        cmd.stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit());
        let output = cmd.output();
        if output.is_ok() {
            log(LogLevel::Info, "  Success");
        } else {
            log(LogLevel::Error, "  Error");
            std::process::exit(1);
        }
    }
}

///Initialises a new project in the current directory
pub fn init(project_name: &str, is_c: Option<bool>, config: GlobalConfig) {
    if Path::new(project_name).exists() {
        log(LogLevel::Error, &format!("{} already exists", project_name));
        log(LogLevel::Error, "Cannot initialise project");
        std::process::exit(1);
    }
    //initialise git repo in project directory
    let mut cmd = std::process::Command::new("git");
    cmd.arg("init").arg(project_name);
    let output = cmd.output();
    if output.is_err() {
        log(LogLevel::Error, "Could not initialise git repo");
        log(LogLevel::Error, &format!("{}", output.err().unwrap()));
        std::process::exit(1);
    }

    #[cfg(target_os = "windows")]
    let config_file = project_name.to_owned() + "/config_win32.toml";
    #[cfg(target_os = "linux")]
    let config_file = project_name.to_owned() + "/config_linux.toml";
    #[cfg(target_os = "android")]
    let config_file = project_name.to_owned() + "/config_linux.toml";

    if Path::new(&config_file).exists() {
        log(LogLevel::Error, &format!("{} already exists", config_file));
        log(LogLevel::Error, "Cannot initialise project");
        std::process::exit(1);
    }

    let mut config_file = fs::OpenOptions::new()
        .write(true)
        .create(true)
        .open(config_file)
        .unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not create config file: {}", why),
            );
            std::process::exit(1);
        });

    let c_compiler = match config.get_default_compiler().as_str() {
        "gcc" => "gcc",
        "clang" => "clang",
        _ => {
            log(LogLevel::Error, "Invalid default compiler");
            std::process::exit(1);
        }
    };
    let cpp_compiler = match config.get_default_compiler().as_str() {
        "gcc" => "g++",
        "clang" => "clang++",
        _ => {
            log(LogLevel::Error, "Invalid default compiler");
            std::process::exit(1);
        }
    };
    let sample_cpp_config = format!("[build]\ncompiler = \"{}\"\n\n[[targets]]\nname = \"main\"\nsrc = \"./src/\"\ninclude_dir = \"./src/include/\"\ntype = \"exe\"\ncflags = \"-g -Wall -Wextra\"\nlibs = \"\"\ndeps = [\"\"]\n", cpp_compiler);

    let sample_c_config = format!("[build]\ncompiler = \"{}\"\n\n[[targets]]\nname = \"main\"\nsrc = \"./src/\"\ninclude_dir = \"./src/include/\"\ntype = \"exe\"\ncflags = \"-g -Wall -Wextra\"\nlibs = \"\"\ndeps = [\"\"]\n", c_compiler);

    let sample_config = match is_c {
        Some(true) => sample_c_config,
        Some(false) => sample_cpp_config,
        None => match config.get_default_language().as_str() {
            "c" => sample_c_config,
            "cpp" => sample_cpp_config,
            _ => {
                log(LogLevel::Error, "Invalid default language");
                std::process::exit(1);
            }
        },
    };

    config_file
        .write_all(sample_config.as_bytes())
        .unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not write to config file: {}", why),
            );
            std::process::exit(1);
        });

    let src_dir = project_name.to_owned() + "/src";
    let include_dir = project_name.to_owned() + "/src/include";

    //Create src and src/include directories
    if !Path::new(&src_dir).exists() {
        fs::create_dir(&src_dir).unwrap_or_else(|why| {
            log(LogLevel::Warn, &format!("Project name {}", project_name));
            log(
                LogLevel::Error,
                &format!("Could not create src directory: {}", why),
            );
            std::process::exit(1);
        });
    }
    if !Path::new(&include_dir).exists() {
        fs::create_dir(&include_dir).unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not create src/include directory: {}", why),
            );
            std::process::exit(1);
        });
    }

    //Create main.c or main.cpp
    let main_path: String;
    match is_c {
        Some(true) => main_path = src_dir.to_owned() + "/main.c",
        Some(false) => main_path = src_dir.to_owned() + "/main.cpp",
        None => match config.get_default_language().as_str() {
            "c" => main_path = src_dir.to_owned() + "/main.c",
            "cpp" => main_path = src_dir.to_owned() + "/main.cpp",
            _ => {
                log(LogLevel::Error, "Invalid default language");
                std::process::exit(1);
            }
        },
    }
    if !Path::new(&main_path).exists() {
        let mut main_file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .open(&main_path)
            .unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not create main.cpp: {}", why),
                );
                std::process::exit(1);
            });
        let c_sample_program =
            b"#include <stdio.h>\n\nint main() {\n\tprintf(\"Hello World!\\n\");\n\treturn 0;\n}";
        let cpp_sample_program = b"#include <iostream>\n\nint main() {\n\tstd::cout << \"Hello World!\" << std::endl;\n\treturn 0;\n}";
        match is_c {
            Some(true) => main_file.write_all(c_sample_program).unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not write to main.c: {}", why),
                );
                std::process::exit(1);
            }),
            Some(false) => main_file
                .write_all(cpp_sample_program)
                .unwrap_or_else(|why| {
                    log(
                        LogLevel::Error,
                        &format!("Could not write to main.cpp: {}", why),
                    );
                    std::process::exit(1);
                }),
            None => match config.get_default_language().as_str() {
                "c" => main_file.write_all(c_sample_program).unwrap_or_else(|why| {
                    log(
                        LogLevel::Error,
                        &format!("Could not write to main.c: {}", why),
                    );
                    std::process::exit(1);
                }),
                "cpp" => main_file
                    .write_all(cpp_sample_program)
                    .unwrap_or_else(|why| {
                        log(
                            LogLevel::Error,
                            &format!("Could not write to main.cpp: {}", why),
                        );
                        std::process::exit(1);
                    }),
                _ => {
                    log(LogLevel::Error, "Invalid default language");
                    std::process::exit(1);
                }
            },
        }
    }

    let gitignore_path = project_name.to_owned() + "/.gitignore";
    if !Path::new(&gitignore_path).exists() {
        let mut gitignore_file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .open(&gitignore_path)
            .unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not create .gitignore: {}", why),
                );
                std::process::exit(1);
            });
        gitignore_file
            .write_all(b".bld_cpp\ncompile_commands.json\n.cache\n")
            .unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not write to .gitignore: {}", why),
                );
                std::process::exit(1);
            });
    }

    let mut readme_file = fs::OpenOptions::new()
        .write(true)
        .create(true)
        .open(project_name.to_owned() + "/README.md")
        .unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not create README.md: {}", why),
            );
            std::process::exit(1);
        });
    readme_file
        .write_all(format!("# {}", project_name).as_bytes())
        .unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not write to README.md: {}", why),
            );
            std::process::exit(1);
        });

    let mut license_file = fs::OpenOptions::new()
        .write(true)
        .create(true)
        .open(project_name.to_owned() + "/LICENSE")
        .unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not create LICENSE: {}", why),
            );
            std::process::exit(1);
        });

    let license = config.get_license();
    if license.as_str() == "NONE" {
        license_file.write_all(b"No license").unwrap_or_else(|why| {
            log(
                LogLevel::Error,
                &format!("Could not write to LICENSE: {}", why),
            );
            std::process::exit(1);
        });
    } else {
        license_file
            .write_all(license.as_bytes())
            .unwrap_or_else(|why| {
                log(
                    LogLevel::Error,
                    &format!("Could not write to LICENSE: {}", why),
                );
                std::process::exit(1);
            });
    }

    log(
        LogLevel::Log,
        &format!("Project {} initialised", project_name),
    );
}

pub fn init_project(project_name: String, is_c: Option<bool>, config: GlobalConfig) {
    log(LogLevel::Log, "Initializing project...");
    init(&project_name, is_c, config);
    std::process::exit(0);
}

pub fn parse_config() -> (BuildConfig, Vec<TargetConfig>, Vec<Package>) {
    #[cfg(target_os = "linux")]
    let (build_config, targets) = utils::configs::parse_config("./config_linux.toml", true);
    #[cfg(target_os = "windows")]
    let (build_config, targets) = utils::configs::parse_config("./config_win32.toml", true);
    #[cfg(target_os = "android")]
    let (build_config, targets) = utils::configs::parse_config("./config_linux.toml", true);

    let mut num_exe = 0;
    let mut exe_target: Option<&TargetConfig> = None;
    if targets.is_empty() {
        log(LogLevel::Error, "No targets in config");
        std::process::exit(1);
    } else {
        //Allow only one exe and set it as the exe_target
        for target in &targets {
            if target.typ == "exe" {
                num_exe += 1;
                exe_target = Some(target);
            } else if target.typ == "dll" {
                // Check if the dll target name starts with lib
                if !target.name.starts_with("lib") {
                    log(
                        LogLevel::Warn,
                        "Dynamic library target name must start with lib",
                    );
                    log(
                        LogLevel::Warn,
                        format!(
                            "Consider renaming \"{}\" to \"lib{}\"",
                            target.name, target.name
                        )
                        .as_str(),
                    );
                    log(
                        LogLevel::Log,
                        "Libraries are prefixed with \"lib\" and the lib is replaced by -l when linking",
                    );
                    log(LogLevel::Log, "For example, libmylib.so becomes -lmylib");
                }
            }
        }
    }

    if num_exe != 1 || exe_target.is_none() {
        log(
            LogLevel::Error,
            "Exactly one executable target must be specified",
        );
        std::process::exit(1);
    }

    #[cfg(target_os = "linux")]
    let packages = Package::parse_packages("./config_linux.toml");
    #[cfg(target_os = "android")]
    let packages = Package::parse_packages("./config_linux.toml");
    #[cfg(target_os = "windows")]
    let packages = Package::parse_packages("./config_win32.toml");

    (build_config, targets, packages)
}

pub fn pre_gen_cc() {
    if !Path::new("./compile_commands.json").exists() {
        fs::File::create(Path::new("./compile_commands.json")).unwrap();
    } else {
        fs::remove_file(Path::new("./compile_commands.json")).unwrap();
        fs::File::create(Path::new("./compile_commands.json")).unwrap();
    }
}

pub fn pre_gen_vsc() {
    if !Path::new("./.vscode").exists() {
        fs::create_dir(Path::new("./.vscode")).unwrap();
    }

    if !Path::new("./.vscode/c_cpp_properties.json").exists() {
        fs::File::create(Path::new("./.vscode/c_cpp_properties.json")).unwrap();
    } else {
        fs::remove_file(Path::new("./.vscode/c_cpp_properties.json")).unwrap();
        fs::File::create(Path::new("./.vscode/c_cpp_properties.json")).unwrap();
    }
}

pub fn clean_packages_wrapper(packages: &Vec<Package>) {
    log(LogLevel::Log, "Cleaning packages...");
    clean_packages(packages);
}

pub fn update_packages(packages: &Vec<Package>) {
    log(LogLevel::Log, "Updating packages...");
    for package in packages {
        package.update();
    }
}

pub fn restore_packages(packages: &Vec<Package>) {
    log(LogLevel::Log, "Restoring packages...");
    for package in packages {
        package.restore();
    }
}