typ2anki 1.0.13

Compile Typst flashcards into Anki decks
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
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::tempdir_in;

use clap::parser::ValueSource;
use clap::{ArgAction, CommandFactory, FromArgMatches, Parser};
use glob::Pattern;
use once_cell::sync::OnceCell;
use serde_json::{Value, json};
use toml::Value as TomlValue;

use html_escape::encode_double_quoted_attribute;

use crate::card_wrapper::CardInfo;
use crate::utils;
use std::sync::{Arc, RwLock};

pub const DEFAULT_CONFIG_FILENAME: &str = "typ2anki.toml";

#[derive(Parser, Debug)]
#[command(about = "Typ2Anki config parser", version)]
struct Cli {
    /// Specify the path to the config file. Set to empty string to disable config file.
    #[arg(long = "config-file", default_value = DEFAULT_CONFIG_FILENAME)]
    config_file: String,

    /// Enable duplicate checking
    #[arg(long = "check-duplicates")]
    check_duplicates: bool,

    /// Specify decks to exclude. Use multiple -e options. Glob patterns supported.
    #[arg(short = 'e', long = "exclude-decks", action = clap::ArgAction::Append)]
    exclude_decks: Vec<String>,

    /// Specify files to exclude. Use multiple --exclude-files options. Glob patterns supported.
    #[arg(long = "exclude-files", action = clap::ArgAction::Append)]
    exclude_files: Vec<String>,

    /// Specify how many cards at a time can be generated. Needs duplicate checking enabled.
    #[arg(long = "generation-concurrency", default_value = "")]
    generation_concurrency: String,

    /// Max card width, 'auto' or a value
    #[arg(long = "max-card-width", default_value = "auto")]
    max_card_width: String,

    /// Force reupload of all images
    #[arg(long = "no-cache")]
    no_cache: bool,

    /// Whether to recompile cards if the config has changed. Accepts 'y' or 'n', or '_' to ask.
    #[arg(long = "recompile-on-config-change", default_value = "_")]
    recompile_on_config_change: String,

    /// Run without making changes
    #[arg(long = "dry-run")]
    dry_run: bool,

    /// Hidden: print config
    #[arg(long = "print-config", hide = true)]
    print_config: bool,

    /// Hidden: print config
    #[arg(long = "auto-number", hide = true)]
    auto_number: Option<String>,

    /// Path to Typst documents folder or zip (positional, allow spaces)
    #[arg(value_parser, num_args = 0..)]
    path: Option<Vec<String>>,

    #[arg(short = 'i', hide = true,action = ArgAction::SetTrue)]
    keep_terminal_open: bool,
}

fn load_toml_config(path: &Path) -> Option<TomlValue> {
    if !path.exists() {
        return None;
    }
    match fs::read_to_string(path) {
        Ok(s) => match s.parse::<TomlValue>() {
            Ok(v) => Some(v),
            Err(e) => panic!("Error parsing TOML {}: {}", path.display(), e),
        },
        Err(e) => panic!("Error reading config file {}: {}", path.display(), e),
    }
}

fn get_real_path_simple(p: &str) -> String {
    match fs::canonicalize(p) {
        Ok(p) => p.to_string_lossy().to_string(),
        Err(_) => p.to_string(),
    }
}

#[derive(Debug, Clone)]
pub struct Config {
    // User controlled options
    pub check_duplicates: bool,
    pub exclude_decks: Vec<Pattern>,
    pub exclude_decks_string: Vec<String>,
    pub exclude_files: Vec<Pattern>,
    pub asked_path: String,
    pub path: PathBuf,
    pub recompile_on_config_change: Arc<RwLock<Option<bool>>>,

    // Processed options / defaults
    pub dry_run: bool,
    pub max_card_width: String,
    pub skip_cache: bool,
    pub generation_concurrency: usize,
    pub keep_terminal_open: bool,

    // Internal options
    pub is_zip: bool,
    pub config_hash: Option<String>,
    pub output_type: String,
    pub typst_input: Vec<(String, String)>,
    pub auto_number_file: Option<String>,
}

impl Config {
    pub fn is_deck_excluded(&self, deck_name: &str) -> bool {
        self.exclude_decks.iter().any(|p| p.matches(deck_name))
    }

    pub fn is_file_excluded(&self, file_name: &str) -> bool {
        self.exclude_files.iter().any(|p| p.matches(file_name))
    }

    pub fn template_front(&self, _card_info: &CardInfo, front_image_path: &str) -> String {
        format!(
            r#"<img src="{}">"#,
            encode_double_quoted_attribute(front_image_path)
        )
    }

    pub fn template_back(&self, _card_info: &CardInfo, back_image_path: &str) -> String {
        format!(
            r#"<img src="{}">"#,
            encode_double_quoted_attribute(back_image_path)
        )
    }

    pub fn destruct(&self) {
        // Be careful not to panic in this function, as it is called during unwinding.
        if self.dry_run {
            println!("Destroying config (dry run)");
        }
        if self.is_zip
            && self.asked_path != self.path.to_string_lossy()
            && let Err(e) = fs::remove_dir_all(&self.path)
        {
            eprintln!(
                "Warning: Failed to remove temporary extracted zip directory {}: {}",
                self.path.display(),
                e
            );
        }
    }

    pub fn compute_hash(&mut self) {
        let relevant_config = json!({
            "output_type": self.output_type,
            "max_card_width": self.max_card_width,
            "exclude_decks": self.exclude_decks_string.clone().sort(),
        });
        let relevant_config = utils::json_sorted_keys(&relevant_config);
        let s = serde_json::to_string(&relevant_config).unwrap();
        self.config_hash = Some(utils::hash_string(&s));
    }

    pub fn path_relative_to_root(&self, p: &PathBuf) -> String {
        pathdiff::diff_paths(p, &self.path)
            .unwrap_or(p.clone())
            .to_string_lossy()
            .into_owned()
    }
}

// RAII guard to ensure Config::destruct() is called when run() exits or unwinds.
// We call destruct() inside catch_unwind to avoid panics during unwinding.
pub struct ConfigGuard;

impl Drop for ConfigGuard {
    fn drop(&mut self) {
        let _ = std::panic::catch_unwind(|| {
            let cfg = get();
            cfg.destruct();
        });
    }
}

fn parse_generation_concurrency(s: &str) -> usize {
    if s.is_empty() {
        1
    } else if s == "max" {
        num_cpus::get()
    } else {
        s.parse::<usize>().unwrap_or(1).max(1)
    }
}

pub fn parse_config() -> Config {
    let matches = Cli::command().get_matches();
    let cli = Cli::from_arg_matches(&matches).unwrap();

    let asked_path = match cli.path {
        Some(p) => {
            if p.is_empty() {
                ".".to_string()
            } else {
                p.join(" ")
            }
        }
        None => ".".to_string(),
    };

    let mut check_duplicates = cli.check_duplicates;
    let mut exclude_decks = cli.exclude_decks.clone();
    let mut exclude_files = cli.exclude_files.clone();
    let mut dry_run = cli.dry_run;
    let mut max_card_width = cli.max_card_width.clone();
    let mut skip_cache = cli.no_cache;
    let mut generation_concurrency = parse_generation_concurrency(&cli.generation_concurrency);
    let mut recompile_on_config_change = cli.recompile_on_config_change.clone();

    #[derive(Debug)]
    enum ConfigSource {
        Cli,
        File,
        Default,
    }

    let mut source_map: HashMap<&str, ConfigSource> = HashMap::new();
    let c = &Cli::command();
    c.get_arguments().for_each(|arg| {
        let name = arg.get_id().as_str();
        match matches.value_source(name) {
            Some(ValueSource::CommandLine) | Some(ValueSource::EnvVariable) => {
                source_map.insert(name, ConfigSource::Cli);
            }
            Some(ValueSource::DefaultValue) => {
                source_map.insert(name, ConfigSource::Default);
            }
            None => {
                // This branch seems to match for exclude_files and exclude_decks when not provided.
                source_map.insert(name, ConfigSource::Default);
            }
            _ => {
                eprintln!("Unknown value source for arg {}", name);
            }
        }
    });

    let mut path = get_real_path_simple(&asked_path);
    let is_zip = path.to_lowercase().ends_with(".zip");

    if is_zip {
        let dir = utils::get_typ2anki_tmp();
        let dir = tempdir_in(dir)
            .expect("Failed to create temporary directory for zip extraction")
            .path()
            .to_path_buf();
        utils::unzip_file_to_dir(Path::new(&path), &dir).expect("Failed to extract zip file");
        path = dir.to_string_lossy().to_string();
    }

    if !cli.config_file.is_empty() {
        let config_file_path = Path::new(&path).join(&cli.config_file);
        if let Some(table) = load_toml_config(&config_file_path) {
            if let Some(&ConfigSource::Default) = source_map.get("check_duplicates")
                && let Some(v) = table.get("check_duplicates")
                && let Some(b) = v.as_bool()
            {
                check_duplicates = b;
                source_map.insert("check_duplicates", ConfigSource::File);
            }

            if let Some(&ConfigSource::Default) = source_map.get("exclude_decks")
                && let Some(v) = table.get("exclude_decks").and_then(|x| x.as_array())
            {
                exclude_decks = v
                    .iter()
                    .filter_map(|e| e.as_str().map(|s| s.to_string()))
                    .collect();
                source_map.insert("exclude_decks", ConfigSource::File);
            }
            if let Some(&ConfigSource::Default) = source_map.get("exclude_files")
                && let Some(v) = table.get("exclude_files").and_then(|x| x.as_array())
            {
                exclude_files = v
                    .iter()
                    .filter_map(|e| e.as_str().map(|s| s.to_string()))
                    .collect();
                source_map.insert("exclude_files", ConfigSource::File);
            }

            if let Some(&ConfigSource::Default) = source_map.get("dry_run")
                && let Some(v) = table.get("dry_run").and_then(|x| x.as_bool())
            {
                dry_run = v;
                source_map.insert("dry_run", ConfigSource::File);
            }

            if let Some(&ConfigSource::Default) = source_map.get("max_card_width")
                && let Some(v) = table.get("max_card_width").and_then(|x| x.as_str())
            {
                max_card_width = v.to_string();
                source_map.insert("max_card_width", ConfigSource::File);
            }

            if let Some(&ConfigSource::Default) = source_map.get("no_cache")
                && let Some(v) = table.get("check_checksums").and_then(|x| x.as_bool())
            {
                skip_cache = v;
                source_map.insert("no_cache", ConfigSource::File);
            }
            if let Some(&ConfigSource::Default) = source_map.get("generation_concurrency")
                && let Some(v) = table.get("generation_concurrency").map(|x| {
                    parse_generation_concurrency(
                        x.as_str()
                            .unwrap_or(x.as_integer().unwrap_or(1).to_string().as_str()),
                    )
                })
            {
                generation_concurrency = v;
                source_map.insert("generation_concurrency", ConfigSource::File);
            }

            if let Some(&ConfigSource::Default) = source_map.get("recompile_on_config_change")
                && let Some(v) = table
                    .get("recompile_on_config_change")
                    .and_then(|x| x.as_str())
            {
                recompile_on_config_change = v.to_string();
                source_map.insert("recompile_on_config_change", ConfigSource::File);
            }
        }
    }
    // println!("Config sources: {:#?}", source_map);

    let mut typst_input: Vec<(String, String)> = Vec::new();
    typst_input.push(("typ2anki_compile".to_string(), "1".to_string()));

    if max_card_width != "auto" {
        typst_input.push(("max_card_width".to_string(), max_card_width.clone()));
    }

    if !check_duplicates && generation_concurrency > 1 {
        eprintln!(
            "WARNING: Concurrent generation can't be enabled without duplicate checking. Disabling concurrent generation."
        );
        generation_concurrency = 1;
    } else if generation_concurrency > num_cpus::get() {
        eprintln!(
            "WARNING: Requested generation concurrency ({}) exceeds number of CPU cores ({}). It is inefficient. Reducing to {}. You can set generation-concurrency to 'max' so that it always takes the amount of logical threads on a given machine.",
            generation_concurrency,
            num_cpus::get(),
            num_cpus::get()
        );
        generation_concurrency = num_cpus::get();
    }

    if cli.print_config {
        let c = Cli::command();
        let mut options: Vec<serde_json::Value> = Vec::new();
        let hidden_args: Vec<String> = [
            "config_file",
            "path",
            "print_config",
            "version",
            "keep_terminal_open",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        c.get_arguments().for_each(|arg| {
            let id = arg.get_id().as_str();
            if hidden_args.iter().any(|s| s == id) {
                return;
            }
            let source = match source_map.get(id).unwrap() {
                ConfigSource::Default => 0,
                ConfigSource::Cli => 1,
                ConfigSource::File => 2,
            };
            let cli_name = format!(
                "--{}",
                arg.get_long()
                    .map(|s| s.to_string())
                    .or(arg.get_short().map(|c| c.to_string()))
                    .unwrap()
            );
            let help = arg.get_help().unwrap().to_string();
            let value: Value = match id {
                "check_duplicates" => json!(check_duplicates),
                "exclude_decks" => json!(exclude_decks),
                "exclude_files" => json!(exclude_files),
                "dry_run" => json!(dry_run),
                "max_card_width" => json!(max_card_width),
                "no_cache" => json!(skip_cache),
                "generation_concurrency" => json!(generation_concurrency),
                "recompile_on_config_change" => json!(recompile_on_config_change),
                _ => json!(null),
            };
            let t = match arg.get_action() {
                ArgAction::SetTrue => "store_true".to_string(),
                ArgAction::Append => "append".to_string(),
                ArgAction::Set => "str".to_string(),
                other => format!("{:?}", other),
            };
            options.push(json!({
                "id": id,
                "source": source,
                "cli_name": cli_name,
                "help": help,
                "type": t,
                "value":value,
            }))
        });
        let output = json!({ "options": options });
        println!("{}", serde_json::to_string_pretty(&output).unwrap());
        std::process::exit(0);
    }

    let mut cfg = Config {
        check_duplicates,
        exclude_decks: exclude_decks
            .iter()
            .map(|s| Pattern::new(s).unwrap_or_default())
            .collect(),
        exclude_files: exclude_files
            .iter()
            .map(|s| Pattern::new(s).unwrap_or_default())
            .collect(),
        exclude_decks_string: exclude_decks,
        asked_path: asked_path.clone(),
        path: PathBuf::from(path),
        recompile_on_config_change: Arc::new(
            match recompile_on_config_change.to_ascii_lowercase().as_str() {
                "y" | "yes" => Some(true),
                "n" | "no" => Some(false),
                "_" => None,
                _ => None,
            }
            .into(),
        ),
        dry_run,
        max_card_width,
        skip_cache,
        generation_concurrency,
        is_zip,
        config_hash: None,
        output_type: "png".to_string(),
        typst_input,
        keep_terminal_open: cli.keep_terminal_open,
        auto_number_file: cli.auto_number.clone(),
    };
    cfg.compute_hash();

    cfg
}

static CACHED_CONFIG: OnceCell<Config> = OnceCell::new();

pub fn get() -> &'static Config {
    CACHED_CONFIG.get_or_init(parse_config)
}