loader.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package clientcmd
  14. import (
  15. "fmt"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. goruntime "runtime"
  20. "strings"
  21. "k8s.io/klog/v2"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apimachinery/pkg/runtime/schema"
  24. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  25. restclient "k8s.io/client-go/rest"
  26. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  27. clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest"
  28. "k8s.io/client-go/util/homedir"
  29. )
  30. const (
  31. RecommendedConfigPathFlag = "kubeconfig"
  32. RecommendedConfigPathEnvVar = "KUBECONFIG"
  33. RecommendedHomeDir = ".kube"
  34. RecommendedFileName = "config"
  35. RecommendedSchemaName = "schema"
  36. )
  37. var (
  38. RecommendedConfigDir = filepath.Join(homedir.HomeDir(), RecommendedHomeDir)
  39. RecommendedHomeFile = filepath.Join(RecommendedConfigDir, RecommendedFileName)
  40. RecommendedSchemaFile = filepath.Join(RecommendedConfigDir, RecommendedSchemaName)
  41. )
  42. // currentMigrationRules returns a map that holds the history of recommended home directories used in previous versions.
  43. // Any future changes to RecommendedHomeFile and related are expected to add a migration rule here, in order to make
  44. // sure existing config files are migrated to their new locations properly.
  45. func currentMigrationRules() map[string]string {
  46. var oldRecommendedHomeFileName string
  47. if goruntime.GOOS == "windows" {
  48. oldRecommendedHomeFileName = RecommendedFileName
  49. } else {
  50. oldRecommendedHomeFileName = ".kubeconfig"
  51. }
  52. return map[string]string{
  53. RecommendedHomeFile: filepath.Join(os.Getenv("HOME"), RecommendedHomeDir, oldRecommendedHomeFileName),
  54. }
  55. }
  56. type ClientConfigLoader interface {
  57. ConfigAccess
  58. // IsDefaultConfig returns true if the returned config matches the defaults.
  59. IsDefaultConfig(*restclient.Config) bool
  60. // Load returns the latest config
  61. Load() (*clientcmdapi.Config, error)
  62. }
  63. type KubeconfigGetter func() (*clientcmdapi.Config, error)
  64. type ClientConfigGetter struct {
  65. kubeconfigGetter KubeconfigGetter
  66. }
  67. // ClientConfigGetter implements the ClientConfigLoader interface.
  68. var _ ClientConfigLoader = &ClientConfigGetter{}
  69. func (g *ClientConfigGetter) Load() (*clientcmdapi.Config, error) {
  70. return g.kubeconfigGetter()
  71. }
  72. func (g *ClientConfigGetter) GetLoadingPrecedence() []string {
  73. return nil
  74. }
  75. func (g *ClientConfigGetter) GetStartingConfig() (*clientcmdapi.Config, error) {
  76. return g.kubeconfigGetter()
  77. }
  78. func (g *ClientConfigGetter) GetDefaultFilename() string {
  79. return ""
  80. }
  81. func (g *ClientConfigGetter) IsExplicitFile() bool {
  82. return false
  83. }
  84. func (g *ClientConfigGetter) GetExplicitFile() string {
  85. return ""
  86. }
  87. func (g *ClientConfigGetter) IsDefaultConfig(config *restclient.Config) bool {
  88. return false
  89. }
  90. // ClientConfigLoadingRules is an ExplicitPath and string slice of specific locations that are used for merging together a Config
  91. // Callers can put the chain together however they want, but we'd recommend:
  92. // EnvVarPathFiles if set (a list of files if set) OR the HomeDirectoryPath
  93. // ExplicitPath is special, because if a user specifically requests a certain file be used and error is reported if this file is not present
  94. type ClientConfigLoadingRules struct {
  95. ExplicitPath string
  96. Precedence []string
  97. // MigrationRules is a map of destination files to source files. If a destination file is not present, then the source file is checked.
  98. // If the source file is present, then it is copied to the destination file BEFORE any further loading happens.
  99. MigrationRules map[string]string
  100. // DoNotResolvePaths indicates whether or not to resolve paths with respect to the originating files. This is phrased as a negative so
  101. // that a default object that doesn't set this will usually get the behavior it wants.
  102. DoNotResolvePaths bool
  103. // DefaultClientConfig is an optional field indicating what rules to use to calculate a default configuration.
  104. // This should match the overrides passed in to ClientConfig loader.
  105. DefaultClientConfig ClientConfig
  106. // WarnIfAllMissing indicates whether the configuration files pointed by KUBECONFIG environment variable are present or not.
  107. // In case of missing files, it warns the user about the missing files.
  108. WarnIfAllMissing bool
  109. // Warner is the warning log callback to use in case of missing files.
  110. Warner WarningHandler
  111. }
  112. // WarningHandler allows to set the logging function to use
  113. type WarningHandler func(error)
  114. func (handler WarningHandler) Warn(err error) {
  115. if handler == nil {
  116. klog.V(1).Info(err)
  117. } else {
  118. handler(err)
  119. }
  120. }
  121. type MissingConfigError struct {
  122. Missing []string
  123. }
  124. func (c MissingConfigError) Error() string {
  125. return fmt.Sprintf("Config not found: %s", strings.Join(c.Missing, ", "))
  126. }
  127. // ClientConfigLoadingRules implements the ClientConfigLoader interface.
  128. var _ ClientConfigLoader = &ClientConfigLoadingRules{}
  129. // NewDefaultClientConfigLoadingRules returns a ClientConfigLoadingRules object with default fields filled in. You are not required to
  130. // use this constructor
  131. func NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules {
  132. chain := []string{}
  133. warnIfAllMissing := false
  134. envVarFiles := os.Getenv(RecommendedConfigPathEnvVar)
  135. if len(envVarFiles) != 0 {
  136. fileList := filepath.SplitList(envVarFiles)
  137. // prevent the same path load multiple times
  138. chain = append(chain, deduplicate(fileList)...)
  139. warnIfAllMissing = true
  140. } else {
  141. chain = append(chain, RecommendedHomeFile)
  142. }
  143. return &ClientConfigLoadingRules{
  144. Precedence: chain,
  145. MigrationRules: currentMigrationRules(),
  146. WarnIfAllMissing: warnIfAllMissing,
  147. }
  148. }
  149. // Load starts by running the MigrationRules and then
  150. // takes the loading rules and returns a Config object based on following rules.
  151. //
  152. // if the ExplicitPath, return the unmerged explicit file
  153. // Otherwise, return a merged config based on the Precedence slice
  154. //
  155. // A missing ExplicitPath file produces an error. Empty filenames or other missing files are ignored.
  156. // Read errors or files with non-deserializable content produce errors.
  157. // The first file to set a particular map key wins and map key's value is never changed.
  158. // BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed.
  159. // This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two.
  160. // It also means that if two files specify a "red-user", only values from the first file's red-user are used. Even
  161. // non-conflicting entries from the second file's "red-user" are discarded.
  162. // Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder
  163. // and only absolute file paths are returned.
  164. func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) {
  165. if err := rules.Migrate(); err != nil {
  166. return nil, err
  167. }
  168. errlist := []error{}
  169. missingList := []string{}
  170. kubeConfigFiles := []string{}
  171. // Make sure a file we were explicitly told to use exists
  172. if len(rules.ExplicitPath) > 0 {
  173. if _, err := os.Stat(rules.ExplicitPath); os.IsNotExist(err) {
  174. return nil, err
  175. }
  176. kubeConfigFiles = append(kubeConfigFiles, rules.ExplicitPath)
  177. } else {
  178. kubeConfigFiles = append(kubeConfigFiles, rules.Precedence...)
  179. }
  180. kubeconfigs := []*clientcmdapi.Config{}
  181. // read and cache the config files so that we only look at them once
  182. for _, filename := range kubeConfigFiles {
  183. if len(filename) == 0 {
  184. // no work to do
  185. continue
  186. }
  187. config, err := LoadFromFile(filename)
  188. if os.IsNotExist(err) {
  189. // skip missing files
  190. // Add to the missing list to produce a warning
  191. missingList = append(missingList, filename)
  192. continue
  193. }
  194. if err != nil {
  195. errlist = append(errlist, fmt.Errorf("error loading config file \"%s\": %v", filename, err))
  196. continue
  197. }
  198. kubeconfigs = append(kubeconfigs, config)
  199. }
  200. if rules.WarnIfAllMissing && len(missingList) > 0 && len(kubeconfigs) == 0 {
  201. rules.Warner.Warn(MissingConfigError{Missing: missingList})
  202. }
  203. // first merge all of our maps
  204. mapConfig := clientcmdapi.NewConfig()
  205. for _, kubeconfig := range kubeconfigs {
  206. if err := merge(mapConfig, kubeconfig); err != nil {
  207. return nil, err
  208. }
  209. }
  210. // merge all of the struct values in the reverse order so that priority is given correctly
  211. // errors are not added to the list the second time
  212. nonMapConfig := clientcmdapi.NewConfig()
  213. for i := len(kubeconfigs) - 1; i >= 0; i-- {
  214. kubeconfig := kubeconfigs[i]
  215. if err := merge(nonMapConfig, kubeconfig); err != nil {
  216. return nil, err
  217. }
  218. }
  219. // since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and
  220. // get the values we expect.
  221. config := clientcmdapi.NewConfig()
  222. if err := merge(config, mapConfig); err != nil {
  223. return nil, err
  224. }
  225. if err := merge(config, nonMapConfig); err != nil {
  226. return nil, err
  227. }
  228. if rules.ResolvePaths() {
  229. if err := ResolveLocalPaths(config); err != nil {
  230. errlist = append(errlist, err)
  231. }
  232. }
  233. return config, utilerrors.NewAggregate(errlist)
  234. }
  235. // Migrate uses the MigrationRules map. If a destination file is not present, then the source file is checked.
  236. // If the source file is present, then it is copied to the destination file BEFORE any further loading happens.
  237. func (rules *ClientConfigLoadingRules) Migrate() error {
  238. if rules.MigrationRules == nil {
  239. return nil
  240. }
  241. for destination, source := range rules.MigrationRules {
  242. if _, err := os.Stat(destination); err == nil {
  243. // if the destination already exists, do nothing
  244. continue
  245. } else if os.IsPermission(err) {
  246. // if we can't access the file, skip it
  247. continue
  248. } else if !os.IsNotExist(err) {
  249. // if we had an error other than non-existence, fail
  250. return err
  251. }
  252. if sourceInfo, err := os.Stat(source); err != nil {
  253. if os.IsNotExist(err) || os.IsPermission(err) {
  254. // if the source file doesn't exist or we can't access it, there's no work to do.
  255. continue
  256. }
  257. // if we had an error other than non-existence, fail
  258. return err
  259. } else if sourceInfo.IsDir() {
  260. return fmt.Errorf("cannot migrate %v to %v because it is a directory", source, destination)
  261. }
  262. data, err := os.ReadFile(source)
  263. if err != nil {
  264. return err
  265. }
  266. // destination is created with mode 0666 before umask
  267. err = os.WriteFile(destination, data, 0666)
  268. if err != nil {
  269. return err
  270. }
  271. }
  272. return nil
  273. }
  274. // GetLoadingPrecedence implements ConfigAccess
  275. func (rules *ClientConfigLoadingRules) GetLoadingPrecedence() []string {
  276. if len(rules.ExplicitPath) > 0 {
  277. return []string{rules.ExplicitPath}
  278. }
  279. // Create a copy in case something tries to sort the returned slice.
  280. precedence := make([]string, len(rules.Precedence))
  281. copy(precedence, rules.Precedence)
  282. return precedence
  283. }
  284. // GetStartingConfig implements ConfigAccess
  285. func (rules *ClientConfigLoadingRules) GetStartingConfig() (*clientcmdapi.Config, error) {
  286. clientConfig := NewNonInteractiveDeferredLoadingClientConfig(rules, &ConfigOverrides{})
  287. rawConfig, err := clientConfig.RawConfig()
  288. if os.IsNotExist(err) {
  289. return clientcmdapi.NewConfig(), nil
  290. }
  291. if err != nil {
  292. return nil, err
  293. }
  294. return &rawConfig, nil
  295. }
  296. // GetDefaultFilename implements ConfigAccess
  297. func (rules *ClientConfigLoadingRules) GetDefaultFilename() string {
  298. // Explicit file if we have one.
  299. if rules.IsExplicitFile() {
  300. return rules.GetExplicitFile()
  301. }
  302. // Otherwise, first existing file from precedence.
  303. for _, filename := range rules.GetLoadingPrecedence() {
  304. if _, err := os.Stat(filename); err == nil {
  305. return filename
  306. }
  307. }
  308. // If none exists, use the first from precedence.
  309. if len(rules.Precedence) > 0 {
  310. return rules.Precedence[0]
  311. }
  312. return ""
  313. }
  314. // IsExplicitFile implements ConfigAccess
  315. func (rules *ClientConfigLoadingRules) IsExplicitFile() bool {
  316. return len(rules.ExplicitPath) > 0
  317. }
  318. // GetExplicitFile implements ConfigAccess
  319. func (rules *ClientConfigLoadingRules) GetExplicitFile() string {
  320. return rules.ExplicitPath
  321. }
  322. // IsDefaultConfig returns true if the provided configuration matches the default
  323. func (rules *ClientConfigLoadingRules) IsDefaultConfig(config *restclient.Config) bool {
  324. if rules.DefaultClientConfig == nil {
  325. return false
  326. }
  327. defaultConfig, err := rules.DefaultClientConfig.ClientConfig()
  328. if err != nil {
  329. return false
  330. }
  331. return reflect.DeepEqual(config, defaultConfig)
  332. }
  333. // LoadFromFile takes a filename and deserializes the contents into Config object
  334. func LoadFromFile(filename string) (*clientcmdapi.Config, error) {
  335. kubeconfigBytes, err := os.ReadFile(filename)
  336. if err != nil {
  337. return nil, err
  338. }
  339. config, err := Load(kubeconfigBytes)
  340. if err != nil {
  341. return nil, err
  342. }
  343. klog.V(6).Infoln("Config loaded from file: ", filename)
  344. // set LocationOfOrigin on every Cluster, User, and Context
  345. for key, obj := range config.AuthInfos {
  346. obj.LocationOfOrigin = filename
  347. config.AuthInfos[key] = obj
  348. }
  349. for key, obj := range config.Clusters {
  350. obj.LocationOfOrigin = filename
  351. config.Clusters[key] = obj
  352. }
  353. for key, obj := range config.Contexts {
  354. obj.LocationOfOrigin = filename
  355. config.Contexts[key] = obj
  356. }
  357. if config.AuthInfos == nil {
  358. config.AuthInfos = map[string]*clientcmdapi.AuthInfo{}
  359. }
  360. if config.Clusters == nil {
  361. config.Clusters = map[string]*clientcmdapi.Cluster{}
  362. }
  363. if config.Contexts == nil {
  364. config.Contexts = map[string]*clientcmdapi.Context{}
  365. }
  366. return config, nil
  367. }
  368. // Load takes a byte slice and deserializes the contents into Config object.
  369. // Encapsulates deserialization without assuming the source is a file.
  370. func Load(data []byte) (*clientcmdapi.Config, error) {
  371. config := clientcmdapi.NewConfig()
  372. // if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input)
  373. if len(data) == 0 {
  374. return config, nil
  375. }
  376. decoded, _, err := clientcmdlatest.Codec.Decode(data, &schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: "Config"}, config)
  377. if err != nil {
  378. return nil, err
  379. }
  380. return decoded.(*clientcmdapi.Config), nil
  381. }
  382. // WriteToFile serializes the config to yaml and writes it out to a file. If not present, it creates the file with the mode 0600. If it is present
  383. // it stomps the contents
  384. func WriteToFile(config clientcmdapi.Config, filename string) error {
  385. content, err := Write(config)
  386. if err != nil {
  387. return err
  388. }
  389. dir := filepath.Dir(filename)
  390. if _, err := os.Stat(dir); os.IsNotExist(err) {
  391. if err = os.MkdirAll(dir, 0755); err != nil {
  392. return err
  393. }
  394. }
  395. if err := os.WriteFile(filename, content, 0600); err != nil {
  396. return err
  397. }
  398. return nil
  399. }
  400. func lockFile(filename string) error {
  401. // TODO: find a way to do this with actual file locks. Will
  402. // probably need separate solution for windows and Linux.
  403. // Make sure the dir exists before we try to create a lock file.
  404. dir := filepath.Dir(filename)
  405. if _, err := os.Stat(dir); os.IsNotExist(err) {
  406. if err = os.MkdirAll(dir, 0755); err != nil {
  407. return err
  408. }
  409. }
  410. f, err := os.OpenFile(lockName(filename), os.O_CREATE|os.O_EXCL, 0)
  411. if err != nil {
  412. return err
  413. }
  414. f.Close()
  415. return nil
  416. }
  417. func unlockFile(filename string) error {
  418. return os.Remove(lockName(filename))
  419. }
  420. func lockName(filename string) string {
  421. return filename + ".lock"
  422. }
  423. // Write serializes the config to yaml.
  424. // Encapsulates serialization without assuming the destination is a file.
  425. func Write(config clientcmdapi.Config) ([]byte, error) {
  426. return runtime.Encode(clientcmdlatest.Codec, &config)
  427. }
  428. func (rules ClientConfigLoadingRules) ResolvePaths() bool {
  429. return !rules.DoNotResolvePaths
  430. }
  431. // ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin
  432. // this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without
  433. // modification of its contents.
  434. func ResolveLocalPaths(config *clientcmdapi.Config) error {
  435. for _, cluster := range config.Clusters {
  436. if len(cluster.LocationOfOrigin) == 0 {
  437. continue
  438. }
  439. base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))
  440. if err != nil {
  441. return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err)
  442. }
  443. if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {
  444. return err
  445. }
  446. }
  447. for _, authInfo := range config.AuthInfos {
  448. if len(authInfo.LocationOfOrigin) == 0 {
  449. continue
  450. }
  451. base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))
  452. if err != nil {
  453. return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err)
  454. }
  455. if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {
  456. return err
  457. }
  458. }
  459. return nil
  460. }
  461. // RelativizeClusterLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already
  462. // absolute, but any existing path will be resolved relative to LocationOfOrigin
  463. func RelativizeClusterLocalPaths(cluster *clientcmdapi.Cluster) error {
  464. if len(cluster.LocationOfOrigin) == 0 {
  465. return fmt.Errorf("no location of origin for %s", cluster.Server)
  466. }
  467. base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))
  468. if err != nil {
  469. return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err)
  470. }
  471. if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {
  472. return err
  473. }
  474. if err := RelativizePathWithNoBacksteps(GetClusterFileReferences(cluster), base); err != nil {
  475. return err
  476. }
  477. return nil
  478. }
  479. // RelativizeAuthInfoLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already
  480. // absolute, but any existing path will be resolved relative to LocationOfOrigin
  481. func RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error {
  482. if len(authInfo.LocationOfOrigin) == 0 {
  483. return fmt.Errorf("no location of origin for %v", authInfo)
  484. }
  485. base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))
  486. if err != nil {
  487. return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err)
  488. }
  489. if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {
  490. return err
  491. }
  492. if err := RelativizePathWithNoBacksteps(GetAuthInfoFileReferences(authInfo), base); err != nil {
  493. return err
  494. }
  495. return nil
  496. }
  497. func RelativizeConfigPaths(config *clientcmdapi.Config, base string) error {
  498. return RelativizePathWithNoBacksteps(GetConfigFileReferences(config), base)
  499. }
  500. func ResolveConfigPaths(config *clientcmdapi.Config, base string) error {
  501. return ResolvePaths(GetConfigFileReferences(config), base)
  502. }
  503. func GetConfigFileReferences(config *clientcmdapi.Config) []*string {
  504. refs := []*string{}
  505. for _, cluster := range config.Clusters {
  506. refs = append(refs, GetClusterFileReferences(cluster)...)
  507. }
  508. for _, authInfo := range config.AuthInfos {
  509. refs = append(refs, GetAuthInfoFileReferences(authInfo)...)
  510. }
  511. return refs
  512. }
  513. func GetClusterFileReferences(cluster *clientcmdapi.Cluster) []*string {
  514. return []*string{&cluster.CertificateAuthority}
  515. }
  516. func GetAuthInfoFileReferences(authInfo *clientcmdapi.AuthInfo) []*string {
  517. s := []*string{&authInfo.ClientCertificate, &authInfo.ClientKey, &authInfo.TokenFile}
  518. // Only resolve exec command if it isn't PATH based.
  519. if authInfo.Exec != nil && strings.ContainsRune(authInfo.Exec.Command, filepath.Separator) {
  520. s = append(s, &authInfo.Exec.Command)
  521. }
  522. return s
  523. }
  524. // ResolvePaths updates the given refs to be absolute paths, relative to the given base directory
  525. func ResolvePaths(refs []*string, base string) error {
  526. for _, ref := range refs {
  527. // Don't resolve empty paths
  528. if len(*ref) > 0 {
  529. // Don't resolve absolute paths
  530. if !filepath.IsAbs(*ref) {
  531. *ref = filepath.Join(base, *ref)
  532. }
  533. }
  534. }
  535. return nil
  536. }
  537. // RelativizePathWithNoBacksteps updates the given refs to be relative paths, relative to the given base directory as long as they do not require backsteps.
  538. // Any path requiring a backstep is left as-is as long it is absolute. Any non-absolute path that can't be relativized produces an error
  539. func RelativizePathWithNoBacksteps(refs []*string, base string) error {
  540. for _, ref := range refs {
  541. // Don't relativize empty paths
  542. if len(*ref) > 0 {
  543. rel, err := MakeRelative(*ref, base)
  544. if err != nil {
  545. return err
  546. }
  547. // if we have a backstep, don't mess with the path
  548. if strings.HasPrefix(rel, "../") {
  549. if filepath.IsAbs(*ref) {
  550. continue
  551. }
  552. return fmt.Errorf("%v requires backsteps and is not absolute", *ref)
  553. }
  554. *ref = rel
  555. }
  556. }
  557. return nil
  558. }
  559. func MakeRelative(path, base string) (string, error) {
  560. if len(path) > 0 {
  561. rel, err := filepath.Rel(base, path)
  562. if err != nil {
  563. return path, err
  564. }
  565. return rel, nil
  566. }
  567. return path, nil
  568. }
  569. // deduplicate removes any duplicated values and returns a new slice, keeping the order unchanged
  570. func deduplicate(s []string) []string {
  571. encountered := map[string]bool{}
  572. ret := make([]string, 0)
  573. for i := range s {
  574. if encountered[s[i]] {
  575. continue
  576. }
  577. encountered[s[i]] = true
  578. ret = append(ret, s[i])
  579. }
  580. return ret
  581. }