graph.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Copyright (c) 2019 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package dig
  21. import (
  22. "io"
  23. "strconv"
  24. "text/template"
  25. "go.uber.org/dig/internal/dot"
  26. )
  27. // A VisualizeOption modifies the default behavior of Visualize.
  28. type VisualizeOption interface {
  29. applyVisualizeOption(*visualizeOptions)
  30. }
  31. type visualizeOptions struct {
  32. VisualizeError error
  33. }
  34. type visualizeOptionFunc func(*visualizeOptions)
  35. func (f visualizeOptionFunc) applyVisualizeOption(opts *visualizeOptions) { f(opts) }
  36. // VisualizeError includes a visualization of the given error in the output of
  37. // Visualize if an error was returned by Invoke or Provide.
  38. //
  39. // if err := c.Provide(...); err != nil {
  40. // dig.Visualize(c, w, dig.VisualizeError(err))
  41. // }
  42. //
  43. // This option has no effect if the error was nil or if it didn't contain any
  44. // information to visualize.
  45. func VisualizeError(err error) VisualizeOption {
  46. return visualizeOptionFunc(func(opts *visualizeOptions) {
  47. opts.VisualizeError = err
  48. })
  49. }
  50. func updateGraph(dg *dot.Graph, err error) error {
  51. var errors []errVisualizer
  52. // Unwrap error to find the root cause.
  53. for {
  54. if ev, ok := err.(errVisualizer); ok {
  55. errors = append(errors, ev)
  56. }
  57. e, ok := err.(causer)
  58. if !ok {
  59. break
  60. }
  61. err = e.cause()
  62. }
  63. // If there are no errVisualizers included, we do not modify the graph.
  64. if len(errors) == 0 {
  65. return nil
  66. }
  67. // We iterate in reverse because the last element is the root cause.
  68. for i := len(errors) - 1; i >= 0; i-- {
  69. errors[i].updateGraph(dg)
  70. }
  71. // Remove non-error entries from the graph for readability.
  72. dg.PruneSuccess()
  73. return nil
  74. }
  75. var _graphTmpl = template.Must(
  76. template.New("DotGraph").
  77. Funcs(template.FuncMap{
  78. "quote": strconv.Quote,
  79. }).
  80. Parse(`digraph {
  81. rankdir=RL;
  82. graph [compound=true];
  83. {{range $g := .Groups}}
  84. {{- quote .String}} [{{.Attributes}}];
  85. {{range .Results}}
  86. {{- quote $g.String}} -> {{quote .String}};
  87. {{end}}
  88. {{end -}}
  89. {{range $index, $ctor := .Ctors}}
  90. subgraph cluster_{{$index}} {
  91. {{ with .Package }}label = {{ quote .}};
  92. {{ end -}}
  93. constructor_{{$index}} [shape=plaintext label={{quote .Name}}];
  94. {{with .ErrorType}}color={{.Color}};{{end}}
  95. {{range .Results}}
  96. {{- quote .String}} [{{.Attributes}}];
  97. {{end}}
  98. }
  99. {{range .Params}}
  100. constructor_{{$index}} -> {{quote .String}} [ltail=cluster_{{$index}}{{if .Optional}} style=dashed{{end}}];
  101. {{end}}
  102. {{range .GroupParams}}
  103. constructor_{{$index}} -> {{quote .String}} [ltail=cluster_{{$index}}];
  104. {{end -}}
  105. {{end}}
  106. {{range .Failed.TransitiveFailures}}
  107. {{- quote .String}} [color=orange];
  108. {{end -}}
  109. {{range .Failed.RootCauses}}
  110. {{- quote .String}} [color=red];
  111. {{end}}
  112. }`))
  113. // Visualize parses the graph in Container c into DOT format and writes it to
  114. // io.Writer w.
  115. func Visualize(c *Container, w io.Writer, opts ...VisualizeOption) error {
  116. dg := c.createGraph()
  117. var options visualizeOptions
  118. for _, o := range opts {
  119. o.applyVisualizeOption(&options)
  120. }
  121. if options.VisualizeError != nil {
  122. if err := updateGraph(dg, options.VisualizeError); err != nil {
  123. return err
  124. }
  125. }
  126. return _graphTmpl.Execute(w, dg)
  127. }
  128. // CanVisualizeError returns true if the error is an errVisualizer.
  129. func CanVisualizeError(err error) bool {
  130. for {
  131. if _, ok := err.(errVisualizer); ok {
  132. return true
  133. }
  134. e, ok := err.(causer)
  135. if !ok {
  136. break
  137. }
  138. err = e.cause()
  139. }
  140. return false
  141. }
  142. func (c *Container) createGraph() *dot.Graph {
  143. dg := dot.NewGraph()
  144. for _, n := range c.nodes {
  145. dg.AddCtor(newDotCtor(n), n.paramList.DotParam(), n.resultList.DotResult())
  146. }
  147. return dg
  148. }
  149. func newDotCtor(n *node) *dot.Ctor {
  150. return &dot.Ctor{
  151. ID: n.id,
  152. Name: n.location.Name,
  153. Package: n.location.Package,
  154. File: n.location.File,
  155. Line: n.location.Line,
  156. }
  157. }