暫無描述

commands.go 21KB

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