omni-dev 0.46.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
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
//! CLI command for `omni-dev drive edit`.

use std::io::Read as _;
use std::path::Path;

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

use crate::cli::drive::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::cli::drive::helpers::{active_account_rules, resolve_ledger_path};
use crate::cli::drive::upload::read_local_content;
use crate::drive::client::DriveClient;
use crate::drive::content_edit::{self, EditOptions, EditOutcome, EditResult};
use crate::drive::files_api::{check_upload_size, MAX_UPLOAD_BYTES};
use crate::drive::lease::check::LeaseGateRefusal;
use crate::drive::write_gate::FolderPermissionRule;

/// MIME type used when `--mime-type` is omitted — Drive's own fallback for
/// unspecified content.
const DEFAULT_CONTENT_MIME_TYPE: &str = "application/octet-stream";

/// Replaces an existing file's content, gated by the account's configured
/// write-permission rules (issues #1574, #1612). Requires the `drive.file`
/// scope if `omni-dev` created the file, or the unrestricted `drive` scope
/// for any pre-existing file (`drive auth login --write-file` or
/// `--write-full`).
///
/// Refuses, client-side, any target that is a Google-native document
/// (Docs/Sheets/Slides/...) — there is no meaningful raw "content" to
/// replace via a media PATCH for those.
#[derive(Parser)]
pub struct EditCommand {
    /// Drive file id (from `drive search`, or the `id` segment of a Drive
    /// URL).
    pub file_id: String,

    /// New content: a local file path, or `-` to read from stdin.
    #[arg(long, value_name = "LOCAL_PATH|-")]
    pub content: String,

    /// MIME type for the content. Defaults to `application/octet-stream`.
    #[arg(long = "mime-type", value_name = "TYPE")]
    pub mime_type: Option<String>,

    /// Reports the gate verdict without calling `files.update`.
    #[arg(long)]
    pub dry_run: bool,

    #[command(flatten)]
    pub lease: crate::cli::drive::helpers::LeaseTokenArg,

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

impl EditCommand {
    /// Runs the command against the shared client resolved by the parent
    /// `DriveCommand::execute`.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let content = resolve_content(&self.content)?;
        let content_type = self
            .mime_type
            .unwrap_or_else(|| DEFAULT_CONTENT_MIME_TYPE.to_string());
        let ledger_path = resolve_ledger_path(self.dry_run)?;
        let opts = EditOptions {
            file_id: self.file_id,
            content,
            content_type,
            dry_run: self.dry_run,
            lease_token: self.lease.lease,
            ledger_path,
        };
        let rules = active_account_rules()?;
        run_edit(client, &opts, &rules, &self.output).await
    }
}

/// Resolves `--content`'s value: `-` reads (and size-checks) stdin, any
/// other value is treated as a local path (via
/// `crate::cli::drive::upload::read_local_content`, shared with `drive
/// upload`'s identical stat-then-read-then-check pattern).
fn resolve_content(content_arg: &str) -> Result<Vec<u8>> {
    if content_arg == "-" {
        read_stdin_content()
    } else {
        read_local_content(Path::new(content_arg))
    }
}

/// Reads stdin, bounded at [`MAX_UPLOAD_BYTES`] + 1 so an unbounded stream
/// can never be buffered past the cap before being refused — there's no
/// upfront size to stat for a pipe, unlike a local file.
fn read_stdin_content() -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    std::io::stdin()
        .take(MAX_UPLOAD_BYTES + 1)
        .read_to_end(&mut buf)
        .context("Failed to read stdin")?;
    check_upload_size(buf.len() as u64)?;
    Ok(buf)
}

/// Runs `edit` and emits the outcome in the requested format.
///
/// Split from [`EditCommand::execute`] so tests can inject a wiremock
/// client and pre-built options/rules directly, without touching the
/// filesystem or credential-loading path.
async fn run_edit(
    client: &DriveClient,
    opts: &EditOptions,
    rules: &[FolderPermissionRule],
    output: &OutputFormat,
) -> Result<()> {
    let outcome = content_edit::edit(client, opts, rules).await;
    if output_as(&outcome, output)? {
        return Ok(());
    }
    print_outcome(&outcome);
    Ok(())
}

fn print_outcome(outcome: &EditOutcome) {
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    // Best-effort, like every other `println!` this replaced: a broken pipe
    // must not turn a completed edit into a failure.
    let _ = write_outcome(outcome, &mut handle);
}

/// Renders an outcome to `out`.
///
/// Split from [`print_outcome`] so the wording is testable, following the
/// `render_*_table` convention the rest of the `drive` CLI already uses.
/// Worth doing here specifically because two of these lines exist to point a
/// refused user at the command that *does* work, and a hint that silently
/// stopped naming the right command would be invisible otherwise.
fn write_outcome(outcome: &EditOutcome, out: &mut dyn std::io::Write) -> std::io::Result<()> {
    let file_id = sanitize_for_terminal(&outcome.file_id);
    match &outcome.result {
        EditResult::WouldEdit => writeln!(out, "Would edit: {file_id}")?,
        EditResult::RefusedNativeDocument => {
            // The refusal itself is unchanged (ADR-0076 §1): a media PATCH
            // has no meaningful content to replace for a native document,
            // and making it "work" would mean convert-on-import re-upload,
            // which destroys comments, suggestions, revision history, tabs
            // and formatting. What it *can* do is name the commands that
            // work, which it previously did not — leaving a user who had
            // just been refused with no route forward.
            writeln!(
                out,
                "Refused: {file_id} is a Google-native document (Docs/Sheets/Slides/...) — no \
                 raw content to replace. Edit a Doc with `omni-dev drive docs \
                 replace`/`append`, or a Sheet with `omni-dev drive sheets \
                 write`/`append`/`clear`."
            )?;
        }
        EditResult::RefusedNoVisibleParents => {
            writeln!(
                out,
                "Refused: {file_id} has no parent folder visible to this account, so no folder \
                 rule can apply to it. This is normal for a file shared by link or email. \
                 Grant it by id instead: add {{\"file_id\": \"<file id>\", \"allow\": \
                 [\"edit\"]}} to write_permissions.rules."
            )?;
        }
        EditResult::Blocked { decided_by } => {
            writeln!(out, "Blocked: {file_id}")?;
            match decided_by {
                Some(rule) => writeln!(
                    out,
                    "  refused by rule on {} {}{}",
                    rule.kind_label(),
                    sanitize_for_terminal(rule.id()),
                    rule.depth_suffix()
                )?,
                None => writeln!(out, "  refused by default policy (no matching rule)")?,
            }
        }
        EditResult::RefusedNoLease => {
            if let Some(line) = LeaseGateRefusal::NoLease.describe_line(&file_id, &file_id) {
                writeln!(out, "{line}")?;
            }
        }
        EditResult::RefusedLeaseExpired => {
            if let Some(line) = LeaseGateRefusal::Expired.describe_line(&file_id, &file_id) {
                writeln!(out, "{line}")?;
            }
        }
        EditResult::RefusedLeaseWrongFile => {
            if let Some(line) = LeaseGateRefusal::WrongFile.describe_line(&file_id, &file_id) {
                writeln!(out, "{line}")?;
            }
        }
        EditResult::RefusedLeaseStale => {
            if let Some(line) = LeaseGateRefusal::Stale.describe_line(&file_id, &file_id) {
                writeln!(out, "{line}")?;
            }
        }
        EditResult::Edited => writeln!(out, "Edited: {file_id}")?,
        EditResult::Failed { detail } => {
            writeln!(out, "Failed: {file_id}: {}", sanitize_for_terminal(detail))?;
        }
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::drive::types::GOOGLE_FOLDER_MIME_TYPE;
    use crate::drive::write_gate::DriveOperation;
    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: DriveGrantedScopes::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 opts(dry_run: bool) -> EditOptions {
        EditOptions {
            file_id: "file-1".to_string(),
            content: b"new content".to_vec(),
            content_type: "text/plain".to_string(),
            dry_run,
            lease_token: None,
            ledger_path: std::path::PathBuf::from("/nonexistent/lease-ledger.jsonl"),
        }
    }

    fn allow_rule() -> FolderPermissionRule {
        FolderPermissionRule {
            folder_id: Some("parent-1".to_string()),
            file_id: None,
            recursive: false,
            allow: std::iter::once(DriveOperation::Edit).collect(),
            deny: std::collections::HashSet::default(),
            require_lease: true,
        }
    }

    #[tokio::test]
    async fn dry_run_reports_verdict_without_calling_the_edit_endpoint() {
        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/file-1"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "file-1", "name": "file-1", "mimeType": "text/plain", "parents": ["parent-1"],
            })))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/parent-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "parent-1", "name": "parent-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;
        // No PATCH mock mounted — dry-run must never call files.update.

        run_edit(&client, &opts(true), &[allow_rule()], &OutputFormat::Table)
            .await
            .unwrap();
    }

    /// Exercises `EditCommand::execute` itself (every other test here calls
    /// `run_edit` directly), specifically to cover the `--dry-run` branch
    /// that skips `ledger_path()` — see its own doc comment for why a
    /// dry-run must never resolve a real ledger path.
    #[tokio::test]
    async fn execute_dry_run_never_resolves_a_ledger_path() {
        let guard = crate::drive::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        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/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "file-1", "name": "file-1", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;
        let content_dir = tempfile::tempdir().unwrap();
        let content_path = content_dir.path().join("content.txt");
        std::fs::write(&content_path, b"new content").unwrap();

        let cmd = EditCommand {
            file_id: "file-1".to_string(),
            content: content_path.to_str().unwrap().to_string(),
            mime_type: None,
            dry_run: true,
            lease: crate::cli::drive::helpers::LeaseTokenArg { lease: None },
            output: OutputFormat::Table,
        };
        cmd.execute(&client).await.unwrap();
    }

    #[tokio::test]
    async fn run_edit_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/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "file-1", "name": "file-1", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;

        run_edit(&client, &opts(false), &[], &OutputFormat::Json)
            .await
            .unwrap();
    }

    // ── resolve_content ─────────────────────────────────────────────

    #[test]
    fn resolve_content_reads_a_local_path() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("content.txt");
        std::fs::write(&path, b"hello").unwrap();
        let content = resolve_content(path.to_str().unwrap()).unwrap();
        assert_eq!(content, b"hello");
    }

    #[test]
    fn resolve_content_dash_is_never_treated_as_a_local_path() {
        // "-" would fail as a local path (no such file); this just asserts
        // the routing decision, not stdin's actual content in a test
        // process (reading real stdin here would hang/misbehave under
        // `cargo test`, so this is intentionally not exercised further).
        assert!(!Path::new("-").exists());
    }

    fn rendered(result: EditResult) -> String {
        let mut buf = Vec::new();
        write_outcome(
            &EditOutcome {
                file_id: "f1".to_string(),
                file_name: Some("f".to_string()),
                resolved_folder_id: None,
                result,
            },
            &mut buf,
        )
        .unwrap();
        String::from_utf8(buf).unwrap()
    }

    /// Every variant renders exactly one line (two for `Blocked`, which
    /// carries its reason on a second), and none of them panics.
    #[test]
    fn every_variant_renders() {
        for (result, lines) in [
            (EditResult::WouldEdit, 1),
            (EditResult::RefusedNativeDocument, 1),
            (EditResult::RefusedNoVisibleParents, 1),
            (EditResult::RefusedNoLease, 1),
            (EditResult::RefusedLeaseExpired, 1),
            (EditResult::RefusedLeaseWrongFile, 1),
            (EditResult::RefusedLeaseStale, 1),
            (EditResult::Edited, 1),
            (
                EditResult::Failed {
                    detail: "boom".to_string(),
                },
                1,
            ),
            (EditResult::Blocked { decided_by: None }, 2),
            (
                EditResult::Blocked {
                    decided_by: Some(crate::drive::write_gate::DecidingRule::Folder {
                        folder_id: "parent-1".to_string(),
                        depth: 0,
                    }),
                },
                2,
            ),
            (
                EditResult::Blocked {
                    decided_by: Some(crate::drive::write_gate::DecidingRule::File {
                        file_id: "f1".to_string(),
                    }),
                },
                2,
            ),
        ] {
            let text = rendered(result);
            assert_eq!(text.lines().count(), lines, "{text}");
            assert!(text.contains("f1"), "{text}");
        }
    }

    /// The native-document refusal must name **both** trees that can do the
    /// job. This is the whole reason the line exists: `drive edit` refuses a
    /// Doc or a Sheet by design (ADR-0076 §1), so without a route forward
    /// the user is simply stuck. It went three weeks naming neither, which
    /// is exactly the drift an untested message invites.
    #[test]
    fn the_native_document_refusal_names_both_drive_docs_and_drive_sheets() {
        let text = rendered(EditResult::RefusedNativeDocument);
        assert!(text.contains("drive docs"), "{text}");
        assert!(text.contains("drive sheets"), "{text}");
        assert!(text.contains("no raw content to replace"), "{text}");
    }

    /// The parentless refusal names the fix that actually works — a
    /// `file_id` rule — rather than sending the reader off to write a
    /// folder rule that can never match (issue #1612).
    #[test]
    fn the_parentless_refusal_names_a_file_id_rule_as_the_fix() {
        let text = rendered(EditResult::RefusedNoVisibleParents);
        assert!(text.contains("file_id"), "{text}");
    }

    /// Server- and operator-supplied strings reach a terminal here, so both
    /// the file id and a failure detail are sanitized.
    #[test]
    fn rendering_strips_control_bytes_from_untrusted_strings() {
        let mut buf = Vec::new();
        write_outcome(
            &EditOutcome {
                file_id: "f\u{1b}[31m1".to_string(),
                file_name: None,
                resolved_folder_id: None,
                result: EditResult::Failed {
                    detail: "bad\nnews".to_string(),
                },
            },
            &mut buf,
        )
        .unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert!(!text.contains('\u{1b}'), "{text}");
        assert_eq!(
            text.lines().count(),
            1,
            "an embedded newline must not add a row: {text}"
        );
    }
}