func (c *CLI) checkVersion() { var shouldCheck bool var outs io.Writer if terminal.IsTerminal(int(os.Stdout.Fd())) { outs = os.Stdout shouldCheck = true } else if terminal.IsTerminal(int(os.Stderr.Fd())) { outs = os.Stderr shouldCheck = true } if strings.Contains(c.Version, "dev") { shouldCheck = false } if shouldCheck { newVersion, err := c.CheckForUpgrade() if err != nil { fmt.Fprintf(outs, errize(fmt.Sprintf( "Failed checking for upgrade: %s\n", err.Error(), ))) } if newVersion != nil { fmt.Fprintf(outs, heyYou(fmt.Sprintf( "You are using an older version (%s; latest: %s) of this client.\nTo upgrade run `%s upgrade`.\n", c.Version, newVersion.Version, c.Name, ))) } } }
// performAutoDetections sets options that are set to "auto" func (o *Options) performAutoDetections(targets []string) { if o.ShowFilename == "auto" { if len(targets) == 1 { fileinfo, err := os.Stat(targets[0]) if err == nil && fileinfo.IsDir() { o.ShowFilename = "on" } else { o.ShowFilename = "off" } } else { o.ShowFilename = "on" } } if o.Color == "auto" { // auto activate colored output only if STDOUT is a terminal if o.Output == "" { if runtime.GOOS != "windows" && terminal.IsTerminal(int(os.Stdout.Fd())) { o.Color = "on" } else { o.Color = "off" } } else { o.Color = "off" } } if o.GroupByFile { if !terminal.IsTerminal(int(os.Stdout.Fd())) { o.GroupByFile = false } } if o.Cores == 0 { o.Cores = runtime.NumCPU() } if o.Color == "on" { global.termHighlightFilename = fmt.Sprintf("\033[%d;%d;%dm", 1, 35, 49) global.termHighlightLineno = fmt.Sprintf("\033[%d;%d;%dm", 1, 32, 49) global.termHighlightMatch = fmt.Sprintf("\033[%d;%d;%dm", 1, 31, 49) global.termHighlightReset = fmt.Sprintf("\033[%d;%d;%dm", 0, 39, 49) } else { global.termHighlightFilename = "" global.termHighlightLineno = "" global.termHighlightMatch = "" global.termHighlightReset = "" } }
func ttyEscape(code string) string { if terminal.IsTerminal(syscall.Stdout) { return "\x1b[" + code + "m" } else { return "" } }
func (cli *CLI) NewCanvas(collection string, filepath string) { cli.doAuth() var body string if filepath != "" { //read from file fileExists, err := exists(filepath) check(err) if !fileExists { fmt.Printf("File %s not found", filepath) } bytes, err := ioutil.ReadFile(filepath) check(err) body = string(bytes) } else if !terminal.IsTerminal(int(os.Stdin.Fd())) { // read from STDIN if not a terminal bytes, err := ioutil.ReadAll(os.Stdin) check(err) body = string(bytes) } // default collection to username if collection == "" { collection = cli.Account.Username } // make the canvas canvas, err := cli.Client.NewCanvas(collection, body) check(err) canvas.URL = cli.Client.JoinWebUrl(canvas.WebName()) fmt.Println(canvas.URL) }
func parseArgs() { // set options flag.DurationVar(&option.interval, "interval", time.Second, "Measurement interval") flag.BoolVar(&option.no_interval_backoff, "no-interval-backoff", false, "Disable interval backoff") flag.DurationVar(&option.timeout, "timeout", time.Second*0, "Measurement timeout") flag.DurationVar(&option.start_delay, "start-delay", time.Second*0, "Wait time before measurement") flag.StringVar(&option.output, "output", "-", "Output file name") flag.BoolVar(&option.no_cpu, "no-cpu", false, "Do not record CPU usage") flag.BoolVar(&option.no_disk, "no-disk", false, "Do not record disk usage") flag.BoolVar(&option.no_net, "no-net", false, "Do not record net usage") flag.BoolVar(&option.debug, "debug", false, "Enable debug mode") flag.BoolVar(&option.listDevices, "list-devices", false, "List devices and exits") flag.StringVar(&option.disks, "disks", "", "Disk devices to be monitored") flag.StringVar(&option.player_bin, "player-bin", "", "Run perfmonger-player to show JSON output") flag.Parse() if option.player_bin == "" && terminal.IsTerminal(int(os.Stdout.Fd())) && option.output == "-" { fmt.Fprintf(os.Stderr, "[recording to data.pgr]\n") option.output = "data.pgr" } if option.disks == "" { option.targetDisks = nil } else { option.targetDisks = new(map[string]bool) *option.targetDisks = make(map[string]bool) for _, dev := range strings.Split(option.disks, ",") { (*option.targetDisks)[dev] = true } } if option.debug { os.Stderr.WriteString( fmt.Sprintf( `== option - output : %s - interval : %s - debug : %t - remainings: %s `, option.output, option.interval.String(), option.debug, fmt.Sprint(flag.Args()))) } }
func runSave(cmd *cobra.Command, args []string) (reterr error) { if len(args) == 0 { return errors.New("image reference missing") } output, err := cmd.Flags().GetString("output") if err != nil { return err } if output == "-" && terminal.IsTerminal(int(os.Stdout.Fd())) { return errors.New("refusing to output to terminal, specify output file") } client, err := engineapi.NewEnvClient() if err != nil { return err } ctx, cancel := context.WithCancel(context.Background()) callOnSignal(ctx, cancel, syscall.SIGINT) defer cancel() graphdir, err := cmd.Flags().GetString("graph") if err != nil { return err } c, err := buildcache.New(client).Get(ctx, graphdir, args[0]) if err != nil { return err } if output == "-" { _, err := io.Copy(os.Stdout, c) return err } f, err := ioutil.TempFile(filepath.Dir(output), ".buildcache-") if err != nil { return err } defer func() { if reterr != nil { os.RemoveAll(f.Name()) } }() if n, err := io.Copy(f, c); err != nil { return err } else { logrus.Debugf("saving: %v", humanize.Bytes(uint64(n))) } if err := f.Sync(); err != nil { return err } if err := f.Close(); err != nil { return err } return os.Rename(f.Name(), output) }
func (ps passwordStore) Basic(u *url.URL) (string, string) { // if it's not a terminal, don't wait on input if ps.anonymous || !terminal.IsTerminal(int(os.Stdin.Fd())) { return "", "" } stdin := bufio.NewReader(os.Stdin) fmt.Fprintf(os.Stdout, "Enter username: "******"error processing username input: %s", err) return "", "" } username := strings.TrimSpace(string(userIn)) fmt.Fprintf(os.Stdout, "Enter password: "******"error processing password input: %s", err) return "", "" } password := strings.TrimSpace(string(passphrase)) return username, password }
func rawConnectionFromSerial() (net.Conn, error) { log.Info("opening ttyS0 for backchannel") f, err := os.OpenFile(pathPrefix+"/ttyS0", os.O_RDWR|os.O_SYNC|syscall.O_NOCTTY, backchannelMode) if err != nil { detail := fmt.Errorf("failed to open serial port for backchannel: %s", err) log.Error(detail) return nil, detail } // set the provided FDs to raw if it's a termial // 0 is the uninitialized value for Fd if f.Fd() != 0 && terminal.IsTerminal(int(f.Fd())) { log.Debug("setting terminal to raw mode") s, err := terminal.MakeRaw(int(f.Fd())) if err != nil { return nil, err } log.Infof("s = %#v", s) } var conn net.Conn log.Infof("creating raw connection from ttyS0 (fd=%d)", f.Fd()) conn, err = serial.NewFileConn(f) return conn, err }
// NewScanner returns a ready-to-use Scanner with configurable settings. // // NewScanner also detects if ANSI-mode is available to let the user edit the input line. If it is not available, it falls back to a dumb-mode // where scanning is using directly a bufio.Scanner using bufio.ScanLines. // // Any parameter can be nil in which case the defaults are used (c.f. DefaultScanner). // // In order to have a good line editing experience, input should be an *os.File with the same file descriptor as output func NewScanner(input io.Reader, output io.Writer, onInterrupt func(s *Scanner) (more bool), km Keymap) *Scanner { if input == nil { input = os.Stdin } if onInterrupt == nil { onInterrupt = defaultOnInterrupt } if km == nil { km = DefaultKeymap() } s := &Scanner{&Core{input: input, output: devNull, dumb: true}, onInterrupt, km} f, ok := input.(*os.File) if !ok { return s } if output != nil { _, ok := output.(*os.File) if !ok { return s } } s.output = input.(io.Writer) // does not panic, since *os.File implements io.Writer fd := f.Fd() s.fd = &fd t := os.Getenv("TERM") s.dumb = !terminal.IsTerminal(int(fd)) || len(t) == 0 || t == "dumb" || t == "cons25" return s }
func doAddPassword(args []string) error { var plaintext []byte var err error if len(args) == 1 && terminal.IsTerminal(0) { fmt.Printf("Contents for password `%s': ", args[0]) plaintext, err = terminal.ReadPassword(0) if err != nil { return err } fmt.Println() } else { var f io.Reader if len(args) > 1 { file, err := os.Open(args[1]) if err != nil { return err } defer file.Close() f = file } else { f = os.Stdin } if plaintext, err = ioutil.ReadAll(f); err != nil { return err } } if err = config.WritePassword(args[0], string(plaintext)); err != nil { return err } fmt.Printf("Saved password `%s'\n", args[0]) return nil }
func (c *fileCmd) edit(config *lxd.Config, args []string) error { if len(args) != 1 { return errArgs } // If stdin isn't a terminal, read text from it if !terminal.IsTerminal(int(syscall.Stdin)) { return c.push(config, append([]string{os.Stdin.Name()}, args[0])) } // Create temp file f, err := ioutil.TempFile("", "lxd_file_edit_") fname := f.Name() f.Close() os.Remove(fname) defer os.Remove(fname) // Extract current value err = c.pull(config, append([]string{args[0]}, fname)) if err != nil { return err } _, err = shared.TextEditor(fname, []byte{}) if err != nil { return err } err = c.push(config, append([]string{fname}, args[0])) if err != nil { return err } return nil }
func init() { if terminal.IsTerminal(int(os.Stdout.Fd())) { ColorReset = "\033[0m" ColorGrey = "\033[2m" ColorRed = "\033[31m" ColorGreen = "\033[32m" ColorYellow = "\033[33m" } Debug = &toggledLogger{ Logger: log.New(os.Stdout, "", 0), } Info = &toggledLogger{ Enabled: true, Logger: log.New(os.Stdout, "", 0), } Warn = &toggledLogger{ Enabled: true, Logger: log.New(os.Stderr, "", 0), } Fatal = &toggledLogger{ Enabled: true, Logger: log.New(os.Stderr, "", 0), prefix: ColorRed, postfix: ColorReset, } }
// printMasterKey - remind the user that he should store the master key in // a safe place func printMasterKey(key []byte) { if !terminal.IsTerminal(int(os.Stdout.Fd())) { // We don't want the master key to end up in a log file tlog.Info.Printf("Not running on a terminal, suppressing master key display\n") return } h := hex.EncodeToString(key) var hChunked string // Try to make it less scary by splitting it up in chunks for i := 0; i < len(h); i += 8 { hChunked += h[i : i+8] if i < 52 { hChunked += "-" } if i == 24 { hChunked += "\n " } } tlog.Info.Printf(` Your master key is: %s If the gocryptfs.conf file becomes corrupted or you ever forget your password, there is only one hope for recovery: The master key. Print it to a piece of paper and store it in a drawer. `, tlog.ColorGrey+hChunked+tlog.ColorReset) }
func doSet(config *lxd.Config, args []string) error { if len(args) != 4 { return errArgs } // [[lxc config]] set dakara:c1 limits.memory 200000 remote, container := config.ParseRemoteAndContainer(args[1]) d, err := lxd.NewClient(config, remote) if err != nil { return err } key := args[2] value := args[3] if !terminal.IsTerminal(int(syscall.Stdin)) && value == "-" { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return fmt.Errorf("Can't read from stdin: %s", err) } value = string(buf[:]) } return d.SetContainerConfig(container, key, value) }
func Color(text string, color int) string { if terminal.IsTerminal(int(os.Stdout.Fd())) { return fmt.Sprintf("\x1b[1;%dm%s\x1b[0m", 30+color, text) } else { return text } }
func doProfileSet(client *lxd.Client, p string, args []string) error { // we shifted @args so so it should read "<key> [<value>]" if len(args) < 1 { return errArgs } key := args[0] var value string if len(args) < 2 { value = "" } else { value = args[1] } if !terminal.IsTerminal(syscall.Stdin) && value == "-" { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return fmt.Errorf("Can't read from stdin: %s", err) } value = string(buf[:]) } err := client.SetProfileConfigItem(p, key, value) return err }
func (t *Table) String() string { if t.Headers == nil && len(t.rows) < 1 { return "" } var ttyWidth int terminalFd := int(os.Stdout.Fd()) if os.Getenv("TSURU_FORCE_WRAP") != "" { terminalFd = int(os.Stdin.Fd()) } if terminal.IsTerminal(terminalFd) { ttyWidth, _, _ = terminal.GetSize(terminalFd) } sizes := t.resizeLastColumn(ttyWidth) result := t.separator() if t.Headers != nil { for column, header := range t.Headers { result += "| " + header result += strings.Repeat(" ", sizes[column]+1-len(header)) } result += "|\n" result += t.separator() } result = t.addRows(t.rows, sizes, result) if !t.LineSeparator { result += t.separator() } return result }
func runAttached(c *cli.Context, app, ps, args, release string) (int, error) { fd := os.Stdin.Fd() var w, h int if terminal.IsTerminal(int(fd)) { stdinState, err := terminal.GetState(int(fd)) if err != nil { return -1, err } defer terminal.Restore(int(fd), stdinState) w, h, err = terminal.GetSize(int(fd)) if err != nil { return -1, err } } code, err := rackClient(c).RunProcessAttached(app, ps, args, release, h, w, os.Stdin, os.Stdout) if err != nil { return -1, err } return code, nil }
func loadStdinUserdata() { if !terminal.IsTerminal(int(os.Stdin.Fd())) { data, err := ioutil.ReadAll(os.Stdin) fatal(err) hostUserdata = string(data) } }
func readLine(w io.Writer, r io.Reader, secret bool) ([]byte, error) { if f, ok := r.(*os.File); ok && secret && terminal.IsTerminal(int(f.Fd())) { defer w.Write([]byte{'\n'}) return terminal.ReadPassword(int(f.Fd())) } var input []byte for { var buf [1]byte n, err := r.Read(buf[:]) if n == 1 { if buf[0] == '\n' { break } input = append(input, buf[0]) } if err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } return nil, errgo.Mask(err) } } if len(input) > 0 && input[len(input)-1] == '\r' { input = input[:len(input)-1] } return input, nil }
// TODO(axw) this is now in three places: change-password, // register, and here. Refactor and move to a common location. func readPassword(stdin io.Reader) (string, error) { if f, ok := stdin.(*os.File); ok && terminal.IsTerminal(int(f.Fd())) { password, err := terminal.ReadPassword(int(f.Fd())) return string(password), err } return readLine(stdin) }
func readCredentials(c *cli.Context) (creds *AwsCredentials, err error) { // read credentials from ENV creds = &AwsCredentials{ Access: os.Getenv("AWS_ACCESS_KEY_ID"), Secret: os.Getenv("AWS_SECRET_ACCESS_KEY"), Session: os.Getenv("AWS_SESSION_TOKEN"), } if os.Getenv("AWS_ENDPOINT_URL") != "" { url := os.Getenv("AWS_ENDPOINT_URL") defaults.DefaultConfig.Endpoint = &url } var inputCreds *AwsCredentials if len(c.Args()) > 0 { fileName := c.Args()[0] inputCreds, err = readCredentialsFromFile(fileName) } else if !terminal.IsTerminal(int(os.Stdin.Fd())) { inputCreds, err = readCredentialsFromSTDIN() } if inputCreds != nil { creds = inputCreds } if err != nil { return nil, err } if creds.Access == "" || creds.Secret == "" { reader := bufio.NewReader(os.Stdin) fmt.Println(CredentialsMessage) fmt.Print("AWS Access Key ID: ") creds.Access, err = reader.ReadString('\n') if err != nil { return creds, err } fmt.Print("AWS Secret Access Key: ") creds.Secret, err = reader.ReadString('\n') if err != nil { return creds, err } fmt.Println("") } creds.Access = strings.TrimSpace(creds.Access) creds.Secret = strings.TrimSpace(creds.Secret) creds.Session = strings.TrimSpace(creds.Session) return }
func NewService(name string, config *project.ServiceConfig, context *Context) *RancherService { return &RancherService{ tty: terminal.IsTerminal(int(os.Stdout.Fd())), name: name, serviceConfig: config, context: context, } }
/* Get the terminal descriptor for stdin */ func getTerminalFd() (fd int, err error) { fd = int(os.Stdin.Fd()) if !terminal.IsTerminal(fd) { err = errors.Errorf("Input is not from a terminal") } return }
// PromptRetriever returns a new Retriever which will provide a prompt on stdin // and stdout to retrieve a passphrase. stdin will be checked if it is a terminal, // else the PromptRetriever will error when attempting to retrieve a passphrase. // Upon successful passphrase retrievals, the passphrase will be cached such that // subsequent prompts will produce the same passphrase. func PromptRetriever() notary.PassRetriever { if !terminal.IsTerminal(int(os.Stdin.Fd())) { return func(string, string, bool, int) (string, bool, error) { return "", false, ErrNoInput } } return PromptRetrieverWithInOut(os.Stdin, os.Stdout, nil) }
func init() { Client = &http.Client{} if !terminal.IsTerminal(int(os.Stdout.Fd())) { Blue = fmt.Sprintf Cyan = fmt.Sprintf } }
func setupColors() { if terminal.IsTerminal(int(os.Stdout.Fd())) { colorReset = "\033[0m" colorGrey = "\033[2m" colorRed = "\033[31m" colorGreen = "\033[32m" } }
// If we are invoked as a crash handler, we might not have a terminal // available for output. In that case, we write to a log file. func newDumpOutputWriter() io.Writer { if terminal.IsTerminal(int(os.Stdout.Fd())) { return os.Stdout } sw, _ := syslog.New(syslog.LOG_INFO|syslog.LOG_USER, "csi") return sw }
func main() { var ( uname = flag.String( "u", "*****@*****.**", "Screeps `username`, often an email address", ) ) flag.Usage = func() { fmt.Fprintf( os.Stderr, `Usage: %v [-v] [-u username] After reading a newline-terminated password on stdin, prints screeps console output to stdout. Options: `, os.Args[0], ) flag.PrintDefaults() } flag.Parse() /* Get password */ var pass []byte var err error if terminal.IsTerminal(int(os.Stdin.Fd())) { fmt.Printf("Password: "******"Unable to read password: %v", err) } /* Remove trailing newline characters from the password */ pass = bytes.TrimRight(pass, "\r\n") /* Get Token and UID. */ token, err = getToken(*uname, string(pass)) if nil != err { log.Fatalf("Unable to get token: %v", err) } verbose("Got token: %v", token) uid, err = getUID(token) if nil != err { log.Fatalf("Unable to get user ID: %v", err) } verbose("Got user ID: %v", uid) /* Handle websocket */ if err := handleWebsocket(*uname, string(pass)); nil != err { log.Fatalf("Error: %v", err) } }
func (c *execCmd) run(config *lxd.Config, args []string) error { if len(args) < 2 { return errArgs } remote, name := config.ParseRemoteAndContainer(args[0]) d, err := lxd.NewClient(config, remote) if err != nil { return err } env := map[string]string{"HOME": "/root", "USER": "******"} myEnv := os.Environ() for _, ent := range myEnv { if strings.HasPrefix(ent, "TERM=") { env["TERM"] = ent[len("TERM="):] } } for _, arg := range envArgs { pieces := strings.SplitN(arg, "=", 2) value := "" if len(pieces) > 1 { value = pieces[1] } env[pieces[0]] = value } cfd := syscall.Stdout var oldttystate *terminal.State if terminal.IsTerminal(cfd) { oldttystate, err = terminal.MakeRaw(cfd) if err != nil { return err } defer terminal.Restore(cfd, oldttystate) } ret, err := d.Exec(name, args[1:], env, os.Stdin, os.Stdout, os.Stderr) if err != nil { return err } if oldttystate != nil { /* A bit of a special case here: we want to exit with the same code as * the process inside the container, so we explicitly exit here * instead of returning an error. * * Additionally, since os.Exit() exits without running deferred * functions, we restore the terminal explicitly. */ terminal.Restore(cfd, oldttystate) } /* we get the result of waitpid() here so we need to transform it */ os.Exit(ret >> 8) return fmt.Errorf(gettext.Gettext("unreachable return reached")) }