From 8c1e0e3ed6c291fa0b7193250980df0a0e6f3ef4 Mon Sep 17 00:00:00 2001 From: Travis Sheppard <36867340+nomadonwheels196@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:03:56 +0100 Subject: [PATCH] feat(drive): return the committed revision from guarded uploads --- CHANGELOG.md | 1 + docs/commands/gog-drive-upload.md | 1 + docs/commands/gog-upload.md | 1 + internal/cmd/drive_upload.go | 79 +++++++----- internal/cmd/drive_upload_receipt_test.go | 147 ++++++++++++++++++++++ 5 files changed, 199 insertions(+), 30 deletions(-) create mode 100644 internal/cmd/drive_upload_receipt_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index e1c42a3c5..79236f582 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 0.48.2 - Unreleased - Dependencies: refresh the MCP and Google API clients, networking libraries, and tracking-worker tooling while preserving the Go 1.26 minimum, 24-hour worker cooldown, and security overrides. +- Drive: include the committed content revision and available checksums in guarded upload JSON with `--include-committed-revision`. ## 0.48.1 - 2026-11-15 diff --git a/docs/commands/gog-drive-upload.md b/docs/commands/gog-drive-upload.md index 5d9a3873a..a2d1d242d 100644 --- a/docs/commands/gog-drive-upload.md +++ b/docs/commands/gog-drive-upload.md @@ -33,6 +33,7 @@ gog drive (drv) upload [flags] | `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | | `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | | `--if-version` | `*int64` | | Replace only if the current Drive version matches; uses an atomic precondition and reports a conflict if the file changes (requires --replace; re-read and reapply on conflict) | +| `--include-committed-revision` | `bool` | | Include the committed content revision and available checksums in JSON (requires --if-version) | | `-j`
`--json`
`--machine` | `bool` | false | Output JSON to stdout (best for scripting) | | `--keep-frontmatter` | `bool` | | Keep YAML frontmatter (---) in Markdown when converting to a Google Doc (--convert or --convert-to doc; default: strip) | | `--keep-revision-forever` | `bool` | | Keep the new head revision forever (binary files only) | diff --git a/docs/commands/gog-upload.md b/docs/commands/gog-upload.md index bbb72e833..04450501b 100644 --- a/docs/commands/gog-upload.md +++ b/docs/commands/gog-upload.md @@ -33,6 +33,7 @@ gog upload (up,put) [flags] | `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | | `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | | `--if-version` | `*int64` | | Replace only if the current Drive version matches; uses an atomic precondition and reports a conflict if the file changes (requires --replace; re-read and reapply on conflict) | +| `--include-committed-revision` | `bool` | | Include the committed content revision and available checksums in JSON (requires --if-version) | | `-j`
`--json`
`--machine` | `bool` | false | Output JSON to stdout (best for scripting) | | `--keep-frontmatter` | `bool` | | Keep YAML frontmatter (---) in Markdown when converting to a Google Doc (--convert or --convert-to doc; default: strip) | | `--keep-revision-forever` | `bool` | | Keep the new head revision forever (binary files only) | diff --git a/internal/cmd/drive_upload.go b/internal/cmd/drive_upload.go index 813aef8df..b8b80f69f 100644 --- a/internal/cmd/drive_upload.go +++ b/internal/cmd/drive_upload.go @@ -23,30 +23,32 @@ import ( ) type DriveUploadCmd struct { - LocalPath string `arg:"" name:"localPath" help:"Path to local file"` - Name string `name:"name" help:"Override filename (create) or rename target (replace)"` - Parent string `name:"parent" help:"Destination folder ID (create only)"` - ReplaceFileID string `name:"replace" help:"Replace the content of an existing Drive file ID (preserves shared link/permissions; unconditional unless --if-version is set)"` - IfVersion *int64 `name:"if-version" help:"Replace only if the current Drive version matches; uses an atomic precondition and reports a conflict if the file changes (requires --replace; re-read and reapply on conflict)"` - MimeType string `name:"mime-type" help:"Override MIME type inference"` - KeepRevisionForever bool `name:"keep-revision-forever" help:"Keep the new head revision forever (binary files only)"` - Convert bool `name:"convert" help:"Auto-convert to native Google format based on file extension (create only)"` - ConvertTo string `name:"convert-to" help:"Convert to a specific Google format: doc|sheet|slides (create only)"` - KeepFrontmatter bool `name:"keep-frontmatter" help:"Keep YAML frontmatter (---) in Markdown when converting to a Google Doc (--convert or --convert-to doc; default: strip)"` + LocalPath string `arg:"" name:"localPath" help:"Path to local file"` + Name string `name:"name" help:"Override filename (create) or rename target (replace)"` + Parent string `name:"parent" help:"Destination folder ID (create only)"` + ReplaceFileID string `name:"replace" help:"Replace the content of an existing Drive file ID (preserves shared link/permissions; unconditional unless --if-version is set)"` + IncludeCommittedRevision bool `name:"include-committed-revision" help:"Include the committed content revision and available checksums in JSON (requires --if-version)"` + IfVersion *int64 `name:"if-version" help:"Replace only if the current Drive version matches; uses an atomic precondition and reports a conflict if the file changes (requires --replace; re-read and reapply on conflict)"` + MimeType string `name:"mime-type" help:"Override MIME type inference"` + KeepRevisionForever bool `name:"keep-revision-forever" help:"Keep the new head revision forever (binary files only)"` + Convert bool `name:"convert" help:"Auto-convert to native Google format based on file extension (create only)"` + ConvertTo string `name:"convert-to" help:"Convert to a specific Google format: doc|sheet|slides (create only)"` + KeepFrontmatter bool `name:"keep-frontmatter" help:"Keep YAML frontmatter (---) in Markdown when converting to a Google Doc (--convert or --convert-to doc; default: strip)"` } type driveUploadOptions struct { - localPath string - fileName string - parent string - replaceFileID string - ifVersion *int64 - mimeType string - convertMimeType string - isExplicitName bool - keepRevisionForever bool - convert bool - size int64 + localPath string + fileName string + parent string + replaceFileID string + includeCommittedRevision bool + ifVersion *int64 + mimeType string + convertMimeType string + isExplicitName bool + keepRevisionForever bool + convert bool + size int64 } func guessMimeType(path string) string { @@ -183,6 +185,9 @@ func (c *DriveUploadCmd) Run(ctx context.Context, flags *RootFlags) error { if opts.ifVersion != nil { dryRunRequest["if_version"] = *opts.ifVersion } + if opts.includeCommittedRevision { + dryRunRequest["include_committed_revision"] = true + } if dryRunErr := dryRunExit(ctx, flags, "drive.upload", dryRunRequest); dryRunErr != nil { return dryRunErr } @@ -218,12 +223,13 @@ func prepareDriveUpload(c *DriveUploadCmd) (driveUploadOptions, error) { } opts := driveUploadOptions{ - localPath: expandedPath, - fileName: strings.TrimSpace(c.Name), - parent: strings.TrimSpace(c.Parent), - replaceFileID: strings.TrimSpace(c.ReplaceFileID), - mimeType: strings.TrimSpace(c.MimeType), - keepRevisionForever: c.KeepRevisionForever, + localPath: expandedPath, + fileName: strings.TrimSpace(c.Name), + parent: strings.TrimSpace(c.Parent), + replaceFileID: strings.TrimSpace(c.ReplaceFileID), + mimeType: strings.TrimSpace(c.MimeType), + keepRevisionForever: c.KeepRevisionForever, + includeCommittedRevision: c.IncludeCommittedRevision, } if c.IfVersion != nil { expectedVersion := *c.IfVersion @@ -231,6 +237,9 @@ func prepareDriveUpload(c *DriveUploadCmd) (driveUploadOptions, error) { } opts.isExplicitName = opts.fileName != "" + if opts.includeCommittedRevision && opts.ifVersion == nil { + return driveUploadOptions{}, usage("--include-committed-revision requires --if-version") + } if opts.ifVersion != nil && opts.replaceFileID == "" { return driveUploadOptions{}, usage("--if-version requires --replace") } @@ -389,10 +398,14 @@ func runDriveConditionalReplaceUpload(ctx context.Context, svc *drivev2.Service, // retrying resumable uploader, while the request context disables retries in // gog's authenticated RetryTransport. updateCtx := gogapi.WithoutRetries(ctx) + fields := "id, title, mimeType, fileSize, alternateLink" + if opts.includeCommittedRevision { + fields += ", headRevisionId, sha256Checksum, md5Checksum" + } call := svc.Files.Update(opts.replaceFileID, meta). SupportsAllDrives(true). Media(file, gapi.ContentType(opts.mimeType), gapi.ChunkSize(0)). - Fields("id, title, mimeType, fileSize, alternateLink"). + Fields(gapi.Field(fields)). Context(updateCtx) if opts.keepRevisionForever { call = call.Pinned(true) @@ -410,13 +423,19 @@ func runDriveConditionalReplaceUpload(ctx context.Context, svc *drivev2.Service, } return err } - return writeDriveUploadResult(ctx, &drive.File{ + result := &drive.File{ Id: updated.Id, Name: updated.Title, MimeType: updated.MimeType, Size: updated.FileSize, WebViewLink: updated.AlternateLink, - }, true, opts.replaceFileID) + } + if opts.includeCommittedRevision { + result.HeadRevisionId = updated.HeadRevisionId + result.Md5Checksum = updated.Md5Checksum + result.Sha256Checksum = updated.Sha256Checksum + } + return writeDriveUploadResult(ctx, result, true, opts.replaceFileID) } func writeDriveUploadResult(ctx context.Context, file *drive.File, replaced bool, replacedFileID string) error { diff --git a/internal/cmd/drive_upload_receipt_test.go b/internal/cmd/drive_upload_receipt_test.go new file mode 100644 index 000000000..78052a107 --- /dev/null +++ b/internal/cmd/drive_upload_receipt_test.go @@ -0,0 +1,147 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "slices" + "strings" + "testing" + + "google.golang.org/api/drive/v3" +) + +const driveUploadReceiptFlag = "--include-committed-revision" + +func TestDriveUpload_ConditionalReceipt(t *testing.T) { + const etag = `"before-write"` + const sha256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + const md5 = "0123456789abcdef0123456789abcdef" + + for _, tc := range []struct { + name string + optIn bool + status int + complete bool + }{ + {name: "opt-in receipt", optIn: true, status: http.StatusOK, complete: true}, + {name: "default output", status: http.StatusOK, complete: true}, + {name: "missing committed fields", optIn: true, status: http.StatusOK}, + {name: "competing update", optIn: true, status: http.StatusPreconditionFailed}, + {name: "ambiguous server error", optIn: true, status: http.StatusInternalServerError}, + } { + t.Run(tc.name, func(t *testing.T) { + var reads, writes int + svc := newDriveUploadReplaceTestService(t, true, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.TrimPrefix(r.URL.Path, "/drive/v2") == "/files/file1": + reads++ + _ = json.NewEncoder(w).Encode(map[string]string{ + "id": "file1", "mimeType": "application/pdf", "version": "42", "etag": etag, + "headRevisionId": "before-head", "sha256Checksum": "before-sha256", + }) + case r.Method == http.MethodPut && r.URL.Path == "/upload/drive/v2/files/file1": + writes++ + if got := r.Header.Get("If-Match"); got != etag { + t.Errorf("If-Match = %q, want %q", got, etag) + } + fields := strings.Split(strings.ReplaceAll(r.URL.Query().Get("fields"), " ", ""), ",") + for _, field := range []string{"headRevisionId", "sha256Checksum", "md5Checksum"} { + if slices.Contains(fields, field) != tc.optIn { + t.Errorf("fields = %q, presence of %q should be %t", fields, field, tc.optIn) + } + } + w.WriteHeader(tc.status) + if tc.status != http.StatusOK { + return + } + reply := map[string]string{"id": "file1", "title": "Existing.pdf", "mimeType": "application/pdf"} + if tc.complete { + reply["headRevisionId"], reply["sha256Checksum"], reply["md5Checksum"] = "committed-head", sha256, md5 + } + _ = json.NewEncoder(w).Encode(reply) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + }) + args := []string{writeDriveUploadReplaceTestFile(t), "--replace", "file1", "--if-version", "42"} + if tc.optIn { + args = append(args, driveUploadReceiptFlag) + } + var out bytes.Buffer + ctx := withDriveV2TestService(newCmdRuntimeJSONOutputContext(t, &out, io.Discard), svc) + err := runKong(t, &DriveUploadCmd{}, args, ctx, &RootFlags{Account: "a@b.com", Force: true}) + if tc.status != http.StatusOK { + if err == nil || out.Len() != 0 { + t.Fatalf("failed write produced err=%v, stdout=%q", err, out.Bytes()) + } + } else { + if err != nil { + t.Fatalf("conditional replace: %v", err) + } + var got struct { + File drive.File `json:"file"` + Replaced bool `json:"replaced"` + PreservedFileID bool `json:"preservedFileId"` + } + if err := json.Unmarshal(out.Bytes(), &got); err != nil { + t.Fatalf("decode receipt: %v", err) + } + if got.File.Id != "file1" || !got.Replaced || !got.PreservedFileID { + t.Fatalf("unexpected replacement result: %s", out.Bytes()) + } + if tc.optIn && tc.complete { + if got.File.HeadRevisionId != "committed-head" || got.File.Sha256Checksum != sha256 || got.File.Md5Checksum != md5 { + t.Fatalf("unexpected committed receipt: %s", out.Bytes()) + } + } else if got.File.HeadRevisionId != "" || got.File.Sha256Checksum != "" || got.File.Md5Checksum != "" { + t.Fatalf("unexpected receipt fields: %s", out.Bytes()) + } + } + if reads != 1 || writes != 1 { + t.Fatalf("got %d reads and %d writes, want one metadata read and one conditional upload", reads, writes) + } + }) + } +} + +func TestDriveUpload_ConditionalReceiptValidation(t *testing.T) { + local := writeDriveUploadReplaceTestFile(t) + for _, tc := range []struct { + name string + args []string + error string + }{ + {"create", []string{local, driveUploadReceiptFlag}, "requires --if-version"}, + {"unguarded replacement", []string{local, "--replace", "file1", driveUploadReceiptFlag}, "requires --if-version"}, + {"no replacement target", []string{local, "--if-version", "42", driveUploadReceiptFlag}, "requires --replace"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := newCmdRuntimeJSONOutputContext(t, io.Discard, io.Discard) + err := runKong(t, &DriveUploadCmd{}, tc.args, ctx, &RootFlags{DryRun: true}) + if ExitCode(err) != 2 || !strings.Contains(err.Error(), tc.error) { + t.Fatalf("got %v, want usage error containing %q", err, tc.error) + } + }) + } + + var out bytes.Buffer + ctx := newCmdRuntimeJSONOutputContext(t, &out, io.Discard) + args := []string{local, "--replace", "file1", "--if-version", "42", driveUploadReceiptFlag} + err := runKong(t, &DriveUploadCmd{}, args, ctx, &RootFlags{DryRun: true}) + if ExitCode(err) != 0 { + t.Fatalf("dry run: %v", err) + } + var got struct { + Request map[string]any `json:"request"` + } + if err := json.Unmarshal(out.Bytes(), &got); err != nil { + t.Fatalf("decode preview: %v", err) + } + if got.Request["include_committed_revision"] != true || got.Request["if_version"] != float64(42) { + t.Fatalf("preview missing conditional receipt intent: %s", out.Bytes()) + } +}