loader.go 21 KB

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