sigi 3.7.1

An organizing tool for terminal lovers who hate organizing
Documentation
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use std::process::Command;

use chrono::Local;

use crate::data::{DataStore, Item};
use crate::output::OutputFormat;

const HISTORY_SUFFIX: &str = "_history";

// TODO: Consider more shuffle words: https://docs.factorcode.org/content/article-shuffle-words.html

pub enum StackEffect {
    Push {
        stack: String,
        content: String,
    },
    Complete {
        stack: String,
        index: usize,
    },
    Delete {
        stack: String,
        index: usize,
    },
    DeleteAll {
        stack: String,
    },
    Edit {
        stack: String,
        editor: String,
        index: usize,
    },
    Pick {
        stack: String,
        indices: Vec<usize>,
    },
    Move {
        stack: String,
        dest: String,
    },
    MoveAll {
        stack: String,
        dest: String,
    },
    Swap {
        stack: String,
    },
    Rot {
        stack: String,
    },
    Next {
        stack: String,
    },
    Peek {
        stack: String,
    },
    ListAll {
        stack: String,
    },
    ListStacks,
    Head {
        stack: String,
        n: usize,
    },
    Tail {
        stack: String,
        n: usize,
    },
    Count {
        stack: String,
    },
    IsEmpty {
        stack: String,
    },
}

impl StackEffect {
    pub fn run(self, data_store: &DataStore, output: &OutputFormat) {
        use StackEffect::*;
        match self {
            Push { stack, content } => push_content(stack, content, data_store, output),
            Complete { stack, index } => complete_item(stack, index, data_store, output),
            Delete { stack, index } => delete_latest_item(stack, index, data_store, output),
            DeleteAll { stack } => delete_all_items(stack, data_store, output),
            Edit {
                stack,
                editor,
                index,
            } => edit_item(stack, editor, index, data_store, output),
            Pick { stack, indices } => pick_indices(stack, indices, data_store, output),
            Move { stack, dest } => move_latest_item(stack, dest, data_store, output),
            MoveAll { stack, dest } => move_all_items(stack, dest, data_store, output),
            Swap { stack } => swap_latest_two_items(stack, data_store, output),
            Rot { stack } => rotate_latest_three_items(stack, data_store, output),
            Next { stack } => next_to_latest(stack, data_store, output),
            Peek { stack } => peek_latest_item(stack, data_store, output),
            ListAll { stack } => list_all_items(stack, data_store, output),
            ListStacks => list_stacks(data_store, output),
            Head { stack, n } => list_n_latest_items(stack, n, data_store, output),
            Tail { stack, n } => list_n_oldest_items(stack, n, data_store, output),
            Count { stack } => count_all_items(stack, data_store, output),
            IsEmpty { stack } => is_empty(stack, data_store, output),
        }
    }
}

fn push_content(stack: String, content: String, data_store: &DataStore, output: &OutputFormat) {
    let item = Item::new(&content);
    push_item(stack, item, data_store, output);
}

fn push_item(stack: String, item: Item, data_store: &DataStore, output: &OutputFormat) {
    let contents = item.contents.clone();

    let items = if let Ok(items) = data_store.load(&stack) {
        let mut items = items;
        items.push(item);
        items
    } else {
        vec![item]
    };

    data_store.save(&stack, items).unwrap();

    output.log(vec!["action", "item"], vec![vec!["Created", &contents]]);
}

fn complete_item(stack: String, index: usize, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;

        if items.len() > index {
            let mut item = items.remove(items.len() - index - 1);
            item.mark_completed();

            // Push the now-marked-completed item to history stack.
            push_item(
                stack_history_of(&stack),
                item.clone(),
                data_store,
                &OutputFormat::Silent,
            );

            // Save the original stack without that item.
            data_store.save(&stack, items).unwrap();

            output.log(
                vec!["action", "item"],
                vec![vec!["Completed", &item.contents]],
            );
        }
    }

    if output.is_nonquiet_for_humans() {
        peek_latest_item(stack, data_store, output);
    }
}

fn delete_latest_item(stack: String, index: usize, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;

        if items.len() > index {
            let mut item = items.remove(items.len() - index - 1);
            item.mark_deleted();

            // Push the now-marked-deleted item to history stack.
            push_item(
                stack_history_of(&stack),
                item.clone(),
                data_store,
                &OutputFormat::Silent,
            );

            // Save the original stack without that item.
            data_store.save(&stack, items).unwrap();

            output.log(
                vec!["action", "item"],
                vec![vec!["Deleted", &item.contents]],
            );
        }
    }

    if output.is_nonquiet_for_humans() {
        peek_latest_item(stack, data_store, output);
    }
}

fn delete_all_items(stack: String, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;
        items.iter_mut().for_each(|item| item.mark_deleted());
        let n_deleted = items.len();

        // Push the now-marked-deleted items to history stack.
        let history_stack = &stack_history_of(&stack);
        let mut history = data_store.load(history_stack).unwrap_or_default();
        history.append(&mut items);
        data_store.save(history_stack, history).unwrap();

        // Save the original stack as empty now.
        data_store.save(&stack, vec![]).unwrap();

        output.log(
            vec!["action", "item"],
            vec![vec!["Deleted", &format!("{} items", n_deleted)]],
        );
    }
}

fn edit_item(
    stack: String,
    editor: String,
    index: usize,
    data_store: &DataStore,
    output: &OutputFormat,
) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;
        if index < items.len() {
            let tmp = std::env::temp_dir().as_path().join("sigi");
            std::fs::create_dir_all(&tmp).unwrap_or_else(|err| {
                panic!(
                    "Unable to create temporary directory {:?} for editing: {}",
                    tmp, err
                )
            });
            let tmpfile = tmp.as_path().join(Local::now().timestamp().to_string());
            std::fs::write(&tmpfile, &items[index].contents).unwrap_or_else(|err| {
                panic!(
                    "Unable to write to temporary file {:?} for editing: {}",
                    tmpfile, err
                )
            });

            let editor = editor.split_whitespace().collect::<Vec<_>>();

            let edit_exit_code = Command::new(editor[0])
                .args(&editor[1..])
                .arg(&tmpfile)
                .status()
                .unwrap_or_else(|err| panic!("Failed to execute {:?} editor: {}", editor, err));

            if edit_exit_code.success() {
                let new_content = std::fs::read_to_string(&tmpfile).unwrap_or_else(|err| {
                    panic!(
                        "Unable to read from temporary file {:?} after editing: {}",
                        tmpfile, err
                    )
                });
                items[index].contents.clone_from(&new_content);

                data_store.save(&stack, items).unwrap();

                output.log(vec!["action", "item"], vec![vec!["Edited", &new_content]]);
            }
        }
    }
}

fn pick_indices(stack: String, indices: Vec<usize>, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;
        let mut seen: Vec<usize> = vec![];
        seen.reserve_exact(indices.len());
        let indices: Vec<usize> = indices.iter().map(|i| items.len() - 1 - i).rev().collect();
        for i in indices {
            if i > items.len() || seen.contains(&i) {
                // TODO: What should be the output here? Some stderr?
                // command.log("Pick", "ignoring out-of-bounds index");
                // command.log("Pick", "ignoring duplicate index");
                continue;
            }
            let i = i - seen.iter().filter(|j| j < &&i).count();
            let picked = items.remove(i);
            items.push(picked);
            seen.push(i);
        }

        data_store.save(&stack, items).unwrap();

        if output.is_nonquiet_for_humans() {
            list_n_latest_items(stack, seen.len(), data_store, output);
        }
    }
}

fn move_latest_item(source: String, dest: String, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&source) {
        let mut items = items;
        if let Some(item) = items.pop() {
            data_store.save(&source, items).unwrap();

            output.log(
                vec!["action", "new-stack", "old-stack"],
                vec![vec!["Move", &dest, &source]],
            );

            push_item(dest, item, data_store, &OutputFormat::Silent);
        }
    }
}

fn move_all_items(source: String, dest: String, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(src_items) = data_store.load(&source) {
        let count = src_items.len();

        if !src_items.is_empty() {
            let all_items = match data_store.load(&dest) {
                Ok(dest_items) => {
                    let mut all_items = dest_items;
                    for item in src_items {
                        all_items.push(item);
                    }
                    all_items
                }
                _ => src_items,
            };

            data_store.save(&dest, all_items).unwrap();
            data_store.save(&source, vec![]).unwrap();
        }

        output.log(
            vec!["action", "new-stack", "old-stack", "num-moved"],
            vec![vec!["Move All", &dest, &source, &count.to_string()]],
        );
    }
}

fn swap_latest_two_items(stack: String, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;

        if items.len() < 2 {
            return;
        }

        let a = items.pop().unwrap();
        let b = items.pop().unwrap();
        items.push(a);
        items.push(b);

        data_store.save(&stack, items).unwrap();

        if output.is_nonquiet_for_humans() {
            list_n_latest_items(stack, 2, data_store, output);
        }
    }
}

fn rotate_latest_three_items(stack: String, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;

        if items.len() < 3 {
            swap_latest_two_items(stack, data_store, output);
            return;
        }

        let a = items.pop().unwrap();
        let b = items.pop().unwrap();
        let c = items.pop().unwrap();

        items.push(a);
        items.push(c);
        items.push(b);

        data_store.save(&stack, items).unwrap();

        if output.is_nonquiet_for_humans() {
            list_n_latest_items(stack, 3, data_store, output);
        }
    }
}

fn next_to_latest(stack: String, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        let mut items = items;
        if items.is_empty() {
            return;
        }
        let to_the_back = items.pop().unwrap();
        items.insert(0, to_the_back);

        data_store.save(&stack, items).unwrap();

        if output.is_nonquiet_for_humans() {
            peek_latest_item(stack, data_store, output);
        }
    }
}

fn peek_latest_item(stack: String, data_store: &DataStore, output: &OutputFormat) {
    if let OutputFormat::Silent = output {
        return;
    }

    if let Ok(items) = data_store.load(&stack) {
        let top_item = items.last().map(|i| i.contents.as_str());

        let output_it = |it| output.log_always(vec!["position", "item"], it);

        match top_item {
            Some(contents) => output_it(vec![vec!["Now", contents]]),
            None => {
                if output.is_nonquiet_for_humans() {
                    output_it(vec![vec!["Now", "NOTHING"]])
                } else {
                    output_it(vec![])
                }
            }
        }
    }
}

fn count_all_items(stack: String, data_store: &DataStore, output: &OutputFormat) {
    if let OutputFormat::Silent = output {
        return;
    }

    if let Ok(items) = data_store.load(&stack) {
        let len = items.len().to_string();
        output.log_always(vec!["items"], vec![vec![&len]])
    }
}

fn is_empty(stack: String, data_store: &DataStore, output: &OutputFormat) {
    if let Ok(items) = data_store.load(&stack) {
        if !items.is_empty() {
            output.log_always(vec!["empty"], vec![vec!["false"]]);
            // Exit with a failure (nonzero status) when not empty.
            // This helps people who do shell scripting do something like:
            //     while ! sigi -t $stack is-empty ; do <ETC> ; done
            // TODO: It would be better modeled as an error, if anyone uses as a lib this will surprise.
            if let OutputFormat::TerseText = output {
                return;
            } else {
                std::process::exit(1);
            }
        }
    }
    output.log_always(vec!["empty"], vec![vec!["true"]]);
}

fn list_stacks(data_store: &DataStore, output: &OutputFormat) {
    if let Ok(stacks) = data_store.list_stacks() {
        let mut stacks = stacks;
        stacks.sort();
        let strs = stacks.iter().map(|stack| vec![stack.as_str()]).collect();
        output.log_always(vec!["stack"], strs);
    }
}

// ===== ListAll/Head/Tail =====

struct ListRange {
    stack: String,
    // Ignored if starting "from_end".
    start: usize,
    limit: Option<usize>,
    from_end: bool,
}

fn list_range(range: ListRange, data_store: &DataStore, output: &OutputFormat) {
    if let OutputFormat::Silent = output {
        return;
    }

    if let Ok(items) = data_store.load(&range.stack) {
        let limit = match range.limit {
            Some(n) => n,
            None => items.len(),
        };

        let start = if range.from_end {
            if limit <= items.len() {
                items.len() - limit
            } else {
                0
            }
        } else {
            range.start
        };

        let lines = items
            .into_iter()
            .rev()
            .enumerate()
            .skip(start)
            .take(limit)
            .map(|(i, item)| {
                // Pad human output numbers to line up nicely with "Now".
                let position = if output.is_nonquiet_for_humans() {
                    match i {
                        0 => "Now".to_string(),
                        1..=9 => format!("  {}", i),
                        10..=99 => format!(" {}", i),
                        _ => i.to_string(),
                    }
                } else {
                    i.to_string()
                };

                let created = item
                    .history
                    .iter()
                    .find(|(status, _)| status == "created")
                    .map(|(_, dt)| output.format_time(*dt))
                    .unwrap_or_else(|| "unknown".to_string());

                vec![position, item.contents, created]
            })
            .collect::<Vec<_>>();

        let labels = vec!["position", "item", "created"];

        if lines.is_empty() {
            if output.is_nonquiet_for_humans() {
                output.log(labels, vec![vec!["Now", "NOTHING"]]);
            }
            return;
        }

        // Get the lines into a "borrow" state (&str instead of String) to make log happy.
        let lines = lines
            .iter()
            .map(|line| line.iter().map(|s| s.as_str()).collect())
            .collect();

        output.log_always(labels, lines);
    }
}

fn list_all_items(stack: String, data_store: &DataStore, output: &OutputFormat) {
    let range = ListRange {
        stack,
        start: 0,
        limit: None,
        from_end: false,
    };

    list_range(range, data_store, output);
}

fn list_n_latest_items(stack: String, n: usize, data_store: &DataStore, output: &OutputFormat) {
    let range = ListRange {
        stack,
        start: 0,
        limit: Some(n),
        from_end: false,
    };

    list_range(range, data_store, output);
}

fn list_n_oldest_items(stack: String, n: usize, data_store: &DataStore, output: &OutputFormat) {
    let range = ListRange {
        stack,
        start: 0,
        limit: Some(n),
        from_end: true,
    };

    list_range(range, data_store, output);
}

// ===== Helper functions =====

fn stack_history_of(stack: &str) -> String {
    stack.to_string() + HISTORY_SUFFIX
}