padzapp 0.16.0

An ergonomic, context-aware scratch pad library with plain text storage
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
use crate::commands::{CmdMessage, CmdResult};
use crate::error::{PadzError, Result};
use crate::index::{DisplayIndex, PadSelector};
use crate::model::Scope;
use crate::store::DataStore;
use uuid::Uuid;

use super::helpers::{indexed_pads, pads_by_selectors};

/// Permanently removes pads from the store.
///
/// **Confirmation required**: The `confirmed` parameter must be `true` to proceed.
/// If `false`, returns an error instructing the user to use `--yes` or `-y`.
///
/// **Safety valve**: When purging pads that have children, the `recursive` flag must be set.
/// This prevents accidental deletion of entire subtrees.
///
/// - If `selectors` is empty, targets all deleted pads
/// - If `recursive` is false and any target has children, returns an error
/// - If `confirmed` is false, returns an error (no pads are deleted)
pub fn run<S: DataStore>(
    store: &mut S,
    scope: Scope,
    selectors: &[PadSelector],
    recursive: bool,
    confirmed: bool,
) -> Result<CmdResult> {
    // 1. Resolve targets
    let pads_to_purge = if selectors.is_empty() {
        let all_pads = indexed_pads(store, scope)?;
        all_pads
            .into_iter()
            .filter(|dp| matches!(dp.index, DisplayIndex::Deleted(_)))
            .collect()
    } else {
        pads_by_selectors(store, scope, selectors, true)?
    };

    if pads_to_purge.is_empty() {
        let mut res = CmdResult::default();
        res.add_message(CmdMessage::info("No pads to purge."));
        return Ok(res);
    }

    // 2. Find descendants
    let target_ids: Vec<Uuid> = pads_to_purge.iter().map(|dp| dp.pad.metadata.id).collect();
    let descendants = super::helpers::get_descendant_ids(store, scope, &target_ids)?;

    // 3. Safety valve: require --recursive if there are children
    if !descendants.is_empty() && !recursive {
        return Err(PadzError::Api(format!(
            "Cannot purge: {} pad(s) have children. Use --recursive (-r) to purge entire subtrees.",
            pads_to_purge
                .iter()
                .filter(|dp| {
                    let id = dp.pad.metadata.id;
                    super::helpers::get_descendant_ids(store, scope, &[id])
                        .map(|d| !d.is_empty())
                        .unwrap_or(false)
                })
                .count()
        )));
    }

    // 4. Calculate total count for message
    let total_count = pads_to_purge.len() + descendants.len();

    // 5. Confirmation check - must come after we know the count
    if !confirmed {
        return Err(PadzError::Api(format!(
            "Purging {} pad(s). Aborted, confirm with --yes or -y for hard deletion.",
            total_count
        )));
    }

    // 6. Execute the purge
    let mut all_ids = target_ids;
    all_ids.extend(descendants.clone());
    all_ids.sort();
    all_ids.dedup();

    let mut result = CmdResult::default();

    // Add the "Purging X padz..." message first
    result.add_message(CmdMessage::info(format!(
        "Purging {} pad(s)...",
        total_count
    )));

    for id in all_ids {
        if store.get_pad(&id, scope).is_ok() {
            store.delete_pad(&id, scope)?;
        }
    }

    for dp in pads_to_purge {
        result.add_message(CmdMessage::success(format!(
            "Purged: {} {}",
            dp.index, dp.pad.metadata.title
        )));
    }
    if !descendants.is_empty() {
        result.add_message(CmdMessage::success(format!(
            "And purged {} descendant(s)",
            descendants.len()
        )));
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::{create, delete, get};
    use crate::index::DisplayIndex;
    use crate::model::Scope;
    use crate::store::memory::InMemoryStore;

    #[test]
    fn purges_deleted_pads_when_confirmed() {
        let mut store = InMemoryStore::new();
        create::run(&mut store, Scope::Project, "A".into(), "".into(), None).unwrap();

        // Delete it
        delete::run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        )
        .unwrap();

        // Verify it's deleted
        let deleted = get::run(
            &store,
            Scope::Project,
            get::PadFilter {
                status: get::PadStatusFilter::Deleted,
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(deleted.listed_pads.len(), 1);

        // Purge with confirmed=true
        let res = run(
            &mut store,
            Scope::Project,
            &[],
            false, // recursive not needed
            true,  // confirmed
        )
        .unwrap();

        // Should have "Purging 1 pad(s)..." and "Purged: d1 A"
        assert!(res.messages.iter().any(|m| m.content.contains("Purging 1")));
        assert!(res
            .messages
            .iter()
            .any(|m| m.content.contains("Purged: d1 A")));

        // Verify empty
        let deleted_after = get::run(
            &store,
            Scope::Project,
            get::PadFilter {
                status: get::PadStatusFilter::Deleted,
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(deleted_after.listed_pads.len(), 0);
    }

    #[test]
    fn purge_without_confirmation_returns_error() {
        let mut store = InMemoryStore::new();
        create::run(&mut store, Scope::Project, "A".into(), "".into(), None).unwrap();

        // Delete it
        delete::run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        )
        .unwrap();

        // Purge with confirmed=false - should fail
        let result = run(
            &mut store,
            Scope::Project,
            &[],
            false, // recursive
            false, // confirmed = false
        );

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Aborted"));
        assert!(err.to_string().contains("--yes"));
        assert!(err.to_string().contains("-y"));

        // Verify pad is still there (not purged)
        let deleted = get::run(
            &store,
            Scope::Project,
            get::PadFilter {
                status: get::PadStatusFilter::Deleted,
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(deleted.listed_pads.len(), 1);
    }

    #[test]
    fn purges_specific_pads_even_if_active() {
        let mut store = InMemoryStore::new();
        create::run(&mut store, Scope::Project, "A".into(), "".into(), None).unwrap();

        // Purge active pad 1 (no children, so recursive not needed)
        let res = run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
            false, // recursive
            true,  // confirmed
        )
        .unwrap();

        assert!(res
            .messages
            .iter()
            .any(|m| m.content.contains("Purged: 1 A")));

        // Verify gone
        let listed = get::run(&store, Scope::Project, get::PadFilter::default()).unwrap();
        assert_eq!(listed.listed_pads.len(), 0);
    }

    #[test]
    fn does_nothing_if_no_deleted_pads() {
        let mut store = InMemoryStore::new();
        create::run(&mut store, Scope::Project, "A".into(), "".into(), None).unwrap();

        // Purge deleted (none) - even with confirmed=true, should just say "No pads"
        let res = run(&mut store, Scope::Project, &[], false, true).unwrap();

        assert_eq!(res.messages.len(), 1);
        assert!(res.messages[0].content.contains("No pads to purge"));

        // A still exists
        let listed = get::run(&store, Scope::Project, get::PadFilter::default()).unwrap();
        assert_eq!(listed.listed_pads.len(), 1);
    }

    #[test]
    fn purges_recursively_with_flag() {
        let mut store = InMemoryStore::new();
        // Create Parent
        create::run(&mut store, Scope::Project, "Parent".into(), "".into(), None).unwrap();
        // Create Child inside Parent (id=1)
        create::run(
            &mut store,
            Scope::Project,
            "Child".into(),
            "".into(),
            Some(PadSelector::Path(vec![DisplayIndex::Regular(1)])),
        )
        .unwrap();

        // Delete Parent
        delete::run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        )
        .unwrap();

        // Purge Parent WITH recursive flag and confirmed
        let res = run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Deleted(1)])],
            true, // recursive = true
            true, // confirmed = true
        )
        .unwrap();

        assert!(res.messages.iter().any(|m| m.content.contains("Purging 2"))); // parent + child
        assert!(res
            .messages
            .iter()
            .any(|m| m.content.contains("Purged: d1 Parent")));
        assert!(res
            .messages
            .iter()
            .any(|m| m.content.contains("And purged 1 descendant")));

        // Verify Store is empty
        let all_pads = store.list_pads(Scope::Project).unwrap();
        assert_eq!(all_pads.len(), 0);
    }

    #[test]
    fn purge_without_recursive_fails_when_has_children() {
        let mut store = InMemoryStore::new();
        // Create Parent
        create::run(&mut store, Scope::Project, "Parent".into(), "".into(), None).unwrap();
        // Create Child inside Parent
        create::run(
            &mut store,
            Scope::Project,
            "Child".into(),
            "".into(),
            Some(PadSelector::Path(vec![DisplayIndex::Regular(1)])),
        )
        .unwrap();

        // Try to purge Parent WITHOUT recursive flag - should fail
        let result = run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
            false, // recursive = false
            true,  // confirmed = true
        );

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("have children"));
        assert!(err.to_string().contains("--recursive"));

        // Verify nothing was deleted
        let all_pads = store.list_pads(Scope::Project).unwrap();
        assert_eq!(all_pads.len(), 2);
    }

    #[test]
    fn purge_selectors_vs_all() {
        let mut store = InMemoryStore::new();
        create::run(&mut store, Scope::Project, "A".into(), "".into(), None).unwrap();
        create::run(&mut store, Scope::Project, "B".into(), "".into(), None).unwrap();

        // Delete both to make them purgeable candidates
        delete::run(
            &mut store,
            Scope::Project,
            &[
                PadSelector::Path(vec![DisplayIndex::Regular(1)]),
                PadSelector::Path(vec![DisplayIndex::Regular(2)]),
            ],
        )
        .unwrap();

        // Purge only one (selectors provided)
        let res = run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Deleted(1)])],
            false, // recursive
            true,  // confirmed
        )
        .unwrap();

        assert!(res.messages.iter().any(|m| m.content.contains("Purging 1")));

        let remaining = store.list_pads(Scope::Project).unwrap();
        assert_eq!(remaining.len(), 1); // One remains
        assert!(remaining[0].metadata.is_deleted);
    }

    #[test]
    fn purge_nothing_found() {
        let mut store = InMemoryStore::new();
        // Empty store - even with confirmed=true
        let res = run(&mut store, Scope::Project, &[], false, true).unwrap();
        assert!(res.messages[0].content.contains("No pads to purge"));
    }

    #[test]
    fn purge_error_includes_count() {
        let mut store = InMemoryStore::new();
        create::run(&mut store, Scope::Project, "A".into(), "".into(), None).unwrap();
        create::run(&mut store, Scope::Project, "B".into(), "".into(), None).unwrap();

        // Delete both
        delete::run(
            &mut store,
            Scope::Project,
            &[
                PadSelector::Path(vec![DisplayIndex::Regular(1)]),
                PadSelector::Path(vec![DisplayIndex::Regular(2)]),
            ],
        )
        .unwrap();

        // Purge without confirmation - error should show count
        let result = run(&mut store, Scope::Project, &[], false, false);

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Purging 2 pad(s)"));
    }
}