Skip to content

Commit eb9246f

Browse files
refactor: Reduce nesting
1 parent 3054cba commit eb9246f

20 files changed

Lines changed: 271 additions & 238 deletions

File tree

build/ci/golangci.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,6 @@ linters:
148148
misspell:
149149
ignore-rules:
150150
- Statuser
151-
nestif:
152-
min-complexity: 6
153151
staticcheck:
154152
checks:
155153
- all

internal/pkg/diff/diff.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -95,21 +95,21 @@ func (d *Differ) Diff() (*Results, error) {
9595
result, err := d.diffState(objectState)
9696
if err != nil {
9797
d.errors.Append(err)
98-
} else {
99-
if result.State != ResultEqual {
100-
results.Equal = false
101-
}
102-
if result.State == ResultNotEqual {
103-
results.HasNotEqualResult = true
104-
}
105-
if result.State != ResultOnlyInRemote {
106-
results.HasOnlyInRemoteResult = true
107-
}
108-
if result.State != ResultOnlyInLocal {
109-
results.HasOnlyInLocalResult = true
110-
}
111-
d.results = append(d.results, result)
98+
continue
99+
}
100+
if result.State != ResultEqual {
101+
results.Equal = false
102+
}
103+
if result.State == ResultNotEqual {
104+
results.HasNotEqualResult = true
105+
}
106+
if result.State != ResultOnlyInRemote {
107+
results.HasOnlyInRemoteResult = true
108+
}
109+
if result.State != ResultOnlyInLocal {
110+
results.HasOnlyInLocalResult = true
112111
}
112+
d.results = append(d.results, result)
113113
}
114114

115115
// Sort results

internal/pkg/mapper/variables/local_persist.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ func (m *variablesMapper) AfterLocalOperation(_ context.Context, changes *model.
6464
if component.IsVariables() {
6565
configs[config.ConfigKey] = true
6666
}
67-
} else if row, ok := object.(*model.ConfigRow); ok {
67+
continue
68+
}
69+
if row, ok := object.(*model.ConfigRow); ok {
6870
// Variables values row?
6971
component, err := m.state.Components().GetOrErr(row.ComponentID)
7072
if err != nil {

internal/pkg/platform/schema/compiler/extension/primarykey/generatekey.go

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,18 @@ func GenerateKeys(config *gen.Config) error {
3535
// Create Go file with a key struct for each schema
3636
for _, schema := range graph.Schemas {
3737
for _, field := range schema.Fields {
38-
if field.Name == "id" {
39-
if asMap, ok := field.Annotations[pkAnnotationName]; ok {
40-
// asMap is PKAnnotation type serialized to a map
41-
pkAnnotation := PKAnnotation{}
42-
if err := json.ConvertByJSON(asMap, &pkAnnotation); err != nil {
43-
return err
44-
}
45-
if err := generateKey(targetDir, schema, pkAnnotation); err != nil {
46-
return err
47-
}
38+
if field.Name != "id" {
39+
continue
40+
}
41+
42+
if asMap, ok := field.Annotations[pkAnnotationName]; ok {
43+
// asMap is PKAnnotation type serialized to a map
44+
pkAnnotation := PKAnnotation{}
45+
if err := json.ConvertByJSON(asMap, &pkAnnotation); err != nil {
46+
return err
47+
}
48+
if err := generateKey(targetDir, schema, pkAnnotation); err != nil {
49+
return err
4850
}
4951
}
5052
}

internal/pkg/service/appsproxy/dataapps/appconfig/appconfig.go

Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -82,51 +82,51 @@ func (l *loader) GetConfig(ctx context.Context, appID api.AppID) (out api.AppCon
8282
// Send API request with cached eTag.
8383
// At first, the item.config.ETag() is empty string.
8484
newConfig, err := l.api.GetAppConfig(appID, item.config.ETag()).Send(ctx)
85-
if err != nil {
86-
// The config hasn't been modified, extend expiration, return cached version
87-
notModifierErr := api.NotModifiedError{}
88-
if errors.As(err, &notModifierErr) {
89-
item.ExtendExpiration(now, notModifierErr.MaxAge)
90-
return item.config, false, nil
91-
}
85+
if err == nil {
86+
// Cache the loaded configuration
87+
item.config = *newConfig
88+
item.ExtendExpiration(now, item.config.MaxAge())
89+
return item.config, true, nil
90+
}
9291

93-
// Only the not found error is expected
94-
var apiErr *api.Error
95-
if errors.As(err, &apiErr) && apiErr.StatusCode() != http.StatusNotFound {
96-
// Log other errors
97-
l.logger.Errorf(ctx, `unable to load configuration for application "%s": %s`, appID, err.Error())
98-
99-
// Keep the proxy running for a limited time in case of an API outage.
100-
// The item.expiresAt may be zero, if there is no cached version, then the condition is skipped.
101-
if now.Before(item.expiresAt.Add(staleCacheFallbackDuration)) {
102-
l.logger.Warnf(ctx, `using stale cache for app "%s": %s`, appID, err.Error())
103-
return item.config, false, nil
104-
}
105-
}
92+
// The config hasn't been modified, extend expiration, return cached version
93+
notModifierErr := api.NotModifiedError{}
94+
if errors.As(err, &notModifierErr) {
95+
item.ExtendExpiration(now, notModifierErr.MaxAge)
96+
return item.config, false, nil
97+
}
98+
99+
// Only the not found error is expected
100+
var apiErr *api.Error
101+
if errors.As(err, &apiErr) && apiErr.StatusCode() != http.StatusNotFound {
102+
// Log other errors
103+
l.logger.Errorf(ctx, `unable to load configuration for application "%s": %s`, appID, err.Error())
106104

107-
// Handle not found error
108-
if apiErr != nil && apiErr.StatusCode() == http.StatusNotFound {
109-
err = svcErrors.NewResourceNotFoundError("application", appID.String(), "stack").Wrap(err)
110-
return api.AppConfig{}, false, err
105+
// Keep the proxy running for a limited time in case of an API outage.
106+
// The item.expiresAt may be zero, if there is no cached version, then the condition is skipped.
107+
if now.Before(item.expiresAt.Add(staleCacheFallbackDuration)) {
108+
l.logger.Warnf(ctx, `using stale cache for app "%s": %s`, appID, err.Error())
109+
return item.config, false, nil
111110
}
111+
}
112112

113-
// Return the error if:
114-
// - It is not found error.
115-
// - There is no cached version.
116-
// - The staleCacheFallbackDuration has been exceeded.
117-
return api.AppConfig{}, false, svcErrors.
118-
NewServiceUnavailableError(errors.PrefixErrorf(err,
119-
`unable to load configuration for application "%s"`, appID,
120-
)).
121-
WithUserMessage(fmt.Sprintf(
122-
`Unable to load configuration for application "%s".`, appID,
123-
))
113+
// Handle not found error
114+
if apiErr != nil && apiErr.StatusCode() == http.StatusNotFound {
115+
err = svcErrors.NewResourceNotFoundError("application", appID.String(), "stack").Wrap(err)
116+
return api.AppConfig{}, false, err
124117
}
125118

126-
// Cache the loaded configuration
127-
item.config = *newConfig
128-
item.ExtendExpiration(now, item.config.MaxAge())
129-
return item.config, true, nil
119+
// Return the error if:
120+
// - It is not found error.
121+
// - There is no cached version.
122+
// - The staleCacheFallbackDuration has been exceeded.
123+
return api.AppConfig{}, false, svcErrors.
124+
NewServiceUnavailableError(errors.PrefixErrorf(err,
125+
`unable to load configuration for application "%s"`, appID,
126+
)).
127+
WithUserMessage(fmt.Sprintf(
128+
`Unable to load configuration for application "%s".`, appID,
129+
))
130130
}
131131

132132
func (v *cachedAppProxyConfig) ExtendExpiration(now time.Time, maxAge time.Duration) {

internal/pkg/service/cli/dialog/use_template.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,8 @@ func (d *useTmplInputsDialog) ask(ctx context.Context, isForTest bool, inputsFil
9898
if err != nil {
9999
if found {
100100
return errors.NewNestedError(err, errors.New("please fix the value in the inputs JSON file"))
101-
} else {
102-
return errors.NewNestedError(err, errors.New("please define value in the inputs JSON file"))
103101
}
102+
return errors.NewNestedError(err, errors.New("please define value in the inputs JSON file"))
104103
}
105104
return nil
106105
}

internal/pkg/service/common/etcdop/op/op_result.go

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -92,15 +92,18 @@ func (v *resultBase) AddErr(err error) {
9292
func getResponseHeader(response *RawResponse) *Header {
9393
if response == nil {
9494
return nil
95-
} else if v := response.Get(); v != nil {
95+
}
96+
if v := response.Get(); v != nil {
9697
return v.Header
97-
} else if v := response.Del(); v != nil {
98+
}
99+
if v := response.Del(); v != nil {
98100
return v.Header
99-
} else if v := response.Put(); v != nil {
101+
}
102+
if v := response.Put(); v != nil {
100103
return v.Header
101-
} else if v := response.Txn(); v != nil {
104+
}
105+
if v := response.Txn(); v != nil {
102106
return v.Header
103-
} else {
104-
return nil
105107
}
108+
return nil
106109
}

internal/pkg/service/common/etcdop/op/op_test.go

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -210,20 +210,20 @@ func TestOpForType_WithProcessorMethods_Pointer(t *testing.T) {
210210
}
211211

212212
mapper := func(ctx context.Context, raw *op.RawResponse) (result *testValue, err error) {
213-
if response := raw.Get(); response != nil {
214-
if len(response.Kvs) == 1 {
215-
value := &testValue{}
216-
if err := json.Unmarshal(raw.Get().Kvs[0].Value, value); err != nil {
217-
return nil, err
218-
}
219-
if value.Foo == "" {
220-
// Return nil without error, if the field is not set
221-
return nil, nil
222-
}
223-
return value, nil
224-
}
213+
response := raw.Get()
214+
if response == nil || len(response.Kvs) != 1 {
215+
return nil, errors.New("not found")
216+
}
217+
218+
value := &testValue{}
219+
if err := json.Unmarshal(raw.Get().Kvs[0].Value, value); err != nil {
220+
return nil, err
221+
}
222+
if value.Foo == "" {
223+
// Return nil without error, if the field is not set
224+
return nil, nil
225225
}
226-
return nil, errors.New("not found")
226+
return value, nil
227227
}
228228

229229
log := &strings.Builder{}

internal/pkg/service/common/goaextension/example/example.go

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,24 +61,26 @@ func visitRoot(root *expr.RootExpr) error {
6161
attr.AddMeta(metaVisitedAttr, metaVisitedAttrValue)
6262

6363
// Process attribute examples
64-
if examples := attr.ExtractUserExamples(); len(examples) == 0 {
64+
examples := attr.ExtractUserExamples()
65+
if len(examples) == 0 {
6566
// Generate example
6667
if v, err := exampleFor(attr, root.API.ExampleGenerator); err == nil {
6768
attr.UserExamples = append(attr.UserExamples, &expr.ExampleExpr{Summary: "default", Value: v})
6869
} else {
6970
return err
7071
}
71-
} else {
72-
// Normalize already defined examples
73-
for _, example := range examples { // example is a pointer
74-
if v, err := normalizeExample(example.Value); err == nil {
75-
example.Value = v
76-
} else {
77-
return err
78-
}
72+
return nil
73+
}
74+
75+
// Normalize already defined examples
76+
for _, example := range examples { // example is a pointer
77+
if v, err := normalizeExample(example.Value); err == nil {
78+
example.Value = v
79+
} else {
80+
return err
7981
}
80-
attr.UserExamples = examples
8182
}
83+
attr.UserExamples = examples
8284

8385
return nil
8486
})
@@ -138,7 +140,8 @@ func exampleFor(attr *expr.AttributeExpr, g *expr.ExampleGenerator) (any, error)
138140
return out, nil
139141
case *expr.Array:
140142
var out []any
141-
if userExamples := value.ElemType.ExtractUserExamples(); len(userExamples) > 0 {
143+
userExamples := value.ElemType.ExtractUserExamples()
144+
if len(userExamples) > 0 {
142145
// Use UserExamples of the element type
143146
for _, item := range userExamples {
144147
if example, err := normalizeExample(item.Value); err == nil {
@@ -147,14 +150,16 @@ func exampleFor(attr *expr.AttributeExpr, g *expr.ExampleGenerator) (any, error)
147150
return nil, err
148151
}
149152
}
153+
return out, nil
154+
}
155+
156+
// Generate array with one example
157+
if example, err := exampleFor(value.ElemType, g); err == nil {
158+
out = append(out, example)
150159
} else {
151-
// Generate array with one example
152-
if example, err := exampleFor(value.ElemType, g); err == nil {
153-
out = append(out, example)
154-
} else {
155-
return nil, err
156-
}
160+
return nil, err
157161
}
162+
158163
return out, nil
159164
}
160165

internal/pkg/service/stream/mapping/recordctx/fasthttp.go

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -118,18 +118,20 @@ func (c *fastHTTPContext) JSONValue(parserPool *fastjson.ParserPool) (*fastjson.
118118
c.lock.Lock()
119119
defer c.lock.Unlock()
120120

121-
if c.jsonValue == nil && c.jsonValueErr == nil {
122-
if body, err := c.BodyBytes(); err != nil {
123-
c.jsonValueErr = err
121+
if c.jsonValue != nil || c.jsonValueErr != nil {
122+
return c.jsonValue, c.jsonValueErr
123+
}
124+
125+
if body, err := c.BodyBytes(); err != nil {
126+
c.jsonValueErr = err
127+
} else {
128+
parser := parserPool.Get()
129+
defer parserPool.Put(parser)
130+
131+
if jsonValue, err := parser.ParseBytes(body); err != nil {
132+
c.jsonValueErr = errors.PrefixError(err, "cannot parse request json")
124133
} else {
125-
parser := parserPool.Get()
126-
defer parserPool.Put(parser)
127-
128-
if jsonValue, err := parser.ParseBytes(body); err != nil {
129-
c.jsonValueErr = errors.PrefixError(err, "cannot parse request json")
130-
} else {
131-
c.jsonValue = jsonValue
132-
}
134+
c.jsonValue = jsonValue
133135
}
134136
}
135137

0 commit comments

Comments
 (0)