jx/internal/resource/os.go

89 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-03-20 19:23:31 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
2024-03-22 17:39:06 +00:00
2024-03-20 16:15:27 +00:00
package resource
import (
2024-03-25 20:31:06 +00:00
"os/user"
"strconv"
2024-04-18 00:07:12 +00:00
"regexp"
2024-05-06 00:48:54 +00:00
"log/slog"
2024-03-20 16:15:27 +00:00
)
2024-04-18 00:07:12 +00:00
var MatchId *regexp.Regexp = regexp.MustCompile(`^[0-9]+$`)
2024-03-20 19:23:31 +00:00
func LookupUIDString(userName string) string {
2024-03-25 20:31:06 +00:00
user, userLookupErr := user.Lookup(userName)
if userLookupErr != nil {
return ""
}
return user.Uid
2024-03-20 19:23:31 +00:00
}
2024-03-25 20:31:06 +00:00
func LookupUID(userName string) (int, error) {
2024-05-06 00:48:54 +00:00
var userLookupErr error
2024-04-18 00:07:12 +00:00
var UID string
if MatchId.MatchString(userName) {
2024-05-06 00:48:54 +00:00
user, err := user.LookupId(userName)
slog.Info("LookupUID() numeric", "user", user, "userLookupErr", err)
if err != nil {
userLookupErr = err
2024-04-18 00:07:12 +00:00
UID = userName
} else {
UID = user.Uid
}
} else {
2024-05-06 00:48:54 +00:00
if user, err := user.Lookup(userName); err != nil {
return -1, err
} else {
UID = user.Uid
2024-04-18 00:07:12 +00:00
}
2024-03-25 20:31:06 +00:00
}
2024-03-20 16:15:27 +00:00
2024-04-18 00:07:12 +00:00
uid, uidErr := strconv.Atoi(UID)
2024-05-06 00:48:54 +00:00
slog.Info("LookupUID()", "uid", uid, "uidErr", uidErr)
2024-03-25 20:31:06 +00:00
if uidErr != nil {
2024-05-06 00:48:54 +00:00
if userLookupErr != nil {
return -1, userLookupErr
} else {
return -1, uidErr
}
2024-03-25 20:31:06 +00:00
}
2024-03-20 16:15:27 +00:00
2024-05-06 00:48:54 +00:00
return uid, userLookupErr
2024-03-20 16:15:27 +00:00
}
2024-03-25 20:31:06 +00:00
func LookupGID(groupName string) (int, error) {
2024-04-18 00:07:12 +00:00
var GID string
if MatchId.MatchString(groupName) {
group, groupLookupErr := user.LookupGroupId(groupName)
if groupLookupErr != nil {
//return -1, groupLookupErr
GID = groupName
} else {
GID = group.Gid
}
} else {
group, groupLookupErr := user.LookupGroup(groupName)
if groupLookupErr != nil {
return -1, groupLookupErr
}
GID = group.Gid
2024-03-25 20:31:06 +00:00
}
2024-04-18 00:07:12 +00:00
gid, gidErr := strconv.Atoi(GID)
2024-03-25 20:31:06 +00:00
if gidErr != nil {
return -1, gidErr
}
return gid, nil
2024-03-20 16:15:27 +00:00
}
2024-07-17 08:34:57 +00:00
func LookupGIDString(groupName string) string {
group, groupLookupErr := user.LookupGroup(groupName)
if groupLookupErr != nil {
return ""
}
return group.Gid
}