1
0

util.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package versioner
  7. import (
  8. "path/filepath"
  9. "regexp"
  10. "strings"
  11. )
  12. // Inserts ~tag just before the extension of the filename.
  13. func TagFilename(name, tag string) string {
  14. dir, file := filepath.Dir(name), filepath.Base(name)
  15. ext := filepath.Ext(file)
  16. withoutExt := file[:len(file)-len(ext)]
  17. return filepath.Join(dir, withoutExt+"~"+tag+ext)
  18. }
  19. var tagExp = regexp.MustCompile(`.*~([^~.]+)(?:\.[^.]+)?$`)
  20. // Returns the tag from a filename, whether at the end or middle.
  21. func ExtractTag(path string) string {
  22. match := tagExp.FindStringSubmatch(path)
  23. // match is []string{"whole match", "submatch"} when successful
  24. if len(match) != 2 {
  25. return ""
  26. }
  27. return match[1]
  28. }
  29. func UntagFilename(path string) (string, string) {
  30. ext := filepath.Ext(path)
  31. versionTag := ExtractTag(path)
  32. // Files tagged with old style tags cannot be untagged.
  33. if versionTag == "" || strings.HasSuffix(ext, versionTag) {
  34. return "", ""
  35. }
  36. withoutExt := path[:len(path)-len(ext)-len(versionTag)-1]
  37. name := withoutExt + ext
  38. return name, versionTag
  39. }