2017-09-21 08:33:28 +02:00
|
|
|
// Copyright 2017 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2016-11-15 09:07:31 +02:00
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"os/user"
|
|
|
|
"path/filepath"
|
|
|
|
"runtime"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2017-11-13 09:52:04 +02:00
|
|
|
const gopsConfigDirEnvKey = "GOPS_CONFIG_DIR"
|
|
|
|
|
2016-11-15 09:07:31 +02:00
|
|
|
func ConfigDir() (string, error) {
|
2017-11-13 09:52:04 +02:00
|
|
|
if configDir := os.Getenv(gopsConfigDirEnvKey); configDir != "" {
|
|
|
|
return configDir, nil
|
|
|
|
}
|
|
|
|
|
2020-05-14 22:01:34 +02:00
|
|
|
if osUserConfigDir := getOSUserConfigDir(); osUserConfigDir != "" {
|
2020-05-30 09:40:59 +02:00
|
|
|
return filepath.Join(osUserConfigDir, "gops"), nil
|
2020-05-14 22:01:34 +02:00
|
|
|
}
|
|
|
|
|
2016-11-15 09:07:31 +02:00
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
return filepath.Join(os.Getenv("APPDATA"), "gops"), nil
|
|
|
|
}
|
2020-03-01 00:24:56 +02:00
|
|
|
|
|
|
|
if xdgConfigDir := os.Getenv("XDG_CONFIG_HOME"); xdgConfigDir != "" {
|
|
|
|
return filepath.Join(xdgConfigDir, "gops"), nil
|
|
|
|
}
|
|
|
|
|
2016-11-15 09:07:31 +02:00
|
|
|
homeDir := guessUnixHomeDir()
|
|
|
|
if homeDir == "" {
|
|
|
|
return "", errors.New("unable to get current user home directory: os/user lookup failed; $HOME is empty")
|
|
|
|
}
|
|
|
|
return filepath.Join(homeDir, ".config", "gops"), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func guessUnixHomeDir() string {
|
|
|
|
usr, err := user.Current()
|
|
|
|
if err == nil {
|
|
|
|
return usr.HomeDir
|
|
|
|
}
|
|
|
|
return os.Getenv("HOME")
|
|
|
|
}
|
|
|
|
|
2017-01-20 04:37:32 +02:00
|
|
|
func PIDFile(pid int) (string, error) {
|
2016-11-15 09:07:31 +02:00
|
|
|
gopsdir, err := ConfigDir()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2017-01-20 04:37:32 +02:00
|
|
|
return fmt.Sprintf("%s/%d", gopsdir, pid), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetPort(pid int) (string, error) {
|
|
|
|
portfile, err := PIDFile(pid)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2016-11-15 09:07:31 +02:00
|
|
|
b, err := ioutil.ReadFile(portfile)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
port := strings.TrimSpace(string(b))
|
|
|
|
return port, nil
|
|
|
|
}
|