1use anyhow::{Error, Result, anyhow};
2use colored::Colorize;
3use std::{
4 path::{Path, PathBuf},
5 process::Command,
6};
7
8use crate::{get_git_path, read_yaml};
9
10pub fn open(module: &PathBuf) -> Result<()> {
11 eprintln!(
13 "{}",
14 format!(
15 "{}: {}",
16 "opening".green(),
17 module.file_name().unwrap().to_str().unwrap().italic(),
18 )
19 );
20
21 match read_yaml(module) {
22 Ok(para_yaml) => {
23 for git in para_yaml.gits {
24 if let Err(e) = init_git(&git, module) {
25 eprintln!("{}: {}", e.to_string().red(), &git.italic());
26 }
27 }
28
29 if let Some(cmd) = para_yaml.open
30 && !cmd.is_empty()
31 {
32 let mut command = Command::new(cmd.first().unwrap());
34 for arg in cmd[1..].iter() {
35 command.arg(arg);
36 }
37 command.current_dir(module);
38 if command.status().is_err() {
39 eprintln!("{}", "failed to spawn `open` command from para.yaml".red());
40 };
41 }
42 }
43 Err(e) => {
44 eprintln!(
45 "{}",
46 format!("Error opening para.yaml: {}", e).green().italic()
47 );
48 }
49 }
50
51 let shell = std::env::var("SHELL").unwrap_or("bash".to_string());
52 Command::new(shell).current_dir(module).status()?;
53 Ok(())
54}
55
56pub fn edit_note(note: PathBuf) -> Result<()> {
57 Command::new("code")
58 .arg(note)
59 .status()
60 .or(Err(anyhow!("Couldn't start vim")))?;
61 Ok(())
62}
63
64fn init_git(git: &str, module: &Path) -> Result<()> {
65 let name = match git.split('/').next_back() {
67 Some(n) => n.trim_end_matches(".git"),
68 None => return Err(anyhow!("para.yaml git url invalid")),
69 };
70
71 if module.join(name).exists() {
73 return Ok(());
75 } else {
76 if module.join(name).is_symlink() {
78 std::fs::remove_file(module.join(name))?;
80 }
81 }
82
83 let original = get_git_path()?.join(name);
85 if !original.exists() {
86 let status = Command::new("git")
88 .arg("clone")
89 .arg(git)
90 .arg(&original)
91 .status()?;
92 if !status.success() {
93 return Err(anyhow!("git clone failed"));
94 }
95 }
96 std::os::unix::fs::symlink(original, module.join(name))?;
101
102 Ok(())
104}