Skip to content

Commit

Permalink
Merge pull request #5555 from overbool/feat/add-force-flag-for-files-rm
Browse files Browse the repository at this point in the history
feat(command): add force flag for files rm
  • Loading branch information
Stebalien authored Oct 5, 2018
2 parents 823d9b9 + a86cde5 commit 05b3b81
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 13 deletions.
33 changes: 20 additions & 13 deletions core/commands/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,7 @@ Remove files or directories.
},
Options: []cmdkit.Option{
cmdkit.BoolOption("recursive", "r", "Recursively remove directories."),
cmdkit.BoolOption("force", "Forcibly remove target at path; implies -r for directories"),
},
Run: func(req oldcmds.Request, res oldcmds.Response) {
defer res.SetOutput(nil)
Expand Down Expand Up @@ -1041,8 +1042,6 @@ Remove files or directories.
return
}

dashr, _, _ := req.Option("r").Bool()

var success bool
defer func() {
if success {
Expand All @@ -1054,8 +1053,10 @@ Remove files or directories.
}
}()

// if '-r' specified, don't check file type (in bad scenarios, the block may not exist)
if dashr {
// if '--force' specified, it will remove anything else,
// including file, directory, corrupted node, etc
force, _, _ := req.Option("force").Bool()
if force {
err := pdir.Unlink(name)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
Expand All @@ -1066,25 +1067,31 @@ Remove files or directories.
return
}

childi, err := pdir.Child(name)
// get child node by name, when the node is corrupted and nonexistent,
// it will return specific error.
child, err := pdir.Child(name)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}

switch childi.(type) {
dashr, _, _ := req.Option("r").Bool()

switch child.(type) {
case *mfs.Directory:
res.SetError(fmt.Errorf("%s is a directory, use -r to remove directories", path), cmdkit.ErrNormal)
return
default:
err := pdir.Unlink(name)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
if !dashr {
res.SetError(fmt.Errorf("%s is a directory, use -r to remove directories", path), cmdkit.ErrNormal)
return
}
}

success = true
err = pdir.Unlink(name)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}

success = true
},
}

Expand Down
14 changes: 14 additions & 0 deletions test/sharness/t0250-files-api.sh
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,20 @@ test_files_api() {
test_expect_success "repo gc $EXTRA" '
ipfs repo gc
'

# test rm

test_expect_success "remove file forcibly" '
echo "hello world" | ipfs files write --create /forcibly &&
ipfs files rm --force /forcibly &&
verify_dir_contents /
'

test_expect_success "remove directory forcibly" '
ipfs files mkdir /forcibly-dir &&
ipfs files rm --force /forcibly-dir &&
verify_dir_contents /
'
}

# test offline and online
Expand Down

0 comments on commit 05b3b81

Please sign in to comment.