Açıklama Yok

commands.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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("quit/exit/^D", "Exit pprof"))
  243. }
  244. help = help + strings.Join(commands, "\n") + "\n\n" +
  245. " Options:\n"
  246. // Print help for variables after sorting them.
  247. // Collect radio variables by their group name to print them together.
  248. radioOptions := make(map[string][]string)
  249. var variables []string
  250. for name, vr := range pprofVariables {
  251. if vr.group != "" {
  252. radioOptions[vr.group] = append(radioOptions[vr.group], name)
  253. continue
  254. }
  255. variables = append(variables, fmtHelp(prefix+name, vr.help))
  256. }
  257. sort.Strings(variables)
  258. help = help + strings.Join(variables, "\n") + "\n\n" +
  259. " Option groups (only set one per group):\n"
  260. var radioStrings []string
  261. for radio, ops := range radioOptions {
  262. sort.Strings(ops)
  263. s := []string{fmtHelp(radio, "")}
  264. for _, op := range ops {
  265. s = append(s, " "+fmtHelp(prefix+op, pprofVariables[op].help))
  266. }
  267. radioStrings = append(radioStrings, strings.Join(s, "\n"))
  268. }
  269. sort.Strings(radioStrings)
  270. return help + strings.Join(radioStrings, "\n")
  271. }
  272. func reportHelp(c string, cum, redirect bool) string {
  273. h := []string{
  274. c + " [n] [focus_regex]* [-ignore_regex]*",
  275. "Include up to n samples",
  276. "Include samples matching focus_regex, and exclude ignore_regex.",
  277. }
  278. if cum {
  279. h[0] += " [-cum]"
  280. h = append(h, "-cum sorts the output by cumulative weight")
  281. }
  282. if redirect {
  283. h[0] += " >f"
  284. h = append(h, "Optionally save the report on the file f")
  285. }
  286. return strings.Join(h, "\n")
  287. }
  288. func listHelp(c string, redirect bool) string {
  289. h := []string{
  290. c + "<func_regex|address> [-focus_regex]* [-ignore_regex]*",
  291. "Include functions matching func_regex, or including the address specified.",
  292. "Include samples matching focus_regex, and exclude ignore_regex.",
  293. }
  294. if redirect {
  295. h[0] += " >f"
  296. h = append(h, "Optionally save the report on the file f")
  297. }
  298. return strings.Join(h, "\n")
  299. }
  300. // browsers returns a list of commands to attempt for web visualization.
  301. func browsers() []string {
  302. cmds := []string{"chrome", "google-chrome", "firefox"}
  303. switch runtime.GOOS {
  304. case "darwin":
  305. return append(cmds, "/usr/bin/open")
  306. case "windows":
  307. return append(cmds, "cmd /c start")
  308. default:
  309. userBrowser := os.Getenv("BROWSER")
  310. if userBrowser != "" {
  311. cmds = append([]string{userBrowser, "sensible-browser"}, cmds...)
  312. } else {
  313. cmds = append([]string{"sensible-browser"}, cmds...)
  314. }
  315. return append(cmds, "xdg-open")
  316. }
  317. }
  318. var kcachegrind = []string{"kcachegrind"}
  319. // awayFromTTY saves the output in a file if it would otherwise go to
  320. // the terminal screen. This is used to avoid dumping binary data on
  321. // the screen.
  322. func awayFromTTY(format string) PostProcessor {
  323. return func(input []byte, output io.Writer, ui plugin.UI) error {
  324. if output == os.Stdout && ui.IsTerminal() {
  325. tempFile, err := newTempFile("", "profile", "."+format)
  326. if err != nil {
  327. return err
  328. }
  329. ui.PrintErr("Generating report in ", tempFile.Name())
  330. _, err = fmt.Fprint(tempFile, string(input))
  331. return err
  332. }
  333. _, err := fmt.Fprint(output, string(input))
  334. return err
  335. }
  336. }
  337. func invokeDot(format string) PostProcessor {
  338. divert := awayFromTTY(format)
  339. return func(input []byte, output io.Writer, ui plugin.UI) error {
  340. cmd := exec.Command("dot", "-T"+format)
  341. var buf bytes.Buffer
  342. cmd.Stdin, cmd.Stdout, cmd.Stderr = bytes.NewBuffer(input), &buf, os.Stderr
  343. if err := cmd.Run(); err != nil {
  344. return fmt.Errorf("Failed to execute dot. Is Graphviz installed? Error: %v", err)
  345. }
  346. return divert(buf.Bytes(), output, ui)
  347. }
  348. }
  349. func saveSVGToFile() PostProcessor {
  350. generateSVG := invokeDot("svg")
  351. divert := awayFromTTY("svg")
  352. return func(input []byte, output io.Writer, ui plugin.UI) error {
  353. baseSVG := &bytes.Buffer{}
  354. if err := generateSVG(input, baseSVG, ui); err != nil {
  355. return err
  356. }
  357. return divert([]byte(svg.Massage(*baseSVG)), output, ui)
  358. }
  359. }
  360. func invokeVisualizer(format PostProcessor, suffix string, visualizers []string) PostProcessor {
  361. return func(input []byte, output io.Writer, ui plugin.UI) error {
  362. if output != os.Stdout {
  363. if format != nil {
  364. return format(input, output, ui)
  365. }
  366. _, err := fmt.Fprint(output, string(input))
  367. return err
  368. }
  369. tempFile, err := newTempFile(os.Getenv("PPROF_TMPDIR"), "pprof", "."+suffix)
  370. if err != nil {
  371. return err
  372. }
  373. deferDeleteTempFile(tempFile.Name())
  374. if format != nil {
  375. if err := format(input, tempFile, ui); err != nil {
  376. return err
  377. }
  378. } else {
  379. if _, err := fmt.Fprint(tempFile, string(input)); err != nil {
  380. return err
  381. }
  382. }
  383. tempFile.Close()
  384. // Try visualizers until one is successful
  385. for _, v := range visualizers {
  386. // Separate command and arguments for exec.Command.
  387. args := strings.Split(v, " ")
  388. if len(args) == 0 {
  389. continue
  390. }
  391. viewer := exec.Command(args[0], append(args[1:], tempFile.Name())...)
  392. viewer.Stderr = os.Stderr
  393. if err = viewer.Start(); err == nil {
  394. // Wait for a second so that the visualizer has a chance to
  395. // open the input file. This needs to be done even if we're
  396. // waiting for the visualizer as it can be just a wrapper that
  397. // spawns a browser tab and returns right away.
  398. defer func(t <-chan time.Time) {
  399. <-t
  400. }(time.After(time.Second))
  401. if waitForVisualizer {
  402. return viewer.Wait()
  403. }
  404. return nil
  405. }
  406. }
  407. return err
  408. }
  409. }
  410. // locateSampleIndex returns the appropriate index for a value of sample index.
  411. // If numeric, it returns the number, otherwise it looks up the text in the
  412. // profile sample types.
  413. func locateSampleIndex(p *profile.Profile, sampleIndex string) (int, error) {
  414. if sampleIndex == "" {
  415. if dst := p.DefaultSampleType; dst != "" {
  416. for i, t := range sampleTypes(p) {
  417. if t == dst {
  418. return i, nil
  419. }
  420. }
  421. }
  422. // By default select the last sample value
  423. return len(p.SampleType) - 1, nil
  424. }
  425. if i, err := strconv.Atoi(sampleIndex); err == nil {
  426. if i < 0 || i >= len(p.SampleType) {
  427. return 0, fmt.Errorf("sample_index %s is outside the range [0..%d]", sampleIndex, len(p.SampleType)-1)
  428. }
  429. return i, nil
  430. }
  431. // Remove the inuse_ prefix to support legacy pprof options
  432. // "inuse_space" and "inuse_objects" for profiles containing types
  433. // "space" and "objects".
  434. noInuse := strings.TrimPrefix(sampleIndex, "inuse_")
  435. for i, t := range p.SampleType {
  436. if t.Type == sampleIndex || t.Type == noInuse {
  437. return i, nil
  438. }
  439. }
  440. return 0, fmt.Errorf("sample_index %q must be one of: %v", sampleIndex, sampleTypes(p))
  441. }
  442. func sampleTypes(p *profile.Profile) []string {
  443. types := make([]string, len(p.SampleType))
  444. for i, t := range p.SampleType {
  445. types[i] = t.Type
  446. }
  447. return types
  448. }
  449. // variables describe the configuration parameters recognized by pprof.
  450. type variables map[string]*variable
  451. // variable is a single configuration parameter.
  452. type variable struct {
  453. kind int // How to interpret the value, must be one of the enums below.
  454. value string // Effective value. Only values appropriate for the Kind should be set.
  455. group string // boolKind variables with the same Group != "" cannot be set simultaneously.
  456. help string // Text describing the variable, in multiple lines separated by newline.
  457. }
  458. const (
  459. // variable.kind must be one of these variables.
  460. boolKind = iota
  461. intKind
  462. floatKind
  463. stringKind
  464. )
  465. // set updates the value of a variable, checking that the value is
  466. // suitable for the variable Kind.
  467. func (vars variables) set(name, value string) error {
  468. v := vars[name]
  469. if v == nil {
  470. return fmt.Errorf("no variable %s", name)
  471. }
  472. var err error
  473. switch v.kind {
  474. case boolKind:
  475. var b bool
  476. if b, err = stringToBool(value); err == nil {
  477. if v.group != "" && b == false {
  478. err = fmt.Errorf("%q can only be set to true", name)
  479. }
  480. }
  481. case intKind:
  482. _, err = strconv.Atoi(value)
  483. case floatKind:
  484. _, err = strconv.ParseFloat(value, 64)
  485. }
  486. if err != nil {
  487. return err
  488. }
  489. vars[name].value = value
  490. if group := vars[name].group; group != "" {
  491. for vname, vvar := range vars {
  492. if vvar.group == group && vname != name {
  493. vvar.value = "f"
  494. }
  495. }
  496. }
  497. return err
  498. }
  499. // boolValue returns the value of a boolean variable.
  500. func (v *variable) boolValue() bool {
  501. b, err := stringToBool(v.value)
  502. if err != nil {
  503. panic("unexpected value " + v.value + " for bool ")
  504. }
  505. return b
  506. }
  507. // intValue returns the value of an intKind variable.
  508. func (v *variable) intValue() int {
  509. i, err := strconv.Atoi(v.value)
  510. if err != nil {
  511. panic("unexpected value " + v.value + " for int ")
  512. }
  513. return i
  514. }
  515. // floatValue returns the value of a Float variable.
  516. func (v *variable) floatValue() float64 {
  517. f, err := strconv.ParseFloat(v.value, 64)
  518. if err != nil {
  519. panic("unexpected value " + v.value + " for float ")
  520. }
  521. return f
  522. }
  523. // stringValue returns a canonical representation for a variable.
  524. func (v *variable) stringValue() string {
  525. switch v.kind {
  526. case boolKind:
  527. return fmt.Sprint(v.boolValue())
  528. case intKind:
  529. return fmt.Sprint(v.intValue())
  530. case floatKind:
  531. return fmt.Sprint(v.floatValue())
  532. }
  533. return v.value
  534. }
  535. func stringToBool(s string) (bool, error) {
  536. switch strings.ToLower(s) {
  537. case "true", "t", "yes", "y", "1", "":
  538. return true, nil
  539. case "false", "f", "no", "n", "0":
  540. return false, nil
  541. default:
  542. return false, fmt.Errorf(`illegal value "%s" for bool variable`, s)
  543. }
  544. }
  545. // makeCopy returns a duplicate of a set of shell variables.
  546. func (vars variables) makeCopy() variables {
  547. varscopy := make(variables, len(vars))
  548. for n, v := range vars {
  549. vcopy := *v
  550. varscopy[n] = &vcopy
  551. }
  552. return varscopy
  553. }