暫無描述

commands.go 23KB

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