ondrajz / go-callvis

Visualize call graph of a Go program using Graphviz
https://ofabry.github.io/go-callvis
MIT License
5.85k stars 406 forks source link

Enhancement: parse comment tag on goroutines to name them in diagram #40

Closed Russtopia closed 5 years ago

Russtopia commented 5 years ago

In my diagrams, goroutines, being anonymous, get the name of their parent function with a $n appended. It would be nice if a specially-formatted comment associated with a goroutine would allow a more meaningful name to be generated for the goroutine in the resulting diagram, eg:

func A() {
..
  // #dot: ControlChannelReader
  go func() {
    ... // labelled 'ControlChannelReader' in resulting diagram rather than 'A$1'
  }()
}

Unsure what the best tag name would be: dot? gv?

Russtopia commented 5 years ago

My apologies for not updating this more promptly. I came up with a sufficient solution many months ago, which I neglected to submit here until now.

Rather than some complex addition to the go-callvis codebase, it ultimately seemed best to just use a post-processing script to achieve this, since it is not really the responsibility of go-callvis to name nodes in the graph, but the dot tool beneath, which is language-agnostic.

My solution was to place a formatted comment tag above a goroutine, naming it as desired, eg:

func doShellMode(...) {
        ...
        // #gv:s/label=\"doShellMode\$1\"/label=\"shellRemoteToStdin\"/
        shellRemoteToStdin := func() {
            ...
            ...
        }
        go shellRemoteToStdin()
}

The #gv introduces a sed expression used by the following script, called from a vis build rule in my Makefiles, to patch the .gv files output by graphvis to use the desired name for the node.

fixup-gv.sh

#!/bin/bash

inFile="${1/.go/}"
visFile="${inFile}-vis.gv"

grep -o "#gv:.*" "$inFile.go" | cut -f2 -d: | \
while read -r expr; do sed -i ${expr} "${visFile}"; done

I typically create a 'vis' Makefile target which invokes fixup-gv.sh to generate the graphics for all files in the project.

Example: https://gogs.blitter.com/RLabs/hkexsh/wiki

It might be nice to include the above 'fixup-gv.sh' script as a helper within this project, or as part of an FAQ on how to name goroutines in the go-callvis output. Other than that, it shouldn't be worth effort within the golang codebase of this project.