loader.go 20 KB

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