1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

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>
This commit is contained in:
Eng Zer Jun 2022-05-09 19:26:05 +08:00
parent bb88ff4ab4
commit 7873c27cfb
No known key found for this signature in database
GPG key ID: DAEBBD2E34C111E6
18 changed files with 35 additions and 35 deletions

View file

@ -34,8 +34,8 @@ func normalizeWorkdirUnix(current string, requested string) (string, error) {
if requested == "" {
return "", errors.New("cannot normalize nothing")
}
current = strings.Replace(current, string(os.PathSeparator), "/", -1)
requested = strings.Replace(requested, string(os.PathSeparator), "/", -1)
current = strings.ReplaceAll(current, string(os.PathSeparator), "/")
requested = strings.ReplaceAll(requested, string(os.PathSeparator), "/")
if !path.IsAbs(requested) {
return path.Join(`/`, current, requested), nil
}

View file

@ -50,7 +50,7 @@ func (l *Link) ToEnv() []string {
env := []string{}
_, n := path.Split(l.Name)
alias := strings.Replace(strings.ToUpper(n), "-", "_", -1)
alias := strings.ReplaceAll(strings.ToUpper(n), "-", "_")
if p := l.getDefaultPort(); p != nil {
env = append(env, fmt.Sprintf("%s_PORT=%s://%s:%s", alias, p.Proto(), l.ChildIP, p.Port()))

View file

@ -705,7 +705,7 @@ func WithMounts(daemon *Daemon, c *container.Container) coci.SpecOpts {
// sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
// exist, so do not add the default ones if running on an old kernel.
func sysctlExists(s string) bool {
f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
f := filepath.Join("/proc", "sys", strings.ReplaceAll(s, ".", "/"))
_, err := os.Stat(f)
return err == nil
}

View file

@ -126,7 +126,7 @@ func TestManifestStore(t *testing.T) {
dgst := digest.Canonical.FromBytes(serialized)
setupTest := func(t *testing.T) (specs.Descriptor, *mockManifestGetter, *manifestStore, content.Store, func(*testing.T)) {
root, err := os.MkdirTemp("", strings.Replace(t.Name(), "/", "_", -1))
root, err := os.MkdirTemp("", strings.ReplaceAll(t.Name(), "/", "_"))
assert.NilError(t, err)
defer func() {
if t.Failed() {

View file

@ -3814,7 +3814,7 @@ func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
e2 := removeLogTimestamps(result2.Error.Error())
// Ignore whitespace since that's what were verifying doesn't change stuff
if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
}
@ -3829,7 +3829,7 @@ func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
e2 = removeLogTimestamps(result2.Error.Error())
// Ignore whitespace since that's what were verifying doesn't change stuff
if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
}
@ -3844,7 +3844,7 @@ func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
e2 = removeLogTimestamps(result2.Error.Error())
// Ignore whitespace since that's what were verifying doesn't change stuff
if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
}

View file

@ -117,7 +117,7 @@ func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *testing.T) {
func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing.T) {
dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true")
timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
timeBeginning = strings.ReplaceAll(timeBeginning, "Z", ".000000000Z")
out, _ := dockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c))
events := strings.Split(out, "\n")
events = events[:len(events)-1]

View file

@ -1292,14 +1292,14 @@ func (s *DockerSuite) TestRunDNSOptions(c *testing.T) {
c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", result.Stderr())
}
actual := strings.Replace(strings.Trim(result.Stdout(), "\r\n"), "\n", " ", -1)
actual := strings.ReplaceAll(strings.Trim(result.Stdout(), "\r\n"), "\n", " ")
if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" {
c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual)
}
out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf").Combined()
actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
actual = strings.ReplaceAll(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ")
if actual != "nameserver 1.1.1.1 options ndots:3" {
c.Fatalf("expected 'nameserver 1.1.1.1 options ndots:3', but says: %q", actual)
}
@ -1309,7 +1309,7 @@ func (s *DockerSuite) TestRunDNSRepeatOptions(c *testing.T) {
testRequires(c, DaemonIsLinux)
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()
actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
actual := strings.ReplaceAll(strings.Trim(out, "\r\n"), "\n", " ")
if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" {
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)
}
@ -1982,7 +1982,7 @@ func (s *DockerSuite) TestRunSetMacAddress(c *testing.T) {
var out string
if testEnv.OSType == "windows" {
out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'")
mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs
mac = strings.ReplaceAll(strings.ToUpper(mac), ":", "-") // To Windows-style MACs
} else {
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}'")
}
@ -2156,7 +2156,7 @@ func (s *DockerSuite) TestRunCreateVolumeEtc(c *testing.T) {
}
out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
out = strings.Replace(out, "\n", " ", -1)
out = strings.ReplaceAll(out, "\n", " ")
if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
c.Fatal("/etc volume mount hides /etc/hosts")
}
@ -2532,7 +2532,7 @@ func (s *DockerSuite) TestRunNonLocalMacAddress(c *testing.T) {
args = append(args, "busybox", "ifconfig")
} else {
args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all")
expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1)
expected = strings.ReplaceAll(strings.ToUpper(addr), ":", "-")
}
if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) {

View file

@ -1215,7 +1215,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *testing.T) {
// sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
// exist, so do not add the default ones if running on an old kernel.
func sysctlExists(s string) bool {
f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
f := filepath.Join("/proc", "sys", strings.ReplaceAll(s, ".", "/"))
_, err := os.Stat(f)
return err == nil
}

View file

@ -191,7 +191,7 @@ func fetchTable(ip string, port int, network, tableName string, clusterPeers, ne
logrus.Warnf("The following keys:%v results as orphan, do you want to proceed with the deletion (this operation is irreversible)? [Yes/No]", orphanKeys)
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
text = strings.ReplaceAll(text, "\n", "")
if strings.Compare(text, "Yes") == 0 {
for _, k := range orphanKeys {
resp, err := http.Get(fmt.Sprintf(deleteEntry, ip, port, network, tableName, k))

View file

@ -633,7 +633,7 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
macAddress := ifInfo.MacAddress()
// Use the macaddress if it was provided
if macAddress != nil {
endpointStruct.MacAddress = strings.Replace(macAddress.String(), ":", "-", -1)
endpointStruct.MacAddress = strings.ReplaceAll(macAddress.String(), ":", "-")
}
portMapping := epConnectivity.PortBindings

View file

@ -11,13 +11,13 @@ import (
// writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
// For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
func writeSystemProperty(key, value string) error {
keyPath := strings.Replace(key, ".", "/", -1)
keyPath := strings.ReplaceAll(key, ".", "/")
return os.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644)
}
// readSystemProperty reads the value from the path under /proc/sys and returns it
func readSystemProperty(key string) (string, error) {
keyPath := strings.Replace(key, ".", "/", -1)
keyPath := strings.ReplaceAll(key, ".", "/")
value, err := os.ReadFile(path.Join("/proc/sys", keyPath))
if err != nil {
return "", err

View file

@ -29,8 +29,8 @@ var (
// clean path already ends in the separator, then another is not added.
func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep byte) string {
// Ensure paths are in platform semantics
cleanedPath = strings.Replace(cleanedPath, "/", string(sep), -1)
originalPath = strings.Replace(originalPath, "/", string(sep), -1)
cleanedPath = strings.ReplaceAll(cleanedPath, "/", string(sep))
originalPath = strings.ReplaceAll(originalPath, "/", string(sep))
if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) {
if !hasTrailingPathSeparator(cleanedPath, sep) {

View file

@ -24,7 +24,7 @@ func Dump() {
func DumpToFile(dir string) (string, error) {
var f *os.File
if dir != "" {
path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.Replace(time.Now().Format(time.RFC3339), ":", "", -1)))
path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.ReplaceAll(time.Now().Format(time.RFC3339), ":", "")))
var err error
f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {

View file

@ -16,5 +16,5 @@ var defaultCertsDir = os.Getenv("programdata") + `\docker\certs.d`
// https:\index.docker.io\v1. Not all platforms support directory names
// which contain those characters (such as : on Windows)
func cleanPath(s string) string {
return filepath.FromSlash(strings.Replace(s, ":", "", -1))
return filepath.FromSlash(strings.ReplaceAll(s, ":", ""))
}

View file

@ -103,7 +103,7 @@ func getPlatformDefaults(info types.Info, osType string) PlatformDefaults {
// Make sure in context of daemon, not the local platform. Note we can't
// use filepath.FromSlash or ToSlash here as they are a no-op on Unix.
func toSlash(path string) string {
return strings.Replace(path, `\`, `/`, -1)
return strings.ReplaceAll(path, `\`, `/`)
}
// IsLocalDaemon is true if the daemon under test is on the same

View file

@ -36,14 +36,14 @@ func linuxSplitRawSpec(raw string) ([]string, error) {
}
func linuxValidateNotRoot(p string) error {
p = path.Clean(strings.Replace(p, `\`, `/`, -1))
p = path.Clean(strings.ReplaceAll(p, `\`, `/`))
if p == "/" {
return ErrVolumeTargetIsRoot
}
return nil
}
func linuxValidateAbsolute(p string) error {
p = strings.Replace(p, `\`, `/`, -1)
p = strings.ReplaceAll(p, `\`, `/`)
if path.IsAbs(p) {
return nil
}

View file

@ -144,7 +144,7 @@ func windowsValidMountMode(mode string) bool {
}
func windowsValidateNotRoot(p string) error {
p = strings.ToLower(strings.Replace(p, `/`, `\`, -1))
p = strings.ToLower(strings.ReplaceAll(p, `/`, `\`))
if p == "c:" || p == `c:\` {
return fmt.Errorf("destination path cannot be `c:` or `c:\\`: %v", p)
}
@ -316,18 +316,18 @@ func (p *windowsParser) parseMount(arr []string, raw, volumeDriver string, conve
return nil, errInvalidSpec(raw)
}
// Host Source Path or Name + Destination
spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
spec.Source = strings.ReplaceAll(arr[0], `/`, `\`)
spec.Target = arr[1]
case 3:
// HostSourcePath+DestinationPath+Mode
spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
spec.Source = strings.ReplaceAll(arr[0], `/`, `\`)
spec.Target = arr[1]
mode = arr[2]
default:
return nil, errInvalidSpec(raw)
}
if convertTargetToBackslash {
spec.Target = strings.Replace(spec.Target, `/`, `\`, -1)
spec.Target = strings.ReplaceAll(spec.Target, `/`, `\`)
}
if !windowsValidMountMode(mode) {
@ -376,7 +376,7 @@ func (p *windowsParser) parseMountSpec(cfg mount.Mount, convertTargetToBackslash
Spec: cfg,
}
if convertTargetToBackslash {
mp.Destination = strings.Replace(cfg.Target, `/`, `\`, -1)
mp.Destination = strings.ReplaceAll(cfg.Target, `/`, `\`)
}
switch cfg.Type {
@ -397,9 +397,9 @@ func (p *windowsParser) parseMountSpec(cfg mount.Mount, convertTargetToBackslash
}
}
case mount.TypeBind:
mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
mp.Source = strings.ReplaceAll(cfg.Source, `/`, `\`)
case mount.TypeNamedPipe:
mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
mp.Source = strings.ReplaceAll(cfg.Source, `/`, `\`)
}
// cleanup trailing `\` except for paths like `c:\`
if len(mp.Source) > 3 && mp.Source[len(mp.Source)-1] == '\\' {

View file

@ -367,7 +367,7 @@ var cmpVolume = cmp.AllowUnexported(volumetestutils.FakeVolume{}, volumeWrapper{
func setupTest(t *testing.T) (*VolumeStore, func()) {
t.Helper()
dirName := strings.Replace(t.Name(), string(os.PathSeparator), "_", -1)
dirName := strings.ReplaceAll(t.Name(), string(os.PathSeparator), "_")
dir, err := os.MkdirTemp("", dirName)
assert.NilError(t, err)