1// Copyright 2024 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package telemetrycmd implements the "go telemetry" command.
6package telemetrycmd
7
8import (
9	"context"
10	"fmt"
11	"os"
12
13	"cmd/go/internal/base"
14	"cmd/internal/telemetry"
15)
16
17var CmdTelemetry = &base.Command{
18	UsageLine: "go telemetry [off|local|on]",
19	Short:     "manage telemetry data and settings",
20	Long: `Telemetry is used to manage Go telemetry data and settings.
21
22Telemetry can be in one of three modes: off, local, or on.
23
24When telemetry is in local mode, counter data is written to the local file
25system, but will not be uploaded to remote servers.
26
27When telemetry is off, local counter data is neither collected nor uploaded.
28
29When telemetry is on, telemetry data is written to the local file system
30and periodically sent to https://telemetry.go.dev/. Uploaded data is used to
31help improve the Go toolchain and related tools, and it will be published as
32part of a public dataset.
33
34For more details, see https://telemetry.go.dev/privacy.
35This data is collected in accordance with the Google Privacy Policy
36(https://policies.google.com/privacy).
37
38To view the current telemetry mode, run "go telemetry".
39To disable telemetry uploading, but keep local data collection, run
40"go telemetry local".
41To enable both collection and uploading, rungo telemetry on”.
42To disable both collection and uploading, run "go telemetry off".
43
44See https://go.dev/doc/telemetry for more information on telemetry.
45`,
46	Run: runTelemetry,
47}
48
49func init() {
50	base.AddChdirFlag(&CmdTelemetry.Flag)
51}
52
53func runTelemetry(ctx context.Context, cmd *base.Command, args []string) {
54	if len(args) == 0 {
55		fmt.Println(telemetry.Mode())
56		return
57	}
58
59	if len(args) != 1 {
60		cmd.Usage()
61	}
62
63	mode := args[0]
64	if mode != "local" && mode != "off" && mode != "on" {
65		cmd.Usage()
66	}
67	if old := telemetry.Mode(); old == mode {
68		return
69	}
70
71	if err := telemetry.SetMode(mode); err != nil {
72		base.Fatalf("go: failed to set the telemetry mode to %s: %v", mode, err)
73	}
74	if mode == "on" {
75		fmt.Fprintln(os.Stderr, telemetryOnMessage())
76	}
77}
78
79func telemetryOnMessage() string {
80	return `Telemetry uploading is now enabled and data will be periodically sent to
81https://telemetry.go.dev/. Uploaded data is used to help improve the Go
82toolchain and related tools, and it will be published as part of a public
83dataset.
84
85For more details, see https://telemetry.go.dev/privacy.
86This data is collected in accordance with the Google Privacy Policy
87(https://policies.google.com/privacy).
88
89To disable telemetry uploading, but keep local data collection, run
90go telemetry local”.
91To disable both collection and uploading, rungo telemetry off“.`
92}
93