├── src ├── oi_helper │ ├── utils.rs │ ├── samples_cli.rs │ ├── utils │ │ ├── strdiff.rs │ │ └── web.rs │ ├── resource.rs │ ├── samples.rs │ └── workspace.rs ├── oi_helper.rs └── main.rs ├── .gitignore ├── .github └── workflows │ └── rust.yml ├── Cargo.toml ├── doc └── Overview.md ├── README.md └── LICENSE /src/oi_helper/utils.rs: -------------------------------------------------------------------------------- 1 | pub mod strdiff; 2 | pub mod web; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | 13 | # Added by cargo 14 | 15 | /target 16 | 17 | publish 18 | 19 | /.vscode 20 | .DS_Store 21 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | # pull_request: 7 | # branches: [ "main" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | - run: cargo publish --token ${CRATES_TOKEN} 24 | env: 25 | CRATES_TOKEN: ${{ secrets.CARGO_TOKEN }} 26 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "oi_helper" 3 | version = "2.0.2" 4 | edition = "2021" 5 | authors = ["27Onion "] 6 | license = "GPL-2.0" 7 | readme = "README.md" 8 | repository = "https://github.com/onion108/oi_helper" 9 | description = "A useful tool for C++ competive programming." 10 | 11 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 12 | 13 | [dependencies] 14 | clap = { version = "3.0", features = ["derive"] } 15 | json = "^0.12.0" 16 | crossterm = "0.25.0" 17 | home = "^0.5.0" 18 | wait-timeout = "0.2.0" 19 | reqwest = { version = "0.11.11", features = ["blocking"] } 20 | html_parser = "0.6.3" 21 | anyhow = "1.0.61" 22 | -------------------------------------------------------------------------------- /doc/Overview.md: -------------------------------------------------------------------------------- 1 | # OIHelper Quick Start 2 | 3 | Before reading this tutorial, please check if you've installed `oi_helper` ([How to install?](../README.md#installation)). 4 | 5 | ## Creating Workspaces 6 | Use the following command to create workspaces. 7 | ``` 8 | oi_helper init [/path/to/workspace] 9 | ``` 10 | 11 | ## Create C++ Source File 12 | Use: 13 | ``` 14 | oi_helper create [NAME without extension] 15 | ``` 16 | You can also do some customizing. For example, if you want to generate a C++ source file with DP's template and set the constant `MAXN` to 114514 you can execute: 17 | ``` 18 | oi_helper create [NAME] -t dp --maxn 114514 19 | ``` 20 | Here are some possible values for `--template`: 21 | ``` 22 | dp 23 | dp-2d 24 | default 25 | ``` 26 | Also you can pass `/path/to/template` to the `--template` option. Here is an example of a template, notice that here are some placeholders start with `{#` and end with `#}`: 27 | ```C++ 28 | // {##} 29 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 30 | // 31 | 32 | #include 33 | #include 34 | 35 | using std::cin; 36 | using std::cout; 37 | using std::endl; 38 | {#debug_kit#} 39 | 40 | static const int MAXN = {#maxn_value#}; 41 | static const int MAXL = {#maxl_value#}; 42 | int dp[MAXN][MAXL]; 43 | 44 | int main() { 45 | } 46 | ``` 47 | 48 | We offer a simple debug tool which looks like this: 49 | ```c++ 50 | /* Debug Kit Start */ 51 | 52 | #ifdef __DEBUG__ 53 | #define debug_do(__b) __b 54 | #else 55 | #define debug_do(__b) 56 | #endif 57 | 58 | /* Debug Kit End */ 59 | ``` 60 | You can use `--debug-kit` or `-d` to enable it. Make sure that the place holder `{#debug_kit#}` is in your template file, or the `--debug-kit` won't work. 61 | -------------------------------------------------------------------------------- /src/oi_helper/samples_cli.rs: -------------------------------------------------------------------------------- 1 | use std::{path::Path, fs}; 2 | 3 | 4 | use crate::SamplesSubcommand; 5 | 6 | use super::{workspace::Workspace, samples::Samples}; 7 | 8 | 9 | 10 | pub fn samples(_workspace: &mut Workspace, subcommand: &SamplesSubcommand) -> Result<(), Option> { 11 | 12 | match subcommand { 13 | SamplesSubcommand::Init { name } => { 14 | 15 | let path_to_sampledir_str = format!("./{}.smpd", name.to_owned()); 16 | let path_to_sampledir = Path::new(&path_to_sampledir_str); 17 | if path_to_sampledir.exists() && !path_to_sampledir.is_dir() { 18 | return Err(Some(format!("Cannot create the sample because the filename {} has been used. Please check your directory.", path_to_sampledir_str))) 19 | } 20 | if !path_to_sampledir.exists() { 21 | match fs::create_dir(path_to_sampledir) { 22 | Ok(_) => {} 23 | Err(err) => { 24 | return Err(Some(format!("Cannot create the sample: {err} "))); 25 | } 26 | } 27 | } 28 | let config_path = path_to_sampledir.join("samples_info.json"); 29 | Samples::create(config_path.to_str().unwrap())?; 30 | 31 | } 32 | 33 | SamplesSubcommand::Create { name, timeout, memory_limit, points } => { 34 | let path_to_sampledir_str = format!("./{}.smpd", name.to_owned()); 35 | let path_to_sampledir = Path::new(&path_to_sampledir_str); 36 | let mut samples = Samples::from_file(path_to_sampledir.join("samples_info.json").to_str().unwrap())?; 37 | samples.create_sample(*points, *timeout, *memory_limit)?; 38 | } 39 | 40 | SamplesSubcommand::Lgfetch { name, problem_id } => { 41 | 42 | let path_to_sampledir_str = format!("./{}.smpd", name.to_owned()); 43 | let path_to_sampledir = Path::new(&path_to_sampledir_str); 44 | if path_to_sampledir.exists() && !path_to_sampledir.is_dir() { 45 | return Err(Some(format!("Cannot create the sample because the filename {} has been used. Please check your directory.", path_to_sampledir_str))) 46 | } 47 | if !path_to_sampledir.exists() { 48 | match fs::create_dir(path_to_sampledir) { 49 | Ok(_) => {} 50 | Err(err) => { 51 | return Err(Some(format!("Cannot create the sample: {err} "))) 52 | } 53 | } 54 | } 55 | let config_path = path_to_sampledir.join("samples_info.json"); 56 | if !config_path.as_path().exists() { 57 | Samples::create(config_path.to_str().unwrap())?; 58 | } 59 | 60 | let mut samples = Samples::from_file(config_path.to_str().unwrap())?; 61 | samples.load_sample_from_luogu(problem_id)?; 62 | 63 | } 64 | } 65 | Ok(()) 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/oi_helper/utils/strdiff.rs: -------------------------------------------------------------------------------- 1 | //! This file contains some utility functions that will output the difference between two strings. 2 | 3 | use crossterm::style::{Stylize, StyledContent}; 4 | 5 | pub fn colored_diff(original: &str, target: &str) -> (Vec>, Vec>) { 6 | let original_chars = original.chars().collect::>(); 7 | let target_chars = target.chars().collect::>(); 8 | let mut result_original: Vec> = vec![]; 9 | let mut result_target: Vec> = vec![]; 10 | 11 | // If the lengths of two are the same. 12 | if original_chars.len() == target_chars.len() { 13 | 14 | // Iterate over each characters and color it. 15 | for i in 0..target_chars.len() { 16 | result_original.push(format!("{}", original_chars[i]).green()); 17 | result_target.push(if original_chars[i] == target_chars[i] { 18 | format!("{}", target_chars[i]).green() 19 | } else { 20 | format!("{}", target_chars[i]).on_red().bold() 21 | }); 22 | } 23 | } else { 24 | if original_chars.len() < target_chars.len() { 25 | // The target is longer. 26 | let mut last_counter = 0; 27 | for i in 0..original_chars.len() { 28 | last_counter = i+1; 29 | result_original.push(format!("{}", original_chars[i]).green()); 30 | result_target.push(if original_chars[i] == target_chars[i] { 31 | format!("{}", target_chars[i]).green() 32 | } else { 33 | format!("{}", target_chars[i]).on_red().bold() 34 | }); 35 | } 36 | 37 | // Color the remaining parts. 38 | while last_counter < target_chars.len() { 39 | result_target.push(format!("{}", target_chars[last_counter]).on_red().bold()); 40 | last_counter += 1; 41 | } 42 | } else { 43 | // The original is longer. 44 | let mut last_counter = 0; 45 | for i in 0..target_chars.len() { 46 | last_counter = i+1; 47 | result_original.push(format!("{}", original_chars[i]).green()); 48 | result_target.push(if original_chars[i] == target_chars[i] { 49 | format!("{}", target_chars[i]).green() 50 | } else { 51 | format!("{}", target_chars[i]).on_red().bold() 52 | }); 53 | } 54 | 55 | // Color the remaining parts. 56 | while last_counter < original_chars.len() { 57 | result_target.push(format!(" ").on_red().bold()); 58 | result_original.push(format!("{}", original_chars[last_counter]).green()); 59 | last_counter += 1; 60 | } 61 | } 62 | } 63 | 64 | // Return the results. 65 | (result_original, result_target) 66 | } 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # oi_helper 2 | `oi_helper` is an utility application to help managing your C++ OI workspaces. 3 | 4 | ## Why `oi_helper` 5 | We all know that we often need a project manager when we're developing an application or a library. For example, I use `cargo` to manage this project. But, there is a special kind of programming, which is for algorithm competitions. This kind of programming is often called OI by people, or at least in China. OI is very special because an OI project often has a lot of source files and each source file can be compiled in to an complete binary executable file alone. It's quite different to those ordinary developings. But who said that OIers (people who do OIs) are not able to have a project manager? Usually they may need to compile everything by themselves. In the past, they should write everything by themselves, includeing `#include`s and `using`s. But with the codegen ability of `oi_helper`, they are no longer need to do this because `oi_helper` will help them generate what they want, for example, the default template is: 6 | ```C++ 7 | // 8 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 9 | // 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | static const int MAXN = 1e5+114514; 20 | 21 | int main() { 22 | return 0; 23 | } 24 | ``` 25 | You can see that `oi_helper` included some header files that OIers may want to use, and also generates the `MAXN` constant, which is very useful when doing DP or other algorithms that needs arrays. 26 | 27 | ## Installation 28 | 29 | If you want to install it easily, just type: 30 | ``` 31 | cargo install oi_helper 32 | ``` 33 | 34 | ## Build 35 | If you are interested in building it by yourself, then type: 36 | ``` 37 | cargo build 38 | ``` 39 | > Before doing this you should install rust from [here](https://rustup.rs/). 40 | 41 | Also, there is a special kind of versions called `developement previews`, where the version number will end with `devpreview`. `devpreview`s are unstable and may cause some problems, and even may fails the compiling, but the `devpreview` have the newest changes. If you really want to use the features that only work with the `devpreview`, you can type the following command after cloning this repository: 42 | ``` 43 | git switch dev 44 | cargo install --path . 45 | ``` 46 | If it builds, you will now have the `devpreview` version instead of your normal release. 47 | 48 | There are another way to install `devpreview`s, that is using `cargo install oi_helper` and add `--version` and pass the version number to it (e.g., `cargo install oi_helper --version 2.0.0-1-devpreview` will install the second stable devpreview). `devpreview`s that can be installed in this way are called **stable `devpreview`s**. 49 | 50 | Current `devpreview`'s features: 51 | - Added local test cases pending. (Currently supports `AC`, `WA` and `TLE`. ) 52 | - Added experimental support for fetching example test cases from Luogu with given problem id. 53 | 54 | Current `devpreview`'s todo: 55 | - [ ] Add result comparations. 56 | 57 | ## Usage Documentation 58 | 59 | [Click Here](doc/Overview.md) 60 | -------------------------------------------------------------------------------- /src/oi_helper/resource.rs: -------------------------------------------------------------------------------- 1 | //! Some resource strings. 2 | 3 | 4 | /// DEBUG Kits 5 | pub static CPP_TEMPLATE_DEBUG_KIT: &'static str = r" 6 | 7 | /* Debug Kit Start */ 8 | 9 | #ifdef __DEBUG__ 10 | #define debug_do(__b) __b 11 | #else 12 | #define debug_do(__b) 13 | #endif 14 | 15 | /* Debug Kit End */ 16 | 17 | "; 18 | 19 | /// The default C++ template. 20 | pub static CPP_TEMPLATE_0: &'static str = r" 21 | // {##} 22 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 23 | // 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | using namespace std; 32 | {#debug_kit#} 33 | 34 | static const int MAXN = {#maxn_value#}; 35 | 36 | int main() { 37 | return 0; 38 | } 39 | 40 | "; 41 | 42 | /// An alternative template. 43 | pub static CPP_TEMPLATE_1: &'static str = r" 44 | // {##} 45 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 46 | // 47 | 48 | #include 49 | #include 50 | 51 | using std::cin; 52 | using std::cout; 53 | using std::endl; 54 | {#debug_kit#} 55 | 56 | static const int MAXN = {#maxn_value#}; 57 | 58 | int main() { 59 | } 60 | 61 | "; 62 | 63 | /// Default dp template. 64 | pub static CPP_DP_TEMPLATE_0: &'static str = r" 65 | // {##} 66 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 67 | // 68 | 69 | #include 70 | #include 71 | #include 72 | #include 73 | #include 74 | #include 75 | using namespace std; 76 | {#debug_kit#} 77 | 78 | static const int MAXN = {#maxn_value#}; 79 | int dp[MAXN]; 80 | 81 | int main() { 82 | return 0; 83 | } 84 | 85 | "; 86 | 87 | /// An alternative template. 88 | pub static CPP_DP_TEMPLATE_1: &'static str = r" 89 | // {##} 90 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 91 | // 92 | 93 | #include 94 | #include 95 | 96 | using std::cin; 97 | using std::cout; 98 | using std::endl; 99 | {#debug_kit#} 100 | 101 | static const int MAXN = {#maxn_value#}; 102 | int dp[MAXN]; 103 | 104 | int main() { 105 | } 106 | 107 | "; 108 | 109 | /// Default dp-2d template. 110 | pub static CPP_DP_2D_TEMPLATE_0: &'static str = r" 111 | // {##} 112 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 113 | // 114 | 115 | #include 116 | #include 117 | #include 118 | #include 119 | #include 120 | #include 121 | using namespace std; 122 | {#debug_kit#} 123 | 124 | static const int MAXN = {#maxn_value#}; 125 | static const int MAXL = {#maxl_value#}; 126 | int dp[MAXN][MAXL]; 127 | 128 | int main() { 129 | return 0; 130 | } 131 | 132 | "; 133 | 134 | /// An alternative template. 135 | pub static CPP_DP_2D_TEMPLATE_1: &'static str = r" 136 | // {##} 137 | // Template generated by oi_helper (https://github.com/onion108/oi_helper) 138 | // 139 | 140 | #include 141 | #include 142 | 143 | using std::cin; 144 | using std::cout; 145 | using std::endl; 146 | {#debug_kit#} 147 | 148 | static const int MAXN = {#maxn_value#}; 149 | static const int MAXL = {#maxl_value#}; 150 | int dp[MAXN][MAXL]; 151 | 152 | int main() { 153 | } 154 | 155 | "; -------------------------------------------------------------------------------- /src/oi_helper.rs: -------------------------------------------------------------------------------- 1 | //! The main model for OI Helper. 2 | 3 | use std::{path::Path, fs}; 4 | 5 | use crate::OIHelperCommands; 6 | 7 | use self::{workspace::Workspace, samples::Samples}; 8 | 9 | mod workspace; 10 | mod resource; 11 | mod samples; 12 | mod samples_cli; 13 | mod utils; 14 | 15 | 16 | /// The main model of the OI Helper. 17 | pub struct OIHelper { 18 | /// Commandline arguments 19 | args: crate::OIHelperCli, 20 | 21 | /// The global configuration file's path. 22 | global_config_path: Option, 23 | } 24 | 25 | impl OIHelper { 26 | pub fn new(args: crate::OIHelperCli) -> Self { 27 | Self { args, global_config_path: None } 28 | } 29 | 30 | pub fn config(&mut self) { 31 | if let Some(user_home) = home::home_dir() { 32 | let mut p = user_home.clone(); 33 | p.push(".oi_helper"); 34 | if !p.as_path().exists() { 35 | fs::create_dir(&p).unwrap(); 36 | } 37 | let ps = p.to_str(); 38 | self.global_config_path = Some(String::from(ps.unwrap())); 39 | } else { 40 | self.global_config_path = None; 41 | } 42 | } 43 | 44 | pub fn run(&mut self) -> Result<(), Option> { 45 | match &self.args.subcommand { 46 | 47 | OIHelperCommands::Init { path } => { 48 | Workspace::create(&path, &self.global_config_path.clone())?; 49 | }, 50 | 51 | OIHelperCommands::Checkver { path } => { 52 | let mut cfg_path = path.clone(); 53 | cfg_path.push("oi_ws.json"); 54 | Workspace::from_file(&cfg_path.as_path(), &self.global_config_path.clone())?.check_version("./oi_ws.json")?; 55 | }, 56 | 57 | OIHelperCommands::Config { key, value } => { 58 | let mut workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 59 | workspace.set_config(key, value); 60 | workspace.save_config(Path::new("./oi_ws.json"))?; 61 | }, 62 | 63 | OIHelperCommands::Create { name , template , maxn , maxl, debug_kit } => { 64 | let mut workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 65 | workspace.check_version("./oi_ws.json")?; 66 | workspace.create_cpp(name, template, maxn, maxl, *debug_kit)?; 67 | }, 68 | 69 | OIHelperCommands::Run { name, debug } => { 70 | let mut workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 71 | workspace.check_version("./oi_ws.json")?; 72 | workspace.run_cpp(name, *debug)?; 73 | }, 74 | 75 | OIHelperCommands::Info => { 76 | let workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 77 | workspace.display_info(); 78 | }, 79 | 80 | OIHelperCommands::Update => { 81 | let mut workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 82 | workspace.update(); 83 | workspace.save_config(&Path::new("./oi_ws.json"))?; 84 | }, 85 | 86 | OIHelperCommands::GlobalConfig { key, value } => { 87 | let mut workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 88 | workspace.set_g_config(key, value)?; 89 | }, 90 | 91 | OIHelperCommands::Samples { subcommand } => { 92 | let mut workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 93 | workspace.check_version("./oi_ws.json")?; 94 | samples_cli::samples(&mut workspace, subcommand)?; 95 | }, 96 | 97 | OIHelperCommands::Test { target, samples_pack } => { 98 | let mut workspace = Workspace::from_file(Path::new("./oi_ws.json"), &self.global_config_path.clone())?; 99 | workspace.check_version("./oi_ws.json")?; 100 | let path_to_sampledir_str; 101 | if let Some(pack) = samples_pack { 102 | path_to_sampledir_str = format!("./{}.smpd", pack.to_owned()); 103 | } else { 104 | path_to_sampledir_str = format!("./{}.smpd", target.to_owned()); 105 | } 106 | let path_to_sampledir = Path::new(&path_to_sampledir_str); 107 | let mut samples = Samples::from_file(path_to_sampledir.join("samples_info.json").to_str().unwrap())?; 108 | workspace.test(target, &mut samples)?; 109 | } 110 | } 111 | Ok(()) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | //! The entry file of the CLI. 2 | 3 | use std::process::ExitCode; 4 | 5 | use clap::{Parser, Subcommand}; 6 | use crossterm::style::Stylize; 7 | 8 | mod oi_helper; 9 | 10 | /// The version of the command-line tool. 11 | pub static VERSION: &str = env!("CARGO_PKG_VERSION"); 12 | pub static DEBUG: bool = false; 13 | 14 | pub fn is_debug() -> bool { 15 | match std::env::var("APP_DEBUG") { 16 | Ok(s) => s.trim().to_uppercase() == "YES", 17 | Err(_) => false, 18 | } 19 | } 20 | 21 | pub struct MemoryLeakTracer; 22 | 23 | impl Drop for MemoryLeakTracer { 24 | fn drop(&mut self) { 25 | println!("No memory leak. "); 26 | } 27 | } 28 | 29 | /// Subcommands for the sample. 30 | #[derive(Subcommand)] 31 | pub enum SamplesSubcommand { 32 | 33 | /// Initialize a new samples group for a source file. 34 | Init { 35 | 36 | /// The name of the source file without the extension. 37 | #[clap()] 38 | name: String, 39 | 40 | }, 41 | 42 | /// Create a sample, 43 | Create { 44 | 45 | /// The name of the source file without the extension. 46 | #[clap()] 47 | name: String, 48 | 49 | /// The timeout of the sample. 50 | #[clap(long, value_parser, default_value_t = 1000)] 51 | timeout: u32, 52 | 53 | /// The memory limit. 54 | #[clap(long, value_parser, default_value_t = 256)] 55 | memory_limit: u32, 56 | 57 | /// The points 58 | #[clap(long, value_parser, default_value_t = 10)] 59 | points: u32, 60 | 61 | }, 62 | 63 | /// Fetch example I/O groups from Luogu. 64 | Lgfetch { 65 | 66 | /// The name of fetched case. 67 | #[clap()] 68 | name: String, 69 | 70 | /// The problem id 71 | #[clap()] 72 | problem_id: String, 73 | 74 | }, 75 | 76 | } 77 | 78 | /// Subcommands 79 | #[derive(Subcommand)] 80 | enum OIHelperCommands { 81 | 82 | /// Check the version 83 | Checkver { 84 | /// The path to the workspace to check. 85 | #[clap(parse(from_os_str), default_value=".")] 86 | path: std::path::PathBuf, 87 | }, 88 | 89 | /// Initialize a workspace. 90 | Init { 91 | /// The path to the workspace directory 92 | #[clap(parse(from_os_str), default_value=".")] 93 | path: std::path::PathBuf, 94 | }, 95 | 96 | /// Config current workspace. 97 | Config { 98 | /// The key of an option. 99 | /// E.g. `cc_flags`. 100 | #[clap()] 101 | key: String, 102 | 103 | /// The value of an option. 104 | /// E.g. `-std=c++17 -xc++ -O1 -Wall` 105 | #[clap()] 106 | value: String, 107 | }, 108 | 109 | /// Edit the global configuration, which will be used when initializing workspace or updating oi_ws.json. 110 | GlobalConfig { 111 | /// The key of an option. 112 | /// E.g. `cc_flags` 113 | #[clap()] 114 | key: String, 115 | 116 | /// The value of an option. 117 | /// E.g. `-std=c++17 -xc++ -O1 -Wall` 118 | #[clap()] 119 | value: String, 120 | }, 121 | 122 | /// Create a C++ source file in the workspace. 123 | Create { 124 | /// The name of the source file, the extension isn't neccessary. 125 | #[clap()] 126 | name: String, 127 | 128 | /// The template name. Defaults to default. 129 | #[clap(short='t', long, default_value="default")] 130 | template: String, 131 | 132 | /// The value of the `MAXN` constant. 133 | #[clap(long, default_value="1e5+114514")] 134 | maxn: String, 135 | 136 | /// The value of the `MAXL` constant, will be used in the 2d dp template. 137 | #[clap(long, default_value="128")] 138 | maxl: String, 139 | 140 | /// Determine if enable the debug kit. 141 | #[clap(short='d', long)] 142 | debug_kit: bool, 143 | }, 144 | 145 | /// Run the program. 146 | Run { 147 | /// The name of the source file, the extension isn't neccessary. 148 | #[clap()] 149 | name: String, 150 | 151 | /// Determine if debug kit is enabled (so the things in debug({}) will be executed. By default, they won't be executed unless you enable this option.) 152 | #[clap(short='d', long)] 153 | debug: bool, 154 | }, 155 | 156 | /// Display the info of current workspace. 157 | Info, 158 | 159 | /// Update the workspace to the newest oi_helper version. 160 | Update, 161 | 162 | /// Edit the sample group. 163 | Samples { 164 | #[clap(subcommand)] 165 | subcommand: SamplesSubcommand, 166 | }, 167 | 168 | /// Run the sample group on a target. 169 | Test { 170 | /// The file name without extension. 171 | #[clap()] 172 | target: String, 173 | 174 | /// The path-to-samples-directory (without .smpd extension). If not specified, it will be the same as the target. 175 | #[clap(short='s', long)] 176 | samples_pack: Option, 177 | }, 178 | 179 | } 180 | 181 | /// A helper for C++ competive programmers (a.k.a. OIers). 182 | #[derive(Parser)] 183 | #[clap(author, version, about, long_about = None)] 184 | pub struct OIHelperCli { 185 | 186 | /// The subcommand. 187 | #[clap(subcommand)] 188 | subcommand: OIHelperCommands, 189 | 190 | } 191 | 192 | #[allow(unused_assignments)] 193 | fn main() -> ExitCode { 194 | let _watcher; 195 | if DEBUG { 196 | _watcher = MemoryLeakTracer; 197 | } 198 | let args = OIHelperCli::parse(); 199 | let mut app = oi_helper::OIHelper::new(args); 200 | app.config(); 201 | match app.run() { 202 | Ok(_) => ExitCode::SUCCESS, 203 | Err(msg) => { 204 | if let Some(msg) = msg { 205 | println!("{}", format!("Error: {}", msg).bold().red()); 206 | } 207 | ExitCode::FAILURE 208 | } 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /src/oi_helper/utils/web.rs: -------------------------------------------------------------------------------- 1 | use std::io::Read; 2 | 3 | use html_parser::{Dom, Node}; 4 | 5 | 6 | pub fn get_remotely(url: &str) -> anyhow::Result { 7 | let mut res = reqwest::blocking::get(url)?; 8 | let mut body = String::new(); 9 | res.read_to_string(&mut body)?; 10 | if crate::is_debug() { 11 | println!("Got content from {}", url); 12 | println!("Status: {}", res.status()); 13 | println!("Headers: \n{:#?}", res.headers()); 14 | println!("Body: \n{}", body); 15 | } 16 | Ok(body) 17 | } 18 | 19 | pub fn get_luogu_problem_content(problem_id: &str) -> anyhow::Result { 20 | let content = get_remotely(&format!("https://www.luogu.com.cn/problem/{}", problem_id))?; 21 | let dom_tree = Dom::parse(&content)?; 22 | Ok(dom_tree) 23 | } 24 | 25 | #[allow(unused_doc_comments)] 26 | /// Search from the Node n. 27 | fn search_from(n: &Node) -> Option> { 28 | 29 | // Store the test cases. 30 | let mut test_cases = Vec::<(String, String)>::new(); 31 | 32 | // Check if the n is an element, 33 | match n.element() { 34 | 35 | Some(el) => { 36 | 37 | // Started to parse. 38 | let mut buffer = (String::new(), String::new()); 39 | 40 | /** 41 | * 0 means normal. 42 | * 1 means reading the test-in. 43 | * 2 means reading the test-out. 44 | */ 45 | let mut next_type = 0; 46 | 47 | for i in &el.children { 48 | 49 | match next_type { 50 | // Check each element 51 | 52 | // Normal mode 53 | 0 => { 54 | match i.element() { 55 | Some(el) => { 56 | // Check if it's before a input test-case. 57 | if el.name == "h3" && el.children.len() != 0 && el.children[0].text().is_some() && el.children[0].text().unwrap().starts_with("输入样例") { 58 | next_type = 1; 59 | continue; 60 | } 61 | // Check if it's before a output test-case. 62 | if el.name == "h3" && el.children.len() != 0 && el.children[0].text().is_some() && el.children[0].text().unwrap().starts_with("输出样例") { 63 | next_type = 2; 64 | continue; 65 | } 66 | 67 | // Otherwise, search its children, and merge the result. 68 | if let Some(cases) = search_from(i) { 69 | for i in cases { 70 | test_cases.push(i); 71 | } 72 | } 73 | } 74 | None => {} 75 | } 76 | } 77 | 78 | // Reading in-case 79 | 1 => { 80 | match i.element() { 81 | // Checking the relationships between them. 82 | // There SHOULD be no problem. 83 | Some(el) => { 84 | if el.name == "pre" && el.children.len() != 0 { 85 | if let Some(c) = el.children[0].element() { 86 | if c.name == "code" { 87 | if let Some(s) = el.children[0].element().unwrap().children[0].text() { 88 | buffer.0 = String::from(s.replace("<", "<").replace(">", ">").replace("&", "&")); 89 | } 90 | } 91 | } 92 | } 93 | next_type = 0; 94 | } 95 | None => { 96 | next_type = 0; 97 | } 98 | } 99 | } 100 | 101 | // Read the out-case 102 | 2 => { 103 | // The same as 1. 104 | match i.element() { 105 | Some(el) => { 106 | if el.name == "pre" && el.children.len() != 0 { 107 | if let Some(c) = el.children[0].element() { 108 | if c.name == "code" { 109 | if let Some(s) = el.children[0].element().unwrap().children[0].text() { 110 | // Update it. 111 | buffer.1 = String::from(s.replace("<", "<").replace(">", ">").replace("&", "&")); 112 | test_cases.push(buffer); 113 | buffer = (String::new(), String::new()); 114 | } 115 | } 116 | } 117 | } 118 | next_type = 0; 119 | } 120 | None => { 121 | next_type = 0; 122 | } 123 | } 124 | } 125 | 126 | _ => {} 127 | } 128 | 129 | } 130 | } 131 | 132 | None => { 133 | return None; 134 | } 135 | 136 | } 137 | 138 | Some(test_cases) 139 | } 140 | 141 | pub fn get_test_case_from_luogu_tree(dom: &Dom) -> Vec::<(String, String)> { 142 | let mut test_cases = Vec::<(String, String)>::new(); 143 | for i in &dom.children { 144 | if let Some(cases) = search_from(i) { 145 | for i in cases { 146 | test_cases.push(i); 147 | } 148 | } 149 | } 150 | test_cases 151 | } 152 | -------------------------------------------------------------------------------- /src/oi_helper/samples.rs: -------------------------------------------------------------------------------- 1 | //! This file contains functions and data types for processing samples. 2 | 3 | use std::{path::{Path, PathBuf}, fs::{File, OpenOptions}, io::{Read, Write}}; 4 | 5 | use json::{JsonValue, object}; 6 | 7 | use super::utils::web::{get_luogu_problem_content, get_test_case_from_luogu_tree}; 8 | 9 | pub struct Samples { 10 | config: JsonValue, 11 | config_file_path: String, 12 | iter_counter: usize, 13 | } 14 | 15 | #[allow(dead_code)] 16 | pub struct SampleInfo { 17 | pub expected_in: String, 18 | pub expected_out: String, 19 | pub timeout: u32, 20 | pub memory_limit: u32, 21 | pub points: u32, 22 | } 23 | 24 | #[allow(dead_code)] 25 | impl Samples { 26 | /// Construct from a file. `filename` is the path to the configuration file, i.e., `samples_info.json` 27 | pub fn from_file(filename: &str) -> Result> { 28 | 29 | let path = Path::new(filename); 30 | let mut file = match File::open(path) { 31 | Ok(file) => file, 32 | Err(err) => { 33 | return Err(Some(format!("Cannot read configuration file: {}", err))); 34 | } 35 | }; 36 | 37 | // Read the file 38 | let mut buffer = String::new(); 39 | match file.read_to_string(&mut buffer) { 40 | Ok(_) => {} 41 | Err(err) => { 42 | return Err(Some(format!("Cannot read configuration file: {}", err))); 43 | } 44 | } 45 | 46 | // Convert the file content to json. 47 | let jsoned_content = match json::parse(&buffer) { 48 | Ok(obj) => obj, 49 | Err(err) => { 50 | return Err(Some(format!("Cannot read configuration file: {}", err))); 51 | } 52 | }; 53 | 54 | Ok(Self { config: jsoned_content, config_file_path: String::from(filename), iter_counter: 0 }) 55 | 56 | } 57 | 58 | fn get_default_config() -> JsonValue { 59 | object! { 60 | "sample_list": [] 61 | } 62 | } 63 | 64 | /// Create a sample configuration. 65 | pub fn create(filename: &str) -> Result<(), Option> { 66 | if crate::is_debug() { 67 | println!("[DEBUG] Creating with (filename = {filename})"); 68 | } 69 | let path = Path::new(filename); 70 | let mut file = match File::create(path) { 71 | Ok(file) => file, 72 | Err(err) => { 73 | return Err(Some(format!("Cannot create configuration file: {}", err))); 74 | } 75 | }; 76 | 77 | // Prepare the default content. 78 | let default_config = Self::get_default_config(); 79 | 80 | match write!(&mut file, "{}", default_config.dump()) { 81 | Ok(_) => { 82 | Ok(()) 83 | } 84 | Err(err) => { 85 | Err(Some(format!("Cannot write to the configuration file: {}", err))) 86 | } 87 | } 88 | } 89 | 90 | /// Save the configuration. 91 | fn save(&self) -> Result<(), Option> { 92 | let mut file = match OpenOptions::new().truncate(true).write(true).open(&Path::new(&self.config_file_path)) { 93 | Ok(file) => file, 94 | Err(err) => { 95 | return Err(Some(format!("Cannot open configuration file: {}", err))); 96 | } 97 | }; 98 | match write!(&mut file, "{}", self.config.dump()) { 99 | Ok(_) => { 100 | Ok(()) 101 | } 102 | Err(err) => { 103 | return Err(Some(format!("Cannot write to the configuration file: {}", err))); 104 | } 105 | } 106 | } 107 | 108 | fn check_config(&self) -> Result<(), Option> { 109 | if !(self.config.has_key("sample_list") && self.config["sample_list"].is_array()) { 110 | return Err(Some(format!("The configuration of the sample list is broken. Please check the samples_info.json."))) 111 | } 112 | Ok(()) 113 | } 114 | 115 | /// Create a sample. 116 | pub fn create_sample(&mut self, points: u32, timeout: u32, mem_limit: u32) -> Result> { 117 | self.check_config()?; 118 | let next_no = self.config["sample_list"].len(); 119 | let parent_dir = match Path::new(&self.config_file_path).parent() { 120 | Some(p) => p, 121 | None => { 122 | unreachable!(); 123 | } 124 | }; 125 | 126 | let in_file_path_buf = parent_dir.join(&format!("{}.in", next_no)); 127 | let out_file_path_buf = parent_dir.join(&format!("{}.out", next_no)); 128 | 129 | match File::create(in_file_path_buf.as_path()) { 130 | Ok(_) => {} 131 | Err(err) => { 132 | return Err(Some(format!("Error creating sample #{next_no}: {err}"))); 133 | } 134 | } 135 | 136 | match File::create(out_file_path_buf.as_path()) { 137 | Ok(_) => {} 138 | Err(err) => { 139 | return Err(Some(format!("Error creating sample #{next_no}: {err}"))); 140 | } 141 | } 142 | 143 | // Register the sample info. 144 | // There should NOT panic because we've confirmed that the key sample_list is already an array. 145 | // So no need to process the error, just unwrap. 146 | self.config["sample_list"].push(object! { 147 | "in_file": format!("{next_no}.in"), 148 | "out_file": format!("{next_no}.out"), 149 | "timeout_ms": timeout, 150 | "memory_limit": mem_limit, 151 | "points": points, 152 | }).unwrap(); 153 | 154 | // Save the configuration. 155 | self.save()?; 156 | 157 | Ok(next_no as i32) 158 | } 159 | 160 | fn read_from_pathbuf(&self, pthbuf: &PathBuf) -> Result> { 161 | let mut buffer = String::new(); 162 | match File::open(pthbuf) { 163 | Ok(mut file) => { 164 | match file.read_to_string(&mut buffer) { 165 | Ok(_) => Ok(buffer), 166 | Err(err) => { 167 | return Err(Some(format!("Error reading {}: {err}", pthbuf.to_str().unwrap()))) 168 | } 169 | } 170 | } 171 | Err(err) => { 172 | return Err(Some(format!("Error reading {}: {err}", pthbuf.to_str().unwrap()))); 173 | } 174 | } 175 | } 176 | 177 | /// Get in-out for a sample with index. 178 | fn get(&self, idx: usize) -> Result, Option> { 179 | self.check_config()?; 180 | if idx >= self.config["sample_list"].len() { 181 | return Ok(None); 182 | } 183 | let infile_name = self.config["sample_list"][idx]["in_file"].to_string(); 184 | let outfile_name = self.config["sample_list"][idx]["out_file"].to_string(); 185 | 186 | // Concat paths 187 | let parent = Path::new(&self.config_file_path).parent().unwrap(); 188 | let infile_pathbuf = parent.join(infile_name); 189 | let outfile_pathbuf = parent.join(outfile_name); 190 | 191 | // Read contents 192 | let infile_content = self.read_from_pathbuf(&infile_pathbuf)?; 193 | let outfile_content = self.read_from_pathbuf(&outfile_pathbuf)?; 194 | 195 | Ok(Some(SampleInfo { 196 | expected_in: infile_content, 197 | expected_out: outfile_content, 198 | timeout: match self.config["sample_list"][idx]["timeout_ms"].as_u32() { 199 | Some(timeout) => timeout, 200 | None => { 201 | return Err(Some(format!("Error reading sample: invalid timeout value. "))); 202 | } 203 | }, 204 | memory_limit: match self.config["sample_list"][idx]["memory_limit"].as_u32() { 205 | Some(timeout) => timeout, 206 | None => { 207 | return Err(Some(format!("Error reading sample: invalid memory_limit value. "))); 208 | } 209 | }, 210 | points: match self.config["sample_list"][idx]["points"].as_u32() { 211 | Some(timeout) => timeout, 212 | None => { 213 | return Err(Some(format!("Error reading sample: invalid points value. "))); 214 | } 215 | }, 216 | })) 217 | } 218 | 219 | /// Load the samples from Luogu with a specified problem id 220 | pub fn load_sample_from_luogu(&mut self, problem_id: &str) -> Result<(), Option> { 221 | 222 | eprintln!("Starting fetching samples from {}... ", problem_id); 223 | 224 | let samples = get_test_case_from_luogu_tree(&(match get_luogu_problem_content(problem_id) { 225 | Ok(o) => o, 226 | Err(err) => return Err(Some(format!("Error occured while fetching samples: {}", err))) 227 | })); 228 | let each_point = 100 / (samples.len() as u32); 229 | 230 | eprintln!("Content fetched. Loading {} sample(s)... ", samples.len()); 231 | 232 | for case in samples { 233 | 234 | let number = self.create_sample(each_point, 1000, 256)?; 235 | eprintln!("Loading sample #{number}... "); 236 | 237 | let in_path = Path::new(&self.config_file_path).parent().unwrap().join(&format!("{}.in", number)); 238 | let out_path = Path::new(&self.config_file_path).parent().unwrap().join(&format!("{}.out", number)); 239 | 240 | let mut in_file = match OpenOptions::new().write(true).truncate(true).open(&in_path) { 241 | Ok(f) => f, 242 | Err(err) => { 243 | return Err(Some(format!("Error while opening sample from {}: {}", in_path.to_str().unwrap_or("undefined"), err))); 244 | } 245 | }; 246 | 247 | let mut out_file = match OpenOptions::new().write(true).truncate(true).open(&out_path) { 248 | Ok(f) => f, 249 | Err(err) => { 250 | return Err(Some(format!("Error while opening sample from {}: {}", out_path.to_str().unwrap_or("undefined"), err))); 251 | } 252 | }; 253 | 254 | match write!(&mut in_file, "{}", case.0) { 255 | Ok(_) => {} 256 | Err(err) => { 257 | return Err(Some(format!("Error while writing sample: {}", err))); 258 | } 259 | } 260 | 261 | match write!(&mut out_file, "{}", case.1) { 262 | Ok(_) => {} 263 | Err(err) => { 264 | return Err(Some(format!("Error while writing sample: {}", err))); 265 | } 266 | } 267 | 268 | eprintln!("Loaded sample #{number}. "); 269 | 270 | } 271 | 272 | eprintln!("Fetching done. "); 273 | Ok(()) 274 | 275 | } 276 | 277 | } 278 | 279 | impl Iterator for Samples { 280 | type Item = Result>; 281 | 282 | fn next(&mut self) -> Option { 283 | match self.get(self.iter_counter) { 284 | Ok(value) => match value { 285 | Some(value) => { 286 | self.iter_counter += 1; 287 | Some(Ok(value)) 288 | }, 289 | None => { 290 | self.iter_counter = 0; 291 | None 292 | } 293 | }, 294 | Err(err) => Some(Err(err)), 295 | } 296 | } 297 | } 298 | 299 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /src/oi_helper/workspace.rs: -------------------------------------------------------------------------------- 1 | //! This file contains operationgs and data structure about a workspace. 2 | 3 | use std::{ 4 | fs::{self, File, OpenOptions}, 5 | io::{stdin, Read, Write}, 6 | path::{Path, PathBuf}, 7 | process::{Command, Stdio}, 8 | time::Duration, 9 | }; 10 | 11 | use crossterm::style::Stylize; 12 | use json::{object, JsonValue}; 13 | use wait_timeout::ChildExt; 14 | 15 | use crate::oi_helper::utils; 16 | 17 | use super::{resource, samples::Samples}; 18 | 19 | /// The workspace model. 20 | pub struct Workspace { 21 | config: JsonValue, 22 | global_config: Option, 23 | } 24 | 25 | #[allow(dead_code)] 26 | impl Workspace { 27 | fn get_default_config(&self) -> JsonValue { 28 | // The default configuration, if the configuration doesn't exist. 29 | let builtin_default = object! { 30 | "initialzed": "true", 31 | "oi_helper_version": crate::VERSION, 32 | "cc_flags": "-std=c++11 -O2 -Wall -xc++ ", 33 | "cc_template": "temp0", 34 | "cc_default_extension": "cc", 35 | "cc_compiler": "g++", 36 | }; 37 | 38 | // If the configuration directory exists 39 | if let Some(p) = &self.global_config { 40 | // Construct a path to the global.json 41 | let pth = Path::new(&p); 42 | let mut pth_buf = pth.to_path_buf(); 43 | pth_buf.push("global.json"); 44 | 45 | // Check if the file exists 46 | if !pth_buf.as_path().exists() { 47 | // If not, create a new file 48 | let mut f = File::create(&pth_buf.as_path()).unwrap(); 49 | f.write_all(builtin_default.dump().as_bytes()).unwrap(); 50 | builtin_default 51 | } else { 52 | // Otherwise, read the file OR update the default file. 53 | let mut f = File::open(&pth_buf.as_path()).unwrap(); 54 | let mut buffer = String::new(); 55 | f.read_to_string(&mut buffer).unwrap(); 56 | let ccfg = json::parse(&buffer).unwrap(); 57 | 58 | // Check the version 59 | if ccfg["oi_helper_version"].to_string() != crate::VERSION { 60 | // The global.json is from an older version 61 | let mut mccfg = ccfg.clone(); 62 | 63 | // Update keys that don't exist in the older version's configuration file 64 | for i in builtin_default.entries().map(|x| x.0) { 65 | if !mccfg.has_key(i) { 66 | mccfg[i] = builtin_default[i].clone(); 67 | } 68 | } 69 | 70 | // Update the version. 71 | mccfg["oi_helper_version"] = JsonValue::String(String::from(crate::VERSION)); 72 | 73 | let mut f = File::create(&pth_buf.as_path()).unwrap(); 74 | f.write_all(mccfg.dump().as_bytes()).unwrap(); 75 | mccfg 76 | } else { 77 | // If it's already the newest, just return what we read 78 | ccfg 79 | } 80 | } 81 | } else { 82 | builtin_default 83 | } 84 | } 85 | 86 | /// Edit the global configuration file. 87 | pub fn set_g_config(&mut self, key: &str, value: &str) -> Result<(), Option> { 88 | if let Some(p) = &self.global_config { 89 | let pth = Path::new(p); 90 | let mut pth_buf = pth.to_path_buf(); 91 | pth_buf.push("global.json"); 92 | let mut cfg = self.get_default_config(); 93 | cfg[key] = JsonValue::String(String::from(value)); 94 | let mut f = match File::create(&pth_buf.as_path()) { 95 | Ok(f) => f, 96 | Err(err) => { 97 | return Err(Some(format!( 98 | "Error saving global configuration file: {err}" 99 | ))); 100 | } 101 | }; 102 | if let Err(err) = f.write_all(cfg.dump().as_bytes()) { 103 | return Err(Some(format!( 104 | "Error saving global configuration file: {err}" 105 | ))); 106 | } 107 | Ok(()) 108 | } else { 109 | Err(Some( 110 | "Cannot edit the global configuration file.".to_string(), 111 | )) 112 | } 113 | } 114 | 115 | /// Create from path. 116 | pub fn create(path: &PathBuf, global_cfg: &Option) -> Result> { 117 | let result = Self { 118 | config: JsonValue::Null, 119 | global_config: global_cfg.clone(), 120 | }; 121 | let default_workspace_file = result.get_default_config(); 122 | let mut cfg_path = path.clone(); 123 | 124 | cfg_path.push("oi_ws.json"); 125 | let cfg_file = cfg_path.as_path(); 126 | 127 | // Check if the configuration exists. 128 | if !cfg_file.exists() { 129 | let mut f = match File::create(&cfg_file) { 130 | Ok(file) => file, 131 | Err(err) => { 132 | return Err(Some(format!("Cannot create workspace file: {}", err))); 133 | } 134 | }; 135 | match f.write_all(default_workspace_file.dump().as_bytes()) { 136 | Ok(_) => {} 137 | Err(err) => { 138 | return Err(Some(format!("Cannot write to workspace file: {}", err))); 139 | } 140 | } 141 | } else { 142 | // Let the user choose if they want to override the existed workspace file. 143 | eprintln!("{} The workspace configuration file already exists. Are you sure to override it? [Y/{}]", "[WARNING]".bold().yellow(), "N".bold().blue()); 144 | let mut choice = String::new(); 145 | std::io::stdin().read_line(&mut choice).unwrap(); 146 | if choice.trim().to_uppercase() == "Y" { 147 | // User chose yes, then override it. 148 | let mut f = 149 | File::create(&cfg_file).expect("cannot create the workspace file. stopped."); 150 | match f.write_all(default_workspace_file.dump().as_bytes()) { 151 | Ok(_) => {} 152 | Err(err) => { 153 | return Err(Some(format!("Cannot write to the workspace file: {}", err))); 154 | } 155 | } 156 | } else { 157 | return Err(None); 158 | } 159 | } 160 | Ok(Self::from_json(default_workspace_file, global_cfg)) 161 | } 162 | 163 | /// Initialize from json. 164 | pub fn from_json(json: JsonValue, global_cfg: &Option) -> Self { 165 | Self { 166 | config: json.clone(), 167 | global_config: global_cfg.clone(), 168 | } 169 | } 170 | 171 | /// Initialize from file. 172 | pub fn from_file(path: &Path, global_cfg: &Option) -> Result> { 173 | // let mut file = File::open(path).expect("cannot find workspace config. stopped. \nHint: Have you executed `oi_helper init` or are you in the root directory of the workspace?"); 174 | let mut file = match File::open(path) { 175 | Ok(file) => file, 176 | Err(_) => { 177 | eprintln!( 178 | "{}", 179 | "Cannot find workspace's configuration file. Stopped. ".red() 180 | ); 181 | eprintln!( 182 | "{}{}{}", 183 | "[HINT] Have you executed ".yellow().bold(), 184 | "oi_helper init".cyan().bold(), 185 | " or are you in the root directory of the workspace? " 186 | .bold() 187 | .yellow() 188 | ); 189 | return Err(None); // Return none here because we need to display custom error messages. 190 | } 191 | }; 192 | let mut file_content = String::new(); 193 | match file.read_to_string(&mut file_content) { 194 | Ok(_) => {} 195 | Err(err) => { 196 | eprintln!("cannot read workspace file: {}", err); 197 | eprintln!( 198 | "{}{}{}", 199 | "[HINT] Have you ran ".bold().yellow(), 200 | "oi_helper init".bold().cyan(), 201 | " yet? ".bold().yellow() 202 | ); 203 | return Err(None); 204 | } 205 | } 206 | return Ok(Self::from_json( 207 | json::parse(&file_content).expect("the oi_ws.json is not a valid json file. stopped."), 208 | global_cfg, 209 | )); 210 | } 211 | 212 | /// Check the version of the workspace. 213 | pub fn check_version(&mut self, p: &str) -> Result<(), Option> { 214 | // If have this key. 215 | if self.config.has_key("oi_helper_version") { 216 | // Get the version string. 217 | let version = self.config["oi_helper_version"].clone(); 218 | 219 | // Check the version. 220 | if version.to_string() != crate::VERSION { 221 | eprintln!("{} The version of oi_helper is {} but the workspace version is {}. Load it anyway? [Y/{}]", "[WARNING]".bold().yellow(), crate::VERSION.bold().green(), version.to_string().bold().red(), "N".bold().blue()); 222 | eprintln!("{}", "[HINT] You can use `oi_helper update` to update your workspace to the newest version safely.".bold().yellow()); 223 | let mut u_c = String::new(); 224 | stdin().read_line(&mut u_c).unwrap(); 225 | 226 | // Unsafely update the workspace. 227 | if u_c.trim().to_uppercase() == "Y" { 228 | self.config["oi_helper_version"] = 229 | JsonValue::String(String::from(crate::VERSION)); 230 | self.config["__unsafe_updating"] = JsonValue::Boolean(true); 231 | self.save_config(Path::new(p))?; 232 | } else { 233 | // Just exit the program if the user didn't want to load the workspace. 234 | // Maybe they'll update the workspace in a safe way later. 235 | return Err(None); 236 | } 237 | } else { 238 | // Check if the workspace is unsafe. 239 | if self.config.has_key("__unsafe_updating") { 240 | if let Some(uu) = self.config["__unsafe_updating"].as_bool() { 241 | // It's true! 242 | if uu { 243 | eprintln!( 244 | "{}", 245 | "[WARNING] Running in an unsafe updated workspace. " 246 | .bold() 247 | .yellow() 248 | ); 249 | eprintln!( 250 | "{}{}{}", 251 | "[HINT] Use ".bold().yellow(), 252 | "oi_helper update".bold().cyan(), 253 | " to update the workspace safely. ".bold().yellow() 254 | ); 255 | } 256 | } 257 | } 258 | // Otherwise, it's must be safe and the newest 259 | } 260 | } else { 261 | // Cannot get the version, which means it's broken. 262 | return Err(Some(String::from( 263 | "The workspace config is broken or not in the correct format. Stopped.", 264 | ))); 265 | } 266 | Ok(()) 267 | } 268 | 269 | /// Set the configuration. 270 | pub fn set_config(&mut self, key: &str, value: &str) { 271 | self.config[key] = JsonValue::String(String::from(value)); 272 | } 273 | 274 | /// Save the configuration. 275 | pub fn save_config(&self, path: &Path) -> Result<(), Option> { 276 | let mut file = match OpenOptions::new().write(true).truncate(true).open(path) { 277 | Ok(f) => f, 278 | Err(err) => { 279 | return Err(Some(format!("Cannot save configuration file: {err}"))); 280 | } 281 | }; 282 | file.write_all(self.config.dump().as_bytes()).unwrap(); 283 | Ok(()) 284 | } 285 | 286 | /// Create a new C++ source file. 287 | pub fn create_cpp( 288 | &self, 289 | name: &str, 290 | template: &str, 291 | maxn: &str, 292 | maxl: &str, 293 | debug_kit: bool, 294 | ) -> Result<(), Option> { 295 | let real_name = if name.ends_with(".cpp") && name.ends_with(".cc") && name.ends_with(".cxx") 296 | { 297 | String::from(name) 298 | } else { 299 | String::from(name) + "." + self.config["cc_default_extension"].to_string().as_str() 300 | }; 301 | let mut file = match File::create(Path::new(&real_name)) { 302 | Ok(file) => file, 303 | Err(_) => { 304 | return Err(Some(format!( 305 | "Failed to create the C++ source file. Please check your configuration." 306 | ))) 307 | } 308 | }; 309 | let template_scheme_obj = self.config["cc_template"].to_string(); 310 | let mut buffer = String::new(); 311 | let template_scheme = template_scheme_obj.as_str(); 312 | 313 | // Choose the tempalte. 314 | let template = match template { 315 | "dp" => match template_scheme { 316 | "temp1" => resource::CPP_DP_TEMPLATE_0.trim_start(), 317 | "temp0" | _ => resource::CPP_DP_TEMPLATE_1.trim_end(), 318 | }, 319 | "default" => match template_scheme { 320 | "temp1" => resource::CPP_TEMPLATE_1.trim_start(), 321 | "temp0" | _ => resource::CPP_TEMPLATE_0.trim_start(), 322 | }, 323 | "dp-2d" => match template_scheme { 324 | "temp1" => resource::CPP_DP_2D_TEMPLATE_1.trim_start(), 325 | "temp0" | _ => resource::CPP_DP_2D_TEMPLATE_0.trim_start(), 326 | }, 327 | "empty" => "", 328 | _ => { 329 | // Try to treat the template name as a path to the template file. 330 | if let Ok(mut f) = File::open(&Path::new(template)) { 331 | // Try to read it. 332 | match f.read_to_string(&mut buffer) { 333 | Ok(_) => {} 334 | Err(err) => { 335 | return Err(Some(format!( 336 | "Failed to read template file {} due to error: {}", 337 | template, err 338 | ))) 339 | } 340 | } 341 | buffer.as_str() 342 | } else { 343 | // All tryings were failed. Tell the user about that. 344 | eprintln!("Invalid template: {}", template); 345 | eprintln!( 346 | "{}", 347 | "Usable tempaltes: dp, default, dp-2d, empty, [path/to/template]" 348 | .bold() 349 | .yellow() 350 | ); 351 | return Err(None); 352 | } 353 | } 354 | }; 355 | 356 | // Fill in all the placeholders and write. 357 | if let Err(err) = file.write_all( 358 | template 359 | .replace("{##}", name) 360 | .replace("{#maxn_value#}", maxn) 361 | .replace("{#debug_kit#}", { 362 | if debug_kit { 363 | resource::CPP_TEMPLATE_DEBUG_KIT 364 | } else { 365 | "" 366 | } 367 | }) 368 | .replace("{#maxl_value#}", maxl) 369 | .as_bytes(), 370 | ) { 371 | return Err(Some(format!("Cannot write template due to error: {err}"))); 372 | } 373 | Ok(()) 374 | } 375 | 376 | fn compile_cpp( 377 | &self, 378 | real_name: &str, 379 | executable_name: &str, 380 | use_debug: bool, 381 | ) -> Result<(), Option> { 382 | match Command::new(self.config["cc_compiler"].to_string().as_str()) 383 | .args(self.parse_args()) 384 | .arg(format!("-o")) 385 | .arg(format!("{}", executable_name)) 386 | .arg({ 387 | if use_debug { 388 | "-D__DEBUG__" 389 | } else { 390 | "" 391 | } 392 | }) 393 | .arg("--") 394 | .arg(real_name) 395 | .status() 396 | { 397 | Ok(_) => { 398 | println!("{}", "Compiled. ".bold().green()); 399 | Ok(()) 400 | } 401 | Err(_) => Err(Some(format!( 402 | "Failed to compile the program. Stopped. (CE(0))" 403 | ))), 404 | } 405 | } 406 | 407 | /// Run a C++ source file. 408 | pub fn run_cpp(&self, name: &str, use_debug: bool) -> Result<(), Option> { 409 | // Get the real name. 410 | let real_name = if name.ends_with(".cpp") && name.ends_with(".cc") && name.ends_with(".cxx") 411 | { 412 | String::from(name) 413 | } else { 414 | String::from(name) + "." + self.config["cc_default_extension"].to_string().as_str() 415 | }; 416 | 417 | // Generate the executable's name. 418 | let executable_name = real_name.split('.').collect::>()[0]; 419 | 420 | // Check if the old build target is already built and haven't been removed yet. 421 | if Path::new(executable_name).exists() { 422 | match fs::remove_file(Path::new(executable_name)) { 423 | Ok(_) => {} 424 | Err(err) => { 425 | return Err(Some(format!( 426 | "failed to clean the old built target: {}", 427 | err 428 | ))); 429 | } 430 | } 431 | } 432 | 433 | // Compile the target. 434 | self.compile_cpp(&real_name, executable_name, use_debug)?; 435 | 436 | // Run the target. 437 | match Command::new(format!("./{}", executable_name)).status() { 438 | Ok(_) => {} 439 | Err(_) => { 440 | return Err(Some("Runtime error ocurred. ".to_string())); 441 | } 442 | } 443 | 444 | // Finally remove the file. 445 | if let Err(err) = fs::remove_file(Path::new(&format!("./{}", executable_name))) { 446 | return Err(Some(format!("Failed to clean the compiled target: {err}"))); 447 | } 448 | 449 | Ok(()) 450 | } 451 | 452 | fn parse_args(&self) -> Vec { 453 | let mut result = Vec::::new(); 454 | let mut buffer = String::new(); 455 | let source = self.config["cc_flags"].to_string(); 456 | let mut status = 0; 457 | 458 | for i in source.chars() { 459 | match status { 460 | 0 => { 461 | match i { 462 | ' ' => status = 1, 463 | '"' => status = 2, 464 | _ => buffer.push(i), 465 | }; 466 | } 467 | 468 | 1 => { 469 | if buffer != "" { 470 | result.push(buffer); 471 | buffer = String::new(); 472 | if i != ' ' { 473 | buffer.push(i); 474 | } 475 | } else { 476 | if i != ' ' { 477 | buffer.push(i); 478 | } 479 | } 480 | status = 0 481 | } 482 | 483 | 2 => match i { 484 | '"' => status = 0, 485 | '\\' => status = 3, 486 | _ => buffer.push(i), 487 | }, 488 | 489 | 3 => { 490 | buffer.push(i); 491 | status = 0; 492 | } 493 | _ => {} 494 | } 495 | } 496 | result 497 | } 498 | 499 | /// Display the info of a workspace. 500 | pub fn display_info(&self) { 501 | if self.config.has_key("oi_helper_version") { 502 | println!( 503 | "Current Workspace's OI Helper Version (oi_helper_version): {} {}", 504 | self.config["oi_helper_version"].to_string(), 505 | if self.config.has_key("__unsafe_updating") { 506 | if let Some(uu) = self.config["__unsafe_updating"].as_bool() { 507 | if uu { 508 | "UNSAFE UPDATED".yellow().bold() 509 | } else { 510 | "".stylize() 511 | } 512 | } else { 513 | "MAYBE BROKEN".red().bold() 514 | } 515 | } else { 516 | "".reset() 517 | } 518 | ); 519 | } 520 | if self.config.has_key("cc_flags") { 521 | println!( 522 | "Current C++ Compiler Flags (cc_flags): {}", 523 | self.config["cc_flags"].to_string() 524 | ); 525 | } 526 | if self.config.has_key("cc_template") { 527 | println!( 528 | "Current Template Theme (cc_template): {}", 529 | self.config["cc_template"].to_string() 530 | ); 531 | } 532 | if self.config.has_key("cc_default_extension") { 533 | println!( 534 | "Current C++ Extension (cc_default_extension): {}", 535 | self.config["cc_default_extension"].to_string() 536 | ); 537 | } 538 | if self.config.has_key("cc_compiler") { 539 | println!( 540 | "Current C++ Compiler (cc_compiler): {}", 541 | self.config["cc_compiler"].to_string() 542 | ); 543 | } 544 | } 545 | 546 | /// Update the workspace file to the newest version. 547 | pub fn update(&mut self) { 548 | if self.config.has_key("oi_helper_version") { 549 | self.config["oi_helper_version"] = JsonValue::String(String::from(crate::VERSION)); 550 | } 551 | let default = &self.get_default_config(); 552 | for i in default.entries().map(|x| x.0) { 553 | if !self.config.has_key(i) { 554 | self.config[i] = default[i].clone(); 555 | } 556 | } 557 | self.config["__unsafe_updating"] = JsonValue::from(false); 558 | } 559 | 560 | /// Test the given target. 561 | pub fn test(&self, name: &str, sample_group: &mut Samples) -> Result<(), Option> { 562 | // Get the real name. 563 | let real_name = if name.ends_with(".cpp") && name.ends_with(".cc") && name.ends_with(".cxx") 564 | { 565 | String::from(name) 566 | } else { 567 | String::from(name) + "." + self.config["cc_default_extension"].to_string().as_str() 568 | }; 569 | 570 | // Generate the executable's name. 571 | let executable_name = real_name.split('.').collect::>()[0]; 572 | 573 | // Check if the old build target is already built and haven't been removed yet. 574 | if Path::new(executable_name).exists() { 575 | match fs::remove_file(Path::new(executable_name)) { 576 | Ok(_) => {} 577 | Err(err) => { 578 | return Err(Some(format!( 579 | "failed to clean the old built target:{}", 580 | err 581 | ))); 582 | } 583 | } 584 | } 585 | 586 | // Compile the target. 587 | self.compile_cpp(&real_name, executable_name, false)?; 588 | 589 | // Run the tests 590 | let mut total_points = 0_u32; 591 | let mut group_id = 0; 592 | let temp_in = Path::new("tkejhowiuyoiuwoiub_in.bakabaka.in.txt"); 593 | // Iterates over each test cases 594 | for sample in sample_group { 595 | let i = sample?; 596 | eprintln!("Testing test #{group_id}..."); 597 | let timeout = Duration::from_millis(i.timeout as u64); 598 | let points = i.points; 599 | 600 | let mut in_file = match OpenOptions::new() 601 | .write(true) 602 | .read(true) 603 | .truncate(true) 604 | .create(true) 605 | .open(temp_in) 606 | { 607 | Ok(file) => file, 608 | Err(err) => { 609 | return Err(Some(format!( 610 | "Error running sample group #{}: {err}", 611 | group_id 612 | ))); 613 | } 614 | }; 615 | match write!(in_file, "{}", i.expected_in) { 616 | Ok(_) => {} 617 | Err(err) => { 618 | return Err(Some(format!( 619 | "Error running sample group #{}: {err}", 620 | group_id 621 | ))); 622 | } 623 | } 624 | if crate::is_debug() { 625 | println!( 626 | "[DEBUG] Write {} to {}.", 627 | i.expected_in, 628 | temp_in.to_str().unwrap() 629 | ); 630 | } 631 | 632 | in_file = match File::open(temp_in) { 633 | Ok(file) => file, 634 | Err(err) => { 635 | return Err(Some(format!( 636 | "Error running sample group #{}: {err}", 637 | group_id 638 | ))); 639 | } 640 | }; 641 | 642 | // Spawn the child process. 643 | let mut child = match Command::new(format!("./{}", executable_name)) 644 | .stdin(in_file) 645 | .stdout(Stdio::piped()) 646 | .spawn() 647 | { 648 | Ok(c) => c, 649 | Err(err) => { 650 | return Err(Some(format!( 651 | "Error running sample group #{}: {err}", 652 | group_id 653 | ))); 654 | } 655 | }; 656 | match child.wait_timeout(timeout) { 657 | Ok(is_timeout) => { 658 | match is_timeout { 659 | // Didn't time out. 660 | Some(_) => { 661 | // Read the result output. 662 | let mut _tmp0 = child.wait_with_output().unwrap(); 663 | let content = String::from_utf8_lossy(&_tmp0.stdout[..]); 664 | 665 | // Check and compare the results. 666 | if content.trim() == i.expected_out { 667 | eprintln!( 668 | "{}", 669 | format!("Test #{group_id} passed: AC({})", i.points).green() 670 | ); 671 | total_points += points; 672 | } else { 673 | let colored_diffs = 674 | utils::strdiff::colored_diff(&i.expected_out, content.trim()); 675 | eprintln!("{}", format!("Test #{group_id} failed: WA(0)").red()); 676 | eprintln!(""); 677 | eprintln!("Expected: "); 678 | // eprintln!("{}", i.expected_out.on_black()); 679 | for i in colored_diffs.0 { 680 | eprint!("{}", i); 681 | } 682 | eprintln!(); 683 | eprintln!("Actually: "); 684 | // eprintln!("{}", content.trim().on_red()); 685 | for i in colored_diffs.1 { 686 | eprint!("{}", i); 687 | } 688 | eprintln!(); 689 | eprintln!("================================================"); 690 | eprintln!("Sample in: "); 691 | eprintln!("{}", i.expected_in); 692 | } 693 | } 694 | 695 | // Timeout. 696 | None => { 697 | child.kill().unwrap(); 698 | eprintln!("{}", format!("Test #{group_id} failed: TLE(0)").red()); 699 | } 700 | } 701 | } 702 | Err(_) => { 703 | child.kill().unwrap(); 704 | eprintln!("{}", format!("Test #{group_id} failed: TLE(0)").red()); 705 | } 706 | } 707 | group_id += 1; 708 | } 709 | 710 | println!("Total points you get: {}", total_points); 711 | 712 | // Finally remove the files. 713 | if let Err(err) = fs::remove_file(Path::new(&format!("./{}", executable_name))) { 714 | return Err(Some(format!("Failed to remove built target: {err}"))); 715 | } 716 | if let Err(err) = fs::remove_file(temp_in) { 717 | return Err(Some(format!( 718 | "Failed to remove temporary input file: {err}" 719 | ))); 720 | } 721 | Ok(()) 722 | } 723 | } 724 | --------------------------------------------------------------------------------