ftest: now can check for read and write.

This commit is contained in:
k1574 2022-06-18 08:45:10 +05:00
parent 6555852663
commit 37a7c5d013

View file

@ -11,9 +11,11 @@ import (
var ( var (
flags [lastFlag]bool flags [lastFlag]bool
flagList []int flagList []int
flagMap = map[int] func(os.FileInfo) bool{ flagMap = map[int] func(string) bool{
fileFlag : IsFile, fileFlag : IsFile,
dirFlag : IsDir, dirFlag : IsDir,
writFlag : IsWritable,
readFlag : IsReadable,
} }
) )
@ -27,32 +29,46 @@ const(
lastFlag lastFlag
) )
func FileInfo(p string) (os.FileInfo, error) { func IsFile(p string) bool {
s, err := os.Stat(p) st, err := os.Stat(p)
if err != nil {
return nil, err
}
return s, nil
}
func IsFile(fi os.FileInfo) bool {
mode := fi.Mode()
return mode.IsRegular()
}
func IsDir(fi os.FileInfo) bool {
return fi.IsDir()
}
func checkFile(p string) bool {
fi, err := FileInfo(p)
if err != nil { if err != nil {
return false return false
} }
mode := st.Mode()
return mode.IsRegular()
}
func IsDir(p string) bool {
st, err := os.Stat(p)
if err != nil {
return false
}
return st.IsDir()
}
func IsWritable(p string) bool {
f, err := os.OpenFile(p, os.O_WRONLY, 0)
if err != nil {
return false
}
defer f.Close()
return true
}
func IsReadable(p string) bool {
f, err := os.OpenFile(p, os.O_RDONLY, 0)
if err != nil {
return false
}
defer f.Close()
return true
}
func checkFile(p string) bool {
for _, v := range flagList { for _, v := range flagList {
if !flagMap[v](fi){ if !flagMap[v](p){
return false return false
} }
} }
@ -65,12 +81,15 @@ func Run(args []string) {
args = args[1:] args = args[1:]
flagSet := flag.NewFlagSet(arg0, flag.ExitOnError) flagSet := flag.NewFlagSet(arg0, flag.ExitOnError)
flagSet.Usage = func() { flagSet.Usage = func() {
flagSet.Usage() fmt.Fprintf(os.Stderr, "usage: %s <options>\n", arg0)
flagSet.PrintDefaults()
os.Exit(1) os.Exit(1)
} }
flagSet.BoolVar(&flags[fileFlag], "f", false, "is file") flagSet.BoolVar(&flags[fileFlag], "f", false, "is file")
flagSet.BoolVar(&flags[dirFlag], "d", false, "is directory") flagSet.BoolVar(&flags[dirFlag], "d", false, "is directory")
flagSet.BoolVar(&flags[writFlag], "w", false, "is writable")
flagSet.BoolVar(&flags[readFlag], "r", false, "is readable")
flagSet.Parse(args) flagSet.Parse(args)
args = flagSet.Args() args = flagSet.Args()