terminotes 0.2.2

Terminotes: A note-taker for people spending most of their time inside terminals.
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use std::env;
use std::time::{SystemTime, UNIX_EPOCH};

use rusqlite::{params, Connection, Result};

struct Note {
    id: i64,
    content: String,
    tag: Option<String>,
    created_at: i64,
}

fn main() -> Result<()> {
    let args: Vec<String> = env::args().skip(1).collect();

    if args.is_empty() {
        show_usage();
        return Ok(());
    }

    match args[0].as_str() {
        "list" => {
            let tag = extract_tag(&args);
            list_notes(tag)?;
        }

        "tags" => {
            list_tags()?;
        }

        "search" => {
            search_notes(&args[1..])?;
        }

        "today" => {
            list_today()?;
        }

        _ => {
            create_note(&args)?;
        }
    }

    Ok(())
}

// ------------------------------------------------------------
// DATABASE
// ------------------------------------------------------------

fn get_db_connection() -> Result<Connection> {
    let mut db_path = dirs::data_dir()
        .expect("Unable to locate your data directory");

    db_path.push("terminote");

    std::fs::create_dir_all(&db_path)
        .expect("Failed to create Terminotes directory");

    db_path.push("terminotes.db");

    let conn = Connection::open(db_path)?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS notes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            content TEXT NOT NULL,
            tag TEXT,
            created_at INTEGER NOT NULL
        )
        ",
        [],
    )?;

    Ok(conn)
}

// ------------------------------------------------------------
// CREATE
// ------------------------------------------------------------

fn create_note(args: &[String]) -> Result<()> {
    let mut content_parts = Vec::new();
    let mut tag: Option<String> = None;

    for arg in args {
        if let Some(value) = arg.strip_prefix("--") {
            if !value.is_empty() {
                tag = Some(value.to_string());
            }
        } else {
            content_parts.push(arg.as_str());
        }
    }

    let content = content_parts.join(" ").trim().to_string();

    if content.is_empty() {
        println!("Nothing to Terminote.");
        return Ok(());
    }

    let timestamp = current_timestamp();

    let conn = get_db_connection()?;

    conn.execute(
        "
        INSERT INTO notes (content, tag, created_at)
        VALUES (?1, ?2, ?3)
        ",
        params![content, tag, timestamp],
    )?;

    println!("Terminoted.");

    Ok(())
}

// ------------------------------------------------------------
// LIST
// ------------------------------------------------------------

fn list_notes(tag: Option<String>) -> Result<()> {
    let notes = get_notes(tag)?;

    if notes.is_empty() {
        println!();
        println!("No Terminotes yet.");
        return Ok(());
    }

    println!();
    println!("Terminotes");
    println!("────────────────────────────────────────");

    for note in &notes {
        print_note(note);
    }

    println!();

    Ok(())
}

fn get_notes(tag: Option<String>) -> Result<Vec<Note>> {
    let conn = get_db_connection()?;

    let mut notes = Vec::new();

    match tag {
        Some(tag) => {
            let mut stmt = conn.prepare(
                "
                SELECT id, content, tag, created_at
                FROM notes
                WHERE tag = ?1
                ORDER BY created_at DESC
                ",
            )?;

            let rows = stmt.query_map([tag], |row| {
                Ok(Note {
                    id: row.get(0)?,
                    content: row.get(1)?,
                    tag: row.get(2)?,
                    created_at: row.get(3)?,
                })
            })?;

            for row in rows {
                notes.push(row?);
            }
        }

        None => {
            let mut stmt = conn.prepare(
                "
                SELECT id, content, tag, created_at
                FROM notes
                ORDER BY created_at DESC
                ",
            )?;

            let rows = stmt.query_map([], |row| {
                Ok(Note {
                    id: row.get(0)?,
                    content: row.get(1)?,
                    tag: row.get(2)?,
                    created_at: row.get(3)?,
                })
            })?;

            for row in rows {
                notes.push(row?);
            }
        }
    }

    Ok(notes)
}

// ------------------------------------------------------------
// SEARCH
// ------------------------------------------------------------

fn search_notes(words: &[String]) -> Result<()> {
    if words.is_empty() {
        println!("What do you want to search for?");
        return Ok(());
    }

    let search = words.join(" ");
    let pattern = format!("%{}%", search);

    let conn = get_db_connection()?;

    let mut stmt = conn.prepare(
        "
        SELECT id, content, tag, created_at
        FROM notes
        WHERE content LIKE ?1
        ORDER BY created_at DESC
        ",
    )?;

    let rows = stmt.query_map([pattern], |row| {
        Ok(Note {
            id: row.get(0)?,
            content: row.get(1)?,
            tag: row.get(2)?,
            created_at: row.get(3)?,
        })
    })?;

    let mut found = false;

    println!();
    println!("Search: {}", search);
    println!("────────────────────────────────────────");

    for row in rows {
        let note = row?;

        found = true;

        print_note(&note);
    }

    if !found {
        println!();
        println!("Nothing found.");
    }

    println!();

    Ok(())
}

// ------------------------------------------------------------
// TAGS
// ------------------------------------------------------------

fn list_tags() -> Result<()> {
    let conn = get_db_connection()?;

    let mut stmt = conn.prepare(
        "
        SELECT tag, COUNT(*)
        FROM notes
        WHERE tag IS NOT NULL
        GROUP BY tag
        ORDER BY COUNT(*) DESC
        ",
    )?;

    let rows = stmt.query_map([], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, i64>(1)?,
        ))
    })?;

    println!();
    println!("Tags");
    println!("────────────────────────────────────────");

    let mut found = false;

    for row in rows {
        let (tag, count) = row?;

        found = true;

        println!("{:<15} {}", tag, count);
    }

    if !found {
        println!("No tags yet.");
    }

    println!();

    Ok(())
}

// ------------------------------------------------------------
// TODAY
// ------------------------------------------------------------

fn list_today() -> Result<()> {
    let now = current_timestamp();

    let day = 60 * 60 * 24;

    let start_of_day = now - (now % day);

    let conn = get_db_connection()?;

    let mut stmt = conn.prepare(
        "
        SELECT id, content, tag, created_at
        FROM notes
        WHERE created_at >= ?1
        ORDER BY created_at DESC
        ",
    )?;

    let rows = stmt.query_map([start_of_day], |row| {
        Ok(Note {
            id: row.get(0)?,
            content: row.get(1)?,
            tag: row.get(2)?,
            created_at: row.get(3)?,
        })
    })?;

    println!();
    println!("Today's Terminotes");
    println!("────────────────────────────────────────");

    let mut found = false;

    for row in rows {
        let note = row?;

        found = true;

        print_note(&note);
    }

    if !found {
        println!();
        println!("Nothing Terminoted today.");
    }

    println!();

    Ok(())
}

// ------------------------------------------------------------
// OUTPUT
// ------------------------------------------------------------

fn print_note(note: &Note) {
    let tag = match &note.tag {
        Some(tag) => tag.as_str(),
        None => "general",
    };

    println!();
    println!("#{}  {}", note.id, note.content);
    println!("     {} · {}", tag, format_date(note.created_at));
}

// ------------------------------------------------------------
// DATE / TIME
// ------------------------------------------------------------

fn current_timestamp() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("System clock is before UNIX epoch")
        .as_secs() as i64
}

fn format_date(timestamp: i64) -> String {
    let now = current_timestamp();

    let difference = now - timestamp;

    if difference < 60 {
        return "just now".to_string();
    }

    if difference < 60 * 60 {
        let minutes = difference / 60;

        return format!(
            "{} minute{} ago",
            minutes,
            if minutes == 1 { "" } else { "s" }
        );
    }

    if difference < 60 * 60 * 24 {
        let hours = difference / (60 * 60);

        return format!(
            "{} hour{} ago",
            hours,
            if hours == 1 { "" } else { "s" }
        );
    }

    if difference < 60 * 60 * 48 {
        return "yesterday".to_string();
    }

    let days = difference / (60 * 60 * 24);

    format!(
        "{} day{} ago",
        days,
        if days == 1 { "" } else { "s" }
    )
}

// ------------------------------------------------------------
// ARGUMENTS
// ------------------------------------------------------------

fn extract_tag(args: &[String]) -> Option<String> {
    args.iter()
        .find_map(|arg| {
            arg.strip_prefix("--")
                .filter(|value| !value.is_empty())
                .map(String::from)
        })
}

// ------------------------------------------------------------
// HELP
// ------------------------------------------------------------

fn show_usage() {
    println!();
    println!("Terminotes");
    println!("A tiny memory for your terminal.");
    println!();

    println!("Usage:");
    println!();
    println!("  terminote \"buy milk\"");
    println!("  terminote \"buy milk\" --todo");
    println!();
    println!("  terminote list");
    println!("  terminote list --todo");
    println!("  terminote --todo");
    println!();
    println!("  terminote tags");
    println!("  terminote search rust");
    println!("  terminote today");
    println!();
}