package main import ( "fmt" "os" "path/filepath" "strings" ) func usage() { fmt.Println("Usage: go run go-zip.go ") } func main() { if len(os.Args) < 2 || len(os.Args) > 3 { usage() os.Exit(1) } dir := strings.TrimSuffix(os.Args[1], string(filepath.Separator)) base := filepath.Base(dir) // ../foo/whatever => ../foo/ trim := strings.TrimSuffix(dir, base) // ./ => error // ../../ => error if "" == base || "." == base || ".." == base { // TODO also don't allow ../self fmt.Println("Error: Cannot zip the directory containing the output file") os.Exit(1) } f, err := os.OpenFile(base+".zip", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) if nil != err { panic(err) } defer f.Close() // ./whatever => whatever.zip // ./path/to/whatever => whatever.zip if err := Zip(f, dir, trim); nil != err { panic(err) } fmt.Println("wrote", base+".zip") }