omni-dev 0.41.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
//! CLI command for `omni-dev drive dedupe`.

use std::collections::BTreeMap;
use std::io::Write;

use anyhow::{Context, Result};
use clap::Parser;
use serde::Serialize;

use crate::cli::drive::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::drive::client::DriveClient;
use crate::drive::files_api::{FilesApi, DEFAULT_SEARCH_LIMIT};
use crate::drive::types::DriveFile;

/// Finds Drive files sharing the same content hash.
///
/// Reuses the same bulk search path as `drive search` — `files.list`
/// already returns full metadata (including `md5Checksum`) per hit, so
/// duplicate detection needs no per-file follow-up call.
#[derive(Parser)]
pub struct DedupeCommand {
    /// Drive search query, passed verbatim to `files.list`'s `q` parameter
    /// (e.g. `'<folder-id>' in parents` to dedupe within one folder).
    pub query: String,

    /// Maximum results to scan. `0` means "scan every match" (capped at a
    /// hard ceiling to bound run time).
    #[arg(long, default_value_t = DEFAULT_SEARCH_LIMIT)]
    pub limit: usize,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl DedupeCommand {
    /// Runs the command against the shared client resolved by the parent
    /// `DriveCommand::execute`.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_dedupe(client, &self.query, self.limit, &self.output).await
    }
}

/// A group of files sharing the same `md5Checksum`.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct DuplicateGroup {
    /// The shared MD5 checksum.
    pub(crate) checksum: String,
    /// The files sharing it (always 2 or more).
    pub(crate) files: Vec<DriveFile>,
}

/// Groups `files` by `md5_checksum`, keeping only groups with 2 or more
/// members. Files with no checksum (folders, Google-native documents) are
/// skipped — md5 is used rather than sha1/sha256 since it has the broadest
/// coverage across Drive files.
///
/// Grouped via a `BTreeMap` rather than a `HashMap` so both table output
/// and callers get deterministic, checksum-sorted ordering.
pub(crate) fn group_duplicates(files: &[DriveFile]) -> Vec<DuplicateGroup> {
    let mut groups: BTreeMap<String, Vec<DriveFile>> = BTreeMap::new();
    for file in files {
        if let Some(checksum) = &file.md5_checksum {
            groups
                .entry(checksum.clone())
                .or_default()
                .push(file.clone());
        }
    }
    groups
        .into_iter()
        .filter(|(_, files)| files.len() >= 2)
        .map(|(checksum, files)| DuplicateGroup { checksum, files })
        .collect()
}

/// Fetches search results, groups them by content hash, and emits
/// duplicates in the requested format.
///
/// Split from [`DedupeCommand::execute`] so tests can inject a wiremock
/// client without going through the credential-loading path.
async fn run_dedupe(
    client: &DriveClient,
    query: &str,
    limit: usize,
    output: &OutputFormat,
) -> Result<()> {
    let list = FilesApi::new(client).search_all(Some(query), limit).await?;
    let groups = group_duplicates(&list.files);
    if output_as(&groups, output)? {
        return Ok(());
    }
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    render_dedupe_table(&groups, &mut handle)
}

/// Renders duplicate groups as an aligned text table.
///
/// Column layout: `HASH | COUNT | FILES`, with `FILES` a comma-joined list
/// of `name (id)` (left unpadded — its length is unbounded, unlike the
/// other two columns). An empty input prints `No duplicate files found.`.
fn render_dedupe_table(groups: &[DuplicateGroup], out: &mut dyn Write) -> Result<()> {
    if groups.is_empty() {
        writeln!(out, "No duplicate files found.")
            .context("Failed to write empty-table message")?;
        return Ok(());
    }

    // Sanitize server-supplied strings *before* computing column widths,
    // matching `render_search_table`'s precedent (#1537).
    let rows: Vec<(String, String, String)> = groups
        .iter()
        .map(|g| {
            let files = g
                .files
                .iter()
                .map(|f| {
                    format!(
                        "{} ({})",
                        sanitize_for_terminal(&f.name),
                        sanitize_for_terminal(&f.id)
                    )
                })
                .collect::<Vec<_>>()
                .join(", ");
            (
                sanitize_for_terminal(&g.checksum),
                g.files.len().to_string(),
                files,
            )
        })
        .collect();

    let hash_width = "HASH"
        .len()
        .max(rows.iter().map(|r| r.0.len()).max().unwrap_or(0));
    let count_width = "COUNT"
        .len()
        .max(rows.iter().map(|r| r.1.len()).max().unwrap_or(0));

    writeln!(
        out,
        "{:<hash_width$}  {:<count_width$}  FILES",
        "HASH", "COUNT"
    )
    .context("Failed to write dedupe row")?;
    for (hash, count, files) in &rows {
        writeln!(out, "{hash:<hash_width$}  {count:<count_width$}  {files}")
            .context("Failed to write dedupe row")?;
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveScope};
    use crate::utils::secret::Secret;

    fn test_credentials() -> DriveCredentials {
        DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveScope::ReadOnly,
        }
    }

    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> DriveClient {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "test-token",
                    "expires_in": 3600,
                })),
            )
            .mount(server)
            .await;

        let mut client = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut client,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        client
    }

    fn file_with_checksum(id: &str, checksum: Option<&str>) -> DriveFile {
        DriveFile {
            id: id.to_string(),
            name: format!("{id}.pdf"),
            mime_type: "application/pdf".to_string(),
            md5_checksum: checksum.map(str::to_string),
            ..Default::default()
        }
    }

    // ── group_duplicates ────────────────────────────────────────────

    #[test]
    fn group_duplicates_returns_empty_for_no_duplicates() {
        let files = [
            file_with_checksum("f1", Some("hash-a")),
            file_with_checksum("f2", Some("hash-b")),
        ];
        assert!(group_duplicates(&files).is_empty());
    }

    #[test]
    fn group_duplicates_groups_files_sharing_checksum() {
        let files = [
            file_with_checksum("f1", Some("hash-a")),
            file_with_checksum("f2", Some("hash-b")),
            file_with_checksum("f3", Some("hash-a")),
        ];
        let groups = group_duplicates(&files);
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].checksum, "hash-a");
        assert_eq!(groups[0].files.len(), 2);
        assert_eq!(groups[0].files[0].id, "f1");
        assert_eq!(groups[0].files[1].id, "f3");
    }

    #[test]
    fn group_duplicates_skips_files_with_no_checksum() {
        let files = [
            file_with_checksum("f1", None),
            file_with_checksum("f2", None),
        ];
        assert!(group_duplicates(&files).is_empty());
    }

    #[test]
    fn group_duplicates_orders_groups_by_checksum() {
        let files = [
            file_with_checksum("f1", Some("hash-z")),
            file_with_checksum("f2", Some("hash-z")),
            file_with_checksum("f3", Some("hash-a")),
            file_with_checksum("f4", Some("hash-a")),
        ];
        let groups = group_duplicates(&files);
        let checksums: Vec<&str> = groups.iter().map(|g| g.checksum.as_str()).collect();
        assert_eq!(checksums, vec!["hash-a", "hash-z"]);
    }

    // ── render_dedupe_table ─────────────────────────────────────────

    #[test]
    fn render_table_empty_prints_message() {
        let mut buf = Vec::new();
        render_dedupe_table(&[], &mut buf).unwrap();
        assert_eq!(
            String::from_utf8(buf).unwrap(),
            "No duplicate files found.\n"
        );
    }

    #[test]
    fn render_table_writes_header_and_grouped_files() {
        let groups = group_duplicates(&[
            file_with_checksum("f1", Some("hash-a")),
            file_with_checksum("f2", Some("hash-a")),
        ]);
        let mut buf = Vec::new();
        render_dedupe_table(&groups, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("HASH"));
        assert!(out.contains("COUNT"));
        assert!(out.contains("FILES"));
        assert!(out.contains("hash-a"));
        assert!(out.contains("f1.pdf (f1)"));
        assert!(out.contains("f2.pdf (f2)"));
        assert_eq!(out.lines().count(), 2);
    }

    #[test]
    fn render_table_strips_control_bytes_from_server_strings() {
        let groups = vec![DuplicateGroup {
            checksum: "hash\x1b[31ma".to_string(),
            files: vec![
                DriveFile {
                    id: "f1".to_string(),
                    name: "evil\x1b[31mname".to_string(),
                    ..Default::default()
                },
                file_with_checksum("f2", Some("hash-a")),
            ],
        }];
        let mut buf = Vec::new();
        render_dedupe_table(&groups, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            !out.contains(|c: char| c.is_control() && c != '\n'),
            "{out:?}"
        );
        assert!(out.contains("evil[31mname"), "{out:?}");
    }

    // ── run_dedupe ──────────────────────────────────────────────────

    #[tokio::test]
    async fn run_dedupe_table_path_writes_to_stdout() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "files": [
                        {"id": "f1", "name": "a", "md5Checksum": "hash-a"},
                        {"id": "f2", "name": "b", "md5Checksum": "hash-a"},
                    ],
                })),
            )
            .mount(&server)
            .await;

        run_dedupe(&client, "name contains 'a'", 10, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_dedupe_json_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "files": [],
                })),
            )
            .mount(&server)
            .await;

        run_dedupe(&client, "*", 10, &OutputFormat::Json)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_dedupe_excludes_groups_of_one() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "files": [{"id": "f1", "name": "a", "md5Checksum": "hash-a"}],
                })),
            )
            .mount(&server)
            .await;

        run_dedupe(&client, "*", 10, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_dedupe_propagates_api_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;

        let err = run_dedupe(&client, "*", 10, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("500"));
    }

    // ── DedupeCommand::execute glue ──────────────────────────────────

    #[tokio::test]
    async fn execute_passes_query_through() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files"))
            .and(wiremock::matchers::query_param("q", "name contains 'x'"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "files": [],
                })),
            )
            .expect(1)
            .mount(&server)
            .await;

        let cmd = DedupeCommand {
            query: "name contains 'x'".to_string(),
            limit: 10,
            output: OutputFormat::Json,
        };
        cmd.execute(&client).await.unwrap();
    }
}