typst-count 0.1.0

Count words and characters in Typst documents
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
//! A library for counting words and characters in Typst documents.
//!
//! This crate provides functionality to compile Typst documents and count the
//! words and characters in the rendered output. It works by:
//!
//! 1. Compiling Typst documents using the Typst compiler
//! 2. Traversing the compiled document's element tree
//! 3. Extracting plain text from rendered elements
//! 4. Counting words (by whitespace) and characters
//!
//! # Features
//!
//! - Count words and characters from compiled Typst documents
//! - Handle imported and included files
//! - Multiple output formats (human-readable, JSON, CSV)
//! - CI/CD integration with limit checking
//!
//! # Examples
//!
//! ```no_run
//! use typst_count::compile_document;
//! use std::path::Path;
//!
//! let path = Path::new("document.typ");
//! let count = compile_document(path, false).unwrap();
//! println!("Words: {}, Characters: {}", count.words, count.characters);
//! ```
pub mod cli;
pub mod counter;
pub mod output;
pub mod world;

use anyhow::{Context, Result};
use cli::Cli;
use counter::Count;
use std::path::Path;
use typst::{World, layout::PagedDocument};

/// Compiles a Typst document and counts its words and characters.
///
/// This function loads a Typst document, compiles it using the Typst compiler,
/// and extracts word and character counts from the rendered output.
///
/// # Arguments
///
/// * `path` - Path to the Typst document file
/// * `exclude_imports` - If `true`, only counts content from the main file,
///   excluding imported/included files
///
/// # Returns
///
/// A `Count` struct containing word and character counts, or an error if
/// compilation fails.
///
/// # Errors
///
/// Returns an error if:
/// - The file cannot be read
/// - The document fails to compile
/// - There are syntax errors in the Typst code
///
/// # Examples
///
/// ```no_run
/// use typst_count::compile_document;
/// use std::path::Path;
///
/// // Count all content including imports
/// let count = compile_document(Path::new("document.typ"), false)?;
///
/// // Count only the main file
/// let count = compile_document(Path::new("document.typ"), true)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn compile_document(path: &Path, exclude_imports: bool) -> Result<Count> {
    let world = world::SimpleWorld::new(path)
        .with_context(|| format!("Failed to load {}", path.display()))?;
    let main_file_id = world.main();

    let result = typst::compile(&world);
    let document: PagedDocument = result.output.map_err(|errors| {
        let error_msg = errors
            .iter()
            .map(|e| format!("{}", e.message))
            .collect::<Vec<_>>()
            .join(", ");
        anyhow::anyhow!("Failed to compile {}: {}", path.display(), error_msg)
    })?;

    Ok(counter::count_document(
        &document.introspector,
        exclude_imports,
        main_file_id,
    ))
}

/// Processes multiple Typst files and returns their counts.
///
/// Compiles each input file specified in the CLI arguments and collects
/// the word and character counts for each file.
///
/// # Arguments
///
/// * `args` - Command-line arguments containing input files and options
///
/// # Returns
///
/// A vector of tuples, each containing a file path (as a string) and its
/// corresponding `Count`, or an error if any file fails to compile.
///
/// # Errors
///
/// Returns an error if any of the input files:
/// - Cannot be read
/// - Fails to compile
/// - Contains syntax errors
///
/// # Examples
///
/// ```no_run
/// use typst_count::{process_files, cli::Cli};
/// use clap::Parser;
///
/// let args = Cli::parse();
/// let results = process_files(&args)?;
///
/// for (path, count) in results {
///     println!("{}: {} words", path, count.words);
/// }
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn process_files(args: &Cli) -> Result<Vec<(String, Count)>> {
    args.input
        .iter()
        .map(|path| {
            compile_document(path, args.exclude_imports)
                .map(|count| (path.display().to_string(), count))
        })
        .collect()
}

/// Checks if word and character counts are within specified limits.
///
/// Validates that the total counts meet any minimum or maximum limits
/// specified in the CLI arguments. This is useful for CI/CD pipelines
/// to enforce document length requirements.
///
/// # Arguments
///
/// * `args` - Command-line arguments containing limit specifications
/// * `total` - The total count to check against limits
///
/// # Returns
///
/// - `Ok(())` if all limits are satisfied
/// - `Err(Vec<String>)` containing error messages for each violated limit
///
/// # Limit Checks
///
/// The following limits are checked if specified:
/// - `max_words` - Maximum allowed word count
/// - `min_words` - Minimum required word count
/// - `max_characters` - Maximum allowed character count
/// - `min_characters` - Minimum required character count
///
/// # Examples
///
/// ```no_run
/// use typst_count::{check_limits, cli::Cli, counter::Count};
/// use clap::Parser;
///
/// let args = Cli::parse();
/// let total = Count { words: 500, characters: 2500 };
///
/// match check_limits(&args, &total) {
///     Ok(()) => println!("All limits satisfied"),
///     Err(errors) => {
///         for error in errors {
///             eprintln!("Limit violation: {}", error);
///         }
///     }
/// }
/// ```
pub fn check_limits(args: &Cli, total: &Count) -> Result<(), Vec<String>> {
    let mut errors = Vec::new();

    if let Some(max) = args.max_words
        && total.words > max
    {
        errors.push(format!(
            "Word count exceeds maximum ({} > {})",
            total.words, max
        ));
    }

    if let Some(min) = args.min_words
        && total.words < min
    {
        errors.push(format!(
            "Word count below minimum ({} < {})",
            total.words, min
        ));
    }

    if let Some(max) = args.max_characters
        && total.characters > max
    {
        errors.push(format!(
            "Character count exceeds maximum ({} > {})",
            total.characters, max
        ));
    }

    if let Some(min) = args.min_characters
        && total.characters < min
    {
        errors.push(format!(
            "Character count below minimum ({} < {})",
            total.characters, min
        ));
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{Cli, CountMode, DisplayMode, OutputFormat};

    fn make_test_cli() -> Cli {
        Cli {
            input: vec![],
            format: OutputFormat::Human,
            mode: CountMode::Both,
            output: None,
            display: DisplayMode::Auto,
            exclude_imports: false,
            max_words: None,
            min_words: None,
            max_characters: None,
            min_characters: None,
        }
    }

    #[test]
    fn test_check_limits_no_limits() {
        let args = make_test_cli();
        let count = Count {
            words: 100,
            characters: 500,
        };

        assert!(check_limits(&args, &count).is_ok());
    }

    #[test]
    fn test_check_limits_max_words_ok() {
        let mut args = make_test_cli();
        args.max_words = Some(200);
        let count = Count {
            words: 100,
            characters: 500,
        };

        assert!(check_limits(&args, &count).is_ok());
    }

    #[test]
    fn test_check_limits_max_words_exceeded() {
        let mut args = make_test_cli();
        args.max_words = Some(50);
        let count = Count {
            words: 100,
            characters: 500,
        };

        let result = check_limits(&args, &count);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("exceeds maximum"));
        assert!(errors[0].contains("100 > 50"));
    }

    #[test]
    fn test_check_limits_min_words_ok() {
        let mut args = make_test_cli();
        args.min_words = Some(50);
        let count = Count {
            words: 100,
            characters: 500,
        };

        assert!(check_limits(&args, &count).is_ok());
    }

    #[test]
    fn test_check_limits_min_words_below() {
        let mut args = make_test_cli();
        args.min_words = Some(200);
        let count = Count {
            words: 100,
            characters: 500,
        };

        let result = check_limits(&args, &count);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("below minimum"));
        assert!(errors[0].contains("100 < 200"));
    }

    #[test]
    fn test_check_limits_max_characters_ok() {
        let mut args = make_test_cli();
        args.max_characters = Some(1000);
        let count = Count {
            words: 100,
            characters: 500,
        };

        assert!(check_limits(&args, &count).is_ok());
    }

    #[test]
    fn test_check_limits_max_characters_exceeded() {
        let mut args = make_test_cli();
        args.max_characters = Some(300);
        let count = Count {
            words: 100,
            characters: 500,
        };

        let result = check_limits(&args, &count);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("exceeds maximum"));
        assert!(errors[0].contains("500 > 300"));
    }

    #[test]
    fn test_check_limits_min_characters_ok() {
        let mut args = make_test_cli();
        args.min_characters = Some(100);
        let count = Count {
            words: 100,
            characters: 500,
        };

        assert!(check_limits(&args, &count).is_ok());
    }

    #[test]
    fn test_check_limits_min_characters_below() {
        let mut args = make_test_cli();
        args.min_characters = Some(1000);
        let count = Count {
            words: 100,
            characters: 500,
        };

        let result = check_limits(&args, &count);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("below minimum"));
        assert!(errors[0].contains("500 < 1000"));
    }

    #[test]
    fn test_check_limits_multiple_violations() {
        let mut args = make_test_cli();
        args.max_words = Some(50);
        args.min_words = Some(200);
        args.max_characters = Some(300);
        args.min_characters = Some(1000);
        let count = Count {
            words: 100,
            characters: 500,
        };

        let result = check_limits(&args, &count);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        // Should have 4 violations: max_words exceeded, min_words not met,
        // max_characters exceeded, min_characters not met
        assert_eq!(errors.len(), 4);
    }

    #[test]
    fn test_check_limits_boundary_values() {
        let mut args = make_test_cli();
        args.max_words = Some(100);
        args.min_words = Some(100);
        let count = Count {
            words: 100,
            characters: 500,
        };

        // Exactly at the boundary should be OK
        assert!(check_limits(&args, &count).is_ok());
    }

    #[test]
    fn test_check_limits_mixed_ok_and_violations() {
        let mut args = make_test_cli();
        args.max_words = Some(200); // OK
        args.min_words = Some(50); // OK
        args.max_characters = Some(300); // Violation
        args.min_characters = Some(100); // OK
        let count = Count {
            words: 100,
            characters: 500,
        };

        let result = check_limits(&args, &count);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("Character count exceeds maximum"));
    }
}