Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions docs/commands/gog-drive-upload.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ gog drive (drv) upload <localPath> [flags]
| `-h`<br>`--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`<br>`--json`<br>`--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) |
Expand Down
1 change: 1 addition & 0 deletions docs/commands/gog-upload.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ gog upload (up,put) <localPath> [flags]
| `-h`<br>`--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`<br>`--json`<br>`--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) |
Expand Down
79 changes: 49 additions & 30 deletions internal/cmd/drive_upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -218,19 +223,23 @@ 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
opts.ifVersion = &expectedVersion
}
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")
}
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand Down
147 changes: 147 additions & 0 deletions internal/cmd/drive_upload_receipt_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
}