File: rename.go

package info (click to toggle)
golang-github-theckman-yacspin 0.13.12-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 252 kB
  • sloc: sh: 8; makefile: 3
file content (62 lines) | stat: -rw-r--r-- 1,211 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
)

func main() {
	var sim bool
	var glob string

	flag.BoolVar(&sim, "sim", false, "simulate")
	flag.StringVar(&glob, "glob", "", "glob to use for matching files, must end in *.gif")
	flag.Parse()

	if !strings.HasSuffix(glob, "*.gif") {
		fmt.Fprintln(os.Stderr, "-glob flag required and must end in *.gif")
		os.Exit(int(syscall.EINVAL))
	}

	m, err := filepath.Glob(glob)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to glob %s: %v\n", glob, err)
		os.Exit(1)
	}

	if len(m) == 0 {
		fmt.Fprintf(os.Stderr, "no files matched glob %s\n", glob)
		os.Exit(1)
	}

	idx := strings.Index(glob, "*")

	for _, match := range m {
		num := strings.TrimSuffix(match[idx:], ".gif")

		ni, err := strconv.Atoi(num)
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to convert number in %s to integer: %v\n", match, err)
			os.Exit(1)
		}

		ni--

		newName := fmt.Sprintf("%d.gif", ni)

		if sim {
			fmt.Printf("would rename %s to %s\n", match, newName)
			continue
		}

		if err := os.Rename(match, newName); err != nil {
			fmt.Fprintf(os.Stderr, "failed to rename %s to %s\n", match, newName)
			os.Exit(1)
		}
	}
}