snip-it 1.3.0

Fast terminal snippet manager with fuzzy search, TUI, variable expansion, and end-to-end encrypted cross-device sync
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
//! Core data structures and library management.
//!
//! This module provides the foundational types for storing and managing snippets:
//! - [`Snippet`]: Individual snippet with command, description, tags, etc.
//! - [`Snippets`]: Collection container for multiple snippets
//! - [`LibraryManager`]: Manages multiple snippet libraries and premade collections
//!
//! # Snippet TOML Format
//!
//! ```toml
//! [[Snippets]]
//! Description = "git commit"
//! Tag = ["git"]
//! command = "git commit -m \"<msg>\""
//! ```

use crate::config::{cached_read_toml, invalidate_toml_cache};
use crate::error::{SnipError, SnipResult};
use crate::utils::config::{get_config_dir, get_snippets_path};
use crate::utils::toml_helpers::{fix_invalid_toml_escapes, quote_strings_containing_backslashes};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

/// Container for a collection of snippets.
///
/// Wraps a list of [`Snippet`] items and optional folder structure.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Snippets {
    #[serde(rename = "Snippets", default)]
    pub snippets: Vec<Snippet>,
    #[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
    pub folders: Vec<String>,
}

/// Individual snippet with metadata.
///
/// A snippet contains a command to execute along with optional description,
/// tags, and sync-related fields. The command may include variables using
/// `<name>` or `<name=default>` syntax.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Snippet {
    #[serde(rename = "Id", alias = "ID", default)]
    pub id: String,
    #[serde(alias = "Description", alias = "name", default)]
    pub description: String,
    #[serde(rename = "Output", alias = "output", default)]
    pub output: String,
    #[serde(
        alias = "Tag",
        alias = "Tags",
        default,
        skip_serializing_if = "Vec::is_empty"
    )]
    pub tags: Vec<String>,
    #[serde(alias = "Command", alias = "cmd", default)]
    pub command: String,
    #[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
    pub folders: Vec<String>,
    #[serde(default)]
    pub favorite: bool,
    #[serde(default)]
    pub created_at: i64,
    #[serde(default)]
    pub updated_at: i64,
    #[serde(default)]
    pub device_id: String,
    #[serde(default)]
    pub deleted: bool,
}

/// Configuration for managing snippet libraries.
///
/// Stored in `libraries.toml` and tracks metadata for all libraries.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LibraryConfig {
    #[serde(default)]
    pub libraries: Vec<LibraryMeta>,
}

/// Metadata for a single snippet library.
///
/// Tracks the library filename, optional server linkage, sync state,
/// and whether it is the primary library.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LibraryMeta {
    pub filename: String,
    #[serde(default)]
    pub library_id: String,
    #[serde(default)]
    pub is_primary: bool,
    #[serde(default)]
    pub last_sync: Option<i64>,
    #[serde(default)]
    pub server_id: Option<String>,
}

impl LibraryMeta {
    /// Creates a new library metadata entry with the given filename.
    pub fn new(filename: &str) -> Self {
        Self {
            filename: filename.to_string(),
            library_id: String::new(),
            is_primary: false,
            last_sync: None,
            server_id: None,
        }
    }
}

fn validate_library_name(name: &str) -> Result<(), (&'static str, &'static str)> {
    if name.is_empty() {
        return Err(("Invalid library name", "Library name cannot be empty"));
    }
    if name.len() > 50 {
        return Err((
            "Invalid library name",
            "Library name cannot exceed 50 characters",
        ));
    }
    if name.contains('/') || name.contains('\\') {
        return Err((
            "Invalid library name",
            "Library name cannot contain slashes",
        ));
    }
    if name.contains('\0') {
        return Err((
            "Invalid library name",
            "Library name cannot contain null bytes",
        ));
    }
    if name == "." || name == ".." || name.contains("..") {
        return Err((
            "Invalid library name",
            "Library name cannot contain path traversal sequences",
        ));
    }
    Ok(())
}

impl Snippet {
    /// Creates a new snippet with the given description, command, and tags.
    ///
    /// Returns an error if the command or description is empty/whitespace.
    pub fn new(description: String, command: String, tags: Vec<String>) -> SnipResult<Self> {
        if command.trim().is_empty() {
            return Err(SnipError::runtime_error(
                "Empty command",
                Some("Snippet command cannot be empty"),
            ));
        }
        if description.trim().is_empty() {
            return Err(SnipError::runtime_error(
                "Empty description",
                Some("Snippet description cannot be empty"),
            ));
        }
        let now = chrono::Utc::now().timestamp();
        Ok(Self {
            id: String::new(),
            description,
            command,
            tags,
            output: String::new(),
            folders: Vec::new(),
            favorite: false,
            created_at: now,
            updated_at: now,
            device_id: String::new(),
            deleted: false,
        })
    }
}

/// Manages snippet libraries and premade collections.
///
/// LibraryManager handles:
/// - Loading and saving the libraries configuration
/// - Creating, deleting, and managing individual libraries
/// - Loading premade libraries
/// - Determining whether to use single-file or library mode
pub struct LibraryManager {
    config_dir: PathBuf,
    libraries_dir: PathBuf,
    premade_dir: PathBuf,
    config: LibraryConfig,
}

impl LibraryManager {
    /// Creates a new `LibraryManager`, loading configuration from disk.
    ///
    /// Handles macOS config directory migration and parses `libraries.toml`.
    /// Returns defaults if the config file is missing or corrupted.
    pub fn new() -> SnipResult<Self> {
        // Migrate legacy macOS config dir if needed
        if let Err(e) = crate::utils::config::migrate_macos_config_dir() {
            tracing::warn!(error = %e, "Failed to migrate config directory");
        }

        let config_dir = get_config_dir();

        let libraries_dir = config_dir.join("libraries");
        let premade_dir = config_dir.join("premade");
        let config_path = config_dir.join("libraries.toml");

        let config = if config_path.exists() {
            let content = cached_read_toml(&config_path)?;
            let content = fix_invalid_toml_escapes(&content);
            match toml::from_str(&content) {
                Ok(c) => c,
                Err(e) => {
                    // Backup corrupted file so data isn't lost on next save
                    let backup = config_path.with_extension("toml.corrupt");
                    if let Err(copy_err) = fs::copy(&config_path, &backup) {
                        tracing::warn!(
                            config = %config_path.display(),
                            error = %e,
                            backup_error = %copy_err,
                            "Failed to parse config (backup also failed)"
                        );
                    } else {
                        tracing::warn!(
                            config = %config_path.display(),
                            error = %e,
                            backup = %backup.display(),
                            "Failed to parse config, backed up to file. Using defaults."
                        );
                    }
                    LibraryConfig::default()
                }
            }
        } else {
            LibraryConfig::default()
        };

        Ok(Self {
            config_dir,
            libraries_dir,
            premade_dir,
            config,
        })
    }

    /// Returns the default path to the legacy single-file snippets TOML.
    pub fn get_default_snippets_path() -> PathBuf {
        get_snippets_path()
    }

    /// Returns a reference to the libraries directory path.
    pub fn get_libraries_dir(&self) -> &PathBuf {
        &self.libraries_dir
    }

    /// Returns `true` if the libraries directory does not exist (legacy single-file mode).
    pub fn is_single_file_mode(&self) -> bool {
        !self.libraries_dir.exists()
    }

    /// Returns the path to the legacy single-file snippets TOML.
    pub fn get_legacy_snippets_path(&self) -> PathBuf {
        Self::get_default_snippets_path()
    }

    /// Ensures the library directory exists, migrating from single-file mode if needed.
    pub fn ensure_library_mode(&mut self) -> SnipResult<()> {
        if self.is_single_file_mode() {
            self.migrate_from_single_file()?;
        }
        Ok(())
    }

    /// Creates the libraries directory if it does not exist.
    pub fn init_libraries_dir(&self) -> SnipResult<()> {
        if !self.libraries_dir.exists() {
            fs::create_dir_all(&self.libraries_dir).map_err(|e| {
                SnipError::io_error("create libraries directory", self.libraries_dir.clone(), e)
            })?;
        }
        Ok(())
    }

    /// Migrates the legacy single-file `snippets.toml` into a library subdirectory.
    pub fn migrate_from_single_file(&mut self) -> SnipResult<()> {
        let legacy_path = self.get_legacy_snippets_path();

        if !legacy_path.exists() {
            return Ok(());
        }

        self.init_libraries_dir()?;

        let content = cached_read_toml(&legacy_path)?;
        if content.trim().is_empty() {
            return Ok(());
        }

        let new_path = self.libraries_dir.join("snippets.toml");
        fs::copy(&legacy_path, &new_path)
            .map_err(|e| SnipError::io_error("migrate snippets file", new_path.clone(), e))?;

        let mut meta = LibraryMeta::new("snippets");
        meta.is_primary = true;
        self.config.libraries.push(meta);

        self.save_config()?;

        Ok(())
    }

    /// Returns references to all registered libraries.
    pub fn list_libraries(&self) -> Vec<&LibraryMeta> {
        self.config.libraries.iter().collect()
    }

    /// Returns the primary library, or `None` if no library is marked primary.
    pub fn get_primary_library(&self) -> Option<&LibraryMeta> {
        self.config.libraries.iter().find(|l| l.is_primary)
    }

    /// Finds a library by its filename (without `.toml` extension).
    pub fn get_library_by_filename(&self, filename: &str) -> Option<&LibraryMeta> {
        self.config
            .libraries
            .iter()
            .find(|l| l.filename == filename)
    }

    /// Finds a library by filename, returning a mutable reference.
    pub fn get_library_by_filename_mut(&mut self, filename: &str) -> Option<&mut LibraryMeta> {
        self.config
            .libraries
            .iter_mut()
            .find(|l| l.filename == filename)
    }

    /// Creates a new snippet library file and registers it in the config.
    ///
    /// The first library created is automatically marked as primary.
    /// Returns the path to the newly created library file.
    pub fn create_library(&mut self, filename: &str) -> SnipResult<PathBuf> {
        validate_library_name(filename)
            .map_err(|(msg, detail)| SnipError::runtime_error(msg, Some(detail)))?;

        self.init_libraries_dir()?;

        let filename_lower = filename.to_lowercase();
        let path = self.libraries_dir.join(format!("{filename}.toml"));

        if path.exists() {
            return Err(SnipError::runtime_error(
                "Library already exists",
                Some(&format!("File {} already exists", path.display())),
            ));
        }

        for lib in &self.config.libraries {
            if lib.filename.to_lowercase() == filename_lower {
                return Err(SnipError::runtime_error(
                    "Library already exists",
                    Some(&format!(
                        "A library with name '{filename}' already exists (case-insensitive duplicate)"
                    )),
                ));
            }
        }

        let default_content = r#"# Snippet library
# Each snippet has: Description, Output, Tag, command, folders, favorite

Snippets = []

"#;

        write_library_file(&path, default_content, filename)?;

        let is_first = self.config.libraries.is_empty();
        let mut meta = LibraryMeta::new(filename);
        meta.is_primary = is_first;
        self.config.libraries.push(meta);

        self.save_config()?;

        Ok(path)
    }

    /// Deletes a library file and removes it from the config.
    ///
    /// If the deleted library was primary, another library is promoted.
    /// Config is saved before file deletion for crash safety.
    pub fn delete_library(&mut self, filename: &str) -> SnipResult<()> {
        let was_primary = self
            .get_library_by_filename(filename)
            .map(|l| l.is_primary)
            .ok_or_else(|| SnipError::runtime_error("Library not found", Some(filename)))?;

        let deleted_was_server = self
            .get_library_by_filename(filename)
            .map(|l| l.server_id.is_some())
            .unwrap_or(false);

        let path = self.libraries_dir.join(format!("{filename}.toml"));

        // Save config first (remove from metadata), then delete the file.
        // If we crash after config save but before file delete, the orphaned
        // file is recoverable — operations on the deleted library will fail
        // gracefully with IO errors. The reverse order (delete file first,
        // then save config) leaves a stale config reference on crash.
        self.config.libraries.retain(|l| l.filename != filename);

        if was_primary && !self.config.libraries.is_empty() {
            let promoted = if deleted_was_server {
                self.config
                    .libraries
                    .iter()
                    .find(|l| l.server_id.is_some())
                    .or_else(|| self.config.libraries.first())
            } else {
                self.config.libraries.first()
            };
            if let Some(promoted_lib) = promoted
                && let Some(idx) = self
                    .config
                    .libraries
                    .iter()
                    .position(|l| l.filename == promoted_lib.filename)
            {
                self.config.libraries[idx].is_primary = true;
            }
        }

        self.save_config()?;

        if path.exists() {
            fs::remove_file(&path)
                .map_err(|e| SnipError::io_error("delete library file", path.clone(), e))?;
        }

        Ok(())
    }

    /// Sets the given library as primary, unmarking all others.
    pub fn set_primary(&mut self, filename: &str) -> SnipResult<()> {
        if !self
            .config
            .libraries
            .iter()
            .any(|lib| lib.filename == filename)
        {
            return Err(SnipError::runtime_error(
                "Library not found",
                Some(&format!("No library with filename '{filename}'")),
            ));
        }
        for lib in &mut self.config.libraries {
            lib.is_primary = lib.filename == filename;
        }

        self.save_config()?;
        Ok(())
    }

    /// Updates the server-side library ID for a local library.
    pub fn update_library_id(&mut self, filename: &str, library_id: &str) -> SnipResult<()> {
        if let Some(lib) = self.get_library_by_filename_mut(filename) {
            lib.library_id = library_id.to_string();

            self.save_config()?;
        }
        Ok(())
    }

    /// Links a local library to a server-side library.
    pub fn link_server_library(&mut self, filename: &str, server_id: &str) -> SnipResult<()> {
        if let Some(lib) = self.get_library_by_filename_mut(filename) {
            lib.library_id = server_id.to_string();
            lib.server_id = Some(server_id.to_string());

            self.save_config()?;
        }
        Ok(())
    }

    /// Clears server linkage metadata for a local library.
    pub fn unlink_server_library(&mut self, filename: &str) -> SnipResult<()> {
        if let Some(lib) = self.get_library_by_filename_mut(filename) {
            lib.library_id.clear();
            lib.server_id = None;

            self.save_config()?;
        }
        Ok(())
    }

    /// Registers an existing library file that is not yet tracked in the config.
    pub fn add_existing_library(&mut self, filename: &str) -> SnipResult<()> {
        validate_library_name(filename)
            .map_err(|(title, detail)| SnipError::runtime_error(title, Some(detail)))?;

        if self.get_library_by_filename(filename).is_some() {
            return Ok(());
        }

        let meta = LibraryMeta {
            filename: filename.to_string(),
            library_id: String::new(),
            is_primary: false,
            last_sync: None,
            server_id: None,
        };

        self.config.libraries.push(meta);

        self.save_config()?;
        Ok(())
    }

    /// Updates the last-sync timestamp for a library.
    pub fn update_last_sync(&mut self, filename: &str, timestamp: i64) -> SnipResult<()> {
        if let Some(lib) = self.get_library_by_filename_mut(filename) {
            lib.last_sync = Some(timestamp);

            self.save_config()?;
        }
        Ok(())
    }

    /// Creates or links a library imported from the sync server.
    ///
    /// If a library with the same filename already exists, its server ID is updated.
    /// Otherwise, a new library file and config entry are created.
    pub fn add_server_library(
        &mut self,
        server_name: &str,
        server_id: &str,
    ) -> SnipResult<PathBuf> {
        let filename = server_name.to_lowercase().replace(' ', "-");

        validate_library_name(&filename)
            .map_err(|(title, detail)| SnipError::runtime_error(title, Some(detail)))?;

        self.init_libraries_dir()?;

        let path = self.libraries_dir.join(format!("{filename}.toml"));

        if !path.exists() {
            let default_content = "# Imported from server\n\nSnippets = []\n";
            write_library_file(&path, default_content, &filename)?;
        }

        // Update existing entry if one with the same filename already exists
        if let Some(existing) = self.get_library_by_filename_mut(&filename) {
            existing.library_id = server_id.to_string();
            existing.server_id = Some(server_id.to_string());

            self.save_config()?;
            return Ok(path);
        }

        let is_first = self.config.libraries.is_empty();
        let mut meta = LibraryMeta::new(&filename);
        meta.library_id = server_id.to_string();
        meta.server_id = Some(server_id.to_string());
        meta.is_primary = is_first;

        self.config.libraries.push(meta);

        self.save_config()?;

        Ok(path)
    }

    /// Creates the premade libraries directory if it does not exist.
    pub fn init_premade_dir(&self) -> SnipResult<()> {
        if !self.premade_dir.exists() {
            fs::create_dir_all(&self.premade_dir).map_err(|e| {
                SnipError::io_error("create premade directory", self.premade_dir.clone(), e)
            })?;
        }
        Ok(())
    }

    /// Returns the path to the premade libraries directory.
    pub fn get_premade_dir(&self) -> &PathBuf {
        &self.premade_dir
    }

    /// Returns `true` if a premade library with the given filename exists on disk.
    pub fn premade_exists(&self, filename: &str) -> bool {
        self.premade_dir.join(format!("{filename}.toml")).exists()
    }

    /// Saves a premade library file to the premade directory.
    ///
    /// Validates the filename against path traversal attacks before writing.
    /// Returns the path to the saved file.
    pub fn save_premade_library(&self, filename: &str, content: &str) -> SnipResult<PathBuf> {
        self.init_premade_dir()?;

        if filename.is_empty()
            || filename.contains('/')
            || filename.contains('\\')
            || filename.contains('\0')
            || filename.contains("..")
        {
            return Err(SnipError::runtime_error(
                "Invalid premade library filename",
                Some(filename),
            ));
        }

        let path = self.premade_dir.join(format!("{filename}.toml"));

        let canonical_premade = self.premade_dir.canonicalize().map_err(|e| {
            SnipError::io_error("resolve premade directory", self.premade_dir.clone(), e)
        })?;
        let canonical_path = path
            .canonicalize()
            .unwrap_or_else(|_| canonical_premade.join(format!("{filename}.toml")));
        if !canonical_path.starts_with(&canonical_premade) {
            return Err(SnipError::runtime_error(
                "Invalid premade library path",
                Some("Filename resolves outside premade directory"),
            ));
        }

        write_library_file(&path, content, filename)?;

        Ok(path)
    }

    fn save_config(&mut self) -> SnipResult<()> {
        let config_path = self.config_dir.join("libraries.toml");

        let toml_str = toml::to_string_pretty(&self.config)
            .map_err(|e| SnipError::toml_error("serialize libraries config", e))?;

        let toml_str = quote_strings_containing_backslashes(&toml_str);

        crate::utils::atomic::write_private_atomic(&config_path, &toml_str, "libraries")?;
        invalidate_toml_cache(&config_path);

        Ok(())
    }
}

fn write_library_file(path: &Path, content: &str, temp_prefix: &str) -> SnipResult<()> {
    crate::utils::atomic::write_private_atomic(path, content, temp_prefix)?;
    invalidate_toml_cache(path);
    Ok(())
}

/// Loads a snippet library from a TOML file.
///
/// Returns an empty collection if the file doesn't exist or is empty.
/// Deduplicates snippet IDs on load and creates backups of corrupted files.
pub fn load_library(path: &Path) -> SnipResult<Snippets> {
    if !path.exists() {
        return Ok(Snippets::default());
    }

    let content = cached_read_toml(path)?;
    if content.is_empty() || content.trim().is_empty() {
        return Ok(Snippets::default());
    }

    let fixed_content = fix_invalid_toml_escapes(&content);

    let snippets: Snippets = match toml::from_str(&fixed_content) {
        Ok(s) => s,
        Err(e) => {
            // Create backup of corrupted file before returning defaults
            let backup_path = path.with_extension("toml.corrupt.bak");
            if let Err(backup_err) = fs::copy(path, &backup_path) {
                tracing::error!(
                    file = %path.display(),
                    error = %backup_err,
                    "Failed to parse TOML and could not create backup"
                );
            } else {
                tracing::error!(
                    file = %path.display(),
                    backup = %backup_path.display(),
                    error = %e,
                    "Failed to parse TOML, backup saved"
                );
            }
            Snippets::default()
        }
    };

    let mut seen_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut deduplicated: Vec<Snippet> = Vec::new();
    for mut snippet in snippets.snippets {
        if snippet.id.is_empty() {
            snippet.id = uuid::Uuid::new_v4().to_string();
        }
        if seen_ids.contains(&snippet.id) {
            snippet.id = uuid::Uuid::new_v4().to_string();
        }
        seen_ids.insert(snippet.id.clone());
        deduplicated.push(snippet);
    }

    Ok(Snippets {
        snippets: deduplicated,
        folders: snippets.folders,
    })
}

/// Saves a snippet library to a TOML file using atomic write.
///
/// Creates a backup before saving and sorts snippets by `updated_at` descending.
pub fn save_library(path: &Path, snippets: &Snippets) -> SnipResult<()> {
    if let Err(e) = backup_library(path) {
        tracing::warn!(error = %e, "Failed to create backup before save");
    }

    let mut sorted = snippets.clone();
    sorted
        .snippets
        .sort_by_key(|b| std::cmp::Reverse(b.updated_at));

    let toml_str = toml::to_string_pretty(&sorted)
        .map_err(|e| SnipError::toml_error("serialize snippets", e))?;

    let toml_str = quote_strings_containing_backslashes(&toml_str);

    let temp_prefix = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("snippets");
    crate::utils::atomic::write_private_atomic(path, &toml_str, temp_prefix)?;

    invalidate_toml_cache(path);

    Ok(())
}

/// Creates a timestamped backup of a library file.
///
/// Stores backups in a `backups/` subdirectory, keeping at most 10 per library.
/// Returns `None` if the source file doesn't exist.
pub fn backup_library(path: &Path) -> SnipResult<Option<PathBuf>> {
    if !path.exists() {
        return Ok(None);
    }

    let backup_dir = path
        .parent()
        .ok_or_else(|| {
            SnipError::runtime_error(
                "backup path has no parent",
                Some(&path.display().to_string()),
            )
        })?
        .join("backups");
    fs::create_dir_all(&backup_dir)
        .map_err(|e| SnipError::io_error("create backup directory", backup_dir.clone(), e))?;

    // Clean up old backups (keep at most 10 per library)
    cleanup_old_backups(&backup_dir, path)?;

    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S_%f");
    let file_stem = path.file_stem().ok_or_else(|| {
        SnipError::runtime_error(
            "backup path has no file stem",
            Some(&path.display().to_string()),
        )
    })?;
    let backup_name = format!("{}.{}.toml.bak", file_stem.to_string_lossy(), timestamp);
    let backup_path = backup_dir.join(backup_name);

    fs::copy(path, &backup_path)
        .map_err(|e| SnipError::io_error("create backup", backup_path.clone(), e))?;

    Ok(Some(backup_path))
}

fn cleanup_old_backups(backup_dir: &Path, original_path: &Path) -> SnipResult<()> {
    const MAX_BACKUPS_PER_LIBRARY: usize = 10;

    let file_stem = match original_path.file_stem() {
        Some(s) => s.to_string_lossy().to_string(),
        None => return Ok(()),
    };

    let prefix = format!("{file_stem}.");
    let mut backups: Vec<_> = fs::read_dir(backup_dir)
        .map_err(|e| SnipError::io_error("read backup directory", backup_dir.to_path_buf(), e))?
        .filter_map(|entry| entry.ok())
        .filter(|entry| {
            let name = entry.file_name().to_string_lossy().to_string();
            name.starts_with(&prefix) && name.ends_with(".toml.bak")
        })
        .filter_map(|entry| {
            let metadata = entry.metadata().ok()?;
            let modified = metadata.modified().ok()?;
            Some((entry.path(), modified))
        })
        .collect();

    backups.sort_by_key(|b| std::cmp::Reverse(b.1));

    if backups.len() > MAX_BACKUPS_PER_LIBRARY {
        for (path, _) in backups.into_iter().skip(MAX_BACKUPS_PER_LIBRARY) {
            if let Err(e) = fs::remove_file(&path) {
                tracing::warn!(
                    backup = %path.display(),
                    error = %e,
                    "Failed to remove old backup"
                );
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[cfg(unix)]
    fn file_mode(path: &Path) -> u32 {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(path).unwrap().permissions().mode() & 0o777
    }

    #[test]
    fn test_pet_format_compatibility() {
        let pet_toml = r#"
[[Snippets]]
  Description = "git commit with message"
  Command = "git commit -m \"message\""
  Tag = ["git", "version-control"]
  Output = ""

[[Snippets]]
  Description = "docker ps"
  Command = "docker ps"
  Tag = ["docker"]
  Output = ""
"#;
        let snippets: Snippets = toml::from_str(pet_toml).unwrap();
        assert_eq!(snippets.snippets.len(), 2);
        assert_eq!(snippets.snippets[0].command, "git commit -m \"message\"");
        assert_eq!(snippets.snippets[0].description, "git commit with message");
        assert_eq!(snippets.snippets[0].tags, vec!["git", "version-control"]);
        assert_eq!(snippets.snippets[1].command, "docker ps");
    }

    #[test]
    fn test_snp_format_compatibility() {
        let snp_toml = r#"
[[Snippets]]
  Description = "git commit"
  Output = ""
  Tag = ["git"]
  command = "git commit -m 'msg'"
"#;
        let snippets: Snippets = toml::from_str(snp_toml).unwrap();
        assert_eq!(snippets.snippets.len(), 1);
        assert_eq!(snippets.snippets[0].command, "git commit -m 'msg'");
    }

    #[test]
    fn test_library_save_load_roundtrip() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test_library.toml");

        let snippets = Snippets {
            snippets: vec![Snippet {
                id: "test-id-1".to_string(),
                description: "Test snippet".to_string(),
                command: "echo hello".to_string(),
                output: "".to_string(),
                tags: vec!["test".to_string()],
                folders: vec![],
                favorite: false,
                created_at: 1234567890,
                updated_at: 1234567890,
                device_id: "device1".to_string(),
                deleted: false,
            }],
            folders: vec!["work".to_string()],
        };

        save_library(&path, &snippets).unwrap();

        let loaded = load_library(&path).unwrap();

        assert_eq!(loaded.snippets.len(), 1);
        assert_eq!(loaded.snippets[0].description, "Test snippet");
        assert_eq!(loaded.snippets[0].command, "echo hello");
    }

    #[test]
    fn test_library_save_load_roundtrip_with_escaped_brackets() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test_library.toml");

        let snippets = Snippets {
            snippets: vec![Snippet {
                id: "test-id-1".to_string(),
                description: "Test with escaped brackets".to_string(),
                command: "ping \\<website\\>".to_string(),
                output: "".to_string(),
                tags: vec!["test".to_string()],
                folders: vec![],
                favorite: false,
                created_at: 1234567890,
                updated_at: 1234567890,
                device_id: "device1".to_string(),
                deleted: false,
            }],
            folders: vec![],
        };

        save_library(&path, &snippets).unwrap();

        let loaded = load_library(&path).unwrap();

        assert_eq!(loaded.snippets.len(), 1);
        assert_eq!(loaded.snippets[0].command, "ping \\<website\\>");
    }

    #[test]
    fn test_library_load_with_invalid_escapes() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("invalid_escapes.toml");

        std::fs::write(
            &path,
            r#"
[[Snippets]]
Id = "test-id"
Description = "Test snippet with invalid escapes"
Command = "sudo iptables-restore \< /path/to/rules"
"#,
        )
        .unwrap();

        let loaded = load_library(&path).unwrap();

        assert_eq!(loaded.snippets.len(), 1);
        assert_eq!(
            loaded.snippets[0].command,
            r"sudo iptables-restore \< /path/to/rules"
        );
    }

    #[test]
    fn test_library_load_empty_file() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("empty.toml");

        std::fs::write(&path, "").unwrap();

        let loaded = load_library(&path).unwrap();

        assert!(loaded.snippets.is_empty());
    }

    #[test]
    fn test_library_backup_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("nonexistent.toml");

        let backup_result = backup_library(&path).unwrap();

        assert!(backup_result.is_none());
    }

    #[test]
    fn test_snippet_serialization() {
        let snippet = Snippet {
            id: "test-id".to_string(),
            description: "Test description".to_string(),
            command: "echo test".to_string(),
            output: "test output".to_string(),
            tags: vec!["test".to_string()],
            folders: vec!["work".to_string()],
            favorite: true,
            created_at: 1234567890,
            updated_at: 1234567891,
            device_id: "device-1".to_string(),
            deleted: false,
        };

        let toml_str = toml::to_string_pretty(&snippet).unwrap();
        assert!(toml_str.contains("test-id"));
        assert!(toml_str.contains("Test description"));
        assert!(toml_str.contains("echo test"));
    }

    #[test]
    fn test_snippets_with_multiple_items() {
        let snippets = Snippets {
            snippets: vec![
                Snippet {
                    id: "id1".to_string(),
                    description: "First".to_string(),
                    command: "cmd1".to_string(),
                    output: "".to_string(),
                    tags: vec![],
                    folders: vec![],
                    favorite: false,
                    created_at: 0,
                    updated_at: 0,
                    device_id: "".to_string(),
                    deleted: false,
                },
                Snippet {
                    id: "id2".to_string(),
                    description: "Second".to_string(),
                    command: "cmd2".to_string(),
                    output: "".to_string(),
                    tags: vec![],
                    folders: vec![],
                    favorite: false,
                    created_at: 0,
                    updated_at: 0,
                    device_id: "".to_string(),
                    deleted: false,
                },
            ],
            folders: vec!["work".to_string()],
        };

        let toml_str = toml::to_string_pretty(&snippets).unwrap();
        assert!(toml_str.contains("id1"));
        assert!(toml_str.contains("id2"));
        assert!(toml_str.contains("work"));
    }

    #[test]
    fn test_library_manager_new() {
        let mgr = LibraryManager::new();
        // Should not panic - just verify it can be created
        assert!(mgr.is_ok() || mgr.is_err());
    }

    #[test]
    fn test_snippet_new_empty_command_fails() {
        let result = Snippet::new("desc".to_string(), "  ".to_string(), vec![]);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Empty command"));
    }

    #[test]
    fn test_snippet_new_empty_description_fails() {
        let result = Snippet::new("  ".to_string(), "echo hi".to_string(), vec![]);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Empty description")
        );
    }

    #[test]
    fn test_snippet_new_valid() {
        let result = Snippet::new(
            "desc".to_string(),
            "echo hi".to_string(),
            vec!["tag".to_string()],
        );
        assert!(result.is_ok());
        let s = result.unwrap();
        assert_eq!(s.description, "desc");
        assert_eq!(s.command, "echo hi");
    }

    #[test]
    fn test_validate_library_name_empty() {
        assert!(validate_library_name("").is_err());
    }

    #[test]
    fn test_validate_library_name_too_long() {
        assert!(validate_library_name(&"a".repeat(51)).is_err());
    }

    #[test]
    fn test_validate_library_name_slash() {
        assert!(validate_library_name("foo/bar").is_err());
    }

    #[test]
    fn test_validate_library_name_backslash() {
        assert!(validate_library_name("foo\\bar").is_err());
    }

    #[test]
    fn test_validate_library_name_null_byte() {
        assert!(validate_library_name("foo\0bar").is_err());
    }

    #[test]
    fn test_validate_library_name_dot() {
        assert!(validate_library_name(".").is_err());
        assert!(validate_library_name("..").is_err());
        assert!(validate_library_name("my..lib").is_err());
    }

    #[test]
    fn test_validate_library_name_valid() {
        assert!(validate_library_name("my-library").is_ok());
        assert!(validate_library_name("work snippets").is_ok());
    }

    #[test]
    fn test_save_library_atomic_write() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test.toml");
        let snippets = Snippets {
            snippets: vec![Snippet {
                id: "atomic-test".to_string(),
                description: "Atomic write test".to_string(),
                command: "echo atomic".to_string(),
                output: "".to_string(),
                tags: vec![],
                folders: vec![],
                favorite: false,
                created_at: 100,
                updated_at: 100,
                device_id: "d1".to_string(),
                deleted: false,
            }],
            folders: vec![],
        };
        save_library(&path, &snippets).unwrap();
        let loaded = load_library(&path).unwrap();
        assert_eq!(loaded.snippets.len(), 1);
        assert_eq!(loaded.snippets[0].id, "atomic-test");
        // Verify no .tmp files remain after atomic rename
        let parent = path.parent().unwrap();
        let has_tmp = std::fs::read_dir(parent)
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| e.path().extension().is_some_and(|ext| ext == "tmp"));
        assert!(!has_tmp, "temp files should not remain after atomic rename");
    }

    #[test]
    fn test_create_library_uses_private_atomic_write() {
        let temp_dir = TempDir::new().unwrap();
        let mut mgr = LibraryManager {
            config_dir: temp_dir.path().to_path_buf(),
            libraries_dir: temp_dir.path().join("libraries"),
            premade_dir: temp_dir.path().join("premade"),
            config: Default::default(),
        };

        let path = mgr.create_library("private").unwrap();

        assert!(path.exists());
        assert!(
            std::fs::read_to_string(&path)
                .unwrap()
                .contains("Snippets = []")
        );

        #[cfg(unix)]
        assert_eq!(file_mode(&path), 0o600);
    }

    #[test]
    fn test_add_server_library_uses_private_atomic_write() {
        let temp_dir = TempDir::new().unwrap();
        let mut mgr = LibraryManager {
            config_dir: temp_dir.path().to_path_buf(),
            libraries_dir: temp_dir.path().join("libraries"),
            premade_dir: temp_dir.path().join("premade"),
            config: Default::default(),
        };

        let path = mgr
            .add_server_library("Shared Commands", "server-library-id")
            .unwrap();

        assert!(path.exists());
        assert!(
            std::fs::read_to_string(&path)
                .unwrap()
                .contains("Imported from server")
        );

        #[cfg(unix)]
        assert_eq!(file_mode(&path), 0o600);
    }

    #[test]
    fn test_save_config_invalidates_libraries_toml_cache() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().to_path_buf();
        let libraries_dir = config_dir.join("libraries");
        let premade_dir = config_dir.join("premade");
        std::fs::create_dir_all(&libraries_dir).unwrap();

        let config_path = config_dir.join("libraries.toml");
        std::fs::write(
            &config_path,
            r#"
[[libraries]]
filename = "old"
library_id = ""
is_primary = true
"#,
        )
        .unwrap();
        let cached_before = cached_read_toml(&config_path).unwrap();
        assert!(cached_before.contains("old"));

        let mut mgr = LibraryManager {
            config_dir,
            libraries_dir,
            premade_dir,
            config: LibraryConfig {
                libraries: vec![LibraryMeta {
                    filename: "old".to_string(),
                    library_id: String::new(),
                    is_primary: true,
                    last_sync: None,
                    server_id: None,
                }],
            },
        };
        mgr.create_library("new").unwrap();

        let cached_after = cached_read_toml(&config_path).unwrap();
        assert!(cached_after.contains("old"));
        assert!(cached_after.contains("new"));
    }

    #[test]
    fn test_backup_library_names_do_not_collide() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("snippets.toml");
        std::fs::write(&path, "test content").unwrap();

        let first = backup_library(&path).unwrap().unwrap();
        let second = backup_library(&path).unwrap().unwrap();

        assert_ne!(first, second);

        let backup_dir = temp_dir.path().join("backups");
        let backup_count = std::fs::read_dir(backup_dir).unwrap().count();
        assert_eq!(backup_count, 2);
    }

    #[test]
    fn test_save_premade_library_path_traversal() {
        let temp_dir = TempDir::new().unwrap();
        let mgr = LibraryManager {
            config_dir: temp_dir.path().to_path_buf(),
            libraries_dir: temp_dir.path().join("libraries"),
            premade_dir: temp_dir.path().join("premade"),
            config: Default::default(),
        };
        assert!(
            mgr.save_premade_library("../../etc/passwd", "content")
                .is_err()
        );
        assert!(mgr.save_premade_library("../escape", "content").is_err());
        assert!(mgr.save_premade_library("foo/bar", "content").is_err());
    }

    #[test]
    fn test_save_premade_library_valid() {
        let temp_dir = TempDir::new().unwrap();
        let mgr = LibraryManager {
            config_dir: temp_dir.path().to_path_buf(),
            libraries_dir: temp_dir.path().join("libraries"),
            premade_dir: temp_dir.path().join("premade"),
            config: Default::default(),
        };
        let result = mgr.save_premade_library("valid-name", "test content");
        assert!(result.is_ok());
        let path = result.unwrap();
        assert!(path.exists());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "test content");

        #[cfg(unix)]
        assert_eq!(file_mode(&path), 0o600);
    }

    #[test]
    fn test_deduplication_on_load() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("dup.toml");
        let toml_content = r#"
[[Snippets]]
Id = "same-id"
Description = "First"
Command = "cmd1"

[[Snippets]]
Id = "same-id"
Description = "Second"
Command = "cmd2"
"#;
        std::fs::write(&path, toml_content).unwrap();
        let loaded = load_library(&path).unwrap();
        assert_eq!(loaded.snippets.len(), 2);
        assert_ne!(loaded.snippets[0].id, loaded.snippets[1].id);
    }
}