loader.go 20 KB

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