edge/pkg/bundle/from_path.go

71 lines
1.4 KiB
Go

package bundle
import (
"fmt"
"os"
"path/filepath"
"github.com/pkg/errors"
)
type ArchiveExt string
const (
ExtZip ArchiveExt = "zip"
ExtTarGz ArchiveExt = "tar.gz"
ExtZim ArchiveExt = "zim"
)
func FromPath(path string) (Bundle, error) {
stat, err := os.Stat(path)
if err != nil {
return nil, errors.Wrapf(err, "could not stat file '%s'", path)
}
var b Bundle
if stat.IsDir() {
b = NewDirectoryBundle(path)
} else {
b, err = matchArchivePattern(path)
if err != nil {
return nil, errors.WithStack(err)
}
}
return b, nil
}
func matchArchivePattern(archivePath string) (Bundle, error) {
base := filepath.Base(archivePath)
matches, err := filepath.Match(fmt.Sprintf("*.%s", ExtTarGz), base)
if err != nil {
return nil, errors.Wrapf(err, "could not match file archive '%s'", archivePath)
}
if matches {
return NewTarBundle(archivePath), nil
}
matches, err = filepath.Match(fmt.Sprintf("*.%s", ExtZip), base)
if err != nil {
return nil, errors.Wrapf(err, "could not match file archive '%s'", archivePath)
}
if matches {
return NewZipBundle(archivePath), nil
}
matches, err = filepath.Match(fmt.Sprintf("*.%s", ExtZim), base)
if err != nil {
return nil, errors.Wrapf(err, "could not match file archive '%s'", archivePath)
}
if matches {
return NewZimBundle(archivePath), nil
}
return nil, errors.WithStack(ErrUnknownBundleArchiveExt)
}