How to use embedFiles method of build Package

Best Syzkaller code snippet using build.embedFiles

embed.go

Source:embed.go Github

copy

Full Screen

...15const (16 embedUnknown = iota17 embedBytes18 embedString19 embedFiles20)21func embedFileList(v *ir.Name, kind int) []string {22 // Build list of files to store.23 have := make(map[string]bool)24 var list []string25 for _, e := range *v.Embed {26 for _, pattern := range e.Patterns {27 files, ok := base.Flag.Cfg.Embed.Patterns[pattern]28 if !ok {29 base.ErrorfAt(e.Pos, "invalid go:embed: build system did not map pattern: %s", pattern)30 }31 for _, file := range files {32 if base.Flag.Cfg.Embed.Files[file] == "" {33 base.ErrorfAt(e.Pos, "invalid go:embed: build system did not map file: %s", file)34 continue35 }36 if !have[file] {37 have[file] = true38 list = append(list, file)39 }40 if kind == embedFiles {41 for dir := path.Dir(file); dir != "." && !have[dir]; dir = path.Dir(dir) {42 have[dir] = true43 list = append(list, dir+"/")44 }45 }46 }47 }48 }49 sort.Slice(list, func(i, j int) bool {50 return embedFileLess(list[i], list[j])51 })52 if kind == embedString || kind == embedBytes {53 if len(list) > 1 {54 base.ErrorfAt(v.Pos(), "invalid go:embed: multiple files for type %v", v.Type())55 return nil56 }57 }58 return list59}60// embedKind determines the kind of embedding variable.61func embedKind(typ *types.Type) int {62 if typ.Sym() != nil && typ.Sym().Name == "FS" && (typ.Sym().Pkg.Path == "embed" || (typ.Sym().Pkg == types.LocalPkg && base.Ctxt.Pkgpath == "embed")) {63 return embedFiles64 }65 if typ.Kind() == types.TSTRING {66 return embedString67 }68 if typ.IsSlice() && typ.Elem().Kind() == types.TUINT8 {69 return embedBytes70 }71 return embedUnknown72}73func embedFileNameSplit(name string) (dir, elem string, isDir bool) {74 if name[len(name)-1] == '/' {75 isDir = true76 name = name[:len(name)-1]77 }78 i := len(name) - 179 for i >= 0 && name[i] != '/' {80 i--81 }82 if i < 0 {83 return ".", name, isDir84 }85 return name[:i], name[i+1:], isDir86}87// embedFileLess implements the sort order for a list of embedded files.88// See the comment inside ../../../../embed/embed.go's Files struct for rationale.89func embedFileLess(x, y string) bool {90 xdir, xelem, _ := embedFileNameSplit(x)91 ydir, yelem, _ := embedFileNameSplit(y)92 return xdir < ydir || xdir == ydir && xelem < yelem93}94// WriteEmbed emits the init data for a //go:embed variable,95// which is either a string, a []byte, or an embed.FS.96func WriteEmbed(v *ir.Name) {97 // TODO(mdempsky): User errors should be reported by the frontend.98 commentPos := (*v.Embed)[0].Pos99 if base.Flag.Cfg.Embed.Patterns == nil {100 base.ErrorfAt(commentPos, "invalid go:embed: build system did not supply embed configuration")101 return102 }103 kind := embedKind(v.Type())104 if kind == embedUnknown {105 base.ErrorfAt(v.Pos(), "go:embed cannot apply to var of type %v", v.Type())106 return107 }108 files := embedFileList(v, kind)109 switch kind {110 case embedString, embedBytes:111 file := files[0]112 fsym, size, err := fileStringSym(v.Pos(), base.Flag.Cfg.Embed.Files[file], kind == embedString, nil)113 if err != nil {114 base.ErrorfAt(v.Pos(), "embed %s: %v", file, err)115 }116 sym := v.Linksym()117 off := 0118 off = objw.SymPtr(sym, off, fsym, 0) // data string119 off = objw.Uintptr(sym, off, uint64(size)) // len120 if kind == embedBytes {121 objw.Uintptr(sym, off, uint64(size)) // cap for slice122 }123 case embedFiles:124 slicedata := base.Ctxt.Lookup(`"".` + v.Sym().Name + `.files`)125 off := 0126 // []files pointed at by Files127 off = objw.SymPtr(slicedata, off, slicedata, 3*types.PtrSize) // []file, pointing just past slice128 off = objw.Uintptr(slicedata, off, uint64(len(files)))129 off = objw.Uintptr(slicedata, off, uint64(len(files)))130 // embed/embed.go type file is:131 // name string132 // data string133 // hash [16]byte134 // Emit one of these per file in the set.135 const hashSize = 16136 hash := make([]byte, hashSize)137 for _, file := range files {...

Full Screen

Full Screen

endtoend_test.go

Source:endtoend_test.go Github

copy

Full Screen

1package tests2import (3 "bytes"4 "io/ioutil"5 "os"6 "os/exec"7 "path/filepath"8 "testing"9 "text/template"10 "github.com/stretchr/testify/require"11)12var endToEndCases = []struct {13 name string14 files []fileConfig15 wantGenOut string16 wantRunOut string17 wantGenErr bool18 wantRunErr bool19}{20 {21 "happy1",22 []fileConfig{23 {"main.go", "main", "import subpkg \"./subpkg\"\n//go:generate genembed EmbedFiles f1", map[string]string{"EmbedFiles": "f1", "subpkg.EmbedFiles": "f2"}},24 {"f1", "", `123123`, nil},25 {"subpkg/subpkg.go", "subpkg", `//go:generate genembed EmbedFiles f2`, nil},26 {"subpkg/f2", "", `456456`, nil},27 },28 "", // gen29 "123123\n456456\n", // run30 false, // gen error31 false, // run error32 },33 {34 "embedNotExistsFile",35 []fileConfig{36 {"main.go", "main", `//go:generate genembed EmbedFiles notexistsfile37 `, map[string]string{"EmbedFiles": "notexistsfile"}},38 {"f1", "", `123123`, nil},39 },40 "failed open embedded file \"notexistsfile\"", // gen41 "\n", // run42 true, // gen error43 false, // run error44 },45 {46 "nothingEmbedded",47 []fileConfig{48 {"main.go", "main", `//go:generate genembed EmbedFiles49 `, map[string]string{"EmbedFiles": "notexistsfile"}},50 {"f1", "", `123123`, nil},51 },52 "nothing to embedded", // gen53 "undefined: EmbedFiles", // run54 true, // gen error55 true, // run error56 },57 {58 "emptyArgs",59 []fileConfig{60 {"main.go", "main", `//go:generate genembed61 `, map[string]string{"EmbedFiles": "notexistsfile"}},62 {"f1", "", `123123`, nil},63 },64 "invalid arguments", // gen65 "undefined: EmbedFiles", // run66 true, // gen error67 true, // run error68 },69}70func TestEndToEndCases(t *testing.T) {71 writeFile := func(t *testing.T, dir, file string, dat string) string {72 t.Helper()73 absFile := filepath.Join(dir, file)74 err := os.MkdirAll(filepath.Dir(absFile), 0700)75 require.NoError(t, err, "failed create dir on the fly")76 err = ioutil.WriteFile(absFile, []byte(dat), 0666)77 require.NoError(t, err, "failed write data to file")78 return absFile79 }80 out, err := runBin(".", "go", "build", "-o", "../bin/genembed", "../genembed/genembed.go")81 require.NoError(t, err, "failed build genembed application err=%v, out=%s", err, out)82 for _, test := range endToEndCases {83 t.Run(test.name, func(t *testing.T) {84 dir, err := ioutil.TempDir("", "genembed")85 require.NoError(t, err, "failed create temporary dir")86 defer os.RemoveAll(dir)87 for _, file := range test.files {88 var buf bytes.Buffer89 switch {90 case file.Name == "main.go":91 err = mainGoTpl.Execute(&buf, file)92 case filepath.Ext(file.Name) == ".go" && file.Name != "main.go":93 err = someFileGoTpl.Execute(&buf, file)94 default:95 _, err = buf.WriteString(file.Code)96 }97 require.NoError(t, err, "failed write to file (or execute tpl)")98 writeFile(t, dir, file.Name, buf.String())99 }100 t.Logf("work dir: %q", dir)101 out, err := runBin(dir, "go", "generate", "./...")102 if test.wantGenErr != (err != nil) {103 t.Errorf("go generate error=%v, wantErr=%v, out=%q", err, test.wantGenErr, out)104 }105 if test.wantGenOut == "" {106 require.Empty(t, out)107 } else {108 require.Contains(t, out, test.wantGenOut)109 }110 out, err = runBin(dir, "go", "run", ".")111 if test.wantRunErr != (err != nil) {112 t.Errorf("run bin error=%v, wantErr=%v, out=%q", err, test.wantRunErr, out)113 }114 if test.wantRunOut == "" {115 require.Empty(t, test.wantRunOut)116 } else {117 require.Contains(t, out, test.wantRunOut)118 }119 })120 }121}122func runBin(dir, name string, arg ...string) (string, error) {123 var buf bytes.Buffer124 cmd := exec.Command(name, arg...)125 cmd.Dir = dir126 cmd.Stderr = &buf127 cmd.Stdout = &buf128 pwd, _ := os.Getwd()129 cmd.Env = append(os.Environ(), "PATH="+os.Getenv("PATH")+":"+pwd+"/../bin")130 err := cmd.Run()131 return buf.String(), err132}133type fileConfig struct {134 Name string135 Pkg string136 Code string137 PrintFiles map[string]string138}139var mainGoTpl = template.Must(template.New("main.go").Parse(`package {{.Pkg}}140{{.Code}}141func main() {142 {{- range $filedName, $fileName := .PrintFiles }}143 println(string({{ $filedName }}["{{ $fileName }}"]))144 {{- end }}145}146`))147var someFileGoTpl = template.Must(template.New("somefile.go").Parse(`package {{.Pkg}}148{{.Code}}149`))...

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 t, err := template.ParseFiles("index.html")5 if err != nil {6 fmt.Println(err)7 }8 t.Execute(w, nil)9 })10 http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {11 fmt.Fprintf(w, "Hello World")12 })13 http.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {14 fmt.Fprintf(w, "Bye World")15 })16 http.HandleFunc("/hello/bye", func(w http.ResponseWriter, r *http.Request) {17 fmt.Fprintf(w, "Hello Bye World")18 })19 log.Fatal(http.ListenAndServe(":8080", nil))20}21import (22func main() {23 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {24 t, err := template.ParseFiles("index.html")25 if err != nil {26 fmt.Println(err)27 }28 t.Execute(w, nil)29 })30 http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {31 fmt.Fprintf(w, "Hello World")32 })33 http.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {34 fmt.Fprintf(w, "Bye World")35 })36 http.HandleFunc("/hello/bye", func(w http.ResponseWriter, r *http.Request) {37 fmt.Fprintf(w, "Hello Bye World")38 })39 log.Fatal(http.ListenAndServe(":8080", nil))40}41import (42func main() {43 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {44 t, err := template.ParseFiles("index.html")45 if err != nil {46 fmt.Println(err)47 }48 t.Execute(w, nil)49 })50 http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {51 fmt.Fprintf(w, "Hello World")52 })

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data, err := files.ReadFile("hello.txt")4 if err != nil {5 panic(err)6 }7 fmt.Println(string(data))8}

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data, err := ioutil.ReadFile("test.txt")4 if err != nil {5 log.Fatal(err)6 }7 fmt.Println(string(data))8 file, err := os.Open("test.txt")9 if err != nil {10 log.Fatal(err)11 }12 defer file.Close()13 data, err = ioutil.ReadAll(file)14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println(string(data))18}

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 contents, err := ioutil.ReadFile("data.txt")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("Contents of file:", string(contents))8}

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 zipWriter := zip.NewWriter(&buf)4 defer zipWriter.Close()5 files, err := ioutil.ReadDir(".")6 if err != nil {7 panic(err)8 }9 for _, file := range files {10 fmt.Println(file.Name())11 f, err := os.Open(file.Name())12 if err != nil {13 panic(err)14 }15 defer f.Close()16 fw, err := zipWriter.Create(file.Name())17 if err != nil {18 panic(err)19 }20 _, err = io.Copy(fw, f)21 if err != nil {22 panic(err)23 }24 }25 err = ioutil.WriteFile("output.zip", buf.Bytes(), 0644)26 if err != nil {27 panic(err)28 }29}30import (31func main() {32 r, err := zip.OpenReader("output.zip")33 if err != nil {34 panic(err)35 }36 defer r.Close()37 for _, f := range r.File {38 fmt.Printf("Contents of %s:\n", f.Name)39 rc, err := f.Open()40 if err != nil {41 panic(err)42 }43 _, err = io.CopyN(os.Stdout, rc, 68)44 if err != nil {45 panic(err)46 }47 rc.Close()48 fmt.Println()49 }50 r, err = zip.OpenReader("output.zip")51 if err != nil {52 panic(err)53 }54 defer r.Close()55 for _, f := range r.File {56 fmt.Printf("Contents of %s:\n", f.Name)

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.Handle("/", http.FileServer(http.FS(f)))4 log.Fatal(http.ListenAndServe(":8080", nil))5}6func main() {7 http.Handle("/", http.FileServer(http.FS(fs.Sub(f, "static"))))8 log.Fatal(http.ListenAndServe(":8080", nil))9}10import (11func main() {12 http.Handle("/", http.FileServer(http.FS(f)))13 log.Fatal(http.ListenAndServe(":8080", nil))14}15import (16func main() {17 http.Handle("/", http.FileServer(http.FS(fs.Sub(f, "static"))))18 log.Fatal(http.ListenAndServe(":8080", nil))19}20import (21func main() {22 http.Handle("/", http.FileServer(http.FS(f)))23 log.Fatal(http.ListenAndServe(":8080", nil))24}25import (26func main() {27 http.Handle("/", http.FileServer(http.FS(fs.Sub(f, "static"))))28 log.Fatal(http.ListenAndServe(":8080", nil))29}30import (

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := f.ReadFile("testdata/test.txt")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(string(file))8 dirs, err := fs.ReadDir(f, "testdata")9 if err != nil {10 fmt.Println(err)11 }12 for _, dir := range dirs {13 fmt.Println(dir.Name())14 }15}

Full Screen

Full Screen

embedFiles

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := ioutil.ReadFile("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(string(file))8}9import (10func main() {11 file, err := ioutil.ReadFile("test.txt")12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(string(file))16}17import (18func main() {19 file, err := ioutil.ReadFile("test.txt")20 if err != nil {21 fmt.Println(err)22 }23 fmt.Println(string(file))24}25import (26func main() {27 file, err := ioutil.ReadFile("test.txt")28 if err != nil {29 fmt.Println(err)30 }31 fmt.Println(string(file))32}33import (34func main() {35 file, err := ioutil.ReadFile("test.txt")36 if err != nil {37 fmt.Println(err)38 }39 fmt.Println(string(file))40}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful