1
0
mirror of https://github.com/google/gops.git synced 2024-11-27 08:31:17 +02:00
gops/internal/internal.go

63 lines
1.3 KiB
Go
Raw Normal View History

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"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strconv"
2016-11-15 09:07:31 +02:00
"strings"
)
const gopsConfigDirEnvKey = "GOPS_CONFIG_DIR"
2016-11-15 09:07:31 +02:00
func ConfigDir() (string, error) {
if configDir := os.Getenv(gopsConfigDirEnvKey); configDir != "" {
return configDir, nil
}
2022-06-24 23:20:02 +02:00
if userConfigDir, err := os.UserConfigDir(); err == nil {
return filepath.Join(userConfigDir, "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")
}
func PIDFile(pid int) (string, error) {
2016-11-15 09:07:31 +02:00
gopsdir, err := ConfigDir()
if err != nil {
return "", err
}
return filepath.Join(gopsdir, strconv.Itoa(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
}