github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/getmodules/subdir.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package getmodules 5 6 import ( 7 "path" 8 9 getter "github.com/hashicorp/go-getter" 10 ) 11 12 // SplitPackageSubdir detects whether the given address string has a 13 // subdirectory portion, and if so returns a non-empty subDir string 14 // along with the trimmed package address. 15 // 16 // If the given string doesn't have a subdirectory portion then it'll 17 // just be returned verbatim in packageAddr, with an empty subDir value. 18 // 19 // Although the rest of this package is focused only on direct remote 20 // module packages, this particular function and its companion 21 // ExpandSubdirGlobs are both also relevant for registry-based module 22 // addresses, because a registry translates such an address into a 23 // remote module package address and thus can contribute its own 24 // additions to the final subdirectory selection. 25 func SplitPackageSubdir(given string) (packageAddr, subDir string) { 26 // We delegate this mostly to go-getter, because older Terraform 27 // versions just used go-getter directly and so we need to preserve 28 // its various quirks for compatibility reasons. 29 // 30 // However, note that in Terraform we _always_ split off the subdirectory 31 // portion and handle it within Terraform-level code, _never_ passing 32 // a subdirectory portion down into go-getter's own Get function, because 33 // Terraform's ability to refer between local paths inside the same 34 // package depends on Terraform itself always being aware of where the 35 // package's root directory ended up on disk, and always needs the 36 // package installed wholesale. 37 packageAddr, subDir = getter.SourceDirSubdir(given) 38 if subDir != "" { 39 subDir = path.Clean(subDir) 40 } 41 return packageAddr, subDir 42 } 43 44 // ExpandSubdirGlobs handles a subdir string that might contain glob syntax, 45 // turning it into a concrete subdirectory path by referring to the actual 46 // files on disk in the given directory which we assume contains the content 47 // of whichever package this is a subdirectory glob for. 48 // 49 // Subdir globs are used, for example, when a module registry wants to specify 50 // to select the contents of the single directory at the root of a conventional 51 // tar archive but it doesn't actually know the exact name of that directory. 52 // In that case it might specify a subdir of just "*", which this function 53 // will then expand into the single subdirectory found inside instDir, or 54 // return an error if the result would be ambiguous. 55 func ExpandSubdirGlobs(instDir string, subDir string) (string, error) { 56 // We just delegate this entirely to go-getter, because older Terraform 57 // versions just used go-getter directly and so we need to preserve 58 // its various quirks for compatibility reasons. 59 return getter.SubdirGlob(instDir, subDir) 60 }