From be20d29a81e816084d7a8d56687a5023aa181394 Mon Sep 17 00:00:00 2001 From: Philip Meulengracht Date: Thu, 24 Feb 2022 14:19:42 +0100 Subject: [PATCH] wrappers: review feedback add new function []int => string in strutils, use that instead of chained string functions --- strutil/strutil.go | 13 +++++++++++++ wrappers/services.go | 2 +- wrappers/services_test.go | 4 ++-- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/strutil/strutil.go b/strutil/strutil.go index 3d21cdf8cbd..b255ea467d9 100644 --- a/strutil/strutil.go +++ b/strutil/strutil.go @@ -39,6 +39,19 @@ func SizeToStr(size int64) string { panic("SizeToStr got a size bigger than math.MaxInt64") } +// SliceToCommaSeparatedString converts an int array to a comma-separated string +func SliceToCommaSeparatedString(vals []int) string { + b := &strings.Builder{} + last := len(vals) - 1 + for i, v := range vals { + b.WriteString(strconv.Itoa(v)) + if i != last { + b.WriteRune(',') + } + } + return b.String() +} + // Quoted formats a slice of strings to a quoted list of // comma-separated strings, e.g. `"snap1", "snap2"` func Quoted(names []string) string { diff --git a/wrappers/services.go b/wrappers/services.go index 1177abd3ec6..6305e5f1664 100644 --- a/wrappers/services.go +++ b/wrappers/services.go @@ -117,7 +117,7 @@ func formatCpuGroupSlice(grp *quota.Group) string { return "" } - allowedCpusValue := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(grp.CPULimit.AllowedCPUs)), ","), "[]") + allowedCpusValue := strutil.SliceToCommaSeparatedString(grp.CPULimit.AllowedCPUs) return fmt.Sprintf("AllowedCPUs=%s\n", allowedCpusValue) } diff --git a/wrappers/services_test.go b/wrappers/services_test.go index 807a0c2f304..6763148990f 100644 --- a/wrappers/services_test.go +++ b/wrappers/services_test.go @@ -284,7 +284,7 @@ TasksAccounting=true TasksMax=%[5]d ` - allowedCpusValue := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(resourceLimits.CPU.AllowedCPUs)), ","), "[]") + allowedCpusValue := strutil.SliceToCommaSeparatedString(resourceLimits.CPU.AllowedCPUs) sliceContent := fmt.Sprintf(sliceTempl, grp.Name, resourceLimits.CPU.Count*resourceLimits.CPU.Percentage, allowedCpusValue, @@ -851,7 +851,7 @@ MemoryLimit=%[3]d TasksAccounting=true ` - allowedCpusValue := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(resourceLimits.CPU.AllowedCPUs)), ","), "[]") + allowedCpusValue := strutil.SliceToCommaSeparatedString(resourceLimits.CPU.AllowedCPUs) c.Assert(sliceFile, testutil.FileEquals, fmt.Sprintf(templ, "foogroup", allowedCpusValue, resourceLimits.Memory.Limit)) c.Assert(subSliceFile, testutil.FileEquals, fmt.Sprintf(templ, "subgroup", allowedCpusValue, resourceLimits.Memory.Limit)) }