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

View File

@@ -0,0 +1,28 @@
package cmd
import (
"fmt"
"github.com/gobuffalo/packr/v2/jam"
"github.com/spf13/cobra"
)
var buildCmd = &cobra.Command{
Use: "build",
Short: "Wraps the go build command with packr",
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
cargs := parseArgs(args)
if globalOptions.Verbose {
fmt.Println(dont)
}
if err := jam.Pack(globalOptions.PackOptions); err != nil {
return err
}
return goCmd("build", cargs...)
},
}
func init() {
rootCmd.AddCommand(buildCmd)
}

View File

@@ -0,0 +1,18 @@
package cmd
import (
"github.com/gobuffalo/packr/v2/jam"
"github.com/spf13/cobra"
)
var cleanCmd = &cobra.Command{
Use: "clean",
Short: "removes any *-packr.go files",
RunE: func(cmd *cobra.Command, args []string) error {
return jam.Clean(args...)
},
}
func init() {
rootCmd.AddCommand(cleanCmd)
}

23
vendor/github.com/gobuffalo/packr/v2/packr2/cmd/fix.go generated vendored Normal file
View File

@@ -0,0 +1,23 @@
package cmd
import (
"fmt"
packr "github.com/gobuffalo/packr/v2"
"github.com/gobuffalo/packr/v2/packr2/cmd/fix"
"github.com/spf13/cobra"
)
// fixCmd represents the info command
var fixCmd = &cobra.Command{
Use: "fix",
Short: fmt.Sprintf("will attempt to fix a application's API to match packr version %s", packr.Version),
RunE: func(cmd *cobra.Command, args []string) error {
return fix.Run()
},
}
func init() {
fixCmd.Flags().BoolVarP(&fix.YesToAll, "y", "", false, "update all without asking for confirmation")
rootCmd.AddCommand(fixCmd)
}

View File

@@ -0,0 +1,49 @@
package fix
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/gobuffalo/packr/v2/jam/store"
)
//YesToAll will be used by the command to skip the questions
var YesToAll bool
var replace = map[string]string{
"github.com/gobuffalo/packr": "github.com/gobuffalo/packr/v2",
}
var ic = ImportConverter{
Data: replace,
}
var checks = []Check{
// packrClean,
ic.Process,
}
func packrClean(r *Runner) error {
pwd, err := os.Getwd()
if err != nil {
return err
}
store.Clean(pwd)
return nil
}
func ask(q string) bool {
if YesToAll {
return true
}
fmt.Printf("? %s [y/n]\n", q)
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
text = strings.ToLower(strings.TrimSpace(text))
return text == "y" || text == "yes"
}

View File

@@ -0,0 +1,251 @@
package fix
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"golang.org/x/tools/go/ast/astutil"
)
// ImportConverter will changes imports from a -> b
type ImportConverter struct {
Data map[string]string
}
// Process will walk all the .go files in an application, excluding ./vendor.
// It will then attempt to convert any old import paths to any new import paths
// used by this version Buffalo.
func (c ImportConverter) Process(r *Runner) error {
fmt.Println("~~~ Rewriting Imports ~~~")
err := filepath.Walk(".", c.processFile)
if err != nil {
return err
}
if _, err := os.Stat("Gopkg.toml"); err != nil {
return nil
}
b, err := ioutil.ReadFile("Gopkg.toml")
if err != nil {
return err
}
for k := range c.Data {
if bytes.Contains(b, []byte(k)) {
r.Warnings = append(r.Warnings, fmt.Sprintf("Your Gopkg.toml contains the following import that need to be changed MANUALLY: %s", k))
}
}
return nil
}
func (c ImportConverter) processFile(p string, info os.FileInfo, err error) error {
er := onlyRelevantFiles(p, info, err, func(p string) error {
err := c.rewriteFile(p)
if err != nil {
err = err
}
return err
})
return er
}
func (c ImportConverter) rewriteFile(name string) error {
// create an empty fileset.
fset := token.NewFileSet()
// parse the .go file.
// we are parsing the entire file with comments, so we don't lose anything
// if we need to write it back out.
f, err := parser.ParseFile(fset, name, nil, parser.ParseComments)
if err != nil {
e := err.Error()
msg := "expected 'package', found 'EOF'"
if e[len(e)-len(msg):] == msg {
return nil
}
return err
}
changed := false
funcs := []*ast.FuncDecl{}
for _, d := range f.Decls {
if fn, isFn := d.(*ast.FuncDecl); isFn {
funcs = append(funcs, fn)
}
}
for _, fun := range funcs {
ast.Inspect(fun, func(node ast.Node) bool {
switch n := node.(type) {
case *ast.CallExpr:
fn, ok := n.Fun.(*ast.SelectorExpr)
if !ok || fn.Sel == nil {
return true
}
sel := fn.Sel
i, ok := fn.X.(*ast.Ident)
if !ok {
return true
}
if i.Name != "packr" {
return true
}
if sel.Name == "NewBox" {
sel.Name = "New"
n.Args = append(n.Args, n.Args[0])
changed = true
}
if sel.Name == "MustBytes" {
sel.Name = "Find"
changed = true
}
if sel.Name == "MustBytes" {
sel.Name = "Find"
changed = true
}
}
return true
})
}
for key, value := range c.Data {
if !astutil.DeleteImport(fset, f, key) {
continue
}
astutil.AddImport(fset, f, value)
changed = true
}
commentsChanged, err := c.handleFileComments(f)
if err != nil {
return err
}
changed = changed || commentsChanged
// if no change occurred, then we don't need to write to disk, just return.
if !changed {
return nil
}
// since the imports changed, resort them.
ast.SortImports(fset, f)
// create a temporary file, this easily avoids conflicts.
temp, err := writeTempResult(name, fset, f)
if err != nil {
return err
}
// rename the .temp to .go
return os.Rename(temp, name)
}
func (c ImportConverter) handleFileComments(f *ast.File) (bool, error) {
change := false
for _, cg := range f.Comments {
for _, cl := range cg.List {
if !strings.HasPrefix(cl.Text, "// import \"") {
continue
}
// trim off extra comment stuff
ctext := cl.Text
ctext = strings.TrimPrefix(ctext, "// import")
ctext = strings.TrimSpace(ctext)
// unquote the comment import path value
ctext, err := strconv.Unquote(ctext)
if err != nil {
return false, err
}
// match the comment import path with the given replacement map
if ctext, ok := c.match(ctext); ok {
cl.Text = "// import " + strconv.Quote(ctext)
change = true
}
}
}
return change, nil
}
// match takes an import path and replacement map.
func (c ImportConverter) match(importpath string) (string, bool) {
for key, value := range c.Data {
if !strings.HasPrefix(importpath, key) {
continue
}
result := strings.Replace(importpath, key, value, 1)
return result, true
}
return importpath, false
}
//onlyRelevantFiles processes only .go files excluding folders like node_modules and vendor.
func onlyRelevantFiles(p string, fi os.FileInfo, err error, fn func(p string) error) error {
if err != nil {
return err
}
if fi.IsDir() && p != "." {
for _, n := range []string{"_", ".", "vendor", "node_modules", ".git"} {
base := filepath.Base(p)
if strings.HasPrefix(base, n) {
return filepath.SkipDir
}
}
return nil
}
ext := filepath.Ext(p)
if ext != ".go" {
return nil
}
return fn(p)
}
func writeTempResult(name string, fset *token.FileSet, f *ast.File) (string, error) {
temp := name + ".temp"
w, err := os.Create(temp)
if err != nil {
return "", err
}
// write changes to .temp file, and include proper formatting.
err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(w, fset, f)
if err != nil {
return "", err
}
// close the writer
err = w.Close()
if err != nil {
return "", err
}
return temp, nil
}

View File

@@ -0,0 +1,47 @@
package fix
import (
"fmt"
packr "github.com/gobuffalo/packr/v2"
)
// Check interface for runnable checker functions
type Check func(*Runner) error
// Runner will run all compatible checks
type Runner struct {
Warnings []string
}
// Run all compatible checks
func Run() error {
fmt.Printf("! This updater will attempt to update your application to packr version: %s\n", packr.Version)
if !ask("Do you wish to continue?") {
fmt.Println("~~~ cancelling update ~~~")
return nil
}
r := &Runner{
Warnings: []string{},
}
defer func() {
if len(r.Warnings) == 0 {
return
}
fmt.Println("\n\n----------------------------")
fmt.Printf("!!! (%d) Warnings Were Found !!!\n\n", len(r.Warnings))
for _, w := range r.Warnings {
fmt.Printf("[WARNING]: %s\n", w)
}
}()
for _, c := range checks {
if err := c(r); err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,67 @@
package cmd
import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/gobuffalo/packr/v2/plog"
)
func goCmd(name string, args ...string) error {
cargs := []string{name}
cargs = append(cargs, args...)
if len(args) > 0 {
err := func() error {
path := "."
pwd, err := os.Getwd()
if err != nil {
return err
}
if fi, err := os.Stat(filepath.Join(pwd, args[len(args)-1])); err == nil {
if fi.IsDir() {
return nil
}
path = fi.Name()
}
if filepath.Ext(path) != ".go" {
return nil
}
path, err = filepath.Abs(filepath.Dir(path))
if err != nil {
return err
}
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
for _, f := range files {
if strings.HasSuffix(f.Name(), "-packr.go") {
cargs = append(cargs, f.Name())
}
}
return nil
}()
if err != nil {
return err
}
}
goBin := os.Getenv("GO_BIN")
if goBin == "" {
goBin = "go"
}
cp := exec.Command(goBin, cargs...)
plog.Logger.Debug(strings.Join(cp.Args, " "))
cp.Stderr = os.Stderr
cp.Stdin = os.Stdin
cp.Stdout = os.Stdout
return cp.Run()
}

View File

@@ -0,0 +1,43 @@
package cmd
import (
"fmt"
"github.com/gobuffalo/packr/v2/jam"
"github.com/spf13/cobra"
)
const dont = `Please don't.
The following commands have been deprecated and should not be used:
* packr2 build
* packr2 install
They are, I'll be kind and say, "problematic" and cause more issues
than than the actually solve. Sorry about that. My bad.
It is recommended you use two commands instead:
$ packr2
$ go build/install
`
var installCmd = &cobra.Command{
Use: "install",
Short: "Don't. ru",
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
cargs := parseArgs(args)
if globalOptions.Verbose {
fmt.Println(dont)
}
if err := jam.Pack(globalOptions.PackOptions); err != nil {
return err
}
return goCmd("install", cargs...)
},
}
func init() {
rootCmd.AddCommand(installCmd)
}

View File

@@ -0,0 +1,25 @@
package cmd
func parseArgs(args []string) []string {
var cargs []string
for _, a := range args {
if a == "--legacy" {
globalOptions.Legacy = true
continue
}
if a == "--verbose" {
globalOptions.Verbose = true
continue
}
if a == "--silent" {
globalOptions.Silent = true
continue
}
if a == "--ignore-imports" {
globalOptions.IgnoreImports = true
continue
}
cargs = append(cargs, a)
}
return cargs
}

View File

@@ -0,0 +1,82 @@
package cmd
import (
"os"
"path/filepath"
"github.com/gobuffalo/logger"
"github.com/gobuffalo/packr/v2/jam"
"github.com/gobuffalo/packr/v2/plog"
"github.com/spf13/cobra"
)
var globalOptions = struct {
jam.PackOptions
Verbose bool
Silent bool
}{
PackOptions: jam.PackOptions{},
}
var rootCmd = &cobra.Command{
Use: "packr2",
Short: "Packr is a simple solution for bundling static assets inside of Go binaries.",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
for _, a := range args {
if a == "--legacy" {
globalOptions.Legacy = true
continue
}
if a == "-v" || a == "--verbose" {
globalOptions.Verbose = true
continue
}
}
// if the last argument is a .go file or directory we should
// find boxes from there, not from the current directory.
// packr2 build -v cmd/main.go
if len(args) > 0 {
i := len(args) - 1
dir := args[i]
if _, err := os.Stat(dir); err == nil {
if filepath.Ext(dir) == ".go" {
dir = filepath.Dir(dir)
}
os.Chdir(dir)
args[i] = filepath.Base(args[i])
}
}
if globalOptions.Verbose {
plog.Logger = logger.New(logger.DebugLevel)
}
if globalOptions.Silent {
plog.Logger = logger.New(logger.FatalLevel)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
opts := globalOptions.PackOptions
roots := opts.Roots
roots = append(roots, args...)
opts.Roots = roots
return jam.Pack(opts)
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func init() {
rootCmd.PersistentFlags().BoolVarP(&globalOptions.Verbose, "verbose", "v", false, "enables verbose logging")
rootCmd.PersistentFlags().BoolVar(&globalOptions.Legacy, "legacy", false, "uses the legacy resolution and packing system (assumes first arg || pwd for input path)")
rootCmd.PersistentFlags().BoolVar(&globalOptions.Silent, "silent", false, "silences all output")
rootCmd.PersistentFlags().BoolVar(&globalOptions.IgnoreImports, "ignore-imports", false, "when set to true packr won't resolve imports for boxes")
rootCmd.PersistentFlags().StringVar(&globalOptions.StoreCmd, "store-cmd", "", "sub command to use for packing")
}

View File

@@ -0,0 +1,21 @@
package cmd
import (
"fmt"
packr "github.com/gobuffalo/packr/v2"
"github.com/spf13/cobra"
)
var versionCmd = &cobra.Command{
Use: "version",
Short: "shows packr version",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println(packr.Version)
return nil
},
}
func init() {
rootCmd.AddCommand(versionCmd)
}