aboutsummaryrefslogtreecommitdiff
path: root/ticket/src/main.rs
blob: 9005471303a06dace9fe1962280ac852434c6af0 (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use anyhow::{
  bail,
  Result,
};
use colored::*;
use rustyline::{
  error::ReadlineError,
  Editor,
};
use serde::{
  Deserialize,
  Serialize,
};
use shared::find_root;
use std::{
  env,
  fs,
  path::PathBuf,
  process,
  process::Command,
};

#[derive(structopt::StructOpt)]
enum Args {
  /// Initialize the repo to use ticket
  Init,
  New,
  Show {
    id: usize,
  },
  Close {
    id: usize,
  },
}

#[paw::main]
fn main(args: Args) {
  if let Err(e) = match args {
    Args::Init => init(),
    Args::New => new(),
    Args::Show { id } => show(id),
    Args::Close { id } => close(id),
  } {
    eprintln!("{}", e);
    std::process::exit(1);
  }
}

fn init() -> Result<()> {
  let root = find_root()?.join(".dev-suite").join("ticket");
  fs::create_dir_all(&root.join("open"))?;
  fs::create_dir_all(&root.join("closed"))?;
  Ok(())
}

fn new() -> Result<()> {
  let ticket_root = ticket_root()?;
  let open = ticket_root.join("open");
  let closed = ticket_root.join("closed");
  let description = ticket_root.join("description");
  let mut ticket_num = 1;

  // Fast enough for now but maybe not in the future
  for entry in fs::read_dir(&open)?.chain(fs::read_dir(&closed)?) {
    let entry = entry?;
    let path = entry.path();
    if path.is_file() {
      ticket_num += 1;
    }
  }

  let mut rl = Editor::<()>::new();
  let title = match rl.readline("Title: ") {
    Ok(line) => {
      if line.is_empty() {
        bail!("Title may not be empty");
      }
      line
    }
    Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => {
      process::exit(0);
    }
    Err(e) => return Err(e.into()),
  };

  fs::File::create(&description)?;
  Command::new(&env::var("EDITOR").unwrap_or_else(|_| "vi".into()))
    .arg(&description)
    .spawn()?
    .wait()?;
  let description_contents = fs::read_to_string(&description)?;
  fs::remove_file(&description)?;

  let t = Ticket {
    title,
    status: Status::Open,
    number: ticket_num,
    assignee: None,
    description: description_contents,
  };

  fs::write(
    open.join(&format!(
      "{}-{}.toml",
      ticket_num,
      t.title
        .to_lowercase()
        .split_whitespace()
        .collect::<Vec<&str>>()
        .join("-")
    )),
    toml::to_string_pretty(&t)?,
  )?;

  Ok(())
}

fn ticket_root() -> Result<PathBuf> {
  Ok(find_root()?.join(".dev-suite").join("ticket"))
}

fn show(id: usize) -> Result<()> {
  let ticket_root = ticket_root()?;
  let open = ticket_root.join("open");
  let closed = ticket_root.join("closed");
  let mut found = false;

  // Fast enough for now but maybe not in the future
  for entry in fs::read_dir(&open)?.chain(fs::read_dir(&closed)?) {
    let entry = entry?;
    let path = entry.path();
    if path.is_file() {
      if let Some(file_name) = path.file_name().and_then(|f| f.to_str()) {
        if file_name.starts_with(&id.to_string()) {
          let ticket = toml::from_slice::<Ticket>(&fs::read(&path)?)?;
          println!(
            "{}",
            format!("{} - {}\n", ticket.number, ticket.title)
              .bold()
              .red()
          );
          if let Some(a) = ticket.assignee {
            println!("{}{}", "Assignee: ".bold().purple(), a);
          }

          print!(
            "{}{}\n\n{}",
            "Status: ".bold().purple(),
            match ticket.status {
              Status::Open => "Open".bold().green(),
              Status::Closed => "Closed".bold().red(),
            },
            ticket.description
          );
          found = true;
          break;
        }
      }
    }
  }
  if found {
    Ok(())
  } else {
    bail!("No ticket with id {} exists", id);
  }
}

fn close(id: usize) -> Result<()> {
  let ticket_root = ticket_root()?;
  let open = ticket_root.join("open");
  let closed = ticket_root.join("closed");
  let mut found = false;
  // Fast enough for now but maybe not in the future
  for entry in fs::read_dir(&open)? {
    let entry = entry?;
    let path = entry.path();
    if path.is_file() {
      if let Some(file_name) = path.file_name().and_then(|f| f.to_str()) {
        if file_name.starts_with(&id.to_string()) {
          let mut ticket = toml::from_slice::<Ticket>(&fs::read(&path)?)?;
          ticket.status = Status::Closed;
          fs::write(closed.join(file_name), toml::to_string_pretty(&ticket)?)?;
          fs::remove_file(&path)?;
          found = true;
          break;
        }
      }
    }
  }
  if found {
    Ok(())
  } else {
    bail!("No ticket with id {} exists", id);
  }
}

#[derive(Serialize, Deserialize)]
struct Ticket {
  title: String,
  status: Status,
  number: usize,
  assignee: Option<String>,
  description: String,
}

#[derive(Serialize, Deserialize)]
enum Status {
  Open,
  Closed,
}