Skip to content

Softorize/gac

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

gac - Google Analytics 4 CLI

A command-line interface for Google Analytics 4. Query reports, monitor realtime data, manage properties, and integrate GA4 into scripts and AI workflows.

Features

  • Reports - Run standard, pivot, and batch reports with flexible dimensions, metrics, filters, and date ranges
  • Realtime - Monitor live traffic with auto-refresh (--watch)
  • Funnel Analysis - Define multi-step funnels and measure conversion rates
  • Property Management - List and inspect accounts, properties, data streams, audiences, and custom definitions
  • Metadata Discovery - Search available dimensions and metrics for any property
  • Multiple Output Formats - Colored tables (default), JSON (--json), or plain TSV (--plain)
  • AI-Friendly - --json output integrates seamlessly with Claude Code, scripts, and pipelines
  • Secure Auth - OAuth2 browser flow with system keyring storage, plus service account support for CI/CD
  • Rate Limiting - Built-in GA4 API quota management (1,250/hr, 25,000/day)

Installation

From Source

git clone https://github.com/Softorize/gac.git
cd gac

Before building, you need Google Cloud OAuth credentials (see Setup below):

export GAC_CLIENT_ID="your-client-id.apps.googleusercontent.com"
export GAC_CLIENT_SECRET="your-client-secret"
make build
# Binary at ./bin/gac

Or create a .env file in the project root (gitignored):

echo 'export GAC_CLIENT_ID="your-client-id"' > .env
echo 'export GAC_CLIENT_SECRET="your-client-secret"' >> .env
source .env && make build

Go Install

go install -ldflags "-X github.com/Softorize/gac/internal/auth.oauthClientID=YOUR_ID -X github.com/Softorize/gac/internal/auth.oauthClientSecret=YOUR_SECRET" github.com/Softorize/gac@latest

Releases

Download pre-built binaries from the Releases page. Available for macOS, Linux, and Windows (amd64/arm64). Release binaries include embedded credentials and work out of the box.

Setup

Google Cloud Project (One-Time)

  1. Go to Google Cloud Console
  2. Create a new project (or select an existing one)
  3. Enable APIs:
    • Navigate to APIs & Services > Library
    • Search and enable Google Analytics Data API
    • Search and enable Google Analytics Admin API
  4. Configure OAuth consent screen:
    • Go to APIs & Services > OAuth consent screen
    • Choose External user type
    • Fill in app name (e.g., "gac"), your email for support/developer contact
    • Add scopes: analytics.readonly and analytics.edit
    • Add your email under Test users (required while in "Testing" status)
  5. Create OAuth credentials:
    • Go to APIs & Services > Credentials
    • Click Create Credentials > OAuth client ID
    • Choose Desktop app as application type
    • Download the JSON file
  6. Extract credentials from the downloaded JSON:
    # The JSON contains "client_id" and "client_secret" fields
    export GAC_CLIENT_ID="your-client-id.apps.googleusercontent.com"
    export GAC_CLIENT_SECRET="GOCSPX-your-secret"

You can also set credentials at runtime instead of build time - just export the environment variables before running gac.

Quick Start

# 1. Authenticate
gac auth login

# 2. List your accounts and properties
gac accounts list
gac properties list

# 3. Set a default property (skip -p flag on every command)
gac config set default_property 123456789

# 4. Run your first report
gac report run -d country -m activeUsers --start 7daysAgo --end today

# 5. Monitor realtime traffic
gac realtime -d country -m activeUsers --watch

Authentication

Browser Login (Interactive)

gac auth login

Opens your browser for Google sign-in. Tokens are stored securely in your system keyring (macOS Keychain, Linux Secret Service, Windows Credential Manager) with a file fallback.

# Check auth status
gac auth status

# Log out (remove stored credentials)
gac auth logout

Service Account (CI/CD)

gac auth service-account set /path/to/service-account-key.json

For automated pipelines, use a Google Cloud service account with GA4 access. Add the service account email as a user on your GA4 property.

Commands

Reports

# Basic report
gac report run -p 123456789 -d country -m activeUsers,sessions

# With date range and filters
gac report run -d city -m sessions \
  --start 2024-01-01 --end 2024-01-31 \
  --filter "country==US"

# Order by metric (descending)
gac report run -d pagePath -m screenPageViews \
  --order-by "-screenPageViews" --limit 20

# Pivot report
gac report pivot -d country,deviceCategory -m sessions \
  --pivot-on deviceCategory

# Batch reports from JSON file
gac report batch -p 123456789 requests.json

# JSON output for scripting
gac report run -d country -m activeUsers --json

Filter Syntax

Filters use a simple field<operator>value syntax:

Operator Example Description
== country==US Equals
!= country!=US Not equals
> sessions>100 Greater than
< sessions<50 Less than
>= sessions>=100 Greater than or equal
<= sessions<=50 Less than or equal
=~ pagePath=~/blog/.* Regex match
!~ pagePath!~/admin/.* Regex not match
contains pagePath contains blog Contains substring
not_contains pagePath not_contains admin Does not contain

Combine multiple filters with commas (AND logic):

gac report run -d city -m sessions --filter "country==US,sessions>100"

Date Formats

--start today          # Today
--start yesterday      # Yesterday
--start 7daysAgo       # 7 days ago
--start 30daysAgo      # 30 days ago
--start 2024-01-15     # Specific date (YYYY-MM-DD)

Realtime

# One-time realtime snapshot
gac realtime -d country -m activeUsers

# Live monitoring (refreshes every 30 seconds)
gac realtime -d country -m activeUsers --watch

# Custom refresh interval
gac realtime -d pagePath -m activeUsers --watch --interval 10

Funnel Analysis

# Inline funnel steps
gac funnel -p 123456789 \
  --steps '[{"name":"Homepage","filter_expression":"pagePath==/"},{"name":"Signup","filter_expression":"pagePath==/signup"},{"name":"Purchase","filter_expression":"eventName==purchase"}]'

# From a JSON file
gac funnel -p 123456789 --steps-file funnel.json

Metadata

# List all available dimensions and metrics
gac metadata -p 123456789

# Filter by type
gac metadata --type dimensions
gac metadata --type metrics

# Search for specific metrics
gac metadata --search "user"

Property Management

# Accounts
gac accounts list
gac accounts get 123456

# Properties
gac properties list
gac properties list --account-id 123456
gac properties get 123456789

# Data streams
gac streams list -p 123456789
gac streams get 456789 -p 123456789

# Audiences
gac audiences list -p 123456789
gac audiences get audience123 -p 123456789

# Custom dimensions and metrics
gac custom dimensions list -p 123456789
gac custom metrics list -p 123456789

Configuration

# Set defaults (avoid repeating flags)
gac config set default_property 123456789
gac config set default_account 123456
gac config set output_format json

# View configuration
gac config list
gac config get default_property
gac config path

Available config keys:

Key Values Description
default_account Account ID Default GA4 account
default_property Property ID Default GA4 property
output_format table, json, plain Default output format
color_mode auto, always, never Color output mode
oauth_port 1-65535 OAuth callback port (default: 8085)

Shell Completions

# Bash
gac completion bash > /usr/local/etc/bash_completion.d/gac

# Zsh
gac completion zsh > "${fpath[1]}/_gac"

# Fish
gac completion fish > ~/.config/fish/completions/gac.fish

Output Formats

Table (Default)

Colored, aligned tables optimized for terminal reading. Dimensions are left-aligned, metrics are right-aligned.

gac report run -d country -m activeUsers,sessions

JSON

Structured JSON for scripting, piping, and AI tool integration.

gac report run -d country -m activeUsers --json
gac accounts list --json | jq '.[].ID'

Plain (TSV)

Tab-separated values with no decoration. Ideal for cut, awk, sort, and spreadsheet import.

gac report run -d country -m activeUsers --plain | sort -t$'\t' -k2 -rn

Environment Variables

All flags can be set via environment variables:

Variable Flag Description
GAC_CLIENT_ID - OAuth client ID (build-time or runtime)
GAC_CLIENT_SECRET - OAuth client secret (build-time or runtime)
GAC_ACCOUNT --account Default account ID
GAC_PROPERTY --property Default property ID
GAC_JSON --json JSON output
GAC_PLAIN --plain Plain TSV output
GAC_CONFIG_DIR - Custom config directory
GAC_DEFAULT_ACCOUNT - Config: default account
GAC_DEFAULT_PROPERTY - Config: default property
GAC_OUTPUT_FORMAT - Config: output format
GAC_COLOR - Config: color mode
NO_COLOR - Disable colors (no-color.org)

AI / Claude Code Integration

gac is designed to work seamlessly with AI assistants. Use --json for structured output that Claude Code can parse and reason about:

# Ask Claude to analyze your traffic
gac report run -d country -m activeUsers,sessions --json

# Pipe to AI workflows
gac report run -d pagePath -m screenPageViews --json --start 7daysAgo | claude "What are the top performing pages?"

# Monitor in scripts
gac realtime -d country -m activeUsers --json

Configuration Files

File Location (macOS) Purpose
Config ~/Library/Application Support/gac/config.yaml Settings
Tokens System Keyring (file fallback in config dir) OAuth tokens
Service Account ~/Library/Application Support/gac/service-account-path SA key path reference

Linux uses ~/.config/gac/ (or $XDG_CONFIG_HOME/gac/). Windows uses %APPDATA%\gac\.

API Quotas

gac includes built-in rate limiting to stay within GA4 API quotas:

Quota Limit Scope
Hourly 1,250 requests Per project
Daily 25,000 requests Per project

If you hit quota limits, gac will report the error with a hint to wait and retry.

Building

make build        # Build binary to ./bin/gac
make test         # Run all tests
make lint         # Run go vet + staticcheck
make install      # Install to $GOPATH/bin
make coverage     # Generate coverage report
make clean        # Remove build artifacts

Requirements

  • Go 1.23+
  • A Google Cloud project with the Google Analytics Data API and Admin API enabled
  • A GA4 property with appropriate access

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors