12 var removeArchives *bool
14 func processPath(curPath string) error {
15 info, err := os.Stat(curPath)
17 return fmt.Errorf("Unable to stat %s: %s", curPath, err.Error())
20 entries, err := os.ReadDir(curPath)
22 return fmt.Errorf("Unable to call readdir on %s: %s", curPath, err.Error())
24 for i := range(entries) {
25 err := processPath(filepath.Join(curPath, entries[i].Name()))
31 extractedBaseName, err := extractIfPossible(curPath)
35 if extractedBaseName != "" {
36 err = processPath(filepath.Join(filepath.Dir(curPath), extractedBaseName))
41 err = os.Remove(curPath)
43 return fmt.Errorf("Unable to remove archive file %s: %s", curPath, err.Error())
45 fmt.Printf("== rm %s\n", curPath)
52 func extractIfPossible(curPath string) (string, error) {
53 if strings.HasSuffix(curPath, ".tgz") {
54 return extractTgz(curPath)
55 } else if strings.HasSuffix(curPath, ".7z") {
56 return extract7z(curPath)
61 func extractTgz(curPath string) (string, error) {
62 fmt.Printf("== decompressing tar file %s\n", curPath)
63 cmd := exec.Command("tar", "xvf", filepath.Base(curPath))
64 cmd.Dir = filepath.Dir(curPath)
65 //cmd.Stdout = os.Stdout
68 return "", fmt.Errorf("error running tar xvf on %s: %s", curPath, err.Error())
70 return filepath.Base(curPath[:len(curPath) - len(".tgz")]), nil
73 func extract7z(curPath string) (string, error) {
74 fmt.Printf("== decompressing 7z file %s\n", curPath)
75 extractedBaseName := curPath[:len(curPath) - len(".7z")]
76 err := os.Mkdir(extractedBaseName, 0755)
78 return "", fmt.Errorf("unable to mkdir '%s': %s", extractedBaseName, err.Error())
80 absCurPath, err := filepath.Abs(curPath)
82 return "", fmt.Errorf("unable to get absolute path for '%s': %s", curPath, err.Error())
84 absExtractedBaseName, err := filepath.Abs(extractedBaseName)
86 return "", fmt.Errorf("unable to get absolute path for '%s': %s", extractedBaseName, err.Error())
88 cmd := exec.Command("7z", "x", absCurPath)
89 cmd.Dir = absExtractedBaseName
90 cmd.Stdout = os.Stdout
93 return "", fmt.Errorf("error running 7z on %s: %s", curPath, err.Error())
95 return extractedBaseName, nil
99 removeArchives = flag.Bool("r", false, "Remove archive files after decompressing them")
100 flag.Usage = func() {
101 fmt.Printf("recursive_decompress: recursively decompresses a path.\n")
102 fmt.Printf("usage: recursive_decompress [flags] [paths...]\n")
108 if flag.Arg(0) != "" {
109 curPath = flag.Arg(0)
111 err := processPath(curPath)
113 fmt.Printf("error: %s\n", err.Error())