Skip to content
This repository was archived by the owner on Apr 25, 2026. It is now read-only.

simplifying if-else chains to switches - #6208

Merged
kannappanr merged 10 commits into
minio:masterfrom
cristaloleg:master
Aug 6, 2018
Merged

kannappanr merged 10 commits into
minio:masterfrom
cristaloleg:master

Conversation

@cristaloleg

@cristaloleg cristaloleg commented Jul 29, 2018 •

Copy link
Copy Markdown
Contributor

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

codecov Bot commented Jul 29, 2018 •

Copy link
Copy Markdown

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.

Comment thread cmd/disk-cache.go
return err
}
go func() {
if err = GetObjectFn(ctx, bucket, object, 0, objInfo.Size, io.MultiWriter(writer, pipeWriter), etag); err != nil {

Copy link
Copy Markdown
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
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yep, sure.

Comment thread cmd/endpoint.go Outdated
hostIPSet, _ := getHostIP4(host)
if IPSet, ok := pathIPMap[endpoint.Path]; ok {
if !IPSet.Intersection(hostIPSet).IsEmpty() {
if ipSet, ok := pathIPMap[endpoint.Path]; ok {

Copy link
Copy Markdown
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
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ok

Comment thread cmd/fallocate.go Outdated
// 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
Copy Markdown
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
Copy Markdown
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

Comment thread cmd/logger/logger.go Outdated
}

API := "SYSTEM"
apiName := "SYSTEM"

Copy link
Copy Markdown
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
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ok

Comment thread cmd/posix-errors.go Outdated
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENOSYS:
if pathErr.Err == syscall.ENOSYS {

Copy link
Copy Markdown
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
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

indeed

Comment thread cmd/posix-errors.go Outdated
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.EIO:
if pathErr.Err == syscall.EIO {

Copy link
Copy Markdown
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

Comment thread cmd/posix-errors.go Outdated
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.EISDIR:
if pathErr.Err == syscall.EISDIR {

Copy link
Copy Markdown
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

Comment thread cmd/posix-errors.go Outdated
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENOTDIR:
if pathErr.Err == syscall.ENOTDIR {

Copy link
Copy Markdown
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

Comment thread cmd/posix-errors.go Outdated
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENAMETOOLONG:
if pathErr.Err == syscall.ENAMETOOLONG {

Copy link
Copy Markdown
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

Comment thread cmd/retry.go Outdated
// 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
Copy Markdown
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
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@cristaloleg cristaloleg left a comment

Copy link
Copy Markdown
Contributor Author

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.

Comment thread cmd/disk-cache.go
return err
}
go func() {
if err = GetObjectFn(ctx, bucket, object, 0, objInfo.Size, io.MultiWriter(writer, pipeWriter), etag); err != nil {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yep, sure.

Comment thread cmd/endpoint.go Outdated
hostIPSet, _ := getHostIP4(host)
if IPSet, ok := pathIPMap[endpoint.Path]; ok {
if !IPSet.Intersection(hostIPSet).IsEmpty() {
if ipSet, ok := pathIPMap[endpoint.Path]; ok {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ok

Comment thread cmd/logger/logger.go Outdated
}

API := "SYSTEM"
apiName := "SYSTEM"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ok

Comment thread cmd/posix-errors.go Outdated
if pathErr, ok := err.(*os.PathError); ok {
switch pathErr.Err {
case syscall.ENOSYS:
if pathErr.Err == syscall.ENOSYS {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

indeed

Comment thread cmd/fallocate.go Outdated
// 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
Copy Markdown
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

Comment thread cmd/retry.go Outdated
// 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
Copy Markdown
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 ebozduman, harshavardhana and kannappanr and removed request for harshavardhana July 30, 2018 00:01
Comment thread cmd/bool-flag.go Outdated
// ParseBoolFlag - parses string into BoolFlag.
func ParseBoolFlag(s string) (bf BoolFlag, err error) {
if s == "on" {
switch {

@kannappanr kannappanr Jul 31, 2018 •

Copy link
Copy Markdown
Contributor

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
Copy Markdown
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

@kannappanr kannappanr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

Comment thread cmd/os-reliable.go
} else if os.IsNotExist(err) {
case os.IsNotExist(err):
return errFileNotFound
}

@ebozduman ebozduman Jul 31, 2018 •

Copy link
Copy Markdown
Contributor

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
Comment thread cmd/os-reliable.go Outdated
return err
}
}
return err

Copy link
Copy Markdown
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
Copy Markdown
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
Copy Markdown
Member

Can you fix the conflicts @cristaloleg ?

Comment thread cmd/os-reliable.go

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

@kannappanr kannappanr Aug 4, 2018 •

Copy link
Copy Markdown
Contributor

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
Copy Markdown
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 😉

@kannappanr kannappanr left a comment

Copy link
Copy Markdown
Contributor

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
Copy Markdown

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.

@ebozduman ebozduman left a comment

Copy link
Copy Markdown
Contributor

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
Copy Markdown
Contributor Author

Thanks to everyone 👍

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants