cookcli 0.38.1

A command-line interface for managing and working with Cooklang recipes
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
use super::common::json_error;
use axum::{
    extract::{Extension, Json, Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
};
use camino::Utf8PathBuf;
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json;
use std::sync::Arc;

use crate::server::{activity, AppState};
use crate::web::viewer::Viewer;

/// Load and parse the pantry file asynchronously.
async fn load_pantry(
    state: &AppState,
) -> Result<cooklang::pantry::PantryConf, (StatusCode, Json<serde_json::Value>)> {
    let pantry_path = get_pantry_path(state)?;

    let content = tokio::fs::read_to_string(pantry_path.as_std_path())
        .await
        .map_err(|e| {
            tracing::error!("Failed to read pantry file: {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                json_error(format!("Failed to read pantry file: {e}")),
            )
        })?;

    let result = cooklang::pantry::parse_lenient(&content);
    result.output().cloned().ok_or_else(|| {
        (
            StatusCode::NOT_FOUND,
            json_error("Failed to parse pantry configuration"),
        )
    })
}

fn get_pantry_path(
    state: &AppState,
) -> Result<&Utf8PathBuf, (StatusCode, Json<serde_json::Value>)> {
    state.pantry_path.as_ref().ok_or_else(|| {
        (
            StatusCode::NOT_FOUND,
            json_error("Pantry configuration not found"),
        )
    })
}

#[derive(Debug, Deserialize)]
pub struct AddPantryItem {
    pub section: String,
    pub name: String,
    pub quantity: Option<String>,
    pub bought: Option<String>,
    pub expire: Option<String>,
    pub low: Option<String>,
}

impl AddPantryItem {
    /// The item with the spaces typed around each field taken off, and blank
    /// attributes left unset.
    ///
    /// The pantry is matched against recipe ingredients by name, so ` Milk`
    /// kept as typed is never taken off a shopping list that asks for `milk`,
    /// and a quantity of ` unlim` is not unlimited.
    ///
    /// # Errors
    ///
    /// When the section or the name is blank.
    fn trimmed(self) -> Result<Self, &'static str> {
        let section = self.section.trim().to_string();
        let name = self.name.trim().to_string();
        if section.is_empty() {
            return Err("Section cannot be empty");
        }
        if name.is_empty() {
            return Err("Item name cannot be empty");
        }

        let attribute = |value: Option<String>| {
            value
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
        };
        Ok(Self {
            section,
            name,
            quantity: attribute(self.quantity),
            bought: attribute(self.bought),
            expire: attribute(self.expire),
            low: attribute(self.low),
        })
    }
}

#[derive(Debug, Deserialize)]
pub struct UpdatePantryItem {
    pub quantity: Option<String>,
    pub bought: Option<String>,
    pub expire: Option<String>,
    pub low: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct ApiResponse {
    pub success: bool,
    pub message: String,
}

pub async fn add_item(
    State(state): State<Arc<AppState>>,
    Extension(viewer): Extension<Viewer>,
    Json(item): Json<AddPantryItem>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
    let item = item
        .trimmed()
        .map_err(|e| (StatusCode::BAD_REQUEST, json_error(e)))?;
    let pantry_path = get_pantry_path(&state)?;
    let mut pantry_conf = load_pantry(&state).await.unwrap_or_default();

    // Create new item
    let new_item = if item.quantity.is_some()
        || item.bought.is_some()
        || item.expire.is_some()
        || item.low.is_some()
    {
        cooklang::pantry::PantryItem::WithAttributes(cooklang::pantry::ItemWithAttributes {
            name: item.name.clone(),
            quantity: item.quantity,
            bought: item.bought,
            expire: item.expire,
            low: item.low,
        })
    } else {
        cooklang::pantry::PantryItem::Simple(item.name.clone())
    };

    // Add item to the specified section
    pantry_conf
        .sections
        .entry(item.section.clone())
        .or_insert_with(Vec::new)
        .push(new_item);

    // Rebuild index
    pantry_conf.rebuild_index();

    // Serialize back to regular TOML format (not array format)
    let new_content = serialize_pantry_to_regular_toml(&pantry_conf);

    // Write back to file
    tokio::fs::write(pantry_path.as_std_path(), new_content)
        .await
        .map_err(|e| {
            tracing::error!("Failed to write pantry file: {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                json_error(format!("Failed to write pantry file: {e}")),
            )
        })?;

    activity::record(
        &viewer,
        format_args!(
            "added {} to the {} section of the pantry",
            activity::quoted(&item.name),
            activity::quoted(&item.section)
        ),
    );

    Ok(Json(ApiResponse {
        success: true,
        message: format!("Added {} to {}", item.name, item.section),
    }))
}

pub async fn remove_item(
    State(state): State<Arc<AppState>>,
    Extension(viewer): Extension<Viewer>,
    Path((section, name)): Path<(String, String)>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
    let pantry_path = get_pantry_path(&state)?;
    let mut pantry_conf = load_pantry(&state).await?;

    // Remove item from the specified section
    if let Some(items) = pantry_conf.sections.get_mut(&section) {
        items.retain(|item| item.name() != name);

        // Remove section if empty
        if items.is_empty() {
            pantry_conf.sections.shift_remove(&section);
        }
    } else {
        return Err((
            StatusCode::NOT_FOUND,
            json_error(format!("Section not found: {section}")),
        ));
    }

    // Rebuild index
    pantry_conf.rebuild_index();

    // Serialize back to regular TOML format (not array format)
    let new_content = serialize_pantry_to_regular_toml(&pantry_conf);

    // Write back to file
    tokio::fs::write(pantry_path.as_std_path(), new_content)
        .await
        .map_err(|e| {
            tracing::error!("Failed to write pantry file: {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                json_error(format!("Failed to write pantry file: {e}")),
            )
        })?;

    activity::record(
        &viewer,
        format_args!(
            "removed {} from the {} section of the pantry",
            activity::quoted(&name),
            activity::quoted(&section)
        ),
    );

    Ok(Json(ApiResponse {
        success: true,
        message: format!("Removed {name} from {section}"),
    }))
}

pub async fn update_item(
    State(state): State<Arc<AppState>>,
    Extension(viewer): Extension<Viewer>,
    Path((section, name)): Path<(String, String)>,
    Json(update): Json<UpdatePantryItem>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
    let pantry_path = get_pantry_path(&state)?;
    let mut pantry_conf = load_pantry(&state).await?;

    // Find and update the item
    if let Some(items) = pantry_conf.sections.get_mut(&section) {
        for item in items.iter_mut() {
            if item.name() == name {
                // Convert to WithAttributes if needed
                let updated_item = match item {
                    cooklang::pantry::PantryItem::Simple(item_name) => {
                        if update.quantity.is_some()
                            || update.bought.is_some()
                            || update.expire.is_some()
                            || update.low.is_some()
                        {
                            cooklang::pantry::PantryItem::WithAttributes(
                                cooklang::pantry::ItemWithAttributes {
                                    name: item_name.clone(),
                                    quantity: update.quantity.clone(),
                                    bought: update.bought.clone(),
                                    expire: update.expire.clone(),
                                    low: update.low,
                                },
                            )
                        } else {
                            cooklang::pantry::PantryItem::Simple(item_name.clone())
                        }
                    }
                    cooklang::pantry::PantryItem::WithAttributes(attrs) => {
                        cooklang::pantry::PantryItem::WithAttributes(
                            cooklang::pantry::ItemWithAttributes {
                                name: attrs.name.clone(),
                                quantity: update.quantity.clone().or(attrs.quantity.clone()),
                                bought: update.bought.clone().or(attrs.bought.clone()),
                                expire: update.expire.clone().or(attrs.expire.clone()),
                                low: update.low.clone().or(attrs.low.clone()),
                            },
                        )
                    }
                };
                *item = updated_item;
                break;
            }
        }
    } else {
        return Err((
            StatusCode::NOT_FOUND,
            json_error(format!("Section not found: {section}")),
        ));
    }

    // Rebuild index
    pantry_conf.rebuild_index();

    // Serialize back to regular TOML format (not array format)
    let new_content = serialize_pantry_to_regular_toml(&pantry_conf);

    // Write back to file
    tokio::fs::write(pantry_path.as_std_path(), new_content)
        .await
        .map_err(|e| {
            tracing::error!("Failed to write pantry file: {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                json_error(format!("Failed to write pantry file: {e}")),
            )
        })?;

    activity::record(
        &viewer,
        format_args!(
            "updated {} in the {} section of the pantry",
            activity::quoted(&name),
            activity::quoted(&section)
        ),
    );

    Ok(Json(ApiResponse {
        success: true,
        message: format!("Updated {name} in {section}"),
    }))
}

pub async fn get_pantry(
    State(state): State<Arc<AppState>>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
    let pantry_conf = load_pantry(&state).await?;
    Ok(Json(pantry_conf))
}

#[derive(Debug, Deserialize)]
pub struct ExpiringQuery {
    pub days: Option<i64>,
}

#[derive(Debug, Serialize)]
pub struct ExpiringItemResponse {
    pub section: String,
    pub name: String,
    pub expire: String,
    pub days_remaining: i64,
}

#[derive(Debug, Serialize)]
pub struct DepletedItemResponse {
    pub section: String,
    pub name: String,
    pub low: Option<String>,
}

pub async fn get_expiring(
    State(state): State<Arc<AppState>>,
    Query(query): Query<ExpiringQuery>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
    let days = query.days.unwrap_or(7);
    if days < 0 {
        return Err((
            StatusCode::BAD_REQUEST,
            json_error("days must be non-negative"),
        ));
    }

    let pantry_conf = load_pantry(&state).await?;
    let today = Local::now().date_naive();
    // A `days` big enough to run off the end of the calendar means every date
    // is within it. Saturating rather than panicking matters here more than in
    // the CLI: `days` comes straight off the query string, so an out-of-range
    // value would take down the request handler.
    let threshold = today
        .checked_add_signed(chrono::Duration::days(days))
        .unwrap_or(NaiveDate::MAX);

    let mut items = Vec::new();

    for (section, section_items) in &pantry_conf.sections {
        for item in section_items {
            if let Some(expire_str) = item.expire() {
                if let Some(date) = parse_date(expire_str) {
                    if date <= threshold {
                        let days_remaining = (date - today).num_days();
                        items.push(ExpiringItemResponse {
                            section: section.clone(),
                            name: item.name().to_string(),
                            expire: date.format("%Y-%m-%d").to_string(),
                            days_remaining,
                        });
                    }
                }
            }
        }
    }

    // Sort by days_remaining so most urgent items come first
    items.sort_by_key(|item| item.days_remaining);

    Ok(Json(items))
}

pub async fn get_depleted(
    State(state): State<Arc<AppState>>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
    let pantry_conf = load_pantry(&state).await?;
    let mut items = Vec::new();

    for (section, section_items) in &pantry_conf.sections {
        for item in section_items {
            if item.is_low() {
                items.push(DepletedItemResponse {
                    section: section.clone(),
                    name: item.name().to_string(),
                    low: item.low().map(|l| l.to_string()),
                });
            }
        }
    }

    Ok(Json(items))
}

/// Parse a date string supporting multiple formats
pub fn parse_date(date_str: &str) -> Option<NaiveDate> {
    let formats = [
        "%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%m/%d/%Y", "%Y.%m.%d", "%d-%m-%Y",
    ];

    for format in &formats {
        if let Ok(date) = NaiveDate::parse_from_str(date_str, format) {
            return Some(date);
        }
    }

    None
}

fn serialize_pantry_to_regular_toml(pantry_conf: &cooklang::pantry::PantryConf) -> String {
    cooklang::pantry::to_toml_string(pantry_conf)
}

#[cfg(test)]
mod tests {
    use super::AddPantryItem;

    fn item(section: &str, name: &str, quantity: Option<&str>) -> AddPantryItem {
        AddPantryItem {
            section: section.to_string(),
            name: name.to_string(),
            quantity: quantity.map(str::to_string),
            bought: None,
            expire: Some(" 2026-01-01 ".to_string()),
            low: Some("   ".to_string()),
        }
    }

    #[test]
    fn a_new_item_is_trimmed() {
        let added = item(" fridge ", " Milk ", Some(" unlim "))
            .trimmed()
            .unwrap();
        assert_eq!(added.section, "fridge");
        assert_eq!(added.name, "Milk");
        assert_eq!(added.quantity.as_deref(), Some("unlim"));
        assert_eq!(added.expire.as_deref(), Some("2026-01-01"));
        // A blank attribute is not an attribute.
        assert_eq!(added.low, None);
    }

    #[test]
    fn a_blank_name_or_section_is_refused() {
        assert!(item("fridge", "   ", None).trimmed().is_err());
        assert!(item(" ", "Milk", None).trimmed().is_err());
    }
}