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
15package driver
16
17import (
18	"bufio"
19	"fmt"
20	"io"
21	"os"
22	"strings"
23
24	"github.com/google/pprof/internal/binutils"
25	"github.com/google/pprof/internal/plugin"
26	"github.com/google/pprof/internal/symbolizer"
27	"github.com/google/pprof/internal/transport"
28)
29
30// setDefaults returns a new plugin.Options with zero fields sets to
31// sensible defaults.
32func setDefaults(o *plugin.Options) *plugin.Options {
33	d := &plugin.Options{}
34	if o != nil {
35		*d = *o
36	}
37	if d.Writer == nil {
38		d.Writer = oswriter{}
39	}
40	if d.Flagset == nil {
41		d.Flagset = &GoFlags{}
42	}
43	if d.Obj == nil {
44		d.Obj = &binutils.Binutils{}
45	}
46	if d.UI == nil {
47		d.UI = &stdUI{r: bufio.NewReader(os.Stdin)}
48	}
49	if d.HTTPTransport == nil {
50		d.HTTPTransport = transport.New(d.Flagset)
51	}
52	if d.Sym == nil {
53		d.Sym = &symbolizer.Symbolizer{Obj: d.Obj, UI: d.UI, Transport: d.HTTPTransport}
54	}
55	return d
56}
57
58type stdUI struct {
59	r *bufio.Reader
60}
61
62func (ui *stdUI) ReadLine(prompt string) (string, error) {
63	os.Stdout.WriteString(prompt)
64	return ui.r.ReadString('\n')
65}
66
67func (ui *stdUI) Print(args ...interface{}) {
68	ui.fprint(os.Stderr, args)
69}
70
71func (ui *stdUI) PrintErr(args ...interface{}) {
72	ui.fprint(os.Stderr, args)
73}
74
75func (ui *stdUI) IsTerminal() bool {
76	return false
77}
78
79func (ui *stdUI) WantBrowser() bool {
80	return true
81}
82
83func (ui *stdUI) SetAutoComplete(func(string) string) {
84}
85
86func (ui *stdUI) fprint(f *os.File, args []interface{}) {
87	text := fmt.Sprint(args...)
88	if !strings.HasSuffix(text, "\n") {
89		text += "\n"
90	}
91	f.WriteString(text)
92}
93
94// oswriter implements the Writer interface using a regular file.
95type oswriter struct{}
96
97func (oswriter) Open(name string) (io.WriteCloser, error) {
98	f, err := os.Create(name)
99	return f, err
100}
101