github.com/euank/go@v0.0.0-20160829210321-495514729181/src/path/filepath/symlink_windows.go (about)

     1  // Copyright 2012 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 filepath
     6  
     7  import (
     8  	"strings"
     9  	"syscall"
    10  )
    11  
    12  // normVolumeName is like VolumeName, but makes drive letter upper case.
    13  // result of EvalSymlinks must be unique, so we have
    14  // EvalSymlinks(`c:\a`) == EvalSymlinks(`C:\a`).
    15  func normVolumeName(path string) string {
    16  	volume := VolumeName(path)
    17  
    18  	if len(volume) > 2 { // isUNC
    19  		return volume
    20  	}
    21  
    22  	return strings.ToUpper(volume)
    23  }
    24  
    25  // normBase retruns the last element of path.
    26  func normBase(path string) (string, error) {
    27  	p, err := syscall.UTF16PtrFromString(path)
    28  	if err != nil {
    29  		return "", err
    30  	}
    31  
    32  	var data syscall.Win32finddata
    33  
    34  	h, err := syscall.FindFirstFile(p, &data)
    35  	if err != nil {
    36  		return "", err
    37  	}
    38  	syscall.FindClose(h)
    39  
    40  	return syscall.UTF16ToString(data.FileName[:]), nil
    41  }
    42  
    43  func toNorm(path string, base func(string) (string, error)) (string, error) {
    44  	if path == "" {
    45  		return path, nil
    46  	}
    47  
    48  	path = Clean(path)
    49  
    50  	volume := normVolumeName(path)
    51  	path = path[len(volume):]
    52  
    53  	// skip special cases
    54  	if path == "." || path == `\` {
    55  		return volume + path, nil
    56  	}
    57  
    58  	var normPath string
    59  
    60  	for {
    61  		name, err := base(volume + path)
    62  		if err != nil {
    63  			return "", err
    64  		}
    65  
    66  		normPath = name + `\` + normPath
    67  
    68  		i := strings.LastIndexByte(path, Separator)
    69  		if i == -1 {
    70  			break
    71  		}
    72  		if i == 0 { // `\Go` or `C:\Go`
    73  			normPath = `\` + normPath
    74  
    75  			break
    76  		}
    77  
    78  		path = path[:i]
    79  	}
    80  
    81  	normPath = normPath[:len(normPath)-1] // remove trailing '\'
    82  
    83  	return volume + normPath, nil
    84  }
    85  
    86  func evalSymlinks(path string) (string, error) {
    87  	path, err := walkSymlinks(path)
    88  	if err != nil {
    89  		return "", err
    90  	}
    91  	return toNorm(path, normBase)
    92  }