Debian Codegraph @

gopls/internal/cache/os_windows.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package cache
6
7 import (
8 "fmt"
9 "path/filepath"
10 "syscall"
11 )
12
13 func init() {
14 checkPathValid = windowsCheckPathValid
15 }
16
17 func windowsCheckPathValid(path string) error {
18 // Back in the day, Windows used to have short and long filenames, and
19 // it still supports those APIs. GetLongPathName gets the real case for a
20 // path, so we can use it here. Inspired by
21 // http://stackoverflow.com/q/2113822.
22
23 namep, err := syscall.UTF16PtrFromString(path)
24 if err != nil {
25 return err
26 }
27
28 // Short paths can be longer than long paths, and unicode, so be generous.
29 plenty := 4 * len(path)
30
31 short := make([]uint16, plenty)
32 n, err := syscall.GetShortPathName(namep, &short[0], uint32(len(short)))
33 if err != nil {
34 return err
35 }
36 if int(n) > len(short) {
37 return fmt.Errorf("short buffer too short: %v vs %v", n, len(short))
38 }
39
40 long := make([]uint16, plenty)
41 n, err = syscall.GetLongPathName(&short[0], &long[0], uint32(len(long)))
42 if err != nil {
43 return err
44 }
45 if int(n) > len(long) {
46 return fmt.Errorf("long buffer too short: %v vs %v", n, len(long))
47 }
48 longstr := syscall.UTF16ToString(long)
49
50 // Check that the path -> short -> long roundtrip was idempotent.
51 isRoot := func(p string) bool {
52 return p[len(p)-1] == filepath.Separator
53 }
54 for got, want := path, longstr; !isRoot(got) && !isRoot(want); got, want = filepath.Dir(got), filepath.Dir(want) {
55 if g, w := filepath.Base(got), filepath.Base(want); g != w {
56 return fmt.Errorf("invalid path %q: component %q is listed by Windows as %q", path, g, w)
57 }
58 }
59 return nil
60 }