当前位置: 首页>>代码示例>>Golang>>正文


Golang os.Chmod函数代码示例

本文整理汇总了Golang中os.Chmod函数的典型用法代码示例。如果您正苦于以下问题:Golang Chmod函数的具体用法?Golang Chmod怎么用?Golang Chmod使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Chmod函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Listen

func (pk *ProxyKeyring) Listen() (string, error) {
	if pk.listener != nil {
		return "", errors.New("Already listening")
	}

	dir, err := ioutil.TempDir("", "proxykeyring")
	if err != nil {
		return "", err
	}

	err = os.Chmod(dir, 0700)
	if err != nil {
		return "", err
	}

	listener := filepath.Join(dir, "listener")
	pk.listener, err = net.Listen("unix", listener)
	if err != nil {
		return "", err
	}

	err = os.Chmod(listener, 0600)
	if err != nil {
		return "", err
	}

	return listener, nil
}
开发者ID:daveadams,项目名称:vaulted,代码行数:28,代码来源:proxy_keyring.go

示例2: TestFileSS_BadPerm

func TestFileSS_BadPerm(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("skipping file permission test on windows")
	}

	// Create a temp dir
	dir1, err := ioutil.TempDir("", "raft")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(dir1)

	// Create a sub dir and remove all permissions
	dir2, err := ioutil.TempDir(dir1, "badperm")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chmod(dir2, 000); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chmod(dir2, 777) // Set perms back for delete

	// Should fail
	if _, err := NewFileSnapshotStore(dir2, 3, nil); err == nil {
		t.Fatalf("should fail to use dir with bad perms")
	}
}
开发者ID:eswdd,项目名称:bosun,代码行数:27,代码来源:file_snapshot_test.go

示例3: InWritableDir

// InWritableDir calls fn(path), while making sure that the directory
// containing `path` is writable for the duration of the call.
func InWritableDir(fn func(string) error, path string) error {
	dir := filepath.Dir(path)
	info, err := os.Stat(dir)
	if err != nil {
		return err
	}
	if !info.IsDir() {
		return errors.New("Not a directory: " + path)
	}
	if info.Mode()&0200 == 0 {
		// A non-writeable directory (for this user; we assume that's the
		// relevant part). Temporarily change the mode so we can delete the
		// file or directory inside it.
		err = os.Chmod(dir, 0755)
		if err == nil {
			defer func() {
				err = os.Chmod(dir, info.Mode())
				if err != nil {
					// We managed to change the permission bits like a
					// millisecond ago, so it'd be bizarre if we couldn't
					// change it back.
					panic(err)
				}
			}()
		}
	}

	return fn(path)
}
开发者ID:hernad,项目名称:syncthing,代码行数:31,代码来源:osutil.go

示例4: tempFile

// tempFile returns the fd for the temporary file, reusing an open fd
// or creating the file as necessary.
func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
	s.mut.Lock()
	defer s.mut.Unlock()

	// If we've already hit an error, return early
	if s.err != nil {
		return nil, s.err
	}

	// If the temp file is already open, return the file descriptor
	if s.fd != nil {
		return lockedWriterAt{&s.mut, s.fd}, nil
	}

	// Ensure that the parent directory is writable. This is
	// osutil.InWritableDir except we need to do more stuff so we duplicate it
	// here.
	dir := filepath.Dir(s.tempName)
	if info, err := os.Stat(dir); err != nil {
		s.failLocked("dst stat dir", err)
		return nil, err
	} else if info.Mode()&0200 == 0 {
		err := os.Chmod(dir, 0755)
		if !s.ignorePerms && err == nil {
			defer func() {
				err := os.Chmod(dir, info.Mode().Perm())
				if err != nil {
					panic(err)
				}
			}()
		}
	}

	// Attempt to create the temp file
	flags := os.O_WRONLY
	if s.reused == 0 {
		flags |= os.O_CREATE | os.O_EXCL
	} else {
		// With sufficiently bad luck when exiting or crashing, we may have
		// had time to chmod the temp file to read only state but not yet
		// moved it to it's final name. This leaves us with a read only temp
		// file that we're going to try to reuse. To handle that, we need to
		// make sure we have write permissions on the file before opening it.
		err := os.Chmod(s.tempName, 0644)
		if !s.ignorePerms && err != nil {
			s.failLocked("dst create chmod", err)
			return nil, err
		}
	}
	fd, err := os.OpenFile(s.tempName, flags, 0666)
	if err != nil {
		s.failLocked("dst create", err)
		return nil, err
	}

	// Same fd will be used by all writers
	s.fd = fd

	return lockedWriterAt{&s.mut, s.fd}, nil
}
开发者ID:rwx-zwx-awx,项目名称:syncthing,代码行数:62,代码来源:sharedpullerstate.go

示例5: InitDataDir

func InitDataDir() {
	if !exists(getDataDir()) {
		fmt.Println("Adding datadir")
		os.MkdirAll(getDataDir(), 0750)
		os.Chmod(getDataDir(), 0750)
	}

	if !exists(filepath.Join(getDataDir(), "index.json")) {
		fmt.Println("Adding index.json")
		file, err := os.Create(filepath.Join(getDataDir(), "index.json"))
		if err == nil {
			_, err := file.WriteString("{}")

			if err != nil {
				fmt.Println(err)
			}
			file.Close()
		}
	}

	if !exists(filepath.Join(getDataDir(), "wwdr.pem")) {
		fmt.Println("Copying wwdr.pem")
		if err := copyWWDR(); err != nil {
			fmt.Println(err)
		}
	}

	if !exists(filepath.Join(getDataDir(), "profiles")) {
		fmt.Println("Adding profiles")
		os.MkdirAll(filepath.Join(getDataDir(), "profiles"), 0750)
		os.Chmod(getDataDir(), 0750)
	}
}
开发者ID:TSRAppLabs,项目名称:pbc,代码行数:33,代码来源:cert-manager.go

示例6: TestInWritableDirWindowsRemoveAll

func TestInWritableDirWindowsRemoveAll(t *testing.T) {
	// os.RemoveAll should remove read only things on windows

	if runtime.GOOS != "windows" {
		t.Skipf("Tests not required")
		return
	}

	err := os.RemoveAll("testdata")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Chmod("testdata/windows/ro/readonlynew", 0700)
	defer os.RemoveAll("testdata")

	create := func(name string) error {
		fd, err := os.Create(name)
		if err != nil {
			return err
		}
		fd.Close()
		return nil
	}

	os.Mkdir("testdata", 0700)

	os.Mkdir("testdata/windows", 0500)
	os.Mkdir("testdata/windows/ro", 0500)
	create("testdata/windows/ro/readonly")
	os.Chmod("testdata/windows/ro/readonly", 0500)

	if err := os.RemoveAll("testdata/windows"); err != nil {
		t.Errorf("Unexpected error: %s", err)
	}
}
开发者ID:letiemble,项目名称:syncthing,代码行数:35,代码来源:osutil_test.go

示例7: TestErrorHandler

// The only real errors right now are log based or RPC.
func TestErrorHandler(t *testing.T) {
	ci := ClusterInfo{Name: "foo", Size: 1}
	_, rpc, log := genNodeArgs(t)

	// Use ChanHandler
	scCh := make(chan StateChange)
	errCh := make(chan error)
	chHand := NewChanHandler(scCh, errCh)

	node, err := New(ci, chHand, rpc, log)
	if err != nil {
		t.Fatalf("Expected no error, got: %v", err)
	}
	defer node.Close()

	// Force a write to err
	os.Chmod(node.logPath, 0400)
	defer os.Chmod(node.logPath, 0660)

	err = errWait(t, errCh)

	perr, ok := err.(*os.PathError)
	if !ok {
		t.Fatalf("Got wrong error type")
	}
	if perr.Op != "open" {
		t.Fatalf("Got wrong operation, wanted 'open', got %q", perr.Op)
	}
	if perr.Path != node.LogPath() {
		t.Fatalf("Expected the logPath, got %s \n", perr.Path)
	}
}
开发者ID:nats-io,项目名称:graft,代码行数:33,代码来源:handler_test.go

示例8: TestAccess

func TestAccess(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Log("Skipping TestAccess() as root.")
		return
	}
	me := NewTestCase(t)
	defer me.Cleanup()

	err := ioutil.WriteFile(me.origFile, []byte(contents), 0700)
	CheckSuccess(err)
	err = os.Chmod(me.origFile, 0)
	CheckSuccess(err)
	// Ugh - copied from unistd.h
	const W_OK uint32 = 2

	errCode := syscall.Access(me.mountFile, W_OK)
	if errCode != syscall.EACCES {
		t.Errorf("Expected EACCES for non-writable, %v %v", errCode, syscall.EACCES)
	}
	err = os.Chmod(me.origFile, 0222)
	CheckSuccess(err)
	errCode = syscall.Access(me.mountFile, W_OK)
	if errCode != nil {
		t.Errorf("Expected no error code for writable. %v", errCode)
	}
}
开发者ID:taruti,项目名称:go-fuse,代码行数:26,代码来源:loopback_test.go

示例9: UnTar

// UnTar a tar file
func UnTar(srcTar string, dstDir string) (err error) {
	// 清理路径字符串
	dstDir = path.Clean(dstDir) + string(os.PathSeparator)

	fr, er := os.Open(srcTar)
	if er != nil {
		return er
	}
	defer fr.Close()

	tr := tar.NewReader(fr)

	for hdr, er := tr.Next(); er != io.EOF; hdr, er = tr.Next() {
		if er != nil {
			return er
		}

		fi := hdr.FileInfo()

		dstFullPath := dstDir + hdr.Name

		if hdr.Typeflag == tar.TypeDir {
			os.MkdirAll(dstFullPath, fi.Mode().Perm())
			os.Chmod(dstFullPath, fi.Mode().Perm())
		} else {
			os.MkdirAll(path.Dir(dstFullPath), os.ModePerm)
			if er := unTarFile(dstFullPath, tr); er != nil {
				return er
			}
			os.Chmod(dstFullPath, fi.Mode().Perm())
		}
	}
	return nil
}
开发者ID:icsnju,项目名称:apt-mesos,代码行数:35,代码来源:tar.go

示例10: Mount

func (d *driver) Mount(
	device, target, mountOptions, mountLabel string) error {

	if d.isNfsDevice(device) {

		if err := d.nfsMount(device, target); err != nil {
			return err
		}

		os.MkdirAll(d.volumeMountPath(target), d.fileModeMountPath())
		os.Chmod(d.volumeMountPath(target), d.fileModeMountPath())

		return nil
	}

	fsType, err := probeFsType(device)
	if err != nil {
		return err
	}

	options := label.FormatMountLabel("", mountLabel)
	options = fmt.Sprintf("%s,%s", mountOptions, mountLabel)
	if fsType == "xfs" {
		options = fmt.Sprintf("%s,nouuid", mountOptions)
	}

	if err := mount.Mount(device, target, fsType, options); err != nil {
		return fmt.Errorf("Couldn't mount directory %s at %s: %s", device, target, err)
	}

	os.MkdirAll(d.volumeMountPath(target), d.fileModeMountPath())
	os.Chmod(d.volumeMountPath(target), d.fileModeMountPath())

	return nil
}
开发者ID:lucmichalski,项目名称:rexray,代码行数:35,代码来源:linux.go

示例11: StreamDirAsTar

// StreamFileAsTar streams the source file as a tar archive.
// The permissions of the file is changed to 0666.
func (t *stiTar) StreamDirAsTar(source, dest string, writer io.Writer) error {
	f, err := os.Open(source)
	if err != nil {
		return err
	}
	if info, _ := f.Stat(); !info.IsDir() {
		return fmt.Errorf("the source %q has to be directory, not a file", source)
	}
	defer f.Close()
	fs := util.NewFileSystem()
	tmpDir, err := ioutil.TempDir("", "s2i-")
	if err != nil {
		return err
	}
	defer os.RemoveAll(tmpDir)
	if err := fs.Copy(source, tmpDir); err != nil {
		return err
	}
	// Skip chmod if on windows OS
	if runtime.GOOS != "windows" {
		err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if info.IsDir() {
				return os.Chmod(path, 0777)
			}
			return os.Chmod(path, 0666)
		})
		if err != nil {
			return err
		}
	}
	return t.CreateTarStream(tmpDir, false, writer)
}
开发者ID:asiainfoLDP,项目名称:datafactory,代码行数:37,代码来源:tar.go

示例12: TestAccess

func TestAccess(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Log("Skipping TestAccess() as root.")
		return
	}
	tc := NewTestCase(t)
	defer tc.Cleanup()

	contents := []byte{1, 2, 3}
	err := ioutil.WriteFile(tc.origFile, []byte(contents), 0700)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}
	err = os.Chmod(tc.origFile, 0)
	if err != nil {
		t.Fatalf("Chmod failed: %v", err)
	}
	// Ugh - copied from unistd.h
	const W_OK uint32 = 2

	errCode := syscall.Access(tc.mountFile, W_OK)
	if errCode != syscall.EACCES {
		t.Errorf("Expected EACCES for non-writable, %v %v", errCode, syscall.EACCES)
	}
	err = os.Chmod(tc.origFile, 0222)
	if err != nil {
		t.Fatalf("Chmod failed: %v", err)
	}
	errCode = syscall.Access(tc.mountFile, W_OK)
	if errCode != nil {
		t.Errorf("Expected no error code for writable. %v", errCode)
	}
}
开发者ID:seacoastboy,项目名称:go-fuse,代码行数:33,代码来源:loopback_test.go

示例13: updatePerms

func updatePerms(dirPath, mockPath string) {
	if knf.GetS(ACCESS_USER) != "" || knf.GetS(ACCESS_GROUP) != "" {
		dirOwnerUID, dirOwnerGID, _ := fsutil.GetOwner(dirPath)
		mockOwnerUID, mockOwnerGID, _ := fsutil.GetOwner(mockPath)

		if knf.GetS(ACCESS_USER) != "" {
			userInfo, err := system.LookupUser(knf.GetS(ACCESS_USER))

			if err == nil {
				dirOwnerUID = userInfo.UID
				mockOwnerUID = userInfo.UID
			}
		}

		if knf.GetS(ACCESS_GROUP) != "" {
			groupInfo, err := system.LookupGroup(knf.GetS(ACCESS_GROUP))

			if err == nil {
				dirOwnerGID = groupInfo.GID
				mockOwnerGID = groupInfo.GID
			}
		}

		os.Chown(dirPath, dirOwnerUID, dirOwnerGID)
		os.Chown(mockPath, mockOwnerUID, mockOwnerGID)
	}

	os.Chmod(dirPath, knf.GetM(ACCESS_MOCK_DIR_PERMS))
	os.Chmod(mockPath, knf.GetM(ACCESS_MOCK_PERMS))
}
开发者ID:essentialkaos,项目名称:mockka,代码行数:30,代码来源:gen.go

示例14: update

func update(p string, f os.FileInfo, err error) error {
	// Check the file mode.
	if f.IsDir() {
		m := os.FileMode(*cliChmodDir)
		if f.Mode().Perm() != m.Perm() {
			err := os.Chmod(p, m)
			if err != nil {
				log.Printf("Failed to chmod directory: %s", p)
			}
			log.Printf("Updated chmod directory: %s", p)
		}
	} else {
		m := os.FileMode(*cliChmodFile)
		if f.Mode().Perm() != m.Perm() {
			err := os.Chmod(p, m)
			if err != nil {
				log.Printf("Failed to chmod file: %s", p)
			}
			log.Printf("Updated chmod file: %s", p)
		}
	}

	// Check the file owner.
	fu := f.Sys().(*syscall.Stat_t).Uid
	fg := f.Sys().(*syscall.Stat_t).Gid
	if int(fu) != uid && int(fg) != gid {
		err := os.Chown(p, uid, gid)
		if err != nil {
			log.Printf("Failed to chown file: %s", p)
		}
		log.Printf("Updated chown file: %s", p)
	}

	return nil
}
开发者ID:nickschuch,项目名称:permissions,代码行数:35,代码来源:main.go

示例15: createCerts

func createCerts() {
	basedir := filepath.Dir(defaultCertFile)
	if _, err := os.Stat(basedir); os.IsNotExist(err) {
		if err := os.MkdirAll(basedir, 0755); err != nil {
			log.Fatal(err)
		}
	}
	if _, err := os.Stat(defaultCertFile); os.IsExist(err) {
		return
	}
	os.Chdir(basedir)
	certHosts := []string{"localhost", "127.0.0.1"}
	if hostname, err := os.Hostname(); err == nil {
		certHosts = append(certHosts, hostname)
	}
	if len(os.Getenv("GOGS_SERVER__ROOT_URL")) > 0 {
		certHosts = append(certHosts, os.Getenv("GOGS_SERVER__ROOT_URL"))
	}
	cmd := exec.Command("/opt/gogs/gogs", "cert", fmt.Sprintf("%s=%s", "-host", strings.Join(certHosts, ",")))
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	os.Chmod("cert.pem", 0644)
	os.Chmod("key.pem", 0644)
}
开发者ID:maxwhale,项目名称:docker-gogs-centos,代码行数:28,代码来源:start-gogs.go


注:本文中的os.Chmod函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。