refactor: replace strings.Replace with strings.ReplaceAll (#15392)

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-08-04 03:22:48 +08:00 committed by GitHub
parent f7cb95968e
commit 61262ad98e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 56 additions and 56 deletions

View File

@ -60,19 +60,19 @@ func (d *OutputStringError) buildCurlString() (string, error) {
finalCurlString = fmt.Sprintf("%s-X %s ", finalCurlString, d.Request.Method)
}
if d.ClientCACert != "" {
clientCACert := strings.Replace(d.ClientCACert, "'", "'\"'\"'", -1)
clientCACert := strings.ReplaceAll(d.ClientCACert, "'", "'\"'\"'")
finalCurlString = fmt.Sprintf("%s--cacert '%s' ", finalCurlString, clientCACert)
}
if d.ClientCAPath != "" {
clientCAPath := strings.Replace(d.ClientCAPath, "'", "'\"'\"'", -1)
clientCAPath := strings.ReplaceAll(d.ClientCAPath, "'", "'\"'\"'")
finalCurlString = fmt.Sprintf("%s--capath '%s' ", finalCurlString, clientCAPath)
}
if d.ClientCert != "" {
clientCert := strings.Replace(d.ClientCert, "'", "'\"'\"'", -1)
clientCert := strings.ReplaceAll(d.ClientCert, "'", "'\"'\"'")
finalCurlString = fmt.Sprintf("%s--cert '%s' ", finalCurlString, clientCert)
}
if d.ClientKey != "" {
clientKey := strings.Replace(d.ClientKey, "'", "'\"'\"'", -1)
clientKey := strings.ReplaceAll(d.ClientKey, "'", "'\"'\"'")
finalCurlString = fmt.Sprintf("%s--key '%s' ", finalCurlString, clientKey)
}
for k, v := range d.Request.Header {
@ -87,7 +87,7 @@ func (d *OutputStringError) buildCurlString() (string, error) {
if len(body) > 0 {
// We need to escape single quotes since that's what we're using to
// quote the body
escapedBody := strings.Replace(string(body), "'", "'\"'\"'", -1)
escapedBody := strings.ReplaceAll(string(body), "'", "'\"'\"'")
finalCurlString = fmt.Sprintf("%s-d '%s' ", finalCurlString, escapedBody)
}

View File

@ -50,7 +50,7 @@ func (b *backend) pathCredsCreateRead(ctx context.Context, req *logical.Request,
return nil, err
}
username := fmt.Sprintf("vault_%s_%s_%s_%d", name, displayName, userUUID, time.Now().Unix())
username = strings.Replace(username, "-", "_", -1)
username = strings.ReplaceAll(username, "-", "_")
password, err := uuid.GenerateUUID()
if err != nil {
return nil, err

View File

@ -15,7 +15,7 @@ import (
// Query templates a query for us.
func substQuery(tpl string, data map[string]string) string {
for k, v := range data {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
tpl = strings.ReplaceAll(tpl, fmt.Sprintf("{{%s}}", k), v)
}
return tpl

View File

@ -711,7 +711,7 @@ func TestBackend_connectionCrud(t *testing.T) {
// Replace connection url with templated version
req.Operation = logical.UpdateOperation
connURL = strings.Replace(connURL, "postgres:secret", "{{username}}:{{password}}", -1)
connURL = strings.ReplaceAll(connURL, "postgres:secret", "{{username}}:{{password}}")
data["connection_url"] = connURL
resp, err = b.HandleRequest(namespace.RootContext(nil), req)
if err != nil || (resp != nil && resp.IsError()) {
@ -1267,7 +1267,7 @@ func TestBackend_RotateRootCredentials(t *testing.T) {
cleanup, connURL := postgreshelper.PrepareTestContainer(t, "13.4-buster")
defer cleanup()
connURL = strings.Replace(connURL, "postgres:secret", "{{username}}:{{password}}", -1)
connURL = strings.ReplaceAll(connURL, "postgres:secret", "{{username}}:{{password}}")
// Configure a connection
data := map[string]interface{}{

View File

@ -44,7 +44,7 @@ func TestBackend_RotateRootCredentials_WAL_rollback(t *testing.T) {
cleanup, connURL := postgreshelper.PrepareTestContainer(t, "")
defer cleanup()
connURL = strings.Replace(connURL, "postgres:secret", "{{username}}:{{password}}", -1)
connURL = strings.ReplaceAll(connURL, "postgres:secret", "{{username}}:{{password}}")
// Configure a connection to the database
data := map[string]interface{}{
@ -183,7 +183,7 @@ func TestBackend_RotateRootCredentials_WAL_no_rollback_1(t *testing.T) {
cleanup, connURL := postgreshelper.PrepareTestContainer(t, "")
defer cleanup()
connURL = strings.Replace(connURL, "postgres:secret", "{{username}}:{{password}}", -1)
connURL = strings.ReplaceAll(connURL, "postgres:secret", "{{username}}:{{password}}")
// Configure a connection to the database
data := map[string]interface{}{
@ -291,7 +291,7 @@ func TestBackend_RotateRootCredentials_WAL_no_rollback_2(t *testing.T) {
cleanup, connURL := postgreshelper.PrepareTestContainer(t, "")
defer cleanup()
connURL = strings.Replace(connURL, "postgres:secret", "{{username}}:{{password}}", -1)
connURL = strings.ReplaceAll(connURL, "postgres:secret", "{{username}}:{{password}}")
// Configure a connection to the database
data := map[string]interface{}{

View File

@ -21,7 +21,7 @@ func SplitSQL(sql string) []string {
// Query templates a query for us.
func Query(tpl string, data map[string]string) string {
for k, v := range data {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
tpl = strings.ReplaceAll(tpl, fmt.Sprintf("{{%s}}", k), v)
}
return tpl

View File

@ -18,7 +18,7 @@ const SecretCredsType = "creds"
// grants, at least we ensure that the open connection is useless. Dropping the
// user will only affect the next connection.
const defaultRevocationSQL = `
REVOKE ALL PRIVILEGES, GRANT OPTION FROM '{{name}}'@'%';
REVOKE ALL PRIVILEGES, GRANT OPTION FROM '{{name}}'@'%';
DROP USER '{{name}}'@'%'
`
@ -119,7 +119,7 @@ func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d
// This is not a prepared statement because not all commands are supported
// 1295: This command is not supported in the prepared statement protocol yet
// Reference https://mariadb.com/kb/en/mariadb/prepare-statement/
query = strings.Replace(query, "{{name}}", username, -1)
query = strings.ReplaceAll(query, "{{name}}", username)
_, err = tx.Exec(query)
if err != nil {
return nil, err

View File

@ -8,7 +8,7 @@ import (
// Query templates a query for us.
func Query(tpl string, data map[string]string) string {
for k, v := range data {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
tpl = strings.ReplaceAll(tpl, fmt.Sprintf("{{%s}}", k), v)
}
return tpl

View File

@ -161,7 +161,7 @@ func fetchCertBySerial(ctx context.Context, b *backend, req *logical.Request, pr
var certEntry *logical.StorageEntry
hyphenSerial := normalizeSerial(serial)
colonSerial := strings.Replace(strings.ToLower(serial), "-", ":", -1)
colonSerial := strings.ReplaceAll(strings.ToLower(serial), "-", ":")
switch {
// Revoked goes first as otherwise crl get hardcoded paths which fail if

View File

@ -150,7 +150,7 @@ func revokeCert(ctx context.Context, b *backend, req *logical.Request, serial st
return nil, errutil.InternalError{Err: "stored CA information not able to be parsed"}
}
colonSerial := strings.Replace(strings.ToLower(serial), "-", ":", -1)
colonSerial := strings.ReplaceAll(strings.ToLower(serial), "-", ":")
if colonSerial == certutil.GetHexFormatted(parsedBundle.Certificate.SerialNumber.Bytes(), ":") {
return logical.ErrorResponse(fmt.Sprintf("adding issuer (id: %v) to its own CRL is not allowed", issuer)), nil
}

View File

@ -68,7 +68,7 @@ func (b *backend) pathRevokeWrite(ctx context.Context, req *logical.Request, dat
// We store and identify by lowercase colon-separated hex, but other
// utilities use dashes and/or uppercase, so normalize
serial = strings.Replace(strings.ToLower(serial), "-", ":", -1)
serial = strings.ReplaceAll(strings.ToLower(serial), "-", ":")
b.revokeStorageLock.Lock()
defer b.revokeStorageLock.Unlock()

View File

@ -26,11 +26,11 @@ var (
)
func normalizeSerial(serial string) string {
return strings.Replace(strings.ToLower(serial), ":", "-", -1)
return strings.ReplaceAll(strings.ToLower(serial), ":", "-")
}
func denormalizeSerial(serial string) string {
return strings.Replace(strings.ToLower(serial), "-", ":", -1)
return strings.ReplaceAll(strings.ToLower(serial), "-", ":")
}
func kmsRequested(input *inputBundle) bool {

View File

@ -8,7 +8,7 @@ import (
// Query templates a query for us.
func Query(tpl string, data map[string]string) string {
for k, v := range data {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
tpl = strings.ReplaceAll(tpl, fmt.Sprintf("{{%s}}", k), v)
}
return tpl

View File

@ -238,7 +238,7 @@ func convertMapToIntSlice(initial map[string]interface{}) (map[string][]int, err
// Serve a template processor for custom format inputs
func substQuery(tpl string, data map[string]string) string {
for k, v := range data {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
tpl = strings.ReplaceAll(tpl, fmt.Sprintf("{{%s}}", k), v)
}
return tpl

View File

@ -76,7 +76,7 @@ func TestTransit_HMAC(t *testing.T) {
}
// Now verify
req.Path = strings.Replace(req.Path, "hmac", "verify", -1)
req.Path = strings.ReplaceAll(req.Path, "hmac", "verify")
req.Data["hmac"] = value.(string)
resp, err = b.HandleRequest(context.Background(), req)
if err != nil {

View File

@ -190,7 +190,7 @@ func setAliCloudEnvCreds() error {
}
assumeRoleReq := sts.CreateAssumeRoleRequest()
assumeRoleReq.RoleArn = os.Getenv(envVarAlicloudRoleArn)
assumeRoleReq.RoleSessionName = strings.Replace(roleSessionName, "-", "", -1)
assumeRoleReq.RoleSessionName = strings.ReplaceAll(roleSessionName, "-", "")
assumeRoleResp, err := client.AssumeRole(assumeRoleReq)
if err != nil {
return err

View File

@ -121,7 +121,7 @@ func TestServer_ReloadListener(t *testing.T) {
inBytes, _ = ioutil.ReadFile(wd + "reload_foo.key")
ioutil.WriteFile(td+"/reload_key.pem", inBytes, 0o777)
relhcl := strings.Replace(reloadHCL, "TMPDIR", td, -1)
relhcl := strings.ReplaceAll(reloadHCL, "TMPDIR", td)
ioutil.WriteFile(td+"/reload.hcl", []byte(relhcl), 0o777)
inBytes, _ = ioutil.ReadFile(wd + "reload_ca.pem")
@ -172,7 +172,7 @@ func TestServer_ReloadListener(t *testing.T) {
t.Fatalf("certificate name didn't check out: %s", err)
}
relhcl = strings.Replace(reloadHCL, "TMPDIR", td, -1)
relhcl = strings.ReplaceAll(reloadHCL, "TMPDIR", td)
inBytes, _ = ioutil.ReadFile(wd + "reload_bar.pem")
ioutil.WriteFile(td+"/reload_cert.pem", inBytes, 0o777)
inBytes, _ = ioutil.ReadFile(wd + "reload_bar.key")

View File

@ -103,7 +103,7 @@ func (h *ExternalTokenHelper) Path() string {
}
func (h *ExternalTokenHelper) cmd(op string) (*exec.Cmd, error) {
script := strings.Replace(h.BinaryPath, "\\", "\\\\", -1) + " " + op
script := strings.ReplaceAll(h.BinaryPath, "\\", "\\\\") + " " + op
cmd, err := ExecScript(script)
if err != nil {
return nil, err

View File

@ -68,7 +68,7 @@ func TestPubKeyFilesFlagSetBinary(t *testing.T) {
t.Fatalf("err: should not have been able to set a second value")
}
expected := []string{strings.Replace(pubKey1, "\n", "", -1), strings.Replace(pubKey2, "\n", "", -1)}
expected := []string{strings.ReplaceAll(pubKey1, "\n", ""), strings.ReplaceAll(pubKey2, "\n", "")}
if !reflect.DeepEqual(pkf.String(), fmt.Sprint(expected)) {
t.Fatalf("Bad: %#v", pkf)
}

View File

@ -122,8 +122,8 @@ func decoratePath(path string) ([]byte, error) {
// Turn a decorated byte array back into a path string
func undecoratePath(decoratedPath []byte) string {
ret := strings.Replace(string(decoratedPath), dirPathMarker, "/", -1)
ret = strings.Replace(ret, dirEntryMarker, "/", -1)
ret := strings.ReplaceAll(string(decoratedPath), dirPathMarker, "/")
ret = strings.ReplaceAll(ret, dirEntryMarker, "/")
return strings.TrimLeft(ret, "/")
}

View File

@ -371,5 +371,5 @@ func sanitizeTable(s string) string {
if end > -1 {
s = s[:end]
}
return strings.Replace(s, `"`, `""`, -1)
return strings.ReplaceAll(s, `"`, `""`)
}

View File

@ -106,7 +106,7 @@ func (h *HANA) NewUser(ctx context.Context, req dbplugin.NewUserRequest) (respon
}
// HANA does not allow hyphens in usernames, and highly prefers capital letters
username = strings.Replace(username, "-", "_", -1)
username = strings.ReplaceAll(username, "-", "_")
username = strings.ToUpper(username)
// If expiration is in the role SQL, HANA will deactivate the user when time is up,

View File

@ -16,7 +16,7 @@ import (
const (
defaultMysqlRevocationStmts = `
REVOKE ALL PRIVILEGES, GRANT OPTION FROM '{{name}}'@'%';
REVOKE ALL PRIVILEGES, GRANT OPTION FROM '{{name}}'@'%';
DROP USER '{{name}}'@'%'
`
@ -174,8 +174,8 @@ func (m *MySQL) DeleteUser(ctx context.Context, req dbplugin.DeleteUserRequest)
// This is not a prepared statement because not all commands are supported
// 1295: This command is not supported in the prepared statement protocol yet
// Reference https://mariadb.com/kb/en/mariadb/prepare-statement/
query = strings.Replace(query, "{{name}}", req.Username, -1)
query = strings.Replace(query, "{{username}}", req.Username, -1)
query = strings.ReplaceAll(query, "{{name}}", req.Username)
query = strings.ReplaceAll(query, "{{username}}", req.Username)
_, err = tx.ExecContext(ctx, query)
if err != nil {
return dbplugin.DeleteUserResponse{}, err

View File

@ -482,7 +482,7 @@ func containsMultilineStatement(stmt string) bool {
}
stmtWithoutLiterals := stmt
for _, literal := range literals {
stmtWithoutLiterals = strings.Replace(stmt, literal, "", -1)
stmtWithoutLiterals = strings.ReplaceAll(stmt, literal, "")
}
// Now look for the word "END" specifically. This will miss any
// representations of END that aren't surrounded by spaces, but

View File

@ -323,11 +323,11 @@ func (mw *DatabaseErrorSanitizerMiddleware) sanitize(err error) error {
// error without changing the actual error message
s, ok := status.FromError(err)
if ok {
err = status.Error(s.Code(), strings.Replace(s.Message(), k, v.(string), -1))
err = status.Error(s.Code(), strings.ReplaceAll(s.Message(), k, v.(string)))
continue
}
err = errors.New(strings.Replace(err.Error(), k, v.(string), -1))
err = errors.New(strings.ReplaceAll(err.Error(), k, v.(string)))
}
}
return err

View File

@ -264,11 +264,11 @@ func (mw DatabaseErrorSanitizerMiddleware) sanitize(err error) error {
// error while changing the actual error message
s, ok := status.FromError(err)
if ok {
err = status.Error(s.Code(), strings.Replace(s.Message(), find, replace, -1))
err = status.Error(s.Code(), strings.ReplaceAll(s.Message(), find, replace))
continue
}
err = errors.New(strings.Replace(err.Error(), find, replace, -1))
err = errors.New(strings.ReplaceAll(err.Error(), find, replace))
}
return err
}

View File

@ -18,7 +18,7 @@ var (
// Query templates a query for us.
func QueryHelper(tpl string, data map[string]string) string {
for k, v := range data {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
tpl = strings.ReplaceAll(tpl, fmt.Sprintf("{{%s}}", k), v)
}
return tpl

View File

@ -41,5 +41,5 @@ func QuoteIdentifier(name string) string {
if end > -1 {
name = name[:end]
}
return `"` + strings.Replace(name, `"`, `""`, -1) + `"`
return `"` + strings.ReplaceAll(name, `"`, `""`) + `"`
}

View File

@ -553,7 +553,7 @@ func expandPattern(pattern string) []string {
if start != -1 && end != -1 && end > start {
regexToRemove = base[start+1 : end]
}
pattern = strings.Replace(pattern, regexToRemove, "", -1)
pattern = strings.ReplaceAll(pattern, regexToRemove, "")
// Simplify named fields that have limited options, e.g. (?P<foo>a|b|c) -> (<P<foo>.+)
pattern = altFieldsGroupRe.ReplaceAllStringFunc(pattern, func(s string) string {
@ -767,7 +767,7 @@ func (d *OASDocument) CreateOperationIDs(context string) {
// Space-split on non-words, title case everything, recombine
opID := nonWordRe.ReplaceAllString(strings.ToLower(path), " ")
opID = strings.Title(opID)
opID = method + strings.Replace(opID, " ", "", -1)
opID = method + strings.ReplaceAll(opID, " ", "")
// deduplicate operationIds. This is a safeguard, since generated IDs should
// already be unique given our current path naming conventions.

View File

@ -77,7 +77,7 @@ func parseQuery(m map[string]string, tpl string) string {
}
for k, v := range m {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
tpl = strings.ReplaceAll(tpl, fmt.Sprintf("{{%s}}", k), v)
}
return tpl
}

View File

@ -1716,7 +1716,7 @@ func (p *Policy) getVersionPrefix(ver int) string {
template = DefaultVersionTemplate
}
prefix := strings.Replace(template, "{{version}}", strconv.Itoa(ver), -1)
prefix := strings.ReplaceAll(template, "{{version}}", strconv.Itoa(ver))
p.versionPrefixCache.Store(ver, prefix)
return prefix

View File

@ -333,7 +333,7 @@ func TLSCAFileCheck(CAFilePath string) ([]string, error) {
// Check for TLS Warnings
warnings, err = TLSFileWarningChecks(leafCerts, interCerts, rootCerts)
for i, warning := range warnings {
warnings[i] = strings.Replace(warning, "leaf", "root", -1)
warnings[i] = strings.ReplaceAll(warning, "leaf", "root")
}
warningsSlc = append(warningsSlc, warnings...)
if err != nil {
@ -345,7 +345,7 @@ func TLSCAFileCheck(CAFilePath string) ([]string, error) {
// Check for TLS Errors
if err = TLSErrorChecks(leafCerts, interCerts, rootCerts); err != nil {
return warningsSlc, fmt.Errorf(strings.Replace(err.Error(), "leaf", "root", -1))
return warningsSlc, fmt.Errorf(strings.ReplaceAll(err.Error(), "leaf", "root"))
}
return warningsSlc, err

View File

@ -1739,13 +1739,13 @@ func formatUsername(format string, alias *identity.Alias, entity *identity.Entit
}
username := format
username = strings.Replace(username, "{{alias.name}}", alias.Name, -1)
username = strings.Replace(username, "{{entity.name}}", entity.Name, -1)
username = strings.ReplaceAll(username, "{{alias.name}}", alias.Name)
username = strings.ReplaceAll(username, "{{entity.name}}", entity.Name)
for k, v := range alias.Metadata {
username = strings.Replace(username, fmt.Sprintf("{{alias.metadata.%s}}", k), v, -1)
username = strings.ReplaceAll(username, fmt.Sprintf("{{alias.metadata.%s}}", k), v)
}
for k, v := range entity.Metadata {
username = strings.Replace(username, fmt.Sprintf("{{entity.metadata.%s}}", k), v, -1)
username = strings.ReplaceAll(username, fmt.Sprintf("{{entity.metadata.%s}}", k), v)
}
return username
}

View File

@ -1623,7 +1623,7 @@ func (c *Core) LoginCreateToken(ctx context.Context, ns *namespace.Namespace, re
auth := resp.Auth
source := strings.TrimPrefix(mountPoint, credentialRoutePrefix)
source = strings.Replace(source, "/", "-", -1)
source = strings.ReplaceAll(source, "/", "-")
// Prepend the source to the display name
auth.DisplayName = strings.TrimSuffix(source+auth.DisplayName, "-")

View File

@ -164,7 +164,7 @@ func (m *RollbackManager) startOrLookupRollback(ctx context.Context, fullPath st
// attemptRollback invokes a RollbackOperation for the given path
func (m *RollbackManager) attemptRollback(ctx context.Context, fullPath string, rs *rollbackState, grabStatelock bool) (err error) {
defer metrics.MeasureSince([]string{"rollback", "attempt", strings.Replace(fullPath, "/", "-", -1)}, time.Now())
defer metrics.MeasureSince([]string{"rollback", "attempt", strings.ReplaceAll(fullPath, "/", "-")}, time.Now())
defer func() {
rs.lastError = err

View File

@ -538,7 +538,7 @@ func (r *Router) routeCommon(ctx context.Context, req *logical.Request, existenc
if !existenceCheck {
defer metrics.MeasureSince([]string{
"route", string(req.Operation),
strings.Replace(mount, "/", "-", -1),
strings.ReplaceAll(mount, "/", "-"),
}, time.Now())
}
re := raw.(*routeEntry)