flk 0.6.3

A CLI tool for managing flake.nix devShell environments
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
//! # Flik Spinner
//!
//! A tiny, dependency-free terminal spinner starring **Flik**, the flk bird.
//!
//! Two styles, each with success + failure flourishes:
//!   * `Style::Thinking` — Flik (calm face) ponders while a snowflake assembles
//!     above his head. On success the flake collapses into a green ✓ and Flik
//!     throws his wings up in a happy hop. On failure the flake snaps into a
//!     red ✗ and Flik settles into his cool/half-lidded pose.
//!   * `Style::Flock`    — birds stream across the line. On success they land in
//!     an asymmetric checkmark formation (long right leg). On failure the V
//!     never forms and a red ✗ replaces the tick.
//!
//! No external crates. ANSI escapes + a background thread. UTF-8 terminal
//! assumed; honours `NO_COLOR`.
//!
//! ```text
//! use flk::utils::flk_spinner::{Spinner, Style};
//! let sp = Spinner::start("building flake", Style::Thinking);
//! // … slow work …
//! sp.success("updated 3 inputs");
//!
//! // failure path:
//! let sp = Spinner::start("building flake", Style::Thinking);
//! sp.fail("input `nixpkgs` could not be resolved");
//!
//! // or run a closure with a Result and auto-finish on Ok/Err:
//! let out = Spinner::run("exporting layers", Style::Flock, || -> Result<(), String> { Ok(()) });
//! ```

use std::io::{self, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::Duration;

// ---- palette ---------------------------------------------------------------
const ACCENT: (u8, u8, u8) = (224, 64, 127); // magenta #e0407f
const GREEN: (u8, u8, u8) = (47, 211, 107);
const RED: (u8, u8, u8) = (255, 77, 109);
const BEAK: (u8, u8, u8) = (246, 169, 60);
const TICK: Duration = Duration::from_millis(130);

#[derive(Clone, Copy)]
pub enum Style {
    Thinking,
    Flock,
}

pub struct Spinner {
    running: Arc<AtomicBool>,
    handle: Option<JoinHandle<()>>,
    style: Style,
    label: String,
    lines: usize,
}

impl Spinner {
    pub fn start(label: &str, style: Style) -> Self {
        let running = Arc::new(AtomicBool::new(true));
        let r = running.clone();
        let lbl = label.to_string();
        // Frame heights — keep in sync with frame generators below.
        let lines = match style {
            Style::Thinking => 7, // 3 flake + 1 gap + 3 bird (+ label tucked on bird row)
            Style::Flock => 4,    // 3 sky rows + 1 label
        };
        let c = use_color();
        let handle = thread::spawn(move || {
            hide_cursor();
            let mut t: u64 = 0;
            let mut first = true;
            while r.load(Ordering::Relaxed) {
                let frame = match style {
                    Style::Thinking => thinking_build(t, &lbl, c),
                    Style::Flock => flock_cross(t, &lbl, c),
                };
                draw(&frame, first);
                first = false;
                t = t.wrapping_add(1);
                thread::sleep(TICK);
            }
        });
        Spinner {
            running,
            handle: Some(handle),
            style,
            label: label.to_string(),
            lines,
        }
    }

    /// Run a closure; auto-success if Ok, auto-fail if Err.
    pub fn run<T, E: std::fmt::Display>(
        label: &str,
        style: Style,
        f: impl FnOnce() -> Result<T, E>,
    ) -> Result<T, E> {
        let sp = Spinner::start(label, style);
        match f() {
            Ok(v) => {
                sp.success(&format!("{label} done"));
                Ok(v)
            }
            Err(e) => {
                let msg = e.to_string();
                sp.fail(&msg);
                Err(e)
            }
        }
    }

    /// Stop the worker and play the success flourish; leaves the final frame.
    pub fn success(mut self, msg: &str) {
        self.halt();
        let c = use_color();
        match self.style {
            Style::Thinking => {
                for k in 0..4 {
                    draw(&thinking_finish(k, msg, /*ok=*/ true, c), false);
                    thread::sleep(TICK);
                }
            }
            Style::Flock => {
                for k in 0..5 {
                    draw(&flock_v(k, msg, /*done=*/ false, /*ok=*/ true, c), false);
                    thread::sleep(TICK);
                }
                draw(&flock_v(0, msg, true, true, c), false);
            }
        }
        show_cursor();
        self.handle = None; // leave the art on screen
    }

    /// Stop and play the failure flourish; leaves the final frame.
    pub fn fail(mut self, msg: &str) {
        self.halt();
        let c = use_color();
        match self.style {
            Style::Thinking => {
                for k in 0..4 {
                    draw(&thinking_finish(k, msg, /*ok=*/ false, c), false);
                    thread::sleep(TICK);
                }
            }
            Style::Flock => {
                for k in 0..5 {
                    draw(&flock_v(k, msg, /*done=*/ false, /*ok=*/ false, c), false);
                    thread::sleep(TICK);
                }
                draw(&flock_v(0, msg, true, false, c), false);
            }
        }
        show_cursor();
        self.handle = None;
    }

    /// Stop and clear, leaving nothing behind.
    pub fn stop(mut self) {
        self.halt();
        self.clear();
        show_cursor();
        self.handle = None;
    }

    fn halt(&mut self) {
        self.running.store(false, Ordering::Relaxed);
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
    }
    fn clear(&self) {
        let mut o = io::stdout();
        let n = self.lines;
        let _ = write!(o, "\r\x1b[{n}A");
        for _ in 0..n {
            let _ = write!(o, "\x1b[2K\x1b[1B");
        }
        let _ = write!(o, "\x1b[{n}A");
        let _ = o.flush();
        let _ = &self.label;
    }
}

impl Drop for Spinner {
    fn drop(&mut self) {
        if self.handle.is_some() {
            self.halt();
            self.clear();
            show_cursor();
        }
    }
}

// ---- ASCII Flik · shared geometry ----------------------------------------
//
// Layout uses a 9-char column with the bird centered on col 4 (0-indexed).
// The flake sits 3 rows up; a blank gap row separates it from the head so the
// composition doesn't read as a ceremonial mask the way the old draft did.
//
//      _*_         <- flake center  (cols 2..7)
//     (•ᴗ•)        <- head          (cols 2..7)
//    <(___)>       <- body+wings    (cols 1..8)
//      ^ ^         <- feet
//
// `bob` shifts the whole block one cell on alternate breaths.

const CREST: [char; 4] = ['', '', '', ''];
const DOTS: [&str; 4] = ["   ", ".  ", ".. ", "..."];

fn head_calm(eye: char, c: bool) -> String {
    // (•ᴗ•) — width 5, centered on col 4
    format!(
        "{}{}{}{}{}",
        paint("(", ACCENT, c),
        paint(&eye.to_string(), ACCENT, c),
        paint("", BEAK, c),
        paint(&eye.to_string(), ACCENT, c),
        paint(")", ACCENT, c),
    )
}
fn head_happy(c: bool) -> String {
    // (^ᴗ^) — same width; arms are added separately so the wings can go up.
    format!(
        "{}{}{}{}{}",
        paint("(", ACCENT, c),
        paint("^", ACCENT, c),
        paint("", BEAK, c),
        paint("^", ACCENT, c),
        paint(")", ACCENT, c),
    )
}
fn head_cool(c: bool) -> String {
    // (¬ᴗ¬) — smug/half-lid; distinct from the (-ᴗ-) blink frame so a blink
    // mid-thinking doesn't get misread as a finished/cool result.
    format!(
        "{}{}{}{}{}",
        paint("(", ACCENT, c),
        paint("¬", ACCENT, c),
        paint("", BEAK, c),
        paint("¬", ACCENT, c),
        paint(")", ACCENT, c),
    )
}

fn body_rest(c: bool) -> String {
    paint("<(___)>", ACCENT, c)
}
fn body_hop(c: bool) -> String {
    paint(" (___) ", ACCENT, c)
} // wings are with the head row
fn feet(c: bool) -> String {
    paint(" ^ ^ ", ACCENT, c)
}

// ---- Flik · thinking ------------------------------------------------------
fn thinking_build(t: u64, label: &str, c: bool) -> Vec<String> {
    let spk = CREST[(t / 3) as usize % CREST.len()];
    let eye = if t.is_multiple_of(14) { '-' } else { '' };
    let d = DOTS[(t / 3) as usize % DOTS.len()];
    let bob = if (t / 3).is_multiple_of(2) { "" } else { " " };
    vec![
        format!("{bob}   {}", paint(&format!(" _{spk}_"), ACCENT, c)),
        format!(
            "{bob}   {}   {}",
            head_calm(eye, c),
            paint(&format!("{label}{d}"), DIM, c)
        ),
        format!("{bob}  {}", body_rest(c)),
        format!("{bob}   {}", feet(c)),
    ]
}

// Two-stage finish: (k=0) flake collapses to a single bright glyph, then
// (k>=1) Flik flips into Hop (success) or Cool (failure) with ✓/✗ overhead.
fn thinking_finish(k: u64, msg: &str, ok: bool, c: bool) -> Vec<String> {
    let mark_rgb = if ok { GREEN } else { RED };
    let mark = if ok { "" } else { "" };
    let msg_rgb = if ok { GREEN } else { RED };

    if k == 0 {
        vec![
            String::new(),
            format!("    {}", paint(&format!("_{mark}_"), mark_rgb, c)),
            format!("   {}", head_calm('', c)),
            format!("  {}", body_rest(c)),
            format!("   {}", feet(c)),
        ]
    } else if ok {
        vec![
            String::new(),
            format!("    {}", paint(&format!("_{mark}_"), mark_rgb, c)),
            format!(
                "  {}{}{}   {}",
                paint("\\", ACCENT, c),
                head_happy(c),
                paint("/", ACCENT, c),
                paint(msg, msg_rgb, c)
            ),
            format!("  {}", body_hop(c)),
            format!("   {}", feet(c)),
        ]
    } else {
        vec![
            String::new(),
            format!("    {}", paint(&format!("_{mark}_"), mark_rgb, c)),
            format!("   {}   {}", head_cool(c), paint(msg, msg_rgb, c)),
            format!("  {}", paint("<(\\|/)>", ACCENT, c)),
            format!("   {}", feet(c)),
        ]
    }
}

// ---- Flik · flock ----------------------------------------------------------
const FW: usize = 36;

const VPOS: [(usize, usize); 5] = [
    (0, 1),  // top-left wing tip
    (0, 28), // top-right wing tip
    (1, 9),  // mid-left
    (1, 20), // mid-right
    (2, 14), // vertex (bottom)
];

fn glyph(flap: bool) -> String {
    let w = if flap { '' } else { '^' };
    format!("~({w}{w})~")
}
fn place(row: &mut [char], x: i64, g: &str) {
    for (k, ch) in g.chars().enumerate() {
        let xx = x + k as i64;
        if xx >= 0 && (xx as usize) < row.len() {
            row[xx as usize] = ch;
        }
    }
}
fn rows_to_lines(rows: Vec<Vec<char>>, c: bool, color: (u8, u8, u8)) -> Vec<String> {
    rows.into_iter()
        .map(|r| paint(&r.into_iter().collect::<String>(), color, c))
        .collect()
}

fn flock_cross(t: u64, label: &str, c: bool) -> Vec<String> {
    let mut rows = vec![vec![' '; FW]; 3];
    for (i, o) in [0usize, 12, 24].iter().enumerate() {
        let span = (FW + 9) as i64;
        let x = ((t as i64 + *o as i64) % span) - 5;
        let flap = (t as usize + i).is_multiple_of(2);
        let y = if ((t / 2) as usize + i).is_multiple_of(2) {
            0
        } else {
            1
        };
        place(&mut rows[y], x, &glyph(flap));
    }
    let mut out = rows_to_lines(rows, c, ACCENT);
    out.push(format!(" {}", paint(&format!("{label}"), DIM, c)));
    out
}

fn flock_v(k: u64, msg: &str, done: bool, ok: bool, c: bool) -> Vec<String> {
    let mut rows = vec![vec![' '; FW]; 3];
    if ok {
        for (i, (ty, tx)) in VPOS.iter().enumerate() {
            let flap = (k as usize + i).is_multiple_of(2);
            place(&mut rows[*ty], *tx as i64, &glyph(flap));
        }
    } else {
        let scatter: [(usize, usize); 4] = [(0, 3), (2, 9), (1, 20), (0, 28)];
        for (i, (ty, tx)) in scatter.iter().enumerate() {
            let flap = (k as usize + i).is_multiple_of(2);
            place(&mut rows[*ty], *tx as i64, &glyph(flap));
        }
    }
    let color = if ok { ACCENT } else { RED };
    let mut out = rows_to_lines(rows, c, color);
    out.push(if done {
        if ok {
            format!(" {}", paint(&format!("{msg}"), GREEN, c))
        } else {
            format!(" {}", paint(&format!("{msg}"), RED, c))
        }
    } else if ok {
        format!(" {}", paint("finalizing…", DIM, c))
    } else {
        format!(" {}", paint("aborting…", DIM, c))
    });
    out
}

// ---- terminal plumbing -----------------------------------------------------
const DIM: (u8, u8, u8) = (0, 0, 0); // sentinel for the 2m dim attribute

fn draw(lines: &[String], first: bool) {
    let mut s = String::new();
    if !first {
        s.push_str(&format!("\x1b[{}A", lines.len()));
    }
    s.push('\r');
    for l in lines {
        s.push_str("\x1b[2K");
        s.push_str(l);
        s.push('\n');
    }
    let mut o = io::stdout();
    let _ = write!(o, "{}", s);
    let _ = o.flush();
}

fn paint(text: &str, rgb: (u8, u8, u8), color: bool) -> String {
    if !color {
        return text.to_string();
    }
    if rgb == DIM {
        return format!("\x1b[2m{text}\x1b[22m");
    }
    let (r, g, b) = rgb;
    format!("\x1b[38;2;{r};{g};{b}m{text}\x1b[39m")
}

fn use_color() -> bool {
    std::env::var_os("NO_COLOR").is_none()
}
fn hide_cursor() {
    let _ = write!(io::stdout(), "\x1b[?25l");
    let _ = io::stdout().flush();
}
fn show_cursor() {
    let _ = write!(io::stdout(), "\x1b[?25h");
    let _ = io::stdout().flush();
}