Skip to content

Commit

Permalink
Merge pull request #271 from phillipsj/feature/klog-windows-nanoserver
Browse files Browse the repository at this point in the history
Using OS targeted go files to separate out the username logic.
  • Loading branch information
k8s-ci-robot committed Dec 18, 2021
2 parents 9248e72 + 16e27a9 commit fb7504b
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 34 deletions.
34 changes: 0 additions & 34 deletions klog_file.go
Expand Up @@ -22,9 +22,7 @@ import (
"errors"
"fmt"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -57,38 +55,6 @@ func init() {
}
}

func getUserName() string {
userNameOnce.Do(func() {
// On Windows, the Go 'user' package requires netapi32.dll.
// This affects Windows Nano Server:
// https://github.com/golang/go/issues/21867
// Fallback to using environment variables.
if runtime.GOOS == "windows" {
u := os.Getenv("USERNAME")
if len(u) == 0 {
return
}
// Sanitize the USERNAME since it may contain filepath separators.
u = strings.Replace(u, `\`, "_", -1)

// user.Current().Username normally produces something like 'USERDOMAIN\USERNAME'
d := os.Getenv("USERDOMAIN")
if len(d) != 0 {
userName = d + "_" + u
} else {
userName = u
}
} else {
current, err := user.Current()
if err == nil {
userName = current.Username
}
}
})

return userName
}

// shortHostname returns its argument, truncating at the first period.
// For instance, given "www.google.com" it returns "www".
func shortHostname(hostname string) string {
Expand Down
19 changes: 19 additions & 0 deletions klog_file_others.go
@@ -0,0 +1,19 @@
//go:build !windows
// +build !windows

package klog

import (
"os/user"
)

func getUserName() string {
userNameOnce.Do(func() {
current, err := user.Current()
if err == nil {
userName = current.Username
}
})

return userName
}
34 changes: 34 additions & 0 deletions klog_file_windows.go
@@ -0,0 +1,34 @@
//go:build windows
// +build windows

package klog

import (
"os"
"strings"
)

func getUserName() string {
userNameOnce.Do(func() {
// On Windows, the Go 'user' package requires netapi32.dll.
// This affects Windows Nano Server:
// https://github.com/golang/go/issues/21867
// Fallback to using environment variables.
u := os.Getenv("USERNAME")
if len(u) == 0 {
return
}
// Sanitize the USERNAME since it may contain filepath separators.
u = strings.Replace(u, `\`, "_", -1)

// user.Current().Username normally produces something like 'USERDOMAIN\USERNAME'
d := os.Getenv("USERDOMAIN")
if len(d) != 0 {
userName = d + "_" + u
} else {
userName = u
}
})

return userName
}

0 comments on commit fb7504b

Please sign in to comment.