edge/pkg/bundle/from_path.go

71 lines
1.4 KiB
Go
Raw Normal View History

2023-02-09 12:16:36 +01:00
package bundle
import (
"fmt"
"os"
"path/filepath"
"github.com/pkg/errors"
)
type ArchiveExt string
const (
ExtZip ArchiveExt = "zip"
ExtTarGz ArchiveExt = "tar.gz"
2023-07-11 02:42:05 +02:00
ExtZim ArchiveExt = "zim"
2023-02-09 12:16:36 +01:00
)
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
}
2023-07-11 02:42:05 +02:00
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
}
2023-02-09 12:16:36 +01:00
return nil, errors.WithStack(ErrUnknownBundleArchiveExt)
}