summaryrefslogtreecommitdiff
path: root/src/bin/jt2.rs
blob: 677bb353e184e612e86d63cc32e44f1e4e108301 (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
use jt2::config::Configuration;
use jt2::error::JournalError;
use jt2::journal::Journal;
use jt2::opt::{Opt, SubCommand};

use std::path::{Path, PathBuf};
use structopt::StructOpt;

fn main() -> anyhow::Result<()> {
    pretty_env_logger::init_custom_env("JT_LOG");
    let opt = Opt::from_args();
    let config = Configuration::read(&opt)?;
    match opt.cmd {
        SubCommand::Config => config.dump(),
        SubCommand::Init {
            journalname,
            description,
        } => init(&config.dirname, &journalname, &description, &config)?,
        SubCommand::IsJournal => is_journal(&config)?,
        SubCommand::New { title, topic } => new_draft(&title, &topic, &config)?,
        SubCommand::NewTopic { path, title } => new_topic(&path, &title, &config)?,
        SubCommand::Edit { draft } => edit_draft(&draft, &config)?,
        SubCommand::Finish { draft, basename } => finish_draft(&draft, &basename, &config)?,
    }
    Ok(())
}

fn init(
    dirname: &Path,
    _journalname: &str,
    _description: &str,
    config: &Configuration,
) -> anyhow::Result<()> {
    Journal::init(dirname, &config.entries)?;
    Ok(())
}

fn is_journal(config: &Configuration) -> anyhow::Result<()> {
    if !Journal::is_journal(&config.dirname, &config.entries) {
        return Err(JournalError::NotAJournal(config.dirname.display().to_string()).into());
    }
    Ok(())
}

fn new_draft(title: &str, topic: &Option<PathBuf>, config: &Configuration) -> anyhow::Result<()> {
    let journal = Journal::new(&config.dirname, &config.entries)?;
    journal.new_draft(title, topic, &config.editor)?;
    Ok(())
}

fn new_topic(path: &Path, title: &str, config: &Configuration) -> anyhow::Result<()> {
    let journal = Journal::new(&config.dirname, &config.entries)?;
    journal.new_topic(path, title, &config.editor)?;
    Ok(())
}

fn edit_draft(draft: &str, config: &Configuration) -> anyhow::Result<()> {
    let journal = Journal::new(&config.dirname, &config.entries)?;
    let filename = journal.pick_draft(draft)?;
    journal.edit_draft(&config.editor, &filename)?;
    Ok(())
}

fn finish_draft(draft: &str, basename: &str, config: &Configuration) -> anyhow::Result<()> {
    let journal = Journal::new(&config.dirname, &config.entries)?;
    let filename = journal.pick_draft(draft)?;
    journal.finish_draft(&filename, basename)?;
    Ok(())
}