tempname.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright (C) 2015 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 fs
  7. import (
  8. "crypto/md5"
  9. "fmt"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. )
  14. const (
  15. WindowsTempPrefix = "~syncthing~"
  16. UnixTempPrefix = ".syncthing."
  17. )
  18. var TempPrefix string
  19. // Real filesystems usually handle 255 bytes. encfs has varying and
  20. // confusing file name limits. We take a safe way out and switch to hashing
  21. // quite early.
  22. const maxFilenameLength = 160 - len(UnixTempPrefix) - len(".tmp")
  23. func init() {
  24. if runtime.GOOS == "windows" {
  25. TempPrefix = WindowsTempPrefix
  26. } else {
  27. TempPrefix = UnixTempPrefix
  28. }
  29. }
  30. // IsTemporary is true if the file name has the temporary prefix. Regardless
  31. // of the normally used prefix, the standard Windows and Unix temp prefixes
  32. // are always recognized as temp files.
  33. func IsTemporary(name string) bool {
  34. name = filepath.Base(name)
  35. if strings.HasPrefix(name, WindowsTempPrefix) ||
  36. strings.HasPrefix(name, UnixTempPrefix) {
  37. return true
  38. }
  39. return false
  40. }
  41. func TempNameWithPrefix(name, prefix string) string {
  42. tdir := filepath.Dir(name)
  43. tbase := filepath.Base(name)
  44. if len(tbase) > maxFilenameLength {
  45. hash := md5.New()
  46. hash.Write([]byte(name))
  47. tbase = fmt.Sprintf("%x", hash.Sum(nil))
  48. }
  49. tname := fmt.Sprintf("%s%s.tmp", prefix, tbase)
  50. return filepath.Join(tdir, tname)
  51. }
  52. func TempName(name string) string {
  53. return TempNameWithPrefix(name, TempPrefix)
  54. }