2015-05-10 02:56:20 -07:00
|
|
|
// Copyright (C) 2015 The Syncthing Authors.
|
2014-09-29 12:43:32 -07:00
|
|
|
//
|
2015-03-07 13:36:35 -07:00
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2017-02-08 23:52:18 -07:00
|
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
2014-06-01 13:50:14 -07:00
|
|
|
|
2017-09-01 22:52:38 -07:00
|
|
|
package fs
|
2014-03-08 15:02:01 -07:00
|
|
|
|
|
|
|
import (
|
2015-05-09 12:37:09 -07:00
|
|
|
"crypto/md5"
|
2014-03-08 15:02:01 -07:00
|
|
|
"fmt"
|
|
|
|
"path/filepath"
|
2015-05-10 02:56:20 -07:00
|
|
|
"runtime"
|
2014-03-08 15:02:01 -07:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2016-11-30 14:23:24 -07:00
|
|
|
const (
|
2017-01-17 00:33:48 -07:00
|
|
|
WindowsTempPrefix = "~syncthing~"
|
|
|
|
UnixTempPrefix = ".syncthing."
|
2016-11-30 14:23:24 -07:00
|
|
|
)
|
|
|
|
|
2017-01-17 00:33:48 -07:00
|
|
|
var TempPrefix string
|
2015-05-10 02:56:20 -07:00
|
|
|
|
2016-06-27 04:47:40 -07:00
|
|
|
// Real filesystems usually handle 255 bytes. encfs has varying and
|
|
|
|
// confusing file name limits. We take a safe way out and switch to hashing
|
|
|
|
// quite early.
|
2017-01-17 00:33:48 -07:00
|
|
|
const maxFilenameLength = 160 - len(UnixTempPrefix) - len(".tmp")
|
2016-06-27 04:47:40 -07:00
|
|
|
|
2015-05-10 02:56:20 -07:00
|
|
|
func init() {
|
|
|
|
if runtime.GOOS == "windows" {
|
2017-01-17 00:33:48 -07:00
|
|
|
TempPrefix = WindowsTempPrefix
|
2015-05-10 02:56:20 -07:00
|
|
|
} else {
|
2017-01-17 00:33:48 -07:00
|
|
|
TempPrefix = UnixTempPrefix
|
2015-05-10 02:56:20 -07:00
|
|
|
}
|
|
|
|
}
|
2014-03-08 15:02:01 -07:00
|
|
|
|
2016-11-30 14:23:24 -07:00
|
|
|
// IsTemporary is true if the file name has the temporary prefix. Regardless
|
|
|
|
// of the normally used prefix, the standard Windows and Unix temp prefixes
|
|
|
|
// are always recognized as temp files.
|
2017-01-17 00:33:48 -07:00
|
|
|
func IsTemporary(name string) bool {
|
2016-11-30 14:23:24 -07:00
|
|
|
name = filepath.Base(name)
|
2017-01-17 00:33:48 -07:00
|
|
|
if strings.HasPrefix(name, WindowsTempPrefix) ||
|
|
|
|
strings.HasPrefix(name, UnixTempPrefix) {
|
|
|
|
return true
|
2016-11-30 14:23:24 -07:00
|
|
|
}
|
|
|
|
return false
|
2014-03-08 15:02:01 -07:00
|
|
|
}
|
|
|
|
|
2017-01-17 00:33:48 -07:00
|
|
|
func TempName(name string) string {
|
2014-03-28 06:36:57 -07:00
|
|
|
tdir := filepath.Dir(name)
|
2015-05-10 02:56:20 -07:00
|
|
|
tbase := filepath.Base(name)
|
2016-06-27 04:47:40 -07:00
|
|
|
if len(tbase) > maxFilenameLength {
|
2015-05-10 02:56:20 -07:00
|
|
|
hash := md5.New()
|
|
|
|
hash.Write([]byte(name))
|
|
|
|
tbase = fmt.Sprintf("%x", hash.Sum(nil))
|
|
|
|
}
|
2017-01-17 00:33:48 -07:00
|
|
|
tname := fmt.Sprintf("%s%s.tmp", TempPrefix, tbase)
|
2014-03-28 06:36:57 -07:00
|
|
|
return filepath.Join(tdir, tname)
|
2014-03-08 15:02:01 -07:00
|
|
|
}
|