github.com/arvindram03/terraform@v0.3.7-0.20150212015210-408f838db36d/config/module/detect.go (about) 1 package module 2 3 import ( 4 "fmt" 5 "path/filepath" 6 ) 7 8 // Detector defines the interface that an invalid URL or a URL with a blank 9 // scheme is passed through in order to determine if its shorthand for 10 // something else well-known. 11 type Detector interface { 12 // Detect will detect whether the string matches a known pattern to 13 // turn it into a proper URL. 14 Detect(string, string) (string, bool, error) 15 } 16 17 // Detectors is the list of detectors that are tried on an invalid URL. 18 // This is also the order they're tried (index 0 is first). 19 var Detectors []Detector 20 21 func init() { 22 Detectors = []Detector{ 23 new(GitHubDetector), 24 new(BitBucketDetector), 25 new(FileDetector), 26 } 27 } 28 29 // Detect turns a source string into another source string if it is 30 // detected to be of a known pattern. 31 // 32 // This is safe to be called with an already valid source string: Detect 33 // will just return it. 34 func Detect(src string, pwd string) (string, error) { 35 getForce, getSrc := getForcedGetter(src) 36 37 // Separate out the subdir if there is one, we don't pass that to detect 38 getSrc, subDir := getDirSubdir(getSrc) 39 40 u, err := urlParse(getSrc) 41 if err == nil && u.Scheme != "" { 42 // Valid URL 43 return src, nil 44 } 45 46 for _, d := range Detectors { 47 result, ok, err := d.Detect(getSrc, pwd) 48 if err != nil { 49 return "", err 50 } 51 if !ok { 52 continue 53 } 54 55 var detectForce string 56 detectForce, result = getForcedGetter(result) 57 result, detectSubdir := getDirSubdir(result) 58 59 // If we have a subdir from the detection, then prepend it to our 60 // requested subdir. 61 if detectSubdir != "" { 62 if subDir != "" { 63 subDir = filepath.Join(detectSubdir, subDir) 64 } else { 65 subDir = detectSubdir 66 } 67 } 68 if subDir != "" { 69 u, err := urlParse(result) 70 if err != nil { 71 return "", fmt.Errorf("Error parsing URL: %s", err) 72 } 73 u.Path += "//" + subDir 74 result = u.String() 75 } 76 77 // Preserve the forced getter if it exists. We try to use the 78 // original set force first, followed by any force set by the 79 // detector. 80 if getForce != "" { 81 result = fmt.Sprintf("%s::%s", getForce, result) 82 } else if detectForce != "" { 83 result = fmt.Sprintf("%s::%s", detectForce, result) 84 } 85 86 return result, nil 87 } 88 89 return "", fmt.Errorf("invalid source string: %s", src) 90 }