readstor 0.6.0

A CLI for Apple Books annotations
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
pub mod app;
pub mod config;
pub mod data;
pub mod defaults;
pub mod utils;

use std::path::PathBuf;
use std::result::Result;
use std::str::FromStr;

use clap::builder::styling::AnsiColor;
use clap::builder::Styles;
use clap::{Parser, Subcommand};
use once_cell::sync::Lazy;
use regex::Regex;

static RE_FILTER_QUERY: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^(?P<operator>[?*=]?)(?P<field>\w*):(?P<query>.*)$").unwrap()
    //            └───┬──────────────┘└───────────┬┘ └───┬───────┘
    //                │                           │      │
    // operator ──────┘                           │      │
    //   Captures a single char representing the  │      │
    //   filter operator. Can be one of:          │      │
    //     - "?" -> any                           │      │
    //     - "*" -> all                           │      │
    //     - "=" -> exact                         │      │
    //                                            │      │
    // field ─────────────────────────────────────┘      │
    //   The field used to run filtering.                │
    //    // query ────────────────────────────────────────────┘
    //   The query string.
});

#[derive(Debug, Parser)]
#[command(
    author,
    version,
    about,
    after_help = "See the documentation for more information: https://tnahs.github.io/readstor",
    styles = cli_styles(),
)]
pub struct Cli {
    #[clap(flatten)]
    pub options: Options,

    #[clap(subcommand)]
    pub command: Command,
}

#[derive(Debug, Clone, Parser)]
pub struct Options {
    /// Set the output directory [default: ~/.readstor]
    #[arg(
        short = 'o',
        long,
        global = true,
        value_name = "PATH",
        value_parser(validate_path_exists),
        help_heading = "Global"
    )]
    pub output_directory: Option<PathBuf>,

    /// Set the directory containing macOS's Apple Books databases
    #[arg(
        short = 'd',
        long,
        global = true,
        value_name = "PATH",
        value_parser(validate_path_exists),
        help_heading = "Global"
    )]
    pub databases_directory: Option<PathBuf>,

    /// Set the directory containing iOS's Apple Books plists
    #[arg(
        short = 'p',
        long,
        global = true,
        value_name = "PATH",
        value_parser(validate_path_exists),
        help_heading = "Global"
    )]
    pub plists_directory: Option<PathBuf>,

    /// Run command even if Apple Books is currently running
    #[arg(short = 'F', long, global = true, help_heading = "Global")]
    pub force: bool,

    /// Silence output messages
    #[arg(short = 'q', long = "quiet", global = true, help_heading = "Global")]
    pub is_quiet: bool,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Render books/annotation via templates
    Render {
        #[clap(flatten)]
        filter_options: FilterOptions,

        #[clap(flatten)]
        template_options: RenderOptions,

        #[clap(flatten)]
        preprocess_options: PreProcessOptions,

        #[clap(flatten)]
        postprocess_options: PostProcessOptions,
    },

    /// Export data as JSON
    Export {
        #[clap(flatten)]
        filter_options: FilterOptions,

        #[clap(flatten)]
        export_options: ExportOptions,

        #[clap(flatten)]
        preprocess_options: PreProcessOptions,
    },

    /// Back-up macOS's Apple Books databases
    Backup {
        #[clap(flatten)]
        backup_options: BackupOptions,
    },
}

#[derive(Debug, Clone, Default, Parser)]
pub struct RenderOptions {
    /// Set a custom templates directory
    #[arg(
        short = 't',
        long,
        value_name = "PATH",
        value_parser(validate_path_exists)
    )]
    pub templates_directory: Option<PathBuf>,

    /// Render specified template-group(s)
    #[arg(short = 'g', long = "template-group", value_name = "GROUP")]
    pub template_groups: Vec<String>,

    /// Overwrite existing files
    #[arg(short = 'O', long)]
    pub overwrite_existing: bool,
}

#[derive(Debug, Clone, Default, Parser)]
pub struct ExportOptions {
    /// Set the output directory template
    #[arg(short = 't', long, value_name = "TEMPLATE")]
    pub directory_template: Option<String>,

    /// Overwrite existing files
    #[arg(short = 'O', long)]
    pub overwrite_existing: bool,
}

#[derive(Debug, Clone, Default, Parser)]
pub struct BackupOptions {
    /// Set the output directory template
    #[arg(short = 't', long, value_name = "TEMPLATE")]
    pub directory_template: Option<String>,
}

#[derive(Debug, Clone, Default, Parser)]
pub struct FilterOptions {
    /// Filter books/annotations before outputting
    #[arg(
        short = 'f',
        long = "filter",
        value_name = "[OP]{FIELD}:{QUERY}",
        help_heading = "Filter"
    )]
    filter_types: Vec<FilterType>,

    /// Auto-confirm filter results
    #[arg(
        short = 'A',
        long = "auto-confirm-filter",
        requires = "filter_types",
        help_heading = "Filter"
    )]
    auto_confirm: bool,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum FilterType {
    /// Filter books by their title
    Title {
        query: Vec<String>,
        operator: FilterOperator,
    },

    /// Filter books by their author
    Author {
        query: Vec<String>,
        operator: FilterOperator,
    },

    /// Filter annotations by their #tags
    Tags {
        query: Vec<String>,
        operator: FilterOperator,
    },
}

#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub enum FilterOperator {
    /// Match any of the query strings
    #[default]
    Any,

    /// Match all of the query strings
    All,

    /// Match the exact query string
    Exact,
}

#[derive(Debug, Clone, Copy, Default, Parser)]
#[allow(clippy::struct_excessive_bools)]
pub struct PreProcessOptions {
    /// Extract #tags from annotation notes
    #[arg(short = 'e', long, help_heading = "Pre-process")]
    pub extract_tags: bool,

    /// Normalize whitespace in annotation body
    #[arg(short = 'n', long, help_heading = "Pre-process")]
    pub normalize_whitespace: bool,

    /// Convert all Unicode characters to ASCII
    #[arg(
        short = 'a',
        long = "ascii-all",
        conflicts_with = "convert_symbols_to_ascii",
        help_heading = "Pre-process"
    )]
    pub convert_all_to_ascii: bool,

    /// Convert "smart" Unicode symbols to ASCII
    #[arg(
        short = 's',
        long = "ascii-symbols",
        conflicts_with = "convert_all_to_ascii",
        help_heading = "Pre-process"
    )]
    pub convert_symbols_to_ascii: bool,
}

#[derive(Debug, Clone, Copy, Default, Parser)]
pub struct PostProcessOptions {
    /// Trim any blocks left after rendering
    #[arg(short = 'b', long, help_heading = "Post-process")]
    pub trim_blocks: bool,

    /// Wrap text to a maximum character width
    #[arg(short = 'w', long, value_name = "WIDTH", help_heading = "Post-process")]
    pub wrap_text: Option<usize>,
}

fn cli_styles() -> Styles {
    Styles::styled()
        .usage(AnsiColor::Green.on_default())
        .header(AnsiColor::Green.on_default())
        .literal(AnsiColor::Cyan.on_default())
        .placeholder(AnsiColor::Yellow.on_default())
}

pub fn validate_path_exists(value: &str) -> Result<PathBuf, String> {
    std::fs::canonicalize(value).map_err(|_| "path does not exist".into())
}

impl From<RenderOptions> for lib::render::renderer::RenderOptions {
    fn from(options: RenderOptions) -> Self {
        Self {
            templates_directory: options.templates_directory,
            template_groups: options.template_groups,
            overwrite_existing: options.overwrite_existing,
        }
    }
}

impl From<ExportOptions> for lib::export::ExportOptions {
    fn from(options: ExportOptions) -> Self {
        Self {
            directory_template: options.directory_template,
            overwrite_existing: options.overwrite_existing,
        }
    }
}

impl From<BackupOptions> for lib::backup::BackupOptions {
    fn from(options: BackupOptions) -> Self {
        Self {
            directory_template: options.directory_template,
        }
    }
}

impl From<FilterOperator> for lib::filter::FilterOperator {
    fn from(filter_operator: FilterOperator) -> Self {
        match filter_operator {
            FilterOperator::Any => Self::Any,
            FilterOperator::All => Self::All,
            FilterOperator::Exact => Self::Exact,
        }
    }
}

impl From<FilterType> for lib::filter::FilterType {
    fn from(filter_type: FilterType) -> Self {
        match filter_type {
            FilterType::Title { query, operator } => Self::Title {
                query,
                operator: operator.into(),
            },
            FilterType::Author { query, operator } => Self::Author {
                query,
                operator: operator.into(),
            },
            FilterType::Tags { query, operator } => Self::Tags {
                query,
                operator: operator.into(),
            },
        }
    }
}

impl From<PreProcessOptions> for lib::process::pre::PreProcessOptions {
    fn from(options: PreProcessOptions) -> Self {
        Self {
            extract_tags: options.extract_tags,
            normalize_whitespace: options.normalize_whitespace,
            convert_all_to_ascii: options.convert_all_to_ascii,
            convert_symbols_to_ascii: options.convert_symbols_to_ascii,
        }
    }
}

impl From<PostProcessOptions> for lib::process::post::PostProcessOptions {
    fn from(options: PostProcessOptions) -> Self {
        Self {
            trim_blocks: options.trim_blocks,
            wrap_text: options.wrap_text,
        }
    }
}

impl FromStr for FilterType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let captures = RE_FILTER_QUERY.captures(s);

        let Some(captures) = captures else {
            return Err("filters must follow the format '[op]{field}:{query}'".into());
        };

        // These unwraps are safe as they will only panic if the capture-group name does not exist.
        // These are all defined above.
        let operator = captures.name("operator").unwrap().as_str();
        let field = captures.name("field").unwrap().as_str().to_lowercase();
        let query = captures.name("query").unwrap();

        let operator = if operator.is_empty() {
            FilterOperator::default()
        } else {
            operator.parse()?
        };

        let query = query
            .as_str()
            .split(' ')
            .map(std::string::ToString::to_string)
            .collect();

        let filter_by = match field.as_str() {
            "title" => Self::Title { query, operator },
            "author" => Self::Author { query, operator },
            "tags" | "tag" => Self::Tags { query, operator },
            _ => return Err(format!("invalid field: '{field}'")),
        };

        Ok(filter_by)
    }
}

impl FromStr for FilterOperator {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let filter_type = match s {
            "?" => Self::Any,
            "*" => Self::All,
            "=" => Self::Exact,
            _ => return Err(format!("invalid operator: '{s}'")),
        };

        Ok(filter_type)
    }
}

#[cfg(test)]
mod test {

    use super::*;

    // Tests that strings are properly converted into `FilterType`s.
    mod parse_filter {

        use super::*;

        #[test]
        fn title_any() {
            assert_eq!(
                FilterType::from_str("?title:art think").unwrap(),
                FilterType::Title {
                    query: vec!["art".to_string(), "think".to_string()],
                    operator: FilterOperator::Any,
                }
            );
        }

        #[test]
        fn title_all() {
            assert_eq!(
                FilterType::from_str("*title:joking feynman").unwrap(),
                FilterType::Title {
                    query: vec!["joking".to_string(), "feynman".to_string()],
                    operator: FilterOperator::All,
                }
            );
        }

        #[test]
        fn title_exact() {
            assert_eq!(
                FilterType::from_str("=title:the art spirit").unwrap(),
                FilterType::Title {
                    query: vec!["the".to_string(), "art".to_string(), "spirit".to_string()],
                    operator: FilterOperator::Exact,
                }
            );
        }

        #[test]
        fn author_any() {
            assert_eq!(
                FilterType::from_str("?author:robert richard").unwrap(),
                FilterType::Author {
                    query: vec!["robert".to_string(), "richard".to_string()],
                    operator: FilterOperator::Any,
                }
            );
        }

        #[test]
        fn author_all() {
            assert_eq!(
                FilterType::from_str("*author:richard feynman").unwrap(),
                FilterType::Author {
                    query: vec!["richard".to_string(), "feynman".to_string()],
                    operator: FilterOperator::All,
                }
            );
        }

        #[test]
        fn author_exact() {
            assert_eq!(
                FilterType::from_str("=author:richard p. feynman").unwrap(),
                FilterType::Author {
                    query: vec![
                        "richard".to_string(),
                        "p.".to_string(),
                        "feynman".to_string(),
                    ],
                    operator: FilterOperator::Exact,
                }
            );
        }

        #[test]
        fn tags_any() {
            assert_eq!(
                FilterType::from_str("?tags:#artist #death").unwrap(),
                FilterType::Tags {
                    query: vec!["#artist".to_string(), "#death".to_string()],
                    operator: FilterOperator::Any,
                }
            );
        }

        #[test]
        fn tags_all() {
            assert_eq!(
                FilterType::from_str("*tags:#death #impermanence").unwrap(),
                FilterType::Tags {
                    query: vec!["#death".to_string(), "#impermanence".to_string()],
                    operator: FilterOperator::All,
                }
            );
        }

        #[test]
        fn tags_exact() {
            assert_eq!(
                FilterType::from_str("=tags:#artist #being").unwrap(),
                FilterType::Tags {
                    query: vec!["#artist".to_string(), "#being".to_string()],
                    operator: FilterOperator::Exact,
                }
            );
        }
    }
}