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//go:build !cmd_go_bootstrap && !compiler_bootstrap
6
7package counter
8
9import (
10	"flag"
11	"os"
12
13	"golang.org/x/telemetry/counter"
14)
15
16var openCalled bool
17
18func OpenCalled() bool { return openCalled }
19
20// Open opens the counter files for writing if telemetry is supported
21// on the current platform (and does nothing otherwise).
22func Open() {
23	openCalled = true
24	counter.OpenDir(os.Getenv("TEST_TELEMETRY_DIR"))
25}
26
27// Inc increments the counter with the given name.
28func Inc(name string) {
29	counter.Inc(name)
30}
31
32// New returns a counter with the given name.
33func New(name string) *counter.Counter {
34	return counter.New(name)
35}
36
37// NewStack returns a new stack counter with the given name and depth.
38func NewStack(name string, depth int) *counter.StackCounter {
39	return counter.NewStack(name, depth)
40}
41
42// CountFlags creates a counter for every flag that is set
43// and increments the counter. The name of the counter is
44// the concatenation of prefix and the flag name.
45func CountFlags(prefix string, flagSet flag.FlagSet) {
46	counter.CountFlags(prefix, flagSet)
47}
48
49// CountFlagValue creates a counter for the flag value
50// if it is set and increments the counter. The name of the
51// counter is the concatenation of prefix, the flagName, ":",
52// and value.String() for the flag's value.
53func CountFlagValue(prefix string, flagSet flag.FlagSet, flagName string) {
54	// TODO(matloob): Maybe pass in a list of flagNames if we end up counting
55	// values for more than one?
56	// TODO(matloob): Add this to x/telemetry?
57	flagSet.Visit(func(f *flag.Flag) {
58		if f.Name == flagName {
59			counter.New(prefix + f.Name + ":" + f.Value.String()).Inc()
60		}
61	})
62}
63