primum 0.1.0

Prioritized work items as plain markdown files, with a command line and a local web board
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
//! The local web board: axum routes, the JSON API and the pages.
//!
//! Every listed project is served under `/p/<name>/`. The project list is
//! read once at start; each request reloads the project's files, so an edit
//! made in a text editor shows on the next page load.
use crate::item_file::{file_name, parse_item_name, stem};
use crate::model::{Item, blockers, kind_rank};
use crate::projects::{self, Entry};
use crate::store::{self, Board, Changes, Doc, Project};
use askama::Template;
use axum::Router;
use axum::extract::{Path, Query, State};
use axum::http::{StatusCode, header};
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use serde::Serialize;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;

/// An item as the API and `--json` give it: its fields, plus what the page
/// shows beside them.
#[derive(Debug, Clone, Serialize)]
pub struct ItemView {
    pub id: String,
    pub kind: String,
    pub num: u32,
    pub title: String,
    pub status: String,
    pub impact: u8,
    pub urgency: u8,
    pub risk: u8,
    pub effort: u8,
    pub needs: Vec<String>,
    pub finished: Option<String>,
    pub source: String,
    pub body: String,
    pub score: f64,
    pub kind_rank: usize,
    pub blockers: Vec<String>,
    pub blocked: bool,
    /// The item's own documents and the ones it lists.
    pub docs: Vec<Doc>,
    /// The item's file, relative to the project root.
    pub file: String,
    /// The start of the item's file names, `TODO-87`; its page is `item/<stem>`.
    pub stem: String,
}

impl ItemView {
    pub fn new(it: &Item, board: &Board) -> ItemView {
        let blockers = blockers(it, &board.items);
        ItemView {
            id: it.id.clone(),
            kind: it.kind.clone(),
            num: it.num,
            title: it.title.clone(),
            status: it.status.clone(),
            impact: it.impact,
            urgency: it.urgency,
            risk: it.risk,
            effort: it.effort,
            needs: it.needs.clone(),
            finished: it.finished.clone(),
            source: it.source.clone(),
            body: it.body.clone(),
            score: it.score(),
            kind_rank: kind_rank(&it.kind),
            blocked: !blockers.is_empty(),
            blockers,
            docs: board.docs.get(&it.id).cloned().unwrap_or_default(),
            file: format!("items/{}", file_name(&it.id)),
            stem: stem(&it.id),
        }
    }
}

/// Every item of the board, in priority order.
pub fn views(board: &Board) -> Vec<ItemView> {
    board
        .items
        .iter()
        .map(|i| ItemView::new(i, board))
        .collect()
}

struct AppState {
    entries: Vec<Entry>,
}

type Shared = Arc<AppState>;

impl AppState {
    fn project(&self, name: &str) -> Result<&Project, ApiError> {
        self.entries
            .iter()
            .filter_map(|e| e.project.as_ref().ok())
            .find(|p| p.name == name)
            .ok_or_else(|| ApiError(StatusCode::NOT_FOUND, format!("no project {name}")))
    }
}

/// An API failure: answered as `{"error": message}`.
#[derive(Debug)]
struct ApiError(StatusCode, String);

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        (self.0, axum::Json(json!({ "error": self.1 }))).into_response()
    }
}

impl From<anyhow::Error> for ApiError {
    fn from(e: anyhow::Error) -> ApiError {
        let message = format!("{e:#}");
        let code = if message.starts_with("no item ") {
            StatusCode::NOT_FOUND
        } else {
            StatusCode::BAD_REQUEST
        };
        ApiError(code, message)
    }
}

fn bad(message: impl Into<String>) -> ApiError {
    ApiError(StatusCode::BAD_REQUEST, message.into())
}

pub fn router(entries: Vec<Entry>) -> Router {
    let state = Arc::new(AppState { entries });
    Router::new()
        .route("/", get(root))
        .route("/p/{project}", get(add_slash))
        .route("/p/{project}/", get(board_page))
        .route("/p/{project}/item/{stem}", get(item_page))
        .route("/p/{project}/api/items", get(api_items).post(api_update))
        .route("/p/{project}/api/items/kind", post(api_kind))
        .route("/p/{project}/api/new", post(api_new))
        .route("/p/{project}/api/delete", post(api_delete))
        .route("/p/{project}/api/doc", get(api_doc))
        .route("/static/{file}", get(asset))
        .with_state(state)
}

/// Serves the board on 127.0.0.1 until interrupted.
pub fn serve(port: u16, open_browser: bool) -> anyhow::Result<()> {
    let entries = projects::list()?;
    if entries.iter().all(|e| e.project.is_err()) {
        anyhow::bail!("no projects to show: run `primum init` in a folder");
    }
    let rt = tokio::runtime::Runtime::new()?;
    rt.block_on(async move {
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
            .await
            .map_err(|e| anyhow::anyhow!("cannot listen on 127.0.0.1:{port}: {e}"))?;
        let url = format!("http://127.0.0.1:{port}/");
        println!("primum board at {url}");
        if open_browser {
            let opener = if cfg!(target_os = "macos") {
                "open"
            } else {
                "xdg-open"
            };
            let _ = std::process::Command::new(opener).arg(&url).spawn();
        }
        axum::serve(listener, router(entries)).await?;
        Ok(())
    })
}

// ---------------------------------------------------------------- pages

fn url_part(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
            out.push(b as char);
        } else {
            out += &format!("%{b:02X}");
        }
    }
    out
}

fn project_url(name: &str) -> String {
    format!("/p/{}/", url_part(name))
}

async fn root(State(s): State<Shared>) -> Response {
    match s.entries.iter().find_map(|e| e.project.as_ref().ok()) {
        Some(p) => Redirect::to(&project_url(&p.name)).into_response(),
        None => (StatusCode::NOT_FOUND, "no projects: run `primum init`").into_response(),
    }
}

async fn add_slash(Path(project): Path<String>) -> Redirect {
    Redirect::permanent(&project_url(&project))
}

/// One tab of the nav strip.
pub struct NavLink {
    pub name: String,
    pub href: String,
    pub on: bool,
    /// Why the project cannot be shown, for an unavailable one.
    pub reason: Option<String>,
}

/// What every page shows around its content.
pub struct PageCommon {
    pub project: String,
    pub path: String,
    pub open: usize,
    pub doing: usize,
    pub nav: Vec<NavLink>,
    /// `PROJECT` and `API` for the page's scripts, as a JSON object.
    pub globals: String,
}

/// JSON for a `<script>`: `</` is escaped so no string can end the element.
fn script_json(v: &Value) -> String {
    v.to_string().replace("</", "<\\/")
}

fn common(s: &AppState, p: &Project, board: &Board) -> PageCommon {
    let nav = s
        .entries
        .iter()
        .map(|e| match &e.project {
            Ok(q) => NavLink {
                name: q.name.clone(),
                href: project_url(&q.name),
                on: q.name == p.name,
                reason: None,
            },
            Err(why) => NavLink {
                name: e
                    .path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| e.path.display().to_string()),
                href: String::new(),
                on: false,
                reason: Some(why.clone()),
            },
        })
        .collect();
    let api = format!("/p/{}/api", url_part(&p.name));
    PageCommon {
        project: p.name.clone(),
        path: projects::contract(&p.root),
        open: board.items.iter().filter(|i| !i.is_closed()).count(),
        doing: board.items.iter().filter(|i| i.status == "doing").count(),
        nav,
        globals: script_json(&json!({ "PROJECT": p.name, "API": api })),
    }
}

#[derive(Template)]
#[template(path = "board.html")]
struct BoardPage {
    page: PageCommon,
}

#[derive(Template)]
#[template(path = "item.html")]
struct ItemPage {
    page: PageCommon,
    id: String,
    title: String,
    /// `ITEM_ID` for the page's script.
    item_json: String,
}

fn html(t: impl Template) -> Response {
    match t.render() {
        Ok(s) => Html(s).into_response(),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    }
}

async fn board_page(
    State(s): State<Shared>,
    Path(project): Path<String>,
) -> Result<Response, ApiError> {
    let p = s.project(&project)?;
    let board = store::load(p)?;
    Ok(html(BoardPage {
        page: common(&s, p, &board),
    }))
}

async fn item_page(
    State(s): State<Shared>,
    Path((project, item)): Path<(String, String)>,
) -> Result<Response, ApiError> {
    let p = s.project(&project)?;
    let board = store::load(p)?;
    let id = parse_item_name(&format!("{item}.md"))
        .map(|(k, n)| crate::model::id_of(&k, n))
        .and_then(|id| board.get(&id).map(|i| i.id.clone()))
        .ok_or_else(|| ApiError(StatusCode::NOT_FOUND, format!("no item {item}")))?;
    let it = board.get(&id).expect("found above");
    Ok(html(ItemPage {
        page: common(&s, p, &board),
        title: it.title.clone(),
        item_json: script_json(&json!(id)),
        id,
    }))
}

// ---------------------------------------------------------------- API

async fn api_items(
    State(s): State<Shared>,
    Path(project): Path<String>,
) -> Result<axum::Json<Vec<ItemView>>, ApiError> {
    let board = store::load(s.project(&project)?)?;
    Ok(axum::Json(views(&board)))
}

async fn api_doc(
    State(s): State<Shared>,
    Path(project): Path<String>,
    Query(q): Query<HashMap<String, String>>,
) -> Result<Response, ApiError> {
    let p = s.project(&project)?;
    let path = q.get("path").map(String::as_str).unwrap_or("");
    Ok(match store::read_doc(p, path) {
        Some(text) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text).into_response(),
        None => (StatusCode::NOT_FOUND, "not a document").into_response(),
    })
}

fn text_field(v: &Value, key: &str) -> Result<Option<String>, ApiError> {
    match v.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) => Ok(Some(s.clone())),
        Some(_) => Err(bad(format!("{key} must be text"))),
    }
}

/// A score as board.py's coerce_priority read it: a number or numeric text,
/// clamped to 1-10 later by the store.
fn score_field(v: &Value, key: &str) -> Result<Option<i64>, ApiError> {
    match v.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Number(n)) => n
            .as_i64()
            .or_else(|| n.as_f64().map(|f| f as i64))
            .map(Some)
            .ok_or_else(|| bad(format!("{key} must be a number"))),
        Some(Value::String(s)) => s
            .trim()
            .parse()
            .map(Some)
            .map_err(|_| bad(format!("{key} must be a number"))),
        Some(_) => Err(bad(format!("{key} must be a number"))),
    }
}

/// `needs` as the page sends it (`"TODO:1, BUG:2"`) or as a list.
fn needs_field(v: &Value) -> Result<Option<Vec<String>>, ApiError> {
    let text = match v.get("needs") {
        None | Some(Value::Null) => return Ok(None),
        Some(Value::String(s)) => s.clone(),
        Some(Value::Array(a)) => a
            .iter()
            .map(|x| x.as_str().unwrap_or_default())
            .collect::<Vec<_>>()
            .join(","),
        Some(_) => return Err(bad("needs must be text or a list")),
    };
    crate::cli::parse_needs(&text)
        .map(Some)
        .map_err(|e| bad(e.to_string()))
}

fn changes(v: &Value) -> Result<Changes, ApiError> {
    Ok(Changes {
        title: text_field(v, "title")?,
        status: text_field(v, "status")?,
        impact: score_field(v, "impact")?,
        urgency: score_field(v, "urgency")?,
        risk: score_field(v, "risk")?,
        effort: score_field(v, "effort")?,
        needs: needs_field(v)?,
        body: text_field(v, "body")?,
    })
}

fn id_field(v: &Value) -> Result<String, ApiError> {
    text_field(v, "id")?.ok_or_else(|| bad("id required"))
}

async fn api_update(
    State(s): State<Shared>,
    Path(project): Path<String>,
    axum::Json(v): axum::Json<Value>,
) -> Result<axum::Json<Value>, ApiError> {
    let p = s.project(&project)?;
    let id = id_field(&v)?;
    let c = changes(&v)?;
    let nothing = c.title.is_none()
        && c.status.is_none()
        && c.impact.is_none()
        && c.urgency.is_none()
        && c.risk.is_none()
        && c.effort.is_none()
        && c.needs.is_none()
        && c.body.is_none();
    if nothing {
        return Err(bad("nothing to update"));
    }
    store::update(p, &id, c)?;
    Ok(axum::Json(json!({ "ok": true })))
}

async fn api_kind(
    State(s): State<Shared>,
    Path(project): Path<String>,
    axum::Json(v): axum::Json<Value>,
) -> Result<axum::Json<Value>, ApiError> {
    let p = s.project(&project)?;
    let id = id_field(&v)?;
    let kind = text_field(&v, "kind")?.ok_or_else(|| bad("kind required"))?;
    let new = store::set_kind(p, &id, &kind)?;
    Ok(axum::Json(
        json!({ "old": id, "new": new, "stem": stem(&new) }),
    ))
}

async fn api_new(
    State(s): State<Shared>,
    Path(project): Path<String>,
    axum::Json(v): axum::Json<Value>,
) -> Result<axum::Json<Value>, ApiError> {
    let p = s.project(&project)?;
    let kind = text_field(&v, "kind")?.unwrap_or_else(|| "TODO".into());
    let title = text_field(&v, "title")?.unwrap_or_default();
    let mut c = changes(&v)?;
    c.title = None;
    let id = store::insert(p, &kind, &title, c)?;
    Ok(axum::Json(json!({ "id": id, "stem": stem(&id) })))
}

async fn api_delete(
    State(s): State<Shared>,
    Path(project): Path<String>,
    axum::Json(v): axum::Json<Value>,
) -> Result<axum::Json<Value>, ApiError> {
    let p = s.project(&project)?;
    let removed = store::delete(p, &id_field(&v)?)?;
    Ok(axum::Json(json!({ "removed": removed })))
}

// ---------------------------------------------------------------- static

/// (name, content type, text) of every file under static/, embedded.
static ASSETS: &[(&str, &str, &str)] = &[
    (
        "chrome.css",
        "text/css; charset=utf-8",
        include_str!("../static/chrome.css"),
    ),
    (
        "primum.css",
        "text/css; charset=utf-8",
        include_str!("../static/primum.css"),
    ),
    (
        "md.js",
        "text/javascript; charset=utf-8",
        include_str!("../static/md.js"),
    ),
    (
        "board.js",
        "text/javascript; charset=utf-8",
        include_str!("../static/board.js"),
    ),
    (
        "item.js",
        "text/javascript; charset=utf-8",
        include_str!("../static/item.js"),
    ),
];

async fn asset(Path(file): Path<String>) -> Response {
    match ASSETS.iter().find(|(name, _, _)| *name == file) {
        Some((_, ctype, text)) => (
            [
                (header::CONTENT_TYPE, *ctype),
                (header::CACHE_CONTROL, "no-cache"),
            ],
            *text,
        )
            .into_response(),
        None => (StatusCode::NOT_FOUND, "no such file").into_response(),
    }
}