It doesn't always work.
For example, a keg could have been installed with a formula from a
URL, which Homebrew now does not know how to access.
Fixes#1496.
This is the (partially) documented public API for Homebrew.
The main class you should look at is the {Formula} class (and classes linked from there). That's the class that's used to create Homebrew formulae (i.e. package descriptions). Assume anything else you stumble upon is private.