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