Skip to content

simplifying if-else chains to switches #6208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Aug 6, 2018
Merged

Conversation

cristaloleg
Copy link
Contributor

@cristaloleg cristaloleg commented Jul 29, 2018

Description

Simplifying if-else chains to switches.
All the changes were suggested by https://github.com/go-critic/go-critic

Motivation and Context

To make code easier to read.

How Has This Been Tested?

Regular build, there is no logical changes, only style and code simplification.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added unit tests to cover my changes.
  • I have added/updated functional tests in mint. (If yes, add mint PR # here: )
  • All new and existing tests passed.

@codecov
Copy link

codecov bot commented Jul 29, 2018

Codecov Report

Merging #6208 into master will increase coverage by 0.05%.
The diff coverage is 55.85%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #6208      +/-   ##
==========================================
+ Coverage   58.41%   58.46%   +0.05%     
==========================================
  Files         222      222              
  Lines       32058    32043      -15     
==========================================
+ Hits        18726    18734       +8     
+ Misses      11689    11685       -4     
+ Partials     1643     1624      -19
Impacted Files Coverage Δ
cmd/common-main.go 13.51% <0%> (-0.08%) ⬇️
cmd/httprange.go 91.54% <100%> (ø) ⬆️
cmd/bool-flag.go 100% <100%> (ø) ⬆️
cmd/admin-rpc-client.go 51.43% <100%> (ø) ⬆️
cmd/admin-handlers.go 55.05% <100%> (+0.1%) ⬆️
cmd/xl-sets.go 55.95% <100%> (+0.86%) ⬆️
cmd/object-api-errors.go 57.63% <100%> (+0.2%) ⬆️
cmd/fs-v1-helpers.go 69.93% <25%> (+0.09%) ⬆️
cmd/postpolicyform.go 70.62% <33.33%> (-0.7%) ⬇️
cmd/posix.go 70.06% <42.3%> (+0.27%) ⬆️
... and 9 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update eabfcea...7dd973e. Read the comment docs.

@@ -230,7 +230,7 @@ func (c cacheObjects) GetObject(ctx context.Context, bucket, object string, star
return err
}
go func() {
if err = GetObjectFn(ctx, bucket, object, 0, objInfo.Size, io.MultiWriter(writer, pipeWriter), etag); err != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These changes are not related to the changes mentioned by this PR, would it be possible to send this separately?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, sure.

cmd/endpoint.go Outdated
@@ -330,12 +330,12 @@ func CreateEndpoints(serverAddr string, args ...[]string) (string, EndpointList,
host = endpoint.Host
}
hostIPSet, _ := getHostIP4(host)
if IPSet, ok := pathIPMap[endpoint.Path]; ok {
if !IPSet.Intersection(hostIPSet).IsEmpty() {
if ipSet, ok := pathIPMap[endpoint.Path]; ok {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep cleanups to separate PR, this doesn't fix anything related to if-else or cyclomatic complexity.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

cmd/fallocate.go Outdated
@@ -20,6 +20,6 @@ package cmd

// Fallocate is not POSIX and not supported under Windows
// Always return successful
func Fallocate(fd int, offset int64, len int64) error {
func Fallocate(fd int, offset int64, length int64) error {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here len is synonymous to length, no reason to rename it. The corresponding function in fallocate_linux.go is untouched..

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a builtin function https://golang.org/pkg/builtin/#len

@@ -283,9 +284,9 @@ func LogIf(ctx context.Context, err error) {
req = &ReqInfo{API: "SYSTEM"}
}

API := "SYSTEM"
apiName := "SYSTEM"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here avoid cleanups like this....

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

@@ -25,8 +25,7 @@ import (
// Function not implemented error
func isSysErrNoSys(err error) bool {
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENOSYS:
if pathErr.Err == syscall.ENOSYS {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Further simplification is possible simply do return pathErr.Err == syscall.ENOSYS

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indeed

@@ -58,8 +55,7 @@ func isSysErrNoSpace(err error) bool {
// Input/output error
func isSysErrIO(err error) bool {
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.EIO:
if pathErr.Err == syscall.EIO {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Further simplification is possible simply do return pathErr.Err == syscall.EIO

@@ -69,8 +65,7 @@ func isSysErrIO(err error) bool {
// Check if the given error corresponds to EISDIR (is a directory).
func isSysErrIsDir(err error) bool {
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.EISDIR:
if pathErr.Err == syscall.EISDIR {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Further simplification is possible simply do return pathErr.Err == syscall.EISDIR

@@ -80,8 +75,7 @@ func isSysErrIsDir(err error) bool {
// Check if the given error corresponds to ENOTDIR (is not a directory).
func isSysErrNotDir(err error) bool {
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENOTDIR:
if pathErr.Err == syscall.ENOTDIR {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Further simplification is possible simply do return pathErr.Err == syscall.ENOTDIR

@@ -91,8 +85,7 @@ func isSysErrNotDir(err error) bool {
// Check if the given error corresponds to the ENAMETOOLONG (name too long).
func isSysErrTooLong(err error) bool {
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENAMETOOLONG:
if pathErr.Err == syscall.ENAMETOOLONG {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Further simplification is possible simply do return pathErr.Err == syscall.ENAMETOOLONG

cmd/retry.go Outdated
@@ -61,7 +61,7 @@ var globalRandomSource = rand.New(&lockedRandSource{
// until the maximum retry attempts are reached. - this function is a fully
// configurable version, meant for only advanced use cases. For the most part
// one should use newRetryTimerSimple and newRetryTimer.
func newRetryTimerWithJitter(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
func newRetryTimerWithJitter(unit time.Duration, max time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not change the variable name cap - any good reason you change it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

@cristaloleg cristaloleg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick review. Will address suggestions quickly.

@@ -230,7 +230,7 @@ func (c cacheObjects) GetObject(ctx context.Context, bucket, object string, star
return err
}
go func() {
if err = GetObjectFn(ctx, bucket, object, 0, objInfo.Size, io.MultiWriter(writer, pipeWriter), etag); err != nil {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, sure.

cmd/endpoint.go Outdated
@@ -330,12 +330,12 @@ func CreateEndpoints(serverAddr string, args ...[]string) (string, EndpointList,
host = endpoint.Host
}
hostIPSet, _ := getHostIP4(host)
if IPSet, ok := pathIPMap[endpoint.Path]; ok {
if !IPSet.Intersection(hostIPSet).IsEmpty() {
if ipSet, ok := pathIPMap[endpoint.Path]; ok {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

@@ -283,9 +284,9 @@ func LogIf(ctx context.Context, err error) {
req = &ReqInfo{API: "SYSTEM"}
}

API := "SYSTEM"
apiName := "SYSTEM"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

@@ -25,8 +25,7 @@ import (
// Function not implemented error
func isSysErrNoSys(err error) bool {
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENOSYS:
if pathErr.Err == syscall.ENOSYS {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indeed

cmd/fallocate.go Outdated
@@ -20,6 +20,6 @@ package cmd

// Fallocate is not POSIX and not supported under Windows
// Always return successful
func Fallocate(fd int, offset int64, len int64) error {
func Fallocate(fd int, offset int64, length int64) error {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a builtin function https://golang.org/pkg/builtin/#len

cmd/retry.go Outdated
@@ -61,7 +61,7 @@ var globalRandomSource = rand.New(&lockedRandSource{
// until the maximum retry attempts are reached. - this function is a fully
// configurable version, meant for only advanced use cases. For the most part
// one should use newRetryTimerSimple and newRetryTimer.
func newRetryTimerWithJitter(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
func newRetryTimerWithJitter(unit time.Duration, max time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kannappanr kannappanr requested review from harshavardhana, ebozduman and kannappanr and removed request for harshavardhana July 30, 2018 00:01
cmd/bool-flag.go Outdated
@@ -56,11 +56,12 @@ func (bf *BoolFlag) UnmarshalJSON(data []byte) (err error) {

// ParseBoolFlag - parses string into BoolFlag.
func ParseBoolFlag(s string) (bf BoolFlag, err error) {
if s == "on" {
switch {
Copy link
Contributor

@kannappanr kannappanr Jul 31, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can be changed to

switch s {
	case "on":
		bf = true
	case "off":
		bf = false
	default:
                err = fmt.Errorf("invalid value ‘%s’ for BoolFlag", s)
	}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

harshavardhana
harshavardhana previously approved these changes Jul 31, 2018
kannappanr
kannappanr previously approved these changes Jul 31, 2018
Copy link
Contributor

@kannappanr kannappanr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

return fmt.Errorf("%s (%s)->(%s)", errCrossDeviceLink, srcFilePath, dstFilePath)
} else if os.IsNotExist(err) {
case os.IsNotExist(err):
return errFileNotFound
}
Copy link
Contributor

@ebozduman ebozduman Jul 31, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we need default here (although it was even also missing in the original code);

default:
    return err

@cristaloleg cristaloleg dismissed stale reviews from kannappanr and harshavardhana via fea64af July 31, 2018 22:01
@@ -95,6 +95,8 @@ func renameAll(srcFilePath, dstFilePath string) (err error) {
return fmt.Errorf("%s (%s)->(%s)", errCrossDeviceLink, srcFilePath, dstFilePath)
case os.IsNotExist(err):
return errFileNotFound
default:
return err
}
}
return err
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will look cleaner, if it is changed to return nil

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cristaloleg,
Could you please incorporate @kannappanr's comment?
Thanks

@harshavardhana
Copy link
Member

Can you fix the conflicts @cristaloleg ?

@@ -83,17 +83,20 @@ func renameAll(srcFilePath, dstFilePath string) (err error) {
}

if err = reliableRename(srcFilePath, dstFilePath); err != nil {
if isSysErrNotDir(err) {
switch {
Copy link
Contributor

@kannappanr kannappanr Aug 4, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I think you misunderstood what I meant. I wanted the renameAll function to look like this

func renameAll(srcFilePath, dstFilePath string) (err error) {
	if srcFilePath == "" || dstFilePath == "" {
		return errInvalidArgument
	}

	if err = checkPathLength(srcFilePath); err != nil {
		return err
	}
	if err = checkPathLength(dstFilePath); err != nil {
		return err
	}

	if err = reliableRename(srcFilePath, dstFilePath); err != nil {
		switch {
		case isSysErrNotDir(err):
			return errFileAccessDenied
		case isSysErrPathNotFound(err):
			// This is a special case should be handled only for
			// windows, because windows API does not return "not a
			// directory" error message. Handle this specifically here.
			return errFileAccessDenied
		case isSysErrCrossDevice(err):
			return fmt.Errorf("%s (%s)->(%s)", errCrossDeviceLink, srcFilePath, dstFilePath)
		case os.IsNotExist(err):
			return errFileNotFound
		default:
			return err
		}
	}
	return nil
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, now it's clear 😉

Copy link
Contributor

@kannappanr kannappanr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@minio-ops
Copy link

Mint Automation

Test Result
mint-gateway-s3.sh ✔️
mint-gateway-azure.sh ✔️
mint-xl.sh ✔️
mint-gateway-nas.sh ✔️
mint-large-bucket.sh ✔️
mint-worm.sh ✔️
mint-fs.sh ✔️
mint-dist-xl.sh more...

6208-7dd973e/mint-dist-xl.sh.log:

Running with
SERVER_ENDPOINT:      minikube:31146
ACCESS_KEY:           minio
SECRET_KEY:           ***REDACTED***
ENABLE_HTTPS:         0
SERVER_REGION:        us-east-1
MINT_DATA_DIR:        /mint/data
MINT_MODE:            full
ENABLE_VIRTUAL_STYLE: 0

To get logs, run 'docker cp 200e1f766a5c:/mint/log /tmp/mint-logs'
(1/13) Running awscli tests ... done in 52 seconds
(2/13) Running aws-sdk-go tests ... done in 0 seconds
(3/13) Running aws-sdk-java tests ... done in 1 seconds
(4/13) Running aws-sdk-php tests ... done in 42 seconds
(5/13) Running aws-sdk-ruby tests ... done in 7 seconds
(6/13) Running mc tests ... done in 20 seconds
(7/13) Running minio-dotnet tests ... FAILED in 2 minutes and 34 seconds

Unhandled Exception: System.AggregateException: One or more errors occurred. (One or more errors occurred. (Minio API responded with message=Multiple disks failures, unable to write data.) (Minio API responded with message=Multiple disks failures, unable to write data.) (Minio API responded with message=Multiple disks failures, unable to write data.)) ---> System.AggregateException: One or more errors occurred. (Minio API responded with message=Multiple disks failures, unable to write data.) (Minio API responded with message=Multiple disks failures, unable to write data.) (Minio API responded with message=Multiple disks failures, unable to write data.) ---> Minio.Exceptions.MinioException: Minio API responded with message=Multiple disks failures, unable to write data.
   at Minio.MinioClient.ParseError(IRestResponse response)
   at Minio.MinioClient.<>c.<.ctor>b__76_0(IRestResponse response)
   at Minio.MinioClient.HandleIfErrorResponse(IRestResponse response, IEnumerable`1 handlers, DateTime startTime)
   at Minio.MinioClient.<ExecuteTaskAsync>d__79.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Minio.MinioClient.<PutObjectAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Minio.MinioClient.<PutObjectAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Minio.Functional.Tests.FunctionalTest.<PutObject_Task>d__52.MoveNext() in /mint/run/core/minio-dotnet/FunctionalTest.cs:line 741
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Minio.Functional.Tests.FunctionalTest.<RemoveObjects_Test2>d__75.MoveNext() in /mint/run/core/minio-dotnet/FunctionalTest.cs:line 1669
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Minio.Functional.Tests.FunctionalTest.Main(String[] args) in /mint/run/core/minio-dotnet/FunctionalTest.cs:line 220

Executed 6 out of 13 tests successfully.

Copy link
Contributor

@ebozduman ebozduman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@kannappanr kannappanr merged commit 37de2db into minio:master Aug 6, 2018
@cristaloleg
Copy link
Contributor Author

Thanks to everyone 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants