Auto merge of #89 - matthiasbeyer:libimagrt-init, r=matthiasbeyer

Libimagrt init

Initial code for `libimagrt`.
This commit is contained in:
Homu 2016-01-21 07:59:38 -08:00
commit 2c1fa1a92a
9 changed files with 562 additions and 3 deletions

70
Cargo.lock generated
View file

@ -8,6 +8,35 @@ dependencies = [
"libimagutil 0.1.0",
]
[[package]]
name = "ansi_term"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "bitflags"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "clap"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ansi_term 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"strsim 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"vec_map 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "config"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"nom 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "fs2"
version = "0.2.2"
@ -18,6 +47,11 @@ dependencies = [
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "itertools"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "kernel32-sys"
version = "0.2.1"
@ -39,6 +73,14 @@ version = "0.1.0"
[[package]]
name = "libimagrt"
version = "0.1.0"
dependencies = [
"clap 1.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
"config 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"itertools 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"libimagstore 0.1.0",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"xdg-basedir 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "libimagstore"
@ -52,11 +94,29 @@ dependencies = [
name = "libimagutil"
version = "0.1.0"
[[package]]
name = "log"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "nom"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "rustc-serialize"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "strsim"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "toml"
version = "0.1.25"
@ -65,6 +125,11 @@ dependencies = [
"rustc-serialize 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "vec_map"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi"
version = "0.2.5"
@ -75,3 +140,8 @@ name = "winapi-build"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "xdg-basedir"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"

View file

@ -28,6 +28,10 @@ Table: Default values for configuration if configuration file unavailable
For the configuration file is searched at the following locations:
1. Path: `$runtimepath/config`
1. Path: `$runtimepath/config.toml`
1. Path: `$runtimepath/imagrc`
1. Path: `$runtimepath/imagrc.toml`
1. Path: `$HOME/.imag/config`
1. Path: `$HOME/.imag/config.toml`
1. Path: `$HOME/.imag/imagrc`

130
libimagrt/Cargo.lock generated
View file

@ -1,4 +1,134 @@
[root]
name = "libimagrt"
version = "0.1.0"
dependencies = [
"clap 1.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
"config 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"itertools 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"libimagstore 0.1.0",
"libimagutil 0.1.0",
"log 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
"xdg-basedir 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ansi_term"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "bitflags"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "clap"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ansi_term 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"strsim 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"vec_map 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "config"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"nom 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "fs2"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "itertools"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "kernel32-sys"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "libc"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "libimagstore"
version = "0.1.0"
dependencies = [
"fs2 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"toml 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "libimagutil"
version = "0.1.0"
[[package]]
name = "log"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "nom"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "rustc-serialize"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "strsim"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "toml"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"rustc-serialize 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "vec_map"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi-build"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "xdg-basedir"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"

View file

@ -2,3 +2,17 @@
name = "libimagrt"
version = "0.1.0"
authors = ["Matthias Beyer <mail@beyermatthias.de>"]
[dependencies]
clap = "1.5.5"
config = "0.1.3"
log = "0.3.4"
xdg-basedir = "0.2.2"
itertools = "0.4.6"
[dependencies.libimagstore]
path = "../libimagstore"
[dependencies.libimagutil]
path = "../libimagutil"

6
libimagrt/README.md Normal file
View file

@ -0,0 +1,6 @@
# libimagrt
This library provides utility functionality for the modules and the binary
frontends, such as reading and parsing the configuration file, a builder
helper for the commandline interface and such.

View file

@ -0,0 +1,157 @@
use std::default::Default;
use std::fmt::{Debug, Display, Formatter, Error};
use std::path::PathBuf;
use std::result::Result as RResult;
pub use config::types::Config;
pub use config::reader::from_file;
pub mod error {
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt::Error as FmtError;
#[derive(Clone, Debug, PartialEq)]
pub enum ConfigErrorKind {
ConfigNotFound,
ConfigParsingFailed,
NoConfigFileFound,
}
#[derive(Debug)]
pub struct ConfigError {
kind: ConfigErrorKind,
cause: Option<Box<Error>>,
}
impl ConfigError {
pub fn new(kind: ConfigErrorKind, cause: Option<Box<Error>>) -> ConfigError {
ConfigError {
kind: kind,
cause: cause,
}
}
pub fn kind(&self) -> ConfigErrorKind {
self.kind.clone()
}
pub fn as_str(e: &ConfigError) -> &'static str {
match e.kind() {
ConfigErrorKind::ConfigNotFound => "Config not found",
ConfigErrorKind::ConfigParsingFailed => "Config parsing failed",
ConfigErrorKind::NoConfigFileFound => "No config file found",
}
}
}
impl Display for ConfigError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
try!(write!(fmt, "{}", ConfigError::as_str(self)));
Ok(())
}
}
impl Error for ConfigError {
fn description(&self) -> &str {
ConfigError::as_str(self)
}
fn cause(&self) -> Option<&Error> {
self.cause.as_ref().map(|e| &**e)
}
}
}
use self::error::{ConfigError, ConfigErrorKind};
pub type Result<T> = RResult<T, ConfigError>;
#[derive(Debug)]
pub struct Configuration {
verbosity: bool,
editor: Option<String>,
editor_opts: String,
}
impl Configuration {
pub fn new(rtp: &PathBuf) -> Result<Configuration> {
fetch_config(&rtp).map(|cfg| {
let verbosity = cfg.lookup_boolean("verbosity").unwrap_or(false);
let editor = cfg.lookup_str("editor").map(String::from);
let editor_opts = String::from(cfg.lookup_str("editor-opts").unwrap_or(""));
debug!("Building configuration");
debug!(" - verbosity : {:?}", verbosity);
debug!(" - editor : {:?}", editor);
debug!(" - editor-opts: {}", editor_opts);
Configuration {
verbosity: verbosity,
editor: editor,
editor_opts: editor_opts,
}
})
}
}
fn fetch_config(rtp: &PathBuf) -> Result<Config> {
use std::process::exit;
use std::env;
use xdg_basedir;
use itertools::Itertools;
use libimagutil::variants::generate_variants as gen_vars;
let variants = vec!["config", "config.toml", "imagrc", "imagrc.toml"];
let modifier = |base: &PathBuf, v: &'static str| {
let mut base = base.clone();
base.push(format!("/{}", v));
base
};
vec![
gen_vars(rtp.clone(), variants.clone(), &modifier),
env::var("HOME").map(|home| gen_vars(PathBuf::from(home), variants.clone(), &modifier))
.unwrap_or(vec![]),
xdg_basedir::get_data_home().map(|data_dir| gen_vars(data_dir, variants.clone(), &modifier))
.unwrap_or(vec![]),
].iter()
.flatten()
.filter(|path| path.exists())
.map(|path| {
from_file(&path)
.map_err(|e| {
ConfigError::new(ConfigErrorKind::ConfigParsingFailed, Some(Box::new(e)))
})
})
.filter(|loaded| loaded.is_ok())
.nth(0)
.map(|inner| inner.unwrap())
.ok_or(ConfigError::new(ConfigErrorKind::NoConfigFileFound, None))
}
impl Default for Configuration {
fn default() -> Configuration {
Configuration {
verbosity: false,
editor: Some(String::from("nano")),
editor_opts: String::from(""),
}
}
}

View file

@ -1,3 +1,14 @@
#[test]
fn it_works() {
}
#[macro_use] extern crate log;
#[macro_use] extern crate itertools;
#[cfg(unix)] extern crate xdg_basedir;
extern crate clap;
extern crate config;
extern crate libimagstore;
extern crate libimagutil;
mod configuration;
mod logger;
mod runtime;

30
libimagrt/src/logger.rs Normal file
View file

@ -0,0 +1,30 @@
use log::{Log, LogLevel, LogRecord, LogMetadata};
pub struct ImagLogger {
lvl: LogLevel,
}
impl ImagLogger {
pub fn new(lvl: LogLevel) -> ImagLogger {
ImagLogger {
lvl: lvl,
}
}
}
impl Log for ImagLogger {
fn enabled(&self, metadata: &LogMetadata) -> bool {
metadata.level() <= self.lvl
}
fn log(&self, record: &LogRecord) {
if self.enabled(record.metadata()) {
// TODO: This is just simple logging. Maybe we can enhance this lateron
println!("[imag][{: <5}]: {}", record.level(), record.args());
}
}
}

137
libimagrt/src/runtime.rs Normal file
View file

@ -0,0 +1,137 @@
use std::path::PathBuf;
pub use clap::App;
use clap::{Arg, ArgMatches};
use log;
use log::LogLevelFilter;
use configuration::Configuration;
use logger::ImagLogger;
use libimagstore::store::Store;
pub struct Runtime<'a> {
rtp: PathBuf,
configuration: Configuration,
cli_matches: ArgMatches<'a, 'a>,
store: Store,
}
impl<'a> Runtime<'a> {
/**
* Gets the CLI spec for the program and retreives the config file path (or uses the default on
* in $HOME/.imag/config, $XDG_CONFIG_DIR/imag/config or from env("$IMAG_CONFIG")
* and builds the Runtime object with it.
*
* The cli_spec object should be initially build with the ::get_default_cli_builder() function.
*
*/
pub fn new(cli_spec: App<'a, 'a, 'a, 'a, 'a, 'a>) -> Runtime<'a> {
let matches = cli_spec.get_matches();
let rtp : PathBuf = matches.value_of("runtimepath").unwrap_or("~/.imag/").into();
let storepath = matches.value_of("storepath")
.map(PathBuf::from)
.unwrap_or({
let mut spath = rtp.clone();
spath.push("/store");
spath
});
Runtime {
cli_matches: matches,
configuration: Configuration::new(&rtp).unwrap_or(Configuration::default()),
rtp: rtp,
store: Store::new(storepath),
}
}
/**
* appname should be "imag-foo"
*/
pub fn get_default_cli_builder(appname: &'a str,
version: &'a str,
about: &'a str)
-> App<'a, 'a, 'a, 'a, 'a, 'a>
{
App::new(appname)
.version(version)
.author("Matthias Beyer <mail@beyermatthias.de>")
.about(about)
.arg(Arg::with_name("verbosity")
.short("v")
.long("verbose")
.help("Enables verbosity")
.required(false)
.takes_value(false))
.arg(Arg::with_name("debugging")
.long("debug")
.help("Enables debugging output")
.required(false)
.takes_value(false))
.arg(Arg::with_name("config")
.short("c")
.long("config")
.help("Path to alternative config file")
.required(false)
.takes_value(true))
.arg(Arg::with_name("runtimepath")
.short("r")
.long("rtp")
.help("Alternative runtimepath")
.required(false)
.takes_value(true))
.arg(Arg::with_name("storepath")
.long("store")
.help("Alternative storepath. Must be specified as full path, can be outside of the RTP")
.required(false)
.takes_value(true))
}
pub fn init_logger(&self) {
let lvl = if self.is_debugging() {
LogLevelFilter::Debug
} else if self.is_verbose() {
LogLevelFilter::Info
} else {
LogLevelFilter::Error
};
log::set_logger(|max_log_lvl| {
max_log_lvl.set(lvl);
debug!("Init logger with {}", lvl);
Box::new(ImagLogger::new(lvl.to_log_level().unwrap()))
})
.map_err(|_| {
panic!("Could not setup logger");
})
.ok();
}
pub fn is_verbose(&self) -> bool {
self.cli_matches.is_present("verbosity")
}
pub fn is_debugging(&self) -> bool {
self.cli_matches.is_present("debugging")
}
pub fn rtp(&self) -> &PathBuf {
&self.rtp
}
pub fn cli(&self) -> &ArgMatches {
&self.cli_matches
}
pub fn store(&self) -> &Store {
&self.store
}
}