feat(command): add force flag for files rm
License: MIT Signed-off-by: Overbool <overbool.xu@gmail.com>
Overbool committed
Oct 3, 2018 at 21:47 UTC
bd23e7d2ed4db6e2058d285fe3a51511b2af1b37
1 file changed
+20
-13
core/commands/files.go
+20
-13
@@ -1002,6 +1002,7 @@ Remove files or directories.
1002
},
1003
Options: []cmdkit.Option{
1004
cmdkit.BoolOption("recursive", "r", "Recursively remove directories."),
1005
+ cmdkit.BoolOption("force", "Forcibly remove target at path; implies -r for directories"),
1006
},
1007
Run: func(req oldcmds.Request, res oldcmds.Response) {
1008
defer res.SetOutput(nil)
@@ -1041,8 +1042,6 @@ Remove files or directories.
1042
return
1043
}
1044
1044
- dashr, _, _ := req.Option("r").Bool()
1045
-
1045
var success bool
1046
defer func() {
1047
if success {
@@ -1054,8 +1053,10 @@ Remove files or directories.
1053
}
1054
}()
1055
1057
- // if '-r' specified, don't check file type (in bad scenarios, the block may not exist)
1058
- if dashr {
1056
+ // if '--force' specified, it will remove anything else,
1057
+ // including file, directory, corrupted node, etc
1058
+ force, _, _ := req.Option("force").Bool()
1059
+ if force {
1060
err := pdir.Unlink(name)
1061
if err != nil {
1062
res.SetError(err, cmdkit.ErrNormal)
@@ -1066,25 +1067,31 @@ Remove files or directories.
1067
return
1068
}
1069
1069
- childi, err := pdir.Child(name)
1070
+ // get child node by name, when the node is corrupted and nonexistent,
1071
+ // it will return specific error.
1072
+ child, err := pdir.Child(name)
1073
if err != nil {
1074
res.SetError(err, cmdkit.ErrNormal)
1075
return
1076
}
1077
1075
- switch childi.(type) {
1078
+ dashr, _, _ := req.Option("r").Bool()
1079
+
1080
+ switch child.(type) {
1081
case *mfs.Directory:
1077
- res.SetError(fmt.Errorf("%s is a directory, use -r to remove directories", path), cmdkit.ErrNormal)
1078
- return
1079
- default:
1080
- err := pdir.Unlink(name)
1081
- if err != nil {
1082
- res.SetError(err, cmdkit.ErrNormal)
1082
+ if !dashr {
1083
+ res.SetError(fmt.Errorf("%s is a directory, use -r to remove directories", path), cmdkit.ErrNormal)
1084
return
1085
}
1086
+ }
1087
1086
- success = true
1088
+ err = pdir.Unlink(name)
1089
+ if err != nil {
1090
+ res.SetError(err, cmdkit.ErrNormal)
1091
+ return
1092
}
1093
+
1094
+ success = true
1095
},
1096
}
1097