mirror of
https://github.com/rclone/rclone
synced 2024-11-30 09:10:05 +01:00
c163e6b250
Standardizes the filename version tagging so that it can be used by any backend.
53 lines
1.5 KiB
Go
53 lines
1.5 KiB
Go
// Package version provides machinery for versioning file names
|
|
// with a timestamp-based version string
|
|
package version
|
|
|
|
import (
|
|
"path"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const versionFormat = "-v2006-01-02-150405.000"
|
|
|
|
var versionRegexp = regexp.MustCompile("-v\\d{4}-\\d{2}-\\d{2}-\\d{6}-\\d{3}")
|
|
|
|
// Add returns fileName modified to include t as the version
|
|
func Add(fileName string, t time.Time) string {
|
|
ext := path.Ext(fileName)
|
|
base := fileName[:len(fileName)-len(ext)]
|
|
s := t.Format(versionFormat)
|
|
// Replace the '.' with a '-'
|
|
s = strings.Replace(s, ".", "-", -1)
|
|
return base + s + ext
|
|
}
|
|
|
|
// Remove returns a modified fileName without the version string and the time it represented
|
|
// If the fileName did not have a version then time.Time{} is returned along with an unmodified fileName
|
|
func Remove(fileName string) (t time.Time, fileNameWithoutVersion string) {
|
|
fileNameWithoutVersion = fileName
|
|
ext := path.Ext(fileName)
|
|
base := fileName[:len(fileName)-len(ext)]
|
|
if len(base) < len(versionFormat) {
|
|
return
|
|
}
|
|
versionStart := len(base) - len(versionFormat)
|
|
// Check it ends in -xxx
|
|
if base[len(base)-4] != '-' {
|
|
return
|
|
}
|
|
// Replace with .xxx for parsing
|
|
base = base[:len(base)-4] + "." + base[len(base)-3:]
|
|
newT, err := time.Parse(versionFormat, base[versionStart:])
|
|
if err != nil {
|
|
return
|
|
}
|
|
return newT, base[:versionStart] + ext
|
|
}
|
|
|
|
// Match returns true if the fileName has a version string
|
|
func Match(fileName string) bool {
|
|
return versionRegexp.MatchString(fileName)
|
|
}
|