Skip to content

Instantly share code, notes, and snippets.

@demdxx
Created April 23, 2014 06:04
Show Gist options
  • Save demdxx/11204233 to your computer and use it in GitHub Desktop.
Save demdxx/11204233 to your computer and use it in GitHub Desktop.
/**
* Prepare android resource files
*
* @copyright Dmitry Ponomarev <[email protected]> 2014
*
* Files: <src_dir>/file_name_<dpi_dir>.<ext> => <dst_dit>/<dpi_dir>file_name.<ext>
*/
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var resourceDirs = []string{
"ldpi", "hdpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi",
}
func main() {
var sourceDir, destDir string
// Prepare source and destination directories
if len(os.Args) > 2 {
sourceDir, destDir = os.Args[1], os.Args[2]
} else if len(os.Args) > 1 {
sourceDir = os.Args[1]
} else {
sourceDir, destDir = ".", "."
}
// Absolute source path
var err error
sourceDir, err = filepath.Abs(sourceDir)
if nil != err {
fmt.Println(err)
return
}
// Absolute destination path
if len(destDir) < 1 {
destDir = sourceDir
} else {
destDir, err = filepath.Abs(destDir)
if nil != err {
fmt.Println(err)
return
}
}
fmt.Println(sourceDir, destDir)
// Process files from source dir
files, _ := ioutil.ReadDir(sourceDir)
for _, f := range files {
if f.IsDir() {
continue
}
dir, fileName := prepareFileName(f.Name())
if len(dir) > 3 {
err := copy(destDir+"/"+dir+"/"+fileName, sourceDir+"/"+f.Name())
if nil != err {
fmt.Println(err)
}
}
}
}
func isResourceDir(ext string) bool {
for _, b := range resourceDirs {
if b == ext {
return true
}
}
return false
}
func prepareFileName(fileName string) (dir, fName string) {
ext := filepath.Ext(fileName)
if len(ext) > 1 {
paths := strings.Split(fileName[:len(fileName)-len(ext)], "_")
for _, path := range paths {
if isResourceDir(path) {
dir = path
} else {
if len(fName) > 0 {
fName += "_"
}
fName += path
}
}
fName += ext
}
return
}
func copy(dst, src string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
err = os.MkdirAll(filepath.Dir(dst), 0755)
if nil != err {
return err
}
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
cerr := out.Close()
if err != nil {
return err
}
return cerr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment