use project;
use snippet;
use error::Error;
use error::Error::InternalError;
use std::process::Command;
use std::fs;
use std::path;
use std::fs::File;
use std::io::Write;
#[derive(Debug)]
pub enum OpCode {
AddSnippet,
ListSnippets(bool),
SyncSnippets,
}
pub fn find_snippets(project: &project::Project) -> Result<Vec<fs::DirEntry>, Error> {
let mut res: Vec<fs::DirEntry> = Vec::new();
for snippet_location in project.locations.iter() {
println!("Finding snippets in {},", &snippet_location.local.as_str());
let entries = fs::read_dir(&snippet_location.local)?;
for e in entries {
let dir_ent = e?;
let path = dir_ent.path();
let ext_opt = path.extension();
if let Some(ext) = ext_opt {
if let Some(s) = ext.to_str() {
if s == snippet_location.ext {
res.push(dir_ent);
}
}
}
}
}
Ok(res)
}
pub fn load_snippets(dir_entries: &Vec<fs::DirEntry>, keywords: &Vec<String>) -> Result<Vec<snippet::Snippet>, Error>
{
let mut result: Vec<snippet::Snippet> = Vec::new();
let keyword_slice = keywords.as_slice();
for entry in dir_entries {
let filename = entry.path();
let tags = snippet::read_tags(entry.path().to_str().unwrap())?;
if keyword_slice.len() == 0 || tags.iter().fold(false, |res, tag| (res || keyword_slice.contains(&tag))) {
result.push(snippet::Snippet::new(filename.to_str().unwrap().to_string(), &tags));
}
}
Ok(result)
}
pub fn edit_snippet(program: &str, full_path: &path::Path) -> Result<(), Error>
{
let _output = Command::new("vim").
arg(&full_path).spawn()?.wait_with_output()?;
Ok(())
}
pub fn start_operation(code: &OpCode, project: &project::Project, keywords: Vec<String>, optional_filename: &str) -> Result<Vec<snippet::Snippet>, Error> {
let result = match code {
OpCode::AddSnippet => {
let full_path = path::Path::new(&project.locations[0].local).join(optional_filename);
if full_path.exists() {
return Err(InternalError("Snippet already exists".to_string()));
}
let mut file = File::create(&full_path)?;
for keyword in &keywords {
file.write(keyword.as_bytes())?;
file.write(b",")?;
}
edit_snippet("vim", &full_path);
let snippet = snippet::Snippet::new(full_path.into_os_string().into_string().unwrap(), &keywords);
Ok(vec![snippet])
}
OpCode::ListSnippets(_) => {
let files = find_snippets(&project)?;
let snippets = load_snippets(&files, &keywords)?;
Ok(snippets)
}
OpCode::SyncSnippets => {
println!("Sync all snippets");
Ok(vec![])
}
};
result
}