1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
extern crate toml;
extern crate serde;
use std::env;
use std::path;
use std::fs;
use std::fs::{File};
use std::io::{Write, Read};
use error;
#[derive(Serialize, Deserialize)]
pub struct SnippetLocation {
pub local: String,
pub ext: String,
pub git: Option<String>,
}
impl SnippetLocation {
pub fn default(home: &String) -> SnippetLocation {
return SnippetLocation{
local: String::from(home.to_owned() + "/.snippets"),
ext: "md".to_string(),
git: None
}
}
pub fn create_if_not_exists(&self) -> Result<(), error::Error> {
let path = path::Path::new(&self.local);
if !path.exists() {
fs::create_dir_all(&path)?;
}
Ok(())
}
}
#[derive(Serialize, Deserialize)]
pub struct Project {
pub locations: Vec<SnippetLocation>
}
pub enum ProjectOperation {
Exist(Project),
NotExist(Project)
}
impl Project {
pub fn write(&self, folder : &path::Path) -> Result<(), error::Error> {
let to_write = toml::to_string(self).expect("Cannot serialize project");
let full_path = path::Path::new(&folder).join(".x.toml");
println!("Writing to {:?}", full_path);
let mut f = File::create(&full_path).expect("Cannot create project file");
f.write_all(to_write.as_bytes()).expect("Cannot write to project file");
Ok(())
}
pub fn default_project() -> Result<ProjectOperation, error::Error> {
let home = String::from(env::home_dir()
.expect("Cannot find the home dir")
.to_str().unwrap());
let format = format!("{}/.x.toml", &home);
let path = path::Path::new(&format);
if path.exists() {
let mut f = File::open(path).expect("Found project file but can't read it.");
let mut buffer = String::new();
f.read_to_string(&mut buffer)?;
let project: Project = toml::from_str(&buffer).expect("Cannot deserialize project file");
return Ok(ProjectOperation::Exist(project));
}
Ok(ProjectOperation::NotExist(Project{ locations: vec![SnippetLocation::default(&home)]}))
}
}