本文整理汇总了Golang中os.IsPermission函数的典型用法代码示例。如果您正苦于以下问题:Golang IsPermission函数的具体用法?Golang IsPermission怎么用?Golang IsPermission使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IsPermission函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ValidateContextDirectory
// ValidateContextDirectory checks if all the contents of the directory
// can be read and returns an error if some files can't be read
// symlinks which point to non-existing files don't trigger an error
func ValidateContextDirectory(srcPath string) error {
var finalError error
filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
// skip this directory/file if it's not in the path, it won't get added to the context
_, err = filepath.Rel(srcPath, filePath)
if err != nil && os.IsPermission(err) {
return nil
}
if _, err := os.Stat(filePath); err != nil && os.IsPermission(err) {
finalError = fmt.Errorf("can't stat '%s'", filePath)
return err
}
// skip checking if symlinks point to non-existing files, such symlinks can be useful
lstat, _ := os.Lstat(filePath)
if lstat.Mode()&os.ModeSymlink == os.ModeSymlink {
return err
}
if !f.IsDir() {
currentFile, err := os.Open(filePath)
if err != nil && os.IsPermission(err) {
finalError = fmt.Errorf("no permission to read from '%s'", filePath)
return err
} else {
currentFile.Close()
}
}
return nil
})
return finalError
}
示例2: checkWriteable
func checkWriteable(dir string) error {
_, err := os.Stat(dir)
if err == nil {
// dir exists, make sure we can write to it
testfile := path.Join(dir, "test")
fi, err := os.Create(testfile)
if err != nil {
if os.IsPermission(err) {
return fmt.Errorf("%s is not writeable by the current user", dir)
}
return fmt.Errorf("unexpected error while checking writeablility of repo root: %s", err)
}
fi.Close()
return os.Remove(testfile)
}
if os.IsNotExist(err) {
// dir doesnt exist, check that we can create it
return os.Mkdir(dir, 0775)
}
if os.IsPermission(err) {
return fmt.Errorf("cannot write to %s, incorrect permissions", err)
}
return err
}
示例3: ServeHTTP
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
// If so, control is handed over to ServeListing.
func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
var bc *Config
// See if there's a browse configuration to match the path
for i := range b.Configs {
if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) {
bc = &b.Configs[i]
goto inScope
}
}
return b.Next.ServeHTTP(w, r)
inScope:
// Browse works on existing directories; delegate everything else
requestedFilepath, err := bc.Root.Open(r.URL.Path)
if err != nil {
switch {
case os.IsPermission(err):
return http.StatusForbidden, err
case os.IsExist(err):
return http.StatusNotFound, err
default:
return b.Next.ServeHTTP(w, r)
}
}
defer requestedFilepath.Close()
info, err := requestedFilepath.Stat()
if err != nil {
switch {
case os.IsPermission(err):
return http.StatusForbidden, err
case os.IsExist(err):
return http.StatusGone, err
default:
return b.Next.ServeHTTP(w, r)
}
}
if !info.IsDir() {
return b.Next.ServeHTTP(w, r)
}
// Do not reply to anything else because it might be nonsensical
switch r.Method {
case http.MethodGet, http.MethodHead:
// proceed, noop
case "PROPFIND", http.MethodOptions:
return http.StatusNotImplemented, nil
default:
return b.Next.ServeHTTP(w, r)
}
// Browsing navigation gets messed up if browsing a directory
// that doesn't end in "/" (which it should, anyway)
if !strings.HasSuffix(r.URL.Path, "/") {
staticfiles.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
return 0, nil
}
return b.ServeListing(w, r, requestedFilepath, bc)
}
示例4: deleteFile
// deleteFile - delete file path if its empty.
func deleteFile(basePath, deletePath string) error {
if basePath == deletePath {
return nil
}
// Verify if the path exists.
pathSt, err := os.Stat(preparePath(deletePath))
if err != nil {
if os.IsNotExist(err) {
return errFileNotFound
} else if os.IsPermission(err) {
return errFileAccessDenied
}
return err
}
if pathSt.IsDir() && !isDirEmpty(deletePath) {
// Verify if directory is empty.
return nil
}
// Attempt to remove path.
if err := os.Remove(preparePath(deletePath)); err != nil {
if os.IsNotExist(err) {
return errFileNotFound
} else if os.IsPermission(err) {
return errFileAccessDenied
}
return err
}
// Recursively go down the next path and delete again.
if err := deleteFile(basePath, slashpath.Dir(deletePath)); err != nil {
return err
}
return nil
}
示例5: fsStat
// fsStat - wrapper function to get file stat.
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
fpath := f.PathURL.Path
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(f.PathURL.Path)
}
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(fpath)
}
st, e := os.Stat(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(fpath)
}
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
if os.IsNotExist(e) {
return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
}
return nil, probe.NewError(e)
}
return st, nil
}
示例6: DiffRepoFile
func (ad *ArchDiff) DiffRepoFile() FileList {
if ad.diffRepoFile == nil {
ad.diffRepoFile = make(FileList)
for _, file := range ad.RepoFile() {
realpath := filepath.Join(ad.Root, file.Name)
repopath := filepath.Join(ad.Repo, file.Name)
realhash, err := filehash(realpath)
if err != nil && !os.IsNotExist(err) {
if os.IsPermission(err) {
if !ad.Silent {
log.Printf("Skipping file: %s", err)
}
continue
}
log.Fatalf("Error looking for modified repo files (real): %s", err)
}
repohash, err := filehash(repopath)
if err != nil && !os.IsNotExist(err) {
if os.IsPermission(err) {
if !ad.Silent {
log.Printf("Skipping file: %s", err)
}
continue
}
log.Fatalf("Error looking for modified repo files (repo): %s", err)
}
if realhash != repohash {
ad.diffRepoFile.Add(file)
}
}
}
return ad.diffRepoFile
}
示例7: listRecursiveInRoutine
func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel) {
defer close(contentCh)
visitFS := func(fp string, fi os.FileInfo, err error) error {
// fp also sends back itself with visitFS, ignore it we don't need it
if fp == f.path {
return nil
}
if err != nil {
if strings.Contains(err.Error(), "operation not permitted") {
contentCh <- client.ContentOnChannel{
Content: nil,
Err: probe.NewError(err),
}
return nil
}
if os.IsPermission(err) {
contentCh <- client.ContentOnChannel{
Content: nil,
Err: probe.NewError(err),
}
return nil
}
return err
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
fi, err = os.Stat(fp)
if err != nil {
if os.IsNotExist(err) || os.IsPermission(err) { // ignore broken symlinks and permission denied
contentCh <- client.ContentOnChannel{
Content: nil,
Err: probe.NewError(err),
}
return nil
}
return err
}
}
if fi.Mode().IsRegular() || fi.Mode().IsDir() {
content := &client.Content{
Name: f.delimited(fp),
Time: fi.ModTime(),
Size: fi.Size(),
Type: fi.Mode(),
}
contentCh <- client.ContentOnChannel{
Content: content,
Err: nil,
}
}
return nil
}
err := filepath.Walk(f.path, visitFS)
if err != nil {
contentCh <- client.ContentOnChannel{
Content: nil,
Err: probe.NewError(err),
}
}
}
示例8: getEnvironments
// return a list of available virtual go environments for the user
func (e *EnvironmentsList) getEnvironments() ([]string, []string, error) {
envs_path := filepath.Join("~", ".VenGO", "*")
files, err := filepath.Glob(cache.ExpandUser(envs_path))
if err != nil {
fmt.Println("while getting list of environments:", err)
return nil, nil, err
}
available, invalid := []string{}, []string{}
for _, file := range files {
var vengoenv string
filename := path.Base(file)
stat, err := os.Stat(file)
if err != nil {
fmt.Println("while getting list of environments:", err)
return nil, nil, err
}
if stat.IsDir() && filename != "bin" && filename != "scripts" {
_, err := os.Open(filepath.Join(file, "bin", "activate"))
if err != nil {
if os.IsNotExist(err) || os.IsPermission(err) {
invalid = append(invalid, filename)
}
continue
}
if r, err := os.Readlink(filepath.Join(file, "lib")); err != nil {
if os.IsNotExist(err) || os.IsPermission(err) {
invalid = append(invalid, filename)
}
continue
} else {
if e.DisplayAs == Text {
vengoenv = fmt.Sprintf("%-22s%-8s", filename, path.Base(r))
} else {
vengoenv = filename
}
if _, err := os.Stat(r); err != nil {
if os.IsNotExist(err) || os.IsPermission(err) {
invalid = append(invalid, vengoenv)
}
continue
}
}
available = append(available, vengoenv)
}
}
return available, invalid, nil
}
示例9: checkUserNS
func checkUserNS(t *testing.T) {
if _, err := os.Stat("/proc/self/ns/user"); err != nil {
if os.IsNotExist(err) {
t.Skip("kernel doesn't support user namespaces")
}
if os.IsPermission(err) {
t.Skip("unable to test user namespaces due to permissions")
}
t.Fatalf("Failed to stat /proc/self/ns/user: %v", err)
}
if isChrooted(t) {
// create_user_ns in the kernel (see
// https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/kernel/user_namespace.c)
// forbids the creation of user namespaces when chrooted.
t.Skip("cannot create user namespaces when chrooted")
}
// On some systems, there is a sysctl setting.
if os.Getuid() != 0 {
data, errRead := ioutil.ReadFile("/proc/sys/kernel/unprivileged_userns_clone")
if errRead == nil && data[0] == '0' {
t.Skip("kernel prohibits user namespace in unprivileged process")
}
}
// When running under the Go continuous build, skip tests for
// now when under Kubernetes. (where things are root but not quite)
// Both of these are our own environment variables.
// See Issue 12815.
if os.Getenv("GO_BUILDER_NAME") != "" && os.Getenv("IN_KUBERNETES") == "1" {
t.Skip("skipping test on Kubernetes-based builders; see Issue 12815")
}
}
示例10: Locked
func Locked(confdir string) (bool, error) {
log.Debugf("Checking lock")
if !util.FileExists(path.Join(confdir, LockFile)) {
log.Debugf("File doesn't exist: %s", path.Join(confdir, LockFile))
return false, nil
}
if lk, err := Lock(confdir); err != nil {
// EAGAIN == someone else has the lock
if err == syscall.EAGAIN {
log.Debugf("Someone else has the lock: %s", path.Join(confdir, LockFile))
return true, nil
}
if strings.Contains(err.Error(), "can't Lock file") {
log.Debugf("Can't lock file: %s.\n reason: %s", path.Join(confdir, LockFile), err.Error())
return true, nil
}
// lock fails on permissions error
if os.IsPermission(err) {
log.Debugf("Lock fails on permissions error")
return false, errPerm(confdir)
}
if isLockCreatePermFail(err) {
log.Debugf("Lock fails on permissions error")
return false, errPerm(confdir)
}
// otherwise, we cant guarantee anything, error out
return false, err
} else {
log.Debugf("No one has a lock")
lk.Close()
return false, nil
}
}
示例11: statusCheckFile
func statusCheckFile(absPath string, file *entities.File, report *StatusReport) error {
log.Infof(2, "%v: checking file status.", absPath)
stat, err := os.Stat(file.Path())
if err != nil {
switch {
case os.IsNotExist(err):
log.Infof(2, "%v: file is missing.", absPath)
report.AddRow(Row{absPath, MISSING})
return nil
case os.IsPermission(err):
log.Warnf("%v: permission denied.", absPath)
case strings.Contains(err.Error(), "not a directory"): //TODO improve
report.AddRow(Row{file.Path(), MISSING})
return nil
default:
return fmt.Errorf("%v: could not stat: %v", file.Path(), err)
}
} else {
if stat.Size() != file.Size || !stat.ModTime().UTC().Equal(file.ModTime) {
log.Infof(2, "%v: file is modified.", absPath)
report.AddRow(Row{absPath, MODIFIED})
} else {
log.Infof(2, "%v: file is unchanged.", absPath)
report.AddRow(Row{absPath, TAGGED})
}
}
return nil
}
示例12: load
func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool) error {
var e error
fileName := v.FileName()
if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists {
if !canRead {
return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
}
if canWrite {
v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
} else {
glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
v.dataFile, e = os.Open(fileName + ".dat")
v.readOnly = true
}
} else {
if createDatIfMissing {
v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
} else {
return fmt.Errorf("Volume Data file %s.dat does not exist.", fileName)
}
}
if e != nil {
if !os.IsPermission(e) {
return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
}
}
if v.ReplicaPlacement == nil {
e = v.readSuperBlock()
} else {
e = v.maybeWriteSuperBlock()
}
if e == nil && alsoLoadIndex {
if v.readOnly {
if v.ensureConvertIdxToCdb(fileName) {
v.nm, e = OpenCdbMap(fileName + ".cdb")
return e
}
}
var indexFile *os.File
if v.readOnly {
glog.V(1).Infoln("open to read file", fileName+".idx")
if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
return fmt.Errorf("cannot read Volume Index %s.idx: %s", fileName, e.Error())
}
} else {
glog.V(1).Infoln("open to write file", fileName+".idx")
if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
return fmt.Errorf("cannot write Volume Index %s.idx: %s", fileName, e.Error())
}
}
glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
if v.nm, e = LoadNeedleMap(indexFile); e != nil {
glog.V(0).Infoln("loading error:", e)
}
}
return e
}
示例13: Load
func (f *JSONFile) Load(warnOnNotFound bool) error {
f.G().Log.Debug("+ loading %s file: %s", f.which, f.filename)
file, err := os.Open(f.filename)
if err != nil {
if os.IsNotExist(err) {
msg := fmt.Sprintf("No %s file found; tried %s", f.which, f.filename)
if warnOnNotFound {
f.G().Log.Warning(msg)
} else {
f.G().Log.Debug(msg)
}
return nil
} else if os.IsPermission(err) {
f.G().Log.Warning("Permission denied opening %s file %s", f.which, f.filename)
return nil
} else {
return err
}
}
f.exists = true
defer file.Close()
decoder := json.NewDecoder(file)
obj := make(map[string]interface{})
// Treat empty files like an empty dictionary
if err = decoder.Decode(&obj); err != nil && err != io.EOF {
f.G().Log.Errorf("Error decoding %s file %s", f.which, f.filename)
return err
}
f.jw = jsonw.NewWrapper(obj)
f.G().Log.Debug("- successfully loaded %s file", f.which)
return nil
}
示例14: load
func (v *Volume) load(alsoLoadIndex bool) error {
var e error
fileName := path.Join(v.dir, v.Id.String())
if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists && !canRead {
return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
} else if !exists || canWrite {
v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
} else if exists && canRead {
glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
v.dataFile, e = os.Open(fileName + ".dat")
v.readOnly = true
} else {
return fmt.Errorf("Unknown state about Volume Data file %s.dat", fileName)
}
if e != nil {
if !os.IsPermission(e) {
return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
}
}
if v.ReplicaType == CopyNil {
e = v.readSuperBlock()
} else {
e = v.maybeWriteSuperBlock()
}
if e == nil && alsoLoadIndex {
var indexFile *os.File
if v.readOnly {
glog.V(1).Infoln("open to read file", fileName+".idx")
if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
return fmt.Errorf("cannot read Volume Data %s.dat: %s", fileName, e.Error())
}
if v.ensureConvertIdxToCdb(fileName) {
v.nm, e = OpenCdbMap(fileName + ".cdb")
return e
}
if indexFile != nil {
glog.V(0).Infoln("converting %s.idx to %s.cdb", fileName, fileName)
if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
glog.Errorln("error converting %s.idx to %s.cdb: %s", fileName, fileName, e)
} else {
indexFile.Close()
os.Remove(indexFile.Name())
indexFile = nil
}
}
} else {
glog.V(1).Infoln("open to write file", fileName+".idx")
if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
return fmt.Errorf("cannot write Volume Data %s.dat: %s", fileName, e.Error())
}
}
glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
if v.nm, e = LoadNeedleMap(indexFile); e != nil {
glog.V(0).Infoln("loading error:", e)
}
}
return e
}
示例15: setupLogging
// setupLogging attempts to log to a file, otherwise stderr
func setupLogging() (*os.File, error) {
// use date, time and filename for log output
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetPrefix(*pluginName + "-volume-plugin: ")
// setup logfile - path is set from logfileDir and pluginName
logfileName := logfilePath()
if !isDebugEnabled() && logfileName != "" {
logFile, err := os.OpenFile(logfileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
// check if we can write to directory - otherwise just log to stderr?
if os.IsPermission(err) {
log.Printf("WARN: logging fallback to STDERR: %v", err)
} else {
// some other, more extreme system error
return nil, err
}
} else {
log.Printf("INFO: setting log file: %s", logfileName)
log.SetOutput(logFile)
return logFile, nil
}
}
return nil, nil
}