Skip to content
Merged
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
48 changes: 48 additions & 0 deletions internal/cmd/analytics_reports.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,15 @@ func (c *AnalyticsBatchReportsCmd) Run(ctx context.Context, flags *RootFlags) er
"reports": resp.Reports,
})
}
if outfmt.IsPlain(ctx) {
w, flush := tableWriter(ctx)
defer flush()
writeTableRow(ctx, w, []string{"REPORT_INDEX", "ROW_INDEX", "FIELD_KIND", "FIELD_NAME", "FIELD_VALUE"})
for reportIndex, report := range resp.Reports {
writeAnalyticsBatchPlainRows(ctx, w, reportIndex+1, report.DimensionHeaders, report.MetricHeaders, report.Rows)
}
return nil
}

u := ui.FromContext(ctx)
if len(resp.Reports) == 0 {
Expand Down Expand Up @@ -245,6 +254,36 @@ func (c *AnalyticsBatchReportsCmd) Run(ctx context.Context, flags *RootFlags) er
return nil
}

func writeAnalyticsBatchPlainRows(
ctx context.Context,
w io.Writer,
reportIndex int,
dimensionHeaders []*analyticsdata.DimensionHeader,
metricHeaders []*analyticsdata.MetricHeader,
rows []*analyticsdata.Row,
) {
for rowIndex, row := range rows {
for fieldIndex, value := range row.DimensionValues {
fieldName := ""
if fieldIndex < len(dimensionHeaders) {
fieldName = dimensionHeaders[fieldIndex].Name
}
writeTableRow(ctx, w, []string{
fmt.Sprint(reportIndex), fmt.Sprint(rowIndex + 1), "DIMENSION", fieldName, value.Value,
})
}
for fieldIndex, value := range row.MetricValues {
fieldName := ""
if fieldIndex < len(metricHeaders) {
fieldName = metricHeaders[fieldIndex].Name
}
writeTableRow(ctx, w, []string{
fmt.Sprint(reportIndex), fmt.Sprint(rowIndex + 1), "METRIC", fieldName, value.Value,
})
}
}
}

// --- batch-pivot-reports ---

type AnalyticsBatchPivotReportsCmd struct {
Expand Down Expand Up @@ -298,6 +337,15 @@ func (c *AnalyticsBatchPivotReportsCmd) Run(ctx context.Context, flags *RootFlag
"pivotReports": resp.PivotReports,
})
}
if outfmt.IsPlain(ctx) {
w, flush := tableWriter(ctx)
defer flush()
writeTableRow(ctx, w, []string{"REPORT_INDEX", "ROW_INDEX", "FIELD_KIND", "FIELD_NAME", "FIELD_VALUE"})
for reportIndex, report := range resp.PivotReports {
writeAnalyticsBatchPlainRows(ctx, w, reportIndex+1, report.DimensionHeaders, report.MetricHeaders, report.Rows)
}
return nil
}

u := ui.FromContext(ctx)
if len(resp.PivotReports) == 0 {
Expand Down
83 changes: 74 additions & 9 deletions internal/cmd/analytics_tsv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ const (
unsafeAnalyticsDimensionValue = "dimension\rvalue"
unsafeAnalyticsMetricValue = "metric\r\nvalue"
analyticsSafeTSV = "dimension name\tmetric name\ndimension value\tmetric value\n"
analyticsBatchSafeTSV = "REPORT_INDEX\tROW_INDEX\tFIELD_KIND\tFIELD_NAME\tFIELD_VALUE\n" +
"1\t1\tDIMENSION\tdimension name\tdimension value\n" +
"1\t1\tMETRIC\tmetric name\tmetric value\n" +
"3\t1\tDIMENSION\tdevice\tMobile\n" +
"3\t1\tMETRIC\tviews\t7\n" +
"3\t2\tDIMENSION\tdevice\tDesktop\n" +
"3\t2\tMETRIC\tviews\t9\n"
)

func analyticsUnsafeReport() map[string]any {
Expand All @@ -33,6 +40,33 @@ func analyticsUnsafeReport() map[string]any {
}
}

func analyticsBatchLongFormReports() []map[string]any {
return []map[string]any{
analyticsUnsafeReport(),
{
"dimensionHeaders": []map[string]any{{"name": "city"}},
"metricHeaders": []map[string]any{{"name": "users", "type": "TYPE_INTEGER"}},
"rows": []map[string]any{},
"rowCount": 0,
},
{
"dimensionHeaders": []map[string]any{{"name": "device"}},
"metricHeaders": []map[string]any{{"name": "views", "type": "TYPE_INTEGER"}},
"rows": []map[string]any{
{
"dimensionValues": []map[string]any{{"value": "Mobile"}},
"metricValues": []map[string]any{{"value": "7"}},
},
{
"dimensionValues": []map[string]any{{"value": "Desktop"}},
"metricValues": []map[string]any{{"value": "9"}},
},
},
"rowCount": 2,
},
}
}

func analyticsTSVTestServer(t *testing.T) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -51,14 +85,9 @@ func analyticsTSVTestServer(t *testing.T) *httptest.Server {
}},
}}
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, ":batchRunReports"):
response = map[string]any{"reports": []map[string]any{analyticsUnsafeReport()}}
response = map[string]any{"reports": analyticsBatchLongFormReports()}
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, ":batchRunPivotReports"):
report := analyticsUnsafeReport()
report["dimensionHeaders"] = []map[string]any{
{"name": unsafeAnalyticsDimensionHeader},
{"name": unsafeAnalyticsMetricHeader},
}
response = map[string]any{"pivotReports": []map[string]any{report}}
response = map[string]any{"pivotReports": analyticsBatchLongFormReports()}
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, ":query"):
response = map[string]any{
"audienceExport": map[string]any{
Expand Down Expand Up @@ -131,12 +160,12 @@ func TestAnalyticsReports_PlainTSVPreservesRows(t *testing.T) {
{
name: "batch",
command: []string{"analytics", "batch-reports", "--property", "456", "--requests-json", `[{}]`},
want: "Report 1: 1 rows\n" + analyticsSafeTSV,
want: analyticsBatchSafeTSV,
},
{
name: "batch pivot",
command: []string{"analytics", "batch-pivot-reports", "--property", "456", "--requests-json", `[{"pivots":[{"fieldNames":["browser"]}]}]`},
want: "Pivot Report 1\n" + analyticsSafeTSV,
want: analyticsBatchSafeTSV,
},
{
name: "audience",
Expand All @@ -162,6 +191,42 @@ func TestAnalyticsReports_PlainTSVPreservesRows(t *testing.T) {
}
}

func TestAnalyticsBatchReports_PlainEmptyResponsesEmitHeader(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, ":batchRunReports"):
_ = json.NewEncoder(w).Encode(map[string]any{"reports": []any{}})
case strings.HasSuffix(r.URL.Path, ":batchRunPivotReports"):
_ = json.NewEncoder(w).Encode(map[string]any{"pivotReports": []any{}})
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
setupAnalyticsTSVService(t, srv)

commands := [][]string{
{"analytics", "batch-reports", "--property", "456", "--requests-json", `[{}]`},
{"analytics", "batch-pivot-reports", "--property", "456", "--requests-json", `[{"pivots":[{"fieldNames":["browser"]}]}]`},
}
const want = "REPORT_INDEX\tROW_INDEX\tFIELD_KIND\tFIELD_NAME\tFIELD_VALUE\n"

for _, command := range commands {
out := captureStdout(t, func() {
_ = captureStderr(t, func() {
args := append([]string{"--plain", "--account", "a@b.com"}, command...)
if err := Execute(args); err != nil {
t.Fatalf("Execute(%q): %v", command[1], err)
}
})
})
if out != want {
t.Fatalf("%s plain output = %q, want %q", command[1], out, want)
}
}
}

func TestAnalyticsReport_JSONPreservesUnsafeStrings(t *testing.T) {
srv := analyticsTSVTestServer(t)
defer srv.Close()
Expand Down
Loading