Files
syncthing/lib/fs/tempname.go
T

60 lines
1.6 KiB
Go
Raw Normal View History

2015-05-10 11:56:20 +02:00
// Copyright (C) 2015 The Syncthing Authors.
2014-09-29 21:43:32 +02:00
//
2015-03-07 21:36:35 +01: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,
// You can obtain one at https://mozilla.org/MPL/2.0/.
2014-06-01 22:50:14 +02:00
2017-09-02 05:52:38 +00:00
package fs
import (
"fmt"
"path/filepath"
"strings"
2021-03-17 22:22:49 +01:00
"github.com/syncthing/syncthing/lib/build"
2021-03-17 22:22:49 +01:00
"github.com/syncthing/syncthing/lib/sha256"
)
const (
WindowsTempPrefix = "~syncthing~"
UnixTempPrefix = ".syncthing."
)
func tempPrefix() string {
if build.IsWindows {
return WindowsTempPrefix
} else {
return UnixTempPrefix
}
}
2015-05-10 11:56:20 +02: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.
const maxFilenameLength = 160 - len(UnixTempPrefix) - len(".tmp")
// 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.
func IsTemporary(name string) bool {
name = filepath.Base(name)
return strings.HasPrefix(name, WindowsTempPrefix) ||
strings.HasPrefix(name, UnixTempPrefix)
}
func TempNameWithPrefix(name, prefix string) string {
tdir := filepath.Dir(name)
2015-05-10 11:56:20 +02:00
tbase := filepath.Base(name)
var tname string
if len(tbase) > maxFilenameLength {
tname = fmt.Sprintf("%s%x.tmp", prefix, sha256.Sum256([]byte(tbase)))
} else {
tname = prefix + tbase + ".tmp"
2015-05-10 11:56:20 +02:00
}
return filepath.Join(tdir, tname)
}
func TempName(name string) string {
return TempNameWithPrefix(name, tempPrefix())
}