Skip to content

Commit

Permalink
Merge pull request #1833 from keboola/lint-add-prealoc-linter
Browse files Browse the repository at this point in the history
lint: Add prealoc linter to reduce realocation
  • Loading branch information
Matovidlo authored Nov 25, 2024
2 parents ce32001 + 33e8a88 commit d09d394
Show file tree
Hide file tree
Showing 36 changed files with 50 additions and 49 deletions.
1 change: 1 addition & 0 deletions build/ci/golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ linters:
- nakedret
- nilerr
- noctx
- prealloc
- predeclared
- promlinter
- rowserrcheck
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/env/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func (m *Map) ToString() (string, error) {
}

func (m *Map) ToSlice() []string {
var out []string
out := make([]string, 0, len(m.Keys()))
for _, k := range m.Keys() {
v := m.Get(k)
out = append(out, fmt.Sprintf(`%s=%s`, k, v))
Expand All @@ -85,7 +85,7 @@ func (m *Map) ToMap() map[string]string {
}

func (m *Map) Keys() []string {
keys := make([]string, 0)
keys := make([]string, 0, len(m.data))
for k := range m.data {
keys = append(keys, k)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/filesystem/knownpaths/paths.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (p *Paths) TrackedPaths() []string {
p.lock.Lock()
defer p.lock.Unlock()

var tracked []string
tracked := make([]string, 0, len(p.tracked))
for path := range p.tracked {
tracked = append(tracked, path)
}
Expand All @@ -140,7 +140,7 @@ func (p *Paths) UntrackedPaths() []string {
p.lock.Lock()
defer p.lock.Unlock()

var untracked []string
untracked := make([]string, 0, len(p.all))
for path := range p.all {
if _, ok := p.tracked[path]; !ok {
untracked = append(untracked, path)
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func (l *zapLogger) logInLevel(level string, message string, fields ...zap.Field
}

func (l *zapLogger) message(ctx context.Context, message string) string {
var replacements []string
replacements := make([]string, 0, len(ctxattr.Attributes(ctx).ToSlice()))
for _, kv := range ctxattr.Attributes(ctx).ToSlice() {
replacements = append(replacements, "<"+string(kv.Key)+">", kv.Value.Emit())
}
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/mapper/orchestrator/local_save_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func TestOrchestratorMapper_MapBeforeLocalSave(t *testing.T) {
assert.Empty(t, logger.WarnAndErrorMessages())

// Minify JSON + remove file description
var files []filesystem.File
files := make([]filesystem.File, 0, len(recipe.Files.All()))
for _, file := range recipe.Files.All() {
var fileRaw *filesystem.RawFile
if f, ok := file.(*filesystem.JSONFile); ok {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/mapper/orchestrator/sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (s *phasesSorter) sortPhases() ([]*model.Phase, error) {
}

// Generate slice
var phases []*model.Phase
phases := make([]*model.Phase, 0, len(order))
for phaseIndex, keyRaw := range order {
key := keyRaw.(string)
phase := s.phaseByKey[key]
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/mapper/sharedcode/links/links_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ func createRemoteTranWithSharedCode(t *testing.T, sharedCodeKey model.ConfigKey,
t.Helper()

// Rows -> rows IDs
var rows []any
rows := make([]any, 0, len(sharedCodeRowsKeys))
for _, row := range sharedCodeRowsKeys {
rows = append(rows, row.ID.String())
}
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/mapper/transformation/local_save_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func TestTransformationMapper_MapBeforeLocalSave(t *testing.T) {
assert.Empty(t, logger.WarnAndErrorMessages())

// Minify JSON + remove file description
var files []filesystem.File
files := make([]filesystem.File, 0, len(recipe.Files.All()))
for _, file := range recipe.Files.All() {
var fileRaw *filesystem.RawFile
if f, ok := file.(*filesystem.JSONFile); ok {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/model/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (v ChangedFields) Remove(field string) {
}

func (v ChangedFields) String() string {
var out []string
out := make([]string, 0, len(v))
for field := range v {
out = append(out, field)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/model/orchestrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (p Phase) String() string {
buf := new(bytes.Buffer)
_, _ = fmt.Fprintf(buf, "# %03d %s\n", p.Index+1, p.Name)

var dependsOn []string
dependsOn := make([]string, 0, len(p.DependsOn))
for _, dependsOnKey := range p.DependsOn {
dependsOn = append(dependsOn, cast.ToString(dependsOnKey.Index+1))
}
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/model/relation.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ func (v *Relations) UnmarshalJSON(data []byte) error {
}

func (v Relations) MarshalJSON() ([]byte, error) {
var out []*orderedmap.OrderedMap
out := make([]*orderedmap.OrderedMap, 0, len(v))
for _, relation := range v {
// Validate, only manifest side should be serialized to JSON
if !relation.IsDefinedInManifest() {
Expand Down
12 changes: 6 additions & 6 deletions internal/pkg/model/transformation.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ type StaticScript struct {
}

func (v UsedSharedCodeRows) IdsSlice() []any {
var ids []any
ids := make([]any, 0, len(v))
for _, rowKey := range v {
ids = append(ids, rowKey.ID.String())
}
Expand Down Expand Up @@ -112,15 +112,15 @@ func (c Code) String() string {
}

func (v Scripts) Slice() []any {
var out []any
out := make([]any, 0, len(v))
for _, script := range v {
out = append(out, script.Content())
}
return out
}

func (v Scripts) String(componentID keboola.ComponentID) string {
var items []string
items := make([]string, 0, len(v))
for _, script := range v {
items = append(items, strings.TrimRight(script.Content(), " \r\n\t"))
}
Expand All @@ -135,7 +135,7 @@ func (v Scripts) String(componentID keboola.ComponentID) string {

// MarshalJSON converts Scripts to JSON []string.
func (v Scripts) MarshalJSON() ([]byte, error) {
var scripts []string
scripts := make([]string, 0, len(v))
for _, script := range v {
scripts = append(scripts, script.(StaticScript).Value)
}
Expand All @@ -152,7 +152,7 @@ func (v *Scripts) UnmarshalJSON(data []byte) error {
return err
}

*v = make(Scripts, 0)
*v = make(Scripts, 0, len(scripts))
for _, item := range scripts {
*v = append(*v, StaticScript{Value: item})
}
Expand Down Expand Up @@ -185,7 +185,7 @@ func ScriptsFromStr(content string, componentID keboola.ComponentID) Scripts {
}

func ScriptsFromSlice(items []any) Scripts {
var scripts Scripts
scripts := make(Scripts, 0, len(items))
for _, item := range items {
scripts = append(scripts, StaticScript{Value: cast.ToString(item)})
}
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/plan/persist/persist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func TestPersistNoChange(t *testing.T) {
t.Parallel()
tc := testCase{
inputDir: `persist-no-change`,
untrackedPaths: nil,
untrackedPaths: []string{},
expectedPlan: nil,
}
tc.run(t)
Expand Down Expand Up @@ -243,7 +243,7 @@ func TestPersistDeleted(t *testing.T) {
t.Parallel()
tc := testCase{
inputDir: `persist-deleted`,
untrackedPaths: nil,
untrackedPaths: []string{},
expectedPlan: []action{
&deleteManifestRecordAction{
ObjectManifest: &model.ConfigManifest{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func generateKey(targetDir string, schema *load.Schema, pkAnnotation PKAnnotatio
for _, field := range pkAnnotation.Fields {
importsMap[field.GoType.PkgPath] = struct{}{}
}
var importPkg []string
importPkg := make([]string, 0, len(importsMap))
for pkgPath := range importsMap {
importPkg = append(importPkg, pkgPath)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func (v *Mixin) Edges() []ent.Edge {

// Indexes method generates index for composed primary key.
func (v *Mixin) Indexes() (indexes []ent.Index) {
var fields []string
fields := make([]string, 0, len(v.pkFields))
for _, f := range v.pkFields {
fields = append(fields, f.Name)
indexes = append(indexes, index.Fields(f.Name).Annotations(PKFieldAnnotation{}))
Expand Down
6 changes: 3 additions & 3 deletions internal/pkg/project/manifest/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (c *file) validate(ctx context.Context) error {
}

func (c *file) records() []model.ObjectManifest {
var out []model.ObjectManifest
out := make([]model.ObjectManifest, 0, 1024)
for _, branch := range c.Branches {
out = append(out, branch)
}
Expand All @@ -124,8 +124,8 @@ func (c *file) setRecords(records []model.ObjectManifest) {
// Convert records map to slices
branchesMap := make(map[string]*model.BranchManifest)
configsMap := make(map[string]*model.ConfigManifestWithRows)
c.Branches = make([]*model.BranchManifest, 0)
c.Configs = make([]*model.ConfigManifestWithRows, 0)
c.Branches = make([]*model.BranchManifest, 0, len(records))
c.Configs = make([]*model.ConfigManifestWithRows, 0, len(records))

for _, manifest := range records {
// Skip invalid (eg. missing config file)
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/cli/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ func (root *RootCommand) Execute() (exitCode int) {

func (root *RootCommand) listAliases() string {
// Join aliases to single line
var lines []string
lines := make([]string, 0, len(root.aliases.Keys()))
var maxLength int
for _, cmd := range root.aliases.Keys() {
aliasesRaw, _ := root.aliases.Get(cmd)
Expand Down
5 changes: 3 additions & 2 deletions internal/pkg/service/cli/cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ func TestCliSubCommandsAndAliases(t *testing.T) {
root, _ := newTestRootCommand(aferofs.NewMemoryFs())

// Map commands to names
var names []string
for _, cmd := range root.Commands() {
cmds := root.Commands()
names := make([]string, 0, len(cmds))
for _, cmd := range cmds {
names = append(names, cmd.Name())
}

Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/cli/cmd/remote/table/create/dialog.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func ParseJSONInputForCreateTable(filePath string) ([]keboola.Column, error) {

// getOptionCreateRequest returns Options.CreateTableRequest from the flags (columns, primary keys, table name). It is used if the `columns-from` flag is not specified.
func getOptionCreateRequest(columns []string) []keboola.Column {
var c []keboola.Column
c := make([]keboola.Column, 0, len(columns))
for _, column := range columns {
var col keboola.Column
col.Name = column
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/cli/cmd/template/create/dialog.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ func (d *templateIdsDialog) parse(result string) ([]create.ConfigDef, error) {
return nil, errs.ErrorOrNil()
}

var defs []create.ConfigDef
defs := make([]create.ConfigDef, 0, len(d.configs))
for _, c := range d.configs {
// Config definition
id := idByKey[c.Key().String()]
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/cli/dialog/inputs.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ func (p *Dialogs) AskNewTemplateInputs(ctx context.Context, deps inputsDialogDep
type inputFields map[string]input.ObjectField

func (f inputFields) Write(out *strings.Builder) {
var table []inputFieldLine
var inputIDMaxLength int
var fieldPathMaxLength int
table := make([]inputFieldLine, 0, len(f))

// Convert and get max lengths for padding
for _, field := range f {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/cli/dialog/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (p *Dialogs) AskTable(allTables []*keboola.Table, id configmap.Value[string
return nil, errors.Errorf(`table with ID "%s" not found in the project`, tableID)
}

var selectOpts []string
selectOpts := make([]string, 0, len(allTables)+1)
if config.allowCreateNew {
selectOpts = []string{"Create a new table"}
}
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/etcdop/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func TestSessionBackoff(t *testing.T) {
b.RandomizationFactor = 0

// Get all delays without sleep
var delays []time.Duration
delays := make([]time.Duration, 0, 14)
for range 14 {
delay := b.NextBackOff()
if delay == backoff.Stop {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/common/etcdop/watch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ func TestWatchBackoff(t *testing.T) {
b.RandomizationFactor = 0

// Get all delays without sleep
var delays []time.Duration
delays := make([]time.Duration, 0, 14)
for range 14 {
delay := b.NextBackOff()
if delay == backoff.Stop {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/service/stream/api/service/aggregation.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (s *service) AggregationSources(ctx context.Context, d dependencies.BranchR

func (s *service) addSinksToAggregationResponse(ctx context.Context, d dependencies.BranchRequestScope, response *stream.AggregatedSourcesResult) error {
// Collect source IDs
var sourceKeys []key.SourceKey
sourceKeys := make([]key.SourceKey, 0, len(response.Sources))
for _, source := range response.Sources {
sourceKey := key.SourceKey{
BranchKey: d.BranchKey(),
Expand Down
3 changes: 2 additions & 1 deletion internal/pkg/service/stream/components.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,11 @@ func ParseComponentsList(args []string) (Components, error) {
}

func (v Components) String() string {
var names []string
names := make([]string, 0, len(v))
for _, n := range v {
names = append(names, string(n))
}

sort.Strings(names)
return strings.Join(names, ",")
}
4 changes: 2 additions & 2 deletions internal/pkg/service/stream/mapping/jsonnet/jsonnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,8 @@ func bodyPathInternalFn(vm *jsonnet.VM[recordctx.Context]) *jsonnet.NativeFuncti
}

func applyNativeFn(fnName string, args ...ast.Node) ast.Node {
var freeVars []ast.Identifier
var fnArgs []ast.CommaSeparatedExpr
freeVars := make([]ast.Identifier, 0, len(args))
fnArgs := make([]ast.CommaSeparatedExpr, 0, len(args))
for _, item := range args {
fnArgs = append(fnArgs, ast.CommaSeparatedExpr{Expr: item})
// Build list of the freeVars manually, so we can skip parser.PreprocessAst step, it is faster
Expand Down
3 changes: 1 addition & 2 deletions internal/pkg/service/stream/mapping/table/column/columns.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ func (v Columns) PrimaryKey() []string {
}

func (v Columns) MarshalJSON() ([]byte, error) {
var items []json.RawMessage

items := make([]json.RawMessage, 0, len(v))
for _, column := range v {
typ := column.ColumnType()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func VolumesFor(all []volume.Metadata, cfg Config, randomSeed int64) (out Assign

// Convert map to slice and sort node volumes by the preferred priority.
// Volumes with the most preferred volume type are first.
var perNode []*nodeVolumes
perNode := make([]*nodeVolumes, 0, len(byNode))
for nodeID, volumes := range byNode {
typePriority.Sort(volumes, randomSeed)
perNode = append(perNode, &nodeVolumes{nodeID: nodeID, volumes: newStack[volume.Metadata](volumes)})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ func (n *Node) volumeDiskDirs(volume *diskwriter.Volume) (out []string, err erro
}

func (n *Node) removeEmptyDirs(ctx context.Context, dirsMap map[string]bool) error {
var dirs []string
dirs := make([]string, 0, len(dirsMap))
for dir := range dirsMap {
dirs = append(dirs, dir)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func TestRepository_Put(t *testing.T) {

// Many
nodeID3 := "test-node-3"
var records []statistics.PerSlice
records := make([]statistics.PerSlice, 0, 150)
start := utctime.MustParse("2000-01-21T00:00:00.000Z")
for i := range 150 {
openedAt := start.Add(time.Duration(i) * time.Second)
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/state/registry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func (s *Registry) All() []ObjectState {
return aKey < bKey
})

var out []ObjectState
out := make([]ObjectState, 0, len(s.objects.Keys()))
for _, key := range s.objects.Keys() {
// Get value
v, _ := s.objects.Get(key)
Expand Down
3 changes: 1 addition & 2 deletions internal/pkg/template/context/create/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ func replacementsForCreate(sourceBranch model.BranchKey, configs []ConfigDef) *r
}

func remoteFilterForCreate(sourceBranch model.BranchKey, configs []ConfigDef) model.ObjectsFilter {
var keys []model.Key

keys := make([]model.Key, 0, len(configs)+1)
// Branch
keys = append(keys, sourceBranch)

Expand Down
Loading

0 comments on commit d09d394

Please sign in to comment.