Given a file like this:
package main
func A() {}
func B() {
A()
}
func C() {
A()
}
func D() {
B()
}
func E() {
B()
}
func F() {
C()
}
func G() {
C()
}
func main() {
D()
E()
F()
G()
}
I would like to print a call tree of the program, something like this:
main
D
B
A
E
B
A
F
C
A
G
C
A
I found the callgraph
program [1], but it does not create a tree:
PS C:\prog> callgraph .
prog.A --static-4:5--> prog.C
prog.A --static-5:5--> prog.D
prog.main --static-19:5--> prog.A
prog.B --static-9:5--> prog.E
prog.B --static-10:5--> prog.F
prog.main --static-20:5--> prog.B
Is some method available to do this?
So I did find a package that seems to handle printing a tree from a graph on the command line [1]. However I thought about it some more, and a printed tree might not be the best solution to my issue. What I want to do, is return an error from one of my functions. However to do that, I need to propagate the error all the way up to
main
. As this can be several layers, I thought it would be best if I start frommain
, and work my way down to the desired function. That way, I can the work in stages if need be. The issue is, how do I get an ordered list of these functions? I found a solution withtsort
[2]:but I may not always want the entire call graph. Next I thought about just adding a
panic
:but this will not give you all branches, only the first path to the target function:
Finally I wrote my own sort function, that takes arbitrary destination as input, and prints all paths in order from
main
to the target function:Example:
Result: