drip-cli 0.1.1

Delta Read Interception Proxy — sends only file diffs to your LLM agent
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
//! `.dripignore` matcher — gitignore-flavored patterns applied to file
//! reads and Grep/Glob results.
//!
//! Lookup order: `$DRIP_IGNORE_FILE` → `./.dripignore` → `~/.dripignore`
//! → built-in defaults.
//!
//! Patterns: one glob per line, `#` for comments, leading `!` negates,
//! `**` matches any number of components. Not 100% gitignore-compatible
//! — anchored vs. unanchored corner cases aren't covered.

use anyhow::{Context, Result};
use globset::{Glob, GlobSet, GlobSetBuilder};
use std::path::Path;

/// Default ignore set — kept tight on purpose: false positives break
/// workflows, false negatives just mean a missed save.
const DEFAULTS: &[&str] = &[
    // VCS and editor noise
    ".git/**",
    ".hg/**",
    ".svn/**",
    ".DS_Store",
    "**/.DS_Store",
    // Dependency directories
    "node_modules/**",
    "**/node_modules/**",
    "vendor/**",
    ".venv/**",
    "venv/**",
    "__pycache__/**",
    "**/__pycache__/**",
    // Build outputs
    "target/**",
    "dist/**",
    "build/**",
    ".next/**",
    ".turbo/**",
    ".svelte-kit/**",
    "out/**",
    // Lock files (huge, agent rarely needs full content)
    "package-lock.json",
    "yarn.lock",
    "pnpm-lock.yaml",
    "bun.lockb",
    "Cargo.lock",
    "Gemfile.lock",
    "poetry.lock",
    "uv.lock",
    "composer.lock",
    // Common binary asset extensions
    "*.png",
    "*.jpg",
    "*.jpeg",
    "*.gif",
    "*.webp",
    "*.ico",
    "*.bmp",
    "*.pdf",
    "*.zip",
    "*.tar",
    "*.gz",
    "*.tgz",
    "*.bz2",
    "*.7z",
    "*.so",
    "*.dylib",
    "*.dll",
    "*.a",
    "*.o",
    "*.exe",
    "*.woff",
    "*.woff2",
    "*.ttf",
    "*.eot",
    "*.otf",
    "*.mp4",
    "*.mov",
    "*.webm",
    "*.mp3",
    "*.wav",
    // Secrets & credentials. `file_registry` persists across sessions
    // until `drip registry gc`, so a single brush with `.env` would
    // bake the content into a long-lived DB row that backup tools
    // could carry off-host.
    ".env",
    ".env.*",
    "**/.env",
    "**/.env.*",
    "*.pem",
    "*.key",
    "*.p12",
    "*.pfx",
    "*.crt",
    "*.cer",
    "*.jks",
    "*.keystore",
    "id_rsa",
    "id_rsa.pub",
    "id_dsa",
    "id_ecdsa",
    "id_ed25519",
    "id_ed25519.pub",
    "**/id_rsa",
    "**/id_rsa.pub",
    "**/id_dsa",
    "**/id_ecdsa",
    "**/id_ed25519",
    "**/id_ed25519.pub",
    "**/.ssh/**",
    "**/.aws/credentials",
    "**/.aws/config",
    "**/.gcp/credentials.json",
    ".netrc",
    "**/.netrc",
    ".npmrc",
    "**/.npmrc",
    ".pypirc",
    "**/.pypirc",
    "kubeconfig",
    "*.kubeconfig",
    "**/kubeconfig",
];

#[derive(Debug)]
pub struct Matcher {
    /// Patterns that mark a path as ignored.
    deny: GlobSet,
    /// Patterns that re-include an otherwise-ignored path (`!foo`).
    allow: GlobSet,
}

impl Matcher {
    /// Load + combine from all four lookup locations. Missing files
    /// contribute nothing; malformed lines log via `eprintln!`.
    pub fn load() -> Self {
        Self::load_with_root(None)
    }

    /// Load with an explicit project root — used by `drip watch` when
    /// cwd is elsewhere.
    pub fn load_with_root(root: Option<&Path>) -> Self {
        let mut deny = GlobSetBuilder::new();
        let mut allow = GlobSetBuilder::new();

        // Defaults first — overridable by user files via `!pattern`.
        for raw in DEFAULTS {
            push_pattern(&mut deny, &mut allow, raw);
        }

        for path in lookup_files(root) {
            if let Some(text) = read_dripignore_capped(&path) {
                for line in text.lines() {
                    let line = line.trim();
                    if line.is_empty() || line.starts_with('#') {
                        continue;
                    }
                    push_pattern(&mut deny, &mut allow, line);
                }
            }
        }

        let deny = deny.build().unwrap_or_else(|_| empty_set());
        let allow = allow.build().unwrap_or_else(|_| empty_set());
        Matcher { deny, allow }
    }

    /// Loaded directly from a string — for tests and `--ignore-file=-`.
    #[allow(dead_code)]
    pub fn from_str(text: &str) -> Result<Self> {
        let mut deny = GlobSetBuilder::new();
        let mut allow = GlobSetBuilder::new();
        for raw in DEFAULTS {
            push_pattern(&mut deny, &mut allow, raw);
        }
        for line in text.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            push_pattern(&mut deny, &mut allow, line);
        }
        Ok(Matcher {
            deny: deny.build().context("building deny globset")?,
            allow: allow.build().context("building allow globset")?,
        })
    }

    /// Match against the full path, the file name alone, and a
    /// `./`-stripped variant — so `package-lock.json` matches
    /// regardless of how the agent spelled the path.
    pub fn is_ignored(&self, path: &Path) -> bool {
        let denied = self.matches_path(path, &self.deny);
        if !denied {
            return false;
        }
        !self.matches_path(path, &self.allow)
    }

    fn matches_path(&self, path: &Path, set: &GlobSet) -> bool {
        if set.is_match(path) {
            return true;
        }
        if let Some(name) = path.file_name() {
            if set.is_match(Path::new(name)) {
                return true;
            }
        }
        if let Some(s) = path.to_str() {
            if let Some(stripped) = s.strip_prefix("./") {
                if set.is_match(Path::new(stripped)) {
                    return true;
                }
            }
        }
        false
    }
}

fn push_pattern(deny: &mut GlobSetBuilder, allow: &mut GlobSetBuilder, raw: &str) {
    let (negated, body) = match raw.strip_prefix('!') {
        Some(rest) => (true, rest),
        None => (false, raw),
    };
    // Expand `dir/` → `dir/**`; `globset` doesn't accept a bare
    // trailing slash, and the descendant form is what matters in
    // practice (DRIP only sees file paths).
    let body = canonicalize_dir_pattern(body);
    let g = match Glob::new(&body) {
        Ok(g) => g,
        Err(e) => {
            eprintln!("drip: ignoring malformed .dripignore pattern {raw:?}: {e}");
            return;
        }
    };
    if negated {
        allow.add(g);
    } else {
        deny.add(g);
    }
}

/// Apply the gitignore "trailing slash = directory + descendants" rule.
/// Returns the input unchanged when the pattern doesn't end with `/`,
/// or already targets a recursive descendant (`/**`, `/**/...`).
fn canonicalize_dir_pattern(body: &str) -> String {
    if !body.ends_with('/') {
        return body.to_string();
    }
    // Already-explicit recursive forms — leave alone. We strip the
    let trimmed = body.trim_end_matches('/');
    if trimmed.ends_with("/**") || trimmed == "**" {
        return trimmed.to_string();
    }
    // Single `**` covers both immediate children and arbitrary depth.
    format!("{trimmed}/**")
}

fn lookup_files(root: Option<&Path>) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    if let Ok(p) = std::env::var("DRIP_IGNORE_FILE") {
        out.push(std::path::PathBuf::from(p));
    }
    // Project root before cwd — the watcher's watched path beats its
    // own cwd.
    if let Some(r) = root {
        out.push(r.join(".dripignore"));
    }
    if let Ok(cwd) = std::env::current_dir() {
        let candidate = cwd.join(".dripignore");
        if !out.contains(&candidate) {
            out.push(candidate);
        }
    }
    if let Some(home) = dirs::home_dir() {
        out.push(home.join(".dripignore"));
    }
    out
}

fn empty_set() -> GlobSet {
    GlobSetBuilder::new()
        .build()
        .expect("empty globset always builds")
}

/// Hard byte cap on `.dripignore` reads — defends against a multi-GB
/// file from a redirect typo. 256 KiB is generous (the linux kernel's
/// `.gitignore` is ~2 KB).
const DRIPIGNORE_CAP: u64 = 256 * 1024;

fn read_dripignore_capped(path: &Path) -> Option<String> {
    use std::io::Read;
    let f = std::fs::File::open(path).ok()?;
    let mut buf = String::new();
    f.take(DRIPIGNORE_CAP).read_to_string(&mut buf).ok()?;
    Some(buf)
}

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

    #[test]
    fn defaults_match_node_modules() {
        let m = Matcher::from_str("").unwrap();
        assert!(m.is_ignored(Path::new("node_modules/foo/bar.js")));
        assert!(m.is_ignored(Path::new("project/node_modules/x.js")));
    }

    #[test]
    fn defaults_match_lock_files() {
        let m = Matcher::from_str("").unwrap();
        assert!(m.is_ignored(Path::new("package-lock.json")));
        assert!(m.is_ignored(Path::new("/abs/path/Cargo.lock")));
        assert!(m.is_ignored(Path::new("./yarn.lock")));
    }

    #[test]
    fn user_pattern_adds_to_defaults() {
        let m = Matcher::from_str("secrets/*.txt\n").unwrap();
        assert!(m.is_ignored(Path::new("secrets/foo.txt")));
        assert!(!m.is_ignored(Path::new("src/main.rs")));
    }

    #[test]
    fn negation_re_includes() {
        let m = Matcher::from_str("!Cargo.lock\n").unwrap();
        assert!(!m.is_ignored(Path::new("Cargo.lock")));
        // Other defaults still apply.
        assert!(m.is_ignored(Path::new("yarn.lock")));
    }

    #[test]
    fn comments_and_blanks_skipped() {
        let m = Matcher::from_str("# comment\n\n  \nsecrets/*\n").unwrap();
        assert!(m.is_ignored(Path::new("secrets/x")));
    }

    #[test]
    fn malformed_pattern_does_not_panic() {
        let _ = Matcher::from_str("[unclosed\n").unwrap();
    }

    // ── gitignore trailing-slash semantics ──────────────────────────

    #[test]
    fn trailing_slash_matches_immediate_children() {
        let m = Matcher::from_str("playground/\n").unwrap();
        assert!(
            m.is_ignored(Path::new("playground/foo.txt")),
            "`playground/` must ignore immediate file children",
        );
    }

    #[test]
    fn trailing_slash_matches_arbitrary_depth() {
        let m = Matcher::from_str("playground/\n").unwrap();
        assert!(
            m.is_ignored(Path::new("playground/a/b.txt")),
            "`playground/` must ignore deeply-nested descendants",
        );
        assert!(
            m.is_ignored(Path::new("playground/a/b/c/d.rs")),
            "`playground/` must recurse arbitrarily",
        );
    }

    #[test]
    fn trailing_slash_does_not_leak_to_siblings() {
        let m = Matcher::from_str("playground/\n").unwrap();
        // `playgroundlol/foo` shares a prefix but not a path component
        // boundary — must NOT be ignored.
        assert!(!m.is_ignored(Path::new("playgroundlol/foo.txt")));
        assert!(!m.is_ignored(Path::new("not-playground/foo.txt")));
    }

    #[test]
    fn explicit_double_star_still_works_unchanged() {
        // The expansion is idempotent: `playground/**` written by the
        // user must keep working exactly as before, not become
        // `playground/**/**`.
        let m = Matcher::from_str("playground/**\n").unwrap();
        assert!(m.is_ignored(Path::new("playground/foo.txt")));
        assert!(m.is_ignored(Path::new("playground/a/b.txt")));
    }

    #[test]
    fn trailing_slash_negation_re_includes_descendants() {
        // `playground/` ignores everything inside; `!playground/keep.js`
        // re-includes one specific descendant. Both halves of the rule
        // must keep working post-expansion.
        let m = Matcher::from_str("playground/\n!playground/keep.js\n").unwrap();
        assert!(m.is_ignored(Path::new("playground/foo.txt")));
        assert!(!m.is_ignored(Path::new("playground/keep.js")));
    }

    #[test]
    fn canonicalize_dir_pattern_helper() {
        assert_eq!(canonicalize_dir_pattern("playground/"), "playground/**");
        assert_eq!(canonicalize_dir_pattern("a/b/"), "a/b/**");
        // No trailing slash → unchanged.
        assert_eq!(canonicalize_dir_pattern("playground"), "playground");
        // Already recursive → stripped trailing slash but no double
        // star duplication.
        assert_eq!(canonicalize_dir_pattern("playground/**"), "playground/**");
        assert_eq!(canonicalize_dir_pattern("playground/**/"), "playground/**");
    }
}