tempname.go 1.7 KB

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