mirror of
https://github.com/gogs/gogs.git
synced 2025-05-28 02:02:09 +00:00
osutil: use system API to get the username when env vars are empty (#6246)
As Golang supports getting usernames via the standard library, this function is now used to get the username if the environment variables are empty. Using the standard library as a fallback is intended to keep compability to existing implementations that rely on the environment variables dictating the current username.
This commit is contained in:
parent
d1caae3f79
commit
252d0fd977
@ -6,6 +6,7 @@ package osutil
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"os/user"
|
||||||
)
|
)
|
||||||
|
|
||||||
// IsFile returns true if given path exists as a file (i.e. not a directory).
|
// IsFile returns true if given path exists as a file (i.e. not a directory).
|
||||||
@ -33,12 +34,20 @@ func IsExist(path string) bool {
|
|||||||
return err == nil || os.IsExist(err)
|
return err == nil || os.IsExist(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CurrentUsername returns the current system user via environment variables.
|
// CurrentUsername returns the current system user
|
||||||
func CurrentUsername() string {
|
func CurrentUsername() string {
|
||||||
username := os.Getenv("USER")
|
username := os.Getenv("USER")
|
||||||
if len(username) > 0 {
|
if len(username) > 0 {
|
||||||
return username
|
return username
|
||||||
}
|
}
|
||||||
|
|
||||||
return os.Getenv("USERNAME")
|
username = os.Getenv("USERNAME")
|
||||||
|
if len(username) > 0 {
|
||||||
|
return username
|
||||||
|
}
|
||||||
|
|
||||||
|
if user, err := user.Current(); err == nil {
|
||||||
|
username = user.Username
|
||||||
|
}
|
||||||
|
return username
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,7 @@
|
|||||||
package osutil
|
package osutil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@ -83,3 +84,17 @@ func TestCurrentUsername(t *testing.T) {
|
|||||||
// Make sure it does not blow up
|
// Make sure it does not blow up
|
||||||
CurrentUsername()
|
CurrentUsername()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCurrentUsernamePrefersEnvironmentVariable(t *testing.T) {
|
||||||
|
// Some users/scripts expect that they can change the current username via environment variables
|
||||||
|
if userBak, ok := os.LookupEnv("USER"); ok {
|
||||||
|
defer os.Setenv("USER", userBak)
|
||||||
|
} else {
|
||||||
|
defer os.Unsetenv("USER")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Setenv("USER", "__TESTING::USERNAME"); err != nil {
|
||||||
|
t.Skip("Could not set the USER environment variable:", err)
|
||||||
|
}
|
||||||
|
assert.Equal(t, "__TESTING::USERNAME", CurrentUsername())
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user