jx/internal/resource/os.go
Matthew Rich 976f654c60
Some checks failed
Lint / golangci-lint (push) Failing after 9m47s
Declarative Tests / test (push) Failing after 10s
handle numeric user ids
2024-04-17 17:07:12 -07:00

72 lines
1.3 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"os/user"
"strconv"
"regexp"
)
var MatchId *regexp.Regexp = regexp.MustCompile(`^[0-9]+$`)
func LookupUIDString(userName string) string {
user, userLookupErr := user.Lookup(userName)
if userLookupErr != nil {
return ""
}
return user.Uid
}
func LookupUID(userName string) (int, error) {
var UID string
if MatchId.MatchString(userName) {
user, userLookupErr := user.LookupId(userName)
if userLookupErr != nil {
//return -1, userLookupErr
UID = userName
} else {
UID = user.Uid
}
} else {
user, userLookupErr := user.Lookup(userName)
if userLookupErr != nil {
return -1, userLookupErr
}
UID = user.Uid
}
uid, uidErr := strconv.Atoi(UID)
if uidErr != nil {
return -1, uidErr
}
return uid, nil
}
func LookupGID(groupName string) (int, error) {
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
}
gid, gidErr := strconv.Atoi(GID)
if gidErr != nil {
return -1, gidErr
}
return gid, nil
}