<|start_filename|>pkg/command/command_unix.go<|end_filename|>
// +build !windows

package command

import (
	"os/exec"
	"path/filepath"
	"strings"
)

func cmdname(cmd *exec.Cmd) string {
	return filepath.Base(cmd.Args[0])
}

func prepare(cmd *exec.Cmd) *exec.Cmd {
	return cmd
}

func argstring(cmd *exec.Cmd) string {
	return strings.Join(cmd.Args, " ")
}


<|start_filename|>pkg/output/console_windows.go<|end_filename|>
// +build windows

package output

import (
	"io"
	"os"

	"golang.org/x/sys/windows"
)

type console struct {
	handle windows.Handle
	mode   uint32
}

func (c *console) Width() int {
	var info windows.ConsoleScreenBufferInfo
	err := windows.GetConsoleScreenBufferInfo(c.handle, &info)
	if err != nil {
		return 0
	}

	return int(info.Window.Right - info.Window.Left + 1)
}

func (c *console) SetRaw() {
	windows.SetConsoleMode(c.handle, c.mode|
		windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING|
		windows.DISABLE_NEWLINE_AUTO_RETURN)
}

func (c *console) Reset() {
	windows.SetConsoleMode(c.handle, c.mode)
}

func getConsole(w io.Writer) *console {
	f, ok := w.(*os.File)
	if !ok {
		return nil
	}

	h := windows.Handle(f.Fd())
	var mode uint32
	if err := windows.GetConsoleMode(h, &mode); err != nil {
		return nil
	}

	// Test if the file handle represents a console by attempting to enable
	// virtual terminal processing; if that fails, then there is no console
	if err := windows.SetConsoleMode(h, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err != nil {
		return nil
	}
	defer windows.SetConsoleMode(h, mode)

	return &console{
		handle: h,
		mode:   mode,
	}
}


<|start_filename|>pkg/output/console_linux.go<|end_filename|>
// +build linux

package output

import (
	"golang.org/x/sys/unix"
)

const (
	ioctlTcGet = unix.TCGETS
	ioctlTcSet = unix.TCSETS
)


<|start_filename|>pkg/output/logger.go<|end_filename|>
package output

import (
	"fmt"
	"io"
	"time"
)

// NewLogger creates a new standard output interface
// that prefixes a timestamp to each line of output
func NewLogger(level Level, format string, utc bool, w io.Writer) *Interface {
	if format == "" {
		format = time.RFC3339Nano
	}
	writeln := func(line string) {
		now := time.Now()
		if utc {
			now = now.UTC()
		}
		fmt.Fprintf(w, "[%s] %s\n", now.Format(format), line)
	}
	return NewStdInterface(level, &StdOptions{
		ObjectFormat: StdObjectFormatJSON,
	}, NewLineWriter(writeln), NewLineWriter(writeln))
}


<|start_filename|>pkg/output/interface.go<|end_filename|>
package output

import (
	"io"
	"sync"
)

// Level represents an output level
type Level int

// Output levels
const (
	LevelQuiet   = Level(-1)
	LevelNormal  = Level(0)
	LevelVerbose = Level(1)
	LevelDebug   = Level(2)
)

// Is indicates if the level matches a level
func (l Level) Is(level Level) bool {
	switch level {
	case LevelQuiet:
		return l < LevelNormal
	case LevelNormal:
		return l == LevelNormal
	default:
		return l >= level
	}
}

// Interface represents an output interface
type Interface struct {
	Level
	mu      sync.Mutex
	closers map[io.Closer]bool
	handler Handler
}

func (in *Interface) message(level Level, format string, v ...interface{}) {
	if in.Level < level {
		return
	}

	in.mu.Lock()
	defer in.mu.Unlock()

	if in.handler == nil {
		return
	}

	in.handler.Message(level, format, v...)
}

// Info outputs an informational message
func (in *Interface) Info(format string, v ...interface{}) {
	in.message(LevelNormal, format, v...)
}

// Verbose outputs a detailed message
func (in *Interface) Verbose(format string, v ...interface{}) {
	in.message(LevelVerbose, format, v...)
}

// Debug outputs a diagnostic message
func (in *Interface) Debug(format string, v ...interface{}) {
	in.message(LevelDebug, format, v...)
}

// Warning outputs a warning message
func (in *Interface) Warning(format string, v ...interface{}) {
	if in.Level.Is(LevelQuiet) {
		return
	}

	in.mu.Lock()
	defer in.mu.Unlock()

	if in.handler == nil {
		return
	}

	in.handler.Warning(format, v...)
}

// Error outputs an error message
func (in *Interface) Error(format string, v ...interface{}) {
	in.mu.Lock()
	defer in.mu.Unlock()

	if in.handler == nil {
		return
	}

	in.handler.Error(format, v...)
}

// Prompt asks an interactive user to answer a question, or for
// non-interactive sessions, returns a pre-configured response
func (in *Interface) Prompt(format string, v ...interface{}) bool {
	in.mu.Lock()
	defer in.mu.Unlock()

	if in.handler == nil {
		return false
	}

	return in.handler.Prompt(format, v...)
}

// Operation represents an output operation
type Operation interface {
	Progress(format string, v ...interface{})
	Aborted()
	Failed()
	Done()
}

type operation struct {
	in *Interface
	op Operation
}

// Start reports the start of an operation
func (in *Interface) Start(format string, v ...interface{}) Operation {
	if in.Level.Is(LevelQuiet) {
		return &operation{
			in: in,
		}
	}

	in.mu.Lock()
	defer in.mu.Unlock()

	if in.closers == nil {
		return &operation{
			in: in,
		}
	}

	o := &operation{
		in: in,
		op: in.handler.Start(format, v...),
	}

	in.closers[o] = true

	return o
}

func (o *operation) Progress(format string, v ...interface{}) {
	o.in.mu.Lock()
	defer o.in.mu.Unlock()

	if o.op == nil {
		return
	}

	o.op.Progress(format, v...)
}

func (o *operation) end() {
	o.op = nil

	if o.in.closers != nil {
		delete(o.in.closers, o)
	}
}

func (o *operation) Aborted() {
	o.in.mu.Lock()
	defer o.in.mu.Unlock()

	if o.op == nil {
		return
	}

	o.op.Aborted()

	o.end()
}

func (o *operation) Failed() {
	o.in.mu.Lock()
	defer o.in.mu.Unlock()

	if o.op == nil {
		return
	}

	o.op.Failed()

	o.end()
}

func (o *operation) Done() {
	o.in.mu.Lock()
	defer o.in.mu.Unlock()

	if o.op == nil {
		return
	}

	o.op.Done()

	o.end()
}

// Do performs an operation
func (in *Interface) Do(format string, v ...interface{}) error {
	op := in.Start(format, v[:len(v)-1]...)

	var err error
	defer func() {
		if err != nil {
			op.Failed()
		} else {
			op.Done()
		}
	}()

	if f, _ := v[len(v)-1].(func() error); f != nil {
		err = f()
	} else if f, _ := v[len(v)-1].(func(Operation) error); f != nil {
		err = f(op)
	}

	return err
}

func (o *operation) Close() error {
	o.Aborted()

	return nil
}

// Stream represents an output stream
type Stream struct {
	in    *Interface
	Label string
	Level
	Err    bool
	writer io.WriteCloser
}

// NewStream creates a new output stream
func (in *Interface) NewStream(label string, level Level, err bool) *Stream {
	if in.Level.Is(LevelQuiet) || level.Is(LevelQuiet) || in.Level < level {
		return &Stream{
			in:    in,
			Label: label,
			Level: level,
			Err:   err,
		}
	}

	in.mu.Lock()
	defer in.mu.Unlock()

	if in.closers == nil {
		return &Stream{
			in:    in,
			Label: label,
			Level: level,
			Err:   err,
		}
	}

	s := &Stream{
		in:     in,
		Label:  label,
		Level:  level,
		Err:    err,
		writer: in.handler.NewWriter(label, level, err),
	}

	in.closers[s] = true

	return s
}

// Write writes data to the output stream
func (s *Stream) Write(p []byte) (n int, err error) {
	s.in.mu.Lock()
	defer s.in.mu.Unlock()

	if s.writer == nil {
		return len(p), nil
	}

	return s.writer.Write(p)
}

// Close flushes and closes the output stream
func (s *Stream) Close() error {
	s.in.mu.Lock()
	defer s.in.mu.Unlock()

	if s.writer == nil {
		return nil
	}

	if err := s.writer.Close(); err != nil {
		return err
	}

	s.writer = nil

	return nil
}

// Object outputs an object
func (in *Interface) Object(level Level, o interface{}) {
	if in.Level.Is(LevelQuiet) || level.Is(LevelQuiet) || in.Level < level {
		return
	}

	in.mu.Lock()
	defer in.mu.Unlock()

	if in.handler == nil {
		return
	}

	in.handler.Object(level, o)
}

// Result returns a result object
func (in *Interface) Result(o interface{}) {
	if in.Level.Is(LevelQuiet) {
		return
	}

	in.mu.Lock()
	defer in.mu.Unlock()

	if in.handler == nil {
		return
	}

	in.handler.Result(o)
}

// Close closes the output interface
func (in *Interface) Close() error {
	in.mu.Lock()

	if in.handler == nil {
		in.mu.Unlock()
		return nil
	}

	var closers []io.Closer
	for closer := range in.closers {
		closers = append(closers, closer)
	}
	in.closers = nil

	in.mu.Unlock()

	for _, closer := range closers {
		closer.Close()
	}

	in.mu.Lock()
	defer in.mu.Unlock()

	if err := in.handler.Close(); err != nil {
		return err
	}

	in.handler = nil

	return nil
}

// NewInterface creates a new output interface
func NewInterface(level Level, handler Handler) *Interface {
	return &Interface{
		Level:   level,
		closers: map[io.Closer]bool{},
		handler: handler,
	}
}


<|start_filename|>pkg/output/handler.go<|end_filename|>
package output

import (
	"io"
)

// Handler represents an output interface handler
type Handler interface {
	Message(level Level, format string, v ...interface{})
	Warning(format string, v ...interface{})
	Error(format string, v ...interface{})
	Prompt(format string, v ...interface{}) bool
	Start(format string, v ...interface{}) Operation
	NewWriter(label string, level Level, err bool) io.WriteCloser
	Object(level Level, o interface{})
	Result(o interface{})
	io.Closer
}


<|start_filename|>pkg/output/console_unix.go<|end_filename|>
// +build !windows

package output

import (
	"io"
	"os"

	"golang.org/x/sys/unix"
)

type console struct {
	fd      int
	termios *unix.Termios
}

func (c *console) Width() int {
	uws, err := unix.IoctlGetWinsize(c.fd, unix.TIOCGWINSZ)
	if err != nil {
		return 0
	}

	return int(uws.Col)
}

func (c *console) SetRaw() {
	t := *c.termios
	t.Iflag &^= (unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON)
	t.Oflag &^= unix.OPOST
	t.Lflag &^= (unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN)
	t.Cflag &^= (unix.CSIZE | unix.PARENB)
	t.Cflag &^= unix.CS8
	t.Cc[unix.VMIN] = 1
	t.Cc[unix.VTIME] = 0

	unix.IoctlSetTermios(c.fd, ioctlTcSet, &t)
}

func (c *console) Reset() {
	unix.IoctlSetTermios(c.fd, ioctlTcSet, c.termios)
}

func getConsole(w io.Writer) *console {
	f, ok := w.(*os.File)
	if !ok {
		return nil
	}

	fd := int(f.Fd())
	termios, err := unix.IoctlGetTermios(fd, ioctlTcGet)
	if err != nil {
		return nil
	}

	return &console{
		fd:      fd,
		termios: termios,
	}
}


<|start_filename|>pkg/output/multiWriter.go<|end_filename|>
package output

import (
	"io"
	"sync"
)

// MultiWriter represents a writer that duplicates its writes to
// a set of writers that can be dynamically attached and detached
type MultiWriter interface {
	Attach(w io.Writer)
	Detach(w io.Writer)
	io.Writer
}

type multiWriter struct {
	mu      sync.Mutex
	writers map[io.Writer]bool
}

func (mw *multiWriter) Attach(w io.Writer) {
	mw.mu.Lock()
	defer mw.mu.Unlock()

	mw.writers[w] = true
}

func (mw *multiWriter) Detach(w io.Writer) {
	mw.mu.Lock()
	defer mw.mu.Unlock()

	delete(mw.writers, w)
}

func (mw *multiWriter) Write(p []byte) (n int, err error) {
	mw.mu.Lock()
	defer mw.mu.Unlock()

	for w := range mw.writers {
		w.Write(p)
	}

	return len(p), nil
}

// NewMultiWriter creates a new multi writer
// with an initial set of attached writers
func NewMultiWriter(w ...io.Writer) MultiWriter {
	mw := multiWriter{
		writers: map[io.Writer]bool{},
	}

	for _, wr := range w {
		mw.writers[wr] = true
	}

	return &mw
}


<|start_filename|>pkg/output/lineWriter.go<|end_filename|>
package output

import (
	"bytes"
	"errors"
	"io"
)

type lineWriter struct {
	buffer  bytes.Buffer
	writeln func(line string)
}

func (w *lineWriter) Write(p []byte) (n int, err error) {
	if w.writeln == nil {
		return 0, errors.New("output: write occurred to closed line writer")
	}

	for {
		if len(p) == 0 {
			return
		}

		i := bytes.IndexByte(p, '\n')
		if i < 0 {
			nw, err := w.buffer.Write(p)
			n += nw
			return n, err
		}

		line := p[:i]

		if len(line) > 0 && line[i-1] == '\r' {
			line = p[:i-1]
		}

		if w.buffer.Len() > 0 {
			line = append(w.buffer.Bytes(), line...)
			w.buffer.Reset()
		}

		w.writeln(string(line))

		i++
		n += i
		p = p[i:]
	}
}

func (w *lineWriter) Close() error {
	if w.writeln == nil {
		return nil
	}

	if w.buffer.Len() > 0 {
		w.writeln(w.buffer.String())
	}

	w.buffer = bytes.Buffer{}
	w.writeln = nil

	return nil
}

// NewLineWriter creates a new line-segmented writer
func NewLineWriter(writeln func(line string)) io.WriteCloser {
	return &lineWriter{
		writeln: writeln,
	}
}


<|start_filename|>samples/todo-app/frontend/server.js<|end_filename|>
const next = require('next');
const express = require('express')
const bodyParser = require("body-parser");
const request = require('request');
const mongodb = require("mongodb");
const serviceBus = require('servicebus');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
    const server = express();
    server.use(bodyParser.json());

    const mongo = mongodb.MongoClient.connect(process.env.MONGO_CONNECTION_STRING, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
    mongo.then(() => console.log("Connected to Mongo server"));
    mongo.catch(reason => {
        console.error(reason);
        process.exit(1);
    });

    server.get("/api/todos", function (req, res) {
        mongo.then(client => {
            const todos = client.db("todos").collection("todos");
            todos.find({}).toArray((err, docs) => {
                if (err) {
                    res.status(500).send(err);
                } else {
                    res.send(docs);
                }
            });
        });
    });

    var bus = serviceBus.bus({ url: process.env.STATS_QUEUE_URI });
    bus.use(bus.logger());
    bus.on("error", err => {
        console.error(err.message)
        process.exit(1);
    })

    function updateStats(updateEvent) {
        console.log("Pushing stats update: " + updateEvent);
        bus.send(updateEvent, { todo: updateEvent });
    }

    server.post('/api/todos', function (req, res) {
        console.log("POST /api/todos");
        if (!req.body) {
            res.status(400).send("missing item");
            return;
        }
        mongo.then(client => {
            const todos = client.db("todos").collection("todos");
            todos.insertOne(req.body, (err, result) => {
                if (err) {
                    res.status(500).send(err);
                } else {
                    res.status(201).send(req.body);
                    updateStats('todo.created');
                }
            });
        });
    });

    server.put("/api/todos/:id", function (req, res) {
        const id = req.params.id;
        console.log("PUT /api/todos/" + id);
        if (!mongodb.ObjectID.isValid(id)) {
            res.status(400).send("invalid id");
            return;
        }
        if (req.body && req.body._id) {
            res.status(500).send({ message: "Request body should not contain '_id' field." });
            return;
        }
        mongo.then(client => {
            const todos = client.db("todos").collection("todos");
            todos.updateOne({ _id: new mongodb.ObjectId(id) }, { $set: req.body }, (err, result) => {
                if (err) {
                    res.status(500).send(err);
                } else if (result.matchedCount == 0) {
                    res.sendStatus(404);
                } else {
                    res.sendStatus(204);
                    if (req.body.completed === true) {
                        updateStats('todo.completed');
                    }
                }
            });
        });
    });

    server.delete("/api/todos/:id", function (req, res) {
        const id = req.params.id;
        console.log("DELETE /api/todos/" + id);
        if (!mongodb.ObjectID.isValid(id)) {
            res.status(400).send("invalid id");
            return;
        }
        mongo.then(client => {
            const todos = client.db("todos").collection("todos");
            todos.deleteOne({ _id: new mongodb.ObjectId(id) }, (err, result) => {
                if (err) {
                    res.status(500).send(err);
                } else if (result.deletedCount == 0) {
                    res.sendStatus(404);
                } else {
                    res.sendStatus(204);
                    updateStats('todo.deleted');
                }
            });
        });
    });

    server.get("/api/stats", function (req, res) {
        request({
            uri: 'http://' + process.env.STATS_API_HOST + "/stats",
        }, function (error, response, body) {
            res.setHeader('Content-Type', 'application/json');
            res.send(body);
        });
    });

    server.get('/', (req, res) => {
        console.log("Serving index");
        return app.render(req, res, '/index', {});
    });

    server.get('*', (req, res) => {
        return handle(req, res);
    });

    const port = process.env.PORT || 3000;
    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`);
    });

    process.on("SIGINT", () => {
        process.exit(130 /* 128 + SIGINT */);
    });

    process.on("SIGTERM", () => {
        bus.close();
        server.close(() => {
            process.exit(143 /* 128 + SIGTERM */);
        });
    });
});


<|start_filename|>pkg/output/json.go<|end_filename|>
package output

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"strings"
)

type jsonHandler struct {
	level Level
	yes   bool
	out   io.Writer
	ops   int
}

type jsonObject struct {
	Type      string      `json:"type"`
	Label     string      `json:"label,omitempty"`
	Operation int         `json:"operation,omitempty"`
	Content   interface{} `json:"content,omitempty"`
}

func (h *jsonHandler) write(typeName string, label string, op int, content interface{}) error {
	o := &jsonObject{
		Type:      typeName,
		Label:     label,
		Operation: op,
		Content:   content,
	}

	data, err := json.Marshal(o)
	if err != nil {
		return err
	}

	h.out.Write(data)
	h.out.Write([]byte("\n"))

	return nil
}

func (h *jsonHandler) Message(level Level, format string, v ...interface{}) {
	var typeName string
	switch level {
	case LevelNormal:
		typeName = "info"
	case LevelVerbose:
		typeName = "verbose"
	case LevelDebug:
		typeName = "debug"
	}

	h.write(typeName, "", 0, fmt.Sprintf(format, v...))
}

func (h *jsonHandler) Warning(format string, v ...interface{}) {
	h.write("warning", "", 0, fmt.Sprintf(format, v...))
}

func (h *jsonHandler) Error(format string, v ...interface{}) {
	h.write("error", "", 0, fmt.Sprintf(format, v...))
}

func (h *jsonHandler) Prompt(format string, v ...interface{}) bool {
	return h.yes
}

type jsonOperation struct {
	h  *jsonHandler
	id int
}

func (h *jsonHandler) Start(format string, v ...interface{}) Operation {
	h.ops++

	o := &jsonOperation{
		h:  h,
		id: h.ops,
	}

	h.write("start", "", o.id, fmt.Sprintf(format, v...))

	return o
}

func (o *jsonOperation) Progress(format string, v ...interface{}) {
	o.h.write("progress", "", o.id, fmt.Sprintf(format, v...))
}

func (o *jsonOperation) Aborted() {
	o.h.write("aborted", "", o.id, nil)
}

func (o *jsonOperation) Failed() {
	o.h.write("failed", "", o.id, nil)
}

func (o *jsonOperation) Done() {
	o.h.write("done", "", o.id, nil)
}

func (h *jsonHandler) NewWriter(label string, level Level, err bool) io.WriteCloser {
	var typeName string
	switch level {
	case LevelNormal:
		typeName = "stream"
	case LevelVerbose:
		typeName = "verboseStream"
	case LevelDebug:
		typeName = "debugStream"
	}
	if err {
		typeName += "Err"
	}

	return NewLineWriter(func(line string) {
		h.write(typeName, label, 0, line)
	})
}

func (h *jsonHandler) Object(level Level, o interface{}) {
	var typeName string
	switch level {
	case LevelNormal:
		typeName = "object"
	case LevelVerbose:
		typeName = "verboseObject"
	case LevelDebug:
		typeName = "debugObject"
	}

	h.write(typeName, "", 0, o)
}

func (h *jsonHandler) Result(o interface{}) {
	h.write("result", "", 0, o)
}

func (h *jsonHandler) Close() error {
	return nil
}

// NewJSONInterface creates a new output interface
// that marshals JSON objects as lines to a writer
func NewJSONInterface(level Level, yes bool, out io.Writer) *Interface {
	return NewInterface(level, &jsonHandler{
		level: level,
		yes:   yes,
		out:   out,
	})
}

// ReplayFromJSON reads the output from a JSON output
// interface and replays it on another output interface,
// optionally capturing the result in an output object
func ReplayFromJSON(r io.Reader, in *Interface, result interface{}) {
	ops := map[int]Operation{}
	streams := map[string]*Stream{}

	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		var o jsonObject
		if err := json.Unmarshal(scanner.Bytes(), &o); err != nil {
			continue
		}

		switch o.Type {
		case "info":
			in.Info("%s", o.Content)
		case "verbose":
			in.Verbose("%s", o.Content)
		case "debug":
			in.Debug("%s", o.Content)
		case "warning":
			in.Warning("%s", o.Content)
		case "error":
			in.Error("%s", o.Content)
		case "start":
			ops[o.Operation] = in.Start("%s", o.Content)
		case "progress":
			ops[o.Operation].Progress("%s", o.Content)
		case "aborted":
			ops[o.Operation].Aborted()
			delete(ops, o.Operation)
		case "failed":
			ops[o.Operation].Failed()
			delete(ops, o.Operation)
		case "done":
			ops[o.Operation].Done()
			delete(ops, o.Operation)
		}

		if strings.HasSuffix(o.Type, "Stream") || strings.HasSuffix(o.Type, "StreamErr") {
			key := fmt.Sprintf("%s\n%s", o.Label, o.Type)
			s, ok := streams[key]
			if !ok {
				level := LevelNormal
				err := false
				switch o.Type {
				case "verboseStream":
					level = LevelVerbose
				case "debugStream":
					level = LevelDebug
				case "streamErr":
					err = true
				case "verboseStreamErr":
					level = LevelVerbose
					err = true
				case "debugStreamErr":
					level = LevelDebug
					err = true
				}
				streams[key] = in.NewStream(o.Label, level, err)
				s = streams[key]
			}
			fmt.Fprintln(s, o.Content)
		}

		switch o.Type {
		case "object":
			in.Object(LevelNormal, o.Content)
		case "verboseObject":
			in.Object(LevelVerbose, o.Content)
		case "debugObject":
			in.Object(LevelDebug, o.Content)
		case "result":
			if result == nil {
				in.Result(o.Content)
			} else if data, err := json.Marshal(o.Content); err != nil {
				in.Result(o.Content)
			} else if err := json.Unmarshal(data, result); err != nil {
				in.Result(o.Content)
			}
		}
	}
}


<|start_filename|>pkg/output/standard.go<|end_filename|>
package output

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/ghodss/yaml"
)

// StdObjectFormat represents a standard output interface object format
type StdObjectFormat int

// Standard output interface object formats
const (
	StdObjectFormatYAML = StdObjectFormat(0)
	StdObjectFormatJSON = StdObjectFormat(1)
)

// StdOptions represents standard output interface options
type StdOptions struct {
	AcceptPrompts bool
	ObjectFormat  StdObjectFormat
}

type stdHandler struct {
	level  Level
	opt    *StdOptions
	out    io.Writer
	err    io.Writer
	cout   *console
	cerr   *console
	clines int
}

func (h *stdHandler) writers(err bool) (w io.Writer, c *console, fd string) {
	w = h.out
	c = h.cout
	if h.out == h.err {
		fd = "1:"
	}

	if err {
		w = h.err
		c = h.cerr
		if h.out == h.err {
			fd = "2:"
		}
	}

	return
}

func (h *stdHandler) write(err bool, format string, v ...interface{}) {
	w, c, fd := h.writers(err)
	if w == nil {
		return
	}

	line := fmt.Sprintf("%s%s", fd, fmt.Sprintf(format, v...))

	fmt.Fprintln(w, line)

	if c != nil {
		width := c.Width()
		length := len(line)
		h.clines += length / width
		if length%width != 0 {
			h.clines++
		}
	}
}

func (h *stdHandler) Message(level Level, format string, v ...interface{}) {
	if level > LevelVerbose {
		_, file, line, ok := runtime.Caller(3)
		if !ok {
			file = "unknown"
			line = 0
		}
		file = filepath.Base(file)
		format = fmt.Sprintf("[%s:%d]: %s", file, line, format)
	}
	h.write(level > LevelVerbose, format, v...)
}

func (h *stdHandler) Warning(format string, v ...interface{}) {
	h.write(true, "Warning: "+format, v...)
}

func (h *stdHandler) Error(format string, v ...interface{}) {
	h.write(true, "Error: "+format, v...)
}

func (h *stdHandler) Prompt(format string, v ...interface{}) bool {
	w, c, fd := h.writers(false)
	if w == nil {
		return h.opt.AcceptPrompts
	}

	line := fmt.Sprintf("%s%s [y/N]: ", fd, fmt.Sprintf(format, v...))

	fmt.Fprint(w, line)

	var accept bool
	if !h.opt.AcceptPrompts {
		r := bufio.NewReader(os.Stdin)
		l, _ := r.ReadString('\n')
		if !strings.HasSuffix(l, "\n") {
			fmt.Fprintln(w)
		}
		l = strings.TrimSuffix(l, "\n")
		l = strings.TrimSuffix(l, "\r")
		line += l
		accept = l == "Y" || l == "y"
	} else {
		line += "Y"
		fmt.Fprintln(w, "Y")
		accept = true
	}

	if c != nil {
		width := c.Width()
		length := len(line)
		h.clines += length / width
		if length%width != 0 {
			h.clines++
		}
	}

	return accept
}

type stdOperation struct {
	h      *stdHandler
	w      io.Writer
	c      *console
	line   int
	action string
}

func (o *stdOperation) fit(width int, format string, v ...interface{}) string {
	s := fmt.Sprintf(format, v...)

	if len(s) > width-1 {
		s = s[:width-1]
	}

	return s
}

func (h *stdHandler) Start(format string, v ...interface{}) Operation {
	w, c, fd := h.writers(false)

	line := 0
	if c != nil {
		line = h.clines
	}

	o := &stdOperation{
		h:      h,
		w:      w,
		c:      c,
		line:   line,
		action: fd + fmt.Sprintf(format, v...),
	}

	action := fmt.Sprintf("%s...", o.action)
	if c != nil {
		action = o.fit(c.Width(), action)
	}

	if w != nil {
		fmt.Fprintln(w, action)
	}

	if c != nil {
		h.clines++
	}

	return o
}

const (
	ansiColorRed     = 31
	ansiColorGreen   = 32
	ansiColorMagenta = 35
)

func (o *stdOperation) writeStatus(color int, status string) {
	h := o.h
	w := o.w
	c := o.c

	if c != nil {
		c.SetRaw()
		defer c.Reset()
		width := c.Width()
		action := o.fit(width, "%s...", o.action)
		status := o.fit(width-len(action), status)
		fmt.Fprint(w, "\r")                         // move to start of line
		fmt.Fprintf(w, "\x1b[%dA", h.clines-o.line) // move up # rows
		fmt.Fprint(w, "\x1b[K")                     // erase line
		fmt.Fprint(w, action)                       // write action
		fmt.Fprintf(w, "\x1b[%dm", color)           // set foreground color
		fmt.Fprint(w, status)                       // write status
		fmt.Fprint(w, "\x1b[m")                     // reset foreground color
		fmt.Fprint(w, "\r")                         // move to start of line
		fmt.Fprintf(w, "\x1b[%dB", h.clines-o.line) // move down # rows
	} else if w != nil {
		fmt.Fprintf(w, "%s: %s\n", o.action, status)
	}
}

func (o *stdOperation) Progress(format string, v ...interface{}) {
	o.writeStatus(ansiColorMagenta, fmt.Sprintf(format, v...))
}

func (o *stdOperation) Aborted() {
	o.writeStatus(ansiColorRed, "aborted")
}

func (o *stdOperation) Failed() {
	o.writeStatus(ansiColorRed, "failed")
}

func (o *stdOperation) Done() {
	o.writeStatus(ansiColorGreen, "done")
}

func (h *stdHandler) NewWriter(label string, level Level, err bool) io.WriteCloser {
	var prefix string
	if label != "" {
		prefix = fmt.Sprintf("[%s] ", label)
	}

	return NewLineWriter(func(line string) {
		h.write(err, "%s%s", prefix, line)
	})
}

func (h *stdHandler) Object(level Level, o interface{}) {
	w, c, fd := h.writers(false)

	if w == nil {
		return
	}

	var data []byte
	var err error
	switch h.opt.ObjectFormat {
	case StdObjectFormatYAML:
		data, err = yaml.Marshal(o)
	case StdObjectFormatJSON:
		data, err = json.MarshalIndent(o, "", "    ")
	}
	if err != nil {
		return
	}

	if fd != "" {
		data = append([]byte(fd), data...)
		data = bytes.ReplaceAll(data, []byte{'\n'}, append([]byte{'\n'}, []byte(fd)...))
		if len(data) > len(fd) && data[len(data)-len(fd)-1] == '\n' {
			data = data[:len(data)-len(fd)]
		}
	}

	w.Write(data)

	if c != nil {
		width := c.Width()
		lines := bytes.Split(data, []byte{'\n'})
		for _, line := range lines {
			length := len(string(line))
			h.clines += length / width
			if length%width != 0 {
				h.clines++
			}
		}
	}

	if h.opt.ObjectFormat == StdObjectFormatJSON {
		fmt.Fprintln(w)
	}
}

func (h *stdHandler) Result(o interface{}) {
	h.Object(LevelNormal, o)
}

func (h *stdHandler) Close() error {
	return nil
}

// NewStdInterface creates a new output interface that
// formats output to standard output and error writers
func NewStdInterface(level Level, opt *StdOptions, out io.Writer, err io.Writer) *Interface {
	if opt == nil {
		opt = &StdOptions{}
	}

	var cout *console
	var cerr *console
	if level == LevelNormal {
		if cout = getConsole(out); cout != nil && cout.Width() == 0 {
			cout = nil
		}
		if cerr = getConsole(err); cerr != nil && cerr.Width() == 0 {
			cerr = nil
		}
	}

	return NewInterface(level, &stdHandler{
		level: level,
		opt:   opt,
		out:   out,
		err:   err,
		cout:  cout,
		cerr:  cerr,
	})
}


<|start_filename|>pkg/output/console_darwin.go<|end_filename|>
// +build darwin

package output

import (
	"golang.org/x/sys/unix"
)

const (
	ioctlTcGet = unix.TIOCGETA
	ioctlTcSet = unix.TIOCSETA
)
