コード例 #1
0
ファイル: 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
0
ファイル: 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
0
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
0
ファイル: harvest.go プロジェクト: pschyska/garvest
func getHome() string {
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	return usr.HomeDir
}
コード例 #5
0
ファイル: build.go プロジェクト: WeavingCode/syncthing
func buildUser() string {
	u, err := user.Current()
	if err != nil {
		return "unknown-user"
	}
	return strings.Replace(u.Username, " ", "-", -1)
}
コード例 #6
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
ファイル: 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
0
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
0
ファイル: 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
0
ファイル: launchd.go プロジェクト: mark-adams/client
func launchdHomeDir() string {
	currentUser, err := user.Current()
	if err != nil {
		panic(err)
	}
	return currentUser.HomeDir
}
コード例 #24
0
func defaultConfigDir() (string, error) {
	usr, err := user.Current()
	if err != nil {
		return "", nil
	}
	return path.Join(usr.HomeDir, defaultDir, configName), nil
}
コード例 #25
0
ファイル: sdk.go プロジェクト: EagerIO/oauth2
func guessUnixHomeDir() string {
	usr, err := user.Current()
	if err == nil {
		return usr.HomeDir
	}
	return os.Getenv("HOME")
}
コード例 #26
0
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
0
ファイル: 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
0
ファイル: 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: "******"failed to get current working directory: ", err)
	}
	return config
}
コード例 #29
0
ファイル: 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
0
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)
}