util.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package versioner
  16. import (
  17. "path/filepath"
  18. "regexp"
  19. "sort"
  20. )
  21. // Inserts ~tag just before the extension of the filename.
  22. func taggedFilename(name, tag string) string {
  23. dir, file := filepath.Dir(name), filepath.Base(name)
  24. ext := filepath.Ext(file)
  25. withoutExt := file[:len(file)-len(ext)]
  26. return filepath.Join(dir, withoutExt+"~"+tag+ext)
  27. }
  28. var tagExp = regexp.MustCompile(`.*~([^~.]+)(?:\.[^.]+)?$`)
  29. // Returns the tag from a filename, whether at the end or middle.
  30. func filenameTag(path string) string {
  31. match := tagExp.FindStringSubmatch(path)
  32. // match is []string{"whole match", "submatch"} when successfull
  33. if len(match) != 2 {
  34. return ""
  35. }
  36. return match[1]
  37. }
  38. func uniqueSortedStrings(strings []string) []string {
  39. seen := make(map[string]struct{}, len(strings))
  40. unique := make([]string, 0, len(strings))
  41. for _, str := range strings {
  42. _, ok := seen[str]
  43. if !ok {
  44. seen[str] = struct{}{}
  45. unique = append(unique, str)
  46. }
  47. }
  48. sort.Strings(unique)
  49. return unique
  50. }