Browse code

all: replace strings.Replace with strings.ReplaceAll

strings.ReplaceAll(s, old, new) is a wrapper function for
strings.Replace(s, old, new, -1). But strings.ReplaceAll is more
readable and removes the hardcoded -1.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>

Eng Zer Jun authored on 2022/05/09 20:26:05
Showing 18 changed files
... ...
@@ -34,8 +34,8 @@ func normalizeWorkdirUnix(current string, requested string) (string, error) {
34 34
 	if requested == "" {
35 35
 		return "", errors.New("cannot normalize nothing")
36 36
 	}
37
-	current = strings.Replace(current, string(os.PathSeparator), "/", -1)
38
-	requested = strings.Replace(requested, string(os.PathSeparator), "/", -1)
37
+	current = strings.ReplaceAll(current, string(os.PathSeparator), "/")
38
+	requested = strings.ReplaceAll(requested, string(os.PathSeparator), "/")
39 39
 	if !path.IsAbs(requested) {
40 40
 		return path.Join(`/`, current, requested), nil
41 41
 	}
... ...
@@ -50,7 +50,7 @@ func (l *Link) ToEnv() []string {
50 50
 	env := []string{}
51 51
 
52 52
 	_, n := path.Split(l.Name)
53
-	alias := strings.Replace(strings.ToUpper(n), "-", "_", -1)
53
+	alias := strings.ReplaceAll(strings.ToUpper(n), "-", "_")
54 54
 
55 55
 	if p := l.getDefaultPort(); p != nil {
56 56
 		env = append(env, fmt.Sprintf("%s_PORT=%s://%s:%s", alias, p.Proto(), l.ChildIP, p.Port()))
... ...
@@ -705,7 +705,7 @@ func WithMounts(daemon *Daemon, c *container.Container) coci.SpecOpts {
705 705
 // sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
706 706
 // exist, so do not add the default ones if running on an old kernel.
707 707
 func sysctlExists(s string) bool {
708
-	f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
708
+	f := filepath.Join("/proc", "sys", strings.ReplaceAll(s, ".", "/"))
709 709
 	_, err := os.Stat(f)
710 710
 	return err == nil
711 711
 }
... ...
@@ -126,7 +126,7 @@ func TestManifestStore(t *testing.T) {
126 126
 	dgst := digest.Canonical.FromBytes(serialized)
127 127
 
128 128
 	setupTest := func(t *testing.T) (specs.Descriptor, *mockManifestGetter, *manifestStore, content.Store, func(*testing.T)) {
129
-		root, err := os.MkdirTemp("", strings.Replace(t.Name(), "/", "_", -1))
129
+		root, err := os.MkdirTemp("", strings.ReplaceAll(t.Name(), "/", "_"))
130 130
 		assert.NilError(t, err)
131 131
 		defer func() {
132 132
 			if t.Failed() {
... ...
@@ -3814,7 +3814,7 @@ func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
3814 3814
 	e2 := removeLogTimestamps(result2.Error.Error())
3815 3815
 
3816 3816
 	// Ignore whitespace since that's what were verifying doesn't change stuff
3817
-	if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
3817
+	if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
3818 3818
 		c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
3819 3819
 	}
3820 3820
 
... ...
@@ -3829,7 +3829,7 @@ func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
3829 3829
 	e2 = removeLogTimestamps(result2.Error.Error())
3830 3830
 
3831 3831
 	// Ignore whitespace since that's what were verifying doesn't change stuff
3832
-	if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
3832
+	if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
3833 3833
 		c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
3834 3834
 	}
3835 3835
 
... ...
@@ -3844,7 +3844,7 @@ func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
3844 3844
 	e2 = removeLogTimestamps(result2.Error.Error())
3845 3845
 
3846 3846
 	// Ignore whitespace since that's what were verifying doesn't change stuff
3847
-	if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
3847
+	if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
3848 3848
 		c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
3849 3849
 	}
3850 3850
 
... ...
@@ -117,7 +117,7 @@ func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *testing.T) {
117 117
 func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing.T) {
118 118
 	dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true")
119 119
 	timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
120
-	timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
120
+	timeBeginning = strings.ReplaceAll(timeBeginning, "Z", ".000000000Z")
121 121
 	out, _ := dockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c))
122 122
 	events := strings.Split(out, "\n")
123 123
 	events = events[:len(events)-1]
... ...
@@ -1292,14 +1292,14 @@ func (s *DockerSuite) TestRunDNSOptions(c *testing.T) {
1292 1292
 		c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", result.Stderr())
1293 1293
 	}
1294 1294
 
1295
-	actual := strings.Replace(strings.Trim(result.Stdout(), "\r\n"), "\n", " ", -1)
1295
+	actual := strings.ReplaceAll(strings.Trim(result.Stdout(), "\r\n"), "\n", " ")
1296 1296
 	if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" {
1297 1297
 		c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual)
1298 1298
 	}
1299 1299
 
1300 1300
 	out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf").Combined()
1301 1301
 
1302
-	actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
1302
+	actual = strings.ReplaceAll(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ")
1303 1303
 	if actual != "nameserver 1.1.1.1 options ndots:3" {
1304 1304
 		c.Fatalf("expected 'nameserver 1.1.1.1 options ndots:3', but says: %q", actual)
1305 1305
 	}
... ...
@@ -1309,7 +1309,7 @@ func (s *DockerSuite) TestRunDNSRepeatOptions(c *testing.T) {
1309 1309
 	testRequires(c, DaemonIsLinux)
1310 1310
 	out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf").Stdout()
1311 1311
 
1312
-	actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
1312
+	actual := strings.ReplaceAll(strings.Trim(out, "\r\n"), "\n", " ")
1313 1313
 	if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" {
1314 1314
 		c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual)
1315 1315
 	}
... ...
@@ -1982,7 +1982,7 @@ func (s *DockerSuite) TestRunSetMacAddress(c *testing.T) {
1982 1982
 	var out string
1983 1983
 	if testEnv.OSType == "windows" {
1984 1984
 		out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'")
1985
-		mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs
1985
+		mac = strings.ReplaceAll(strings.ToUpper(mac), ":", "-") // To Windows-style MACs
1986 1986
 	} else {
1987 1987
 		out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
1988 1988
 	}
... ...
@@ -2156,7 +2156,7 @@ func (s *DockerSuite) TestRunCreateVolumeEtc(c *testing.T) {
2156 2156
 	}
2157 2157
 
2158 2158
 	out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
2159
-	out = strings.Replace(out, "\n", " ", -1)
2159
+	out = strings.ReplaceAll(out, "\n", " ")
2160 2160
 	if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
2161 2161
 		c.Fatal("/etc volume mount hides /etc/hosts")
2162 2162
 	}
... ...
@@ -2532,7 +2532,7 @@ func (s *DockerSuite) TestRunNonLocalMacAddress(c *testing.T) {
2532 2532
 		args = append(args, "busybox", "ifconfig")
2533 2533
 	} else {
2534 2534
 		args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all")
2535
-		expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1)
2535
+		expected = strings.ReplaceAll(strings.ToUpper(addr), ":", "-")
2536 2536
 	}
2537 2537
 
2538 2538
 	if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) {
... ...
@@ -1215,7 +1215,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *testing.T) {
1215 1215
 // sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
1216 1216
 // exist, so do not add the default ones if running on an old kernel.
1217 1217
 func sysctlExists(s string) bool {
1218
-	f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
1218
+	f := filepath.Join("/proc", "sys", strings.ReplaceAll(s, ".", "/"))
1219 1219
 	_, err := os.Stat(f)
1220 1220
 	return err == nil
1221 1221
 }
... ...
@@ -191,7 +191,7 @@ func fetchTable(ip string, port int, network, tableName string, clusterPeers, ne
191 191
 		logrus.Warnf("The following keys:%v results as orphan, do you want to proceed with the deletion (this operation is irreversible)? [Yes/No]", orphanKeys)
192 192
 		reader := bufio.NewReader(os.Stdin)
193 193
 		text, _ := reader.ReadString('\n')
194
-		text = strings.Replace(text, "\n", "", -1)
194
+		text = strings.ReplaceAll(text, "\n", "")
195 195
 		if strings.Compare(text, "Yes") == 0 {
196 196
 			for _, k := range orphanKeys {
197 197
 				resp, err := http.Get(fmt.Sprintf(deleteEntry, ip, port, network, tableName, k))
... ...
@@ -633,7 +633,7 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
633 633
 	macAddress := ifInfo.MacAddress()
634 634
 	// Use the macaddress if it was provided
635 635
 	if macAddress != nil {
636
-		endpointStruct.MacAddress = strings.Replace(macAddress.String(), ":", "-", -1)
636
+		endpointStruct.MacAddress = strings.ReplaceAll(macAddress.String(), ":", "-")
637 637
 	}
638 638
 
639 639
 	portMapping := epConnectivity.PortBindings
... ...
@@ -11,13 +11,13 @@ import (
11 11
 // writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
12 12
 // For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
13 13
 func writeSystemProperty(key, value string) error {
14
-	keyPath := strings.Replace(key, ".", "/", -1)
14
+	keyPath := strings.ReplaceAll(key, ".", "/")
15 15
 	return os.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644)
16 16
 }
17 17
 
18 18
 // readSystemProperty reads the value from the path under /proc/sys and returns it
19 19
 func readSystemProperty(key string) (string, error) {
20
-	keyPath := strings.Replace(key, ".", "/", -1)
20
+	keyPath := strings.ReplaceAll(key, ".", "/")
21 21
 	value, err := os.ReadFile(path.Join("/proc/sys", keyPath))
22 22
 	if err != nil {
23 23
 		return "", err
... ...
@@ -29,8 +29,8 @@ var (
29 29
 // clean path already ends in the separator, then another is not added.
30 30
 func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep byte) string {
31 31
 	// Ensure paths are in platform semantics
32
-	cleanedPath = strings.Replace(cleanedPath, "/", string(sep), -1)
33
-	originalPath = strings.Replace(originalPath, "/", string(sep), -1)
32
+	cleanedPath = strings.ReplaceAll(cleanedPath, "/", string(sep))
33
+	originalPath = strings.ReplaceAll(originalPath, "/", string(sep))
34 34
 
35 35
 	if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) {
36 36
 		if !hasTrailingPathSeparator(cleanedPath, sep) {
... ...
@@ -24,7 +24,7 @@ func Dump() {
24 24
 func DumpToFile(dir string) (string, error) {
25 25
 	var f *os.File
26 26
 	if dir != "" {
27
-		path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.Replace(time.Now().Format(time.RFC3339), ":", "", -1)))
27
+		path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.ReplaceAll(time.Now().Format(time.RFC3339), ":", "")))
28 28
 		var err error
29 29
 		f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
30 30
 		if err != nil {
... ...
@@ -16,5 +16,5 @@ var defaultCertsDir = os.Getenv("programdata") + `\docker\certs.d`
16 16
 // https:\index.docker.io\v1. Not all platforms support directory names
17 17
 // which contain those characters (such as : on Windows)
18 18
 func cleanPath(s string) string {
19
-	return filepath.FromSlash(strings.Replace(s, ":", "", -1))
19
+	return filepath.FromSlash(strings.ReplaceAll(s, ":", ""))
20 20
 }
... ...
@@ -103,7 +103,7 @@ func getPlatformDefaults(info types.Info, osType string) PlatformDefaults {
103 103
 // Make sure in context of daemon, not the local platform. Note we can't
104 104
 // use filepath.FromSlash or ToSlash here as they are a no-op on Unix.
105 105
 func toSlash(path string) string {
106
-	return strings.Replace(path, `\`, `/`, -1)
106
+	return strings.ReplaceAll(path, `\`, `/`)
107 107
 }
108 108
 
109 109
 // IsLocalDaemon is true if the daemon under test is on the same
... ...
@@ -36,14 +36,14 @@ func linuxSplitRawSpec(raw string) ([]string, error) {
36 36
 }
37 37
 
38 38
 func linuxValidateNotRoot(p string) error {
39
-	p = path.Clean(strings.Replace(p, `\`, `/`, -1))
39
+	p = path.Clean(strings.ReplaceAll(p, `\`, `/`))
40 40
 	if p == "/" {
41 41
 		return ErrVolumeTargetIsRoot
42 42
 	}
43 43
 	return nil
44 44
 }
45 45
 func linuxValidateAbsolute(p string) error {
46
-	p = strings.Replace(p, `\`, `/`, -1)
46
+	p = strings.ReplaceAll(p, `\`, `/`)
47 47
 	if path.IsAbs(p) {
48 48
 		return nil
49 49
 	}
... ...
@@ -144,7 +144,7 @@ func windowsValidMountMode(mode string) bool {
144 144
 }
145 145
 
146 146
 func windowsValidateNotRoot(p string) error {
147
-	p = strings.ToLower(strings.Replace(p, `/`, `\`, -1))
147
+	p = strings.ToLower(strings.ReplaceAll(p, `/`, `\`))
148 148
 	if p == "c:" || p == `c:\` {
149 149
 		return fmt.Errorf("destination path cannot be `c:` or `c:\\`: %v", p)
150 150
 	}
... ...
@@ -316,18 +316,18 @@ func (p *windowsParser) parseMount(arr []string, raw, volumeDriver string, conve
316 316
 			return nil, errInvalidSpec(raw)
317 317
 		}
318 318
 		// Host Source Path or Name + Destination
319
-		spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
319
+		spec.Source = strings.ReplaceAll(arr[0], `/`, `\`)
320 320
 		spec.Target = arr[1]
321 321
 	case 3:
322 322
 		// HostSourcePath+DestinationPath+Mode
323
-		spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
323
+		spec.Source = strings.ReplaceAll(arr[0], `/`, `\`)
324 324
 		spec.Target = arr[1]
325 325
 		mode = arr[2]
326 326
 	default:
327 327
 		return nil, errInvalidSpec(raw)
328 328
 	}
329 329
 	if convertTargetToBackslash {
330
-		spec.Target = strings.Replace(spec.Target, `/`, `\`, -1)
330
+		spec.Target = strings.ReplaceAll(spec.Target, `/`, `\`)
331 331
 	}
332 332
 
333 333
 	if !windowsValidMountMode(mode) {
... ...
@@ -376,7 +376,7 @@ func (p *windowsParser) parseMountSpec(cfg mount.Mount, convertTargetToBackslash
376 376
 		Spec:        cfg,
377 377
 	}
378 378
 	if convertTargetToBackslash {
379
-		mp.Destination = strings.Replace(cfg.Target, `/`, `\`, -1)
379
+		mp.Destination = strings.ReplaceAll(cfg.Target, `/`, `\`)
380 380
 	}
381 381
 
382 382
 	switch cfg.Type {
... ...
@@ -397,9 +397,9 @@ func (p *windowsParser) parseMountSpec(cfg mount.Mount, convertTargetToBackslash
397 397
 			}
398 398
 		}
399 399
 	case mount.TypeBind:
400
-		mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
400
+		mp.Source = strings.ReplaceAll(cfg.Source, `/`, `\`)
401 401
 	case mount.TypeNamedPipe:
402
-		mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
402
+		mp.Source = strings.ReplaceAll(cfg.Source, `/`, `\`)
403 403
 	}
404 404
 	// cleanup trailing `\` except for paths like `c:\`
405 405
 	if len(mp.Source) > 3 && mp.Source[len(mp.Source)-1] == '\\' {
... ...
@@ -367,7 +367,7 @@ var cmpVolume = cmp.AllowUnexported(volumetestutils.FakeVolume{}, volumeWrapper{
367 367
 func setupTest(t *testing.T) (*VolumeStore, func()) {
368 368
 	t.Helper()
369 369
 
370
-	dirName := strings.Replace(t.Name(), string(os.PathSeparator), "_", -1)
370
+	dirName := strings.ReplaceAll(t.Name(), string(os.PathSeparator), "_")
371 371
 	dir, err := os.MkdirTemp("", dirName)
372 372
 	assert.NilError(t, err)
373 373