github.com/gernest/nezuko@v0.1.2/internal/load/path.go (about)

     1  // Copyright 2017 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 load
     6  
     7  import (
     8  	"path/filepath"
     9  	"strings"
    10  )
    11  
    12  // hasSubdir reports whether dir is a subdirectory of
    13  // (possibly multiple levels below) root.
    14  // If so, it sets rel to the path fragment that must be
    15  // appended to root to reach dir.
    16  func hasSubdir(root, dir string) (rel string, ok bool) {
    17  	if p, err := filepath.EvalSymlinks(root); err == nil {
    18  		root = p
    19  	}
    20  	if p, err := filepath.EvalSymlinks(dir); err == nil {
    21  		dir = p
    22  	}
    23  	const sep = string(filepath.Separator)
    24  	root = filepath.Clean(root)
    25  	if !strings.HasSuffix(root, sep) {
    26  		root += sep
    27  	}
    28  	dir = filepath.Clean(dir)
    29  	if !strings.HasPrefix(dir, root) {
    30  		return "", false
    31  	}
    32  	return filepath.ToSlash(dir[len(root):]), true
    33  }
    34  
    35  // expandPath returns the symlink-expanded form of path.
    36  func expandPath(p string) string {
    37  	x, err := filepath.EvalSymlinks(p)
    38  	if err == nil {
    39  		return x
    40  	}
    41  	return p
    42  }