暫無描述

commands.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package driver
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "os"
  20. "os/exec"
  21. "runtime"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/google/pprof/internal/plugin"
  27. "github.com/google/pprof/internal/report"
  28. )
  29. // commands describes the commands accepted by pprof.
  30. type commands map[string]*command
  31. // command describes the actions for a pprof command. Includes a
  32. // function for command-line completion, the report format to use
  33. // during report generation, any postprocessing functions, and whether
  34. // the command expects a regexp parameter (typically a function name).
  35. type command struct {
  36. format int // report format to generate
  37. postProcess PostProcessor // postprocessing to run on report
  38. visualizer PostProcessor // display output using some callback
  39. hasParam bool // collect a parameter from the CLI
  40. description string // single-line description text saying what the command does
  41. usage string // multi-line help text saying how the command is used
  42. }
  43. // help returns a help string for a command.
  44. func (c *command) help(name string) string {
  45. message := c.description + "\n"
  46. if c.usage != "" {
  47. message += " Usage:\n"
  48. lines := strings.Split(c.usage, "\n")
  49. for _, line := range lines {
  50. message += fmt.Sprintf(" %s\n", line)
  51. }
  52. }
  53. return message + "\n"
  54. }
  55. // AddCommand adds an additional command to the set of commands
  56. // accepted by pprof. This enables extensions to add new commands for
  57. // specialized visualization formats. If the command specified already
  58. // exists, it is overwritten.
  59. func AddCommand(cmd string, format int, post PostProcessor, desc, usage string) {
  60. pprofCommands[cmd] = &command{format, post, nil, false, desc, usage}
  61. }
  62. // SetVariableDefault sets the default value for a pprof
  63. // variable. This enables extensions to set their own defaults.
  64. func SetVariableDefault(variable, value string) {
  65. if v := pprofVariables[variable]; v != nil {
  66. v.value = value
  67. }
  68. }
  69. // PostProcessor is a function that applies post-processing to the report output
  70. type PostProcessor func(input io.Reader, output io.Writer, ui plugin.UI) error
  71. // interactiveMode is true if pprof is running on interactive mode, reading
  72. // commands from its shell.
  73. var interactiveMode = false
  74. // pprofCommands are the report generation commands recognized by pprof.
  75. var pprofCommands = commands{
  76. // Commands that require no post-processing.
  77. "comments": {report.Comments, nil, nil, false, "Output all profile comments", ""},
  78. "disasm": {report.Dis, nil, nil, true, "Output assembly listings annotated with samples", listHelp("disasm", true)},
  79. "dot": {report.Dot, nil, nil, false, "Outputs a graph in DOT format", reportHelp("dot", false, true)},
  80. "list": {report.List, nil, nil, true, "Output annotated source for functions matching regexp", listHelp("list", false)},
  81. "peek": {report.Tree, nil, nil, true, "Output callers/callees of functions matching regexp", "peek func_regex\nDisplay callers and callees of functions matching func_regex."},
  82. "raw": {report.Raw, nil, nil, false, "Outputs a text representation of the raw profile", ""},
  83. "tags": {report.Tags, nil, nil, false, "Outputs all tags in the profile", "tags [tag_regex]* [-ignore_regex]* [>file]\nList tags with key:value matching tag_regex and exclude ignore_regex."},
  84. "text": {report.Text, nil, nil, false, "Outputs top entries in text form", reportHelp("text", true, true)},
  85. "top": {report.Text, nil, nil, false, "Outputs top entries in text form", reportHelp("top", true, true)},
  86. "traces": {report.Traces, nil, nil, false, "Outputs all profile samples in text form", ""},
  87. "tree": {report.Tree, nil, nil, false, "Outputs a text rendering of call graph", reportHelp("tree", true, true)},
  88. // Save binary formats to a file
  89. "callgrind": {report.Callgrind, nil, awayFromTTY("callgraph.out"), false, "Outputs a graph in callgrind format", reportHelp("callgrind", false, true)},
  90. "proto": {report.Proto, nil, awayFromTTY("pb.gz"), false, "Outputs the profile in compressed protobuf format", ""},
  91. "topproto": {report.TopProto, nil, awayFromTTY("pb.gz"), false, "Outputs top entries in compressed protobuf format", ""},
  92. // Generate report in DOT format and postprocess with dot
  93. "gif": {report.Dot, invokeDot("gif"), awayFromTTY("gif"), false, "Outputs a graph image in GIF format", reportHelp("gif", false, true)},
  94. "pdf": {report.Dot, invokeDot("pdf"), awayFromTTY("pdf"), false, "Outputs a graph in PDF format", reportHelp("pdf", false, true)},
  95. "png": {report.Dot, invokeDot("png"), awayFromTTY("png"), false, "Outputs a graph image in PNG format", reportHelp("png", false, true)},
  96. "ps": {report.Dot, invokeDot("ps"), awayFromTTY("ps"), false, "Outputs a graph in PS format", reportHelp("ps", false, true)},
  97. // Save SVG output into a file
  98. "svg": {report.Dot, massageDotSVG(), awayFromTTY("svg"), false, "Outputs a graph in SVG format", reportHelp("svg", false, true)},
  99. // Visualize postprocessed dot output
  100. "eog": {report.Dot, invokeDot("svg"), invokeVisualizer("svg", []string{"eog"}), false, "Visualize graph through eog", reportHelp("eog", false, false)},
  101. "evince": {report.Dot, invokeDot("pdf"), invokeVisualizer("pdf", []string{"evince"}), false, "Visualize graph through evince", reportHelp("evince", false, false)},
  102. "gv": {report.Dot, invokeDot("ps"), invokeVisualizer("ps", []string{"gv --noantialias"}), false, "Visualize graph through gv", reportHelp("gv", false, false)},
  103. "web": {report.Dot, massageDotSVG(), invokeVisualizer("svg", browsers()), false, "Visualize graph through web browser", reportHelp("web", false, false)},
  104. // Visualize callgrind output
  105. "kcachegrind": {report.Callgrind, nil, invokeVisualizer("grind", kcachegrind), false, "Visualize report in KCachegrind", reportHelp("kcachegrind", false, false)},
  106. // Visualize HTML directly generated by report.
  107. "weblist": {report.WebList, nil, invokeVisualizer("html", browsers()), true, "Display annotated source in a web browser", listHelp("weblist", false)},
  108. }
  109. // pprofVariables are the configuration parameters that affect the
  110. // reported generated by pprof.
  111. var pprofVariables = variables{
  112. // Filename for file-based output formats, stdout by default.
  113. "output": &variable{stringKind, "", "", helpText("Output filename for file-based outputs")},
  114. // Comparisons.
  115. "drop_negative": &variable{boolKind, "f", "", helpText(
  116. "Ignore negative differences",
  117. "Do not show any locations with values <0.")},
  118. // Graph handling options.
  119. "call_tree": &variable{boolKind, "f", "", helpText(
  120. "Create a context-sensitive call tree",
  121. "Treat locations reached through different paths as separate.")},
  122. // Display options.
  123. "relative_percentages": &variable{boolKind, "f", "", helpText(
  124. "Show percentages relative to focused subgraph",
  125. "If unset, percentages are relative to full graph before focusing",
  126. "to facilitate comparison with original graph.")},
  127. "unit": &variable{stringKind, "minimum", "", helpText(
  128. "Measurement units to display",
  129. "Scale the sample values to this unit.",
  130. "For time-based profiles, use seconds, milliseconds, nanoseconds, etc.",
  131. "For memory profiles, use megabytes, kilobytes, bytes, etc.",
  132. "Using auto will scale each value independently to the most natural unit.")},
  133. "compact_labels": &variable{boolKind, "f", "", "Show minimal headers"},
  134. "source_path": &variable{stringKind, "", "", "Search path for source files"},
  135. "trim_path": &variable{stringKind, "", "", "Path to trim from source paths before search"},
  136. // Filtering options
  137. "nodecount": &variable{intKind, "-1", "", helpText(
  138. "Max number of nodes to show",
  139. "Uses heuristics to limit the number of locations to be displayed.",
  140. "On graphs, dotted edges represent paths through nodes that have been removed.")},
  141. "nodefraction": &variable{floatKind, "0.005", "", "Hide nodes below <f>*total"},
  142. "edgefraction": &variable{floatKind, "0.001", "", "Hide edges below <f>*total"},
  143. "trim": &variable{boolKind, "t", "", helpText(
  144. "Honor nodefraction/edgefraction/nodecount defaults",
  145. "Set to false to get the full profile, without any trimming.")},
  146. "focus": &variable{stringKind, "", "", helpText(
  147. "Restricts to samples going through a node matching regexp",
  148. "Discard samples that do not include a node matching this regexp.",
  149. "Matching includes the function name, filename or object name.")},
  150. "ignore": &variable{stringKind, "", "", helpText(
  151. "Skips paths going through any nodes matching regexp",
  152. "If set, discard samples that include a node matching this regexp.",
  153. "Matching includes the function name, filename or object name.")},
  154. "prune_from": &variable{stringKind, "", "", helpText(
  155. "Drops any functions below the matched frame.",
  156. "If set, any frames matching the specified regexp and any frames",
  157. "below it will be dropped from each sample.")},
  158. "hide": &variable{stringKind, "", "", helpText(
  159. "Skips nodes matching regexp",
  160. "Discard nodes that match this location.",
  161. "Other nodes from samples that include this location will be shown.",
  162. "Matching includes the function name, filename or object name.")},
  163. "show": &variable{stringKind, "", "", helpText(
  164. "Only show nodes matching regexp",
  165. "If set, only show nodes that match this location.",
  166. "Matching includes the function name, filename or object name.")},
  167. "show_from": &variable{stringKind, "", "", helpText(
  168. "Drops functions above the highest matched frame.",
  169. "If set, all frames above the highest match are dropped from every sample.",
  170. "Matching includes the function name, filename or object name.")},
  171. "tagfocus": &variable{stringKind, "", "", helpText(
  172. "Restricts to samples with tags in range or matched by regexp",
  173. "Use name=value syntax to limit the matching to a specific tag.",
  174. "Numeric tag filter examples: 1kb, 1kb:10kb, memory=32mb:",
  175. "String tag filter examples: foo, foo.*bar, mytag=foo.*bar")},
  176. "tagignore": &variable{stringKind, "", "", helpText(
  177. "Discard samples with tags in range or matched by regexp",
  178. "Use name=value syntax to limit the matching to a specific tag.",
  179. "Numeric tag filter examples: 1kb, 1kb:10kb, memory=32mb:",
  180. "String tag filter examples: foo, foo.*bar, mytag=foo.*bar")},
  181. "tagshow": &variable{stringKind, "", "", helpText(
  182. "Only consider tags matching this regexp",
  183. "Discard tags that do not match this regexp")},
  184. "taghide": &variable{stringKind, "", "", helpText(
  185. "Skip tags matching this regexp",
  186. "Discard tags that match this regexp")},
  187. // Heap profile options
  188. "divide_by": &variable{floatKind, "1", "", helpText(
  189. "Ratio to divide all samples before visualization",
  190. "Divide all samples values by a constant, eg the number of processors or jobs.")},
  191. "mean": &variable{boolKind, "f", "", helpText(
  192. "Average sample value over first value (count)",
  193. "For memory profiles, report average memory per allocation.",
  194. "For time-based profiles, report average time per event.")},
  195. "sample_index": &variable{stringKind, "", "", helpText(
  196. "Sample value to report (0-based index or name)",
  197. "Profiles contain multiple values per sample.",
  198. "Use sample_index=i to select the ith value (starting at 0).")},
  199. "normalize": &variable{boolKind, "f", "", helpText(
  200. "Scales profile based on the base profile.")},
  201. // Data sorting criteria
  202. "flat": &variable{boolKind, "t", "cumulative", helpText("Sort entries based on own weight")},
  203. "cum": &variable{boolKind, "f", "cumulative", helpText("Sort entries based on cumulative weight")},
  204. // Output granularity
  205. "functions": &variable{boolKind, "t", "granularity", helpText(
  206. "Aggregate at the function level.",
  207. "Takes into account the filename/lineno where the function was defined.")},
  208. "files": &variable{boolKind, "f", "granularity", "Aggregate at the file level."},
  209. "lines": &variable{boolKind, "f", "granularity", "Aggregate at the source code line level."},
  210. "addresses": &variable{boolKind, "f", "granularity", helpText(
  211. "Aggregate at the function level.",
  212. "Includes functions' addresses in the output.")},
  213. "noinlines": &variable{boolKind, "f", "granularity", helpText(
  214. "Aggregate at the function level.",
  215. "Attributes inlined functions to their first out-of-line caller.")},
  216. "addressnoinlines": &variable{boolKind, "f", "granularity", helpText(
  217. "Aggregate at the function level, including functions' addresses in the output.",
  218. "Attributes inlined functions to their first out-of-line caller.")},
  219. }
  220. func helpText(s ...string) string {
  221. return strings.Join(s, "\n") + "\n"
  222. }
  223. // usage returns a string describing the pprof commands and variables.
  224. // if commandLine is set, the output reflect cli usage.
  225. func usage(commandLine bool) string {
  226. var prefix string
  227. if commandLine {
  228. prefix = "-"
  229. }
  230. fmtHelp := func(c, d string) string {
  231. return fmt.Sprintf(" %-16s %s", c, strings.SplitN(d, "\n", 2)[0])
  232. }
  233. var commands []string
  234. for name, cmd := range pprofCommands {
  235. commands = append(commands, fmtHelp(prefix+name, cmd.description))
  236. }
  237. sort.Strings(commands)
  238. var help string
  239. if commandLine {
  240. help = " Output formats (select at most one):\n"
  241. } else {
  242. help = " Commands:\n"
  243. commands = append(commands, fmtHelp("o/options", "List options and their current values"))
  244. commands = append(commands, fmtHelp("quit/exit/^D", "Exit pprof"))
  245. }
  246. help = help + strings.Join(commands, "\n") + "\n\n" +
  247. " Options:\n"
  248. // Print help for variables after sorting them.
  249. // Collect radio variables by their group name to print them together.
  250. radioOptions := make(map[string][]string)
  251. var variables []string
  252. for name, vr := range pprofVariables {
  253. if vr.group != "" {
  254. radioOptions[vr.group] = append(radioOptions[vr.group], name)
  255. continue
  256. }
  257. variables = append(variables, fmtHelp(prefix+name, vr.help))
  258. }
  259. sort.Strings(variables)
  260. help = help + strings.Join(variables, "\n") + "\n\n" +
  261. " Option groups (only set one per group):\n"
  262. var radioStrings []string
  263. for radio, ops := range radioOptions {
  264. sort.Strings(ops)
  265. s := []string{fmtHelp(radio, "")}
  266. for _, op := range ops {
  267. s = append(s, " "+fmtHelp(prefix+op, pprofVariables[op].help))
  268. }
  269. radioStrings = append(radioStrings, strings.Join(s, "\n"))
  270. }
  271. sort.Strings(radioStrings)
  272. return help + strings.Join(radioStrings, "\n")
  273. }
  274. func reportHelp(c string, cum, redirect bool) string {
  275. h := []string{
  276. c + " [n] [focus_regex]* [-ignore_regex]*",
  277. "Include up to n samples",
  278. "Include samples matching focus_regex, and exclude ignore_regex.",
  279. }
  280. if cum {
  281. h[0] += " [-cum]"
  282. h = append(h, "-cum sorts the output by cumulative weight")
  283. }
  284. if redirect {
  285. h[0] += " >f"
  286. h = append(h, "Optionally save the report on the file f")
  287. }
  288. return strings.Join(h, "\n")
  289. }
  290. func listHelp(c string, redirect bool) string {
  291. h := []string{
  292. c + "<func_regex|address> [-focus_regex]* [-ignore_regex]*",
  293. "Include functions matching func_regex, or including the address specified.",
  294. "Include samples matching focus_regex, and exclude ignore_regex.",
  295. }
  296. if redirect {
  297. h[0] += " >f"
  298. h = append(h, "Optionally save the report on the file f")
  299. }
  300. return strings.Join(h, "\n")
  301. }
  302. // browsers returns a list of commands to attempt for web visualization.
  303. // Commands which definitely will open a browser are prioritized over other
  304. // commands like xdg-open, which may not open the javascript embedded SVG
  305. // files produced by the -web command in a browser.
  306. func browsers() []string {
  307. var cmds []string
  308. if userBrowser := os.Getenv("BROWSER"); userBrowser != "" {
  309. cmds = append(cmds, userBrowser)
  310. }
  311. cmds = append(cmds, []string{"chrome", "google-chrome", "chromium", "firefox"}...)
  312. switch runtime.GOOS {
  313. case "darwin":
  314. cmds = append(cmds, "/usr/bin/open")
  315. case "windows":
  316. cmds = append(cmds, "cmd /c start")
  317. default:
  318. if os.Getenv("DISPLAY") != "" {
  319. cmds = append(cmds, "xdg-open")
  320. }
  321. cmds = append(cmds, "sensible-browser")
  322. }
  323. return cmds
  324. }
  325. var kcachegrind = []string{"kcachegrind"}
  326. // awayFromTTY saves the output in a file if it would otherwise go to
  327. // the terminal screen. This is used to avoid dumping binary data on
  328. // the screen.
  329. func awayFromTTY(format string) PostProcessor {
  330. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  331. if output == os.Stdout && (ui.IsTerminal() || interactiveMode) {
  332. tempFile, err := newTempFile("", "profile", "."+format)
  333. if err != nil {
  334. return err
  335. }
  336. ui.PrintErr("Generating report in ", tempFile.Name())
  337. output = tempFile
  338. }
  339. _, err := io.Copy(output, input)
  340. return err
  341. }
  342. }
  343. func invokeDot(format string) PostProcessor {
  344. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  345. cmd := exec.Command("dot", "-T"+format)
  346. cmd.Stdin, cmd.Stdout, cmd.Stderr = input, output, os.Stderr
  347. if err := cmd.Run(); err != nil {
  348. return fmt.Errorf("Failed to execute dot. Is Graphviz installed? Error: %v", err)
  349. }
  350. return nil
  351. }
  352. }
  353. // massageDotSVG invokes the dot tool to generate an SVG image and alters
  354. // the image to have panning capabilities when viewed in a browser.
  355. func massageDotSVG() PostProcessor {
  356. generateSVG := invokeDot("svg")
  357. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  358. baseSVG := new(bytes.Buffer)
  359. if err := generateSVG(input, baseSVG, ui); err != nil {
  360. return err
  361. }
  362. _, err := output.Write([]byte(massageSVG(baseSVG.String())))
  363. return err
  364. }
  365. }
  366. func invokeVisualizer(suffix string, visualizers []string) PostProcessor {
  367. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  368. tempFile, err := newTempFile(os.TempDir(), "pprof", "."+suffix)
  369. if err != nil {
  370. return err
  371. }
  372. deferDeleteTempFile(tempFile.Name())
  373. if _, err := io.Copy(tempFile, input); err != nil {
  374. return err
  375. }
  376. tempFile.Close()
  377. // Try visualizers until one is successful
  378. for _, v := range visualizers {
  379. // Separate command and arguments for exec.Command.
  380. args := strings.Split(v, " ")
  381. if len(args) == 0 {
  382. continue
  383. }
  384. viewer := exec.Command(args[0], append(args[1:], tempFile.Name())...)
  385. viewer.Stderr = os.Stderr
  386. if err = viewer.Start(); err == nil {
  387. // Wait for a second so that the visualizer has a chance to
  388. // open the input file. This needs to be done even if we're
  389. // waiting for the visualizer as it can be just a wrapper that
  390. // spawns a browser tab and returns right away.
  391. defer func(t <-chan time.Time) {
  392. <-t
  393. }(time.After(time.Second))
  394. // On interactive mode, let the visualizer run in the background
  395. // so other commands can be issued.
  396. if !interactiveMode {
  397. return viewer.Wait()
  398. }
  399. return nil
  400. }
  401. }
  402. return err
  403. }
  404. }
  405. // variables describe the configuration parameters recognized by pprof.
  406. type variables map[string]*variable
  407. // variable is a single configuration parameter.
  408. type variable struct {
  409. kind int // How to interpret the value, must be one of the enums below.
  410. value string // Effective value. Only values appropriate for the Kind should be set.
  411. group string // boolKind variables with the same Group != "" cannot be set simultaneously.
  412. help string // Text describing the variable, in multiple lines separated by newline.
  413. }
  414. const (
  415. // variable.kind must be one of these variables.
  416. boolKind = iota
  417. intKind
  418. floatKind
  419. stringKind
  420. )
  421. // set updates the value of a variable, checking that the value is
  422. // suitable for the variable Kind.
  423. func (vars variables) set(name, value string) error {
  424. v := vars[name]
  425. if v == nil {
  426. return fmt.Errorf("no variable %s", name)
  427. }
  428. var err error
  429. switch v.kind {
  430. case boolKind:
  431. var b bool
  432. if b, err = stringToBool(value); err == nil {
  433. if v.group != "" && !b {
  434. err = fmt.Errorf("%q can only be set to true", name)
  435. }
  436. }
  437. case intKind:
  438. _, err = strconv.Atoi(value)
  439. case floatKind:
  440. _, err = strconv.ParseFloat(value, 64)
  441. case stringKind:
  442. // Remove quotes, particularly useful for empty values.
  443. if len(value) > 1 && strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`) {
  444. value = value[1 : len(value)-1]
  445. }
  446. }
  447. if err != nil {
  448. return err
  449. }
  450. vars[name].value = value
  451. if group := vars[name].group; group != "" {
  452. for vname, vvar := range vars {
  453. if vvar.group == group && vname != name {
  454. vvar.value = "f"
  455. }
  456. }
  457. }
  458. return err
  459. }
  460. // boolValue returns the value of a boolean variable.
  461. func (v *variable) boolValue() bool {
  462. b, err := stringToBool(v.value)
  463. if err != nil {
  464. panic("unexpected value " + v.value + " for bool ")
  465. }
  466. return b
  467. }
  468. // intValue returns the value of an intKind variable.
  469. func (v *variable) intValue() int {
  470. i, err := strconv.Atoi(v.value)
  471. if err != nil {
  472. panic("unexpected value " + v.value + " for int ")
  473. }
  474. return i
  475. }
  476. // floatValue returns the value of a Float variable.
  477. func (v *variable) floatValue() float64 {
  478. f, err := strconv.ParseFloat(v.value, 64)
  479. if err != nil {
  480. panic("unexpected value " + v.value + " for float ")
  481. }
  482. return f
  483. }
  484. // stringValue returns a canonical representation for a variable.
  485. func (v *variable) stringValue() string {
  486. switch v.kind {
  487. case boolKind:
  488. return fmt.Sprint(v.boolValue())
  489. case intKind:
  490. return fmt.Sprint(v.intValue())
  491. case floatKind:
  492. return fmt.Sprint(v.floatValue())
  493. }
  494. return v.value
  495. }
  496. func stringToBool(s string) (bool, error) {
  497. switch strings.ToLower(s) {
  498. case "true", "t", "yes", "y", "1", "":
  499. return true, nil
  500. case "false", "f", "no", "n", "0":
  501. return false, nil
  502. default:
  503. return false, fmt.Errorf(`illegal value "%s" for bool variable`, s)
  504. }
  505. }
  506. // makeCopy returns a duplicate of a set of shell variables.
  507. func (vars variables) makeCopy() variables {
  508. varscopy := make(variables, len(vars))
  509. for n, v := range vars {
  510. vcopy := *v
  511. varscopy[n] = &vcopy
  512. }
  513. return varscopy
  514. }