Golang Current示例

说明

golang current示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: os/user

示例#1
文件: cdglobal.go 项目: sqp/godock

// ConfigDirDock returns a full path to the dock config dir, according to the given user option.
//
func ConfigDirDock(dir string) string {
	if len(dir) > 0 {
		switch dir[0] {
		case '/':
			return dir // Full path, used as is.

		case '~':
			usr, e := user.Current()
			if e == nil {
				return usr.HomeDir + dir[1:] // Relative path to the homedir.
			}
		}

		current, e := os.Getwd()
		if e == nil {
			return filepath.Join(current, dir) // Relative path to the current dir.
		}
	}

	usr, e := user.Current()
	if e == nil {
		return filepath.Join(usr.HomeDir, ".config", ConfigDirBaseName) // Default dock config path in .config.
	}

	return ""
}

示例#2
文件: common.go 项目: howbazaar/lingo

// TenetCfgPathRecusive looks for a config file at cfgPath. If the config
// file name is equal to DefaultTenetCfgPath, the func recursively searches the
// parent directory until a file with that name is found. In the case that
// none is found "" is retuned.
func TenetCfgPathRecusive(cfgPath string) (string, error) {
	var err error
	cfgPath, err = filepath.Abs(cfgPath)
	if err != nil {
		return "", err
	}

	if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
		dir, file := path.Split(cfgPath)
		if file == DefaultTenetCfgPath {
			if dir == "/" {
				// we've reached the end of the line. Fall back to default:
				usr, err := user.Current()
				if err != nil {
					return "", err
				}

				lHome, err := util.LingoHome()
				if err != nil {
					return "", errors.Trace(err)
				}
				defaultTenets := path.Join(usr.HomeDir, lHome, DefaultTenetCfgPath)
				if _, err := os.Stat(defaultTenets); err != nil {
					return "", err
				}
				return defaultTenets, nil
			}
			parent := path.Dir(path.Dir(dir))
			return TenetCfgPathRecusive(parent + "/" + DefaultTenetCfgPath)
		}
		return "", err
	}
	return cfgPath, nil
}

示例#3
文件: factory_test.go 项目: ravihansa3000/kubernetes

func TestSubstitueUser(t *testing.T) {
	usr, err := user.Current()
	if err != nil {
		t.Logf("SKIPPING TEST: unexpected error: %v", err)
		return
	}
	tests := []struct {
		input     string
		expected  string
		expectErr bool
	}{
		{input: "~/foo", expected: path.Join(os.Getenv("HOME"), "foo")},
		{input: "~" + usr.Username + "/bar", expected: usr.HomeDir + "/bar"},
		{input: "/foo/bar", expected: "/foo/bar"},
		{input: "~doesntexit/bar", expectErr: true},
	}
	for _, test := range tests {
		output, err := substituteUserHome(test.input)
		if test.expectErr {
			if err == nil {
				t.Error("unexpected non-error")
			}
			continue
		}
		if err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if output != test.expected {
			t.Errorf("expected: %s, saw: %s", test.expected, output)
		}
	}
}

示例#4
文件: harvest.go 项目: pschyska/garvest

func getHome() string {
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	return usr.HomeDir
}

示例#5
文件: build.go 项目: WeavingCode/syncthing

func buildUser() string {
	u, err := user.Current()
	if err != nil {
		return "unknown-user"
	}
	return strings.Replace(u.Username, " ", "-", -1)
}

示例#6
文件: skeleton.go 项目: jkotrlik/salsaflow

func cacheDirectoryAbsolutePath() (path string, err error) {
	me, err := user.Current()
	if err != nil {
		return "", nil
	}
	return filepath.Join(me.HomeDir, SkeletonCacheDirname), nil
}

示例#7
文件: simplessh.go 项目: bvnarayan/simplessh

func connect(username, host string, authMethod ssh.AuthMethod, timeout time.Duration) (*Client, error) {
	if username == "" {
		user, err := user.Current()
		if err != nil {
			return nil, fmt.Errorf("Username wasn't specified and couldn't get current user: %v", err)
		}

		username = user.Username
	}

	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{authMethod},
	}

	host = addPortToHost(host)

	conn, err := net.DialTimeout("tcp", host, timeout)
	if err != nil {
		return nil, err
	}
	sshConn, chans, reqs, err := ssh.NewClientConn(conn, host, config)
	if err != nil {
		return nil, err
	}
	client := ssh.NewClient(sshConn, chans, reqs)

	c := &Client{SSHClient: client}
	return c, nil
}

示例#8
文件: conf.go 项目: gongshw/lighthouse

func tryConfigFilePath(configFilePath string) (string, error) {
	if configFilePath != "" {
		configFilePath, _ = filepath.Abs(configFilePath)
		if _, err := os.Stat(configFilePath); err == nil {
			log.Println("found log file at " + configFilePath)
			return configFilePath, nil
		} else {
			return "", err
		}
	} else {
		posibleConfigFiles := []string{}
		if p, e := os.Getwd(); e == nil {
			// loop for lighthouse.json from current working directory
			posibleConfigFiles = append(posibleConfigFiles, p+"/lighthouse.json")
		}
		if u, e := user.Current(); e == nil {
			// loop for lighthouse.json from current user's home directory
			posibleConfigFiles = append(posibleConfigFiles, u.HomeDir+"/lighthouse.json")
		}
		for _, path := range posibleConfigFiles {
			if _, err := os.Stat(path); err == nil {
				log.Println("found configuration file at " + path)
				return path, nil
			}
		}
		log.Println("no configuration file found. use defalut config.")
		// not valid config file found
		return "", nil
	}
}

示例#9
文件: config.go 项目: kajali/fish

func init() {
	var u *user.User
	if u, _ = user.Current(); u == nil {
		panic("user.Current is nil")
	}
	configFile = path.Join(u.HomeDir, ".fish")
}

示例#10
文件: config.go 项目: b1lly/guppy

// NewGuppyConfig will return a config based on a few things;
// It first creates some default settings and merges/overwrites that with the root config (~/.guppy)
// It then looks for a project specific config (current working directory) and will merge/overwrite
// that previous result with the project specific config settings.
func NewGuppyConfig() *GuppyConfig {
	cwd, err := os.Getwd()
	if err != nil {
		return nil
	}

	gc := &GuppyConfig{
		cwd,
		"/guppy_modules",
		"localhost:13379",
		"localhost:13379",
		true,
	}

	user, err := user.Current()
	if err == nil {
		err = gc.load(user.HomeDir)

		if err != nil {
			glog.Error("Failed to load guppy root config:", err)
		}
	}

	if cwd != user.HomeDir {
		err = gc.load(cwd)
		if err != nil {
			glog.Error("Failed to load guppy project config:", err)
		}
	}

	return gc
}

示例#11
文件: file_helpers.go 项目: thacker99/textql

func CleanPath(path string) string {
	result := ""

	if path == "" {
		return ""
	}

	usr, err := user.Current()
	if err != nil {
		log.Fatalln(err)
	}

	if len(path) > 1 && path[:2] == "~/" {
		dir := usr.HomeDir + "/"
		result = strings.Replace(path, "~/", dir, 1)
	} else {
		result = path
	}

	absResult, absErr := filepath.Abs(result)
	if absErr != nil {
		log.Fatalln(absErr)
	}

	cleanResult := filepath.Clean(absResult)

	return cleanResult
}

示例#12
文件: auth.go 项目: tnum5/gogas

// secretsFile creates a file path/filename
// It returns the app client secrets path/filename.
func secretsFile() (string, error) {
	usr, err := user.Current()
	if err != nil {
		return "", err
	}
	return filepath.Join(usr.HomeDir, ".credentials", "client_secret", "gogas_client_secret.json"), err
}

示例#13
文件: 00_write_random_data.go 项目: xqbumu/learn

func init() {
	usr, err := user.Current()
	if err != nil {
		panic(err)
	}
	dbPath = filepath.Join(usr.HomeDir, dbPath)
}

示例#14
文件: cache.go 项目: dmcgowan/golem

func (b *Builder) loadCache() (err error) {
	b.cache = map[string]string{}

	usr, err := user.Current()
	if err != nil {
		return fmt.Errorf("unable to get current user: %s", err)
	}

	cacheFilename := fmt.Sprintf("%s%c%s", usr.HomeDir, filepath.Separator, ".dockrampcache")
	cacheFile, err := os.Open(cacheFilename)
	if os.IsNotExist(err) {
		// No cache file exists to load.
		return nil
	}
	if err != nil {
		return fmt.Errorf("unable to open cache file: %s", err)
	}
	defer func() {
		if closeErr := cacheFile.Close(); err == nil {
			err = closeErr
		}
	}()

	if err := json.NewDecoder(cacheFile).Decode(&b.cache); err != nil {
		return fmt.Errorf("unable to decode build cache: %s", err)
	}

	return nil
}

示例#15
文件: gdrive.go 项目: santeriv/gdrive-webdav

func NewGDriveFileSystem(clientId string, clientSecret string) *GDriveFileSystem {
	u, err := user.Current()

	tokenFile := u.HomeDir + "/.gdrive_token"

	if *tokenFileFlag != "" {
		tokenFile = *tokenFileFlag
	}

	config.TokenCache = oauth.CacheFile(tokenFile)
	config.ClientId = clientId
	config.ClientSecret = clientSecret

	transport := &oauth.Transport{
		Config:    config,
		Transport: &loggingTransport{http.DefaultTransport},
	}

	obtainToken(transport)

	client, err := drive.New(transport.Client())
	if err != nil {
		log.Errorf("An error occurred creating Drive client: %v\n", err)
		panic(-3)
	}

	fs := &GDriveFileSystem{
		client:    client,
		transport: transport,
		cache:     gocache.New(5*time.Minute, 30*time.Second),
	}
	return fs
}

示例#16
文件: acme.go 项目: uvelichitel/compl

// taken from src/lib9/getns.c
// This should go into goplan9/plan9/client.
func nsFromDisplay() (string, error) {
	disp := os.Getenv("DISPLAY")
	if disp == "" {
		// original code had heuristic for OS X here;
		// we'll just assume that and fail anyway if it
		// doesn't work.
		disp = ":0.0"
	}
	// canonicalize: xxx:0.0 => xxx:0
	if i := strings.LastIndex(disp, ":"); i >= 0 {
		if strings.HasSuffix(disp, ".0") {
			disp = disp[:len(disp)-2]
		}
	}

	// turn /tmp/launch/:0 into _tmp_launch_:0 (OS X 10.5)
	disp = strings.Replace(disp, "/", "_", -1)

	u, err := user.Current()
	if err != nil {
		return "", fmt.Errorf("cannot get current user name: %v", err)
	}
	ns := fmt.Sprintf("/tmp/ns.%s.%s", u.Username, disp)
	_, err = os.Stat(ns)
	if os.IsNotExist(err) {
		return "", fmt.Errorf("no name space directory found")
	}
	if err != nil {
		return "", fmt.Errorf("cannot stat name space directory: %v", err)
	}
	// heuristics for checking permissions and owner of name space
	// directory omitted.
	return ns, nil
}

示例#17
文件: create.go 项目: pwaller/mantle

// Because Go is like... naaaaa, no groups aren't a thing!
// Based on Go's src/os/user/lookup_unix.go
func currentUserAndGroup() (*userAndGroup, error) {
	u, err := user.Current()
	if err != nil {
		return nil, err
	}
	gid, err := strconv.Atoi(u.Gid)
	if err != nil {
		return nil, err
	}

	var grp C.struct_group
	var result *C.struct_group
	buflen := C.sysconf(C._SC_GETPW_R_SIZE_MAX)
	if buflen <= 0 || buflen > 1<<20 {
		return nil, fmt.Errorf("unreasonable _SC_GETGR_R_SIZE_MAX of %d", buflen)
	}
	buf := C.malloc(C.size_t(buflen))
	defer C.free(buf)

	r := C.mygetgrgid_r(C.gid_t(gid), &grp,
		(*C.char)(buf),
		C.size_t(buflen),
		&result)
	if r != 0 {
		return nil, fmt.Errorf("lookup gid %d: %s", gid, syscall.Errno(r))
	}
	if result == nil {
		return nil, fmt.Errorf("lookup gid %d failed", gid)
	}

	return &userAndGroup{
		User:      u,
		Groupname: C.GoString(grp.gr_name),
	}, nil
}

示例#18
文件: config.go 项目: iopred/discord-cli

//CreateConfig creates folder inside $HOME and makes a new empty configuration file
func CreateConfig() {
	//Get User
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	var EmptyStruct Session

	//Create Folder
	err = os.MkdirAll(usr.HomeDir+"/.config/discord-cli/", os.ModePerm)
	if err != nil {
		log.Fatalln(err)
	}

	//Create File
	file, err := os.Create(usr.HomeDir + "/.config/discord-cli/config.json")
	if err != nil {
		log.Fatalln(err)
	}

	//Marshall EmptyStruct
	raw, err := json.Marshal(EmptyStruct)
	if err != nil {
		log.Fatalln(err)
	}

	//PrintToFile
	_, err = file.Write(raw)
	if err != nil {
		log.Fatalln(err)
	}

	file.Close()
}

示例#19
文件: keys.go 项目: colebrumley/mssh-go

func loadDefaultKeys() (auths []ssh.AuthMethod, err error) {
	k := ""
	currentUser, err := user.Current()
	defaultKeyPathA := filepath.FromSlash(currentUser.HomeDir + "/.ssh/id_rsa")
	defaultKeyPathB := filepath.FromSlash(currentUser.HomeDir + "/ssh/id_rsa")
	if fileExists(defaultKeyPathA) {
		k = defaultKeyPathA
	} else if fileExists(defaultKeyPathB) {
		k = defaultKeyPathB
	}
	if len(k) == 0 {
		err = errors.New("No key specified")
		return
	}
	pemBytes, err := ioutil.ReadFile(k)
	if err != nil {
		return
	}
	signer, err := ssh.ParsePrivateKey(pemBytes)
	if err != nil {
		return
	}
	auths = []ssh.AuthMethod{ssh.PublicKeys(signer)}
	return
}

示例#20
文件: runtime_test.go 项目: neomantra/docker

func init() {
	// Hack to run sys init during unit testing
	if SelfPath() == "/sbin/init" {
		SysInit()
		return
	}

	if usr, err := user.Current(); err != nil {
		panic(err)
	} else if usr.Uid != "0" {
		panic("docker tests needs to be run as root")
	}

	// Make it our Store root
	runtime, err := NewRuntimeFromDirectory(unitTestStoreBase)
	if err != nil {
		panic(err)
	}
	// Create the "Server"
	srv := &Server{
		runtime: runtime,
	}
	// Retrieve the Image
	if err := srv.CmdPull(os.Stdin, rcli.NewDockerLocalConn(os.Stdout), unitTestImageName); err != nil {
		panic(err)
	}
}

示例#21
文件: jaegerdb.go 项目: tomzhang/golang-devops-stuff

func processPublicKeyRing() (entity *openpgp.Entity, entitylist openpgp.EntityList) {
	// TODO: Handle a specified recipient
	// Get default public keyring location
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	jaegerPublicKeyRing := fmt.Sprintf("%v/.gnupg/jaeger_pubring.gpg", usr.HomeDir)
	publicKeyRing := ""

	if _, err := os.Stat(jaegerPublicKeyRing); err == nil {
		publicKeyRing = jaegerPublicKeyRing
	} else {
		publicKeyRing = fmt.Sprintf("%v/.gnupg/pubring.gpg", usr.HomeDir)
	}

	debug.Printf("publicKeyRing file:", publicKeyRing)
	publicKeyRingBuffer, err := os.Open(publicKeyRing)
	if err != nil {
		panic(err)
	}
	entitylist, err = openpgp.ReadKeyRing(publicKeyRingBuffer)
	if err != nil {
		log.Fatal(err)
	}

	entity = entitylist[0]
	debug.Printf("Public key default keyring:", entity.Identities)

	return entity, entitylist
}

示例#22
文件: main.go 项目: nymsio/nyms-agent

func getLogPath() string {
	u, err := user.Current()
	if err != nil {
		panic(fmt.Sprintf("Failed to get current user information: %v", err))
	}
	return filepath.Join(u.HomeDir, defaultLogPath)
}

示例#23
文件: launchd.go 项目: mark-adams/client

func launchdHomeDir() string {
	currentUser, err := user.Current()
	if err != nil {
		panic(err)
	}
	return currentUser.HomeDir
}

示例#24
文件: config.go 项目: frederikfroehle/phraseapp-client

func defaultConfigDir() (string, error) {
	usr, err := user.Current()
	if err != nil {
		return "", nil
	}
	return path.Join(usr.HomeDir, defaultDir, configName), nil
}

示例#25
文件: sdk.go 项目: EagerIO/oauth2

func guessUnixHomeDir() string {
	usr, err := user.Current()
	if err == nil {
		return usr.HomeDir
	}
	return os.Getenv("HOME")
}

示例#26
文件: executor_docker.go 项目: mikew/gitlab-ci-multi-runner

func (s *DockerExecutor) getAuthConfig(imageName string) (docker.AuthConfiguration, error) {
	user, err := u.Current()
	if s.Shell.User != nil {
		user, err = u.Lookup(*s.Shell.User)
	}
	if err != nil {
		return docker.AuthConfiguration{}, err
	}

	indexName, _ := docker_helpers.SplitDockerImageName(imageName)

	authConfigs, err := docker_helpers.ReadDockerAuthConfigs(user.HomeDir)
	if err != nil {
		// ignore doesn't exist errors
		if os.IsNotExist(err) {
			err = nil
		}
		return docker.AuthConfiguration{}, err
	}

	authConfig := docker_helpers.ResolveDockerAuthConfig(indexName, authConfigs)
	if authConfig != nil {
		s.Debugln("Using", authConfig.Username, "to connect to", authConfig.ServerAddress, "in order to resolve", imageName, "...")
		return *authConfig, nil
	}

	return docker.AuthConfiguration{}, fmt.Errorf("No credentials found for %v", indexName)
}

示例#27
文件: director.go 项目: wangDalii/gogobosh

// DefaultBoshConfigPath returns the path to ~/.bosh_config
func DefaultBoshConfigPath() (configPath string, err error) {
	usr, err := user.Current()
	if err != nil {
		return "", err
	}
	return filepath.Abs(usr.HomeDir + "/.bosh_config")
}

示例#28
文件: conf.go 项目: JohannWeging/covey

func NewConfig() *Config {
	var runControllerScript string = `
sshd_run=$(which sshd)
$sshd_run -D&

munged_run=$(which munged)
$munged_run -F&

slurm_env_config_run=$(which 'slurm-env-config')
$slurm_env_config_run >> /etc/slurm.conf

slurmctl_run=$(which /usr/sbin/slurmctld)
$slurmctl_run -D -v&
wait
`

	var runNodeScript string = `
sshd_run=$(which sshd)
$sshd_run -D&

munged_run=$(which munged)
$munged_run -F&

slurm_env_config_run=$(which 'slurm-env-config')
$slurm_env_config_run >> /etc/slurm.conf

slurmctl_run=$(which /usr/sbin/slurmd)
$slurmctl_run -D -v&
wait
`
	config := &Config{
		CLI: newCli(),
		Dir: newConfDir(),
	}

	controllerScriptPath := filepath.Join(config.Dir, "run_controller.sh")
	err := ioutil.WriteFile(controllerScriptPath, []byte(runControllerScript), 0755)
	if err != nil {
		log.Fatal("failed to write run_controller.sh: ", err)
	}

	nodeScriptPath := filepath.Join(config.Dir, "run_node.sh")
	err = ioutil.WriteFile(nodeScriptPath, []byte(runNodeScript), 0755)
	if err != nil {
		log.Fatal("failed to write run_node.sh: ", err)
	}

	u, err := user.Current()
	if err != nil {
		log.Fatal("failed to get current user: ", err)
	}
	config.User = u.Username
	config.GID = u.Gid

	config.PWD, err = os.Getwd()
	if err != nil {
		log.Fatal("failed to get current working directory: ", err)
	}
	return config
}

示例#29
文件: cli.go 项目: rjeczalik/pulsekit

func config(mode int) (f *os.File, err error) {
	u, err := user.Current()
	if err != nil {
		return
	}
	return os.OpenFile(filepath.Join(u.HomeDir, ".pulsecli"), mode, 0644)
}

示例#30
文件: sete_datashapes_test.go 项目: jchris/indexing

func TestLargeDocumentSize(t *testing.T) {
	log.Printf("In TestLargeDocumentSize()")

	u, _ := user.Current()
	datapath := filepath.Join(u.HomeDir, "testdata/TwitterFeed1.txt.gz")
	tc.DownloadDataFile(tc.IndexTypesTwitterFeed1JSONDataS3, datapath, true)
	largeDocs := datautility.LoadJSONFromCompressedFile(datapath, "id_str")
	UpdateKVDocs(largeDocs, docs)

	log.Printf("Length of docs and largeDocs = %d and %d", len(docs), len(largeDocs))

	bucketName := "default"
	index1 := "index_userscreenname"

	kvutility.SetKeyValues(largeDocs, bucketName, "", clusterconfig.KVAddress)

	err := secondaryindex.CreateSecondaryIndex(index1, bucketName, indexManagementAddress, "", []string{"`user`.screen_name"}, false, nil, true, defaultIndexActiveTimeout, nil)
	FailTestIfError(err, "Error in creating the index", t)

	docScanResults := datautility.ExpectedScanAllResponse(docs, "user.screen_name")
	scanResults, err := secondaryindex.ScanAll(index1, bucketName, indexScanAddress, defaultlimit, c.SessionConsistency, nil)
	FailTestIfError(err, "Error in scan 1: ", t)
	err = tv.Validate(docScanResults, scanResults)
	FailTestIfError(err, "Error in scan 1:  result validation", t)
}

展开阅读全文