>> add truncate flag

This commit is contained in:
Thomas Lindop 2025-05-27 23:45:09 +01:00
parent 00f8ca515f
commit f871153f29

33
main.go
View file

@ -25,6 +25,7 @@ import (
"os" "os"
fpath "path/filepath" fpath "path/filepath"
"slices" "slices"
"strconv"
"strings" "strings"
) )
@ -48,6 +49,7 @@ type context struct {
DoHelp bool DoHelp bool
DoVersion bool DoVersion bool
Rset runeset Rset runeset
TruncLen int
} }
@ -189,6 +191,22 @@ func (ctx *context) restrictRuneset(s string) string {
return result return result
} }
/**
* Truncate to the number of bytes given by the context, but don't break in
* the middle of a rune.
*/
func (ctx *context) truncate(name string) string {
if ctx.TruncLen < 1 {
return name
}
for byteIndex, _ := range name {
if byteIndex > ctx.TruncLen {
return name[:byteIndex]
}
}
return name
}
func warn(msg string) { func warn(msg string) {
fmt.Fprintf(os.Stderr, "\x1b[33m%s\x1b[0m\n", msg) fmt.Fprintf(os.Stderr, "\x1b[33m%s\x1b[0m\n", msg)
} }
@ -211,6 +229,7 @@ func parseCLIArgs(args []string) (context, error) {
DoHelp: false, DoHelp: false,
DoVersion: false, DoVersion: false,
Rset: FAT_RUNESET, Rset: FAT_RUNESET,
TruncLen: 0,
} }
index := 1 index := 1
isFlag := func(arg string) bool { isFlag := func(arg string) bool {
@ -228,6 +247,16 @@ func parseCLIArgs(args []string) (context, error) {
result.Strategy = args[index] result.Strategy = args[index]
case "-p", "--portable": case "-p", "--portable":
result.Rset = POSIX_PORTABLE_RUNESET result.Rset = POSIX_PORTABLE_RUNESET
case "-t", "--truncate":
index++
var err error
result.TruncLen, err = strconv.Atoi(args[index])
if err != nil || result.TruncLen < 1 {
return result, errors.New(fmt.Sprintf(
"Invalid truncation length: <<%s>>",
args[index],
))
}
case "-h", "--help": case "-h", "--help":
result.DoHelp = true result.DoHelp = true
case "-v", "--version": case "-v", "--version":
@ -292,9 +321,9 @@ func main() {
// Calculate the new name // Calculate the new name
oldName := fpath.Base(file) oldName := fpath.Base(file)
dirName := fpath.Dir(file) dirName := fpath.Dir(file)
newName := ctx.restrictRuneset( newName := ctx.truncate(ctx.restrictRuneset(
strings.ToValidUTF8(oldName, "_INVALID_"), strings.ToValidUTF8(oldName, "_INVALID_"),
) ))
newPath := fpath.Join(dirName, newName) newPath := fpath.Join(dirName, newName)
// Check that we want to rename this file // Check that we want to rename this file
if newPath == file { if newPath == file {