Skip to content

Commit

Permalink
auto formatted code with rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
ko1N authored and reitermarkus committed Jun 29, 2020
1 parent d639381 commit 082fe6f
Show file tree
Hide file tree
Showing 13 changed files with 766 additions and 530 deletions.
57 changes: 30 additions & 27 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::env;
use std::path::PathBuf;

use clap::{App, Arg, ArgGroup, ArgMatches, SubCommand, AppSettings};
use clap::{App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand};
use dirs;

use crate::templates;
Expand All @@ -10,24 +10,24 @@ const NAME: &str = "cargo-eval";

#[inline(always)]
const fn name() -> &'static str {
NAME
NAME
}

#[inline(always)]
fn subcommand_name() -> &'static str {
&name()[6..]
&name()[6..]
}

pub fn data_dir() -> Option<PathBuf> {
Some(dirs::data_local_dir()?.join(name()))
Some(dirs::data_local_dir()?.join(name()))
}

pub fn cache_dir() -> Option<PathBuf> {
Some(dirs::cache_dir()?.join(name()))
Some(dirs::cache_dir()?.join(name()))
}

fn app() -> App<'static, 'static> {
let mut app = SubCommand::with_name(subcommand_name())
let mut app = SubCommand::with_name(subcommand_name())
.version(env!("CARGO_PKG_VERSION"))
.about("Compiles and runs “Cargoified Rust scripts”.")
.usage("cargo eval [FLAGS OPTIONS] [--] <script> <args>...")
Expand Down Expand Up @@ -152,30 +152,33 @@ fn app() -> App<'static, 'static> {
.requires("expr")
);

#[cfg(windows)] {
app = app.subcommand(crate::file_assoc::Args::subcommand())
}
#[cfg(windows)]
{
app = app.subcommand(crate::file_assoc::Args::subcommand())
}

app = app.subcommand(templates::Args::subcommand());
app = app.subcommand(templates::Args::subcommand());

app
app
}

pub fn get_matches() -> ArgMatches<'static> {
let mut args = env::args().collect::<Vec<_>>();

let subcommand = app();

// Insert subcommand argument if called directly.
if args.get(1).map(|s| *s == subcommand_name()) != Some(true) {
args.insert(1, subcommand_name().into());
}

// We have to wrap our command for the output to look right.
App::new("cargo")
.bin_name("cargo")
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(subcommand)
.get_matches_from(args)
.subcommand_matches(subcommand_name()).unwrap().clone()
let mut args = env::args().collect::<Vec<_>>();

let subcommand = app();

// Insert subcommand argument if called directly.
if args.get(1).map(|s| *s == subcommand_name()) != Some(true) {
args.insert(1, subcommand_name().into());
}

// We have to wrap our command for the output to look right.
App::new("cargo")
.bin_name("cargo")
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(subcommand)
.get_matches_from(args)
.subcommand_matches(subcommand_name())
.unwrap()
.clone()
}
26 changes: 17 additions & 9 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ Records who we have chosen to blame for a particular error.
This is used to distinguish between "report this to a user" and "explode violently".
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Blame { Human, Internal }
pub enum Blame {
Human,
Internal,
}

impl MainError {
pub fn blame(&self) -> Blame {
Expand All @@ -41,7 +44,7 @@ impl MainError {
| Tag(blame, _, _)
| Other(blame, _)
| OtherOwned(blame, _)
| OtherBorrowed(blame, _) => blame
| OtherBorrowed(blame, _) => blame,
}
}

Expand All @@ -56,8 +59,7 @@ impl MainError {
| Tag(ref mut cur_blame, _, _)
| Other(ref mut cur_blame, _)
| OtherOwned(ref mut cur_blame, _)
| OtherBorrowed(ref mut cur_blame, _)
=> *cur_blame = blame,
| OtherBorrowed(ref mut cur_blame, _) => *cur_blame = blame,
}
}
}
Expand Down Expand Up @@ -96,7 +98,7 @@ macro_rules! from_impl {
$e
}
}
}
};
}

from_impl! { (Blame, io::Error) => MainError, v -> MainError::Io(v.0, v.1) }
Expand All @@ -106,7 +108,10 @@ from_impl! { io::Error => MainError, v -> MainError::Io(Blame::Internal, v) }
from_impl! { String => MainError, v -> MainError::OtherOwned(Blame::Internal, v) }
from_impl! { &'static str => MainError, v -> MainError::OtherBorrowed(Blame::Internal, v) }

impl<T> From<Box<T>> for MainError where T: 'static + Error {
impl<T> From<Box<T>> for MainError
where
T: 'static + Error,
{
fn from(src: Box<T>) -> Self {
MainError::Other(Blame::Internal, src)
}
Expand All @@ -115,7 +120,8 @@ impl<T> From<Box<T>> for MainError where T: 'static + Error {
pub trait ResultExt {
type Ok;
fn err_tag<S>(self, msg: S) -> Result<Self::Ok>
where S: Into<Cow<'static, str>>;
where
S: Into<Cow<'static, str>>;

fn shift_blame(self, blame: Blame) -> Self;
}
Expand All @@ -124,7 +130,9 @@ impl<T> ResultExt for Result<T> {
type Ok = T;

fn err_tag<S>(self, msg: S) -> Result<T>
where S: Into<Cow<'static, str>> {
where
S: Into<Cow<'static, str>>,
{
match self {
Ok(v) => Ok(v),
Err(e) => Err(MainError::Tag(e.blame(), msg.into(), Box::new(e))),
Expand All @@ -137,7 +145,7 @@ impl<T> ResultExt for Result<T> {
Err(mut e) => {
e.shift_blame(blame);
Err(e)
},
}
}
}
}
60 changes: 35 additions & 25 deletions src/file_assoc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::io;

use clap;
use itertools::Itertools;
use winreg::{RegKey, enums as wre};
use winreg::{enums as wre, RegKey};

use crate::error::{Blame, Result};

Expand Down Expand Up @@ -36,13 +36,11 @@ impl Args {

pub fn parse(m: &clap::ArgMatches) -> Self {
match m.subcommand() {
("install", Some(m)) => {
Args::Install {
amend_pathext: m.is_present("amend_pathext"),
}
("install", Some(m)) => Args::Install {
amend_pathext: m.is_present("amend_pathext"),
},
("uninstall", _) => Args::Uninstall,
(name, _) => panic!("bad subcommand: {:?}", name)
(name, _) => panic!("bad subcommand: {:?}", name),
}
}
}
Expand Down Expand Up @@ -88,7 +86,9 @@ fn install(amend_pathext: bool) -> Result<()> {
Ok(()) => (),
Err(e) => {
if e.kind() == io::ErrorKind::PermissionDenied {
println!("Access denied. Make sure you run this command from an administrator prompt.");
println!(
"Access denied. Make sure you run this command from an administrator prompt."
);
return Err((Blame::Human, e).into());
} else {
return Err(e.into());
Expand All @@ -102,36 +102,46 @@ fn install(amend_pathext: bool) -> Result<()> {
// Amend PATHEXT.
if amend_pathext {
let hklm = RegKey::predef(wre::HKEY_LOCAL_MACHINE);
let env = hklm.open_subkey(r#"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"#)?;
let env =
hklm.open_subkey(r#"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"#)?;

let pathext: String = env.get_value("PATHEXT")?;
if !pathext.split(';').any(|e| e.eq_ignore_ascii_case(".crs")) {
let pathext = pathext.split(';').chain(Some(".CRS")).join(";");
env.set_value("PATHEXT", &pathext)?;
}

println!("Added `.crs` to PATHEXT. You may need to log out for the change to take effect.");
println!(
"Added `.crs` to PATHEXT. You may need to log out for the change to take effect."
);
}

Ok(())
}

fn uninstall() -> Result<()> {
let hlcr = RegKey::predef(wre::HKEY_CLASSES_ROOT);
hlcr.delete_subkey(r#"CargoScript.Crs\shell\open\command"#).ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs\shell\open"#).ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs\shell"#).ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs"#).ignore_missing()?;
let hlcr = RegKey::predef(wre::HKEY_CLASSES_ROOT);
hlcr.delete_subkey(r#"CargoScript.Crs\shell\open\command"#)
.ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs\shell\open"#)
.ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs\shell"#)
.ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs"#).ignore_missing()?;

println!("Deleted cargo-eval registry entry.");

{
let hklm = RegKey::predef(wre::HKEY_LOCAL_MACHINE);
let env = hklm.open_subkey(r#"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"#)?;
let env =
hklm.open_subkey(r#"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"#)?;

let pathext: String = env.get_value("PATHEXT")?;
if pathext.split(';').any(|e| e.eq_ignore_ascii_case(".crs")) {
let pathext = pathext.split(';').filter(|e| !e.eq_ignore_ascii_case(".crs")).join(";");
let pathext = pathext
.split(';')
.filter(|e| !e.eq_ignore_ascii_case(".crs"))
.join(";");
env.set_value("PATHEXT", &pathext)?;
println!("Removed `.crs` from PATHEXT. You may need to log out for the change to take effect.");
}
Expand All @@ -141,17 +151,17 @@ fn uninstall() -> Result<()> {
}

trait IgnoreMissing {
fn ignore_missing(self) -> Self;
fn ignore_missing(self) -> Self;
}

impl IgnoreMissing for io::Result<()> {
fn ignore_missing(self) -> Self {
if let Err(ref e) = self {
if e.kind() == io::ErrorKind::NotFound {
return Ok(())
}
}
fn ignore_missing(self) -> Self {
if let Err(ref e) = self {
if e.kind() == io::ErrorKind::NotFound {
return Ok(());
}
}

self
}
self
}
}
Loading

0 comments on commit 082fe6f

Please sign in to comment.