github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/analytics/client/sync/reporters/test.go (about)

     1  package reporters
     2  
     3  import (
     4  	"encoding/json"
     5  	"path/filepath"
     6  
     7  	"github.com/ActiveState/cli/internal/analytics/dimensions"
     8  	"github.com/ActiveState/cli/internal/errs"
     9  	"github.com/ActiveState/cli/internal/fileutils"
    10  	"github.com/ActiveState/cli/internal/installation/storage"
    11  	"github.com/ActiveState/cli/internal/logging"
    12  )
    13  
    14  type TestReporter struct {
    15  	path string
    16  }
    17  
    18  const TestReportFilename = "analytics.log"
    19  
    20  func TestReportFilepath() string {
    21  	appdata, err := storage.AppDataPath()
    22  	if err != nil {
    23  		logging.Warning("Could not acquire appdata path, using cwd instead. Error received: %s", errs.JoinMessage(err))
    24  	}
    25  	return filepath.Join(appdata, TestReportFilename)
    26  }
    27  
    28  func NewTestReporter(path string) *TestReporter {
    29  	return &TestReporter{path}
    30  }
    31  
    32  func (r *TestReporter) ID() string {
    33  	return "TestReporter"
    34  }
    35  
    36  type TestLogEntry struct {
    37  	Category   string
    38  	Action     string
    39  	Source     string
    40  	Label      string
    41  	Dimensions *dimensions.Values
    42  }
    43  
    44  func (r *TestReporter) Event(category, action, source, label string, d *dimensions.Values) error {
    45  	b, err := json.Marshal(TestLogEntry{category, action, source, label, d})
    46  	if err != nil {
    47  		return errs.Wrap(err, "Could not marshal test log entry")
    48  	}
    49  	b = append(b, []byte("\n\x00")...)
    50  
    51  	if err := fileutils.AmendFileLocked(r.path, b, fileutils.AmendByAppend); err != nil {
    52  		return errs.Wrap(err, "Could not write to file")
    53  	}
    54  	return nil
    55  }