Skip to content

Instantly share code, notes, and snippets.

@dustin
Created July 19, 2013 05:49
Show Gist options
  • Select an option

  • Save dustin/6036931 to your computer and use it in GitHub Desktop.

Select an option

Save dustin/6036931 to your computer and use it in GitHub Desktop.
I literally wrote this passing out. Seems to work. I've got a bunch of files in the format of something/yyyy-mm-dd-... and I want to make somethingelse/{yyyy}.tar files out of them. This does it.
package main
import (
"archive/tar"
"flag"
"io"
"log"
"os"
"path/filepath"
)
func maybefatal(err error) {
if err != nil {
log.Fatalf("%v", err)
}
}
func addFile(w *tar.Writer, filename string) {
f, err := os.Open(filename)
maybefatal(err)
defer f.Close()
fileSize, err := f.Seek(0, 2)
maybefatal(err)
_, err = f.Seek(0, 0)
maybefatal(err)
w.WriteHeader(&tar.Header{
Name: filename,
Mode: 0666,
Size: fileSize,
})
_, err = io.Copy(w, f)
maybefatal(err)
}
func process(base string, tarfiles, fns []string) error {
log.Printf("Processing %v files", len(fns))
prefixes := map[string]*tar.Writer{}
for _, n := range tarfiles {
b := filepath.Base(n)[:4]
f, err := os.Create(n)
maybefatal(err)
defer f.Close()
w := tar.NewWriter(f)
defer w.Close()
prefixes[b] = w
}
log.Printf("Tarfiles: %v", prefixes)
for _, n := range fns {
w := prefixes[n[:4]]
if w == nil {
log.Printf("Skipping %v", n)
continue
}
log.Printf("Doing %v", n)
addFile(w, filepath.Join(base, n))
}
return nil
}
func main() {
flag.Parse()
d, err := os.Open(flag.Arg(0))
maybefatal(err)
names, err := d.Readdirnames(0)
maybefatal(err)
process(flag.Arg(0), flag.Args()[1:], names)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment