我将如何编写一个函数来检查文件在 Go 中是否可执行?给定os.FileInfo
,我可以得到os.FileInfo.Mode()
,但是我在尝试解析权限位时遇到了困难。
测试用例:
#!/usr/bin/env bash
function setup() {
mkdir -p test/foo/bar
touch test/foo/bar/{baz.txt,quux.sh}
chmod +x test/foo/bar/quux.sh
}
function teardown() { rm -r ./test }
setup
Run Code Online (Sandbox Code Playgroud)
import (
"os"
"path/filepath"
"fmt"
)
func IsExectuable(mode os.FileMode) bool {
// ???
}
func main() {
filepath.Walk("test", func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return err
}
fmt.Printf("%v %v", path, IsExectuable(info.Mode().Perm()))
}
}
// should print "test/foo/bar/baz.txt false"
// "test/foo/bar/quux.txt true" …
Run Code Online (Sandbox Code Playgroud) 我想为异步函数编写一个装饰器。如何注释装饰器定义的类型?
这是我想做的一个例子:
from typing import TypeVar # will Awaitable help?
AsyncFn = TypeVar('AsyncFn') # how to narrow this type definition down to async functions?
def my_decorator(to_decorate: AsyncFn) -> AsyncFn:
async def decorated(*args, **kwargs): # mypy keeps saying "Function is missing a type"
return await to_decorate(*args, **kwargs)
@my_decorator
async def foo(bar: int) -> str:
return f"async: {bar}"
@my_decorator
async def quux(spam: str, **eggs: str) -> None:
return
foo(1) # should check
foo("baz") # mypy should yell
quux("spam") # should check
quux(1) …
Run Code Online (Sandbox Code Playgroud)