2020-04-06 22:09:45 +02:00
|
|
|
package fs
|
|
|
|
|
|
|
|
import (
|
2020-05-18 15:45:55 +02:00
|
|
|
"fmt"
|
|
|
|
"os"
|
2020-04-06 22:09:45 +02:00
|
|
|
"path/filepath"
|
2020-05-08 12:01:22 +02:00
|
|
|
"strconv"
|
2020-04-06 22:09:45 +02:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Base returns the filename base without any extensions and path.
|
2020-04-14 14:28:47 +02:00
|
|
|
func Base(fileName string, stripSequence bool) string {
|
2020-04-06 22:09:45 +02:00
|
|
|
basename := filepath.Base(fileName)
|
|
|
|
|
2020-05-08 12:01:22 +02:00
|
|
|
// strip file type extension
|
|
|
|
if end := strings.LastIndex(basename, "."); end != -1 {
|
2020-04-06 22:09:45 +02:00
|
|
|
basename = basename[:end]
|
|
|
|
}
|
|
|
|
|
2020-04-14 14:28:47 +02:00
|
|
|
if !stripSequence {
|
|
|
|
return basename
|
|
|
|
}
|
|
|
|
|
2020-05-08 12:01:22 +02:00
|
|
|
// strip numeric extensions like .0000, .0001, .4542353245,....
|
2020-05-18 15:45:55 +02:00
|
|
|
if dot := strings.LastIndex(basename, "."); dot != -1 && len(basename[dot+1:]) >= 5 {
|
2020-05-08 12:01:22 +02:00
|
|
|
if i, err := strconv.Atoi(basename[dot+1:]); err == nil && i >= 0 {
|
|
|
|
basename = basename[:dot]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// other common sequential naming schemes
|
2020-04-06 22:09:45 +02:00
|
|
|
if end := strings.Index(basename, " ("); end != -1 {
|
|
|
|
// copies created by Chrome & Windows, example: IMG_1234 (2)
|
|
|
|
basename = basename[:end]
|
|
|
|
} else if end := strings.Index(basename, " copy"); end != -1 {
|
|
|
|
// copies created by OS X, example: IMG_1234 copy 2
|
|
|
|
basename = basename[:end]
|
|
|
|
}
|
|
|
|
|
|
|
|
return basename
|
|
|
|
}
|
|
|
|
|
|
|
|
// AbsBase returns the directory and base filename without any extensions.
|
2020-04-14 14:28:47 +02:00
|
|
|
func AbsBase(fileName string, stripSequence bool) string {
|
|
|
|
return filepath.Join(filepath.Dir(fileName), Base(fileName, stripSequence))
|
2020-04-06 22:09:45 +02:00
|
|
|
}
|
2020-05-18 15:45:55 +02:00
|
|
|
|
|
|
|
// SubFileName returns the a filename with the same base name and a given extension in a sub directory.
|
|
|
|
func SubFileName(fileName, subDir, fileExt string, stripSequence bool) string {
|
|
|
|
baseName := Base(fileName, stripSequence)
|
|
|
|
dirName := filepath.Join(filepath.Dir(fileName), subDir)
|
|
|
|
|
|
|
|
if err := os.MkdirAll(dirName, os.ModePerm); err != nil {
|
|
|
|
fmt.Println(err.Error())
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
result := filepath.Join(dirName, baseName) + fileExt
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|