Skip to content

Instantly share code, notes, and snippets.

@shadowmint
Created September 15, 2014 03:11
Show Gist options
  • Select an option

  • Save shadowmint/b069144f6d528adfb2e7 to your computer and use it in GitHub Desktop.

Select an option

Save shadowmint/b069144f6d528adfb2e7 to your computer and use it in GitHub Desktop.
use std::io::{File,IoResult,UserRWX};
use std::os;
use std::io::TempDir;
use std::io::fs;
pub struct FileUtils {
pub path:Option<TempDir>
}
impl FileUtils {
// Create a new temporary folder
pub fn new() -> FileUtils {
match TempDir::new("tmp") {
Ok(d) => {
return FileUtils {
path: Some(d)
};
},
Err(e) => {
trace!("{}", e);
fail!("Unable to create temporary folder");
}
}
return FileUtils {
path: None
};
}
// Add folder
pub fn folder(&self, path:&str) {
let target = self.path.as_ref().unwrap().path().join(path);
fs::mkdir_recursive(&target, UserRWX).unwrap_or_else(|why| {
println!("! {}", why.kind);
});
//trace!("Created: {}", target.as_str());
}
// Create a file
pub fn file(&self, path:&str) {
let s = "tmp";
let target = self.path.as_ref().unwrap().path().join(path);
File::create(&target).and_then(|mut f| f.write_str(s));
}
// Update a file
pub fn touch(&self, path:&str) {
/*if !path.exists() {
File::create(path).and_then(|_| Ok(()))
}*/
}
// Delete a file
pub fn delete(&self, path:&str) {
/*fs::unlink(&Path::new("a/c/e.txt")).unwrap_or_else(|why| {
println!("! {}", why.kind);
});*/
}
}
#![macro_escape]
use std::io::LineBufferedWriter;
use std::io::stdio::StdWriter;
use std::mem::transmute;
static mut stdout_:*mut LineBufferedWriter<StdWriter> = 0 as *mut LineBufferedWriter<StdWriter>;
#[allow(dead_code)]
pub fn stdout<'a>() -> &'a mut LineBufferedWriter<StdWriter> {
unsafe {
if stdout_.is_null() {
let s = box ::std::io::stdout();
stdout_ = transmute(s);
}
}
unsafe {
return &mut (*stdout_);
}
}
/**
* Create a new T with default values.
* usage:
*
* let x:T = default!();
* let x = default!(Foo, x:1);
* let x = default!(Foo);
*/
#[macro_export]
macro_rules! default(
($T:ident, $($k:ident: $v:expr), *) => (
$T { $($k: $v), *, ..::std::default::Default::default() }
);
($T:ident) => (
$T { ..::std::default::Default::default() }
);
() => (
::std::default::Default::default();
);
)
/**
* Debug print immediately to stdout
* usage:
*
* trace!("Hello: {}", 1);
*/
#[macro_export]
macro_rules! trace(
{$($arg:tt)*} => {
{
let s = ::fixtures::macros::stdout();
let _foo = s.write_line(format_args!(::std::fmt::format, $($arg)*).as_slice());
}
};
)
/**
* Fabricate any T that implments std::container::MutableMap
* usage:
*
* let mut hm = map! {HashMap, "a string" => 21, "another string" => 33 };
*/
#[macro_export]
macro_rules! map(
{ $T:ident, $($key:expr => $value:expr),+ } => {
{
let mut m = $T::new();
$(
m.insert($key, $value);
)+
m
}
};
)
#[cfg(test)]
mod tests {
extern crate collections;
use std::collections::hashmap::HashMap;
use std::default::Default;
#[deriving(Show)]
struct Foo {
x:int,
y:int,
z:int,
a:int,
b:int,
c:int
}
impl Default for Foo {
fn default() -> Foo {
return Foo { x: 1, y: 2, z: 3, a: 4, b: 5, c: 6};
}
}
#[test]
fn test_default_works() {
let x:Foo = default!();
assert!(x.x == 1);
assert!(x.y == 2);
assert!(x.z == 3);
assert!(x.a == 4);
assert!(x.b == 5);
assert!(x.c == 6);
}
#[test]
fn test_default_works_with_x_args() {
let x = default!(Foo, x:9, a:0, b:1, c:2);
assert!(x.x == 9);
assert!(x.y == 2);
assert!(x.z == 3);
assert!(x.a == 0);
assert!(x.b == 1);
assert!(x.c == 2);
}
#[test]
fn test_default_works_with_y_args() {
let x = default!(Foo, y:1, z:9, c:0);
assert!(x.x == 1);
assert!(x.y == 1);
assert!(x.z == 9);
assert!(x.a == 4);
assert!(x.b == 5);
assert!(x.c == 0);
}
fn t_factory<T: Default>() -> T {
let rtn:T = default!();
return rtn;
}
#[test]
fn test_default_works_with_unknown_t() {
let x = t_factory::<Foo>();
assert!(x.x == 1);
assert!(x.y == 2);
assert!(x.z == 3);
assert!(x.a == 4);
assert!(x.b == 5);
assert!(x.c == 6);
}
#[test]
fn test_default_works_with_primitive_t() {
let x = t_factory::<int>();
let y = t_factory::<f64>();
assert!(x == 0);
assert!(y == 0.0);
}
#[test]
fn test_trace_macro() {
// trace!("Trace test: {} {}", 0u, 2i);
}
#[test]
fn test_map_create() {
let mut hm = map! {HashMap, "a string" => 21u, "another string" => 33u };
hm.insert("and another", 43);
for (k, v) in hm.iter() {
println!("Map ({}, {})", *k, *v);
}
}
}
pub mod macros;
pub mod file;
mod fixtures;
use libc::c_void;
use glob::Glob;
/// Change event types
#[deriving(PartialEq)]
enum WatchEvents {
Delete,
Create,
Modify
}
/// Watcher to look for changes in files
struct Watch {
glob:Glob,
rvm:Vec<*mut c_void>,
pub paths:Vec<String>,
pub callback:Option<fn(&String, WatchEvents)>
}
impl Watch {
/// Create a new instance
pub fn new() -> Watch {
return Watch {
glob: Glob::new(),
rvm: Vec::new(),
paths: Vec::new(),
callback: None
};
}
/// Add a set of patterns matching the given glob expr
/// Note that watching won't actually start until watch() is invoked.
pub fn pattern(&mut self, glob:&str) {
self.glob.parse(glob);
}
/// Start watching for changes in any of the files matching known patterns
pub fn watch(&mut self, path:&str) {
for path in self.glob.iter(path) {
// TODO: Expand glob
}
}
/// Poll for events and dispatch then to the callback if it is set
pub fn poll(&self) {
}
}
pub fn watch() {
println!("Hi");
}
#[cfg(test)]
mod tests {
use super::Watch;
use fixtures::file::FileUtils;
#[register(file)]
fn file_fixture() -> FileUtils {
let rtn = FileUtils::new();
return rtn;
}
#[test]
#[fixture(file)]
fn test_watch_existing_files() {
file.folder("foo/bar1");
file.folder("foo/bar2");
file.file("foo/bar1/foo1.c");
file.file("foo/bar1/foo2.c");
file.file("foo/bar2/foo1.c");
file.file("foo/bar2/foo2.c");
//let mut watch = Watch::new();
//watch.pattern("**/*.c");
//watch.watch(file.path.as_slice());
// Test touch
//file.touch("foo/bar1/foo1.c");
//watch.poll();
assert!(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment