| package generator |
| |
| /* |
| Package generator provides functionality for generating a source file containing |
| DEPS entries. It is designed to require the absolute minimum of boilerplate from |
| the caller so that they just need to call MustGenerate, along with the necessary |
| go:build / +build comments: |
| |
| ``` |
| generator.MustGenerate("../../../DEPS") |
| ``` |
| */ |
| |
| import ( |
| "fmt" |
| "os" |
| "path/filepath" |
| "sort" |
| "strings" |
| |
| "go.skia.org/infra/go/depot_tools/deps_parser" |
| "go.skia.org/infra/go/skerr" |
| "go.skia.org/infra/go/sklog" |
| ) |
| |
| const ( |
| targetFile = "deps_gen.go" |
| header = `// Code generated by "go run generate.go"; DO NOT EDIT |
| |
| package deps |
| |
| import ( |
| "go.skia.org/infra/go/depot_tools/deps_parser" |
| ) |
| |
| var deps = deps_parser.DepsEntries{` |
| |
| entryTmpl = ` "%s": { |
| Id: "%s", |
| Version: "%s", |
| Path: "%s", |
| },` |
| footer = `} |
| ` |
| ) |
| |
| // Generate creates a deps_gen.go file with the contents of the DEPS file. |
| // It assumes that it's being run via "go generate" and therefore the output |
| // file is to be written to the current working directory. relPathToDeps is the |
| // relative path to the DEPS file from the current working directory. |
| func Generate(relPathToDeps string) error { |
| cwd, err := os.Getwd() |
| if err != nil { |
| return skerr.Wrap(err) |
| } |
| depsPath := filepath.Join(cwd, filepath.FromSlash(relPathToDeps)) |
| depsContents, err := os.ReadFile(depsPath) |
| if err != nil { |
| return skerr.Wrap(err) |
| } |
| entries, err := deps_parser.ParseDeps(string(depsContents)) |
| if err != nil { |
| return skerr.Wrap(err) |
| } |
| ids := make([]string, 0, len(entries)) |
| for id := range entries { |
| ids = append(ids, id) |
| } |
| sort.Strings(ids) |
| |
| parts := []string{header} |
| for _, id := range ids { |
| entry := entries[id] |
| parts = append(parts, fmt.Sprintf(entryTmpl, entry.Id, entry.Id, entry.Version, entry.Path)) |
| } |
| parts = append(parts, footer) |
| |
| targetContents := strings.Join(parts, "\n") |
| if err := os.WriteFile(targetFile, []byte(targetContents), os.ModePerm); err != nil { |
| return skerr.Wrap(err) |
| } |
| return nil |
| } |
| |
| // MustGenerate runs Generate and panics if it fails. |
| func MustGenerate(relPathToDeps string) { |
| if err := Generate(relPathToDeps); err != nil { |
| sklog.Fatal(err) |
| } |
| } |