Initial v1.0.0 commit

This commit is contained in:
Jakub Vavřík
2021-01-28 17:37:47 +01:00
commit 1481d27782
4164 changed files with 1264675 additions and 0 deletions

113
vendor/github.com/gobuffalo/packr/v2/jam/pack.go generated vendored Normal file
View File

@@ -0,0 +1,113 @@
package jam
import (
"context"
"encoding/json"
"io"
"os"
"os/exec"
"time"
"github.com/gobuffalo/packr/v2/jam/parser"
"github.com/gobuffalo/packr/v2/jam/store"
"github.com/gobuffalo/packr/v2/plog"
)
// PackOptions ...
type PackOptions struct {
IgnoreImports bool
Legacy bool
StoreCmd string
Roots []string
RootsOptions *parser.RootsOptions
}
// Pack the roots given + PWD
func Pack(opts PackOptions) error {
pwd, err := os.Getwd()
if err != nil {
return err
}
opts.Roots = append(opts.Roots, pwd)
if err := Clean(opts.Roots...); err != nil {
return err
}
if opts.RootsOptions == nil {
opts.RootsOptions = &parser.RootsOptions{}
}
if opts.IgnoreImports {
opts.RootsOptions.IgnoreImports = true
}
p, err := parser.NewFromRoots(opts.Roots, opts.RootsOptions)
if err != nil {
return err
}
boxes, err := p.Run()
if err != nil {
return err
}
// reduce boxes - remove ones we don't want
// MB: current assumption is we want all these
// boxes, just adding a comment suggesting they're
// might be a reason to exclude some
plog.Logger.Debugf("found %d boxes", len(boxes))
if len(opts.StoreCmd) != 0 {
return ShellPack(opts, boxes)
}
var st store.Store = store.NewDisk("", "")
if opts.Legacy {
st = store.NewLegacy()
}
for _, b := range boxes {
if b.Name == store.DISK_GLOBAL_KEY {
continue
}
if err := st.Pack(b); err != nil {
return err
}
}
if cl, ok := st.(io.Closer); ok {
return cl.Close()
}
return nil
}
// ShellPack ...
func ShellPack(opts PackOptions, boxes parser.Boxes) error {
b, err := json.Marshal(boxes)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
c := exec.CommandContext(ctx, opts.StoreCmd, string(b))
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return c.Run()
}
// Clean ...
func Clean(args ...string) error {
pwd, err := os.Getwd()
if err != nil {
return err
}
args = append(args, pwd)
for _, root := range args {
if err := store.Clean(root); err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,52 @@
package parser
import (
"encoding/json"
"fmt"
)
// FromArgs is useful when writing packr store-cmd binaries.
/*
package main
import (
"log"
"os"
"github.com/gobuffalo/packr/v2/jam/parser"
"github.com/markbates/s3packr/s3packr"
)
func main() {
err := parser.FromArgs(os.Args[1:], func(boxes parser.Boxes) error {
for _, box := range boxes {
s3 := s3packr.New(box)
if err := s3.Pack(box); err != nil {
return err
}
}
return nil
})
if err != nil {
log.Fatal(err)
}
}
*/
func FromArgs(args []string, fn func(Boxes) error) error {
if len(args) == 0 {
return fmt.Errorf("you must supply a payload")
}
payload := args[0]
if len(payload) == 0 {
return fmt.Errorf("you must supply a payload")
}
var boxes Boxes
err := json.Unmarshal([]byte(payload), &boxes)
if err != nil {
return err
}
return fn(boxes)
}

40
vendor/github.com/gobuffalo/packr/v2/jam/parser/box.go generated vendored Normal file
View File

@@ -0,0 +1,40 @@
package parser
import (
"encoding/json"
"os"
"strings"
)
// Box found while parsing a file
type Box struct {
Name string // name of the box
Path string // relative path of folder NewBox("./templates")
AbsPath string // absolute path of Path
Package string // the package name the box was found in
PWD string // the PWD when the parser was run
PackageDir string // the absolute path of the package where the box was found
}
type Boxes []*Box
// String - json returned
func (b Box) String() string {
x, _ := json.Marshal(b)
return string(x)
}
// NewBox stub from the name and the path provided
func NewBox(name string, path string) *Box {
if len(name) == 0 {
name = path
}
name = strings.Replace(name, "\"", "", -1)
pwd, _ := os.Getwd()
box := &Box{
Name: name,
Path: path,
PWD: pwd,
}
return box
}

View File

@@ -0,0 +1,54 @@
package parser
import (
"bytes"
"io"
"io/ioutil"
"path/filepath"
)
// File that is to be parsed
type File struct {
io.Reader
Path string
AbsPath string
}
// Name of the file "app.go"
func (f File) Name() string {
return f.Path
}
// String returns the contents of the reader
func (f *File) String() string {
src, _ := ioutil.ReadAll(f)
f.Reader = bytes.NewReader(src)
return string(src)
}
func (s *File) Write(p []byte) (int, error) {
bb := &bytes.Buffer{}
i, err := bb.Write(p)
s.Reader = bb
return i, err
}
// NewFile takes the name of the file you want to
// write to and a reader to reader from
func NewFile(path string, r io.Reader) *File {
if r == nil {
r = &bytes.Buffer{}
}
if seek, ok := r.(io.Seeker); ok {
seek.Seek(0, 0)
}
abs := path
if !filepath.IsAbs(path) {
abs, _ = filepath.Abs(path)
}
return &File{
Reader: r,
Path: path,
AbsPath: abs,
}
}

View File

@@ -0,0 +1,112 @@
package parser
import (
"fmt"
"go/build"
"os"
"path/filepath"
"strings"
"time"
"github.com/gobuffalo/packr/v2/plog"
"github.com/karrick/godirwalk"
"github.com/markbates/errx"
"github.com/markbates/oncer"
)
type finder struct {
id time.Time
}
func (fd *finder) key(m, dir string) string {
return fmt.Sprintf("%s-*parser.finder#%s-%s", fd.id, m, dir)
}
// findAllGoFiles *.go files for a given diretory
func (fd *finder) findAllGoFiles(dir string) ([]string, error) {
var err error
var names []string
oncer.Do(fd.key("findAllGoFiles", dir), func() {
plog.Debug(fd, "findAllGoFiles", "dir", dir)
callback := func(path string, do *godirwalk.Dirent) error {
ext := filepath.Ext(path)
if ext != ".go" {
return nil
}
//check if path is a dir
fi, err := os.Stat(path)
if err != nil {
return nil
}
if fi.IsDir() {
return nil
}
names = append(names, path)
return nil
}
err = godirwalk.Walk(dir, &godirwalk.Options{
FollowSymbolicLinks: true,
Callback: callback,
})
})
return names, err
}
func (fd *finder) findAllGoFilesImports(dir string) ([]string, error) {
var err error
var names []string
oncer.Do(fd.key("findAllGoFilesImports", dir), func() {
ctx := build.Default
if len(ctx.SrcDirs()) == 0 {
err = fmt.Errorf("no src directories found")
return
}
pkg, err := ctx.ImportDir(dir, 0)
if strings.HasPrefix(pkg.ImportPath, "github.com/gobuffalo/packr") {
return
}
if err != nil {
if !strings.Contains(err.Error(), "cannot find package") {
if _, ok := errx.Unwrap(err).(*build.NoGoError); !ok {
err = err
return
}
}
}
if pkg.Goroot {
return
}
if len(pkg.GoFiles) <= 0 {
return
}
plog.Debug(fd, "findAllGoFilesImports", "dir", dir)
names, _ = fd.findAllGoFiles(dir)
for _, n := range pkg.GoFiles {
names = append(names, filepath.Join(pkg.Dir, n))
}
for _, imp := range pkg.Imports {
if len(ctx.SrcDirs()) == 0 {
continue
}
d := ctx.SrcDirs()[len(ctx.SrcDirs())-1]
ip := filepath.Join(d, imp)
n, err := fd.findAllGoFilesImports(ip)
if err != nil && len(n) != 0 {
names = n
return
}
names = append(names, n...)
}
})
return names, err
}

View File

@@ -0,0 +1,43 @@
package parser
import (
"go/ast"
"go/parser"
"go/token"
"io"
"strings"
"github.com/gobuffalo/packd"
"github.com/markbates/errx"
)
// ParsedFile ...
type ParsedFile struct {
File packd.SimpleFile
FileSet *token.FileSet
Ast *ast.File
Lines []string
}
// ParseFileMode ...
func ParseFileMode(gf packd.SimpleFile, mode parser.Mode) (ParsedFile, error) {
pf := ParsedFile{
FileSet: token.NewFileSet(),
File: gf,
}
src := gf.String()
f, err := parser.ParseFile(pf.FileSet, gf.Name(), src, mode)
if err != nil && errx.Unwrap(err) != io.EOF {
return pf, err
}
pf.Ast = f
pf.Lines = strings.Split(src, "\n")
return pf, nil
}
// ParseFile ...
func ParseFile(gf packd.SimpleFile) (ParsedFile, error) {
return ParseFileMode(gf, 0)
}

View File

@@ -0,0 +1,46 @@
package parser
import (
"os"
"sort"
"strings"
"github.com/gobuffalo/packr/v2/plog"
)
// Parser to find boxes
type Parser struct {
Prospects []*File // a list of files to check for boxes
IgnoreImports bool
}
// Run the parser and run any boxes found
func (p *Parser) Run() (Boxes, error) {
var boxes Boxes
for _, pros := range p.Prospects {
plog.Debug(p, "Run", "parsing", pros.Name())
v := NewVisitor(pros)
pbr, err := v.Run()
if err != nil {
return boxes, err
}
for _, b := range pbr {
plog.Debug(p, "Run", "file", pros.Name(), "box", b.Name)
boxes = append(boxes, b)
}
}
pwd, _ := os.Getwd()
sort.Slice(boxes, func(a, b int) bool {
b1 := boxes[a]
return !strings.HasPrefix(b1.AbsPath, pwd)
})
return boxes, nil
}
// New Parser from a list of File
func New(prospects ...*File) *Parser {
return &Parser{
Prospects: prospects,
}
}

View File

@@ -0,0 +1,77 @@
package parser
import (
"os"
"path/filepath"
"strings"
"github.com/gobuffalo/packr/v2/file/resolver"
"github.com/gobuffalo/packr/v2/plog"
)
var DefaultIgnoredFolders = []string{".", "_", "vendor", "node_modules", "_fixtures", "testdata"}
func IsProspect(path string, ignore ...string) (status bool) {
// plog.Debug("parser", "IsProspect", "path", path, "ignore", ignore)
defer func() {
if status {
plog.Debug("parser", "IsProspect (TRUE)", "path", path, "status", status)
}
}()
if path == "." {
return true
}
ext := filepath.Ext(path)
dir := filepath.Dir(path)
fi, _ := os.Stat(path)
if fi != nil {
if fi.IsDir() {
dir = filepath.Base(path)
} else {
if len(ext) > 0 {
dir = filepath.Base(filepath.Dir(path))
}
}
}
path = strings.ToLower(path)
dir = strings.ToLower(dir)
if strings.HasSuffix(path, "-packr.go") {
return false
}
if strings.HasSuffix(path, "_test.go") {
return false
}
ignore = append(ignore, DefaultIgnoredFolders...)
for i, x := range ignore {
ignore[i] = strings.TrimSpace(strings.ToLower(x))
}
parts := strings.Split(resolver.OsPath(path), string(filepath.Separator))
if len(parts) == 0 {
return false
}
for _, i := range ignore {
for _, p := range parts {
if strings.HasPrefix(p, i) {
return false
}
}
}
un := filepath.Base(path)
if len(ext) != 0 {
un = filepath.Base(filepath.Dir(path))
}
if strings.HasPrefix(un, "_") {
return false
}
return ext == ".go"
}

View File

@@ -0,0 +1,89 @@
package parser
import (
"bytes"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/gobuffalo/packr/v2/plog"
"github.com/karrick/godirwalk"
)
type RootsOptions struct {
IgnoreImports bool
Ignores []string
}
func (r RootsOptions) String() string {
x, _ := json.Marshal(r)
return string(x)
}
// NewFromRoots scans the file roots provided and returns a
// new Parser containing the prospects
func NewFromRoots(roots []string, opts *RootsOptions) (*Parser, error) {
if opts == nil {
opts = &RootsOptions{}
}
if len(roots) == 0 {
pwd, _ := os.Getwd()
roots = append(roots, pwd)
}
p := New()
plog.Debug(p, "NewFromRoots", "roots", roots, "options", opts)
callback := func(path string, de *godirwalk.Dirent) error {
if IsProspect(path, opts.Ignores...) {
if de.IsDir() {
return nil
}
roots = append(roots, path)
return nil
}
if de.IsDir() {
return filepath.SkipDir
}
return nil
}
wopts := &godirwalk.Options{
FollowSymbolicLinks: true,
Callback: callback,
}
for _, root := range roots {
plog.Debug(p, "NewFromRoots", "walking", root)
err := godirwalk.Walk(root, wopts)
if err != nil {
return p, err
}
}
dd := map[string]string{}
fd := &finder{id: time.Now()}
for _, r := range roots {
var names []string
if opts.IgnoreImports {
names, _ = fd.findAllGoFiles(r)
} else {
names, _ = fd.findAllGoFilesImports(r)
}
for _, n := range names {
if IsProspect(n) {
plog.Debug(p, "NewFromRoots", "mapping", n)
dd[n] = n
}
}
}
for path := range dd {
plog.Debug(p, "NewFromRoots", "reading file", path)
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
p.Prospects = append(p.Prospects, NewFile(path, bytes.NewReader(b)))
}
plog.Debug(p, "NewFromRoots", "found prospects", len(p.Prospects))
return p, nil
}

View File

@@ -0,0 +1,324 @@
package parser
import (
"fmt"
"go/ast"
"os"
"path/filepath"
"sort"
"strings"
"github.com/gobuffalo/packd"
)
type Visitor struct {
File packd.SimpleFile
Package string
boxes map[string]*Box
errors []error
}
func NewVisitor(f *File) *Visitor {
return &Visitor{
File: f,
boxes: map[string]*Box{},
errors: []error{},
}
}
func (v *Visitor) Run() (Boxes, error) {
var boxes Boxes
pf, err := ParseFile(v.File)
if err != nil {
return boxes, err
}
v.Package = pf.Ast.Name.Name
ast.Walk(v, pf.Ast)
for _, vb := range v.boxes {
boxes = append(boxes, vb)
}
sort.Slice(boxes, func(i, j int) bool {
return boxes[i].Name < boxes[j].Name
})
if len(v.errors) > 0 {
s := make([]string, len(v.errors))
for i, e := range v.errors {
s[i] = e.Error()
}
return boxes, err
}
return boxes, nil
}
func (v *Visitor) Visit(node ast.Node) ast.Visitor {
if node == nil {
return v
}
if err := v.eval(node); err != nil {
v.errors = append(v.errors, err)
}
return v
}
func (v *Visitor) eval(node ast.Node) error {
switch t := node.(type) {
case *ast.CallExpr:
return v.evalExpr(t)
case *ast.Ident:
return v.evalIdent(t)
case *ast.GenDecl:
for _, n := range t.Specs {
if err := v.eval(n); err != nil {
return err
}
}
case *ast.FuncDecl:
if t.Body == nil {
return nil
}
for _, b := range t.Body.List {
if err := v.evalStmt(b); err != nil {
return err
}
}
return nil
case *ast.ValueSpec:
for _, e := range t.Values {
if err := v.evalExpr(e); err != nil {
return err
}
}
}
return nil
}
func (v *Visitor) evalStmt(stmt ast.Stmt) error {
switch t := stmt.(type) {
case *ast.ExprStmt:
return v.evalExpr(t.X)
case *ast.AssignStmt:
for _, e := range t.Rhs {
if err := v.evalArgs(e); err != nil {
return err
}
}
}
return nil
}
func (v *Visitor) evalExpr(expr ast.Expr) error {
switch t := expr.(type) {
case *ast.CallExpr:
if t.Fun == nil {
return nil
}
for _, a := range t.Args {
switch at := a.(type) {
case *ast.CallExpr:
if sel, ok := t.Fun.(*ast.SelectorExpr); ok {
return v.evalSelector(at, sel)
}
if err := v.evalArgs(at); err != nil {
return err
}
case *ast.CompositeLit:
for _, e := range at.Elts {
if err := v.evalExpr(e); err != nil {
return err
}
}
}
}
if ft, ok := t.Fun.(*ast.SelectorExpr); ok {
return v.evalSelector(t, ft)
}
case *ast.KeyValueExpr:
return v.evalExpr(t.Value)
}
return nil
}
func (v *Visitor) evalArgs(expr ast.Expr) error {
switch at := expr.(type) {
case *ast.CompositeLit:
for _, e := range at.Elts {
if err := v.evalExpr(e); err != nil {
return err
}
}
case *ast.CallExpr:
if at.Fun == nil {
return nil
}
switch st := at.Fun.(type) {
case *ast.SelectorExpr:
if err := v.evalSelector(at, st); err != nil {
return err
}
case *ast.Ident:
return v.evalIdent(st)
}
for _, a := range at.Args {
if err := v.evalArgs(a); err != nil {
return err
}
}
}
return nil
}
func (v *Visitor) evalSelector(expr *ast.CallExpr, sel *ast.SelectorExpr) error {
x, ok := sel.X.(*ast.Ident)
if !ok {
return nil
}
if x.Name == "packr" {
switch sel.Sel.Name {
case "New":
if len(expr.Args) != 2 {
return fmt.Errorf("`New` requires two arguments")
}
zz := func(e ast.Expr) (string, error) {
switch at := e.(type) {
case *ast.Ident:
switch at.Obj.Kind {
case ast.Var:
if as, ok := at.Obj.Decl.(*ast.AssignStmt); ok {
return v.fromVariable(as)
}
case ast.Con:
if vs, ok := at.Obj.Decl.(*ast.ValueSpec); ok {
return v.fromConstant(vs)
}
}
return "", v.evalIdent(at)
case *ast.BasicLit:
return at.Value, nil
case *ast.CallExpr:
return "", v.evalExpr(at)
}
return "", fmt.Errorf("can't handle %T", e)
}
k1, err := zz(expr.Args[0])
if err != nil {
return err
}
k2, err := zz(expr.Args[1])
if err != nil {
return err
}
v.addBox(k1, k2)
return nil
case "NewBox":
for _, e := range expr.Args {
switch at := e.(type) {
case *ast.Ident:
switch at.Obj.Kind {
case ast.Var:
if as, ok := at.Obj.Decl.(*ast.AssignStmt); ok {
v.addVariable("", as)
}
case ast.Con:
if vs, ok := at.Obj.Decl.(*ast.ValueSpec); ok {
v.addConstant("", vs)
}
}
return v.evalIdent(at)
case *ast.BasicLit:
v.addBox("", at.Value)
case *ast.CallExpr:
return v.evalExpr(at)
}
}
}
}
return nil
}
func (v *Visitor) evalIdent(i *ast.Ident) error {
if i.Obj == nil {
return nil
}
if s, ok := i.Obj.Decl.(*ast.AssignStmt); ok {
return v.evalStmt(s)
}
return nil
}
func (v *Visitor) addBox(name string, path string) {
if len(name) == 0 {
name = path
}
name = strings.Replace(name, "\"", "", -1)
path = strings.Replace(path, "\"", "", -1)
abs := path
if _, ok := v.boxes[name]; !ok {
box := NewBox(name, path)
box.Package = v.Package
pd := filepath.Dir(v.File.Name())
pwd, _ := os.Getwd()
if !filepath.IsAbs(pd) {
pd = filepath.Join(pwd, pd)
}
box.PackageDir = pd
if !filepath.IsAbs(abs) {
abs = filepath.Join(pd, abs)
}
box.AbsPath = abs
v.boxes[name] = box
}
}
func (v *Visitor) fromVariable(as *ast.AssignStmt) (string, error) {
if len(as.Rhs) == 1 {
if bs, ok := as.Rhs[0].(*ast.BasicLit); ok {
return bs.Value, nil
}
}
return "", fmt.Errorf("unable to find value from variable %v", as)
}
func (v *Visitor) addVariable(bn string, as *ast.AssignStmt) error {
bv, err := v.fromVariable(as)
if err != nil {
return nil
}
if len(bn) == 0 {
bn = bv
}
v.addBox(bn, bv)
return nil
}
func (v *Visitor) fromConstant(vs *ast.ValueSpec) (string, error) {
if len(vs.Values) == 1 {
if bs, ok := vs.Values[0].(*ast.BasicLit); ok {
return bs.Value, nil
}
}
return "", fmt.Errorf("unable to find value from constant %v", vs)
}
func (v *Visitor) addConstant(bn string, vs *ast.ValueSpec) error {
if len(vs.Values) == 1 {
if bs, ok := vs.Values[0].(*ast.BasicLit); ok {
bv := bs.Value
if len(bn) == 0 {
bn = bv
}
v.addBox(bn, bv)
}
}
return nil
}

View File

@@ -0,0 +1,75 @@
package store
import (
"os"
"path/filepath"
"strings"
"github.com/gobuffalo/packr/v2/jam/parser"
)
func Clean(root string) error {
defer func() {
packd := filepath.Join(root, "packrd")
os.RemoveAll(packd)
}()
p, err := parser.NewFromRoots([]string{root}, &parser.RootsOptions{})
if err != nil {
return err
}
boxes, err := p.Run()
if err != nil {
return err
}
d := NewDisk("", "")
for _, box := range boxes {
if err := d.Clean(box); err != nil {
return err
}
}
return nil
}
func clean(root string) error {
if len(root) == 0 {
pwd, err := os.Getwd()
if err != nil {
return err
}
root = pwd
}
if _, err := os.Stat(root); err != nil {
return nil
}
defer func() {
packd := filepath.Join(root, "packrd")
os.RemoveAll(packd)
}()
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if filepath.Base(path) == "packrd" {
os.RemoveAll(path)
return filepath.SkipDir
}
}
if strings.HasSuffix(path, "-packr.go") {
err := os.RemoveAll(path)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
return nil
}

348
vendor/github.com/gobuffalo/packr/v2/jam/store/disk.go generated vendored Normal file
View File

@@ -0,0 +1,348 @@
package store
import (
"bytes"
"compress/gzip"
"crypto/md5"
"fmt"
"go/build"
"html/template"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/gobuffalo/packr/v2/internal"
"github.com/karrick/godirwalk"
"github.com/gobuffalo/packr/v2/file/resolver/encoding/hex"
"github.com/gobuffalo/packr/v2/plog"
"github.com/rogpeppe/go-internal/modfile"
"github.com/gobuffalo/packr/v2/jam/parser"
"golang.org/x/sync/errgroup"
)
var _ Store = &Disk{}
const DISK_GLOBAL_KEY = "__packr_global__"
type Disk struct {
DBPath string
DBPackage string
global map[string]string
boxes map[string]*parser.Box
moot *sync.RWMutex
}
func NewDisk(path string, pkg string) *Disk {
if len(path) == 0 {
path = "packrd"
}
if len(pkg) == 0 {
pkg = "packrd"
}
if !filepath.IsAbs(path) {
path, _ = filepath.Abs(path)
}
return &Disk{
DBPath: path,
DBPackage: pkg,
global: map[string]string{},
boxes: map[string]*parser.Box{},
moot: &sync.RWMutex{},
}
}
func (d *Disk) FileNames(box *parser.Box) ([]string, error) {
path := box.AbsPath
if len(box.AbsPath) == 0 {
path = box.Path
}
var names []string
if _, err := os.Stat(path); err != nil {
return names, nil
}
err := godirwalk.Walk(path, &godirwalk.Options{
FollowSymbolicLinks: true,
Callback: func(path string, de *godirwalk.Dirent) error {
if !de.IsRegular() {
return nil
}
names = append(names, path)
return nil
},
})
return names, err
}
func (d *Disk) Files(box *parser.Box) ([]*parser.File, error) {
var files []*parser.File
names, err := d.FileNames(box)
if err != nil {
return files, err
}
for _, n := range names {
b, err := ioutil.ReadFile(n)
if err != nil {
return files, err
}
f := parser.NewFile(n, bytes.NewReader(b))
files = append(files, f)
}
return files, nil
}
func (d *Disk) Pack(box *parser.Box) error {
plog.Debug(d, "Pack", "box", box.Name)
d.boxes[box.Name] = box
names, err := d.FileNames(box)
if err != nil {
return err
}
for _, n := range names {
_, ok := d.global[n]
if ok {
continue
}
k := makeKey(box, n)
// not in the global, so add it!
d.global[n] = k
}
return nil
}
func (d *Disk) Clean(box *parser.Box) error {
root := box.PackageDir
if len(root) == 0 {
return fmt.Errorf("can't clean an empty box.PackageDir")
}
plog.Debug(d, "Clean", "box", box.Name, "root", root)
return clean(root)
}
type options struct {
Package string
GlobalFiles map[string]string
Boxes []optsBox
GK string
}
type optsBox struct {
Name string
Path string
}
// Close ...
func (d *Disk) Close() error {
if len(d.boxes) == 0 {
return nil
}
xb := &parser.Box{Name: DISK_GLOBAL_KEY}
opts := options{
Package: d.DBPackage,
GlobalFiles: map[string]string{},
GK: makeKey(xb, d.DBPath),
}
wg := errgroup.Group{}
for k, v := range d.global {
func(k, v string) {
wg.Go(func() error {
bb := &bytes.Buffer{}
enc := hex.NewEncoder(bb)
zw := gzip.NewWriter(enc)
f, err := os.Open(k)
if err != nil {
return err
}
defer f.Close()
io.Copy(zw, f)
if err := zw.Close(); err != nil {
return err
}
d.moot.Lock()
opts.GlobalFiles[makeKey(xb, k)] = bb.String()
d.moot.Unlock()
return nil
})
}(k, v)
}
if err := wg.Wait(); err != nil {
return err
}
for _, b := range d.boxes {
ob := optsBox{
Name: b.Name,
}
opts.Boxes = append(opts.Boxes, ob)
}
sort.Slice(opts.Boxes, func(a, b int) bool {
return opts.Boxes[a].Name < opts.Boxes[b].Name
})
fm := template.FuncMap{
"printBox": func(ob optsBox) (template.HTML, error) {
box := d.boxes[ob.Name]
if box == nil {
return "", fmt.Errorf("could not find box %s", ob.Name)
}
fn, err := d.FileNames(box)
if err != nil {
return "", err
}
if len(fn) == 0 {
return "", nil
}
type file struct {
Resolver string
ForwardPath string
}
tmpl, err := template.New("box.go").Parse(diskGlobalBoxTmpl)
if err != nil {
return "", err
}
var files []file
for _, s := range fn {
p := strings.TrimPrefix(s, box.AbsPath)
p = strings.TrimPrefix(p, string(filepath.Separator))
files = append(files, file{
Resolver: strings.Replace(p, "\\", "/", -1),
ForwardPath: makeKey(box, s),
})
}
opts := map[string]interface{}{
"Box": box,
"Files": files,
}
bb := &bytes.Buffer{}
if err := tmpl.Execute(bb, opts); err != nil {
return "", err
}
return template.HTML(bb.String()), nil
},
}
os.MkdirAll(d.DBPath, 0755)
fp := filepath.Join(d.DBPath, "packed-packr.go")
global, err := os.Create(fp)
if err != nil {
return err
}
defer global.Close()
tmpl := template.New(fp).Funcs(fm)
tmpl, err = tmpl.Parse(diskGlobalTmpl)
if err != nil {
return err
}
if err := tmpl.Execute(global, opts); err != nil {
return err
}
var ip string
if internal.Mods() {
// Starting in 1.12, we can rely on Go's method for
// resolving where go.mod resides. Prior versions will
// simply return an empty string.
cmd := exec.Command("go", "env", "GOMOD")
out, err := cmd.Output()
if err != nil {
return fmt.Errorf("go.mod cannot be read or does not exist while go module is enabled")
}
mp := strings.TrimSpace(string(out))
if mp == "" {
// We are on a prior version of Go; try and do
// the resolution ourselves.
mp = filepath.Join(filepath.Dir(d.DBPath), "go.mod")
if _, err := os.Stat(mp); err != nil {
mp = filepath.Join(d.DBPath, "go.mod")
}
}
moddata, err := ioutil.ReadFile(mp)
if err != nil {
return fmt.Errorf("go.mod cannot be read or does not exist while go module is enabled")
}
ip = modfile.ModulePath(moddata)
if ip == "" {
return fmt.Errorf("go.mod is malformed")
}
ip = filepath.Join(ip, strings.TrimPrefix(filepath.Dir(d.DBPath), filepath.Dir(mp)))
ip = strings.Replace(ip, "\\", "/", -1)
} else {
ip = filepath.Dir(d.DBPath)
srcs := internal.GoPaths()
srcs = append(srcs, build.Default.SrcDirs()...)
for _, x := range srcs {
ip = strings.TrimPrefix(ip, "/private")
ip = strings.TrimPrefix(ip, x)
}
ip = strings.TrimPrefix(ip, string(filepath.Separator))
ip = strings.TrimPrefix(ip, "src")
ip = strings.TrimPrefix(ip, string(filepath.Separator))
ip = strings.Replace(ip, "\\", "/", -1)
}
ip = path.Join(ip, d.DBPackage)
for _, n := range opts.Boxes {
b := d.boxes[n.Name]
if b == nil {
continue
}
p := filepath.Join(b.PackageDir, b.Package+"-packr.go")
f, err := os.Create(p)
if err != nil {
return err
}
defer f.Close()
o := struct {
Package string
Import string
}{
Package: b.Package,
Import: ip,
}
tmpl, err := template.New(p).Parse(diskImportTmpl)
if err != nil {
return err
}
if err := tmpl.Execute(f, o); err != nil {
return err
}
}
return nil
}
// resolve file paths (only) for the boxes
// compile "global" db
// resolve files for boxes to point at global db
// write global db to disk (default internal/packr)
// write boxes db to disk (default internal/packr)
// write -packr.go files in each package (1 per package) that init the global db
func makeKey(box *parser.Box, path string) string {
w := md5.New()
fmt.Fprint(w, path)
h := hex.EncodeToString(w.Sum(nil))
return h
}

View File

@@ -0,0 +1,51 @@
package store
const diskGlobalTmpl = `// +build !skippackr
// Code generated by github.com/gobuffalo/packr/v2. DO NOT EDIT.
// You can use the "packr2 clean" command to clean up this,
// and any other packr generated files.
package {{.Package}}
import (
"github.com/gobuffalo/packr/v2"
"github.com/gobuffalo/packr/v2/file/resolver"
)
var _ = func() error {
const gk = "{{.GK}}"
g := packr.New(gk, "")
hgr, err := resolver.NewHexGzip(map[string]string{
{{- range $k, $v := .GlobalFiles }}
"{{$k}}": "{{$v}}",
{{- end }}
})
if err != nil {
panic(err)
}
g.DefaultResolver = hgr
{{- range $box := .Boxes}}
{{ printBox $box -}}
{{ end }}
return nil
}()
`
const diskImportTmpl = `// +build !skippackr
// Code generated by github.com/gobuffalo/packr/v2. DO NOT EDIT.
// You can use the "packr clean" command to clean up this,
// and any other packr generated files.
package {{.Package}}
import _ "{{.Import}}"
`
const diskGlobalBoxTmpl = `
func() {
b := packr.New("{{.Box.Name}}", "{{.Box.Path}}")
{{- range $file := .Files }}
b.SetResolver("{{$file.Resolver}}", packr.Pointer{ForwardBox: gk, ForwardPath: "{{$file.ForwardPath}}"})
{{- end }}
}()`

39
vendor/github.com/gobuffalo/packr/v2/jam/store/env.go generated vendored Normal file
View File

@@ -0,0 +1,39 @@
package store
import (
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
)
var goPath = filepath.Join(os.Getenv("HOME"), "go")
func init() {
var once sync.Once
once.Do(func() {
cmd := exec.Command("go", "env", "GOPATH")
b, err := cmd.CombinedOutput()
if err != nil {
return
}
goPath = strings.TrimSpace(string(b))
})
}
// GoPath returns the current GOPATH env var
// or if it's missing, the default.
func GoPath() string {
return goPath
}
// GoBin returns the current GO_BIN env var
// or if it's missing, a default of "go"
func GoBin() string {
go_bin := os.Getenv("GO_BIN")
if go_bin == "" {
return "go"
}
return go_bin
}

44
vendor/github.com/gobuffalo/packr/v2/jam/store/fn.go generated vendored Normal file
View File

@@ -0,0 +1,44 @@
package store
import (
"fmt"
"github.com/gobuffalo/packr/v2/jam/parser"
)
var _ Store = &FnStore{}
type FnStore struct {
FileNamesFn func(*parser.Box) ([]string, error)
FilesFn func(*parser.Box) ([]*parser.File, error)
PackFn func(*parser.Box) error
CleanFn func(*parser.Box) error
}
func (f *FnStore) FileNames(box *parser.Box) ([]string, error) {
if f.FileNamesFn == nil {
return []string{}, fmt.Errorf("FileNames not implemented")
}
return f.FileNames(box)
}
func (f *FnStore) Files(box *parser.Box) ([]*parser.File, error) {
if f.FilesFn == nil {
return []*parser.File{}, fmt.Errorf("Files not implemented")
}
return f.FilesFn(box)
}
func (f *FnStore) Pack(box *parser.Box) error {
if f.PackFn == nil {
return fmt.Errorf("Pack not implemented")
}
return f.PackFn(box)
}
func (f *FnStore) Clean(box *parser.Box) error {
if f.CleanFn == nil {
return fmt.Errorf("Clean not implemented")
}
return f.Clean(box)
}

View File

@@ -0,0 +1,129 @@
package store
import (
"bytes"
"encoding/json"
"html/template"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/gobuffalo/packr/v2/jam/parser"
)
var _ Store = &Legacy{}
type Legacy struct {
*Disk
boxes map[string][]legacyBox
}
func NewLegacy() *Legacy {
return &Legacy{
Disk: NewDisk("", ""),
boxes: map[string][]legacyBox{},
}
}
func (l *Legacy) Pack(box *parser.Box) error {
files, err := l.Files(box)
if err != nil {
return err
}
var fcs []legacyFile
for _, f := range files {
n := strings.TrimPrefix(f.Name(), box.AbsPath+string(filepath.Separator))
c, err := l.prepFile(f)
if err != nil {
return err
}
fcs = append(fcs, legacyFile{Name: n, Contents: c})
}
sort.Slice(fcs, func(a, b int) bool {
return fcs[a].Name < fcs[b].Name
})
lbs := l.boxes[box.PackageDir]
lbs = append(lbs, legacyBox{
Box: box,
Files: fcs,
})
l.boxes[box.PackageDir] = lbs
return nil
}
func (l *Legacy) prepFile(r io.Reader) (string, error) {
bb := &bytes.Buffer{}
if _, err := io.Copy(bb, r); err != nil {
return "", err
}
b, err := json.Marshal(bb.Bytes())
if err != nil {
return "", err
}
return strings.Replace(string(b), "\"", "\\\"", -1), nil
}
// Close ...
func (l *Legacy) Close() error {
for _, b := range l.boxes {
if len(b) == 0 {
continue
}
bx := b[0].Box
pkg := bx.Package
opts := map[string]interface{}{
"Package": pkg,
"Boxes": b,
}
p := filepath.Join(bx.PackageDir, "a_"+bx.Package+"-packr.go.tmpl")
tmpl, err := template.New(p).Parse(legacyTmpl)
if err != nil {
return err
}
f, err := os.Create(p)
if err != nil {
return err
}
if err := tmpl.Execute(f, opts); err != nil {
return err
}
}
return nil
}
type legacyBox struct {
Box *parser.Box
Files []legacyFile
}
type legacyFile struct {
Name string
Contents string
}
var legacyTmpl = `// Code generated by github.com/gobuffalo/packr. DO NOT EDIT.
package {{.Package}}
import "github.com/gobuffalo/packr"
// You can use the "packr clean" command to clean up this,
// and any other packr generated files.
func init() {
{{- range $box := .Boxes }}
{{- range $box.Files }}
_ = packr.PackJSONBytes("{{$box.Box.Name}}", "{{.Name}}", "{{.Contents}}")
{{- end }}
{{- end }}
}
`

View File

@@ -0,0 +1,12 @@
package store
import (
"github.com/gobuffalo/packr/v2/jam/parser"
)
type Store interface {
FileNames(*parser.Box) ([]string, error)
Files(*parser.Box) ([]*parser.File, error)
Pack(*parser.Box) error
Clean(*parser.Box) error
}