github.com/gobuffalo/buffalo-cli/v2@v2.0.0-alpha.15.0.20200919213536-a7350c8e6799/cli/internal/plugins/docker/generator.go (about) 1 package docker 2 3 import ( 4 "context" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "strings" 9 "text/template" 10 11 "github.com/gobuffalo/buffalo-cli/v2/cli/cmds/newapp" 12 "github.com/gobuffalo/here" 13 "github.com/markbates/pkger" 14 "github.com/markbates/pkger/pkging" 15 "github.com/spf13/pflag" 16 ) 17 18 var _ newapp.Newapper = &Generator{} 19 20 type Generator struct { 21 style string 22 flags *pflag.FlagSet 23 } 24 25 func (Generator) PluginName() string { 26 return "docker" 27 } 28 29 func (Generator) Description() string { 30 return "Generates Dockerfile" 31 } 32 33 func (g Generator) Newapp(ctx context.Context, root string, name string, args []string) error { 34 35 f, err := os.Create(filepath.Join(root, "Dockerfile")) 36 if err != nil { 37 return err 38 } 39 defer f.Close() 40 41 tmpl, err := g.buildTemplate() 42 if err != nil { 43 return err 44 } 45 46 version, err := g.imageTag(root) 47 if err != nil { 48 return err 49 } 50 51 info, err := here.Dir(root) 52 if err != nil { 53 return err 54 } 55 56 data := struct { 57 BuffaloVersion string 58 Tool string 59 WebPack bool 60 Name string 61 }{ 62 BuffaloVersion: version, 63 Tool: g.tool(root), 64 WebPack: g.hasWebpack(root), 65 Name: info.Name, 66 } 67 68 err = tmpl.Execute(f, data) 69 if err != nil { 70 return err 71 } 72 73 return nil 74 } 75 76 func (g Generator) hasWebpack(root string) bool { 77 if _, err := os.Stat(filepath.Join(root, "webpack.config.js")); os.IsNotExist(err) { 78 return false 79 } 80 81 return true 82 } 83 84 func (g Generator) tool(root string) string { 85 _, err := os.Stat(filepath.Join(root, "yarn.lock")) 86 if os.IsNotExist(err) { 87 return "npm" 88 } 89 90 return "yarn" 91 } 92 93 func (Generator) imageTag(root string) (string, error) { 94 info, err := here.Package("github.com/gobuffalo/buffalo") 95 if err != nil { 96 return "", err 97 } 98 99 parts := strings.Split(info.Module.Dir, "/") 100 version := parts[len(parts)-1] 101 102 return version, nil 103 } 104 105 func (g Generator) buildTemplate() (*template.Template, error) { 106 file, err := g.templateFile() 107 if err != nil { 108 return nil, err 109 } 110 111 t, err := ioutil.ReadAll(file) 112 if err != nil { 113 return nil, err 114 } 115 116 template, err := template.New("Dockerfile").Parse(string(t)) 117 if err != nil { 118 return nil, err 119 } 120 121 return template, nil 122 } 123 124 func (g Generator) templateFile() (pkging.File, error) { 125 td := pkger.Include("github.com/gobuffalo/buffalo-cli/v2:/cli/internal/plugins/docker/templates") 126 127 file := "Dockerfile.multistage.tmpl" 128 if g.style == "standard" { 129 file = "Dockerfile.standard.tmpl" 130 } 131 132 return pkger.Open(filepath.Join(td, file)) 133 }