src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

filepath.go (776B)


      1 // Copyright 2022 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 scan
      6 
      7 import (
      8 	"path/filepath"
      9 	"strings"
     10 )
     11 
     12 // AbsRelShorter takes path and returns its path relative
     13 // to the current directory, if shorter. Returns path
     14 // when path is an empty string or upon any error.
     15 func AbsRelShorter(path string) string {
     16 	if path == "" {
     17 		return ""
     18 	}
     19 
     20 	c, err := filepath.Abs(".")
     21 	if err != nil {
     22 		return path
     23 	}
     24 	r, err := filepath.Rel(c, path)
     25 	if err != nil {
     26 		return path
     27 	}
     28 
     29 	rSegments := strings.Split(r, string(filepath.Separator))
     30 	pathSegments := strings.Split(path, string(filepath.Separator))
     31 	if len(rSegments) < len(pathSegments) {
     32 		return r
     33 	}
     34 	return path
     35 }