<|start_filename|>internal/cmdutil/args.go<|end_filename|>
package cmdutil

import (
	"os"
	"path/filepath"
)

func WorkingDirFromArg(args []string, indexPosition int) (wd string, err error) {
	if wd, err = os.Getwd(); err != nil {
		return
	}
	if wd, err = filepath.Abs(wd); err != nil {
		return
	}
	if len(args) < indexPosition+1 {
		return
	}

	argWd := args[indexPosition]
	if argWd == "" {
		return
	}

	if filepath.IsAbs(argWd) {
		return argWd, nil
	}

	wd = filepath.Join(wd, argWd)
	return
}


<|start_filename|>internal/build/imgsrc/archive_test.go<|end_filename|>
package imgsrc

import (
	"archive/tar"
	"io"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/docker/docker/pkg/archive"
	"github.com/stretchr/testify/assert"
)

func newTestDir(filenames ...string) (tempDir string, err error) {
	tempDir, err = os.MkdirTemp("", "")
	if err != nil {
		return
	}

	defer func() {
		if err != nil {
			os.RemoveAll(tempDir)
		}
	}()

	for _, filename := range filenames {
		content := []byte(filename)
		filename = filepath.Join(tempDir, filename)
		err = os.MkdirAll(filepath.Dir(filename), 0777)
		if err != nil {
			return
		}

		err = os.WriteFile(filename, content, 0777)
		if err != nil {
			return
		}

	}

	return
}

func unpackTar(r io.ReadCloser) ([]string, map[string][]byte, error) {
	tr := tar.NewReader(r)

	names := []string{}
	out := map[string][]byte{}

	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, nil, err
		}

		if hdr.Typeflag != tar.TypeReg {
			continue
		}

		names = append(names, hdr.Name)

		data, err := io.ReadAll(tr)
		if err != nil {
			return nil, nil, err
		}
		out[hdr.Name] = data
	}

	return names, out, nil
}

func TestArchiver(t *testing.T) {
	testDir, err := newTestDir("a.jpg", "content/foo.md", "images/a.jpg", "images/b.jpg")
	assert.NoError(t, err)
	defer os.RemoveAll(testDir)

	r, err := archiveDirectory(archiveOptions{
		sourcePath: testDir,
	})
	assert.NoError(t, err)

	names, _, err := unpackTar(r)
	assert.NoError(t, err)

	assert.ElementsMatch(t, names, []string{"a.jpg", "content/foo.md", "images/a.jpg", "images/b.jpg"})
}

func TestArchiverExcludes(t *testing.T) {
	testDir, err := newTestDir("a.jpg", "content/foo.md", "images/a.jpg", "images/b.jpg")
	assert.NoError(t, err)
	defer os.RemoveAll(testDir)

	r, err := archiveDirectory(archiveOptions{
		sourcePath: testDir,
		exclusions: []string{"**/*.jpg"},
	})
	assert.NoError(t, err)

	names, _, err := unpackTar(r)
	assert.NoError(t, err)

	assert.ElementsMatch(t, names, []string{"content/foo.md"})
}

func TestArchiverAdditions(t *testing.T) {
	testDir, err := newTestDir("a.jpg", "content/foo.md", "images/a.jpg", "images/b.jpg")
	assert.NoError(t, err)
	defer os.RemoveAll(testDir)

	r, err := archiveDirectory(archiveOptions{
		sourcePath: testDir,
		additions: map[string][]byte{
			"Dockerfile": []byte("this is a dockerfile"),
		},
	})
	assert.NoError(t, err)

	names, contents, err := unpackTar(r)
	assert.NoError(t, err)

	assert.Contains(t, names, "Dockerfile")
	assert.Equal(t, []byte("this is a dockerfile"), contents["Dockerfile"])
}

func TestArchiverCompression(t *testing.T) {
	testDir, err := newTestDir("a.jpg", "content/foo.md", "images/a.jpg", "images/b.jpg")
	assert.NoError(t, err)
	defer os.RemoveAll(testDir)

	r, err := archiveDirectory(archiveOptions{sourcePath: testDir, compressed: true})
	assert.NoError(t, err)
	data, err := io.ReadAll(r)
	assert.NoError(t, err)
	assert.Equal(t, archive.Gzip, archive.DetectCompression(data))

	r, err = archiveDirectory(archiveOptions{sourcePath: testDir, compressed: false})
	assert.NoError(t, err)
	data, err = io.ReadAll(r)
	assert.NoError(t, err)
	assert.Equal(t, archive.Uncompressed, archive.DetectCompression(data))
}

func TestArchiverNoCompressionWithAdditions(t *testing.T) {
	testDir, err := newTestDir("a.jpg", "content/foo.md", "images/a.jpg", "images/b.jpg")
	assert.NoError(t, err)
	defer os.RemoveAll(testDir)

	r, err := archiveDirectory(archiveOptions{sourcePath: testDir, compressed: true, additions: map[string][]byte{
		"Dockerfile": []byte("this is a dockerfile"),
	}})
	assert.NoError(t, err)
	data, err := io.ReadAll(r)
	assert.NoError(t, err)
	assert.Equal(t, archive.Uncompressed, archive.DetectCompression(data))
}

func TestParseDockerignore(t *testing.T) {
	cases := map[string][]string{
		"node_modules\n*.jpg":                {"node_modules", "*.jpg", "fly.toml"},
		"node_modules\n*.jpg\nDockerfile":    {"node_modules", "*.jpg", "Dockerfile", "fly.toml", "![Dd]ockerfile"},
		"node_modules\n*.jpg\ndockerfile":    {"node_modules", "*.jpg", "dockerfile", "fly.toml", "![Dd]ockerfile"},
		"node_modules\n*.jpg\n.dockerignore": {"node_modules", "*.jpg", ".dockerignore", "fly.toml", "!.dockerignore"},
	}

	for input, expected := range cases {
		excludes, err := parseDockerignore(strings.NewReader(input))
		assert.NoError(t, err)
		assert.Equal(t, expected, excludes, input)
	}
}

func TestIsPathInRoot(t *testing.T) {
	cases := []struct {
		filename string
		rootDir  string
		rooted   bool
	}{
		{filename: "Dockerfile", rootDir: "/a/b/c", rooted: true},
		{filename: "../Dockerfile", rootDir: "/a/b/c", rooted: false},
		{filename: "path/to/Dockerfile", rootDir: "/a/b/c", rooted: true},
		{filename: "/a/b/c/Dockerfile", rootDir: "/a/b/c", rooted: true},
		{filename: "/a/b/c/path/to/Dockerfile", rootDir: "/a/b/c", rooted: true},
		{filename: "/Dockerfile", rootDir: "/a/b/c", rooted: false},
		{filename: "/a/b/c/../Dockerfile", rootDir: "/a/b/c", rooted: false},
		{filename: "/a/b/c/path/to/../../../Dockerfile", rootDir: "/a/b/c", rooted: false},
	}

	for _, c := range cases {
		assert.Equal(t, c.rooted, isPathInRoot(c.filename, c.rootDir), "target: %s root:%s", c.filename, c.rootDir)
	}

}


<|start_filename|>Dockerfile<|end_filename|>
FROM golang:alpine as build
RUN apk --no-cache add ca-certificates

FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY flyctl /
ENTRYPOINT ["/flyctl"]


<|start_filename|>docstrings/docstrings.go<|end_filename|>
package docstrings

//go:generate sh ../scripts/helpgen.sh

// KeyStrings - Struct for help string storage
type KeyStrings struct {
	Usage string
	Short string
	Long  string
}


<|start_filename|>pkg/logs/entry.go<|end_filename|>
package logs

type LogEntry struct {
	Level     string `json:"level"`
	Instance  string `json:"instance"`
	Message   string `json:"message"`
	Region    string `json:"region"`
	Timestamp string `json:"timestamp"`
	Meta      Meta   `json:"meta"`
}

type Meta struct {
	Instance string
	Region   string
	Event    struct {
		Provider string
	}
	HTTP struct {
		Request struct {
			ID      string
			Method  string
			Version string
		}
		Response struct {
			StatusCode int `json:"status_code"`
		}
	}
	Error struct {
		Code    int
		Message string
	}
	URL struct {
		Full string
	}
}

type natsLog struct {
	Event struct {
		Provider string `json:"provider"`
	} `json:"event"`
	Fly struct {
		App struct {
			Instance string `json:"instance"`
			Name     string `json:"name"`
		} `json:"app"`
		Region string `json:"region"`
	} `json:"fly"`
	Host string `json:"host"`
	Log  struct {
		Level string `json:"level"`
	} `json:"log"`
	Message   string `json:"message"`
	Timestamp string `json:"timestamp"`
}


<|start_filename|>helpers/duration.go<|end_filename|>
package helpers

import (
	"math"
	"time"
)

func Duration(d time.Duration, dicimal int) time.Duration {
	shift := int(math.Pow10(dicimal))

	units := []time.Duration{time.Second, time.Millisecond, time.Microsecond, time.Nanosecond}
	for _, u := range units {
		if d > u {
			div := u / time.Duration(shift)
			if div == 0 {
				break
			}
			d = d / div * div
			break
		}
	}

	return d
}


<|start_filename|>cmd/presenters/env.go<|end_filename|>
package presenters

import (
	"fmt"
)

type Environment struct {
	Envs map[string]interface{}
}

func (p *Environment) APIStruct() interface{} {
	return nil
}
func (p *Environment) FieldNames() []string {
	return []string{"Name", "Value"}
}

func (p *Environment) Records() []map[string]string {
	out := []map[string]string{}

	for key, value := range p.Envs {
		out = append(out, map[string]string{
			"Name":  key,
			"Value": fmt.Sprintf("%v", value),
		})
	}
	return out
}


<|start_filename|>pkg/ssh/terminal_unix.go<|end_filename|>
//go:build !windows
// +build !windows

package ssh

import (
	"context"
	"os"
	"os/signal"
	"syscall"

	"golang.org/x/crypto/ssh"
	"golang.org/x/term"
)

func watchWindowSize(ctx context.Context, fd int, sess *ssh.Session) error {
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGWINCH)

	for {
		select {
		case <-sigc:
		case <-ctx.Done():
			return nil
		}

		width, height, err := term.GetSize(fd)
		if err != nil {
			return err
		}

		if err := sess.WindowChange(height, width); err != nil {
			return err
		}
	}
}


<|start_filename|>flyctl/machine_config.go<|end_filename|>
package flyctl

type MachineConfig struct {
	AppName string
	Config  map[string]interface{}
}

func NewMachineConfig() *MachineConfig {
	return &MachineConfig{
		Config: map[string]interface{}{},
	}
}

func (mc *MachineConfig) SetEnvVariables(vals map[string]string) {
	var env map[string]string

	if rawEnv, ok := mc.Config["env"]; ok {
		if castEnv, ok := rawEnv.(map[string]string); ok {
			env = castEnv
		}
	}
	if env == nil {
		env = map[string]string{}
	}

	for k, v := range vals {
		env[k] = v
	}

	mc.Config["env"] = env
}


<|start_filename|>api/resource_logs.go<|end_filename|>
package api

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
)

type getLogsResponse struct {
	Data []struct {
		Id         string
		Attributes LogEntry
	}
	Meta struct {
		NextToken string `json:"next_token"`
	}
}

func (c *Client) GetAppLogs(appName string, nextToken string, region string, instanceId string) ([]LogEntry, string, error) {

	data := url.Values{}
	data.Set("next_token", nextToken)
	if instanceId != "" {
		data.Set("instance", instanceId)
	}
	if region != "" {
		data.Set("region", region)
	}

	url := fmt.Sprintf("%s/api/v1/apps/%s/logs?%s", baseURL, appName, data.Encode())
	entries := []LogEntry{}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return entries, "", err
	}
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.accessToken))

	var result getLogsResponse

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return entries, "", err
	}

	if resp.StatusCode != 200 {
		return entries, "", ErrorFromResp(resp)
	}

	defer resp.Body.Close()

	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return entries, "", err
	}

	for _, d := range result.Data {
		entries = append(entries, d.Attributes)
	}

	return entries, result.Meta.NextToken, nil
}


<|start_filename|>internal/build/imgsrc/errors.go<|end_filename|>
package imgsrc

import "fmt"

type RegistryUnauthorizedError struct {
	Tag string
}

func (err *RegistryUnauthorizedError) Error() string {
	return fmt.Sprintf("you are not authorized to push \"%s\"", err.Tag)
}


<|start_filename|>example/Dockerfile<|end_filename|>
FROM nginx:alpine

RUN sed -i 's/    listen       80;/    listen       8080;/g' /etc/nginx/conf.d/default.conf

ARG SOURCE_DIR=.
ARG APP_DIR=/usr/share/nginx/html
ARG ENTRY_FILE=index.html

COPY release.sh /release.sh
COPY ${SOURCE_DIR} ${APP_DIR}

ENV NGINX_PORT=8080

<|start_filename|>internal/cmdfmt/messages.go<|end_filename|>
package cmdfmt

import (
	"fmt"
	"io"

	"github.com/logrusorgru/aurora"
)

// extract message printing from cmdctx until we find a better way to do this

func PrintBegin(w io.Writer, args ...interface{}) {
	fmt.Fprintln(w, aurora.Green("==> "+fmt.Sprint(args...)))
}

func PrintDone(w io.Writer, args ...interface{}) {
	fmt.Fprintln(w, aurora.Gray(20, "--> "+fmt.Sprint(args...)))
}


<|start_filename|>internal/build/imgsrc/archive.go<|end_filename|>
package imgsrc

import (
	"archive/tar"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/docker/docker/builder/dockerignore"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/fileutils"
)

type archiveOptions struct {
	sourcePath string
	exclusions []string
	compressed bool
	additions  map[string][]byte
}

func archiveDirectory(options archiveOptions) (io.ReadCloser, error) {
	opts := &archive.TarOptions{
		ExcludePatterns: options.exclusions,
	}
	if options.compressed && len(options.additions) == 0 {
		opts.Compression = archive.Gzip
	}

	r, err := archive.TarWithOptions(options.sourcePath, opts)
	if err != nil {
		return nil, err
	}

	if options.additions != nil {
		mods := map[string]archive.TarModifierFunc{}
		for name, contents := range options.additions {
			mods[name] = func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
				newHeader := &tar.Header{
					Name: name,
					Size: int64(len(contents)),
				}

				return newHeader, contents, nil
			}
		}

		r = archive.ReplaceFileTarWrapper(r, mods)
	}

	return r, nil
}

func readDockerignore(workingDir string) ([]string, error) {
	file, err := os.Open(filepath.Join(workingDir, ".dockerignore"))
	if os.IsNotExist(err) {
		return []string{}, nil
	} else if err != nil {
		return nil, err
	}
	defer file.Close()

	return parseDockerignore(file)
}

func parseDockerignore(r io.Reader) ([]string, error) {
	excludes, err := dockerignore.ReadAll(r)
	if err != nil {
		return nil, err
	}

	if match, _ := fileutils.Matches("fly.toml", excludes); !match {
		excludes = append(excludes, "fly.toml")
	}

	if match, _ := fileutils.Matches(".dockerignore", excludes); match {
		excludes = append(excludes, "!.dockerignore")
	}

	if match, _ := fileutils.Matches("Dockerfile", excludes); match {
		excludes = append(excludes, "![Dd]ockerfile")
	}

	if match, _ := fileutils.Matches("dockerfile", excludes); match {
		excludes = append(excludes, "![Dd]ockerfile")
	}

	return excludes, nil
}

func isPathInRoot(target, rootDir string) bool {
	rootDir, _ = filepath.Abs(rootDir)
	if !filepath.IsAbs(target) {
		target = filepath.Join(rootDir, target)
	}

	rel, err := filepath.Rel(rootDir, target)
	if err != nil {
		return false
	}
	return !strings.HasPrefix(filepath.ToSlash(rel), "../")
}


<|start_filename|>internal/build/imgsrc/builtins/builtinsupport.go<|end_filename|>
package builtins

import (
	"fmt"
	"strings"
	"text/template"
)

// Setting is a simple holder for names and defaults in Settings
type Setting struct {
	Name        string
	Default     interface{}
	Description string
}

// Builtin - Definition of a Fly Builtin Builder
type Builtin struct {
	Name        string
	Description string
	Details     string
	Template    string
	Settings    []Setting
	settingsMap map[string]Setting
}

// GetBuiltin - Finds the Builtin by name
func GetBuiltin(builtinname string) (*Builtin, error) {
	for _, builtin := range basicbuiltins {
		if builtin.Name == builtinname {
			return &builtin, nil
		}
	}

	return nil, fmt.Errorf("no builtin with %s name supported", builtinname)
}

// ResolveSettings - Given defaults abd values return actural settings
func (b *Builtin) ResolveSettings(vars map[string]interface{}) map[string]interface{} {
	resolvedSettings := make(map[string]interface{}, len(vars))

	for k, v := range vars {
		if b.Settings != nil {
			for _, setting := range b.Settings {
				if setting.Name == k {
					// This is good to add
					resolvedSettings[k] = v
					break
				}
			}
		}
	}

	// settings now has all the values which were in settings, but no others

	// Now scan settings for any value not set and copy the default over
	for _, setting := range b.Settings {
		_, found := resolvedSettings[setting.Name]
		if !found {
			// This is good to set to default
			resolvedSettings[setting.Name] = setting.Default
		}
	}

	return resolvedSettings
}

// GetVDockerfile - given an map of variables, get the definition and populate it
func (b *Builtin) GetVDockerfile(vars map[string]interface{}) (string, error) {
	template, err := template.New("builtin").Parse(b.Template)

	if err != nil {
		return "", err
	}

	// Now the create the proper vars from
	// If it's set in the vars map, set it in the settings map

	settings := b.ResolveSettings(vars)

	result := strings.Builder{}

	err = template.Execute(&result, settings)
	if err != nil {
		return "", err
	}

	return result.String(), nil
}

// GetSetting - Gets the Setting structure for a named setting
func (b *Builtin) GetSetting(name string) Setting {
	if len(b.settingsMap) != len(b.Settings) {
		b.settingsMap = make(map[string]Setting)
		for _, a := range b.Settings {
			b.settingsMap[a.Name] = a
		}
	}

	return b.settingsMap[name]
}

// GetBuiltins - Get an array of all the builtins
func GetBuiltins() []Builtin {
	return basicbuiltins
}


<|start_filename|>api/error.go<|end_filename|>
package api

import "net/http"

type ApiError struct {
	WrappedError error
	Message      string
	Status       int
}

func (e *ApiError) Error() string { return e.Message }

func ErrorFromResp(resp *http.Response) *ApiError {
	return &ApiError{
		Message: resp.Status,
		Status:  resp.StatusCode,
	}
}

func IsNotAuthenticatedError(err error) bool {
	if apiErr, ok := err.(*ApiError); ok {
		return apiErr.Status == 401
	}
	return false
}

func IsNotFoundError(err error) bool {
	if apiErr, ok := err.(*ApiError); ok {
		return apiErr.Status == 404
	}
	return false
}

func IsServerError(err error) bool {
	if apiErr, ok := err.(*ApiError); ok {
		return apiErr.Status >= 500
	}
	return false
}

func IsClientError(err error) bool {
	if apiErr, ok := err.(*ApiError); ok {
		return apiErr.Status >= 400 && apiErr.Status < 500
	}
	return false
}


<|start_filename|>internal/cmdfmt/logging.go<|end_filename|>
package cmdfmt

const lineFeed = '\n'

// AppendMissingLineFeed adds \n to a line unless already present
func AppendMissingLineFeed(msg string) string {
	buff := []byte(msg)
	if len(buff) == 0 || buff[len(buff)-1] != lineFeed {
		buff = append(buff, lineFeed)
	}
	return string(buff)
}


<|start_filename|>internal/flyerr/flyerr.go<|end_filename|>
package flyerr

import (
	"context"
	"errors"
	"fmt"

	"github.com/logrusorgru/aurora"
)

// ErrAbort is an error for when the CLI aborts
var ErrAbort = errors.New("abort")

// ErrorDescription is an error with a detailed description that will be printed before the CLI exits
type ErrorDescription interface {
	error
	Description() string
}

func GetErrorDescription(err error) string {
	var ferr ErrorDescription
	if errors.As(err, &ferr) {
		return ferr.Description()
	}
	return ""
}

// ErrorSuggestion is an error with suggested next steps that will be printed before the CLI exits
type ErrorSuggestion interface {
	error
	Suggestion() string
}

func GetErrorSuggestion(err error) string {
	var ferr ErrorSuggestion
	if errors.As(err, &ferr) {
		return ferr.Suggestion()
	}
	return ""
}

func PrintCLIOutput(err error) {
	if err == nil {
		return
	}

	if IsCancelledError(err) {
		return
	}

	fmt.Println()
	fmt.Println(aurora.Red("Error"), err)

	description := GetErrorDescription(err)
	suggestion := GetErrorSuggestion(err)

	if description != "" {
		fmt.Printf("\n%s", description)
	}

	if suggestion != "" {
		if description != "" {
			fmt.Println()
		}
		fmt.Printf("\n%s", suggestion)
	}
	fmt.Println()
}

func IsCancelledError(err error) bool {
	if errors.Is(err, ErrAbort) {
		return true
	}

	if errors.Is(err, context.Canceled) {
		return true
	}

	// if err == cmd.ErrAbort {
	// 	return true
	// }

	// if err == context.Canceled {
	// 	return true
	// }

	// if merr, ok := err.(*multierror.Error); ok {
	// 	if len(merr.Errors) == 1 && merr.Errors[0] == context.Canceled {
	// 		return true
	// 	}
	// }

	return false
}


<|start_filename|>internal/cmdutil/terminal.go<|end_filename|>
package cmdutil

import (
	"os"

	"github.com/mattn/go-isatty"
)

func IsTerminal(f *os.File) bool {
	return isatty.IsTerminal(f.Fd()) || IsCygwinTerminal(f)
}

func IsCygwinTerminal(f *os.File) bool {
	return isatty.IsCygwinTerminal(f.Fd())
}


<|start_filename|>cmd/presenters/presenter.go<|end_filename|>
package presenters

import (
	"encoding/json"
	"fmt"
	"github.com/logrusorgru/aurora"
	"io"

	"github.com/olekukonko/tablewriter"
)

// Presentable - Records (and field names) which may be presented by a Presenter
type Presentable interface {
	FieldNames() []string
	Records() []map[string]string
	APIStruct() interface{}
}

// Presenter - A self managing presenter which can be rendered in multiple ways
type Presenter struct {
	Item Presentable
	Out  io.Writer
	Opts Options
}

// Options - Presenter options
type Options struct {
	Vertical   bool
	HideHeader bool
	Title      string
	AsJSON     bool
}

// Render - Renders a presenter as a field list or table
func (p *Presenter) Render() error {
	if p.Opts.AsJSON {
		return p.renderJSON()
	}

	if p.Opts.Vertical {
		return p.renderFieldList()
	}

	return p.renderTable()
}

func (p *Presenter) renderTable() error {
	if p.Opts.Title != "" {
		fmt.Fprintln(p.Out, aurora.Bold(p.Opts.Title))
	}

	table := tablewriter.NewWriter(p.Out)

	cols := p.Item.FieldNames()

	if !p.Opts.HideHeader {
		table.SetHeader(cols)
	}
	table.SetBorder(false)
	table.SetHeaderLine(false)
	table.SetAutoWrapText(false)
	table.SetAutoFormatHeaders(true)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetColumnSeparator(" ")
	table.SetNoWhiteSpace(true)
	table.SetTablePadding(" ") // pad with tabs

	for _, kv := range p.Item.Records() {
		fields := []string{}
		for _, col := range cols {
			fields = append(fields, kv[col])
		}
		table.Append(fields)
	}

	table.Render()

	fmt.Fprintln(p.Out)

	return nil
}

func (p *Presenter) renderFieldList() error {
	table := tablewriter.NewWriter(p.Out)

	if p.Opts.Title != "" {
		fmt.Fprintln(p.Out, aurora.Bold(p.Opts.Title))
	}
	cols := p.Item.FieldNames()

	table.SetBorder(false)
	table.SetAutoWrapText(false)
	table.SetColumnSeparator("=")
	table.SetColumnAlignment([]int{tablewriter.ALIGN_DEFAULT, tablewriter.ALIGN_LEFT})

	for _, kv := range p.Item.Records() {
		for _, col := range cols {
			table.Append([]string{col, kv[col]})
		}
		table.Render()

		fmt.Fprintln(p.Out)
	}

	return nil
}

func (p *Presenter) renderJSON() error {
	var data = p.Item.APIStruct()

	if data == nil {
		return fmt.Errorf("JSON output not available")
	}

	if p.Opts.Title == "" {
		prettyJSON, err := json.MarshalIndent(data, "", "    ")
		fmt.Fprintln(p.Out, string(prettyJSON))
		return err
	} else {
		wrapper := make(map[string]interface{}, 1)
		wrapper[p.Opts.Title] = p.Item.APIStruct()
		prettyJSON, err := json.MarshalIndent(wrapper, "", "    ")
		fmt.Fprintln(p.Out, string(prettyJSON))
		return err
	}
}


<|start_filename|>internal/flyerr/sentry.go<|end_filename|>
package flyerr

import "github.com/getsentry/sentry-go"

type CaptureOption func(scope *sentry.Scope)

func WithContext(key string, val interface{}) CaptureOption {
	return func(scope *sentry.Scope) {
		scope.SetContext(key, val)
	}
}

func WithContexts(contexts map[string]interface{}) CaptureOption {
	return func(scope *sentry.Scope) {
		scope.SetContexts(contexts)
	}
}

func WithTag(key, value string) CaptureOption {
	return func(scope *sentry.Scope) {
		scope.SetTag(key, value)
	}
}

func CaptureException(err error, opts ...CaptureOption) {
	sentry.WithScope(func(scope *sentry.Scope) {
		for _, opt := range opts {
			opt(scope)
		}
		sentry.CaptureException(err)
	})
}

func CaptureMessage(msg string, opts ...CaptureOption) {
	sentry.WithScope(func(scope *sentry.Scope) {
		for _, opt := range opts {
			opt(scope)
		}
		sentry.CaptureMessage(msg)
	})
}


<|start_filename|>internal/build/imgsrc/docker_test.go<|end_filename|>
package imgsrc

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestAllowedDockerDaemonMode(t *testing.T) {
	tests := []struct {
		allowLocal  bool
		allowRemote bool
		expected    DockerDaemonType
	}{
		{true, true, DockerDaemonTypeNone | DockerDaemonTypeLocal | DockerDaemonTypeRemote},
		{false, true, DockerDaemonTypeNone | DockerDaemonTypeRemote},
		{true, false, DockerDaemonTypeNone | DockerDaemonTypeLocal},
		{false, false, DockerDaemonTypeNone},
	}

	for _, test := range tests {
		m := NewDockerDaemonType(test.allowLocal, test.allowRemote)
		assert.Equal(t, test.expected, m)
	}
}


<|start_filename|>api/logger.go<|end_filename|>
package api

type Logger interface {
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
}

<|start_filename|>pkg/logs/logs.go<|end_filename|>
package logs

import (
	"context"
	"io"
	"time"
)

type LogOptions struct {
	W io.Writer

	MaxBackoff time.Duration
	AppName    string
	VMID       string
	RegionCode string
}

type LogStream interface {
	Err() error
	Stream(ctx context.Context, opts *LogOptions) <-chan LogEntry
}


<|start_filename|>pkg/ssh/client.go<|end_filename|>
package ssh

import (
	"context"
	"errors"
	"log"
	"net"

	"golang.org/x/crypto/ssh"
)

type Client struct {
	Addr string
	User string

	Dial func(ctx context.Context, network, addr string) (net.Conn, error)

	PrivateKey, Certificate string

	client *ssh.Client
	conn   ssh.Conn
}

func (c *Client) Close() error {
	if c.conn != nil {
		if err := c.conn.Close(); err != nil {
			return err
		}
	}

	c.conn = nil
	return nil
}

func (c *Client) Connect(ctx context.Context) error {
	pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(c.Certificate))
	if err != nil {
		return err
	}

	cert, ok := pubKey.(*ssh.Certificate)
	if !ok {
		return errors.New("SSH public key must be a certificate")
	}

	keySigner, err := ssh.ParsePrivateKey([]byte(c.PrivateKey))
	if err != nil {
		return err
	}

	signer, err := ssh.NewCertSigner(cert, keySigner)
	if err != nil {
		log.Fatal(err)
	}

	tcpConn, err := c.Dial(ctx, "tcp", c.Addr)
	if err != nil {
		return err
	}

	conf := &ssh.ClientConfig{
		User: c.User,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(signer),
		},
		HostKeyCallback:   ssh.InsecureIgnoreHostKey(),
		HostKeyAlgorithms: []string{ssh.KeyAlgoED25519},
	}

	conn, chans, reqs, err := ssh.NewClientConn(tcpConn, tcpConn.RemoteAddr().String(), conf)
	if err != nil {
		return err
	}

	c.conn, c.client = conn, ssh.NewClient(conn, chans, reqs)
	return nil
}

func (c *Client) Shell(ctx context.Context, term *Terminal, cmd string) error {
	if c.client == nil {
		if err := c.Connect(ctx); err != nil {
			return err
		}
	}

	sess, err := c.client.NewSession()
	if err != nil {
		return err
	}
	defer sess.Close()

	return term.attach(ctx, sess, cmd)
}


<|start_filename|>internal/sourcecode/templates/deno/Dockerfile<|end_filename|>
# Based on https://github.com/denoland/deno_docker/blob/main/alpine.dockerfile

ARG DENO_VERSION=1.14.0
ARG BIN_IMAGE=denoland/deno:bin-${DENO_VERSION}
FROM ${BIN_IMAGE} AS bin

FROM frolvlad/alpine-glibc:alpine-3.13

RUN apk --no-cache add ca-certificates

RUN addgroup --gid 1000 deno \
  && adduser --uid 1000 --disabled-password deno --ingroup deno \
  && mkdir /deno-dir/ \
  && chown deno:deno /deno-dir/

ENV DENO_DIR /deno-dir/
ENV DENO_INSTALL_ROOT /usr/local

ARG DENO_VERSION
ENV DENO_VERSION=${DENO_VERSION}
COPY --from=bin /deno /bin/deno

WORKDIR /deno-dir
COPY . .

ENTRYPOINT ["/bin/deno"]
CMD ["run", "--allow-net", "https://deno.land/std/examples/echo_server.ts"]


<|start_filename|>internal/buildinfo/version_test.go<|end_filename|>
package buildinfo

import (
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestProdMeta(t *testing.T) {
	environment = "production"
	version = "1.2.3"
	buildDate = "2020-06-05T13:32:23Z"
	commit = "c8f7b8f"

	loadMeta()

	assert.Equal(t, "1.2.3", Version().String())
	assert.Equal(t, "2020-06-05T13:32:23Z", BuildDate().Format(time.RFC3339))
	assert.Equal(t, "c8f7b8f", Commit())
}

func TestDevMeta(t *testing.T) {
	environment = "development"
	version = "<version>"
	commit = "<commit>"

	loadMeta()

	assert.Equal(t, fmt.Sprintf("0.0.0-%d+dev", BuildDate().Unix()), Version().String())
	assert.Equal(t, "<commit>", Commit())
}


<|start_filename|>api/casting.go<|end_filename|>
package api

// IntPointer - Returns a pointer to an int
func IntPointer(val int) *int {
	return &val
}

// BoolPointer - Returns a pointer to a bool
func BoolPointer(val bool) *bool {
	return &val
}

// StringPointer - Returns a pointer to a string
func StringPointer(val string) *string {
	return &val
}


<|start_filename|>pkg/retry/retry_test.go<|end_filename|>
package retry

import (
	"errors"
	"testing"

	"github.com/stretchr/testify/assert"
)

var errFail = errors.New("fail")

func TestRetry(t *testing.T) {
	t.Parallel()
	t.Run("testSuccess", testSuccess)
	t.Run("testFail1", testFail1)
	t.Run("testFail2", testFail2)
	t.Run("testFailAll", testFailAll)
}

func testSuccess(t *testing.T) {
	var count int

	fn := func() error {
		count++
		return nil
	}

	err := Retry(fn, 3)
	assert.NoError(t, err)
	assert.Equal(t, 1, count)
}

func testFail1(t *testing.T) {
	var count int

	fn := func() error {
		count++
		if count == 1 {
			return errors.New("1")
		}
		return nil
	}

	err := Retry(fn, 3)
	assert.NoError(t, err)
	assert.Equal(t, 2, count)
}

func testFail2(t *testing.T) {
	var count int

	fn := func() error {
		count++
		if count <= 2 {
			return errFail
		}
		return nil
	}

	err := Retry(fn, 3)
	assert.NoError(t, err)
	assert.Equal(t, 3, count)
}

func testFailAll(t *testing.T) {
	var count int

	fn := func() error {
		count++
		return errFail
	}

	err := Retry(fn, 3)
	assert.ErrorIs(t, err, errFail)
	assert.Equal(t, 3, count)
}


<|start_filename|>internal/buildinfo/buildinfo.go<|end_filename|>
package buildinfo

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"time"

	"github.com/blang/semver"
)

var cachedName string // populated during init

func init() {
	var err error
	if cachedName, err = os.Executable(); err != nil {
		panic(err)
	}
	cachedName = filepath.Base(cachedName)
}

// Name returns the name for the executable that started the current
// process.
//
// Name is safe for concurrent use.
func Name() string {
	return cachedName
}

type info struct {
	Name         string
	Version      semver.Version
	Commit       string
	BuildDate    time.Time
	OS           string
	Architecture string
	Environment  string
}

func (i info) String() string {
	return fmt.Sprintf("%s v%s %s/%s Commit: %s BuildDate: %s",
		i.Name,
		i.Version,
		i.OS,
		i.Architecture,
		i.Commit,
		i.BuildDate.Format(time.RFC3339))
}

func Info() info {
	return info{
		Name:         Name(),
		Version:      Version(),
		Commit:       Commit(),
		BuildDate:    BuildDate(),
		OS:           OS(),
		Architecture: Arch(),
		Environment:  Environment(),
	}
}

func OS() string {
	return runtime.GOOS
}

func Arch() string {
	return runtime.GOARCH
}


<|start_filename|>pkg/agent/prot.go<|end_filename|>
package agent

import (
	"encoding/binary"
	"fmt"
	"io"
)

func writef(w io.Writer, format string, args ...interface{}) error {
	cmd := fmt.Sprintf(format, args...)
	var lenb [2]byte

	binary.LittleEndian.PutUint16(lenb[:], uint16(len(cmd)))

	if _, err := w.Write(lenb[:]); err != nil {
		return fmt.Errorf("can't write len: %w", err)
	}

	if _, err := w.Write([]byte(cmd)); err != nil {
		return fmt.Errorf("can't write command: %w", err)
	}

	return nil
}

func read(r io.Reader) ([]byte, error) {
	var lenb [2]byte

	if _, err := io.ReadFull(r, lenb[:]); err != nil {
		return nil, fmt.Errorf("reading length: %w", err)
	}

	l := binary.LittleEndian.Uint16(lenb[:])

	buf := make([]byte, l)

	if _, err := io.ReadFull(r, buf); err != nil {
		return nil, fmt.Errorf("reading command: %w", err)
	}

	return buf, nil
}


<|start_filename|>deps/wintun/include/wintun.h<|end_filename|>
/* SPDX-License-Identifier: GPL-2.0 OR MIT
 *
 * Copyright (C) 2018-2021 WireGuard LLC. All Rights Reserved.
 */

#pragma once

#include <Windows.h>
#include <IPExport.h>
#include <ifdef.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * A handle representing Wintun adapter
 */
typedef void *WINTUN_ADAPTER_HANDLE;

/**
 * Maximum pool name length including zero terminator
 */
#define WINTUN_MAX_POOL 256

/**
 * Creates a new Wintun adapter.
 *
 * @param Pool          Name of the adapter pool. Zero-terminated string of up to WINTUN_MAX_POOL-1 characters.
 *
 * @param Name          The requested name of the adapter. Zero-terminated string of up to MAX_ADAPTER_NAME-1
 *                      characters.
 *
 * @param RequestedGUID The GUID of the created network adapter, which then influences NLA generation deterministically.
 *                      If it is set to NULL, the GUID is chosen by the system at random, and hence a new NLA entry is
 *                      created for each new adapter. It is called "requested" GUID because the API it uses is
 *                      completely undocumented, and so there could be minor interesting complications with its usage.
 *
 * @param RebootRequired  Optional pointer to a boolean flag to be set to TRUE in case SetupAPI suggests a reboot.
 *
 * @return If the function succeeds, the return value is the adapter handle. Must be released with WintunFreeAdapter. If
 *         the function fails, the return value is NULL. To get extended error information, call GetLastError.
 */
typedef _Return_type_success_(return != NULL) WINTUN_ADAPTER_HANDLE(WINAPI *WINTUN_CREATE_ADAPTER_FUNC)(
    _In_z_ const WCHAR *Pool,
    _In_z_ const WCHAR *Name,
    _In_opt_ const GUID *RequestedGUID,
    _Out_opt_ BOOL *RebootRequired);

/**
 * Opens an existing Wintun adapter.
 *
 * @param Pool          Name of the adapter pool. Zero-terminated string of up to WINTUN_MAX_POOL-1 characters.
 *
 * @param Name          Adapter name. Zero-terminated string of up to MAX_ADAPTER_NAME-1 characters.
 *
 * @return If the function succeeds, the return value is adapter handle. Must be released with WintunFreeAdapter. If the
 *         function fails, the return value is NULL. To get extended error information, call GetLastError. Possible
 *         errors include the following:
 *         ERROR_FILE_NOT_FOUND if adapter with given name is not found;
 *         ERROR_ALREADY_EXISTS if adapter is found but not a Wintun-class or not a member of the pool
 */
typedef _Return_type_success_(return != NULL)
    WINTUN_ADAPTER_HANDLE(WINAPI *WINTUN_OPEN_ADAPTER_FUNC)(_In_z_ const WCHAR *Pool, _In_z_ const WCHAR *Name);


/**
 * Deletes a Wintun adapter.
 *
 * @param Adapter            Adapter handle obtained with WintunOpenAdapter or WintunCreateAdapter.
 *
 * @param ForceCloseSessions Force close adapter handles that may be in use by other processes. Only set this to TRUE
 *                           with extreme care, as this is resource intensive and may put processes into an undefined
 *                           or unpredictable state. Most users should set this to FALSE.
 *
 * @param RebootRequired     Optional pointer to a boolean flag to be set to TRUE in case SetupAPI suggests a reboot.
 *
 * @return If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To
 *         get extended error information, call GetLastError.
 */
typedef _Return_type_success_(return != FALSE) BOOL(WINAPI *WINTUN_DELETE_ADAPTER_FUNC)(
    _In_ WINTUN_ADAPTER_HANDLE Adapter,
    _In_ BOOL ForceCloseSessions,
    _Out_opt_ BOOL *RebootRequired);

/**
 * Called by WintunEnumAdapters for each adapter in the pool.
 *
 * @param Adapter       Adapter handle, which will be freed when this function returns.
 *
 * @param Param         An application-defined value passed to the WintunEnumAdapters.
 *
 * @return Non-zero to continue iterating adapters; zero to stop.
 */
typedef BOOL(CALLBACK *WINTUN_ENUM_CALLBACK)(_In_ WINTUN_ADAPTER_HANDLE Adapter, _In_ LPARAM Param);

/**
 * Enumerates all Wintun adapters.
 *
 * @param Pool          Name of the adapter pool. Zero-terminated string of up to WINTUN_MAX_POOL-1 characters.
 *
 * @param Callback      Callback function. To continue enumeration, the callback function must return TRUE; to stop
 *                      enumeration, it must return FALSE.
 *
 * @param Param         An application-defined value to be passed to the callback function.
 *
 * @return If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To
 *         get extended error information, call GetLastError.
 */
typedef _Return_type_success_(return != FALSE) BOOL(
    WINAPI *WINTUN_ENUM_ADAPTERS_FUNC)(_In_z_ const WCHAR *Pool, _In_ WINTUN_ENUM_CALLBACK Callback, _In_ LPARAM Param);

/**
 * Releases Wintun adapter resources.
 *
 * @param Adapter       Adapter handle obtained with WintunOpenAdapter or WintunCreateAdapter.
 */
typedef void(WINAPI *WINTUN_FREE_ADAPTER_FUNC)(_In_ WINTUN_ADAPTER_HANDLE Adapter);

/**
 * Deletes all Wintun adapters in a pool and if there are no more adapters in any other pools, also removes Wintun
 * from the driver store, usually called by uninstallers.
 *
 * @param Pool             Name of the adapter pool. Zero-terminated string of up to WINTUN_MAX_POOL-1 characters.
 *
 * @param RebootRequired   Optional pointer to a boolean flag to be set to TRUE in case SetupAPI suggests a reboot.
 *
 * @return If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To
 *         get extended error information, call GetLastError.
 */
typedef _Return_type_success_(return != FALSE)
    BOOL(WINAPI *WINTUN_DELETE_POOL_DRIVER_FUNC)(_In_z_ const WCHAR *Pool, _Out_opt_ BOOL *RebootRequired);

/**
 * Returns the LUID of the adapter.
 *
 * @param Adapter       Adapter handle obtained with WintunOpenAdapter or WintunCreateAdapter
 *
 * @param Luid          Pointer to LUID to receive adapter LUID.
 */
typedef void(WINAPI *WINTUN_GET_ADAPTER_LUID_FUNC)(_In_ WINTUN_ADAPTER_HANDLE Adapter, _Out_ NET_LUID *Luid);

/**
 * Returns the name of the Wintun adapter.
 *
 * @param Adapter       Adapter handle obtained with WintunOpenAdapter or WintunCreateAdapter
 *
 * @param Name          Pointer to a string to receive adapter name
 *
 * @return If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To
 *         get extended error information, call GetLastError.
 */
typedef _Return_type_success_(return != FALSE) BOOL(WINAPI *WINTUN_GET_ADAPTER_NAME_FUNC)(
    _In_ WINTUN_ADAPTER_HANDLE Adapter,
    _Out_cap_c_(MAX_ADAPTER_NAME) WCHAR *Name);

/**
 * Sets name of the Wintun adapter.
 *
 * @param Adapter       Adapter handle obtained with WintunOpenAdapter or WintunCreateAdapter
 *
 * @param Name          Adapter name. Zero-terminated string of up to MAX_ADAPTER_NAME-1 characters.
 *
 * @return If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To
 *         get extended error information, call GetLastError.
 */
typedef _Return_type_success_(return != FALSE)
    BOOL(WINAPI *WINTUN_SET_ADAPTER_NAME_FUNC)(_In_ WINTUN_ADAPTER_HANDLE Adapter, _In_z_ const WCHAR *Name);

/**
 * Determines the version of the Wintun driver currently loaded.
 *
 * @return If the function succeeds, the return value is the version number. If the function fails, the return value is
 *         zero. To get extended error information, call GetLastError. Possible errors include the following:
 *         ERROR_FILE_NOT_FOUND  Wintun not loaded
 */
typedef DWORD(WINAPI *WINTUN_GET_RUNNING_DRIVER_VERSION_FUNC)(void);

/**
 * Determines the level of logging, passed to WINTUN_LOGGER_CALLBACK.
 */
typedef enum
{
    WINTUN_LOG_INFO, /**< Informational */
    WINTUN_LOG_WARN, /**< Warning */
    WINTUN_LOG_ERR   /**< Error */
} WINTUN_LOGGER_LEVEL;

/**
 * Called by internal logger to report diagnostic messages
 *
 * @param Level         Message level.
 *
 * @param Message       Message text.
 */
typedef void(CALLBACK *WINTUN_LOGGER_CALLBACK)(_In_ WINTUN_LOGGER_LEVEL Level, _In_z_ const WCHAR *Message);

/**
 * Sets logger callback function.
 *
 * @param NewLogger     Pointer to callback function to use as a new global logger. NewLogger may be called from various
 *                      threads concurrently. Should the logging require serialization, you must handle serialization in
 *                      NewLogger. Set to NULL to disable.
 */
typedef void(WINAPI *WINTUN_SET_LOGGER_FUNC)(_In_ WINTUN_LOGGER_CALLBACK NewLogger);

/**
 * Minimum ring capacity.
 */
#define WINTUN_MIN_RING_CAPACITY 0x20000 /* 128kiB */

/**
 * Maximum ring capacity.
 */
#define WINTUN_MAX_RING_CAPACITY 0x4000000 /* 64MiB */

/**
 * A handle representing Wintun session
 */
typedef void *WINTUN_SESSION_HANDLE;

/**
 * Starts Wintun session.
 *
 * @param Adapter       Adapter handle obtained with WintunOpenAdapter or WintunCreateAdapter
 *
 * @param Capacity      Rings capacity. Must be between WINTUN_MIN_RING_CAPACITY and WINTUN_MAX_RING_CAPACITY (incl.)
 *                      Must be a power of two.
 *
 * @return Wintun session handle. Must be released with WintunEndSession. If the function fails, the return value is
 *         NULL. To get extended error information, call GetLastError.
 */
typedef _Return_type_success_(return != NULL)
    WINTUN_SESSION_HANDLE(WINAPI *WINTUN_START_SESSION_FUNC)(_In_ WINTUN_ADAPTER_HANDLE Adapter, _In_ DWORD Capacity);

/**
 * Ends Wintun session.
 *
 * @param Session       Wintun session handle obtained with WintunStartSession
 */
typedef void(WINAPI *WINTUN_END_SESSION_FUNC)(_In_ WINTUN_SESSION_HANDLE Session);

/**
 * Gets Wintun session's read-wait event handle.
 *
 * @param Session       Wintun session handle obtained with WintunStartSession
 *
 * @return Pointer to receive event handle to wait for available data when reading. Should
 *         WintunReceivePackets return ERROR_NO_MORE_ITEMS (after spinning on it for a while under heavy
 *         load), wait for this event to become signaled before retrying WintunReceivePackets. Do not call
 *         CloseHandle on this event - it is managed by the session.
 */
typedef HANDLE(WINAPI *WINTUN_GET_READ_WAIT_EVENT_FUNC)(_In_ WINTUN_SESSION_HANDLE Session);

/**
 * Maximum IP packet size
 */
#define WINTUN_MAX_IP_PACKET_SIZE 0xFFFF

/**
 * Retrieves one or packet. After the packet content is consumed, call WintunReleaseReceivePacket with Packet returned
 * from this function to release internal buffer. This function is thread-safe.
 *
 * @param Session       Wintun session handle obtained with WintunStartSession
 *
 * @param PacketSize    Pointer to receive packet size.
 *
 * @return Pointer to layer 3 IPv4 or IPv6 packet. Client may modify its content at will. If the function fails, the
 *         return value is NULL. To get extended error information, call GetLastError. Possible errors include the
 *         following:
 *         ERROR_HANDLE_EOF     Wintun adapter is terminating;
 *         ERROR_NO_MORE_ITEMS  Wintun buffer is exhausted;
 *         ERROR_INVALID_DATA   Wintun buffer is corrupt
 */
typedef _Return_type_success_(return != NULL) _Ret_bytecount_(*PacketSize) BYTE *(
    WINAPI *WINTUN_RECEIVE_PACKET_FUNC)(_In_ WINTUN_SESSION_HANDLE Session, _Out_ DWORD *PacketSize);

/**
 * Releases internal buffer after the received packet has been processed by the client. This function is thread-safe.
 *
 * @param Session       Wintun session handle obtained with WintunStartSession
 *
 * @param Packet        Packet obtained with WintunReceivePacket
 */
typedef void(WINAPI *WINTUN_RELEASE_RECEIVE_PACKET_FUNC)(_In_ WINTUN_SESSION_HANDLE Session, _In_ const BYTE *Packet);

/**
 * Allocates memory for a packet to send. After the memory is filled with packet data, call WintunSendPacket to send
 * and release internal buffer. WintunAllocateSendPacket is thread-safe and the WintunAllocateSendPacket order of
 * calls define the packet sending order.
 *
 * @param Session       Wintun session handle obtained with WintunStartSession
 *
 * @param PacketSize    Exact packet size. Must be less or equal to WINTUN_MAX_IP_PACKET_SIZE.
 *
 * @return Returns pointer to memory where to prepare layer 3 IPv4 or IPv6 packet for sending. If the function fails,
 *         the return value is NULL. To get extended error information, call GetLastError. Possible errors include the
 *         following:
 *         ERROR_HANDLE_EOF       Wintun adapter is terminating;
 *         ERROR_BUFFER_OVERFLOW  Wintun buffer is full;
 */
typedef _Return_type_success_(return != NULL) _Ret_bytecount_(PacketSize) BYTE *(
    WINAPI *WINTUN_ALLOCATE_SEND_PACKET_FUNC)(_In_ WINTUN_SESSION_HANDLE Session, _In_ DWORD PacketSize);

/**
 * Sends the packet and releases internal buffer. WintunSendPacket is thread-safe, but the WintunAllocateSendPacket
 * order of calls define the packet sending order. This means the packet is not guaranteed to be sent in the
 * WintunSendPacket yet.
 *
 * @param Session       Wintun session handle obtained with WintunStartSession
 *
 * @param Packet        Packet obtained with WintunAllocateSendPacket
 */
typedef void(WINAPI *WINTUN_SEND_PACKET_FUNC)(_In_ WINTUN_SESSION_HANDLE Session, _In_ const BYTE *Packet);

#ifdef __cplusplus
}
#endif


<|start_filename|>pkg/ssh/terminal_windows.go<|end_filename|>
//go:build windows
// +build windows

package ssh

import (
	"context"

	"golang.org/x/crypto/ssh"
)

func watchWindowSize(ctx context.Context, fd int, sess *ssh.Session) error {
	// TODO: SIGWINCH for windows?
	return nil
}


<|start_filename|>pkg/retry/retry.go<|end_filename|>
package retry

import (
	"time"

	"github.com/jpillora/backoff"
)

func Retry(fn func() error, attempts uint) (err error) {
	for i := attempts; i > 0; i-- {
		err = fn()
		if err == nil {
			break
		}
	}

	return
}

func RetryBackoff(fn func() error, attempts uint, backoff *backoff.Backoff) (err error) {
	for i := attempts; i > 0; i-- {
		err = fn()
		if err == nil {
			break
		}
		time.Sleep(backoff.Duration())
	}

	return
}


<|start_filename|>internal/buildinfo/env.go<|end_filename|>
package buildinfo

var environment = "development"

func Environment() string {
	return environment
}

func IsDev() bool {
	return environment == "development"
}

func IsRelease() bool {
	return !IsDev()
}
