Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[chore] enable gofumpt globally #36471

Merged
merged 1 commit into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ linters:
- exhaustive
- gci
- gocritic
- gofmt
- gofumpt
- goimports
- gosec
- govet
Expand Down
5 changes: 3 additions & 2 deletions Makefile.Common
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ CHECKFILE := $(TOOLS_BIN_DIR)/checkfile
CROSSLINK := $(TOOLS_BIN_DIR)/crosslink
GOJUNIT := $(TOOLS_BIN_DIR)/go-junit-report
BUILDER := $(TOOLS_BIN_DIR)/builder
GOFUMPT := $(TOOLS_BIN_DIR)/gofumpt
GOVULNCHECK := $(TOOLS_BIN_DIR)/govulncheck
GCI := $(TOOLS_BIN_DIR)/gci
GOTESTSUM := $(TOOLS_BIN_DIR)/gotestsum
Expand Down Expand Up @@ -207,8 +208,8 @@ checklinks:
$(MDLINKCHECK) -q -c $(SRC_ROOT)/.github/workflows/check_links_config.json || true

.PHONY: fmt
fmt: $(GOIMPORTS)
gofmt -w -s ./
fmt: $(GOFUMPT) $(GOIMPORTS)
$(GOFUMPT) -l -w .
$(GOIMPORTS) -w -local github.com/open-telemetry/opentelemetry-collector-contrib ./

.PHONY: lint
Expand Down
4 changes: 2 additions & 2 deletions cmd/githubgen/codeowners.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,11 +179,11 @@ LOOP:
codeowners += fmt.Sprintf("reports/distributions/%s.yaml%s @open-telemetry/collector-contrib-approvers %s\n", dist.Name, strings.Repeat(" ", longestName-len(dist.Name)), strings.Join(maintainers, " "))
}

err = os.WriteFile(filepath.Join(".github", "CODEOWNERS"), []byte(codeowners+unmaintainedCodeowners), 0600)
err = os.WriteFile(filepath.Join(".github", "CODEOWNERS"), []byte(codeowners+unmaintainedCodeowners), 0o600)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(".github", "ALLOWLIST"), []byte(allowlistHeader+deprecatedList+unmaintainedList), 0600)
err = os.WriteFile(filepath.Join(".github", "ALLOWLIST"), []byte(allowlistHeader+deprecatedList+unmaintainedList), 0o600)
if err != nil {
return err
}
Expand Down
5 changes: 2 additions & 3 deletions cmd/githubgen/distributions.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import (
"gopkg.in/yaml.v3"
)

type distributionsGenerator struct {
}
type distributionsGenerator struct{}

type distOutput struct {
Name string `yaml:"name"`
Expand Down Expand Up @@ -54,7 +53,7 @@ func (cg distributionsGenerator) generate(data *githubData) error {
if err != nil {
return nil
}
err = os.WriteFile(filepath.Join("reports", "distributions", fmt.Sprintf("%s.yaml", dist.Name)), b, 0600)
err = os.WriteFile(filepath.Join("reports", "distributions", fmt.Sprintf("%s.yaml", dist.Name)), b, 0o600)
if err != nil {
return nil
}
Expand Down
5 changes: 2 additions & 3 deletions cmd/githubgen/issuetemplates.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ func folderToShortName(folder string) string {
return strings.Join(path, "/")
}

type issueTemplatesGenerator struct {
}
type issueTemplatesGenerator struct{}

func (itg issueTemplatesGenerator) generate(data *githubData) error {
keys := map[string]struct{}{}
Expand All @@ -59,7 +58,7 @@ func (itg issueTemplatesGenerator) generate(data *githubData) error {
oldContent := matchOldContent.FindSubmatch(templateContents)
if len(oldContent) > 0 {
templateContents = bytes.ReplaceAll(templateContents, oldContent[0], replacement)
err = os.WriteFile(filepath.Join(issuesFolder, e.Name()), templateContents, 0600)
err = os.WriteFile(filepath.Join(issuesFolder, e.Name()), templateContents, 0o600)
if err != nil {
return err
}
Expand Down
11 changes: 2 additions & 9 deletions cmd/opampsupervisor/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ func TestSupervisorStartsCollectorWithNoOpAMPServer(t *testing.T) {
marshalledRemoteConfig, err := proto.Marshal(remoteConfigProto)
require.NoError(t, err)

require.NoError(t, os.WriteFile(remoteConfigFilePath, marshalledRemoteConfig, 0600))
require.NoError(t, os.WriteFile(remoteConfigFilePath, marshalledRemoteConfig, 0o600))

connected := atomic.Bool{}
server := newUnstartedOpAMPServer(t, defaultConnectingHandler, server.ConnectionCallbacksStruct{
Expand Down Expand Up @@ -407,7 +407,6 @@ func TestSupervisorStartsWithNoOpAMPServer(t *testing.T) {

return n != 0
}, 10*time.Second, 500*time.Millisecond, "Log never appeared in output")

}

func TestSupervisorRestartsCollectorAfterBadConfig(t *testing.T) {
Expand Down Expand Up @@ -1077,7 +1076,6 @@ func TestSupervisorRestartsWithLastReceivedConfig(t *testing.T) {

return strings.Contains(loadedConfig, "filelog")
}, 10*time.Second, 500*time.Millisecond, "Collector was not started with the last received remote config")

}

func TestSupervisorPersistsInstanceID(t *testing.T) {
Expand All @@ -1091,7 +1089,6 @@ func TestSupervisorPersistsInstanceID(t *testing.T) {
defaultConnectingHandler,
server.ConnectionCallbacksStruct{
OnMessageFunc: func(_ context.Context, _ types.Connection, message *protobufs.AgentToServer) *protobufs.ServerToAgent {

select {
case agentIDChan <- message.InstanceUid:
default:
Expand Down Expand Up @@ -1168,7 +1165,6 @@ func TestSupervisorPersistsNewInstanceID(t *testing.T) {
defaultConnectingHandler,
server.ConnectionCallbacksStruct{
OnMessageFunc: func(_ context.Context, _ types.Connection, message *protobufs.AgentToServer) *protobufs.ServerToAgent {

select {
case agentIDChan <- message.InstanceUid:
default:
Expand Down Expand Up @@ -1359,7 +1355,6 @@ func TestSupervisorStopsAgentProcessWithEmptyConfigMap(t *testing.T) {
} else {
require.ErrorContains(t, err, "No connection could be made")
}

}

type LogEntry struct {
Expand Down Expand Up @@ -1387,7 +1382,7 @@ func TestSupervisorLogging(t *testing.T) {
}
marshalledRemoteCfg, err := proto.Marshal(remoteCfgProto)
require.NoError(t, err)
require.NoError(t, os.WriteFile(remoteCfgFilePath, marshalledRemoteCfg, 0600))
require.NoError(t, os.WriteFile(remoteCfgFilePath, marshalledRemoteCfg, 0o600))

connected := atomic.Bool{}
server := newUnstartedOpAMPServer(t, defaultConnectingHandler, server.ConnectionCallbacksStruct{
Expand Down Expand Up @@ -1635,15 +1630,13 @@ func TestSupervisorOpAmpServerPort(t *testing.T) {

func findRandomPort() (int, error) {
l, err := net.Listen("tcp", "localhost:0")

if err != nil {
return 0, err
}

port := l.Addr().(*net.TCPAddr).Port

err = l.Close()

if err != nil {
return 0, err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/opampsupervisor/supervisor/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ func TestValidate(t *testing.T) {
tmpDir := t.TempDir()

filePath := filepath.Join(tmpDir, "file")
require.NoError(t, os.WriteFile(filePath, []byte{}, 0600))
require.NoError(t, os.WriteFile(filePath, []byte{}, 0o600))

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion cmd/opampsupervisor/supervisor/persistence.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (p *persistentState) writeState() error {
return err
}

return os.WriteFile(p.configPath, by, 0600)
return os.WriteFile(p.configPath, by, 0o600)
}

// loadOrCreatePersistentState attempts to load the persistent state from disk. If it doesn't
Expand Down
2 changes: 1 addition & 1 deletion cmd/opampsupervisor/supervisor/persistence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func TestCreateOrLoadPersistentState(t *testing.T) {
t.Run("loads state from file if it exists", func(t *testing.T) {
f := filepath.Join(t.TempDir(), "state.yaml")

err := os.WriteFile(f, []byte(`instance_id: "018feed6-905b-7aa6-ba37-b0eec565de03"`), 0600)
err := os.WriteFile(f, []byte(`instance_id: "018feed6-905b-7aa6-ba37-b0eec565de03"`), 0o600)
require.NoError(t, err)

state, err := loadOrCreatePersistentState(f)
Expand Down
27 changes: 9 additions & 18 deletions cmd/opampsupervisor/supervisor/supervisor.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ func NewSupervisor(logger *zap.Logger, cfg config.Supervisor) (*Supervisor, erro
}
s.config = cfg

if err := os.MkdirAll(s.config.Storage.Directory, 0700); err != nil {
if err := os.MkdirAll(s.config.Storage.Directory, 0o700); err != nil {
return nil, fmt.Errorf("error creating storage dir: %w", err)
}

Expand All @@ -203,7 +203,6 @@ func (s *Supervisor) Start() error {
healthCheckPort := s.config.Agent.HealthCheckPort
if healthCheckPort == 0 {
healthCheckPort, err = s.findRandomPort()

if err != nil {
return fmt.Errorf("could not find port for health check: %w", err)
}
Expand Down Expand Up @@ -285,7 +284,7 @@ func (s *Supervisor) getBootstrapInfo() (err error) {
return err
}

err = os.WriteFile(s.agentConfigFilePath(), bootstrapConfig, 0600)
err = os.WriteFile(s.agentConfigFilePath(), bootstrapConfig, 0o600)
if err != nil {
return fmt.Errorf("failed to write agent config: %w", err)
}
Expand Down Expand Up @@ -708,7 +707,7 @@ func (s *Supervisor) composeNoopPipeline() ([]byte, error) {
}

func (s *Supervisor) composeNoopConfig() ([]byte, error) {
var k = koanf.New("::")
k := koanf.New("::")

cfg, err := s.composeNoopPipeline()
if err != nil {
Expand Down Expand Up @@ -821,7 +820,7 @@ func (s *Supervisor) loadAndWriteInitialMergedConfig() error {

// write the initial merged config to disk
cfgState := s.cfgState.Load().(*configState)
if err := os.WriteFile(s.agentConfigFilePath(), []byte(cfgState.mergedConfig), 0600); err != nil {
if err := os.WriteFile(s.agentConfigFilePath(), []byte(cfgState.mergedConfig), 0o600); err != nil {
s.logger.Error("Failed to write agent config.", zap.Error(err))
}

Expand Down Expand Up @@ -861,7 +860,6 @@ func (s *Supervisor) setupOwnMetrics(_ context.Context, settings *protobufs.Tele
s.logger.Debug("Enabling own metrics pipeline in the config")

port, err := s.findRandomPort()

if err != nil {
s.logger.Error("Could not setup own metrics", zap.Error(err))
return
Expand Down Expand Up @@ -896,7 +894,7 @@ func (s *Supervisor) setupOwnMetrics(_ context.Context, settings *protobufs.Tele
// 2) the own metrics config section
// 3) the local override config that is hard-coded in the Supervisor.
func (s *Supervisor) composeMergedConfig(config *protobufs.AgentRemoteConfig) (configChanged bool, err error) {
var k = koanf.New("::")
k := koanf.New("::")

configMapIsEmpty := len(config.GetConfig().GetConfigMap()) == 0

Expand Down Expand Up @@ -924,7 +922,7 @@ func (s *Supervisor) composeMergedConfig(config *protobufs.AgentRemoteConfig) (c
if item == nil {
continue
}
var k2 = koanf.New("::")
k2 := koanf.New("::")
err = k2.Load(rawbytes.Provider(item.Body), yaml.Parser())
if err != nil {
return false, fmt.Errorf("cannot parse config named %s: %w", name, err)
Expand Down Expand Up @@ -1010,7 +1008,6 @@ func (s *Supervisor) startAgent() {
if err != nil {
s.logger.Error("Cannot start the agent", zap.Error(err))
err = s.opampClient.SetHealth(&protobufs.ComponentHealth{Healthy: false, LastError: fmt.Sprintf("Cannot start the agent: %v", err)})

if err != nil {
s.logger.Error("Failed to report OpAMP client health", zap.Error(err))
}
Expand Down Expand Up @@ -1128,7 +1125,6 @@ func (s *Supervisor) runAgentProcess() {
s.commander.Pid(), s.commander.ExitCode(),
)
err := s.opampClient.SetHealth(&protobufs.ComponentHealth{Healthy: false, LastError: errMsg})

if err != nil {
s.logger.Error("Could not report health to OpAMP server", zap.Error(err))
}
Expand Down Expand Up @@ -1173,12 +1169,11 @@ func (s *Supervisor) stopAgentApplyConfig() {
s.logger.Debug("Stopping the agent to apply new config")
cfgState := s.cfgState.Load().(*configState)
err := s.commander.Stop(context.Background())

if err != nil {
s.logger.Error("Could not stop agent process", zap.Error(err))
}

if err := os.WriteFile(s.agentConfigFilePath(), []byte(cfgState.mergedConfig), 0600); err != nil {
if err := os.WriteFile(s.agentConfigFilePath(), []byte(cfgState.mergedConfig), 0o600); err != nil {
s.logger.Error("Failed to write agent config.", zap.Error(err))
}
}
Expand Down Expand Up @@ -1210,13 +1205,11 @@ func (s *Supervisor) Shutdown() {
Healthy: false, LastError: "Supervisor is shutdown",
},
)

if err != nil {
s.logger.Error("Could not report health to OpAMP server", zap.Error(err))
}

err = s.stopOpAMPClient()

if err != nil {
s.logger.Error("Could not stop the OpAMP client", zap.Error(err))
}
Expand All @@ -1233,7 +1226,7 @@ func (s *Supervisor) saveLastReceivedConfig(config *protobufs.AgentRemoteConfig)
return err
}

return os.WriteFile(filepath.Join(s.config.Storage.Directory, lastRecvRemoteConfigFile), cfg, 0600)
return os.WriteFile(filepath.Join(s.config.Storage.Directory, lastRecvRemoteConfigFile), cfg, 0o600)
}

func (s *Supervisor) saveLastReceivedOwnTelemetrySettings(set *protobufs.TelemetryConnectionSettings, filePath string) error {
Expand All @@ -1242,7 +1235,7 @@ func (s *Supervisor) saveLastReceivedOwnTelemetrySettings(set *protobufs.Telemet
return err
}

return os.WriteFile(filepath.Join(s.config.Storage.Directory, filePath), cfg, 0600)
return os.WriteFile(filepath.Join(s.config.Storage.Directory, filePath), cfg, 0o600)
}

func (s *Supervisor) reportConfigStatus(status protobufs.RemoteConfigStatuses, errorMessage string) {
Expand Down Expand Up @@ -1392,15 +1385,13 @@ func (s *Supervisor) getSupervisorOpAMPServerPort() (int, error) {

func (s *Supervisor) findRandomPort() (int, error) {
l, err := net.Listen("tcp", "localhost:0")

if err != nil {
return 0, err
}

port := l.Addr().(*net.TCPAddr).Port

err = l.Close()

if err != nil {
return 0, err
}
Expand Down
6 changes: 4 additions & 2 deletions cmd/opampsupervisor/supervisor/supervisor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1042,12 +1042,14 @@ type mockConn struct {
func (mockConn) Connection() net.Conn {
return nil
}

func (m mockConn) Send(ctx context.Context, message *protobufs.ServerToAgent) error {
if m.sendFunc != nil {
return m.sendFunc(ctx, message)
}
return nil
}

func (mockConn) Disconnect() error {
return nil
}
Expand Down Expand Up @@ -1273,8 +1275,8 @@ service:
marshalledOwnMetricsCfg, err := proto.Marshal(ownMetricsCfg)
require.NoError(t, err)

require.NoError(t, os.WriteFile(filepath.Join(configDir, lastRecvRemoteConfigFile), marshalledRemoteCfg, 0600))
require.NoError(t, os.WriteFile(filepath.Join(configDir, lastRecvOwnMetricsConfigFile), marshalledOwnMetricsCfg, 0600))
require.NoError(t, os.WriteFile(filepath.Join(configDir, lastRecvRemoteConfigFile), marshalledRemoteCfg, 0o600))
require.NoError(t, os.WriteFile(filepath.Join(configDir, lastRecvOwnMetricsConfigFile), marshalledOwnMetricsCfg, 0o600))

s := Supervisor{
logger: zap.NewNop(),
Expand Down
2 changes: 1 addition & 1 deletion cmd/telemetrygen/internal/traces/exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func TestHTTPExporterOptions_TLS(t *testing.T) {
err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: srv.TLS.Certificates[0].Certificate[0],
}), 0600)
}), 0o600)
require.NoError(t, err)
cfg.CaFile = caFile
}
Expand Down
1 change: 0 additions & 1 deletion confmap/provider/secretsmanagerprovider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ func (provider *provider) Retrieve(ctx context.Context, uri string, _ confmap.Wa
// initialize the secrets manager client in the first call of Retrieve
if provider.client == nil {
cfg, err := config.LoadDefaultConfig(ctx)

if err != nil {
return nil, fmt.Errorf("failed to load configurations to initialize an AWS SDK client, error: %w", err)
}
Expand Down
3 changes: 2 additions & 1 deletion confmap/provider/secretsmanagerprovider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ type testSecretManagerClient struct {

// Implement GetSecretValue()
func (client *testSecretManagerClient) GetSecretValue(_ context.Context, _ *secretsmanager.GetSecretValueInput,
_ ...func(*secretsmanager.Options)) (*secretsmanager.GetSecretValueOutput, error) {
_ ...func(*secretsmanager.Options),
) (*secretsmanager.GetSecretValueOutput, error) {
return &secretsmanager.GetSecretValueOutput{SecretString: &client.secretValue}, nil
}

Expand Down
2 changes: 1 addition & 1 deletion internal/tools/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ require (
golang.org/x/tools v0.26.0
golang.org/x/vuln v1.1.3
gotest.tools/gotestsum v1.12.0
mvdan.cc/gofumpt v0.6.0
)

require (
Expand Down Expand Up @@ -257,7 +258,6 @@ require (
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
honnef.co/go/tools v0.4.7 // indirect
mvdan.cc/gofumpt v0.6.0 // indirect
mvdan.cc/unparam v0.0.0-20240528143540-8a5130ca722f // indirect
)

Expand Down
Loading