Last active
August 31, 2018 10:35
-
-
Save sathishvj/4ce86d811896f70ae7015c7e4fe3718d to your computer and use it in GitHub Desktop.
Flatten a directory - copy all files into one directory with directory named prefixed to files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
var pathSep = string(os.PathSeparator) | |
var nameSep *string | |
func main() { | |
fromDir := flag.String("s", "src", "from/source directory.") | |
toDir := flag.String("d", "dest", "to/destination directory.") | |
nameSep = flag.String("n", "-", "separator to use for filename. dir/dir/file->dir-dir-file.") | |
createDest := flag.Bool("f", true, "create dest dir if not exists.") | |
flag.Parse() | |
if !isDirExists(*fromDir) { | |
fmt.Println("From/Source dir does not exist:", *fromDir) | |
flag.Usage() | |
os.Exit(1) | |
} | |
if !isDirExists(*toDir) { | |
if !*createDest { | |
fmt.Println("To/Destination dir does not exist:", *toDir) | |
flag.Usage() | |
os.Exit(1) | |
} | |
err := os.MkdirAll(*toDir, 0755) | |
if err != nil { | |
fmt.Println("Error! Could not create destination directory:", err) | |
os.Exit(1) | |
} | |
} | |
fileList := make([]string, 0) | |
err := filepath.Walk(*fromDir, func(path string, f os.FileInfo, err error) error { | |
fileList = append(fileList, path) | |
return err | |
}) | |
if err != nil { | |
panic(err) | |
} | |
for _, file := range fileList { | |
fi, err := os.Stat(file) | |
if err != nil { | |
fmt.Println(err) | |
} | |
if fi.Mode().IsRegular() { | |
outPath := *toDir + pathSep + flattenFullPath(file, *fromDir) | |
err = copyFile(file, outPath) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
} | |
} | |
func flattenFullPath(fullPath, fromDir string) string { | |
s := strings.Replace(fullPath, fromDir, "", 1) | |
if strings.HasPrefix(s, pathSep) { | |
s = strings.Replace(s, pathSep, "", 1) | |
} | |
s = strings.Replace(s, pathSep, *nameSep, -1) | |
return s | |
} | |
func isDirExists(path string) bool { | |
if stat, err := os.Stat(path); err == nil && stat.IsDir() { | |
return true | |
} | |
return false | |
} | |
func copyFile(from string, to string) error { | |
fmt.Printf("From: %s, To: %s\n", from, to) | |
fromF, err := os.Open(from) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer fromF.Close() | |
toF, err := os.OpenFile(to, os.O_RDWR|os.O_CREATE, 0666) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer toF.Close() | |
_, err = io.Copy(toF, fromF) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment