bb/tool/ftest/main.go

126 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-06-18 04:32:54 +03:00
package ftest
import (
"os"
"io"
"bufio"
"fmt"
2024-05-15 21:07:35 +03:00
"surdeus.su/core/cli/mtool"
2023-03-30 13:22:02 +03:00
"path/filepath"
2022-06-18 04:32:54 +03:00
)
var (
flags [lastFlag]bool
flagList []int
flagMap = map[int] func(string) bool{
2022-06-18 04:32:54 +03:00
fileFlag : IsFile,
dirFlag : IsDir,
writFlag : IsWritable,
readFlag : IsReadable,
2022-06-18 04:32:54 +03:00
}
)
const(
fileFlag = iota
readFlag
writFlag
execFlag
dirFlag
sizeFlag
lastFlag
)
func IsFile(p string) bool {
st, err := os.Stat(p)
2022-06-18 04:32:54 +03:00
if err != nil {
return false
2022-06-18 04:32:54 +03:00
}
mode := st.Mode()
return mode.IsRegular()
2022-06-18 04:32:54 +03:00
}
func IsDir(p string) bool {
st, err := os.Stat(p)
if err != nil {
return false
}
return st.IsDir()
2022-06-18 04:32:54 +03:00
}
func IsWritable(p string) bool {
f, err := os.OpenFile(p, os.O_WRONLY, 0)
if err != nil {
return false
}
defer f.Close()
return true
2022-06-18 04:32:54 +03:00
}
func IsReadable(p string) bool {
f, err := os.OpenFile(p, os.O_RDONLY, 0)
2022-06-18 04:32:54 +03:00
if err != nil {
return false
}
defer f.Close()
2022-06-18 04:32:54 +03:00
return true
}
func checkFile(p string) bool {
2023-03-30 13:22:02 +03:00
p = filepath.FromSlash(p)
2022-06-18 04:32:54 +03:00
for _, v := range flagList {
if !flagMap[v](p){
2022-06-18 04:32:54 +03:00
return false
}
}
return true
}
2023-03-24 19:47:31 +03:00
func Run(flagSet *mtool.Flags) {
2022-06-18 04:32:54 +03:00
flagSet.BoolVar(&flags[fileFlag], "f", false, "is file")
flagSet.BoolVar(&flags[dirFlag], "d", false, "is directory")
flagSet.BoolVar(&flags[writFlag], "w", false, "is writable")
flagSet.BoolVar(&flags[readFlag], "r", false, "is readable")
2022-06-18 04:32:54 +03:00
2023-03-24 19:47:31 +03:00
flagSet.Parse()
args := flagSet.Args()
2022-06-18 04:32:54 +03:00
if len(args) != 0 {
flagSet.Usage()
}
for i, v := range flags {
if v {
break;
} else if i == (len(flags) - 1) {
flagSet.Usage()
}
}
for i, v := range flags {
if v {
flagList = append(flagList, i)
}
}
rd := bufio.NewReader(os.Stdin)
for {
s, err := rd.ReadString('\n')
if err == io.EOF {
os.Exit(0)
} else if err != nil {
panic(err)
}
if s[len(s)-1] == '\n' {
s = s[:len(s)-1]
}
if checkFile(s) {
fmt.Println(s)
}
}
}