srcdmp 0.1.0-alpha.1

Amazing code snapshot tool and library
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
use time::{OffsetDateTime, format_description};

use crate::raw::error::SdmpError;
use crate::raw::header::{CODEC_C2, CODEC_C4, CODEC_SDMP7, CODEC_SDMP8};
use std::collections::HashMap;
use std::path::PathBuf;

/// The compression codec used when encoding a snapshot.
///
/// Each variant selects a different compression strategy with
/// varying trade-offs between speed, size, and character support.
///
/// # Variants
///
/// * [`Generic7`](Codec::Generic7) — SDMP-7 three-tier compression.
/// * [`Generic8`](Codec::Generic8) — Raw UTF-8 passthrough (no compression).
/// * [`Compact4`](Codec::Compact4) — Huffman-tree-based compression (SDMP-C4).
/// * [`Compact2`](Codec::Compact2) — Reserved for future use (SDMP-C2).
///
/// # Examples
///
/// ```rust
/// use srcdmp::Codec;
///
/// match Codec::Compact4 {
///     Codec::Compact4 => println!("using Huffman compression"),
///     _ => unreachable!(),
/// }
/// ```
pub enum Codec {
    /// SDMP-7 three-tier compression.
    Generic7,
    /// Raw UTF-8 passthrough.
    Generic8,
    /// Huffman-tree-based compression (SDMP-C4).
    Compact4,
    /// Reserved for future use (SDMP-C2).
    Compact2,
}

impl Codec {
    const fn to_byte(&self) -> u8 {
        match self {
            Self::Generic7 => CODEC_SDMP7,
            Self::Generic8 => CODEC_SDMP8,
            Self::Compact4 => CODEC_C4,
            Self::Compact2 => CODEC_C2,
        }
    }
}

/// Builder for constructing a [`Dump`] from a directory on disk.
///
/// Created via [`Dump::from_dir`]. Configure codec, ignore patterns,
/// and `.gitignore` respect before calling [`build`](DumpBuilder::build).
///
/// # Examples
///
/// ```no_run
/// use srcdmp::{Codec, Dump};
///
/// let builder = Dump::from_dir("my_project")
///     .codec(Codec::Compact4)
///     .gitignore()
///     .ignore("target/**")
///     .ignore("*.log");
///
/// let dump = builder.build().expect("failed to build snapshot");
/// ```
pub struct DumpBuilder {
    directory: PathBuf,
    codec: Codec,
    ignores: Vec<String>,
    use_gitignore: bool,
}

impl DumpBuilder {
    /// Set the compression codec for this snapshot.
    ///
    /// Defaults to [`Codec::Compact4`] if not called.
    #[must_use]
    pub const fn codec(mut self, codec: Codec) -> Self {
        self.codec = codec;
        self
    }

    /// Add a glob pattern to exclude files matching this pattern.
    ///
    /// Patterns are matched against the relative path from the source directory.
    #[must_use]
    pub fn ignore(mut self, pattern: &str) -> Self {
        self.ignores.push(pattern.to_string());
        self
    }

    /// Respect `.gitignore` rules when walking the source directory.
    #[must_use]
    pub const fn gitignore(mut self) -> Self {
        self.use_gitignore = true;
        self
    }

    /// Walk the source directory, encode all matching files, and produce a [`Dump`].
    ///
    /// Skips binary files (those containing a null byte within the first 8000 bytes)
    /// and files containing the annotation `@srcdmp:ignore` in their first 512 bytes.
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::IoError`] if files cannot be read.
    /// Returns [`SdmpError::InvalidUtf8`] if a file is not valid UTF-8.
    pub fn build(self) -> Result<Dump, SdmpError> {
        use ignore::WalkBuilder;

        let mut files = Vec::new();
        let mut original_size = 0u32;

        let mut walker = WalkBuilder::new(&self.directory);

        walker.git_ignore(self.use_gitignore);

        for result in walker.build() {
            let entry =
                result.map_err(|e| SdmpError::IoError(std::io::Error::other(e.to_string())))?;

            if !entry.path().is_file() {
                continue;
            }

            let content = std::fs::read(entry.path())?;

            if is_binary(&content) {
                continue;
            }

            let relative = entry
                .path()
                .strip_prefix(&self.directory)
                .unwrap()
                .to_string_lossy()
                .to_string();

            if self.ignores.iter().any(|pat| glob_match(pat, &relative)) {
                continue;
            }

            if has_annotation(&content, b"@srcdmp:ignore") {
                continue;
            }

            let _force = has_annotation(&content, b"@srcdmp:force");

            let text = String::from_utf8(content).map_err(|_| SdmpError::InvalidUtf8)?;

            original_size += text.len() as u32;
            let encoded = match self.codec.to_byte() {
                crate::raw::header::CODEC_SDMP8 => crate::raw::codec::sdmp8::encode(&text),
                crate::raw::header::CODEC_SDMP7 => crate::raw::codec::sdmp7::encode(&text),
                _ => crate::raw::codec::sdmpc4::encode(&text),
            };
            files.push((relative, encoded));
        }

        Ok(Dump {
            files,
            codec: self.codec.to_byte(),
            original_size,
        })
    }
}

/// A compressed snapshot of a source directory.
///
/// Contains the encoded file data, the codec used, and the total
/// uncompressed size. Created via [`DumpBuilder::build`] or by
/// opening an existing `.srcdmp` file with [`Dump::open`].
///
/// # Examples
///
/// ```no_run
/// use srcdmp::Dump;
///
/// let dump = Dump::open("snapshot.srcdmp").expect("failed to open");
/// println!("codec: {}", dump.codec_name());
/// println!("files: {}", dump.file_count());
/// ```
pub struct Dump {
    pub(crate) files: Vec<(String, Vec<u8>)>,
    pub(crate) codec: u8,
    pub(crate) original_size: u32,
}

impl Dump {
    fn decode_file(&self, encoded: &[u8]) -> Result<String, SdmpError> {
        match self.codec {
            crate::raw::header::CODEC_SDMP7 => crate::raw::codec::sdmp7::decode(encoded),
            crate::raw::header::CODEC_SDMP8 => crate::raw::codec::sdmp8::decode(encoded),
            crate::raw::header::CODEC_C4 => crate::raw::codec::sdmpc4::decode(encoded),
            _ => Err(SdmpError::UnknownCodec(self.codec)),
        }
    }

    /// Return an iterator over the file paths stored in this snapshot.
    #[must_use]
    pub fn files(&self) -> impl Iterator<Item = &str> {
        self.files.iter().map(|(path, _)| path.as_str())
    }

    /// Return the human-readable name of the codec used for this snapshot.
    #[must_use]
    pub const fn codec_name(&self) -> &'static str {
        match self.codec {
            crate::raw::header::CODEC_SDMP7 => "SDMP-7",
            crate::raw::header::CODEC_SDMP8 => "SDMP-8",
            crate::raw::header::CODEC_C4 => "SDMP-C4",
            crate::raw::header::CODEC_C2 => "SDMP-C2",
            _ => "unknown",
        }
    }

    /// Create a [`DumpBuilder`] that reads files from the given directory path.
    ///
    /// The builder defaults to [`Codec::Compact4`] compression and does
    /// not respect `.gitignore` until [`gitignore`](DumpBuilder::gitignore) is called.
    #[must_use]
    pub fn from_dir(path: &str) -> DumpBuilder {
        DumpBuilder {
            directory: PathBuf::from(path),
            codec: Codec::Compact4,
            ignores: Vec::new(),
            use_gitignore: false,
        }
    }

    /// Open and parse an existing `.srcdmp` file from disk.
    ///
    /// Reads the entire file into memory, parses the header, and loads
    /// all file entries (but does not decode file content until
    /// [`unpack`](Dump::unpack) is called).
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::NotAnSdmpFile`] if the file does not start
    /// with the SDMP magic bytes.
    /// Returns [`SdmpError::UnknownCodec`] if the codec ID is unrecognized.
    /// Returns [`SdmpError::UnexpectedEof`] if the file is truncated.
    /// Returns [`SdmpError::IoError`] for underlying I/O failures.
    pub fn open(path: &str) -> Result<Self, SdmpError> {
        use crate::raw::entry::Entry;
        use crate::raw::header::Header;

        let data = std::fs::read(path)?;
        let header = Header::read(&data)?;

        let mut files = Vec::new();
        let mut i = Header::SIZE;

        for _ in 0..header.file_count {
            let (entry, consumed) = Entry::read(&data[i..])?;
            i += consumed;

            let end = i + entry.file_size as usize;
            if end > data.len() {
                return Err(SdmpError::UnexpectedEof);
            }

            let encoded = data[i..end].to_vec();
            i = end;

            files.push((entry.path, encoded));
        }

        Ok(Self {
            files,
            codec: header.codec,
            original_size: header.original_size,
        })
    }

    /// Return the number of files stored in this snapshot.
    #[must_use]
    pub const fn file_count(&self) -> usize {
        self.files.len()
    }

    /// Return the total uncompressed size of all file content in bytes.
    #[must_use]
    pub const fn original_size(&self) -> u32 {
        self.original_size
    }

    /// Write the snapshot to a `.srcdmp` file on disk.
    ///
    /// Serializes the header, all file entries, and their encoded content
    /// into a single file at the given path.
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::IoError`] if the file cannot be written.
    pub fn write(&self, path: &str) -> Result<(), SdmpError> {
        use crate::raw::entry::Entry;
        use crate::raw::header::Header;

        let mut body = Vec::new();

        for (file_path, encoded) in &self.files {
            let entry = Entry {
                path: file_path.clone(),
                file_size: encoded.len() as u32,
            };
            entry.write(&mut body);
            body.extend_from_slice(encoded);
        }

        let header = Header {
            codec: self.codec,
            version: 1,
            original_size: self.original_size,
            file_count: self.files.len() as u32,
        };

        let mut file = Vec::new();
        file.extend_from_slice(&header.write());
        file.extend_from_slice(&body);

        std::fs::write(path, file)?;
        Ok(())
    }

    /// Create a [`DumpWriteBuilder`] with a custom snapshot name.
    ///
    /// The resulting file will be named
    /// `{date}-{name}-{version}.srcdmp`.
    #[must_use]
    pub fn named(&self, name: &str) -> DumpWriteBuilder<'_> {
        DumpWriteBuilder {
            dump: self,
            name: name.to_string(),
            version: None,
        }
    }

    /// Create a [`DumpWriteBuilder`] with name and version extracted from `Cargo.toml`.
    ///
    /// Reads `Cargo.toml` in the current directory to determine the
    /// package name and version. Falls back to `"unnamed"` and `"0.1.0"`
    /// if the file cannot be parsed.
    #[must_use]
    pub fn from_cargo(&self) -> DumpWriteBuilder<'_> {
        let cargo = std::fs::read_to_string("Cargo.toml")
            .ok()
            .and_then(|s| s.parse::<toml::Table>().ok());

        let name = cargo
            .as_ref()
            .and_then(|t| t.get("package"))
            .and_then(|p| p.as_table())
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
            .unwrap_or("unnamed")
            .to_string();

        let version = cargo
            .as_ref()
            .and_then(|t| t.get("package"))
            .and_then(|p| p.as_table())
            .and_then(|p| p.get("version"))
            .and_then(|v| v.as_str())
            .unwrap_or("0.1.0")
            .to_string();

        DumpWriteBuilder {
            dump: self,
            name,
            version: Some(version),
        }
    }

    /// Decode all stored files and return them as a map of path → content.
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::InvalidUtf8`] if decoded content is not valid UTF-8,
    /// [`SdmpError::UnknownCodec`] if the codec ID is unrecognized,
    /// or [`SdmpError::UnexpectedEof`] if encoded data is truncated.
    pub fn unpack(&self) -> Result<HashMap<String, String>, SdmpError> {
        let mut map = HashMap::new();
        for (path, encoded) in &self.files {
            let content = self.decode_file(encoded)?;
            map.insert(path.clone(), content);
        }
        Ok(map)
    }

    /// Decode and write all stored files into the given directory.
    ///
    /// Creates parent directories as needed. Existing files will be
    /// overwritten.
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::IoError`] if files cannot be written.
    /// Returns [`SdmpError::InvalidUtf8`] if decoded content is not valid UTF-8.
    /// Returns [`SdmpError::UnknownCodec`] if the codec ID is unrecognized.
    pub fn unpack_to(&self, dir: &str) -> Result<(), SdmpError> {
        for (path, encoded) in &self.files {
            let content = self.decode_file(encoded)?;
            let full_path = std::path::Path::new(dir).join(path);

            if let Some(parent) = full_path.parent() {
                std::fs::create_dir_all(parent)?;
            }

            std::fs::write(full_path, content)?;
        }
        Ok(())
    }

    /// Decode the snapshot and write a human-readable log file.
    ///
    /// The log begins with a manifest section (codec, file count,
    /// original size), followed by each file's decoded content
    /// delimited by `===> {path}` and `===> EOF` markers.
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::IoError`] if the log file cannot be written.
    /// Returns [`SdmpError::InvalidUtf8`] if decoded content is not valid UTF-8.
    /// Returns [`SdmpError::UnknownCodec`] if the codec ID is unrecognized.
    pub fn to_log(&self, path: &str) -> Result<(), SdmpError> {
        use std::fmt::Write as FmtWrite;
        let mut log = String::new();

        writeln!(log, "===> MANIFEST <===").unwrap();
        writeln!(log, "codec: {}", self.codec).unwrap();
        writeln!(log, "files: {}", self.files.len()).unwrap();
        writeln!(log, "original_size: {}", self.original_size).unwrap();

        for (file_path, encoded) in &self.files {
            let content = self.decode_file(encoded)?;
            writeln!(log, "\n===> {file_path}").unwrap();
            log.push_str(&content);
            writeln!(log, "===> EOF").unwrap();
        }

        std::fs::write(path, log)?;
        Ok(())
    }
}

/// Builder for writing a [`Dump`] to a date-stamped filename.
///
/// Created via [`Dump::named`] or [`Dump::from_cargo`]. Produces
/// filenames of the form `{date}-{name}-{version}.srcdmp`.
///
/// # Examples
///
/// ```no_run
/// use srcdmp::Dump;
///
/// let dump = Dump::open("old.srcdmp").expect("failed to open");
/// dump.named("my-project")
///     .version("1.0.0")
///     .write_to("output/")
///     .expect("failed to write");
/// ```
pub struct DumpWriteBuilder<'a> {
    dump: &'a Dump,
    name: String,
    version: Option<String>,
}

impl DumpWriteBuilder<'_> {
    /// Override the version string used in the output filename.
    ///
    /// If not called, the version defaults to `"0.1.0"`.
    #[must_use]
    pub fn version(mut self, version: &str) -> Self {
        self.version = Some(version.to_string());
        self
    }

    /// Write the snapshot to `{date}-{name}-{version}.srcdmp`
    /// in the current directory.
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::IoError`] if the file cannot be written.
    pub fn write(self) -> Result<(), SdmpError> {
        let version = self.version.unwrap_or("0.1.0".to_string());

        let format = format_description::parse("[year]-[month]-[day]").unwrap();
        let date = OffsetDateTime::now_local()
            .unwrap_or(OffsetDateTime::now_utc())
            .format(&format)
            .unwrap();

        let filename = format!("{}-{}-{}.srcdmp", date, self.name, version);
        self.dump.write(&filename)
    }

    /// Write the snapshot to `{dir}/{date}-{name}-{version}.srcdmp`.
    ///
    /// # Errors
    ///
    /// Returns [`SdmpError::IoError`] if the file cannot be written.
    pub fn write_to(self, dir: &str) -> Result<(), SdmpError> {
        let version = self.version.unwrap_or("0.1.0".to_string());
        let format = time::format_description::parse("[year]-[month]-[day]").unwrap();
        let date = time::OffsetDateTime::now_local()
            .unwrap_or(time::OffsetDateTime::now_utc())
            .format(&format)
            .unwrap();
        let filename = format!("{}/{}-{}-{}.srcdmp", dir, date, self.name, version);
        self.dump.write(&filename)
    }
}

// helpers

fn is_binary(content: &[u8]) -> bool {
    content.iter().take(8000).any(|&b| b == 0x00)
}

fn has_annotation(content: &[u8], annotation: &[u8]) -> bool {
    let search_area = &content[..content.len().min(512)];
    search_area
        .windows(annotation.len())
        .any(|w| w == annotation)
}

fn glob_match(pattern: &str, path: &str) -> bool {
    glob::Pattern::new(pattern)
        .map(|p| p.matches(path))
        .unwrap_or(false)
}