Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add MatchingFormat function to archiver package and refactor main.go to use it. #45

Merged
merged 1 commit into from
Oct 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions archiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ func RegisterFormat(name string, format Archiver) {
SupportedFormats[name] = format
}

// MatchingFormat returns the first archive format that matches
// the given file, or nil if there is no match
func MatchingFormat(fpath string) Archiver {
for _, fmt := range SupportedFormats {
if fmt.Match(fpath) {
return fmt
}
}
return nil
}

func writeNewFile(fpath string, in io.Reader, fm os.FileMode) error {
err := os.MkdirAll(filepath.Dir(fpath), 0755)
if err != nil {
Expand Down
47 changes: 22 additions & 25 deletions cmd/archiver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,32 @@ func main() {

cmd, filename := os.Args[1], os.Args[2]

for _, ff := range archiver.SupportedFormats {
if !ff.Match(filename) {
continue
}
var err error
switch cmd {
case "make":
if len(os.Args) < 4 {
fatal(usage)
}
err = ff.Make(filename, os.Args[3:])
case "open":
dest := ""
if len(os.Args) == 4 {
dest = os.Args[3]
} else if len(os.Args) > 4 {
fatal(usage)
}
err = ff.Open(filename, dest)
default:
ff := archiver.MatchingFormat(filename)
if ff == nil {
fatalf("%s: Unsupported file extension", filename)
}

var err error
switch cmd {
case "make":
if len(os.Args) < 4 {
fatal(usage)
}
if err != nil {
fatal(err)
err = ff.Make(filename, os.Args[3:])
case "open":
dest := ""
if len(os.Args) == 4 {
dest = os.Args[3]
} else if len(os.Args) > 4 {
fatal(usage)
}
return
err = ff.Open(filename, dest)
default:
fatal(usage)
}
if err != nil {
fatal(err)
}

fatalf("%s: Unsupported file extension", filename)
}

func fatal(v ...interface{}) {
Expand Down