Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Output, Schemas and Dry Runs

gog supports 3 output formats for command results: human-readable text, JSON, and tab-separated text. This chapter covers selecting a format, filtering JSON, inspecting commands with gog schema, handling exit codes, and supplying date and time arguments.

Use --dry-run to preview a write request without contacting Google. The final examples use jq to inspect the plan.

All output in this chapter comes from gog v0.48.1 running with an empty configuration directory, so nothing here needs a Google account. To reproduce it, start a shell with a throwaway home:

export GOG_HOME="$(mktemp -d)"
cd "$(mktemp -d)"
printf 'Hello,\n\nThe agenda for Monday is attached.\n' > note.txt
printf 'Agenda\n1. Budget review\n2. Hiring plan\n' > agenda.txt

GOG_HOME moves the root of the gog configuration, data, state and cache directories to that directory (see Installation and First Checks). The 2 text files are used by the Gmail examples below.

Output modes

gog writes the result of a command to standard output (stdout) and everything else, such as prompts, progress messages, warnings and hints, to standard error (stderr). Standard output supports these 3 formats.

ModeFlagShapeUse it for
Humannonealigned table or labeled lines, color when the terminal supports itreading at the terminal
JSON--json or -j1 JSON document, pretty-printedscripts, jq, AI agents
Plain--plain or -ptab-separated values (TSV) with a header row, no colorcut, awk, sort, spreadsheets

The rule in docs/automation.md is simple: anything a program reads should use --json or --plain, because the human layout can change. gog auth services works without an account, so it is a convenient way to compare the modes. The human table pads its columns with spaces:

$ gog auth services | cut -c 1-36 | sed 's/ *$//' | head -n 3
SERVICE        USER   APIS
gmail          true   Gmail API
calendar       true   Calendar API

The plain form separates the same columns with tabs, so cut -f selects them reliably:

$ gog auth services --plain | cut -f 1,3 | head -n 4
SERVICE	APIS
gmail	Gmail API
calendar	Calendar API
chat	Chat API

Choose 1 machine-readable format per command. Requesting both produces a usage error with exit code 2.

$ gog --json --plain auth services
invalid output mode (cannot combine --json and --plain)
{"error":{"class":"usage","code":2,"message":"invalid output mode (cannot combine --json and --plain)"}}

The environment variables GOG_JSON=1 and GOG_PLAIN=1 set a default mode for every command in a shell, which is convenient in agent sessions. An explicit flag on the command line wins over the environment:

$ GOG_JSON=1 gog auth services --plain | cut -f 1 | head -n 3
SERVICE
gmail
calendar

Color, prompts and confirmations

--color takes auto (the default), always or never, and GOG_COLOR sets the same choice from the environment. In auto mode gog detects whether the output is a terminal. JSON and plain output remain uncolored at every --color setting (internal/cmd/root.go).

A few destructive commands, such as gog calendar delete and gog gmail drafts delete, ask Proceed to ...? [y/N] before they act. --no-input makes commands fail whenever they would otherwise prompt.

gog also refuses to prompt when standard input is not a terminal, so a script gets the same refusal even without the flag. --force (or -y) skips the confirmation (internal/cmd/confirm.go).

$ gog --account you@example.com --no-input calendar delete primary EVENT_ID
refusing to delete event EVENT_ID from calendar primary without --force (non-interactive)

The exit code is 2. Use --no-input in every script, CI job and agent session, so that a missing argument or an unexpected question stops the run instead of waiting forever for an answer.

Shaping JSON with --results-only and --select

Many JSON results are wrapped in an envelope, an object that holds the result list alongside metadata such as nextPageToken (the token for the next page of a list). --results-only removes the envelope and prints only the primary result.

--select keeps only the named fields. It accepts a comma-separated list and dot paths such as request.to.

Both options apply only in JSON mode:

$ gog auth services --json --results-only --select service,user | head -n 9
[
  {
    "service": "gmail",
    "user": true
  },
  {
    "service": "calendar",
    "user": true
  },
$ gog auth services --select service
--select requires --json

--results-only runs before --select, so for a list the selected fields are relative to each item (docs/automation.md). --fields is an alias for --select on commands that have no --fields flag of their own.

Some commands, such as gog calendar events, define their own --fields, which acts as a field mask by specifying the fields the Google API should return. The help page of each command shows which meaning applies.

Errors in JSON mode

When a command fails in JSON mode, gog still writes a JSON document to stdout. It has 1 key, error, whose object holds the numeric code (equal to the exit status), a stable class name, and the message.

The human message also appears on stderr. Here a search fails because this machine has no OAuth client, the application identity gog needs before it can sign in (see Authentication and Accounts):

$ gog --account you@example.com --json gmail search 'is:unread' 2>/dev/null | jq '.error | {class, code}'
{
  "class": "config",
  "code": 10
}

--results-only and --select do not touch the error object, so a script can always read .error.code (docs/automation.md). If a command has already printed part of its result before it fails, gog leaves that output alone and adds no error object, which is why a script should look at the exit status first and at stdout second.

Exit codes

gog uses named exit codes so that scripts can react to a failure without parsing English text. The table lists them as gog schema reports them:

CodeNameWhen gog uses it
0okthe command succeeded
1errora failure that fits no other class
2usagewrong arguments or flags, conflicting options, a blocked or refused operation
3empty_resultsthe query ran but found nothing, and the command was asked to signal that (--fail-empty)
4auth_requiredthe stored login is missing, expired, revoked or unusable
5not_foundthe message, event or other resource does not exist
6permission_deniedthe account is signed in but lacks access
7rate_limiteda Google quota or rate limit was hit
8retryablea temporary server or network failure
10configlocal setup, such as the OAuth client file, is missing
11orphaneda Google Docs comment lost its anchor (not relevant to Gmail or Calendar)
130cancelledthe run was interrupted, for example with Ctrl-C

gog retries rate-limited Google requests with increasing delays before exiting with code 7 (docs/automation.md). The project may add codes later, so every case statement needs a fallback branch. The following script, saved as labels-or-explain.sh, lists Gmail labels and explains the common failures:

#!/usr/bin/env bash
set -u

if output=$(gog --account you@example.com --no-input --json gmail labels list); then
  printf '%s\n' "$output" | jq -r '.labels[].name'
else
  rc=$?
  case $rc in
  4) echo "the token is missing or expired: sign in again" >&2 ;;
  7 | 8) echo "temporary failure: try again later" >&2 ;;
  10) echo "gog has no OAuth client on this machine" >&2 ;;
  *) echo "gog failed with exit code $rc" >&2 ;;
  esac
  exit "$rc"
fi

On a machine without credentials, gog prints its own message on stderr, the script adds its explanation, and the script exits with 10:

$ ./labels-or-explain.sh
OAuth client credentials missing (OAuth client ID JSON).
Download from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)
Then run: gog auth credentials <credentials.json> (expected at /tmp/tmp.xNGZrwgGOu/data/credentials.json)
gog has no OAuth client on this machine

Reading the contract with gog schema

gog schema prints a JSON description of the command tree. Without arguments it covers the whole CLI; with a command path such as gog schema gmail search it describes only that command.

It always prints JSON, and it rejects --plain (docs/automation.md). The top level has 4 keys:

$ gog schema --json | jq -c 'keys'
["automation","build","command","schema_version"]
KeyContent
schema_versionthe version of the schema format (1 in v0.48.1)
buildthe gog version string
commandthe command: name, aliases, path, usage, help, flags, positionals and, for groups, subcommands
automationoutput_formats, exit_codes and safety, the safety settings in force for this invocation

The exit code table above comes from this object:

$ gog schema --json | jq '.automation.exit_codes'
{
  "auth_required": 4,
  "cancelled": 130,
  "config": 10,
  "empty_results": 3,
  "error": 1,
  "not_found": 5,
  "ok": 0,
  "orphaned": 11,
  "permission_denied": 6,
  "rate_limited": 7,
  "retryable": 8,
  "usage": 2
}

Positional arguments, the values written without a flag name, are listed under command.positionals. cumulative means that the argument takes every remaining word:

$ gog schema gmail search | jq '.command | {path, usage, positionals}'
{
  "path": "gog gmail (mail,email) search (find,query,ls,list)",
  "usage": "gmail (mail,email) search (find,query,ls,list) <query> ... [flags]",
  "positionals": [
    {
      "name": "query",
      "help": "Search query",
      "type": "[]string",
      "required": true,
      "cumulative": true
    }
  ]
}

Each flag object can carry name, aliases, short, help, type, default, has_default, enum, envs (environment variables that set it), required and placeholder. The flag list includes the global flags, so --json and --account appear on every command:

$ gog schema gmail search | jq '.command.flags[] | select(.name == "max")'
{
  "name": "max",
  "aliases": [
    "limit"
  ],
  "help": "Max results",
  "type": "int64",
  "default": "10",
  "has_default": true,
  "placeholder": "10"
}

The schema covers the input side of a command: its arguments, flags, exit codes and safety state. The JSON fields that the Gmail and Calendar commands print are described in Reading Gmail, Writing Gmail and Google Calendar, from the documentation and the source code. The safety object is the subject of Safety Controls for Scripts and Agents.

Date and time arguments

docs/dates.md lists the input formats gog accepts where it parses times:

FormExample
Date only2026-12-03
RFC 3339 date and time with offset2026-12-03T14:00:00-05:00 or 2026-12-03T19:00:00Z
ISO offset without colon2026-12-03T14:00:00-0500
Local date and time, no offset2026-12-03T14:00 or 2026-12-03 14:00
Relative (calendar range flags only)now, today, tomorrow, yesterday, monday, next friday

An RFC 3339 timestamp contains a date, the letter T, a time, and a UTC offset. It is the safest choice in scripts because it names one instant without depending on any time zone setting.

The relative words work only in the range flags --from and --to of commands that search a period, such as gog calendar events and gog calendar freebusy. The --from and --to flags for gog calendar create and gog calendar update document RFC3339 as their input format. gog copies the supplied text unchanged into the event. A dry run (next section) shows the effect:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Check-in" --from tomorrow --to tomorrow | jq '.request.event.start'
{
  "dateTime": "tomorrow"
}

gog did not convert tomorrow into a timestamp. Always pass RFC 3339 values, with an explicit offset, when you create or move an event. Google Calendar explains how range flags choose their time zone.

Dry runs

--dry-run (short form -n, with the aliases --dryrun, --noop and --preview) prints the planned write request and stops before contacting Google. The exit status is 0. In JSON mode the plan has 3 keys: dry_run (always true), op (the operation name, such as gmail.send) and request (the parameters gog collected):

$ gog --account you@example.com --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt --attach agenda.txt
{
  "dry_run": true,
  "op": "gmail.send",
  "request": {
    "attachments": [
      "agenda.txt"
    ],
    "bcc": null,
    "body_html_len": 0,
    "body_len": 43,
    "cc": null,
    "from": "",
    "reply_all": false,
    "reply_to": "",
    "reply_to_message_id": "",
    "signature": false,
    "signature_file": "",
    "signature_from": "",
    "subject": "Agenda for Monday",
    "thread_id": "",
    "to": [
      "friend@example.com"
    ],
    "track": false,
    "track_split": false
  }
}

The plan records the body as its length in bytes (body_len) and lists attachments by path. An unset recipient field is null, while a set one is a list. The same dry run for a calendar event shows the complete event resource that gog would send:

$ gog --account you@example.com --dry-run --json calendar create primary --summary "Project review" --from 2026-12-03T14:00:00-05:00 --to 2026-12-03T15:00:00-05:00 --timezone America/Toronto --attendees friend@example.com --location "Room 4B" --description "Review the open items before the holidays."
{
  "dry_run": true,
  "op": "calendar.create",
  "request": {
    "calendar_id": "primary",
    "conference_version_1": false,
    "event": {
      "attendees": [
        {
          "email": "friend@example.com"
        }
      ],
      "description": "Review the open items before the holidays.",
      "end": {
        "dateTime": "2026-12-03T15:00:00-05:00",
        "timeZone": "America/Toronto"
      },
      "location": "Room 4B",
      "start": {
        "dateTime": "2026-12-03T14:00:00-05:00",
        "timeZone": "America/Toronto"
      },
      "summary": "Project review"
    },
    "send_updates": "",
    "supports_attachments": false
  }
}

What the other modes print

Use --json when a program needs to parse the full plan. The human-readable form prints a banner on stdout before the request. Plain output puts the request on 1 line as request_json.

$ gog --account you@example.com --dry-run gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | head -n 3
Dry run: would gmail.send
{
  "attachments": [],
$ gog --account you@example.com --dry-run --plain gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | cut -c 1-60
dry_run	true
op	gmail.send
request_json	{"attachments":[],"bcc":null,"body_html_len":0,

A dry-run plan ignores --select and --results-only and always prints all 3 keys (internal/cmd/dryrun.go). Use jq to pick fields from it:

$ gog --account you@example.com --dry-run --json --select op gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -c 'keys'
["dry_run","op","request"]

What a dry run checks

A dry run needs no account and makes no network request, yet it runs most of the local validation. These checks were observed with v0.48.1:

Problem in the commandDry run result
a required flag is missing, such as --subject on gmail drafts createexit 2, required: --subject
a recipient is not an email addressexit 2, invalid --to recipient list ...
--body-file names a file that does not existexit 1, open missing.txt: no such file or directory
an unknown IANA time zone name (a region name such as America/Toronto) in --timezoneexit 2
a send while --gmail-no-send is activeexit 2, Gmail sending is blocked by --gmail-no-send
--attach names a file that does not existnot detected, exit 0
a message, thread or event ID that does not existnot detected, gog does not look it up
a time string that is not RFC 3339 in calendar createnot detected, forwarded as written

A successful dry run confirms that the command passed the local checks that run before the preview. Google can still reject the actual request.

Inspecting a plan with jq

jq is a command-line JSON processor that most package managers provide. Because unset recipient fields are null, a filter that iterates over them must supply an empty list first.

The // operator supplies a default. For example, .cc // [] yields [] when .cc is null.

Without it, jq stops with an error:

$ gog --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -r '.request | [.to[], .cc[]] | join(", ")'
jq: error (at <stdin>:25): Cannot iterate over null (null)
$ gog --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -r '.request | [.to[], (.cc // [])[], (.bcc // [])[]] | join(", ")'
friend@example.com
$ gog --dry-run --json gmail send --to friend@example.com --cc you@example.org --subject "Agenda for Monday" --body-file note.txt | jq -r '.request | [.to[], (.cc // [])[], (.bcc // [])[]] | join(", ")'
friend@example.com, you@example.org

jq -e sets its own exit status from the last value: 0 for true, 1 for false or null. That turns a filter into a test that a script can use in an if:

$ gog --dry-run --json gmail send --to friend@example.com --subject "Agenda for Monday" --body-file note.txt | jq -e '.op == "gmail.send" and (.request.attachments | length) == 0'
true

The script takes an allowed domain and the flags of a gmail send command, builds the dry-run plan, and refuses when any recipient falls outside the domain.

It never sends anything itself, so you can place it in front of the real command. Save it as check-recipients.sh and make it executable:

#!/usr/bin/env bash
# Usage: check-recipients.sh DOMAIN [gmail send flags...]
set -euo pipefail

domain=$1
shift

plan=$(gog --dry-run --json gmail send "$@")

recipients=$(printf '%s\n' "$plan" | jq -r '
  .request | [(.to // [])[], (.cc // [])[], (.bcc // [])[]] | .[]')

if [ -z "$recipients" ]; then
  echo "no explicit recipients in the plan" >&2
  exit 1
fi

while IFS= read -r address; do
  case $address in
  *@"$domain") ;;
  *)
    echo "refusing: $address is outside $domain" >&2
    exit 1
    ;;
  esac
done <<<"$recipients"

echo "plan ok: $(printf '%s\n' "$recipients" | paste -sd, -)"
$ ./check-recipients.sh example.com --to friend@example.com --cc you@example.com --subject "Agenda for Monday" --body-file note.txt
plan ok: friend@example.com,you@example.com
$ ./check-recipients.sh example.com --to friend@example.com --cc you@example.org --subject "Agenda for Monday" --body-file note.txt
refusing: you@example.org is outside example.com

The second run exits with 1. Safety Controls for Scripts and Agents describes the controls that gog itself enforces, which are stronger than a wrapper script because they cannot be skipped by calling gog directly.