2020-05-03 14:40:59 +02:00
|
|
|
package fs
|
|
|
|
|
|
|
|
import (
|
2020-06-07 10:09:35 +02:00
|
|
|
"fmt"
|
2020-05-03 14:40:59 +02:00
|
|
|
"os"
|
2020-06-07 10:09:35 +02:00
|
|
|
"path/filepath"
|
2020-05-03 14:40:59 +02:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2020-06-07 10:09:35 +02:00
|
|
|
// FileName returns the a relative filename with the same base and a given extension in a directory.
|
2020-12-12 13:05:58 +01:00
|
|
|
func FileName(fileName, dirName, baseDir, fileExt string) string {
|
2020-06-07 10:09:35 +02:00
|
|
|
fileDir := filepath.Dir(fileName)
|
|
|
|
|
|
|
|
if dirName == "" || dirName == "." {
|
|
|
|
dirName = fileDir
|
|
|
|
} else if fileDir != dirName {
|
|
|
|
if filepath.IsAbs(dirName) {
|
2020-07-14 11:00:49 +02:00
|
|
|
dirName = filepath.Join(dirName, RelName(fileDir, baseDir))
|
2020-06-07 10:09:35 +02:00
|
|
|
} else {
|
|
|
|
dirName = filepath.Join(fileDir, dirName)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.MkdirAll(dirName, os.ModePerm); err != nil {
|
|
|
|
fmt.Println(err.Error())
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2020-12-12 13:05:58 +01:00
|
|
|
result := filepath.Join(dirName, filepath.Base(fileName)) + fileExt
|
2020-06-07 10:09:35 +02:00
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2020-07-14 11:00:49 +02:00
|
|
|
// RelName returns the file name relative to a directory.
|
|
|
|
func RelName(fileName, dir string) string {
|
2020-05-31 14:42:41 +02:00
|
|
|
if fileName == dir {
|
2020-05-22 19:05:16 +02:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2020-06-07 10:09:35 +02:00
|
|
|
if dir == "" {
|
|
|
|
return fileName
|
|
|
|
}
|
|
|
|
|
2020-05-31 14:42:41 +02:00
|
|
|
if index := strings.Index(fileName, dir); index == 0 {
|
|
|
|
if index := strings.LastIndex(dir, string(os.PathSeparator)); index == len(dir)-1 {
|
|
|
|
pos := len(dir)
|
2020-05-03 14:40:59 +02:00
|
|
|
return fileName[pos:]
|
2020-05-31 14:42:41 +02:00
|
|
|
} else if index := strings.LastIndex(dir, string(os.PathSeparator)); index != len(dir) {
|
|
|
|
pos := len(dir) + 1
|
2020-05-03 14:40:59 +02:00
|
|
|
return fileName[pos:]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return fileName
|
|
|
|
}
|