|
| 1 | +// Copyright The KCL Authors. |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | + |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | + |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | +// |
| 14 | +// Reference: k8s.io/client-go/util/homedir |
| 15 | +package path |
| 16 | + |
| 17 | +import ( |
| 18 | + "os" |
| 19 | + "runtime" |
| 20 | +) |
| 21 | + |
| 22 | +// HomeDir returns the home directory for the current user. |
| 23 | +// On Windows: |
| 24 | +// 1. if none of those locations are writeable, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists is returned. |
| 25 | +// 2. if none of those locations exists, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that is set is returned. |
| 26 | +func HomeDir() string { |
| 27 | + if runtime.GOOS == "windows" { |
| 28 | + home := os.Getenv("HOME") |
| 29 | + homeDriveHomePath := "" |
| 30 | + if homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH"); len(homeDrive) > 0 && len(homePath) > 0 { |
| 31 | + homeDriveHomePath = homeDrive + homePath |
| 32 | + } |
| 33 | + userProfile := os.Getenv("USERPROFILE") |
| 34 | + |
| 35 | + firstSetPath := "" |
| 36 | + firstExistingPath := "" |
| 37 | + |
| 38 | + // Prefer %USERPROFILE% over %HOMEDRIVE%/%HOMEPATH% for compatibility with other auth-writing tools |
| 39 | + for _, p := range []string{home, userProfile, homeDriveHomePath} { |
| 40 | + if len(p) == 0 { |
| 41 | + continue |
| 42 | + } |
| 43 | + if len(firstSetPath) == 0 { |
| 44 | + // remember the first path that is set |
| 45 | + firstSetPath = p |
| 46 | + } |
| 47 | + info, err := os.Stat(p) |
| 48 | + if err != nil { |
| 49 | + continue |
| 50 | + } |
| 51 | + if len(firstExistingPath) == 0 { |
| 52 | + // remember the first path that exists |
| 53 | + firstExistingPath = p |
| 54 | + } |
| 55 | + if info.IsDir() && info.Mode().Perm()&(1<<(uint(7))) != 0 { |
| 56 | + // return first path that is writeable |
| 57 | + return p |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // If none are writeable, return first location that exists |
| 62 | + if len(firstExistingPath) > 0 { |
| 63 | + return firstExistingPath |
| 64 | + } |
| 65 | + |
| 66 | + // If none exist, return first location that is set |
| 67 | + if len(firstSetPath) > 0 { |
| 68 | + return firstSetPath |
| 69 | + } |
| 70 | + |
| 71 | + // We've got nothing |
| 72 | + return "" |
| 73 | + } |
| 74 | + return os.Getenv("HOME") |
| 75 | +} |
0 commit comments