I really like docker’s names generator. It makes remembering id’s easier, and as of version 0.7.x, it generates names from notable scientists and hackers, which gives it an extra bonus!
There are a number of ports out there (shamrin/namesgenerator for example), but all of them just copy-and-paste the names, which is not cool at all.
I decided to parse names-generator.go and extract the names from it, thus making sure it’s always up to date.
I wrote two implementations, one in python and one in go.
- python: parses the code directly using regular expressions
- go: parses the code using go’s AST package, and spit python code to stdout.
^ The hyperlinks lead to the relevant section in the blog post.
The amount of lines needed to do all that work is relatively short, which shows how powerful these languages are.
The following code is straight forward. First I download the text, then I parse it using a regular expressions.
I did use a cool trick - I’ve update the locals from the generated code.
When go ported its compiler to go a few years ago, it added a bunch of packages that the compiler needed to do its work. One of them is the excellent go/ast package, which makes parsing go code a breeze.
The following snippet spits PEP8 conformant python code to stdout:
- Downloads the names-generator.go file
- Parses the code
- Walks over the AST and prints out the variables it finds
- Prints the python get function