2018-11-18 09:55:05 -08: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.
|
|
|
|
|
2017-03-23 15:28:55 -07:00
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"os"
|
|
|
|
"os/user"
|
|
|
|
"path/filepath"
|
2020-07-18 08:27:41 -07:00
|
|
|
"strconv"
|
2017-03-23 15:28:55 -07:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-11-18 09:55:05 -08:00
|
|
|
const gopsConfigDirEnvKey = "GOPS_CONFIG_DIR"
|
|
|
|
|
2017-03-23 15:28:55 -07:00
|
|
|
func ConfigDir() (string, error) {
|
2018-11-18 09:55:05 -08:00
|
|
|
if configDir := os.Getenv(gopsConfigDirEnvKey); configDir != "" {
|
|
|
|
return configDir, nil
|
|
|
|
}
|
|
|
|
|
2022-08-13 07:14:26 -07:00
|
|
|
if userConfigDir, err := os.UserConfigDir(); err == nil {
|
|
|
|
return filepath.Join(userConfigDir, "gops"), nil
|
2020-07-18 08:27:41 -07:00
|
|
|
}
|
|
|
|
|
2017-03-23 15:28:55 -07: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")
|
|
|
|
}
|
|
|
|
|
|
|
|
func PIDFile(pid int) (string, error) {
|
|
|
|
gopsdir, err := ConfigDir()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2020-07-18 08:27:41 -07:00
|
|
|
return filepath.Join(gopsdir, strconv.Itoa(pid)), nil
|
2017-03-23 15:28:55 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func GetPort(pid int) (string, error) {
|
|
|
|
portfile, err := PIDFile(pid)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2023-03-09 13:48:00 -08:00
|
|
|
b, err := os.ReadFile(portfile)
|
2017-03-23 15:28:55 -07:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
port := strings.TrimSpace(string(b))
|
|
|
|
return port, nil
|
|
|
|
}
|