longpath.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Package longpath introduces some constants and helper functions for handling
  2. // long paths in Windows.
  3. //
  4. // Long paths are expected to be prepended with "\\?\" and followed by either a
  5. // drive letter, a UNC server\share, or a volume identifier.
  6. package longpath // import "github.com/docker/docker/pkg/longpath"
  7. import (
  8. "os"
  9. "runtime"
  10. "strings"
  11. )
  12. // Prefix is the longpath prefix for Windows file paths.
  13. const Prefix = `\\?\`
  14. // AddPrefix adds the Windows long path prefix to the path provided if
  15. // it does not already have it.
  16. func AddPrefix(path string) string {
  17. if !strings.HasPrefix(path, Prefix) {
  18. if strings.HasPrefix(path, `\\`) {
  19. // This is a UNC path, so we need to add 'UNC' to the path as well.
  20. path = Prefix + `UNC` + path[1:]
  21. } else {
  22. path = Prefix + path
  23. }
  24. }
  25. return path
  26. }
  27. // MkdirTemp is the equivalent of [os.MkdirTemp], except that on Windows
  28. // the result is in Windows longpath format. On Unix systems it is
  29. // equivalent to [os.MkdirTemp].
  30. func MkdirTemp(dir, prefix string) (string, error) {
  31. tempDir, err := os.MkdirTemp(dir, prefix)
  32. if err != nil {
  33. return "", err
  34. }
  35. if runtime.GOOS != "windows" {
  36. return tempDir, nil
  37. }
  38. return AddPrefix(tempDir), nil
  39. }