Skip to content

Commit

Permalink
chore: enable early-return from revive
Browse files Browse the repository at this point in the history
Signed-off-by: Matthieu MOREL <[email protected]>
  • Loading branch information
mmorel-35 committed Jan 9, 2025
1 parent cc19e6b commit 36350ff
Show file tree
Hide file tree
Showing 24 changed files with 122 additions and 139 deletions.
5 changes: 5 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ linters-settings:
- name: context-keys-type
# Importing with `.` makes the programs much harder to understand
- name: dot-imports
- name: early-return
arguments:
- "preserveScope"
# Empty blocks make code less readable and could be a symptom of a bug or unfinished refactoring.
- name: empty-block
# for better readability, variables of type `error` must be named with the prefix `err`.
Expand All @@ -111,6 +114,8 @@ linters-settings:
- name: redefines-builtin-id
# redundant else-blocks that can be eliminated from the code.
- name: superfluous-else
arguments:
- "preserveScope"
# prevent confusing name for variables when using `time` package
- name: time-naming
# warns when an exported function or method returns a value of an un-exported type.
Expand Down
5 changes: 2 additions & 3 deletions confmap/provider/aesprovider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,12 @@ func TestAESCredentialProvider(t *testing.T) {

p := NewFactory().Create(confmap.ProviderSettings{})
retrieved, err := p.Retrieve(context.Background(), tt.configValue, nil)
if tt.expectedError == "" {
require.NoError(t, err)
} else {
if tt.expectedError != "" {
require.Error(t, err)
require.Equal(t, tt.expectedError, err.Error())
return
}
require.NoError(t, err)
require.NotNil(t, retrieved)
stringValue, err := retrieved.AsString()
require.NoError(t, err)
Expand Down
20 changes: 8 additions & 12 deletions exporter/datadogexporter/metrics_exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,20 +371,18 @@ func Test_metricsExporter_PushMetricsData(t *testing.T) {
reporter,
nil,
)
if tt.expectedErr == nil {
assert.NoError(t, err, "unexpected error")
} else {
if tt.expectedErr != nil {
assert.Equal(t, tt.expectedErr, err, "expected error doesn't match")
return
}
assert.NoError(t, err, "unexpected error")
exp.getPushTime = func() uint64 { return 0 }
err = exp.PushMetricsData(context.Background(), tt.metrics)
if tt.expectedErr == nil {
assert.NoError(t, err, "unexpected error")
} else {
if tt.expectedErr != nil {
assert.Equal(t, tt.expectedErr, err, "expected error doesn't match")
return
}
assert.NoError(t, err, "unexpected error")
if len(tt.expectedSeries) == 0 {
assert.Nil(t, seriesRecorder.ByteBody)
} else {
Expand Down Expand Up @@ -815,20 +813,18 @@ func Test_metricsExporter_PushMetricsData_Zorkian(t *testing.T) {
reporter,
nil,
)
if tt.expectedErr == nil {
assert.NoError(t, err, "unexpected error")
} else {
if tt.expectedErr != nil {
assert.Equal(t, tt.expectedErr, err, "expected error doesn't match")
return
}
assert.NoError(t, err, "unexpected error")
exp.getPushTime = func() uint64 { return 0 }
err = exp.PushMetricsData(context.Background(), tt.metrics)
if tt.expectedErr == nil {
assert.NoError(t, err, "unexpected error")
} else {
if tt.expectedErr != nil {
assert.Equal(t, tt.expectedErr, err, "expected error doesn't match")
return
}
assert.NoError(t, err, "unexpected error")
if len(tt.expectedSeries) == 0 {
assert.Nil(t, seriesRecorder.ByteBody)
} else {
Expand Down
5 changes: 2 additions & 3 deletions exporter/datasetexporter/datasetexporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,11 @@ func updateWithPrefixedValues(target map[string]any, prefix string, separator st
// now the last value wins
// Should the first value win?
_, found := target[prefix]
if found && len(suffix) > 0 {
prefix += suffix
} else {
if !found || len(suffix) == 0 {
target[prefix] = source
break
}
prefix += suffix
}
}

Expand Down
31 changes: 15 additions & 16 deletions exporter/honeycombmarkerexporter/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,24 +64,23 @@ func (cfg *Config) Validate() error {
return fmt.Errorf("invalid API Key")
}

if len(cfg.Markers) != 0 {
for _, m := range cfg.Markers {
if m.Type == "" {
return fmt.Errorf("marker must have a type %v", m)
}

if len(m.Rules.LogConditions) == 0 {
return fmt.Errorf("marker must have rules %v", m)
}

_, err := filterottl.NewBoolExprForLog(m.Rules.LogConditions, filterottl.StandardLogFuncs(), ottl.PropagateError, component.TelemetrySettings{Logger: zap.NewNop()})
if err != nil {
return err
}
}
} else {
if len(cfg.Markers) == 0 {
return fmt.Errorf("no markers supplied")
}
for _, m := range cfg.Markers {
if m.Type == "" {
return fmt.Errorf("marker must have a type %v", m)
}

if len(m.Rules.LogConditions) == 0 {
return fmt.Errorf("marker must have rules %v", m)
}

_, err := filterottl.NewBoolExprForLog(m.Rules.LogConditions, filterottl.StandardLogFuncs(), ottl.PropagateError, component.TelemetrySettings{Logger: zap.NewNop()})
if err != nil {
return err
}
}

return nil
}
Expand Down
7 changes: 3 additions & 4 deletions exporter/prometheusexporter/accumulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,15 +261,14 @@ func (a *lastValueAccumulator) accumulateHistogram(metric pmetric.Metric, il pco
zap.String("pp_timestamp", pp.Timestamp().String()),
zap.String("ip_timestamp", ip.Timestamp().String()),
).Warn("Misaligned starting timestamps")
if ip.StartTimestamp().AsTime().After(pp.Timestamp().AsTime()) {
a.logger.Debug("treating it like reset")
ip.CopyTo(m.Histogram().DataPoints().AppendEmpty())
} else {
if !ip.StartTimestamp().AsTime().After(pp.Timestamp().AsTime()) {
a.logger.With(
zap.String("metric_name", metric.Name()),
).Warn("Dropped misaligned histogram datapoint")
continue
}
a.logger.Debug("treating it like reset")
ip.CopyTo(m.Histogram().DataPoints().AppendEmpty())
} else {
a.logger.Debug("Accumulate another histogram datapoint")
accumulateHistogramValues(pp, ip, m.Histogram().DataPoints().AppendEmpty())
Expand Down
5 changes: 2 additions & 3 deletions exporter/signalfxexporter/internal/correlation/correlation.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,11 @@ func (cor *Tracker) ProcessTraces(ctx context.Context, traces ptrace.Traces) err
res := traces.ResourceSpans().At(0).Resource()
hostID, ok := splunk.ResourceToHostID(res)

if ok {
cor.log.Info("Detected host resource ID for correlation", zap.Any("hostID", hostID))
} else {
if !ok {
cor.log.Warn("Unable to determine host resource ID for correlation syncing")
return
}
cor.log.Info("Detected host resource ID for correlation", zap.Any("hostID", hostID))

hostDimension := string(hostID.Key)

Expand Down
6 changes: 3 additions & 3 deletions exporter/sumologicexporter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,12 +390,12 @@ func (se *sumologicexporter) handleUnauthorizedErrors(ctx context.Context, errs
for _, err := range errs {
if errors.Is(err, errUnauthorized) {
se.logger.Warn("Received unauthorized status code, triggering reconfiguration")
if errC := se.configure(ctx); errC != nil {
se.logger.Error("Error configuring the exporter with new credentials", zap.Error(err))
} else {
errC := se.configure(ctx)
if errC == nil {
// It's enough to successfully reconfigure the exporter just once.
return
}
se.logger.Error("Error configuring the exporter with new credentials", zap.Error(err))
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions internal/aws/metrics/metric_calculator.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@ func NewFloat64DeltaCalculator() MetricCalculator {

func calculateDelta(prev *MetricValue, val any, _ time.Time) (any, bool) {
var deltaValue float64
if prev != nil {
deltaValue = val.(float64) - prev.RawValue.(float64)
} else {
if prev == nil {
return deltaValue, false
}
deltaValue = val.(float64) - prev.RawValue.(float64)
return deltaValue, true
}

Expand Down
5 changes: 2 additions & 3 deletions internal/sqlquery/scraper.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,10 @@ func (s *Scraper) ScrapeMetrics(ctx context.Context) (pmetric.Metrics, error) {
out := pmetric.NewMetrics()
rows, err := s.Client.QueryRows(ctx)
if err != nil {
if errors.Is(err, ErrNullValueWarning) {
s.Logger.Warn("problems encountered getting metric rows", zap.Error(err))
} else {
if !errors.Is(err, ErrNullValueWarning) {
return out, fmt.Errorf("Scraper: %w", err)
}
s.Logger.Warn("problems encountered getting metric rows", zap.Error(err))
}
ts := pcommon.NewTimestampFromTime(time.Now())
rms := out.ResourceMetrics()
Expand Down
6 changes: 3 additions & 3 deletions pkg/stanza/entry/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,11 @@ func (entry *Entry) readToStringMap(field FieldInterface, dest *map[string]strin
case map[string]any:
newDest := make(map[string]string)
for k, v := range m {
if vStr, ok := v.(string); ok {
newDest[k] = vStr
} else {
vStr, ok := v.(string)
if !ok {
return fmt.Errorf("can not cast map members '%s' of type '%s' to string", k, v)
}
newDest[k] = vStr
}
*dest = newDest
case map[any]any:
Expand Down
17 changes: 8 additions & 9 deletions receiver/awscontainerinsightreceiver/internal/stores/podstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,17 @@ func (p *PodStore) Decorate(ctx context.Context, metric CIMetric, kubernetesBlob
}

// If the entry is not a placeholder, decorate the pod
if entry.pod.Name != "" {
p.decorateCPU(metric, &entry.pod)
p.decorateMem(metric, &entry.pod)
p.addStatus(metric, &entry.pod)
addContainerCount(metric, &entry.pod)
addContainerID(&entry.pod, metric, kubernetesBlob, p.logger)
p.addPodOwnersAndPodName(metric, &entry.pod, kubernetesBlob)
addLabels(&entry.pod, kubernetesBlob)
} else {
if entry.pod.Name == "" {
p.logger.Warn("no pod information is found in podstore for pod " + podKey)
return false
}
p.decorateCPU(metric, &entry.pod)
p.decorateMem(metric, &entry.pod)
p.addStatus(metric, &entry.pod)
addContainerCount(metric, &entry.pod)
addContainerID(&entry.pod, metric, kubernetesBlob, p.logger)
p.addPodOwnersAndPodName(metric, &entry.pod, kubernetesBlob)
addLabels(&entry.pod, kubernetesBlob)
}
return true
}
Expand Down
6 changes: 3 additions & 3 deletions receiver/awss3receiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,11 @@ func newEncodingExtensions(encodingsConfig []Encoding, host component.Host) (enc
encodings := make(encodingExtensions, 0)
extensions := host.GetExtensions()
for _, configItem := range encodingsConfig {
if e, ok := extensions[configItem.Extension]; ok {
encodings = append(encodings, encodingExtension{extension: e, suffix: configItem.Suffix})
} else {
e, ok := extensions[configItem.Extension]
if !ok {
return nil, fmt.Errorf("extension %q not found", configItem.Extension)
}
encodings = append(encodings, encodingExtension{extension: e, suffix: configItem.Suffix})
}
return encodings, nil
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,11 @@ func (r azureResourceMetricsUnmarshaler) UnmarshalMetrics(event *eventhub.Event)
}

var startTimestamp pcommon.Timestamp
if azureMetric.TimeGrain == "PT1M" {
startTimestamp = pcommon.NewTimestampFromTime(nanos.AsTime().Add(-time.Minute))
} else {
if azureMetric.TimeGrain != "PT1M" {
r.logger.Warn("Unhandled Time Grain", zap.String("timegrain", azureMetric.TimeGrain))
continue
}
startTimestamp = pcommon.NewTimestampFromTime(nanos.AsTime().Add(-time.Minute))

metricTotal := metrics.AppendEmpty()
metricTotal.SetName(strings.ToLower(fmt.Sprintf("%s_%s", strings.ReplaceAll(azureMetric.MetricName, " ", "_"), "Total")))
Expand Down
5 changes: 2 additions & 3 deletions receiver/cloudfoundryreceiver/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@ type authorizationProvider struct {

func (ap *authorizationProvider) Do(request *http.Request) (*http.Response, error) {
token, err := ap.authTokenProvider.ProvideToken()
if err == nil {
request.Header.Set("Authorization", token)
} else {
if err != nil {
ap.logger.Error("fetching authentication token", zap.Error(err))
return nil, errors.New("obtaining authentication token for the request")
}
request.Header.Set("Authorization", token)

return ap.client.Do(request)
}
12 changes: 6 additions & 6 deletions receiver/kubeletstatsreceiver/internal/kubelet/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ var supportedLabels = map[MetadataLabel]bool{
func ValidateMetadataLabelsConfig(labels []MetadataLabel) error {
labelsFound := map[MetadataLabel]bool{}
for _, label := range labels {
if _, supported := supportedLabels[label]; supported {
if _, duplicate := labelsFound[label]; duplicate {
return fmt.Errorf("duplicate metadata label: %q", label)
}
labelsFound[label] = true
} else {
_, supported := supportedLabels[label]
if !supported {
return fmt.Errorf("label %q is not supported", label)
}
if _, duplicate := labelsFound[label]; duplicate {
return fmt.Errorf("duplicate metadata label: %q", label)
}
labelsFound[label] = true
}
return nil
}
Expand Down
6 changes: 3 additions & 3 deletions receiver/prometheusreceiver/internal/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,13 +198,13 @@ func (t *transaction) getOrCreateMetricFamily(key resourceKey, scope scopeID, mn
if _, ok := t.mc.GetMetadata(mn); !ok {
fn = normalizeMetricName(mn)
}
if mf, ok := t.families[key][scope][fn]; ok && mf.includesMetric(mn) {
curMf = mf
} else {
mf, ok := t.families[key][scope][fn]
if !ok || !mf.includesMetric(mn) {
curMf = newMetricFamily(mn, t.mc, t.logger)
t.families[key][scope][curMf.name] = curMf
return curMf, false
}
curMf = mf
}
return curMf, true
}
Expand Down
9 changes: 4 additions & 5 deletions receiver/saphanareceiver/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,12 @@ func (q *queryStat) collectStat(s *sapHanaScraper, m *monitoringQuery, now pcomm
return fmt.Errorf("unable to parse metric for key %s: %w", q.key, err)
}

if q.addMetricFunction != nil {
if err = q.addMetricFunction(mb, now, val, row); err != nil {
return fmt.Errorf("failed to record metric for key %s: %w", q.key, err)
}
} else {
if q.addMetricFunction == nil {
return errors.New("incorrectly configured query, addMetricFunction must be provided")
}
if err = q.addMetricFunction(mb, now, val, row); err != nil {
return fmt.Errorf("failed to record metric for key %s: %w", q.key, err)
}
}
return nil
}
Expand Down
Loading

0 comments on commit 36350ff

Please sign in to comment.