Allow abigen to use custom templates

This commit is contained in:
maskpp 2023-09-24 21:14:24 +08:00
parent 82ec555d70
commit a1a049db8d
2 changed files with 28 additions and 0 deletions

View file

@ -78,6 +78,13 @@ var tmplSource = map[Lang]string{
LangGo: tmplSourceGo, LangGo: tmplSourceGo,
} }
// SetTmplSource supports this func in order to set special template file.
func SetTmplSource(lang Lang, source string) {
if _, ok := tmplSource[lang]; ok {
tmplSource[lang] = source
}
}
// tmplSourceGo is the Go source template that the generated Go contract binding // tmplSourceGo is the Go source template that the generated Go contract binding
// is based on. // is based on.
const tmplSourceGo = ` const tmplSourceGo = `

View file

@ -72,6 +72,14 @@ var (
Name: "alias", Name: "alias",
Usage: "Comma separated aliases for function and event renaming, e.g. original1=alias1, original2=alias2", Usage: "Comma separated aliases for function and event renaming, e.g. original1=alias1, original2=alias2",
} }
contractFlag = cli.StringFlag{
Name: "contract",
Usage: "Name of the contract to generate the bindings for",
}
tmplFlag = cli.StringFlag{
Name: "tmpl",
Usage: "Template file if a user wants to customize",
}
) )
var app = flags.NewApp("Ethereum ABI wrapper code generator") var app = flags.NewApp("Ethereum ABI wrapper code generator")
@ -182,6 +190,10 @@ func abigen(c *cli.Context) error {
// fully qualified name is of the form <solFilePath>:<type> // fully qualified name is of the form <solFilePath>:<type>
nameParts := strings.Split(name, ":") nameParts := strings.Split(name, ":")
typeName := nameParts[len(nameParts)-1] typeName := nameParts[len(nameParts)-1]
// If a contract name is provided then ignore all other contracts
if c.IsSet(contractFlag.Name) && c.String(contractFlag.Name) != typeName {
continue
}
if exclude != nil && exclude.Matches(name) { if exclude != nil && exclude.Matches(name) {
fmt.Fprintf(os.Stderr, "excluding: %v\n", name) fmt.Fprintf(os.Stderr, "excluding: %v\n", name)
continue continue
@ -215,6 +227,15 @@ func abigen(c *cli.Context) error {
aliases[match[1]] = match[2] aliases[match[1]] = match[2]
} }
} }
// Set customize template file.
if c.IsSet(tmplFlag.Name) {
tmplFile := c.String(tmplFlag.Name)
data, err := os.ReadFile(tmplFile)
if err != nil {
utils.Fatalf("Failed to read template file: %v", err)
}
bind.SetTmplSource(lang, string(data))
}
// Generate the contract binding // Generate the contract binding
code, err := bind.Bind(types, abis, bins, sigs, c.String(pkgFlag.Name), lang, libs, aliases) code, err := bind.Bind(types, abis, bins, sigs, c.String(pkgFlag.Name), lang, libs, aliases)
if err != nil { if err != nil {