reformat-core 0.1.6

Core library for text and file reformatting
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
//! Emoji removal and replacement transformer
//!
//! This module provides functionality to remove or replace emojis in text files,
//! with special handling for task completion emojis.

use regex::Regex;
use std::fs;
use std::path::Path;
use walkdir::WalkDir;

/// Options for emoji transformation
#[derive(Debug, Clone)]
pub struct EmojiOptions {
    /// Replace task completion emojis with text alternatives
    pub replace_task_emojis: bool,
    /// Remove all other emojis
    pub remove_other_emojis: bool,
    /// File extensions to process
    pub file_extensions: Vec<String>,
    /// Process directories recursively
    pub recursive: bool,
    /// Dry run mode (don't modify files)
    pub dry_run: bool,
}

impl Default for EmojiOptions {
    fn default() -> Self {
        EmojiOptions {
            replace_task_emojis: true,
            remove_other_emojis: true,
            file_extensions: vec![
                ".md", ".txt", ".rst", ".org", ".py", ".rs", ".go", ".java", ".js", ".ts", ".jsx",
                ".tsx", ".c", ".h", ".cpp", ".hpp",
            ]
            .iter()
            .map(|s| s.to_string())
            .collect(),
            recursive: true,
            dry_run: false,
        }
    }
}

/// Emoji transformer for removing and replacing emojis
pub struct EmojiTransformer {
    options: EmojiOptions,
    task_emoji_pattern: Regex,
    general_emoji_pattern: Regex,
}

impl EmojiTransformer {
    /// Creates a new emoji transformer with the given options
    pub fn new(options: EmojiOptions) -> Self {
        // Task completion emojis that should be replaced with text
        let task_emoji_pattern = Regex::new(
            r"(?x)
            [\u2705]|          # White check mark (✅)
            [\u2611]|          # Ballot box with check (☑)
            [\u2714]|          # Heavy check mark (✔)
            [\u2713]|          # Check mark (✓)
            [\u2610]|          # Ballot box (☐)
            [\u2612]|          # Ballot box with X (☒)
            [\u274C]|          # Cross mark (❌)
            [\u274E]|          # Negative squared cross mark (❎)
            [\u26A0]|          # Warning sign (⚠)
            [\u26D4]|          # No entry (⛔)
            [\u2B50]|          # Star (⭐)
            [\u{1F7E0}]|       # Orange circle (🟠)
            [\u{1F7E1}]|       # Yellow circle (🟡)
            [\u{1F7E8}]|       # Yellow square (🟨)
            [\u{1F7E2}]|       # Green circle (🟢)
            [\u{1F534}]|       # Red circle (🔴)
            [\u{1F4DD}]|       # Memo (📝)
            [\u{1F4CB}]|       # Clipboard (📋)
            [\u{1F4C4}]|       # Page facing up (📄)
            [\u{1F4C5}]|       # Calendar (📅)
            [\u{1F4C6}]|       # Tear-off calendar (📆)
            [\u{1F5D3}]|       # Spiral calendar (🗓)
            [\u{1F4D1}]|       # Bookmark tabs (📑)
            [\u{1F4CC}]|       # Pushpin (📌)
            [\u{1F4CD}]|       # Round pushpin (📍)
            [\u{1F4CE}]        # Paperclip (📎)
            ",
        )
        .unwrap();

        // General emoji pattern (all emojis not covered by task emojis)
        let general_emoji_pattern = Regex::new(
            r"(?x)
            [\u{1F600}-\u{1F64F}]|  # Emoticons
            [\u{1F300}-\u{1F5FF}]|  # Symbols & pictographs
            [\u{1F680}-\u{1F6FF}]|  # Transport & map symbols
            [\u{1F1E0}-\u{1F1FF}]|  # Flags
            [\u{2600}-\u{26FF}]|    # Miscellaneous symbols
            [\u{2700}-\u{27BF}]|    # Dingbats
            [\u{1F900}-\u{1F9FF}]|  # Supplemental symbols
            [\u{1FA00}-\u{1FA6F}]|  # Extended-A
            [\u{1FA70}-\u{1FAFF}]|  # Extended-B
            [\u{FE00}-\u{FE0F}]|    # Variation selectors
            [\u{1F004}]|            # Mahjong tile
            [\u{1F0CF}]|            # Playing card
            [\u{1F18E}]|            # Negative squared AB
            [\u{1F191}-\u{1F19A}]|  # Squared CL, COOL, etc.
            [\u{1F1E6}-\u{1F1FF}]   # Regional indicator symbols
            ",
        )
        .unwrap();

        EmojiTransformer {
            options,
            task_emoji_pattern,
            general_emoji_pattern,
        }
    }

    /// Creates a transformer with default options
    pub fn with_defaults() -> Self {
        EmojiTransformer::new(EmojiOptions::default())
    }

    /// Checks if a file should be processed
    fn should_process(&self, path: &Path) -> bool {
        if !path.is_file() {
            return false;
        }

        // Skip hidden files and directories
        if path.components().any(|c| {
            c.as_os_str()
                .to_str()
                .map(|s| s.starts_with('.'))
                .unwrap_or(false)
        }) {
            return false;
        }

        // Skip build directories
        let skip_dirs = [
            "build",
            "__pycache__",
            ".git",
            "node_modules",
            "venv",
            ".venv",
            "target",
        ];
        if path.components().any(|c| {
            c.as_os_str()
                .to_str()
                .map(|s| skip_dirs.contains(&s))
                .unwrap_or(false)
        }) {
            return false;
        }

        // Check file extension
        if let Some(ext) = path.extension() {
            let ext_str = format!(".{}", ext.to_string_lossy());
            self.options.file_extensions.contains(&ext_str)
        } else {
            false
        }
    }

    /// Replace task emojis with text equivalents
    fn replace_task_emoji(&self, emoji: &str) -> &str {
        match emoji {
            "\u{2705}" => "[x]",       // ✅ -> [x]
            "\u{2611}" => "[x]",       // ☑ -> [x]
            "\u{2714}" => "[x]",       // ✔ -> [x]
            "\u{2713}" => "[x]",       // ✓ -> [x]
            "\u{2610}" => "[ ]",       // ☐ -> [ ]
            "\u{2612}" => "[X]",       // ☒ -> [X]
            "\u{274C}" => "[X]",       // ❌ -> [X]
            "\u{274E}" => "[X]",       // ❎ -> [X]
            "\u{26A0}" => "[!]",       // ⚠ -> [!]
            "\u{26D4}" => "[!]",       // ⛔ -> [!]
            "\u{2B50}" => "[+]",       // ⭐ -> [+]
            "\u{1F7E0}" => "[orange]", // 🟠 -> [orange]
            "\u{1F7E1}" => "[yellow]", // 🟡 -> [yellow]
            "\u{1F7E8}" => "[yellow]", // 🟨 -> [yellow]
            "\u{1F7E2}" => "[green]",  // 🟢 -> [green]
            "\u{1F534}" => "[red]",    // 🔴 -> [red]
            "\u{1F4DD}" => "[note]",   // 📝 -> [note]
            "\u{1F4CB}" => "[list]",   // 📋 -> [list]
            "\u{1F4C4}" => "[doc]",    // 📄 -> [doc]
            "\u{1F4C5}" => "[cal]",    // 📅 -> [cal]
            "\u{1F4C6}" => "[cal]",    // 📆 -> [cal]
            "\u{1F5D3}" => "[cal]",    // 🗓 -> [cal]
            "\u{1F4D1}" => "[tab]",    // 📑 -> [tab]
            "\u{1F4CC}" => "[pin]",    // 📌 -> [pin]
            "\u{1F4CD}" => "[pin]",    // 📍 -> [pin]
            "\u{1F4CE}" => "[clip]",   // 📎 -> [clip]
            _ => "",
        }
    }

    /// Transform emojis in a single file
    pub fn transform_file(&self, path: &Path) -> crate::Result<usize> {
        if !self.should_process(path) {
            return Ok(0);
        }

        let content = fs::read_to_string(path)?;
        let original_content = content.clone();

        let mut modified_content = content;
        let mut changes = 0;

        // Replace task emojis with text alternatives
        if self.options.replace_task_emojis {
            let before = modified_content.clone();
            let replaced = self
                .task_emoji_pattern
                .replace_all(&modified_content, |caps: &regex::Captures| {
                    self.replace_task_emoji(&caps[0])
                });

            if replaced != before {
                // Count the number of replacements made
                let task_emojis_found = self.task_emoji_pattern.find_iter(&before).count();
                changes += task_emojis_found;
                modified_content = replaced.to_string();
            }
        }

        // Remove other emojis
        if self.options.remove_other_emojis {
            let before = modified_content.clone();
            let cleaned = self
                .general_emoji_pattern
                .replace_all(&modified_content, "");
            if cleaned != before {
                // Count the number of emojis removed
                let emojis_found = self.general_emoji_pattern.find_iter(&before).count();
                changes += emojis_found;
                modified_content = cleaned.to_string();
            }
        }

        if modified_content != original_content {
            if self.options.dry_run {
                println!("Would transform emojis in '{}'", path.display());
            } else {
                fs::write(path, modified_content)?;
                println!("Transformed emojis in '{}'", path.display());
            }
            Ok(changes.max(1))
        } else {
            Ok(0)
        }
    }

    /// Processes a directory or file
    pub fn process(&self, path: &Path) -> crate::Result<(usize, usize)> {
        let mut total_files = 0;
        let mut total_changes = 0;

        if path.is_file() {
            let changes = self.transform_file(path)?;
            if changes > 0 {
                total_files = 1;
                total_changes = changes;
            }
        } else if path.is_dir() {
            if self.options.recursive {
                for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
                    if entry.file_type().is_file() {
                        let changes = self.transform_file(entry.path())?;
                        if changes > 0 {
                            total_files += 1;
                            total_changes += changes;
                        }
                    }
                }
            } else {
                for entry in fs::read_dir(path)? {
                    let entry = entry?;
                    let entry_path = entry.path();
                    if entry_path.is_file() {
                        let changes = self.transform_file(&entry_path)?;
                        if changes > 0 {
                            total_files += 1;
                            total_changes += changes;
                        }
                    }
                }
            }
        }

        Ok((total_files, total_changes))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn test_replace_task_emojis() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_test");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("test.md");
        fs::write(
            &test_file,
            "- [x] Done task\n- [ ] Todo task\n- Task complete\n",
        )
        .unwrap();

        // Replace checkmarks with [x]
        let content = fs::read_to_string(&test_file).unwrap();
        let updated = content.replace("", "[x]");
        fs::write(&test_file, updated).unwrap();

        let transformer = EmojiTransformer::with_defaults();
        let (_files, _) = transformer.process(&test_file).unwrap();

        // Should still be valid markdown
        let content = fs::read_to_string(&test_file).unwrap();
        assert!(content.contains("[x]") || content.contains("[ ]"));

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_checkmark_replacement() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_checkmark");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("test.txt");
        fs::write(&test_file, "Task done ✅\nTask pending ☐\n").unwrap();

        let transformer = EmojiTransformer::with_defaults();
        let (files, _) = transformer.process(&test_file).unwrap();

        if files > 0 {
            let content = fs::read_to_string(&test_file).unwrap();
            assert!(content.contains("[x]") || content.contains("[ ]"));
            assert!(!content.contains(""));
            assert!(!content.contains(""));
        }

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_dry_run_mode() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_dry");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("test.txt");
        let original = "Task ✅ done";
        fs::write(&test_file, original).unwrap();

        let mut opts = EmojiOptions::default();
        opts.dry_run = true;

        let transformer = EmojiTransformer::new(opts);
        transformer.process(&test_file).unwrap();

        // File should be unchanged
        let content = fs::read_to_string(&test_file).unwrap();
        assert_eq!(content, original);

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_skip_hidden_files() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_hidden");
        fs::create_dir_all(&test_dir).unwrap();

        let hidden_file = test_dir.join(".hidden.txt");
        fs::write(&hidden_file, "Task ✅\n").unwrap();

        let transformer = EmojiTransformer::with_defaults();
        let (files, _) = transformer.process(&hidden_file).unwrap();

        // Hidden file should be skipped
        assert_eq!(files, 0);

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_extension_filtering() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_ext");
        fs::create_dir_all(&test_dir).unwrap();

        let md_file = test_dir.join("test.md");
        let xyz_file = test_dir.join("test.xyz");

        fs::write(&md_file, "✅ Task\n").unwrap();
        fs::write(&xyz_file, "✅ Task\n").unwrap();

        let mut opts = EmojiOptions::default();
        opts.file_extensions = vec![".md".to_string()];

        let transformer = EmojiTransformer::new(opts);
        let (files, _) = transformer.process(&test_dir).unwrap();

        // Only .md should be processed
        assert_eq!(files, 1);

        let md_content = fs::read_to_string(&md_file).unwrap();
        let xyz_content = fs::read_to_string(&xyz_file).unwrap();

        assert!(md_content.contains("[x]") || !md_content.contains(""));
        assert_eq!(xyz_content, "✅ Task\n"); // Unchanged

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_recursive_processing() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_recursive");
        fs::create_dir_all(&test_dir).unwrap();

        let sub_dir = test_dir.join("subdir");
        fs::create_dir_all(&sub_dir).unwrap();

        let file1 = test_dir.join("file1.md");
        let file2 = sub_dir.join("file2.md");

        fs::write(&file1, "✅ Done\n").unwrap();
        fs::write(&file2, "☐ Todo\n").unwrap();

        let transformer = EmojiTransformer::with_defaults();
        let (files, _) = transformer.process(&test_dir).unwrap();

        assert_eq!(files, 2);

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_star_and_circle_replacement() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_star_circle");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("test.md");
        fs::write(
            &test_file,
            "⭐ Important task\n🟡 In progress\n🟢 Complete\n🔴 Blocked\n",
        )
        .unwrap();

        let transformer = EmojiTransformer::with_defaults();
        let (files, _) = transformer.process(&test_file).unwrap();

        if files > 0 {
            let content = fs::read_to_string(&test_file).unwrap();
            assert!(
                content.contains("[+]"),
                "Star emoji should be replaced with [+]"
            );
            assert!(
                content.contains("[yellow]"),
                "Yellow circle should be replaced with [yellow]"
            );
            assert!(
                content.contains("[green]"),
                "Green circle should be replaced with [green]"
            );
            assert!(
                content.contains("[red]"),
                "Red circle should be replaced with [red]"
            );
            assert!(!content.contains(""), "Star emoji should be removed");
            assert!(!content.contains("🟡"), "Yellow circle should be removed");
            assert!(!content.contains("🟢"), "Green circle should be removed");
            assert!(!content.contains("🔴"), "Red circle should be removed");
        }

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_yellow_square_replacement() {
        let test_dir = std::env::temp_dir().join("reformat_emoji_yellow_square");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("test.md");
        fs::write(&test_file, "🟨 In progress task\n🟡 Another yellow\n").unwrap();

        let transformer = EmojiTransformer::with_defaults();
        let (files, _) = transformer.process(&test_file).unwrap();

        if files > 0 {
            let content = fs::read_to_string(&test_file).unwrap();
            assert!(
                content.contains("[yellow]"),
                "Yellow square should be replaced with [yellow]"
            );
            assert!(
                !content.contains("🟨"),
                "Yellow square emoji should be removed"
            );
            assert!(
                !content.contains("🟡"),
                "Yellow circle emoji should be removed"
            );
        }

        fs::remove_dir_all(&test_dir).unwrap();
    }
}