{"id": "patchbench-go-real-0028", "repo": "knative/eventing", "base_commit": "5bcf8011acc8310ca0e469e507c1b4c757de4fff", "status": "p2p_regression", "verify_status": null, "error": null, "timing": {"setup": 6.7, "pre_test_0": 419.7, "pre_test_1": 81.7, "post_test_0": 221.9, "post_test_1": 137.9, "total": 868.1}, "test_cmds": ["/usr/local/go/bin/go test -v ./... -json > reports/go-test-results.json"], "rebuild_cmds": [], "print_cmds": [], "f2p_pre_ok": true, "pre_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 2869}, "f2p_post_ok": true, "p2p_post_ok": false, "post_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 2891}, "raw_tail": "http\",\"Output\":\"? \\tknative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/go-retryablehttp\\t[no test files]\\n\"}\n{\"Time\":\"2026-09-10T09:26:43.458421087Z\",\"Action\":\"skip\",\"Package\":\"knative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/go-retryablehttp\",\"Elapsed\":0}\n{\"Time\":\"2026-09-10T09:26:43.458487059Z\",\"Action\":\"start\",\"Package\":\"knative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru\"}\n{\"Time\":\"2026-09-10T09:26:43.458511025Z\",\"Action\":\"output\",\"Package\":\"knative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru\",\"Output\":\"? \\tknative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru\\t[no test files]\\n\"}\n{\"Time\":\"2026-09-10T09:26:43.458516952Z\",\"Action\":\"skip\",\"Package\":\"knative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru\",\"Elapsed\":0}\n{\"Time\":\"2026-09-10T09:26:43.492614267Z\",\"Action\":\"start\",\"Package\":\"knative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru/simplelru\"}\n{\"Time\":\"2026-09-10T09:26:43.492645014Z\",\"Action\":\"output\",\"Package\":\"knative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru/simplelru\",\"Output\":\"? \\tknative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru/simplelru\\t[no test files]\\n\"}\n{\"Time\":\"2026-09-10T09:26:43.492652526Z\",\"Action\":\"skip\",\"Package\":\"knative.dev/eventing/third_party/VENDOR-LICENSE/github.com/hashicorp/golang-lru/simplelru\",\"Elapsed\":0}\n\n"} {"id": "patchbench-go-real-0006", "repo": "ossf/scorecard", "base_commit": "4feedb857ab8d82158aa9774bf8054df41992180", "status": "verified", "verify_status": "verified", "error": null, "timing": {"setup": 6.8, "pre_test_0": 805.7, "pre_test_1": 609.6, "post_test_0": 619.5, "post_test_1": 607.6, "total": 2650.1}, "test_cmds": ["go test -v ./... -json > reports/go-test-results.json"], "rebuild_cmds": [], "print_cmds": [], "f2p_pre_ok": true, "pre_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 2282}, "f2p_post_ok": true, "p2p_post_ok": true, "post_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 2283}, "raw_tail": "om/onsi/ginkgo/v2/internal.extractBodyFunction.func3({0xc000181c00?, 0xc00007a008?})\\n\"}\n{\"Time\":\"2026-09-10T09:47:38.133470285Z\",\"Action\":\"output\",\"Package\":\"github.com/ossf/scorecard/v5/pkg/scorecard\",\"Test\":\"TestPkg\",\"Output\":\"\\t/go/pkg/mod/github.com/onsi/ginkgo/v2@v2.23.4/internal/node.go:475 +0x13\\n\"}\n{\"Time\":\"2026-09-10T09:47:38.133476515Z\",\"Action\":\"output\",\"Package\":\"github.com/ossf/scorecard/v5/pkg/scorecard\",\"Test\":\"TestPkg\",\"Output\":\"github.com/onsi/ginkgo/v2/internal.(*Suite).runNode.func3()\\n\"}\n{\"Time\":\"2026-09-10T09:47:38.133481245Z\",\"Action\":\"output\",\"Package\":\"github.com/ossf/scorecard/v5/pkg/scorecard\",\"Test\":\"TestPkg\",\"Output\":\"\\t/go/pkg/mod/github.com/onsi/ginkgo/v2@v2.23.4/internal/suite.go:894 +0x7b\\n\"}\n{\"Time\":\"2026-09-10T09:47:38.133487337Z\",\"Action\":\"output\",\"Package\":\"github.com/ossf/scorecard/v5/pkg/scorecard\",\"Test\":\"TestPkg\",\"Output\":\"created by github.com/onsi/ginkgo/v2/internal.(*Suite).runNode in goroutine 79\\n\"}\n{\"Time\":\"2026-09-10T09:47:38.133492727Z\",\"Action\":\"output\",\"Package\":\"github.com/ossf/scorecard/v5/pkg/scorecard\",\"Test\":\"TestPkg\",\"Output\":\"\\t/go/pkg/mod/github.com/onsi/ginkgo/v2@v2.23.4/internal/suite.go:881 +0xd50\\n\"}\n{\"Time\":\"2026-09-10T09:47:38.135697298Z\",\"Action\":\"output\",\"Package\":\"github.com/ossf/scorecard/v5/pkg/scorecard\",\"Output\":\"FAIL\\tgithub.com/ossf/scorecard/v5/pkg/scorecard\\t600.036s\\n\"}\n{\"Time\":\"2026-09-10T09:47:38.135749148Z\",\"Action\":\"fail\",\"Package\":\"github.com/ossf/scorecard/v5/pkg/scorecard\",\"Elapsed\":600.036}\n\n", "context_files": [{"path": "probes/releasesAreSigned/impl.go", "content": "// Copyright 2023 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//nolint:stylecheck\npackage releasesAreSigned\n\nimport (\n\t\"embed\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/ossf/scorecard/v5/checker\"\n\t\"github.com/ossf/scorecard/v5/finding\"\n\t\"github.com/ossf/scorecard/v5/internal/checknames\"\n\t\"github.com/ossf/scorecard/v5/internal/probes\"\n\t\"github.com/ossf/scorecard/v5/probes/internal/utils/uerror\"\n)\n\nfunc init() {\n\tprobes.MustRegister(Probe, Run, []checknames.CheckName{checknames.SignedReleases})\n}\n\n//go:embed *.yml\nvar fs embed.FS\n\nconst (\n\tProbe = \"releasesAreSigned\"\n\tReleaseNameKey = \"releaseName\"\n\tAssetNameKey = \"assetName\"\n\treleaseLookBack = 5\n)\n\nvar signatureExtensions = []string{\".asc\", \".minisig\", \".sig\", \".sign\", \".sigstore\", \".sigstore.json\"}\n\nfunc Run(raw *checker.RawResults) ([]finding.Finding, string, error) {\n\tif raw == nil {\n\t\treturn nil, \"\", fmt.Errorf(\"%w: raw\", uerror.ErrNil)\n\t}\n\n\tvar findings []finding.Finding\n\n\treleases := raw.SignedReleasesResults.Releases\n\n\ttotalReleases := 0\n\tfor releaseIndex, release := range releases {\n\t\tif releaseIndex >= releaseLookBack {\n\t\t\tbreak\n\t\t}\n\n\t\tif len(release.Assets) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalReleases++\n\t\tsigned := false\n\t\tfor j := range release.Assets {\n\t\t\tasset := release.Assets[j]\n\t\t\tfor _, suffix := range signatureExtensions {\n\t\t\t\tif !strings.HasSuffix(asset.Name, suffix) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Create True Finding\n\t\t\t\t// with file info\n\t\t\t\tloc := &finding.Location{\n\t\t\t\t\tType: finding.FileTypeURL,\n\t\t\t\t\tPath: asset.URL,\n\t\t\t\t}\n\t\t\t\tf, err := finding.NewWith(fs, Probe,\n\t\t\t\t\tfmt.Sprintf(\"signed release artifact: %s\", asset.Name),\n\t\t\t\t\tloc,\n\t\t\t\t\tfinding.OutcomeTrue)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, Probe, fmt.Errorf(\"create finding: %w\", err)\n\t\t\t\t}\n\t\t\t\tf.Values = map[string]string{\n\t\t\t\t\tReleaseNameKey: release.TagName,\n\t\t\t\t\tAssetNameKey: asset.Name,\n\t\t\t\t}\n\t\t\t\tfindings = append(findings, *f)\n\t\t\t\tsigned = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif signed {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif signed {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Release is not signed\n\t\tloc := &finding.Location{\n\t\t\tType: finding.FileTypeURL,\n\t\t\tPath: release.URL,\n\t\t}\n\t\tf, err := finding.NewWith(fs, Probe,\n\t\t\tfmt.Sprintf(\"release artifact %s not signed\", release.TagName),\n\t\t\tloc,\n\t\t\tfinding.OutcomeFalse)\n\t\tif err != nil {\n\t\t\treturn nil, Probe, fmt.Errorf(\"create finding: %w\", err)\n\t\t}\n\t\tf = f.WithValue(ReleaseNameKey, release.TagName)\n\t\tfindings = append(findings, *f)\n\t}\n\n\tif len(findings) == 0 {\n\t\tf, err := finding.NewWith(fs, Probe,\n\t\t\t\"no GitHub/GitLab releases found\",\n\t\t\tnil,\n\t\t\tfinding.OutcomeNotApplicable)\n\t\tif err != nil {\n\t\t\treturn nil, Probe, fmt.Errorf(\"create finding: %w\", err)\n\t\t}\n\t\tfindings = append(findings, *f)\n\t}\n\treturn findings, Probe, nil\n}\n"}, {"path": "docs/checks/internal/reader.go", "content": "// Copyright 2021 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Package internal contains internal functions for reading input YAML file.\npackage internal\n\nimport (\n\t// Used to embed `checks.yaml` file.\n\t_ \"embed\"\n\t\"fmt\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\n//go:embed checks.yaml\nvar checksYAML []byte\n\n// Check stores a check's information.\n//\n//nolint:govet\ntype Check struct {\n\tRisk string `yaml:\"risk\"`\n\tShort string `yaml:\"short\"`\n\tDescription string `yaml:\"description\"`\n\tTags string `yaml:\"tags\"`\n\tRepos string `yaml:\"repos\"`\n\tRemediation []string `yaml:\"remediation\"`\n\tName string `yaml:\"-\"`\n\tURL string `yaml:\"-\"`\n}\n\n// Doc stores the documentation for all checks.\ntype Doc struct {\n\tInternalChecks map[string]Check `yaml:\"checks\"`\n}\n\n// ReadDoc reads documentation from the `checks.yaml` file.\nfunc ReadDoc() (Doc, error) {\n\tvar m Doc\n\tif err := yaml.Unmarshal(checksYAML, &m); err != nil {\n\t\treturn Doc{}, fmt.Errorf(\"yaml.Unmarshal: %w\", err)\n\t}\n\treturn m, nil\n}\n"}, {"path": "probes/releasesAreSigned/impl_test.go", "content": "// Copyright 2023 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//nolint:stylecheck\npackage releasesAreSigned\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\n\t\"github.com/ossf/scorecard/v5/checker\"\n\t\"github.com/ossf/scorecard/v5/clients\"\n\t\"github.com/ossf/scorecard/v5/finding\"\n\t\"github.com/ossf/scorecard/v5/probes/internal/utils/test\"\n)\n\nfunc Test_Run(t *testing.T) {\n\tt.Parallel()\n\t//nolint:govet\n\ttests := []struct {\n\t\tname string\n\t\traw *checker.RawResults\n\t\toutcomes []finding.Outcome\n\t\terr error\n\t}{\n\t\t{\n\t\t\tname: \"Has one signed release.\",\n\t\t\traw: &checker.RawResults{\n\t\t\t\tSignedReleasesResults: checker.SignedReleasesData{\n\t\t\t\t\tReleases: []clients.Release{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v1.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.sig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutcomes: []finding.Outcome{\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Has two signed releases.\",\n\t\t\traw: &checker.RawResults{\n\t\t\t\tSignedReleasesResults: checker.SignedReleasesData{\n\t\t\t\t\tReleases: []clients.Release{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v1.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.sig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v2.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.sig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutcomes: []finding.Outcome{\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Has two unsigned releases.\",\n\t\t\traw: &checker.RawResults{\n\t\t\t\tSignedReleasesResults: checker.SignedReleasesData{\n\t\t\t\t\tReleases: []clients.Release{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v1.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.notSig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v2.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.notSig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutcomes: []finding.Outcome{\n\t\t\t\tfinding.OutcomeFalse,\n\t\t\t\tfinding.OutcomeFalse,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Has two unsigned releases and one signed release.\",\n\t\t\traw: &checker.RawResults{\n\t\t\t\tSignedReleasesResults: checker.SignedReleasesData{\n\t\t\t\t\tReleases: []clients.Release{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v1.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.notSig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v2.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.sig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tTagName: \"v3.0\",\n\t\t\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.notSig\"},\n\t\t\t\t\t\t\t\t{Name: \"binary.tar.gz.intoto.jsonl\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutcomes: []finding.Outcome{\n\t\t\t\tfinding.OutcomeFalse,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeFalse,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Many releases.\",\n\t\t\traw: &checker.RawResults{\n\t\t\t\tSignedReleasesResults: checker.SignedReleasesData{\n\t\t\t\t\tReleases: []clients.Release{\n\t\t\t\t\t\trelease(\"v0.8.5\"),\n\t\t\t\t\t\trelease(\"v0.8.4\"),\n\t\t\t\t\t\trelease(\"v0.8.3\"),\n\t\t\t\t\t\trelease(\"v0.8.2\"),\n\t\t\t\t\t\trelease(\"v0.8.1\"),\n\t\t\t\t\t\trelease(\"v0.8.0\"),\n\t\t\t\t\t\trelease(\"v0.7.0\"),\n\t\t\t\t\t\trelease(\"v0.6.0\"),\n\t\t\t\t\t\trelease(\"v0.5.0\"),\n\t\t\t\t\t\trelease(\"v0.4.0\"),\n\t\t\t\t\t\trelease(\"v0.3.0\"),\n\t\t\t\t\t\trelease(\"v0.2.0\"),\n\t\t\t\t\t\trelease(\"v0.1.0\"),\n\t\t\t\t\t\trelease(\"v0.0.6\"),\n\t\t\t\t\t\trelease(\"v0.0.5\"),\n\t\t\t\t\t\trelease(\"v0.0.4\"),\n\t\t\t\t\t\trelease(\"v0.0.3\"),\n\t\t\t\t\t\trelease(\"v0.0.2\"),\n\t\t\t\t\t\trelease(\"v0.0.1\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutcomes: []finding.Outcome{\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// https://github.com/ossf/scorecard/issues/4059\n\t\t\tname: \"lookback cutoff not skipped if 6th release has no assets\",\n\t\t\traw: &checker.RawResults{\n\t\t\t\tSignedReleasesResults: checker.SignedReleasesData{\n\t\t\t\t\tReleases: []clients.Release{\n\t\t\t\t\t\trelease(\"v0.8.5\"),\n\t\t\t\t\t\trelease(\"v0.8.4\"),\n\t\t\t\t\t\trelease(\"v0.8.3\"),\n\t\t\t\t\t\trelease(\"v0.8.2\"),\n\t\t\t\t\t\trelease(\"v0.8.1\"),\n\t\t\t\t\t\treleaseNoAssets(\"v0.8.0\"),\n\t\t\t\t\t\trelease(\"v0.7.0\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutcomes: []finding.Outcome{\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t\tfinding.OutcomeTrue,\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tfindings, s, err := Run(tt.raw)\n\t\t\tif !cmp.Equal(tt.err, err, cmpopts.EquateErrors()) {\n\t\t\t\tt.Errorf(\"mismatch (-want +got):\\n%s\", cmp.Diff(tt.err, err, cmpopts.EquateErrors()))\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif diff := cmp.Diff(Probe, s); diff != \"\" {\n\t\t\t\tt.Errorf(\"mismatch (-want +got):\\n%s\", diff)\n\t\t\t}\n\t\t\ttest.AssertOutcomes(t, findings, tt.outcomes)\n\t\t})\n\t}\n}\n\nfunc release(version string) clients.Release {\n\treturn clients.Release{\n\t\tTagName: version,\n\t\tURL: fmt.Sprintf(\"https://github.com/test/test_artifact/releases/tag/%s\", version),\n\t\tTargetCommitish: \"master\",\n\t\tAssets: []clients.ReleaseAsset{\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_checksums.txt\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_checksums.txt\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_checksums.txt.sig\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_checksums.txt.sig\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_darwin_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_darwin_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_arm64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_arm64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_i386.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_i386.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_windows_i386.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_windows_i386.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_windows_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_windows_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc releaseNoAssets(version string) clients.Release {\n\treturn clients.Release{\n\t\tTagName: version,\n\t\tURL: fmt.Sprintf(\"https://github.com/test/test_artifact/releases/tag/%s\", version),\n\t\tTargetCommitish: \"master\",\n\t\tAssets: []clients.ReleaseAsset{},\n\t}\n}\n"}, {"path": "checks/signed_releases_test.go", "content": "// Copyright 2020 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage checks\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"go.uber.org/mock/gomock\"\n\n\t\"github.com/ossf/scorecard/v5/checker\"\n\t\"github.com/ossf/scorecard/v5/clients\"\n\tmockrepo \"github.com/ossf/scorecard/v5/clients/mockclients\"\n\t\"github.com/ossf/scorecard/v5/internal/packageclient\"\n\tscut \"github.com/ossf/scorecard/v5/utests\"\n)\n\nfunc TestSignedRelease(t *testing.T) {\n\tt.Parallel()\n\ttests := []struct {\n\t\terr error\n\t\tname string\n\t\treleases []clients.Release\n\t\texpected checker.CheckResult\n\t}{\n\t\t{\n\t\t\tname: \"NoReleases\",\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with no assets\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets without signed artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 0,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-asc\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.asc\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.asc\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with intoto SLSA provenance\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.intoto.jsonl\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.intoto.jsonl\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 10,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sig\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sign\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sign\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sign\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-minisig\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sigstore\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sigstore\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sigstore\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sigstore-json\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sigstore.json\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sigstore.json\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed and unsigned artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple Releases with assets with signed and unsigned artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v2.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Some releases with assets with signed and unsigned artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v2.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 4,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"6 Releases with assets with signed artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v2.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v3.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v4.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v5.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v6.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"Error getting releases\",\n\t\t\terr: errors.New(\"Error getting releases\"),\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t\tError: errors.New(\"Error getting releases\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"9 Releases with assets with signed artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\trelease(\"v0.8.5\"),\n\t\t\t\trelease(\"v0.8.4\"),\n\t\t\t\trelease(\"v0.8.3\"),\n\t\t\t\trelease(\"v0.8.2\"),\n\t\t\t\trelease(\"v0.8.1\"),\n\t\t\t\trelease(\"v0.8.0\"),\n\t\t\t\trelease(\"v0.7.0\"),\n\t\t\t\trelease(\"v0.6.0\"),\n\t\t\t\trelease(\"v0.5.0\"),\n\t\t\t\trelease(\"v0.4.0\"),\n\t\t\t\trelease(\"v0.3.0\"),\n\t\t\t\trelease(\"v0.2.0\"),\n\t\t\t\trelease(\"v0.1.0\"),\n\t\t\t\trelease(\"v0.0.6\"),\n\t\t\t\trelease(\"v0.0.5\"),\n\t\t\t\trelease(\"v0.0.4\"),\n\t\t\t\trelease(\"v0.0.3\"),\n\t\t\t\trelease(\"v0.0.2\"),\n\t\t\t\trelease(\"v0.0.1\"),\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"Error getting releases\",\n\t\t\terr: errors.New(\"Error getting releases\"),\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t\tError: errors.New(\"Error getting releases\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tctrl := gomock.NewController(t)\n\n\t\t\tmockRepoC := mockrepo.NewMockRepoClient(ctrl)\n\t\t\tmockRepoC.EXPECT().ListReleases().DoAndReturn(\n\t\t\t\tfunc() ([]clients.Release, error) {\n\t\t\t\t\tif tt.err != nil {\n\t\t\t\t\t\treturn nil, tt.err\n\t\t\t\t\t}\n\t\t\t\t\treturn tt.releases, tt.err\n\t\t\t\t},\n\t\t\t).MinTimes(1)\n\n\t\t\tmockRepo := mockrepo.NewMockRepo(ctrl)\n\t\t\tmockRepo.EXPECT().Host().DoAndReturn(\n\t\t\t\tfunc() string {\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t).AnyTimes()\n\t\t\tmockRepo.EXPECT().Path().DoAndReturn(\n\t\t\t\tfunc() string {\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t).AnyTimes()\n\n\t\t\tmockPkgC := mockrepo.NewMockProjectPackageClient(ctrl)\n\t\t\tmockPkgC.EXPECT().GetProjectPackageVersions(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(\n\t\t\t\tfunc(ctx context.Context, host, project string) (*packageclient.ProjectPackageVersions, error) {\n\t\t\t\t\tv := packageclient.ProjectPackageVersions{}\n\t\t\t\t\treturn &v, nil\n\t\t\t\t},\n\t\t\t).AnyTimes()\n\n\t\t\treq := checker.CheckRequest{\n\t\t\t\tRepoClient: mockRepoC,\n\t\t\t\tRepo: mockRepo,\n\t\t\t\tProjectClient: mockPkgC,\n\t\t\t}\n\t\t\treq.Dlogger = &scut.TestDetailLogger{}\n\t\t\tres := SignedReleases(&req)\n\n\t\t\tif tt.err != nil {\n\t\t\t\tif res.Error == nil {\n\t\t\t\t\tt.Errorf(\"Expected error %v, got nil\", tt.err)\n\t\t\t\t}\n\t\t\t\t// return as we don't need to check the rest of the fields.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif res.Score != tt.expected.Score {\n\t\t\t\tt.Errorf(\"Expected score %d, got %d for %v\", tt.expected.Score, res.Score, tt.name)\n\t\t\t}\n\t\t\tctrl.Finish()\n\t\t})\n\t}\n}\n\nfunc release(version string) clients.Release {\n\treturn clients.Release{\n\t\tTagName: version,\n\t\tURL: fmt.Sprintf(\"https://github.com/test/test_artifact/releases/tag/%s\", version),\n\t\tTargetCommitish: \"master\",\n\t\tAssets: []clients.ReleaseAsset{\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_checksums.txt\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_checksums.txt\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_checksums.txt.sig\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_checksums.txt.sig\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_darwin_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_darwin_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_arm64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_arm64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_i386.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_i386.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_windows_i386.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_windows_i386.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_windows_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_windows_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t},\n\t}\n}\n"}, {"path": "attestor/command/check.go", "content": "// Copyright 2022 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//\thttp://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage command\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/ossf/scorecard/v5/attestor/policy\"\n\t\"github.com/ossf/scorecard/v5/checker\"\n\tsclog \"github.com/ossf/scorecard/v5/log\"\n\t\"github.com/ossf/scorecard/v5/pkg/scorecard\"\n)\n\ntype EmptyParameterError struct {\n\tParam string\n}\n\nfunc (ep EmptyParameterError) Error() string {\n\treturn fmt.Sprintf(\"param %s is empty\", ep.Param)\n}\n\nfunc runCheck() (policy.PolicyResult, error) {\n\treturn RunCheckWithParams(repoURL, commitSHA, policyPath)\n}\n\n// RunCheckWithParams: Run scorecard check on repo. Export for testability.\nfunc RunCheckWithParams(repoURL, commitSHA, policyPath string) (policy.PolicyResult, error) {\n\tctx := context.Background()\n\tlogger := sclog.NewLogger(sclog.DefaultLevel)\n\n\t// Read the Binauthz attestation policy\n\tif policyPath == \"\" {\n\t\treturn policy.Fail, EmptyParameterError{Param: \"policy\"}\n\t}\n\n\tvar attestationPolicy *policy.AttestationPolicy\n\n\tattestationPolicy, err := policy.ParseAttestationPolicyFromFile(policyPath)\n\tif err != nil {\n\t\treturn policy.Fail, fmt.Errorf(\"fail to load scorecard attestation policy: %w\", err)\n\t}\n\n\tif repoURL == \"\" {\n\t\tbuildRepo := os.Getenv(\"REPO_NAME\")\n\t\tif buildRepo == \"\" {\n\t\t\treturn policy.Fail, EmptyParameterError{Param: \"repoURL\"}\n\t\t}\n\t\trepoURL = buildRepo\n\t\tlogger.Info(fmt.Sprintf(\"Found repo URL %s Cloud Build environment\", repoURL))\n\t} else {\n\t\tlogger.Info(fmt.Sprintf(\"Running scorecard on %s\", repoURL))\n\t}\n\n\tif commitSHA == \"\" {\n\t\tbuildSHA := os.Getenv(\"COMMIT_SHA\")\n\t\tif buildSHA == \"\" {\n\t\t\tlogger.Info(\"commit not specified, running on HEAD\")\n\t\t\tcommitSHA = \"HEAD\"\n\t\t} else {\n\t\t\tcommitSHA = buildSHA\n\t\t\tlogger.Info(fmt.Sprintf(\"Found revision %s from GCB build environment\", commitSHA))\n\t\t}\n\t}\n\n\trepo, repoClient, ossFuzzRepoClient, ciiClient, vulnsClient, _, err := checker.GetClients(\n\t\tctx, repoURL, \"\", logger)\n\tif err != nil {\n\t\treturn policy.Fail, fmt.Errorf(\"couldn't set up clients: %w\", err)\n\t}\n\n\trequiredChecks := attestationPolicy.GetRequiredChecksForPolicy()\n\n\tvar enabledChecks []string\n\tfor check, required := range requiredChecks {\n\t\tif required {\n\t\t\tenabledChecks = append(enabledChecks, check)\n\t\t}\n\t}\n\n\trepoResult, err := scorecard.Run(ctx, repo,\n\t\tscorecard.WithCommitSHA(commitSHA),\n\t\tscorecard.WithChecks(enabledChecks),\n\t\tscorecard.WithRepoClient(repoClient),\n\t\tscorecard.WithOSSFuzzClient(ossFuzzRepoClient),\n\t\tscorecard.WithOpenSSFBestPraticesClient(ciiClient),\n\t\tscorecard.WithVulnerabilitiesClient(vulnsClient),\n\t)\n\tif err != nil {\n\t\treturn policy.Fail, fmt.Errorf(\"scorecard.Run: %w\", err)\n\t}\n\n\tresult, err := attestationPolicy.EvaluateResults(&repoResult.RawResults)\n\tif err != nil {\n\t\treturn policy.Fail, fmt.Errorf(\"error when evaluating image %q against policy: %w\", image, err)\n\t}\n\tif result != policy.Pass {\n\t\tlogger.Info(\"image failed scorecard attestation policy check\")\n\t} else {\n\t\tlogger.Info(\"image passed scorecard attestation policy check\")\n\t}\n\treturn result, nil\n}\n"}, {"path": "attestor/command/cli.go", "content": "// Copyright 2022 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Package pkg defines fns for running Scorecard checks on a Repo.\n\npackage command\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\t// input flags.\n\trepoURL string\n\tcommitSHA string\n\timage string\n\tpolicyPath string\n\tattestationProject string\n\toverwrite bool\n\t// input flags: pgp key flags.\n\tpgpPriKeyPath string\n\tpgpPassphrase string\n\t// pkix key flags.\n\tpkixPriKeyPath string\n\tpkixAlg string\n\n\t// input flags: kms flags.\n\tkmsKeyName string\n\tkmsDigestAlg string\n)\n\n//nolint:lll\nfunc addCheckFlags(cmd *cobra.Command) {\n\tcmd.PersistentFlags().StringVar(&policyPath, \"policy\", \"\", \"(required for check) scorecard attestation policy file path, e.g., /tmp/policy-binauthz.yml\")\n\t//nolint:errcheck\n\tcmd.MarkPersistentFlagRequired(\"policy\")\n\tcmd.PersistentFlags().StringVar(&repoURL, \"repo-url\", \"\", \"Repo URL from which source was built\")\n\t//nolint:errcheck\n\tcmd.MarkPersistentFlagRequired(\"repo-url\")\n\tcmd.PersistentFlags().StringVar(&commitSHA, \"commit\", \"\", \"Git SHA at which image was built\")\n}\n\n//nolint:lll\nfunc addSignFlags(cmd *cobra.Command) {\n\tcmd.PersistentFlags().StringVar(&image, \"image\", \"\", \"Image url, e.g., gcr.io/foo/bar@sha256:abcd\")\n\t//nolint:errcheck\n\tcmd.MarkPersistentFlagRequired(\"image\")\n\tcmd.PersistentFlags().StringVar(&attestationProject, \"attestation-project\", \"\", \"project id for GCP project that stores attestation, use image project if set to empty\")\n\tcmd.PersistentFlags().BoolVar(&overwrite, \"overwrite\", false, \"overwrite attestation if already existed (default false)\")\n\tcmd.PersistentFlags().StringVar(&kmsKeyName, \"kms-key-name\", \"\", \"kms key name, in the format of in the format projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*\")\n\tcmd.PersistentFlags().StringVar(&kmsDigestAlg, \"kms-digest-alg\", \"\", \"kms digest algorithm, must be one of SHA256|SHA384|SHA512, and the same as specified by the key version's algorithm\")\n\tcmd.PersistentFlags().StringVar(&pgpPriKeyPath, \"pgp-private-key\", \"\", \"pgp private signing key path, e.g., /dev/shm/key.pgp\")\n\tcmd.PersistentFlags().StringVar(&pgpPassphrase, \"pgp-passphrase\", \"\", \"passphrase for pgp private key, if any\")\n\tcmd.PersistentFlags().StringVar(&pkixPriKeyPath, \"pkix-private-key\", \"\", \"pkix private signing key path, e.g., /dev/shm/key.pem\")\n\tcmd.PersistentFlags().StringVar(&pkixAlg, \"pkix-alg\", \"\", \"pkix signature algorithm, e.g., ecdsa-p256-sha256\")\n}\n\nvar RootCmd = &cobra.Command{\n\tUse: \"scorecard-attestor\",\n\tShort: \"scorecard-attestor generates attestations based on scorecard results\",\n}\n\nvar checkAndSignCmd = &cobra.Command{\n\tUse: \"attest\",\n\tShort: \"Run scorecard and sign a container image if attestation policy check passes\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tpassed, err := runCheck()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif passed {\n\t\t\treturn runSign()\n\t\t}\n\n\t\treturn nil\n\t},\n\tSilenceUsage: true,\n}\n\nvar checkCmd = &cobra.Command{\n\tUse: \"verify\",\n\tShort: \"Run scorecard and check an image against a policy\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t_, err := runCheck()\n\t\treturn err\n\t},\n\tSilenceUsage: true,\n}\n\n//nolint:gochecknoinits\nfunc init() {\n\tRootCmd.AddCommand(checkCmd, checkAndSignCmd)\n\n\taddCheckFlags(checkAndSignCmd)\n\taddSignFlags(checkAndSignCmd)\n\n\taddCheckFlags(checkCmd)\n}\n\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n"}, {"path": "attestor/command/cli_test.go", "content": "// Copyright 2023 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//\thttp://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage command\n\nimport (\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc Test_addSignFlags(t *testing.T) {\n\tt.Parallel()\n\ttype args struct {\n\t\tcmd *cobra.Command\n\t}\n\ttestArgs := args{\n\t\tcmd: &cobra.Command{},\n\t}\n\n\taddSignFlags(testArgs.cmd)\n\t// persistent flags of Image being set has to be tested in the integration test\n\tif testArgs.cmd.PersistentFlags().Lookup(\"image\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'image'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"attestation-project\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'attestation-project'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"overwrite\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'overwrite'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"kms-key-name\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'kms-key-name'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"kms-digest-alg\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'kms-digest-alg'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"pgp-private-key\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'pgp-private-key'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"pgp-passphrase\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'pgp-passphrase'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"pkix-private-key\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'pkix-private-key'\")\n\t}\n\tif testArgs.cmd.PersistentFlags().Lookup(\"pkix-alg\") == nil {\n\t\tt.Errorf(\"addSignFlags() did not add persistent flag 'pkix-alg'\")\n\t}\n}\n"}, {"path": "attestor/command/sign.go", "content": "// Copyright 2022 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//\thttp://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage command\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/grafeas/kritis/pkg/attestlib\"\n\t\"github.com/grafeas/kritis/pkg/kritis/metadata/containeranalysis\"\n\t\"github.com/grafeas/kritis/pkg/kritis/signer\"\n\t\"github.com/grafeas/kritis/pkg/kritis/util\"\n\n\tsclog \"github.com/ossf/scorecard/v5/log\"\n)\n\nconst scorecardNoteID = \"ossf-scorecard-attestation\"\n\ntype EncryptionParamError struct {\n\tMessage string\n}\n\nfunc (ep EncryptionParamError) Error() string {\n\treturn ep.Message\n}\n\nfunc runSign() error {\n\tlogger := sclog.NewLogger(sclog.DefaultLevel)\n\n\t// Create a client\n\tclient, err := containeranalysis.New()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not initialize the client %w\", err)\n\t}\n\n\t// Read the signing credentials\n\t// Either kmsKeyName or pgpPriKeyPath needs to be set\n\tif kmsKeyName == \"\" && pgpPriKeyPath == \"\" && pkixPriKeyPath == \"\" {\n\t\treturn EncryptionParamError{\"neither kms_key_name, pgp_private_key, or pkix_private_key is specified\"}\n\t}\n\tvar cSigner attestlib.Signer\n\tswitch {\n\tcase kmsKeyName != \"\":\n\t\tlogger.Info(fmt.Sprintf(\"Using kms key %s for signing.\", kmsKeyName))\n\t\tif kmsDigestAlg == \"\" {\n\t\t\t//nolint:lll\n\t\t\treturn EncryptionParamError{\"kms_digest_alg is unspecified, must be one of SHA256|SHA384|SHA512, and the same as specified by the key version's algorithm\"}\n\t\t}\n\t\tkmsDigestAlg = strings.ToUpper(kmsDigestAlg)\n\t\tcSigner, err = signer.NewCloudKmsSigner(kmsKeyName, signer.DigestAlgorithm(kmsDigestAlg))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"creating kms signer failed: %w\", err)\n\t\t}\n\tcase pgpPriKeyPath != \"\":\n\t\tlogger.Info(\"Using pgp key for signing.\")\n\t\tsignerKey, err := os.ReadFile(pgpPriKeyPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fail to read signer key: %w\", err)\n\t\t}\n\t\t// Create a cryptolib signer\n\t\tcSigner, err = attestlib.NewPgpSigner(signerKey, pgpPassphrase)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"creating pgp signer failed: %w\", err)\n\t\t}\n\tdefault:\n\t\tlogger.Info(\"Using pkix key for signing.\")\n\t\tsignerKey, err := os.ReadFile(pkixPriKeyPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fail to read signer key: %w\", err)\n\t\t}\n\t\tsAlg := attestlib.ParseSignatureAlgorithm(pkixAlg)\n\t\tif sAlg == attestlib.UnknownSigningAlgorithm {\n\t\t\treturn EncryptionParamError{fmt.Sprintf(\"empty or unknown PKIX signature algorithm: %s\", pkixAlg)}\n\t\t}\n\t\tcSigner, err = attestlib.NewPkixSigner(signerKey, sAlg, \"\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"creating pkix signer failed: %w\", err)\n\t\t}\n\t}\n\n\t// Parse attestation project\n\tif attestationProject == \"\" {\n\t\tattestationProject = util.GetProjectFromContainerImage(image)\n\t\tlogger.Info(fmt.Sprintf(\"Using image project as attestation project: %s\", attestationProject))\n\t} else {\n\t\tlogger.Info(fmt.Sprintf(\"Using specified attestation project: %s\", attestationProject))\n\t}\n\n\t// Check note name\n\tscorecardNoteName := fmt.Sprintf(\"projects/%s/notes/%s\", attestationProject, scorecardNoteID)\n\n\terr = util.CheckNoteName(scorecardNoteName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"note name is invalid %w\", err)\n\t}\n\n\t// Create signer\n\tr := signer.New(client, cSigner, scorecardNoteName, attestationProject, overwrite)\n\t// Sign image\n\terr = r.SignImage(image)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"signing image failed: %w\", err)\n\t}\n\treturn nil\n}\n"}, {"path": "attestor/root.go", "content": "// Copyright 2022 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//\thttp://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage main\n\nimport \"github.com/ossf/scorecard/v5/attestor/command\"\n\nfunc main() {\n\tcommand.Execute()\n}\n"}, {"path": "checker/detail_logger.go", "content": "// Copyright 2020 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage checker\n\n// DetailLogger logs a CheckDetail struct.\ntype DetailLogger interface {\n\tInfo(msg *LogMessage)\n\tWarn(msg *LogMessage)\n\tDebug(msg *LogMessage)\n\t// Flush resets the logger state and returns collected logs.\n\tFlush() []CheckDetail\n}\n"}, {"path": "probes/unsafeblock/testdata/malformed.go", "content": "\nimp ort \"unsafe\"\n\nfu SafeFoo(inpu string {\n\t\n\n"}], "context_lines": 1497, "buggy_files": ["docs/checks.md", "docs/checks/internal/checks.yaml", "probes/releasesAreSigned/impl.go"], "test_files": [{"path": "checks/signed_releases_test.go", "content": "// Copyright 2020 OpenSSF Scorecard Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage checks\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"go.uber.org/mock/gomock\"\n\n\t\"github.com/ossf/scorecard/v5/checker\"\n\t\"github.com/ossf/scorecard/v5/clients\"\n\tmockrepo \"github.com/ossf/scorecard/v5/clients/mockclients\"\n\t\"github.com/ossf/scorecard/v5/internal/packageclient\"\n\tscut \"github.com/ossf/scorecard/v5/utests\"\n)\n\nfunc TestSignedRelease(t *testing.T) {\n\tt.Parallel()\n\ttests := []struct {\n\t\terr error\n\t\tname string\n\t\treleases []clients.Release\n\t\texpected checker.CheckResult\n\t}{\n\t\t{\n\t\t\tname: \"NoReleases\",\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with no assets\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets without signed artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 0,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-asc\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.asc\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.asc\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with intoto SLSA provenance\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.intoto.jsonl\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.intoto.jsonl\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 10,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sig\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sign\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sign\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sign\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-minisig\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sigstore\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sigstore\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sigstore\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed artifacts-sigstore-json\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sigstore.json\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.sigstore.json\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Releases with assets with signed and unsigned artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple Releases with assets with signed and unsigned artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v2.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Some releases with assets with signed and unsigned artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v2.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 4,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"6 Releases with assets with signed artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v1.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v1.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.minisig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.minisig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v1.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v2.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v3.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v4.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v5.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTagName: \"v6.0.0\",\n\t\t\t\t\tURL: \"http://foo.com/v2.0.0\",\n\t\t\t\t\tTargetCommitish: \"master\",\n\t\t\t\t\tAssets: []clients.ReleaseAsset{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.sig\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.sig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"foo.txt\",\n\t\t\t\t\t\t\tURL: \"http://foo.com/v2.0.0/foo.txt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"Error getting releases\",\n\t\t\terr: errors.New(\"Error getting releases\"),\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t\tError: errors.New(\"Error getting releases\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"9 Releases with assets with signed artifacts\",\n\t\t\treleases: []clients.Release{\n\t\t\t\trelease(\"v0.8.5\"),\n\t\t\t\trelease(\"v0.8.4\"),\n\t\t\t\trelease(\"v0.8.3\"),\n\t\t\t\trelease(\"v0.8.2\"),\n\t\t\t\trelease(\"v0.8.1\"),\n\t\t\t\trelease(\"v0.8.0\"),\n\t\t\t\trelease(\"v0.7.0\"),\n\t\t\t\trelease(\"v0.6.0\"),\n\t\t\t\trelease(\"v0.5.0\"),\n\t\t\t\trelease(\"v0.4.0\"),\n\t\t\t\trelease(\"v0.3.0\"),\n\t\t\t\trelease(\"v0.2.0\"),\n\t\t\t\trelease(\"v0.1.0\"),\n\t\t\t\trelease(\"v0.0.6\"),\n\t\t\t\trelease(\"v0.0.5\"),\n\t\t\t\trelease(\"v0.0.4\"),\n\t\t\t\trelease(\"v0.0.3\"),\n\t\t\t\trelease(\"v0.0.2\"),\n\t\t\t\trelease(\"v0.0.1\"),\n\t\t\t},\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: 8,\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"Error getting releases\",\n\t\t\terr: errors.New(\"Error getting releases\"),\n\t\t\texpected: checker.CheckResult{\n\t\t\t\tScore: -1,\n\t\t\t\tError: errors.New(\"Error getting releases\"),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tctrl := gomock.NewController(t)\n\n\t\t\tmockRepoC := mockrepo.NewMockRepoClient(ctrl)\n\t\t\tmockRepoC.EXPECT().ListReleases().DoAndReturn(\n\t\t\t\tfunc() ([]clients.Release, error) {\n\t\t\t\t\tif tt.err != nil {\n\t\t\t\t\t\treturn nil, tt.err\n\t\t\t\t\t}\n\t\t\t\t\treturn tt.releases, tt.err\n\t\t\t\t},\n\t\t\t).MinTimes(1)\n\n\t\t\tmockRepo := mockrepo.NewMockRepo(ctrl)\n\t\t\tmockRepo.EXPECT().Host().DoAndReturn(\n\t\t\t\tfunc() string {\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t).AnyTimes()\n\t\t\tmockRepo.EXPECT().Path().DoAndReturn(\n\t\t\t\tfunc() string {\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t).AnyTimes()\n\n\t\t\tmockPkgC := mockrepo.NewMockProjectPackageClient(ctrl)\n\t\t\tmockPkgC.EXPECT().GetProjectPackageVersions(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(\n\t\t\t\tfunc(ctx context.Context, host, project string) (*packageclient.ProjectPackageVersions, error) {\n\t\t\t\t\tv := packageclient.ProjectPackageVersions{}\n\t\t\t\t\treturn &v, nil\n\t\t\t\t},\n\t\t\t).AnyTimes()\n\n\t\t\treq := checker.CheckRequest{\n\t\t\t\tRepoClient: mockRepoC,\n\t\t\t\tRepo: mockRepo,\n\t\t\t\tProjectClient: mockPkgC,\n\t\t\t}\n\t\t\treq.Dlogger = &scut.TestDetailLogger{}\n\t\t\tres := SignedReleases(&req)\n\n\t\t\tif tt.err != nil {\n\t\t\t\tif res.Error == nil {\n\t\t\t\t\tt.Errorf(\"Expected error %v, got nil\", tt.err)\n\t\t\t\t}\n\t\t\t\t// return as we don't need to check the rest of the fields.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif res.Score != tt.expected.Score {\n\t\t\t\tt.Errorf(\"Expected score %d, got %d for %v\", tt.expected.Score, res.Score, tt.name)\n\t\t\t}\n\t\t\tctrl.Finish()\n\t\t})\n\t}\n}\n\nfunc release(version string) clients.Release {\n\treturn clients.Release{\n\t\tTagName: version,\n\t\tURL: fmt.Sprintf(\"https://github.com/test/test_artifact/releases/tag/%s\", version),\n\t\tTargetCommitish: \"master\",\n\t\tAssets: []clients.ReleaseAsset{\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_checksums.txt\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_checksums.txt\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_checksums.txt.sig\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_checksums.txt.sig\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_darwin_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_darwin_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_arm64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_arm64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_i386.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_i386.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_Linux_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_Linux_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_windows_i386.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_windows_i386.tar.gz\", version, version),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"%s_windows_x86_64.tar.gz\", version),\n\t\t\t\tURL: fmt.Sprintf(\"https://github.com/test/repo/releases/%s/%s_windows_x86_64.tar.gz\", version, version),\n\t\t\t},\n\t\t},\n\t}\n}\n"}], "eval": {"test_cmds": ["go test -v ./... -json > reports/go-test-results.json"], "print_cmds": [], "log_parser": "def parser(log: str) -> dict[str, str]:\n import json\n import re\n\n results: dict[str, str] = {}\n\n # Track last seen test per package and tests recorded per package\n package_last_test: dict[str, str] = {}\n package_tests: dict[str, set] = {}\n failed_packages: set[str] = set()\n\n # Fallback regex patterns for non-JSON lines\n pass_fail_re = re.compile(r'---\\s+(PASS|FAIL):\\s+([^\\s(]+)')\n skip_re = re.compile(r'===\\s+SKIP\\s+([^\\s(]+)')\n pkg_fail_re = re.compile(r'^\\s*FAIL\\s+(\\S+)\\s')\n\n for raw in log.splitlines():\n s = raw.strip()\n if not s:\n continue\n\n # Prefer structured Go test JSON\n if s.startswith(\"{\") and s.endswith(\"}\"):\n obj = None\n try:\n obj = json.loads(s)\n except Exception:\n obj = None\n if isinstance(obj, dict):\n action = obj.get(\"Action\")\n test = obj.get(\"Test\")\n pkg = obj.get(\"Package\")\n output = obj.get(\"Output\")\n\n if pkg and test:\n package_last_test[pkg] = test\n package_tests.setdefault(pkg, set()).add(test)\n\n if action in (\"pass\", \"fail\", \"skip\") and test:\n name = f\"{pkg}/{test}\" if pkg else test\n if action == \"pass\":\n results[name] = \"pass\"\n elif action == \"fail\":\n results[name] = \"fail\"\n elif action == \"skip\":\n results[name] = \"skip\"\n elif action == \"fail\" and pkg and not test:\n failed_packages.add(pkg)\n\n # Also detect textual package FAIL lines present in Output field\n if output:\n m = pkg_fail_re.match(output)\n if m:\n failed_packages.add(m.group(1))\n continue\n\n # Fallback parsing for plain text lines\n m = pass_fail_re.search(s)\n if m:\n status, testname = m.groups()\n results[testname] = \"pass\" if status.upper() == \"PASS\" else \"fail\"\n continue\n\n m = skip_re.search(s)\n if m:\n testname = m.group(1)\n results[testname] = \"skip\"\n continue\n\n m = pkg_fail_re.match(s)\n if m:\n failed_packages.add(m.group(1))\n continue\n\n # Attribute package-level failures to the last observed test in that package if not already marked\n for pkg in failed_packages:\n last = package_last_test.get(pkg)\n if last:\n key = f\"{pkg}/{last}\"\n if key not in results:\n results[key] = \"fail\"\n\n return results", "rebuild_cmds": []}} {"id": "patchbench-go-real-0070", "repo": "twpayne/chezmoi", "base_commit": "5ffd82cb395bc0c33ad885234a72bef108f8243c", "status": "verified", "verify_status": "verified", "error": null, "timing": {"setup": 4.3, "pre_test_0": 99.4, "pre_test_1": 32.9, "post_test_0": 38.1, "post_test_1": 1.7, "total": 176.5}, "test_cmds": ["mkdir -p reports && go test -v -json ./... > reports/go-test-results.json"], "rebuild_cmds": [], "print_cmds": [], "f2p_pre_ok": true, "pre_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 3947}, "f2p_post_ok": true, "p2p_post_ok": true, "post_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 3947}, "raw_tail": "\"chezmoi.io/chezmoi/internal/cmd\",\"Test\":\"TestScript/scriptonce_unix\",\"Output\":\" --- PASS: TestScript/scriptonce_unix (0.15s)\\n\"}\n{\"Time\":\"2026-09-10T10:19:59.110461571Z\",\"Action\":\"pass\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Test\":\"TestScript/scriptonce_unix\",\"Elapsed\":0.15}\n{\"Time\":\"2026-09-10T10:19:59.110465958Z\",\"Action\":\"output\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Test\":\"TestScript/script\",\"Output\":\" --- PASS: TestScript/script (0.04s)\\n\"}\n{\"Time\":\"2026-09-10T10:19:59.110470968Z\",\"Action\":\"pass\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Test\":\"TestScript/script\",\"Elapsed\":0.04}\n{\"Time\":\"2026-09-10T10:19:59.110475788Z\",\"Action\":\"output\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Test\":\"TestScript/script_unix\",\"Output\":\" --- PASS: TestScript/script_unix (0.14s)\\n\"}\n{\"Time\":\"2026-09-10T10:19:59.110480185Z\",\"Action\":\"pass\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Test\":\"TestScript/script_unix\",\"Elapsed\":0.14}\n{\"Time\":\"2026-09-10T10:19:59.110484304Z\",\"Action\":\"fail\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Test\":\"TestScript\",\"Elapsed\":0.01}\n{\"Time\":\"2026-09-10T10:19:59.110488764Z\",\"Action\":\"output\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Output\":\"FAIL\\n\"}\n{\"Time\":\"2026-09-10T10:19:59.128317092Z\",\"Action\":\"output\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Output\":\"FAIL\\tchezmoi.io/chezmoi/internal/cmd\\t32.399s\\n\"}\n{\"Time\":\"2026-09-10T10:19:59.128360154Z\",\"Action\":\"fail\",\"Package\":\"chezmoi.io/chezmoi/internal/cmd\",\"Elapsed\":32.399}\n\n", "context_files": [{"path": "internal/cmd/executetemplatecmd.go", "content": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"chezmoi.io/chezmoi/internal/chezmoi\"\n)\n\ntype executeTemplateCmdConfig struct {\n\tfile bool\n\tinit bool\n\tpromptBool map[string]string\n\tpromptChoice map[string]string\n\tpromptInt map[string]int\n\tpromptMultichoice map[string]string\n\tpromptString map[string]string\n\tstdinIsATTY bool\n\ttemplateOptions chezmoi.TemplateOptions\n\twithStdin bool\n}\n\nfunc (c *Config) newExecuteTemplateCmd() *cobra.Command {\n\texecuteTemplateCmd := &cobra.Command{\n\t\tGroupID: groupIDTemplate,\n\t\tUse: \"execute-template [template]...\",\n\t\tShort: \"Execute the given template(s)\",\n\t\tLong: mustLongHelp(\"execute-template\"),\n\t\tExample: example(\"execute-template\"),\n\t\tRunE: c.runExecuteTemplateCmd,\n\t\tAnnotations: newAnnotations(\n\t\t\tpersistentStateModeReadWrite,\n\t\t),\n\t}\n\n\texecuteTemplateCmd.Flags().\n\t\tBoolVarP(&c.executeTemplate.file, \"file\", \"f\", c.executeTemplate.file, \"Treat arguments as filenames\")\n\texecuteTemplateCmd.Flags().BoolVarP(&c.executeTemplate.init, \"init\", \"i\", c.executeTemplate.init, \"Simulate chezmoi init\")\n\texecuteTemplateCmd.Flags().\n\t\tStringToStringVar(&c.executeTemplate.promptBool, \"promptBool\", c.executeTemplate.promptBool, \"Simulate promptBool\")\n\texecuteTemplateCmd.Flags().\n\t\tStringToStringVar(&c.executeTemplate.promptChoice, \"promptChoice\", c.executeTemplate.promptChoice, \"Simulate promptChoice\")\n\texecuteTemplateCmd.Flags().\n\t\tStringToIntVar(&c.executeTemplate.promptInt, \"promptInt\", c.executeTemplate.promptInt, \"Simulate promptInt\")\n\texecuteTemplateCmd.Flags().\n\t\tStringToStringVar(&c.executeTemplate.promptMultichoice, \"promptMultichoice\", c.executeTemplate.promptMultichoice, \"Simulate promptMultichoice\")\n\texecuteTemplateCmd.Flags().\n\t\tStringToStringVarP(&c.executeTemplate.promptString, \"promptString\", \"p\", c.executeTemplate.promptString, \"Simulate promptString\")\n\texecuteTemplateCmd.Flags().\n\t\tBoolVar(&c.executeTemplate.stdinIsATTY, \"stdinisatty\", c.executeTemplate.stdinIsATTY, \"Simulate stdinIsATTY\")\n\texecuteTemplateCmd.Flags().\n\t\tStringVar(&c.executeTemplate.templateOptions.LeftDelimiter, \"left-delimiter\", c.executeTemplate.templateOptions.LeftDelimiter, \"Set left template delimiter\")\n\texecuteTemplateCmd.Flags().\n\t\tStringVar(&c.executeTemplate.templateOptions.RightDelimiter, \"right-delimiter\", c.executeTemplate.templateOptions.RightDelimiter, \"Set right template delimiter\")\n\texecuteTemplateCmd.Flags().\n\t\tBoolVar(&c.executeTemplate.withStdin, \"with-stdin\", c.executeTemplate.withStdin, \"Set .chezmoi.stdin to the contents of the standard input\")\n\n\treturn executeTemplateCmd\n}\n\nfunc (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error {\n\toptions := []chezmoi.SourceStateOption{\n\t\tchezmoi.WithTemplateDataOnly(true),\n\t\tchezmoi.WithReadTemplates(!c.executeTemplate.init),\n\t}\n\tif c.executeTemplate.init {\n\t\toptions = append(options, chezmoi.WithReadTemplateData(false))\n\t}\n\tif c.executeTemplate.withStdin && len(args) > 0 {\n\t\tstdin, err := io.ReadAll(c.stdin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toptions = append(options, chezmoi.WithPriorityTemplateData(map[string]any{\n\t\t\t\"chezmoi\": map[string]any{\n\t\t\t\t\"stdin\": string(stdin),\n\t\t\t},\n\t\t}))\n\t}\n\tsourceState, err := c.newSourceState(cmd.Context(), cmd, options...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpromptBool := make(map[string]bool)\n\tfor key, valueStr := range c.executeTemplate.promptBool {\n\t\tvalue, err := chezmoi.ParseBool(valueStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpromptBool[key] = value\n\t}\n\tif c.executeTemplate.init {\n\t\tpromptBoolInitTemplateFunc := func(prompt string, args ...bool) bool {\n\t\t\tswitch len(args) {\n\t\t\tcase 0:\n\t\t\t\treturn promptBool[prompt]\n\t\t\tcase 1:\n\t\t\t\tif value, ok := promptBool[prompt]; ok {\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn args[0]\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"want 1 or 2 arguments, got %d\", len(args)+1))\n\t\t\t}\n\t\t}\n\n\t\tpromptBoolOnceInitTemplateFunc := func(m map[string]any, path any, field string, args ...bool) bool {\n\t\t\tnestedMap, lastKey := mustValues(nestedMapAtPath(m, path))\n\t\t\tif value, ok := nestedMap[lastKey]; ok {\n\t\t\t\tif boolValue, ok := value.(bool); ok {\n\t\t\t\t\treturn boolValue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn promptBoolInitTemplateFunc(field, args...)\n\t\t}\n\n\t\tpromptChoiceInitTemplateFunc := func(prompt string, choices any, args ...string) string {\n\t\t\tchoiceStrs := mustValue(anyToStringSlice(choices))\n\t\t\tswitch len(args) {\n\t\t\tcase 0:\n\t\t\t\tif value, ok := c.executeTemplate.promptChoice[prompt]; ok {\n\t\t\t\t\tif !slices.Contains(choiceStrs, value) {\n\t\t\t\t\t\tpanic(fmt.Errorf(\"%s: invalid choice\", value))\n\t\t\t\t\t}\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn prompt\n\t\t\tcase 1:\n\t\t\t\tif value, ok := c.executeTemplate.promptChoice[prompt]; ok {\n\t\t\t\t\tif !slices.Contains(choiceStrs, value) {\n\t\t\t\t\t\tpanic(fmt.Errorf(\"%s: invalid choice\", value))\n\t\t\t\t\t}\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn args[0]\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"want 2 or 3 arguments, got %d\", len(args)+1))\n\t\t\t}\n\t\t}\n\n\t\tpromptChoiceOnceInitTemplateFunc := func(m map[string]any, path any, prompt string, choices []any, args ...string) string {\n\t\t\tnestedMap, lastKey := mustValues(nestedMapAtPath(m, path))\n\t\t\tif value, ok := nestedMap[lastKey]; ok {\n\t\t\t\tif stringValue, ok := value.(string); ok {\n\t\t\t\t\treturn stringValue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn promptChoiceInitTemplateFunc(prompt, choices, args...)\n\t\t}\n\n\t\tpromptMultichoiceInitTemplateFunc := func(prompt string, choices any, args ...any) []string {\n\t\t\tchoiceStrs := mustValue(anyToStringSlice(choices))\n\t\t\tif value, ok := c.executeTemplate.promptMultichoice[prompt]; ok {\n\t\t\t\tvalues := strings.Split(value, \"/\")\n\n\t\t\t\tfor _, v := range values {\n\t\t\t\t\tif !slices.Contains(choiceStrs, v) {\n\t\t\t\t\t\tpanic(fmt.Errorf(\"%s: invalid choice\", value))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn values\n\t\t\t}\n\n\t\t\tif len(args) == 0 {\n\t\t\t\treturn []string{prompt}\n\t\t\t}\n\n\t\t\treturn mustValue(anyToStringSlice(args[0]))\n\t\t}\n\n\t\tpromptMultichoiceOnceInitTemplateFunc := func(m map[string]any, path any, prompt string, choices []any, args ...any) []string {\n\t\t\tnestedMap, lastKey := mustValues(nestedMapAtPath(m, path))\n\t\t\tif value, ok := nestedMap[lastKey]; ok {\n\t\t\t\tif stringValue, ok := value.(string); ok {\n\t\t\t\t\treturn strings.Split(stringValue, \",\")\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn promptMultichoiceInitTemplateFunc(prompt, choices, args...)\n\t\t}\n\n\t\tpromptIntInitTemplateFunc := func(prompt string, args ...int64) int64 {\n\t\t\tswitch len(args) {\n\t\t\tcase 0:\n\t\t\t\treturn int64(c.executeTemplate.promptInt[prompt])\n\t\t\tcase 1:\n\t\t\t\tif value, ok := c.executeTemplate.promptInt[prompt]; ok {\n\t\t\t\t\treturn int64(value)\n\t\t\t\t}\n\t\t\t\treturn args[0]\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"want 1 or 2 arguments, got %d\", len(args)+1))\n\t\t\t}\n\t\t}\n\n\t\tpromptIntOnceInitTemplateFunc := func(m map[string]any, path any, prompt string, args ...int64) int64 {\n\t\t\tnestedMap, lastKey := mustValues(nestedMapAtPath(m, path))\n\t\t\tif value, ok := nestedMap[lastKey]; ok {\n\t\t\t\tif intValue, ok := value.(int64); ok {\n\t\t\t\t\treturn intValue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn promptIntInitTemplateFunc(prompt, args...)\n\t\t}\n\n\t\tpromptStringInitTemplateFunc := func(prompt string, args ...string) string {\n\t\t\tswitch len(args) {\n\t\t\tcase 0:\n\t\t\t\tif value, ok := c.executeTemplate.promptString[prompt]; ok {\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn prompt\n\t\t\tcase 1:\n\t\t\t\tif value, ok := c.executeTemplate.promptString[prompt]; ok {\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn args[0]\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"want 1 or 2 arguments, got %d\", len(args)+1))\n\t\t\t}\n\t\t}\n\n\t\tpromptStringOnceInitTemplateFunc := func(m map[string]any, path any, prompt string, args ...string) string {\n\t\t\tnestedMap, lastKey := mustValues(nestedMapAtPath(m, path))\n\t\t\tif value, ok := nestedMap[lastKey]; ok {\n\t\t\t\tif stringValue, ok := value.(string); ok {\n\t\t\t\t\treturn stringValue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn promptStringInitTemplateFunc(prompt, args...)\n\t\t}\n\n\t\tinitTemplateFuncs := map[string]any{\n\t\t\t\"exit\": c.exitInitTemplateFunc,\n\t\t\t\"promptBool\": promptBoolInitTemplateFunc,\n\t\t\t\"promptBoolOnce\": promptBoolOnceInitTemplateFunc,\n\t\t\t\"promptChoice\": promptChoiceInitTemplateFunc,\n\t\t\t\"promptChoiceOnce\": promptChoiceOnceInitTemplateFunc,\n\t\t\t\"promptInt\": promptIntInitTemplateFunc,\n\t\t\t\"promptIntOnce\": promptIntOnceInitTemplateFunc,\n\t\t\t\"promptMultichoice\": promptMultichoiceInitTemplateFunc,\n\t\t\t\"promptMultichoiceOnce\": promptMultichoiceOnceInitTemplateFunc,\n\t\t\t\"promptString\": promptStringInitTemplateFunc,\n\t\t\t\"promptStringOnce\": promptStringOnceInitTemplateFunc,\n\t\t\t\"writeToStdout\": c.writeToStdout,\n\t\t}\n\n\t\tchezmoi.RecursiveMerge(c.templateFuncs, initTemplateFuncs)\n\t}\n\n\tif len(args) == 0 {\n\t\tdata, err := io.ReadAll(c.stdin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutput, err := sourceState.ExecuteTemplateData(chezmoi.ExecuteTemplateDataOptions{\n\t\t\tNameRelPath: chezmoi.NewRelPath(\"stdin\"),\n\t\t\tData: data,\n\t\t\tTemplateOptions: c.executeTemplate.templateOptions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn c.writeOutput(output, 0o666)\n\t}\n\n\toutput := strings.Builder{}\n\tfor i, arg := range args {\n\t\tvar data []byte\n\t\tvar nameRelPath chezmoi.RelPath\n\t\tif c.executeTemplate.file {\n\t\t\t// If the argument filename is in the source directory, then\n\t\t\t// specify the template sourcePath as relative to sourceDir, just\n\t\t\t// like `chezmoi apply` does. If it is not, then pass it unmodified.\n\t\t\tpath, err := chezmoi.NormalizePath(arg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsourceDir, err := c.getSourceDirAbsPath(nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif relPath, err := path.TrimDirPrefix(sourceDir); err == nil {\n\t\t\t\tnameRelPath = relPath\n\t\t\t} else {\n\t\t\t\tnameRelPath = chezmoi.NewRelPath(path.String())\n\t\t\t}\n\n\t\t\tdata, err = os.ReadFile(arg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tnameRelPath = chezmoi.NewRelPath(\"arg\" + strconv.Itoa(i+1))\n\t\t\tdata = []byte(arg)\n\t\t}\n\t\tresult, err := sourceState.ExecuteTemplateData(chezmoi.ExecuteTemplateDataOptions{\n\t\t\tNameRelPath: nameRelPath,\n\t\t\tData: data,\n\t\t\tTemplateOptions: c.executeTemplate.templateOptions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := output.Write(result); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn c.writeOutputString(output.String(), 0o666)\n}\n"}, {"path": "internal/cmd/inittemplatefuncs.go", "content": "package cmd\n\nimport (\n\t\"chezmoi.io/chezmoi/internal/chezmoi\"\n)\n\nfunc (c *Config) exitInitTemplateFunc(code int) string {\n\tpanic(chezmoi.ExitCodeError(code))\n}\n\nfunc (c *Config) writeToStdout(args ...string) string {\n\tfor _, arg := range args {\n\t\t_ = mustValue(c.stdout.Write([]byte(arg)))\n\t}\n\treturn \"\"\n}\n"}, {"path": "internal/cmd/addcmd.go", "content": "package cmd\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"maps\"\n\t\"os\"\n\t\"slices\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"chezmoi.io/chezmoi/internal/chezmoi\"\n\t\"chezmoi.io/chezmoi/internal/chezmoiset\"\n)\n\nconst (\n\tseverityIgnore = \"ignore\"\n\tseverityWarning = \"warning\"\n\tseverityError = \"error\"\n)\n\nvar severityValues = []string{\n\tseverityIgnore,\n\tseverityWarning,\n\tseverityError,\n}\n\ntype addCmdConfig struct {\n\tEncrypt bool `json:\"encrypt\" mapstructure:\"encrypt\" yaml:\"encrypt\"`\n\tSecrets *choiceFlag `json:\"secrets\" mapstructure:\"secrets\" yaml:\"secrets\"`\n\tTemplateSymlinks bool `json:\"templateSymlinks\" mapstructure:\"templateSymlinks\" yaml:\"templateSymlinks\"`\n\tautoTemplate bool\n\tcreate bool\n\texact bool\n\tfilter *chezmoi.EntryTypeFilter\n\tfollow bool\n\tnew bool\n\tprompt bool\n\tquiet bool\n\trecursive bool\n\ttemplate bool\n}\n\nfunc (c *Config) newAddCmd() *cobra.Command {\n\taddCmd := &cobra.Command{\n\t\tGroupID: groupIDDaily,\n\t\tUse: \"add targets...\",\n\t\tAliases: []string{\"manage\"},\n\t\tShort: \"Add an existing file, directory, or symlink to the source state\",\n\t\tLong: mustLongHelp(\"add\"),\n\t\tExample: example(\"add\"),\n\t\tArgs: cobra.MinimumNArgs(1),\n\t\tRunE: c.makeRunEWithSourceState(c.runAddCmd),\n\t\tAnnotations: newAnnotations(\n\t\t\tcreateSourceDirectoryIfNeeded,\n\t\t\tmodifiesSourceDirectory,\n\t\t\tpersistentStateModeReadWrite,\n\t\t\trequiresWorkingTree,\n\t\t),\n\t}\n\n\taddCmd.Flags().\n\t\tBoolVarP(&c.Add.autoTemplate, \"autotemplate\", \"a\", c.Add.autoTemplate, \"Generate the template when adding files as templates\")\n\taddCmd.Flags().BoolVar(&c.Add.create, \"create\", c.Add.create, \"Add files that should exist, irrespective of their contents\")\n\taddCmd.Flags().BoolVar(&c.Add.Encrypt, \"encrypt\", c.Add.Encrypt, \"Encrypt files\")\n\taddCmd.Flags().BoolVar(&c.Add.exact, \"exact\", c.Add.exact, \"Add directories exactly\")\n\taddCmd.Flags().VarP(c.Add.filter.Exclude, \"exclude\", \"x\", \"Exclude entry types\")\n\taddCmd.Flags().BoolVarP(&c.Add.follow, \"follow\", \"f\", c.Add.follow, \"Add symlink targets instead of symlinks\")\n\taddCmd.Flags().VarP(c.Add.filter.Include, \"include\", \"i\", \"Include entry types\")\n\taddCmd.Flags().BoolVar(&c.Add.new, \"new\", c.Add.new, \"Create new file if target does not exist\")\n\taddCmd.Flags().BoolVarP(&c.Add.prompt, \"prompt\", \"p\", c.Add.prompt, \"Prompt before adding each entry\")\n\taddCmd.Flags().BoolVarP(&c.Add.quiet, \"quiet\", \"q\", c.Add.quiet, \"Suppress warnings\")\n\taddCmd.Flags().BoolVarP(&c.Add.recursive, \"recursive\", \"r\", c.Add.recursive, \"Recurse into subdirectories\")\n\taddCmd.Flags().Var(c.Add.Secrets, \"secrets\", \"Scan for secrets when adding unencrypted files\")\n\tmust(addCmd.RegisterFlagCompletionFunc(\"secrets\", c.Add.Secrets.FlagCompletionFunc()))\n\taddCmd.Flags().BoolVarP(&c.Add.template, \"template\", \"T\", c.Add.template, \"Add files as templates\")\n\taddCmd.Flags().\n\t\tBoolVar(&c.Add.TemplateSymlinks, \"template-symlinks\", c.Add.TemplateSymlinks, \"Add symlinks with target in source or home dirs as templates\")\n\n\treturn addCmd\n}\n\nfunc (c *Config) defaultOnIgnoreFunc(targetRelPath chezmoi.RelPath) {\n\tif !c.Add.quiet {\n\t\tc.errorf(\"warning: ignoring %s\\n\", targetRelPath)\n\t}\n}\n\nfunc (c *Config) defaultPreAddFunc(\n\ttargetRelPath chezmoi.RelPath,\n\tfileInfo fs.FileInfo,\n\tsourceStateEntry chezmoi.SourceStateEntry,\n) error {\n\t// Scan unencrypted files for secrets, if configured.\n\tencrypted := false\n\tif sourceStateFile, ok := sourceStateEntry.(*chezmoi.SourceStateFile); ok {\n\t\tencrypted = sourceStateFile.Attr().Encrypted\n\t}\n\tif c.Add.Secrets.String() != severityIgnore && fileInfo.Mode().Type() == 0 && !encrypted {\n\t\tabsPath := c.DestDirAbsPath.Join(targetRelPath)\n\t\tcontent, err := c.destSystem.ReadFile(absPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbetterleaksDetector, err := c.getBetterleaksDetector()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfindings := betterleaksDetector.DetectString(string(content))\n\t\tfor _, finding := range findings {\n\t\t\tc.errorf(\"%s:%d: %s\\n\", absPath, finding.StartLine+1, finding.Description)\n\t\t}\n\t\tif !c.force && c.Add.Secrets.String() == severityError && len(findings) > 0 {\n\t\t\treturn chezmoi.ExitCodeError(1)\n\t\t}\n\t}\n\n\tif !c.Add.prompt {\n\t\treturn nil\n\t}\n\n\tprompt := fmt.Sprintf(\"add %s\", c.SourceDirAbsPath.Join(targetRelPath))\n\tfor {\n\t\tswitch choice, err := c.promptChoice(prompt, choicesYesNoAllQuit); {\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase choice == \"all\":\n\t\t\tc.Add.prompt = false\n\t\t\treturn nil\n\t\tcase choice == \"no\":\n\t\t\treturn fs.SkipDir\n\t\tcase choice == \"quit\":\n\t\t\treturn chezmoi.ExitCodeError(0)\n\t\tcase choice == \"yes\":\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tpanic(choice + \": unexpected choice\")\n\t\t}\n\t}\n}\n\n// defaultReplaceFunc prompts the user for confirmation if the adding the entry\n// would remove any of the encrypted, private, or template attributes.\nfunc (c *Config) defaultReplaceFunc(\n\ttargetRelPath chezmoi.RelPath,\n\tnewSourceStateEntry, oldSourceStateEntry chezmoi.SourceStateEntry,\n) error {\n\tif c.force {\n\t\treturn nil\n\t}\n\n\tnewFile, newIsFile := newSourceStateEntry.(*chezmoi.SourceStateFile)\n\toldFile, oldIsFile := oldSourceStateEntry.(*chezmoi.SourceStateFile)\n\tif !newIsFile || !oldIsFile {\n\t\treturn nil\n\t}\n\n\tvar removedAttributes []string\n\tif !newFile.Attr().Encrypted && oldFile.Attr().Encrypted {\n\t\tremovedAttributes = append(removedAttributes, \"encrypted\")\n\t}\n\tif !newFile.Attr().Private && oldFile.Attr().Private {\n\t\tremovedAttributes = append(removedAttributes, \"private\")\n\t}\n\tif !newFile.Attr().Template && oldFile.Attr().Template {\n\t\tremovedAttributes = append(removedAttributes, \"template\")\n\t}\n\tif len(removedAttributes) == 0 {\n\t\treturn nil\n\t}\n\tremovedAttributesStr := englishListWithNoun(removedAttributes, \"attribute\", \"\")\n\tprompt := fmt.Sprintf(\"adding %s would remove %s, continue\", targetRelPath, removedAttributesStr)\n\n\tfor {\n\t\tswitch choice, err := c.promptChoice(prompt, choicesYesNoAllQuit); {\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase choice == \"all\":\n\t\t\tc.force = true\n\t\t\treturn nil\n\t\tcase choice == \"no\":\n\t\t\treturn fs.SkipDir\n\t\tcase choice == \"quit\":\n\t\t\treturn chezmoi.ExitCodeError(0)\n\t\tcase choice == \"yes\":\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tpanic(choice + \": unexpected choice\")\n\t\t}\n\t}\n}\n\nfunc (c *Config) runAddCmd(cmd *cobra.Command, args []string, sourceState *chezmoi.SourceState) error {\n\tswitch severity := c.Add.Secrets.String(); severity {\n\tcase severityIgnore:\n\tcase severityWarning:\n\tcase severityError:\n\tdefault:\n\t\treturn fmt.Errorf(\"%s: invalid severity\", severity)\n\t}\n\n\tonNotExist := onNotExistError\n\tif c.Add.new {\n\t\tonNotExist = onNotExistAdd\n\t}\n\tdestAbsPathInfos, err := c.destAbsPathInfos(sourceState, args, destAbsPathInfosOptions{\n\t\tfollow: c.Mode == chezmoi.ModeSymlink || c.Add.follow,\n\t\tonIgnoreFunc: c.defaultOnIgnoreFunc,\n\t\tonNotExist: onNotExist,\n\t\trecursive: c.Add.recursive,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Add.follow && c.Add.recursive {\n\t\tfor _, absPath := range slices.Sorted(maps.Keys(destAbsPathInfos)) {\n\t\t\tif destAbsPathInfo := destAbsPathInfos[absPath]; destAbsPathInfo.IsDir() {\n\t\t\t\treturn errors.New(absPath.String() + \": follow and recursive are mutually exclusive for directories\")\n\t\t\t}\n\t\t}\n\t}\n\n\tpersistentStateFileAbsPath, err := c.persistentStateFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texecutable, err := os.Executable()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfigFileAbsPath, err := c.getConfigFileAbsPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Build exact target paths set from the original args when --exact is used.\n\t// This ensures only explicitly specified paths (and their descendants) get\n\t// the exact_ prefix, not implicitly-added parent directories.\n\tvar exactTargetRelPaths chezmoiset.Set[chezmoi.RelPath]\n\tif c.Add.exact {\n\t\texactTargetRelPaths = chezmoiset.New[chezmoi.RelPath]()\n\t\tfor _, arg := range args {\n\t\t\tdestAbsPath, err := chezmoi.NormalizePath(arg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttargetRelPath, err := destAbsPath.TrimDirPrefix(c.DestDirAbsPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\texactTargetRelPaths.Add(targetRelPath)\n\t\t}\n\t}\n\n\treturn sourceState.Add(\n\t\tc.sourceSystem,\n\t\tc.persistentState,\n\t\tc.destSystem,\n\t\tdestAbsPathInfos,\n\t\t&chezmoi.AddOptions{\n\t\t\tAutoTemplate: c.Add.autoTemplate,\n\t\t\tCreate: c.Add.create,\n\t\t\tEncrypt: c.Add.Encrypt,\n\t\t\tEncryptedSuffix: c.encryption.EncryptedSuffix(),\n\t\t\tExact: c.Add.exact,\n\t\t\tExactTargetRelPaths: exactTargetRelPaths,\n\t\t\tErrorf: c.errorf,\n\t\t\tFilter: c.Add.filter,\n\t\t\tOnIgnoreFunc: c.defaultOnIgnoreFunc,\n\t\t\tPreAddFunc: c.defaultPreAddFunc,\n\t\t\tConfigFileAbsPath: configFileAbsPath,\n\t\t\tProtectedAbsPaths: []chezmoi.AbsPath{\n\t\t\t\tc.CacheDirAbsPath,\n\t\t\t\tc.WorkingTreeAbsPath,\n\t\t\t\tconfigFileAbsPath.Dir(),\n\t\t\t\tpersistentStateFileAbsPath,\n\t\t\t\tc.sourceDirAbsPath,\n\t\t\t\tchezmoi.NewAbsPath(executable),\n\t\t\t},\n\t\t\tReplaceFunc: c.defaultReplaceFunc,\n\t\t\tTemplate: c.Add.template,\n\t\t\tTemplateSymlinks: c.Add.TemplateSymlinks,\n\t\t},\n\t)\n}\n"}, {"path": "internal/cmd/addcmd_test.go", "content": "package cmd\n\nimport (\n\t\"io/fs\"\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com/alecthomas/assert/v2\"\n\t\"github.com/twpayne/go-vfs/v5\"\n\t\"github.com/twpayne/go-vfs/v5/vfst\"\n\n\t\"chezmoi.io/chezmoi/internal/chezmoitest\"\n)\n\nfunc TestAddCmd(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\troot any\n\t\targs []string\n\t\ttests []any\n\t}{\n\t\t{\n\t\t\tname: \"dir\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".dir\": &vfst.Dir{Perm: fs.ModePerm},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.dir\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir\",\n\t\t\t\t\tvfst.TestIsDir(),\n\t\t\t\t\tvfst.TestModePerm(fs.ModePerm&^chezmoitest.Umask),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir/.keep\",\n\t\t\t\t\tvfst.TestContents(nil),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"dir_with_file\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".dir\": &vfst.Dir{\n\t\t\t\t\t\tPerm: fs.ModePerm,\n\t\t\t\t\t\tEntries: map[string]any{\n\t\t\t\t\t\t\t\"file\": \"# contents of .dir/file\\n\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.dir\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir\",\n\t\t\t\t\tvfst.TestIsDir(),\n\t\t\t\t\tvfst.TestModePerm(fs.ModePerm&^chezmoitest.Umask),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir/.keep\",\n\t\t\t\t\tvfst.TestDoesNotExist(),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir/file\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\"# contents of .dir/file\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"dir_with_file_with_--recursive=false\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".dir\": &vfst.Dir{\n\t\t\t\t\t\tPerm: fs.ModePerm,\n\t\t\t\t\t\tEntries: map[string]any{\n\t\t\t\t\t\t\t\"file\": \"# contents of .dir/file\\n\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.dir\", \"--recursive=false\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir\",\n\t\t\t\t\tvfst.TestIsDir(),\n\t\t\t\t\tvfst.TestModePerm(fs.ModePerm&^chezmoitest.Umask),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir/.keep\",\n\t\t\t\t\tvfst.TestContents(nil),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_dir/file\",\n\t\t\t\t\tvfst.TestDoesNotExist(),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"dir_private_unix\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".dir\": &vfst.Dir{\n\t\t\t\t\t\tPerm: 0o700,\n\t\t\t\t\t\tEntries: map[string]any{\n\t\t\t\t\t\t\t\"file\": \"# contents of .dir/file\\n\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.dir\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/private_dot_dir\",\n\t\t\t\t\tvfst.TestIsDir(),\n\t\t\t\t\tvfst.TestModePerm(fs.ModePerm&^chezmoitest.Umask),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/private_dot_dir/.keep\",\n\t\t\t\t\tvfst.TestDoesNotExist(),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/private_dot_dir/file\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\"# contents of .dir/file\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"dir_file_private_unix\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".dir\": &vfst.Dir{\n\t\t\t\t\t\tPerm: 0o700,\n\t\t\t\t\t\tEntries: map[string]any{\n\t\t\t\t\t\t\t\"file\": \"# contents of .dir/file\\n\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.dir/file\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/private_dot_dir\",\n\t\t\t\t\tvfst.TestIsDir(),\n\t\t\t\t\tvfst.TestModePerm(fs.ModePerm&^chezmoitest.Umask),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/private_dot_dir/.keep\",\n\t\t\t\t\tvfst.TestDoesNotExist(),\n\t\t\t\t),\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/private_dot_dir/file\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\"# contents of .dir/file\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"empty\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".empty\": \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.empty\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/empty_dot_empty\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContents(nil),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"executable_unix\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".executable\": &vfst.File{\n\t\t\t\t\t\tPerm: fs.ModePerm,\n\t\t\t\t\t\tContents: []byte(\"#!/bin/sh\\n\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.executable\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/executable_dot_executable\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\"#!/bin/sh\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"file\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".file\": \"# contents of .file\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.file\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_file\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\"# contents of .file\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"symlink\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".symlink\": &vfst.Symlink{\n\t\t\t\t\t\tTarget: \".dir/subdir/file\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.symlink\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/symlink_dot_symlink\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\".dir/subdir/file\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"symlink_with_--follow\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".file\": \"# contents of .file\\n\",\n\t\t\t\t\t\".symlink\": &vfst.Symlink{\n\t\t\t\t\t\tTarget: \".file\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"--follow\", \"~/.symlink\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_symlink\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\"# contents of .file\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"issue_3666\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".config/helix/themes/ayu_custom.toml\": \"# contents of ayu_custom.toml\\n\",\n\t\t\t\t\t\".local/share/chezmoi\": map[string]any{\n\t\t\t\t\t\t\"dot_config/exact_helix\": &vfst.Dir{Perm: 0o777 &^ chezmoitest.Umask},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"~/.config/helix/themes/ayu_custom.toml\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/dot_config/exact_helix/themes/ayu_custom.toml\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContentsString(\"# contents of ayu_custom.toml\\n\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"new\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".local/share/chezmoi\": &vfst.Dir{Perm: 0o777 &^ chezmoitest.Umask},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"--new\", \"~/.file\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/empty_dot_file\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContents(nil),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"new_--recursive=false\",\n\t\t\troot: map[string]any{\n\t\t\t\t\"/home/user\": map[string]any{\n\t\t\t\t\t\".local/share/chezmoi\": &vfst.Dir{Perm: 0o777 &^ chezmoitest.Umask},\n\t\t\t\t},\n\t\t\t},\n\t\t\targs: []string{\"--new\", \"--recursive=false\", \"~/.file\"},\n\t\t\ttests: []any{\n\t\t\t\tvfst.TestPath(\"/home/user/.local/share/chezmoi/empty_dot_file\",\n\t\t\t\t\tvfst.TestModeIsRegular(),\n\t\t\t\t\tvfst.TestModePerm(0o666&^chezmoitest.Umask),\n\t\t\t\t\tvfst.TestContents(nil),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tchezmoitest.SkipUnlessGOOS(t, tc.name)\n\t\t\tchezmoitest.WithTestFS(t, tc.root, func(fileSystem vfs.FS) {\n\t\t\t\tassert.NoError(t, newTestConfig(t, fileSystem).execute(append([]string{\"add\"}, tc.args...)))\n\t\t\t\tvfst.RunTests(t, fileSystem, \"\", tc.tests...)\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestAddCmdChmod(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"skipping UNIX test on Windows\")\n\t}\n\n\tchezmoitest.WithTestFS(t, map[string]any{\n\t\t\"/home/user\": map[string]any{\n\t\t\t\".dir/subdir/file\": \"# contents of .dir/subdir/file\\n\",\n\t\t},\n\t}, func(fileSystem vfs.FS) {\n\t\tassert.NoError(t, newTestConfig(t, fileSystem).execute([]string{\"add\", \"/home/user/.dir\"}))\n\t\tassert.NoError(t, fileSystem.Chmod(\"/home/user/.dir/subdir\", 0o700))\n\t\tassert.NoError(t, newTestConfig(t, fileSystem).execute([]string{\"add\", \"--force\", \"/home/user/.dir\"}))\n\t})\n}\n\nfunc TestAddCmdSecretsError(t *testing.T) {\n\tchezmoitest.WithTestFS(t, map[string]any{\n\t\t\"/home/user\": map[string]any{\n\t\t\t\".secret\": \"SUMO_ACCESS_KEY: gxq3rJQkS6qovOg9UY2Q70iH1jFZx0WBrrsiAYv4XHodogAwTKyLzvFK4neRN8Dk\",\n\t\t},\n\t}, func(fileSystem vfs.FS) {\n\t\tassert.Error(t, newTestConfig(t, fileSystem).execute([]string{\"add\", \"--secrets=error\", \"/home/user/.secret\"}))\n\t})\n}\n\nfunc TestIssue4107(t *testing.T) {\n\tif runtime.GOOS == \"windows\" && os.Getenv(\"GITHUB_RUN_ID\") != \"\" {\n\t\t// FIXME fix this test. It may be failing because the home directory on\n\t\t// GitHub Actions is on the D: drive\n\t\tt.Skip(\"skipping failing test on Windows on GitHub Actions\")\n\t}\n\tchezmoitest.WithTestFS(t, map[string]any{\n\t\t\"/home/user\": map[string]any{\n\t\t\t\".secret\": \"SUMO_ACCESS_KEY: gxq3rJQkS6qovOg9UY2Q70iH1jFZx0WBrrsiAYv4XHodogAwTKyLzvFK4neRN8Dk\",\n\t\t\t\".config/chezmoi\": map[string]any{\n\t\t\t\t\"chezmoi.toml\": chezmoitest.JoinLines(\n\t\t\t\t\t`[add]`,\n\t\t\t\t\t` secrets = \"error\"`,\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t}, func(fileSystem vfs.FS) {\n\t\tassert.NoError(t, newTestConfig(t, fileSystem).execute([]string{\"add\", \"--secrets=ignore\", \"/home/user/.secret\"}))\n\t})\n}\n"}, {"path": "internal/cmd/agecmd.go", "content": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\n\t\"filippo.io/age\"\n\t\"filippo.io/age/armor\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype ageDecryptCmdConfig struct {\n\tpassphrase bool\n}\n\ntype ageEncryptCmdConfig struct {\n\tpassphrase bool\n}\n\ntype ageCmdConfig struct {\n\tdecrypt ageDecryptCmdConfig\n\tencrypt ageEncryptCmdConfig\n}\n\nfunc (c *Config) newAgeCmd() *cobra.Command {\n\tageCmd := &cobra.Command{\n\t\tGroupID: groupIDEncryption,\n\t\tUse: \"age\",\n\t\tArgs: cobra.NoArgs,\n\t\tShort: \"Interact with age\",\n\t\tAnnotations: newAnnotations(\n\t\t\tpersistentStateModeReadOnly,\n\t\t),\n\t}\n\n\tageDecryptCmd := &cobra.Command{\n\t\tUse: \"decrypt [file...]\",\n\t\tShort: \"Decrypt file or standard input\",\n\t\tRunE: c.runAgeDecryptCmd,\n\t\tAnnotations: newAnnotations(\n\t\t\tpersistentStateModeReadOnly,\n\t\t),\n\t}\n\tageDecryptCmd.Flags().\n\t\tBoolVarP(&c.age.decrypt.passphrase, \"passphrase\", \"p\", c.age.decrypt.passphrase, \"Decrypt with a passphrase\")\n\tageCmd.AddCommand(ageDecryptCmd)\n\n\tageEncryptCmd := &cobra.Command{\n\t\tUse: \"encrypt [file...]\",\n\t\tShort: \"Encrypt file or standard input\",\n\t\tRunE: c.runAgeEncryptCmd,\n\t\tAnnotations: newAnnotations(\n\t\t\tpersistentStateModeReadOnly,\n\t\t),\n\t}\n\tageEncryptCmd.Flags().\n\t\tBoolVarP(&c.age.encrypt.passphrase, \"passphrase\", \"p\", c.age.encrypt.passphrase, \"Encrypt with a passphrase\")\n\tageCmd.AddCommand(ageEncryptCmd)\n\n\treturn ageCmd\n}\n\nfunc (c *Config) runAgeDecryptCmd(cmd *cobra.Command, args []string) error {\n\tif !c.age.decrypt.passphrase {\n\t\treturn errors.New(\"only passphrase encryption is supported\")\n\t}\n\tdecrypt := func(ciphertext []byte) ([]byte, error) {\n\t\tvar ciphertextReader io.Reader = bytes.NewReader(ciphertext)\n\t\tif bytes.HasPrefix(ciphertext, []byte(armor.Header)) {\n\t\t\tciphertextReader = armor.NewReader(ciphertextReader)\n\t\t}\n\t\tidentity := &LazyScryptIdentity{\n\t\t\tPassphrase: func() (string, error) {\n\t\t\t\treturn c.readPassword(\"Enter passphrase: \", \"passphrase\")\n\t\t\t},\n\t\t}\n\t\tplaintextReader, err := age.Decrypt(ciphertextReader, identity)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tplaintextBuffer := &bytes.Buffer{}\n\t\tif _, err := io.Copy(plaintextBuffer, plaintextReader); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn plaintextBuffer.Bytes(), nil\n\t}\n\treturn c.filterInput(args, decrypt)\n}\n\nfunc (c *Config) runAgeEncryptCmd(cmd *cobra.Command, args []string) error {\n\tif !c.age.encrypt.passphrase {\n\t\treturn errors.New(\"only passphrase encryption is supported\")\n\t}\n\tpassphrase, err := c.readPassword(\"Enter passphrase: \", \"passphrase\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfirmPassphrase, err := c.readPassword(\"Confirm passphrase: \", \"passphrase\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif passphrase != confirmPassphrase {\n\t\treturn errors.New(\"passphrases didn't match\")\n\t}\n\trecipient, err := age.NewScryptRecipient(passphrase)\n\tif err != nil {\n\t\treturn err\n\t}\n\tencrypt := func(plaintext []byte) ([]byte, error) {\n\t\tciphertextBuffer := &bytes.Buffer{}\n\t\tarmoredCiphertextWriter := armor.NewWriter(ciphertextBuffer)\n\t\tciphertextWriteCloser, err := age.Encrypt(armoredCiphertextWriter, recipient)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err := io.Copy(ciphertextWriteCloser, bytes.NewReader(plaintext)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := ciphertextWriteCloser.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := armoredCiphertextWriter.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ciphertextBuffer.Bytes(), nil\n\t}\n\treturn c.filterInput(args, encrypt)\n}\n"}, {"path": "internal/cmd/agekeygencmd.go", "content": "package cmd\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"filippo.io/age\"\n\t\"github.com/spf13/cobra\"\n\t\"golang.org/x/term\"\n\n\t\"chezmoi.io/chezmoi/internal/chezmoi\"\n)\n\ntype ageKeygenCmdConfig struct {\n\tconvert bool\n\tpostQuantum bool\n}\n\nfunc (c *Config) newAgeKeygenCmd() *cobra.Command {\n\tageKeygenCommand := &cobra.Command{\n\t\tGroupID: groupIDEncryption,\n\t\tUse: \"age-keygen\",\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tShort: \"Generate an age identity or convert an age identity to an age recipient\",\n\t\tLong: mustLongHelp(\"age-keygen\"),\n\t\tExample: example(\"age-keygen\"),\n\t\tRunE: c.runAgeKeygenCmd,\n\t\tAnnotations: newAnnotations(\n\t\t\tpersistentStateModeNone,\n\t\t),\n\t}\n\tageKeygenCommand.Flags().\n\t\tBoolVarP(&c.ageKeygen.convert, \"convert\", \"y\", c.ageKeygen.convert, \"convert identities to recipients\")\n\tageKeygenCommand.Flags().\n\t\tBoolVar(&c.ageKeygen.postQuantum, \"pq\", c.ageKeygen.postQuantum, \"generate a post-quantum key pair\")\n\n\treturn ageKeygenCommand\n}\n\nfunc (c *Config) runAgeKeygenCmd(cmd *cobra.Command, args []string) error {\n\tswitch {\n\tcase c.ageKeygen.convert && c.ageKeygen.postQuantum:\n\t\treturn errors.New(\"--pq cannot be used with --convert\")\n\tcase c.ageKeygen.convert:\n\t\treturn c.runAgeKeygenConvertCmd(args)\n\tdefault:\n\t\treturn c.runAgeKeygenGenerateCmd(cmd, args)\n\t}\n}\n\nfunc (c *Config) runAgeKeygenConvertCmd(args []string) error {\n\tinput := c.stdin\n\tif len(args) > 0 {\n\t\tinputFile, err := os.Open(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer inputFile.Close()\n\t\tinput = inputFile\n\t}\n\n\tidentities, err := age.ParseIdentities(input)\n\tswitch {\n\tcase err != nil:\n\t\treturn err\n\tcase len(identities) == 0:\n\t\treturn errors.New(\"no identities found in input\")\n\t}\n\n\tvar builder strings.Builder\n\tfor _, identity := range identities {\n\t\tid, ok := identity.(*age.X25519Identity)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"internal error: unexpected identity type: %T\", id)\n\t\t}\n\t\tbuilder.WriteString(id.Recipient().String())\n\t\tbuilder.WriteByte('\\n')\n\t}\n\treturn c.writeOutputString(builder.String(), 0o666)\n}\n\nfunc (c *Config) runAgeKeygenGenerateCmd(cmd *cobra.Command, args []string) error {\n\tif len(args) > 0 {\n\t\treturn fmt.Errorf(\"unknown command %q for %q\", args[0], cmd.CommandPath())\n\t}\n\n\tvar identity age.Identity\n\tvar recipient age.Recipient\n\tif c.ageKeygen.postQuantum {\n\t\tkey, err := age.GenerateHybridIdentity()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tidentity = key\n\t\trecipient = key.Recipient()\n\t} else {\n\t\tkey, err := age.GenerateX25519Identity()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tidentity = key\n\t\trecipient = key.Recipient()\n\t}\n\n\tif stdout, ok := c.stdout.(*os.File); ok && term.IsTerminal(int(stdout.Fd())) {\n\t\tfmt.Fprintf(c.stderr, \"Public key: %s\\n\", recipient)\n\t}\n\n\tif !c.outputAbsPath.IsEmpty() && c.outputAbsPath != chezmoi.NewAbsPath(\"-\") {\n\t\tswitch fileInfo, err := c.baseSystem.Stat(c.outputAbsPath); {\n\t\tcase errors.Is(err, fs.ErrNotExist):\n\t\t\t// Do nothing.\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase fileInfo.Mode().IsRegular() && fileInfo.Mode().Perm()&0o004 != 0:\n\t\t\tc.errorf(\"writing secret key to a world-readable file\\n\")\n\t\t}\n\t}\n\n\tvar builder strings.Builder\n\tfmt.Fprintf(&builder, \"# created: %s\\n\", time.Now().Format(time.RFC3339))\n\tfmt.Fprintf(&builder, \"# public key: %s\\n\", recipient)\n\tfmt.Fprintf(&builder, \"%s\\n\", identity)\n\treturn c.writeOutputString(builder.String(), 0o660)\n}\n"}, {"path": "internal/cmd/annotation.go", "content": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n// Annotations.\nvar (\n\tcreateSourceDirectoryIfNeeded = tagAnnotation(\"chezmoi_create_source_directory_if_needed\")\n\tdoesNotRequireValidConfig = tagAnnotation(\"chezmoi_runs_with_invalid_config\")\n\tdryRun = tagAnnotation(\"chezmoi_dry_run\")\n\tmodifiesConfigFile = tagAnnotation(\"chezmoi_modifies_config_file\")\n\tmodifiesDestinationDirectory = tagAnnotation(\"chezmoi_modifies_destination_directory\")\n\tmodifiesSourceDirectory = tagAnnotation(\"chezmoi_modifies_source_directory\")\n\toutputsDiff = tagAnnotation(\"chezmoi_outputs_diff\")\n\tpersistentStateModeKey = tagAnnotation(\"chezmoi_persistent_state_mode\")\n\trequiresConfigDirectory = tagAnnotation(\"chezmoi_requires_config_directory\")\n\trequiresSourceDirectory = tagAnnotation(\"chezmoi_requires_source_directory\")\n\trequiresWorkingTree = tagAnnotation(\"chezmoi_requires_working_tree\")\n\trunsCommands = tagAnnotation(\"chezmoi_runs_commands\")\n)\n\n// Persistent state modes.\nconst (\n\tpersistentStateModeEmpty persistentStateModeValue = \"empty\"\n\tpersistentStateModeNone persistentStateModeValue = \"none\"\n\tpersistentStateModeReadOnly persistentStateModeValue = \"read-only\"\n\tpersistentStateModeReadMockWrite persistentStateModeValue = \"read-mock-write\"\n\tpersistentStateModeReadWrite persistentStateModeValue = \"read-write\"\n)\n\ntype annotation interface {\n\tkey() string\n\tvalue() string\n}\n\ntype annotationsSet map[string]string\n\nfunc getAnnotations(cmd *cobra.Command) annotationsSet {\n\treturn annotationsSet(cmd.Annotations)\n}\n\nfunc newAnnotations(annotations ...annotation) annotationsSet {\n\tresult := make(map[string]string, len(annotations))\n\tfor _, annotation := range annotations {\n\t\tresult[annotation.key()] = annotation.value()\n\t}\n\treturn result\n}\n\nfunc (a annotationsSet) hasTag(tag annotation) bool {\n\treturn a[tag.key()] == tag.value()\n}\n\nfunc (a annotationsSet) persistentStateMode() persistentStateModeValue {\n\treturn persistentStateModeValue(a[persistentStateModeKey.key()])\n}\n\ntype persistentStateModeValue string\n\nfunc (m persistentStateModeValue) key() string {\n\treturn string(persistentStateModeKey)\n}\n\nfunc (m persistentStateModeValue) value() string {\n\treturn string(m)\n}\n\ntype tagAnnotation string\n\nfunc (a tagAnnotation) key() string {\n\treturn string(a)\n}\n\nfunc (a tagAnnotation) value() string {\n\treturn \"true\"\n}\n"}, {"path": "internal/cmd/applycmd.go", "content": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\t\"chezmoi.io/chezmoi/internal/chezmoi\"\n)\n\ntype applyCmdConfig struct {\n\tfilter *chezmoi.EntryTypeFilter\n\tinit bool\n\tparentDirs bool\n\trecursive bool\n}\n\nfunc (c *Config) newApplyCmd() *cobra.Command {\n\tapplyCmd := &cobra.Command{\n\t\tGroupID: groupIDDaily,\n\t\tUse: \"apply [target]...\",\n\t\tShort: \"Update the destination directory to match the target state\",\n\t\tLong: mustLongHelp(\"apply\"),\n\t\tExample: example(\"apply\"),\n\t\tValidArgsFunction: c.targetValidArgs,\n\t\tRunE: c.runApplyCmd,\n\t\tAnnotations: newAnnotations(\n\t\t\tmodifiesDestinationDirectory,\n\t\t\tpersistentStateModeReadWrite,\n\t\t\trequiresSourceDirectory,\n\t\t),\n\t}\n\n\tapplyCmd.Flags().VarP(c.apply.filter.Exclude, \"exclude\", \"x\", \"Exclude entry types\")\n\tapplyCmd.Flags().VarP(c.apply.filter.Include, \"include\", \"i\", \"Include entry types\")\n\tapplyCmd.Flags().BoolVar(&c.apply.init, \"init\", c.apply.init, \"Recreate config file from template\")\n\tapplyCmd.Flags().BoolVarP(&c.apply.parentDirs, \"parent-dirs\", \"P\", c.apply.parentDirs, \"Apply all parent directories\")\n\tapplyCmd.Flags().BoolVarP(&c.apply.recursive, \"recursive\", \"r\", c.apply.recursive, \"Recurse into subdirectories\")\n\n\treturn applyCmd\n}\n\nfunc (c *Config) runApplyCmd(cmd *cobra.Command, args []string) error {\n\treturn c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, args, applyArgsOptions{\n\t\tcmd: cmd,\n\t\tfilter: c.apply.filter,\n\t\tinit: c.apply.init,\n\t\tparentDirs: c.apply.parentDirs,\n\t\trecursive: c.apply.recursive,\n\t\tumask: c.Umask,\n\t\tpreApplyFunc: c.defaultPreApplyFunc,\n\t})\n}\n"}, {"path": "internal/cmd/awssecretsmanagertemplatefuncs.go", "content": "package cmd\n\nimport (\n\t\"context\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\n\t\"github.com/aws/aws-sdk-go-v2/aws\"\n\t\"github.com/aws/aws-sdk-go-v2/config\"\n\t\"github.com/aws/aws-sdk-go-v2/service/secretsmanager\"\n)\n\ntype awsSecretsManagerConfig struct {\n\tRegion string `json:\"region\" mapstructure:\"region\" yaml:\"region\"`\n\tProfile string `json:\"profile\" mapstructure:\"profile\" yaml:\"profile\"`\n\tsvc *secretsmanager.Client\n\tcache map[string]string\n\tjsonCache map[string]map[string]any\n}\n\nfunc (c *Config) awsSecretsManagerRawTemplateFunc(arn string) string {\n\tif secret, ok := c.AWSSecretsManager.cache[arn]; ok {\n\t\treturn secret\n\t}\n\n\tif c.AWSSecretsManager.svc == nil {\n\t\tvar opts []func(*config.LoadOptions) error\n\t\tif region := c.AWSSecretsManager.Region; region != \"\" {\n\t\t\topts = append(opts, config.WithRegion(region))\n\t\t}\n\t\tif profile := c.AWSSecretsManager.Profile; profile != \"\" {\n\t\t\topts = append(opts, config.WithSharedConfigProfile(profile))\n\t\t}\n\n\t\topts = append(opts, config.WithRetryMaxAttempts(1))\n\n\t\tcfg, err := config.LoadDefaultConfig(context.Background(), opts...)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tc.AWSSecretsManager.svc = secretsmanager.NewFromConfig(cfg)\n\t}\n\n\tresult, err := c.AWSSecretsManager.svc.GetSecretValue(context.Background(), &secretsmanager.GetSecretValueInput{\n\t\tSecretId: aws.String(arn),\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar secret string\n\tif result.SecretString != nil {\n\t\tsecret = *result.SecretString\n\t} else {\n\t\tdecodedBinarySecretBytes := make([]byte, base64.StdEncoding.DecodedLen(len(result.SecretBinary)))\n\t\tlength, err := base64.StdEncoding.Decode(decodedBinarySecretBytes, result.SecretBinary)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tsecret = string(decodedBinarySecretBytes[:length])\n\t}\n\n\tif c.AWSSecretsManager.cache == nil {\n\t\tc.AWSSecretsManager.cache = make(map[string]string)\n\t}\n\n\tc.AWSSecretsManager.cache[arn] = secret\n\treturn secret\n}\n\nfunc (c *Config) awsSecretsManagerTemplateFunc(arn string) map[string]any {\n\tif secret, ok := c.AWSSecretsManager.jsonCache[arn]; ok {\n\t\treturn secret\n\t}\n\n\traw := c.awsSecretsManagerRawTemplateFunc(arn)\n\n\tvar data map[string]any\n\tif err := json.Unmarshal([]byte(raw), &data); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif c.AWSSecretsManager.jsonCache == nil {\n\t\tc.AWSSecretsManager.jsonCache = make(map[string]map[string]any)\n\t}\n\n\tc.AWSSecretsManager.jsonCache[arn] = data\n\treturn data\n}\n"}, {"path": "internal/cmd/catconfigcmd.go", "content": "package cmd\n\nimport \"github.com/spf13/cobra\"\n\nfunc (c *Config) newCatConfigCmd() *cobra.Command {\n\tcatConfigCmd := &cobra.Command{\n\t\tGroupID: groupIDInternal,\n\t\tUse: \"cat-config\",\n\t\tShort: \"Print the configuration file\",\n\t\tLong: mustLongHelp(\"cat-config\"),\n\t\tExample: example(\"cat-config\"),\n\t\tArgs: cobra.NoArgs,\n\t\tValidArgsFunction: cobra.NoFileCompletions,\n\t\tRunE: c.runCatConfigCmd,\n\t\tAnnotations: newAnnotations(\n\t\t\tdoesNotRequireValidConfig,\n\t\t\tpersistentStateModeReadOnly,\n\t\t\trequiresConfigDirectory,\n\t\t),\n\t}\n\n\treturn catConfigCmd\n}\n\nfunc (c *Config) runCatConfigCmd(cmd *cobra.Command, args []string) error {\n\tconfigFileAbsPath, err := c.getConfigFileAbsPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := c.baseSystem.ReadFile(configFileAbsPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.writeOutput(data, 0o666)\n}\n"}], "context_lines": 1492, "buggy_files": ["assets/chezmoi.io/docs/reference/templates/functions/stdinIsATTY.md", "assets/chezmoi.io/docs/reference/templates/init-functions/stdinIsATTY.md", "assets/chezmoi.io/mkdocs.yml", "internal/cmd/config.go", "internal/cmd/executetemplatecmd.go", "internal/cmd/inittemplatefuncs.go", "internal/cmd/templatefuncs.go"], "test_files": [{"path": "internal/cmd/testdata/scripts/templatefuncs.txtar", "content": "[unix] chmod 755 bin/chezmoi-output-test\n[unix] chmod 755 bin/generate-color-formats\n[unix] chmod 755 bin/ioreg\n[unix] chmod 755 bin/executable\n[windows] unix2dos bin/chezmoi-output-test.cmd\n\nsymlink $HOME/symlink -> dir\n\n# test comment template function\nexec chezmoi execute-template '{{ \"line1\\nline2\" | comment \"# \" }}'\nrmfinalnewline golden/comment\ncmp stdout golden/comment\n\n# test completion template function\nexec chezmoi execute-template '{{ completion \"zsh\" }}'\nstdout '^# zsh completion for chezmoi'\n\n# test deleteValueAtPath template function\nexec chezmoi execute-template '{{ dict \"a\" (dict \"b\" (dict \"c\" 1 \"d\" 2)) | deleteValueAtPath \"a.b.c\" | toJson }}'\nrmfinalnewline golden/deleteValueAtPath\ncmp stdout golden/deleteValueAtPath\n\n# test ensureLinePrefix template function with two arguments\nexec chezmoi execute-template '{{ \"### Heading\\nBody\\n\" | ensureLinePrefix \"#\" }}'\ncmp stdout golden/ensureLinePrefix2\n\n# test ensureLinePrefix template function with three arguments\nexec chezmoi execute-template '{{ \"### Heading\\nBody\\n\" | ensureLinePrefix \"#\" \"# \" }}'\ncmp stdout golden/ensureLinePrefix3\n\n# test eqFold template function\nexec chezmoi execute-template '{{ eqFold \"foo\" \"Foo\" \"FOO\" }}'\nstdout '^true$'\n\n# test that the fromJson template function can deserialize JSON values\nexec chezmoi execute-template '{{ fromJson \"1\" }}'\nstdout '^1$'\n\n# test that the fromJson template function can deserialize JSON arrays\nexec chezmoi execute-template '{{ fromJson \"[1, 2]\" }}'\nstdout '^\\[1 2\\]$'\n\n# test fromJsonc template function\nstdin golden/example.jsonc\nexec chezmoi execute-template --with-stdin '{{ fromJsonc .chezmoi.stdin | toJson }}'\nstdout '{\"key\":1}'\n\n# test glob template function\nexec chezmoi execute-template '{{ glob \"*.txt\" | join \"\\n\" }}{{ \"\\n\" }}'\ncmp stdout golden/glob\n\n# test globCaseInsensitive template function\nexec chezmoi execute-template '{{ globCaseInsensitive \"*.TXT\" | join \"\\n\" }}{{ \"\\n\" }}'\ncmp stdout golden/glob\n\n# test hexDecode template function\nexec chezmoi execute-template '{{ \"6578616d706c65\" | hexDecode }}'\nstdout '^example$'\n\n# test hexEncode template function\nexec chezmoi execute-template '{{ \"example\" | hexEncode }}'\nstdout '^6578616d706c65$'\n\n# test ioreg template function\n[darwin] exec chezmoi execute-template '{{ index ioreg \"IOKitBuildVersion\" }}'\n[darwin] stdout 'Darwin Kernel Version'\n\n# test include template function with absolute path\nexec chezmoi execute-template '{{ joinPath (env \"HOME\") \".include\" | include }}'\ncmp stdout golden/include-abspath\n\n# test include template function with relative paths\nexec chezmoi execute-template '{{ include \".include\" }}'\ncmp stdout golden/include-relpath\n\n# test includeTemplate template function\nexec chezmoi execute-template '{{ includeTemplate \".template\" \"data\" }}'\nstdout ^data$\n\n# test includeTemplate template function searches .chezmoitemplates\nexec chezmoi execute-template '{{ includeTemplate \"template\" \"data\" }}'\nstdout ^data$\n\n# test joinPath template function\nexec chezmoi execute-template '{{ joinPath \"a\" \"b\" }}'\nstdout a${/}b\nexec chezmoi execute-template '{{ joinPath .chezmoi.destDir \"string\" }}'\nstdout home${/@R}user${/@R}string\n\n# test jq template function\nexec chezmoi execute-template '{{ dict \"key\" \"value\" | jq \".key\" | first }}'\nstdout ^value$\n\n# test isExecutable template function positive test case\n[unix] exec chezmoi execute-template '{{ isExecutable \"bin/executable\" }}'\n[windows] exec chezmoi execute-template '{{ isExecutable \"bin/executable.cmd\" }}'\nstdout ^true$\n\n# test isExecutable template function negative test case\nexec chezmoi execute-template '{{ isExecutable \"bin/not-executable\" }}'\nstdout ^false$\n\n# test findExecutable template function to find in specified script varargs - success\n[!windows] exec chezmoi execute-template '{{ findExecutable \"echo\" (list \"/lib\" \"/bin\" \"/usr/bin\") }}'\n[!windows] stdout ^/bin/echo$\n\n# test findOneExecutable template function to find in specified script varargs - success\n[!windows] exec chezmoi execute-template '{{ findOneExecutable (list \"chezmoish\" \"echo\") (list \"/lib\" \"/bin\" \"/usr/bin\") }}'\n[!windows] stdout ^/bin/echo$\n\n# test findExecutable template function to find in specified script varargs - failure\n[!windows] exec chezmoi execute-template '{{ findExecutable \"echo\" (list \"/lib\") }}'\n[!windows] stdout ^$\n\n# test findExecutable template function to find in specified script - success\n[!windows] exec chezmoi execute-template '{{ findExecutable \"echo\" (list \"/lib\" \"/bin\" \"/usr/bin\") }}'\n[!windows] stdout ^/bin/echo$\n\n# test findExecutable template function to find in specified script - failure\n[!windows] exec chezmoi execute-template '{{ findExecutable \"echo\" (list \"/lib\") }}'\n[!windows] stdout ^$\n\n# test findExecutable template function to find in specified script - success with extension\n[windows] exec chezmoi execute-template '{{ findExecutable \"git.exe\" (list \"c:\\\\windows\\\\system32\" \"c:\\\\windows\\\\system64\" \"C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\" \"C:\\\\Program Files\\\\Git\\\\cmd\") }}'\n[windows] stdout 'git'\n\n# test findExecutable template function to find in specified script - success without extension\n[windows] exec chezmoi execute-template '{{ findExecutable \"git\" (list \"c:\\\\windows\\\\system32\" \"c:\\\\windows\\\\system64\" \"C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\" \"C:\\\\Program Files\\\\Git\\\\cmd\") }}'\n[windows] stdout 'git'\n\n# test findExecutable template function to find in specified script - failure\n[windows] exec chezmoi execute-template '{{ findExecutable \"asdf\" (list \"c:\\\\windows\\\\system32\" \"c:\\\\windows\\\\system64\" \"C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\" \"C:\\\\Program Files\\\\Git\\\\cmd\") }}'\n[windows] stdout '^$'\n\n# test lookPath template function to find in PATH\nexec chezmoi execute-template '{{ lookPath \"go\" }}'\nstdout go$exe\n\n# test lookPath template function to check if file exists\nexec chezmoi execute-template '{{ lookPath \"/non-existing-file\" }}'\n! stdout .\n\n# test lstat template function\nexec chezmoi execute-template '{{ (joinPath .chezmoi.homeDir \"symlink\" | lstat).type }}'\nstdout ^symlink$\n\n# test mozillaInstallHash template function\nexec chezmoi execute-template '{{ mozillaInstallHash \"/Applications/Firefox.app/Contents/MacOS\" }}'\nstdout 2656FF1E876E9973\n\n# test the output and fromJson template functions\n[unix] exec chezmoi execute-template '{{ $red := output \"generate-color-formats\" \"#ff0000\" | fromJson }}{{ $red.rgb.r }}'\n[unix] stdout '^255$'\n\n# test the outputList and fromJson template functions\n[unix] exec chezmoi execute-template '{{ $red := outputList \"generate-color-formats\" (list \"#ff0000\" ) | fromJson }}{{ $red.rgb.r }}'\n[unix] stdout '^255$'\n\n# test that the output function returns an error if the command fails\n[unix] ! exec chezmoi execute-template '{{ output \"false\" }}'\n[unix] stderr 'error calling output: .*/false: exit status 1'\n\n# test pruneEmptyDicts template function\nexec chezmoi execute-template '{{ dict \"key1\" \"value1\" \"key2\" (dict) | pruneEmptyDicts | toJson }}'\nrmfinalnewline golden/pruneEmptyDicts\ncmp stdout golden/pruneEmptyDicts\n\n# test replaceAllRegex template function\nexec chezmoi execute-template '{{ \"foo bar baz\" | replaceAllRegex \"ba\" \"BA\" }}'\nstdout 'foo BAr BAz'\n\n# test the abortEmpty template function\nexec chezmoi execute-template 'before {{ abortEmpty }} after'\n! stdout .\n\n# test setValueAtPath template function\nexec chezmoi execute-template '{{ dict | setValueAtPath \"key1.key2\" \"value2\" | toJson }}'\nrmfinalnewline golden/setValueAtPath\ncmp stdout golden/setValueAtPath\n\n# test stdinIsATTY template function\nexec chezmoi execute-template '{{ stdinIsATTY }}'\nstdout false\n\n# test toIni template function\nexec chezmoi execute-template '{{ dict \"key\" \"value\" \"section\" (dict \"subkey\" \"subvalue\") | toIni }}'\ncmp stdout golden/toIni\n\n# test stat template function\nexec chezmoi execute-template '{{ (joinPath .chezmoi.homeDir \"symlink\" | stat).isDir }}'\nstdout true\n\n# test that the output template function returns a command's output\nexec chezmoi execute-template '{{ output \"chezmoi-output-test\" \"arg\" | trim }}'\nstdout arg\n\n# test that the output template function fails if the command fails\n! exec chezmoi execute-template '{{ output \"false\" }}'\n\n# test fromToml template function\nexec chezmoi execute-template '{{ (fromToml \"[section]\\nkey = \\\"value\\\"\").section.key }}'\nstdout '^value$'\n\n# test toToml template function\nexec chezmoi execute-template '{{ dict \"key\" \"value\" | toToml }}'\nstdout '^key = .value.$'\n\n# test that the toPrettyJson template function does not escape HTML characters, see https://github.com/golang/go/blob/7a6ddbb425218b2f4866478d0c673ba82c8438e6/src/encoding/json/encode.go#L48-L55\nexec chezmoi execute-template '{{ dict \"a\" (dict \"b\" \"&\") | toPrettyJson \" \" }}'\ncmp stdout golden/toPrettyJson\n\n# test that toStrings flattens nested lists\nexec chezmoi execute-template '{{ toStrings (list \"a\" \"b\" (list \"c\" \"d\")) }}'\nstdout '\\[a b c d\\]'\n\n# test fromYaml template function\nexec chezmoi execute-template '{{ (fromYaml \"key1: value1\\nkey2: value2\").key2 }}'\nstdout '^value2$'\n\n# test toYaml template function\nexec chezmoi execute-template '{{ dict \"key\" \"value\" | toYaml }}'\nstdout '^key: value$'\n\n# test that the overridden splitList function's output is compatible with quoteList\nexec chezmoi execute-template '{{ \"a b\" | splitList \" \" | quoteList }}'\nstdout '[\"a\" \"b\"]'\n\n-- bin/chezmoi-output-test --\n#!/bin/sh\n\necho \"$*\"\n-- bin/chezmoi-output-test.cmd --\n@echo off\nsetlocal\nset out=%*\nset out=%out:\\=%\necho %out%\nendlocal\n-- bin/executable --\n#!/bin/sh\n-- bin/executable.cmd --\n-- bin/generate-color-formats --\n#!/bin/sh\n\ncase \"$1\" in\n\"#ff0000\")\n cat <\"\n ;;\nesac\n-- bin/ioreg --\n#!/bin/sh\n\necho ''\necho ''\necho ''\necho ''\necho ' IOKitBuildVersion'\necho ' Darwin Kernel Version 21.1.0: Wed Oct 13 17:33:24 PDT 2021; root:xnu-8019.41.5~1/RELEASE_ARM64_T8101'\necho ''\necho ''\n-- bin/not-executable --\n-- golden/comment --\n# line1\n# line2\n-- golden/deleteValueAtPath --\n{\"a\":{\"b\":{\"d\":2}}}\n-- golden/ensureLinePrefix2 --\n### Heading\n#Body\n-- golden/ensureLinePrefix3 --\n### Heading\n# Body\n-- golden/example.jsonc --\n{\n \"key\": 1, // Comment\n}\n-- golden/expected --\n255\n-- golden/glob --\nfile1.txt\nfile2.txt\n-- golden/include-abspath --\n# contents of .include\n-- golden/include-relpath --\n# contents of .local/share/chezmoi/.include\n-- golden/pruneEmptyDicts --\n{\"key1\":\"value1\"}\n-- golden/setValueAtPath --\n{\"key1\":{\"key2\":\"value2\"}}\n-- golden/toIni --\nkey = value\n\n[section]\nsubkey = subvalue\n-- golden/toPrettyJson --\n{\n \"a\": {\n \"b\": \"&\"\n }\n}\n-- home/user/.include --\n# contents of .include\n-- home/user/.local/share/chezmoi/.chezmoitemplates/template --\n{{ . }}\n-- home/user/.local/share/chezmoi/.include --\n# contents of .local/share/chezmoi/.include\n-- home/user/.local/share/chezmoi/.template --\nchezmoi:template:left-delimiter=[[ right-delimiter=]]\n[[ . ]]\n-- home/user/.local/share/chezmoi/template --\n-- home/user/dir/.keep --\n-- home/user/file1.txt --\n-- home/user/file2.txt --\n"}], "eval": {"test_cmds": ["mkdir -p reports && go test -v -json ./... > reports/go-test-results.json"], "print_cmds": [], "log_parser": "def parser(log: str) -> dict[str, str]:\n import json\n import re\n import xml.etree.ElementTree as ET\n\n results: dict[str, str] = {}\n priority = {\"pass\": 0, \"skip\": 1, \"fail\": 2}\n\n def update(name: str | None, status: str) -> None:\n if not name:\n return\n status = status.lower()\n if status not in priority:\n return\n prev = results.get(name)\n if prev is None or priority[status] > priority[prev]:\n results[name] = status\n\n go_status_re = re.compile(r\"---\\s+(PASS|FAIL|SKIP):\\s+([^\\s]+)\")\n pytest_re = re.compile(r\"(\\S+::\\S+)\\s+(PASSED|FAILED|SKIPPED|ERROR|XFAIL|XPASS)\")\n unittest_re = re.compile(r\"^([\\w./:#-]+)\\s+\\.\\.\\.\\s+(ok|FAIL|ERROR|skipped)\", re.IGNORECASE)\n\n def parse_output(output: str, package: str | None = None) -> None:\n if not output:\n return\n for line in output.splitlines():\n match = go_status_re.search(line)\n if match:\n status = match.group(1).lower()\n test = match.group(2)\n name = f\"{package}/{test}\" if package else test\n update(name, status)\n match = pytest_re.search(line)\n if match:\n raw = match.group(2).lower()\n if raw in (\"passed\",):\n status = \"pass\"\n elif raw in (\"skipped\", \"xfail\"):\n status = \"skip\"\n else:\n status = \"fail\"\n update(match.group(1), status)\n match = unittest_re.search(line.strip())\n if match:\n raw = match.group(2).lower()\n if raw == \"ok\":\n status = \"pass\"\n elif raw == \"skipped\":\n status = \"skip\"\n else:\n status = \"fail\"\n update(match.group(1), status)\n\n for line in log.splitlines():\n line = line.strip()\n if not line:\n continue\n try:\n event = json.loads(line)\n except json.JSONDecodeError:\n parse_output(line)\n continue\n\n action = event.get(\"Action\")\n test = event.get(\"Test\")\n package = event.get(\"Package\")\n if action in (\"pass\", \"fail\", \"skip\") and test:\n name = f\"{package}/{test}\" if package else test\n update(name, action)\n\n output = event.get(\"Output\")\n if output:\n parse_output(output, package=package)\n\n if \"\", log)\n if not suites and log.strip().startswith(\"<\"):\n suites = [log]\n for suite in suites:\n try:\n root = ET.fromstring(suite)\n except ET.ParseError:\n continue\n\n def iter_testcases(elem):\n if elem.tag == \"testcase\":\n yield elem\n for child in elem:\n yield from iter_testcases(child)\n\n for tc in iter_testcases(root):\n classname = tc.attrib.get(\"classname\")\n name = tc.attrib.get(\"name\")\n full = f\"{classname}.{name}\" if classname and name else classname or name\n status = \"pass\"\n for child in tc:\n tag = child.tag.lower()\n if tag in (\"failure\", \"error\"):\n status = \"fail\"\n break\n if tag == \"skipped\":\n status = \"skip\"\n update(full, status)\n\n return results", "rebuild_cmds": []}} {"id": "patchbench-go-real-0062", "repo": "open-telemetry/opentelemetry-go", "base_commit": "73b2cd39b0fb6ca97ee3fc2c495d79e0b72e2b11", "status": "verified", "verify_status": "verified", "error": null, "timing": {"setup": 2.4, "pre_test_0": 12.0, "pre_test_1": 1.6, "post_test_0": 4.2, "post_test_1": 2.0, "total": 22.6}, "test_cmds": ["go test -json -v ./... > reports/go-test-results.json"], "rebuild_cmds": [], "print_cmds": [], "f2p_pre_ok": true, "pre_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 514}, "f2p_post_ok": true, "p2p_post_ok": true, "post_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 518}, "raw_tail": "opentelemetry.io/otel/semconv/v1.6.1\",\"Output\":\"? \\tgo.opentelemetry.io/otel/semconv/v1.6.1\\t[no test files]\\n\"}\n{\"Time\":\"2026-09-10T10:21:26.676902088Z\",\"Action\":\"skip\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.6.1\",\"Elapsed\":0}\n{\"Time\":\"2026-09-10T10:21:26.681775139Z\",\"Action\":\"start\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.7.0\"}\n{\"Time\":\"2026-09-10T10:21:26.681797944Z\",\"Action\":\"output\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.7.0\",\"Output\":\"? \\tgo.opentelemetry.io/otel/semconv/v1.7.0\\t[no test files]\\n\"}\n{\"Time\":\"2026-09-10T10:21:26.681803348Z\",\"Action\":\"skip\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.7.0\",\"Elapsed\":0}\n{\"Time\":\"2026-09-10T10:21:26.732836433Z\",\"Action\":\"start\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.8.0\"}\n{\"Time\":\"2026-09-10T10:21:26.732875338Z\",\"Action\":\"output\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.8.0\",\"Output\":\"? \\tgo.opentelemetry.io/otel/semconv/v1.8.0\\t[no test files]\\n\"}\n{\"Time\":\"2026-09-10T10:21:26.732884682Z\",\"Action\":\"skip\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.8.0\",\"Elapsed\":0}\n{\"Time\":\"2026-09-10T10:21:26.74046078Z\",\"Action\":\"start\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.9.0\"}\n{\"Time\":\"2026-09-10T10:21:26.740487888Z\",\"Action\":\"output\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.9.0\",\"Output\":\"? \\tgo.opentelemetry.io/otel/semconv/v1.9.0\\t[no test files]\\n\"}\n{\"Time\":\"2026-09-10T10:21:26.740494543Z\",\"Action\":\"skip\",\"Package\":\"go.opentelemetry.io/otel/semconv/v1.9.0\",\"Elapsed\":0}\n\n", "context_files": [{"path": "semconv/v1.34.0/error_type.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage semconv // import \"go.opentelemetry.io/otel/semconv/v1.34.0\"\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n)\n\n// ErrorType returns an [attribute.KeyValue] identifying the error type of err.\nfunc ErrorType(err error) attribute.KeyValue {\n\tif err == nil {\n\t\treturn ErrorTypeOther\n\t}\n\tt := reflect.TypeOf(err)\n\tvar value string\n\tif t.PkgPath() == \"\" && t.Name() == \"\" {\n\t\t// Likely a builtin type.\n\t\tvalue = t.String()\n\t} else {\n\t\tvalue = fmt.Sprintf(\"%s.%s\", t.PkgPath(), t.Name())\n\t}\n\n\tif value == \"\" {\n\t\treturn ErrorTypeOther\n\t}\n\treturn ErrorTypeKey.String(value)\n}\n"}, {"path": "doc.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n/*\nPackage otel provides global access to the OpenTelemetry API. The subpackages of\nthe otel package provide an implementation of the OpenTelemetry API.\n\nThe provided API is used to instrument code and measure data about that code's\nperformance and operation. The measured data, by default, is not processed or\ntransmitted anywhere. An implementation of the OpenTelemetry SDK, like the\ndefault SDK implementation (go.opentelemetry.io/otel/sdk), and associated\nexporters are used to process and transport this data.\n\nTo read the getting started guide, see https://opentelemetry.io/docs/languages/go/getting-started/.\n\nTo read more about tracing, see go.opentelemetry.io/otel/trace.\n\nTo read more about metrics, see go.opentelemetry.io/otel/metric.\n\nTo read more about logs, see go.opentelemetry.io/otel/log.\n\nTo read more about propagation, see go.opentelemetry.io/otel/propagation and\ngo.opentelemetry.io/otel/baggage.\n*/\npackage otel // import \"go.opentelemetry.io/otel\"\n"}, {"path": "error_handler.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\n// ErrorHandler handles irremediable events.\ntype ErrorHandler interface {\n\t// DO NOT CHANGE: any modification will not be backwards compatible and\n\t// must never be done outside of a new major release.\n\n\t// Handle handles any error deemed irremediable by an OpenTelemetry\n\t// component.\n\tHandle(error)\n\t// DO NOT CHANGE: any modification will not be backwards compatible and\n\t// must never be done outside of a new major release.\n}\n\n// ErrorHandlerFunc is a convenience adapter to allow the use of a function\n// as an ErrorHandler.\ntype ErrorHandlerFunc func(error)\n\nvar _ ErrorHandler = ErrorHandlerFunc(nil)\n\n// Handle handles the irremediable error by calling the ErrorHandlerFunc itself.\nfunc (f ErrorHandlerFunc) Handle(err error) {\n\tf(err)\n}\n"}, {"path": "handler.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"go.opentelemetry.io/otel/internal/global\"\n)\n\n// Compile-time check global.ErrDelegator implements ErrorHandler.\nvar _ ErrorHandler = (*global.ErrDelegator)(nil)\n\n// GetErrorHandler returns the global ErrorHandler instance.\n//\n// The default ErrorHandler instance returned will log all errors to STDERR\n// until an override ErrorHandler is set with SetErrorHandler. All\n// ErrorHandler returned prior to this will automatically forward errors to\n// the set instance instead of logging.\n//\n// Subsequent calls to SetErrorHandler after the first will not forward errors\n// to the new ErrorHandler for prior returned instances.\nfunc GetErrorHandler() ErrorHandler { return global.GetErrorHandler() }\n\n// SetErrorHandler sets the global ErrorHandler to h.\n//\n// The first time this is called all ErrorHandler previously returned from\n// GetErrorHandler will send errors to h instead of the default logging\n// ErrorHandler. Subsequent calls will set the global ErrorHandler, but not\n// delegate errors to h.\nfunc SetErrorHandler(h ErrorHandler) { global.SetErrorHandler(h) }\n\n// Handle is a convenience function for GetErrorHandler().Handle(err).\nfunc Handle(err error) { global.GetErrorHandler().Handle(err) }\n"}, {"path": "handler_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype testErrHandler struct {\n\terr error\n}\n\nvar _ ErrorHandler = &testErrHandler{}\n\nfunc (eh *testErrHandler) Handle(err error) { eh.err = err }\n\nfunc TestGlobalErrorHandler(t *testing.T) {\n\tSetErrorHandler(GetErrorHandler())\n\tassert.NotPanics(t, func() { Handle(assert.AnError) }, \"Default assignment\")\n\n\te1 := &testErrHandler{}\n\tSetErrorHandler(e1)\n\tHandle(assert.AnError)\n\tassert.ErrorIs(t, e1.err, assert.AnError)\n\te1.err = nil\n\n\te2 := &testErrHandler{}\n\tSetErrorHandler(e2)\n\tGetErrorHandler().Handle(assert.AnError)\n\tassert.ErrorIs(t, e2.err, assert.AnError)\n}\n"}, {"path": "internal_logging.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"github.com/go-logr/logr\"\n\n\t\"go.opentelemetry.io/otel/internal/global\"\n)\n\n// SetLogger configures the logger used internally to opentelemetry.\nfunc SetLogger(logger logr.Logger) {\n\tglobal.SetLogger(logger)\n}\n"}, {"path": "internal_logging_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel_test\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/go-logr/stdr\"\n\n\t\"go.opentelemetry.io/otel\"\n)\n\nfunc ExampleSetLogger() {\n\tlogger := stdr.New(log.New(os.Stdout, \"\", log.LstdFlags|log.Lshortfile))\n\totel.SetLogger(logger)\n}\n"}, {"path": "metric.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"go.opentelemetry.io/otel/internal/global\"\n\t\"go.opentelemetry.io/otel/metric\"\n)\n\n// Meter returns a Meter from the global MeterProvider. The name must be the\n// name of the library providing instrumentation. This name may be the same as\n// the instrumented code only if that code provides built-in instrumentation.\n// If the name is empty, then a implementation defined default name will be\n// used instead.\n//\n// If this is called before a global MeterProvider is registered the returned\n// Meter will be a No-op implementation of a Meter. When a global MeterProvider\n// is registered for the first time, the returned Meter, and all the\n// instruments it has created or will create, are recreated automatically from\n// the new MeterProvider.\n//\n// This is short for GetMeterProvider().Meter(name).\nfunc Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn GetMeterProvider().Meter(name, opts...)\n}\n\n// GetMeterProvider returns the registered global meter provider.\n//\n// If no global GetMeterProvider has been registered, a No-op GetMeterProvider\n// implementation is returned. When a global GetMeterProvider is registered for\n// the first time, the returned GetMeterProvider, and all the Meters it has\n// created or will create, are recreated automatically from the new\n// GetMeterProvider.\nfunc GetMeterProvider() metric.MeterProvider {\n\treturn global.MeterProvider()\n}\n\n// SetMeterProvider registers mp as the global MeterProvider.\nfunc SetMeterProvider(mp metric.MeterProvider) {\n\tglobal.SetMeterProvider(mp)\n}\n"}, {"path": "metric_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t\"go.opentelemetry.io/otel/metric/noop\"\n)\n\ntype testMeterProvider struct{ embedded.MeterProvider }\n\nvar _ metric.MeterProvider = &testMeterProvider{}\n\nfunc (*testMeterProvider) Meter(_ string, _ ...metric.MeterOption) metric.Meter {\n\treturn noop.NewMeterProvider().Meter(\"\")\n}\n\nfunc TestMultipleGlobalMeterProvider(t *testing.T) {\n\tp1 := testMeterProvider{}\n\tp2 := noop.NewMeterProvider()\n\tSetMeterProvider(&p1)\n\tSetMeterProvider(p2)\n\n\tgot := GetMeterProvider()\n\tassert.Equal(t, p2, got)\n}\n"}, {"path": "propagation.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"go.opentelemetry.io/otel/internal/global\"\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n// GetTextMapPropagator returns the global TextMapPropagator. If none has been\n// set, a No-Op TextMapPropagator is returned.\nfunc GetTextMapPropagator() propagation.TextMapPropagator {\n\treturn global.TextMapPropagator()\n}\n\n// SetTextMapPropagator sets propagator as the global TextMapPropagator.\nfunc SetTextMapPropagator(propagator propagation.TextMapPropagator) {\n\tglobal.SetTextMapPropagator(propagator)\n}\n"}, {"path": "semconv/v1.34.0/doc.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package semconv implements OpenTelemetry semantic conventions.\n//\n// OpenTelemetry semantic conventions are agreed standardized naming\n// patterns for OpenTelemetry things. This package represents the v1.34.0\n// version of the OpenTelemetry semantic conventions.\npackage semconv // import \"go.opentelemetry.io/otel/semconv/v1.34.0\"\n"}, {"path": "semconv/v1.34.0/exception.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage semconv // import \"go.opentelemetry.io/otel/semconv/v1.34.0\"\n\nconst (\n\t// ExceptionEventName is the name of the Span event representing an exception.\n\tExceptionEventName = \"exception\"\n)\n"}, {"path": "semconv/v1.34.0/schema.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage semconv // import \"go.opentelemetry.io/otel/semconv/v1.34.0\"\n\n// SchemaURL is the schema URL that matches the version of the semantic conventions\n// that this package defines. Semconv packages starting from v1.4.0 must declare\n// non-empty schema URL in the form https://opentelemetry.io/schemas/\nconst SchemaURL = \"https://opentelemetry.io/schemas/1.34.0\"\n"}, {"path": "trace.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"go.opentelemetry.io/otel/internal/global\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\n// Tracer creates a named tracer that implements Tracer interface.\n// If the name is an empty string then provider uses default name.\n//\n// This is short for GetTracerProvider().Tracer(name, opts...)\nfunc Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn GetTracerProvider().Tracer(name, opts...)\n}\n\n// GetTracerProvider returns the registered global trace provider.\n// If none is registered then an instance of NoopTracerProvider is returned.\n//\n// Use the trace provider to create a named tracer. E.g.\n//\n//\ttracer := otel.GetTracerProvider().Tracer(\"example.com/foo\")\n//\n// or\n//\n//\ttracer := otel.Tracer(\"example.com/foo\")\nfunc GetTracerProvider() trace.TracerProvider {\n\treturn global.TracerProvider()\n}\n\n// SetTracerProvider registers `tp` as the global trace provider.\nfunc SetTracerProvider(tp trace.TracerProvider) {\n\tglobal.SetTracerProvider(tp)\n}\n"}, {"path": "trace_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.opentelemetry.io/otel/trace/embedded\"\n\t\"go.opentelemetry.io/otel/trace/noop\"\n)\n\ntype testTracerProvider struct{ embedded.TracerProvider }\n\nvar _ trace.TracerProvider = &testTracerProvider{}\n\nfunc (*testTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer {\n\treturn noop.NewTracerProvider().Tracer(\"\")\n}\n\nfunc TestMultipleGlobalTracerProvider(t *testing.T) {\n\tp1 := testTracerProvider{}\n\tp2 := noop.NewTracerProvider()\n\tSetTracerProvider(&p1)\n\tSetTracerProvider(p2)\n\n\tgot := GetTracerProvider()\n\tassert.Equal(t, p2, got)\n}\n"}, {"path": "version.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\n// Version is the current release version of OpenTelemetry in use.\nfunc Version() string {\n\treturn \"1.37.0\"\n}\n"}, {"path": "version_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel_test\n\nimport (\n\t\"regexp\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/otel\"\n)\n\n// regex taken from https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nvar versionRegex = regexp.MustCompile(`^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)` +\n\t`(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)` +\n\t`(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?` +\n\t`(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$`)\n\nfunc TestVersionSemver(t *testing.T) {\n\tv := otel.Version()\n\tassert.NotNil(t, versionRegex.FindStringSubmatch(v), \"version is not semver: %s\", v)\n}\n"}, {"path": "semconv/v1.34.0/error_type_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage semconv // import \"go.opentelemetry.io/otel/semconv/v1.34.0\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n)\n\ntype CustomError struct{}\n\nfunc (CustomError) Error() string {\n\treturn \"custom error\"\n}\n\nfunc TestErrorType(t *testing.T) {\n\tcustomErr := CustomError{}\n\tbuiltinErr := errors.New(\"something went wrong\")\n\tvar nilErr error\n\n\twantCustomType := reflect.TypeOf(customErr)\n\twantCustomStr := fmt.Sprintf(\"%s.%s\", wantCustomType.PkgPath(), wantCustomType.Name())\n\n\ttests := []struct {\n\t\tname string\n\t\terr error\n\t\twant attribute.KeyValue\n\t}{\n\t\t{\n\t\t\tname: \"BuiltinError\",\n\t\t\terr: builtinErr,\n\t\t\twant: attribute.String(\"error.type\", \"*errors.errorString\"),\n\t\t},\n\t\t{\n\t\t\tname: \"CustomError\",\n\t\t\terr: customErr,\n\t\t\twant: attribute.String(\"error.type\", wantCustomStr),\n\t\t},\n\t\t{\n\t\t\tname: \"NilError\",\n\t\t\terr: nilErr,\n\t\t\twant: ErrorTypeOther,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := ErrorType(tt.err)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"ErrorType(%v) = %v, want %v\", tt.err, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"}, {"path": "attribute/benchmark_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute_test\n\nimport (\n\t\"testing\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n)\n\n// Store results in a file scope var to ensure compiler does not optimize the\n// test away.\nvar (\n\toutV attribute.Value\n\toutKV attribute.KeyValue\n\n\toutBool bool\n\toutBoolSlice []bool\n\toutInt64 int64\n\toutInt64Slice []int64\n\toutFloat64 float64\n\toutFloat64Slice []float64\n\toutStr string\n\toutStrSlice []string\n)\n\nfunc benchmarkEmit(kv attribute.KeyValue) func(*testing.B) {\n\treturn func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutStr = kv.Value.Emit()\n\t\t}\n\t}\n}\n\nfunc BenchmarkBool(b *testing.B) {\n\tk, v := \"bool\", true\n\tkv := attribute.Bool(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.BoolValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.Bool(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsBool\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutBool = kv.Value.AsBool()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkBoolSlice(b *testing.B) {\n\tk, v := \"bool slice\", []bool{true, false, true}\n\tkv := attribute.BoolSlice(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.BoolSliceValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.BoolSlice(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsBoolSlice\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutBoolSlice = kv.Value.AsBoolSlice()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkInt(b *testing.B) {\n\tk, v := \"int\", int(42)\n\tkv := attribute.Int(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.IntValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.Int(k, v)\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkIntSlice(b *testing.B) {\n\tk, v := \"int slice\", []int{42, -3, 12}\n\tkv := attribute.IntSlice(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.IntSliceValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.IntSlice(k, v)\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkInt64(b *testing.B) {\n\tk, v := \"int64\", int64(42)\n\tkv := attribute.Int64(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.Int64Value(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.Int64(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsInt64\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutInt64 = kv.Value.AsInt64()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkInt64Slice(b *testing.B) {\n\tk, v := \"int64 slice\", []int64{42, -3, 12}\n\tkv := attribute.Int64Slice(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.Int64SliceValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.Int64Slice(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsInt64Slice\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutInt64Slice = kv.Value.AsInt64Slice()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkFloat64(b *testing.B) {\n\tk, v := \"float64\", float64(42)\n\tkv := attribute.Float64(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.Float64Value(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.Float64(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsFloat64\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutFloat64 = kv.Value.AsFloat64()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkFloat64Slice(b *testing.B) {\n\tk, v := \"float64 slice\", []float64{42, -3, 12}\n\tkv := attribute.Float64Slice(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.Float64SliceValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.Float64Slice(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsFloat64Slice\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutFloat64Slice = kv.Value.AsFloat64Slice()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkString(b *testing.B) {\n\tk, v := \"string\", \"42\"\n\tkv := attribute.String(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.StringValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.String(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsString\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutStr = kv.Value.AsString()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n\nfunc BenchmarkStringSlice(b *testing.B) {\n\tk, v := \"float64 slice\", []string{\"forty-two\", \"negative three\", \"twelve\"}\n\tkv := attribute.StringSlice(k, v)\n\n\tb.Run(\"Value\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutV = attribute.StringSliceValue(v)\n\t\t}\n\t})\n\tb.Run(\"KeyValue\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutKV = attribute.StringSlice(k, v)\n\t\t}\n\t})\n\tb.Run(\"AsStringSlice\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toutStrSlice = kv.Value.AsStringSlice()\n\t\t}\n\t})\n\tb.Run(\"Emit\", benchmarkEmit(kv))\n}\n"}, {"path": "attribute/doc.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package attribute provides key and value attributes.\npackage attribute // import \"go.opentelemetry.io/otel/attribute\"\n"}, {"path": "attribute/encoder.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute // import \"go.opentelemetry.io/otel/attribute\"\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\ntype (\n\t// Encoder is a mechanism for serializing an attribute set into a specific\n\t// string representation that supports caching, to avoid repeated\n\t// serialization. An example could be an exporter encoding the attribute\n\t// set into a wire representation.\n\tEncoder interface {\n\t\t// Encode returns the serialized encoding of the attribute set using\n\t\t// its Iterator. This result may be cached by a attribute.Set.\n\t\tEncode(iterator Iterator) string\n\n\t\t// ID returns a value that is unique for each class of attribute\n\t\t// encoder. Attribute encoders allocate these using `NewEncoderID`.\n\t\tID() EncoderID\n\t}\n\n\t// EncoderID is used to identify distinct Encoder\n\t// implementations, for caching encoded results.\n\tEncoderID struct {\n\t\tvalue uint64\n\t}\n\n\t// defaultAttrEncoder uses a sync.Pool of buffers to reduce the number of\n\t// allocations used in encoding attributes. This implementation encodes a\n\t// comma-separated list of key=value, with '/'-escaping of '=', ',', and\n\t// '\\'.\n\tdefaultAttrEncoder struct {\n\t\t// pool is a pool of attribute set builders. The buffers in this pool\n\t\t// grow to a size that most attribute encodings will not allocate new\n\t\t// memory.\n\t\tpool sync.Pool // *bytes.Buffer\n\t}\n)\n\n// escapeChar is used to ensure uniqueness of the attribute encoding where\n// keys or values contain either '=' or ','. Since there is no parser needed\n// for this encoding and its only requirement is to be unique, this choice is\n// arbitrary. Users will see these in some exporters (e.g., stdout), so the\n// backslash ('\\') is used as a conventional choice.\nconst escapeChar = '\\\\'\n\nvar (\n\t_ Encoder = &defaultAttrEncoder{}\n\n\t// encoderIDCounter is for generating IDs for other attribute encoders.\n\tencoderIDCounter uint64\n\n\tdefaultEncoderOnce sync.Once\n\tdefaultEncoderID = NewEncoderID()\n\tdefaultEncoderInstance *defaultAttrEncoder\n)\n\n// NewEncoderID returns a unique attribute encoder ID. It should be called\n// once per each type of attribute encoder. Preferably in init() or in var\n// definition.\nfunc NewEncoderID() EncoderID {\n\treturn EncoderID{value: atomic.AddUint64(&encoderIDCounter, 1)}\n}\n\n// DefaultEncoder returns an attribute encoder that encodes attributes in such\n// a way that each escaped attribute's key is followed by an equal sign and\n// then by an escaped attribute's value. All key-value pairs are separated by\n// a comma.\n//\n// Escaping is done by prepending a backslash before either a backslash, equal\n// sign or a comma.\nfunc DefaultEncoder() Encoder {\n\tdefaultEncoderOnce.Do(func() {\n\t\tdefaultEncoderInstance = &defaultAttrEncoder{\n\t\t\tpool: sync.Pool{\n\t\t\t\tNew: func() interface{} {\n\t\t\t\t\treturn &bytes.Buffer{}\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n\treturn defaultEncoderInstance\n}\n\n// Encode is a part of an implementation of the AttributeEncoder interface.\nfunc (d *defaultAttrEncoder) Encode(iter Iterator) string {\n\tbuf := d.pool.Get().(*bytes.Buffer)\n\tdefer d.pool.Put(buf)\n\tbuf.Reset()\n\n\tfor iter.Next() {\n\t\ti, keyValue := iter.IndexedAttribute()\n\t\tif i > 0 {\n\t\t\t_, _ = buf.WriteRune(',')\n\t\t}\n\t\tcopyAndEscape(buf, string(keyValue.Key))\n\n\t\t_, _ = buf.WriteRune('=')\n\n\t\tif keyValue.Value.Type() == STRING {\n\t\t\tcopyAndEscape(buf, keyValue.Value.AsString())\n\t\t} else {\n\t\t\t_, _ = buf.WriteString(keyValue.Value.Emit())\n\t\t}\n\t}\n\treturn buf.String()\n}\n\n// ID is a part of an implementation of the AttributeEncoder interface.\nfunc (*defaultAttrEncoder) ID() EncoderID {\n\treturn defaultEncoderID\n}\n\n// copyAndEscape escapes `=`, `,` and its own escape character (`\\`),\n// making the default encoding unique.\nfunc copyAndEscape(buf *bytes.Buffer, val string) {\n\tfor _, ch := range val {\n\t\tswitch ch {\n\t\tcase '=', ',', escapeChar:\n\t\t\t_, _ = buf.WriteRune(escapeChar)\n\t\t}\n\t\t_, _ = buf.WriteRune(ch)\n\t}\n}\n\n// Valid returns true if this encoder ID was allocated by\n// `NewEncoderID`. Invalid encoder IDs will not be cached.\nfunc (id EncoderID) Valid() bool {\n\treturn id.value != 0\n}\n"}, {"path": "attribute/filter.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute // import \"go.opentelemetry.io/otel/attribute\"\n\n// Filter supports removing certain attributes from attribute sets. When\n// the filter returns true, the attribute will be kept in the filtered\n// attribute set. When the filter returns false, the attribute is excluded\n// from the filtered attribute set, and the attribute instead appears in\n// the removed list of excluded attributes.\ntype Filter func(KeyValue) bool\n\n// NewAllowKeysFilter returns a Filter that only allows attributes with one of\n// the provided keys.\n//\n// If keys is empty a deny-all filter is returned.\nfunc NewAllowKeysFilter(keys ...Key) Filter {\n\tif len(keys) <= 0 {\n\t\treturn func(kv KeyValue) bool { return false }\n\t}\n\n\tallowed := make(map[Key]struct{}, len(keys))\n\tfor _, k := range keys {\n\t\tallowed[k] = struct{}{}\n\t}\n\treturn func(kv KeyValue) bool {\n\t\t_, ok := allowed[kv.Key]\n\t\treturn ok\n\t}\n}\n\n// NewDenyKeysFilter returns a Filter that only allows attributes\n// that do not have one of the provided keys.\n//\n// If keys is empty an allow-all filter is returned.\nfunc NewDenyKeysFilter(keys ...Key) Filter {\n\tif len(keys) <= 0 {\n\t\treturn func(kv KeyValue) bool { return true }\n\t}\n\n\tforbid := make(map[Key]struct{}, len(keys))\n\tfor _, k := range keys {\n\t\tforbid[k] = struct{}{}\n\t}\n\treturn func(kv KeyValue) bool {\n\t\t_, ok := forbid[kv.Key]\n\t\treturn !ok\n\t}\n}\n"}, {"path": "attribute/filter_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute\n\nimport \"testing\"\n\nfunc TestNewAllowKeysFilter(t *testing.T) {\n\tkeys := []string{\"zero\", \"one\", \"two\"}\n\tattrs := []KeyValue{Int(keys[0], 0), Int(keys[1], 1), Int(keys[2], 2)}\n\n\tt.Run(\"Empty\", func(t *testing.T) {\n\t\tempty := NewAllowKeysFilter()\n\t\tfor _, kv := range attrs {\n\t\t\tif empty(kv) {\n\t\t\t\tt.Errorf(\"empty NewAllowKeysFilter filter accepted %v\", kv)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Partial\", func(t *testing.T) {\n\t\tpartial := NewAllowKeysFilter(Key(keys[0]), Key(keys[1]))\n\t\tfor _, kv := range attrs[:2] {\n\t\t\tif !partial(kv) {\n\t\t\t\tt.Errorf(\"partial NewAllowKeysFilter filter denied %v\", kv)\n\t\t\t}\n\t\t}\n\t\tif partial(attrs[2]) {\n\t\t\tt.Errorf(\"partial NewAllowKeysFilter filter accepted %v\", attrs[2])\n\t\t}\n\t})\n\n\tt.Run(\"Full\", func(t *testing.T) {\n\t\tfull := NewAllowKeysFilter(Key(keys[0]), Key(keys[1]), Key(keys[2]))\n\t\tfor _, kv := range attrs {\n\t\t\tif !full(kv) {\n\t\t\t\tt.Errorf(\"full NewAllowKeysFilter filter denied %v\", kv)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestNewDenyKeysFilter(t *testing.T) {\n\tkeys := []string{\"zero\", \"one\", \"two\"}\n\tattrs := []KeyValue{Int(keys[0], 0), Int(keys[1], 1), Int(keys[2], 2)}\n\n\tt.Run(\"Empty\", func(t *testing.T) {\n\t\tempty := NewDenyKeysFilter()\n\t\tfor _, kv := range attrs {\n\t\t\tif !empty(kv) {\n\t\t\t\tt.Errorf(\"empty NewDenyKeysFilter filter denied %v\", kv)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Partial\", func(t *testing.T) {\n\t\tpartial := NewDenyKeysFilter(Key(keys[0]), Key(keys[1]))\n\t\tfor _, kv := range attrs[:2] {\n\t\t\tif partial(kv) {\n\t\t\t\tt.Errorf(\"partial NewDenyKeysFilter filter accepted %v\", kv)\n\t\t\t}\n\t\t}\n\t\tif !partial(attrs[2]) {\n\t\t\tt.Errorf(\"partial NewDenyKeysFilter filter denied %v\", attrs[2])\n\t\t}\n\t})\n\n\tt.Run(\"Full\", func(t *testing.T) {\n\t\tfull := NewDenyKeysFilter(Key(keys[0]), Key(keys[1]), Key(keys[2]))\n\t\tfor _, kv := range attrs {\n\t\t\tif full(kv) {\n\t\t\t\tt.Errorf(\"full NewDenyKeysFilter filter accepted %v\", kv)\n\t\t\t}\n\t\t}\n\t})\n}\n"}, {"path": "attribute/internal/attribute.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n/*\nPackage attribute provide several helper functions for some commonly used\nlogic of processing attributes.\n*/\npackage attribute // import \"go.opentelemetry.io/otel/attribute/internal\"\n\nimport (\n\t\"reflect\"\n)\n\n// BoolSliceValue converts a bool slice into an array with same elements as slice.\nfunc BoolSliceValue(v []bool) interface{} {\n\tvar zero bool\n\tcp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem()\n\treflect.Copy(cp, reflect.ValueOf(v))\n\treturn cp.Interface()\n}\n\n// Int64SliceValue converts an int64 slice into an array with same elements as slice.\nfunc Int64SliceValue(v []int64) interface{} {\n\tvar zero int64\n\tcp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem()\n\treflect.Copy(cp, reflect.ValueOf(v))\n\treturn cp.Interface()\n}\n\n// Float64SliceValue converts a float64 slice into an array with same elements as slice.\nfunc Float64SliceValue(v []float64) interface{} {\n\tvar zero float64\n\tcp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem()\n\treflect.Copy(cp, reflect.ValueOf(v))\n\treturn cp.Interface()\n}\n\n// StringSliceValue converts a string slice into an array with same elements as slice.\nfunc StringSliceValue(v []string) interface{} {\n\tvar zero string\n\tcp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem()\n\treflect.Copy(cp, reflect.ValueOf(v))\n\treturn cp.Interface()\n}\n\n// AsBoolSlice converts a bool array into a slice into with same elements as array.\nfunc AsBoolSlice(v interface{}) []bool {\n\trv := reflect.ValueOf(v)\n\tif rv.Type().Kind() != reflect.Array {\n\t\treturn nil\n\t}\n\tcpy := make([]bool, rv.Len())\n\tif len(cpy) > 0 {\n\t\t_ = reflect.Copy(reflect.ValueOf(cpy), rv)\n\t}\n\treturn cpy\n}\n\n// AsInt64Slice converts an int64 array into a slice into with same elements as array.\nfunc AsInt64Slice(v interface{}) []int64 {\n\trv := reflect.ValueOf(v)\n\tif rv.Type().Kind() != reflect.Array {\n\t\treturn nil\n\t}\n\tcpy := make([]int64, rv.Len())\n\tif len(cpy) > 0 {\n\t\t_ = reflect.Copy(reflect.ValueOf(cpy), rv)\n\t}\n\treturn cpy\n}\n\n// AsFloat64Slice converts a float64 array into a slice into with same elements as array.\nfunc AsFloat64Slice(v interface{}) []float64 {\n\trv := reflect.ValueOf(v)\n\tif rv.Type().Kind() != reflect.Array {\n\t\treturn nil\n\t}\n\tcpy := make([]float64, rv.Len())\n\tif len(cpy) > 0 {\n\t\t_ = reflect.Copy(reflect.ValueOf(cpy), rv)\n\t}\n\treturn cpy\n}\n\n// AsStringSlice converts a string array into a slice into with same elements as array.\nfunc AsStringSlice(v interface{}) []string {\n\trv := reflect.ValueOf(v)\n\tif rv.Type().Kind() != reflect.Array {\n\t\treturn nil\n\t}\n\tcpy := make([]string, rv.Len())\n\tif len(cpy) > 0 {\n\t\t_ = reflect.Copy(reflect.ValueOf(cpy), rv)\n\t}\n\treturn cpy\n}\n"}, {"path": "attribute/internal/attribute_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar wrapFloat64SliceValue = func(v interface{}) interface{} {\n\tif vi, ok := v.([]float64); ok {\n\t\treturn Float64SliceValue(vi)\n\t}\n\treturn nil\n}\n\nvar wrapInt64SliceValue = func(v interface{}) interface{} {\n\tif vi, ok := v.([]int64); ok {\n\t\treturn Int64SliceValue(vi)\n\t}\n\treturn nil\n}\n\nvar wrapBoolSliceValue = func(v interface{}) interface{} {\n\tif vi, ok := v.([]bool); ok {\n\t\treturn BoolSliceValue(vi)\n\t}\n\treturn nil\n}\n\nvar wrapStringSliceValue = func(v interface{}) interface{} {\n\tif vi, ok := v.([]string); ok {\n\t\treturn StringSliceValue(vi)\n\t}\n\treturn nil\n}\n\nvar (\n\twrapAsBoolSlice = func(v interface{}) interface{} { return AsBoolSlice(v) }\n\twrapAsInt64Slice = func(v interface{}) interface{} { return AsInt64Slice(v) }\n\twrapAsFloat64Slice = func(v interface{}) interface{} { return AsFloat64Slice(v) }\n\twrapAsStringSlice = func(v interface{}) interface{} { return AsStringSlice(v) }\n)\n\nfunc TestSliceValue(t *testing.T) {\n\ttype args struct {\n\t\tv interface{}\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant interface{}\n\t\tfn func(interface{}) interface{}\n\t}{\n\t\t{\n\t\t\tname: \"Float64SliceValue() two items\",\n\t\t\targs: args{v: []float64{1, 2.3}}, want: [2]float64{1, 2.3}, fn: wrapFloat64SliceValue,\n\t\t},\n\t\t{\n\t\t\tname: \"Int64SliceValue() two items\",\n\t\t\targs: args{[]int64{1, 2}}, want: [2]int64{1, 2}, fn: wrapInt64SliceValue,\n\t\t},\n\t\t{\n\t\t\tname: \"BoolSliceValue() two items\",\n\t\t\targs: args{v: []bool{true, false}}, want: [2]bool{true, false}, fn: wrapBoolSliceValue,\n\t\t},\n\t\t{\n\t\t\tname: \"StringSliceValue() two items\",\n\t\t\targs: args{[]string{\"123\", \"2\"}}, want: [2]string{\"123\", \"2\"}, fn: wrapStringSliceValue,\n\t\t},\n\t\t{\n\t\t\tname: \"AsBoolSlice() two items\",\n\t\t\targs: args{[2]bool{true, false}}, want: []bool{true, false}, fn: wrapAsBoolSlice,\n\t\t},\n\t\t{\n\t\t\tname: \"AsInt64Slice() two items\",\n\t\t\targs: args{[2]int64{1, 3}}, want: []int64{1, 3}, fn: wrapAsInt64Slice,\n\t\t},\n\t\t{\n\t\t\tname: \"AsFloat64Slice() two items\",\n\t\t\targs: args{[2]float64{1.2, 3.1}}, want: []float64{1.2, 3.1}, fn: wrapAsFloat64Slice,\n\t\t},\n\t\t{\n\t\t\tname: \"AsStringSlice() two items\",\n\t\t\targs: args{[2]string{\"1234\", \"12\"}}, want: []string{\"1234\", \"12\"}, fn: wrapAsStringSlice,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := tt.fn(tt.args.v); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"got %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// sync is a global used to ensure the benchmark are not optimized away.\nvar sync any\n\nfunc BenchmarkBoolSliceValue(b *testing.B) {\n\tb.ReportAllocs()\n\ts := []bool{true, false, true, false}\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tsync = BoolSliceValue(s)\n\t}\n}\n\nfunc BenchmarkInt64SliceValue(b *testing.B) {\n\tb.ReportAllocs()\n\ts := []int64{1, 2, 3, 4}\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tsync = Int64SliceValue(s)\n\t}\n}\n\nfunc BenchmarkFloat64SliceValue(b *testing.B) {\n\tb.ReportAllocs()\n\ts := []float64{1.2, 3.4, 5.6, 7.8}\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tsync = Float64SliceValue(s)\n\t}\n}\n\nfunc BenchmarkStringSliceValue(b *testing.B) {\n\tb.ReportAllocs()\n\ts := []string{\"a\", \"b\", \"c\", \"d\"}\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tsync = StringSliceValue(s)\n\t}\n}\n\nfunc BenchmarkAsFloat64Slice(b *testing.B) {\n\tb.ReportAllocs()\n\tvar in interface{} = [2]float64{1, 2.3}\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tsync = AsFloat64Slice(in)\n\t}\n}\n"}, {"path": "attribute/iterator.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute // import \"go.opentelemetry.io/otel/attribute\"\n\n// Iterator allows iterating over the set of attributes in order, sorted by\n// key.\ntype Iterator struct {\n\tstorage *Set\n\tidx int\n}\n\n// MergeIterator supports iterating over two sets of attributes while\n// eliminating duplicate values from the combined set. The first iterator\n// value takes precedence.\ntype MergeIterator struct {\n\tone oneIterator\n\ttwo oneIterator\n\tcurrent KeyValue\n}\n\ntype oneIterator struct {\n\titer Iterator\n\tdone bool\n\tattr KeyValue\n}\n\n// Next moves the iterator to the next position. Returns false if there are no\n// more attributes.\nfunc (i *Iterator) Next() bool {\n\ti.idx++\n\treturn i.idx < i.Len()\n}\n\n// Label returns current KeyValue. Must be called only after Next returns\n// true.\n//\n// Deprecated: Use Attribute instead.\nfunc (i *Iterator) Label() KeyValue {\n\treturn i.Attribute()\n}\n\n// Attribute returns the current KeyValue of the Iterator. It must be called\n// only after Next returns true.\nfunc (i *Iterator) Attribute() KeyValue {\n\tkv, _ := i.storage.Get(i.idx)\n\treturn kv\n}\n\n// IndexedLabel returns current index and attribute. Must be called only\n// after Next returns true.\n//\n// Deprecated: Use IndexedAttribute instead.\nfunc (i *Iterator) IndexedLabel() (int, KeyValue) {\n\treturn i.idx, i.Attribute()\n}\n\n// IndexedAttribute returns current index and attribute. Must be called only\n// after Next returns true.\nfunc (i *Iterator) IndexedAttribute() (int, KeyValue) {\n\treturn i.idx, i.Attribute()\n}\n\n// Len returns a number of attributes in the iterated set.\nfunc (i *Iterator) Len() int {\n\treturn i.storage.Len()\n}\n\n// ToSlice is a convenience function that creates a slice of attributes from\n// the passed iterator. The iterator is set up to start from the beginning\n// before creating the slice.\nfunc (i *Iterator) ToSlice() []KeyValue {\n\tl := i.Len()\n\tif l == 0 {\n\t\treturn nil\n\t}\n\ti.idx = -1\n\tslice := make([]KeyValue, 0, l)\n\tfor i.Next() {\n\t\tslice = append(slice, i.Attribute())\n\t}\n\treturn slice\n}\n\n// NewMergeIterator returns a MergeIterator for merging two attribute sets.\n// Duplicates are resolved by taking the value from the first set.\nfunc NewMergeIterator(s1, s2 *Set) MergeIterator {\n\tmi := MergeIterator{\n\t\tone: makeOne(s1.Iter()),\n\t\ttwo: makeOne(s2.Iter()),\n\t}\n\treturn mi\n}\n\nfunc makeOne(iter Iterator) oneIterator {\n\toi := oneIterator{\n\t\titer: iter,\n\t}\n\toi.advance()\n\treturn oi\n}\n\nfunc (oi *oneIterator) advance() {\n\tif oi.done = !oi.iter.Next(); !oi.done {\n\t\toi.attr = oi.iter.Attribute()\n\t}\n}\n\n// Next returns true if there is another attribute available.\nfunc (m *MergeIterator) Next() bool {\n\tif m.one.done && m.two.done {\n\t\treturn false\n\t}\n\tif m.one.done {\n\t\tm.current = m.two.attr\n\t\tm.two.advance()\n\t\treturn true\n\t}\n\tif m.two.done {\n\t\tm.current = m.one.attr\n\t\tm.one.advance()\n\t\treturn true\n\t}\n\tif m.one.attr.Key == m.two.attr.Key {\n\t\tm.current = m.one.attr // first iterator attribute value wins\n\t\tm.one.advance()\n\t\tm.two.advance()\n\t\treturn true\n\t}\n\tif m.one.attr.Key < m.two.attr.Key {\n\t\tm.current = m.one.attr\n\t\tm.one.advance()\n\t\treturn true\n\t}\n\tm.current = m.two.attr\n\tm.two.advance()\n\treturn true\n}\n\n// Label returns the current value after Next() returns true.\n//\n// Deprecated: Use Attribute instead.\nfunc (m *MergeIterator) Label() KeyValue {\n\treturn m.current\n}\n\n// Attribute returns the current value after Next() returns true.\nfunc (m *MergeIterator) Attribute() KeyValue {\n\treturn m.current\n}\n"}, {"path": "attribute/kv.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute // import \"go.opentelemetry.io/otel/attribute\"\n\nimport (\n\t\"fmt\"\n)\n\n// KeyValue holds a key and value pair.\ntype KeyValue struct {\n\tKey Key\n\tValue Value\n}\n\n// Valid returns if kv is a valid OpenTelemetry attribute.\nfunc (kv KeyValue) Valid() bool {\n\treturn kv.Key.Defined() && kv.Value.Type() != INVALID\n}\n\n// Bool creates a KeyValue with a BOOL Value type.\nfunc Bool(k string, v bool) KeyValue {\n\treturn Key(k).Bool(v)\n}\n\n// BoolSlice creates a KeyValue with a BOOLSLICE Value type.\nfunc BoolSlice(k string, v []bool) KeyValue {\n\treturn Key(k).BoolSlice(v)\n}\n\n// Int creates a KeyValue with an INT64 Value type.\nfunc Int(k string, v int) KeyValue {\n\treturn Key(k).Int(v)\n}\n\n// IntSlice creates a KeyValue with an INT64SLICE Value type.\nfunc IntSlice(k string, v []int) KeyValue {\n\treturn Key(k).IntSlice(v)\n}\n\n// Int64 creates a KeyValue with an INT64 Value type.\nfunc Int64(k string, v int64) KeyValue {\n\treturn Key(k).Int64(v)\n}\n\n// Int64Slice creates a KeyValue with an INT64SLICE Value type.\nfunc Int64Slice(k string, v []int64) KeyValue {\n\treturn Key(k).Int64Slice(v)\n}\n\n// Float64 creates a KeyValue with a FLOAT64 Value type.\nfunc Float64(k string, v float64) KeyValue {\n\treturn Key(k).Float64(v)\n}\n\n// Float64Slice creates a KeyValue with a FLOAT64SLICE Value type.\nfunc Float64Slice(k string, v []float64) KeyValue {\n\treturn Key(k).Float64Slice(v)\n}\n\n// String creates a KeyValue with a STRING Value type.\nfunc String(k, v string) KeyValue {\n\treturn Key(k).String(v)\n}\n\n// StringSlice creates a KeyValue with a STRINGSLICE Value type.\nfunc StringSlice(k string, v []string) KeyValue {\n\treturn Key(k).StringSlice(v)\n}\n\n// Stringer creates a new key-value pair with a passed name and a string\n// value generated by the passed Stringer interface.\nfunc Stringer(k string, v fmt.Stringer) KeyValue {\n\treturn Key(k).String(v.String())\n}\n"}], "context_lines": 1495, "buggy_files": ["CHANGELOG.md", "internal/tools/semconvkit/templates/error_type.go.tmpl", "semconv/v1.34.0/error_type.go"], "test_files": [{"path": "internal/tools/semconvkit/templates/error_type_test.go.tmpl", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage semconv // import \"go.opentelemetry.io/otel/semconv/{{.TagVer}}\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n)\n\ntype CustomError struct{}\n\nfunc (CustomError) Error() string {\n\treturn \"custom error\"\n}\n\nfunc TestErrorType(t *testing.T) {\n\tcustomErr := CustomError{}\n\tbuiltinErr := errors.New(\"something went wrong\")\n\tvar nilErr error\n\n\twantCustomType := reflect.TypeOf(customErr)\n\twantCustomStr := fmt.Sprintf(\"%s.%s\", wantCustomType.PkgPath(), wantCustomType.Name())\n\n\ttests := []struct {\n\t\tname string\n\t\terr error\n\t\twant attribute.KeyValue\n\t}{\n\t\t{\n\t\t\tname: \"BuiltinError\",\n\t\t\terr: builtinErr,\n\t\t\twant: attribute.String(\"error.type\", \"*errors.errorString\"),\n\t\t},\n\t\t{\n\t\t\tname: \"CustomError\",\n\t\t\terr: customErr,\n\t\t\twant: attribute.String(\"error.type\", wantCustomStr),\n\t\t},\n\t\t{\n\t\t\tname: \"NilError\",\n\t\t\terr: nilErr,\n\t\t\twant: ErrorTypeOther,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := ErrorType(tt.err)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"ErrorType(%v) = %v, want %v\", tt.err, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"}, {"path": "semconv/v1.34.0/error_type_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage semconv // import \"go.opentelemetry.io/otel/semconv/v1.34.0\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n)\n\ntype CustomError struct{}\n\nfunc (CustomError) Error() string {\n\treturn \"custom error\"\n}\n\nfunc TestErrorType(t *testing.T) {\n\tcustomErr := CustomError{}\n\tbuiltinErr := errors.New(\"something went wrong\")\n\tvar nilErr error\n\n\twantCustomType := reflect.TypeOf(customErr)\n\twantCustomStr := fmt.Sprintf(\"%s.%s\", wantCustomType.PkgPath(), wantCustomType.Name())\n\n\ttests := []struct {\n\t\tname string\n\t\terr error\n\t\twant attribute.KeyValue\n\t}{\n\t\t{\n\t\t\tname: \"BuiltinError\",\n\t\t\terr: builtinErr,\n\t\t\twant: attribute.String(\"error.type\", \"*errors.errorString\"),\n\t\t},\n\t\t{\n\t\t\tname: \"CustomError\",\n\t\t\terr: customErr,\n\t\t\twant: attribute.String(\"error.type\", wantCustomStr),\n\t\t},\n\t\t{\n\t\t\tname: \"NilError\",\n\t\t\terr: nilErr,\n\t\t\twant: ErrorTypeOther,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := ErrorType(tt.err)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"ErrorType(%v) = %v, want %v\", tt.err, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"}], "eval": {"test_cmds": ["go test -json -v ./... > reports/go-test-results.json"], "print_cmds": [], "log_parser": "def parser(log: str) -> dict[str, str]:\n # Improved parser for Go test -json output and textual fallbacks.\n import json\n import re\n\n results: dict[str, str] = {}\n\n # Precedence: fail > skip > pass\n precedence = {\"pass\": 0, \"skip\": 1, \"fail\": 2}\n\n def update_status(key: str, status: str):\n cur = results.get(key)\n if cur is None or precedence[status] > precedence[cur]:\n results[key] = status\n\n # Matches lines like:\n # --- PASS: TestName (0.00s)\n # --- SKIP: TestName/Subtest with spaces (reason)\n status_line_re = re.compile(r\"---\\s+(PASS|FAIL|SKIP):\\s+(.+?)(?:\\s+\\(|$)\")\n\n current_pkg: str | None = None\n\n for raw_line in log.splitlines():\n s = raw_line.strip()\n if not s:\n continue\n\n obj = None\n if s.startswith(\"{\") and s.endswith(\"}\"):\n try:\n obj = json.loads(s)\n except Exception:\n obj = None\n\n if isinstance(obj, dict):\n pkg = obj.get(\"Package\") or current_pkg\n if pkg:\n current_pkg = pkg\n\n action = obj.get(\"Action\")\n testname = obj.get(\"Test\")\n output_text = obj.get(\"Output\")\n\n # Prefer structured JSON status events.\n if action in (\"pass\", \"fail\", \"skip\") and testname:\n key = f\"{pkg}::{testname}\" if pkg else testname\n status = \"pass\" if action == \"pass\" else \"fail\" if action == \"fail\" else \"skip\"\n update_status(key, status)\n\n # Parse embedded textual status lines in JSON output events.\n if isinstance(output_text, str):\n m = status_line_re.search(output_text)\n if m:\n status_word, name = m.groups()\n status = (\n \"pass\" if status_word.upper() == \"PASS\"\n else \"fail\" if status_word.upper() == \"FAIL\"\n else \"skip\"\n )\n key = f\"{pkg}::{name}\" if pkg else name\n update_status(key, status)\n\n continue\n\n # Fallback: parse plain textual lines (if any appear outside JSON).\n m = status_line_re.search(s)\n if m:\n status_word, name = m.groups()\n status = (\n \"pass\" if status_word.upper() == \"PASS\"\n else \"fail\" if status_word.upper() == \"FAIL\"\n else \"skip\"\n )\n key = f\"{current_pkg}::{name}\" if current_pkg else name\n update_status(key, status)\n\n return results", "rebuild_cmds": []}} {"id": "patchbench-go-real-0057", "repo": "rook/rook", "base_commit": "540b0c8637e93f80e1a91d7ce94a87ba384179ba", "status": "p2p_regression", "verify_status": null, "error": null, "timing": {"setup": 3.5, "pre_test_0": 556.4, "pre_test_1": 286.6, "post_test_0": 373.6, "post_test_1": 286.6, "total": 1506.8}, "test_cmds": ["cd /tmp/cache/repos/rook__rook && go test ./... -v 2>&1 | tee test-output.log"], "rebuild_cmds": [], "print_cmds": [], "f2p_pre_ok": true, "pre_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 2271}, "f2p_post_ok": true, "p2p_post_ok": false, "post_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 2405}, "raw_tail": "hr/testify/suite.Run.func2()\n \t/go/pkg/mod/github.com/stretchr/testify@v1.10.0/suite/suite.go:210 +0x70\n github.com/stretchr/testify/suite.Run(0xc0004e8540, {0x47681d8, 0xc000631c00})\n \t/go/pkg/mod/github.com/stretchr/testify@v1.10.0/suite/suite.go:221 +0x490\n github.com/rook/rook/tests/integration.TestCephUpgradeSuite(0xc0004e8540)\n \t/tmp/cache/repos/rook__rook/tests/integration/ceph_upgrade_test.go:59 +0x6f\n testing.tRunner(0xc0004e8540, 0x4219058)\n \t/usr/local/go/src/testing/testing.go:1934 +0xea\n created by testing.(*T).Run in goroutine 1\n \t/usr/local/go/src/testing/testing.go:1997 +0x465\n--- FAIL: TestCephUpgradeSuite (120.05s)\n --- FAIL: TestCephUpgradeSuite/TestUpgradeCephToReefDevel (30.02s)\n --- FAIL: TestCephUpgradeSuite/TestUpgradeCephToSquidDevel (30.03s)\n --- FAIL: TestCephUpgradeSuite/TestUpgradeHelm (30.00s)\n --- FAIL: TestCephUpgradeSuite/TestUpgradeRook (30.00s)\nFAIL\nFAIL\tgithub.com/rook/rook/tests/integration\t270.114s\n? \tgithub.com/rook/rook/tests/integration/object/bucketowner\t[no test files]\n? \tgithub.com/rook/rook/tests/integration/object/topic/kafka\t[no test files]\n? \tgithub.com/rook/rook/tests/integration/object/user/userkeys\t[no test files]\n? \tgithub.com/rook/rook/tests/integration/object/util/admin\t[no test files]\n? \tgithub.com/rook/rook/tests/integration/object/util/s3\t[no test files]\n? \tgithub.com/rook/rook/tests/integration/object/util/sns\t[no test files]\nFAIL\n\n\n"} {"id": "patchbench-go-real-0035", "repo": "open-telemetry/opentelemetry-go", "base_commit": "c5e68b201067cb4e6b98a3e619927abc4a235e3e", "status": "verified", "verify_status": "verified", "error": null, "timing": {"setup": 0.6, "pre_test_0": 134.9, "pre_test_1": 7.2, "post_test_0": 57.0, "post_test_1": 8.4, "total": 208.3}, "test_cmds": ["make test-verbose 2>&1 | tee test-output.log"], "rebuild_cmds": [], "print_cmds": [], "f2p_pre_ok": true, "pre_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 1828}, "f2p_post_ok": true, "p2p_post_ok": true, "post_detail": {"missing": 0, "wrong": [], "missing_ids": [], "parsed_count": 3353}, "raw_tail": "entelemetry.io/otel/sdk/resource\t1.036s\nFAIL\tgo.opentelemetry.io/otel/sdk/trace [build failed]\n=== RUN TestSelfObservability\n=== RUN TestSelfObservability/100\n=== RUN TestSelfObservability/true\n=== RUN TestSelfObservability/True\n=== RUN TestSelfObservability/false\n=== RUN TestSelfObservability/empty\n--- PASS: TestSelfObservability (0.00s)\n --- PASS: TestSelfObservability/100 (0.00s)\n --- PASS: TestSelfObservability/true (0.00s)\n --- PASS: TestSelfObservability/True (0.00s)\n --- PASS: TestSelfObservability/false (0.00s)\n --- PASS: TestSelfObservability/empty (0.00s)\nPASS\nok \tgo.opentelemetry.io/otel/sdk/trace/internal/x\t1.012s\n=== RUN TestNoop\n--- PASS: TestNoop (0.00s)\n=== RUN TestNewInMemoryExporter\n--- PASS: TestNewInMemoryExporter (0.00s)\n=== RUN TestSpanRecorderOnStartAppends\n--- PASS: TestSpanRecorderOnStartAppends (0.00s)\n=== RUN TestSpanRecorderOnEndAppends\n--- PASS: TestSpanRecorderOnEndAppends (0.00s)\n=== RUN TestSpanRecorderShutdownNoError\n--- PASS: TestSpanRecorderShutdownNoError (0.00s)\n=== RUN TestSpanRecorderForceFlushNoError\n--- PASS: TestSpanRecorderForceFlushNoError (0.00s)\n=== RUN TestEndingConcurrentSafe\n--- PASS: TestEndingConcurrentSafe (0.00s)\n=== RUN TestStartingConcurrentSafe\n--- PASS: TestStartingConcurrentSafe (0.00s)\n=== RUN TestResetConcurrentSafe\n--- PASS: TestResetConcurrentSafe (0.00s)\nPASS\nok \tgo.opentelemetry.io/otel/sdk/trace/tracetest\t1.013s\nFAIL\nmake: *** [Makefile:161: test/./sdk] Error 123\n\n\n", "context_files": [{"path": "sdk/trace/batch_span_processor.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage trace // import \"go.opentelemetry.io/otel/sdk/trace\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/internal/global\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/sdk\"\n\t\"go.opentelemetry.io/otel/sdk/internal/env\"\n\t\"go.opentelemetry.io/otel/sdk/trace/internal/x\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.36.0\"\n\t\"go.opentelemetry.io/otel/semconv/v1.36.0/otelconv\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\n// Defaults for BatchSpanProcessorOptions.\nconst (\n\tDefaultMaxQueueSize = 2048\n\t// DefaultScheduleDelay is the delay interval between two consecutive exports, in milliseconds.\n\tDefaultScheduleDelay = 5000\n\t// DefaultExportTimeout is the duration after which an export is cancelled, in milliseconds.\n\tDefaultExportTimeout = 30000\n\tDefaultMaxExportBatchSize = 512\n)\n\nvar queueFull = otelconv.ErrorTypeAttr(\"queue_full\")\n\n// BatchSpanProcessorOption configures a BatchSpanProcessor.\ntype BatchSpanProcessorOption func(o *BatchSpanProcessorOptions)\n\n// BatchSpanProcessorOptions is configuration settings for a\n// BatchSpanProcessor.\ntype BatchSpanProcessorOptions struct {\n\t// MaxQueueSize is the maximum queue size to buffer spans for delayed processing. If the\n\t// queue gets full it drops the spans. Use BlockOnQueueFull to change this behavior.\n\t// The default value of MaxQueueSize is 2048.\n\tMaxQueueSize int\n\n\t// BatchTimeout is the maximum duration for constructing a batch. Processor\n\t// forcefully sends available spans when timeout is reached.\n\t// The default value of BatchTimeout is 5000 msec.\n\tBatchTimeout time.Duration\n\n\t// ExportTimeout specifies the maximum duration for exporting spans. If the timeout\n\t// is reached, the export will be cancelled.\n\t// The default value of ExportTimeout is 30000 msec.\n\tExportTimeout time.Duration\n\n\t// MaxExportBatchSize is the maximum number of spans to process in a single batch.\n\t// If there are more than one batch worth of spans then it processes multiple batches\n\t// of spans one batch after the other without any delay.\n\t// The default value of MaxExportBatchSize is 512.\n\tMaxExportBatchSize int\n\n\t// BlockOnQueueFull blocks onEnd() and onStart() method if the queue is full\n\t// AND if BlockOnQueueFull is set to true.\n\t// Blocking option should be used carefully as it can severely affect the performance of an\n\t// application.\n\tBlockOnQueueFull bool\n}\n\n// batchSpanProcessor is a SpanProcessor that batches asynchronously-received\n// spans and sends them to a trace.Exporter when complete.\ntype batchSpanProcessor struct {\n\te SpanExporter\n\to BatchSpanProcessorOptions\n\n\tqueue chan ReadOnlySpan\n\tdropped uint32\n\n\tselfObservabilityEnabled bool\n\tcallbackRegistration metric.Registration\n\tspansProcessedCounter otelconv.SDKProcessorSpanProcessed\n\tcomponentNameAttr attribute.KeyValue\n\n\tbatch []ReadOnlySpan\n\tbatchMutex sync.Mutex\n\ttimer *time.Timer\n\tstopWait sync.WaitGroup\n\tstopOnce sync.Once\n\tstopCh chan struct{}\n\tstopped atomic.Bool\n}\n\nvar _ SpanProcessor = (*batchSpanProcessor)(nil)\n\n// NewBatchSpanProcessor creates a new SpanProcessor that will send completed\n// span batches to the exporter with the supplied options.\n//\n// If the exporter is nil, the span processor will perform no action.\nfunc NewBatchSpanProcessor(exporter SpanExporter, options ...BatchSpanProcessorOption) SpanProcessor {\n\tmaxQueueSize := env.BatchSpanProcessorMaxQueueSize(DefaultMaxQueueSize)\n\tmaxExportBatchSize := env.BatchSpanProcessorMaxExportBatchSize(DefaultMaxExportBatchSize)\n\n\tif maxExportBatchSize > maxQueueSize {\n\t\tmaxExportBatchSize = min(DefaultMaxExportBatchSize, maxQueueSize)\n\t}\n\n\to := BatchSpanProcessorOptions{\n\t\tBatchTimeout: time.Duration(env.BatchSpanProcessorScheduleDelay(DefaultScheduleDelay)) * time.Millisecond,\n\t\tExportTimeout: time.Duration(env.BatchSpanProcessorExportTimeout(DefaultExportTimeout)) * time.Millisecond,\n\t\tMaxQueueSize: maxQueueSize,\n\t\tMaxExportBatchSize: maxExportBatchSize,\n\t}\n\tfor _, opt := range options {\n\t\topt(&o)\n\t}\n\tbsp := &batchSpanProcessor{\n\t\te: exporter,\n\t\to: o,\n\t\tbatch: make([]ReadOnlySpan, 0, o.MaxExportBatchSize),\n\t\ttimer: time.NewTimer(o.BatchTimeout),\n\t\tqueue: make(chan ReadOnlySpan, o.MaxQueueSize),\n\t\tstopCh: make(chan struct{}),\n\t}\n\n\tbsp.configureSelfObservability()\n\n\tbsp.stopWait.Add(1)\n\tgo func() {\n\t\tdefer bsp.stopWait.Done()\n\t\tbsp.processQueue()\n\t\tbsp.drainQueue()\n\t}()\n\n\treturn bsp\n}\n\nvar processorIDCounter atomic.Int64\n\n// nextProcessorID returns an identifier for this batch span processor,\n// starting with 0 and incrementing by 1 each time it is called.\nfunc nextProcessorID() int64 {\n\treturn processorIDCounter.Add(1) - 1\n}\n\n// configureSelfObservability configures metrics for the batch span processor.\nfunc (bsp *batchSpanProcessor) configureSelfObservability() {\n\tif !x.SelfObservability.Enabled() {\n\t\treturn\n\t}\n\tbsp.selfObservabilityEnabled = true\n\tbsp.componentNameAttr = semconv.OTelComponentName(\n\t\tfmt.Sprintf(\"%s/%d\", otelconv.ComponentTypeBatchingSpanProcessor, nextProcessorID()))\n\tmeter := otel.GetMeterProvider().Meter(\n\t\tselfObsScopeName,\n\t\tmetric.WithInstrumentationVersion(sdk.Version()),\n\t\tmetric.WithSchemaURL(semconv.SchemaURL),\n\t)\n\n\tqueueCapacityUpDownCounter, err := otelconv.NewSDKProcessorSpanQueueCapacity(meter)\n\tif err != nil {\n\t\totel.Handle(err)\n\t}\n\tqueueSizeUpDownCounter, err := otelconv.NewSDKProcessorSpanQueueSize(meter)\n\tif err != nil {\n\t\totel.Handle(err)\n\t}\n\tbsp.spansProcessedCounter, err = otelconv.NewSDKProcessorSpanProcessed(meter)\n\tif err != nil {\n\t\totel.Handle(err)\n\t}\n\n\tcallabckAttributesOpt := metric.WithAttributes(bsp.componentNameAttr,\n\t\tsemconv.OTelComponentTypeBatchingSpanProcessor)\n\tbsp.callbackRegistration, err = meter.RegisterCallback(\n\t\tfunc(_ context.Context, o metric.Observer) error {\n\t\t\to.ObserveInt64(queueSizeUpDownCounter.Inst(), int64(len(bsp.queue)), callabckAttributesOpt)\n\t\t\to.ObserveInt64(queueCapacityUpDownCounter.Inst(), int64(bsp.o.MaxQueueSize), callabckAttributesOpt)\n\t\t\treturn nil\n\t\t},\n\t\tqueueSizeUpDownCounter.Inst(), queueCapacityUpDownCounter.Inst())\n\tif err != nil {\n\t\totel.Handle(err)\n\t}\n}\n\n// OnStart method does nothing.\nfunc (*batchSpanProcessor) OnStart(context.Context, ReadWriteSpan) {}\n\n// OnEnd method enqueues a ReadOnlySpan for later processing.\nfunc (bsp *batchSpanProcessor) OnEnd(s ReadOnlySpan) {\n\t// Do not enqueue spans after Shutdown.\n\tif bsp.stopped.Load() {\n\t\treturn\n\t}\n\n\t// Do not enqueue spans if we are just going to drop them.\n\tif bsp.e == nil {\n\t\treturn\n\t}\n\tbsp.enqueue(s)\n}\n\n// Shutdown flushes the queue and waits until all spans are processed.\n// It only executes once. Subsequent call does nothing.\nfunc (bsp *batchSpanProcessor) Shutdown(ctx context.Context) error {\n\tvar err error\n\tbsp.stopOnce.Do(func() {\n\t\tbsp.stopped.Store(true)\n\t\twait := make(chan struct{})\n\t\tgo func() {\n\t\t\tclose(bsp.stopCh)\n\t\t\tbsp.stopWait.Wait()\n\t\t\tif bsp.e != nil {\n\t\t\t\tif err := bsp.e.Shutdown(ctx); err != nil {\n\t\t\t\t\totel.Handle(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(wait)\n\t\t}()\n\t\t// Wait until the wait group is done or the context is cancelled\n\t\tselect {\n\t\tcase <-wait:\n\t\tcase <-ctx.Done():\n\t\t\terr = ctx.Err()\n\t\t}\n\t\tif bsp.selfObservabilityEnabled {\n\t\t\terr = errors.Join(err, bsp.callbackRegistration.Unregister())\n\t\t}\n\t})\n\treturn err\n}\n\ntype forceFlushSpan struct {\n\tReadOnlySpan\n\tflushed chan struct{}\n}\n\nfunc (forceFlushSpan) SpanContext() trace.SpanContext {\n\treturn trace.NewSpanContext(trace.SpanContextConfig{TraceFlags: trace.FlagsSampled})\n}\n\n// ForceFlush exports all ended spans that have not yet been exported.\nfunc (bsp *batchSpanProcessor) ForceFlush(ctx context.Context) error {\n\t// Interrupt if context is already canceled.\n\tif err := ctx.Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// Do nothing after Shutdown.\n\tif bsp.stopped.Load() {\n\t\treturn nil\n\t}\n\n\tvar err error\n\tif bsp.e != nil {\n\t\tflushCh := make(chan struct{})\n\t\tif bsp.enqueueBlockOnQueueFull(ctx, forceFlushSpan{flushed: flushCh}) {\n\t\t\tselect {\n\t\t\tcase <-bsp.stopCh:\n\t\t\t\t// The batchSpanProcessor is Shutdown.\n\t\t\t\treturn nil\n\t\t\tcase <-flushCh:\n\t\t\t\t// Processed any items in queue prior to ForceFlush being called\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t}\n\n\t\twait := make(chan error, 1)\n\t\tgo func() {\n\t\t\twait <- bsp.exportSpans(ctx)\n\t\t}()\n\t\t// Wait until the export is finished or the context is cancelled/timed out\n\t\tselect {\n\t\tcase err = <-wait:\n\t\tcase <-ctx.Done():\n\t\t\terr = ctx.Err()\n\t\t}\n\t}\n\treturn err\n}\n\n// WithMaxQueueSize returns a BatchSpanProcessorOption that configures the\n// maximum queue size allowed for a BatchSpanProcessor.\nfunc WithMaxQueueSize(size int) BatchSpanProcessorOption {\n\treturn func(o *BatchSpanProcessorOptions) {\n\t\to.MaxQueueSize = size\n\t}\n}\n\n// WithMaxExportBatchSize returns a BatchSpanProcessorOption that configures\n// the maximum export batch size allowed for a BatchSpanProcessor.\nfunc WithMaxExportBatchSize(size int) BatchSpanProcessorOption {\n\treturn func(o *BatchSpanProcessorOptions) {\n\t\to.MaxExportBatchSize = size\n\t}\n}\n\n// WithBatchTimeout returns a BatchSpanProcessorOption that configures the\n// maximum delay allowed for a BatchSpanProcessor before it will export any\n// held span (whether the queue is full or not).\nfunc WithBatchTimeout(delay time.Duration) BatchSpanProcessorOption {\n\treturn func(o *BatchSpanProcessorOptions) {\n\t\to.BatchTimeout = delay\n\t}\n}\n\n// WithExportTimeout returns a BatchSpanProcessorOption that configures the\n// amount of time a BatchSpanProcessor waits for an exporter to export before\n// abandoning the export.\nfunc WithExportTimeout(timeout time.Duration) BatchSpanProcessorOption {\n\treturn func(o *BatchSpanProcessorOptions) {\n\t\to.ExportTimeout = timeout\n\t}\n}\n\n// WithBlocking returns a BatchSpanProcessorOption that configures a\n// BatchSpanProcessor to wait for enqueue operations to succeed instead of\n// dropping data when the queue is full.\nfunc WithBlocking() BatchSpanProcessorOption {\n\treturn func(o *BatchSpanProcessorOptions) {\n\t\to.BlockOnQueueFull = true\n\t}\n}\n\n// exportSpans is a subroutine of processing and draining the queue.\nfunc (bsp *batchSpanProcessor) exportSpans(ctx context.Context) error {\n\tbsp.timer.Reset(bsp.o.BatchTimeout)\n\n\tbsp.batchMutex.Lock()\n\tdefer bsp.batchMutex.Unlock()\n\n\tif bsp.o.ExportTimeout > 0 {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeoutCause(ctx, bsp.o.ExportTimeout, errors.New(\"processor export timeout\"))\n\t\tdefer cancel()\n\t}\n\n\tif l := len(bsp.batch); l > 0 {\n\t\tglobal.Debug(\"exporting spans\", \"count\", len(bsp.batch), \"total_dropped\", atomic.LoadUint32(&bsp.dropped))\n\t\tif bsp.selfObservabilityEnabled {\n\t\t\tbsp.spansProcessedCounter.Add(ctx, int64(l),\n\t\t\t\tbsp.componentNameAttr,\n\t\t\t\tbsp.spansProcessedCounter.AttrComponentType(otelconv.ComponentTypeBatchingSpanProcessor))\n\t\t}\n\t\terr := bsp.e.ExportSpans(ctx, bsp.batch)\n\n\t\t// A new batch is always created after exporting, even if the batch failed to be exported.\n\t\t//\n\t\t// It is up to the exporter to implement any type of retry logic if a batch is failing\n\t\t// to be exported, since it is specific to the protocol and backend being sent to.\n\t\tclear(bsp.batch) // Erase elements to let GC collect objects\n\t\tbsp.batch = bsp.batch[:0]\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// processQueue removes spans from the `queue` channel until processor\n// is shut down. It calls the exporter in batches of up to MaxExportBatchSize\n// waiting up to BatchTimeout to form a batch.\nfunc (bsp *batchSpanProcessor) processQueue() {\n\tdefer bsp.timer.Stop()\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tfor {\n\t\tselect {\n\t\tcase <-bsp.stopCh:\n\t\t\treturn\n\t\tcase <-bsp.timer.C:\n\t\t\tif err := bsp.exportSpans(ctx); err != nil {\n\t\t\t\totel.Handle(err)\n\t\t\t}\n\t\tcase sd := <-bsp.queue:\n\t\t\tif ffs, ok := sd.(forceFlushSpan); ok {\n\t\t\t\tclose(ffs.flushed)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbsp.batchMutex.Lock()\n\t\t\tbsp.batch = append(bsp.batch, sd)\n\t\t\tshouldExport := len(bsp.batch) >= bsp.o.MaxExportBatchSize\n\t\t\tbsp.batchMutex.Unlock()\n\t\t\tif shouldExport {\n\t\t\t\tif !bsp.timer.Stop() {\n\t\t\t\t\t// Handle both GODEBUG=asynctimerchan=[0|1] properly.\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-bsp.timer.C:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err := bsp.exportSpans(ctx); err != nil {\n\t\t\t\t\totel.Handle(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// drainQueue awaits the any caller that had added to bsp.stopWait\n// to finish the enqueue, then exports the final batch.\nfunc (bsp *batchSpanProcessor) drainQueue() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tfor {\n\t\tselect {\n\t\tcase sd := <-bsp.queue:\n\t\t\tif _, ok := sd.(forceFlushSpan); ok {\n\t\t\t\t// Ignore flush requests as they are not valid spans.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbsp.batchMutex.Lock()\n\t\t\tbsp.batch = append(bsp.batch, sd)\n\t\t\tshouldExport := len(bsp.batch) == bsp.o.MaxExportBatchSize\n\t\t\tbsp.batchMutex.Unlock()\n\n\t\t\tif shouldExport {\n\t\t\t\tif err := bsp.exportSpans(ctx); err != nil {\n\t\t\t\t\totel.Handle(err)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// There are no more enqueued spans. Make final export.\n\t\t\tif err := bsp.exportSpans(ctx); err != nil {\n\t\t\t\totel.Handle(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (bsp *batchSpanProcessor) enqueue(sd ReadOnlySpan) {\n\tctx := context.TODO()\n\tif bsp.o.BlockOnQueueFull {\n\t\tbsp.enqueueBlockOnQueueFull(ctx, sd)\n\t} else {\n\t\tbsp.enqueueDrop(ctx, sd)\n\t}\n}\n\nfunc (bsp *batchSpanProcessor) enqueueBlockOnQueueFull(ctx context.Context, sd ReadOnlySpan) bool {\n\tif !sd.SpanContext().IsSampled() {\n\t\treturn false\n\t}\n\n\tselect {\n\tcase bsp.queue <- sd:\n\t\treturn true\n\tcase <-ctx.Done():\n\t\tif bsp.selfObservabilityEnabled {\n\t\t\tbsp.spansProcessedCounter.Add(ctx, 1,\n\t\t\t\tbsp.componentNameAttr,\n\t\t\t\tbsp.spansProcessedCounter.AttrComponentType(otelconv.ComponentTypeBatchingSpanProcessor),\n\t\t\t\tbsp.spansProcessedCounter.AttrErrorType(queueFull))\n\t\t}\n\t\treturn false\n\t}\n}\n\nfunc (bsp *batchSpanProcessor) enqueueDrop(ctx context.Context, sd ReadOnlySpan) bool {\n\tif !sd.SpanContext().IsSampled() {\n\t\treturn false\n\t}\n\n\tselect {\n\tcase bsp.queue <- sd:\n\t\treturn true\n\tdefault:\n\t\tatomic.AddUint32(&bsp.dropped, 1)\n\t\tif bsp.selfObservabilityEnabled {\n\t\t\tbsp.spansProcessedCounter.Add(ctx, 1,\n\t\t\t\tbsp.componentNameAttr,\n\t\t\t\tbsp.spansProcessedCounter.AttrComponentType(otelconv.ComponentTypeBatchingSpanProcessor),\n\t\t\t\tbsp.spansProcessedCounter.AttrErrorType(queueFull))\n\t\t}\n\t}\n\treturn false\n}\n\n// MarshalLog is the marshaling function used by the logging system to represent this Span Processor.\nfunc (bsp *batchSpanProcessor) MarshalLog() any {\n\treturn struct {\n\t\tType string\n\t\tSpanExporter SpanExporter\n\t\tConfig BatchSpanProcessorOptions\n\t}{\n\t\tType: \"BatchSpanProcessor\",\n\t\tSpanExporter: bsp.e,\n\t\tConfig: bsp.o,\n\t}\n}\n"}, {"path": "sdk/trace/provider.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage trace // import \"go.opentelemetry.io/otel/sdk/trace\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/internal/global\"\n\t\"go.opentelemetry.io/otel/sdk/instrumentation\"\n\t\"go.opentelemetry.io/otel/sdk/resource\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.opentelemetry.io/otel/trace/embedded\"\n\t\"go.opentelemetry.io/otel/trace/noop\"\n)\n\nconst (\n\tdefaultTracerName = \"go.opentelemetry.io/otel/sdk/tracer\"\n\tselfObsScopeName = \"go.opentelemetry.io/otel/sdk/trace\"\n)\n\n// tracerProviderConfig.\ntype tracerProviderConfig struct {\n\t// processors contains collection of SpanProcessors that are processing pipeline\n\t// for spans in the trace signal.\n\t// SpanProcessors registered with a TracerProvider and are called at the start\n\t// and end of a Span's lifecycle, and are called in the order they are\n\t// registered.\n\tprocessors []SpanProcessor\n\n\t// sampler is the default sampler used when creating new spans.\n\tsampler Sampler\n\n\t// idGenerator is used to generate all Span and Trace IDs when needed.\n\tidGenerator IDGenerator\n\n\t// spanLimits defines the attribute, event, and link limits for spans.\n\tspanLimits SpanLimits\n\n\t// resource contains attributes representing an entity that produces telemetry.\n\tresource *resource.Resource\n}\n\n// MarshalLog is the marshaling function used by the logging system to represent this Provider.\nfunc (cfg tracerProviderConfig) MarshalLog() any {\n\treturn struct {\n\t\tSpanProcessors []SpanProcessor\n\t\tSamplerType string\n\t\tIDGeneratorType string\n\t\tSpanLimits SpanLimits\n\t\tResource *resource.Resource\n\t}{\n\t\tSpanProcessors: cfg.processors,\n\t\tSamplerType: fmt.Sprintf(\"%T\", cfg.sampler),\n\t\tIDGeneratorType: fmt.Sprintf(\"%T\", cfg.idGenerator),\n\t\tSpanLimits: cfg.spanLimits,\n\t\tResource: cfg.resource,\n\t}\n}\n\n// TracerProvider is an OpenTelemetry TracerProvider. It provides Tracers to\n// instrumentation so it can trace operational flow through a system.\ntype TracerProvider struct {\n\tembedded.TracerProvider\n\n\tmu sync.Mutex\n\tnamedTracer map[instrumentation.Scope]*tracer\n\tspanProcessors atomic.Pointer[spanProcessorStates]\n\n\tisShutdown atomic.Bool\n\n\t// These fields are not protected by the lock mu. They are assumed to be\n\t// immutable after creation of the TracerProvider.\n\tsampler Sampler\n\tidGenerator IDGenerator\n\tspanLimits SpanLimits\n\tresource *resource.Resource\n}\n\nvar _ trace.TracerProvider = &TracerProvider{}\n\n// NewTracerProvider returns a new and configured TracerProvider.\n//\n// By default the returned TracerProvider is configured with:\n// - a ParentBased(AlwaysSample) Sampler\n// - a random number IDGenerator\n// - the resource.Default() Resource\n// - the default SpanLimits.\n//\n// The passed opts are used to override these default values and configure the\n// returned TracerProvider appropriately.\nfunc NewTracerProvider(opts ...TracerProviderOption) *TracerProvider {\n\to := tracerProviderConfig{\n\t\tspanLimits: NewSpanLimits(),\n\t}\n\to = applyTracerProviderEnvConfigs(o)\n\n\tfor _, opt := range opts {\n\t\to = opt.apply(o)\n\t}\n\n\to = ensureValidTracerProviderConfig(o)\n\n\ttp := &TracerProvider{\n\t\tnamedTracer: make(map[instrumentation.Scope]*tracer),\n\t\tsampler: o.sampler,\n\t\tidGenerator: o.idGenerator,\n\t\tspanLimits: o.spanLimits,\n\t\tresource: o.resource,\n\t}\n\tglobal.Info(\"TracerProvider created\", \"config\", o)\n\n\tspss := make(spanProcessorStates, 0, len(o.processors))\n\tfor _, sp := range o.processors {\n\t\tspss = append(spss, newSpanProcessorState(sp))\n\t}\n\ttp.spanProcessors.Store(&spss)\n\n\treturn tp\n}\n\n// Tracer returns a Tracer with the given name and options. If a Tracer for\n// the given name and options does not exist it is created, otherwise the\n// existing Tracer is returned.\n//\n// If name is empty, DefaultTracerName is used instead.\n//\n// This method is safe to be called concurrently.\nfunc (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\t// This check happens before the mutex is acquired to avoid deadlocking if Tracer() is called from within Shutdown().\n\tif p.isShutdown.Load() {\n\t\treturn noop.NewTracerProvider().Tracer(name, opts...)\n\t}\n\tc := trace.NewTracerConfig(opts...)\n\tif name == \"\" {\n\t\tname = defaultTracerName\n\t}\n\tis := instrumentation.Scope{\n\t\tName: name,\n\t\tVersion: c.InstrumentationVersion(),\n\t\tSchemaURL: c.SchemaURL(),\n\t\tAttributes: c.InstrumentationAttributes(),\n\t}\n\n\tt, ok := func() (trace.Tracer, bool) {\n\t\tp.mu.Lock()\n\t\tdefer p.mu.Unlock()\n\t\t// Must check the flag after acquiring the mutex to avoid returning a valid tracer if Shutdown() ran\n\t\t// after the first check above but before we acquired the mutex.\n\t\tif p.isShutdown.Load() {\n\t\t\treturn noop.NewTracerProvider().Tracer(name, opts...), true\n\t\t}\n\t\tt, ok := p.namedTracer[is]\n\t\tif !ok {\n\t\t\tt = &tracer{\n\t\t\t\tprovider: p,\n\t\t\t\tinstrumentationScope: is,\n\t\t\t}\n\t\t\tt.initSelfObservability()\n\t\t\tp.namedTracer[is] = t\n\t\t}\n\t\treturn t, ok\n\t}()\n\tif !ok {\n\t\t// This code is outside the mutex to not hold the lock while calling third party logging code:\n\t\t// - That code may do slow things like I/O, which would prolong the duration the lock is held,\n\t\t// slowing down all tracing consumers.\n\t\t// - Logging code may be instrumented with tracing and deadlock because it could try\n\t\t// acquiring the same non-reentrant mutex.\n\t\tglobal.Info(\n\t\t\t\"Tracer created\",\n\t\t\t\"name\",\n\t\t\tname,\n\t\t\t\"version\",\n\t\t\tis.Version,\n\t\t\t\"schemaURL\",\n\t\t\tis.SchemaURL,\n\t\t\t\"attributes\",\n\t\t\tis.Attributes,\n\t\t)\n\t}\n\treturn t\n}\n\n// RegisterSpanProcessor adds the given SpanProcessor to the list of SpanProcessors.\nfunc (p *TracerProvider) RegisterSpanProcessor(sp SpanProcessor) {\n\t// This check prevents calls during a shutdown.\n\tif p.isShutdown.Load() {\n\t\treturn\n\t}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\t// This check prevents calls after a shutdown.\n\tif p.isShutdown.Load() {\n\t\treturn\n\t}\n\n\tcurrent := p.getSpanProcessors()\n\tnewSPS := make(spanProcessorStates, 0, len(current)+1)\n\tnewSPS = append(newSPS, current...)\n\tnewSPS = append(newSPS, newSpanProcessorState(sp))\n\tp.spanProcessors.Store(&newSPS)\n}\n\n// UnregisterSpanProcessor removes the given SpanProcessor from the list of SpanProcessors.\nfunc (p *TracerProvider) UnregisterSpanProcessor(sp SpanProcessor) {\n\t// This check prevents calls during a shutdown.\n\tif p.isShutdown.Load() {\n\t\treturn\n\t}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\t// This check prevents calls after a shutdown.\n\tif p.isShutdown.Load() {\n\t\treturn\n\t}\n\told := p.getSpanProcessors()\n\tif len(old) == 0 {\n\t\treturn\n\t}\n\tspss := make(spanProcessorStates, len(old))\n\tcopy(spss, old)\n\n\t// stop the span processor if it is started and remove it from the list\n\tvar stopOnce *spanProcessorState\n\tvar idx int\n\tfor i, sps := range spss {\n\t\tif sps.sp == sp {\n\t\t\tstopOnce = sps\n\t\t\tidx = i\n\t\t}\n\t}\n\tif stopOnce != nil {\n\t\tstopOnce.state.Do(func() {\n\t\t\tif err := sp.Shutdown(context.Background()); err != nil {\n\t\t\t\totel.Handle(err)\n\t\t\t}\n\t\t})\n\t}\n\tif len(spss) > 1 {\n\t\tcopy(spss[idx:], spss[idx+1:])\n\t}\n\tspss[len(spss)-1] = nil\n\tspss = spss[:len(spss)-1]\n\n\tp.spanProcessors.Store(&spss)\n}\n\n// ForceFlush immediately exports all spans that have not yet been exported for\n// all the registered span processors.\nfunc (p *TracerProvider) ForceFlush(ctx context.Context) error {\n\tspss := p.getSpanProcessors()\n\tif len(spss) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, sps := range spss {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tif err := sps.sp.ForceFlush(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// Shutdown shuts down TracerProvider. All registered span processors are shut down\n// in the order they were registered and any held computational resources are released.\n// After Shutdown is called, all methods are no-ops.\nfunc (p *TracerProvider) Shutdown(ctx context.Context) error {\n\t// This check prevents deadlocks in case of recursive shutdown.\n\tif p.isShutdown.Load() {\n\t\treturn nil\n\t}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\t// This check prevents calls after a shutdown has already been done concurrently.\n\tif !p.isShutdown.CompareAndSwap(false, true) { // did toggle?\n\t\treturn nil\n\t}\n\n\tvar retErr error\n\tfor _, sps := range p.getSpanProcessors() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tvar err error\n\t\tsps.state.Do(func() {\n\t\t\terr = sps.sp.Shutdown(ctx)\n\t\t})\n\t\tif err != nil {\n\t\t\tif retErr == nil {\n\t\t\t\tretErr = err\n\t\t\t} else {\n\t\t\t\t// Poor man's list of errors\n\t\t\t\tretErr = fmt.Errorf(\"%w; %w\", retErr, err)\n\t\t\t}\n\t\t}\n\t}\n\tp.spanProcessors.Store(&spanProcessorStates{})\n\treturn retErr\n}\n\nfunc (p *TracerProvider) getSpanProcessors() spanProcessorStates {\n\treturn *(p.spanProcessors.Load())\n}\n\n// TracerProviderOption configures a TracerProvider.\ntype TracerProviderOption interface {\n\tapply(tracerProviderConfig) tracerProviderConfig\n}\n\ntype traceProviderOptionFunc func(tracerProviderConfig) tracerProviderConfig\n\nfunc (fn traceProviderOptionFunc) apply(cfg tracerProviderConfig) tracerProviderConfig {\n\treturn fn(cfg)\n}\n\n// WithSyncer registers the exporter with the TracerProvider using a\n// SimpleSpanProcessor.\n//\n// This is not recommended for production use. The synchronous nature of the\n// SimpleSpanProcessor that will wrap the exporter make it good for testing,\n// debugging, or showing examples of other feature, but it will be slow and\n// have a high computation resource usage overhead. The WithBatcher option is\n// recommended for production use instead.\nfunc WithSyncer(e SpanExporter) TracerProviderOption {\n\treturn WithSpanProcessor(NewSimpleSpanProcessor(e))\n}\n\n// WithBatcher registers the exporter with the TracerProvider using a\n// BatchSpanProcessor configured with the passed opts.\nfunc WithBatcher(e SpanExporter, opts ...BatchSpanProcessorOption) TracerProviderOption {\n\treturn WithSpanProcessor(NewBatchSpanProcessor(e, opts...))\n}\n\n// WithSpanProcessor registers the SpanProcessor with a TracerProvider.\nfunc WithSpanProcessor(sp SpanProcessor) TracerProviderOption {\n\treturn traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig {\n\t\tcfg.processors = append(cfg.processors, sp)\n\t\treturn cfg\n\t})\n}\n\n// WithResource returns a TracerProviderOption that will configure the\n// Resource r as a TracerProvider's Resource. The configured Resource is\n// referenced by all the Tracers the TracerProvider creates. It represents the\n// entity producing telemetry.\n//\n// If this option is not used, the TracerProvider will use the\n// resource.Default() Resource by default.\nfunc WithResource(r *resource.Resource) TracerProviderOption {\n\treturn traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig {\n\t\tvar err error\n\t\tcfg.resource, err = resource.Merge(resource.Environment(), r)\n\t\tif err != nil {\n\t\t\totel.Handle(err)\n\t\t}\n\t\treturn cfg\n\t})\n}\n\n// WithIDGenerator returns a TracerProviderOption that will configure the\n// IDGenerator g as a TracerProvider's IDGenerator. The configured IDGenerator\n// is used by the Tracers the TracerProvider creates to generate new Span and\n// Trace IDs.\n//\n// If this option is not used, the TracerProvider will use a random number\n// IDGenerator by default.\nfunc WithIDGenerator(g IDGenerator) TracerProviderOption {\n\treturn traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig {\n\t\tif g != nil {\n\t\t\tcfg.idGenerator = g\n\t\t}\n\t\treturn cfg\n\t})\n}\n\n// WithSampler returns a TracerProviderOption that will configure the Sampler\n// s as a TracerProvider's Sampler. The configured Sampler is used by the\n// Tracers the TracerProvider creates to make their sampling decisions for the\n// Spans they create.\n//\n// This option overrides the Sampler configured through the OTEL_TRACES_SAMPLER\n// and OTEL_TRACES_SAMPLER_ARG environment variables. If this option is not used\n// and the sampler is not configured through environment variables or the environment\n// contains invalid/unsupported configuration, the TracerProvider will use a\n// ParentBased(AlwaysSample) Sampler by default.\nfunc WithSampler(s Sampler) TracerProviderOption {\n\treturn traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig {\n\t\tif s != nil {\n\t\t\tcfg.sampler = s\n\t\t}\n\t\treturn cfg\n\t})\n}\n\n// WithSpanLimits returns a TracerProviderOption that configures a\n// TracerProvider to use the SpanLimits sl. These SpanLimits bound any Span\n// created by a Tracer from the TracerProvider.\n//\n// If any field of sl is zero or negative it will be replaced with the default\n// value for that field.\n//\n// If this or WithRawSpanLimits are not provided, the TracerProvider will use\n// the limits defined by environment variables, or the defaults if unset.\n// Refer to the NewSpanLimits documentation for information about this\n// relationship.\n//\n// Deprecated: Use WithRawSpanLimits instead which allows setting unlimited\n// and zero limits. This option will be kept until the next major version\n// incremented release.\nfunc WithSpanLimits(sl SpanLimits) TracerProviderOption {\n\tif sl.AttributeValueLengthLimit <= 0 {\n\t\tsl.AttributeValueLengthLimit = DefaultAttributeValueLengthLimit\n\t}\n\tif sl.AttributeCountLimit <= 0 {\n\t\tsl.AttributeCountLimit = DefaultAttributeCountLimit\n\t}\n\tif sl.EventCountLimit <= 0 {\n\t\tsl.EventCountLimit = DefaultEventCountLimit\n\t}\n\tif sl.AttributePerEventCountLimit <= 0 {\n\t\tsl.AttributePerEventCountLimit = DefaultAttributePerEventCountLimit\n\t}\n\tif sl.LinkCountLimit <= 0 {\n\t\tsl.LinkCountLimit = DefaultLinkCountLimit\n\t}\n\tif sl.AttributePerLinkCountLimit <= 0 {\n\t\tsl.AttributePerLinkCountLimit = DefaultAttributePerLinkCountLimit\n\t}\n\treturn traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig {\n\t\tcfg.spanLimits = sl\n\t\treturn cfg\n\t})\n}\n\n// WithRawSpanLimits returns a TracerProviderOption that configures a\n// TracerProvider to use these limits. These limits bound any Span created by\n// a Tracer from the TracerProvider.\n//\n// The limits will be used as-is. Zero or negative values will not be changed\n// to the default value like WithSpanLimits does. Setting a limit to zero will\n// effectively disable the related resource it limits and setting to a\n// negative value will mean that resource is unlimited. Consequentially, this\n// means that the zero-value SpanLimits will disable all span resources.\n// Because of this, limits should be constructed using NewSpanLimits and\n// updated accordingly.\n//\n// If this or WithSpanLimits are not provided, the TracerProvider will use the\n// limits defined by environment variables, or the defaults if unset. Refer to\n// the NewSpanLimits documentation for information about this relationship.\nfunc WithRawSpanLimits(limits SpanLimits) TracerProviderOption {\n\treturn traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig {\n\t\tcfg.spanLimits = limits\n\t\treturn cfg\n\t})\n}\n\nfunc applyTracerProviderEnvConfigs(cfg tracerProviderConfig) tracerProviderConfig {\n\tfor _, opt := range tracerProviderOptionsFromEnv() {\n\t\tcfg = opt.apply(cfg)\n\t}\n\n\treturn cfg\n}\n\nfunc tracerProviderOptionsFromEnv() []TracerProviderOption {\n\tvar opts []TracerProviderOption\n\n\tsampler, err := samplerFromEnv()\n\tif err != nil {\n\t\totel.Handle(err)\n\t}\n\n\tif sampler != nil {\n\t\topts = append(opts, WithSampler(sampler))\n\t}\n\n\treturn opts\n}\n\n// ensureValidTracerProviderConfig ensures that given TracerProviderConfig is valid.\nfunc ensureValidTracerProviderConfig(cfg tracerProviderConfig) tracerProviderConfig {\n\tif cfg.sampler == nil {\n\t\tcfg.sampler = ParentBased(AlwaysSample())\n\t}\n\tif cfg.idGenerator == nil {\n\t\tcfg.idGenerator = defaultIDGenerator()\n\t}\n\tif cfg.resource == nil {\n\t\tcfg.resource = resource.Default()\n\t}\n\treturn cfg\n}\n"}, {"path": "sdk/trace/tracer.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage trace // import \"go.opentelemetry.io/otel/sdk/trace\"\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/sdk\"\n\t\"go.opentelemetry.io/otel/sdk/instrumentation\"\n\t\"go.opentelemetry.io/otel/sdk/trace/internal/x\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.36.0\"\n\t\"go.opentelemetry.io/otel/semconv/v1.36.0/otelconv\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.opentelemetry.io/otel/trace/embedded\"\n)\n\ntype tracer struct {\n\tembedded.Tracer\n\n\tprovider *TracerProvider\n\tinstrumentationScope instrumentation.Scope\n\n\tselfObservabilityEnabled bool\n\tspanLiveMetric otelconv.SDKSpanLive\n\tspanStartedMetric otelconv.SDKSpanStarted\n}\n\nvar _ trace.Tracer = &tracer{}\n\nfunc (tr *tracer) initSelfObservability() {\n\tif !x.SelfObservability.Enabled() {\n\t\treturn\n\t}\n\n\ttr.selfObservabilityEnabled = true\n\tmp := otel.GetMeterProvider()\n\tm := mp.Meter(selfObsScopeName,\n\t\tmetric.WithInstrumentationVersion(sdk.Version()),\n\t\tmetric.WithSchemaURL(semconv.SchemaURL))\n\n\tvar err error\n\tif tr.spanLiveMetric, err = otelconv.NewSDKSpanLive(m); err != nil {\n\t\totel.Handle(err)\n\t}\n\tif tr.spanStartedMetric, err = otelconv.NewSDKSpanStarted(m); err != nil {\n\t\totel.Handle(err)\n\t}\n}\n\n// Start starts a Span and returns it along with a context containing it.\n//\n// The Span is created with the provided name and as a child of any existing\n// span context found in the passed context. The created Span will be\n// configured appropriately by any SpanOption passed.\nfunc (tr *tracer) Start(\n\tctx context.Context,\n\tname string,\n\toptions ...trace.SpanStartOption,\n) (context.Context, trace.Span) {\n\tconfig := trace.NewSpanStartConfig(options...)\n\n\tif ctx == nil {\n\t\t// Prevent trace.ContextWithSpan from panicking.\n\t\tctx = context.Background()\n\t}\n\n\t// For local spans created by this SDK, track child span count.\n\tif p := trace.SpanFromContext(ctx); p != nil {\n\t\tif sdkSpan, ok := p.(*recordingSpan); ok {\n\t\t\tsdkSpan.addChild()\n\t\t}\n\t}\n\n\ts := tr.newSpan(ctx, name, &config)\n\tif tr.selfObservabilityEnabled {\n\t\t// Check if the span has a parent span and set the origin attribute accordingly.\n\t\tvar attrParentOrigin attribute.KeyValue\n\t\tif psc := trace.SpanContextFromContext(ctx); psc.IsValid() {\n\t\t\tif psc.IsRemote() {\n\t\t\t\tattrParentOrigin = tr.spanStartedMetric.AttrSpanParentOrigin(otelconv.SpanParentOriginRemote)\n\t\t\t} else {\n\t\t\t\tattrParentOrigin = tr.spanStartedMetric.AttrSpanParentOrigin(otelconv.SpanParentOriginLocal)\n\t\t\t}\n\t\t} else {\n\t\t\tattrParentOrigin = tr.spanStartedMetric.AttrSpanParentOrigin(otelconv.SpanParentOriginNone)\n\t\t}\n\n\t\t// Determine the sampling result and create the corresponding attribute.\n\t\tvar attrSamplingResult attribute.KeyValue\n\t\tswitch {\n\t\tcase s.SpanContext().IsSampled() && s.IsRecording():\n\t\t\tattrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(\n\t\t\t\totelconv.SpanSamplingResultRecordAndSample,\n\t\t\t)\n\t\tcase s.IsRecording():\n\t\t\tattrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultRecordOnly)\n\t\tdefault:\n\t\t\tattrSamplingResult = tr.spanStartedMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultDrop)\n\t\t}\n\n\t\ttr.spanStartedMetric.Add(context.Background(), 1, attrParentOrigin, attrSamplingResult)\n\t}\n\n\tif rw, ok := s.(ReadWriteSpan); ok && s.IsRecording() {\n\t\tsps := tr.provider.getSpanProcessors()\n\t\tfor _, sp := range sps {\n\t\t\tsp.sp.OnStart(ctx, rw)\n\t\t}\n\t}\n\tif rtt, ok := s.(runtimeTracer); ok {\n\t\tctx = rtt.runtimeTrace(ctx)\n\t}\n\n\treturn trace.ContextWithSpan(ctx, s), s\n}\n\ntype runtimeTracer interface {\n\t// runtimeTrace starts a \"runtime/trace\".Task for the span and\n\t// returns a context containing the task.\n\truntimeTrace(ctx context.Context) context.Context\n}\n\n// newSpan returns a new configured span.\nfunc (tr *tracer) newSpan(ctx context.Context, name string, config *trace.SpanConfig) trace.Span {\n\t// If told explicitly to make this a new root use a zero value SpanContext\n\t// as a parent which contains an invalid trace ID and is not remote.\n\tvar psc trace.SpanContext\n\tif config.NewRoot() {\n\t\tctx = trace.ContextWithSpanContext(ctx, psc)\n\t} else {\n\t\tpsc = trace.SpanContextFromContext(ctx)\n\t}\n\n\t// If there is a valid parent trace ID, use it to ensure the continuity of\n\t// the trace. Always generate a new span ID so other components can rely\n\t// on a unique span ID, even if the Span is non-recording.\n\tvar tid trace.TraceID\n\tvar sid trace.SpanID\n\tif !psc.TraceID().IsValid() {\n\t\ttid, sid = tr.provider.idGenerator.NewIDs(ctx)\n\t} else {\n\t\ttid = psc.TraceID()\n\t\tsid = tr.provider.idGenerator.NewSpanID(ctx, tid)\n\t}\n\n\tsamplingResult := tr.provider.sampler.ShouldSample(SamplingParameters{\n\t\tParentContext: ctx,\n\t\tTraceID: tid,\n\t\tName: name,\n\t\tKind: config.SpanKind(),\n\t\tAttributes: config.Attributes(),\n\t\tLinks: config.Links(),\n\t})\n\n\tscc := trace.SpanContextConfig{\n\t\tTraceID: tid,\n\t\tSpanID: sid,\n\t\tTraceState: samplingResult.Tracestate,\n\t}\n\tif isSampled(samplingResult) {\n\t\tscc.TraceFlags = psc.TraceFlags() | trace.FlagsSampled\n\t} else {\n\t\tscc.TraceFlags = psc.TraceFlags() &^ trace.FlagsSampled\n\t}\n\tsc := trace.NewSpanContext(scc)\n\n\tif !isRecording(samplingResult) {\n\t\treturn tr.newNonRecordingSpan(sc)\n\t}\n\treturn tr.newRecordingSpan(psc, sc, name, samplingResult, config)\n}\n\n// newRecordingSpan returns a new configured recordingSpan.\nfunc (tr *tracer) newRecordingSpan(\n\tpsc, sc trace.SpanContext,\n\tname string,\n\tsr SamplingResult,\n\tconfig *trace.SpanConfig,\n) *recordingSpan {\n\tstartTime := config.Timestamp()\n\tif startTime.IsZero() {\n\t\tstartTime = time.Now()\n\t}\n\n\ts := &recordingSpan{\n\t\t// Do not pre-allocate the attributes slice here! Doing so will\n\t\t// allocate memory that is likely never going to be used, or if used,\n\t\t// will be over-sized. The default Go compiler has been tested to\n\t\t// dynamically allocate needed space very well. Benchmarking has shown\n\t\t// it to be more performant than what we can predetermine here,\n\t\t// especially for the common use case of few to no added\n\t\t// attributes.\n\n\t\tparent: psc,\n\t\tspanContext: sc,\n\t\tspanKind: trace.ValidateSpanKind(config.SpanKind()),\n\t\tname: name,\n\t\tstartTime: startTime,\n\t\tevents: newEvictedQueueEvent(tr.provider.spanLimits.EventCountLimit),\n\t\tlinks: newEvictedQueueLink(tr.provider.spanLimits.LinkCountLimit),\n\t\ttracer: tr,\n\t}\n\n\tfor _, l := range config.Links() {\n\t\ts.AddLink(l)\n\t}\n\n\ts.SetAttributes(sr.Attributes...)\n\ts.SetAttributes(config.Attributes()...)\n\n\tif tr.selfObservabilityEnabled {\n\t\t// Determine the sampling result and create the corresponding attribute.\n\t\tvar attrSamplingResult attribute.KeyValue\n\t\tif s.spanContext.IsSampled() {\n\t\t\tattrSamplingResult = tr.spanLiveMetric.AttrSpanSamplingResult(\n\t\t\t\totelconv.SpanSamplingResultRecordAndSample,\n\t\t\t)\n\t\t} else {\n\t\t\tattrSamplingResult = tr.spanLiveMetric.AttrSpanSamplingResult(otelconv.SpanSamplingResultRecordOnly)\n\t\t}\n\n\t\ttr.spanLiveMetric.Add(context.Background(), 1, attrSamplingResult)\n\t}\n\n\treturn s\n}\n\n// newNonRecordingSpan returns a new configured nonRecordingSpan.\nfunc (tr *tracer) newNonRecordingSpan(sc trace.SpanContext) nonRecordingSpan {\n\treturn nonRecordingSpan{tracer: tr, sc: sc}\n}\n"}, {"path": "doc.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n/*\nPackage otel provides global access to the OpenTelemetry API. The subpackages of\nthe otel package provide an implementation of the OpenTelemetry API.\n\nThe provided API is used to instrument code and measure data about that code's\nperformance and operation. The measured data, by default, is not processed or\ntransmitted anywhere. An implementation of the OpenTelemetry SDK, like the\ndefault SDK implementation (go.opentelemetry.io/otel/sdk), and associated\nexporters are used to process and transport this data.\n\nTo read the getting started guide, see https://opentelemetry.io/docs/languages/go/getting-started/.\n\nTo read more about tracing, see go.opentelemetry.io/otel/trace.\n\nTo read more about metrics, see go.opentelemetry.io/otel/metric.\n\nTo read more about logs, see go.opentelemetry.io/otel/log.\n\nTo read more about propagation, see go.opentelemetry.io/otel/propagation and\ngo.opentelemetry.io/otel/baggage.\n*/\npackage otel // import \"go.opentelemetry.io/otel\"\n"}, {"path": "error_handler.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\n// ErrorHandler handles irremediable events.\ntype ErrorHandler interface {\n\t// DO NOT CHANGE: any modification will not be backwards compatible and\n\t// must never be done outside of a new major release.\n\n\t// Handle handles any error deemed irremediable by an OpenTelemetry\n\t// component.\n\tHandle(error)\n\t// DO NOT CHANGE: any modification will not be backwards compatible and\n\t// must never be done outside of a new major release.\n}\n\n// ErrorHandlerFunc is a convenience adapter to allow the use of a function\n// as an ErrorHandler.\ntype ErrorHandlerFunc func(error)\n\nvar _ ErrorHandler = ErrorHandlerFunc(nil)\n\n// Handle handles the irremediable error by calling the ErrorHandlerFunc itself.\nfunc (f ErrorHandlerFunc) Handle(err error) {\n\tf(err)\n}\n"}, {"path": "handler.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"go.opentelemetry.io/otel/internal/global\"\n)\n\n// Compile-time check global.ErrDelegator implements ErrorHandler.\nvar _ ErrorHandler = (*global.ErrDelegator)(nil)\n\n// GetErrorHandler returns the global ErrorHandler instance.\n//\n// The default ErrorHandler instance returned will log all errors to STDERR\n// until an override ErrorHandler is set with SetErrorHandler. All\n// ErrorHandler returned prior to this will automatically forward errors to\n// the set instance instead of logging.\n//\n// Subsequent calls to SetErrorHandler after the first will not forward errors\n// to the new ErrorHandler for prior returned instances.\nfunc GetErrorHandler() ErrorHandler { return global.GetErrorHandler() }\n\n// SetErrorHandler sets the global ErrorHandler to h.\n//\n// The first time this is called all ErrorHandler previously returned from\n// GetErrorHandler will send errors to h instead of the default logging\n// ErrorHandler. Subsequent calls will set the global ErrorHandler, but not\n// delegate errors to h.\nfunc SetErrorHandler(h ErrorHandler) { global.SetErrorHandler(h) }\n\n// Handle is a convenience function for GetErrorHandler().Handle(err).\nfunc Handle(err error) { global.GetErrorHandler().Handle(err) }\n"}, {"path": "handler_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype testErrHandler struct {\n\terr error\n}\n\nvar _ ErrorHandler = &testErrHandler{}\n\nfunc (eh *testErrHandler) Handle(err error) { eh.err = err }\n\nfunc TestGlobalErrorHandler(t *testing.T) {\n\tSetErrorHandler(GetErrorHandler())\n\tassert.NotPanics(t, func() { Handle(assert.AnError) }, \"Default assignment\")\n\n\te1 := &testErrHandler{}\n\tSetErrorHandler(e1)\n\tHandle(assert.AnError)\n\tassert.ErrorIs(t, e1.err, assert.AnError)\n\te1.err = nil\n\n\te2 := &testErrHandler{}\n\tSetErrorHandler(e2)\n\tGetErrorHandler().Handle(assert.AnError)\n\tassert.ErrorIs(t, e2.err, assert.AnError)\n}\n"}, {"path": "internal_logging.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"github.com/go-logr/logr\"\n\n\t\"go.opentelemetry.io/otel/internal/global\"\n)\n\n// SetLogger configures the logger used internally to opentelemetry.\nfunc SetLogger(logger logr.Logger) {\n\tglobal.SetLogger(logger)\n}\n"}, {"path": "internal_logging_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel_test\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/go-logr/stdr\"\n\n\t\"go.opentelemetry.io/otel\"\n)\n\nfunc ExampleSetLogger() {\n\tlogger := stdr.New(log.New(os.Stdout, \"\", log.LstdFlags|log.Lshortfile))\n\totel.SetLogger(logger)\n}\n"}, {"path": "metric.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"go.opentelemetry.io/otel/internal/global\"\n\t\"go.opentelemetry.io/otel/metric\"\n)\n\n// Meter returns a Meter from the global MeterProvider. The name must be the\n// name of the library providing instrumentation. This name may be the same as\n// the instrumented code only if that code provides built-in instrumentation.\n// If the name is empty, then a implementation defined default name will be\n// used instead.\n//\n// If this is called before a global MeterProvider is registered the returned\n// Meter will be a No-op implementation of a Meter. When a global MeterProvider\n// is registered for the first time, the returned Meter, and all the\n// instruments it has created or will create, are recreated automatically from\n// the new MeterProvider.\n//\n// This is short for GetMeterProvider().Meter(name).\nfunc Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn GetMeterProvider().Meter(name, opts...)\n}\n\n// GetMeterProvider returns the registered global meter provider.\n//\n// If no global GetMeterProvider has been registered, a No-op GetMeterProvider\n// implementation is returned. When a global GetMeterProvider is registered for\n// the first time, the returned GetMeterProvider, and all the Meters it has\n// created or will create, are recreated automatically from the new\n// GetMeterProvider.\nfunc GetMeterProvider() metric.MeterProvider {\n\treturn global.MeterProvider()\n}\n\n// SetMeterProvider registers mp as the global MeterProvider.\nfunc SetMeterProvider(mp metric.MeterProvider) {\n\tglobal.SetMeterProvider(mp)\n}\n"}, {"path": "metric_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t\"go.opentelemetry.io/otel/metric/noop\"\n)\n\ntype testMeterProvider struct{ embedded.MeterProvider }\n\nvar _ metric.MeterProvider = &testMeterProvider{}\n\nfunc (*testMeterProvider) Meter(string, ...metric.MeterOption) metric.Meter {\n\treturn noop.NewMeterProvider().Meter(\"\")\n}\n\nfunc TestMultipleGlobalMeterProvider(t *testing.T) {\n\tp1 := testMeterProvider{}\n\tp2 := noop.NewMeterProvider()\n\tSetMeterProvider(&p1)\n\tSetMeterProvider(p2)\n\n\tgot := GetMeterProvider()\n\tassert.Equal(t, p2, got)\n}\n"}, {"path": "propagation.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otel // import \"go.opentelemetry.io/otel\"\n\nimport (\n\t\"go.opentelemetry.io/otel/internal/global\"\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n// GetTextMapPropagator returns the global TextMapPropagator. If none has been\n// set, a No-Op TextMapPropagator is returned.\nfunc GetTextMapPropagator() propagation.TextMapPropagator {\n\treturn global.TextMapPropagator()\n}\n\n// SetTextMapPropagator sets propagator as the global TextMapPropagator.\nfunc SetTextMapPropagator(propagator propagation.TextMapPropagator) {\n\tglobal.SetTextMapPropagator(propagator)\n}\n"}], "context_lines": 1497, "buggy_files": ["CHANGELOG.md", "sdk/trace/batch_span_processor.go", "sdk/trace/provider.go", "sdk/trace/tracer.go"], "test_files": [{"path": "sdk/trace/batch_span_processor_test.go", "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage trace\n\nimport (\n\t\"context\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk\"\n\t\"go.opentelemetry.io/otel/sdk/instrumentation\"\n\t\"go.opentelemetry.io/otel/sdk/internal/env\"\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.36.0\"\n\t\"go.opentelemetry.io/otel/semconv/v1.36.0/otelconv\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\ntype testBatchExporter struct {\n\tmu sync.Mutex\n\tspans []ReadOnlySpan\n\tsizes []int\n\tbatchCount int\n\tshutdownCount int\n\terrors []error\n\tdroppedCount int\n\tidx int\n\terr error\n}\n\nfunc (t *testBatchExporter) ExportSpans(ctx context.Context, spans []ReadOnlySpan) error {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tif t.idx < len(t.errors) {\n\t\tt.droppedCount += len(spans)\n\t\terr := t.errors[t.idx]\n\t\tt.idx++\n\t\treturn err\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tt.err = ctx.Err()\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\n\tt.spans = append(t.spans, spans...)\n\tt.sizes = append(t.sizes, len(spans))\n\tt.batchCount++\n\treturn nil\n}\n\nfunc (t *testBatchExporter) Shutdown(context.Context) error {\n\tt.shutdownCount++\n\treturn nil\n}\n\nfunc (t *testBatchExporter) len() int {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\treturn len(t.spans)\n}\n\nfunc (t *testBatchExporter) getBatchCount() int {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\treturn t.batchCount\n}\n\nvar _ SpanExporter = (*testBatchExporter)(nil)\n\nfunc TestNewBatchSpanProcessorWithNilExporter(t *testing.T) {\n\ttp := basicTracerProvider(t)\n\tbsp := NewBatchSpanProcessor(nil)\n\ttp.RegisterSpanProcessor(bsp)\n\ttr := tp.Tracer(\"NilExporter\")\n\n\t_, span := tr.Start(context.Background(), \"foo\")\n\tspan.End()\n\n\t// These should not panic.\n\tbsp.OnStart(context.Background(), span.(ReadWriteSpan))\n\tbsp.OnEnd(span.(ReadOnlySpan))\n\tif err := bsp.ForceFlush(context.Background()); err != nil {\n\t\tt.Errorf(\"failed to ForceFlush the BatchSpanProcessor: %v\", err)\n\t}\n\tif err := bsp.Shutdown(context.Background()); err != nil {\n\t\tt.Errorf(\"failed to Shutdown the BatchSpanProcessor: %v\", err)\n\t}\n}\n\ntype testOption struct {\n\tname string\n\to []BatchSpanProcessorOption\n\twantNumSpans int\n\twantBatchCount int\n\tgenNumSpans int\n\tparallel bool\n\tenvs map[string]string\n}\n\nfunc TestNewBatchSpanProcessorWithOptions(t *testing.T) {\n\tschDelay := 200 * time.Millisecond\n\toptions := []testOption{\n\t\t{\n\t\t\tname: \"default BatchSpanProcessorOptions\",\n\t\t\twantNumSpans: 2053,\n\t\t\twantBatchCount: 4,\n\t\t\tgenNumSpans: 2053,\n\t\t},\n\t\t{\n\t\t\tname: \"non-default BatchTimeout\",\n\t\t\to: []BatchSpanProcessorOption{\n\t\t\t\tWithBatchTimeout(schDelay),\n\t\t\t},\n\t\t\twantNumSpans: 2053,\n\t\t\twantBatchCount: 4,\n\t\t\tgenNumSpans: 2053,\n\t\t},\n\t\t{\n\t\t\tname: \"non-default MaxQueueSize and BatchTimeout\",\n\t\t\to: []BatchSpanProcessorOption{\n\t\t\t\tWithBatchTimeout(schDelay),\n\t\t\t\tWithMaxQueueSize(200),\n\t\t\t},\n\t\t\twantNumSpans: 205,\n\t\t\twantBatchCount: 1,\n\t\t\tgenNumSpans: 205,\n\t\t},\n\t\t{\n\t\t\tname: \"non-default MaxQueueSize, BatchTimeout and MaxExportBatchSize\",\n\t\t\to: []BatchSpanProcessorOption{\n\t\t\t\tWithBatchTimeout(schDelay),\n\t\t\t\tWithMaxQueueSize(205),\n\t\t\t\tWithMaxExportBatchSize(20),\n\t\t\t},\n\t\t\twantNumSpans: 210,\n\t\t\twantBatchCount: 11,\n\t\t\tgenNumSpans: 210,\n\t\t},\n\t\t{\n\t\t\tname: \"blocking option\",\n\t\t\to: []BatchSpanProcessorOption{\n\t\t\t\tWithBatchTimeout(schDelay),\n\t\t\t\tWithMaxQueueSize(200),\n\t\t\t\tWithMaxExportBatchSize(20),\n\t\t\t},\n\t\t\twantNumSpans: 205,\n\t\t\twantBatchCount: 11,\n\t\t\tgenNumSpans: 205,\n\t\t},\n\t\t{\n\t\t\tname: \"parallel span generation\",\n\t\t\to: []BatchSpanProcessorOption{\n\t\t\t\tWithBatchTimeout(schDelay),\n\t\t\t\tWithMaxQueueSize(200),\n\t\t\t},\n\t\t\twantNumSpans: 205,\n\t\t\twantBatchCount: 1,\n\t\t\tgenNumSpans: 205,\n\t\t\tparallel: true,\n\t\t},\n\t\t{\n\t\t\tname: \"parallel span blocking\",\n\t\t\to: []BatchSpanProcessorOption{\n\t\t\t\tWithBatchTimeout(schDelay),\n\t\t\t\tWithMaxExportBatchSize(200),\n\t\t\t},\n\t\t\twantNumSpans: 2000,\n\t\t\twantBatchCount: 10,\n\t\t\tgenNumSpans: 2000,\n\t\t\tparallel: true,\n\t\t},\n\t}\n\tfor _, option := range options {\n\t\tt.Run(option.name, func(t *testing.T) {\n\t\t\tte := testBatchExporter{}\n\t\t\ttp := basicTracerProvider(t)\n\t\t\tssp := createAndRegisterBatchSP(option, &te)\n\t\t\tif ssp == nil {\n\t\t\t\tt.Fatalf(\"%s: Error creating new instance of BatchSpanProcessor\\n\", option.name)\n\t\t\t}\n\t\t\ttp.RegisterSpanProcessor(ssp)\n\t\t\ttr := tp.Tracer(\"BatchSpanProcessorWithOptions\")\n\n\t\t\tif option.parallel {\n\t\t\t\tgenerateSpanParallel(t, tr, option)\n\t\t\t} else {\n\t\t\t\tgenerateSpan(t, tr, option)\n\t\t\t}\n\n\t\t\ttp.UnregisterSpanProcessor(ssp)\n\n\t\t\tgotNumOfSpans := te.len()\n\t\t\tif option.wantNumSpans > 0 && option.wantNumSpans != gotNumOfSpans {\n\t\t\t\tt.Errorf(\"number of exported span: got %+v, want %+v\\n\",\n\t\t\t\t\tgotNumOfSpans, option.wantNumSpans)\n\t\t\t}\n\n\t\t\tgotBatchCount := te.getBatchCount()\n\t\t\tif option.wantBatchCount > 0 && gotBatchCount < option.wantBatchCount {\n\t\t\t\tt.Errorf(\"number batches: got %+v, want >= %+v\\n\",\n\t\t\t\t\tgotBatchCount, option.wantBatchCount)\n\t\t\t\tt.Errorf(\"Batches %v\\n\", te.sizes)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNewBatchSpanProcessorWithEnvOptions(t *testing.T) {\n\toptions := []testOption{\n\t\t{\n\t\t\tname: \"BatchSpanProcessorEnvOptions - Basic\",\n\t\t\twantNumSpans: 2053,\n\t\t\twantBatchCount: 1,\n\t\t\tgenNumSpans: 2053,\n\t\t\tenvs: map[string]string{\n\t\t\t\tenv.BatchSpanProcessorMaxQueueSizeKey: \"5000\",\n\t\t\t\tenv.BatchSpanProcessorMaxExportBatchSizeKey: \"5000\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"BatchSpanProcessorEnvOptions - A lager max export batch size than queue size\",\n\t\t\twantNumSpans: 2053,\n\t\t\twantBatchCount: 4,\n\t\t\tgenNumSpans: 2053,\n\t\t\tenvs: map[string]string{\n\t\t\t\tenv.BatchSpanProcessorMaxQueueSizeKey: \"5000\",\n\t\t\t\tenv.BatchSpanProcessorMaxExportBatchSizeKey: \"10000\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"BatchSpanProcessorEnvOptions - A lage max export batch size with a small queue size\",\n\t\t\twantNumSpans: 2053,\n\t\t\twantBatchCount: 42,\n\t\t\tgenNumSpans: 2053,\n\t\t\tenvs: map[string]string{\n\t\t\t\tenv.BatchSpanProcessorMaxQueueSizeKey: \"50\",\n\t\t\t\tenv.BatchSpanProcessorMaxExportBatchSizeKey: \"10000\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, option := range options {\n\t\tt.Run(option.name, func(t *testing.T) {\n\t\t\tfor k, v := range option.envs {\n\t\t\t\tt.Setenv(k, v)\n\t\t\t}\n\n\t\t\tte := testBatchExporter{}\n\t\t\ttp := basicTracerProvider(t)\n\t\t\tssp := createAndRegisterBatchSP(option, &te)\n\t\t\tif ssp == nil {\n\t\t\t\tt.Fatalf(\"%s: Error creating new instance of BatchSpanProcessor\\n\", option.name)\n\t\t\t}\n\t\t\ttp.RegisterSpanProcessor(ssp)\n\t\t\ttr := tp.Tracer(\"BatchSpanProcessorWithOptions\")\n\n\t\t\tif option.parallel {\n\t\t\t\tgenerateSpanParallel(t, tr, option)\n\t\t\t} else {\n\t\t\t\tgenerateSpan(t, tr, option)\n\t\t\t}\n\n\t\t\ttp.UnregisterSpanProcessor(ssp)\n\n\t\t\tgotNumOfSpans := te.len()\n\t\t\tif option.wantNumSpans > 0 && option.wantNumSpans != gotNumOfSpans {\n\t\t\t\tt.Errorf(\"number of exported span: got %+v, want %+v\\n\",\n\t\t\t\t\tgotNumOfSpans, option.wantNumSpans)\n\t\t\t}\n\n\t\t\tgotBatchCount := te.getBatchCount()\n\t\t\tif option.wantBatchCount > 0 && gotBatchCount < option.wantBatchCount {\n\t\t\t\tt.Errorf(\"number batches: got %+v, want >= %+v\\n\",\n\t\t\t\t\tgotBatchCount, option.wantBatchCount)\n\t\t\t\tt.Errorf(\"Batches %v\\n\", te.sizes)\n\t\t\t}\n\t\t})\n\t}\n}\n\ntype stuckExporter struct {\n\ttestBatchExporter\n}\n\n// ExportSpans waits for ctx to expire and returns that error.\nfunc (e *stuckExporter) ExportSpans(ctx context.Context, _ []ReadOnlySpan) error {\n\t<-ctx.Done()\n\te.err = ctx.Err()\n\treturn ctx.Err()\n}\n\nfunc TestBatchSpanProcessorExportTimeout(t *testing.T) {\n\texp := new(stuckExporter)\n\tbsp := NewBatchSpanProcessor(\n\t\texp,\n\t\t// Set a non-zero export timeout so a deadline is set.\n\t\tWithExportTimeout(1*time.Microsecond),\n\t\tWithBlocking(),\n\t)\n\ttp := basicTracerProvider(t)\n\ttp.RegisterSpanProcessor(bsp)\n\n\ttr := tp.Tracer(\"BatchSpanProcessorExportTimeout\")\n\tgenerateSpan(t, tr, testOption{genNumSpans: 1})\n\ttp.UnregisterSpanProcessor(bsp)\n\n\tif !errors.Is(exp.err, context.DeadlineExceeded) {\n\t\tt.Errorf(\"context deadline error not returned: got %+v\", exp.err)\n\t}\n}\n\nfunc createAndRegisterBatchSP(option testOption, te *testBatchExporter) SpanProcessor {\n\t// Always use blocking queue to avoid flaky tests.\n\toptions := append(option.o, WithBlocking())\n\treturn NewBatchSpanProcessor(te, options...)\n}\n\nfunc generateSpan(_ *testing.T, tr trace.Tracer, option testOption) {\n\tsc := getSpanContext()\n\n\tfor i := 0; i < option.genNumSpans; i++ {\n\t\ttid := sc.TraceID()\n\t\tbinary.BigEndian.PutUint64(tid[0:8], uint64(i+1))\n\t\tnewSc := sc.WithTraceID(tid)\n\t\tctx := trace.ContextWithRemoteSpanContext(context.Background(), newSc)\n\t\t_, span := tr.Start(ctx, option.name)\n\t\tspan.End()\n\t}\n}\n\nfunc generateSpanParallel(_ *testing.T, tr trace.Tracer, option testOption) {\n\tsc := getSpanContext()\n\n\twg := &sync.WaitGroup{}\n\tfor i := 0; i < option.genNumSpans; i++ {\n\t\ttid := sc.TraceID()\n\t\tbinary.BigEndian.PutUint64(tid[0:8], uint64(i+1))\n\n\t\twg.Add(1)\n\t\tgo func(sc trace.SpanContext) {\n\t\t\tctx := trace.ContextWithRemoteSpanContext(context.Background(), sc)\n\t\t\t_, span := tr.Start(ctx, option.name)\n\t\t\tspan.End()\n\t\t\twg.Done()\n\t\t}(sc.WithTraceID(tid))\n\t}\n\twg.Wait()\n}\n\nfunc getSpanContext() trace.SpanContext {\n\ttid, _ := trace.TraceIDFromHex(\"01020304050607080102040810203040\")\n\tsid, _ := trace.SpanIDFromHex(\"0102040810203040\")\n\treturn trace.NewSpanContext(trace.SpanContextConfig{\n\t\tTraceID: tid,\n\t\tSpanID: sid,\n\t\tTraceFlags: 0x1,\n\t})\n}\n\nfunc TestBatchSpanProcessorShutdown(t *testing.T) {\n\tvar bp testBatchExporter\n\tbsp := NewBatchSpanProcessor(&bp)\n\n\terr := bsp.Shutdown(context.Background())\n\tif err != nil {\n\t\tt.Error(\"Error shutting the BatchSpanProcessor down\\n\")\n\t}\n\tassert.Equal(t, 1, bp.shutdownCount, \"shutdown from span exporter not called\")\n\n\t// Multiple call to Shutdown() should not panic.\n\terr = bsp.Shutdown(context.Background())\n\tif err != nil {\n\t\tt.Error(\"Error shutting the BatchSpanProcessor down\\n\")\n\t}\n\tassert.Equal(t, 1, bp.shutdownCount)\n}\n\nfunc TestBatchSpanProcessorPostShutdown(t *testing.T) {\n\ttp := basicTracerProvider(t)\n\tbe := testBatchExporter{}\n\tbsp := NewBatchSpanProcessor(&be)\n\n\ttp.RegisterSpanProcessor(bsp)\n\ttr := tp.Tracer(\"Normal\")\n\n\tgenerateSpanParallel(t, tr, testOption{\n\t\to: []BatchSpanProcessorOption{\n\t\t\tWithMaxExportBatchSize(50),\n\t\t},\n\t\tgenNumSpans: 60,\n\t})\n\n\trequire.NoError(t, bsp.Shutdown(context.Background()), \"shutting down BatchSpanProcessor\")\n\tlenJustAfterShutdown := be.len()\n\n\t_, span := tr.Start(context.Background(), \"foo\")\n\tspan.End()\n\tassert.NoError(t, bsp.ForceFlush(context.Background()), \"force flushing BatchSpanProcessor\")\n\n\tassert.Equal(t, lenJustAfterShutdown, be.len(), \"OnEnd and ForceFlush should have no effect after Shutdown\")\n}\n\nfunc TestBatchSpanProcessorForceFlushSucceeds(t *testing.T) {\n\tte := testBatchExporter{}\n\ttp := basicTracerProvider(t)\n\toption := testOption{\n\t\tname: \"default BatchSpanProcessorOptions\",\n\t\to: []BatchSpanProcessorOption{\n\t\t\tWithMaxQueueSize(0),\n\t\t\tWithMaxExportBatchSize(3000),\n\t\t},\n\t\twantNumSpans: 2053,\n\t\twantBatchCount: 1,\n\t\tgenNumSpans: 2053,\n\t}\n\tssp := createAndRegisterBatchSP(option, &te)\n\tif ssp == nil {\n\t\tt.Fatalf(\"%s: Error creating new instance of BatchSpanProcessor\\n\", option.name)\n\t}\n\ttp.RegisterSpanProcessor(ssp)\n\ttr := tp.Tracer(\"BatchSpanProcessorWithOption\")\n\tif option.parallel {\n\t\tgenerateSpanParallel(t, tr, option)\n\t} else {\n\t\tgenerateSpan(t, tr, option)\n\t}\n\n\t// Force flush any held span batches\n\terr := ssp.ForceFlush(context.Background())\n\n\tassertMaxSpanDiff(t, te.len(), option.wantNumSpans, 10)\n\n\tgotBatchCount := te.getBatchCount()\n\tif gotBatchCount < option.wantBatchCount {\n\t\tt.Errorf(\"number batches: got %+v, want >= %+v\\n\",\n\t\t\tgotBatchCount, option.wantBatchCount)\n\t\tt.Errorf(\"Batches %v\\n\", te.sizes)\n\t}\n\tassert.NoError(t, err)\n}\n\nfunc TestBatchSpanProcessorDropBatchIfFailed(t *testing.T) {\n\tte := testBatchExporter{\n\t\terrors: []error{errors.New(\"fail to export\")},\n\t}\n\ttp := basicTracerProvider(t)\n\toption := testOption{\n\t\to: []BatchSpanProcessorOption{\n\t\t\tWithMaxQueueSize(0),\n\t\t\tWithMaxExportBatchSize(2000),\n\t\t},\n\t\twantNumSpans: 1000,\n\t\twantBatchCount: 1,\n\t\tgenNumSpans: 1000,\n\t}\n\tssp := createAndRegisterBatchSP(option, &te)\n\tif ssp == nil {\n\t\tt.Fatalf(\"%s: Error creating new instance of BatchSpanProcessor\\n\", option.name)\n\t}\n\ttp.RegisterSpanProcessor(ssp)\n\ttr := tp.Tracer(\"BatchSpanProcessorWithOption\")\n\tif option.parallel {\n\t\tgenerateSpanParallel(t, tr, option)\n\t} else {\n\t\tgenerateSpan(t, tr, option)\n\t}\n\n\t// Force flush any held span batches\n\terr := ssp.ForceFlush(context.Background())\n\tassert.Error(t, err)\n\tassert.EqualError(t, err, \"fail to export\")\n\n\t// First flush will fail, nothing should be exported.\n\tassertMaxSpanDiff(t, te.droppedCount, option.wantNumSpans, 10)\n\tassert.Equal(t, 0, te.len())\n\tassert.Equal(t, 0, te.getBatchCount())\n\n\t// Generate a new batch, this will succeed\n\tif option.parallel {\n\t\tgenerateSpanParallel(t, tr, option)\n\t} else {\n\t\tgenerateSpan(t, tr, option)\n\t}\n\n\t// Force flush any held span batches\n\terr = ssp.ForceFlush(context.Background())\n\tassert.NoError(t, err)\n\n\tassertMaxSpanDiff(t, te.len(), option.wantNumSpans, 10)\n\tgotBatchCount := te.getBatchCount()\n\tif gotBatchCount < option.wantBatchCount {\n\t\tt.Errorf(\"number batches: got %+v, want >= %+v\\n\",\n\t\t\tgotBatchCount, option.wantBatchCount)\n\t\tt.Errorf(\"Batches %v\\n\", te.sizes)\n\t}\n}\n\nfunc assertMaxSpanDiff(t *testing.T, want, got, maxDif int) {\n\tspanDifference := want - got\n\tif spanDifference < 0 {\n\t\tspanDifference *= -1\n\t}\n\tif spanDifference > maxDif {\n\t\tt.Errorf(\"number of exported span not equal to or within %d less than: got %+v, want %+v\\n\",\n\t\t\tmaxDif, got, want)\n\t}\n}\n\ntype indefiniteExporter struct {\n\tstop chan struct{}\n}\n\nfunc newIndefiniteExporter(t *testing.T) indefiniteExporter {\n\te := indefiniteExporter{stop: make(chan struct{})}\n\tt.Cleanup(func() {\n\t\tgo close(e.stop)\n\t})\n\treturn e\n}\n\nfunc (indefiniteExporter) Shutdown(context.Context) error {\n\treturn nil\n}\n\nfunc (e indefiniteExporter) ExportSpans(ctx context.Context, _ []ReadOnlySpan) error {\n\t<-e.stop\n\treturn ctx.Err()\n}\n\nfunc TestBatchSpanProcessorForceFlushCancellation(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\t// Cancel the context\n\tcancel()\n\n\tbsp := NewBatchSpanProcessor(newIndefiniteExporter(t))\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, bsp.Shutdown(context.Background()))\n\t})\n\n\tif got, want := bsp.ForceFlush(ctx), context.Canceled; !errors.Is(got, want) {\n\t\tt.Errorf(\"expected %q error, got %v\", want, got)\n\t}\n}\n\nfunc TestBatchSpanProcessorForceFlushTimeout(t *testing.T) {\n\ttp := basicTracerProvider(t)\n\texp := newIndefiniteExporter(t)\n\tbsp := NewBatchSpanProcessor(exp)\n\ttp.RegisterSpanProcessor(bsp)\n\ttr := tp.Tracer(t.Name())\n\t_, span := tr.Start(context.Background(), \"foo\")\n\tspan.End()\n\n\t// Add timeout to context to test deadline\n\tctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)\n\tdefer cancel()\n\n\tif got, want := bsp.ForceFlush(ctx), context.DeadlineExceeded; !errors.Is(got, want) {\n\t\tt.Errorf(\"expected %q error, got %v\", want, got)\n\t}\n}\n\nfunc TestBatchSpanProcessorForceFlushQueuedSpans(t *testing.T) {\n\tctx := context.Background()\n\n\tvar bp testBatchExporter\n\tbsp := NewBatchSpanProcessor(&bp)\n\ttp := basicTracerProvider(t)\n\ttp.RegisterSpanProcessor(bsp)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, tp.Shutdown(context.Background()))\n\t})\n\n\ttracer := tp.Tracer(\"tracer\")\n\n\tfor i := range 10 {\n\t\t_, span := tracer.Start(ctx, fmt.Sprintf(\"span%d\", i))\n\t\tspan.End()\n\n\t\terr := tp.ForceFlush(ctx)\n\t\tassert.NoError(t, err)\n\n\t\tassert.Len(t, bp.spans, i+1)\n\t}\n}\n\nfunc TestBatchSpanProcessorConcurrentSafe(t *testing.T) {\n\tctx := context.Background()\n\tvar bp testBatchExporter\n\tbsp := NewBatchSpanProcessor(&bp)\n\ttp := basicTracerProvider(t)\n\ttp.RegisterSpanProcessor(bsp)\n\ttr := tp.Tracer(t.Name())\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tgenerateSpan(t, tr, testOption{genNumSpans: 1})\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t_ = bsp.ForceFlush(ctx)\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t_ = bsp.Shutdown(ctx)\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t_ = tp.ForceFlush(ctx)\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t_ = tp.Shutdown(ctx)\n\t}()\n\n\twg.Wait()\n}\n\n// Drop metrics not being tested in this test.\nvar dropSpanMetricsView = sdkmetric.NewView(\n\tsdkmetric.Instrument{\n\t\tName: \"otel.sdk.span.*\",\n\t},\n\tsdkmetric.Stream{Aggregation: sdkmetric.AggregationDrop{}},\n)\n\nfunc TestBatchSpanProcessorMetricsDisabled(t *testing.T) {\n\tt.Setenv(\"OTEL_GO_X_SELF_OBSERVABILITY\", \"false\")\n\ttp := basicTracerProvider(t)\n\treader := sdkmetric.NewManualReader()\n\tmeterProvider := sdkmetric.NewMeterProvider(\n\t\tsdkmetric.WithReader(reader),\n\t\tsdkmetric.WithView(dropSpanMetricsView),\n\t)\n\totel.SetMeterProvider(meterProvider)\n\tme := newBlockingExporter()\n\tt.Cleanup(func() { assert.NoError(t, me.Shutdown(context.Background())) })\n\tbsp := NewBatchSpanProcessor(\n\t\tme,\n\t\t// Make sure timeout doesn't trigger during the test.\n\t\tWithBatchTimeout(time.Hour),\n\t\tWithMaxQueueSize(2),\n\t\tWithMaxExportBatchSize(2),\n\t)\n\ttp.RegisterSpanProcessor(bsp)\n\n\ttr := tp.Tracer(\"TestBatchSpanProcessorMetricsDisabled\")\n\t// Generate 2 spans, which export and block during the export call.\n\tgenerateSpan(t, tr, testOption{genNumSpans: 2})\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\tassert.NoError(t, me.waitForSpans(ctx, 2))\n\n\t// Validate that there are no metrics produced.\n\tgotMetrics := new(metricdata.ResourceMetrics)\n\tassert.NoError(t, reader.Collect(context.Background(), gotMetrics))\n\trequire.Empty(t, gotMetrics.ScopeMetrics)\n\t// Generate 3 spans. 2 fill the queue, and 1 is dropped because the queue is full.\n\tgenerateSpan(t, tr, testOption{genNumSpans: 3})\n\t// Validate that there are no metrics produced.\n\tgotMetrics = new(metricdata.ResourceMetrics)\n\tassert.NoError(t, reader.Collect(context.Background(), gotMetrics))\n\trequire.Empty(t, gotMetrics.ScopeMetrics)\n}\n\nfunc TestBatchSpanProcessorMetrics(t *testing.T) {\n\tt.Setenv(\"OTEL_GO_X_SELF_OBSERVABILITY\", \"true\")\n\ttp := basicTracerProvider(t)\n\treader := sdkmetric.NewManualReader()\n\tmeterProvider := sdkmetric.NewMeterProvider(\n\t\tsdkmetric.WithReader(reader),\n\t\tsdkmetric.WithView(dropSpanMetricsView),\n\t)\n\totel.SetMeterProvider(meterProvider)\n\tme := newBlockingExporter()\n\tt.Cleanup(func() { assert.NoError(t, me.Shutdown(context.Background())) })\n\tbsp := NewBatchSpanProcessor(\n\t\tme,\n\t\t// Make sure timeout doesn't trigger during the test.\n\t\tWithBatchTimeout(time.Hour),\n\t\tWithMaxQueueSize(2),\n\t\tWithMaxExportBatchSize(2),\n\t)\n\tinternalBsp := bsp.(*batchSpanProcessor)\n\ttp.RegisterSpanProcessor(bsp)\n\n\ttr := tp.Tracer(\"TestBatchSpanProcessorMetrics\")\n\t// Generate 2 spans, which export and block during the export call.\n\tgenerateSpan(t, tr, testOption{genNumSpans: 2})\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\tassert.NoError(t, me.waitForSpans(ctx, 2))\n\tassertSelfObsScopeMetrics(t, internalBsp.componentNameAttr, reader,\n\t\texpectMetrics{queueCapacity: 2, queueSize: 0, successProcessed: 2})\n\t// Generate 3 spans. 2 fill the queue, and 1 is dropped because the queue is full.\n\tgenerateSpan(t, tr, testOption{genNumSpans: 3})\n\tassertSelfObsScopeMetrics(t, internalBsp.componentNameAttr, reader,\n\t\texpectMetrics{queueCapacity: 2, queueSize: 2, queueFullProcessed: 1, successProcessed: 2})\n}\n\nfunc TestBatchSpanProcessorBlockingMetrics(t *testing.T) {\n\tt.Setenv(\"OTEL_GO_X_SELF_OBSERVABILITY\", \"true\")\n\ttp := basicTracerProvider(t)\n\treader := sdkmetric.NewManualReader()\n\tmeterProvider := sdkmetric.NewMeterProvider(\n\t\tsdkmetric.WithReader(reader),\n\t\tsdkmetric.WithView(dropSpanMetricsView),\n\t)\n\totel.SetMeterProvider(meterProvider)\n\tme := newBlockingExporter()\n\tt.Cleanup(func() { assert.NoError(t, me.Shutdown(context.Background())) })\n\tbsp := NewBatchSpanProcessor(\n\t\tme,\n\t\t// Use WithBlocking so we can trigger a queueFull using ForceFlush.\n\t\tWithBlocking(),\n\t\t// Make sure timeout doesn't trigger during the test.\n\t\tWithBatchTimeout(time.Hour),\n\t\tWithMaxQueueSize(2),\n\t\tWithMaxExportBatchSize(2),\n\t)\n\tinternalBsp := bsp.(*batchSpanProcessor)\n\ttp.RegisterSpanProcessor(bsp)\n\n\ttr := tp.Tracer(\"TestBatchSpanProcessorBlockingMetrics\")\n\t// Generate 2 spans that are exported to the exporter, which blocks.\n\tgenerateSpan(t, tr, testOption{genNumSpans: 2})\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\tassert.NoError(t, me.waitForSpans(ctx, 2))\n\tassertSelfObsScopeMetrics(t, internalBsp.componentNameAttr, reader,\n\t\texpectMetrics{queueCapacity: 2, queueSize: 0, successProcessed: 2})\n\t// Generate 2 spans to fill the queue.\n\tgenerateSpan(t, tr, testOption{genNumSpans: 2})\n\tgo func() {\n\t\t// Generate a span which blocks because the queue is full.\n\t\tgenerateSpan(t, tr, testOption{genNumSpans: 1})\n\t}()\n\tassertSelfObsScopeMetrics(t, internalBsp.componentNameAttr, reader,\n\t\texpectMetrics{queueCapacity: 2, queueSize: 2, successProcessed: 2})\n\n\t// Use ForceFlush to force the span that is blocking on the full queue to be dropped.\n\tctx, cancel = context.WithTimeout(context.Background(), 10*time.Millisecond)\n\tdefer cancel()\n\tassert.Error(t, tp.ForceFlush(ctx))\n\tassertSelfObsScopeMetrics(t, internalBsp.componentNameAttr, reader,\n\t\texpectMetrics{queueCapacity: 2, queueSize: 2, queueFullProcessed: 1, successProcessed: 2})\n}\n\ntype expectMetrics struct {\n\tqueueCapacity int64\n\tqueueSize int64\n\tsuccessProcessed int64\n\tqueueFullProcessed int64\n}\n\nfunc assertSelfObsScopeMetrics(t *testing.T, componentNameAttr attribute.KeyValue, reader sdkmetric.Reader,\n\texpectation expectMetrics,\n) {\n\tt.Helper()\n\tgotResourceMetrics := new(metricdata.ResourceMetrics)\n\tassert.NoError(t, reader.Collect(context.Background(), gotResourceMetrics))\n\n\tbaseAttrs := attribute.NewSet(\n\t\tsemconv.OTelComponentTypeBatchingSpanProcessor,\n\t\tcomponentNameAttr,\n\t)\n\twantMetrics := []metricdata.Metrics{\n\t\t{\n\t\t\tName: otelconv.SDKProcessorSpanQueueCapacity{}.Name(),\n\t\t\tDescription: otelconv.SDKProcessorSpanQueueCapacity{}.Description(),\n\t\t\tUnit: otelconv.SDKProcessorSpanQueueCapacity{}.Unit(),\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{{Attributes: baseAttrs, Value: expectation.queueCapacity}},\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: false,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: otelconv.SDKProcessorSpanQueueSize{}.Name(),\n\t\t\tDescription: otelconv.SDKProcessorSpanQueueSize{}.Description(),\n\t\t\tUnit: otelconv.SDKProcessorSpanQueueSize{}.Unit(),\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{{Attributes: baseAttrs, Value: expectation.queueSize}},\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: false,\n\t\t\t},\n\t\t},\n\t}\n\n\twantProcessedDataPoints := []metricdata.DataPoint[int64]{}\n\tif expectation.successProcessed > 0 {\n\t\twantProcessedDataPoints = append(wantProcessedDataPoints, metricdata.DataPoint[int64]{\n\t\t\tValue: expectation.successProcessed,\n\t\t\tAttributes: attribute.NewSet(\n\t\t\t\tsemconv.OTelComponentTypeBatchingSpanProcessor,\n\t\t\t\tcomponentNameAttr,\n\t\t\t),\n\t\t})\n\t}\n\tif expectation.queueFullProcessed > 0 {\n\t\twantProcessedDataPoints = append(wantProcessedDataPoints, metricdata.DataPoint[int64]{\n\t\t\tValue: expectation.queueFullProcessed,\n\t\t\tAttributes: attribute.NewSet(\n\t\t\t\tsemconv.OTelComponentTypeBatchingSpanProcessor,\n\t\t\t\tcomponentNameAttr,\n\t\t\t\tsemconv.ErrorTypeKey.String(string(queueFull)),\n\t\t\t),\n\t\t})\n\t}\n\n\tif len(wantProcessedDataPoints) > 0 {\n\t\twantMetrics = append(wantMetrics,\n\t\t\tmetricdata.Metrics{\n\t\t\t\tName: otelconv.SDKProcessorSpanProcessed{}.Name(),\n\t\t\t\tDescription: otelconv.SDKProcessorSpanProcessed{}.Description(),\n\t\t\t\tUnit: otelconv.SDKProcessorSpanProcessed{}.Unit(),\n\t\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\t\tDataPoints: wantProcessedDataPoints,\n\t\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\t\tIsMonotonic: true,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\twantScopeMetric := metricdata.ScopeMetrics{\n\t\tScope: instrumentation.Scope{\n\t\t\tName: \"go.opentelemetry.io/otel/sdk/trace\",\n\t\t\tVersion: sdk.Version(),\n\t\t\tSchemaURL: semconv.SchemaURL,\n\t\t},\n\t\tMetrics: wantMetrics,\n\t}\n\tmetricdatatest.AssertEqual(t, wantScopeMetric, gotResourceMetrics.ScopeMetrics[0], metricdatatest.IgnoreTimestamp())\n}\n\n// blockingExporter blocks until the exported span is removed from the channel.\ntype blockingExporter struct {\n\tshutdown chan struct{}\n\ttotal atomic.Int32\n}\n\nfunc newBlockingExporter() *blockingExporter {\n\te := &blockingExporter{shutdown: make(chan struct{})}\n\treturn e\n}\n\nfunc (e *blockingExporter) Shutdown(ctx context.Context) error {\n\tselect {\n\tcase <-e.shutdown:\n\tdefault:\n\t\tclose(e.shutdown)\n\t}\n\treturn ctx.Err()\n}\n\nfunc (e *blockingExporter) ExportSpans(ctx context.Context, s []ReadOnlySpan) error {\n\te.total.Add(int32(len(s)))\n\t<-e.shutdown\n\treturn ctx.Err()\n}\n\nfunc (e *blockingExporter) waitForSpans(ctx context.Context, n int32) error {\n\t// Wait for all n spans to reach the export call\n\tfor e.total.Load() < n {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"timeout waiting for %d spans to be exported\", n)\n\t\tdefault:\n\t\t\t// So the select will not block\n\t\t}\n\t\truntime.Gosched()\n\t}\n\treturn nil\n}\n"}], "eval": {"test_cmds": ["make test-verbose 2>&1 | tee test-output.log"], "print_cmds": [], "log_parser": "def parser(log: str) -> dict[str, str]:\n import re\n results: dict[str, str] = {}\n # Match lines like: --- PASS: TestName (0.00s) and subtests like --- PASS: Parent/Sub (0.00s)\n pattern = re.compile(r'^\\s*---\\s+(PASS|FAIL|SKIP):\\s+(.+?)(?:\\s+\\(|$)', re.MULTILINE)\n for m in pattern.finditer(log):\n status, name = m.groups()\n status = status.upper()\n if status == \"PASS\":\n results[name.strip()] = \"pass\"\n elif status == \"FAIL\":\n results[name.strip()] = \"fail\"\n elif status == \"SKIP\":\n results[name.strip()] = \"skip\"\n return results", "rebuild_cmds": []}}