refactor: 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-17 00:11:45 +08:00 committed by Nick Craig-Wood
parent b929a56f46
commit 4f0ddb60e7
20 changed files with 32 additions and 32 deletions

View File

@ -515,7 +515,7 @@ func (f *Fs) setChunkNameFormat(pattern string) error {
strRegex := regexp.QuoteMeta(pattern) strRegex := regexp.QuoteMeta(pattern)
strRegex = reHashes.ReplaceAllLiteralString(strRegex, reDataOrCtrl) strRegex = reHashes.ReplaceAllLiteralString(strRegex, reDataOrCtrl)
strRegex = strings.Replace(strRegex, "\\*", mainNameRegStr, -1) strRegex = strings.ReplaceAll(strRegex, "\\*", mainNameRegStr)
strRegex = fmt.Sprintf("^%s(?:%s|%s)?$", strRegex, tempSuffixRegStr, tempSuffixRegOld) strRegex = fmt.Sprintf("^%s(?:%s|%s)?$", strRegex, tempSuffixRegStr, tempSuffixRegOld)
f.nameRegexp = regexp.MustCompile(strRegex) f.nameRegexp = regexp.MustCompile(strRegex)
@ -524,7 +524,7 @@ func (f *Fs) setChunkNameFormat(pattern string) error {
if numDigits > 1 { if numDigits > 1 {
fmtDigits = fmt.Sprintf("%%0%dd", numDigits) fmtDigits = fmt.Sprintf("%%0%dd", numDigits)
} }
strFmt := strings.Replace(pattern, "%", "%%", -1) strFmt := strings.ReplaceAll(pattern, "%", "%%")
strFmt = strings.Replace(strFmt, "*", "%s", 1) strFmt = strings.Replace(strFmt, "*", "%s", 1)
f.dataNameFmt = reHashes.ReplaceAllLiteralString(strFmt, fmtDigits) f.dataNameFmt = reHashes.ReplaceAllLiteralString(strFmt, fmtDigits)
f.ctrlNameFmt = reHashes.ReplaceAllLiteralString(strFmt, "_%s") f.ctrlNameFmt = reHashes.ReplaceAllLiteralString(strFmt, "_%s")

View File

@ -829,8 +829,8 @@ func (f *Fs) list(ctx context.Context, dirIDs []string, title string, directorie
if title != "" { if title != "" {
searchTitle := f.opt.Enc.FromStandardName(title) searchTitle := f.opt.Enc.FromStandardName(title)
// Escaping the backslash isn't documented but seems to work // Escaping the backslash isn't documented but seems to work
searchTitle = strings.Replace(searchTitle, `\`, `\\`, -1) searchTitle = strings.ReplaceAll(searchTitle, `\`, `\\`)
searchTitle = strings.Replace(searchTitle, `'`, `\'`, -1) searchTitle = strings.ReplaceAll(searchTitle, `'`, `\'`)
var titleQuery bytes.Buffer var titleQuery bytes.Buffer
_, _ = fmt.Fprintf(&titleQuery, "(name='%s'", searchTitle) _, _ = fmt.Fprintf(&titleQuery, "(name='%s'", searchTitle)

View File

@ -562,7 +562,7 @@ func (f *Fs) list(ctx context.Context, filter api.SearchFilter, fn listFn) (err
for i := range items { for i := range items {
item := &result.MediaItems[i] item := &result.MediaItems[i]
remote := item.Filename remote := item.Filename
remote = strings.Replace(remote, "/", "", -1) remote = strings.ReplaceAll(remote, "/", "")
err = fn(remote, item, false) err = fn(remote, item, false)
if err != nil { if err != nil {
return err return err

View File

@ -119,7 +119,7 @@ func (f *Fs) getCredentials(ctx context.Context) (err error) {
defer fs.CheckClose(resp.Body, &err) defer fs.CheckClose(resp.Body, &err)
if resp.StatusCode < 200 || resp.StatusCode > 299 { if resp.StatusCode < 200 || resp.StatusCode > 299 {
body, _ := ioutil.ReadAll(resp.Body) body, _ := ioutil.ReadAll(resp.Body)
bodyStr := strings.TrimSpace(strings.Replace(string(body), "\n", " ", -1)) bodyStr := strings.TrimSpace(strings.ReplaceAll(string(body), "\n", " "))
return fmt.Errorf("failed to get credentials: %s: %s", resp.Status, bodyStr) return fmt.Errorf("failed to get credentials: %s: %s", resp.Status, bodyStr)
} }
decoder := json.NewDecoder(resp.Body) decoder := json.NewDecoder(resp.Body)

View File

@ -191,7 +191,7 @@ machines.`)
m.Set("auth_code", "") m.Set("auth_code", "")
return fs.ConfigGoto("legacy_do_auth") return fs.ConfigGoto("legacy_do_auth")
case "legacy_auth_code": case "legacy_auth_code":
authCode := strings.Replace(config.Result, "-", "", -1) // remove any "-" contained in the code so we have a 6 digit number authCode := strings.ReplaceAll(config.Result, "-", "") // remove any "-" contained in the code so we have a 6 digit number
m.Set("auth_code", authCode) m.Set("auth_code", authCode)
return fs.ConfigGoto("legacy_do_auth") return fs.ConfigGoto("legacy_do_auth")
case "legacy_do_auth": case "legacy_do_auth":
@ -649,7 +649,7 @@ func errorHandler(resp *http.Response) error {
// Jottacloud wants '+' to be URL encoded even though the RFC states it's not reserved // Jottacloud wants '+' to be URL encoded even though the RFC states it's not reserved
func urlPathEscape(in string) string { func urlPathEscape(in string) string {
return strings.Replace(rest.URLPathEscape(in), "+", "%2B", -1) return strings.ReplaceAll(rest.URLPathEscape(in), "+", "%2B")
} }
// filePathRaw returns an unescaped file path (f.root, file) // filePathRaw returns an unescaped file path (f.root, file)

View File

@ -2966,7 +2966,7 @@ func (f *Fs) Precision() time.Duration {
// pathEscape escapes s as for a URL path. It uses rest.URLPathEscape // pathEscape escapes s as for a URL path. It uses rest.URLPathEscape
// but also escapes '+' for S3 and Digital Ocean spaces compatibility // but also escapes '+' for S3 and Digital Ocean spaces compatibility
func pathEscape(s string) string { func pathEscape(s string) string {
return strings.Replace(rest.URLPathEscape(s), "+", "%2B", -1) return strings.ReplaceAll(rest.URLPathEscape(s), "+", "%2B")
} }
// copy does a server-side copy // copy does a server-side copy

View File

@ -109,7 +109,7 @@ when the ssh-agent contains many keys.`,
Default: false, Default: false,
}, { }, {
Name: "use_insecure_cipher", Name: "use_insecure_cipher",
Help: `Enable the use of insecure ciphers and key exchange methods. Help: `Enable the use of insecure ciphers and key exchange methods.
This enables the use of the following insecure ciphers and key exchange methods: This enables the use of the following insecure ciphers and key exchange methods:
@ -1311,7 +1311,7 @@ var shellEscapeRegex = regexp.MustCompile("[^A-Za-z0-9_.,:/\\@\u0080-\uFFFFFFFF\
// when sending it to a shell. // when sending it to a shell.
func shellEscape(str string) string { func shellEscape(str string) string {
safe := shellEscapeRegex.ReplaceAllString(str, `\$0`) safe := shellEscapeRegex.ReplaceAllString(str, `\$0`)
return strings.Replace(safe, "\n", "'\n'", -1) return strings.ReplaceAll(safe, "\n", "'\n'")
} }
// Converts a byte array from the SSH session returned by // Converts a byte array from the SSH session returned by

View File

@ -173,8 +173,8 @@ func buildZip(dir string) string {
func buildDebAndRpm(dir, version, goarch string) []string { func buildDebAndRpm(dir, version, goarch string) []string {
// Make internal version number acceptable to .deb and .rpm // Make internal version number acceptable to .deb and .rpm
pkgVersion := version[1:] pkgVersion := version[1:]
pkgVersion = strings.Replace(pkgVersion, "β", "-beta", -1) pkgVersion = strings.ReplaceAll(pkgVersion, "β", "-beta")
pkgVersion = strings.Replace(pkgVersion, "-", ".", -1) pkgVersion = strings.ReplaceAll(pkgVersion, "-", ".")
nfpmArch, ok := goarchToNfpm[goarch] nfpmArch, ok := goarchToNfpm[goarch]
if !ok { if !ok {
nfpmArch = goarch nfpmArch = goarch

View File

@ -79,7 +79,7 @@ rclone.org website.`,
var description = map[string]string{} var description = map[string]string{}
var addDescription func(root *cobra.Command) var addDescription func(root *cobra.Command)
addDescription = func(root *cobra.Command) { addDescription = func(root *cobra.Command) {
name := strings.Replace(root.CommandPath(), " ", "_", -1) + ".md" name := strings.ReplaceAll(root.CommandPath(), " ", "_") + ".md"
description[name] = root.Short description[name] = root.Short
for _, c := range root.Commands() { for _, c := range root.Commands() {
addDescription(c) addDescription(c)
@ -93,11 +93,11 @@ rclone.org website.`,
base := strings.TrimSuffix(name, path.Ext(name)) base := strings.TrimSuffix(name, path.Ext(name))
data := frontmatter{ data := frontmatter{
Date: now, Date: now,
Title: strings.Replace(base, "_", " ", -1), Title: strings.ReplaceAll(base, "_", " "),
Description: description[name], Description: description[name],
Slug: base, Slug: base,
URL: "/commands/" + strings.ToLower(base) + "/", URL: "/commands/" + strings.ToLower(base) + "/",
Source: strings.Replace(strings.Replace(base, "rclone", "cmd", -1), "_", "/", -1) + "/", Source: strings.ReplaceAll(strings.ReplaceAll(base, "rclone", "cmd"), "_", "/") + "/",
} }
var buf bytes.Buffer var buf bytes.Buffer
err := frontmatterTemplate.Execute(&buf, data) err := frontmatterTemplate.Execute(&buf, data)

View File

@ -290,7 +290,7 @@ func list(ctx context.Context) error {
if !ok { if !ok {
return errors.New("bad JSON") return errors.New("bad JSON")
} }
fmt.Printf("### %s: %s {#%s}\n\n", info["Path"], info["Title"], strings.Replace(info["Path"].(string), "/", "-", -1)) fmt.Printf("### %s: %s {#%s}\n\n", info["Path"], info["Title"], strings.ReplaceAll(info["Path"].(string), "/", "-"))
fmt.Printf("%s\n\n", info["Help"]) fmt.Printf("%s\n\n", info["Help"])
if authRequired := info["AuthRequired"]; authRequired != nil { if authRequired := info["AuthRequired"]; authRequired != nil {
if authRequired.(bool) { if authRequired.(bool) {

View File

@ -43,7 +43,7 @@ var shellUnEscapeRegex = regexp.MustCompile(`\\(.)`)
// Unescape a string that was escaped by rclone // Unescape a string that was escaped by rclone
func shellUnEscape(str string) string { func shellUnEscape(str string) string {
str = strings.Replace(str, "'\n'", "\n", -1) str = strings.ReplaceAll(str, "'\n'", "\n")
str = shellUnEscapeRegex.ReplaceAllString(str, `$1`) str = shellUnEscapeRegex.ReplaceAllString(str, `$1`)
return str return str
} }

View File

@ -230,7 +230,7 @@ func ConfigChoose(state string, name string, help string, n int, getItem func(i
// StatePush pushes a new values onto the front of the config string // StatePush pushes a new values onto the front of the config string
func StatePush(state string, values ...string) string { func StatePush(state string, values ...string) string {
for i := range values { for i := range values {
values[i] = strings.Replace(values[i], ",", "", -1) // replace comma with unicode wide version values[i] = strings.ReplaceAll(values[i], ",", "") // replace comma with unicode wide version
} }
if state != "" { if state != "" {
values = append(values[:len(values):len(values)], state) values = append(values[:len(values):len(values)], state)
@ -262,7 +262,7 @@ func StatePop(state string) (newState string, value string) {
return "", state return "", state
} }
value, newState = state[:comma], state[comma+1:] value, newState = state[:comma], state[comma+1:]
value = strings.Replace(value, "", ",", -1) // replace unicode wide comma with comma value = strings.ReplaceAll(value, "", ",") // replace unicode wide comma with comma
return newState, value return newState, value
} }

View File

@ -248,11 +248,11 @@ func AddConfig(ctx context.Context) (context.Context, *ConfigInfo) {
// "ignore-size") into an environment name // "ignore-size") into an environment name
// "RCLONE_CONFIG_MY-REMOTE_IGNORE_SIZE" // "RCLONE_CONFIG_MY-REMOTE_IGNORE_SIZE"
func ConfigToEnv(section, name string) string { func ConfigToEnv(section, name string) string {
return "RCLONE_CONFIG_" + strings.ToUpper(section+"_"+strings.Replace(name, "-", "_", -1)) return "RCLONE_CONFIG_" + strings.ToUpper(section+"_"+strings.ReplaceAll(name, "-", "_"))
} }
// OptionToEnv converts an option name, e.g. "ignore-size" into an // OptionToEnv converts an option name, e.g. "ignore-size" into an
// environment name "RCLONE_IGNORE_SIZE" // environment name "RCLONE_IGNORE_SIZE"
func OptionToEnv(name string) string { func OptionToEnv(name string) string {
return "RCLONE_" + strings.ToUpper(strings.Replace(name, "-", "_", -1)) return "RCLONE_" + strings.ToUpper(strings.ReplaceAll(name, "-", "_"))
} }

View File

@ -50,7 +50,7 @@ func setConfigFile(t *testing.T, data string) func() {
// toUnix converts \r\n to \n in buf // toUnix converts \r\n to \n in buf
func toUnix(buf string) string { func toUnix(buf string) string {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
return strings.Replace(buf, "\r\n", "\n", -1) return strings.ReplaceAll(buf, "\r\n", "\n")
} }
return buf return buf
} }

View File

@ -417,7 +417,7 @@ func ChooseOption(o *fs.Option, name string) string {
fmt.Printf("Option %s.\n", o.Name) fmt.Printf("Option %s.\n", o.Name)
if o.Help != "" { if o.Help != "" {
// Show help string without empty lines. // Show help string without empty lines.
help := strings.Replace(strings.TrimSpace(o.Help), "\n\n", "\n", -1) help := strings.ReplaceAll(strings.TrimSpace(o.Help), "\n\n", "\n")
fmt.Println(help) fmt.Println(help)
} }

View File

@ -208,7 +208,7 @@ loop:
value := path[prev : i-1] value := path[prev : i-1]
// replace any doubled quotes if there were any // replace any doubled quotes if there were any
if doubled { if doubled {
value = strings.Replace(value, string(quote)+string(quote), string(quote), -1) value = strings.ReplaceAll(value, string(quote)+string(quote), string(quote))
} }
prev = i + 1 prev = i + 1
parsed.Config[param] = value parsed.Config[param] = value

View File

@ -1407,7 +1407,7 @@ func TestDirMove(t *testing.T) {
require.NoError(t, operations.DirMove(ctx, r.Fremote, "A1", "A2")) require.NoError(t, operations.DirMove(ctx, r.Fremote, "A1", "A2"))
for i := range files { for i := range files {
files[i].Path = strings.Replace(files[i].Path, "A1/", "A2/", -1) files[i].Path = strings.ReplaceAll(files[i].Path, "A1/", "A2/")
} }
fstest.CheckListingWithPrecision( fstest.CheckListingWithPrecision(
@ -1432,7 +1432,7 @@ func TestDirMove(t *testing.T) {
require.NoError(t, operations.DirMove(ctx, r.Fremote, "A2", "A3")) require.NoError(t, operations.DirMove(ctx, r.Fremote, "A2", "A3"))
for i := range files { for i := range files {
files[i].Path = strings.Replace(files[i].Path, "A2/", "A3/", -1) files[i].Path = strings.ReplaceAll(files[i].Path, "A2/", "A3/")
} }
fstest.CheckListingWithPrecision( fstest.CheckListingWithPrecision(

View File

@ -44,7 +44,7 @@ type RegInfo struct {
// FileName returns the on disk file name for this backend // FileName returns the on disk file name for this backend
func (ri *RegInfo) FileName() string { func (ri *RegInfo) FileName() string {
return strings.Replace(ri.Name, " ", "", -1) return strings.ReplaceAll(ri.Name, " ", "")
} }
// Options is a slice of configuration Option for a backend // Options is a slice of configuration Option for a backend
@ -210,7 +210,7 @@ func (o *Option) Type() string {
// FlagName for the option // FlagName for the option
func (o *Option) FlagName(prefix string) string { func (o *Option) FlagName(prefix string) string {
name := strings.Replace(o.Name, "_", "-", -1) // convert snake_case to kebab-case name := strings.ReplaceAll(o.Name, "_", "-") // convert snake_case to kebab-case
if !o.NoPrefix { if !o.NoPrefix {
name = prefix + "-" + name name = prefix + "-" + name
} }

View File

@ -317,7 +317,7 @@ func (r *Run) RemoveTestBinary() {
func (r *Run) Name() string { func (r *Run) Name() string {
ns := []string{ ns := []string{
r.Backend, r.Backend,
strings.Replace(r.Path, "/", ".", -1), strings.ReplaceAll(r.Path, "/", "."),
r.Remote, r.Remote,
} }
if r.FastList { if r.FastList {
@ -325,7 +325,7 @@ func (r *Run) Name() string {
} }
ns = append(ns, fmt.Sprintf("%d", r.Try)) ns = append(ns, fmt.Sprintf("%d", r.Try))
s := strings.Join(ns, "-") s := strings.Join(ns, "-")
s = strings.Replace(s, ":", "", -1) s = strings.ReplaceAll(s, ":", "")
return s return s
} }

View File

@ -30,7 +30,7 @@ func Add(fileName string, t time.Time) string {
base, ext := splitExt(fileName) base, ext := splitExt(fileName)
s := t.Format(versionFormat) s := t.Format(versionFormat)
// Replace the '.' with a '-' // Replace the '.' with a '-'
s = strings.Replace(s, ".", "-", -1) s = strings.ReplaceAll(s, ".", "-")
return base + s + ext return base + s + ext
} }