github.com/safing/portbase@v0.19.5/updater/filename.go (about) 1 package updater 2 3 import ( 4 "path" 5 "regexp" 6 "strings" 7 ) 8 9 var ( 10 fileVersionRegex = regexp.MustCompile(`_v[0-9]+-[0-9]+-[0-9]+(-[a-z]+)?`) 11 rawVersionRegex = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+(-[a-z]+)?$`) 12 ) 13 14 // GetIdentifierAndVersion splits the given file path into its identifier and version. 15 func GetIdentifierAndVersion(versionedPath string) (identifier, version string, ok bool) { 16 dirPath, filename := path.Split(versionedPath) 17 18 // Extract version from filename. 19 rawVersion := fileVersionRegex.FindString(filename) 20 if rawVersion == "" { 21 // No version present in file, making it invalid. 22 return "", "", false 23 } 24 25 // Trim the `_v` that gets caught by the regex and 26 // replace `-` with `.` to get the version string. 27 version = strings.Replace(strings.TrimLeft(rawVersion, "_v"), "-", ".", 2) 28 29 // Put the filename back together without version. 30 i := strings.Index(filename, rawVersion) 31 if i < 0 { 32 // extracted version not in string (impossible) 33 return "", "", false 34 } 35 filename = filename[:i] + filename[i+len(rawVersion):] 36 37 // Put the full path back together and return it. 38 // `dirPath + filename` is guaranteed by path.Split() 39 return dirPath + filename, version, true 40 } 41 42 // GetVersionedPath combines the identifier and version and returns it as a file path. 43 func GetVersionedPath(identifier, version string) (versionedPath string) { 44 identifierPath, filename := path.Split(identifier) 45 46 // Split the filename where the version should go. 47 splittedFilename := strings.SplitN(filename, ".", 2) 48 // Replace `.` with `-` for the filename format. 49 transformedVersion := strings.Replace(version, ".", "-", 2) 50 51 // Put everything back together and return it. 52 versionedPath = identifierPath + splittedFilename[0] + "_v" + transformedVersion 53 if len(splittedFilename) > 1 { 54 versionedPath += "." + splittedFilename[1] 55 } 56 return versionedPath 57 }