util.go 1.2 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 http://mozilla.org/MPL/2.0/.
  6. package versioner
  7. import (
  8. "path/filepath"
  9. "regexp"
  10. "sort"
  11. )
  12. // Inserts ~tag just before the extension of the filename.
  13. func taggedFilename(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 filenameTag(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 uniqueSortedStrings(strings []string) []string {
  30. seen := make(map[string]struct{}, len(strings))
  31. unique := make([]string, 0, len(strings))
  32. for _, str := range strings {
  33. _, ok := seen[str]
  34. if !ok {
  35. seen[str] = struct{}{}
  36. unique = append(unique, str)
  37. }
  38. }
  39. sort.Strings(unique)
  40. return unique
  41. }