loader.go 20 KB

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