repo_id
stringclasses 927
values | file_path
stringlengths 99
214
| content
stringlengths 2
4.15M
|
|---|---|---|
gotelemetry
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/cmd/gotelemetry/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go test -run=TestDocHelp -update
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"golang.org/x/telemetry/cmd/gotelemetry/internal/csv"
"golang.org/x/telemetry/cmd/gotelemetry/internal/view"
"golang.org/x/telemetry/internal/counter"
"golang.org/x/telemetry/internal/telemetry"
"golang.org/x/telemetry/internal/upload"
)
type command struct {
usage string
short string
long string
flags *flag.FlagSet
hasArgs bool
run func([]string)
}
func (c command) name() string {
name, _, _ := strings.Cut(c.usage, " ")
return name
}
var (
viewFlags = flag.NewFlagSet("view", flag.ExitOnError)
viewServer view.Server
normalCommands = []*command{
{
usage: "on",
short: "enable telemetry collection and uploading",
long: `Gotelemetry on enables telemetry collection and uploading.
When telemetry is enabled, telemetry data is written to the local file system and periodically sent to https://telemetry.go.dev/. Uploaded data is used to help improve the Go toolchain and related tools, and it will be published as part of a public dataset.
For more details, see https://telemetry.go.dev/privacy.
This data is collected in accordance with the Google Privacy Policy (https://policies.google.com/privacy).
To disable telemetry uploading, but keep local data collection, run “gotelemetry local”.
To disable both collection and uploading, run “gotelemetry off“.
`,
run: runOn,
},
{
usage: "local",
short: "enable telemetry collection but disable uploading",
long: `Gotelemetry local enables telemetry collection but not uploading.
When telemetry is in local mode, counter data is written to the local file system, but will not be uploaded to remote servers.
To enable telemetry uploading, run “gotelemetry on”.
To disable both collection and uploading, run “gotelemetry off”`,
run: runLocal,
},
{
usage: "off",
short: "disable telemetry collection and uploading",
long: `Gotelemetry off disables telemetry collection and uploading.
When telemetry is disabled, local counter data is neither collected nor uploaded.
To enable local collection (but not uploading) of telemetry data, run “gotelemetry local“.
To enable both collection and uploading, run “gotelemetry on”.`,
run: runOff,
},
{
usage: "view [flags]",
short: "run a web viewer for local telemetry data",
long: `Gotelemetry view runs a web viewer for local telemetry data.
This viewer displays charts for locally collected data, as well as information about the current upload configuration.`,
flags: viewFlags,
run: runView,
},
{
usage: "env",
short: "print the current telemetry environment",
run: runEnv,
},
{
usage: "clean",
short: "remove all local telemetry data",
long: `Gotelemetry clean removes locally collected counters and reports.
Removing counter files that are currently in use may fail on some operating
systems.
Gotelemetry clean does not affect the current telemetry mode.`,
run: runClean,
},
}
experimentalCommands = []*command{
{
usage: "csv",
short: "print all known counters",
run: runCSV,
},
{
usage: "dump [files]",
short: "view counter file data",
run: runDump,
hasArgs: true,
},
{
usage: "upload",
short: "run upload with logging enabled",
run: runUpload,
},
}
)
func init() {
viewFlags.StringVar(&viewServer.Addr, "addr", "localhost:4040", "server listens on the given TCP network address")
viewFlags.BoolVar(&viewServer.Dev, "dev", false, "rebuild static assets on save")
viewFlags.StringVar(&viewServer.FsConfig, "config", "", "load a config from the filesystem")
viewFlags.BoolVar(&viewServer.Open, "open", true, "open the browser to the server address")
for _, cmd := range append(normalCommands, experimentalCommands...) {
name := cmd.name()
if cmd.flags == nil {
cmd.flags = flag.NewFlagSet(name, flag.ExitOnError)
}
cmd.flags.Usage = func() {
help(name)
}
}
}
func output(msgs ...any) {
fmt.Fprintln(flag.CommandLine.Output(), msgs...)
}
func usage() {
printCommand := func(cmd *command) {
output(fmt.Sprintf("\t%s\t%s", cmd.name(), cmd.short))
}
output("Gotelemetry is a tool for managing Go telemetry data and settings.")
output()
output("Usage:")
output()
output("\tgotelemetry <command> [arguments]")
output()
output("The commands are:")
output()
for _, cmd := range normalCommands {
printCommand(cmd)
}
output()
output("Use \"gotelemetry help <command>\" for details about any command.")
output()
output("The following additional commands are available for diagnostic")
output("purposes, and may change or be removed in the future:")
output()
for _, cmd := range experimentalCommands {
printCommand(cmd)
}
}
func failf(format string, args ...any) {
fmt.Fprintf(os.Stderr, format, args...)
os.Exit(1)
}
func warnf(format string, args ...any) {
fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...)
}
func findCommand(name string) *command {
for _, cmd := range append(normalCommands, experimentalCommands...) {
if cmd.name() == name {
return cmd
}
}
return nil
}
func help(name string) {
cmd := findCommand(name)
if cmd == nil {
failf("unknown command %q", name)
}
output(fmt.Sprintf("Usage: gotelemetry %s", cmd.usage))
output()
if cmd.long != "" {
output(cmd.long)
} else {
output(fmt.Sprintf("Gotelemetry %s is used to %s.", cmd.name(), cmd.short))
}
anyflags := false
cmd.flags.VisitAll(func(*flag.Flag) {
anyflags = true
})
if anyflags {
output()
output("Flags:")
output()
cmd.flags.PrintDefaults()
}
}
func runOn(_ []string) {
if old, _ := telemetry.Default.Mode(); old == "on" {
return
}
if err := telemetry.Default.SetMode("on"); err != nil {
failf("Failed to enable telemetry: %v", err)
}
// We could perhaps only show the telemetry on message when the mode goes
// from off->on (i.e. check the previous state before calling setMode),
// but that seems like an unnecessary optimization.
fmt.Fprintln(os.Stderr, telemetryOnMessage())
}
func telemetryOnMessage() string {
return `Telemetry uploading is now enabled.
Data will be sent periodically to https://telemetry.go.dev/.
Uploaded data is used to help improve the Go toolchain and related tools,
and it will be published as part of a public dataset.
For more details, see https://telemetry.go.dev/privacy.
This data is collected in accordance with the Google Privacy Policy
(https://policies.google.com/privacy).
To disable telemetry uploading, but keep local data collection,
run “gotelemetry local”.
To disable both collection and uploading, run “gotelemetry off“.`
}
func runLocal(_ []string) {
if old, _ := telemetry.Default.Mode(); old == "local" {
return
}
if err := telemetry.Default.SetMode("local"); err != nil {
failf("Failed to set the telemetry mode to local: %v", err)
}
}
func runOff(_ []string) {
if old, _ := telemetry.Default.Mode(); old == "off" {
return
}
if err := telemetry.Default.SetMode("off"); err != nil {
failf("Failed to disable telemetry: %v", err)
}
}
func runView(_ []string) {
viewServer.Serve()
}
func runEnv(_ []string) {
m, t := telemetry.Default.Mode()
fmt.Printf("mode: %s %s\n", m, t)
fmt.Println()
fmt.Println("modefile:", telemetry.Default.ModeFile())
fmt.Println("localdir:", telemetry.Default.LocalDir())
fmt.Println("uploaddir:", telemetry.Default.UploadDir())
}
func runClean(_ []string) {
// For now, be careful to only remove counter files and reports.
// It would probably be OK to just remove everything, but it may
// be useful to preserve the weekends file.
for dir, suffixes := range map[string][]string{
telemetry.Default.LocalDir(): {"." + counter.FileVersion + ".count", ".json"},
telemetry.Default.UploadDir(): {".json"},
} {
entries, err := os.ReadDir(dir)
if err != nil {
if !os.IsNotExist(err) {
warnf("failed to read telemetry dir: %v", err)
}
continue
}
for _, entry := range entries {
// TODO: use slices.ContainsFunc once it is available in all supported Go
// versions.
remove := false
for _, suffix := range suffixes {
if strings.HasSuffix(entry.Name(), suffix) {
remove = true
break
}
}
if remove {
path := filepath.Join(dir, entry.Name())
if err := os.Remove(path); err != nil {
warnf("failed to remove %s: %v", path, err)
}
}
}
}
}
func runCSV(_ []string) {
csv.Csv()
}
func runDump(args []string) {
if len(args) == 0 {
localdir := telemetry.Default.LocalDir()
fi, err := os.ReadDir(localdir)
if err != nil && len(args) == 0 {
log.Fatal(err)
}
for _, f := range fi {
args = append(args, filepath.Join(localdir, f.Name()))
}
}
for _, file := range args {
if !strings.HasSuffix(file, ".count") {
log.Printf("%s: not a counter file, skipping", file)
continue
}
data, err := os.ReadFile(file)
if err != nil {
log.Printf("%v, skipping", err)
continue
}
f, err := counter.Parse(file, data)
if err != nil {
log.Printf("%v, skipping", err)
continue
}
js, err := json.MarshalIndent(f, "", "\t")
if err != nil {
log.Printf("%s: failed to print - %v", file, err)
}
fmt.Printf("-- %v --\n%s\n", file, js)
}
}
func runUpload(_ []string) {
if err := upload.Run(upload.RunConfig{
LogWriter: os.Stderr,
}); err != nil {
fmt.Printf("Upload failed: %v\n", err)
} else {
fmt.Println("Upload completed.")
}
}
func main() {
log.SetFlags(0)
flag.Usage = usage
flag.Parse()
args := flag.Args()
if flag.NArg() == 0 {
flag.Usage()
os.Exit(2)
}
if args[0] == "help" {
flag.CommandLine.SetOutput(os.Stdout)
switch len(args) {
case 1:
flag.Usage()
case 2:
help(args[1])
default:
flag.Usage()
failf("too many arguments to \"help\"")
}
os.Exit(0)
}
cmd := findCommand(args[0])
if cmd == nil {
flag.Usage()
os.Exit(2)
}
cmd.flags.Parse(args[1:]) // will exit on error
args = cmd.flags.Args()
if !cmd.hasArgs && len(args) > 0 {
help(cmd.name())
failf("command %s does not accept any arguments", cmd.name())
}
cmd.run(args)
}
|
browser
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/cmd/gotelemetry/internal/browser/browser.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package browser provides utilities for interacting with users' browsers.
// This is a copy of the go project's src/cmd/internal/browser.
package browser
import (
"os"
"os/exec"
"runtime"
"time"
)
// Commands returns a list of possible commands to use to open a url.
func Commands() [][]string {
var cmds [][]string
if exe := os.Getenv("BROWSER"); exe != "" {
cmds = append(cmds, []string{exe})
}
switch runtime.GOOS {
case "darwin":
cmds = append(cmds, []string{"/usr/bin/open"})
case "windows":
cmds = append(cmds, []string{"cmd", "/c", "start"})
default:
if os.Getenv("DISPLAY") != "" {
// xdg-open is only for use in a desktop environment.
cmds = append(cmds, []string{"xdg-open"})
}
}
cmds = append(cmds,
[]string{"chrome"},
[]string{"google-chrome"},
[]string{"chromium"},
[]string{"firefox"},
)
return cmds
}
// Open tries to open url in a browser and reports whether it succeeded.
func Open(url string) bool {
for _, args := range Commands() {
cmd := exec.Command(args[0], append(args[1:], url)...)
if cmd.Start() == nil && appearsSuccessful(cmd, 3*time.Second) {
return true
}
}
return false
}
// appearsSuccessful reports whether the command appears to have run successfully.
// If the command runs longer than the timeout, it's deemed successful.
// If the command runs within the timeout, it's deemed successful if it exited cleanly.
func appearsSuccessful(cmd *exec.Cmd, timeout time.Duration) bool {
errc := make(chan error, 1)
go func() {
errc <- cmd.Wait()
}()
select {
case <-time.After(timeout):
return true
case err := <-errc:
return err == nil
}
}
|
view
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/cmd/gotelemetry/internal/view/README.md
|
# Go Telemetry View
Telemetry data it is stored in files on the user machine. Users can run the
command `gotelemetry view` to view the data in a browser. The HTML page served
by the command will generate graphs based on the local copies of report uploads
and active counter files.
## Development
The static files are generated with a generator command. You can edit the source
files and run go generate to rebuild them.
go generate ./content
Running the server with the `--dev` flag will watch and rebuild the static files
on save.
go run ./cmd/gotelemetry view --dev
|
view
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/cmd/gotelemetry/internal/view/view_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The view command is a server intended to be run on a users machine to
// display the local counters and time series charts of counters.
package view
import (
"fmt"
"html/template"
"reflect"
"testing"
"time"
"golang.org/x/telemetry/internal/config"
"golang.org/x/telemetry/internal/telemetry"
)
func Test_summary(t *testing.T) {
type args struct {
cfg *config.Config
meta map[string]string
counts map[string]uint64
}
cfg := config.NewConfig(&telemetry.UploadConfig{
GOOS: []string{"linux"},
GOARCH: []string{"amd64"},
GoVersion: []string{"go1.20.1"},
Programs: []*telemetry.ProgramConfig{
{
Name: "gopls",
Versions: []string{"v1.2.3"},
Counters: []telemetry.CounterConfig{
{Name: "editor"},
},
},
},
})
tests := []struct {
name string
args args
want template.HTML
}{
{
"empty summary",
args{
cfg: cfg,
meta: map[string]string{"Program": "gopls", "Version": "v1.2.3", "GOOS": "linux", "GOARCH": "amd64", "GoVersion": "go1.20.1"},
counts: map[string]uint64{"editor": 10},
},
template.HTML(""),
},
{
"empty config/unknown program",
args{
cfg: config.NewConfig(&telemetry.UploadConfig{}),
meta: map[string]string{"Program": "gopls", "Version": "v1.2.3", "GOOS": "linux", "GOARCH": "amd64", "GoVersion": "go1.20.1"},
counts: map[string]uint64{"editor": 10},
},
template.HTML("The program <code>gopls</code> is unregistered. No data from this set would be uploaded to the Go team."),
},
{
"unknown counter",
args{
cfg: cfg,
meta: map[string]string{"Program": "gopls", "Version": "v1.2.3", "GOOS": "linux", "GOARCH": "amd64", "GoVersion": "go1.20.1"},
counts: map[string]uint64{"editor": 10, "foobar": 10},
},
template.HTML("Unregistered counter(s) <code>foobar</code> would be excluded from a report. "),
},
{
"unknown goos",
args{
cfg: cfg,
meta: map[string]string{"Program": "gopls", "Version": "v1.2.3", "GOOS": "windows", "GOARCH": "arm64", "GoVersion": "go1.20.1"},
counts: map[string]uint64{"editor": 10, "foobar": 10},
},
template.HTML("The GOOS/GOARCH combination <code>windows/arm64</code> is unregistered. No data from this set would be uploaded to the Go team."),
},
{
"multiple unknown fields",
args{
cfg: cfg,
meta: map[string]string{"Program": "gopls", "Version": "v1.2.5", "GOOS": "linux", "GOARCH": "amd64", "GoVersion": "go1.25.1"},
counts: map[string]uint64{"editor": 10, "foobar": 10},
},
template.HTML("The go version <code>go1.25.1</code> is unregistered. No data from this set would be uploaded to the Go team."),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := summary(tt.args.cfg, tt.args.meta, tt.args.counts)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("summary() = %q, want %q", got, tt.want)
}
})
}
}
func Test_reportsDomain(t *testing.T) {
mustParseDate := func(date string) time.Time {
ts, err := time.Parse(time.DateOnly, date)
if err != nil {
t.Fatalf("failed to parse date %q: %v", date, err)
}
return ts
}
tests := []struct {
name string
reportDates []string
want [2]time.Time
wantErr bool
}{
{
name: "empty",
wantErr: true,
},
{
name: "one",
reportDates: []string{"2024-01-08"},
want: [2]time.Time{mustParseDate("2024-01-01"), mustParseDate("2024-01-08")},
},
{
name: "two",
reportDates: []string{"2024-04-08", "2024-06-01"},
want: [2]time.Time{mustParseDate("2024-04-01"), mustParseDate("2024-06-01")},
},
{
name: "three",
reportDates: []string{"2024-04-08", "2024-01-08", "2024-06-01"},
want: [2]time.Time{mustParseDate("2024-01-01"), mustParseDate("2024-06-01")},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reports := make([]*telemetryReport, len(tt.reportDates))
for i, date := range tt.reportDates {
weekEnd, err := parseReportDate(date)
if err != nil {
t.Fatalf("parseReport(%v) failed: %v", date, err)
}
reports[i] = &telemetryReport{
WeekEnd: weekEnd,
ID: fmt.Sprintf("report-%d", i),
}
}
got, err := reportsDomain(reports)
if tt.wantErr && err == nil ||
err == nil && !reflect.DeepEqual(got, tt.want) {
t.Errorf("reportsDomain() = (%v, %v), want (%v, err=%v)", got, err, tt.want, tt.wantErr)
}
})
}
}
|
view
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/cmd/gotelemetry/internal/view/view.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The view command is a server intended to be run on a user's machine to
// display the local counters and time series charts of counters.
package view
import (
"bytes"
"encoding/json"
"fmt"
"html"
"html/template"
"io/fs"
"log"
"net"
"net/http"
"os"
"path"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/telemetry/cmd/gotelemetry/internal/browser"
"golang.org/x/telemetry/internal/config"
"golang.org/x/telemetry/internal/configstore"
contentfs "golang.org/x/telemetry/internal/content"
tcounter "golang.org/x/telemetry/internal/counter"
"golang.org/x/telemetry/internal/telemetry"
"golang.org/x/telemetry/internal/unionfs"
)
type Server struct {
Addr string
Dev bool
FsConfig string
Open bool
}
// Serve starts the telemetry viewer and runs indefinitely.
func (s *Server) Serve() {
var fsys fs.FS = contentfs.FS
if s.Dev {
fsys = os.DirFS("internal/content")
contentfs.RunESBuild(true)
}
var err error
fsys, err = unionfs.Sub(fsys, "gotelemetryview", "shared")
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/", s.handleIndex(fsys))
listener, err := net.Listen("tcp", s.Addr)
if err != nil {
log.Fatal(err)
}
addr := fmt.Sprintf("http://%s", listener.Addr())
fmt.Printf("server listening at %s\n", addr)
if s.Open {
browser.Open(addr)
}
log.Fatal(http.Serve(listener, mux))
}
type page struct {
// Config is the config used to render the requested page.
Config *config.Config
// PrettyConfig is the Config struct formatted as indented JSON for display on the page.
PrettyConfig string
// ConfigVersion is used to render a dropdown list of config versions for a user to select.
ConfigVersions []string
// RequestedConfig is the URL query param value for config.
RequestedConfig string
// Files are the local counter files for display on the page.
Files []*counterFile
// Reports are the local reports for display on the page.
Reports []*telemetryReport
// Charts is the counter data from files and reports grouped by program and counter name.
Charts *chartdata
}
// TODO: filtering and pagination for date ranges
func (s *Server) handleIndex(fsys fs.FS) handlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
if r.URL.Path != "/" {
http.FileServer(http.FS(fsys)).ServeHTTP(w, r)
return nil
}
requestedConfig := r.URL.Query().Get("config")
if requestedConfig == "" {
requestedConfig = "latest"
}
cfg, err := s.configAt(requestedConfig)
if err != nil {
log.Printf("Falling back to empty config: %v", err)
cfg, _ = s.configAt("empty")
}
cfgVersionList, err := configVersions()
if err != nil {
return err
}
cfgJSON, err := json.MarshalIndent(cfg, "", "\t")
if err != nil {
return err
}
localDir := telemetry.Default.LocalDir()
if _, err := os.Stat(localDir); err != nil {
return fmt.Errorf(
`The telemetry dir %s does not exist.
There is nothing to report.`, telemetry.Default.LocalDir())
}
reports, err := reports(localDir, cfg)
if err != nil {
return err
}
files, err := files(localDir, cfg)
if err != nil {
return err
}
charts, err := charts(append(reports, pending(files, cfg)...), cfg)
if err != nil {
return err
}
data := page{
Config: cfg,
PrettyConfig: string(cfgJSON),
ConfigVersions: cfgVersionList,
Reports: reports,
Files: files,
Charts: charts,
RequestedConfig: requestedConfig,
}
return renderTemplate(w, fsys, "index.html", data, http.StatusOK)
}
}
// configAt gets the config at a given version.
func (s Server) configAt(version string) (ucfg *config.Config, err error) {
if version == "" || version == "empty" {
return config.NewConfig(&telemetry.UploadConfig{}), nil
}
if s.FsConfig != "" {
ucfg, err = config.ReadConfig(s.FsConfig)
if err != nil {
return nil, err
}
} else {
cfg, _, err := configstore.Download(version, nil)
if err != nil {
return nil, err
}
ucfg = config.NewConfig(cfg)
}
return ucfg, nil
}
// configVersions is the set of config versions the user may select from the UI.
// TODO: get the list of versions available from the proxy.
func configVersions() ([]string, error) {
v := []string{"latest"}
return v, nil
}
// reports reads the local report files from a directory.
func reports(dir string, cfg *config.Config) ([]*telemetryReport, error) {
fsys := os.DirFS(dir)
entries, err := fs.ReadDir(fsys, ".")
if err != nil {
return nil, err
}
var reports []*telemetryReport
for _, e := range entries {
if path.Ext(e.Name()) != ".json" {
continue
}
data, err := fs.ReadFile(fsys, e.Name())
if err != nil {
log.Printf("read report file failed: %v", err)
continue
}
var report *telemetry.Report
if err := json.Unmarshal(data, &report); err != nil {
log.Printf("unmarshal report file %v failed: %v, skipping...", e.Name(), err)
continue
}
wrapped, err := newTelemetryReport(report, cfg)
if err != nil {
log.Printf("processing report file %v failed: %v, skipping", e.Name(), err)
continue
}
reports = append(reports, wrapped)
}
// sort the reports descending by week.
sort.Slice(reports, func(i, j int) bool {
return reports[j].Week < reports[i].Week
})
return reports, nil
}
// telemetryReport wraps telemetry report to add convenience fields for the UI.
type telemetryReport struct {
*telemetry.Report
ID string
WeekEnd time.Time // parsed telemetry.Report.Week
Programs []*telemetryProgram
}
type telemetryProgram struct {
*telemetry.ProgramReport
ID string
Summary template.HTML
}
func newTelemetryReport(t *telemetry.Report, cfg *config.Config) (*telemetryReport, error) {
weekEnd, err := parseReportDate(t.Week)
if err != nil {
return nil, fmt.Errorf("unexpected Week %q in the report", t.Week)
}
var prgms []*telemetryProgram
for _, p := range t.Programs {
meta := map[string]string{
"Program": p.Program,
"Version": p.Version,
"GOOS": p.GOOS,
"GOARCH": p.GOARCH,
"GoVersion": p.GoVersion,
}
counters := make(map[string]uint64)
for k, v := range p.Counters {
counters[k] = uint64(v)
}
prgms = append(prgms, &telemetryProgram{
ProgramReport: p,
ID: strings.Join([]string{"reports", t.Week, p.Program, p.Version, p.GOOS, p.GOARCH, p.GoVersion}, ":"),
Summary: summary(cfg, meta, counters),
})
}
return &telemetryReport{
Report: t,
WeekEnd: weekEnd,
ID: "reports:" + t.Week,
Programs: prgms,
}, nil
}
// files reads the local counter files from a directory.
func files(dir string, cfg *config.Config) ([]*counterFile, error) {
fsys := os.DirFS(dir)
entries, err := fs.ReadDir(fsys, ".")
if err != nil {
return nil, err
}
var files []*counterFile
for _, e := range entries {
if e.IsDir() || path.Ext(e.Name()) != ".count" {
continue
}
data, err := fs.ReadFile(fsys, e.Name())
if err != nil {
log.Printf("read counter file failed: %v", err)
continue
}
file, err := tcounter.Parse(e.Name(), data)
if err != nil {
log.Printf("parse counter file failed: %v", err)
continue
}
files = append(files, newCounterFile(e.Name(), file, cfg))
}
return files, nil
}
// counterFile wraps counter file to add convenience fields for the UI.
type counterFile struct {
*tcounter.File
ID string
Summary template.HTML
ActiveMeta map[string]bool
Counts []*count
Stacks []*stack
}
type count struct {
Name string
Value uint64
Active bool
}
type stack struct {
Name string
Trace string
Value uint64
Active bool
}
func newCounterFile(name string, c *tcounter.File, cfg *config.Config) *counterFile {
activeMeta := map[string]bool{
"Program": cfg.HasProgram(c.Meta["Program"]),
"Version": cfg.HasVersion(c.Meta["Program"], c.Meta["Version"]),
"GOOS": cfg.HasGOOS(c.Meta["GOOS"]),
"GOARCH": cfg.HasGOARCH(c.Meta["GOARCH"]),
"GoVersion": cfg.HasGoVersion(c.Meta["GoVersion"]),
}
var counts []*count
var stacks []*stack
for k, v := range c.Count {
if summary, details, ok := strings.Cut(k, "\n"); ok {
active := cfg.HasStack(c.Meta["Program"], k)
stacks = append(stacks, &stack{summary, details, v, active})
} else {
active := cfg.HasCounter(c.Meta["Program"], k)
counts = append(counts, &count{k, v, active})
}
}
sort.Slice(counts, func(i, j int) bool {
return counts[i].Name < counts[j].Name
})
sort.Slice(stacks, func(i, j int) bool {
return stacks[i].Name < stacks[j].Name
})
return &counterFile{
File: c,
ID: name,
ActiveMeta: activeMeta,
Counts: counts,
Stacks: stacks,
Summary: summary(cfg, c.Meta, c.Count),
}
}
// summary generates a summary of a set of telemetry data. It describes what data is
// located in the set is not allowed given a config and how the data would be handled
// in the event of a telemetry upload event.
func summary(cfg *config.Config, meta map[string]string, counts map[string]uint64) template.HTML {
msg := " is unregistered. No data from this set would be uploaded to the Go team."
if prog := meta["Program"]; !(cfg.HasProgram(prog)) {
return template.HTML(fmt.Sprintf(
"The program <code>%s</code>"+msg,
html.EscapeString(prog),
))
}
var result strings.Builder
if !(cfg.HasGOOS(meta["GOOS"])) || !(cfg.HasGOARCH(meta["GOARCH"])) {
return template.HTML(fmt.Sprintf(
"The GOOS/GOARCH combination <code>%s/%s</code> "+msg,
html.EscapeString(meta["GOOS"]),
html.EscapeString(meta["GOARCH"]),
))
}
goVersion := meta["GoVersion"]
if !(cfg.HasGoVersion(goVersion)) {
return template.HTML(fmt.Sprintf(
"The go version <code>%s</code> "+msg,
html.EscapeString(goVersion),
))
}
version := meta["Version"]
if !(cfg.HasVersion(meta["Program"], version)) {
return template.HTML(fmt.Sprintf(
"The version <code>%s</code> "+msg,
html.EscapeString(version),
))
}
var counters []string
for c := range counts {
summary, _, ok := strings.Cut(c, "\n")
if ok && !cfg.HasStack(meta["Program"], c) {
counters = append(counters, fmt.Sprintf("<code>%s</code>", html.EscapeString(summary)))
}
if !ok && !(cfg.HasCounter(meta["Program"], c)) {
counters = append(counters, fmt.Sprintf("<code>%s</code>", html.EscapeString(c)))
}
}
if len(counters) > 0 {
result.WriteString("Unregistered counter(s) ")
result.WriteString(strings.Join(counters, ", "))
result.WriteString(" would be excluded from a report. ")
}
return template.HTML(result.String())
}
type chartdata struct {
Programs []*program
// DateRange is used to align the week intervals for each of the charts.
DateRange [2]string
// UploadDay is the day of the week the reports are uploaded.
// This is used as d3 chart time interval name
// to customize the date range bining in the charts.
UploadDay string
}
type program struct {
ID string
Name string
Counters []*counter
Active bool
}
type counter struct {
ID string
Name string
Data []*datum
Active bool
}
type datum struct {
Week string // End of the week in UTC. YYYY-MM-DDT00:00:00Z format.
Program string
Version string
GOARCH string
GOOS string
GoVersion string
Key string
Value int64
}
// formatDateTime formats the date to the format that
// includes time zone. Telemetry uses UTC for date string
// parsing, but JavaScript Date parsing uses local time
// unless the date string include the time zone info.
func formatDateTime(date time.Time) string {
return date.Format("2006-01-02T15:04:05Z") // UTC
}
// parseReportDate parses the date string in the format
// used byt the telemetry report.
func parseReportDate(s string) (time.Time, error) {
return time.Parse(time.DateOnly, s)
}
// charts returns chartdata for a set of telemetry reports. It uses the config
// to determine if the programs and counters are active.
func charts(reports []*telemetryReport, cfg *config.Config) (*chartdata, error) {
data := grouped(reports)
// domain is a [min, max] array used in d3.js where min is the minimum
// observable time and max is the maximum observable time; both values
// are inclusive.
domain, err := reportsDomain(reports)
if err != nil {
return nil, err
}
result := &chartdata{
DateRange: [2]string{formatDateTime(domain[0]), formatDateTime(domain[1])},
UploadDay: strings.ToLower(domain[1].Weekday().String()),
}
for pg, pgdata := range data {
prog := &program{ID: "charts:" + pg.Name, Name: pg.Name, Active: cfg.HasProgram(pg.Name)}
result.Programs = append(result.Programs, prog)
for c, cdata := range pgdata {
count := &counter{
ID: "charts:" + pg.Name + ":" + c.Name,
Name: c.Name,
Data: cdata,
Active: cfg.HasCounter(pg.Name, c.Name) || cfg.HasCounterPrefix(pg.Name, c.Name),
}
prog.Counters = append(prog.Counters, count)
sort.Slice(count.Data, func(i, j int) bool {
a, err1 := strconv.ParseFloat(count.Data[i].Key, 32)
b, err2 := strconv.ParseFloat(count.Data[j].Key, 32)
if err1 == nil && err2 == nil {
return a < b
}
return count.Data[i].Key < count.Data[j].Key
})
}
sort.Slice(prog.Counters, func(i, j int) bool {
return prog.Counters[i].Name < prog.Counters[j].Name
})
}
sort.Slice(result.Programs, func(i, j int) bool {
return result.Programs[i].Name < result.Programs[j].Name
})
return result, nil
}
// reportsDomain computes a common reportsDomain.
func reportsDomain(reports []*telemetryReport) ([2]time.Time, error) {
var start, end time.Time
for _, r := range reports {
if start.IsZero() || start.After(r.WeekEnd) {
start = r.WeekEnd
}
if end.IsZero() || r.WeekEnd.After(end) {
end = r.WeekEnd
}
}
if start.IsZero() || end.IsZero() {
return [2]time.Time{}, fmt.Errorf("no report with valid Week data")
}
start = start.AddDate(0, 0, -7) // 7 days before the first report.
return [2]time.Time{start, end}, nil
}
type programKey struct {
Name string
}
type counterKey struct {
Name string
}
// grouped returns normalized counter data grouped by program and counter.
func grouped(reports []*telemetryReport) map[programKey]map[counterKey][]*datum {
result := make(map[programKey]map[counterKey][]*datum)
for _, r := range reports {
// Adjust the Week string to include the time zone info.
// JS's Date.parse uses local time, otherwise.
//
// r.Week is the end of the week interval in UTC.
// If r.Week is 2024-01-08, the report is the data
// for the d3 domain[2024-01-01T00:00:00Z, 2024-01-08T00:00:00Z).
// Note: the end is exclusive.
// To make the report data align with the d3 domain,
// adjust the time to the start of the week interval.
weekStart := formatDateTime(r.WeekEnd.AddDate(0, 0, -7))
for _, e := range r.Programs {
pgkey := programKey{e.Program}
if _, ok := result[pgkey]; !ok {
result[pgkey] = make(map[counterKey][]*datum)
}
for counter, value := range e.Counters {
name, bucket, found := strings.Cut(counter, ":")
key := name
if found {
key = bucket
}
element := &datum{
Week: weekStart,
Program: e.Program,
Version: e.Version,
GOARCH: e.GOARCH,
GOOS: e.GOOS,
GoVersion: e.GoVersion,
Key: key,
Value: value,
}
ckey := counterKey{name}
result[pgkey][ckey] = append(result[pgkey][ckey], element)
}
for counter, value := range e.Stacks {
summary, _, _ := strings.Cut(counter, "\n")
element := &datum{
Week: weekStart,
Program: e.Program,
Version: e.Version,
GOARCH: e.GOARCH,
GOOS: e.GOOS,
GoVersion: e.GoVersion,
Key: summary,
Value: value,
}
ckey := counterKey{summary}
result[pgkey][ckey] = append(result[pgkey][ckey], element)
}
}
}
return result
}
// pending transforms the active counter files into a report. Used to add
// the data they contain to the charts in the UI.
func pending(files []*counterFile, cfg *config.Config) []*telemetryReport {
reports := make(map[string]*telemetry.Report)
for _, f := range files {
tb, err := time.Parse(time.RFC3339, f.Meta["TimeEnd"])
if err != nil {
log.Printf("skipping malformed %v: unexpected TimeEnd value %q", f.ID, f.Meta["TimeEnd"])
continue
}
week := tb.Format(time.DateOnly)
if _, ok := reports[week]; !ok {
reports[week] = &telemetry.Report{Week: week}
}
program := &telemetry.ProgramReport{
Program: f.Meta["Program"],
GOOS: f.Meta["GOOS"],
GOARCH: f.Meta["GOARCH"],
GoVersion: f.Meta["GoVersion"],
Version: f.Meta["Version"],
}
program.Counters = make(map[string]int64)
program.Stacks = make(map[string]int64)
for k, v := range f.Count {
if tcounter.IsStackCounter(k) {
program.Stacks[k] = int64(v)
} else {
program.Counters[k] = int64(v)
}
}
reports[week].Programs = append(reports[week].Programs, program)
}
var result []*telemetryReport
for _, r := range reports {
wrapped, err := newTelemetryReport(r, cfg)
if err != nil {
log.Printf("skipping the invalid report from week %v: %v", r.Week, err)
continue
}
result = append(result, wrapped)
}
return result
}
type handlerFunc func(http.ResponseWriter, *http.Request) error
func (f handlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// renderTemplate executes a template response.
func renderTemplate(w http.ResponseWriter, fsys fs.FS, tmplPath string, data any, code int) error {
patterns, err := tmplPatterns(fsys, tmplPath)
if err != nil {
return err
}
patterns = append(patterns, tmplPath)
funcs := template.FuncMap{
"chartName": func(name string) string {
name, _, _ = strings.Cut(name, ":")
return name
},
"programName": func(name string) string {
name = strings.TrimPrefix(name, "golang.org/")
name = strings.TrimPrefix(name, "github.com/")
return name
},
}
tmpl, err := template.New("").Funcs(funcs).ParseFS(fsys, patterns...)
if err != nil {
return err
}
name := path.Base(tmplPath)
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil {
return err
}
if code != 0 {
w.WriteHeader(code)
}
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
if _, err := w.Write(buf.Bytes()); err != nil {
return err
}
return nil
}
// tmplPatterns generates a slice of file patterns to use in template.ParseFS.
func tmplPatterns(fsys fs.FS, tmplPath string) ([]string, error) {
var patterns []string
globs := []string{"*.tmpl", path.Join(path.Dir(tmplPath), "*.tmpl")}
for _, g := range globs {
matches, err := fs.Glob(fsys, g)
if err != nil {
return nil, err
}
patterns = append(patterns, matches...)
}
return patterns, nil
}
|
csv
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/cmd/gotelemetry/internal/csv/csv.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// csv dumps all the active counters. The output is
// a sequence of lines
// value,"counter-name",program, version,go-version,goos, garch
// sorted by counter name. It looks at the files in
// telemetry.LocalDir that are counter files or local reports
// By design it pays no attention to dates. The combination
// of program version and go version are deemed sufficient.
package csv
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"golang.org/x/telemetry/internal/counter"
"golang.org/x/telemetry/internal/telemetry"
)
type file struct {
path, name string
// one of counters or report is set
counters *counter.File
report *telemetry.Report
}
func Csv() {
files, err := readdir(telemetry.Default.LocalDir(), nil)
if err != nil {
log.Fatal(err)
}
for _, f := range files {
if strings.HasSuffix(f.name, "v1.count") {
buf, err := os.ReadFile(f.path)
if err != nil {
log.Print(err)
continue
}
cf, err := counter.Parse(f.name, buf)
if err != nil {
log.Print(err)
continue
}
f.counters = cf
} else if strings.HasSuffix(f.name, ".json") {
buf, err := os.ReadFile(f.path)
if err != nil {
log.Print(err)
continue
}
var x telemetry.Report
if err := json.Unmarshal(buf, &x); err != nil {
log.Print(err)
continue
}
f.report = &x
}
}
printTable(files)
}
type record struct {
goos, garch, program, version, goversion string
cntr string
count int
}
func printTable(files []*file) {
lines := make(map[string]*record)
work := func(k string, v int64, rec *record) {
x, ok := lines[k]
if !ok {
x = new(record)
*x = *rec
x.cntr = k
}
x.count += int(v)
lines[k] = x
}
worku := func(k string, v uint64, rec *record) {
work(k, int64(v), rec)
}
for _, f := range files {
if f.counters != nil {
var rec record
rec.goos = f.counters.Meta["GOOS"]
rec.garch = f.counters.Meta["GOARCH"]
rec.program = f.counters.Meta["Program"]
rec.version = f.counters.Meta["Version"]
rec.goversion = f.counters.Meta["GoVersion"]
for k, v := range f.counters.Count {
worku(k, v, &rec)
}
} else if f.report != nil {
for _, p := range f.report.Programs {
var rec record
rec.goos = p.GOOS
rec.garch = p.GOARCH
rec.goversion = p.GoVersion
rec.program = p.Program
rec.version = p.Version
for k, v := range p.Counters {
work(k, v, &rec)
}
for k, v := range p.Stacks {
work(k, v, &rec)
}
}
}
}
keys := make([]string, 0, len(lines))
for k := range lines {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
printRecord(lines[k])
}
}
func printRecord(r *record) {
fmt.Printf("%d,%q,%s,%s,%s,%s,%s\n", r.count, r.cntr, r.program,
r.version, r.goversion, r.goos, r.garch)
}
func readdir(dir string, files []*file) ([]*file, error) {
fi, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, f := range fi {
files = append(files, &file{path: filepath.Join(dir, f.Name()), name: f.Name()})
}
return files, nil
}
|
crashmonitor
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/crashmonitor/supported.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package crashmonitor
import ic "golang.org/x/telemetry/internal/crashmonitor"
// Supported reports whether the runtime supports [runtime.SetCrashOutput].
//
// TODO(adonovan): eliminate once go1.23+ is assured.
func Supported() bool { return ic.Supported() }
|
config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/config/doc.go
|
// The config package holds the config.json file defining the Go telemetry
// upload configuration.
//
// An upload configuration specifies the set of values that are permitted in
// telemetry uploads: GOOS, GOARCH, Go version, and per-program counters.
//
// This package contains no actual Go code, and exists only so the config.json
// file can be served by module proxies.
//
// The config.json is generated by golang.org/x/telemetry/internal/configgen.
package config
|
config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/config/go.mod
|
module golang.org/x/telemetry/config
go 1.21
|
config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/config/config.json
|
{
"GOOS": [
"aix",
"android",
"darwin",
"dragonfly",
"freebsd",
"hurd",
"illumos",
"ios",
"js",
"linux",
"nacl",
"netbsd",
"openbsd",
"plan9",
"solaris",
"wasip1",
"windows",
"zos"
],
"GOARCH": [
"386",
"amd64",
"amd64p32",
"arm",
"arm64",
"arm64be",
"armbe",
"loong64",
"mips",
"mips64",
"mips64le",
"mips64p32",
"mips64p32le",
"mipsle",
"ppc",
"ppc64",
"ppc64le",
"riscv",
"riscv64",
"s390",
"s390x",
"sparc",
"sparc64",
"wasm"
],
"GoVersion": [
"go1.9.2rc2",
"go1.2.2",
"go1.3rc1",
"go1.3rc2",
"go1.3",
"go1.3.1",
"go1.3.2",
"go1.3.3",
"go1.4beta1",
"go1.4rc1",
"go1.4rc2",
"go1.4",
"go1.4.1",
"go1.4.2",
"go1.4.3",
"go1.5beta1",
"go1.5beta2",
"go1.5beta3",
"go1.5rc1",
"go1.5",
"go1.5.1",
"go1.5.2",
"go1.5.3",
"go1.5.4",
"go1.6beta1",
"go1.6beta2",
"go1.6rc1",
"go1.6rc2",
"go1.6",
"go1.6.1",
"go1.6.2",
"go1.6.3",
"go1.6.4",
"go1.7beta1",
"go1.7beta2",
"go1.7rc1",
"go1.7rc2",
"go1.7rc3",
"go1.7rc4",
"go1.7rc5",
"go1.7rc6",
"go1.7",
"go1.7.1",
"go1.7.3",
"go1.7.4",
"go1.7.5",
"go1.7.6",
"go1.8beta1",
"go1.8beta2",
"go1.8rc1",
"go1.8rc2",
"go1.8rc3",
"go1.8",
"go1.8.1",
"go1.8.2",
"go1.8.3",
"go1.8.4",
"go1.8.5",
"go1.8.6",
"go1.8.7",
"go1.9beta1",
"go1.9beta2",
"go1.9rc1",
"go1.9rc2",
"go1.9",
"go1.9.1",
"go1.9.2",
"go1.9.3",
"go1.9.4",
"go1.9.5",
"go1.9.6",
"go1.9.7",
"go1.10beta1",
"go1.10beta2",
"go1.10rc1",
"go1.10rc2",
"go1.10",
"go1.10.1",
"go1.10.2",
"go1.10.3",
"go1.10.4",
"go1.10.5",
"go1.10.6",
"go1.10.7",
"go1.10.8",
"go1.11beta1",
"go1.11beta2",
"go1.11beta3",
"go1.11rc1",
"go1.11rc2",
"go1.11",
"go1.11.1",
"go1.11.2",
"go1.11.3",
"go1.11.4",
"go1.11.5",
"go1.11.6",
"go1.11.7",
"go1.11.8",
"go1.11.9",
"go1.11.10",
"go1.11.11",
"go1.11.12",
"go1.11.13",
"go1.12beta1",
"go1.12beta2",
"go1.12rc1",
"go1.12",
"go1.12.1",
"go1.12.2",
"go1.12.3",
"go1.12.4",
"go1.12.5",
"go1.12.6",
"go1.12.7",
"go1.12.8",
"go1.12.9",
"go1.12.10",
"go1.12.11",
"go1.12.12",
"go1.12.13",
"go1.12.14",
"go1.12.15",
"go1.12.16",
"go1.12.17",
"go1.13beta1",
"go1.13rc1",
"go1.13rc2",
"go1.13",
"go1.13.1",
"go1.13.2",
"go1.13.3",
"go1.13.4",
"go1.13.5",
"go1.13.6",
"go1.13.7",
"go1.13.8",
"go1.13.9",
"go1.13.10",
"go1.13.11",
"go1.13.12",
"go1.13.13",
"go1.13.14",
"go1.13.15",
"go1.14beta1",
"go1.14rc1",
"go1.14",
"go1.14.1",
"go1.14.2",
"go1.14.3",
"go1.14.4",
"go1.14.5",
"go1.14.6",
"go1.14.7",
"go1.14.8",
"go1.14.9",
"go1.14.10",
"go1.14.11",
"go1.14.12",
"go1.14.13",
"go1.14.14",
"go1.14.15",
"go1.15beta1",
"go1.15rc1",
"go1.15rc2",
"go1.15",
"go1.15.1",
"go1.15.2",
"go1.15.3",
"go1.15.4",
"go1.15.5",
"go1.15.6",
"go1.15.7",
"go1.15.8",
"go1.15.9",
"go1.15.10",
"go1.15.11",
"go1.15.12",
"go1.15.13",
"go1.15.14",
"go1.15.15",
"go1.16beta1",
"go1.16rc1",
"go1.16",
"go1.16.1",
"go1.16.2",
"go1.16.3",
"go1.16.4",
"go1.16.5",
"go1.16.6",
"go1.16.7",
"go1.16.8",
"go1.16.9",
"go1.16.10",
"go1.16.11",
"go1.16.12",
"go1.16.13",
"go1.16.14",
"go1.16.15",
"go1.17beta1",
"go1.17rc1",
"go1.17rc2",
"go1.17",
"go1.17.1",
"go1.17.2",
"go1.17.3",
"go1.17.4",
"go1.17.5",
"go1.17.6",
"go1.17.7",
"go1.17.8",
"go1.17.9",
"go1.17.10",
"go1.17.11",
"go1.17.12",
"go1.17.13",
"go1.18beta1",
"go1.18beta2",
"go1.18rc1",
"go1.18",
"go1.18.1",
"go1.18.2",
"go1.18.3",
"go1.18.4",
"go1.18.5",
"go1.18.6",
"go1.18.7",
"go1.18.8",
"go1.18.9",
"go1.18.10",
"go1.19beta1",
"go1.19rc1",
"go1.19rc2",
"go1.19",
"go1.19.1",
"go1.19.2",
"go1.19.3",
"go1.19.4",
"go1.19.5",
"go1.19.6",
"go1.19.7",
"go1.19.8",
"go1.19.9",
"go1.19.10",
"go1.19.11",
"go1.19.12",
"go1.19.13",
"go1.20rc1",
"go1.20rc2",
"go1.20rc3",
"go1.20",
"go1.20.1",
"go1.20.2",
"go1.20.3",
"go1.20.4",
"go1.20.5",
"go1.20.6",
"go1.20.7",
"go1.20.8",
"go1.20.9",
"go1.20.10",
"go1.20.11",
"go1.20.12",
"go1.20.13",
"go1.20.14",
"go1.21rc2",
"go1.21rc3",
"go1.21rc4",
"go1.21.0",
"go1.21.1",
"go1.21.2",
"go1.21.3",
"go1.21.4",
"go1.21.5",
"go1.21.6",
"go1.21.7",
"go1.21.8",
"go1.21.9",
"go1.21.10",
"go1.21.11",
"go1.21.12",
"go1.22rc1",
"go1.22rc2",
"go1.22.0",
"go1.22.1",
"go1.22.2",
"go1.22.3",
"go1.22.4",
"go1.22.5",
"go1.23rc1",
"go1.23rc2"
],
"SampleRate": 1,
"Programs": [
{
"Name": "cmd/compile",
"Versions": [
"go1.23rc1",
"go1.23rc2"
],
"Counters": [
{
"Name": "compile/invocations",
"Rate": 1
}
],
"Stacks": [
{
"Name": "compile/bug",
"Rate": 1,
"Depth": 16
}
]
},
{
"Name": "cmd/go",
"Versions": [
"go1.23rc1",
"go1.23rc2"
],
"Counters": [
{
"Name": "go/invocations",
"Rate": 1
},
{
"Name": "go/build/flag:{buildmode}",
"Rate": 1
},
{
"Name": "go/build/flag/buildmode:{archive,c-archive,c-shared,default,exe,pie,shared,plugin}",
"Rate": 1
}
]
},
{
"Name": "golang.org/x/tools/gopls",
"Versions": [
"v0.13.0",
"v0.13.1-pre.1",
"v0.13.1-pre.2",
"v0.13.1",
"v0.13.2-pre.1",
"v0.13.2",
"v0.14.0-pre.1",
"v0.14.0-pre.2",
"v0.14.0-pre.3",
"v0.14.0-pre.4",
"v0.14.0-pre.5",
"v0.14.0",
"v0.14.1-pre.1",
"v0.14.1",
"v0.14.2-pre.1",
"v0.14.2",
"v0.15.0-pre.1",
"v0.15.0-pre.2",
"v0.15.0-pre.3",
"v0.15.0-pre.4",
"v0.15.0-pre.5",
"v0.15.0",
"v0.15.1-pre.1",
"v0.15.1",
"v0.15.2-pre.1",
"v0.15.2-pre.2",
"v0.15.2",
"v0.15.3-pre.1",
"v0.15.3-pre.2",
"v0.15.3",
"v0.16.0-pre.1",
"v0.16.0-pre.2",
"v0.16.0-pre.3",
"v0.16.0",
"v0.16.1-pre.1",
"v0.16.1",
"v0.16.2-pre.1",
"v0.16.2-pre.2",
"v0.16.2-pre.3",
"v0.16.2-pre.4",
"v0.16.2",
"v0.16.3-pre.1",
"v0.16.3-pre.2",
"v0.16.3-pre.3",
"v0.16.3-pre.4",
"v0.16.3",
"v0.16.4-pre.1",
"v0.16.4-pre.2",
"v0.16.4-pre.3",
"v0.16.4-pre.4",
"v0.16.4",
"v0.16.5-pre.1",
"v0.16.5-pre.2",
"v0.16.5-pre.3",
"v0.16.5-pre.4",
"v0.16.5",
"v0.16.6-pre.1",
"v0.16.6-pre.2",
"v0.16.6-pre.3",
"v0.16.6-pre.4",
"v0.16.6",
"v0.16.7-pre.1",
"v0.16.7-pre.2",
"v0.16.7-pre.3",
"v0.16.7-pre.4",
"v0.16.7",
"v0.17.0-pre.1",
"v0.17.0-pre.2",
"v0.17.0-pre.3",
"v0.17.0-pre.4",
"v0.17.0",
"v0.17.1-pre.1",
"v0.17.1-pre.2",
"v0.17.1-pre.3",
"v0.17.1-pre.4",
"v0.17.1",
"v0.17.2-pre.1",
"v0.17.2-pre.2",
"v0.17.2-pre.3",
"v0.17.2-pre.4",
"v0.17.2",
"v0.17.3-pre.1",
"v0.17.3-pre.2",
"v0.17.3-pre.3",
"v0.17.3-pre.4",
"v0.17.3",
"v0.17.4-pre.1",
"v0.17.4-pre.2",
"v0.17.4-pre.3",
"v0.17.4-pre.4",
"v0.17.4",
"v0.17.5-pre.1",
"v0.17.5-pre.2",
"v0.17.5-pre.3",
"v0.17.5-pre.4",
"v0.17.5",
"v0.18.0-pre.1",
"v0.18.0-pre.2",
"v0.18.0-pre.3",
"v0.18.0-pre.4",
"v0.18.0",
"v0.18.1-pre.1",
"v0.18.1-pre.2",
"v0.18.1-pre.3",
"v0.18.1-pre.4",
"v0.18.1",
"v0.18.2-pre.1",
"v0.18.2-pre.2",
"v0.18.2-pre.3",
"v0.18.2-pre.4",
"v0.18.2",
"v0.18.3-pre.1",
"v0.18.3-pre.2",
"v0.18.3-pre.3",
"v0.18.3-pre.4",
"v0.18.3",
"v0.18.4-pre.1",
"v0.18.4-pre.2",
"v0.18.4-pre.3",
"v0.18.4-pre.4",
"v0.18.4",
"v0.19.0-pre.1",
"v0.19.0-pre.2",
"v0.19.0-pre.3",
"v0.19.0-pre.4",
"v0.19.0",
"v0.19.1-pre.1",
"v0.19.1-pre.2",
"v0.19.1-pre.3",
"v0.19.1-pre.4",
"v0.19.1",
"v0.19.2-pre.1",
"v0.19.2-pre.2",
"v0.19.2-pre.3",
"v0.19.2-pre.4",
"v0.19.2",
"v0.19.3-pre.1",
"v0.19.3-pre.2",
"v0.19.3-pre.3",
"v0.19.3-pre.4",
"v0.19.3",
"v1.0.0-pre.1",
"v1.0.0-pre.2",
"v1.0.0-pre.3",
"v1.0.0-pre.4",
"v1.0.0",
"v1.0.1-pre.1",
"v1.0.1-pre.2",
"v1.0.1-pre.3",
"v1.0.1-pre.4",
"v1.0.1",
"v1.0.2-pre.1",
"v1.0.2-pre.2",
"v1.0.2-pre.3",
"v1.0.2-pre.4",
"v1.0.2",
"v1.0.3-pre.1",
"v1.0.3-pre.2",
"v1.0.3-pre.3",
"v1.0.3-pre.4",
"v1.0.3",
"v1.0.4-pre.1",
"v1.0.4-pre.2",
"v1.0.4-pre.3",
"v1.0.4-pre.4",
"v1.0.4",
"v1.0.5-pre.1",
"v1.0.5-pre.2",
"v1.0.5-pre.3",
"v1.0.5-pre.4",
"v1.0.5",
"v1.1.0-pre.1",
"v1.1.0-pre.2",
"v1.1.0-pre.3",
"v1.1.0-pre.4",
"v1.1.0",
"v1.1.1-pre.1",
"v1.1.1-pre.2",
"v1.1.1-pre.3",
"v1.1.1-pre.4",
"v1.1.1",
"v1.1.2-pre.1",
"v1.1.2-pre.2",
"v1.1.2-pre.3",
"v1.1.2-pre.4",
"v1.1.2",
"v1.1.3-pre.1",
"v1.1.3-pre.2",
"v1.1.3-pre.3",
"v1.1.3-pre.4",
"v1.1.3",
"v1.1.4-pre.1",
"v1.1.4-pre.2",
"v1.1.4-pre.3",
"v1.1.4-pre.4",
"v1.1.4",
"v1.2.0-pre.1",
"v1.2.0-pre.2",
"v1.2.0-pre.3",
"v1.2.0-pre.4",
"v1.2.0",
"v1.2.1-pre.1",
"v1.2.1-pre.2",
"v1.2.1-pre.3",
"v1.2.1-pre.4",
"v1.2.1",
"v1.2.2-pre.1",
"v1.2.2-pre.2",
"v1.2.2-pre.3",
"v1.2.2-pre.4",
"v1.2.2",
"v1.2.3-pre.1",
"v1.2.3-pre.2",
"v1.2.3-pre.3",
"v1.2.3-pre.4",
"v1.2.3"
],
"Counters": [
{
"Name": "gopls/client:{vscode,vscodium,vscode-insiders,code-server,eglot,govim,neovim,coc.nvim,sublimetext,other}",
"Rate": 1
},
{
"Name": "gopls/goversion:{1.16,1.17,1.18,1.19,1.20,1.21,1.22,1.23,1.24,1.25,1.26,1.27,1.28,1.29,1.30}",
"Rate": 1
},
{
"Name": "crash/malformed",
"Rate": 1
},
{
"Name": "crash/no-running-goroutine",
"Rate": 1
}
],
"Stacks": [
{
"Name": "gopls/bug",
"Rate": 1,
"Depth": 16
},
{
"Name": "crash/crash",
"Rate": 1,
"Depth": 16
}
]
},
{
"Name": "golang.org/x/vuln/cmd/govulncheck",
"Versions": [
"v0.0.1-pre.1",
"v0.0.1-pre.2",
"v0.0.1-pre.3",
"v0.0.1-pre.4",
"v0.0.1",
"v0.0.2-pre.1",
"v0.0.2-pre.2",
"v0.0.2-pre.3",
"v0.0.2-pre.4",
"v0.0.2",
"v0.0.3-pre.1",
"v0.0.3-pre.2",
"v0.0.3-pre.3",
"v0.0.3-pre.4",
"v0.0.3",
"v0.0.4-pre.1",
"v0.0.4-pre.2",
"v0.0.4-pre.3",
"v0.0.4-pre.4",
"v0.0.4",
"v0.0.5-pre.1",
"v0.0.5-pre.2",
"v0.0.5-pre.3",
"v0.0.5-pre.4",
"v0.0.5",
"v0.0.6-pre.1",
"v0.0.6-pre.2",
"v0.0.6-pre.3",
"v0.0.6-pre.4",
"v0.0.6",
"v0.1.0-pre.1",
"v0.1.0-pre.2",
"v0.1.0-pre.3",
"v0.1.0-pre.4",
"v0.1.0",
"v0.1.1-pre.1",
"v0.1.1-pre.2",
"v0.1.1-pre.3",
"v0.1.1-pre.4",
"v0.1.1",
"v0.1.2-pre.1",
"v0.1.2-pre.2",
"v0.1.2-pre.3",
"v0.1.2-pre.4",
"v0.1.2",
"v0.1.3-pre.1",
"v0.1.3-pre.2",
"v0.1.3-pre.3",
"v0.1.3-pre.4",
"v0.1.3",
"v0.1.4-pre.1",
"v0.1.4-pre.2",
"v0.1.4-pre.3",
"v0.1.4-pre.4",
"v0.1.4",
"v0.1.5-pre.1",
"v0.1.5-pre.2",
"v0.1.5-pre.3",
"v0.1.5-pre.4",
"v0.1.5",
"v0.2.0-pre.1",
"v0.2.0-pre.2",
"v0.2.0-pre.3",
"v0.2.0-pre.4",
"v0.2.0",
"v0.2.1-pre.1",
"v0.2.1-pre.2",
"v0.2.1-pre.3",
"v0.2.1-pre.4",
"v0.2.1",
"v0.2.2-pre.1",
"v0.2.2-pre.2",
"v0.2.2-pre.3",
"v0.2.2-pre.4",
"v0.2.2",
"v0.2.3-pre.1",
"v0.2.3-pre.2",
"v0.2.3-pre.3",
"v0.2.3-pre.4",
"v0.2.3",
"v0.2.4-pre.1",
"v0.2.4-pre.2",
"v0.2.4-pre.3",
"v0.2.4-pre.4",
"v0.2.4",
"v0.3.0-pre.1",
"v0.3.0-pre.2",
"v0.3.0-pre.3",
"v0.3.0-pre.4",
"v0.3.0",
"v0.3.1-pre.1",
"v0.3.1-pre.2",
"v0.3.1-pre.3",
"v0.3.1-pre.4",
"v0.3.1",
"v0.3.2-pre.1",
"v0.3.2-pre.2",
"v0.3.2-pre.3",
"v0.3.2-pre.4",
"v0.3.2",
"v0.3.3-pre.1",
"v0.3.3-pre.2",
"v0.3.3-pre.3",
"v0.3.3-pre.4",
"v0.3.3",
"v1.0.0-pre.1",
"v1.0.0-pre.2",
"v1.0.0-pre.3",
"v1.0.0-pre.4",
"v1.0.0",
"v1.0.1-pre.1",
"v1.0.1-pre.2",
"v1.0.1-pre.3",
"v1.0.1-pre.4",
"v1.0.1",
"v1.0.2-pre.1",
"v1.0.2-pre.2",
"v1.0.2-pre.3",
"v1.0.2-pre.4",
"v1.0.2",
"v1.0.3-pre.1",
"v1.0.3-pre.2",
"v1.0.3-pre.3",
"v1.0.3-pre.4",
"v1.0.3",
"v1.0.4-pre.1",
"v1.0.4-pre.2",
"v1.0.4-pre.3",
"v1.0.4-pre.4",
"v1.0.4",
"v1.0.5-pre.1",
"v1.0.5-pre.2",
"v1.0.5-pre.3",
"v1.0.5-pre.4",
"v1.0.5",
"v1.1.0-pre.1",
"v1.1.0-pre.2",
"v1.1.0-pre.3",
"v1.1.0-pre.4",
"v1.1.0",
"v1.1.1-pre.1",
"v1.1.1-pre.2",
"v1.1.1-pre.3",
"v1.1.1-pre.4",
"v1.1.1",
"v1.1.2-pre.1",
"v1.1.2-pre.2",
"v1.1.2-pre.3",
"v1.1.2-pre.4",
"v1.1.2",
"v1.1.3-pre.1",
"v1.1.3-pre.2",
"v1.1.3-pre.3",
"v1.1.3-pre.4",
"v1.1.3",
"v1.1.4-pre.1",
"v1.1.4-pre.2",
"v1.1.4-pre.3",
"v1.1.4-pre.4",
"v1.1.4",
"v1.2.0-pre.1",
"v1.2.0-pre.2",
"v1.2.0-pre.3",
"v1.2.0-pre.4",
"v1.2.0",
"v1.2.1-pre.1",
"v1.2.1-pre.2",
"v1.2.1-pre.3",
"v1.2.1-pre.4",
"v1.2.1",
"v1.2.2-pre.1",
"v1.2.2-pre.2",
"v1.2.2-pre.3",
"v1.2.2-pre.4",
"v1.2.2",
"v1.2.3-pre.1",
"v1.2.3-pre.2",
"v1.2.3-pre.3",
"v1.2.3-pre.4",
"v1.2.3"
],
"Counters": [
{
"Name": "govulncheck/scan:{symbol,package,module}",
"Rate": 1
},
{
"Name": "govulncheck/mode:{source,binary,extract,query,convert}",
"Rate": 1
},
{
"Name": "govulncheck/format:{text,json,sarif,openvex}",
"Rate": 1
},
{
"Name": "govulncheck/show:{none,traces,color,verbose,version}",
"Rate": 1
},
{
"Name": "govulncheck/assumptions:{multi-patterns,no-binary-platform,no-relative-path,no-go-root,local-replace,unknown-pkg-mod-path}",
"Rate": 1
}
]
}
]
}
|
godev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/go.mod
|
module golang.org/x/telemetry/godev
go 1.21.0
require (
cloud.google.com/go/cloudtasks v1.12.4
cloud.google.com/go/storage v1.30.1
github.com/evanw/esbuild v0.17.19
github.com/google/go-cmp v0.6.0
github.com/yuin/goldmark v1.5.4
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63
golang.org/x/mod v0.19.0
golang.org/x/telemetry v0.0.0-00010101000000-000000000000
google.golang.org/api v0.149.0
)
require (
cloud.google.com/go v0.110.8 // indirect
cloud.google.com/go/compute v1.23.1 // indirect
cloud.google.com/go/compute/metadata v0.2.3 // indirect
cloud.google.com/go/iam v1.1.3 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/s2a-go v0.1.7 // indirect
github.com/google/uuid v1.4.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
github.com/kr/pretty v0.1.0 // indirect
go.opencensus.io v0.24.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/oauth2 v0.13.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20231016165738-49dd2c1f3d0b // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b // indirect
google.golang.org/grpc v1.59.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
require (
github.com/yuin/goldmark-meta v1.1.0
golang.org/x/sys v0.22.0 // indirect
)
replace golang.org/x/telemetry => ./..
|
godev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/go.sum
|
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.110.8 h1:tyNdfIxjzaWctIiLYOTalaLKZ17SI44SKFW26QbOhME=
cloud.google.com/go v0.110.8/go.mod h1:Iz8AkXJf1qmxC3Oxoep8R1T36w8B92yU29PcBhHO5fk=
cloud.google.com/go/cloudtasks v1.12.4 h1:5xXuFfAjg0Z5Wb81j2GAbB3e0bwroCeSF+5jBn/L650=
cloud.google.com/go/cloudtasks v1.12.4/go.mod h1:BEPu0Gtt2dU6FxZHNqqNdGqIG86qyWKBPGnsb7udGY0=
cloud.google.com/go/compute v1.23.1 h1:V97tBoDaZHb6leicZ1G6DLK2BAaZLJ/7+9BB/En3hR0=
cloud.google.com/go/compute v1.23.1/go.mod h1:CqB3xpmPKKt3OJpW2ndFIXnA9A4xAy/F3Xp1ixncW78=
cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
cloud.google.com/go/iam v1.1.3 h1:18tKG7DzydKWUnLjonWcJO6wjSCAtzh4GcRKlH/Hrzc=
cloud.google.com/go/iam v1.1.3/go.mod h1:3khUlaBXfPKKe7huYgEpDn6FtgRyMEqbkvBxrQyY5SE=
cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM=
cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/evanw/esbuild v0.17.19 h1:JdzNCvfFEoUCXKHhdP326Vn2mhCu8PybXeBDHaSRyWo=
github.com/evanw/esbuild v0.17.19/go.mod h1:iINY06rn799hi48UqEnaQvVfZWe6W9bET78LbvN8VWk=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw=
github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk=
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas=
github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/yuin/goldmark v1.5.4 h1:2uY/xC0roWy8IBEGLgB1ywIoEJFGmRrX21YQcvGZzjU=
github.com/yuin/goldmark v1.5.4/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark-meta v1.1.0 h1:pWw+JLHGZe8Rk0EGsMVssiNb/AaPMHfSRszZeUeiOUc=
github.com/yuin/goldmark-meta v1.1.0/go.mod h1:U4spWENafuA7Zyg+Lj5RqK/MF+ovMYtBvXi1lBb2VP0=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 h1:m64FZMko/V45gv0bNmrNYoDEq8U5YUhetc9cBWKS1TQ=
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63/go.mod h1:0v4NqG35kSWCMzLaMeX+IQrlSnVE/bqGSyC2cz/9Le8=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.13.0 h1:jDDenyj+WgFtmV3zYVoi8aE2BwtXFLWOA67ZfNWftiY=
golang.org/x/oauth2 v0.13.0/go.mod h1:/JMhi4ZRXAf4HG9LiNmxvk+45+96RUlVThiH8FzNBn0=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8=
google.golang.org/api v0.149.0 h1:b2CqT6kG+zqJIVKRQ3ELJVLN1PwHZ6DJ3dW8yl82rgY=
google.golang.org/api v0.149.0/go.mod h1:Mwn1B7JTXrzXtnvmzQE2BD6bYZQ8DShKZDZbeN9I7qI=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20231016165738-49dd2c1f3d0b h1:+YaDE2r2OG8t/z5qmsh7Y+XXwCbvadxxZ0YY6mTdrVA=
google.golang.org/genproto v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:CgAqfJo+Xmu0GwA0411Ht3OU3OntXwsGmrmjI8ioGXI=
google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b h1:CIC2YMXmIhYw6evmhPxBKJ4fmLbOFtXQN/GV3XOZR8k=
google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:IBQ646DjkDkvUIsVq/cc03FUFQ9wbZu7yE396YcL870=
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b h1:ZlWIi1wSK56/8hn4QcBp/j9M7Gt3U/3hZw3mC7vDICo=
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:swOH3j0KzcDDgGUWr+SNpyTen5YrXjS3eyPzFYKc6lc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk=
google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
log
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/log/cloudlog.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package log
import (
"os"
"time"
"golang.org/x/exp/slog"
)
func NewGCPLogHandler() slog.Handler {
return slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
ReplaceAttr: gcpReplaceAttr,
Level: slog.LevelDebug,
})
}
func gcpReplaceAttr(groups []string, a slog.Attr) slog.Attr {
switch a.Key {
case slog.TimeKey:
if a.Value.Kind() == slog.KindTime {
a.Value = slog.StringValue(a.Value.Time().Format(time.RFC3339))
}
case slog.MessageKey:
a.Key = "message"
case slog.LevelKey:
a.Key = "severity"
case slog.SourceKey:
a.Key = "logging.googleapis.com/sourceLocation"
case "traceID":
a.Key = "logging.googleapis.com/trace"
case "spanID":
a.Key = "logging.googleapis.com/spanId"
}
return a
}
|
middleware
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/middleware/middleware.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package middleware implements a simple middleware pattern for http handlers,
// along with implementations for some common middlewares.
package middleware
import (
"fmt"
"net/http"
"runtime/debug"
"time"
"golang.org/x/exp/slog"
)
// A Middleware is a func that wraps an http.Handler.
type Middleware func(http.Handler) http.Handler
// Chain creates a new Middleware that applies a sequence of Middlewares, so
// that they execute in the given order when handling an http request.
//
// In other words, Chain(m1, m2)(handler) = m1(m2(handler))
//
// A similar pattern is used in e.g. github.com/justinas/alice:
// https://github.com/justinas/alice/blob/ce87934/chain.go#L45
func Chain(middlewares ...Middleware) Middleware {
return func(h http.Handler) http.Handler {
for i := range middlewares {
h = middlewares[len(middlewares)-1-i](h)
}
return h
}
}
// Log is a middleware that logs request start, end, duration, and status.
func Log(logger *slog.Logger) Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ctx := r.Context()
l := logger.With(
slog.String("method", r.Method),
slog.String("uri", r.RequestURI),
// TODO(hyangah): set trace context from X-Cloud-Trace-Context
)
l.InfoContext(ctx, "request start")
w2 := &statusRecorder{w, 200}
h.ServeHTTP(w2, r)
level := slog.LevelInfo
msg := "request end"
switch w2.status / 100 {
case 5:
level = slog.LevelError // 5XX error
msg = "request error"
case 4:
level = slog.LevelWarn // 4XX error
msg = "request rejected"
}
l.Log(ctx, level, msg,
slog.Int("status", w2.status),
slog.Duration("duration", time.Since(start)),
)
})
}
}
// Recover is a middleware that recovers from panics in the delegate
// handler and prints a stack trace.
func Recover() Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
slog.Error(r.RequestURI, fmt.Errorf(`panic("%s")`, err))
fmt.Println(string(debug.Stack()))
}
}()
h.ServeHTTP(w, r)
})
}
}
// RequestSize limits the size of incoming request bodies.
func RequestSize(n int64) Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, n)
h.ServeHTTP(w, r)
})
}
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (rec *statusRecorder) WriteHeader(code int) {
rec.status = code
rec.ResponseWriter.WriteHeader(code)
}
// Timeout returns a new Middleware that times out each request after the given
// duration.
func Timeout(d time.Duration) Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.TimeoutHandler(h, d, "request timed out").ServeHTTP(w, r)
})
}
}
|
content
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/content.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package content implements a basic web serving framework.
//
// # Content Server
//
// A content server is an http.Handler that serves requests from a file system.
// Use Server(fsys) to create a new content server.
//
// The server is defined primarily by the content of its file system fsys,
// which holds files to be served. It renders markdown files and golang
// templates into HTML.
//
// # Page Rendering
//
// A request for a path like "/page" will search the file system for
// "page.md", "page.html", "page/index.md", and "page/index.html" and
// render HTML output for the first file found.
//
// Partial templates with the extension ".tmpl" at the root of the file system
// and in the same directory as the requested page are included in the
// html/template execution step to allow for sharing and composing logic from
// multiple templates.
//
// Markdown templates must have an html layout template set in the frontmatter
// section. The markdown content is available to the layout template as the
// field `{{.Content}}`.
package content
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/fs"
"net/http"
"path"
"strconv"
"strings"
"github.com/yuin/goldmark"
meta "github.com/yuin/goldmark-meta"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
)
// contentServer serves requests for a given file system and renders html
// templates.
type contentServer struct {
fsys fs.FS
fserv http.Handler
handlers map[string]HandlerFunc
}
type HandlerFunc func(http.ResponseWriter, *http.Request) error
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
handleErr(w, r, err, http.StatusInternalServerError)
}
}
// Server returns a handler that serves HTTP requests with the contents
// of the file system rooted at fsys. For requests to a path without an
// extension, the server will search fsys for markdown or html templates
// first by appending .md, .html, /index.md, and /index.html to the
// requested url path.
//
// The default behavior of looking for templates within fsys can be overridden
// by using an optional set of content handlers.
//
// For example, a server can be constructed for a file system with a single
// template, “index.html“, in a directory, “content“, and a handler:
//
// fsys := os.DirFS("content")
// s := content.Server(fsys,
// content.Handler("/", func(w http.ReponseWriter, _ *http.Request) error {
// return content.Template(w, fsys, "index.html", nil, http.StatusOK)
// }))
//
// or without a handler:
//
// content.Server(os.DirFS("content"))
//
// Both examples will render the template index.html for requests to "/".
func Server(fsys fs.FS, handlers ...*handler) http.Handler {
fserv := http.FileServer(http.FS(fsys))
hs := make(map[string]HandlerFunc)
for _, h := range handlers {
if _, ok := hs[h.path]; ok {
panic("multiple registrations for " + h.path)
}
hs[h.path] = h.fn
}
return &contentServer{fsys, fserv, hs}
}
type handler struct {
path string
fn HandlerFunc
}
func Handler(path string, h HandlerFunc) *handler {
return &handler{path, h}
}
func (c *contentServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) > 255 {
handleErr(w, r, errors.New("url too long"), http.StatusBadRequest)
return
}
if h, ok := c.handlers[r.URL.Path]; ok {
h.ServeHTTP(w, r)
return
}
ext := path.Ext(r.URL.Path)
if ext == ".md" || ext == ".html" {
http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, ext), http.StatusMovedPermanently)
return
}
filepath, err := stat(c.fsys, r.URL.Path)
if errors.Is(err, fs.ErrNotExist) {
handleErr(w, r, errors.New(http.StatusText(http.StatusNotFound)), http.StatusNotFound)
return
}
if err == nil {
if strings.HasSuffix(r.URL.Path, "/index") {
http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, "/index"), http.StatusMovedPermanently)
return
}
switch path.Ext(filepath) {
case ".html":
err = Template(w, c.fsys, filepath, nil, nil, http.StatusOK)
case ".md":
err = markdown(w, c.fsys, filepath, http.StatusOK)
default:
c.fserv.ServeHTTP(w, r)
}
}
if err != nil {
handleErr(w, r, err, http.StatusInternalServerError)
}
}
// Template executes a template response.
// TODO(rfindley): this abstraction no longer holds its weight. Refactor.
func Template(w http.ResponseWriter, fsys fs.FS, tmplPath string, funcs template.FuncMap, data any, code int) error {
patterns, err := tmplPatterns(fsys, tmplPath)
if err != nil {
return err
}
patterns = append(patterns, tmplPath)
tmpl, err := template.New("").Funcs(funcs).ParseFS(fsys, patterns...)
if err != nil {
return err
}
name := path.Base(tmplPath)
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil {
return err
}
if code != 0 {
w.WriteHeader(code)
}
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
if _, err := w.Write(buf.Bytes()); err != nil {
return err
}
return nil
}
// JSON encodes data as JSON response with a status code.
func JSON(w http.ResponseWriter, data any, code int) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(data); err != nil {
return err
}
if code != 0 {
w.WriteHeader(code)
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
if _, err := w.Write(buf.Bytes()); err != nil {
return err
}
return nil
}
// Text formats data as a text response with a status code.
func Text(w http.ResponseWriter, data any, code int) error {
var buf bytes.Buffer
if _, err := fmt.Fprint(&buf, data); err != nil {
return err
}
if code != 0 {
w.WriteHeader(code)
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
if _, err := w.Write(buf.Bytes()); err != nil {
return err
}
return nil
}
// TODO(rfindley): this docstring is stale, and Status should be a pure
// function.
// Text renders an http status code as a text response.
func Status(w http.ResponseWriter, code int) error {
if code < http.StatusBadRequest {
return Text(w, http.StatusText(code), code)
}
return Error(errors.New(http.StatusText(code)), code)
}
// Error annotates an error with http status information.
func Error(err error, code int) error {
return &contentError{err, code}
}
type contentError struct {
err error
Code int
}
func (e *contentError) Error() string { return e.err.Error() }
// handleErr writes an error as an HTTP response with a status code.
func handleErr(w http.ResponseWriter, req *http.Request, err error, code int) {
// TODO(rfindley): should we log here? Do we need to scrub errors before
// logging?
if cerr, ok := err.(*contentError); ok {
code = cerr.Code
}
if code == http.StatusInternalServerError {
http.Error(w, http.StatusText(http.StatusInternalServerError), code)
} else {
http.Error(w, err.Error(), code)
}
}
// markdown renders a markdown template as html.
func markdown(w http.ResponseWriter, fsys fs.FS, tmplPath string, code int) error {
markdown, err := fs.ReadFile(fsys, tmplPath)
if err != nil {
return err
}
md := goldmark.New(
goldmark.WithParserOptions(
parser.WithHeadingAttribute(),
parser.WithAutoHeadingID(),
),
goldmark.WithRendererOptions(
html.WithUnsafe(),
html.WithXHTML(),
),
goldmark.WithExtensions(
extension.GFM,
extension.NewTypographer(),
meta.Meta,
),
)
var content bytes.Buffer
ctx := parser.NewContext()
if err := md.Convert(markdown, &content, parser.WithContext(ctx)); err != nil {
return err
}
data := meta.Get(ctx)
if data == nil {
data = map[string]interface{}{}
}
data["Content"] = template.HTML(content.String())
layout, ok := data["Layout"]
if !ok {
return errors.New("missing layout for template " + tmplPath)
}
return Template(w, fsys, layout.(string), nil, data, code)
}
// stat trys to coerce a urlPath into an openable file then returns the
// file path.
func stat(fsys fs.FS, urlPath string) (string, error) {
cleanPath := path.Clean(strings.TrimPrefix(urlPath, "/"))
ext := path.Ext(cleanPath)
filePaths := []string{cleanPath}
if ext == "" || ext == "." {
md := cleanPath + ".md"
html := cleanPath + ".html"
indexMD := path.Join(cleanPath, "index.md")
indexHTML := path.Join(cleanPath, "index.html")
filePaths = []string{md, html, indexMD, indexHTML, cleanPath}
}
var p string
var err error
for _, p = range filePaths {
if _, err = fs.Stat(fsys, p); err == nil {
break
}
}
return p, err
}
// tmplPatterns generates a slice of file patterns to use in template.ParseFS.
func tmplPatterns(fsys fs.FS, tmplPath string) ([]string, error) {
var patterns []string
globs := []string{"*.tmpl", path.Join(path.Dir(tmplPath), "*.tmpl")}
for _, g := range globs {
matches, err := fs.Glob(fsys, g)
if err != nil {
return nil, err
}
patterns = append(patterns, matches...)
}
return patterns, nil
}
|
content
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/content_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"errors"
"io/fs"
"net/http"
"net/http/httptest"
"os"
"path"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/telemetry/internal/testenv"
)
func TestServer_ServeHTTP(t *testing.T) {
testenv.NeedsGo1Point(t, 23) // output of some http helpers changed in Go 1.23
fsys := os.DirFS("testdata")
server := Server(fsys,
Handler("/data", handleTemplate(fsys)),
Handler("/json", handleJSON()),
Handler("/text", handleText()),
Handler("/teapot", handleTeapot()),
Handler("/error", handleError()),
)
tests := []struct {
path string
wantOut string
wantCode int
}{
{
"/index.html",
"redirect.html.out",
http.StatusMovedPermanently,
},
{
"/index",
"redirect.out",
http.StatusMovedPermanently,
},
{
"/json",
"json.out",
http.StatusOK,
},
{
"/text",
"text.out",
http.StatusOK,
},
{
"/error",
"error.out",
http.StatusBadRequest,
},
{
"/teapot",
"teapot.out",
http.StatusTeapot,
},
{
"/style.css",
"style.css.out",
http.StatusOK,
},
{
"/",
"index.html.out",
http.StatusOK,
},
{
"/data",
"data.html.out",
http.StatusOK,
},
{
"/markdown",
"markdown.md.out",
http.StatusOK,
},
{
"/404",
"404.html.out",
http.StatusNotFound,
},
{
"/subdir",
"subdir/index.html.out",
http.StatusOK,
},
{
"/noindex/",
"noindex/noindex.html.out",
http.StatusOK,
},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
rr := httptest.NewRecorder()
req, err := http.NewRequest("GET", tt.path, nil)
if err != nil {
t.Fatal(err)
}
server.ServeHTTP(rr, req)
got := strings.TrimSpace(rr.Body.String())
data, err := os.ReadFile(path.Join("testdata", tt.wantOut))
if err != nil {
t.Fatal(err)
}
wantBody := strings.TrimSpace(string(data))
if diff := cmp.Diff(wantBody, got); diff != "" {
t.Errorf("GET %s response body mismatch (-want, +got):\n%s", tt.path, diff)
}
if rr.Code != tt.wantCode {
t.Errorf("GET %s response code = %d, want %d", tt.path, rr.Code, tt.wantCode)
}
})
}
}
func Test_stat(t *testing.T) {
fsys := os.DirFS("testdata")
tests := []struct {
urlPath string
want string
}{
{"/", "index.html"},
{"/markdown", "markdown.md"},
{"/sub/path", "sub/path"},
}
for _, tt := range tests {
t.Run(tt.urlPath, func(t *testing.T) {
if got, _ := stat(fsys, tt.urlPath); got != tt.want {
t.Errorf("stat() = %v, want %v", got, tt.want)
}
})
}
}
func handleTemplate(fsys fs.FS) HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) error {
return Template(w, fsys, "data.html", nil, "Data from Handler", http.StatusOK)
}
}
func handleJSON() HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) error {
return JSON(w, struct{ Data string }{Data: "Data"}, http.StatusOK)
}
}
func handleText() HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) error {
return Text(w, "Hello, World!", http.StatusOK)
}
}
func handleTeapot() HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
return Status(w, http.StatusTeapot)
}
}
func handleError() HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
return Error(errors.New("Bad Request"), http.StatusBadRequest)
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/redirect.html.out
|
<a href="/index">Moved Permanently</a>.
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/index.html.out
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
</head>
<body>
<main>
<header>
<h1>Page Title</h1>
</header>
</main>
</body>
</html>
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/teapot.out
|
I'm a teapot
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/base.tmpl
|
<!--
Copyright 2023 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{block "title" .}}{{.Title}}{{end}}</title>
</head>
<body>
<main>
{{block "content" .}}{{.Content}}{{end}}
</main>
</body>
</html>
{{end}}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/data.html.out
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
</head>
<body>
<main>
<header>
<h1>Data from Handler</h1>
</header>
</main>
</body>
</html>
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/style.css
|
/*!
* Copyright 2023 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
a {
color: transparent;
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/error.out
|
Bad Request
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/text.out
|
Hello, World!
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/base.html
|
<!--
Copyright 2023 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{{template "base" .}}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/markdown.md
|
---
Title: Page Title
Layout: base.html
---
# This is a heading
## This is a subheading
[link](https://go.dev)
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/style.css.out
|
/*!
* Copyright 2023 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
a {
color: transparent;
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/index.html
|
<!--
Copyright 2023 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{{template "base" .}}
{{define "title"}}Page Title{{end}}
{{define "content"}}
<header>
<h1>Page Title</h1>
</header>
{{end}}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/markdown.md.out
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
</head>
<body>
<main>
<h1 id="this-is-a-heading">This is a heading</h1>
<h2 id="this-is-a-subheading">This is a subheading</h2>
<p><a href="https://go.dev">link</a></p>
</main>
</body>
</html>
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/data.html
|
<!--
Copyright 2023 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{{template "base" .}}
{{define "title"}}Page Title{{end}}
{{define "content"}}
<header>
<h1>{{.}}</h1>
</header>
{{end}}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/redirect.out
|
<a href="/">Moved Permanently</a>.
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/json.out
|
{"Data":"Data"}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/404.html.out
|
Not Found
|
noindex
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/noindex/noindex.html.out
|
<!doctype html>
<meta name="viewport" content="width=device-width">
<pre>
<a href="noindex.html.out">noindex.html.out</a>
</pre>
|
subdir
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/subdir/index.html.out
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
</head>
<body>
<main>
<header>
<h1>Page in subdirectory</h1>
</header>
</main>
</body>
</html>
|
subdir
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/content/testdata/subdir/index.html
|
<!--
Copyright 2023 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{{template "base" .}}
{{define "title"}}Page Title{{end}}
{{define "content"}}
<header>
<h1>Page in subdirectory</h1>
</header>
{{end}}
|
config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/config/config.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package config
import (
"flag"
"log"
"os"
"strconv"
"time"
)
type Config struct {
// ServerPort is the port for the cmd/telemetrygodev.
ServerPort string
// WorkerPort is the port for the cmd/worker.
WorkerPort string
// WorkerURL is the location url of the worker used in queueing worker tasks.
WorkerURL string
// ProjectID is a GCP project ID.
ProjectID string
// LocationID is a GCP location ID.
LocationID string
// QueueID is the name of the queue for worker tasks.
QueueID string
// IAPServiceAccount is the service account used when queueing worker tasks.
IAPServiceAccount string
// ClientID is the OAuth client used in authentication for queue tasks.
ClientID string
// StorageEmulatorHost is a network address for a Cloud Storage emulator.
StorageEmulatorHost string
// LocalStorage is a directory for storage I/O used when the using the filesystem
// or storage emulator modes.
LocalStorage string
// MergedBucket is the storage bucket for merged reports. The worker merges the
// reports from the upload bucket and saves them here.
MergedBucket string
// UploadBucket is the storage bucket for report uploads.
UploadBucket string
// ChartDataBucket is the storage bucket for chart data.
ChartDataBucket string
// UploadConfig is the location of the upload config deployed with the server.
// It's used to validate telemetry uploads.
UploadConfig string
// MaxRequestBytes is the maximum request body size the server will allow.
MaxRequestBytes int64
// RequestTimeout is the default request timeout for the server.
RequestTimeout time.Duration
// UseGCS is true if the server should use the Cloud Storage API for reading and
// writing storage objects.
UseGCS bool
// DevMode is true if the server should read content files from the filesystem.
// If false, content files are read from the embed.FS in ../content.go.
DevMode bool
}
var (
devMode = flag.Bool("dev", false, "load static content and templates from the filesystem")
useGCS = flag.Bool("gcs", false, "use Cloud Storage for reading and writing storage objects")
)
// NewConfig returns a new config. Getting the config should follow a call to flag.Parse.
func NewConfig() *Config {
environment := env("GO_TELEMETRY_ENV", "local")
return &Config{
ServerPort: env("PORT", "8080"),
WorkerPort: env("PORT", "8082"),
WorkerURL: env("GO_TELEMETRY_WORKER_URL", "http://localhost:8082"),
ProjectID: env("GO_TELEMETRY_PROJECT_ID", ""),
LocationID: env("GO_TELEMETRY_LOCATION_ID", ""),
QueueID: environment + "-worker-tasks",
IAPServiceAccount: env("GO_TELEMETRY_IAP_SERVICE_ACCOUNT", ""),
ClientID: env("GO_TELEMETRY_CLIENT_ID", ""),
StorageEmulatorHost: env("GO_TELEMETRY_STORAGE_EMULATOR_HOST", "localhost:8081"),
LocalStorage: env("GO_TELEMETRY_LOCAL_STORAGE", ".localstorage"),
ChartDataBucket: environment + "-telemetry-charted",
MergedBucket: environment + "-telemetry-merged",
UploadBucket: environment + "-telemetry-uploaded",
UploadConfig: env("GO_TELEMETRY_UPLOAD_CONFIG", "./config/config.json"),
MaxRequestBytes: env("GO_TELEMETRY_MAX_REQUEST_BYTES", int64(100*1024)),
RequestTimeout: 10 * time.Duration(time.Minute),
UseGCS: *useGCS,
DevMode: *devMode,
}
}
// env reads a value from the os environment and returns a fallback
// when it is unset.
func env[T string | int64](key string, fallback T) T {
if s, ok := os.LookupEnv(key); ok {
switch any(fallback).(type) {
case string:
return any(s).(T)
case int64:
v, err := strconv.Atoi(s)
if err != nil {
log.Fatalf("bad value %q for %s: %v", s, key, err)
}
return any(v).(T)
}
}
return fallback
}
|
storage
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/storage/storage_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package storage
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/google/go-cmp/cmp"
)
type jsondata struct {
Tars string
Case string
Kipp map[string]int
}
var writeData = jsondata{
Tars: "foo",
Case: "bar",
Kipp: map[string]int{"plex": 0},
}
func TestFSStore(t *testing.T) {
ctx := context.Background()
s, err := NewFSBucket(ctx, t.TempDir(), "test-bucket")
if err != nil {
t.Fatal(err)
}
runTest(t, ctx, s)
}
func runTest(t *testing.T, ctx context.Context, s BucketHandle) {
// write the object to store
if err := write(ctx, s, "prefix/test-object", writeData); err != nil {
t.Fatal(err)
}
// read same object from store
readData, err := read(ctx, s, "prefix/test-object")
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(writeData, readData); diff != "" {
t.Errorf("data write read mismatch (-wrote +read):\n%s", diff)
}
// write an object with a different prefix to store
if err = write(ctx, s, "other-prefix/test-object-2", writeData); err != nil {
t.Fatal(err)
}
// check that prefix matches single object
it := s.Objects(ctx, "prefix")
var list1 []string
for {
elem, err := it.Next()
if errors.Is(err, ErrObjectIteratorDone) {
break
}
if err != nil {
t.Fatal(err)
}
list1 = append(list1, elem)
}
if diff := cmp.Diff(list1, []string{"prefix/test-object"}); diff != "" {
t.Errorf("Objects() mismatch (-want +got):\n%s", diff)
}
// check that prefix matches with partial path and separator
it = s.Objects(ctx, "prefix/test")
var list2 []string
for {
elem, err := it.Next()
if errors.Is(err, ErrObjectIteratorDone) {
break
}
if err != nil {
t.Fatal(err)
}
list2 = append(list2, elem)
}
if diff := cmp.Diff(list2, []string{"prefix/test-object"}); diff != "" {
t.Errorf("Objects() mismatch (-want +got):\n%s", diff)
}
}
func write(ctx context.Context, s BucketHandle, object string, data any) error {
obj, err := s.Object("prefix/test-object").NewWriter(ctx)
if err != nil {
return err
}
if err := json.NewEncoder(obj).Encode(writeData); err != nil {
return err
}
return obj.Close()
}
func read(ctx context.Context, s BucketHandle, object string) (any, error) {
obj, err := s.Object("prefix/test-object").NewReader(ctx)
if err != nil {
return nil, err
}
var data jsondata
if err := json.NewDecoder(obj).Decode(&data); err != nil {
return nil, err
}
if err := obj.Close(); err != nil {
return nil, err
}
return data, nil
}
|
storage
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/storage/storage.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package storage provides an interface and types for reading and writing
// files to Cloud Storage or a filesystem.
package storage
import (
"context"
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"cloud.google.com/go/storage"
"google.golang.org/api/iterator"
)
var (
_ BucketHandle = &GCSBucket{}
_ BucketHandle = &FSBucket{}
)
var (
ErrObjectIteratorDone = errors.New("object iterator done")
ErrObjectNotExist = errors.New("object not exist")
)
type BucketHandle interface {
Object(name string) ObjectHandle
Objects(ctx context.Context, prefix string) ObjectIterator
URI() string
}
type ObjectHandle interface {
NewReader(ctx context.Context) (io.ReadCloser, error)
NewWriter(ctx context.Context) (io.WriteCloser, error)
}
type ObjectIterator interface {
Next() (name string, err error)
}
type GCSBucket struct {
*storage.BucketHandle
url string
}
func NewGCSBucket(ctx context.Context, project, bucket string) (BucketHandle, error) {
client, err := storage.NewClient(ctx)
if err != nil {
return nil, err
}
bkt := client.Bucket(bucket)
// Check if the bucket exists by reading its metadata and on error create the bucket.
_, err = bkt.Attrs(ctx)
if err != nil {
if err := bkt.Create(ctx, project, nil); err != nil {
return nil, err
}
}
url := "https://storage.googleapis.com/" + bucket
return &GCSBucket{bkt, url}, nil
}
func (b *GCSBucket) Object(name string) ObjectHandle {
return NewGCSObject(b, name)
}
type GCSObject struct {
*storage.ObjectHandle
}
func NewGCSObject(b *GCSBucket, name string) ObjectHandle {
return &GCSObject{b.BucketHandle.Object(name)}
}
func (o *GCSObject) NewReader(ctx context.Context) (io.ReadCloser, error) {
return o.ObjectHandle.NewReader(ctx)
}
func (o *GCSObject) NewWriter(ctx context.Context) (io.WriteCloser, error) {
return o.ObjectHandle.NewWriter(ctx), nil
}
func (b *GCSBucket) Objects(ctx context.Context, prefix string) ObjectIterator {
return &GCSObjectIterator{b.BucketHandle.Objects(ctx, &storage.Query{Prefix: prefix})}
}
type GCSObjectIterator struct {
*storage.ObjectIterator
}
func (it *GCSObjectIterator) Next() (elem string, err error) {
o, err := it.ObjectIterator.Next()
if errors.Is(err, iterator.Done) {
return "", ErrObjectIteratorDone
}
if err != nil {
return "", err
}
return o.Name, nil
}
func (b *GCSBucket) URI() string {
return b.url
}
type FSBucket struct {
dir, bucket, uri string
}
func NewFSBucket(ctx context.Context, dir, bucket string) (BucketHandle, error) {
if err := os.MkdirAll(filepath.Join(dir, bucket), os.ModePerm); err != nil {
return nil, err
}
uri, err := filepath.Abs(filepath.Join(dir, filepath.Clean(bucket)))
if err != nil {
return nil, err
}
return &FSBucket{dir, bucket, uri}, nil
}
func (b *FSBucket) Object(name string) ObjectHandle {
return NewFSObject(b, name)
}
type FSObject struct {
filename string
}
func NewFSObject(b *FSBucket, name string) ObjectHandle {
filename := filepath.Join(b.dir, b.bucket, filepath.FromSlash(name))
return &FSObject{filename}
}
func (o *FSObject) NewReader(ctx context.Context) (io.ReadCloser, error) {
r, err := os.Open(o.filename)
if errors.Is(err, os.ErrNotExist) {
return nil, ErrObjectNotExist
}
return r, err
}
func (o *FSObject) NewWriter(ctx context.Context) (io.WriteCloser, error) {
if err := os.MkdirAll(filepath.Dir(o.filename), os.ModePerm); err != nil {
return nil, err
}
return os.Create(o.filename)
}
func (b *FSBucket) Objects(ctx context.Context, prefix string) ObjectIterator {
var names []string
err := fs.WalkDir(
os.DirFS(filepath.Join(b.dir, b.bucket)),
".",
func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}
name := filepath.ToSlash(path)
if strings.HasPrefix(name, prefix) {
names = append(names, name)
}
return nil
},
)
return &FSObjectIterator{names, err, 0}
}
type FSObjectIterator struct {
names []string
err error
index int
}
func (it *FSObjectIterator) Next() (name string, err error) {
if it.index >= len(it.names) {
return "", ErrObjectIteratorDone
}
name = it.names[it.index]
it.index++
return name, nil
}
func (b *FSBucket) URI() string {
return b.uri
}
|
storage
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/internal/storage/api.go
|
package storage
import (
"context"
"golang.org/x/telemetry/godev/internal/config"
)
type API struct {
Upload BucketHandle
Merge BucketHandle
Chart BucketHandle
}
func NewAPI(ctx context.Context, cfg *config.Config) (*API, error) {
upload, err := newBucket(ctx, cfg, cfg.UploadBucket)
if err != nil {
return nil, err
}
merge, err := newBucket(ctx, cfg, cfg.MergedBucket)
if err != nil {
return nil, err
}
chart, err := newBucket(ctx, cfg, cfg.ChartDataBucket)
if err != nil {
return nil, err
}
return &API{upload, merge, chart}, nil
}
func newBucket(ctx context.Context, cfg *config.Config, name string) (BucketHandle, error) {
if cfg.UseGCS {
return NewGCSBucket(ctx, cfg.ProjectID, name)
}
return NewFSBucket(ctx, cfg.LocalStorage, name)
}
|
devtools
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/devtools/localstorage.sh
|
#!/usr/bin/env bash
# Copyright 2023 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
set -e
# Script for running a Google Cloud Storage API emulator.
#
# Connect to the emulator by adding an endpoint option when creating a storage
# client.
#
# client, err := storage.NewClient(
# context.Background(),
# option.WithEndpoint("http://localhost:8081/storage/v1/"),
# )
#
# Or by setting STORAGE_EMULATOR_HOST=localhost:8081 when running your program.
#
# STORAGE_EMULATOR_HOST=localhost:8081 go run ./cmd/my-command
#
# OR
#
# if err := os.Setenv("STORAGE_EMULATOR_HOST", "localhost:8081"); err != nil {
# log.Fatal(err)
# }
#
# By default, the emulator will read and write from godev/.localstorage. Pass a
# directory to override that location.
#
# ./devtools/localstorage.sh ~/storage
version=v0.0.0-20230523204811-eccb7d2267b0
port=8081
dir="${GO_TELEMETRY_LOCAL_STORAGE:-.localstorage}"
if [ ! -z "$1" ]; then
dir="$1"
fi
if ! command -v gcsemulator &> /dev/null
then
echo "Command gcsemulator could not be found. Installing..."
go install github.com/fullstorydev/emulators/storage/cmd/gcsemulator@$version
fi
gcsemulator -port $port -dir $dir
|
esbuild
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/devtools/cmd/esbuild/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !plan9
// Command esbuild bundles and minifies stylesheet and typescript files.
//
// The command will walk the directory it is run in to gather the set of
// entrypoints and filenames beginning with an underscore are ignored.
//
// go run golang.org/x/telemetry/godev/devtools/cmd/esbuild
//
// You can also pass a directory as an argument to the command.
//
// go run golang.org/x/telemetry/godev/devtools/cmd/esbuild directory
//
// By default the command writes the output files to the same directory as
// the entrypoints with .min.css or .min.js extensions for .css and .ts files
// respectively. Override the output directory with a flag.
//
// go run golang.org/x/telemetry/godev/devtools/cmd/esbuild --outdir static
//
// To watch the entrypoints and rebuild the output files on changes use the
// watch flag.
//
// go run golang.org/x/telemetry/godev/devtools/cmd/esbuild --watch
package main
import (
"flag"
"io/fs"
"log"
"os"
"path"
"strings"
"github.com/evanw/esbuild/pkg/api"
)
var (
outdir = flag.String("outdir", ".", "output directory for the build operation")
watch = flag.Bool("watch", false, "listen for changes on the filesystem and automatically rebuild")
)
func main() {
flag.Parse()
dirs := []string{"."}
if len(flag.Args()) > 0 {
dirs = flag.Args()
}
for _, dir := range dirs {
opts := api.BuildOptions{
Banner: map[string]string{"css": "/* Code generated by esbuild. DO NOT EDIT. */", "js": "// Code generated by esbuild. DO NOT EDIT."},
Bundle: true,
EntryPoints: entrypoints(dir),
LogLevel: api.LogLevelInfo,
MinifyWhitespace: true,
MinifyIdentifiers: true,
MinifySyntax: true,
OutExtension: map[string]string{".css": ".min.css", ".js": ".min.js"},
Outdir: *outdir,
Sourcemap: api.SourceMapLinked,
Write: true,
}
if *watch {
ctx, err := api.Context(opts)
if err != nil {
log.Fatal(err)
}
if err := ctx.Watch(api.WatchOptions{}); err != nil {
log.Fatal(err)
}
// Returning from main() exits immediately in Go.
// Block forever so we keep watching and don't exit.
<-make(chan struct{})
} else {
result := api.Build(opts)
if len(result.Errors) > 0 {
// esbuild already logs errors
os.Exit(1)
}
}
}
}
func entrypoints(dir string) []string {
var e []string
if err := fs.WalkDir(os.DirFS(dir), ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
base := path.Base(p)
if strings.HasPrefix(base, "_") || strings.HasSuffix(base, ".min.css") || strings.HasSuffix(base, ".min.js") {
return nil
}
switch path.Ext(p) {
case ".css", ".ts":
e = append(e, path.Join(dir, p))
}
return nil
}); err != nil {
log.Fatal(err)
}
return e
}
|
worker
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/worker/Dockerfile
|
# Copyright 2023 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# This Dockerfile expects the build context to be the repo root.
# NOTE: don't put anything in /tmp here. It will work locally,
# but Cloud Run mounts something else to /tmp, so anything
# installed here will be shadowed.
FROM golang:1.22
LABEL maintainer="Go Telemetry Team <go-telemetry-team@google.com>"
#### Preliminaries
WORKDIR /
# Create some directories.
# The worker binary and related files live here.
RUN mkdir /app
#### Building binaries
# Set the working directory outside $GOPATH to ensure module mode is enabled.
WORKDIR /telemetry
# Copy go.mods and go.sums into the container.
# If they don't change, which is the common case, then docker can
# cache these COPYs and the subsequent RUN.
COPY go.mod go.sum ./
WORKDIR /telemetry/godev
COPY go.mod go.sum ./
# Download the dependencies.
RUN go mod download
WORKDIR /telemetry
# Copy the repo from local machine into Docker client’s current working
# directory, so that we can use it to build the binary.
# See .dockerignore at the repo root for excluded files.
COPY . ./
WORKDIR /telemetry/godev
# Build the worker binary and put it in /app.
RUN go build -mod=readonly -o /app/worker ./cmd/worker
WORKDIR /telemetry
COPY config/config.json /app/config.json
#### worker init
WORKDIR /app
ENV GO_TELEMETRY_UPLOAD_CONFIG=/app/config.json
CMD ["./worker", "--gcs"]
|
worker
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/worker/main_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"net/url"
"reflect"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"golang.org/x/telemetry/internal/config"
"golang.org/x/telemetry/internal/telemetry"
)
var exampleReports = []telemetry.Report{
{
Week: "2999-01-01",
LastWeek: "2998-01-01",
X: 0.123456789,
Programs: []*telemetry.ProgramReport{
{
Program: "cmd/go",
Version: "go1.2.3",
GoVersion: "go1.2.3",
GOOS: "darwin",
GOARCH: "arm64",
Counters: map[string]int64{
"main": 1,
},
},
{
Program: "example.com/mod/pkg",
Version: "v2.3.4",
GoVersion: "go1.2.3",
GOOS: "darwin",
GOARCH: "arm64",
Counters: map[string]int64{
"main": 1,
"flag:a": 2,
"flag:b": 3,
},
// TODO: add support for stacks
Stacks: map[string]int64{
"panic": 4,
},
},
},
Config: "v0.0.1",
},
{
Week: "2999-01-01",
LastWeek: "2998-01-01",
X: 0.123456789,
Programs: []*telemetry.ProgramReport{
{
Program: "example.com/mod/pkg",
Version: "v1.2.3",
GoVersion: "go1.2.3",
GOOS: "darwin",
GOARCH: "arm64",
Counters: map[string]int64{
"main": 1,
"flag:a": 2,
"flag:b": 3,
},
// TODO: add support for stacks
Stacks: map[string]int64{
"panic": 4,
},
},
{
Program: "example.com/mod/pkg",
Version: "v2.3.4",
GoVersion: "go1.2.3",
GOOS: "darwin",
GOARCH: "arm64",
Counters: map[string]int64{
"main": 1,
"flag:a": 2,
"flag:b": 3,
},
// TODO: add support for stacks
Stacks: map[string]int64{
"panic": 4,
},
},
},
Config: "v0.0.1",
},
{
Week: "2999-01-01",
LastWeek: "2998-01-01",
X: 0.987654321,
Programs: []*telemetry.ProgramReport{
{
Program: "example.com/mod/pkg",
Version: "v1.2.3",
GoVersion: "go1.2.3",
GOOS: "linux",
GOARCH: "amd64",
Counters: map[string]int64{
"main": 4,
"flag:a": 5,
"flag:b": 6,
"flag:c": 1,
},
// TODO: add support for stacks
Stacks: map[string]int64{
"panic": 7,
},
},
},
Config: "v0.0.1",
},
}
func TestNest(t *testing.T) {
type args struct {
reports []telemetry.Report
}
tests := []struct {
name string
args args
want data
}{
{
name: "single report",
args: args{
[]telemetry.Report{
{
Week: "2999-01-01",
LastWeek: "2998-01-01",
X: 0.123456789,
Programs: []*telemetry.ProgramReport{
{
Program: "example.com/mod/pkg",
Version: "v1.2.3",
GoVersion: "go1.2.3",
GOOS: "darwin",
GOARCH: "arm64",
Counters: map[string]int64{
"main": 1,
"flag:a": 2,
"flag:b": 3,
},
// TODO: add support for stacks
Stacks: map[string]int64{
"panic": 4,
},
},
},
Config: "v0.0.1",
},
},
},
want: data{
weekName("2999-01-01"): {
programName("example.com/mod/pkg"): {
graphName("Version"): {
counterName("Version"): {
reportID(0.1234567890): 1,
},
counterName("Version:v1.2"): {
reportID(0.1234567890): 1,
},
},
graphName("GOOS"): {
counterName("GOOS"): {
reportID(0.1234567890): 1,
},
counterName("GOOS:darwin"): {
reportID(0.1234567890): 1,
},
},
graphName("GOARCH"): {
counterName("GOARCH"): {
reportID(0.1234567890): 1,
},
counterName("GOARCH:arm64"): {
reportID(0.1234567890): 1,
},
},
graphName("GoVersion"): {
counterName("GoVersion"): {
reportID(0.1234567890): 1,
},
counterName("GoVersion:go1.2"): {
reportID(0.1234567890): 1,
},
},
graphName("main"): {
counterName("main"): {
reportID(0.1234567890): 1,
},
},
graphName("flag"): {
counterName("flag"): {
reportID(0.1234567890): 5,
},
counterName("flag:a"): {
reportID(0.1234567890): 2,
},
counterName("flag:b"): {
reportID(0.1234567890): 3,
},
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := nest(tt.args.reports)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("nest() = %v, want %v", got, tt.want)
}
})
}
}
func TestPartition(t *testing.T) {
exampleData := nest(exampleReports)
type args struct {
program string
name string
buckets []string
}
tests := []struct {
name string
data data
args args
want *chart
}{
{
name: "major.minor.patch version counter",
data: exampleData,
args: args{
program: "example.com/mod/pkg",
name: "Version",
buckets: []string{"v1.2.3", "v2.3.4"},
},
want: &chart{
ID: "charts:example.com/mod/pkg:Version",
Name: "Version",
Type: "partition",
Data: []*datum{
{
Week: "2999-01-01",
Key: "v1.2",
Value: 2,
},
{
Week: "2999-01-01",
Key: "v2.3",
Value: 1,
},
},
},
},
{
name: "major.minor version counter should have same result as major.minor.patch",
data: exampleData,
args: args{
program: "example.com/mod/pkg",
name: "Version",
buckets: []string{"v1.2", "v2.3"},
},
want: &chart{
ID: "charts:example.com/mod/pkg:Version",
Name: "Version",
Type: "partition",
Data: []*datum{
{
Week: "2999-01-01",
Key: "v1.2",
Value: 2,
},
{
Week: "2999-01-01",
Key: "v2.3",
Value: 1,
},
},
},
},
{
name: "duplicated counter should be ignored",
data: exampleData,
args: args{
program: "example.com/mod/pkg",
name: "Version",
buckets: []string{"v1.2.3", "v2.3.4", "v1.2.3"},
},
want: &chart{
ID: "charts:example.com/mod/pkg:Version",
Name: "Version",
Type: "partition",
Data: []*datum{
{
Week: "2999-01-01",
Key: "v1.2",
Value: 2,
},
{
Week: "2999-01-01",
Key: "v2.3",
Value: 1,
},
},
},
},
{
name: "goos counter",
data: exampleData,
args: args{
program: "example.com/mod/pkg",
name: "GOOS",
buckets: []string{"darwin", "linux"},
},
want: &chart{
ID: "charts:example.com/mod/pkg:GOOS",
Name: "GOOS",
Type: "partition",
Data: []*datum{
{
Week: "2999-01-01",
Key: "darwin",
Value: 1,
},
{
Week: "2999-01-01",
Key: "linux",
Value: 1,
},
},
},
},
{
name: "three days, multiple versions",
data: data{
"2999-01-01": {"example.com/mod/pkg": {"Version": {
"Version": {0.1: 5},
"Version:v1.2": {0.1: 2},
"Version:v2.3": {0.1: 3},
},
}},
"2999-01-04": {"example.com/mod/pkg": {"Version": {
"Version": {0.3: 2, 0.4: 5},
"Version:v1.2": {0.3: 2},
"Version:v2.3": {0.4: 5},
},
}},
"2999-01-05": {"example.com/mod/pkg": {"Version": {
"Version": {0.5: 6},
"Version:v2.3": {0.5: 6},
}}},
},
args: args{
program: "example.com/mod/pkg",
name: "Version",
buckets: []string{"v1.2.3", "v2.3.4"},
},
want: &chart{
ID: "charts:example.com/mod/pkg:Version",
Name: "Version",
Type: "partition",
Data: []*datum{
{
Week: "2999-01-05",
Key: "v1.2",
Value: 2,
},
{
Week: "2999-01-05",
Key: "v2.3",
Value: 3,
},
},
},
},
{
name: "three days, multiple GOOS",
data: data{
"2999-01-01": {"example.com/mod/pkg": {"GOOS": {
"GOOS": {0.1: 4, 0.2: 4, 0.3: 2},
"GOOS:darwin": {0.1: 2, 0.2: 2, 0.3: 2},
"GOOS:linux": {0.1: 2, 0.2: 2},
},
}},
"2999-01-02": {"example.com/mod/pkg": {"GOOS": {
"GOOS": {0.4: 2, 0.5: 2, 0.6: 5},
"GOOS:darwin": {0.4: 2, 0.5: 2},
"GOOS:linux": {0.6: 5},
},
}},
"2999-01-03": {"example.com/mod/pkg": {"GOOS": {
"GOOS": {0.6: 3},
"GOOS:darwin": {0.6: 3},
},
}},
},
args: args{
program: "example.com/mod/pkg",
name: "GOOS",
buckets: []string{"darwin", "linux"},
},
want: &chart{
ID: "charts:example.com/mod/pkg:GOOS",
Name: "GOOS",
Type: "partition",
Data: []*datum{
{
Week: "2999-01-03",
Key: "darwin",
Value: 6,
},
{
Week: "2999-01-03",
Key: "linux",
Value: 3,
},
},
},
},
{
name: "two days data, missing GOOS in first day",
data: data{
"2999-01-01": {"example.com/mod/pkg": {"Version": {
"Version": {0.1: 2},
"Version:v1.2": {0.1: 2},
},
}},
"2999-01-02": {"example.com/mod/pkg": {"GOOS": {
"GOOS": {0.3: 4},
"GOOS:darwin": {0.3: 2},
"GOOS:linux": {0.3: 2},
},
}},
},
args: args{
program: "example.com/mod/pkg",
name: "GOOS",
buckets: []string{"darwin", "linux"},
},
want: &chart{
ID: "charts:example.com/mod/pkg:GOOS",
Name: "GOOS",
Type: "partition",
Data: []*datum{
{
Week: "2999-01-02",
Key: "darwin",
Value: 1,
},
{
Week: "2999-01-02",
Key: "linux",
Value: 1,
},
},
},
},
{
name: "three days, missing version data all days",
data: data{
"2999-01-01": {"example.com/mod/pkg": {"GOOS": {
"GOOS": {0.1: 2},
"GOOS:darwin": {0.1: 2},
},
}},
"2999-01-02": {"example.com/mod/pkg": {"GOOS": {
"GOOS": {0.6: 5},
"GOOS:linux": {0.6: 5},
},
}},
"2999-01-03": {"example.com/mod/pkg": {"GOOS": {
"GOOS": {0.6: 3},
"GOOS:darwin": {0.6: 3},
},
}},
},
args: args{
program: "example.com/mod/pkg",
name: "Version",
buckets: []string{"v1.2.3", "v2.3.4"},
},
want: nil,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := tc.data.partition(tc.args.program, tc.args.name, tc.args.buckets); !reflect.DeepEqual(got, tc.want) {
t.Errorf("partition() = %v, want %v", got, tc.want)
}
})
}
}
func TestCharts(t *testing.T) {
exampleData := nest(exampleReports)
cfg := &config.Config{
UploadConfig: &telemetry.UploadConfig{
GOOS: []string{"darwin"},
GOARCH: []string{"amd64"},
GoVersion: []string{"go1.2.3"},
SampleRate: 1,
Programs: []*telemetry.ProgramConfig{
{
Name: "cmd/go",
Versions: []string{"go1.2.3"},
Counters: []telemetry.CounterConfig{{
Name: "main",
}},
},
{
Name: "cmd/compiler",
Versions: []string{"go1.2.3"},
Counters: []telemetry.CounterConfig{{
Name: "count1",
}},
},
{
Name: "example.com/mod/pkg",
Versions: []string{"v0.15.0"},
Counters: []telemetry.CounterConfig{{
Name: "count2",
}},
},
},
},
}
want := &chartdata{
DateRange: [2]string{"2999-01-01", "2999-01-01"},
Programs: []*program{
{
ID: "charts:cmd/go",
Name: "cmd/go",
Charts: []*chart{
{
ID: "charts:cmd/go:GOOS",
Name: "GOOS",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "darwin",
Value: 1,
}},
},
{
ID: "charts:cmd/go:GOARCH",
Name: "GOARCH",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "amd64",
Value: 0,
}},
},
{
ID: "charts:cmd/go:GoVersion",
Name: "GoVersion",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "go1.2",
Value: 1,
}},
},
{
ID: "charts:cmd/go:main",
Name: "main",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "main",
Value: 1,
}},
},
},
},
{
ID: "charts:cmd/compiler",
Name: "cmd/compiler",
},
{
ID: "charts:example.com/mod/pkg",
Name: "example.com/mod/pkg",
Charts: []*chart{
{
ID: "charts:example.com/mod/pkg:Version",
Name: "Version",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "v0.15",
Value: 0,
}},
},
{
ID: "charts:example.com/mod/pkg:GOOS",
Name: "GOOS",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "darwin",
Value: 1,
}},
},
{
ID: "charts:example.com/mod/pkg:GOARCH",
Name: "GOARCH",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "amd64",
Value: 1,
}},
},
{
ID: "charts:example.com/mod/pkg:GoVersion",
Name: "GoVersion",
Type: "partition",
Data: []*datum{{
Week: "2999-01-01",
Key: "go1.2",
Value: 2,
}},
},
},
},
},
NumReports: 1,
}
got := charts(cfg, "2999-01-01", "2999-01-01", exampleData, []float64{0.12345})
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("charts = %+v\n, (-want +got): %v", got, diff)
}
}
func TestNormalizeCounterName(t *testing.T) {
testcases := []struct {
name string
prefix string
counter string
want string
}{
{
name: "strip patch version for Version",
prefix: "Version",
counter: "v0.15.3",
want: "Version:v0.15",
},
{
name: "strip patch go version for Version",
prefix: "Version",
counter: "go1.12.3",
want: "Version:go1.12",
},
{
name: "concatenate devel for Version",
prefix: "Version",
counter: "devel",
want: "Version:devel",
},
{
name: "concatenate for GOOS",
prefix: "GOOS",
counter: "darwin",
want: "GOOS:darwin",
},
{
name: "concatenate for GOARCH",
prefix: "GOARCH",
counter: "amd64",
want: "GOARCH:amd64",
},
{
name: "strip patch version for GoVersion",
prefix: "GoVersion",
counter: "go1.12.3",
want: "GoVersion:go1.12",
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
got := normalizeCounterName(tc.prefix, tc.counter)
if tc.want != got {
t.Errorf("normalizeCounterName(%q, %q) = %q, want %q", tc.prefix, tc.counter, got, tc.want)
}
})
}
}
func TestWriteCount(t *testing.T) {
type keyValue struct {
week, program, prefix, counter string
x float64
value int64
}
testcases := []struct {
name string
inputs []keyValue
wants []keyValue
}{
{
name: "program version counter should have value",
inputs: []keyValue{
{"2987-07-01", "golang.org/x/tools/gopls", "Version", "v0.15.3", 0.00009, 1},
},
wants: []keyValue{
{"2987-07-01", "golang.org/x/tools/gopls", "Version", "Version:v0.15", 0.00009, 1},
{"2987-07-01", "golang.org/x/tools/gopls", "Version", "Version", 0.00009, 1},
},
},
{
name: "only one count with same prefix and counter",
inputs: []keyValue{
{"2987-06-30", "cmd/go", "go/invocations", "go/invocations", 0.86995, 84},
},
wants: []keyValue{
{"2987-06-30", "cmd/go", "go/invocations", "go/invocations", 0.86995, 84},
},
},
{
name: "sum together when calling multiple times",
inputs: []keyValue{
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "windows", 0.86018, 1},
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "windows", 0.86018, 2},
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "windows", 0.86018, 3},
},
wants: []keyValue{
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "GOOS:windows", 0.86018, 6},
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "GOOS", 0.86018, 6},
},
},
{
name: "sum together when the prefix is the same",
inputs: []keyValue{
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "windows", 0.86018, 1},
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "windows", 0.86018, 2},
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "linux", 0.86018, 4},
},
wants: []keyValue{
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "GOOS:windows", 0.86018, 3},
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "GOOS:linux", 0.86018, 4},
{"2987-06-30", "golang.org/x/tools/gopls", "GOOS", "GOOS", 0.86018, 7},
},
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
d := make(data)
for _, input := range tc.inputs {
d.writeCount(input.week, input.program, input.prefix, input.counter, input.x, input.value)
}
for _, want := range tc.wants {
got, _ := d.readCount(want.week, want.program, want.prefix, want.counter, want.x)
if want.value != got {
t.Errorf("d[%q][%q][%q][%q][%v] = %v, want %v", want.week, want.program, want.prefix, want.counter, want.x, got, want.value)
}
}
})
}
}
func TestParseDateRange(t *testing.T) {
testcases := []struct {
name string
url string
wantStart time.Time
wantEnd time.Time
wantErr bool
}{
{
name: "regular key start & end input",
url: "http://localhost:8082/chart/?start=2024-06-10&end=2024-06-17",
wantStart: time.Date(2024, 06, 10, 0, 0, 0, 0, time.UTC),
wantEnd: time.Date(2024, 06, 17, 0, 0, 0, 0, time.UTC),
},
{
name: "regular key date input",
url: "http://localhost:8082/chart/?date=2024-06-11",
wantStart: time.Date(2024, 06, 11, 0, 0, 0, 0, time.UTC),
wantEnd: time.Date(2024, 06, 11, 0, 0, 0, 0, time.UTC),
},
{
name: "malformatted value for start",
url: "http://localhost:8082/chart/?start=2024-066-01&end=2024-06-17",
wantErr: true,
},
{
name: "malformatted value for start",
url: "http://localhost:8082/chart/?start=2024-06-10&end=2024-06-179",
wantErr: true,
},
{
name: "end is earlier than start",
url: "http://localhost:8082/chart/?start=2024-06-17&end=2024-06-10",
wantErr: true,
},
{
name: "have only start but missing end",
url: "http://localhost:8082/chart/?start=2024-06-01",
wantErr: true,
},
{
name: "key date and start used together",
url: "http://localhost:8082/chart/?start=2024-06-17&date=2024-06-19",
wantErr: true,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
url, err := url.Parse(tc.url)
if err != nil {
t.Fatalf("failed to parse url %q: %v", url, err)
}
gotStart, gotEnd, err := parseDateRange(url)
if tc.wantErr && err == nil {
t.Errorf("parseDateRange %v should return error but return nil", tc.url)
}
if !tc.wantErr && err != nil {
t.Errorf("parseDateRange %v should return nil but return error: %v", tc.url, err)
}
if !tc.wantErr {
if !gotStart.Equal(tc.wantStart) || !gotEnd.Equal(tc.wantEnd) {
t.Errorf("parseDateRange(%s) = (%s, %s), want (%s, %s)", tc.url, gotStart.Format(time.DateOnly), gotEnd.Format(time.DateOnly), tc.wantStart.Format(time.DateOnly), tc.wantEnd.Format(time.DateOnly))
}
}
})
}
}
|
worker
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/worker/README.md
|
# worker
## Endpoints
### `/merge/?date=<YYYY-MM-DD>`
The merge endpoint reads the set of reports from the upload bucket prefixed with
the value of the data param and encodes each report as newline separated JSON in
a merged report. It returns the number of reports merged and the location of the
merged report.
### `/chart/?date=<YYYY-MM-DD>`
The chart endpoint reads the report from the merge bucket from the given date
and generates chart data for that report. It returns the number of reports used
in generated the report and the location of the chart data.
## Local Development
For local development, simply build and run. It serves on localhost:8082.
go run ./godev/cmd/worker
By default, the server will use the filesystem for storage object I/O. Use the
-gcs flag to use the Cloud Storage API.
go run ./godev/cmd/worker --gcs
Optionally, use the localstorage devtool the emulate the GCS server on your
machine.
./godev/devtools/localstorage.sh
STORAGE_EMULATOR_HOST=localhost:8081 go run ./godev/cmd/worker --gcs
### Environment Variables
| Name | Default | Description |
| ------------------------------ | --------------------- | --------------------------------------------------------- |
| GO_TELEMETRY_PROJECT_ID | go-telemetry | GCP project ID |
| GO_TELEMETRY_LOCAL_STORAGE | .localstorage | Directory for storage emulator I/O or file system storage |
| GO_TELEMETRY_UPLOAD_CONFIG | ../config/config.json | Location of the upload config used for report validation |
| GO_TELEMETRY_MAX_REQUEST_BYTES | 102400 | Maximum request body size the server allows |
| GO_TELEMETRY_ENV | local | Deployment environment (e.g. prod, dev, local, ... ) |
| GO_TELEMETRY_LOCATION_ID | | GCP location of the service (e.g, us-east1) |
| GO_TELEMETRY_SERVICE_ACCOUNT | | GCP service account used for queueing work tasks |
| GO_TELEMETRY_CLIENT_ID | | GCP OAuth client used in authentication for queue tasks |
| GO_TELEMETRY_WORKER_URL | http://localhost:8082 | |
## Testing
The worker servie has a suite of regression tests that can be run with:
go test golang.org/x/telemetry/...
## Deploying
Each time a CL is reviewed and submitted, the site is automatically deployed to
Cloud Run. If it passes its serving-readiness checks, it will be automatically
promoted to handle traffic.
If the automatic deployment is not working, or to check on the status of a
pending deployment, see the “worker” trigger in the
[Cloud Build history](https://console.cloud.google.com/cloud-build/builds?project=go-telemetry).
### Test Instance
To deploy a test instance of this service, push to a branch and manually trigger
the deploy job from the
[Cloud Build console](https://console.cloud.google.com/cloud-build/triggers?project=go-telemetry)
with the desired values for branch and service name.
|
worker
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/worker/cloudbuild.yaml
|
# Copyright 2023 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
steps:
# Build the container image
- name: "gcr.io/cloud-builders/docker"
args:
- "build"
- "-t"
- "gcr.io/$PROJECT_ID/worker:$COMMIT_SHA"
- "-f"
- "godev/cmd/worker/Dockerfile"
- "."
# Push the container image to Container Registry
- name: "gcr.io/cloud-builders/docker"
args:
- "push"
- "gcr.io/$PROJECT_ID/worker:$COMMIT_SHA"
- name: golang
args:
- "go"
- "run"
- "golang.org/x/website/cmd/locktrigger@latest"
- "--project=$PROJECT_ID"
- "--build=$BUILD_ID"
- "--repo=https://go.googlesource.com/telemetry"
# Deploy container image to Cloud Run
- name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
entrypoint: gcloud
args:
- "run"
- "deploy"
- "$_ENV-worker"
- "--image"
- "gcr.io/$PROJECT_ID/worker:$COMMIT_SHA"
- "--region"
- "us-central1"
- "--service-account"
- "$_RUN_SERVICE_ACCOUNT"
- "--set-env-vars"
- "GO_TELEMETRY_PROJECT_ID=$PROJECT_ID"
- "--set-env-vars"
- "GO_TELEMETRY_ENV=$_ENV"
- "--set-env-vars"
- "GO_TELEMETRY_IAP_SERVICE_ACCOUNT=$_IAP_SERVICE_ACCOUNT"
- "--set-env-vars"
- "GO_TELEMETRY_CLIENT_ID=$_CLIENT_ID"
- "--set-env-vars"
- "GO_TELEMETRY_LOCATION_ID=$_LOCATION_ID"
- "--set-env-vars"
- "GO_TELEMETRY_WORKER_URL=$_WORKER_URL"
images:
- "gcr.io/$PROJECT_ID/worker:$COMMIT_SHA"
|
worker
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/worker/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"log"
"net/http"
"net/url"
"os"
"sort"
"strings"
"time"
cloudtasks "cloud.google.com/go/cloudtasks/apiv2"
taskspb "cloud.google.com/go/cloudtasks/apiv2/cloudtaskspb"
"golang.org/x/exp/slog"
"golang.org/x/mod/semver"
"golang.org/x/telemetry/godev/internal/config"
"golang.org/x/telemetry/godev/internal/content"
ilog "golang.org/x/telemetry/godev/internal/log"
"golang.org/x/telemetry/godev/internal/middleware"
"golang.org/x/telemetry/godev/internal/storage"
tconfig "golang.org/x/telemetry/internal/config"
contentfs "golang.org/x/telemetry/internal/content"
"golang.org/x/telemetry/internal/telemetry"
"golang.org/x/telemetry/internal/unionfs"
)
func main() {
flag.Parse()
ctx := context.Background()
cfg := config.NewConfig()
if cfg.UseGCS {
slog.SetDefault(slog.New(ilog.NewGCPLogHandler()))
}
buckets, err := storage.NewAPI(ctx, cfg)
if err != nil {
log.Fatal(err)
}
ucfg, err := tconfig.ReadConfig(cfg.UploadConfig)
if err != nil {
log.Fatal(err)
}
fsys := fsys(cfg.DevMode)
cserv := content.Server(fsys)
mux := http.NewServeMux()
mux.Handle("/", cserv)
mux.Handle("/merge/", handleMerge(buckets))
mux.Handle("/chart/", handleChart(ucfg, buckets))
mux.Handle("/queue-tasks/", handleTasks(cfg))
mw := middleware.Chain(
middleware.Log(slog.Default()),
middleware.Timeout(cfg.RequestTimeout),
middleware.RequestSize(cfg.MaxRequestBytes),
middleware.Recover(),
)
fmt.Printf("server listening at http://localhost:%s\n", cfg.WorkerPort)
log.Fatal(http.ListenAndServe(":"+cfg.WorkerPort, mw(mux)))
}
// handleTasks will populate the task queue that processes report
// data. Cloud Scheduler will be instrumented to call this endpoint
// daily to merge reports and generate chart data. The merge tasks
// will merge the previous weeks reports and the chart tasks will do
// the same minus one day.
// TODO(golang/go#62575): adjust the date range to align with report
// upload cutoff.
func handleTasks(cfg *config.Config) content.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
now := time.Now().UTC()
for i := 7; i > 0; i-- {
date := now.AddDate(0, 0, -1*i).Format(time.DateOnly)
url := cfg.WorkerURL + "/merge/?date=" + date
if _, err := createHTTPTask(cfg, url); err != nil {
return err
}
}
for i := 8; i > 1; i-- {
date := now.AddDate(0, 0, -1*i).Format(time.DateOnly)
url := cfg.WorkerURL + "/chart/?date=" + date
if _, err := createHTTPTask(cfg, url); err != nil {
return err
}
}
return nil
}
}
// createHTTPTask constructs a task with a authorization token
// and HTTP target then adds it to a Queue.
func createHTTPTask(cfg *config.Config, url string) (*taskspb.Task, error) {
ctx := context.Background()
client, err := cloudtasks.NewClient(ctx)
if err != nil {
return nil, fmt.Errorf("cloudtasks.NewClient: %w", err)
}
defer client.Close()
queuePath := fmt.Sprintf("projects/%s/locations/%s/queues/%s", cfg.ProjectID, cfg.LocationID, cfg.QueueID)
req := &taskspb.CreateTaskRequest{
Parent: queuePath,
Task: &taskspb.Task{
MessageType: &taskspb.Task_HttpRequest{
HttpRequest: &taskspb.HttpRequest{
HttpMethod: taskspb.HttpMethod_POST,
Url: url,
AuthorizationHeader: &taskspb.HttpRequest_OidcToken{
OidcToken: &taskspb.OidcToken{
ServiceAccountEmail: cfg.IAPServiceAccount,
Audience: cfg.ClientID,
},
},
},
},
},
}
createdTask, err := client.CreateTask(ctx, req)
if err != nil {
return nil, fmt.Errorf("cloudtasks.CreateTask: %w", err)
}
return createdTask, nil
}
// TODO: monitor duration and processed data volume.
func handleMerge(s *storage.API) content.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
date := r.URL.Query().Get("date")
if _, err := time.Parse(time.DateOnly, date); err != nil {
return content.Error(err, http.StatusBadRequest)
}
it := s.Upload.Objects(ctx, date)
mergeWriter, err := s.Merge.Object(date + ".json").NewWriter(ctx)
if err != nil {
return err
}
defer mergeWriter.Close()
encoder := json.NewEncoder(mergeWriter)
var count int
for {
obj, err := it.Next()
if errors.Is(err, storage.ErrObjectIteratorDone) {
break
}
if err != nil {
return err
}
count++
reader, err := s.Upload.Object(obj).NewReader(ctx)
if err != nil {
return err
}
defer reader.Close()
var report telemetry.Report
if err := json.NewDecoder(reader).Decode(&report); err != nil {
return err
}
if err := encoder.Encode(report); err != nil {
return err
}
if err := reader.Close(); err != nil {
return err
}
}
if err := mergeWriter.Close(); err != nil {
return err
}
msg := fmt.Sprintf("merged %d reports into %s/%s", count, s.Merge.URI(), date)
return content.Text(w, msg, http.StatusOK)
}
}
func fileName(start, end time.Time) string {
if start.Equal(end) {
return end.Format(time.DateOnly) + ".json"
}
return start.Format(time.DateOnly) + "_" + end.Format(time.DateOnly) + ".json"
}
// parseDateRange returns the start and end date from the given url.
func parseDateRange(url *url.URL) (start, end time.Time, _ error) {
if dateString := url.Query().Get("date"); dateString != "" {
if url.Query().Get("start") != "" || url.Query().Get("end") != "" {
return time.Time{}, time.Time{}, content.Error(fmt.Errorf("start or end key should be empty when date key is being used"), http.StatusBadRequest)
}
date, err := time.Parse(time.DateOnly, dateString)
if err != nil {
return time.Time{}, time.Time{}, content.Error(err, http.StatusBadRequest)
}
return date, date, nil
}
var err error
startString := url.Query().Get("start")
start, err = time.Parse(time.DateOnly, startString)
if err != nil {
return time.Time{}, time.Time{}, content.Error(err, http.StatusBadRequest)
}
endString := url.Query().Get("end")
end, err = time.Parse(time.DateOnly, endString)
if err != nil {
return time.Time{}, time.Time{}, content.Error(err, http.StatusBadRequest)
}
if end.Before(start) {
return time.Time{}, time.Time{}, content.Error(fmt.Errorf("end date is earlier than start"), http.StatusBadRequest)
}
return start, end, nil
}
func readMergedReports(ctx context.Context, fileName string, s *storage.API) ([]telemetry.Report, error) {
in, err := s.Merge.Object(fileName).NewReader(ctx)
if errors.Is(err, storage.ErrObjectNotExist) {
return nil, content.Error(fmt.Errorf("merge file %s not found", fileName), http.StatusNotFound)
}
if err != nil {
return nil, err
}
defer in.Close()
var reports []telemetry.Report
scanner := bufio.NewScanner(in)
for scanner.Scan() {
var report telemetry.Report
if err := json.Unmarshal(scanner.Bytes(), &report); err != nil {
return nil, err
}
reports = append(reports, report)
}
return reports, nil
}
func handleChart(cfg *tconfig.Config, s *storage.API) content.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
start, end, err := parseDateRange(r.URL)
if err != nil {
return err
}
var reports []telemetry.Report
var xs []float64
for date := start; !date.After(end); date = date.AddDate(0, 0, 1) {
dailyReports, err := readMergedReports(ctx, date.Format(time.DateOnly)+".json", s)
if err != nil {
return err
}
for _, r := range dailyReports {
reports = append(reports, r)
xs = append(xs, r.X)
}
}
data := nest(reports)
charts := charts(cfg, start.Format(time.DateOnly), end.Format(time.DateOnly), data, xs)
obj := fileName(start, end)
out, err := s.Chart.Object(obj).NewWriter(ctx)
if err != nil {
return err
}
defer out.Close()
if err := json.NewEncoder(out).Encode(charts); err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
msg := fmt.Sprintf("processed %d reports from date %s to %s into %s", len(reports), start.Format(time.DateOnly), end.Format(time.DateOnly), s.Chart.URI()+"/"+obj)
return content.Text(w, msg, http.StatusOK)
}
}
type chartdata struct {
DateRange [2]string
Programs []*program
NumReports int
}
type program struct {
ID string
Name string
Charts []*chart
}
type chart struct {
ID string
Name string
Type string
Data []*datum
}
func (c *chart) String() string {
bytes, _ := json.Marshal(c)
return string(bytes)
}
type datum struct {
Week string
Key string
Value float64
}
func charts(cfg *tconfig.Config, start, end string, d data, xs []float64) *chartdata {
result := &chartdata{DateRange: [2]string{start, end}, NumReports: len(xs)}
for _, p := range cfg.Programs {
prog := &program{ID: "charts:" + p.Name, Name: p.Name}
result.Programs = append(result.Programs, prog)
var charts []*chart
if !telemetry.IsToolchainProgram(p.Name) {
charts = append(charts, d.partition(p.Name, "Version", p.Versions))
}
charts = append(charts,
d.partition(p.Name, "GOOS", cfg.GOOS),
d.partition(p.Name, "GOARCH", cfg.GOARCH),
d.partition(p.Name, "GoVersion", cfg.GoVersion))
for _, c := range p.Counters {
// TODO: add support for histogram counters by getting the counter type
// from the chart config.
charts = append(charts, d.partition(p.Name, c.Name, tconfig.Expand(c.Name)))
}
for _, p := range charts {
if p != nil {
prog.Charts = append(prog.Charts, p)
}
}
}
return result
}
// partition builds a chart for the program and the counter. It can return nil
// if there is no data for the counter in dat.
func (d data) partition(program, counterPrefix string, counters []string) *chart {
count := &chart{
ID: "charts:" + program + ":" + counterPrefix,
Name: counterPrefix,
Type: "partition",
}
pk := programName(program)
prefix, _ := splitCounterName(counterPrefix)
gk := graphName(prefix)
var (
counts = make(map[string]float64) // bucket name -> total count
end weekName // latest week observed
)
for wk := range d {
if wk >= end {
end = wk
}
// TODO: when should this be number of reports?
// total := len(xs)
if total := len(d[wk][pk][gk][counterName(gk)]); total == 0 {
continue
}
// We group versions into major minor buckets, we must skip
// major minor versions we've already added to the dataset.
seen := make(map[string]bool)
for _, b := range counters {
// TODO(hyangah): let caller normalize names in counters.
counter := normalizeCounterName(counterPrefix, b)
if seen[counter] {
continue
}
seen[counter] = true
ck := counterName(counter)
// number of reports where count prefix:bucket > 0
n := len(d[wk][pk][gk][ck])
_, bucket := splitCounterName(counter)
counts[bucket] += float64(n)
}
}
if len(counts) == 0 {
return nil
}
// datum.Week always points to the end date
for k, v := range counts {
d := &datum{
Week: string(end),
Key: k,
Value: v,
}
count.Data = append(count.Data, d)
}
// Sort the data based on bucket name to ensure deterministic output.
sort.Slice(count.Data, func(i, j int) bool {
return count.Data[i].Key < count.Data[j].Key
})
return count
}
// weekName is the date of the report week in the format "YYYY-MM-DD".
type weekName string
// programName is the package path of the program, as used in
// telemetry.ProgramReport and chartconfig.Program.
// e.g. golang.org/x/tools/gopls, cmd/go.
type programName string
// graphName is the graph name.
// A graph plots distribution or timeseries of related counters.
type graphName string
// counterName is the counter name.
type counterName string
// reportID is the upload report ID.
// The current implementation uses telemetry.Report.X,
// a random number, computed by the uploader when creating a Report object.
// See x/telemetry/internal/upload.(*uploader).createReport.
type reportID float64
type data map[weekName]map[programName]map[graphName]map[counterName]map[reportID]int64
// Names of special counters.
// Unlike other counters, these are constructed from the metadata in the report.
const (
versionCounter = "Version"
goosCounter = "GOOS"
goarchCounter = "GOARCH"
goversionCounter = "GoVersion"
)
// nest groups the report data by week, program, prefix, counter, and x value
// summing together counter values for each program report in a report.
func nest(reports []telemetry.Report) data {
result := make(data)
for _, r := range reports {
for _, p := range r.Programs {
result.writeCount(r.Week, p.Program, versionCounter, p.Version, r.X, 1)
result.writeCount(r.Week, p.Program, goosCounter, p.GOOS, r.X, 1)
result.writeCount(r.Week, p.Program, goarchCounter, p.GOARCH, r.X, 1)
result.writeCount(r.Week, p.Program, goversionCounter, p.GoVersion, r.X, 1)
for c, value := range p.Counters {
prefix, _ := splitCounterName(c)
result.writeCount(r.Week, p.Program, prefix, c, r.X, value)
}
}
}
return result
}
// readCount reads the count value based on the input keys.
// Return error if any key does not exist.
func (d data) readCount(week, program, prefix, counter string, x float64) (int64, error) {
wk := weekName(week)
if _, ok := d[wk]; !ok {
return -1, fmt.Errorf("missing weekKey %q", week)
}
pk := programName(program)
if _, ok := d[wk][pk]; !ok {
return -1, fmt.Errorf("missing programKey %q", program)
}
gk := graphName(prefix)
if _, ok := d[wk][pk][gk]; !ok {
return -1, fmt.Errorf("missing graphKey key %q", prefix)
}
ck := counterName(counter)
if _, ok := d[wk][pk][gk][ck]; !ok {
return -1, fmt.Errorf("missing counterKey %v", counter)
}
return d[wk][pk][gk][ck][reportID(x)], nil
}
// writeCount writes the counter values to the result. When a report contains
// multiple program reports for the same program, the value of the counters
// in that report are summed together.
func (d data) writeCount(week, program, prefix, counter string, x float64, value int64) {
wk := weekName(week)
if _, ok := d[wk]; !ok {
d[wk] = make(map[programName]map[graphName]map[counterName]map[reportID]int64)
}
pk := programName(program)
if _, ok := d[wk][pk]; !ok {
d[wk][pk] = make(map[graphName]map[counterName]map[reportID]int64)
}
// We want to group and plot bucket/histogram counters with the same prefix.
// Use the prefix as the graph name.
gk := graphName(prefix)
if _, ok := d[wk][pk][gk]; !ok {
d[wk][pk][gk] = make(map[counterName]map[reportID]int64)
}
// TODO(hyangah): let caller pass the normalized counter name.
counter = normalizeCounterName(prefix, counter)
ck := counterName(counter)
if _, ok := d[wk][pk][gk][ck]; !ok {
d[wk][pk][gk][ck] = make(map[reportID]int64)
}
// x is a random number sent with each upload report.
// Since there is no identifier for the uploader, we use x as the uploader ID
// to approximate the number of unique uploader.
id := reportID(x)
d[wk][pk][gk][ck][id] += value
// TODO: each uploader should send the report only once.
// Shouldn't we overwrite, instead of summing?
// If the counter is an instance of a bucket counter or histogram counter
// record the value with a special counter (prefix). For example, if
// there are gopls/client:vscode-go, gopls/vlient:vim-go, ...,
// we compute the total number of gopls/client:* by summing up all values
// with a special counter name "gopls/client".
// TODO(hyangah): why do we want to compute the fraction, instead of showing
// the absolute number of reports?
if prefix != counter {
ck = counterName(prefix)
if _, ok := d[wk][pk][gk][ck]; !ok {
d[wk][pk][gk][ck] = make(map[reportID]int64)
}
d[wk][pk][gk][ck][id] += value
}
}
// normalizeCounterName normalizes the counter name.
// More specifically, program version, goos, goarch, and goVersion
// are not a real counter, but information from the metadata in the report.
// This function constructs pseudo counter names to handle them
// like other normal counters in aggregation and chart drawing.
// To limit the cardinality of version and goVersion, this function
// uses only major and minor version numbers in the pseudo-counter names.
// If the counter is a normal counter name, it is returned as is.
func normalizeCounterName(prefix, counter string) string {
switch prefix {
case versionCounter:
if counter == "devel" {
return prefix + ":" + counter
}
if strings.HasPrefix(counter, "go") {
return prefix + ":" + goMajorMinor(counter)
}
return prefix + ":" + semver.MajorMinor(counter)
case goosCounter:
return prefix + ":" + counter
case goarchCounter:
return prefix + ":" + counter
case goversionCounter:
return prefix + ":" + goMajorMinor(counter)
}
return counter
}
// splitCounterName gets splits the prefix and bucket splitCounterName of a counter name
// or a bucket name. For an input with no bucket part prefix and bucket
// are the same.
func splitCounterName(name string) (prefix, bucket string) {
prefix, bucket, found := strings.Cut(name, ":")
if !found {
bucket = prefix
}
return prefix, bucket
}
// goMajorMinor gets the go<Maj>,<Min> version for a given go version.
// For example, go1.20.1 -> go1.20.
// TODO(hyangah): replace with go/version.Lang (available from go1.22)
// after our builders stop running go1.21.
func goMajorMinor(v string) string {
v = v[2:]
maj, x, ok := cutInt(v)
if !ok {
return ""
}
x = x[1:]
min, _, ok := cutInt(x)
if !ok {
return ""
}
return fmt.Sprintf("go%s.%s", maj, min)
}
// cutInt scans the leading decimal number at the start of x to an integer
// and returns that value and the rest of the string.
func cutInt(x string) (n, rest string, ok bool) {
i := 0
for i < len(x) && '0' <= x[i] && x[i] <= '9' {
i++
}
if i == 0 || x[0] == '0' && i != 1 {
return "", "", false
}
return x[:i], x[i:], true
}
func fsys(fromOS bool) fs.FS {
var f fs.FS = contentfs.FS
if fromOS {
f = os.DirFS("internal/content")
}
f, err := unionfs.Sub(f, "worker", "shared")
if err != nil {
log.Fatal(err)
}
return f
}
|
telemetrygodev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/telemetrygodev/Dockerfile
|
# Copyright 2023 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# This Dockerfile expects the build context to be the repo root.
# NOTE: don't put anything in /tmp here. It will work locally,
# but Cloud Run mounts something else to /tmp, so anything
# installed here will be shadowed.
FROM golang:1.22
LABEL maintainer="Go Telemetry Team <go-telemetry-team@google.com>"
#### Preliminaries
WORKDIR /
# Create some directories.
# The telemetrygodev binary and related files live here.
RUN mkdir /app
#### Building binaries
# Set the working directory outside $GOPATH to ensure module mode is enabled.
WORKDIR /telemetry
# Copy go.mods and go.sums into the container.
# If they don't change, which is the common case, then docker can
# cache these COPYs and the subsequent RUN.
COPY go.mod go.sum ./
WORKDIR /telemetry/godev
COPY go.mod go.sum ./
# Download the dependencies.
RUN go mod download
WORKDIR /telemetry
# Copy the repo from local machine into Docker client’s current working
# directory, so that we can use it to build the binary.
# See .dockerignore at the repo root for excluded files.
COPY . ./
WORKDIR /telemetry/godev
# Build the telemetrygodev binary and put it in /app.
RUN go build -mod=readonly -o /app/telemetrygodev ./cmd/telemetrygodev
WORKDIR /telemetry
COPY config/config.json /app/config.json
#### telemetrygodev init
WORKDIR /app
ENV GO_TELEMETRY_UPLOAD_CONFIG=/app/config.json
CMD ["./telemetrygodev", "--gcs"]
|
telemetrygodev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/telemetrygodev/main_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"context"
_ "embed"
"flag"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"golang.org/x/telemetry/godev/internal/config"
tconfig "golang.org/x/telemetry/internal/config"
"golang.org/x/telemetry/internal/telemetry"
"golang.org/x/telemetry/internal/testenv"
)
func TestMain(m *testing.M) {
if !canRunGoDevModuleTests() {
return
}
os.Exit(m.Run())
}
// First class ports, https://go.dev/wiki/PortingPolicy, excluding 386 and arm.
var onSupportedPlatform = map[string]bool{
"darwin/amd64": true,
"darwin/arm64": true,
"linux/amd64": true,
"linux/arm64": true,
"windows/amd64": true,
}
// canRunGoDevModuleTests returns whether the current test environment
// is suitable for golang.org/x/telemetry/godev module tests.
func canRunGoDevModuleTests() bool {
// Even though telemetry.go.dev runs on linux,
// we should be still able to debug and test telemetry.go.dev on
// contributors' machines locally.
if goosarch := runtime.GOOS + "/" + runtime.GOARCH; !onSupportedPlatform[goosarch] {
return false
}
// Must be able to run 'go'.
if err := testenv.HasGo(); err != nil {
return false
}
// Our tests must run from the repository source, not from module cache.
// Check golang.org/x/telemetry directory is accessible and has go.mod and config/config.json.
output, err := exec.Command("go", "list", "-f", "{{.Dir}}", "golang.org/x/telemetry").Output()
if err != nil {
return false
}
xTelemetryDir := string(bytes.TrimSpace(output))
if xTelemetryDir == "" {
return false
}
if _, err := os.Stat(filepath.Join(xTelemetryDir, "go.mod")); err != nil {
return false
}
// config/config.json is in the golang.org/x/telemetry/config module, so
// this doesn't hold from e.g. GOMODCACHE.
if _, err := os.Stat(filepath.Join(xTelemetryDir, "config", "config.json")); err != nil {
return false
}
return true
}
// If telemetry_url is configured, TestPaths may be used as a basic push test.
var telemetryURL = flag.String("telemetry_url", "", "url of the telemetry instance to test")
func TestPaths(t *testing.T) {
rootURL := *telemetryURL
if rootURL == "" {
ctx := context.Background()
cfg := config.NewConfig()
cfg.LocalStorage = t.TempDir()
// NewConfig assumes that the command is run from the repo root, but tests
// run from their test directory. We should fix this, but for now just
// fix up the config path.
// TODO(rfindley): fix this.
cfg.UploadConfig = filepath.Join("..", "..", "..", "config", "config.json")
handler := newHandler(ctx, cfg)
ts := httptest.NewServer(handler)
defer ts.Close()
rootURL = ts.URL
}
tests := []struct {
method string
path string
body string
code int
fragments []string
}{
{"GET", "/", "", 200, []string{"Go Telemetry"}},
{
"POST",
"/upload/2023-01-01/123.json",
`{"Week":"2023-01-01","LastWeek":"2022-12-25","X":0.123,"Programs":null,"Config":"v0.0.0-20230822160736-17171dbf1d76"}`,
200,
nil, // the body returned by /upload doesn't matter
},
}
for _, test := range tests {
t.Run(test.method+" "+test.path, func(t *testing.T) {
url := strings.TrimRight(rootURL, "/") + test.path
r := strings.NewReader(test.body)
req, err := http.NewRequest(test.method, url, r)
if err != nil {
t.Fatalf("NewRequest failed: %v", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != test.code {
t.Errorf("status code = %d, want %d", resp.StatusCode, test.code)
}
content, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("reading body: %v", err)
}
for _, fragment := range test.fragments {
if !bytes.Contains(content, []byte(fragment)) {
t.Errorf("missing fragment %q", fragment)
}
}
})
}
}
func TestValidate(t *testing.T) {
cfg, err := tconfig.ReadConfig("testdata/config.json")
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
report *telemetry.Report
wantErr bool
}{
{
name: "empty report",
report: &telemetry.Report{},
wantErr: true,
},
{
name: "valid report with no counters",
report: &telemetry.Report{
Week: "2023-06-15",
LastWeek: "",
X: 0.1,
Programs: []*telemetry.ProgramReport{},
Config: "v0.0.1-test",
},
wantErr: false,
},
{
name: "valid report with counters",
report: &telemetry.Report{
Week: "2023-06-15",
LastWeek: "",
X: 0.1,
Programs: []*telemetry.ProgramReport{
{
Program: "golang.org/x/tools/gopls",
Version: "v0.10.1",
GoVersion: "go1.20.1",
GOOS: "linux",
GOARCH: "arm64",
Counters: map[string]int64{
"editor:vim": 100,
},
},
},
Config: "v0.0.1-test",
},
},
{
name: "valid report with a stack counter",
report: &telemetry.Report{
Week: "2023-06-15",
LastWeek: "",
X: 1.0,
Programs: []*telemetry.ProgramReport{
{
Program: "golang.org/x/tools/gopls",
Version: "v0.10.1",
GoVersion: "go1.20.1",
GOOS: "linux",
GOARCH: "arm64",
Stacks: map[string]int64{
"gopls/bug\ngolang.org/x/tools/gopls/internal/bug.report:35\ngolang.org/x/tools/gopls/internal/bug.Errorf:2\ngolang.org/x/tools/gopls/internal/lsp.(*Server).SignatureHelp:1\nruntime.goexit:0": 1,
},
},
},
Config: "v0.0.1-test",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := validate(tt.report, cfg); (err != nil) != tt.wantErr {
t.Errorf("validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
|
telemetrygodev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/telemetrygodev/deploy-prod.yaml
|
# Copyright 2023 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
steps:
# Build the container image
- name: "gcr.io/cloud-builders/docker"
args:
- "build"
- "-t"
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
- "-f"
- "godev/cmd/telemetrygodev/Dockerfile"
- "."
# Push the container image to Container Registry
- name: "gcr.io/cloud-builders/docker"
args:
- "push"
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
# Acquire the deployment lock
- name: golang
args:
- "go"
- "run"
- "golang.org/x/website/cmd/locktrigger@latest"
- "--project=$PROJECT_ID"
- "--build=$BUILD_ID"
- "--repo=https://go.googlesource.com/telemetry"
# Deploy container image to dev Cloud Run service
- name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
entrypoint: gcloud
args:
- "run"
- "deploy"
- "dev-telemetry"
- "--image"
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
- "--region"
- "us-central1"
- "--service-account"
- "$_RUN_SERVICE_ACCOUNT"
- "--set-env-vars"
- "GO_TELEMETRY_PROJECT_ID=$PROJECT_ID,GO_TELEMETRY_ENV=dev"
# Run push tests
- name: "golang"
entrypoint: sh
dir: "godev"
args:
- "-c"
- "go test ./cmd/telemetrygodev -run=TestPaths -telemetry_url=https://dev-telemetry.go.dev"
# Deploy container image to prod Cloud Run service
- name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
entrypoint: gcloud
args:
- "run"
- "deploy"
- "prod-telemetry"
- "--image"
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
- "--region"
- "us-central1"
- "--service-account"
- "$_RUN_SERVICE_ACCOUNT"
- "--set-env-vars"
- "GO_TELEMETRY_PROJECT_ID=$PROJECT_ID,GO_TELEMETRY_ENV=prod"
images:
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
|
telemetrygodev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/telemetrygodev/README.md
|
# telemetrygodev
## Local Development
For local development, simply build and run. It serves on localhost:8080.
go run ./godev/cmd/telemetrygodev
By default, the server will use the filesystem for storage object I/O. Use the
-gcs flag to use the Cloud Storage API.
go run ./godev/cmd/worker --gcs
Optionally, use the localstorage devtool the emulate the GCS server on your machine.
./godev/devtools/localstorage.sh
STORAGE_EMULATOR_HOST=localhost:8081 go run ./godev/cmd/worker --gcs
### Environment Variables
| Name | Default | Description |
| ---------------------------------- | --------------------- | --------------------------------------------------------- |
| GO_TELEMETRY_PROJECT_ID | go-telemetry | GCP project ID |
| GO_TELEMETRY_LOCAL_STORAGE | .localstorage | Directory for storage emulator I/O or file system storage |
| GO_TELEMETRY_UPLOAD_CONFIG | ../config/config.json | Location of the upload config used for report validation |
| GO_TELEMETRY_MAX_REQUEST_BYTES | 102400 | Maximum request body size the server allows |
| GO_TELEMETRY_ENV | local | Deployment environment (e.g. prod, dev, local, ... ) |
## Testing
The telemetry.go.dev web site has a suite of regression tests that can be run
with:
go test golang.org/x/telemetry/...
## Deploying
Each time a CL is reviewed and submitted, the site is automatically deployed to
Cloud Run. If it passes its serving-readiness checks, it will be automatically
promoted to handle traffic.
If the automatic deployment is not working, or to check on the status of a
pending deployment, see the “telemetrygodev” trigger in the
[Cloud Build history](https://pantheon.corp.google.com/cloud-build/builds?project=go-telemetry).
### Test Instance
To deploy a test instance of this service, push to a branch and manually trigger
the deploy job from the
[Cloud Build console](https://pantheon.corp.google.com/cloud-build/triggers?project=go-telemetry)
with the desired values for branch and service name.
|
telemetrygodev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/telemetrygodev/cloudbuild.yaml
|
# Copyright 2023 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
steps:
# Build the container image
- name: "gcr.io/cloud-builders/docker"
args:
- "build"
- "-t"
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
- "-f"
- "godev/cmd/telemetrygodev/Dockerfile"
- "."
# Push the container image to Container Registry
- name: "gcr.io/cloud-builders/docker"
args:
- "push"
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
- name: golang
args:
- "go"
- "run"
- "golang.org/x/website/cmd/locktrigger@latest"
- "--project=$PROJECT_ID"
- "--build=$BUILD_ID"
- "--repo=https://go.googlesource.com/telemetry"
# Deploy container image to Cloud Run
- name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
entrypoint: gcloud
args:
- "run"
- "deploy"
- "$_ENV-telemetry"
- "--image"
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
- "--region"
- "us-central1"
- "--service-account"
- "$_RUN_SERVICE_ACCOUNT"
- "--set-env-vars"
- "GO_TELEMETRY_PROJECT_ID=$PROJECT_ID,GO_TELEMETRY_ENV=$_ENV"
images:
- "gcr.io/$PROJECT_ID/telemetrygodev:$COMMIT_SHA"
|
telemetrygodev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/telemetrygodev/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Telemetrygodev serves the telemetry.go.dev website.
package main
import (
"context"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"net/http"
"os"
"strings"
"time"
"golang.org/x/exp/slog"
"golang.org/x/mod/semver"
"golang.org/x/telemetry/godev/internal/config"
"golang.org/x/telemetry/godev/internal/content"
ilog "golang.org/x/telemetry/godev/internal/log"
"golang.org/x/telemetry/godev/internal/middleware"
"golang.org/x/telemetry/godev/internal/storage"
"golang.org/x/telemetry/internal/chartconfig"
tconfig "golang.org/x/telemetry/internal/config"
contentfs "golang.org/x/telemetry/internal/content"
"golang.org/x/telemetry/internal/telemetry"
"golang.org/x/telemetry/internal/unionfs"
)
func main() {
flag.Parse()
ctx := context.Background()
cfg := config.NewConfig()
if cfg.UseGCS {
// We are likely running on GCP. Use GCP logging JSON format.
slog.SetDefault(slog.New(ilog.NewGCPLogHandler()))
}
handler := newHandler(ctx, cfg)
fmt.Printf("server listening at http://:%s\n", cfg.ServerPort)
log.Fatal(http.ListenAndServe(":"+cfg.ServerPort, handler))
}
// renderer implements shared template rendering for handlers below.
type renderer func(w http.ResponseWriter, tmpl string, page any) error
func newHandler(ctx context.Context, cfg *config.Config) http.Handler {
buckets, err := storage.NewAPI(ctx, cfg)
if err != nil {
log.Fatal(err)
}
ucfg, err := tconfig.ReadConfig(cfg.UploadConfig)
if err != nil {
log.Fatal(err)
}
fsys := fsys(cfg.DevMode)
mux := http.NewServeMux()
render := func(w http.ResponseWriter, tmpl string, page any) error {
return content.Template(w, fsys, tmpl, chartFuncs(), page, http.StatusOK)
}
logger := slog.Default()
// TODO(rfindley): use Go 1.22 routing once 1.23 is released and we can bump
// the go directive to 1.22.
mux.Handle("/", handleRoot(render, fsys, buckets.Chart, logger))
mux.Handle("/config", handleConfig(fsys, ucfg))
// TODO(rfindley): restrict this routing to POST
mux.Handle("/upload/", handleUpload(ucfg, buckets.Upload, logger))
mux.Handle("/charts/", handleCharts(render, buckets.Chart))
mux.Handle("/data/", handleData(render, buckets.Merge))
mw := middleware.Chain(
middleware.Log(logger),
middleware.Timeout(cfg.RequestTimeout),
middleware.RequestSize(cfg.MaxRequestBytes),
middleware.Recover(),
)
return mw(mux)
}
func chartFuncs() template.FuncMap {
return template.FuncMap{
"chartName": func(name string) string {
name, _, _ = strings.Cut(name, ":")
return name
},
"programName": func(name string) string {
name = strings.TrimPrefix(name, "golang.org/")
name = strings.TrimPrefix(name, "github.com/")
return name
},
}
}
// breadcrumb holds a breadcrumb nav element.
//
// If Link is empty, breadcrumbs are rendered as plain text.
type breadcrumb struct {
Link, Label string
}
type indexPage struct {
ChartDate string
Charts map[string]any
ChartError string // if set, the error
}
func (indexPage) Breadcrumbs() []breadcrumb {
return []breadcrumb{{Link: "/", Label: "Go Telemetry"}, {Label: "Home"}}
}
func handleRoot(render renderer, fsys fs.FS, chartBucket storage.BucketHandle, log *slog.Logger) content.HandlerFunc {
// TODO(rfindley): handle static serving with a different route.
cserv := content.Server(fsys)
return func(w http.ResponseWriter, r *http.Request) error {
if r.URL.Path != "/" {
cserv.ServeHTTP(w, r)
return nil
}
page := indexPage{}
ctx := r.Context()
it := chartBucket.Objects(ctx, "")
for {
obj, err := it.Next()
if errors.Is(err, storage.ErrObjectIteratorDone) {
break
} else if err != nil {
return err
}
date := strings.TrimSuffix(obj, ".json")
if date == obj {
// We have discussed eventually have nested subdirectories in the
// charts bucket. Defensively check for json files.
continue // not a chart object
}
page.ChartDate = date
}
if page.ChartDate == "" {
page.ChartError = "No data."
} else {
charts, err := loadCharts(ctx, page.ChartDate, chartBucket)
if err != nil {
log.ErrorContext(ctx, fmt.Sprintf("error loading index charts: %v", err))
page.ChartError = "Error loading charts."
} else {
page.Charts = charts
}
}
return render(w, "index.html", page)
}
}
type chartsPage []string
func (chartsPage) Breadcrumbs() []breadcrumb {
return []breadcrumb{{Link: "/", Label: "Go Telemetry"}, {Label: "Charts"}}
}
func handleCharts(render renderer, chartBucket storage.BucketHandle) content.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
if p := strings.TrimPrefix(r.URL.Path, "/charts/"); p != "" {
return handleChart(ctx, w, p, render, chartBucket)
}
it := chartBucket.Objects(ctx, "")
var page chartsPage
for {
obj, err := it.Next()
if errors.Is(err, storage.ErrObjectIteratorDone) {
break
} else if err != nil {
return err
}
date := strings.TrimSuffix(obj, ".json")
if date == obj {
continue // not a chart object
}
page = append(page, date)
}
return render(w, "allcharts.html", page)
}
}
type chartPage struct {
Date string
Charts map[string]any
}
func (p chartPage) Breadcrumbs() []breadcrumb {
return []breadcrumb{
{Link: "/", Label: "Go Telemetry"},
{Link: "/charts/", Label: "Charts"},
{Label: p.Date},
}
}
func handleChart(ctx context.Context, w http.ResponseWriter, date string, render renderer, chartBucket storage.BucketHandle) error {
// TODO(rfindley): refactor to return a content.HandlerFunc once we can use Go 1.22 routing.
page := chartPage{Date: date}
var err error
page.Charts, err = loadCharts(ctx, date, chartBucket)
if errors.Is(err, storage.ErrObjectNotExist) {
return content.Status(w, http.StatusNotFound)
} else if err != nil {
return err
}
return render(w, "charts.html", page)
}
type dataPage struct {
BucketURL string
Dates []string
}
func (dataPage) Breadcrumbs() []breadcrumb {
return []breadcrumb{{Link: "/", Label: "Go Telemetry"}, {Label: "Data"}}
}
func handleData(render renderer, mergeBucket storage.BucketHandle) content.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
it := mergeBucket.Objects(r.Context(), "")
var page dataPage
page.BucketURL = mergeBucket.URI()
for {
obj, err := it.Next()
if errors.Is(err, storage.ErrObjectIteratorDone) {
break
} else if err != nil {
return err
}
date := strings.TrimSuffix(obj, ".json")
if date == obj {
continue // not a data object
}
page.Dates = append(page.Dates, date)
}
return render(w, "data.html", page)
}
}
func loadCharts(ctx context.Context, date string, bucket storage.BucketHandle) (map[string]any, error) {
reader, err := bucket.Object(date + ".json").NewReader(ctx)
if err != nil {
return nil, err
}
defer reader.Close()
data, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
var charts map[string]any
if err := json.Unmarshal(data, &charts); err != nil {
return nil, err
}
return charts, nil
}
func handleUpload(ucfg *tconfig.Config, uploadBucket storage.BucketHandle, log *slog.Logger) content.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
if r.Method == "POST" {
ctx := r.Context()
// Log the error, but only the first 80 characters.
// This prevents excessive logging related to broken payloads.
// The first line should give us a sense of the failure mode.
warn := func(msg string, err error) {
errs := []rune(err.Error())
if len(errs) > 80 {
errs = append(errs[:79], '…')
}
log.WarnContext(ctx, msg+": "+string(errs))
}
var report telemetry.Report
if err := json.NewDecoder(r.Body).Decode(&report); err != nil {
warn("invalid JSON payload", err)
return content.Error(err, http.StatusBadRequest)
}
if err := validate(&report, ucfg); err != nil {
warn("invalid report", err)
return content.Error(err, http.StatusBadRequest)
}
// TODO: capture metrics for collisions.
name := fmt.Sprintf("%s/%g.json", report.Week, report.X)
f, err := uploadBucket.Object(name).NewWriter(ctx)
if err != nil {
return err
}
defer f.Close()
if err := json.NewEncoder(f).Encode(report); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
return content.Status(w, http.StatusOK)
}
return content.Status(w, http.StatusMethodNotAllowed)
}
}
// validate validates the telemetry report data against the latest config.
func validate(r *telemetry.Report, cfg *tconfig.Config) error {
// TODO: reject/drop data arrived too early or too late.
if _, err := time.Parse(time.DateOnly, r.Week); err != nil {
return fmt.Errorf("invalid week %s", r.Week)
}
if !semver.IsValid(r.Config) {
return fmt.Errorf("invalid config %s", r.Config)
}
if r.X == 0 {
return fmt.Errorf("invalid X %g", r.X)
}
// TODO: We can probably keep known programs and counters even when a report
// includes something that has been removed from the latest config.
for _, p := range r.Programs {
if !cfg.HasGOARCH(p.GOARCH) ||
!cfg.HasGOOS(p.GOOS) ||
!cfg.HasGoVersion(p.GoVersion) ||
!cfg.HasProgram(p.Program) ||
!cfg.HasVersion(p.Program, p.Version) {
return fmt.Errorf("unknown program build %s@%q %q %s/%s", p.Program, p.Version, p.GoVersion, p.GOOS, p.GOARCH)
}
for c := range p.Counters {
if !cfg.HasCounter(p.Program, c) {
return fmt.Errorf("unknown counter %s", c)
}
}
for s := range p.Stacks {
prefix, _, _ := strings.Cut(s, "\n")
if !cfg.HasStack(p.Program, prefix) {
return fmt.Errorf("unknown stack %s", s)
}
}
}
return nil
}
func fsys(fromOS bool) fs.FS {
var f fs.FS = contentfs.FS
if fromOS {
f = os.DirFS("internal/content")
contentfs.RunESBuild(true)
}
f, err := unionfs.Sub(f, "telemetrygodev", "shared")
if err != nil {
log.Fatal(err)
}
return f
}
type configPage struct {
Version string
ChartConfig string
UploadConfig string
}
func (configPage) Breadcrumbs() []breadcrumb {
return []breadcrumb{{Link: "/", Label: "Go Telemetry"}, {Label: "Upload Configuration"}}
}
func handleConfig(fsys fs.FS, ucfg *tconfig.Config) content.HandlerFunc {
ccfg := chartconfig.Raw()
cfg := ucfg.UploadConfig
version := "default"
return func(w http.ResponseWriter, r *http.Request) error {
cfgJSON, err := json.MarshalIndent(cfg, "", "\t")
if err != nil {
cfgJSON = []byte("unknown")
}
page := configPage{
Version: version,
ChartConfig: string(ccfg),
UploadConfig: string(cfgJSON),
}
return content.Template(w, fsys, "config.html", chartFuncs(), page, http.StatusOK)
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/telemetry/godev/cmd/telemetrygodev/testdata/config.json
|
{
"Version": "v0.0.1-test",
"GOOS": [
"linux",
"darwin"
],
"GOARCH": [
"amd64",
"arm64"
],
"GoVersion": [
"go1.20",
"go1.20.1"
],
"Programs": [
{
"Name": "golang.org/x/tools/gopls",
"Versions": [
"v0.10.1",
"v0.11.0"
],
"Counters": [
{
"Name": "editor:{emacs,vim,vscode,other}",
"Rate": 0.01
}
],
"Stacks": [
{
"Name": "gopls/bug",
"Rate": 1,
"Depth": 16
}
]
},
{
"Name": "cmd/go",
"Versions": [
"v0.10.1",
"v0.11.0"
],
"Counters": [
{
"Name": "go/buildcache/miss:{0,0.1,0.2,0.5,1,10,100,2,20,5,50}",
"Rate": 0.01
}
]
}
]
}
|
review
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/CONTRIBUTING.md
|
# Contributing to Go
Go is an open source project.
It is the work of hundreds of contributors. We appreciate your help!
## Filing issues
When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions:
1. What version of Go are you using (`go version`)?
2. What operating system and processor architecture are you using?
3. What did you do?
4. What did you expect to see?
5. What did you see instead?
General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker.
The gophers there will answer or ask you to file an issue if you've tripped over a bug.
## Contributing code
Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html)
before sending patches.
Unless otherwise noted, the Go source files are distributed under
the BSD-style license found in the LICENSE file.
|
review
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/PATENTS
|
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
|
review
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/go.mod
|
module golang.org/x/review
go 1.18
|
review
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/README.md
|
# git-codereview
The git-codereview tool is a command-line tool for working with Gerrit.
## Download/Install
The easiest way to install is to run `go install golang.org/x/review/git-codereview@latest`. You can
also manually git clone the repository to `$GOPATH/src/golang.org/x/review`.
Run `git codereview hooks` to install Gerrit hooks for your git repository.
## Report Issues / Send Patches
This repository uses Gerrit for code changes. To learn how to submit changes to
this repository, see https://golang.org/doc/contribute.html.
The main issue tracker for the review repository is located at
https://github.com/golang/go/issues. Prefix your issue with "x/review:" in the
subject line, so it is easy to find.
|
review
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/LICENSE
|
Copyright 2014 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
review
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/codereview.cfg
|
issuerepo: golang/go
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/config.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
)
var (
configPath string
cachedConfig map[string]string
)
// Config returns the code review config.
// Configs consist of lines of the form "key: value".
// Lines beginning with # are comments.
// If there is no config, it returns an empty map.
// If the config is malformed, it dies.
func config() map[string]string {
if cachedConfig != nil {
return cachedConfig
}
configPath = filepath.Join(repoRoot(), "codereview.cfg")
b, err := os.ReadFile(configPath)
raw := string(b)
if err != nil {
verbosef("%sfailed to load config from %q: %v", raw, configPath, err)
cachedConfig = make(map[string]string)
return cachedConfig
}
cachedConfig, err = parseConfig(raw)
if err != nil {
dief("%v", err)
}
return cachedConfig
}
// haveGerrit returns true if gerrit should be used.
// To enable gerrit, codereview.cfg must be present with "gerrit" property set to
// the gerrit https URL or the git origin must be to
// "https://<project>.googlesource.com/<repo>".
func haveGerrit() bool {
gerrit := config()["gerrit"]
origin := trim(cmdOutput("git", "config", "remote.origin.url"))
return haveGerritInternal(gerrit, origin)
}
// haveGerritInternal is the same as haveGerrit but factored out
// for testing.
func haveGerritInternal(gerrit, origin string) bool {
if gerrit == "off" {
return false
}
if gerrit != "" {
return true
}
u, err := url.Parse(origin)
if err != nil {
return false
}
if u.Scheme == "sso" || u.Scheme == "rpc" {
return true
}
if u.Scheme != "https" {
return false
}
return strings.HasSuffix(u.Host, ".googlesource.com")
}
func haveGitHub() bool {
origin := trim(cmdOutput("git", "config", "remote.origin.url"))
return strings.Contains(origin, "github.com")
}
func parseConfig(raw string) (map[string]string, error) {
cfg := make(map[string]string)
for _, line := range nonBlankLines(raw) {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") {
// comment line
continue
}
fields := strings.SplitN(line, ":", 2)
if len(fields) != 2 {
return nil, fmt.Errorf("bad config line, expected 'key: value': %q", line)
}
cfg[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1])
}
return cfg, nil
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/gofmt_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"os"
"strings"
"testing"
)
const (
goodGo = "package good\n"
badGo = " package bad1 "
badGoFixed = "package bad1\n"
bad2Go = " package bad2 "
bad2GoFixed = "package bad2\n"
brokenGo = "package B R O K E N"
)
func TestGofmt(t *testing.T) {
// Test of basic operations.
gt := newGitTest(t)
defer gt.done()
gt.work(t)
if err := os.MkdirAll(gt.client+"/test/bench", 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(gt.client+"/vendor", 0755); err != nil {
t.Fatal(err)
}
write(t, gt.client+"/bad.go", badGo, 0644)
write(t, gt.client+"/good.go", goodGo, 0644)
write(t, gt.client+"/vendor/bad.go", badGo, 0644)
write(t, gt.client+"/test/bad.go", badGo, 0644)
write(t, gt.client+"/test/good.go", goodGo, 0644)
write(t, gt.client+"/test/bench/bad.go", badGo, 0644)
write(t, gt.client+"/test/bench/good.go", goodGo, 0644)
trun(t, gt.client, "git", "add", ".") // make files tracked
testMain(t, "gofmt", "-l")
testPrintedStdout(t, "bad.go\n", "!good.go", fromSlash("!test/bad"), fromSlash("test/bench/bad.go"), fromSlash("!vendor/bad.go"))
testMain(t, "gofmt", "-l")
testPrintedStdout(t, "bad.go\n", "!good.go", fromSlash("!test/bad"), fromSlash("test/bench/bad.go"), fromSlash("!vendor/bad.go"))
testMain(t, "gofmt")
testNoStdout(t)
testMain(t, "gofmt", "-l")
testNoStdout(t)
write(t, gt.client+"/bad.go", badGo, 0644)
write(t, gt.client+"/broken.go", brokenGo, 0644)
trun(t, gt.client, "git", "add", ".")
testMainDied(t, "gofmt", "-l")
testPrintedStdout(t, "bad.go")
testPrintedStderr(t, "gofmt reported errors", "broken.go")
}
func TestGofmtSubdir(t *testing.T) {
// Check that gofmt prints relative paths for files in or below the current directory.
gt := newGitTest(t)
defer gt.done()
gt.work(t)
mkdir(t, gt.client+"/dir1")
mkdir(t, gt.client+"/longnamedir2")
write(t, gt.client+"/dir1/bad1.go", badGo, 0644)
write(t, gt.client+"/longnamedir2/bad2.go", badGo, 0644)
trun(t, gt.client, "git", "add", ".") // make files tracked
chdir(t, gt.client)
testMain(t, "gofmt", "-l")
testPrintedStdout(t, fromSlash("dir1/bad1.go"), fromSlash("longnamedir2/bad2.go"))
chdir(t, gt.client+"/dir1")
testMain(t, "gofmt", "-l")
testPrintedStdout(t, "bad1.go", fromSlash("!/bad1.go"), fromSlash("longnamedir2/bad2.go"))
chdir(t, gt.client+"/longnamedir2")
testMain(t, "gofmt", "-l")
testPrintedStdout(t, "bad2.go", fromSlash("!/bad2.go"), fromSlash("dir1/bad1.go"))
mkdir(t, gt.client+"/z")
chdir(t, gt.client+"/z")
testMain(t, "gofmt", "-l")
testPrintedStdout(t, fromSlash("longnamedir2/bad2.go"), fromSlash("dir1/bad1.go"))
}
func TestGofmtSubdirIndexCheckout(t *testing.T) {
// Like TestGofmtSubdir but bad Go files are only in index, not working copy.
// Check also that prints a correct path (relative or absolute) for files outside the
// current directory, even when running with Git before 2.3.0 which doesn't
// handle those right in git checkout-index --temp.
gt := newGitTest(t)
defer gt.done()
gt.work(t)
mkdir(t, gt.client+"/dir1")
mkdir(t, gt.client+"/longnamedir2")
write(t, gt.client+"/dir1/bad1.go", badGo, 0644)
write(t, gt.client+"/longnamedir2/bad2.go", badGo, 0644)
trun(t, gt.client, "git", "add", ".") // put files in index
write(t, gt.client+"/dir1/bad1.go", goodGo, 0644)
write(t, gt.client+"/longnamedir2/bad2.go", goodGo, 0644)
chdir(t, gt.client)
testMain(t, "gofmt", "-l")
testPrintedStdout(t, fromSlash("dir1/bad1.go (staged)"), fromSlash("longnamedir2/bad2.go (staged)"))
chdir(t, gt.client+"/dir1")
testMain(t, "gofmt", "-l")
testPrintedStdout(t, "bad1.go (staged)", fromSlash("!/bad1.go"), fromSlash("longnamedir2/bad2.go (staged)"))
chdir(t, gt.client+"/longnamedir2")
testMain(t, "gofmt", "-l")
testPrintedStdout(t, "bad2.go (staged)", fromSlash("!/bad2.go"), fromSlash("dir1/bad1.go (staged)"))
mkdir(t, gt.client+"/z")
chdir(t, gt.client+"/z")
testMain(t, "gofmt", "-l")
testPrintedStdout(t, fromSlash("longnamedir2/bad2.go (staged)"), fromSlash("dir1/bad1.go (staged)"))
}
func TestGofmtUnstaged(t *testing.T) {
// Test when unstaged files are different from staged ones.
// See TestHookPreCommitUnstaged for an explanation.
// In this test we use two different kinds of bad files, so that
// we can test having a bad file in the index and a different
// bad file in the working directory.
gt := newGitTest(t)
defer gt.done()
gt.work(t)
name := []string{"good", "bad", "bad2", "broken"}
orig := []string{goodGo, badGo, bad2Go, brokenGo}
fixed := []string{goodGo, badGoFixed, bad2GoFixed, brokenGo}
const N = 4
var allFiles, wantOut, wantErr []string
writeFiles := func(n int) {
allFiles = nil
wantOut = nil
wantErr = nil
for i := 0; i < N*N*N; i++ {
// determine n'th digit of 3-digit base-N value i
j := i
for k := 0; k < (3 - 1 - n); k++ {
j /= N
}
text := orig[j%N]
file := fmt.Sprintf("%s-%s-%s.go", name[i/N/N], name[(i/N)%N], name[i%N])
allFiles = append(allFiles, file)
write(t, gt.client+"/"+file, text, 0644)
if (i/N)%N != i%N {
staged := file + " (staged)"
switch {
case strings.Contains(file, "-bad-"), strings.Contains(file, "-bad2-"):
wantOut = append(wantOut, staged)
wantErr = append(wantErr, "!"+staged)
case strings.Contains(file, "-broken-"):
wantOut = append(wantOut, "!"+staged)
wantErr = append(wantErr, staged)
default:
wantOut = append(wantOut, "!"+staged)
wantErr = append(wantErr, "!"+staged)
}
}
switch {
case strings.Contains(file, "-bad.go"), strings.Contains(file, "-bad2.go"):
if (i/N)%N != i%N {
file += " (unstaged)"
}
wantOut = append(wantOut, file+"\n")
wantErr = append(wantErr, "!"+file+":", "!"+file+" (unstaged)")
case strings.Contains(file, "-broken.go"):
wantOut = append(wantOut, "!"+file+"\n", "!"+file+" (unstaged)")
wantErr = append(wantErr, file+":")
default:
wantOut = append(wantOut, "!"+file+"\n", "!"+file+":", "!"+file+" (unstaged)")
wantErr = append(wantErr, "!"+file+"\n", "!"+file+":", "!"+file+" (unstaged)")
}
}
}
// committed files
writeFiles(0)
trun(t, gt.client, "git", "add", ".")
trun(t, gt.client, "git", "commit", "-m", "msg")
// staged files
writeFiles(1)
trun(t, gt.client, "git", "add", ".")
// unstaged files
writeFiles(2)
// Check that gofmt -l shows the right output and errors.
testMainDied(t, "gofmt", "-l")
testPrintedStdout(t, wantOut...)
testPrintedStderr(t, wantErr...)
// Again (last command should not have written anything).
testMainDied(t, "gofmt", "-l")
testPrintedStdout(t, wantOut...)
testPrintedStderr(t, wantErr...)
// Reformat in place.
testMainDied(t, "gofmt")
testNoStdout(t)
testPrintedStderr(t, wantErr...)
// Read files to make sure unstaged did not bleed into staged.
for i, file := range allFiles {
if data, err := os.ReadFile(gt.client + "/" + file); err != nil {
t.Errorf("%v", err)
} else if want := fixed[i%N]; string(data) != want {
t.Errorf("%s: working tree = %q, want %q", file, string(data), want)
}
if data, want := trun(t, gt.client, "git", "show", ":"+file), fixed[i/N%N]; data != want {
t.Errorf("%s: index = %q, want %q", file, data, want)
}
if data, want := trun(t, gt.client, "git", "show", "HEAD:"+file), orig[i/N/N]; data != want {
t.Errorf("%s: commit = %q, want %q", file, data, want)
}
}
// Check that gofmt -l still shows the errors.
testMainDied(t, "gofmt", "-l")
testNoStdout(t)
testPrintedStderr(t, wantErr...)
}
func TestGofmtAmbiguousRevision(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
t.Logf("creating file that conflicts with revision parameter")
write(t, gt.client+"/HEAD", "foo", 0644)
testMain(t, "gofmt")
}
func TestGofmtFastForwardMerge(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// merge dev.branch into main
write(t, gt.server+"/file", "more work", 0644)
trun(t, gt.server, "git", "commit", "-m", "work", "file")
trun(t, gt.server, "git", "merge", "-m", "merge", "dev.branch")
// add bad go file on main
write(t, gt.server+"/bad.go", "package {\n", 0644)
trun(t, gt.server, "git", "add", "bad.go")
trun(t, gt.server, "git", "commit", "-m", "bad go")
// update client
trun(t, gt.client, "git", "checkout", "main")
trun(t, gt.client, "git", "pull")
testMain(t, "change", "dev.branch")
trun(t, gt.client, "git", "pull")
// merge main into dev.branch, fast forward merge
trun(t, gt.client, "git", "merge", "--ff-only", "main")
// verify that now client is in a state where just the tag is changing; there's no new commit.
mainHash := strings.TrimSpace(trun(t, gt.server, "git", "rev-parse", "main"))
devHash := strings.TrimSpace(trun(t, gt.client, "git", "rev-parse", "HEAD"))
if mainHash != devHash {
t.Logf("branches:\n%s", trun(t, gt.client, "git", "branch", "-a", "-v"))
t.Logf("log:\n%s", trun(t, gt.client, "git", "log", "--graph", "--decorate"))
t.Fatalf("setup wrong - got different commit hashes on main and dev branch")
}
// check that gofmt finds nothing to do, ignoring the bad (but committed) file1.go.
testMain(t, "gofmt")
testNoStdout(t)
testNoStderr(t)
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/hook_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
func TestHookCommitMsgGerrit(t *testing.T) {
gt := newGitTest(t)
gt.enableGerrit(t)
defer gt.done()
// Check that hook adds Change-Id.
write(t, gt.client+"/msg.txt", "Test message.\n", 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/msg.txt")
data := read(t, gt.client+"/msg.txt")
if !bytes.Contains(data, []byte("\n\nChange-Id: ")) {
t.Fatalf("after hook-invoke commit-msg, missing Change-Id:\n%s", data)
}
// Check that hook is no-op when Change-Id is already present.
testMain(t, "hook-invoke", "commit-msg", gt.client+"/msg.txt")
data1 := read(t, gt.client+"/msg.txt")
if !bytes.Equal(data, data1) {
t.Fatalf("second hook-invoke commit-msg changed Change-Id:\nbefore:\n%s\n\nafter:\n%s", data, data1)
}
// Check that hook rejects multiple Change-Ids.
write(t, gt.client+"/msgdouble.txt", string(data)+string(data), 0644)
testMainDied(t, "hook-invoke", "commit-msg", gt.client+"/msgdouble.txt")
const multiple = "git-codereview: multiple Change-Id lines\n"
if got := testStderr.String(); got != multiple {
t.Fatalf("unexpected output:\ngot: %q\nwant: %q", got, multiple)
}
// Check that hook doesn't add two line feeds before Change-Id
// if the exsting message ends with a metadata line.
write(t, gt.client+"/msg.txt", "Test message.\n\nBug: 1234\n", 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/msg.txt")
data = read(t, gt.client+"/msg.txt")
if !bytes.Contains(data, []byte("Bug: 1234\nChange-Id: ")) {
t.Fatalf("after hook-invoke commit-msg, missing Change-Id: directly after Bug line\n%s", data)
}
}
func TestHookCommitMsg(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// Check that hook fails when message is empty.
write(t, gt.client+"/empty.txt", "\n\n# just a file with\n# comments\n", 0644)
testMainDied(t, "hook-invoke", "commit-msg", gt.client+"/empty.txt")
const empty = "git-codereview: empty commit message\n"
if got := testStderr.String(); got != empty {
t.Fatalf("unexpected output:\ngot: %q\nwant: %q", got, empty)
}
// Check that hook inserts a blank line after the first line as needed.
rewrites := []struct {
in string
want string
}{
{in: "all: gofmt", want: "all: gofmt"},
{in: "all: gofmt\n", want: "all: gofmt\n"},
{in: "all: gofmt\nahhh", want: "all: gofmt\n\nahhh"},
{in: "all: gofmt\n\nahhh", want: "all: gofmt\n\nahhh"},
{in: "all: gofmt\n\n\nahhh", want: "all: gofmt\n\n\nahhh"},
// Issue 16376
{
in: "all: gofmt\n# ------------------------ >8 ------------------------\ndiff",
want: "all: gofmt\n",
},
}
for _, tt := range rewrites {
write(t, gt.client+"/in.txt", tt.in, 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/in.txt")
write(t, gt.client+"/want.txt", tt.want, 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/want.txt")
got, err := os.ReadFile(gt.client + "/in.txt")
if err != nil {
t.Fatal(err)
}
want, err := os.ReadFile(gt.client + "/want.txt")
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatalf("failed to rewrite:\n%s\n\ngot:\n\n%s\n\nwant:\n\n%s\n", tt.in, got, want)
}
}
}
func TestHookCommitMsgIssueRepoRewrite(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
msgs := []string{
// If there's no config, don't rewrite issue references.
"math/big: catch all the rats\n\nFixes #99999, at least for now\n",
// Fix the fix-message, even without config
"math/big: catch all the rats\n\nFixes issue #99999, at least for now\n",
"math/big: catch all the rats\n\nFixes issue 99999, at least for now\n",
// Don't forget to write back if Change-Id already exists
}
for _, msg := range msgs {
write(t, gt.client+"/msg.txt", msg, 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/msg.txt")
got := read(t, gt.client+"/msg.txt")
const want = "math/big: catch all the rats\n\nFixes #99999, at least for now\n"
if string(got) != want {
t.Errorf("issue rewrite failed: got\n\n%s\nwant\n\n%s\nlen %d and %d", got, want, len(got), len(want))
}
}
// Add issuerepo config, clear any previous config.
write(t, gt.client+"/codereview.cfg", "issuerepo: golang/go", 0644)
cachedConfig = nil
// Check for the rewrite
msgs = []string{
"math/big: catch all the rats\n\nFixes #99999, at least for now\n",
"math/big: catch all the rats\n\nFixes issue #99999, at least for now\n",
"math/big: catch all the rats\n\nFixes issue 99999, at least for now\n",
"math/big: catch all the rats\n\nFixes issue golang/go#99999, at least for now\n",
}
for _, msg := range msgs {
write(t, gt.client+"/msg.txt", msg, 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/msg.txt")
got := read(t, gt.client+"/msg.txt")
const want = "math/big: catch all the rats\n\nFixes golang/go#99999, at least for now\n"
if string(got) != want {
t.Errorf("issue rewrite failed: got\n\n%s\nwant\n\n%s", got, want)
}
}
// Reset config state
cachedConfig = nil
}
func TestHookCommitMsgBranchPrefix(t *testing.T) {
testHookCommitMsgBranchPrefix(t, false)
testHookCommitMsgBranchPrefix(t, true)
}
func testHookCommitMsgBranchPrefix(t *testing.T, gerrit bool) {
t.Logf("gerrit=%v", gerrit)
gt := newGitTest(t)
if gerrit {
gt.enableGerrit(t)
}
defer gt.done()
checkPrefix := func(prefix string) {
write(t, gt.client+"/msg.txt", "Test message.\n", 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/msg.txt")
data, err := os.ReadFile(gt.client + "/msg.txt")
if err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(data, []byte(prefix)) {
t.Errorf("after hook-invoke commit-msg on %s, want prefix %q:\n%s", CurrentBranch().Name, prefix, data)
}
if i := strings.Index(prefix, "]"); i >= 0 {
prefix := prefix[:i+1]
for _, magic := range []string{"fixup!", "squash!"} {
write(t, gt.client+"/msg.txt", magic+" Test message.\n", 0644)
testMain(t, "hook-invoke", "commit-msg", gt.client+"/msg.txt")
data, err := os.ReadFile(gt.client + "/msg.txt")
if err != nil {
t.Fatal(err)
}
if bytes.HasPrefix(data, []byte(prefix)) {
t.Errorf("after hook-invoke commit-msg on %s with %s, found incorrect prefix %q:\n%s", CurrentBranch().Name, magic, prefix, data)
}
}
}
}
// Create server branch and switch to server branch on client.
// Test that commit hook adds prefix.
trun(t, gt.server, "git", "checkout", "-b", "dev.cc")
trun(t, gt.client, "git", "fetch", "-q")
testMain(t, "change", "dev.cc")
if gerrit {
checkPrefix("[dev.cc] Test message.\n")
} else {
checkPrefix("Test message.\n")
}
// Work branch with server branch as upstream.
testMain(t, "change", "ccwork")
if gerrit {
checkPrefix("[dev.cc] Test message.\n")
} else {
checkPrefix("Test message.\n")
}
// Master has no prefix.
testMain(t, "change", "main")
checkPrefix("Test message.\n")
// Work branch from main has no prefix.
testMain(t, "change", "work")
checkPrefix("Test message.\n")
}
func TestHookPreCommit(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// Write out a non-Go file.
testMain(t, "change", "mybranch")
write(t, gt.client+"/msg.txt", "A test message.", 0644)
trun(t, gt.client, "git", "add", "msg.txt")
testMain(t, "hook-invoke", "pre-commit") // should be no-op
if err := os.MkdirAll(gt.client+"/test/bench", 0755); err != nil {
t.Fatal(err)
}
write(t, gt.client+"/bad.go", badGo, 0644)
write(t, gt.client+"/good.go", goodGo, 0644)
write(t, gt.client+"/test/bad.go", badGo, 0644)
write(t, gt.client+"/test/good.go", goodGo, 0644)
write(t, gt.client+"/test/bench/bad.go", badGo, 0644)
write(t, gt.client+"/test/bench/good.go", goodGo, 0644)
trun(t, gt.client, "git", "add", ".")
testMainDied(t, "hook-invoke", "pre-commit")
testPrintedStderr(t, "gofmt needs to format these files (run 'git gofmt'):",
"bad.go", "!good.go", fromSlash("!test/bad"), fromSlash("test/bench/bad.go"))
write(t, gt.client+"/broken.go", brokenGo, 0644)
trun(t, gt.client, "git", "add", "broken.go")
testMainDied(t, "hook-invoke", "pre-commit")
testPrintedStderr(t, "gofmt needs to format these files (run 'git gofmt'):",
"bad.go", "!good.go", fromSlash("!test/bad"), fromSlash("test/bench/bad.go"),
"gofmt reported errors:", "broken.go")
}
func TestHookChangeGofmt(t *testing.T) {
// During git change, we run the gofmt check before invoking commit,
// so we should not see the line about 'git commit' failing.
// That is, the failure should come from git change, not from
// the commit hook.
gt := newGitTest(t)
defer gt.done()
gt.work(t)
// Write out a non-Go file.
write(t, gt.client+"/bad.go", badGo, 0644)
trun(t, gt.client, "git", "add", ".")
t.Logf("invoking commit hook explicitly")
testMainDied(t, "hook-invoke", "pre-commit")
testPrintedStderr(t, "gofmt needs to format these files (run 'git gofmt'):", "bad.go")
t.Logf("change without hook installed")
testCommitMsg = "foo: msg"
testMainDied(t, "change")
testPrintedStderr(t, "gofmt needs to format these files (run 'git gofmt'):", "bad.go", "!running: git")
t.Logf("change with hook installed")
restore := testInstallHook(t, gt)
defer restore()
testCommitMsg = "foo: msg"
testMainDied(t, "change")
testPrintedStderr(t, "gofmt needs to format these files (run 'git gofmt'):", "bad.go", "!running: git")
}
func TestHookPreCommitDetachedHead(t *testing.T) {
// If we're in detached head mode, something special is going on,
// like git rebase. We disable the gofmt-checking precommit hook,
// since we expect it would just get in the way at that point.
// (It also used to crash.)
gt := newGitTest(t)
defer gt.done()
gt.work(t)
write(t, gt.client+"/bad.go", badGo, 0644)
trun(t, gt.client, "git", "add", ".")
trun(t, gt.client, "git", "checkout", "HEAD^0")
testMainDied(t, "hook-invoke", "pre-commit")
testPrintedStderr(t, "gofmt needs to format these files (run 'git gofmt'):", "bad.go")
/*
OLD TEST, back when we disabled gofmt in detached head,
in case we go back to that:
// If we're in detached head mode, something special is going on,
// like git rebase. We disable the gofmt-checking precommit hook,
// since we expect it would just get in the way at that point.
// (It also used to crash.)
gt := newGitTest(t)
defer gt.done()
gt.work(t)
write(t, gt.client+"/bad.go", badGo, 0644)
trun(t, gt.client, "git", "add", ".")
trun(t, gt.client, "git", "checkout", "HEAD^0")
testMain(t, "hook-invoke", "pre-commit")
testNoStdout(t)
testNoStderr(t)
*/
}
func TestHookPreCommitEnv(t *testing.T) {
// If $GIT_GOFMT_HOOK == "off", gofmt hook should not complain.
gt := newGitTest(t)
defer gt.done()
gt.work(t)
write(t, gt.client+"/bad.go", badGo, 0644)
trun(t, gt.client, "git", "add", ".")
os.Setenv("GIT_GOFMT_HOOK", "off")
defer os.Unsetenv("GIT_GOFMT_HOOK")
testMain(t, "hook-invoke", "pre-commit")
testNoStdout(t)
testPrintedStderr(t, "git-codereview pre-commit gofmt hook disabled by $GIT_GOFMT_HOOK=off")
}
func TestHookPreCommitUnstaged(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
write(t, gt.client+"/bad.go", badGo, 0644)
write(t, gt.client+"/good.go", goodGo, 0644)
// The pre-commit hook is being asked about files in the index.
// Make sure it is not looking at files in the working tree (current directory) instead.
// There are three possible kinds of file: good, bad (misformatted), and broken (syntax error).
// There are also three possible places files live: the most recent commit, the index,
// and the working tree. We write a sequence of files that cover all possible
// combination of kinds of file in the various places. For example,
// good-bad-broken.go is a good file in the most recent commit,
// a bad file in the index, and a broken file in the working tree.
// After creating these files, we check that the gofmt hook reports
// about the index only.
const N = 3
name := []string{"good", "bad", "broken"}
content := []string{goodGo, badGo, brokenGo}
var wantErr []string
var allFiles []string
writeFiles := func(n int) {
allFiles = nil
wantErr = nil
for i := 0; i < N*N*N; i++ {
// determine n'th digit of 3-digit base-N value i
j := i
for k := 0; k < (3 - 1 - n); k++ {
j /= N
}
file := fmt.Sprintf("%s-%s-%s.go", name[i/N/N], name[(i/N)%N], name[i%N])
allFiles = append(allFiles, file)
write(t, gt.client+"/"+file, content[j%N], 0644)
switch {
case strings.Contains(file, "-bad-"):
wantErr = append(wantErr, "\t"+file+"\n")
case strings.Contains(file, "-broken-"):
wantErr = append(wantErr, "\t"+file+":")
default:
wantErr = append(wantErr, "!"+file)
}
}
}
// committed files
writeFiles(0)
trun(t, gt.client, "git", "add", ".")
trun(t, gt.client, "git", "commit", "-m", "msg")
// staged files
writeFiles(1)
trun(t, gt.client, "git", "add", ".")
// unstaged files
writeFiles(2)
wantErr = append(wantErr, "gofmt reported errors", "gofmt needs to format these files")
testMainDied(t, "hook-invoke", "pre-commit")
testPrintedStderr(t, wantErr...)
}
func TestHooks(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.removeStubHooks()
testMain(t, "hooks") // install hooks
data, err := os.ReadFile(gt.client + "/.git/hooks/commit-msg")
if err != nil {
t.Fatalf("hooks did not write commit-msg hook: %v", err)
}
if string(data) != "#!/bin/sh\nexec git-codereview hook-invoke commit-msg \"$@\"\n" {
t.Fatalf("invalid commit-msg hook:\n%s", string(data))
}
}
var worktreeRE = regexp.MustCompile(`\sworktree\s`)
func mustHaveWorktree(t *testing.T) {
commands := trun(t, "", "git", "help", "-a")
if !worktreeRE.MatchString(commands) {
t.Skip("git doesn't support worktree")
}
}
func TestHooksInWorktree(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
mustHaveWorktree(t)
trun(t, gt.client, "git", "worktree", "add", "../worktree")
chdir(t, filepath.Join("..", "worktree"))
gt.removeStubHooks()
testMain(t, "hooks") // install hooks
data, err := os.ReadFile(gt.client + "/.git/hooks/commit-msg")
if err != nil {
t.Fatalf("hooks did not write commit-msg hook: %v", err)
}
if string(data) != "#!/bin/sh\nexec git-codereview hook-invoke commit-msg \"$@\"\n" {
t.Fatalf("invalid commit-msg hook:\n%s", string(data))
}
}
func TestHooksInSubdir(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.removeStubHooks()
if err := os.MkdirAll(gt.client+"/test", 0755); err != nil {
t.Fatal(err)
}
chdir(t, gt.client+"/test")
testMain(t, "hooks") // install hooks
data, err := os.ReadFile(gt.client + "/.git/hooks/commit-msg")
if err != nil {
t.Fatalf("hooks did not write commit-msg hook: %v", err)
}
if string(data) != "#!/bin/sh\nexec git-codereview hook-invoke commit-msg \"$@\"\n" {
t.Fatalf("invalid commit-msg hook:\n%s", string(data))
}
}
func TestHooksOverwriteOldCommitMsg(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.removeStubHooks()
mkdir(t, gt.client+"/.git/hooks")
write(t, gt.client+"/.git/hooks/commit-msg", oldCommitMsgHook, 0755)
testMain(t, "hooks") // install hooks
data, err := os.ReadFile(gt.client + "/.git/hooks/commit-msg")
if err != nil {
t.Fatalf("hooks did not write commit-msg hook: %v", err)
}
if string(data) == oldCommitMsgHook {
t.Fatalf("hooks left old commit-msg hook in place")
}
if string(data) != "#!/bin/sh\nexec git-codereview hook-invoke commit-msg \"$@\"\n" {
t.Fatalf("invalid commit-msg hook:\n%s", string(data))
}
}
// Test that 'git-codereview hooks' reports when it fails to write hooks.
// See go.dev/issue/16777.
func TestHooksReportConflictingContent(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
const pretendUserHook = "#!/bin/sh\necho 'pretend to be a custom hook'\nexit 1\n"
for _, h := range hookFiles {
write(t, gt.client+"/.git/hooks/"+h, pretendUserHook, 0755)
}
testMainDied(t, "hooks") // install hooks
testPrintedStderr(t, "Hooks files", "already exist.", "To install git-codereview hooks, delete these files and re-run 'git-codereview hooks'.")
for _, h := range hookFiles {
data := read(t, gt.client+"/.git/hooks/"+h)
if string(data) != pretendUserHook {
t.Errorf("existing hook file %s was unexpectedly modified", h)
}
}
}
func testInstallHook(t *testing.T, gt *gitTest) (restore func()) {
trun(t, gt.pwd, "go", "build", "-o", gt.client+"/git-codereview")
path := os.Getenv("PATH")
os.Setenv("PATH", gt.client+string(filepath.ListSeparator)+path)
gt.removeStubHooks()
testMain(t, "hooks") // install hooks
return func() {
os.Setenv("PATH", path)
}
}
func TestHookCommitMsgFromGit(t *testing.T) {
gt := newGitTest(t)
gt.enableGerrit(t)
defer gt.done()
restore := testInstallHook(t, gt)
defer restore()
testMain(t, "change", "mybranch")
write(t, gt.client+"/file", "more data", 0644)
trun(t, gt.client, "git", "add", "file")
trun(t, gt.client, "git", "commit", "-m", "mymsg")
log := trun(t, gt.client, "git", "log", "-n", "1")
if !strings.Contains(log, "mymsg") {
t.Fatalf("did not find mymsg in git log output:\n%s", log)
}
// The 4 spaces are because git indents the commit message proper.
if !strings.Contains(log, "\n \n Change-Id:") {
t.Fatalf("did not find Change-Id in git log output:\n%s", log)
}
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/pending.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"sort"
"strings"
"time"
)
var (
pendingLocal bool // -l flag, use only local operations (no network)
pendingCurrentOnly bool // -c flag, show only current branch
pendingShort bool // -s flag, short display
)
// A pendingBranch collects information about a single pending branch.
// We overlap the reading of this information for each branch.
type pendingBranch struct {
*Branch // standard Branch functionality
current bool // is this the current branch?
staged []string // files in staging area, only if current==true
unstaged []string // files unstaged in local directory, only if current==true
untracked []string // files untracked in local directory, only if current==true
}
// load populates b with information about the branch.
func (b *pendingBranch) load() {
b.loadPending()
if !b.current && b.commitsAhead == 0 {
// Won't be displayed, don't bother looking any closer.
return
}
b.OriginBranch() // cache result
if b.current {
b.staged, b.unstaged, b.untracked = LocalChanges()
}
var changeIDs []string
var commits []*Commit
for _, c := range b.Pending() {
c.committed = ListFiles(c)
if c.ChangeID == "" {
c.gerr = fmt.Errorf("missing Change-Id in commit message")
} else {
changeIDs = append(changeIDs, fullChangeID(b.Branch, c))
commits = append(commits, c)
}
}
if !pendingLocal {
gs, err := b.GerritChanges(changeIDs, "DETAILED_LABELS", "CURRENT_REVISION", "MESSAGES", "DETAILED_ACCOUNTS")
if len(gs) != len(commits) && err == nil {
err = fmt.Errorf("invalid response from Gerrit server - %d queries but %d results", len(changeIDs), len(gs))
}
if err != nil {
for _, c := range commits {
if c.gerr != nil {
c.gerr = err
}
}
} else {
for i, c := range commits {
if len(gs[i]) == 1 {
c.g = gs[i][0]
}
}
}
}
for _, c := range b.Pending() {
if c.g == nil {
c.g = new(GerritChange) // easier for formatting code
}
}
}
func cmdPending(args []string) {
// NOTE: New flags should be added to the usage message below as well as doc.go.
flags.BoolVar(&pendingCurrentOnly, "c", false, "show only current branch")
flags.BoolVar(&pendingLocal, "l", false, "use only local information - no network operations")
flags.BoolVar(&pendingShort, "s", false, "show short listing")
flags.Parse(args)
if len(flags.Args()) > 0 {
fmt.Fprintf(stderr(), "Usage: %s pending %s [-c] [-l] [-s]\n", progName, globalFlags)
exit(2)
}
// Fetch info about remote changes, so that we can say which branches need sync.
doneFetch := make(chan bool, 1)
if pendingLocal {
doneFetch <- true
} else {
http.DefaultClient.Timeout = 60 * time.Second
go func() {
run("git", "fetch", "-q")
doneFetch <- true
}()
}
// Build list of pendingBranch structs to be filled in.
// The current branch is always first.
var branches []*pendingBranch
branches = []*pendingBranch{{Branch: CurrentBranch(), current: true}}
if !pendingCurrentOnly {
current := CurrentBranch().Name
for _, b := range LocalBranches() {
if b.Name != current {
branches = append(branches, &pendingBranch{Branch: b})
}
}
}
// The various data gathering is a little slow,
// especially run in serial with a lot of branches.
// Overlap inspection of multiple branches.
// Each branch is only accessed by a single worker.
// Build work queue.
work := make(chan *pendingBranch, len(branches))
done := make(chan bool, len(branches))
for _, b := range branches {
work <- b
}
close(work)
// Kick off goroutines to do work.
n := len(branches)
if n > 10 {
n = 10
}
for i := 0; i < n; i++ {
go func() {
for b := range work {
// This b.load may be using a stale origin/master ref, which is OK.
b.load()
done <- true
}
}()
}
// Wait for goroutines to finish.
// Note: Counting work items, not goroutines (there may be fewer goroutines).
for range branches {
<-done
}
<-doneFetch
// Print output.
// If there are multiple changes in the current branch, the output splits them out into separate sections,
// in reverse commit order, to match git log output.
//
// wbshadow 7a524a1..a496c1e (current branch, all mailed, 23 behind, tracking master)
// + uncommitted changes
// Files unstaged:
// src/runtime/proc1.go
//
// + a496c1e https://go-review.googlesource.com/2064 (mailed)
// runtime: add missing write barriers in append's copy of slice data
//
// Found with GODEBUG=wbshadow=1 mode.
// Eventually that will run automatically, but right now
// it still detects other missing write barriers.
//
// Change-Id: Ic8624401d7c8225a935f719f96f2675c6f5c0d7c
//
// Code-Review:
// +0 Austin Clements, Rick Hudson
// Files in this change:
// src/runtime/slice.go
//
// + 95390c7 https://go-review.googlesource.com/2061 (mailed)
// runtime: add GODEBUG wbshadow for finding missing write barriers
//
// This is the detection code. It works well enough that I know of
// a handful of missing write barriers. However, those are subtle
// enough that I'll address them in separate followup CLs.
//
// Change-Id: If863837308e7c50d96b5bdc7d65af4969bf53a6e
//
// Code-Review:
// +0 Austin Clements, Rick Hudson
// Files in this change:
// src/runtime/extern.go
// src/runtime/malloc1.go
// src/runtime/malloc2.go
// src/runtime/mgc.go
// src/runtime/mgc0.go
// src/runtime/proc1.go
// src/runtime/runtime1.go
// src/runtime/runtime2.go
// src/runtime/stack1.go
//
// The first line only gives information that applies to the entire branch:
// the name, the commit range, whether this is the current branch, whether
// all the commits are mailed/submitted, how far behind, what remote branch
// it is tracking.
// The individual change sections have per-change information: the hash of that
// commit, the URL on the Gerrit server, whether it is mailed/submitted, the list of
// files in that commit. The uncommitted file modifications are shown as a separate
// section, at the beginning, to fit better into the reverse commit order.
//
// The short view compresses the listing down to two lines per commit:
// wbshadow 7a524a1..a496c1e (current branch, all mailed, 23 behind, tracking master)
// + uncommitted changes
// Files unstaged:
// src/runtime/proc1.go
// + a496c1e runtime: add missing write barriers in append's copy of slice data (CL 2064, mailed)
// + 95390c7 runtime: add GODEBUG wbshadow for finding missing write barriers (CL 2061, mailed)
var buf bytes.Buffer
printFileList := func(name string, list []string) {
if len(list) == 0 {
return
}
fmt.Fprintf(&buf, "\tFiles %s:\n", name)
for _, file := range list {
fmt.Fprintf(&buf, "\t\t%s\n", file)
}
}
for _, b := range branches {
if !b.current && b.commitsAhead == 0 {
// Hide branches with no work on them.
continue
}
fmt.Fprintf(&buf, "%s", b.Name)
work := b.Pending()
if len(work) > 0 {
fmt.Fprintf(&buf, " %.7s..%s", b.branchpoint, work[0].ShortHash)
}
var tags []string
if b.DetachedHead() {
tags = append(tags, "detached")
} else if b.current {
tags = append(tags, "current branch")
}
if allMailed(work) && len(work) > 0 {
tags = append(tags, "all mailed")
}
if allSubmitted(work) && len(work) > 0 {
tags = append(tags, "all submitted")
}
if n := b.CommitsBehind(); n > 0 {
tags = append(tags, fmt.Sprintf("%d behind", n))
}
if br := b.OriginBranch(); br == "" {
tags = append(tags, "remote branch unknown")
} else if br != "origin/master" && br != "origin/main" {
tags = append(tags, "tracking "+strings.TrimPrefix(b.OriginBranch(), "origin/"))
}
if len(tags) > 0 {
fmt.Fprintf(&buf, " (%s)", strings.Join(tags, ", "))
}
fmt.Fprintf(&buf, "\n")
printed := false
if b.current && len(b.staged)+len(b.unstaged)+len(b.untracked) > 0 {
printed = true
fmt.Fprintf(&buf, "+ uncommitted changes\n")
printFileList("untracked", b.untracked)
printFileList("unstaged", b.unstaged)
printFileList("staged", b.staged)
if !pendingShort {
fmt.Fprintf(&buf, "\n")
}
}
for _, c := range work {
printed = true
fmt.Fprintf(&buf, "+ ")
formatCommit(&buf, c, pendingShort)
if !pendingShort {
printFileList("in this change", c.committed)
fmt.Fprintf(&buf, "\n")
}
}
if pendingShort || !printed {
fmt.Fprintf(&buf, "\n")
}
}
stdout().Write(buf.Bytes())
}
// formatCommit writes detailed information about c to w. c.g must
// have the "CURRENT_REVISION" (or "ALL_REVISIONS") and
// "DETAILED_LABELS" options set.
//
// If short is true, this writes a single line overview.
//
// If short is false, this writes detailed information about the
// commit and its Gerrit state.
func formatCommit(w io.Writer, c *Commit, short bool) {
g := c.g
if g == nil {
g = new(GerritChange)
}
msg := strings.TrimRight(c.Message, "\r\n")
fmt.Fprintf(w, "%s", c.ShortHash)
var tags []string
if short {
if i := strings.Index(msg, "\n"); i >= 0 {
msg = msg[:i]
}
fmt.Fprintf(w, " %s", msg)
if g.Number != 0 {
tags = append(tags, fmt.Sprintf("CL %d%s", g.Number, codeReviewScores(g)))
}
} else {
if g.Number != 0 {
fmt.Fprintf(w, " %s/%d", auth.url, g.Number)
}
}
if g.CurrentRevision == c.Hash {
tags = append(tags, "mailed")
}
switch g.Status {
case "MERGED":
tags = append(tags, "submitted")
case "ABANDONED":
tags = append(tags, "abandoned")
}
if len(c.Parents) > 1 {
var h []string
for _, p := range c.Parents[1:] {
h = append(h, p[:7])
}
tags = append(tags, "merge="+strings.Join(h, ","))
}
if g.UnresolvedCommentCount > 0 {
tags = append(tags, fmt.Sprintf("%d unresolved comments", g.UnresolvedCommentCount))
}
if len(tags) > 0 {
fmt.Fprintf(w, " (%s)", strings.Join(tags, ", "))
}
fmt.Fprintf(w, "\n")
if short {
return
}
fmt.Fprintf(w, "\t%s\n", strings.Replace(msg, "\n", "\n\t", -1))
fmt.Fprintf(w, "\n")
for _, name := range g.LabelNames() {
label := g.Labels[name]
minValue := 10000
maxValue := -10000
byScore := map[int][]string{}
for _, x := range label.All {
// Hide CL owner unless owner score is nonzero.
if g.Owner != nil && x.ID == g.Owner.ID && x.Value == 0 {
continue
}
byScore[x.Value] = append(byScore[x.Value], x.Name)
if minValue > x.Value {
minValue = x.Value
}
if maxValue < x.Value {
maxValue = x.Value
}
}
// Unless there are scores to report, do not show labels other than Code-Review.
// This hides Run-TryBot and TryBot-Result.
if minValue >= 0 && maxValue <= 0 && name != "Code-Review" {
continue
}
fmt.Fprintf(w, "\t%s:\n", name)
for score := maxValue; score >= minValue; score-- {
who := byScore[score]
if len(who) == 0 || score == 0 && name != "Code-Review" {
continue
}
sort.Strings(who)
fmt.Fprintf(w, "\t\t%+d %s\n", score, strings.Join(who, ", "))
}
}
}
// codeReviewScores reports the code review scores as tags for the short output.
//
// g must have the "DETAILED_LABELS" option set.
func codeReviewScores(g *GerritChange) string {
label := g.Labels["Code-Review"]
if label == nil {
return ""
}
minValue := 10000
maxValue := -10000
for _, x := range label.All {
if minValue > x.Value {
minValue = x.Value
}
if maxValue < x.Value {
maxValue = x.Value
}
}
var scores string
if minValue < 0 {
scores += fmt.Sprintf(" %d", minValue)
}
if maxValue > 0 {
scores += fmt.Sprintf(" %+d", maxValue)
}
return scores
}
// allMailed reports whether all commits in work have been posted to Gerrit.
func allMailed(work []*Commit) bool {
for _, c := range work {
if c.Hash != c.g.CurrentRevision {
return false
}
}
return true
}
// allSubmitted reports whether all commits in work have been submitted to the origin branch.
func allSubmitted(work []*Commit) bool {
for _, c := range work {
if c.g.Status != "MERGED" {
return false
}
}
return true
}
// suffix returns an empty string if n == 1, s otherwise.
func suffix(n int, s string) string {
if n == 1 {
return ""
}
return s
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/pending_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"testing"
)
func TestPendingNone(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testPending(t, `
main (current branch)
`)
}
func TestPendingNoneBranch(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
trun(t, gt.client, "git", "checkout", "--no-track", "-b", "work")
testPending(t, `
work (current branch)
`)
}
func TestPendingBasic(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
testPending(t, `
work REVHASH..REVHASH (current branch)
+ REVHASH
msg
Change-Id: I123456789
Files in this change:
file
`)
}
func TestPendingComplex(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
write(t, gt.server+"/file", "v2", 0644)
trun(t, gt.server, "git", "commit", "-a", "-m", "v2")
write(t, gt.server+"/file", "v3", 0644)
trun(t, gt.server, "git", "commit", "-a", "-m", "v3")
trun(t, gt.client, "git", "fetch")
trun(t, gt.client, "git", "checkout", "-b", "work3ignored", "-t", "origin/main")
write(t, gt.server+"/file", "v4", 0644)
trun(t, gt.server, "git", "commit", "-a", "-m", "v4")
trun(t, gt.client, "git", "fetch")
trun(t, gt.client, "git", "checkout", "-b", "work2", "-t", "origin/main")
write(t, gt.client+"/file", "modify", 0644)
write(t, gt.client+"/file1", "new", 0644)
trun(t, gt.client, "git", "add", "file", "file1")
trun(t, gt.client, "git", "commit", "-m", "some changes")
write(t, gt.client+"/file1", "modify", 0644)
write(t, gt.client+"/afile1", "new", 0644)
trun(t, gt.client, "git", "add", "file1", "afile1")
write(t, gt.client+"/file1", "modify again", 0644)
write(t, gt.client+"/file", "modify again", 0644)
write(t, gt.client+"/bfile", "untracked", 0644)
testPending(t, `
work2 REVHASH..REVHASH (current branch)
+ uncommitted changes
Files untracked:
bfile
Files unstaged:
file
file1
Files staged:
afile1
file1
+ REVHASH
some changes
Files in this change:
file
file1
work REVHASH..REVHASH (3 behind)
+ REVHASH
msg
Change-Id: I123456789
Files in this change:
file
`)
testPendingArgs(t, []string{"-c"}, `
work2 REVHASH..REVHASH (current branch)
+ uncommitted changes
Files untracked:
bfile
Files unstaged:
file
file1
Files staged:
afile1
file1
+ REVHASH
some changes
Files in this change:
file
file1
`)
testPendingArgs(t, []string{"-c", "-s"}, `
work2 REVHASH..REVHASH (current branch)
+ uncommitted changes
Files untracked:
bfile
Files unstaged:
file
file1
Files staged:
afile1
file1
+ REVHASH some changes
`)
}
func TestPendingMultiChange(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
write(t, gt.client+"/file", "v2", 0644)
trun(t, gt.client, "git", "commit", "-a", "-m", "v2")
write(t, gt.client+"/file", "v4", 0644)
trun(t, gt.client, "git", "add", "file")
write(t, gt.client+"/file", "v5", 0644)
write(t, gt.client+"/file2", "v6", 0644)
testPending(t, `
work REVHASH..REVHASH (current branch)
+ uncommitted changes
Files untracked:
file2
Files unstaged:
file
Files staged:
file
+ REVHASH
v2
Files in this change:
file
+ REVHASH
msg
Change-Id: I123456789
Files in this change:
file
`)
testPendingArgs(t, []string{"-s"}, `
work REVHASH..REVHASH (current branch)
+ uncommitted changes
Files untracked:
file2
Files unstaged:
file
Files staged:
file
+ REVHASH v2
+ REVHASH msg
`)
}
func TestPendingGerrit(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
srv := newGerritServer(t)
defer srv.done()
// Test error from Gerrit server.
testPending(t, `
work REVHASH..REVHASH (current branch)
+ REVHASH
msg
Change-Id: I123456789
Files in this change:
file
`)
testPendingReply(srv, "I123456789", CurrentBranch().Pending()[0].Hash, "MERGED", 0)
// Test local mode does not talk to any server.
// Make client 1 behind server.
// The '1 behind' should not show up, nor any Gerrit information.
write(t, gt.server+"/file", "v4", 0644)
trun(t, gt.server, "git", "add", "file")
trun(t, gt.server, "git", "commit", "-m", "msg")
testPendingArgs(t, []string{"-l"}, `
work REVHASH..REVHASH (current branch)
+ REVHASH
msg
Change-Id: I123456789
Files in this change:
file
`)
testPendingArgs(t, []string{"-l", "-s"}, `
work REVHASH..REVHASH (current branch)
+ REVHASH msg
`)
// Without -l, the 1 behind should appear, as should Gerrit information.
testPending(t, `
work REVHASH..REVHASH (current branch, all mailed, all submitted, 1 behind)
+ REVHASH http://127.0.0.1:PORT/1234 (mailed, submitted)
msg
Change-Id: I123456789
Code-Review:
+1 Grace Emlin
-2 George Opher
Other-Label:
+2 The Owner
Files in this change:
file
`)
testPendingArgs(t, []string{"-s"}, `
work REVHASH..REVHASH (current branch, all mailed, all submitted, 1 behind)
+ REVHASH msg (CL 1234 -2 +1, mailed, submitted)
`)
// Since pending did a fetch, 1 behind should show up even with -l.
testPendingArgs(t, []string{"-l"}, `
work REVHASH..REVHASH (current branch, 1 behind)
+ REVHASH
msg
Change-Id: I123456789
Files in this change:
file
`)
testPendingArgs(t, []string{"-l", "-s"}, `
work REVHASH..REVHASH (current branch, 1 behind)
+ REVHASH msg
`)
}
func TestPendingGerritMultiChange(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
hash1 := CurrentBranch().Pending()[0].Hash
write(t, gt.client+"/file", "v2", 0644)
trun(t, gt.client, "git", "commit", "-a", "-m", "v2\n\nChange-Id: I2345")
hash2 := CurrentBranch().Pending()[0].Hash
write(t, gt.client+"/file", "v4", 0644)
trun(t, gt.client, "git", "add", "file")
write(t, gt.client+"/file", "v5", 0644)
write(t, gt.client+"/file2", "v6", 0644)
srv := newGerritServer(t)
defer srv.done()
testPendingReply(srv, "I123456789", hash1, "MERGED", 0)
testPendingReply(srv, "I2345", hash2, "NEW", 99)
testPending(t, `
work REVHASH..REVHASH (current branch, all mailed)
+ uncommitted changes
Files untracked:
file2
Files unstaged:
file
Files staged:
file
+ REVHASH http://127.0.0.1:PORT/1234 (mailed, 99 unresolved comments)
v2
Change-Id: I2345
Code-Review:
+1 Grace Emlin
-2 George Opher
Other-Label:
+2 The Owner
Files in this change:
file
+ REVHASH http://127.0.0.1:PORT/1234 (mailed, submitted)
msg
Change-Id: I123456789
Code-Review:
+1 Grace Emlin
-2 George Opher
Other-Label:
+2 The Owner
Files in this change:
file
`)
testPendingArgs(t, []string{"-s"}, `
work REVHASH..REVHASH (current branch, all mailed)
+ uncommitted changes
Files untracked:
file2
Files unstaged:
file
Files staged:
file
+ REVHASH v2 (CL 1234 -2 +1, mailed, 99 unresolved comments)
+ REVHASH msg (CL 1234 -2 +1, mailed, submitted)
`)
}
func TestPendingGerritMultiChange15(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
gt.work(t)
hash1 := CurrentBranch().Pending()[0].Hash
testPendingReply(srv, "I123456789", hash1, "MERGED", 0)
for i := 1; i < 15; i++ {
write(t, gt.client+"/file", fmt.Sprintf("v%d", i), 0644)
trun(t, gt.client, "git", "commit", "-a", "-m", fmt.Sprintf("v%d\n\nChange-Id: I%010d", i, i))
hash2 := CurrentBranch().Pending()[0].Hash
testPendingReply(srv, fmt.Sprintf("I%010d", i), hash2, "NEW", 0)
}
testPendingArgs(t, []string{"-s"}, `
work REVHASH..REVHASH (current branch, all mailed)
+ REVHASH v14 (CL 1234 -2 +1, mailed)
+ REVHASH v13 (CL 1234 -2 +1, mailed)
+ REVHASH v12 (CL 1234 -2 +1, mailed)
+ REVHASH v11 (CL 1234 -2 +1, mailed)
+ REVHASH v10 (CL 1234 -2 +1, mailed)
+ REVHASH v9 (CL 1234 -2 +1, mailed)
+ REVHASH v8 (CL 1234 -2 +1, mailed)
+ REVHASH v7 (CL 1234 -2 +1, mailed)
+ REVHASH v6 (CL 1234 -2 +1, mailed)
+ REVHASH v5 (CL 1234 -2 +1, mailed)
+ REVHASH v4 (CL 1234 -2 +1, mailed)
+ REVHASH v3 (CL 1234 -2 +1, mailed)
+ REVHASH v2 (CL 1234 -2 +1, mailed)
+ REVHASH v1 (CL 1234 -2 +1, mailed)
+ REVHASH msg (CL 1234 -2 +1, mailed, submitted)
`)
}
func testPendingReply(srv *gerritServer, id, rev, status string, unresolved int) {
srv.setJSON(id, `{
"id": "proj~main~`+id+`",
"project": "proj",
"current_revision": "`+rev+`",
"status": "`+status+`",
"unresolved_comment_count":`+fmt.Sprint(unresolved)+`,
"_number": 1234,
"owner": {"_id": 42},
"labels": {
"Code-Review": {
"all": [
{
"_id": 42,
"value": 0
},
{
"_id": 43,
"name": "George Opher",
"value": -2
},
{
"_id": 44,
"name": "Grace Emlin",
"value": 1
}
]
},
"Trybot-Spam": {
"all": [
{
"_account_id": 42,
"name": "The Owner",
"value": 0
}
]
},
"Other-Label": {
"all": [
{
"_id": 43,
"name": "George Opher",
"value": 0
},
{
"_account_id": 42,
"name": "The Owner",
"value": 2
}
]
}
}
}`)
}
func testPending(t *testing.T, want string) {
t.Helper()
testPendingArgs(t, nil, want)
}
func testPendingArgs(t *testing.T, args []string, want string) {
t.Helper()
// fake auth information to avoid Gerrit error
if !auth.initialized {
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
}
want = strings.Replace(want, "\n\t", "\n", -1)
want = strings.Replace(want, "\n\t", "\n", -1)
want = strings.TrimPrefix(want, "\n")
testMain(t, append([]string{"pending"}, args...)...)
out := testStdout.Bytes()
out = regexp.MustCompile(`\b[0-9a-f]{7}\b`).ReplaceAllLiteral(out, []byte("REVHASH"))
out = regexp.MustCompile(`\b127\.0\.0\.1:\d+\b`).ReplaceAllLiteral(out, []byte("127.0.0.1:PORT"))
out = regexp.MustCompile(`(?m)[ \t]+$`).ReplaceAllLiteral(out, nil) // ignore trailing space differences
if string(out) != want {
t.Errorf("invalid pending output:\n%s\nwant:\n%s", out, want)
if d, err := diff([]byte(want), out); err == nil {
t.Errorf("diff want actual:\n%s", d)
}
}
}
func diff(b1, b2 []byte) (data []byte, err error) {
f1, err := os.CreateTemp("", "gofmt")
if err != nil {
return
}
defer os.Remove(f1.Name())
defer f1.Close()
f2, err := os.CreateTemp("", "gofmt")
if err != nil {
return
}
defer os.Remove(f2.Name())
defer f2.Close()
f1.Write(b1)
f2.Write(b2)
data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
if len(data) > 0 {
// diff exits with a non-zero status when the files don't match.
// Ignore that failure as long as we get output.
err = nil
}
return
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/branch_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"path/filepath"
"reflect"
"strings"
"testing"
)
func TestCurrentBranch(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
t.Logf("on main")
checkCurrentBranch(t, "main", "origin/main", false, "", "")
t.Logf("on newbranch")
trun(t, gt.client, "git", "checkout", "--no-track", "-b", "newbranch")
checkCurrentBranch(t, "newbranch", "origin/main", false, "", "")
t.Logf("making change")
write(t, gt.client+"/file", "i made a change", 0644)
trun(t, gt.client, "git", "commit", "-a", "-m", "My change line.\n\nChange-Id: I0123456789abcdef0123456789abcdef\n")
checkCurrentBranch(t, "newbranch", "origin/main", true, "I0123456789abcdef0123456789abcdef", "My change line.")
t.Logf("on dev.branch")
trun(t, gt.client, "git", "checkout", "-t", "-b", "dev.branch", "origin/dev.branch")
checkCurrentBranch(t, "dev.branch", "origin/dev.branch", false, "", "")
t.Logf("on newdev")
trun(t, gt.client, "git", "checkout", "-t", "-b", "newdev", "origin/dev.branch")
checkCurrentBranch(t, "newdev", "origin/dev.branch", false, "", "")
t.Logf("making change")
write(t, gt.client+"/file", "i made another change", 0644)
trun(t, gt.client, "git", "commit", "-a", "-m", "My other change line.\n\nChange-Id: I1123456789abcdef0123456789abcdef\n")
checkCurrentBranch(t, "newdev", "origin/dev.branch", true, "I1123456789abcdef0123456789abcdef", "My other change line.")
t.Logf("detached head mode")
trun(t, gt.client, "git", "checkout", "main^0")
checkCurrentBranch(t, "HEAD", "", false, "", "")
trun(t, gt.client, "git", "checkout", "dev.branch^0")
checkCurrentBranch(t, "HEAD", "origin/dev.branch", false, "", "")
}
func checkCurrentBranch(t *testing.T, name, origin string, hasPending bool, changeID, subject string) {
t.Helper()
b := CurrentBranch()
if b.Name != name {
t.Errorf("b.Name = %q, want %q", b.Name, name)
}
if x := b.OriginBranch(); x != origin {
t.Errorf("b.OriginBranch() = %q, want %q", x, origin)
}
if x := b.HasPendingCommit(); x != hasPending {
t.Errorf("b.HasPendingCommit() = %v, want %v", x, hasPending)
}
if work := b.Pending(); len(work) > 0 {
c := work[0]
if x := c.ChangeID; x != changeID {
t.Errorf("b.Pending()[0].ChangeID = %q, want %q", x, changeID)
}
if x := c.Subject; x != subject {
t.Errorf("b.Pending()[0].Subject = %q, want %q", x, subject)
}
}
}
func TestLocalBranches(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
t.Logf("on main")
checkLocalBranches(t, "main")
t.Logf("on dev branch")
trun(t, gt.client, "git", "checkout", "-b", "newbranch")
checkLocalBranches(t, "main", "newbranch")
t.Logf("detached head mode")
trun(t, gt.client, "git", "checkout", "HEAD^0")
checkLocalBranches(t, "HEAD", "main", "newbranch")
t.Logf("worktree")
wt := filepath.Join(gt.tmpdir, "git-worktree")
trun(t, gt.client, "git", "worktree", "add", "-b", "wtbranch", wt)
checkLocalBranches(t, "HEAD", "main", "newbranch", "wtbranch")
}
func checkLocalBranches(t *testing.T, want ...string) {
var names []string
branches := LocalBranches()
for _, b := range branches {
names = append(names, b.Name)
}
if !reflect.DeepEqual(names, want) {
t.Errorf("LocalBranches() = %v, want %v", names, want)
}
}
func TestAmbiguousRevision(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
t.Logf("creating file paths that conflict with revision parameters")
mkdir(t, gt.client+"/origin")
write(t, gt.client+"/origin/main..work", "Uh-Oh! SpaghettiOs", 0644)
mkdir(t, gt.client+"/work..origin")
write(t, gt.client+"/work..origin/main", "Be sure to drink your Ovaltine", 0644)
b := CurrentBranch()
b.Submitted("I123456789")
}
func TestBranchpoint(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// Get hash corresponding to checkout (known to server).
hash := strings.TrimSpace(trun(t, gt.client, "git", "rev-parse", "HEAD"))
// Any work we do after this point should find hash as branchpoint.
for i := 0; i < 4; i++ {
testMain(t, "branchpoint")
t.Logf("numCommits=%d", i)
testPrintedStdout(t, hash)
testNoStderr(t)
gt.work(t)
}
}
func TestRebaseWork(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// Get hash corresponding to checkout (known to server).
// Any work we do after this point should find hash as branchpoint.
hash := strings.TrimSpace(trun(t, gt.client, "git", "rev-parse", "HEAD"))
testMainDied(t, "rebase-work", "-n")
testPrintedStderr(t, "no pending work")
write(t, gt.client+"/file", "uncommitted", 0644)
testMainDied(t, "rebase-work", "-n")
testPrintedStderr(t, "cannot rebase with uncommitted work")
gt.work(t)
for i := 0; i < 4; i++ {
testMain(t, "rebase-work", "-n")
t.Logf("numCommits=%d", i)
testPrintedStderr(t, "git rebase -i "+hash)
gt.work(t)
}
}
func TestBranchpointMerge(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// commit more work on main
write(t, gt.server+"/file", "more work", 0644)
trun(t, gt.server, "git", "commit", "-m", "work", "file")
// update client
trun(t, gt.client, "git", "checkout", "main")
trun(t, gt.client, "git", "pull")
hash := strings.TrimSpace(trun(t, gt.client, "git", "rev-parse", "HEAD"))
// Merge dev.branch but delete the codereview.cfg that comes in,
// or else we'll think we are on the wrong branch.
trun(t, gt.client, "git", "merge", "-m", "merge", "origin/dev.branch")
trun(t, gt.client, "git", "rm", "codereview.cfg")
trun(t, gt.client, "git", "commit", "-m", "rm codereview.cfg")
// check branchpoint is old head (despite this commit having two parents)
bp := CurrentBranch().Branchpoint()
if bp != hash {
t.Logf("branches:\n%s", trun(t, gt.client, "git", "branch", "-a", "-v"))
t.Logf("log:\n%s", trun(t, gt.client, "git", "log", "--graph", "--decorate"))
t.Logf("log origin/main..HEAD:\n%s", trun(t, gt.client, "git", "log", "origin/main..HEAD"))
t.Fatalf("branchpoint=%q, want %q", bp, hash)
}
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/util_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime/debug"
"strings"
"sync"
"testing"
)
var gitversion = "unknown git version" // git version for error logs
type gitTest struct {
pwd string // current directory before test
tmpdir string // temporary directory holding repos
server string // server repo root
client string // client repo root
nwork int // number of calls to work method
nworkServer int // number of calls to serverWork method
nworkOther int // number of calls to serverWorkUnrelated method
}
// resetReadOnlyFlagAll resets windows read-only flag
// set on path and any children it contains.
// The flag is set by git and has to be removed.
// os.Remove refuses to remove files with read-only flag set.
func resetReadOnlyFlagAll(path string) error {
fi, err := os.Stat(path)
if err != nil {
return err
}
if !fi.IsDir() {
return os.Chmod(path, 0666)
}
fd, err := os.Open(path)
if err != nil {
return err
}
defer fd.Close()
names, _ := fd.Readdirnames(-1)
for _, name := range names {
resetReadOnlyFlagAll(path + string(filepath.Separator) + name)
}
return nil
}
func (gt *gitTest) done() {
os.Chdir(gt.pwd) // change out of gt.tmpdir first, otherwise following os.RemoveAll fails on windows
resetReadOnlyFlagAll(gt.tmpdir)
os.RemoveAll(gt.tmpdir)
cachedConfig = nil
}
// doWork simulates commit 'n' touching 'file' in 'dir'
func doWork(t *testing.T, n int, dir, file, changeid string, msg string) {
t.Helper()
write(t, dir+"/"+file, fmt.Sprintf("new content %d", n), 0644)
trun(t, dir, "git", "add", file)
suffix := ""
if n > 1 {
suffix = fmt.Sprintf(" #%d", n)
}
if msg != "" {
msg += "\n\n"
}
cmsg := fmt.Sprintf("%smsg%s\n\nChange-Id: I%d%s\n", msg, suffix, n, changeid)
trun(t, dir, "git", "commit", "-m", cmsg)
}
func (gt *gitTest) work(t *testing.T) {
t.Helper()
if gt.nwork == 0 {
trun(t, gt.client, "git", "checkout", "-b", "work")
trun(t, gt.client, "git", "branch", "--set-upstream-to", "origin/main")
trun(t, gt.client, "git", "tag", "work") // make sure commands do the right thing when there is a tag of the same name
}
// make local change on client
gt.nwork++
doWork(t, gt.nwork, gt.client, "file", "23456789", "")
}
func (gt *gitTest) workFile(t *testing.T, file string) {
t.Helper()
// make local change on client in the specific file
gt.nwork++
doWork(t, gt.nwork, gt.client, file, "23456789", "")
}
func (gt *gitTest) serverWork(t *testing.T) {
t.Helper()
// make change on server
// duplicating the sequence of changes in gt.work to simulate them
// having gone through Gerrit and submitted with possibly
// different commit hashes but the same content.
gt.nworkServer++
doWork(t, gt.nworkServer, gt.server, "file", "23456789", "")
}
func (gt *gitTest) serverWorkUnrelated(t *testing.T, msg string) {
t.Helper()
// make unrelated change on server
// this makes history different on client and server
gt.nworkOther++
doWork(t, gt.nworkOther, gt.server, "otherfile", "9999", msg)
}
func newGitTest(t *testing.T) (gt *gitTest) {
t.Helper()
// The Linux builders seem not to have git in their paths.
// That makes this whole repo a bit useless on such systems,
// but make sure the tests don't fail.
_, err := exec.LookPath("git")
if err != nil {
t.Skipf("cannot find git in path: %v", err)
}
tmpdir, err := os.MkdirTemp("", "git-codereview-test")
if err != nil {
t.Fatal(err)
}
defer func() {
if gt == nil {
os.RemoveAll(tmpdir)
}
}()
gitversion = trun(t, tmpdir, "git", "--version")
server := tmpdir + "/git-origin"
mkdir(t, server)
write(t, server+"/file", "this is main", 0644)
write(t, server+"/.gitattributes", "* -text\n", 0644)
trun(t, server, "git", "init", ".")
trun(t, server, "git", "config", "user.name", "gopher")
trun(t, server, "git", "config", "user.email", "gopher@example.com")
trun(t, server, "git", "add", "file", ".gitattributes")
trun(t, server, "git", "commit", "-m", "initial commit")
// Newer gits use a default branch name of main.
// Older ones used master.
// So the branch name now may be main or master.
// We would like to assume main for the tests.
// Newer gits would let us do
// git init --initial-branch=main .
// above, but older gits don't have initial-branch.
// And we don't trust older gits to handle a no-op branch rename.
// So rename it to something different, and then to main.
// Then we'll be in a known state.
trun(t, server, "git", "branch", "-M", "certainly-not-main")
trun(t, server, "git", "branch", "-M", "main")
for _, name := range []string{"dev.branch", "release.branch"} {
trun(t, server, "git", "checkout", "main")
trun(t, server, "git", "checkout", "-b", name)
write(t, server+"/file."+name, "this is "+name, 0644)
cfg := "branch: " + name + "\n"
if name == "dev.branch" {
cfg += "parent-branch: main\n"
}
write(t, server+"/codereview.cfg", cfg, 0644)
trun(t, server, "git", "add", "file."+name, "codereview.cfg")
trun(t, server, "git", "commit", "-m", "on "+name)
}
trun(t, server, "git", "checkout", "main")
client := tmpdir + "/git-client"
mkdir(t, client)
trun(t, client, "git", "clone", server, ".")
trun(t, client, "git", "config", "user.name", "gopher")
trun(t, client, "git", "config", "user.email", "gopher@example.com")
// write stub hooks to keep installHook from installing its own.
// If it installs its own, git will look for git-codereview on the current path
// and may find an old git-codereview that does just about anything.
// In any event, we wouldn't be testing what we want to test.
// Tests that want to exercise hooks need to arrange for a git-codereview
// in the path and replace these with the real ones.
if _, err := os.Stat(client + "/.git/hooks"); os.IsNotExist(err) {
mkdir(t, client+"/.git/hooks")
}
for _, h := range hookFiles {
write(t, client+"/.git/hooks/"+h, "#!/bin/sh\nexit 0\n", 0755)
}
trun(t, client, "git", "config", "core.editor", "false")
pwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(client); err != nil {
t.Fatal(err)
}
return &gitTest{
pwd: pwd,
tmpdir: tmpdir,
server: server,
client: client,
}
}
func (gt *gitTest) enableGerrit(t *testing.T) {
t.Helper()
write(t, gt.server+"/codereview.cfg", "gerrit: myserver\n", 0644)
trun(t, gt.server, "git", "add", "codereview.cfg")
trun(t, gt.server, "git", "commit", "-m", "add gerrit")
trun(t, gt.client, "git", "pull", "-r")
}
func (gt *gitTest) removeStubHooks() {
os.RemoveAll(gt.client + "/.git/hooks/")
}
func mkdir(t *testing.T, dir string) {
if err := os.Mkdir(dir, 0777); err != nil {
t.Helper()
t.Fatal(err)
}
}
func chdir(t *testing.T, dir string) {
if err := os.Chdir(dir); err != nil {
t.Helper()
t.Fatal(err)
}
}
func write(t *testing.T, file, data string, perm os.FileMode) {
if err := os.WriteFile(file, []byte(data), perm); err != nil {
t.Helper()
t.Fatal(err)
}
}
func read(t *testing.T, file string) []byte {
b, err := os.ReadFile(file)
if err != nil {
t.Helper()
t.Fatal(err)
}
return b
}
func remove(t *testing.T, file string) {
if err := os.RemoveAll(file); err != nil {
t.Helper()
t.Fatal(err)
}
}
func trun(t *testing.T, dir string, cmdline ...string) string {
cmd := exec.Command(cmdline[0], cmdline[1:]...)
cmd.Dir = dir
setEnglishLocale(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
t.Helper()
if cmdline[0] == "git" {
t.Fatalf("in %s/, ran %s with %s:\n%v\n%s", filepath.Base(dir), cmdline, gitversion, err, out)
}
t.Fatalf("in %s/, ran %s: %v\n%s", filepath.Base(dir), cmdline, err, out)
}
return string(out)
}
// fromSlash is like filepath.FromSlash, but it ignores ! at the start of the path
// and " (staged)" at the end.
func fromSlash(path string) string {
if len(path) > 0 && path[0] == '!' {
return "!" + fromSlash(path[1:])
}
if strings.HasSuffix(path, " (staged)") {
return fromSlash(path[:len(path)-len(" (staged)")]) + " (staged)"
}
return filepath.FromSlash(path)
}
var (
runLog []string
testStderr *bytes.Buffer
testStdout *bytes.Buffer
died bool
mainCanDie bool
)
func testMainDied(t *testing.T, args ...string) {
t.Helper()
mainCanDie = true
testMain(t, args...)
if !died {
t.Fatalf("expected to die, did not\nstdout:\n%sstderr:\n%s", testStdout, testStderr)
}
}
func testMain(t *testing.T, args ...string) {
t.Helper()
*noRun = false
*verbose = 0
cachedConfig = nil
t.Logf("git-codereview %s", strings.Join(args, " "))
canDie := mainCanDie
mainCanDie = false // reset for next invocation
defer func() {
t.Helper()
runLog = runLogTrap
testStdout = stdoutTrap
testStderr = stderrTrap
exitTrap = nil
runLogTrap = nil
stdoutTrap = nil
stderrTrap = nil
if err := recover(); err != nil {
if died && canDie {
return
}
var msg string
if died {
msg = "died"
} else {
msg = fmt.Sprintf("panic: %v\n%s", err, debug.Stack())
}
t.Fatalf("%s\nstdout:\n%sstderr:\n%s", msg, testStdout, testStderr)
}
if testStdout.Len() > 0 {
t.Logf("stdout:\n%s", testStdout)
}
if testStderr.Len() > 0 {
t.Logf("stderr:\n%s", testStderr)
}
}()
exitTrap = func() {
died = true
panic("died")
}
died = false
runLogTrap = []string{} // non-nil, to trigger saving of commands
stdoutTrap = new(bytes.Buffer)
stderrTrap = new(bytes.Buffer)
os.Args = append([]string{"git-codereview"}, args...)
main()
}
func testRan(t *testing.T, cmds ...string) {
if cmds == nil {
cmds = []string{}
}
if !reflect.DeepEqual(runLog, cmds) {
t.Helper()
t.Errorf("ran:\n%s", strings.Join(runLog, "\n"))
t.Errorf("wanted:\n%s", strings.Join(cmds, "\n"))
}
}
func testPrinted(t *testing.T, buf *bytes.Buffer, name string, messages ...string) {
all := buf.String()
var errors bytes.Buffer
for _, msg := range messages {
if strings.HasPrefix(msg, "!") {
if strings.Contains(all, msg[1:]) {
fmt.Fprintf(&errors, "%s does (but should not) contain %q\n", name, msg[1:])
}
continue
}
if !strings.Contains(all, msg) {
fmt.Fprintf(&errors, "%s does not contain %q\n", name, msg)
}
}
if errors.Len() > 0 {
t.Helper()
t.Fatalf("wrong output\n%s%s:\n%s", &errors, name, all)
}
}
func testHideRevHashes(t *testing.T) {
for _, b := range []*bytes.Buffer{testStdout, testStderr} {
out := b.Bytes()
out = regexp.MustCompile(`\b[0-9a-f]{7}\b`).ReplaceAllLiteral(out, []byte("REVHASH"))
out = regexp.MustCompile(`\b\d{4}-\d{2}-\d{2}\b`).ReplaceAllLiteral(out, []byte("DATE"))
b.Reset()
b.Write(out)
}
}
func testPrintedStdout(t *testing.T, messages ...string) {
t.Helper()
testPrinted(t, testStdout, "stdout", messages...)
}
func testPrintedStderr(t *testing.T, messages ...string) {
t.Helper()
testPrinted(t, testStderr, "stderr", messages...)
}
func testNoStdout(t *testing.T) {
if testStdout.Len() != 0 {
t.Helper()
t.Fatalf("unexpected stdout:\n%s", testStdout)
}
}
func testNoStderr(t *testing.T) {
if testStderr.Len() != 0 {
t.Helper()
t.Fatalf("unexpected stderr:\n%s", testStderr)
}
}
type gerritServer struct {
l net.Listener
mu sync.Mutex
reply map[string]gerritReply
}
func newGerritServer(t *testing.T) *gerritServer {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Helper()
t.Fatalf("starting fake gerrit: %v", err)
}
auth.initialized = true
auth.host = l.Addr().String()
auth.url = "http://" + auth.host
auth.project = "proj"
auth.user = "gopher"
auth.password = "PASSWORD"
s := &gerritServer{l: l, reply: make(map[string]gerritReply)}
go http.Serve(l, s)
return s
}
func (s *gerritServer) done() {
s.l.Close()
auth.initialized = false
auth.host = ""
auth.url = ""
auth.project = ""
auth.user = ""
auth.password = ""
}
type gerritReply struct {
status int
body string
json interface{}
f func() gerritReply
}
func (s *gerritServer) setReply(path string, reply gerritReply) {
s.mu.Lock()
defer s.mu.Unlock()
s.reply[path] = reply
}
func (s *gerritServer) setJSON(id, json string) {
s.setReply("/a/changes/proj~main~"+id, gerritReply{body: ")]}'\n" + json})
}
func (s *gerritServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/a/changes/" {
s.serveChangesQuery(w, req)
return
}
s.mu.Lock()
defer s.mu.Unlock()
reply, ok := s.reply[req.URL.Path]
if !ok {
http.NotFound(w, req)
return
}
if reply.f != nil {
reply = reply.f()
}
if reply.status != 0 {
w.WriteHeader(reply.status)
}
if reply.json != nil {
body, err := json.Marshal(reply.json)
if err != nil {
dief("%v", err)
}
reply.body = ")]}'\n" + string(body)
}
if len(reply.body) > 0 {
w.Write([]byte(reply.body))
}
}
func (s *gerritServer) serveChangesQuery(w http.ResponseWriter, req *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
qs := req.URL.Query()["q"]
if len(qs) > 10 {
http.Error(w, "too many queries", 500)
}
var buf bytes.Buffer
fmt.Fprintf(&buf, ")]}'\n")
end := ""
if len(qs) > 1 {
fmt.Fprintf(&buf, "[")
end = "]"
}
sep := ""
for _, q := range qs {
fmt.Fprintf(&buf, "%s[", sep)
if strings.HasPrefix(q, "change:") {
reply, ok := s.reply[req.URL.Path+strings.TrimPrefix(q, "change:")]
if ok {
if reply.json != nil {
body, err := json.Marshal(reply.json)
if err != nil {
dief("%v", err)
}
reply.body = ")]}'\n" + string(body)
}
body := reply.body
i := strings.Index(body, "\n")
if i > 0 {
body = body[i+1:]
}
fmt.Fprintf(&buf, "%s", body)
}
}
fmt.Fprintf(&buf, "]")
sep = ","
}
fmt.Fprintf(&buf, "%s", end)
w.Write(buf.Bytes())
}
func TestUsage(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testMainDied(t)
testPrintedStderr(t, "Usage: git-codereview <command>")
testMainDied(t, "not-a-command")
testPrintedStderr(t, "Usage: git-codereview <command>")
// During tests we configure the flag package to panic on error
// instead of
testMainDied(t, "mail", "-not-a-flag")
testPrintedStderr(t, "flag provided but not defined")
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/api_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"os"
"path/filepath"
"testing"
)
var authTests = []struct {
netrc string
cookiefile string
user string
password string
cookieName string
cookieValue string
died bool
}{
{
// If we specify the empty string here, git will store an empty
// value for the local http.cookiefile, and fall back to the global
// http.cookiefile, which will fail this test on any machine that has
// a global http.cookiefile configured. If we write a local, invalid
// value, git will try to load the local cookie file (and then fail
// later).
cookiefile: " ",
died: true,
},
{
netrc: "machine go.googlesource.com login u1 password pw\n",
cookiefile: " ", // prevent global fallback
user: "u1",
password: "pw",
},
{
cookiefile: "go.googlesource.com TRUE / TRUE 2147483647 o2 git-u2=pw\n",
cookieName: "o2",
cookieValue: "git-u2=pw",
},
{
cookiefile: ".googlesource.com TRUE / TRUE 2147483647 o3 git-u3=pw\n",
cookieName: "o3",
cookieValue: "git-u3=pw",
},
{
cookiefile: ".googlesource.com TRUE / TRUE 2147483647 o4 WRONG\n" +
"go.googlesource.com TRUE / TRUE 2147483647 o4 git-u4=pw\n",
cookieName: "o4",
cookieValue: "git-u4=pw",
},
{
cookiefile: "go.googlesource.com TRUE / TRUE 2147483647 o5 git-u5=pw\n" +
".googlesource.com TRUE / TRUE 2147483647 o5 WRONG\n",
cookieName: "o5",
cookieValue: "git-u5=pw",
},
{
netrc: "machine go.googlesource.com login u6 password pw\n",
cookiefile: "BOGUS",
user: "u6",
password: "pw",
},
{
netrc: "BOGUS",
cookiefile: "go.googlesource.com TRUE / TRUE 2147483647 o7 git-u7=pw\n",
cookieName: "o7",
cookieValue: "git-u7=pw",
},
{
netrc: "machine go.googlesource.com login u8 password pw\n",
cookiefile: "MISSING",
user: "u8",
password: "pw",
},
}
func TestLoadAuth(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
defer os.Setenv("HOME", os.Getenv("HOME"))
os.Setenv("HOME", gt.client)
testHomeDir = gt.client
netrc := filepath.Join(gt.client, netrcName())
defer func() {
testHomeDir = ""
}()
trun(t, gt.client, "git", "config", "remote.origin.url", "https://go.googlesource.com/go")
for i, tt := range authTests {
t.Logf("#%d", i)
auth.initialized = false
auth.user = ""
auth.password = ""
auth.cookieName = ""
auth.cookieValue = ""
trun(t, gt.client, "git", "config", "http.cookiefile", "XXX")
trun(t, gt.client, "git", "config", "--unset", "http.cookiefile")
remove(t, netrc)
remove(t, gt.client+"/.cookies")
if tt.netrc != "" {
write(t, netrc, tt.netrc, 0644)
}
if tt.cookiefile != "" {
if tt.cookiefile != "MISSING" {
write(t, gt.client+"/.cookies", tt.cookiefile, 0644)
}
trun(t, gt.client, "git", "config", "http.cookiefile", "~/.cookies")
}
// Run command via testMain to trap stdout, stderr, death.
if tt.died {
testMainDied(t, "test-loadAuth")
} else {
testMain(t, "test-loadAuth")
}
if auth.user != tt.user || auth.password != tt.password {
t.Errorf("#%d: have user, password = %q, %q, want %q, %q", i, auth.user, auth.password, tt.user, tt.password)
}
if auth.cookieName != tt.cookieName || auth.cookieValue != tt.cookieValue {
t.Errorf("#%d: have cookie name, value = %q, %q, want %q, %q", i, auth.cookieName, auth.cookieValue, tt.cookieName, tt.cookieValue)
}
}
}
func TestLoadGerritOrigin(t *testing.T) {
list := []struct {
origin, originUrl string
fail bool
host, url, project string
}{
{
// *.googlesource.com
origin: "",
originUrl: "https://go.googlesource.com/crypto",
host: "go.googlesource.com",
url: "https://go-review.googlesource.com",
project: "crypto",
},
{
// Clone with sso://go/ (Google-internal but common with Go developers)
origin: "",
originUrl: "sso://go/tools",
host: "go.googlesource.com",
url: "https://go-review.googlesource.com",
project: "tools",
},
{
// Clone with rpc://go/ (Google-internal but common with Go developers)
origin: "",
originUrl: "rpc://go/tools",
host: "go.googlesource.com",
url: "https://go-review.googlesource.com",
project: "tools",
},
{
// Gerrit origin is set.
// Gerrit is hosted on a sub-domain.
origin: "https://gerrit.mysite.com",
originUrl: "https://gerrit.mysite.com/projectA",
host: "gerrit.mysite.com",
url: "https://gerrit.mysite.com",
project: "projectA",
},
{
// Gerrit origin is set.
// Gerrit is hosted under sub-path under "/gerrit".
origin: "https://mysite.com/gerrit",
originUrl: "https://mysite.com/gerrit/projectA",
host: "mysite.com",
url: "https://mysite.com/gerrit",
project: "projectA",
},
{
// Gerrit origin is set.
// Gerrit is hosted under sub-path under "/gerrit" and repo is under
// sub-folder.
origin: "https://mysite.com/gerrit",
originUrl: "https://mysite.com/gerrit/sub/projectA",
host: "mysite.com",
url: "https://mysite.com/gerrit",
project: "sub/projectA",
},
}
for _, item := range list {
auth.initialized = false
auth.host = ""
auth.url = ""
auth.project = ""
err := loadGerritOriginInternal(item.origin, item.originUrl)
if err != nil && !item.fail {
t.Errorf("unexpected error from item %q %q: %v", item.origin, item.originUrl, err)
continue
}
if auth.host != item.host || auth.url != item.url || auth.project != item.project {
t.Errorf("want %q %q %q, got %q %q %q", item.host, item.url, item.project, auth.host, auth.url, auth.project)
continue
}
if item.fail {
continue
}
have := haveGerritInternal(item.origin, item.originUrl)
if !have {
t.Errorf("for %q %q expect haveGerrit() == true, but got false", item.origin, item.originUrl)
}
}
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/submit.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"strings"
"time"
)
func cmdSubmit(args []string) {
// NOTE: New flags should be added to the usage message below as well as doc.go.
var interactive bool
flags.BoolVar(&interactive, "i", false, "interactively select commits to submit")
flags.Usage = func() {
fmt.Fprintf(stderr(), "Usage: %s submit %s [-i | commit...]\n", progName, globalFlags)
exit(2)
}
flags.Parse(args)
if interactive && flags.NArg() > 0 {
flags.Usage()
exit(2)
}
b := CurrentBranch()
var cs []*Commit
if interactive {
hashes := submitHashes(b)
if len(hashes) == 0 {
printf("nothing to submit")
return
}
for _, hash := range hashes {
cs = append(cs, b.CommitByRev("submit", hash))
}
} else if args := flags.Args(); len(args) >= 1 {
for _, arg := range args {
cs = append(cs, b.CommitByRev("submit", arg))
}
} else {
cs = append(cs, b.DefaultCommit("submit", "must specify commit on command line or use submit -i"))
}
// No staged changes.
// Also, no unstaged changes, at least for now.
// This makes sure the sync at the end will work well.
// We can relax this later if there is a good reason.
checkStaged("submit")
checkUnstaged("submit")
// Submit the changes.
var g *GerritChange
for _, c := range cs {
printf("submitting %s %s", c.ShortHash, c.Subject)
g = submit(b, c)
}
// Sync client to revision that Gerrit committed, but only if we can do it cleanly.
// Otherwise require user to run 'git sync' themselves (if they care).
run("git", "fetch", "-q")
if len(cs) == 1 && len(b.Pending()) == 1 {
if err := runErr("git", "checkout", "-q", "-B", b.Name, g.CurrentRevision, "--"); err != nil {
dief("submit succeeded, but cannot sync local branch\n"+
"\trun 'git sync' to sync, or\n"+
"\trun 'git branch -D %s; git change master; git sync' to discard local branch", b.Name)
}
} else {
printf("submit succeeded; run 'git sync' to sync")
}
// Done! Change is submitted, branch is up to date, ready for new work.
}
// submit submits a single commit c on branch b and returns the
// GerritChange for the submitted change. It dies if the submit fails.
func submit(b *Branch, c *Commit) *GerritChange {
if strings.Contains(strings.ToLower(c.Message), "do not submit") {
dief("%s: CL says DO NOT SUBMIT", c.ShortHash)
}
// Fetch Gerrit information about this change.
g, err := b.GerritChange(c, "LABELS", "CURRENT_REVISION")
if err != nil {
dief("%v", err)
}
// Pre-check that this change appears submittable.
// The final submit will check this too, but it is better to fail now.
if err = submitCheck(g); err != nil {
dief("cannot submit: %v", err)
}
// Upload most recent revision if not already on server.
if c.Hash != g.CurrentRevision {
run("git", "push", "-q", "origin", b.PushSpec(c))
// Refetch change information.
g, err = b.GerritChange(c, "LABELS", "CURRENT_REVISION")
if err != nil {
dief("%v", err)
}
}
if *noRun {
printf("stopped before submit")
return g
}
// Otherwise, try the submit. Sends back updated GerritChange,
// but we need extended information and the reply is in the
// "SUBMITTED" state anyway, so ignore the GerritChange
// in the response and fetch a new one below.
if err := gerritAPI("/a/changes/"+fullChangeID(b, c)+"/submit", []byte(`{"wait_for_merge": true}`), nil); err != nil {
dief("cannot submit: %v", err)
}
// It is common to get back "SUBMITTED" for a split second after the
// request is made. That indicates that the change has been queued for submit,
// but the first merge (the one wait_for_merge waited for)
// failed, possibly due to a spurious condition. We see this often, and the
// status usually changes to MERGED shortly thereafter.
// Wait a little while to see if we can get to a different state.
const steps = 6
const max = 2 * time.Second
for i := 0; i < steps; i++ {
time.Sleep(max * (1 << uint(i+1)) / (1 << steps))
g, err = b.GerritChange(c, "LABELS", "CURRENT_REVISION")
if err != nil {
dief("waiting for merge: %v", err)
}
if g.Status != "SUBMITTED" {
break
}
}
switch g.Status {
default:
dief("submit error: unexpected post-submit Gerrit change status %q", g.Status)
case "MERGED":
// good
case "SUBMITTED":
// see above
dief("cannot submit: timed out waiting for change to be submitted by Gerrit")
}
return g
}
// submitCheck checks that g should be submittable. This is
// necessarily a best-effort check.
//
// g must have the "LABELS" option.
func submitCheck(g *GerritChange) error {
// Check Gerrit change status.
switch g.Status {
default:
return fmt.Errorf("unexpected Gerrit change status %q", g.Status)
case "NEW", "SUBMITTED":
// Not yet "MERGED", so try the submit.
// "SUBMITTED" is a weird state. It means that Submit has been clicked once,
// but it hasn't happened yet, usually because of a merge failure.
// The user may have done git sync and may now have a mergable
// copy waiting to be uploaded, so continue on as if it were "NEW".
case "MERGED":
// Can happen if moving between different clients.
return fmt.Errorf("change already submitted, run 'git sync'")
case "ABANDONED":
return fmt.Errorf("change abandoned")
}
// Check for label approvals (like CodeReview+2).
for _, name := range g.LabelNames() {
label := g.Labels[name]
if label.Optional {
continue
}
if label.Rejected != nil {
return fmt.Errorf("change has %s rejection", name)
}
if label.Approved == nil {
return fmt.Errorf("change missing %s approval", name)
}
}
return nil
}
// submitHashes interactively prompts for commits to submit.
func submitHashes(b *Branch) []string {
// Get pending commits on b.
pending := b.Pending()
for _, c := range pending {
// Note that DETAILED_LABELS does not imply LABELS.
c.g, c.gerr = b.GerritChange(c, "CURRENT_REVISION", "LABELS", "DETAILED_LABELS")
if c.g == nil {
c.g = new(GerritChange)
}
}
// Construct submit script.
var script bytes.Buffer
for i := len(pending) - 1; i >= 0; i-- {
c := pending[i]
if c.g.ID == "" {
fmt.Fprintf(&script, "# change not on Gerrit:\n#")
} else if err := submitCheck(c.g); err != nil {
fmt.Fprintf(&script, "# %v:\n#", err)
}
formatCommit(&script, c, true)
}
fmt.Fprintf(&script, `
# The above commits will be submitted in order from top to bottom
# when you exit the editor.
#
# These lines can be re-ordered, removed, and commented out.
#
# If you remove all lines, the submit will be aborted.
`)
// Edit the script.
final := editor(script.String())
// Parse the final script.
var hashes []string
for _, line := range lines(final) {
line := strings.TrimSpace(line)
if len(line) == 0 || line[0] == '#' {
continue
}
if i := strings.Index(line, " "); i >= 0 {
line = line[:i]
}
hashes = append(hashes, line)
}
return hashes
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/reword.go
|
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
)
func cmdReword(args []string) {
flags.Usage = func() {
fmt.Fprintf(stderr(), "Usage: %s reword %s [commit...]\n",
progName, globalFlags)
exit(2)
}
flags.Parse(args)
args = flags.Args()
// Check that we understand the structure
// before we let the user spend time editing messages.
b := CurrentBranch()
pending := b.Pending()
if len(pending) == 0 {
dief("reword: no commits pending")
}
if b.Name == "HEAD" {
dief("reword: no current branch")
}
var last *Commit
for i := len(pending) - 1; i >= 0; i-- {
c := pending[i]
if last != nil && !c.HasParent(last.Hash) {
dief("internal error: confused about pending commit graph: parent %.7s vs %.7s", last.Hash, c.Parents)
}
last = c
}
headState := func() (head, branch string) {
head = trim(cmdOutput("git", "rev-parse", "HEAD"))
for _, line := range nonBlankLines(cmdOutput("git", "branch", "-l")) {
if strings.HasPrefix(line, "* ") {
branch = trim(line[1:])
return head, branch
}
}
dief("internal error: cannot find current branch")
panic("unreachable")
}
head, branch := headState()
if head != last.Hash {
dief("internal error: confused about pending commit graph: HEAD vs parent: %.7s vs %.7s", head, last.Hash)
}
if branch != b.Name {
dief("internal error: confused about pending commit graph: branch name %s vs %s", branch, b.Name)
}
// Build list of commits to be reworded.
// Do first, in case there are typos on the command line.
var cs []*Commit
newMsg := make(map[*Commit]string)
if len(args) == 0 {
for _, c := range pending {
cs = append(cs, c)
}
} else {
for _, arg := range args {
c := b.CommitByRev("reword", arg)
cs = append(cs, c)
}
}
for _, c := range cs {
newMsg[c] = ""
}
// Invoke editor to reword all the messages message.
// Save the edits to REWORD_MSGS immediately after editor exit
// in case we for some reason cannot apply the changes - don't want
// to throw away the user's writing.
// But we don't use REWORD_MSGS as the actual editor file,
// because if there are multiple git rewords happening
// (perhaps the user has forgotten about one in another window),
// we don't want them to step on each other during editing.
var buf bytes.Buffer
saveFile := filepath.Join(gitPathDir(), "REWORD_MSGS")
saveBuf := func() {
if err := os.WriteFile(saveFile, buf.Bytes(), 0666); err != nil {
dief("cannot save messages: %v", err)
}
}
saveBuf() // make sure it works before we let the user edit anything
printf("editing messages (new texts logged in %s in case of failure)", saveFile)
note := "edited messages saved in " + saveFile
if len(cs) == 1 {
c := cs[0]
edited := editor(c.Message)
if edited == "" {
dief("edited message is empty")
}
newMsg[c] = string(fixCommitMessage([]byte(edited)))
fmt.Fprintf(&buf, "# %s\n\n%s\n\n", c.Subject, edited)
saveBuf()
} else {
// Edit all at once.
var ed bytes.Buffer
ed.WriteString(rewordProlog)
byHash := make(map[string]*Commit)
for _, c := range cs {
if strings.HasPrefix(c.Message, "# ") || strings.Contains(c.Message, "\n# ") {
// Will break our framing.
// Should be pretty rare since 'git commit' and 'git commit --amend'
// delete lines beginning with # after editing sessions.
dief("commit %.7s has a message line beginning with # - cannot reword with other commits", c.Hash)
}
hash := c.Hash[:7]
byHash[hash] = c
// Two blank lines before #, one after.
// Lots of space to make it easier to see the boundaries
// between commit messages.
fmt.Fprintf(&ed, "\n\n# %s %s\n\n%s\n", hash, c.Subject, c.Message)
}
edited := editor(ed.String())
if edited == "" {
dief("edited text is empty")
}
// Save buffer for user before going further.
buf.WriteString(edited)
saveBuf()
for i, text := range strings.Split("\n"+edited, "\n# ") {
if i == 0 {
continue
}
text = "# " + text // restore split separator
// Pull out # hash header line and body.
hdr, body, _ := strings.Cut(text, "\n")
// Cut blank lines at start and end of body but keep newline-terminated.
for body != "" {
line, rest, _ := strings.Cut(body, "\n")
if line != "" {
break
}
body = rest
}
body = strings.TrimRight(body, " \t\n")
if body != "" {
body += "\n"
}
// Look up hash.
f := strings.Fields(hdr)
if len(f) < 2 {
dief("edited text has # line with no commit hash\n%s", note)
}
c := byHash[f[1]]
if c == nil {
dief("cannot find commit for header: %s\n%s", strings.TrimSpace(hdr), note)
}
newMsg[c] = string(fixCommitMessage([]byte(body)))
}
}
// Rebuild the commits the way git would,
// but without doing any git checkout that
// would affect the files in the working directory.
var newHash string
last = nil
for i := len(pending) - 1; i >= 0; i-- {
c := pending[i]
if (newMsg[c] == "" || newMsg[c] == c.Message) && newHash == "" {
// Have not started making changes yet. Leave exactly as is.
last = c
continue
}
// Rebuilding.
msg := newMsg[c]
if msg == "" {
msg = c.Message
}
if last != nil && newHash != "" && !c.HasParent(last.Hash) {
dief("internal error: confused about pending commit graph")
}
gitArgs := []string{"commit-tree", "-p"}
for _, p := range c.Parents {
if last != nil && newHash != "" && p == last.Hash {
p = newHash
}
gitArgs = append(gitArgs, p)
}
gitArgs = append(gitArgs, "-m", msg, c.Tree)
os.Setenv("GIT_AUTHOR_NAME", c.AuthorName)
os.Setenv("GIT_AUTHOR_EMAIL", c.AuthorEmail)
os.Setenv("GIT_AUTHOR_DATE", c.AuthorDate)
newHash = trim(cmdOutput("git", gitArgs...))
last = c
}
if newHash == "" {
// No messages changed.
return
}
// Attempt swap of HEAD but leave index and working copy alone.
// No obvious way to make it atomic, but check for races.
head, branch = headState()
if head != pending[0].Hash {
dief("cannot reword: commits changed underfoot\n%s", note)
}
if branch != b.Name {
dief("cannot reword: branch changed underfoot\n%s", note)
}
run("git", "reset", "--soft", newHash)
}
var rewordProlog = `Rewording multiple commit messages.
The # lines separate the different commits and must be left unchanged.
`
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/submit_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"os"
"runtime"
"strings"
"testing"
)
func TestSubmitErrors(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
t.Logf("> no commit")
testMainDied(t, "submit")
testPrintedStderr(t, "cannot submit: no changes pending")
write(t, gt.client+"/file1", "", 0644)
trun(t, gt.client, "git", "add", "file1")
trun(t, gt.client, "git", "commit", "-m", "msg\n\nDO NOT SUBMIT\n\nChange-Id: I123456789\n")
// Gerrit checks this too, but add a local check.
t.Logf("> do not submit")
testMainDied(t, "submit")
testPrintedStderr(t, "DO NOT SUBMIT")
trun(t, gt.client, "git", "commit", "--amend", "-m", "msg\n\nChange-Id: I123456789\n")
t.Logf("> staged changes")
write(t, gt.client+"/file1", "asdf", 0644)
trun(t, gt.client, "git", "add", "file1")
testMainDied(t, "submit")
testPrintedStderr(t, "cannot submit: staged changes exist",
"git status", "!git stash", "!git add", "git-codereview change")
testNoStdout(t)
t.Logf("> unstaged changes")
write(t, gt.client+"/file1", "actual content", 0644)
testMainDied(t, "submit")
testPrintedStderr(t, "cannot submit: unstaged changes exist",
"git status", "git stash", "git add", "git-codereview change")
testNoStdout(t)
testRan(t)
trun(t, gt.client, "git", "add", "file1")
trun(t, gt.client, "git", "commit", "--amend", "--no-edit")
t.Logf("> not found")
testMainDied(t, "submit")
testPrintedStderr(t, "change not found on Gerrit server")
const id = "I123456789"
t.Logf("> malformed json")
srv.setJSON(id, "XXX")
testMainDied(t, "submit")
testRan(t) // nothing
testPrintedStderr(t, "malformed json response")
t.Logf("> unexpected change status")
srv.setJSON(id, `{"status": "UNEXPECTED"}`)
testMainDied(t, "submit")
testRan(t) // nothing
testPrintedStderr(t, "cannot submit: unexpected Gerrit change status \"UNEXPECTED\"")
t.Logf("> already merged")
srv.setJSON(id, `{"status": "MERGED"}`)
testMainDied(t, "submit")
testRan(t) // nothing
testPrintedStderr(t, "cannot submit: change already submitted, run 'git sync'")
t.Logf("> abandoned")
srv.setJSON(id, `{"status": "ABANDONED"}`)
testMainDied(t, "submit")
testRan(t) // nothing
testPrintedStderr(t, "cannot submit: change abandoned")
t.Logf("> missing approval")
srv.setJSON(id, `{"status": "NEW", "labels": {"Code-Review": {}, "Color": {"Optional": true}}}`)
testMainDied(t, "submit")
testRan(t) // nothing
testPrintedStderr(t, "cannot submit: change missing Code-Review approval")
t.Logf("> rejection")
srv.setJSON(id, `{"status": "NEW", "labels": {"Code-Review": {"rejected": {}}}}`)
testMainDied(t, "submit")
testRan(t) // nothing
testPrintedStderr(t, "cannot submit: change has Code-Review rejection")
t.Logf("> submit with unexpected status")
const newJSON = `{"status": "NEW", "labels": {"Code-Review": {"approved": {}}}}`
srv.setJSON(id, newJSON)
srv.setReply("/a/changes/proj~main~I123456789/submit", gerritReply{body: ")]}'\n" + newJSON})
testMainDied(t, "submit")
testRan(t, "git push -q origin HEAD:refs/for/main")
testPrintedStderr(t, "submit error: unexpected post-submit Gerrit change status \"NEW\"")
}
func TestSubmitTimeout(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
gt.work(t)
setJSON := func(json string) {
srv.setReply("/a/changes/proj~main~I123456789", gerritReply{body: ")]}'\n" + json})
}
t.Log("> submit with timeout")
const submittedJSON = `{"status": "SUBMITTED", "mergeable": true, "labels": {"Code-Review": {"approved": {}}}}`
setJSON(submittedJSON)
srv.setReply("/a/changes/proj~main~I123456789/submit", gerritReply{body: ")]}'\n" + submittedJSON})
testMainDied(t, "submit")
testRan(t, "git push -q origin HEAD:refs/for/main")
testPrintedStderr(t, "cannot submit: timed out waiting for change to be submitted by Gerrit")
}
func TestSubmit(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
gt.work(t)
trun(t, gt.client, "git", "tag", "-f", "work.mailed")
clientHead := strings.TrimSpace(trun(t, gt.client, "git", "log", "-n", "1", "--format=format:%H"))
write(t, gt.server+"/file", "another change", 0644)
trun(t, gt.server, "git", "add", "file")
trun(t, gt.server, "git", "commit", "-m", "conflict")
serverHead := strings.TrimSpace(trun(t, gt.server, "git", "log", "-n", "1", "--format=format:%H"))
t.Log("> submit")
var (
newJSON = `{"status": "NEW", "mergeable": true, "current_revision": "` + clientHead + `", "labels": {"Code-Review": {"approved": {}}}}`
submittedJSON = `{"status": "SUBMITTED", "mergeable": true, "current_revision": "` + clientHead + `", "labels": {"Code-Review": {"approved": {}}}}`
mergedJSON = `{"status": "MERGED", "mergeable": true, "current_revision": "` + serverHead + `", "labels": {"Code-Review": {"approved": {}}}}`
)
submitted := false
npoll := 0
srv.setReply("/a/changes/proj~main~I123456789", gerritReply{f: func() gerritReply {
if !submitted {
return gerritReply{body: ")]}'\n" + newJSON}
}
if npoll++; npoll <= 2 {
return gerritReply{body: ")]}'\n" + submittedJSON}
}
return gerritReply{body: ")]}'\n" + mergedJSON}
}})
srv.setReply("/a/changes/proj~main~I123456789/submit", gerritReply{f: func() gerritReply {
if submitted {
return gerritReply{status: 409}
}
submitted = true
return gerritReply{body: ")]}'\n" + submittedJSON}
}})
testMain(t, "submit", "-n")
testPrintedStderr(t, "submitting")
testPrintedStderr(t, "stopped before submit")
testMain(t, "pending", "-c", "-l")
testPrintedStdout(t, "(current branch)")
testPrintedStdout(t, "Files in this change:")
testMain(t, "submit")
testRan(t,
"git fetch -q",
"git checkout -q -B work "+serverHead+" --")
}
func TestSubmitMultiple(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
cl1, cl2 := testSubmitMultiple(t, gt, srv)
testMain(t, "submit", cl1.CurrentRevision, cl2.CurrentRevision)
}
func TestSubmitMultipleNamed(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
_, _ = testSubmitMultiple(t, gt, srv)
testMain(t, "submit", "HEAD^", "HEAD")
}
func TestSubmitInteractive(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("see golang.org/issue/13406")
}
gt := newGitTest(t)
defer gt.done()
os.Setenv("GIT_EDITOR", ":")
testMain(t, "submit", "-i")
testPrintedStderr(t, "nothing to submit")
srv := newGerritServer(t)
defer srv.done()
cl1, cl2 := testSubmitMultiple(t, gt, srv)
os.Setenv("GIT_EDITOR", "echo > ")
testMain(t, "submit", "-i")
if cl1.Status != "NEW" {
t.Fatalf("want cl1.Status == NEW; got %v", cl1.Status)
}
if cl2.Status != "NEW" {
t.Fatalf("want cl2.Status == NEW; got %v", cl2.Status)
}
os.Setenv("GIT_EDITOR", "( echo "+cl1.CurrentRevision+"; echo; echo '# comment' ) > ")
testMain(t, "submit", "-i")
if cl1.Status != "MERGED" {
t.Fatalf("want cl1.Status == MERGED; got %v", cl1.Status)
}
if cl2.Status != "NEW" {
t.Fatalf("want cl2.Status == NEW; got %v", cl2.Status)
}
}
func testSubmitMultiple(t *testing.T, gt *gitTest, srv *gerritServer) (*GerritChange, *GerritChange) {
write(t, gt.client+"/file1", "", 0644)
trun(t, gt.client, "git", "add", "file1")
trun(t, gt.client, "git", "commit", "-m", "msg\n\nChange-Id: I0000001\n")
hash1 := strings.TrimSpace(trun(t, gt.client, "git", "log", "-n", "1", "--format=format:%H"))
write(t, gt.client+"/file2", "", 0644)
trun(t, gt.client, "git", "add", "file2")
trun(t, gt.client, "git", "commit", "-m", "msg\n\nChange-Id: I0000002\n")
hash2 := strings.TrimSpace(trun(t, gt.client, "git", "log", "-n", "1", "--format=format:%H"))
testMainDied(t, "submit")
testPrintedStderr(t, "cannot submit: multiple changes pending")
cl1 := GerritChange{
Status: "NEW",
CurrentRevision: hash1,
Labels: map[string]*GerritLabel{"Code-Review": {Approved: new(GerritAccount)}},
}
cl2 := GerritChange{
Status: "NEW",
CurrentRevision: hash2,
Labels: map[string]*GerritLabel{"Code-Review": {Approved: new(GerritAccount)}},
}
srv.setReply("/a/changes/proj~main~I0000001", gerritReply{f: func() gerritReply {
return gerritReply{json: cl1}
}})
srv.setReply("/a/changes/proj~main~I0000001/submit", gerritReply{f: func() gerritReply {
if cl1.Status != "NEW" {
return gerritReply{status: 409}
}
cl1.Status = "MERGED"
return gerritReply{json: cl1}
}})
srv.setReply("/a/changes/proj~main~I0000002", gerritReply{f: func() gerritReply {
return gerritReply{json: cl2}
}})
srv.setReply("/a/changes/proj~main~I0000002/submit", gerritReply{f: func() gerritReply {
if cl2.Status != "NEW" {
return gerritReply{status: 409}
}
cl2.Status = "MERGED"
return gerritReply{json: cl2}
}})
return &cl1, &cl2
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/change.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
)
var commitMsg string
var changeAuto bool
var changeQuick bool
var changeSignoff bool
func cmdChange(args []string) {
// NOTE: New flags should be added to the usage message below as well as doc.go.
flags.StringVar(&commitMsg, "m", "", "specify a commit message")
flags.BoolVar(&changeAuto, "a", false, "add changes to any tracked files")
flags.BoolVar(&changeQuick, "q", false, "do not edit pending commit msg")
flags.BoolVar(&changeSignoff, "s", false, "add a Signed-off-by trailer at the end of the commit message")
flags.Parse(args)
if len(flags.Args()) > 1 {
fmt.Fprintf(stderr(), "Usage: %s change %s [-a] [-m msg] [-q] [branch]\n", progName, globalFlags)
exit(2)
}
if _, err := cmdOutputErr("git", "rev-parse", "--abbrev-ref", "MERGE_HEAD"); err == nil {
diePendingMerge("change")
}
// Note: A rebase with a conflict + rebase --continue sometimes leaves behind REBASE_HEAD.
// So check for the rebase-merge directory instead, which it does a better job cleaning up.
if _, err := os.Stat(filepath.Join(gitPathDir(), "rebase-merge")); err == nil {
dief("cannot change: found pending rebase or sync")
}
// Checkout or create branch, if specified.
target := flags.Arg(0)
if target != "" {
checkoutOrCreate(target)
b := CurrentBranch()
if HasStagedChanges() && !b.HasPendingCommit() {
commitChanges(false)
}
b.check()
return
}
// Create or amend change commit.
b := CurrentBranch()
amend := b.HasPendingCommit()
if amend {
// Dies if there is not exactly one commit.
b.DefaultCommit("amend change", "")
}
commitChanges(amend)
b.loadedPending = false // force reload after commitChanges
b.check()
}
func (b *Branch) check() {
staged, unstaged, _ := LocalChanges()
if len(staged) == 0 && len(unstaged) == 0 {
// No staged changes, no unstaged changes.
// If the branch is behind upstream, now is a good time to point that out.
// This applies to both local work branches and tracking branches.
b.loadPending()
if n := b.CommitsBehind(); n > 0 {
printf("warning: %d commit%s behind %s; run 'git codereview sync' to update.", n, suffix(n, "s"), b.OriginBranch())
}
}
}
var testCommitMsg string
func commitChanges(amend bool) {
// git commit will run the gofmt hook.
// Run it now to give a better error (won't show a git commit command failing).
hookGofmt()
if HasUnstagedChanges() && !HasStagedChanges() && !changeAuto {
printf("warning: unstaged changes and no staged changes; use 'git add' or 'git change -a'")
}
commit := func(amend bool) {
args := []string{"commit", "-q", "--allow-empty"}
if amend {
args = append(args, "--amend")
if changeQuick {
args = append(args, "--no-edit")
}
}
if commitMsg != "" {
args = append(args, "-m", commitMsg)
} else if testCommitMsg != "" {
args = append(args, "-m", testCommitMsg)
}
if changeAuto {
args = append(args, "-a")
}
if changeSignoff {
args = append(args, "-s")
}
run("git", args...)
}
commit(amend)
for !commitMessageOK() {
fmt.Print("re-edit commit message (y/n)? ")
if !scanYes() {
break
}
commit(true)
}
printf("change updated.")
}
func checkoutOrCreate(target string) {
// If it's a valid Gerrit number CL or CL/PS or GitHub pull request number PR,
// checkout the CL or PR.
cl, ps, isCL := parseCL(target)
if isCL {
what := "CL"
if !haveGerrit() && haveGitHub() {
what = "PR"
if ps != "" {
dief("change PR syntax is NNN not NNN.PP")
}
}
if what == "CL" && !haveGerrit() {
dief("cannot change to a CL without gerrit")
}
if HasStagedChanges() || HasUnstagedChanges() {
dief("cannot change to a %s with uncommitted work", what)
}
checkoutCL(what, cl, ps)
return
}
if strings.ToUpper(target) == "HEAD" {
// Git gets very upset and confused if you 'git change head'
// on systems with case-insensitive file names: the branch
// head conflicts with the usual HEAD.
dief("invalid branch name %q: ref name HEAD is reserved for git.", target)
}
// If local branch exists, check it out.
for _, b := range LocalBranches() {
if b.Name == target {
run("git", "checkout", "-q", target)
printf("changed to branch %v.", target)
return
}
}
// If origin branch exists, create local branch tracking it.
for _, name := range OriginBranches() {
if name == "origin/"+target {
run("git", "checkout", "-q", "-t", "-b", target, name)
printf("created branch %v tracking %s.", target, name)
return
}
}
// Otherwise, this is a request to create a local work branch.
// Check for reserved names. We take everything with a dot.
if strings.Contains(target, ".") {
dief("invalid branch name %v: branch names with dots are reserved for git-codereview.", target)
}
// If the current branch has a pending commit, building
// on top of it will not help. Don't allow that.
// Otherwise, inherit branchpoint and upstream from the current branch.
b := CurrentBranch()
branchpoint := "HEAD"
if b.HasPendingCommit() {
fmt.Fprintf(stderr(), "warning: pending changes on %s are not copied to new branch %s\n", b.Name, target)
branchpoint = b.Branchpoint()
}
origin := b.OriginBranch()
// NOTE: This is different from git checkout -q -t -b origin,
// because the -t wold use the origin directly, and that may be
// ahead of the current directory. The goal of this command is
// to create a new branch for work on the current directory,
// not to incorporate new commits at the same time (use 'git sync' for that).
// The ideal is that HEAD doesn't change at all.
// In the absence of pending commits, that ideal is achieved.
// But if there are pending commits, it'd be too confusing to have them
// on two different work branches, so we drop them and use the
// branchpoint they started from (after warning above), moving HEAD
// as little as possible.
run("git", "checkout", "-q", "-b", target, branchpoint)
run("git", "branch", "-q", "--set-upstream-to", origin)
printf("created branch %v tracking %s.", target, origin)
}
// Checkout the patch set of the given CL. When patch set is empty, use the latest.
func checkoutCL(what, cl, ps string) {
if what == "CL" && ps == "" {
change, err := readGerritChange(cl + "?o=CURRENT_REVISION")
if err != nil {
dief("cannot change to CL %s: %v", cl, err)
}
rev, ok := change.Revisions[change.CurrentRevision]
if !ok {
dief("cannot change to CL %s: invalid current revision from gerrit", cl)
}
ps = strconv.Itoa(rev.Number)
}
var ref string
if what == "CL" {
var group string
if len(cl) > 1 {
group = cl[len(cl)-2:]
} else {
group = "0" + cl
}
cl = fmt.Sprintf("%s/%s", cl, ps)
ref = fmt.Sprintf("refs/changes/%s/%s", group, cl)
} else {
ref = fmt.Sprintf("pull/%s/head", cl)
}
err := runErr("git", "fetch", "-q", "origin", ref)
if err != nil {
dief("cannot change to %v %s: %v", what, cl, err)
}
err = runErr("git", "checkout", "-q", "FETCH_HEAD")
if err != nil {
dief("cannot change to %s %s: %v", what, cl, err)
}
if *noRun {
return
}
subject, err := trimErr(cmdOutputErr("git", "log", "--format=%s", "-1"))
if err != nil {
printf("changed to %s %s.", what, cl)
dief("cannot read change subject from git: %v", err)
}
printf("changed to %s %s.\n\t%s", what, cl, subject)
}
var parseCLRE = regexp.MustCompile(`^([0-9]+)(?:/([0-9]+))?$`)
// parseCL validates and splits the CL number and patch set (if present).
func parseCL(arg string) (cl, patchset string, ok bool) {
m := parseCLRE.FindStringSubmatch(arg)
if len(m) == 0 {
return "", "", false
}
return m[1], m[2], true
}
var messageRE = regexp.MustCompile(`^(\[[a-zA-Z0-9.-]+\] )?[a-zA-Z0-9-_/,. ]+: `)
func commitMessageOK() bool {
body := cmdOutput("git", "log", "--format=format:%B", "-n", "1")
ok := true
if !messageRE.MatchString(body) {
fmt.Print(commitMessageWarning)
ok = false
}
return ok
}
const commitMessageWarning = `
Your CL description appears not to use the standard form.
The first line of your change description is conventionally a one-line summary
of the change, prefixed by the primary affected package, and is used as the
subject for code review mail; the rest of the description elaborates.
Examples:
encoding/rot13: new package
math: add IsInf, IsNaN
net: fix cname in LookupHost
unicode: update to Unicode 5.0.2
`
func scanYes() bool {
var s string
fmt.Scan(&s)
return strings.HasPrefix(strings.ToLower(s), "y")
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/doc.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Git-codereview manages the code review process for Git changes using a Gerrit
server.
The git-codereview tool manages “change branches” in the local git repository.
Each such branch tracks a single commit, or “pending change”,
that is reviewed using a Gerrit server; the Gerrit remote must be
named “origin” in the local git repo.
Modifications to the pending change are applied by amending the commit.
This process implements the “single-commit feature branch” model.
Creating multiple-commit feature branches, for example to break a large
change into a reviewable sequence, is also supported; see the discussion below.
Each local git branch is expected to have a configured upstream branch on the server.
For example, for a local “work” branch, .git/config might contain:
[branch "work"]
remote = origin
merge = refs/heads/main
to instruct git itself that the local “work” branch tracks the upstream “main” branch.
Git-codereview inspects this setting, which is referred to as “upstream” below.
If upstream is not configured, which can happen when using checkouts managed by
very old versions of git-codereview or other tools, git-codereview initializes upstream
to “main” if that branch exists, or else “master”.
Once installed as git-codereview, the tool's commands are available through git
either by running
git codereview <command>
or, if aliases are installed, as
git <command>
The review tool's command names do not conflict with any extant git commands.
This document uses the first form for clarity, but most users install these
aliases in their .gitconfig file:
[alias]
change = codereview change
gofmt = codereview gofmt
mail = codereview mail
pending = codereview pending
rebase-work = codereview rebase-work
reword = codereview reword
submit = codereview submit
sync = codereview sync
sync-branch = codereview sync-branch
# Single-Commit Work Branches
For simple, unrelated changes, the typical usage of the git-codereview tool
is to place each pending change in its own Git branch.
In this workflow, the work branch contains
either no pending change beyond upstream (when there's no local work)
or exactly one pending change beyond upstream (the change being developed).
When there is no pending change on the work branch,
“git codereview change” creates one by running “git commit”.
Otherwise, when there is already a pending change,
“git codereview change” revises it by running “git commit --amend”.
The “git codereview mail” and “git codereview submit” commands
implicitly operate on the lone pending change.
# Multiple-Commit Work Branches
Of course, it is not always feasible to put each pending change in a separate branch.
A sequence of changes that build on one another is more easily
managed as multiple commits on a single branch, and the git-codereview tool
supports this workflow as well.
To add a new pending change, invoke “git commit” directly,
instead of “git codereview change”.
The git-codereview tool adjusts its behavior when there are
multiple pending changes.
The “git codereview change” command amends the top commit in the stack (HEAD).
To amend a commit further down the stack, use Git's rebase support,
for example by using “git commit --fixup” followed by “git codereview rebase-work”.
The “git codereview mail” command requires an explicit revision argument,
but note that since “git codereview mail” is implemented as a “git push”,
any commits earlier in the stack are necessarily also mailed.
The “git codereview submit” command also requires an explicit revision argument,
and while earlier commits are necessarily still uploaded and mailed,
only the named revision or revisions are submitted (merged into upstream).
In a single-commit work branch, a successful “git codereview submit”
effectively runs “git codereview sync” automatically.
In a multiple-commit work branch, it does not, because
the implied “git rebase” may conflict with the remaining pending commits.
Instead it is necessary to run “git codereview sync” explicitly
(when ready) after “git codereview submit”.
# Reusing Work Branches
Although one common practice is to create a new branch for each pending change,
running “git codereview submit” (and possibly “git codereview sync”)
leaves the current branch ready for reuse with a future change.
Some developers find it helpful to create a single work branch
(“git change work”) and then do all work in that branch,
possibly in the multiple-commit mode, never changing between branches.
# Commands
All commands accept these global flags:
The -n flag prints all commands that would be run, but does not run them.
The -v flag prints all commands that make changes. Multiple occurrences
trigger more verbosity in some commands, including sync.
These are omitted from the per-command descriptions below.
# Branchpoint
The branchpoint command prints the commit hash of the most recent commit
on the current branch that is shared with the Gerrit server.
git codereview branchpoint
This commit is the point where local work branched from the published tree.
The command is intended mainly for use in scripts. For example,
“git diff $(git codereview branchpoint)” or
“git log $(git codereview branchpoint)..HEAD”.
# Change
The change command creates and moves between Git branches and maintains the
pending changes on work branches.
git codereview change [-a] [-q] [-m <message>] [branchname]
Given a branch name as an argument, the change command switches to the named
branch, creating it if necessary. If the branch is created and there are staged
changes, it will commit the changes to the branch, creating a new pending
change.
With no argument, the change command creates a new pending change from the
staged changes in the current branch or, if there is already a pending change,
amends that change.
The -q option skips the editing of an extant pending change's commit message.
If -m is present, -q is ignored.
The -a option automatically adds any unstaged edits in tracked files during
commit; it is equivalent to the 'git commit' -a option.
The -m option specifies a commit message and skips the editor prompt. This
option is only useful when creating commits (e.g. if there are unstaged
changes). If a commit already exists, it is overwritten. If -q is also
present, -q will be ignored.
The -s option adds a Signed-off-by trailer at the end of the commit message;
it is equivalent to the 'git commit' -s option.
As a special case, if branchname is a decimal CL number, such as 987, the change
command downloads the latest patch set of that CL from the server and switches to it.
A specific patch set P can be requested by adding /P: 987.2 for patch set 2 of CL 987.
If the origin server is GitHub instead of Gerrit, then the number is
treated a GitHub pull request number, and the change command downloads the latest
version of that pull request. In this case, the /P suffix is disallowed.
# Gofmt
The gofmt command applies the gofmt program to all files modified in the
current work branch, both in the staging area (index) and the working tree
(local directory).
git codereview gofmt [-l]
The -l option causes the command to list the files that need reformatting but
not reformat them. Otherwise, the gofmt command reformats modified files in
place. That is, files in the staging area are reformatted in the staging area,
and files in the working tree are reformatted in the working tree.
# Help
The help command displays basic usage instructions.
git codereview help
# Hooks
The hooks command installs the Git hooks to enforce code review conventions.
git codereview hooks
The pre-commit hook checks that all Go code is formatted with gofmt and that
the commit is not being made directly to a branch with the same name as the
upstream branch.
The commit-msg hook adds the Gerrit “Change-Id” line to the commit message if
not present. It also checks that the message uses the convention established by
the Go project that the first line has the form, pkg/path: summary.
The hooks command will not overwrite an existing hook.
This hook installation is also done at startup by all other git codereview
commands, except “git codereview help”.
# Hook-Invoke
The hook-invoke command is an internal command that invokes the named Git hook.
git codereview hook-invoke <hook> [args]
It is run by the shell scripts installed by the “git codereview hooks” command.
# Mail
The mail command starts the code review process for the pending change.
git codereview mail [-r email,...] [-cc email,...]
[-autosubmit] [-diff] [-f] [-hashtag tag,...]
[-nokeycheck] [-topic topic] [-trybot] [-wip]
[revision]
It pushes the pending change commit in the current branch to the Gerrit code
review server and prints the URL for the change on the server.
If the change already exists on the server, the mail command updates that
change with a new changeset.
If there are multiple pending commits, the revision argument is mandatory.
If no revision is specified, the mail command prints a short summary of
the pending commits for use in deciding which to mail.
If any commit that would be pushed to the server contains the text
“DO NOT MAIL” (case insensitive) in its commit message, the mail command
will refuse to send the commit to the server.
The -r and -cc flags identify the email addresses of people to do the code
review and to be CC'ed about the code review.
Multiple addresses are given as a comma-separated list.
An email address passed to -r or -cc can be shortened from name@domain to name.
The mail command resolves such shortenings by reading the list of past reviewers
from the git repository log to find email addresses of the form name@somedomain
and then, in case of ambiguity, using the reviewer who appears most often.
The -diff flag shows a diff of the named revision compared against the latest
upstream commit incorporated into the local branch.
The -f flag forces mail to proceed even if there are staged changes that have
not been committed. By default, mail fails in that case.
The -nokeycheck flag disables the Gerrit server check for committed files
containing data that looks like public keys. (The most common time -nokeycheck
is needed is when checking in test cases for cryptography libraries.)
The -trybot flag sets a Commit-Queue+1 vote on any uploaded changes.
The Go project uses this vote to start running integration tests on the CL.
During the transition between two CI systems, the environment variable
GIT_CODEREVIEW_TRYBOT can be set to one of "luci", "farmer", or "both"
to explicitly override where the -trybot flag starts integration tests.
The -autosubmit flag sets a Auto-Submit+1 vote on any uploaded changes.
The -wip flag marks any uploaded changes as work-in-progress.
The mail command updates the tag <branchname>.mailed to refer to the
commit that was most recently mailed, so running “git diff <branchname>.mailed”
shows diffs between what is on the Gerrit server and the current directory.
# Pending
The pending command prints to standard output the status of all pending changes
and staged, unstaged, and untracked files in the local repository.
git codereview pending [-c] [-l] [-s]
The -c flag causes the command to show pending changes only on the current branch.
The -l flag causes the command to use only locally available information.
By default, it fetches recent commits and code review information from the
Gerrit server.
The -s flag causes the command to print abbreviated (short) output.
Useful aliases include “git p” for “git pending” and “git pl” for “git pending -l”
(notably faster but without Gerrit information).
# Rebase-work
The rebase-work command runs git rebase in interactive mode over pending changes.
git codereview rebase-work
The command is shorthand for “git rebase -i $(git codereview branchpoint)”.
It differs from plain “git rebase -i” in that the latter will try to incorporate
new commits from the origin branch during the rebase;
“git codereview rebase-work” does not.
In multiple-commit workflows, rebase-work is used so often that it can be helpful
to alias it to “git rw”.
# Reword
The reword command edits pending commit messages.
git codereview reword [commit...]
Reword opens the editor on the commit messages for the named comments.
When the editing is finished, it applies the changes to the pending commits.
If no commit is listed, reword applies to all pending commits.
Reword is similar in effect to running “git codereview rebase-work” and changing
the script action for the named commits to “reword”, or (with no arguments)
to “git commit --amend”, but it only affects the commit messages, not the state
of the git staged index, nor any checked-out files. This more careful implementation
makes it safe to use when there are local changes or, for example, when tests are
running that would be broken by temporary changes to the checked-out tree,
as would happen during “git codereview rebase-work”.
Reword is most useful for editing commit messages on a multiple-commit work
branch, but it can also be useful in single-commit work branches to allow
editing a commit message without committing staged changes at the same time.
# Submit
The submit command pushes the pending change to the Gerrit server and tells
Gerrit to submit it to the upstream branch.
git codereview submit [-i | revision...]
The command fails if there are modified files (staged or unstaged) that are not
part of the pending change.
The -i option causes the submit command to open a list of commits to submit
in the configured text editor, similar to “git rebase -i”.
If multiple revisions are specified, the submit command submits each one in turn,
stopping at the first failure.
When run in a multiple-commit work branch,
either the -i option or the revision argument is mandatory.
If both are omitted, the submit command prints a short summary of
the pending commits for use in deciding which to submit.
After submitting the pending changes, the submit command tries to synchronize the
current branch to the submitted commit, if it can do so cleanly.
If not, it will prompt the user to run “git codereview sync” manually.
After a successful sync, the branch can be used to prepare a new change.
# Sync
The sync command updates the local repository.
git codereview sync
It fetches commits from the remote repository and merges them from the
upstream branch to the current branch, rebasing any pending changes.
# Sync-branch
The sync-branch command merges changes from the parent branch into
the current branch.
git codereview sync-branch
There must be no pending work in the current checkout. Sync-branch pulls
all commits from the parent branch to the current branch and creates a
merge commit. If there are merge conflicts, sync-branch reports those
conflicts and exits. After fixing the conflicts, running
git codereview sync-branch -continue
will continue the process. (If the merge should be abandoned, use
the standard “git merge -abort” command instead.)
The sync-branch command depends on the codereview.cfg having
branch and parent-branch keys. See the Configuration section below.
When a server-side development branch is being shut down and
the changes should be merged back into the parent branch, the command
git codereview sync-branch -merge-back-to-parent
runs the merge in reverse. This is a very rare operation and should not
be used unless you are certain that you want changes to flow in the
reverse direction, because work on the dev branch has been ended.
After running this command, the local checkout of the dev branch will
be configured to mail changes to the parent branch instead of the
dev branch.
# Configuration
If a file named codereview.cfg is present in the repository root,
git-codereview will use it for configuration. It should contain lines
of this format:
key: value
The “gerrit” key sets the Gerrit URL for this project. Git-codereview
automatically derives the Gerrit URL from repositories hosted in
*.googlesource.com. If not set or derived, the repository is assumed to
not have Gerrit, and certain features won't work.
The “issuerepo” key specifies the GitHub repository to use for issues,
if different from the source repository. If set to “golang/go”, for example,
lines such as “Fixes #123” in a commit message will be rewritten to
“Fixes golang/go#123”.
The “branch” key specifies the name of the branch on the origin server
corresponding to the current checkout. If this setting is missing, git-codereview
uses the name of the remote branch that the current checkout is tracking.
If that setting is missing, git-codereview uses “main”.
The “parent-branch” key specifies the name of the parent branch on
the origin server. The parent branch is the branch from which the current
pulls regular updates. For example the parent branch of “dev.feature”
would typically be “main”, in which case it would have this codereview.cfg:
branch: dev.feature
parent-branch: main
In a more complex configuration, one feature branch might depend upon
another, like “dev.feature2” containing follow-on work for “dev.feature”,
neither of which has merged yet. In this case, the dev.feature2 branch
would have this codereview.cfg:
branch: dev.feature2
parent-branch: dev.feature
The parent branch setting is used by the sync-branch command.
*/
package main
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/mail_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"testing"
)
func TestMail(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
h := CurrentBranch().Pending()[0].ShortHash
// fake auth information to avoid Gerrit error
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
testMain(t, "mail")
testRan(t,
"git push -q origin HEAD:refs/for/main",
"git tag --no-sign -f work.mailed "+h)
}
func TestDoNotMail(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
trun(t, gt.client, "git", "commit", "--amend", "-m", "This is my commit.\n\nDO NOT MAIL\n")
testMainDied(t, "mail")
testPrintedStderr(t, "DO NOT MAIL")
trun(t, gt.client, "git", "commit", "--amend", "-m", "fixup! This is my commit.")
testMainDied(t, "mail")
testPrintedStderr(t, "fixup! commit")
trun(t, gt.client, "git", "commit", "--amend", "-m", "squash! This is my commit.")
testMainDied(t, "mail")
testPrintedStderr(t, "squash! commit")
trun(t, gt.client, "git", "commit", "--amend", "-m", "This is my commit.\n\nDO NOT MAIL\n")
// Do not mail even when the DO NOT MAIL is a parent of the thing we asked to mail.
gt.work(t)
testMainDied(t, "mail", "HEAD")
testPrintedStderr(t, "DO NOT MAIL")
}
func TestDoNotMailTempFiles(t *testing.T) {
// fake auth information to avoid Gerrit error
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
testFile := func(file string) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
gt.workFile(t, file)
testMainDied(t, "mail", "HEAD")
testPrintedStderr(t, "cannot mail temporary")
}
testFile("vim-backup.go~")
testFile("#emacs-auto-save.go#")
testFile(".#emacs-lock.go")
// Do not mail when a parent of the thing we asked to mail has temporary files.
gt := newGitTest(t)
defer gt.done()
gt.work(t)
gt.workFile(t, "backup~")
gt.work(t)
testMainDied(t, "mail", "HEAD")
testPrintedStderr(t, "cannot mail temporary")
}
func TestMailNonPrintables(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
// fake auth information to avoid Gerrit error
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
trun(t, gt.client, "git", "commit", "--amend", "-m", "This is my commit.\x10\n\n")
testMainDied(t, "mail")
testPrintedStderr(t, "message with non-printable")
// This should be mailed.
trun(t, gt.client, "git", "commit", "--amend", "-m", "Printable unicode: \u263A \u0020. Spaces: \v \f \r \t\n\n")
testMain(t, "mail", "HEAD")
}
func TestMailGitHub(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
trun(t, gt.client, "git", "config", "remote.origin.url", "https://github.com/golang/go")
testMainDied(t, "mail")
testPrintedStderr(t, "git origin must be a Gerrit host, not GitHub: https://github.com/golang/go")
}
func TestMailAmbiguousRevision(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
t.Logf("creating file that conflicts with revision parameter")
b := CurrentBranch()
mkdir(t, gt.client+"/origin")
write(t, gt.client+"/"+b.Branchpoint()+"..HEAD", "foo", 0644)
testMain(t, "mail", "-diff")
}
func TestMailMultiple(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
gt.work(t)
gt.work(t)
gt.work(t)
testMainDied(t, "mail")
testPrintedStderr(t, "cannot mail: multiple changes pending")
// Mail first two and test non-HEAD mail.
h := CurrentBranch().Pending()[1].ShortHash
testMain(t, "mail", "HEAD^")
testRan(t,
"git push -q origin "+h+":refs/for/main",
"git tag --no-sign -f work.mailed "+h)
// Mail HEAD.
h = CurrentBranch().Pending()[0].ShortHash
testMain(t, "mail", "HEAD")
testRan(t,
"git push -q origin HEAD:refs/for/main",
"git tag --no-sign -f work.mailed "+h)
}
var reviewerLog = []string{
"Fake 1 <r1@fake.com>",
"Fake 1 <r1@fake.com>",
"Fake 1 <r1@fake.com>",
"Reviewer 1 <r1@golang.org>",
"Reviewer 1 <r1@golang.org>",
"Reviewer 1 <r1@golang.org>",
"Reviewer 1 <r1@golang.org>",
"Reviewer 1 <r1@golang.org>",
"Other <other@golang.org>",
"<anon@golang.org>",
"Reviewer 2 <r2@new.example>",
"Reviewer 2 <r2@old.example>",
"Reviewer 2 <r2@old.example>",
"Reviewer 2 <r2@old.example>",
}
func TestMailShort(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// fake auth information to avoid Gerrit error
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
// Seed commit history with reviewers.
for i, addr := range reviewerLog {
write(t, gt.server+"/file", fmt.Sprintf("v%d", i), 0644)
trun(t, gt.server, "git", "commit", "-a", "-m", "msg\n\nReviewed-by: "+addr+"\n")
}
trun(t, gt.client, "git", "pull")
// Do some work.
gt.work(t)
h := CurrentBranch().Pending()[0].ShortHash
testMain(t, "mail")
testRan(t,
"git push -q origin HEAD:refs/for/main",
"git tag --no-sign -f work.mailed "+h)
testMain(t, "mail", "-r", "r1")
testRan(t,
"git push -q origin HEAD:refs/for/main%r=r1@golang.org",
"git tag --no-sign -f work.mailed "+h)
testMain(t, "mail", "-r", "other,anon", "-cc", "r1,full@email.com")
testRan(t,
"git push -q origin HEAD:refs/for/main%r=other@golang.org,r=anon@golang.org,cc=r1@golang.org,cc=full@email.com",
"git tag --no-sign -f work.mailed "+h)
testMainDied(t, "mail", "-r", "other", "-r", "anon,r1,missing")
testPrintedStderr(t, "unknown reviewer: missing")
// Test shortOptOut.
orig := shortOptOut
defer func() { shortOptOut = orig }()
shortOptOut = map[string]bool{"r2@old.example": true}
testMain(t, "mail", "-r", "r2")
testRan(t,
"git push -q origin HEAD:refs/for/main%r=r2@new.example",
"git tag --no-sign -f work.mailed "+h)
}
func TestWIP(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
h := CurrentBranch().Pending()[0].ShortHash
testMain(t, "mail", "-wip")
testRan(t,
"git push -q origin HEAD:refs/for/main%wip",
"git tag --no-sign -f work.mailed "+h)
}
func TestMailTopic(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
h := CurrentBranch().Pending()[0].ShortHash
// fake auth information to avoid Gerrit error
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
testMainDied(t, "mail", "-topic", "contains,comma")
testPrintedStderr(t, "topic may not contain a comma")
testMain(t, "mail", "-topic", "test-topic")
testRan(t,
"git push -q origin HEAD:refs/for/main%topic=test-topic",
"git tag --no-sign -f work.mailed "+h)
}
func TestMailHashtag(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
h := CurrentBranch().Pending()[0].ShortHash
// fake auth information to avoid Gerrit error
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
testMain(t, "mail", "-hashtag", "test1,test2")
testRan(t,
"git push -q origin HEAD:refs/for/main%hashtag=test1,hashtag=test2",
"git tag --no-sign -f work.mailed "+h)
testMain(t, "mail", "-hashtag", "")
testRan(t,
"git push -q origin HEAD:refs/for/main",
"git tag --no-sign -f work.mailed "+h)
testMainDied(t, "mail", "-hashtag", "test1,,test3")
testPrintedStderr(t, "hashtag may not contain empty tags")
}
func TestMailEmpty(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// fake auth information to avoid Gerrit error
auth.initialized = true
auth.host = "gerrit.fake"
auth.user = "not-a-user"
defer func() {
auth.initialized = false
auth.host = ""
auth.user = ""
}()
testMain(t, "change", "work")
testRan(t, "git checkout -q -b work HEAD",
"git branch -q --set-upstream-to origin/main")
t.Logf("creating empty change")
testCommitMsg = "foo: this commit will be empty"
testMain(t, "change")
testRan(t, "git commit -q --allow-empty -m foo: this commit will be empty")
h := CurrentBranch().Pending()[0].ShortHash
testMainDied(t, "mail")
testPrintedStderr(t, "cannot mail: commit "+h+" is empty")
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/reword_test.go
|
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"os"
"strings"
"testing"
)
func TestReword(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t)
gt.work(t)
gt.work(t)
trun(t, gt.client, "git", "tag", "MSG3")
gt.work(t)
trun(t, gt.client, "git", "tag", "MSG4")
const fakeName = "Grace R. Emlin"
os.Setenv("GIT_AUTHOR_NAME", fakeName)
gt.work(t)
os.Unsetenv("GIT_AUTHOR_NAME")
write(t, gt.client+"/file", "pending work", 0644) // would make git checkout unhappy
testMainDied(t, "rebase-work")
testNoStdout(t)
testPrintedStderr(t, "cannot rebase with uncommitted work")
os.Setenv("GIT_EDITOR", "sed -i.bak -e s/msg/MESSAGE/")
defer os.Unsetenv("GIT_EDITOR")
testMain(t, "reword", "MSG3", "MSG4")
testNoStdout(t)
testPrintedStderr(t, "editing messages (new texts logged in",
".git"+string(os.PathSeparator)+"REWORD_MSGS in case of failure)")
testMain(t, "pending", "-c", "-l", "-s")
testNoStderr(t)
testPrintedStdout(t,
"msg #2",
"MESSAGE #3",
"MESSAGE #4",
"msg #5",
)
testMain(t, "reword") // reword all
testNoStdout(t)
testPrintedStderr(t, "editing messages (new texts logged in",
".git"+string(os.PathSeparator)+"REWORD_MSGS in case of failure)")
testMain(t, "pending", "-c", "-l", "-s")
testNoStderr(t)
testPrintedStdout(t,
"MESSAGE #2",
"MESSAGE #3",
"MESSAGE #4",
"MESSAGE #5",
)
out := trun(t, gt.client, "git", "log", "-n1")
if !strings.Contains(out, fakeName) {
t.Fatalf("reword lost author name (%s):\n%s", fakeName, out)
}
write(t, gt.client+"/codereview.cfg", "issuerepo: my/issues\ngerrit: on\n", 0644)
os.Setenv("GIT_EDITOR", "sed -i.bak -e 's/Change-Id:.*/Fixes #12345/'")
testMain(t, "reword", "HEAD") // editing single commit message
out = trun(t, gt.client, "git", "log", "-n1", "HEAD")
if !strings.Contains(out, "Fixes my/issues#12345") || !strings.Contains(out, "Change-Id:") {
t.Fatalf("reword single commit did not run commit message hook:\n%s", out)
}
trun(t, gt.client, "git", "reset", "--hard", "MSG4")
testMain(t, "reword") // editing all commit messages
out = trun(t, gt.client, "git", "log", "-n1", "HEAD")
if !strings.Contains(out, "Fixes my/issues#12345") || !strings.Contains(out, "Change-Id:") {
t.Fatalf("reword multiple commits did not run commit message hook:\n%s", out)
}
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/hook.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
)
var hookFiles = []string{
"commit-msg",
"pre-commit",
}
// installHook installs Git hooks to enforce code review conventions.
//
// auto is whether hooks are being installed automatically as part of
// running another git-codereview command, rather than an explicit
// invocation of the 'hooks' command itself.
func installHook(args []string, auto bool) {
flags.Parse(args)
hooksDir := gitPath("hooks")
var existingHooks []string
for _, hookFile := range hookFiles {
filename := filepath.Join(hooksDir, hookFile)
hookContent := fmt.Sprintf(hookScript, hookFile)
if data, err := os.ReadFile(filename); err == nil {
// Special case: remove old hooks that use 'git-review'
oldHookContent := fmt.Sprintf(oldHookScript, hookFile)
if string(data) == oldHookContent {
verbosef("removing old %v hook", hookFile)
os.Remove(filename)
}
// Special case: remove old commit-msg shell script
// in favor of invoking the git-codereview hook
// implementation, which will be easier to change in
// the future.
if hookFile == "commit-msg" && string(data) == oldCommitMsgHook {
verbosef("removing old commit-msg hook")
os.Remove(filename)
}
}
// If hook file exists but has different content, let the user know.
_, err := os.Stat(filename)
if err == nil {
data, err := os.ReadFile(filename)
if err != nil {
verbosef("reading hook: %v", err)
} else if string(data) != hookContent {
verbosef("unexpected hook content in %s", filename)
if !auto {
existingHooks = append(existingHooks, filename)
}
}
continue
}
if !os.IsNotExist(err) {
dief("checking hook: %v", err)
}
verbosef("installing %s hook", hookFile)
if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
verbosef("creating hooks directory %s", hooksDir)
if err := os.Mkdir(hooksDir, 0777); err != nil {
dief("creating hooks directory: %v", err)
}
}
if err := os.WriteFile(filename, []byte(hookContent), 0700); err != nil {
dief("writing hook: %v", err)
}
}
switch {
case len(existingHooks) == 1:
dief("Hooks file %s already exists."+
"\nTo install git-codereview hooks, delete that"+
" file and re-run 'git-codereview hooks'.",
existingHooks[0])
case len(existingHooks) > 1:
dief("Hooks files %s already exist."+
"\nTo install git-codereview hooks, delete these"+
" files and re-run 'git-codereview hooks'.",
strings.Join(existingHooks, ", "))
}
}
// repoRoot returns the root of the currently selected git repo, or
// worktree root if this is an alternate worktree of a repo.
func repoRoot() string {
return filepath.Clean(trim(cmdOutput("git", "rev-parse", "--show-toplevel")))
}
// gitPathDir returns the directory used by git to store temporary
// files such as COMMIT_EDITMSG, FETCH_HEAD, and such for the repo.
// For a simple git repo, this will be <root>/.git, and for an
// alternate worktree of a repo it will be in
// <root>/.git/worktrees/<worktreename>.
func gitPathDir() string {
gcd := trim(cmdOutput("git", "rev-parse", "--git-path", "."))
result, err := filepath.Abs(gcd)
if err != nil {
dief("%v", err)
}
return result
}
// gitPath resolve the $GIT_DIR/path, taking in consideration
// all other path relocations, e.g. hooks for linked worktrees
// are not kept in their gitdir, but shared in the main one.
func gitPath(path string) string {
root := repoRoot()
// git 2.13.0 changed the behavior of --git-path from printing
// a path relative to the repo root to printing a path
// relative to the working directory (issue #19477). Normalize
// both behaviors by running the command from the repo root.
p, err := trimErr(cmdOutputErr("git", "-C", root, "rev-parse", "--git-path", path))
if err != nil {
// When --git-path is not available, assume the common case.
p = filepath.Join(".git", path)
}
if !filepath.IsAbs(p) {
p = filepath.Join(root, p)
}
return p
}
var hookScript = `#!/bin/sh
exec git-codereview hook-invoke %s "$@"
`
var oldHookScript = `#!/bin/sh
exec git-review hook-invoke %s "$@"
`
func cmdHookInvoke(args []string) {
flags.Parse(args)
args = flags.Args()
if len(args) == 0 {
dief("usage: git-codereview hook-invoke <hook-name> [args...]")
}
switch args[0] {
case "commit-msg":
hookCommitMsg(args[1:])
case "pre-commit":
hookPreCommit(args[1:])
}
}
var (
issueRefRE = regexp.MustCompile(`(?P<space>\s)(?P<ref>#\d+\w)`)
oldFixesRETemplate = `Fixes +(issue +(%s)?#?)?(?P<issueNum>[0-9]+)`
)
// hookCommitMsg is installed as the git commit-msg hook.
// It adds a Change-Id line to the bottom of the commit message
// if there is not one already.
func hookCommitMsg(args []string) {
if len(args) != 1 {
dief("usage: git-codereview hook-invoke commit-msg message.txt\n")
}
// We used to bail in detached head mode, but it's very common
// to be modifying things during git rebase -i and it's annoying
// that those new commits made don't get Commit-Msg lines.
// Let's try keeping the hook on and see what breaks.
/*
b := CurrentBranch()
if b.DetachedHead() {
// Likely executing rebase or some other internal operation.
// Probably a mistake to make commit message changes.
return
}
*/
file := args[0]
oldData, err := os.ReadFile(file)
if err != nil {
dief("%v", err)
}
data := fixCommitMessage(oldData)
// Write back.
if !bytes.Equal(data, oldData) {
if err := os.WriteFile(file, data, 0666); err != nil {
dief("%v", err)
}
}
}
// fixCommitMessage fixes various commit message issues,
// including adding a Change-Id line and rewriting #12345
// into repo#12345 as directed by codereview.cfg.
func fixCommitMessage(msg []byte) []byte {
data := append([]byte{}, msg...)
data = stripComments(data)
// Empty message not allowed.
if len(bytes.TrimSpace(data)) == 0 {
dief("empty commit message")
}
// Insert a blank line between first line and subsequent lines if not present.
eol := bytes.IndexByte(data, '\n')
if eol != -1 && len(data) > eol+1 && data[eol+1] != '\n' {
data = append(data, 0)
copy(data[eol+1:], data[eol:])
data[eol+1] = '\n'
}
issueRepo := config()["issuerepo"]
// Update issue references to point to issue repo, if set.
if issueRepo != "" {
data = issueRefRE.ReplaceAll(data, []byte("${space}"+issueRepo+"${ref}"))
}
// TestHookCommitMsgIssueRepoRewrite makes sure the regex is valid
oldFixesRE := regexp.MustCompile(fmt.Sprintf(oldFixesRETemplate, regexp.QuoteMeta(issueRepo)))
data = oldFixesRE.ReplaceAll(data, []byte("Fixes "+issueRepo+"#${issueNum}"))
if haveGerrit() {
// Complain if two Change-Ids are present.
// This can happen during an interactive rebase;
// it is easy to forget to remove one of them.
nChangeId := bytes.Count(data, []byte("\nChange-Id: "))
if nChangeId > 1 {
dief("multiple Change-Id lines")
}
// Add Change-Id to commit message if not present.
if nChangeId == 0 {
data = bytes.TrimRight(data, "\n")
sep := "\n\n"
if endsWithMetadataLine(data) {
sep = "\n"
}
data = append(data, fmt.Sprintf("%sChange-Id: I%x\n", sep, randomBytes())...)
}
// Add branch prefix to commit message if not present and on a
// dev or release branch and not a special Git fixup! or
// squash! commit message.
b := CurrentBranch()
branch := strings.TrimPrefix(b.OriginBranch(), "origin/")
if strings.HasPrefix(branch, "dev.") || strings.HasPrefix(branch, "release-branch.") {
prefix := "[" + branch + "] "
if !bytes.HasPrefix(data, []byte(prefix)) && !isFixup(data) {
data = []byte(prefix + string(data))
}
}
}
return data
}
// randomBytes returns 20 random bytes suitable for use in a Change-Id line.
func randomBytes() []byte {
var id [20]byte
if _, err := io.ReadFull(rand.Reader, id[:]); err != nil {
dief("generating Change-Id: %v", err)
}
return id[:]
}
var metadataLineRE = regexp.MustCompile(`^[a-zA-Z0-9-]+: `)
// endsWithMetadataLine reports whether the given commit message ends with a
// metadata line such as "Bug: #42" or "Signed-off-by: Al <al@example.com>".
func endsWithMetadataLine(msg []byte) bool {
i := bytes.LastIndexByte(msg, '\n')
return i >= 0 && metadataLineRE.Match(msg[i+1:])
}
var (
fixupBang = []byte("fixup!")
squashBang = []byte("squash!")
ignoreBelow = []byte("\n# ------------------------ >8 ------------------------\n")
)
// isFixup reports whether text is a Git fixup! or squash! commit,
// which must not have a prefix.
func isFixup(text []byte) bool {
return bytes.HasPrefix(text, fixupBang) || bytes.HasPrefix(text, squashBang)
}
// stripComments strips lines that begin with "#" and removes the
// "everything below will be removed" section containing the diff when
// using commit --verbose.
func stripComments(in []byte) []byte {
// Issue 16376
if i := bytes.Index(in, ignoreBelow); i >= 0 {
in = in[:i+1]
}
return regexp.MustCompile(`(?m)^#.*\n`).ReplaceAll(in, nil)
}
// hookPreCommit is installed as the git pre-commit hook.
// It prevents commits to the master branch.
// It checks that the Go files added, copied, or modified by
// the change are gofmt'd, and if not it prints gofmt instructions
// and exits with nonzero status.
func hookPreCommit(args []string) {
// We used to bail in detached head mode, but it's very common
// to be modifying things during git rebase -i and it's annoying
// that those new commits made don't get the gofmt check.
// Let's try keeping the hook on and see what breaks.
/*
b := CurrentBranch()
if b.DetachedHead() {
// This is an internal commit such as during git rebase.
// Don't die, and don't force gofmt.
return
}
*/
hookGofmt()
}
func hookGofmt() {
if os.Getenv("GIT_GOFMT_HOOK") == "off" {
fmt.Fprintf(stderr(), "git-codereview pre-commit gofmt hook disabled by $GIT_GOFMT_HOOK=off\n")
return
}
files, stderr := runGofmt(gofmtPreCommit)
if stderr != "" {
msgf := printf
if len(files) == 0 {
msgf = dief
}
msgf("gofmt reported errors:\n\t%s", strings.Replace(strings.TrimSpace(stderr), "\n", "\n\t", -1))
}
if len(files) == 0 {
return
}
dief("gofmt needs to format these files (run 'git gofmt'):\n\t%s",
strings.Join(files, "\n\t"))
}
// This is NOT USED ANYMORE.
// It is here only for comparing against old commit-hook files.
var oldCommitMsgHook = `#!/bin/sh
# From Gerrit Code Review 2.2.1
#
# Part of Gerrit Code Review (http://code.google.com/p/gerrit/)
#
# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
CHANGE_ID_AFTER="Bug|Issue"
MSG="$1"
# Check for, and add if missing, a unique Change-Id
#
add_ChangeId() {
clean_message=` + "`" + `sed -e '
/^diff --git a\/.*/{
s///
q
}
/^Signed-off-by:/d
/^#/d
' "$MSG" | git stripspace` + "`" + `
if test -z "$clean_message"
then
return
fi
if grep -i '^Change-Id:' "$MSG" >/dev/null
then
return
fi
id=` + "`" + `_gen_ChangeId` + "`" + `
perl -e '
$MSG = shift;
$id = shift;
$CHANGE_ID_AFTER = shift;
undef $/;
open(I, $MSG); $_ = <I>; close I;
s|^diff --git a/.*||ms;
s|^#.*$||mg;
exit unless $_;
@message = split /\n/;
$haveFooter = 0;
$startFooter = @message;
for($line = @message - 1; $line >= 0; $line--) {
$_ = $message[$line];
if (/^[a-zA-Z0-9-]+:/ && !m,^[a-z0-9-]+://,) {
$haveFooter++;
next;
}
next if /^[ []/;
$startFooter = $line if ($haveFooter && /^\r?$/);
last;
}
@footer = @message[$startFooter+1..@message];
@message = @message[0..$startFooter];
push(@footer, "") unless @footer;
for ($line = 0; $line < @footer; $line++) {
$_ = $footer[$line];
next if /^($CHANGE_ID_AFTER):/i;
last;
}
splice(@footer, $line, 0, "Change-Id: I$id");
$_ = join("\n", @message, @footer);
open(O, ">$MSG"); print O; close O;
' "$MSG" "$id" "$CHANGE_ID_AFTER"
}
_gen_ChangeIdInput() {
echo "tree ` + "`" + `git write-tree` + "`" + `"
if parent=` + "`" + `git rev-parse HEAD^0 2>/dev/null` + "`" + `
then
echo "parent $parent"
fi
echo "author ` + "`" + `git var GIT_AUTHOR_IDENT` + "`" + `"
echo "committer ` + "`" + `git var GIT_COMMITTER_IDENT` + "`" + `"
echo
printf '%s' "$clean_message"
}
_gen_ChangeId() {
_gen_ChangeIdInput |
git hash-object -t commit --stdin
}
add_ChangeId
`
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/gofmt.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
)
var gofmtList bool
func cmdGofmt(args []string) {
// NOTE: New flags should be added to the usage message below as well as doc.go.
flags.BoolVar(&gofmtList, "l", false, "list files that need to be formatted")
flags.Parse(args)
if len(flag.Args()) > 0 {
fmt.Fprintf(stderr(), "Usage: %s gofmt %s [-l]\n", progName, globalFlags)
exit(2)
}
f := gofmtCommand
if !gofmtList {
f |= gofmtWrite
}
files, stderr := runGofmt(f)
if gofmtList {
w := stdout()
for _, file := range files {
fmt.Fprintf(w, "%s\n", file)
}
}
if stderr != "" {
dief("gofmt reported errors:\n\t%s", strings.Replace(strings.TrimSpace(stderr), "\n", "\n\t", -1))
}
}
const (
gofmtPreCommit = 1 << iota
gofmtCommand
gofmtWrite
)
// runGofmt runs the external gofmt command over modified files.
//
// The definition of "modified files" depends on the bit flags.
// If gofmtPreCommit is set, then runGofmt considers *.go files that
// differ between the index (staging area) and the branchpoint
// (the latest commit before the branch diverged from upstream).
// If gofmtCommand is set, then runGofmt considers all those files
// in addition to files with unstaged modifications.
// It never considers untracked files.
//
// As a special case for the main repo (but applied everywhere)
// *.go files under a top-level test directory are excluded from the
// formatting requirement, except run.go and those in test/bench/.
//
// If gofmtWrite is set (only with gofmtCommand, meaning this is 'git gofmt'),
// runGofmt replaces the original files with their formatted equivalents.
// Git makes this difficult. In general the file in the working tree
// (the local file system) can have unstaged changes that make it different
// from the equivalent file in the index. To help pass the precommit hook,
// 'git gofmt' must make it easy to update the files in the index.
// One option is to run gofmt on all the files of the same name in the
// working tree and leave it to the user to sort out what should be staged
// back into the index. Another is to refuse to reformat files for which
// different versions exist in the index vs the working tree. Both of these
// options are unsatisfying: they foist busy work onto the user,
// and it's exactly the kind of busy work that a program is best for.
// Instead, when runGofmt finds files in the index that need
// reformatting, it reformats them there, bypassing the working tree.
// It also reformats files in the working tree that need reformatting.
// For both, only files modified since the branchpoint are considered.
// The result should be that both index and working tree get formatted
// correctly and diffs between the two remain meaningful (free of
// formatting distractions). Modifying files in the index directly may
// surprise Git users, but it seems the best of a set of bad choices, and
// of course those users can choose not to use 'git gofmt'.
// This is a bit more work than the other git commands do, which is
// a little worrying, but the choice being made has the nice property
// that if 'git gofmt' is interrupted, a second 'git gofmt' will put things into
// the same state the first would have.
//
// runGofmt returns a list of files that need (or needed) reformatting.
// If gofmtPreCommit is set, the names always refer to files in the index.
// If gofmtCommand is set, then a name without a suffix (see below)
// refers to both the copy in the index and the copy in the working tree
// and implies that the two copies are identical. Otherwise, in the case
// that the index and working tree differ, the file name will have an explicit
// " (staged)" or " (unstaged)" suffix saying which is meant.
//
// runGofmt also returns any standard error output from gofmt,
// usually indicating syntax errors in the Go source files.
// If gofmtCommand is set, syntax errors in index files that do not match
// the working tree show a " (staged)" suffix after the file name.
// The errors never use the " (unstaged)" suffix, in order to keep
// references to the local file system in the standard file:line form.
func runGofmt(flags int) (files []string, stderrText string) {
pwd, err := os.Getwd()
if err != nil {
dief("%v", err)
}
pwd = filepath.Clean(pwd) // convert to host \ syntax
if !strings.HasSuffix(pwd, string(filepath.Separator)) {
pwd += string(filepath.Separator)
}
b := CurrentBranch()
repo := repoRoot()
if !strings.HasSuffix(repo, string(filepath.Separator)) {
repo += string(filepath.Separator)
}
// Find files modified in the index compared to the branchpoint.
// The default of HEAD will only compare against the most recent commit.
// But if we know the origin branch, and this isn't a branch tag move,
// then check all the pending commits.
branchpt := "HEAD"
if b.OriginBranch() != "" {
isBranchTagMove := strings.Contains(cmdOutput("git", "branch", "-r", "--contains", b.FullName()), "origin/")
if !isBranchTagMove {
branchpt = b.Branchpoint()
}
}
indexFiles := addRoot(repo, filter(gofmtRequired, nonBlankLines(cmdOutput("git", "diff", "--name-only", "--diff-filter=ACM", "--cached", branchpt, "--"))))
localFiles := addRoot(repo, filter(gofmtRequired, nonBlankLines(cmdOutput("git", "diff", "--name-only", "--diff-filter=ACM"))))
localFilesMap := stringMap(localFiles)
isUnstaged := func(file string) bool {
return localFilesMap[file]
}
if len(indexFiles) == 0 && ((flags&gofmtCommand) == 0 || len(localFiles) == 0) {
return
}
// Determine which files have unstaged changes and are therefore
// different from their index versions. For those, the index version must
// be copied into a temporary file in the local file system.
needTemp := filter(isUnstaged, indexFiles)
// Map between temporary file name and place in file tree where
// file would be checked out (if not for the unstaged changes).
tempToFile := map[string]string{}
fileToTemp := map[string]string{}
cleanup := func() {} // call before dying (defer won't run)
if len(needTemp) > 0 {
// Ask Git to copy the index versions into temporary files.
// Git stores the temporary files, named .merge_*, in the repo root.
// Unlike the Git commands above, the non-temp file names printed
// here are relative to the current directory, not the repo root.
// git checkout-index --temp is broken on windows. Running this command:
//
// git checkout-index --temp -- bad-bad-bad2.go bad-bad-broken.go bad-bad-good.go bad-bad2-bad.go bad-bad2-broken.go bad-bad2-good.go bad-broken-bad.go bad-broken-bad2.go bad-broken-good.go bad-good-bad.go bad-good-bad2.go bad-good-broken.go bad2-bad-bad2.go bad2-bad-broken.go bad2-bad-good.go bad2-bad2-bad.go bad2-bad2-broken.go bad2-bad2-good.go bad2-broken-bad.go bad2-broken-bad2.go bad2-broken-good.go bad2-good-bad.go bad2-good-bad2.go bad2-good-broken.go broken-bad-bad2.go broken-bad-broken.go broken-bad-good.go broken-bad2-bad.go broken-bad2-broken.go broken-bad2-good.go
//
// produces this output
//
// .merge_file_a05448 bad-bad-bad2.go
// .merge_file_b05448 bad-bad-broken.go
// .merge_file_c05448 bad-bad-good.go
// .merge_file_d05448 bad-bad2-bad.go
// .merge_file_e05448 bad-bad2-broken.go
// .merge_file_f05448 bad-bad2-good.go
// .merge_file_g05448 bad-broken-bad.go
// .merge_file_h05448 bad-broken-bad2.go
// .merge_file_i05448 bad-broken-good.go
// .merge_file_j05448 bad-good-bad.go
// .merge_file_k05448 bad-good-bad2.go
// .merge_file_l05448 bad-good-broken.go
// .merge_file_m05448 bad2-bad-bad2.go
// .merge_file_n05448 bad2-bad-broken.go
// .merge_file_o05448 bad2-bad-good.go
// .merge_file_p05448 bad2-bad2-bad.go
// .merge_file_q05448 bad2-bad2-broken.go
// .merge_file_r05448 bad2-bad2-good.go
// .merge_file_s05448 bad2-broken-bad.go
// .merge_file_t05448 bad2-broken-bad2.go
// .merge_file_u05448 bad2-broken-good.go
// .merge_file_v05448 bad2-good-bad.go
// .merge_file_w05448 bad2-good-bad2.go
// .merge_file_x05448 bad2-good-broken.go
// .merge_file_y05448 broken-bad-bad2.go
// .merge_file_z05448 broken-bad-broken.go
// error: unable to create file .merge_file_XXXXXX (No error)
// .merge_file_XXXXXX broken-bad-good.go
// error: unable to create file .merge_file_XXXXXX (No error)
// .merge_file_XXXXXX broken-bad2-bad.go
// error: unable to create file .merge_file_XXXXXX (No error)
// .merge_file_XXXXXX broken-bad2-broken.go
// error: unable to create file .merge_file_XXXXXX (No error)
// .merge_file_XXXXXX broken-bad2-good.go
//
// so limit the number of file arguments to 25.
for len(needTemp) > 0 {
n := len(needTemp)
if n > 25 {
n = 25
}
args := []string{"checkout-index", "--temp", "--"}
args = append(args, needTemp[:n]...)
// Until Git 2.3.0, git checkout-index --temp is broken if not run in the repo root.
// Work around by running in the repo root.
// http://article.gmane.org/gmane.comp.version-control.git/261739
// https://github.com/git/git/commit/74c4de5
for _, line := range nonBlankLines(cmdOutputDir(repo, "git", args...)) {
i := strings.Index(line, "\t")
if i < 0 {
continue
}
temp, file := line[:i], line[i+1:]
temp = filepath.Join(repo, temp)
file = filepath.Join(repo, file)
tempToFile[temp] = file
fileToTemp[file] = temp
}
needTemp = needTemp[n:]
}
cleanup = func() {
for temp := range tempToFile {
os.Remove(temp)
}
tempToFile = nil
}
defer cleanup()
}
dief := func(format string, args ...interface{}) {
cleanup()
dief(format, args...) // calling top-level dief function
}
// Run gofmt to find out which files need reformatting;
// if gofmtWrite is set, reformat them in place.
// For references to local files, remove leading pwd if present
// to make relative to current directory.
// Temp files and local-only files stay as absolute paths for easy matching in output.
args := []string{"-l"}
if flags&gofmtWrite != 0 {
args = append(args, "-w")
}
for _, file := range indexFiles {
if isUnstaged(file) {
args = append(args, fileToTemp[file])
} else {
args = append(args, strings.TrimPrefix(file, pwd))
}
}
if flags&gofmtCommand != 0 {
args = append(args, localFiles...)
}
if *verbose > 1 {
fmt.Fprintln(stderr(), commandString("gofmt", args))
}
cmd := exec.Command("gofmt", args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if stderr.Len() == 0 && err != nil {
// Error but no stderr: usually can't find gofmt.
dief("invoking gofmt: %v", err)
}
// Build file list.
files = lines(stdout.String())
// Restage files that need to be restaged.
if flags&gofmtWrite != 0 {
add := []string{"add"}
write := []string{"hash-object", "-w", "--"}
updateIndex := []string{}
for _, file := range files {
if real := tempToFile[file]; real != "" {
write = append(write, file)
updateIndex = append(updateIndex, strings.TrimPrefix(real, repo))
} else if !isUnstaged(file) {
add = append(add, file)
}
}
if len(add) > 1 {
run("git", add...)
}
if len(updateIndex) > 0 {
hashes := nonBlankLines(cmdOutput("git", write...))
if len(hashes) != len(write)-3 {
dief("git hash-object -w did not write expected number of objects")
}
var buf bytes.Buffer
for i, name := range updateIndex {
fmt.Fprintf(&buf, "100644 %s\t%s\n", hashes[i], name)
}
verbosef("git update-index --index-info")
cmd := exec.Command("git", "update-index", "--index-info")
cmd.Stdin = &buf
out, err := cmd.CombinedOutput()
if err != nil {
dief("git update-index: %v\n%s", err, out)
}
}
}
// Remap temp files back to original names for caller.
for i, file := range files {
if real := tempToFile[file]; real != "" {
if flags&gofmtCommand != 0 {
real += " (staged)"
}
files[i] = strings.TrimPrefix(real, pwd)
} else if isUnstaged(file) {
files[i] = strings.TrimPrefix(file+" (unstaged)", pwd)
}
}
// Rewrite temp names in stderr, and shorten local file names.
// No suffix added for local file names (see comment above).
text := "\n" + stderr.String()
for temp, file := range tempToFile {
if flags&gofmtCommand != 0 {
file += " (staged)"
}
text = strings.Replace(text, "\n"+temp+":", "\n"+strings.TrimPrefix(file, pwd)+":", -1)
}
for _, file := range localFiles {
text = strings.Replace(text, "\n"+file+":", "\n"+strings.TrimPrefix(file, pwd)+":", -1)
}
text = text[1:]
sort.Strings(files)
return files, text
}
// gofmtRequired reports whether the specified file should be checked
// for gofmt'dness by the pre-commit hook.
// The file name is relative to the repo root.
func gofmtRequired(file string) bool {
// TODO: Consider putting this policy into codereview.cfg.
if !strings.HasSuffix(file, ".go") {
return false
}
if strings.HasPrefix(file, "vendor/") || strings.Contains(file, "/vendor/") {
return false
}
if strings.HasPrefix(file, "testdata/") || strings.Contains(file, "/testdata/") {
return false
}
if !strings.HasPrefix(file, "test/") {
return true
}
return strings.HasPrefix(file, "test/bench/") || file == "test/run.go"
}
// stringMap returns a map m such that m[s] == true if s was in the original list.
func stringMap(list []string) map[string]bool {
m := map[string]bool{}
for _, x := range list {
m[x] = true
}
return m
}
// filter returns the elements in list satisfying f.
func filter(f func(string) bool, list []string) []string {
var out []string
for _, x := range list {
if f(x) {
out = append(out, x)
}
}
return out
}
func addRoot(root string, list []string) []string {
var out []string
for _, x := range list {
out = append(out, filepath.Join(root, x))
}
return out
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/sync_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
func TestSync(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testMain(t, "change", "work")
// check for error with unstaged changes
write(t, gt.client+"/file1", "", 0644)
trun(t, gt.client, "git", "add", "file1")
write(t, gt.client+"/file1", "actual content", 0644)
testMainDied(t, "sync")
testPrintedStderr(t, "cannot sync: unstaged changes exist",
"git status", "git stash", "git add", "git-codereview change")
testNoStdout(t)
// check for error with staged changes
trun(t, gt.client, "git", "add", "file1")
testMainDied(t, "sync")
testPrintedStderr(t, "cannot sync: staged changes exist",
"git status", "!git stash", "!git add", "git-codereview change")
testNoStdout(t)
// check for success after stash
trun(t, gt.client, "git", "stash")
testMain(t, "sync")
testNoStdout(t)
testNoStderr(t)
// make server 1 step ahead of client
write(t, gt.server+"/file", "new content", 0644)
trun(t, gt.server, "git", "add", "file")
trun(t, gt.server, "git", "commit", "-m", "msg")
// check for success
testMain(t, "sync")
testNoStdout(t)
testNoStderr(t)
}
func TestSyncRebase(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// Suppress --reapply-cherry-picks hint.
trun(t, gt.client, "git", "config", "advice.skippedCherryPicks", "false")
// client 3 ahead
gt.work(t)
gt.work(t)
gt.work(t)
b := CurrentBranch()
if len(b.Pending()) != 3 {
t.Fatalf("have %d pending CLs, want 3", len(b.Pending()))
}
top := b.Pending()[0].Hash
// check for success for sync no-op
testMain(t, "sync")
testNoStdout(t)
testNoStderr(t)
b = CurrentBranch()
if len(b.Pending()) != 3 {
t.Fatalf("have %d pending CLs after no-op sync, want 3", len(b.Pending()))
}
if b.Pending()[0].Hash != top {
t.Fatalf("CL hashes changed during no-op sync")
}
// submit first two CLs - gt.serverWork does same thing gt.work does, but on server
gt.serverWork(t)
gt.serverWorkUnrelated(t, "") // wedge in unrelated work to get different hashes
gt.serverWork(t)
testMain(t, "sync")
testNoStdout(t)
testNoStderr(t)
// there should be one left, and it should be a different hash
b = CurrentBranch()
if len(b.Pending()) != 1 {
t.Fatalf("have %d pending CLs after submitting two, want 1", len(b.Pending()))
}
if b.Pending()[0].Hash == top {
t.Fatalf("CL hashes DID NOT change during sync after submit")
}
// submit final change
gt.serverWork(t)
testMain(t, "sync")
testNoStdout(t)
testNoStderr(t)
// there should be none left
b = CurrentBranch()
if len(b.Pending()) != 0 {
t.Fatalf("have %d pending CLs after final sync, want 0", len(b.Pending()))
}
// sync -v prints git output.
// also exercising -v parsing.
testMain(t, "sync", "-v=true")
testNoStdout(t)
testPrintedStderr(t, "git -c advice.skippedCherryPicks=false pull -q -r origin main")
testMain(t, "sync", "-v=1")
testNoStdout(t)
testPrintedStderr(t, "git -c advice.skippedCherryPicks=false pull -q -r origin main")
testMain(t, "sync", "-v")
testNoStdout(t)
testPrintedStderr(t, "git -c advice.skippedCherryPicks=false pull -q -r origin main")
testMain(t, "sync", "-v=false")
testNoStdout(t)
testNoStderr(t)
}
func TestBranchConfig(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t) // do the main-branch work setup now to avoid unwanted change below
trun(t, gt.client, "git", "checkout", "dev.branch")
testMain(t, "pending", "-c", "-l")
// The !+ means reject any output with a +, which introduces a pending commit.
// There should be no pending commits.
testPrintedStdout(t, "dev.branch (current branch, tracking dev.branch)", "!+")
// If we make a branch with raw git,
// the codereview.cfg should help us see the tracking info
// even though git doesn't know the right upstream.
trun(t, gt.client, "git", "checkout", "-b", "mywork", "HEAD^0")
if out, err := cmdOutputDirErr(gt.client, "git", "rev-parse", "--abbrev-ref", "@{u}"); err == nil {
t.Fatalf("git knows @{u} but should not:\n%s", out)
}
testMain(t, "pending", "-c", "-l")
testPrintedStdout(t, "mywork (current branch, tracking dev.branch)", "!+")
// Pending should have set @{u} correctly for us.
if out, err := cmdOutputDirErr(gt.client, "git", "rev-parse", "--abbrev-ref", "@{u}"); err != nil {
t.Fatalf("git does not know @{u} but should: %v\n%s", err, out)
} else if out = strings.TrimSpace(out); out != "origin/dev.branch" {
t.Fatalf("git @{u} = %q, want %q", out, "origin/dev.branch")
}
// Even if we add a pending commit, we should see the right tracking info.
// The !codereview.cfg makes sure we do not see the codereview.cfg-changing
// commit from the server in the output. (That would happen if we were printing
// new commits relative to main instead of relative to dev.branch.)
gt.work(t)
testMain(t, "pending", "-c", "-l")
testHideRevHashes(t)
testPrintedStdout(t, "mywork REVHASH..REVHASH (current branch, tracking dev.branch)", "!codereview.cfg")
// If we make a new branch using the old work HEAD
// then we should be back to something tracking main.
trun(t, gt.client, "git", "checkout", "-b", "mywork2", "work^0")
gt.work(t)
testMain(t, "pending", "-c", "-l")
testHideRevHashes(t)
testPrintedStdout(t, "mywork2 REVHASH..REVHASH (current branch)", "!codereview.cfg")
// Now look at all branches, which should use the appropriate configs
// from the commits on each branch.
testMain(t, "pending", "-l")
testHideRevHashes(t)
testPrintedStdout(t, "mywork2 REVHASH..REVHASH (current branch)",
"mywork REVHASH..REVHASH (tracking dev.branch)",
"work REVHASH..REVHASH\n") // the \n checks for not having a (tracking main)
}
func TestDetachedHead(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.work(t) // do the main-branch work setup now to avoid unwanted change below
trun(t, gt.client, "git", "checkout", "HEAD^0") // enter detached HEAD mode with one pending commit
// Pending should succeed and just print very little.
testMain(t, "pending", "-c", "-l")
testPrintedStdout(t, "HEAD (detached, remote branch unknown)", "!+")
testNoStderr(t)
// Sync, branchpoint should fail - branch unknown
// (there is no "upstream" coming from git, and there's no branch line
// in codereview.cfg on main in the test setup).
for _, cmd := range []string{"sync", "branchpoint"} {
testMainDied(t, cmd)
testNoStdout(t)
testPrintedStderr(t, "cannot "+cmd+": no origin branch (in detached HEAD mode)")
}
// If we switch to dev.branch, which does have a branch line,
// detached HEAD mode should be able to find the branchpoint.
trun(t, gt.client, "git", "checkout", "dev.branch")
gt.work(t)
trun(t, gt.client, "git", "checkout", "HEAD^0")
}
func TestSyncBranch(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.serverWork(t)
gt.serverWork(t)
trun(t, gt.server, "git", "checkout", "dev.branch")
gt.serverWorkUnrelated(t, "")
gt.serverWorkUnrelated(t, "")
gt.serverWorkUnrelated(t, "")
trun(t, gt.server, "git", "checkout", "main")
testMain(t, "change", "dev.branch")
testMain(t, "sync-branch")
testHideRevHashes(t)
testPrintedStdout(t, "[dev.branch] all: merge main (REVHASH) into dev.branch",
"Merge List:",
"+ DATE REVHASH msg #2",
"+ DATE REVHASH",
)
testPrintedStderr(t, "* Merge commit created.",
"Run 'git codereview mail' to send for review.")
}
func TestSyncBranchWorktree(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.serverWork(t)
gt.serverWork(t)
trun(t, gt.server, "git", "checkout", "dev.branch")
gt.serverWorkUnrelated(t, "")
gt.serverWorkUnrelated(t, "")
gt.serverWorkUnrelated(t, "")
trun(t, gt.server, "git", "checkout", "main")
wt := filepath.Join(gt.tmpdir, "git-worktree")
trun(t, gt.client, "git", "worktree", "add", "-b", "dev.branch", wt, "origin/dev.branch")
if err := os.Chdir(wt); err != nil {
t.Fatal(err)
}
testMain(t, "sync-branch")
testHideRevHashes(t)
testPrintedStdout(t, "[dev.branch] all: merge main (REVHASH) into dev.branch")
}
func TestSyncBranchMergeBack(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
// server does not default to having a codereview.cfg on main,
// but sync-branch requires one.
var mainCfg = []byte("branch: main\n")
os.WriteFile(filepath.Join(gt.server, "codereview.cfg"), mainCfg, 0666)
trun(t, gt.server, "git", "add", "codereview.cfg")
trun(t, gt.server, "git", "commit", "-m", "config for main", "codereview.cfg")
gt.serverWork(t)
gt.serverWork(t)
trun(t, gt.server, "git", "checkout", "dev.branch")
gt.serverWorkUnrelated(t, "work on dev.branch#1")
gt.serverWorkUnrelated(t, "work on dev.branch#2")
gt.serverWorkUnrelated(t, "work on dev.branch#3")
trun(t, gt.server, "git", "checkout", "main")
testMain(t, "change", "dev.branch")
// Merge back should fail because there are
// commits in the parent that have not been merged here yet.
testMainDied(t, "sync-branch", "--merge-back-to-parent")
testNoStdout(t)
testPrintedStderr(t, "parent has new commits")
// Bring them in, creating a merge commit.
testMain(t, "sync-branch")
// Merge back should still fail - merge commit not submitted yet.
testMainDied(t, "sync-branch", "--merge-back-to-parent")
testNoStdout(t)
testPrintedStderr(t, "pending changes exist")
// Push the changes back to the server.
// (In a real system this would happen through Gerrit.)
trun(t, gt.client, "git", "push", "origin")
devHash := trim(trun(t, gt.client, "git", "rev-parse", "HEAD"))
// Nothing should be pending.
testMain(t, "pending", "-c")
testPrintedStdout(t, "!+")
// This time should work.
testMain(t, "sync-branch", "--merge-back-to-parent")
testPrintedStdout(t,
"\n\tall: REVERSE MERGE dev.branch ("+devHash[:7]+") into main",
"This commit is a REVERSE MERGE.",
"It merges dev.branch back into its parent branch, main.",
"This marks the end of development on dev.branch.",
"Merge List:",
"msg #2",
"!config for main",
)
testPrintedStderr(t, "Merge commit created.")
data, err := os.ReadFile(filepath.Join(gt.client, "codereview.cfg"))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, mainCfg) {
t.Fatalf("codereview.cfg not restored:\n%s", data)
}
// Check pending knows what branch it is on.
testMain(t, "pending", "-c")
testHideRevHashes(t)
testPrintedStdout(t,
"dev.branch REVHASH..REVHASH (current branch)", // no "tracking dev.branch" anymore
"REVHASH (merge=REVHASH)",
"Merge List:",
"!config for main",
)
// Check that mail sends the merge to the right place!
testMain(t, "mail", "-n")
testNoStdout(t)
testPrintedStderr(t,
"git push -q origin HEAD:refs/for/main",
"git tag --no-sign -f dev.branch.mailed",
)
}
func TestSyncBranchConflict(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
gt.serverWork(t)
gt.serverWork(t)
trun(t, gt.server, "git", "checkout", "dev.branch")
gt.serverWork(t)
trun(t, gt.server, "git", "checkout", "main")
testMain(t, "change", "dev.branch")
testMainDied(t, "sync-branch")
testNoStdout(t)
testPrintedStderr(t,
"git-codereview: sync-branch: merge conflicts in:",
" - file",
"Please fix them (use 'git status' to see the list again),",
"then 'git add' or 'git rm' to resolve them,",
"and then 'git sync-branch -continue' to continue.",
"Or run 'git merge --abort' to give up on this sync-branch.",
)
// Other client-changing commands should fail now.
testDisallowed := func(cmd ...string) {
t.Helper()
testMainDied(t, cmd...)
testNoStdout(t)
testPrintedStderr(t,
"git-codereview: cannot "+cmd[0]+": found pending merge",
"Run 'git codereview sync-branch -continue' if you fixed",
"merge conflicts after a previous sync-branch operation.",
"Or run 'git merge --abort' to give up on the sync-branch.",
)
}
testDisallowed("change", "main")
testDisallowed("sync-branch")
// throw away server changes to resolve merge
trun(t, gt.client, "git", "checkout", "HEAD", "file")
// Still cannot change branches even with conflicts resolved.
testDisallowed("change", "main")
testDisallowed("sync-branch")
testMain(t, "sync-branch", "-continue")
testHideRevHashes(t)
testPrintedStdout(t,
"[dev.branch] all: merge main (REVHASH) into dev.branch",
"+ REVHASH (merge=REVHASH)",
"Conflicts:",
"- file",
"Merge List:",
"+ DATE REVHASH msg #2",
"+ DATE REVHASH",
)
testPrintedStderr(t,
"* Merge commit created.",
"Run 'git codereview mail' to send for review.",
)
// Check that pending only shows the merge, not more commits.
testMain(t, "pending", "-c", "-l", "-s")
n := strings.Count(testStdout.String(), "+")
if n != 1 {
t.Fatalf("git pending shows %d commits, want 1:\n%s", n, testStdout.String())
}
testNoStderr(t)
// Check that mail sends the merge to the right place!
testMain(t, "mail", "-n")
testNoStdout(t)
testPrintedStderr(t,
"git push -q origin HEAD:refs/for/dev.branch",
"git tag --no-sign -f dev.branch.mailed",
)
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/editor.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"io"
"os"
"os/exec"
)
// editor invokes an interactive editor on a temporary file containing
// initial, blocks until the editor exits, and returns the (possibly
// edited) contents of the temporary file. It follows the conventions
// of git for selecting and invoking the editor (see git-var(1)).
func editor(initial string) string {
// Query the git editor command.
gitEditor := trim(cmdOutput("git", "var", "GIT_EDITOR"))
// Create temporary file.
temp, err := os.CreateTemp("", "git-codereview")
if err != nil {
dief("creating temp file: %v", err)
}
tempName := temp.Name()
defer os.Remove(tempName)
if _, err := io.WriteString(temp, initial); err != nil {
dief("%v", err)
}
if err := temp.Close(); err != nil {
dief("%v", err)
}
// Invoke the editor. See git's prepare_shell_cmd.
cmd := exec.Command("sh", "-c", gitEditor+" \"$@\"", gitEditor, tempName)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
if err := cmd.Run(); err != nil {
os.Remove(tempName)
dief("editor exited with: %v", err)
}
// Read the edited file.
b, err := os.ReadFile(tempName)
if err != nil {
dief("%v", err)
}
return string(b)
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/branch.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
)
// Branch describes a Git branch.
type Branch struct {
Name string // branch name
Current bool // branch is currently checked out
loadedPending bool // following fields are valid
originBranch string // upstream origin branch
commitsAhead int // number of commits ahead of origin branch
branchpoint string // latest commit hash shared with origin branch
pending []*Commit // pending commits, newest first (children before parents)
config map[string]string // cached config; use Config instead
}
// A Commit describes a single pending commit on a Git branch.
type Commit struct {
Hash string // commit hash
ShortHash string // abbreviated commit hash
Parent string // parent hash (== Parents[0])
Parents []string // all parent hashes (merges have > 1)
Tree string // tree hash
Message string // commit message
Subject string // first line of commit message
ChangeID string // Change-Id in commit message ("" if missing)
AuthorName string // author name (from %an)
AuthorEmail string // author email (from %ae)
AuthorDate string // author date as Unix timestamp string (from %at)
// For use by pending command.
g *GerritChange // associated Gerrit change data
gerr error // error loading Gerrit data
committed []string // list of files in this commit
}
// HasParent reports whether hash appears in c.Parents.
func (c *Commit) HasParent(hash string) bool {
for _, p := range c.Parents {
if p == hash {
return true
}
}
return false
}
// Config returns the configuration for the branch.
func (b *Branch) Config() map[string]string {
if b.config != nil {
return b.config
}
var cfgText string
if b.Current {
data, _ := os.ReadFile(filepath.Join(repoRoot(), "codereview.cfg"))
cfgText = string(data)
} else {
out, err := cmdOutputDirErr(repoRoot(), "git", "show", b.Name+":codereview.cfg")
if err == nil {
cfgText = out
}
}
cfg, err := parseConfig(cfgText)
if err != nil {
verbosef("failed to load config for branch %v: %v", b.Name, err)
cfg = make(map[string]string)
}
b.config = cfg
return b.config
}
// CurrentBranch returns the current branch.
func CurrentBranch() *Branch {
name := strings.TrimPrefix(trim(cmdOutput("git", "rev-parse", "--abbrev-ref", "HEAD")), "heads/")
return &Branch{Name: name, Current: true}
}
// DetachedHead reports whether branch b corresponds to a detached HEAD
// (does not have a real branch name).
func (b *Branch) DetachedHead() bool {
return b.Name == "HEAD"
}
// NeedOriginBranch exits with an error message
// if the origin branch is unknown.
// The cmd is the user command reported in the failure message.
func (b *Branch) NeedOriginBranch(cmd string) {
if b.OriginBranch() == "" {
why := ""
if b.DetachedHead() {
why = " (in detached HEAD mode)"
}
if cmd == "<internal branchpoint>" && exitTrap != nil {
panic("NeedOriginBranch")
}
dief("cannot %s: no origin branch%s", cmd, why)
}
}
// OriginBranch returns the name of the origin branch that branch b tracks.
// The returned name is like "origin/master" or "origin/dev.garbage" or
// "origin/release-branch.go1.4".
func (b *Branch) OriginBranch() string {
if b.originBranch != "" {
return b.originBranch
}
cfg := b.Config()["branch"]
upstream := ""
if cfg != "" {
upstream = "origin/" + cfg
}
// Consult and possibly update git,
// but only if we are actually on a real branch,
// not in detached HEAD mode.
if !b.DetachedHead() {
gitUpstream := b.gitOriginBranch()
if upstream == "" {
upstream = gitUpstream
}
if upstream == "" {
// Assume branch was created before we set upstream correctly.
// See if origin/main exists; if so, use it.
// Otherwise, fall back to origin/master.
argv := []string{"git", "rev-parse", "--abbrev-ref", "origin/main"}
cmd := exec.Command(argv[0], argv[1:]...)
setEnglishLocale(cmd)
if err := cmd.Run(); err == nil {
upstream = "origin/main"
} else {
upstream = "origin/master"
}
}
if gitUpstream != upstream && b.Current {
// Best effort attempt to correct setting for next time,
// and for "git status".
exec.Command("git", "branch", "-u", upstream).Run()
}
}
b.originBranch = upstream
return b.originBranch
}
func (b *Branch) gitOriginBranch() string {
argv := []string{"git", "rev-parse", "--abbrev-ref", b.Name + "@{u}"}
cmd := exec.Command(argv[0], argv[1:]...)
if runtime.GOOS == "windows" {
// Workaround on windows. git for windows can't handle @{u} as same as
// given. Disable glob for this command if running on Cygwin or MSYS2.
envs := os.Environ()
envs = append(envs, "CYGWIN=noglob "+os.Getenv("CYGWIN"))
envs = append(envs, "MSYS=noglob "+os.Getenv("MSYS"))
cmd.Env = envs
}
setEnglishLocale(cmd)
out, err := cmd.CombinedOutput()
if err == nil && len(out) > 0 {
return string(bytes.TrimSpace(out))
}
// Have seen both "No upstream configured" and "no upstream configured".
if strings.Contains(string(out), "upstream configured") {
return ""
}
fmt.Fprintf(stderr(), "%v\n%s\n", commandString(argv[0], argv[1:]), out)
dief("%v", err)
panic("not reached")
}
func (b *Branch) FullName() string {
if b.Name != "HEAD" {
return "refs/heads/" + b.Name
}
return b.Name
}
// HasPendingCommit reports whether b has any pending commits.
func (b *Branch) HasPendingCommit() bool {
b.loadPending()
return b.commitsAhead > 0
}
// Pending returns b's pending commits, newest first (children before parents).
func (b *Branch) Pending() []*Commit {
b.loadPending()
return b.pending
}
// Branchpoint returns an identifier for the latest revision
// common to both this branch and its upstream branch.
func (b *Branch) Branchpoint() string {
b.NeedOriginBranch("<internal branchpoint>")
b.loadPending()
return b.branchpoint
}
func gitHash(expr string) string {
out, err := cmdOutputErr("git", "rev-parse", expr)
if err != nil {
dief("cannot resolve %s: %v\n%s", expr, err, out)
}
if strings.HasPrefix(expr, "-") {
// Git has a bug where it will just echo these back with no error.
// (Try "git rev-parse -qwerty".)
// Reject them ourselves instead.
dief("cannot resolve %s: invalid reference", expr)
}
return trim(out)
}
func (b *Branch) loadPending() {
if b.loadedPending {
return
}
b.loadedPending = true
// In case of early return.
// But avoid the git exec unless really needed.
b.branchpoint = ""
defer func() {
if b.branchpoint == "" {
b.branchpoint = gitHash("HEAD")
}
}()
if b.DetachedHead() {
return
}
// Note: This runs in parallel with "git fetch -q",
// so the commands may see a stale version of origin/master.
// The use of origin here is for identifying what the branch has
// in common with origin (what's old on the branch).
// Any new commits in origin do not affect that.
// Note: --topo-order means child first, then parent.
origin := b.OriginBranch()
const numField = 9
all := trim(cmdOutput("git", "log", "--topo-order",
"--format=format:%H%x00%h%x00%P%x00%T%x00%B%x00%s%x00%an%x00%ae%x00%at%x00",
origin+".."+b.FullName(), "--"))
fields := strings.Split(all, "\x00")
if len(fields) < numField {
return // nothing pending
}
for i, field := range fields {
fields[i] = strings.TrimLeft(field, "\r\n")
}
Log:
for i := 0; i+numField <= len(fields); i += numField {
parents := strings.Fields(fields[i+2])
c := &Commit{
Hash: fields[i],
ShortHash: fields[i+1],
Parents: parents,
Tree: fields[i+3],
Message: fields[i+4],
Subject: fields[i+5],
AuthorName: fields[i+6],
AuthorEmail: fields[i+7],
AuthorDate: fields[i+8],
}
if len(c.Parents) > 0 {
c.Parent = c.Parents[0]
}
if len(c.Parents) > 1 {
// Found merge point.
// Merges break the invariant that the last shared commit (the branchpoint)
// is the parent of the final commit in the log output.
// If c.Parent is on the origin branch, then since we are reading the log
// in (reverse) topological order, we know that c.Parent is the actual branchpoint,
// even if we later see additional commits on a different branch leading down to
// a lower location on the same origin branch.
// Check c.Merge (the second parent) too, so we don't depend on the parent order.
for _, parent := range c.Parents {
if strings.Contains(cmdOutput("git", "branch", "-a", "--contains", parent), " remotes/"+origin+"\n") {
b.pending = append(b.pending, c)
b.branchpoint = parent
break Log
}
}
}
for _, line := range lines(c.Message) {
// Note: Keep going even if we find one, so that
// we take the last Change-Id line, just in case
// there is a commit message quoting another
// commit message.
// I'm not sure this can come up at all, but just in case.
if strings.HasPrefix(line, "Change-Id: ") {
c.ChangeID = line[len("Change-Id: "):]
}
}
b.pending = append(b.pending, c)
b.branchpoint = c.Parent
}
b.commitsAhead = len(b.pending)
}
// CommitsBehind reports the number of commits present upstream
// that are not present in the current branch.
func (b *Branch) CommitsBehind() int {
return len(lines(cmdOutput("git", "log", "--format=format:x", b.FullName()+".."+b.OriginBranch(), "--")))
}
// Submitted reports whether some form of b's pending commit
// has been cherry picked to origin.
func (b *Branch) Submitted(id string) bool {
if id == "" {
return false
}
line := "Change-Id: " + id
out := cmdOutput("git", "log", "-n", "1", "-F", "--grep", line, b.Name+".."+b.OriginBranch(), "--")
return strings.Contains(out, line)
}
var stagedRE = regexp.MustCompile(`^[ACDMR] `)
// HasStagedChanges reports whether the working directory contains staged changes.
func HasStagedChanges() bool {
for _, s := range nonBlankLines(cmdOutput("git", "status", "-b", "--porcelain")) {
if stagedRE.MatchString(s) {
return true
}
}
return false
}
var unstagedRE = regexp.MustCompile(`^.[ACDMR]`)
// HasUnstagedChanges reports whether the working directory contains unstaged changes.
func HasUnstagedChanges() bool {
for _, s := range nonBlankLines(cmdOutput("git", "status", "-b", "--porcelain")) {
if unstagedRE.MatchString(s) {
return true
}
}
return false
}
// LocalChanges returns a list of files containing staged, unstaged, and untracked changes.
// The elements of the returned slices are typically file names, always relative to the root,
// but there are a few alternate forms. First, for renaming or copying, the element takes
// the form `from -> to`. Second, in the case of files with names that contain unusual characters,
// the files (or the from, to fields of a rename or copy) are quoted C strings.
// For now, we expect the caller only shows these to the user, so these exceptions are okay.
func LocalChanges() (staged, unstaged, untracked []string) {
for _, s := range lines(cmdOutput("git", "status", "-b", "--porcelain")) {
if len(s) < 4 || s[2] != ' ' {
continue
}
switch s[0] {
case 'A', 'C', 'D', 'M', 'R':
staged = append(staged, s[3:])
case '?':
untracked = append(untracked, s[3:])
}
switch s[1] {
case 'A', 'C', 'D', 'M', 'R':
unstaged = append(unstaged, s[3:])
}
}
return
}
// LocalBranches returns a list of all known local branches.
// If the current directory is in detached HEAD mode, one returned
// branch will have Name == "HEAD" and DetachedHead() == true.
func LocalBranches() []*Branch {
var branches []*Branch
current := CurrentBranch()
for _, s := range nonBlankLines(cmdOutput("git", "branch", "-q")) {
s = strings.TrimSpace(s)
if strings.HasPrefix(s, "* ") {
// * marks current branch in output.
// Normally the current branch has a name like any other,
// but in detached HEAD mode the branch listing shows
// a localized (translated) textual description instead of
// a branch name. Avoid language-specific differences
// by using CurrentBranch().Name for the current branch.
// It detects detached HEAD mode in a more portable way.
// (git rev-parse --abbrev-ref HEAD returns 'HEAD').
s = current.Name
}
// + marks a branch checked out in a worktree. Worktrees in detached
// HEAD mode don't appear in the "git branch" output, so this is always
// a normal name.
s = strings.TrimPrefix(s, "+ ")
branches = append(branches, &Branch{Name: s})
}
return branches
}
func OriginBranches() []string {
var branches []string
for _, line := range nonBlankLines(cmdOutput("git", "branch", "-a", "-q")) {
line = strings.TrimSpace(line)
if i := strings.Index(line, " -> "); i >= 0 {
line = line[:i]
}
name := strings.TrimSpace(strings.TrimPrefix(line, "* "))
if strings.HasPrefix(name, "remotes/origin/") {
branches = append(branches, strings.TrimPrefix(name, "remotes/"))
}
}
return branches
}
// GerritChange returns the change metadata from the Gerrit server
// for the branch's pending change.
// The extra strings are passed to the Gerrit API request as o= parameters,
// to enable additional information. Typical values include "LABELS" and "CURRENT_REVISION".
// See https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html for details.
func (b *Branch) GerritChange(c *Commit, extra ...string) (*GerritChange, error) {
if !b.HasPendingCommit() {
return nil, fmt.Errorf("no changes pending")
}
if c.ChangeID == "" {
return nil, fmt.Errorf("missing Change-Id")
}
id := fullChangeID(b, c)
for i, x := range extra {
if i == 0 {
id += "?"
} else {
id += "&"
}
id += "o=" + x
}
return readGerritChange(id)
}
// GerritChanges returns the change metadata from the Gerrit server
// for the given changes, which each be the result of fullChangeID(b, c) for some c.
// The extra strings are passed to the Gerrit API request as o= parameters,
// to enable additional information. Typical values include "LABELS" and "CURRENT_REVISION".
// See https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html for details.
func (b *Branch) GerritChanges(ids []string, extra ...string) ([][]*GerritChange, error) {
q := ""
for _, id := range ids {
if q != "" {
q += "&"
}
if strings.HasSuffix(id, "~") {
// result of fullChangeID(b, c) with missing Change-Id; don't send
q += "q=is:closed+is:open" // cannot match anything
continue
}
q += "q=change:" + url.QueryEscape(id)
}
if q == "" {
return nil, fmt.Errorf("no changes found")
}
for _, x := range extra {
q += "&o=" + url.QueryEscape(x)
}
return readGerritChanges(q)
}
// CommitByRev finds a unique pending commit by its git <rev>.
// It dies if rev cannot be resolved to a commit or that commit is not
// pending on b using the action ("mail", "submit") in the failure message.
func (b *Branch) CommitByRev(action, rev string) *Commit {
// Parse rev to a commit hash.
hash, err := cmdOutputErr("git", "rev-parse", "--verify", rev+"^{commit}")
if err != nil {
msg := strings.TrimPrefix(trim(err.Error()), "fatal: ")
dief("cannot %s: %s", action, msg)
}
hash = trim(hash)
// Check that hash is a pending commit.
var c *Commit
for _, c1 := range b.Pending() {
if c1.Hash == hash {
c = c1
break
}
}
if c == nil {
dief("cannot %s: commit hash %q not found in the current branch", action, hash)
}
return c
}
// DefaultCommit returns the default pending commit for this branch.
// It dies if there is not exactly one pending commit,
// using the action (e.g. "mail", "submit") and optional extra instructions
// in the failure message.
func (b *Branch) DefaultCommit(action, extra string) *Commit {
work := b.Pending()
if len(work) == 0 {
dief("cannot %s: no changes pending", action)
}
if len(work) >= 2 {
var buf bytes.Buffer
for _, c := range work {
fmt.Fprintf(&buf, "\n\t%s %s", c.ShortHash, c.Subject)
}
if extra != "" {
extra = "; " + extra
}
dief("cannot %s: multiple changes pending%s:%s", action, extra, buf.String())
}
return work[0]
}
// ListFiles returns the list of files in a given commit.
func ListFiles(c *Commit) []string {
if c.Parent == "" {
return nil
}
return nonBlankLines(cmdOutput("git", "diff", "--name-only", c.Parent, c.Hash, "--"))
}
func cmdBranchpoint(args []string) {
expectZeroArgs(args, "branchpoint")
b := CurrentBranch()
b.NeedOriginBranch("branchpoint")
fmt.Fprintf(stdout(), "%s\n", b.Branchpoint())
}
func cmdRebaseWork(args []string) {
expectZeroArgs(args, "rebase-work")
b := CurrentBranch()
if HasStagedChanges() || HasUnstagedChanges() {
dief("cannot rebase with uncommitted work")
}
if len(b.Pending()) == 0 {
dief("no pending work")
}
run("git", "rebase", "-i", b.Branchpoint())
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/change_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"strings"
"testing"
)
func TestChange(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
t.Logf("main -> main")
testMain(t, "change", "main")
testRan(t, "git checkout -q main")
branchpoint := strings.TrimSpace(trun(t, gt.client, "git", "rev-parse", "HEAD"))
testCommitMsg = "foo: my commit msg"
t.Logf("main -> work")
testMain(t, "change", "work")
testRan(t, "git checkout -q -b work HEAD",
"git branch -q --set-upstream-to origin/main")
t.Logf("work -> main")
testMain(t, "change", "main")
testRan(t, "git checkout -q main")
t.Logf("main -> work with staged changes")
write(t, gt.client+"/file", "new content", 0644)
trun(t, gt.client, "git", "add", "file")
testMain(t, "change", "work")
testRan(t, "git checkout -q work",
"git commit -q --allow-empty -m foo: my commit msg")
t.Logf("work -> work2")
testMain(t, "change", "work2")
testRan(t, "git checkout -q -b work2 "+branchpoint,
"git branch -q --set-upstream-to origin/main")
t.Logf("work2 -> dev.branch")
testMain(t, "change", "dev.branch")
testRan(t, "git checkout -q -t -b dev.branch origin/dev.branch")
testMain(t, "pending", "-c")
testPrintedStdout(t, "tracking dev.branch")
testMain(t, "change", "main")
testMain(t, "change", "work2")
t.Logf("server work × 2")
gt.serverWork(t)
gt.serverWork(t)
testMain(t, "sync")
t.Logf("-> work with server ahead")
testMain(t, "change", "work")
testPrintedStderr(t, "warning: 2 commits behind origin/main; run 'git codereview sync' to update")
}
func TestChangeHEAD(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testMainDied(t, "change", "HeAd")
testPrintedStderr(t, "invalid branch name \"HeAd\": ref name HEAD is reserved for git")
}
func TestMessageRE(t *testing.T) {
for _, c := range []struct {
in string
want bool
}{
{"blah", false},
{"[release-branch.go1.4] blah", false},
{"[release-branch.go1.4] math: fix cosine", true},
{"math: fix cosine", true},
{"math/rand: make randomer", true},
{"math/rand, crypto/rand: fix random sources", true},
{"cmd/internal/rsc.io/x86: update from external repo", true},
{"_content/blog: fix typos", true},
} {
got := messageRE.MatchString(c.in)
if got != c.want {
t.Errorf("MatchString(%q) = %v, want %v", c.in, got, c.want)
}
}
}
func TestChangeAmendCommit(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testCommitMsg = "foo: amended commit message"
gt.work(t)
write(t, gt.client+"/file", "new content in work to be amend", 0644)
trun(t, gt.client, "git", "add", "file")
testMain(t, "change")
}
func TestChangeFailAmendWithMultiplePending(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testCommitMsg = "foo: amended commit message"
gt.work(t)
gt.work(t)
write(t, gt.client+"/file", "new content in work to be amend", 0644)
trun(t, gt.client, "git", "add", "file")
testMainDied(t, "change")
testPrintedStderr(t, "multiple changes pending")
}
func TestChangeCL(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
srv := newGerritServer(t)
defer srv.done()
// Ensure that 'change' with a CL accepts we have gerrit. Test address is injected by newGerritServer.
write(t, gt.server+"/codereview.cfg", "gerrit: on", 0644)
trun(t, gt.server, "git", "add", "codereview.cfg")
trun(t, gt.server, "git", "commit", "-m", "codereview.cfg on main")
trun(t, gt.client, "git", "pull")
defer srv.done()
hash1 := trim(trun(t, gt.server, "git", "rev-parse", "dev.branch"))
hash2 := trim(trun(t, gt.server, "git", "rev-parse", "release.branch"))
trun(t, gt.server, "git", "update-ref", "refs/changes/00/100/1", hash1)
trun(t, gt.server, "git", "update-ref", "refs/changes/00/100/2", hash2)
trun(t, gt.server, "git", "update-ref", "refs/changes/00/100/3", hash1)
srv.setReply("/a/changes/100", gerritReply{f: func() gerritReply {
changeJSON := `{
"current_revision": "HASH",
"revisions": {
"HASH": {
"_number": 3
}
}
}`
changeJSON = strings.Replace(changeJSON, "HASH", hash1, -1)
return gerritReply{body: ")]}'\n" + changeJSON}
}})
checkChangeCL := func(arg, ref, hash string) {
testMain(t, "change", "main")
testMain(t, "change", arg)
testRan(t,
fmt.Sprintf("git fetch -q origin %s", ref),
"git checkout -q FETCH_HEAD")
if hash != trim(trun(t, gt.client, "git", "rev-parse", "HEAD")) {
t.Fatalf("hash do not match for CL %s", arg)
}
}
checkChangeCL("100/1", "refs/changes/00/100/1", hash1)
checkChangeCL("100/2", "refs/changes/00/100/2", hash2)
checkChangeCL("100", "refs/changes/00/100/3", hash1)
// turn off gerrit, make it look like we are on GitHub
write(t, gt.server+"/codereview.cfg", "nothing: here", 0644)
trun(t, gt.server, "git", "add", "codereview.cfg")
trun(t, gt.server, "git", "commit", "-m", "new codereview.cfg on main")
testMain(t, "change", "main")
trun(t, gt.client, "git", "pull", "-r")
trun(t, gt.client, "git", "remote", "set-url", "origin", "https://github.com/google/not-a-project")
testMain(t, "change", "-n", "123")
testNoStdout(t)
testPrintedStderr(t,
"git fetch -q origin pull/123/head",
"git checkout -q FETCH_HEAD",
)
}
func TestChangeWithMessage(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testMain(t, "change", "new_branch")
testMain(t, "change", "-m", "foo: some commit message")
testRan(t, "git commit -q --allow-empty -m foo: some commit message")
}
func TestChangeWithSignoff(t *testing.T) {
gt := newGitTest(t)
defer gt.done()
testMain(t, "change", "new_branch")
// There are no staged changes, hence an empty commit will be created.
// Hence we also need a commit message.
testMain(t, "change", "-s", "-m", "foo: bar")
testRan(t, "git commit -q --allow-empty -m foo: bar -s")
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/review.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// TODO(rsc): Document multi-change branch behavior.
// Command git-codereview provides a simple command-line user interface for
// working with git repositories and the Gerrit code review system.
// See "git-codereview help" for details.
package main // import "golang.org/x/review/git-codereview"
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
var (
flags *flag.FlagSet
verbose = new(count) // installed as -v below
noRun = new(bool)
)
const progName = "git-codereview"
func initFlags() {
flags = flag.NewFlagSet("", flag.ExitOnError)
flags.Usage = func() {
fmt.Fprintf(stderr(), usage, progName, progName)
exit(2)
}
flags.SetOutput(stderr())
flags.BoolVar(noRun, "n", false, "print but do not run commands")
flags.Var(verbose, "v", "report commands")
}
const globalFlags = "[-n] [-v]"
const usage = `Usage: %s <command> ` + globalFlags + `
Use "%s help" for a list of commands.
`
const help = `Usage: %s <command> ` + globalFlags + `
Git-codereview is a git helper command for managing pending commits
against an upstream server, typically a Gerrit server.
The -n flag prints commands that would make changes but does not run them.
The -v flag prints those commands as they run.
Available commands:
branchpoint
change [name]
change NNNN[/PP]
gofmt [-l]
help
hooks
mail [-r reviewer,...] [-cc mail,...] [options] [commit]
pending [-c] [-l] [-s]
rebase-work
reword [commit...]
submit [-i | commit...]
sync
sync-branch [-continue]
See https://pkg.go.dev/golang.org/x/review/git-codereview
for the full details of each command.
`
func main() {
initFlags()
if len(os.Args) < 2 {
flags.Usage()
exit(2)
}
command, args := os.Args[1], os.Args[2:]
// NOTE: Keep this switch in sync with the list of commands above.
var cmd func([]string)
switch command {
default:
flags.Usage()
exit(2) // avoid installing hooks.
case "help":
fmt.Fprintf(stdout(), help, progName)
return // avoid installing hooks.
case "hooks": // in case hooks weren't installed.
installHook(args, false)
return // avoid invoking installHook twice.
case "branchpoint":
cmd = cmdBranchpoint
case "change":
cmd = cmdChange
case "gofmt":
cmd = cmdGofmt
case "hook-invoke":
cmd = cmdHookInvoke
case "mail", "m":
cmd = cmdMail
case "pending":
cmd = cmdPending
case "rebase-work":
cmd = cmdRebaseWork
case "reword":
cmd = cmdReword
case "submit":
cmd = cmdSubmit
case "sync":
cmd = cmdSync
case "sync-branch":
cmd = cmdSyncBranch
case "test-loadAuth": // for testing only.
cmd = func([]string) { loadAuth() }
}
// Install hooks automatically, but only if this is a Gerrit repo.
if haveGerrit() {
// Don't pass installHook args directly,
// since args might contain args meant for other commands.
// Filter down to just global flags.
var hookArgs []string
for _, arg := range args {
switch arg {
case "-n", "-v":
hookArgs = append(hookArgs, arg)
}
}
installHook(hookArgs, true)
}
cmd(args)
}
func expectZeroArgs(args []string, command string) {
flags.Parse(args)
if len(flags.Args()) > 0 {
fmt.Fprintf(stderr(), "Usage: %s %s %s\n", progName, command, globalFlags)
exit(2)
}
}
func setEnglishLocale(cmd *exec.Cmd) {
// Override the existing locale to prevent non-English locales from
// interfering with string parsing. See golang.org/issue/33895.
if cmd.Env == nil {
cmd.Env = os.Environ()
}
cmd.Env = append(cmd.Env, "LC_ALL=C")
}
func run(command string, args ...string) {
if err := runErr(command, args...); err != nil {
if *verbose == 0 {
// If we're not in verbose mode, print the command
// before dying to give context to the failure.
fmt.Fprintf(stderr(), "(running: %s)\n", commandString(command, args))
}
dief("%v", err)
}
}
func runErr(command string, args ...string) error {
return runDirErr(".", command, args...)
}
var runLogTrap []string
func runDirErr(dir, command string, args ...string) error {
if *noRun || *verbose == 1 {
fmt.Fprintln(stderr(), commandString(command, args))
} else if *verbose > 1 {
start := time.Now()
defer func() {
fmt.Fprintf(stderr(), "%s # %.3fs\n", commandString(command, args), time.Since(start).Seconds())
}()
}
if *noRun {
return nil
}
if runLogTrap != nil {
runLogTrap = append(runLogTrap, strings.TrimSpace(command+" "+strings.Join(args, " ")))
}
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = stdout()
cmd.Stderr = stderr()
if dir != "." {
cmd.Dir = dir
}
setEnglishLocale(cmd)
return cmd.Run()
}
// cmdOutput runs the command line, returning its output.
// If the command cannot be run or does not exit successfully,
// cmdOutput dies.
//
// NOTE: cmdOutput must be used only to run commands that read state,
// not for commands that make changes. Commands that make changes
// should be run using runDirErr so that the -v and -n flags apply to them.
func cmdOutput(command string, args ...string) string {
return cmdOutputDir(".", command, args...)
}
// cmdOutputDir runs the command line in dir, returning its output.
// If the command cannot be run or does not exit successfully,
// cmdOutput dies.
//
// NOTE: cmdOutput must be used only to run commands that read state,
// not for commands that make changes. Commands that make changes
// should be run using runDirErr so that the -v and -n flags apply to them.
func cmdOutputDir(dir, command string, args ...string) string {
s, err := cmdOutputDirErr(dir, command, args...)
if err != nil {
fmt.Fprintf(stderr(), "%v\n%s\n", commandString(command, args), s)
dief("%v", err)
}
return s
}
// cmdOutputErr runs the command line in dir, returning its output
// and any error results.
//
// NOTE: cmdOutputErr must be used only to run commands that read state,
// not for commands that make changes. Commands that make changes
// should be run using runDirErr so that the -v and -n flags apply to them.
func cmdOutputErr(command string, args ...string) (string, error) {
return cmdOutputDirErr(".", command, args...)
}
// cmdOutputDirErr runs the command line in dir, returning its output
// and any error results.
//
// NOTE: cmdOutputDirErr must be used only to run commands that read state,
// not for commands that make changes. Commands that make changes
// should be run using runDirErr so that the -v and -n flags apply to them.
func cmdOutputDirErr(dir, command string, args ...string) (string, error) {
// NOTE: We only show these non-state-modifying commands with -v -v.
// Otherwise things like 'git sync -v' show all our internal "find out about
// the git repo" commands, which is confusing if you are just trying to find
// out what git sync means.
if *verbose > 1 {
start := time.Now()
defer func() {
fmt.Fprintf(stderr(), "%s # %.3fs\n", commandString(command, args), time.Since(start).Seconds())
}()
}
cmd := exec.Command(command, args...)
if dir != "." {
cmd.Dir = dir
}
setEnglishLocale(cmd)
b, err := cmd.CombinedOutput()
return string(b), err
}
// trim is shorthand for strings.TrimSpace.
func trim(text string) string {
return strings.TrimSpace(text)
}
// trimErr applies strings.TrimSpace to the result of cmdOutput(Dir)Err,
// passing the error along unmodified.
func trimErr(text string, err error) (string, error) {
return strings.TrimSpace(text), err
}
// lines returns the lines in text.
func lines(text string) []string {
out := strings.Split(text, "\n")
// Split will include a "" after the last line. Remove it.
if n := len(out) - 1; n >= 0 && out[n] == "" {
out = out[:n]
}
return out
}
// nonBlankLines returns the non-blank lines in text.
func nonBlankLines(text string) []string {
var out []string
for _, s := range lines(text) {
if strings.TrimSpace(s) != "" {
out = append(out, s)
}
}
return out
}
func commandString(command string, args []string) string {
return strings.Join(append([]string{command}, args...), " ")
}
func dief(format string, args ...interface{}) {
printf(format, args...)
exit(1)
}
var exitTrap func()
func exit(code int) {
if exitTrap != nil {
exitTrap()
}
os.Exit(code)
}
func verbosef(format string, args ...interface{}) {
if *verbose > 0 {
printf(format, args...)
}
}
var stdoutTrap, stderrTrap *bytes.Buffer
func stdout() io.Writer {
if stdoutTrap != nil {
return stdoutTrap
}
return os.Stdout
}
func stderr() io.Writer {
if stderrTrap != nil {
return stderrTrap
}
return os.Stderr
}
func printf(format string, args ...interface{}) {
fmt.Fprintf(stderr(), "%s: %s\n", progName, fmt.Sprintf(format, args...))
}
// count is a flag.Value that is like a flag.Bool and a flag.Int.
// If used as -name, it increments the count, but -name=x sets the count.
// Used for verbose flag -v.
type count int
func (c *count) String() string {
return fmt.Sprint(int(*c))
}
func (c *count) Set(s string) error {
switch s {
case "true":
*c++
case "false":
*c = 0
default:
n, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("invalid count %q", s)
}
*c = count(n)
}
return nil
}
func (c *count) IsBoolFlag() bool {
return true
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/config_test.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"reflect"
"testing"
)
func TestParseConfig(t *testing.T) {
cases := []struct {
raw string
want map[string]string
wanterr bool
}{
{raw: "", want: map[string]string{}},
{raw: "issuerepo: golang/go", want: map[string]string{"issuerepo": "golang/go"}},
{raw: "# comment", want: map[string]string{}},
{raw: "# comment\n k : v \n# comment 2\n\n k2:v2\n", want: map[string]string{"k": "v", "k2": "v2"}},
}
for _, tt := range cases {
cfg, err := parseConfig(tt.raw)
if err != nil != tt.wanterr {
t.Errorf("parse(%q) error: %v", tt.raw, err)
continue
}
if !reflect.DeepEqual(cfg, tt.want) {
t.Errorf("parse(%q)=%v want %v", tt.raw, cfg, tt.want)
}
}
}
func TestHaveGerritInternal(t *testing.T) {
tests := []struct {
gerrit string
origin string
want bool
}{
{gerrit: "off", want: false},
{gerrit: "on", want: true},
{origin: "invalid url", want: false},
{origin: "https://github.com/golang/go", want: false},
{origin: "http://github.com/golang/go", want: false},
{origin: "git@github.com:golang/go", want: false},
{origin: "git@github.com:golang/go.git", want: false},
{origin: "git@github.com:/golang/go", want: false},
{origin: "git@github.com:/golang/go.git", want: false},
{origin: "ssh://git@github.com/golang/go", want: false},
{origin: "ssh://git@github.com/golang/go.git", want: false},
{origin: "git+ssh://git@github.com/golang/go", want: false},
{origin: "git+ssh://git@github.com/golang/go.git", want: false},
{origin: "git://github.com/golang/go", want: false},
{origin: "git://github.com/golang/go.git", want: false},
{origin: "sso://go/tools", want: true}, // Google-internal
{origin: "rpc://go/tools", want: true}, // Google-internal
{origin: "http://go.googlesource.com/sys", want: false},
{origin: "https://go.googlesource.com/review", want: true},
{origin: "https://go.googlesource.com/review/", want: true},
}
for _, test := range tests {
if got := haveGerritInternal(test.gerrit, test.origin); got != test.want {
t.Errorf("haveGerritInternal(%q, %q) = %t, want %t", test.gerrit, test.origin, got, test.want)
}
}
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/sync.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strings"
)
func cmdSync(args []string) {
expectZeroArgs(args, "sync")
// Get current branch and commit ID for fixup after pull.
b := CurrentBranch()
b.NeedOriginBranch("sync")
var id string
if work := b.Pending(); len(work) > 0 {
id = work[0].ChangeID
}
// If this is a Gerrit repo, disable the status advice that
// tells users to run 'git push' and so on, like the marked (<<<) lines:
//
// % git status
// On branch master
// Your branch is ahead of 'origin/master' by 3 commits. <<<
// (use "git push" to publish your local commits) <<<
// ...
//
// (This advice is inappropriate when using Gerrit.)
if len(b.Pending()) > 0 && haveGerrit() {
// Only disable if statusHints is unset in the local config.
// This allows users who really want them to put them back
// in the .git/config for the Gerrit-cloned repo.
_, err := cmdOutputErr("git", "config", "--local", "advice.statusHints")
if err != nil {
run("git", "config", "--local", "advice.statusHints", "false")
}
}
// Don't sync with staged or unstaged changes.
// rebase is going to complain if we don't, and we can give a nicer error.
checkStaged("sync")
checkUnstaged("sync")
// Pull remote changes into local branch.
// We do this in one command so that people following along with 'git sync -v'
// see fewer commands to understand.
// We want to pull in the remote changes from the upstream branch
// and rebase the current pending commit (if any) on top of them.
// If there is no pending commit, the pull will do a fast-forward merge.
//
// The -c advice.skippedCherryPicks=false disables this message:
//
// hint: use --reapply-cherry-picks to include skipped commits
// hint: Disable this message with "git config advice.skippedCherryPicks false"
//
if *verbose > 1 {
run("git", "-c", "advice.skippedCherryPicks=false", "pull", "-q", "-r", "-v", "origin", strings.TrimPrefix(b.OriginBranch(), "origin/"))
} else {
run("git", "-c", "advice.skippedCherryPicks=false", "pull", "-q", "-r", "origin", strings.TrimPrefix(b.OriginBranch(), "origin/"))
}
b = CurrentBranch() // discard any cached information
if len(b.Pending()) == 1 && b.Submitted(id) {
// If the change commit has been submitted,
// roll back change leaving any changes unstaged.
// Pull should have done this for us, but check just in case.
run("git", "reset", b.Branchpoint())
}
}
func checkStaged(cmd string) {
if HasStagedChanges() {
dief("cannot %s: staged changes exist\n"+
"\trun 'git status' to see changes\n"+
"\trun 'git-codereview change' to commit staged changes", cmd)
}
}
func checkUnstaged(cmd string) {
if HasUnstagedChanges() {
dief("cannot %s: unstaged changes exist\n"+
"\trun 'git status' to see changes\n"+
"\trun 'git stash' to save unstaged changes\n"+
"\trun 'git add' and 'git-codereview change' to commit staged changes", cmd)
}
}
type syncBranchStatus struct {
Local string
Parent string
Branch string
ParentHash string
BranchHash string
Conflicts []string
}
func syncBranchStatusFile() string {
return gitPath("codereview-sync-branch-status")
}
func readSyncBranchStatus() *syncBranchStatus {
data, err := os.ReadFile(syncBranchStatusFile())
if err != nil {
dief("cannot sync-branch: reading status: %v", err)
}
status := new(syncBranchStatus)
err = json.Unmarshal(data, status)
if err != nil {
dief("cannot sync-branch: reading status: %v", err)
}
return status
}
func writeSyncBranchStatus(status *syncBranchStatus) {
js, err := json.MarshalIndent(status, "", "\t")
if err != nil {
dief("cannot sync-branch: writing status: %v", err)
}
if err := os.WriteFile(syncBranchStatusFile(), js, 0666); err != nil {
dief("cannot sync-branch: writing status: %v", err)
}
}
func cmdSyncBranch(args []string) {
os.Setenv("GIT_EDITOR", ":") // do not bring up editor during merge, commit
os.Setenv("GIT_GOFMT_HOOK", "off") // do not require gofmt during merge
var cont, mergeBackToParent bool
flags.BoolVar(&cont, "continue", false, "continue after merge conflicts")
flags.BoolVar(&mergeBackToParent, "merge-back-to-parent", false, "for shutting down the dev branch")
flags.Parse(args)
if len(flag.Args()) > 0 {
fmt.Fprintf(stderr(), "Usage: %s sync-branch %s [-continue]\n", progName, globalFlags)
exit(2)
}
parent := config()["parent-branch"]
if parent == "" {
dief("cannot sync-branch: codereview.cfg does not list parent-branch")
}
branch := config()["branch"]
if parent == "" {
dief("cannot sync-branch: codereview.cfg does not list branch")
}
b := CurrentBranch()
if b.DetachedHead() {
dief("cannot sync-branch: on detached head")
}
if len(b.Pending()) > 0 {
dief("cannot sync-branch: pending changes exist\n" +
"\trun 'git codereview pending' to see them")
}
if cont {
// Note: There is no -merge-back-to-parent -continue
// because -merge-back-to-parent never has merge conflicts.
// (It requires that the parent be fully merged into the
// dev branch or it won't even attempt the reverse merge.)
if mergeBackToParent {
dief("cannot use -continue with -merge-back-to-parent")
}
if _, err := os.Stat(syncBranchStatusFile()); err != nil {
dief("cannot sync-branch -continue: no pending sync-branch status file found")
}
syncBranchContinue(syncBranchContinueFlag, b, readSyncBranchStatus())
return
}
if _, err := cmdOutputErr("git", "rev-parse", "--abbrev-ref", "MERGE_HEAD"); err == nil {
diePendingMerge("sync-branch")
}
// Don't sync with staged or unstaged changes.
// rebase is going to complain if we don't, and we can give a nicer error.
checkStaged("sync")
checkUnstaged("sync")
// Make sure client is up-to-date on current branch.
// Note that this does a remote fetch of b.OriginBranch() (aka branch).
cmdSync(nil)
// Pull down parent commits too.
quiet := "-q"
if *verbose > 0 {
quiet = "-v"
}
run("git", "fetch", quiet, "origin", "refs/heads/"+parent+":refs/remotes/origin/"+parent)
// Write the status file to make sure we can, before starting a merge.
status := &syncBranchStatus{
Local: b.Name,
Parent: parent,
ParentHash: gitHash("origin/" + parent),
Branch: branch,
BranchHash: gitHash("origin/" + branch),
}
writeSyncBranchStatus(status)
parentHash, err := cmdOutputErr("git", "rev-parse", "origin/"+parent)
if err != nil {
dief("cannot sync-branch: cannot resolve origin/%s: %v\n%s", parent, err, parentHash)
}
branchHash, err := cmdOutputErr("git", "rev-parse", "origin/"+branch)
if err != nil {
dief("cannot sync-branch: cannot resolve origin/%s: %v\n%s", branch, err, branchHash)
}
parentHash = trim(parentHash)
branchHash = trim(branchHash)
// Only --merge-back-to-parent when there's nothing waiting
// to be merged in from parent. If a non-trivial merge needs
// to be done, it should be done first on the dev branch,
// not the parent branch.
if mergeBackToParent {
other := cmdOutput("git", "log", "--format=format:+ %cd %h %s", "--date=short", "origin/"+branch+"..origin/"+parent)
if other != "" {
dief("cannot sync-branch --merge-back-to-parent: parent has new commits.\n"+
"\trun 'git sync-branch' to bring them into this branch first:\n%s",
other)
}
}
// Start the merge.
if mergeBackToParent {
// Change HEAD back to "parent" and merge "branch" into it,
// even though we could instead merge "parent" into "branch".
// This way the parent-branch lineage ends up the first parent
// of the merge, the same as it would when we are doing it by hand
// with a plain "git merge". This may help the display of the
// merge graph in some tools more closely reflect what we did.
run("git", "reset", "--hard", "origin/"+parent)
_, err = cmdOutputErr("git", "merge", "--no-ff", "origin/"+branch)
} else {
_, err = cmdOutputErr("git", "merge", "--no-ff", "origin/"+parent)
}
// Resolve codereview.cfg the right way - never take it from the merge.
// For a regular sync-branch we keep the branch's.
// For a merge-back-to-parent we take the parent's.
// The codereview.cfg contains the branch config and we don't want
// it to change.
what := branchHash
if mergeBackToParent {
what = parentHash
}
cmdOutputDir(repoRoot(), "git", "checkout", what, "--", "codereview.cfg")
if mergeBackToParent {
syncBranchContinue(syncBranchMergeBackFlag, b, status)
return
}
if err != nil {
// Check whether the only listed file is codereview.cfg and try again if so.
// Build list of unmerged files.
for _, s := range nonBlankLines(cmdOutputDir(repoRoot(), "git", "status", "-b", "--porcelain")) {
// Unmerged status is anything with a U and also AA and DD.
if len(s) >= 4 && s[2] == ' ' && (s[0] == 'U' || s[1] == 'U' || s[0:2] == "AA" || s[0:2] == "DD") {
status.Conflicts = append(status.Conflicts, s[3:])
}
}
if len(status.Conflicts) == 0 {
// Must have been codereview.cfg that was the problem.
// Try continuing the merge.
// Note that as of Git 2.12, git merge --continue is a synonym for git commit,
// but older Gits do not have merge --continue.
var out string
out, err = cmdOutputErr("git", "commit", "-m", "TEMPORARY MERGE MESSAGE")
if err != nil {
printf("git commit failed with no apparent unmerged files:\n%s\n", out)
}
} else {
writeSyncBranchStatus(status)
}
}
if err != nil {
if len(status.Conflicts) == 0 {
dief("cannot sync-branch: git merge failed but no conflicts found\n"+
"(unexpected error, please ask for help!)\n\ngit status:\n%s\ngit status -b --porcelain:\n%s",
cmdOutputDir(repoRoot(), "git", "status"),
cmdOutputDir(repoRoot(), "git", "status", "-b", "--porcelain"))
}
dief("sync-branch: merge conflicts in:\n\t- %s\n\n"+
"Please fix them (use 'git status' to see the list again),\n"+
"then 'git add' or 'git rm' to resolve them,\n"+
"and then 'git sync-branch -continue' to continue.\n"+
"Or run 'git merge --abort' to give up on this sync-branch.\n",
strings.Join(status.Conflicts, "\n\t- "))
}
syncBranchContinue("", b, status)
}
func diePendingMerge(cmd string) {
dief("cannot %s: found pending merge\n"+
"Run 'git codereview sync-branch -continue' if you fixed\n"+
"merge conflicts after a previous sync-branch operation.\n"+
"Or run 'git merge --abort' to give up on the sync-branch.\n",
cmd)
}
func prefixFor(branch string) string {
if strings.HasPrefix(branch, "dev.") || strings.HasPrefix(branch, "release-branch.") {
return "[" + branch + "] "
}
return ""
}
const (
syncBranchContinueFlag = " -continue"
syncBranchMergeBackFlag = " -merge-back-to-parent"
)
func syncBranchContinue(flag string, b *Branch, status *syncBranchStatus) {
if h := gitHash("origin/" + status.Parent); h != status.ParentHash {
dief("cannot sync-branch%s: parent hash changed: %.7s -> %.7s", flag, status.ParentHash, h)
}
if h := gitHash("origin/" + status.Branch); h != status.BranchHash {
dief("cannot sync-branch%s: branch hash changed: %.7s -> %.7s", flag, status.BranchHash, h)
}
if b.Name != status.Local {
dief("cannot sync-branch%s: branch changed underfoot: %s -> %s", flag, status.Local, b.Name)
}
var (
dst = status.Branch
dstHash = status.BranchHash
src = status.Parent
srcHash = status.ParentHash
)
if flag == syncBranchMergeBackFlag {
// This is a reverse merge: commits are flowing
// in the opposite direction from normal.
dst, src = src, dst
dstHash, srcHash = srcHash, dstHash
}
prefix := prefixFor(dst)
op := "merge"
if flag == syncBranchMergeBackFlag {
op = "REVERSE MERGE"
}
msg := fmt.Sprintf("%sall: %s %s (%.7s) into %s", prefix, op, src, srcHash, dst)
if flag == syncBranchContinueFlag {
// Need to commit the merge.
// Check that the state of the client is the way we left it before any merge conflicts.
mergeHead, err := cmdOutputErr("git", "rev-parse", "MERGE_HEAD")
if err != nil {
dief("cannot sync-branch%s: no pending merge\n"+
"If you accidentally ran 'git merge --continue' or 'git commit',\n"+
"then use 'git reset --hard HEAD^' to undo.\n", flag)
}
mergeHead = trim(mergeHead)
if mergeHead != srcHash {
dief("cannot sync-branch%s: MERGE_HEAD is %.7s, but origin/%s is %.7s", flag, mergeHead, src, srcHash)
}
head := gitHash("HEAD")
if head != dstHash {
dief("cannot sync-branch%s: HEAD is %.7s, but origin/%s is %.7s", flag, head, dst, dstHash)
}
if HasUnstagedChanges() {
dief("cannot sync-branch%s: unstaged changes (unresolved conflicts)\n"+
"\tUse 'git status' to see them, 'git add' or 'git rm' to resolve them,\n"+
"\tand then run 'git sync-branch -continue' again.\n", flag)
}
run("git", "commit", "-m", msg)
}
// Amend the merge message, which may be auto-generated by git
// or may have been written by us during the post-conflict commit above,
// to use our standard format and list the incorporated CLs.
// Merge must never sync codereview.cfg,
// because it contains the src and dst config.
// Force the on-dst copy back while amending the commit.
cmdOutputDir(repoRoot(), "git", "checkout", "origin/"+dst, "--", "codereview.cfg")
conflictMsg := ""
if len(status.Conflicts) > 0 {
conflictMsg = "Conflicts:\n\n- " + strings.Join(status.Conflicts, "\n- ") + "\n\n"
}
if flag == syncBranchMergeBackFlag {
msg += fmt.Sprintf("\n\n"+
"This commit is a REVERSE MERGE.\n"+
"It merges %s back into its parent branch, %s.\n"+
"This marks the end of development on %s.\n",
status.Branch, status.Parent, status.Branch)
}
msg += fmt.Sprintf("\n\n%sMerge List:\n\n%s", conflictMsg,
cmdOutput("git", "log", "--format=format:+ %cd %h %s", "--date=short", "HEAD^1..HEAD^2"))
run("git", "commit", "--amend", "-m", msg)
fmt.Fprintf(stderr(), "\n")
cmdPending([]string{"-c", "-l"})
fmt.Fprintf(stderr(), "\n* Merge commit created.\nRun 'git codereview mail' to send for review.\n")
os.Remove(syncBranchStatusFile())
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/mail.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"os"
"regexp"
"sort"
"strings"
"unicode"
"unicode/utf8"
)
func cmdMail(args []string) {
// NOTE: New flags should be added to the usage message below as well as doc.go.
var (
rList = new(stringList) // installed below
ccList = new(stringList) // installed below
diff = flags.Bool("diff", false, "show change commit diff and don't upload or mail")
force = flags.Bool("f", false, "mail even if there are staged changes")
hashtagList = new(stringList) // installed below
noKeyCheck = flags.Bool("nokeycheck", false, "set 'git push -o nokeycheck', to prevent Gerrit from checking for private keys")
topic = flags.String("topic", "", "set Gerrit topic")
trybot = flags.Bool("trybot", false, "run trybots on the uploaded CLs")
wip = flags.Bool("wip", false, "set the status of a change to Work-in-Progress")
noverify = flags.Bool("no-verify", false, "disable presubmits")
autoSubmit = flags.Bool("autosubmit", false, "set autosubmit on the uploaded CLs")
)
flags.Var(rList, "r", "comma-separated list of reviewers")
flags.Var(ccList, "cc", "comma-separated list of people to CC:")
flags.Var(hashtagList, "hashtag", "comma-separated list of tags to set")
flags.Usage = func() {
fmt.Fprintf(stderr(),
"Usage: %s mail %s [-r reviewer,...] [-cc mail,...]\n"+
"\t[-autosubmit] [-f] [-diff] [-hashtag tag,...]\n"+
"\t[-nokeycheck] [-topic topic] [-trybot] [-wip]\n"+
"\t[commit]\n", progName, globalFlags)
exit(2)
}
flags.Parse(args)
if len(flags.Args()) > 1 {
flags.Usage()
exit(2)
}
var trybotVotes []string
switch os.Getenv("GIT_CODEREVIEW_TRYBOT") {
case "", "luci":
trybotVotes = []string{"Commit-Queue+1"}
case "farmer":
trybotVotes = []string{"Run-TryBot"}
case "both":
trybotVotes = []string{"Commit-Queue+1", "Run-TryBot"}
default:
fmt.Fprintf(stderr(), "GIT_CODEREVIEW_TRYBOT must be unset, blank, or one of 'luci', 'farmer', or 'both'\n")
exit(2)
}
b := CurrentBranch()
var c *Commit
if len(flags.Args()) == 1 {
c = b.CommitByRev("mail", flags.Arg(0))
} else {
c = b.DefaultCommit("mail", "must specify commit on command line; use HEAD to mail all pending changes")
}
if *diff {
run("git", "diff", b.Branchpoint()[:7]+".."+c.ShortHash, "--")
return
}
if len(ListFiles(c)) == 0 && len(c.Parents) == 1 {
dief("cannot mail: commit %s is empty", c.ShortHash)
}
foundCommit := false
for _, c1 := range b.Pending() {
if c1 == c {
foundCommit = true
}
if !foundCommit {
continue
}
if strings.Contains(strings.ToLower(c1.Message), "do not mail") {
dief("%s: CL says DO NOT MAIL", c1.ShortHash)
}
if strings.HasPrefix(c1.Message, "fixup!") {
dief("%s: CL is a fixup! commit", c1.ShortHash)
}
if strings.HasPrefix(c1.Message, "squash!") {
dief("%s: CL is a squash! commit", c1.ShortHash)
}
for _, f := range ListFiles(c1) {
if strings.HasPrefix(f, ".#") || strings.HasSuffix(f, "~") ||
(strings.HasPrefix(f, "#") && strings.HasSuffix(f, "#")) {
dief("cannot mail temporary files: %s", f)
}
}
}
if !foundCommit {
// b.CommitByRev and b.DefaultCommit both return a commit on b.
dief("internal error: did not find chosen commit on current branch")
}
if !*force && HasStagedChanges() {
dief("there are staged changes; aborting.\n"+
"Use '%s change' to include them or '%s mail -f' to force it.", progName, progName)
}
if !utf8.ValidString(c.Message) {
dief("cannot mail message with invalid UTF-8")
}
for _, r := range c.Message {
if !unicode.IsPrint(r) && !unicode.IsSpace(r) {
dief("cannot mail message with non-printable rune %q", r)
}
}
// for side effect of dying with a good message if origin is GitHub
loadGerritOrigin()
refSpec := b.PushSpec(c)
start := "%"
if *rList != "" {
refSpec += mailList(start, "r", string(*rList))
start = ","
}
if *ccList != "" {
refSpec += mailList(start, "cc", string(*ccList))
start = ","
}
if *hashtagList != "" {
for _, tag := range strings.Split(string(*hashtagList), ",") {
if tag == "" {
dief("hashtag may not contain empty tags")
}
refSpec += start + "hashtag=" + tag
start = ","
}
}
if *topic != "" {
// There's no way to escape the topic, but the only
// ambiguous character is ',' (though other characters
// like ' ' will be rejected outright by git).
if strings.Contains(*topic, ",") {
dief("topic may not contain a comma")
}
refSpec += start + "topic=" + *topic
start = ","
}
if *trybot {
for _, v := range trybotVotes {
refSpec += start + "l=" + v
start = ","
}
}
if *wip {
refSpec += start + "wip"
start = ","
}
if *autoSubmit {
refSpec += start + "l=Auto-Submit"
}
args = []string{"push", "-q"}
if *noKeyCheck {
args = append(args, "-o", "nokeycheck")
}
if *noverify {
args = append(args, "--no-verify")
}
args = append(args, "origin", refSpec)
run("git", args...)
// Create local tag for mailed change.
// If in the 'work' branch, this creates or updates work.mailed.
// Older mailings are in the reflog, so work.mailed is newest,
// work.mailed@{1} is the one before that, work.mailed@{2} before that,
// and so on.
// Git doesn't actually have a concept of a local tag,
// but Gerrit won't let people push tags to it, so the tag
// can't propagate out of the local client into the official repo.
// There is no conflict with the branch names people are using
// for work, because git change rejects any name containing a dot.
// The space of names with dots is ours (the Go team's) to define.
run("git", "tag", "--no-sign", "-f", b.Name+".mailed", c.ShortHash)
}
// PushSpec returns the spec for a Gerrit push command to publish the change c in b.
// If c is nil, PushSpec returns a spec for pushing all changes in b.
func (b *Branch) PushSpec(c *Commit) string {
local := "HEAD"
if c != nil && (len(b.Pending()) == 0 || b.Pending()[0].Hash != c.Hash) {
local = c.ShortHash
}
return local + ":refs/for/" + strings.TrimPrefix(b.OriginBranch(), "origin/")
}
// mailAddressRE matches the mail addresses we admit. It's restrictive but admits
// all the addresses in the Go CONTRIBUTORS file at time of writing (tested separately).
var mailAddressRE = regexp.MustCompile(`^([a-zA-Z0-9][-_.a-zA-Z0-9]*)(@[-_.a-zA-Z0-9]+)?$`)
// mailList turns the list of mail addresses from the flag value into the format
// expected by gerrit. The start argument is a % or , depending on where we
// are in the processing sequence.
func mailList(start, tag string, flagList string) string {
errors := false
spec := start
short := ""
long := ""
for i, addr := range strings.Split(flagList, ",") {
m := mailAddressRE.FindStringSubmatch(addr)
if m == nil {
printf("invalid reviewer mail address: %s", addr)
errors = true
continue
}
if m[2] == "" {
email := mailLookup(addr)
if email == "" {
printf("unknown reviewer: %s", addr)
errors = true
continue
}
short += "," + addr
long += "," + email
addr = email
}
if i > 0 {
spec += ","
}
spec += tag + "=" + addr
}
if short != "" {
verbosef("expanded %s to %s", short[1:], long[1:])
}
if errors {
exit(1)
}
return spec
}
// reviewers is the list of reviewers for the current repository,
// sorted by how many reviews each has done.
var reviewers []reviewer
type reviewer struct {
addr string
count int
}
// mailLookup translates the short name (like adg) into a full
// email address (like adg@golang.org).
// It returns "" if no translation is found.
// The algorithm for expanding short user names is as follows:
// Look at the git commit log for the current repository,
// extracting all the email addresses in Reviewed-By lines
// and sorting by how many times each address appears.
// For each short user name, walk the list, most common
// address first, and use the first address found that has
// the short user name on the left side of the @.
func mailLookup(short string) string {
loadReviewers()
short += "@"
for _, r := range reviewers {
if strings.HasPrefix(r.addr, short) && !shortOptOut[r.addr] {
return r.addr
}
}
return ""
}
// shortOptOut lists email addresses whose owners have opted out
// from consideration for purposes of expanding short user names.
var shortOptOut = map[string]bool{
"dmitshur@google.com": true, // My @golang.org is primary; @google.com is used for +1 only.
}
// loadReviewers reads the reviewer list from the current git repo
// and leaves it in the global variable reviewers.
// See the comment on mailLookup for a description of how the
// list is generated and used.
func loadReviewers() {
if reviewers != nil {
return
}
countByAddr := map[string]int{}
for _, line := range nonBlankLines(cmdOutput("git", "log", "--format=format:%B", "-n", "1000")) {
if strings.HasPrefix(line, "Reviewed-by:") {
f := strings.Fields(line)
addr := f[len(f)-1]
if strings.HasPrefix(addr, "<") && strings.Contains(addr, "@") && strings.HasSuffix(addr, ">") {
countByAddr[addr[1:len(addr)-1]]++
}
}
}
reviewers = []reviewer{}
for addr, count := range countByAddr {
reviewers = append(reviewers, reviewer{addr, count})
}
sort.Sort(reviewersByCount(reviewers))
}
type reviewersByCount []reviewer
func (x reviewersByCount) Len() int { return len(x) }
func (x reviewersByCount) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x reviewersByCount) Less(i, j int) bool {
if x[i].count != x[j].count {
return x[i].count > x[j].count
}
return x[i].addr < x[j].addr
}
// stringList is a flag.Value that is like flag.String, but if repeated
// keeps appending to the old value, inserting commas as separators.
// This allows people to write -r rsc,adg (like the old hg command)
// but also -r rsc -r adg (like standard git commands).
// This does change the meaning of -r rsc -r adg (it used to mean just adg).
type stringList string
func (x *stringList) String() string {
return string(*x)
}
func (x *stringList) Set(s string) error {
if *x != "" && s != "" {
*x += ","
}
*x += stringList(s)
return nil
}
|
git-codereview
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/review/git-codereview/api.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
)
// auth holds cached data about authentication to Gerrit.
var auth struct {
initialized bool
host string // "go.googlesource.com"
url string // "https://go-review.googlesource.com"
project string // "go", "tools", "crypto", etc
// Authentication information.
// Either cookie name + value from git cookie file
// or username and password from .netrc.
cookieName string
cookieValue string
user string
password string
}
// loadGerritOriginMutex is used to control access when initializing auth
// in loadGerritOrigin, which can be called in parallel by "pending".
// We use a mutex rather than a sync.Once because the tests clear auth.
var loadGerritOriginMutex sync.Mutex
// loadGerritOrigin loads the Gerrit host name from the origin remote.
// This sets auth.{initialized,host,url,project}.
// If the origin remote does not appear to be a Gerrit server
// (is missing, is GitHub, is not https, has too many path elements),
// loadGerritOrigin dies.
func loadGerritOrigin() {
loadGerritOriginMutex.Lock()
defer loadGerritOriginMutex.Unlock()
if auth.initialized {
return
}
// Gerrit must be set, either explicitly via the code review config or
// implicitly as Git's origin remote.
origin := config()["gerrit"]
originUrl := trim(cmdOutput("git", "config", "remote.origin.url"))
err := loadGerritOriginInternal(origin, originUrl)
if err != nil {
dief("failed to load Gerrit origin: %v", err)
}
auth.initialized = true
}
// loadGerritOriginInternal does the work of loadGerritOrigin, just extracted out
// for easier testing.
func loadGerritOriginInternal(origin, remoteOrigin string) error {
originUrl, err := url.Parse(remoteOrigin)
if err != nil {
return fmt.Errorf("failed to parse git's remote.origin.url %q as a URL: %v", remoteOrigin, err)
} else {
originUrl.User = nil
remoteOrigin = originUrl.String()
}
hasGerritConfig := true
if origin == "" {
hasGerritConfig = false
origin = remoteOrigin
}
if strings.Contains(origin, "github.com") {
return fmt.Errorf("git origin must be a Gerrit host, not GitHub: %s", origin)
}
// Google employees are required to use sso://go/ or rpc://go/
// instead of https://go.googlesource.com/ for git operations.
// Normally that happens with a "insteadOf" in $HOME/.gitconfig,
// but in case people do a git clone from these directly, convert to
// their real meaning.
if strings.HasPrefix(origin, "sso://go/") || strings.HasPrefix(origin, "rpc://go/") {
origin = "https://go.googlesource.com/" + origin[len("sso://go/"):]
}
if googlesourceIndex := strings.Index(origin, ".googlesource.com"); googlesourceIndex >= 0 {
if !strings.HasPrefix(origin, "https://") {
return fmt.Errorf("git origin must be an https:// URL: %s", origin)
}
// Remove trailing slash from the origin, if any.
origin = strings.TrimRight(origin, "/")
// https:// prefix and then one slash between host and top-level name
if strings.Count(origin, "/") != 3 {
return fmt.Errorf("git origin is malformed: %s", origin)
}
host := origin[len("https://"):strings.LastIndex(origin, "/")]
// In the case of Google's Gerrit, host is go.googlesource.com
// and apiURL uses go-review.googlesource.com, but the Gerrit
// setup instructions do not write down a cookie explicitly for
// go-review.googlesource.com, so we look for the non-review
// host name instead.
url := origin
i := googlesourceIndex
url = url[:i] + "-review" + url[i:]
i = strings.LastIndex(url, "/")
url, project := url[:i], url[i+1:]
auth.host = host
auth.url = url
auth.project = project
return nil
}
// Origin is not *.googlesource.com.
//
// If the Gerrit origin is set from the codereview.cfg file than we handle it
// differently to allow for sub-path hosted Gerrit.
auth.host = originUrl.Host
if hasGerritConfig {
if !strings.HasPrefix(remoteOrigin, origin) {
return fmt.Errorf("Gerrit origin %q from %q different than git origin url %q", origin, configPath, originUrl)
}
auth.project = strings.Trim(strings.TrimPrefix(remoteOrigin, origin), "/")
auth.url = origin
} else {
auth.project = strings.Trim(originUrl.Path, "/")
auth.url = strings.TrimSuffix(remoteOrigin, originUrl.Path)
}
return nil
}
// testHomeDir is empty for normal use. During tests it may be set and used
// in place of the actual home directory. Tests may still need to
// set the HOME var for sub-processes such as git.
var testHomeDir = ""
func netrcName() string {
// Git on Windows will look in $HOME\_netrc.
if runtime.GOOS == "windows" {
return "_netrc"
}
return ".netrc"
}
// loadAuth loads the authentication tokens for making API calls to
// the Gerrit origin host.
func loadAuth() {
if auth.user != "" || auth.cookieName != "" {
return
}
loadGerritOrigin()
// First look in Git's http.cookiefile, which is where Gerrit
// now tells users to store this information.
if cookieFile, _ := trimErr(cmdOutputErr("git", "config", "--path", "--get-urlmatch", "http.cookiefile", auth.url)); cookieFile != "" {
data, _ := os.ReadFile(cookieFile)
maxMatch := -1
for _, line := range lines(string(data)) {
f := strings.Split(line, "\t")
if len(f) >= 7 && (f[0] == auth.host || strings.HasPrefix(f[0], ".") && strings.HasSuffix(auth.host, f[0])) {
if len(f[0]) > maxMatch {
auth.cookieName = f[5]
auth.cookieValue = f[6]
maxMatch = len(f[0])
}
}
}
if maxMatch > 0 {
return
}
}
// If not there, then look in $HOME/.netrc, which is where Gerrit
// used to tell users to store the information, until the passwords
// got so long that old versions of curl couldn't handle them.
netrc := netrcName()
homeDir := testHomeDir
if homeDir == "" {
usr, err := user.Current()
if err != nil {
dief("failed to get current user home directory to look for %q: %v", netrc, err)
}
homeDir = usr.HomeDir
}
data, _ := os.ReadFile(filepath.Join(homeDir, netrc))
for _, line := range lines(string(data)) {
if i := strings.Index(line, "#"); i >= 0 {
line = line[:i]
}
f := strings.Fields(line)
if len(f) >= 6 && f[0] == "machine" && f[1] == auth.host && f[2] == "login" && f[4] == "password" {
auth.user = f[3]
auth.password = f[5]
return
}
}
dief("cannot find authentication info for %s", auth.host)
}
// gerritError is an HTTP error response served by Gerrit.
type gerritError struct {
url string
statusCode int
status string
body string
}
func (e *gerritError) Error() string {
if e.statusCode == http.StatusNotFound {
return "change not found on Gerrit server"
}
extra := strings.TrimSpace(e.body)
if extra != "" {
extra = ": " + extra
}
return fmt.Sprintf("%s%s", e.status, extra)
}
// gerritAPI executes a GET or POST request to a Gerrit API endpoint.
// It uses GET when requestBody is nil, otherwise POST. If target != nil,
// gerritAPI expects to get a 200 response with a body consisting of an
// anti-xss line (]})' or some such) followed by JSON.
// If requestBody != nil, gerritAPI sets the Content-Type to application/json.
func gerritAPI(path string, requestBody []byte, target interface{}) (err error) {
var respBodyBytes []byte
defer func() {
if err != nil {
// os.Stderr, not stderr(), because the latter is not safe for
// use from multiple goroutines.
fmt.Fprintf(os.Stderr, "git-codereview: fetch %s: %v\n", path, err)
if len(respBodyBytes) > 0 {
fmt.Fprintf(os.Stderr, "Gerrit response:\n%s\n", respBodyBytes)
}
}
}()
// Strictly speaking, we might be able to use unauthenticated
// access, by removing the /a/ from the URL, but that assumes
// that all the information we care about is publicly visible.
// Using authentication makes it possible for this to work with
// non-public CLs or Gerrit hosts too.
loadAuth()
if !strings.HasPrefix(path, "/") {
dief("internal error: gerritAPI called with malformed path")
}
url := auth.url + path
method := "GET"
var reader io.Reader
if requestBody != nil {
method = "POST"
reader = bytes.NewReader(requestBody)
}
req, err := http.NewRequest(method, url, reader)
if err != nil {
return err
}
if requestBody != nil {
req.Header.Set("Content-Type", "application/json")
}
if auth.cookieName != "" {
req.AddCookie(&http.Cookie{
Name: auth.cookieName,
Value: auth.cookieValue,
})
} else {
req.SetBasicAuth(auth.user, auth.password)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
respBodyBytes = body
if err != nil {
return fmt.Errorf("reading response body: %v", err)
}
if resp.StatusCode != http.StatusOK {
return &gerritError{url, resp.StatusCode, resp.Status, string(body)}
}
if target != nil {
i := bytes.IndexByte(body, '\n')
if i < 0 {
return fmt.Errorf("%s: malformed json response - bad header", url)
}
body = body[i:]
if err := json.Unmarshal(body, target); err != nil {
return fmt.Errorf("%s: malformed json response", url)
}
}
return nil
}
// fullChangeID returns the unambigous Gerrit change ID for the commit c on branch b.
// The returned ID has the form project~originbranch~Ihexhexhexhexhex.
// See https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-id for details.
func fullChangeID(b *Branch, c *Commit) string {
loadGerritOrigin()
return auth.project + "~" + strings.TrimPrefix(b.OriginBranch(), "origin/") + "~" + c.ChangeID
}
// readGerritChange reads the metadata about a change from the Gerrit server.
// The changeID should use the syntax project~originbranch~Ihexhexhexhexhex returned
// by fullChangeID. Using only Ihexhexhexhexhex will work provided it uniquely identifies
// a single change on the server.
// The changeID can have additional query parameters appended to it, as in "normalid?o=LABELS".
// See https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-id for details.
func readGerritChange(changeID string) (*GerritChange, error) {
var c GerritChange
err := gerritAPI("/a/changes/"+changeID, nil, &c)
if err != nil {
return nil, err
}
return &c, nil
}
// readGerritChanges is like readGerritChange but expects changeID
// to be a query parameter list like q=change:XXX&q=change:YYY&o=OPTIONS,
// and it expects to receive a JSON array of GerritChanges, not just one.
func readGerritChanges(query string) ([][]*GerritChange, error) {
// The Gerrit server imposes a limit of at most 10 q= parameters.
v, err := url.ParseQuery(query)
if err != nil {
return nil, err
}
var results []chan gerritChangeResult
for len(v["q"]) > 0 {
n := len(v["q"])
if n > 10 {
n = 10
}
all := v["q"]
v["q"] = all[:n]
query := v.Encode()
v["q"] = all[n:]
ch := make(chan gerritChangeResult, 1)
go readGerritChangesBatch(query, n, ch)
results = append(results, ch)
}
var c [][]*GerritChange
for _, ch := range results {
res := <-ch
if res.err != nil {
return nil, res.err
}
c = append(c, res.c...)
}
return c, nil
}
type gerritChangeResult struct {
c [][]*GerritChange
err error
}
func readGerritChangesBatch(query string, n int, ch chan gerritChangeResult) {
var c [][]*GerritChange
// If there are multiple q=, the server sends back an array of arrays of results.
// If there is a single q=, it only sends back an array of results; in that case
// we need to do the wrapping ourselves.
var arg interface{} = &c
if n == 1 {
c = append(c, nil)
arg = &c[0]
}
err := gerritAPI("/a/changes/?"+query, nil, arg)
if len(c) != n && err == nil {
err = fmt.Errorf("gerrit result count mismatch")
}
ch <- gerritChangeResult{c, err}
}
// GerritChange is the JSON struct for a Gerrit ChangeInfo, returned by a Gerrit CL query.
type GerritChange struct {
ID string
Project string
Branch string
ChangeId string `json:"change_id"`
Subject string
Status string
Created string
Updated string
Insertions int
Deletions int
Number int `json:"_number"`
Owner *GerritAccount
Labels map[string]*GerritLabel
CurrentRevision string `json:"current_revision"`
Revisions map[string]*GerritRevision
Messages []*GerritMessage
TotalCommentCount int `json:"total_comment_count"`
UnresolvedCommentCount int `json:"unresolved_comment_count"`
}
// LabelNames returns the label names for the change, in lexicographic order.
func (g *GerritChange) LabelNames() []string {
var names []string
for name := range g.Labels {
names = append(names, name)
}
sort.Strings(names)
return names
}
// GerritMessage is the JSON struct for a Gerrit MessageInfo.
type GerritMessage struct {
Author struct {
Name string
}
Message string
}
// GerritLabel is the JSON struct for a Gerrit LabelInfo.
type GerritLabel struct {
Optional bool
Blocking bool
Approved *GerritAccount
Rejected *GerritAccount
All []*GerritApproval
}
// GerritAccount is the JSON struct for a Gerrit AccountInfo.
type GerritAccount struct {
ID int `json:"_account_id"`
Name string
Email string
Username string
}
// GerritApproval is the JSON struct for a Gerrit ApprovalInfo.
type GerritApproval struct {
GerritAccount
Value int
Date string
}
// GerritRevision is the JSON struct for a Gerrit RevisionInfo.
type GerritRevision struct {
Number int `json:"_number"`
Ref string
Fetch map[string]*GerritFetch
}
// GerritFetch is the JSON struct for a Gerrit FetchInfo.
type GerritFetch struct {
URL string
Ref string
}
// GerritComment is the JSON struct for a Gerrit CommentInfo.
type GerritComment struct {
PatchSet string `json:"patch_set"`
ID string
Path string
Side string
Parent string
Line string
Range *GerritCommentRange
InReplyTo string
Message string
Updated string
Author *GerritAccount
Tag string
Unresolved bool
ChangeMessageID string `json:"change_message_id"`
CommitID string `json:"commit_id"` // SHA1 hex
}
// GerritCommentRange is the JSON struct for a Gerrit CommentRange.
type GerritCommentRange struct {
StartLine int `json:"start_line"` // 1-based
StartCharacter int `json:"start_character"` // 0-based
EndLine int `json:"end_line"` // 1-based
EndCharacter int `json:"end_character"` // 0-based
}
// GerritContextLine is the JSON struct for a Gerrit ContextLine.
type GerritContextLine struct {
LineNumber int `json:"line_number"` // 1-based
ContextLine string `json:"context_line"`
}
// GerritCommentInput is the JSON struct for a Gerrit CommentInput.
type GerritCommentInput struct {
ID string `json:"id,omitempty"` // ID of a draft comment to update
Path string `json:"path,omitempty"` // file to attach comment to
Side string `json:"side,omitempty"` // REVISION (default) or PARENT
Line int `json:"line,omitempty"` // 0 to use range (or else file comment)
Range *GerritCommentRange `json:"range,omitempty"`
InReplyTo string `json:"in_reply_to,omitempty"` // ID of comment being replied to
Message string `json:"message,omitempty"`
Unresolved *bool `json:"unresolved,omitempty"` // defaults to parent setting or else false
}
|
dl
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/CONTRIBUTING.md
|
# Contributing to Go
Go is an open source project.
It is the work of hundreds of contributors. We appreciate your help!
## Filing issues
When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions:
1. What version of Go are you using (`go version`)?
2. What operating system and processor architecture are you using?
3. What did you do?
4. What did you expect to see?
5. What did you see instead?
General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker.
The gophers there will answer or ask you to file an issue if you've tripped over a bug.
## Contributing code
Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html)
before sending patches.
Unless otherwise noted, the Go source files are distributed under
the BSD-style license found in the LICENSE file.
|
dl
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/PATENTS
|
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
|
dl
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go.mod
|
module golang.org/dl
go 1.18
|
dl
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/README.md
|
# golang.org/dl
This repository holds the Go wrapper programs that run specific versions of Go, such
as `go install golang.org/dl/go1.10.3@latest` and `go install golang.org/dl/gotip@latest`.
## Report Issues / Send Patches
This repository uses Gerrit for code changes. To learn how to submit
changes to this repository, see https://golang.org/doc/contribute.html.
The main issue tracker for the net repository is located at
https://github.com/golang/go/issues. Prefix your issue with "dl:" in the
subject line, so it is easy to find.
|
dl
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/LICENSE
|
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
dl
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/codereview.cfg
|
issuerepo: golang/go
|
go1.17.13
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.17.13/main.go
|
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.17.13 command runs the go command from Go 1.17.13.
//
// To install, run:
//
// $ go install golang.org/dl/go1.17.13@latest
// $ go1.17.13 download
//
// And then use the go1.17.13 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.17.minor.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.17.13")
}
|
go1.14rc1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.14rc1/main.go
|
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.14rc1 command runs the go command from Go 1.14rc1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.14rc1@latest
// $ go1.14rc1 download
//
// And then use the go1.14rc1 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.14
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.14rc1")
}
|
go1.10.6
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.10.6/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.10.6 command runs the go command from Go 1.10.6.
//
// To install, run:
//
// $ go install golang.org/dl/go1.10.6@latest
// $ go1.10.6 download
//
// And then use the go1.10.6 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.10.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.10.6")
}
|
go1.14.2
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.14.2/main.go
|
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.14.2 command runs the go command from Go 1.14.2.
//
// To install, run:
//
// $ go install golang.org/dl/go1.14.2@latest
// $ go1.14.2 download
//
// And then use the go1.14.2 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.14.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.14.2")
}
|
go1.9.6
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.9.6/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.9.6 command runs the go command from Go 1.9.6.
//
// To install, run:
//
// $ go install golang.org/dl/go1.9.6@latest
// $ go1.9.6 download
//
// And then use the go1.9.6 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.9.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.9.6")
}
|
go1.15.10
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.15.10/main.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.15.10 command runs the go command from Go 1.15.10.
//
// To install, run:
//
// $ go install golang.org/dl/go1.15.10@latest
// $ go1.15.10 download
//
// And then use the go1.15.10 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.15.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.15.10")
}
|
go1.16.6
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.16.6/main.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.16.6 command runs the go command from Go 1.16.6.
//
// To install, run:
//
// $ go install golang.org/dl/go1.16.6@latest
// $ go1.16.6 download
//
// And then use the go1.16.6 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.16.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.16.6")
}
|
go1.12beta1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.12beta1/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.12beta1 command runs the go command from Go 1.12beta1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.12beta1@latest
// $ go1.12beta1 download
//
// And then use the go1.12beta1 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.12
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.12beta1")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.