tempname.go 977 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. func init() {
  19. if runtime.GOOS == "windows" {
  20. defTempNamer = tempNamer{"~syncthing~"}
  21. } else {
  22. defTempNamer = tempNamer{".syncthing."}
  23. }
  24. }
  25. func (t tempNamer) IsTemporary(name string) bool {
  26. return strings.HasPrefix(filepath.Base(name), t.prefix)
  27. }
  28. func (t tempNamer) TempName(name string) string {
  29. tdir := filepath.Dir(name)
  30. tbase := filepath.Base(name)
  31. if len(tbase) > 240 {
  32. hash := md5.New()
  33. hash.Write([]byte(name))
  34. tbase = fmt.Sprintf("%x", hash.Sum(nil))
  35. }
  36. tname := fmt.Sprintf("%s%s.tmp", t.prefix, tbase)
  37. return filepath.Join(tdir, tname)
  38. }