feat: v0.2
This commit is contained in:
36
src/help.rs
Normal file
36
src/help.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
pub fn print_help() {
|
||||
println!(r##"{} v{} - {}
|
||||
|
||||
Show help:
|
||||
$ runrs -h|--help
|
||||
|
||||
Show template:
|
||||
$ runrs -t|--template
|
||||
|
||||
Install script:
|
||||
$ runrs -i|--install <script.rs>
|
||||
|
||||
Run script:
|
||||
$ runrs <script.rs> [arguments]
|
||||
|
||||
Binaries dir:
|
||||
~/Library/Caches/rust-script/binaries/release/
|
||||
|
||||
Environment variables:
|
||||
┌──────────────────────┬────────────────────────────────────────────────┐
|
||||
│ Variable │ Description │
|
||||
├──────────────────────┼────────────────────────────────────────────────┤
|
||||
│ HOME │ User home, default by OS system │
|
||||
│ RUNRS_SKIP_CACHE │ Skip compiled cached file, `bool` │
|
||||
│ RUNRS_REBUILD │ Force rebuild, `bool` │
|
||||
│ RUNRS_SILENT_BUILD │ Build new binary in silent mode, `bool` │
|
||||
│ RUNRS_RUST_SCRIPT │ `rust_script` command line bin file │
|
||||
│ RUNRS_MAX_SCRIPT_LEN │ Max script length, default 1MB │
|
||||
└──────────────────────┴────────────────────────────────────────────────┘
|
||||
> Type `bool`: `true`, `yes`, `on` or `1` for true, otherwise false
|
||||
"##,
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
env!("CARGO_PKG_DESCRIPTION")
|
||||
);
|
||||
}
|
||||
35
src/install.rs
Normal file
35
src/install.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
const SCRIPT_PATTERN: &'static str = "https://git.hatter.ink/rust-scripts/scriptbase/raw/branch/main/$NAME/src/main.rs";
|
||||
|
||||
pub fn install_script(args: Vec<&String>) {
|
||||
if args.is_empty() {
|
||||
failure!("No script name assigned!");
|
||||
}
|
||||
let script_name = &args[0];
|
||||
let normalized_script_name = if script_name.ends_with(".rs") {
|
||||
script_name.chars().take(script_name.len() - 3).collect::<String>() + "-rs"
|
||||
} else if script_name.ends_with("-rs") {
|
||||
script_name.to_string()
|
||||
} else {
|
||||
failure_and_exit!("Invalid script name: {}", script_name);
|
||||
};
|
||||
|
||||
let script_url = SCRIPT_PATTERN.replace("$NAME", &normalized_script_name);
|
||||
information!("Script URL: {}", &script_url);
|
||||
|
||||
let get_script_response_result = reqwest::blocking::get(script_url);
|
||||
debugging!("Get script response: {:#?}", &get_script_response_result);
|
||||
|
||||
let get_script_response = match get_script_response_result {
|
||||
Err(e) => {
|
||||
failure_and_exit!("Get script failed: {}", e);
|
||||
}
|
||||
Ok(response) => { response }
|
||||
};
|
||||
let get_script_response_status = get_script_response.status().as_u16();
|
||||
if get_script_response_status == 404 {
|
||||
failure_and_exit!("Script not found!");
|
||||
} else if get_script_response_status != 200 {
|
||||
failure_and_exit!("Get script failed: {}", get_script_response_status);
|
||||
}
|
||||
success!("{}", get_script_response.text().unwrap());
|
||||
}
|
||||
163
src/main.rs
163
src/main.rs
@@ -1,17 +1,22 @@
|
||||
#[macro_use]
|
||||
extern crate rust_util;
|
||||
|
||||
use std::{env, fs, process};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::SystemTime;
|
||||
use std::env;
|
||||
|
||||
use rust_util::util_cmd;
|
||||
use rust_util::util_os::get_user_home;
|
||||
|
||||
use crate::help::print_help;
|
||||
use crate::install::install_script;
|
||||
use crate::util::{build_script_command, get_run_script_bin_name, read_file_and_digest, run_script_command};
|
||||
|
||||
mod util;
|
||||
mod help;
|
||||
mod install;
|
||||
|
||||
const SCRIPT_TEMPLATE: &'static str = include_str!("script.template");
|
||||
|
||||
fn main() {
|
||||
let user_home = get_user_home();
|
||||
let user_home = get_user_home().unwrap_or_else(|| failure_and_exit!("$HOME not found!"));
|
||||
let rust_script = get_run_script_bin_name(&user_home);
|
||||
|
||||
let args = env::args().skip(1).collect::<Vec<_>>();
|
||||
@@ -27,6 +32,10 @@ fn main() {
|
||||
println!("{}", SCRIPT_TEMPLATE);
|
||||
return;
|
||||
}
|
||||
if first_argument == "--install" || first_argument == "-i" {
|
||||
install_script(args.iter().skip(1).collect());
|
||||
return;
|
||||
}
|
||||
|
||||
let script_file = first_argument;
|
||||
|
||||
@@ -40,145 +49,3 @@ fn main() {
|
||||
}
|
||||
run_script_command(script_file, &cache_script_bin_name, &mut run_script_cmd)
|
||||
}
|
||||
|
||||
fn build_script_command(rust_script: PathBuf, script_file: &str, script_sha256: &str, cache_script_bin_name: &str) -> Command {
|
||||
let skip_cache = is_env_on("RUNRS_SKIP_CACHE");
|
||||
let rebuild = is_env_on("RUNRS_REBUILD");
|
||||
let cache_script_bin_name_exists = fs::metadata(&cache_script_bin_name).is_ok();
|
||||
debugging!("Bin name: {} {}exists", cache_script_bin_name, iff!(cache_script_bin_name_exists, "", "not "));
|
||||
if !rebuild && !skip_cache && cache_script_bin_name_exists {
|
||||
Command::new(&cache_script_bin_name)
|
||||
} else {
|
||||
let mut cmd = Command::new(rust_script);
|
||||
if !is_env_on("RUNRS_SILENT_BUILD") {
|
||||
information!("Cached binary not exists, RUNRS_SILENT_BUILD=1 turn off");
|
||||
cmd.arg("--cargo-output");
|
||||
}
|
||||
if rebuild {
|
||||
cmd.arg("--force");
|
||||
}
|
||||
cmd.args(&["--bin-name", &script_sha256, script_file]);
|
||||
cmd
|
||||
}
|
||||
}
|
||||
|
||||
fn run_script_command(script_file: &str, cache_script_bin_name: &str, mut run_script_cmd: &mut Command) -> ! {
|
||||
debugging!("Run command: {:?}", run_script_cmd);
|
||||
let run_command_start = SystemTime::now();
|
||||
match util_cmd::run_command_and_wait(&mut run_script_cmd) {
|
||||
Err(e) => failure_and_exit!("Run rust-script failed: {}", e),
|
||||
Ok(exit_status) => {
|
||||
write_script_file_to_src(script_file, cache_script_bin_name);
|
||||
if let Ok(run_command_cost) = SystemTime::now().duration_since(run_command_start) {
|
||||
debugging!("Run command cost: {}ms", run_command_cost.as_millis());
|
||||
}
|
||||
process::exit(exit_status.code().unwrap_or_else(|| 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_script_file_to_src(script_file: &str, cache_script_bin_name: &str) {
|
||||
if let Ok(Some(canonicalized_script_file)) = PathBuf::from(script_file)
|
||||
.canonicalize().map(|f| f.to_str().map(|f| f.to_string())) {
|
||||
let cache_script_bin_name_src = format!("{}.src", cache_script_bin_name);
|
||||
let src_content = fs::read_to_string(&cache_script_bin_name_src).ok();
|
||||
if src_content.as_ref().map(|c| c.contains(&canonicalized_script_file)).unwrap_or_else(|| false) {
|
||||
return;
|
||||
}
|
||||
let new_src_content = src_content.unwrap_or_else(|| "".to_string()) + &format!("{}\n", canonicalized_script_file);
|
||||
if let Ok(_) = fs::write(&cache_script_bin_name_src, &new_src_content) {
|
||||
debugging!("Add {} to {}", canonicalized_script_file, cache_script_bin_name_src);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_help() {
|
||||
println!(r##"{} v{} - {}
|
||||
|
||||
Show help:
|
||||
$ runrs -h|--help
|
||||
|
||||
Show template:
|
||||
$ runrs -t|--template
|
||||
|
||||
Run script:
|
||||
$ runrs <script.rs> [arguments]
|
||||
|
||||
Binaries dir:
|
||||
~/Library/Caches/rust-script/binaries/release/
|
||||
|
||||
Environment variables:
|
||||
┌──────────────────────┬────────────────────────────────────────────────┐
|
||||
│ Variable │ Description │
|
||||
├──────────────────────┼────────────────────────────────────────────────┤
|
||||
│ HOME │ User home, default by OS system │
|
||||
│ RUNRS_SKIP_CACHE │ Skip compiled cached file, `bool` │
|
||||
│ RUNRS_REBUILD │ Force rebuild, `bool` │
|
||||
│ RUNRS_SILENT_BUILD │ Build new binary in silent mode, `bool` │
|
||||
│ RUNRS_RUST_SCRIPT │ `rust_script` command line bin file │
|
||||
│ RUNRS_MAX_SCRIPT_LEN │ Max script length, default 1MB │
|
||||
└──────────────────────┴────────────────────────────────────────────────┘
|
||||
> Type `bool`: `true`, `yes`, `on` or `1` for true, otherwise false
|
||||
"##,
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
env!("CARGO_PKG_DESCRIPTION")
|
||||
);
|
||||
}
|
||||
|
||||
fn read_file_and_digest(script_file: &str) -> (String, String) {
|
||||
let default_max_script_len = 1024 * 1024;
|
||||
let max_script_len: u64 = env::var("RUNRS_MAX_SCRIPT_LEN")
|
||||
.map(|len| len.parse().unwrap_or_else(|_| default_max_script_len)).unwrap_or_else(|_| default_max_script_len);
|
||||
match fs::metadata(script_file) {
|
||||
Err(_) => failure_and_exit!("Script file not exists: {}", script_file),
|
||||
Ok(metadata) => if metadata.is_dir() {
|
||||
failure_and_exit!("Assigned input is dir: {}", script_file);
|
||||
} else if metadata.len() > max_script_len {
|
||||
failure_and_exit!("Script file: {} too large: {}", script_file, metadata.len());
|
||||
}
|
||||
}
|
||||
let script_content = fs::read_to_string(script_file).unwrap_or_else(|e|
|
||||
failure_and_exit!("Read file: {}, failed: {}", script_file, e)
|
||||
);
|
||||
let script_sha256 = sha256::digest(script_content.as_str());
|
||||
|
||||
(script_content, script_sha256)
|
||||
}
|
||||
|
||||
fn get_run_script_bin_name(home: &str) -> PathBuf {
|
||||
if let Ok(rust_script) = env::var("RUNRS_RUST_SCRIPT") {
|
||||
let rust_script_path_buf = PathBuf::from(&rust_script);
|
||||
if !rust_script_path_buf.exists() {
|
||||
warning!("RUST_SCRIPT={} not exists", &rust_script);
|
||||
}
|
||||
return rust_script_path_buf;
|
||||
}
|
||||
let rust_script = PathBuf::from(format!("{}/.cargo/bin/rust-script", home));
|
||||
if !rust_script.exists() {
|
||||
warning!("rust-script not found, install it...");
|
||||
let mut cargo_install_rust_script = Command::new("cargo");
|
||||
cargo_install_rust_script.args(&["install", "--git", "https://git.hatter.ink/hatter/runrs", "rust-script"]);
|
||||
debugging!("Run command: {:?}", cargo_install_rust_script);
|
||||
match util_cmd::run_command_and_wait(&mut cargo_install_rust_script) {
|
||||
Err(e) => failure_and_exit!("Install rust-script failed: {}", e),
|
||||
Ok(exist_status) => if !exist_status.success() {
|
||||
failure!("Install rust-script not success: {}", exist_status);
|
||||
},
|
||||
}
|
||||
}
|
||||
rust_script
|
||||
}
|
||||
|
||||
fn is_env_on(env: &str) -> bool {
|
||||
env::var(env).map(|v| {
|
||||
let v = v.to_lowercase();
|
||||
v == "true" || v == "on" || v == "yes" || v == "1"
|
||||
}).unwrap_or_else(|_| false)
|
||||
}
|
||||
|
||||
fn get_user_home() -> String {
|
||||
env::var("HOME").unwrap_or_else(|_|
|
||||
failure_and_exit!("$HOME not found!")
|
||||
)
|
||||
}
|
||||
102
src/util.rs
Normal file
102
src/util.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
use std::{env, fs, process};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::SystemTime;
|
||||
use rust_util::util_cmd;
|
||||
use rust_util::util_env::is_env_on;
|
||||
|
||||
|
||||
pub fn build_script_command(rust_script: PathBuf, script_file: &str, script_sha256: &str, cache_script_bin_name: &str) -> Command {
|
||||
let skip_cache = is_env_on("RUNRS_SKIP_CACHE");
|
||||
let rebuild = is_env_on("RUNRS_REBUILD");
|
||||
let cache_script_bin_name_exists = fs::metadata(&cache_script_bin_name).is_ok();
|
||||
debugging!("Bin name: {} {}exists", cache_script_bin_name, iff!(cache_script_bin_name_exists, "", "not "));
|
||||
if !rebuild && !skip_cache && cache_script_bin_name_exists {
|
||||
Command::new(&cache_script_bin_name)
|
||||
} else {
|
||||
let mut cmd = Command::new(rust_script);
|
||||
if !is_env_on("RUNRS_SILENT_BUILD") {
|
||||
information!("Cached binary not exists, RUNRS_SILENT_BUILD=1 turn off");
|
||||
cmd.arg("--cargo-output");
|
||||
}
|
||||
if rebuild {
|
||||
cmd.arg("--force");
|
||||
}
|
||||
cmd.args(&["--bin-name", &script_sha256, script_file]);
|
||||
cmd
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_script_command(script_file: &str, cache_script_bin_name: &str, mut run_script_cmd: &mut Command) -> ! {
|
||||
debugging!("Run command: {:?}", run_script_cmd);
|
||||
let run_command_start = SystemTime::now();
|
||||
match util_cmd::run_command_and_wait(&mut run_script_cmd) {
|
||||
Err(e) => failure_and_exit!("Run rust-script failed: {}", e),
|
||||
Ok(exit_status) => {
|
||||
write_script_file_to_src(script_file, cache_script_bin_name);
|
||||
if let Ok(run_command_cost) = SystemTime::now().duration_since(run_command_start) {
|
||||
debugging!("Run command cost: {}ms", run_command_cost.as_millis());
|
||||
}
|
||||
process::exit(exit_status.code().unwrap_or_else(|| 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_script_file_to_src(script_file: &str, cache_script_bin_name: &str) {
|
||||
if let Ok(Some(canonicalized_script_file)) = PathBuf::from(script_file)
|
||||
.canonicalize().map(|f| f.to_str().map(|f| f.to_string())) {
|
||||
let cache_script_bin_name_src = format!("{}.src", cache_script_bin_name);
|
||||
let src_content = fs::read_to_string(&cache_script_bin_name_src).ok();
|
||||
if src_content.as_ref().map(|c| c.contains(&canonicalized_script_file)).unwrap_or_else(|| false) {
|
||||
return;
|
||||
}
|
||||
let new_src_content = src_content.unwrap_or_else(|| "".to_string()) + &format!("{}\n", canonicalized_script_file);
|
||||
if let Ok(_) = fs::write(&cache_script_bin_name_src, &new_src_content) {
|
||||
debugging!("Add {} to {}", canonicalized_script_file, cache_script_bin_name_src);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_run_script_bin_name(home: &str) -> PathBuf {
|
||||
if let Ok(rust_script) = env::var("RUNRS_RUST_SCRIPT") {
|
||||
let rust_script_path_buf = PathBuf::from(&rust_script);
|
||||
if !rust_script_path_buf.exists() {
|
||||
warning!("RUST_SCRIPT={} not exists", &rust_script);
|
||||
}
|
||||
return rust_script_path_buf;
|
||||
}
|
||||
let rust_script = PathBuf::from(format!("{}/.cargo/bin/rust-script", home));
|
||||
if !rust_script.exists() {
|
||||
warning!("rust-script not found, install it...");
|
||||
let mut cargo_install_rust_script = Command::new("cargo");
|
||||
cargo_install_rust_script.args(&["install", "--git", "https://git.hatter.ink/hatter/runrs", "rust-script"]);
|
||||
debugging!("Run command: {:?}", cargo_install_rust_script);
|
||||
match util_cmd::run_command_and_wait(&mut cargo_install_rust_script) {
|
||||
Err(e) => failure_and_exit!("Install rust-script failed: {}", e),
|
||||
Ok(exist_status) => if !exist_status.success() {
|
||||
failure!("Install rust-script not success: {}", exist_status);
|
||||
},
|
||||
}
|
||||
}
|
||||
rust_script
|
||||
}
|
||||
|
||||
pub fn read_file_and_digest(script_file: &str) -> (String, String) {
|
||||
let default_max_script_len = 1024 * 1024;
|
||||
let max_script_len: u64 = env::var("RUNRS_MAX_SCRIPT_LEN")
|
||||
.map(|len| len.parse().unwrap_or_else(|_| default_max_script_len)).unwrap_or_else(|_| default_max_script_len);
|
||||
match fs::metadata(script_file) {
|
||||
Err(_) => failure_and_exit!("Script file not exists: {}", script_file),
|
||||
Ok(metadata) => if metadata.is_dir() {
|
||||
failure_and_exit!("Assigned input is dir: {}", script_file);
|
||||
} else if metadata.len() > max_script_len {
|
||||
failure_and_exit!("Script file: {} too large: {}", script_file, metadata.len());
|
||||
}
|
||||
}
|
||||
let script_content = fs::read_to_string(script_file).unwrap_or_else(|e|
|
||||
failure_and_exit!("Read file: {}, failed: {}", script_file, e)
|
||||
);
|
||||
let script_sha256 = sha256::digest(script_content.as_str());
|
||||
|
||||
(script_content, script_sha256)
|
||||
}
|
||||
Reference in New Issue
Block a user