Skip to content

Instantly share code, notes, and snippets.

@parkghost
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parkghost/11278457 to your computer and use it in GitHub Desktop.
Save parkghost/11278457 to your computer and use it in GitHub Desktop.
urldecode filenames
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/mgutz/ansi"
)
func main() {
perform := flag.Bool("p", false, "perform the rename manipuations")
force := flag.Bool("f", false, "overwrite existing files and create non-existent directories")
showAll := flag.Bool("a", false, "show all files")
flag.Usage = func() {
fmt.Println("This utility helps to batch rename files from urlencoded to normal at current directory")
fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
fis, err := ioutil.ReadDir(".")
checkErr(err)
for _, fi := range fis {
if fi.IsDir() {
continue
}
// convert filename to normal
origName := fi.Name()
escapedName, err := url.QueryUnescape(origName)
checkErr(err)
if escapedName == origName {
if *showAll {
fmt.Printf("[%s]%s => %s\n", ansi.Color("ignored", "gray+b"), origName, escapedName)
}
} else {
if *perform { // check conditions and perform the rename manipuations
performOp(origName, escapedName, *force)
} else { // dryrun only without perform the reanme manipuations
fmt.Printf("[%s]%s => %s\n", ansi.Color("to be converted", "yellow+b"), origName, escapedName)
}
}
}
}
func checkErr(err error) {
if err != nil {
log.Fatal(ansi.Color(err.Error(), "red+b"))
}
}
func performOp(orig string, target string, force bool) {
existed := fileExist(target)
// check if target file is existed
if existed {
if !force {
fmt.Printf("[%s]%s => %s\n", ansi.Color("skipped", "cyan+b"), orig, target)
return
}
}
// check if target file contains non-existent directories
hasDir := strings.ContainsRune(target, os.PathSeparator)
if hasDir {
baseDir := filepath.Dir(target)
if !fileExist(baseDir) {
if !force {
fmt.Printf("[%s]%s => %s\n", ansi.Color("skipped", "cyan+b"), orig, target)
return
}
err := os.MkdirAll(baseDir, 0766)
checkErr(err)
}
}
performRename(orig, target)
}
func fileExist(name string) bool {
_, err := os.Stat(name)
return err == nil
}
func performRename(orig string, target string) {
fmt.Printf("[%s]%s => %s\n", ansi.Color("renamed", "green+b"), orig, target)
err := os.Rename(orig, target)
checkErr(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment