tempname.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. }
  17. var defTempNamer tempNamer
  18. // Real filesystems usually handle 255 bytes. encfs has varying and
  19. // confusing file name limits. We take a safe way out and switch to hashing
  20. // quite early.
  21. const maxFilenameLength = 160 - len(".syncthing.") - len(".tmp")
  22. func init() {
  23. if runtime.GOOS == "windows" {
  24. defTempNamer = tempNamer{"~syncthing~"}
  25. } else {
  26. defTempNamer = tempNamer{".syncthing."}
  27. }
  28. }
  29. func (t tempNamer) IsTemporary(name string) bool {
  30. return strings.HasPrefix(filepath.Base(name), t.prefix)
  31. }
  32. func (t tempNamer) TempName(name string) string {
  33. tdir := filepath.Dir(name)
  34. tbase := filepath.Base(name)
  35. if len(tbase) > maxFilenameLength {
  36. hash := md5.New()
  37. hash.Write([]byte(name))
  38. tbase = fmt.Sprintf("%x", hash.Sum(nil))
  39. }
  40. tname := fmt.Sprintf("%s%s.tmp", t.prefix, tbase)
  41. return filepath.Join(tdir, tname)
  42. }