Skip to content

Commit

Permalink
refactor: use more functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Tricked-dev committed Oct 20, 2021
1 parent ba3c455 commit b80a72a
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 123 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<!-- # Diplo omit in toc -->

[![GitHub issues](https://img.shields.io/github/issues/tricked-dev/diplo?style=for-the-badge)](https://github.com/tricked-dev/diplo/issues)[![GitHub license](https://img.shields.io/github/license/Tricked-dev/diplo?style=for-the-badge)](https://github.com/Tricked-dev/diplo/blob/main/LICENSE)[![Crates.io](https://img.shields.io/crates/d/diplo?label=crate%20downloads&style=for-the-badge)](https://crates.io/crates/diplo/)[![GitHub all releases](https://img.shields.io/github/downloads/tricked-dev/diplo/total?label=github%20downloads&style=for-the-badge)](https://github.com/Tricked-dev/diplo/releases/tag/v0.3.1)[![Discord](https://img.shields.io/discord/748956745409232945?logo=discord&style=for-the-badge)](https://discord.gg/mY8zTARu4g)![Lines of code](https://img.shields.io/tokei/lines/github/tricked-dev/diplo?style=for-the-badge)![GitHub repo size](https://img.shields.io/github/repo-size/tricked-dev/diplo)
[![GitHub issues](https://img.shields.io/github/issues/tricked-dev/diplo?style=for-the-badge)](https://github.com/tricked-dev/diplo/issues)[![GitHub license](https://img.shields.io/github/license/Tricked-dev/diplo?style=for-the-badge)](https://github.com/Tricked-dev/diplo/blob/main/LICENSE)[![Crates.io](https://img.shields.io/crates/d/diplo?label=crate%20downloads&style=for-the-badge)](https://crates.io/crates/diplo/)[![GitHub all releases](https://img.shields.io/github/downloads/tricked-dev/diplo/total?label=github%20downloads&style=for-the-badge)](https://github.com/Tricked-dev/diplo/releases/tag/v0.3.1)[![Discord](https://img.shields.io/discord/748956745409232945?logo=discord&style=for-the-badge)](https://discord.gg/mY8zTARu4g)![Lines of code](https://img.shields.io/tokei/lines/github/tricked-dev/diplo?style=for-the-badge)![GitHub repo size](https://img.shields.io/github/repo-size/tricked-dev/diplo?style=for-the-badge)

### Diplo is a script runner and dependency manager made in rust mainly for [Deno](https://deno.land/).

Expand Down
1 change: 1 addition & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub fn create_app() -> App<'static> {
.arg(
Arg::new("json")
.about("Create a config using the json format instead of toml")
.long_about("Create a config using the json format instead of toml\nThis is not recommended to do due to diplo being build with toml in mind")
.required(false)
.takes_value(false)
.short('j')
Expand Down
1 change: 1 addition & 0 deletions src/bin/diplo.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use diplo::{app::create_app, commands::handle_match};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = create_app().get_matches();
Expand Down
2 changes: 1 addition & 1 deletion src/commands/cache.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{load_config::create_deps, CONFIG, DOTDIPLO};
use crate::{run_utils::create_deps, CONFIG, DOTDIPLO};
use anyhow::Result;
use colored::Colorize;
use serde_json::json;
Expand Down
59 changes: 9 additions & 50 deletions src/commands/exec.rs
Original file line number Diff line number Diff line change
@@ -1,69 +1,28 @@
use crate::{
load_config::create_deps,
run_utils::{append_extra_args, ensure_dependencies, run_script},
utils::load_env,
watcher::{get_config, DiploHandler},
CONFIG, DOTDIPLO,
CONFIG,
};
use anyhow::Result;
use clap::ArgMatches;
use colored::Colorize;
use serde_json::json;
use std::{fs::write, process::Command};
use watchexec::{run::ExecHandler, watch};

pub fn exec(sub_m: &ArgMatches) -> Result<()> {
if let Some(script) = sub_m.values_of("command") {
let mut extra_args: Vec<String> = vec![];
let extra_args: Vec<String> = vec![];

if let Some(dependencies) = &CONFIG.dependencies {
create_deps(dependencies);
if let Some(import_map) = CONFIG.import_map {
if import_map {
let imports = json!({ "imports": dependencies });
write(
format!("{}/import_map.json", &*DOTDIPLO),
serde_json::to_string(&imports)?,
)?;
extra_args.push(format!("--import-map={}/import_map.json", &*DOTDIPLO));
}
}
}
if let Some(load_env) = CONFIG.load_env {
if load_env {
if dotenv::dotenv().is_err() {
println!(
"{}",
format!("no .env file found continuing without loading dotenv").dimmed(),
);
}
}
}
ensure_dependencies()?;
load_env::load_env(CONFIG.load_env);

let mut tp = String::from("deno run ");

//Allow inserting the import-map and future things
tp.push_str(&extra_args.join(" "));
// TODO: replace with intersperse once it becomes stable
let data_2 = script
.collect::<Vec<&str>>()
.join(" ")
.replace("deno run", &tp);
let command = append_extra_args(script.collect::<Vec<&str>>().join(" "), extra_args);

if sub_m.is_present("watch") {
let config = get_config(&data_2);
let config = get_config(&command);
let handler = DiploHandler(ExecHandler::new(config)?);
watch(&handler).unwrap();
} else {
let mut parts = data_2.trim().split_whitespace();

let command = parts.next().unwrap();

let args = parts;

let mut out = Command::new(command).args(args).spawn()?;

if let Err(error) = out.wait() {
println!("{}", error);
}
run_script(command)?;
}
}
Ok(())
Expand Down
1 change: 0 additions & 1 deletion src/commands/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::fs::{self};

pub fn exec(sub_m: &ArgMatches) -> Result<()> {
if fs::File::open(&*DIPLO_CONFIG).is_ok() {
// debug!("{} Already exists", &*DIPLO_CONFIG);
let red = "THIS WILL RESET YOUR CONFIG".red();
println!("{}", red);
}
Expand Down
18 changes: 3 additions & 15 deletions src/commands/install.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
use crate::{load_config::create_deps, CONFIG, DOTDIPLO};
use crate::run_utils::ensure_dependencies;
use anyhow::Result;
use serde_json::json;
use std::fs::write;

pub fn exec() -> Result<()> {
if let Some(dependencies) = &CONFIG.dependencies {
create_deps(dependencies);
if let Some(import_map) = CONFIG.import_map {
if import_map {
let imports = json!({ "imports": dependencies });
write(
format!("{}/import_map.json", &*DOTDIPLO),
serde_json::to_string(&imports)?,
)?;
}
}
}
ensure_dependencies()?;

println!("Successfully initialized diplo");

Ok(())
Expand Down
54 changes: 8 additions & 46 deletions src/commands/run.rs
Original file line number Diff line number Diff line change
@@ -1,69 +1,31 @@
use crate::{
load_config::create_deps,
load_env,
run_utils::{append_extra_args, ensure_dependencies, run_script},
watcher::{get_config, DiploHandler},
CONFIG, DIPLO_CONFIG, DOTDIPLO,
CONFIG, DIPLO_CONFIG,
};
use anyhow::Result;
use clap::ArgMatches;
use colored::Colorize;
use serde_json::json;
use std::{fs::write, process::Command};
use watchexec::{run::ExecHandler, watch};

pub fn exec(sub_m: &ArgMatches) -> Result<()> {
if let Some(script) = sub_m.value_of("script") {
let mut extra_args: Vec<String> = vec![];
let extra_args: Vec<String> = vec![];

if let Some(dependencies) = &CONFIG.dependencies {
create_deps(dependencies);
if let Some(import_map) = CONFIG.import_map {
if import_map {
let imports = json!({ "imports": dependencies });
write(
format!("{}/import_map.json", &*DOTDIPLO),
serde_json::to_string(&imports)?,
)?;
extra_args.push(format!("--import-map={}/import_map.json", &*DOTDIPLO));
}
}
}
if let Some(load_env) = CONFIG.load_env {
if load_env {
if dotenv::dotenv().is_err() {
println!(
"{}",
format!("no .env file found continuing without loading dotenv").dimmed(),
);
}
}
}
ensure_dependencies()?;
load_env::load_env(CONFIG.load_env);

if let Some(data) = CONFIG.scripts.as_ref().unwrap().get(script) {
let mut tp = String::from("deno run ");

//Allow inserting the import-map and future things
tp.push_str(&extra_args.join(" "));

let data_2 = data.replace("deno run", &tp);

let data_2 = append_extra_args(data.to_string(), extra_args);
println!("Starting script {}", script.yellow());
println!("> {}", data.dimmed());
if sub_m.is_present("watch") {
let config = get_config(&data_2);
let handler = DiploHandler(ExecHandler::new(config)?);
watch(&handler)?;
} else {
let mut parts = data_2.trim().split_whitespace();

let command = parts.next().unwrap();

let args = parts;

let mut out = Command::new(command).args(args).spawn()?;

if let Err(error) = out.wait() {
println!("{}", error);
}
run_script(data_2)?;
}

return Ok(());
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ pub mod app;
pub mod commands;
pub mod load_config;
pub mod update_deno;
mod utils;
pub mod watcher;
use lazy_static::lazy_static;
use load_config::{create_config, Config};
use once_cell::sync::Lazy;
use std::env;
use utils::*;

//TODO: use try_exists when released https://github.com/rust-lang/rust/issues/83186
use std::fs::read;
Expand Down
9 changes: 0 additions & 9 deletions src/load_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,6 @@ pub fn create_config() -> Config {
config
}

pub fn create_deps(dependencies: &HashMap<String, String>) {
create_dir_all(&*DOTDIPLO).unwrap();
let mut data: Vec<String> = vec![];
for (_, value) in dependencies.iter() {
data.push(format!("export * from \"{}\"", value))
}
write(format!("{}/deps.ts", &*DOTDIPLO), data.join("\n")).unwrap()
}

pub fn merge(a: &mut Value, b: Value) {
match (a, b) {
(a @ &mut Value::Object(_), Value::Object(b)) => {
Expand Down
13 changes: 13 additions & 0 deletions src/utils/load_env.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use colored::Colorize;
pub fn load_env(data: Option<bool>) {
if let Some(data) = data {
if data {
if dotenv::dotenv().is_err() {
println!(
"{}",
format!("no .env file found continuing without loading dotenv").dimmed(),
);
}
}
}
}
2 changes: 2 additions & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod load_env;
pub mod run_utils;
55 changes: 55 additions & 0 deletions src/utils/run_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use crate::{CONFIG, DOTDIPLO};
use anyhow::Result;
use serde_json::json;
use std::{
collections::HashMap,
fs::{create_dir_all, write},
process::Command,
};

pub fn create_deps(dependencies: &HashMap<String, String>) {
create_dir_all(&*DOTDIPLO).unwrap();
let mut data: Vec<String> = vec![];
for (_, value) in dependencies.iter() {
data.push(format!("export * from \"{}\"", value))
}
write(format!("{}/deps.ts", &*DOTDIPLO), data.join("\n")).unwrap()
}

pub fn ensure_dependencies() -> Result<()> {
if let Some(dependencies) = &CONFIG.dependencies {
create_deps(dependencies);
if let Some(import_map) = CONFIG.import_map {
if import_map {
let imports = json!({ "imports": dependencies });
write(
format!("{}/import_map.json", &*DOTDIPLO),
serde_json::to_string(&imports)?,
)?;
}
}
}
Ok(())
}

pub fn append_extra_args(input: String, extra_args: Vec<String>) -> String {
let mut data = "deno run ".to_owned();
//Allow inserting the import-map and future things
data.push_str(&extra_args.join(" "));
input.replace("deno run", &data)
}

pub fn run_script(command: String) -> Result<()> {
let mut parts = command.trim().split_whitespace();

let command = parts.next().unwrap();

let args = parts;

let mut out = Command::new(command).args(args).spawn()?;

if let Err(error) = out.wait() {
println!("{}", error);
}
Ok(())
}

0 comments on commit b80a72a

Please sign in to comment.