github.com/richardwilkes/toolbox@v1.121.0/xio/fs/split.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package fs 11 12 import ( 13 "path/filepath" 14 ) 15 16 // Split a path into its component parts. In the case of a full path, the first element will be filepath.Separator, 17 // possibly prefixed by a volume name. In the case of a relative path, the first element will be ".". 18 func Split(path string) []string { 19 var parts []string 20 path = filepath.Clean(path) 21 parts = append(parts, filepath.Base(path)) 22 sep := string(filepath.Separator) 23 volName := filepath.VolumeName(path) 24 path = path[len(volName):] 25 for { 26 path = filepath.Dir(path) 27 parts = append(parts, filepath.Base(path)) 28 if path == "." || path == sep { 29 break 30 } 31 } 32 result := make([]string, len(parts)) 33 for i := 0; i < len(parts); i++ { 34 result[len(parts)-(i+1)] = parts[i] 35 } 36 if volName != "" && result[0] == sep { 37 result[0] = volName + sep 38 } 39 return result 40 }