simplifying if-else chains to switches (#6208)

master
Oleg Kovalov 6 years ago committed by kannappanr
parent a82500f162
commit 37de2dbd3b
  1. 3
      cmd/admin-handlers.go
  2. 6
      cmd/admin-rpc-client.go
  3. 7
      cmd/bool-flag.go
  4. 7
      cmd/common-main.go
  5. 14
      cmd/fs-v1-helpers.go
  6. 34
      cmd/fs-v1-rwpool.go
  7. 9
      cmd/httprange.go
  8. 7
      cmd/logger/logger.go
  9. 14
      cmd/object-api-errors.go
  10. 13
      cmd/os-reliable.go
  11. 81
      cmd/posix-errors.go
  12. 44
      cmd/posix.go
  13. 14
      cmd/postpolicyform.go
  14. 5
      cmd/xl-sets.go

@ -478,8 +478,9 @@ func toAdminAPIErrCode(err error) APIErrorCode {
switch err { switch err {
case errXLWriteQuorum: case errXLWriteQuorum:
return ErrAdminConfigNoQuorum return ErrAdminConfigNoQuorum
default:
return toAPIErrorCode(err)
} }
return toAPIErrorCode(err)
} }
// SetConfigResult - represents detailed results of a set-config // SetConfigResult - represents detailed results of a set-config

@ -398,14 +398,16 @@ func getValidServerConfig(serverConfigs []serverConfig, errs []error) (scv serve
// seen. See example above for // seen. See example above for
// clarity. // clarity.
continue continue
} else if j < i && serverConfigs[i].ConfigDiff(&serverConfigs[j]) == "" { }
if j < i && serverConfigs[i].ConfigDiff(&serverConfigs[j]) == "" {
// serverConfigs[i] is equal to // serverConfigs[i] is equal to
// serverConfigs[j], update // serverConfigs[j], update
// serverConfigs[j]'s counter since it // serverConfigs[j]'s counter since it
// is the lower index. // is the lower index.
configCounter[j]++ configCounter[j]++
break break
} else if j == i { }
if j == i {
// serverConfigs[i] is equal to no // serverConfigs[i] is equal to no
// other value seen before. It is // other value seen before. It is
// unique so far. // unique so far.

@ -56,11 +56,12 @@ func (bf *BoolFlag) UnmarshalJSON(data []byte) (err error) {
// ParseBoolFlag - parses string into BoolFlag. // ParseBoolFlag - parses string into BoolFlag.
func ParseBoolFlag(s string) (bf BoolFlag, err error) { func ParseBoolFlag(s string) (bf BoolFlag, err error) {
if s == "on" { switch s {
case "on":
bf = true bf = true
} else if s == "off" { case "off":
bf = false bf = false
} else { default:
err = fmt.Errorf("invalid value ‘%s’ for BoolFlag", s) err = fmt.Errorf("invalid value ‘%s’ for BoolFlag", s)
} }

@ -99,9 +99,10 @@ func handleCommonCmdArgs(ctx *cli.Context) {
var configDir string var configDir string
if ctx.IsSet("config-dir") { switch {
case ctx.IsSet("config-dir"):
configDir = ctx.String("config-dir") configDir = ctx.String("config-dir")
} else if ctx.GlobalIsSet("config-dir") { case ctx.GlobalIsSet("config-dir"):
configDir = ctx.GlobalString("config-dir") configDir = ctx.GlobalString("config-dir")
// cli package does not expose parent's "config-dir" option. Below code is workaround. // cli package does not expose parent's "config-dir" option. Below code is workaround.
if configDir == "" || configDir == getConfigDir() { if configDir == "" || configDir == getConfigDir() {
@ -109,7 +110,7 @@ func handleCommonCmdArgs(ctx *cli.Context) {
configDir = ctx.Parent().GlobalString("config-dir") configDir = ctx.Parent().GlobalString("config-dir")
} }
} }
} else { default:
// Neither local nor global config-dir option is provided. In this case, try to use // Neither local nor global config-dir option is provided. In this case, try to use
// default config directory. // default config directory.
configDir = getConfigDir() configDir = getConfigDir()

@ -121,23 +121,25 @@ func fsMkdir(ctx context.Context, dirPath string) (err error) {
} }
if err = os.Mkdir((dirPath), 0777); err != nil { if err = os.Mkdir((dirPath), 0777); err != nil {
if os.IsExist(err) { switch {
case os.IsExist(err):
return errVolumeExists return errVolumeExists
} else if os.IsPermission(err) { case os.IsPermission(err):
logger.LogIf(ctx, errDiskAccessDenied) logger.LogIf(ctx, errDiskAccessDenied)
return errDiskAccessDenied return errDiskAccessDenied
} else if isSysErrNotDir(err) { case isSysErrNotDir(err):
// File path cannot be verified since // File path cannot be verified since
// one of the parents is a file. // one of the parents is a file.
logger.LogIf(ctx, errDiskAccessDenied) logger.LogIf(ctx, errDiskAccessDenied)
return errDiskAccessDenied return errDiskAccessDenied
} else if isSysErrPathNotFound(err) { case isSysErrPathNotFound(err):
// Add specific case for windows. // Add specific case for windows.
logger.LogIf(ctx, errDiskAccessDenied) logger.LogIf(ctx, errDiskAccessDenied)
return errDiskAccessDenied return errDiskAccessDenied
default:
logger.LogIf(ctx, err)
return err
} }
logger.LogIf(ctx, err)
return err
} }
return nil return nil

@ -93,18 +93,20 @@ func (fsi *fsIOPool) Open(path string) (*lock.RLockedFile, error) {
// Open file for reading with read lock. // Open file for reading with read lock.
newRlkFile, err := lock.RLockedOpenFile(path) newRlkFile, err := lock.RLockedOpenFile(path)
if err != nil { if err != nil {
if os.IsNotExist(err) { switch {
case os.IsNotExist(err):
return nil, errFileNotFound return nil, errFileNotFound
} else if os.IsPermission(err) { case os.IsPermission(err):
return nil, errFileAccessDenied return nil, errFileAccessDenied
} else if isSysErrIsDir(err) { case isSysErrIsDir(err):
return nil, errIsNotRegular return nil, errIsNotRegular
} else if isSysErrNotDir(err) { case isSysErrNotDir(err):
return nil, errFileAccessDenied return nil, errFileAccessDenied
} else if isSysErrPathNotFound(err) { case isSysErrPathNotFound(err):
return nil, errFileNotFound return nil, errFileNotFound
default:
return nil, err
} }
return nil, err
} }
/// Save new reader on the map. /// Save new reader on the map.
@ -148,14 +150,16 @@ func (fsi *fsIOPool) Write(path string) (wlk *lock.LockedFile, err error) {
wlk, err = lock.LockedOpenFile(path, os.O_RDWR, 0666) wlk, err = lock.LockedOpenFile(path, os.O_RDWR, 0666)
if err != nil { if err != nil {
if os.IsNotExist(err) { switch {
case os.IsNotExist(err):
return nil, errFileNotFound return nil, errFileNotFound
} else if os.IsPermission(err) { case os.IsPermission(err):
return nil, errFileAccessDenied return nil, errFileAccessDenied
} else if isSysErrIsDir(err) { case isSysErrIsDir(err):
return nil, errIsNotRegular return nil, errIsNotRegular
default:
return nil, err
} }
return nil, err
} }
return wlk, nil return wlk, nil
} }
@ -175,14 +179,16 @@ func (fsi *fsIOPool) Create(path string) (wlk *lock.LockedFile, err error) {
// Attempt to create the file. // Attempt to create the file.
wlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666) wlk, err = lock.LockedOpenFile(path, os.O_RDWR|os.O_CREATE, 0666)
if err != nil { if err != nil {
if os.IsPermission(err) { switch {
case os.IsPermission(err):
return nil, errFileAccessDenied return nil, errFileAccessDenied
} else if isSysErrIsDir(err) { case isSysErrIsDir(err):
return nil, errIsNotRegular return nil, errIsNotRegular
} else if isSysErrPathNotFound(err) { case isSysErrPathNotFound(err):
return nil, errFileAccessDenied return nil, errFileAccessDenied
default:
return nil, err
} }
return nil, err
} }
// Success. // Success.

@ -89,7 +89,8 @@ func parseRequestRange(rangeString string, resourceSize int64) (hrange *httpRang
} }
// rangeString contains first and last byte positions. eg. "bytes=2-5" // rangeString contains first and last byte positions. eg. "bytes=2-5"
if offsetBegin > -1 && offsetEnd > -1 { switch {
case offsetBegin > -1 && offsetEnd > -1:
if offsetBegin > offsetEnd { if offsetBegin > offsetEnd {
// Last byte position is not greater than first byte position. eg. "bytes=5-2" // Last byte position is not greater than first byte position. eg. "bytes=5-2"
return nil, fmt.Errorf("'%s' does not have valid range value", rangeString) return nil, fmt.Errorf("'%s' does not have valid range value", rangeString)
@ -103,7 +104,7 @@ func parseRequestRange(rangeString string, resourceSize int64) (hrange *httpRang
if offsetEnd >= resourceSize { if offsetEnd >= resourceSize {
offsetEnd = resourceSize - 1 offsetEnd = resourceSize - 1
} }
} else if offsetBegin > -1 { case offsetBegin > -1:
// rangeString contains only first byte position. eg. "bytes=8-" // rangeString contains only first byte position. eg. "bytes=8-"
if offsetBegin >= resourceSize { if offsetBegin >= resourceSize {
// First byte position should not be >= resourceSize. // First byte position should not be >= resourceSize.
@ -111,7 +112,7 @@ func parseRequestRange(rangeString string, resourceSize int64) (hrange *httpRang
} }
offsetEnd = resourceSize - 1 offsetEnd = resourceSize - 1
} else if offsetEnd > -1 { case offsetEnd > -1:
// rangeString contains only last byte position. eg. "bytes=-3" // rangeString contains only last byte position. eg. "bytes=-3"
if offsetEnd == 0 { if offsetEnd == 0 {
// Last byte position should not be zero eg. "bytes=-0" // Last byte position should not be zero eg. "bytes=-0"
@ -125,7 +126,7 @@ func parseRequestRange(rangeString string, resourceSize int64) (hrange *httpRang
} }
offsetEnd = resourceSize - 1 offsetEnd = resourceSize - 1
} else { default:
// rangeString contains first and last byte positions missing. eg. "bytes=-" // rangeString contains first and last byte positions missing. eg. "bytes=-"
return nil, fmt.Errorf("'%s' does not have valid range value", rangeString) return nil, fmt.Errorf("'%s' does not have valid range value", rangeString)
} }

@ -94,13 +94,14 @@ type Console interface {
} }
func consoleLog(console Console, msg string, args ...interface{}) { func consoleLog(console Console, msg string, args ...interface{}) {
if jsonFlag { switch {
case jsonFlag:
// Strip escape control characters from json message // Strip escape control characters from json message
msg = ansiRE.ReplaceAllLiteralString(msg, "") msg = ansiRE.ReplaceAllLiteralString(msg, "")
console.json(msg, args...) console.json(msg, args...)
} else if quiet { case quiet:
console.quiet(msg, args...) console.quiet(msg, args...)
} else { default:
console.pretty(msg, args...) console.pretty(msg, args...)
} }
} }

@ -375,20 +375,14 @@ func (e BackendDown) Error() string {
// isErrIncompleteBody - Check if error type is IncompleteBody. // isErrIncompleteBody - Check if error type is IncompleteBody.
func isErrIncompleteBody(err error) bool { func isErrIncompleteBody(err error) bool {
switch err.(type) { _, ok := err.(IncompleteBody)
case IncompleteBody: return ok
return true
}
return false
} }
// isErrObjectNotFound - Check if error type is ObjectNotFound. // isErrObjectNotFound - Check if error type is ObjectNotFound.
func isErrObjectNotFound(err error) bool { func isErrObjectNotFound(err error) bool {
switch err.(type) { _, ok := err.(ObjectNotFound)
case ObjectNotFound: return ok
return true
}
return false
} }
// isInsufficientReadQuorum - Check if error type is InsufficientReadQuorum. // isInsufficientReadQuorum - Check if error type is InsufficientReadQuorum.

@ -130,20 +130,23 @@ func renameAll(srcFilePath, dstFilePath string) (err error) {
} }
if err = reliableRename(srcFilePath, dstFilePath); err != nil { if err = reliableRename(srcFilePath, dstFilePath); err != nil {
if isSysErrNotDir(err) { switch {
case isSysErrNotDir(err):
return errFileAccessDenied return errFileAccessDenied
} else if isSysErrPathNotFound(err) { case isSysErrPathNotFound(err):
// This is a special case should be handled only for // This is a special case should be handled only for
// windows, because windows API does not return "not a // windows, because windows API does not return "not a
// directory" error message. Handle this specifically here. // directory" error message. Handle this specifically here.
return errFileAccessDenied return errFileAccessDenied
} else if isSysErrCrossDevice(err) { case isSysErrCrossDevice(err):
return fmt.Errorf("%s (%s)->(%s)", errCrossDeviceLink, srcFilePath, dstFilePath) return fmt.Errorf("%s (%s)->(%s)", errCrossDeviceLink, srcFilePath, dstFilePath)
} else if os.IsNotExist(err) { case os.IsNotExist(err):
return errFileNotFound return errFileNotFound
default:
return err
} }
} }
return err return nil
} }
// Reliably retries os.RenameAll if for some reason os.RenameAll returns // Reliably retries os.RenameAll if for some reason os.RenameAll returns

@ -27,13 +27,9 @@ func isSysErrNoSys(err error) bool {
if err == syscall.ENOSYS { if err == syscall.ENOSYS {
return true return true
} }
if pathErr, ok := err.(*os.PathError); ok { pathErr, ok := err.(*os.PathError)
switch pathErr.Err { return ok && pathErr.Err == syscall.ENOSYS
case syscall.ENOSYS:
return true
}
}
return false
} }
// Not supported error // Not supported error
@ -41,13 +37,9 @@ func isSysErrOpNotSupported(err error) bool {
if err == syscall.EOPNOTSUPP { if err == syscall.EOPNOTSUPP {
return true return true
} }
if pathErr, ok := err.(*os.PathError); ok { pathErr, ok := err.(*os.PathError)
switch pathErr.Err { return ok && pathErr.Err == syscall.EOPNOTSUPP
case syscall.EOPNOTSUPP:
return true
}
}
return false
} }
// No space left on device error // No space left on device error
@ -55,13 +47,8 @@ func isSysErrNoSpace(err error) bool {
if err == syscall.ENOSPC { if err == syscall.ENOSPC {
return true return true
} }
if pathErr, ok := err.(*os.PathError); ok { pathErr, ok := err.(*os.PathError)
switch pathErr.Err { return ok && pathErr.Err == syscall.ENOSPC
case syscall.ENOSPC:
return true
}
}
return false
} }
// Input/output error // Input/output error
@ -69,13 +56,8 @@ func isSysErrIO(err error) bool {
if err == syscall.EIO { if err == syscall.EIO {
return true return true
} }
if pathErr, ok := err.(*os.PathError); ok { pathErr, ok := err.(*os.PathError)
switch pathErr.Err { return ok && pathErr.Err == syscall.EIO
case syscall.EIO:
return true
}
}
return false
} }
// Check if the given error corresponds to EISDIR (is a directory). // Check if the given error corresponds to EISDIR (is a directory).
@ -83,13 +65,9 @@ func isSysErrIsDir(err error) bool {
if err == syscall.EISDIR { if err == syscall.EISDIR {
return true return true
} }
if pathErr, ok := err.(*os.PathError); ok { pathErr, ok := err.(*os.PathError)
switch pathErr.Err { return ok && pathErr.Err == syscall.EISDIR
case syscall.EISDIR:
return true
}
}
return false
} }
// Check if the given error corresponds to ENOTDIR (is not a directory). // Check if the given error corresponds to ENOTDIR (is not a directory).
@ -97,13 +75,8 @@ func isSysErrNotDir(err error) bool {
if err == syscall.ENOTDIR { if err == syscall.ENOTDIR {
return true return true
} }
if pathErr, ok := err.(*os.PathError); ok { pathErr, ok := err.(*os.PathError)
switch pathErr.Err { return ok && pathErr.Err == syscall.ENOTDIR
case syscall.ENOTDIR:
return true
}
}
return false
} }
// Check if the given error corresponds to the ENAMETOOLONG (name too long). // Check if the given error corresponds to the ENAMETOOLONG (name too long).
@ -111,13 +84,8 @@ func isSysErrTooLong(err error) bool {
if err == syscall.ENAMETOOLONG { if err == syscall.ENAMETOOLONG {
return true return true
} }
if pathErr, ok := err.(*os.PathError); ok { pathErr, ok := err.(*os.PathError)
switch pathErr.Err { return ok && pathErr.Err == syscall.ENAMETOOLONG
case syscall.ENAMETOOLONG:
return true
}
}
return false
} }
// Check if the given error corresponds to ENOTEMPTY for unix // Check if the given error corresponds to ENOTEMPTY for unix
@ -133,8 +101,7 @@ func isSysErrNotEmpty(err error) bool {
return true return true
} }
} }
switch pathErr.Err { if pathErr.Err == syscall.ENOTEMPTY {
case syscall.ENOTEMPTY:
return true return true
} }
} }
@ -161,15 +128,11 @@ func isSysErrHandleInvalid(err error) bool {
return false return false
} }
// Check if err contains ERROR_INVALID_HANDLE errno // Check if err contains ERROR_INVALID_HANDLE errno
if errno, ok := err.(syscall.Errno); ok && errno == 0x6 { errno, ok := err.(syscall.Errno)
return true return ok && errno == 0x6
}
return false
} }
func isSysErrCrossDevice(err error) bool { func isSysErrCrossDevice(err error) bool {
if e, ok := err.(*os.LinkError); ok { e, ok := err.(*os.LinkError)
return e.Err == syscall.EXDEV return ok && e.Err == syscall.EXDEV
}
return false
} }

@ -329,14 +329,16 @@ func (s *posix) checkDiskFound() (err error) {
} }
_, err = os.Stat(s.diskPath) _, err = os.Stat(s.diskPath)
if err != nil { if err != nil {
if os.IsNotExist(err) { switch {
case os.IsNotExist(err):
return errDiskNotFound return errDiskNotFound
} else if isSysErrTooLong(err) { case isSysErrTooLong(err):
return errFileNameTooLong return errFileNameTooLong
} else if isSysErrIO(err) { case isSysErrIO(err):
return errFaultyDisk return errFaultyDisk
default:
return err
} }
return err
} }
return nil return nil
} }
@ -597,16 +599,18 @@ func (s *posix) DeleteVol(volume string) (err error) {
} }
err = os.Remove((volumeDir)) err = os.Remove((volumeDir))
if err != nil { if err != nil {
if os.IsNotExist(err) { switch {
case os.IsNotExist(err):
return errVolumeNotFound return errVolumeNotFound
} else if isSysErrNotEmpty(err) { case isSysErrNotEmpty(err):
return errVolumeNotEmpty return errVolumeNotEmpty
} else if os.IsPermission(err) { case os.IsPermission(err):
return errDiskAccessDenied return errDiskAccessDenied
} else if isSysErrIO(err) { case isSysErrIO(err):
return errFaultyDisk return errFaultyDisk
default:
return err
} }
return err
} }
return nil return nil
} }
@ -771,16 +775,18 @@ func (s *posix) ReadFile(volume, path string, offset int64, buffer []byte, verif
// Open the file for reading. // Open the file for reading.
file, err := os.Open((filePath)) file, err := os.Open((filePath))
if err != nil { if err != nil {
if os.IsNotExist(err) { switch {
case os.IsNotExist(err):
return 0, errFileNotFound return 0, errFileNotFound
} else if os.IsPermission(err) { case os.IsPermission(err):
return 0, errFileAccessDenied return 0, errFileAccessDenied
} else if isSysErrNotDir(err) { case isSysErrNotDir(err):
return 0, errFileAccessDenied return 0, errFileAccessDenied
} else if isSysErrIO(err) { case isSysErrIO(err):
return 0, errFaultyDisk return 0, errFaultyDisk
default:
return 0, err
} }
return 0, err
} }
// Close the file descriptor. // Close the file descriptor.
@ -880,14 +886,16 @@ func (s *posix) createFile(volume, path string) (f *os.File, err error) {
w, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666) w, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
if err != nil { if err != nil {
// File path cannot be verified since one of the parents is a file. // File path cannot be verified since one of the parents is a file.
if isSysErrNotDir(err) { switch {
case isSysErrNotDir(err):
return nil, errFileAccessDenied return nil, errFileAccessDenied
} else if os.IsPermission(err) { case os.IsPermission(err):
return nil, errFileAccessDenied return nil, errFileAccessDenied
} else if isSysErrIO(err) { case isSysErrIO(err):
return nil, errFaultyDisk return nil, errFaultyDisk
default:
return nil, err
} }
return nil, err
} }
return w, nil return w, nil

@ -57,8 +57,9 @@ func toString(val interface{}) string {
switch v := val.(type) { switch v := val.(type) {
case string: case string:
return v return v
default:
return ""
} }
return ""
} }
// toLowerString - safely convert interface to lower string // toLowerString - safely convert interface to lower string
@ -78,18 +79,15 @@ func toInteger(val interface{}) (int64, error) {
case string: case string:
i, err := strconv.Atoi(v) i, err := strconv.Atoi(v)
return int64(i), err return int64(i), err
default:
return 0, errors.New("Invalid number format")
} }
return 0, errors.New("Invalid number format")
} }
// isString - Safely check if val is of type string without causing panic. // isString - Safely check if val is of type string without causing panic.
func isString(val interface{}) bool { func isString(val interface{}) bool {
switch val.(type) { _, ok := val.(string)
case string: return ok
return true
}
return false
} }
// ContentLengthRange - policy content-length-range field. // ContentLengthRange - policy content-length-range field.

@ -427,9 +427,10 @@ func hashKey(algo string, key string, cardinality int) int {
switch algo { switch algo {
case formatXLVersionV2DistributionAlgo: case formatXLVersionV2DistributionAlgo:
return crcHashMod(key, cardinality) return crcHashMod(key, cardinality)
default:
// Unknown algorithm returns -1, also if cardinality is lesser than 0.
return -1
} }
// Unknown algorithm returns -1, also if cardinality is lesser than 0.
return -1
} }
// Returns always a same erasure coded set for a given input. // Returns always a same erasure coded set for a given input.

Loading…
Cancel
Save