ctoai

package module
v2.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2021 License: MIT Imports: 5 Imported by: 0

README

sdk-go

The Ops Platform SDK for Go

Usage

Example sdk usage

Documentation and example usage can be found in their respective source code.

package main

import (
	"fmt"
	"github.com/cto-ai/sdk-go"
	"log"
	"time"
)

func main() {
	// instantiate new CTO.ai client
	client := ctoai.NewClient()

	// printing text to interface
	err := client.Ux.Print("starting e2e test of Go SDK")
	if err != nil {
		log.Fatal(err)
	}

	// prompt user to confirm
	// captures user stdin and converts to a bool
	output, err := client.Prompt.Confirm("confirmation", "confirm?", ctoai.OptConfirmFlag("C"), ctoai.OptConfirmDefault(true))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("You confirmed with a %v\n", output)

	// displays a progress bar to the interface
	err = client.Ux.ProgressBarStart(5, 1, "Finishing...")
	if err != nil {
		log.Fatal(err)
	}

	// do some work
	time.Sleep(2 * time.Second)

	err = client.Ux.ProgressBarAdvance(4)
	if err != nil {
		log.Fatal(err)
	}

	err = client.Ux.ProgressBarStop("Done!")
	if err != nil {
		log.Fatal(err)
	}
}

Running inside an op

This uses the example code above.

############################
# Build container
############################
FROM golang:1.13.6 AS build

WORKDIR /ops

ADD . .

RUN go build -ldflags="-s -w" -o main

############################
# Final container
############################
FROM registry.cto.ai/official_images/base:latest

COPY --from=build /ops/main /ops/main

Corresponding ops.yml run command:

run: /ops/main

Documentation

Index

Constants

View Source
const (
	DATETIME = "datetime"
	DATE     = "date"
	TIME     = "time"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CheckboxOption

type CheckboxOption func(*daemon.CheckboxPromptBody)

func OptCheckboxDefaultIndex

func OptCheckboxDefaultIndex(defaultIndexes []int) CheckboxOption

func OptCheckboxDefaultValues

func OptCheckboxDefaultValues(defaultValues []string) CheckboxOption

func OptCheckboxFlag

func OptCheckboxFlag(flag string) CheckboxOption

OptCheckboxFlag sets the flag value for the checkbox prompt.

The flag value is used to match command line arguments to prompts.

type Client

type Client struct {
	Prompt *Prompt
	Ux     *Ux
	Sdk    *Sdk
}

Client is the top-level client for Ops Platform services

func NewClient

func NewClient() Client

NewClient creates an Ops Platform client with all services included

type ConfirmOption

type ConfirmOption func(*daemon.ConfirmPromptBody)

func OptConfirmDefault

func OptConfirmDefault(defaultValue bool) ConfirmOption

func OptConfirmFlag

func OptConfirmFlag(flag string) ConfirmOption

OptConfirmFlag sets the flag value for the confirm prompt.

The flag value is used to match command line arguments to prompts.

type DatetimeOption

type DatetimeOption func(*daemon.DatetimePromptBody)

DatetimeOption is an option for the Datetime prompt function

func OptDatetimeDefault

func OptDatetimeDefault(defaultValue time.Time) DatetimeOption

func OptDatetimeFlag

func OptDatetimeFlag(flag string) DatetimeOption

OptDatetimeFlag sets the flag value for the datetime prompt.

The flag value is used to match command line arguments to prompts.

func OptDatetimeMaximum

func OptDatetimeMaximum(maximumValue time.Time) DatetimeOption

func OptDatetimeMinimum

func OptDatetimeMinimum(minimumValue time.Time) DatetimeOption

func OptDatetimeVariant

func OptDatetimeVariant(variant string) DatetimeOption

type EditorOption

type EditorOption func(*daemon.EditorPromptBody)

EditorOption is an option for the Editor prompt function

func OptEditorDefault

func OptEditorDefault(defaultValue string) EditorOption

func OptEditorFlag

func OptEditorFlag(flag string) EditorOption

OptEditorFlag sets the flag value for the editor prompt.

The flag value is used to match command line arguments to prompts.

type GetSecretOption

type GetSecretOption func(*daemon.GetSecretBody)

GetSecretOption is an option for the GetSecret function

func OptGetSecretHidden

func OptGetSecretHidden() GetSecretOption

OptGetSecretHidden suppresses the notification that a secret has been retrieved for this request

type InputOption

type InputOption func(*daemon.InputPromptBody)

InputOption is an option for the Input prompt function

func OptInputAllowEmpty

func OptInputAllowEmpty(allowEmpty bool) InputOption

OptInputAllowEmpty sets whether the input prompt should accept an empty line.

Has no effect if a default is set.

func OptInputDefault

func OptInputDefault(defaultValue string) InputOption

OptInputDefault sets the default value for the input prompt.

func OptInputFlag

func OptInputFlag(flag string) InputOption

OptInputFlag sets the flag value for the input prompt.

The flag value is used to match command line arguments to prompts.

type ListOption

type ListOption func(*daemon.ListPromptBody)

func OptListAutocomplete

func OptListAutocomplete(autocomplete bool) ListOption

func OptListDefaultIndex

func OptListDefaultIndex(defaultIndex int) ListOption

func OptListDefaultValue

func OptListDefaultValue(defaultValue string) ListOption

func OptListFlag

func OptListFlag(flag string) ListOption

OptListFlag sets the flag value for the list prompt.

The flag value is used to match command line arguments to prompts.

type NumberOption

type NumberOption func(*daemon.NumberPromptBody)

NumberOption is a functional option type for the Number method.

func OptNumberDefault

func OptNumberDefault(defaultValue int) NumberOption

func OptNumberFlag

func OptNumberFlag(flag string) NumberOption

OptNumberFlag sets the flag value for the number prompt.

The flag value is used to match command line arguments to prompts.

func OptNumberMaximum

func OptNumberMaximum(maximumValue int) NumberOption

func OptNumberMinimum

func OptNumberMinimum(minimumValue int) NumberOption

type PasswordOption

type PasswordOption func(*daemon.PasswordPromptBody)

func OptPasswordConfirm

func OptPasswordConfirm(confirm bool) PasswordOption

func OptPasswordFlag

func OptPasswordFlag(flag string) PasswordOption

OptPasswordFlag sets the flag value for the password prompt.

The flag value is used to match command line arguments to prompts.

type Prompt

type Prompt struct{}

Prompt is the object that contains the prompt methods

func NewPrompt

func NewPrompt() *Prompt

func (*Prompt) Checkbox

func (*Prompt) Checkbox(name, msg string, choices []string, options ...CheckboxOption) ([]string, error)

Checkbox presents a list of options to the user, who can select multiple items in the interface (i.e. terminal or slack).

choices is the list of string options that can be selected

Example:

p := ctoai.NewPrompt()
resp, err := s.PromptCheckbox("tools", "Which interpreters would you like to have included in your OS image?", []string{"Lua", "Node.js", "Perl", "Python 2", "Python 3", "Raku", "Ruby"}, OptCheckboxDefaultValues([]string{"Lua"}), OptCheckboxFlag("C")) // user selects Lua
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: Lua

func (*Prompt) Confirm

func (*Prompt) Confirm(name, msg string, options ...ConfirmOption) (bool, error)

Confirm presents a yes/no question to the user in the interface (i.e. terminal or slack).

Example:

p := ctoai.NewPrompt()
resp, err := p.PromptConfirm("verbose", "Do you want to run in verbose mode?", OptConfirmFlag("c"), OptConfirmDefault(false)) // user responds with y
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: true

func (*Prompt) Datetime

func (*Prompt) Datetime(name, msg string, options ...DatetimeOption) (time.Time, error)

Datetime presents a date picker to the user that allows them to select a date and/or time.

The method returns the user's response as a time.Time type.

Example:

import "time"

p := ctoai.NewPrompt()
resp, err := p.Datetime("nextRun", "When do you want to run the code next?", OptDatetimeVariant(DATETIME), OptDatetimeFlag("T"), OptDatetimeDefault(time.Now()), OptDatetimeMaximum(time.Now().Add(time.Hour * 2)), OptDatetimeMinimum(time.Now())) // user selects default
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: [the output will equal time.Now() in 2006-01-02 15:04:05 format]

func (*Prompt) Editor

func (*Prompt) Editor(name, msg string, options ...EditorOption) (string, error)

Editor presets a prompt requesting a multi-line response from the user. If used in a terminal interface, the nano editor will be presented.

Example:

p := ctoai.NewPrompt()

template := `Features:

Fixes:

Chores:

`

resp, err := p.Editor("notes", "Please enter your release notes", OptEditorDefault(template), OptEditorFlag("e"))
if err != nil {
    panic(err)
}

Output: [Nano will be brought up with the template in the editor]

func (*Prompt) Input

func (*Prompt) Input(name, msg string, options ...InputOption) (string, error)

Input presents an input (single-line text) prompt on the interface (i.e. terminal or slack).

The method returns the user's response as string.

Example:

p := ctoai.NewPrompt()
resp, err := p.Input("opinion" ,"What do you think of Go?", "good") // user responds with "good"
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: good

func (*Prompt) List

func (*Prompt) List(name, msg string, choices []string, options ...ListOption) (string, error)

List presents a list of options to the user to select one item from in the interface (i.e. terminal or slack).

choices is the list of string options that can be selected

Example:

p := ctoai.NewPrompt()
resp, err := p.List("platform", "What cloud platform would you like to deploy to?", []string{"AWS", "Google Cloud", "Azure"}, OptListDefaultValue("AWS"), OptListFlag("L"), OptListAutocomplete(true)) // user selects Azure
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: Azure

func (*Prompt) Number

func (*Prompt) Number(name, msg string, options ...NumberOption) (int, error)

Number presents a prompt for a numeric value to the interface (i.e. terminal or slack).

The method returns the user's response as int.

Example:

p := ctoai.NewPrompt()
resp, err := p.Number("count", "How many hoorays do you want?", OptNumberFlag("n"), OptNumberDefault(10), OptNumberMinimum(0), OptNumberMaximum(10)) // user responds with 7
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: 7

func (*Prompt) Password

func (*Prompt) Password(name, msg string, options ...PasswordOption) (string, error)

Password presents an input prompt for passwords in the interface (i.e. terminal or slack).

The password can be entered by the user or selected from their team's secret store. If the value is entered directly, it will be obscured on the screen.

For passwords, the name doubles as the default secret store key for the desired secret. If this key is present, it will be selected as the default option for the user.

The method returns the user's response as string.

Example:

p := ctoai.NewPrompt()
resp, err := p.Password("password", "What new password would you like to use?", OptPasswordFlag("p")) // user responds with 1234asdf
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: 1234asdf

func (*Prompt) Secret

func (*Prompt) Secret(name, msg string, options ...SecretOption) (string, error)

Secret presents an input prompt for secrets in the interface (i.e. terminal or slack).

The secret can be entered by the user or selected from their team's secret store. The value will be displayed on the terminal/screen as it is entered for verification

For secrets, the name doubles as the default secret store key for the desired secret. If this key is present, it will be selected as the default option for the user.

The method returns the user's response as string.

Example:

p := ctoai.NewPrompt()
resp, err := p.Secret("SSH_KEY", "What SSH private key do you want to use?", OptSecretFlag("s")) // user responds with 1234asdf
if err != nil {
    panic(err)
}

fmt.Println(resp)

Output: 1234asdf

type Sdk

type Sdk struct{}

Sdk is the object that contains the SDK methods

func NewSdk

func NewSdk() *Sdk

func (*Sdk) DeleteConfig

func (s *Sdk) DeleteConfig(key string) (bool, error)

DeleteConfig deletes a value from the config (user-specific) key/value store Returns false if key not found, true if success

func (*Sdk) Events

func (*Sdk) Events(start, end string) ([]map[string]interface{}, error)

func (*Sdk) GetAllConfig

func (s *Sdk) GetAllConfig() (map[string]string, error)

GetAllConfig returns a map of all keys to values in the config (workflow-local) key/value store

func (*Sdk) GetAllState

func (s *Sdk) GetAllState() (map[string]interface{}, error)

GetAllState returns a map of all keys to values in the state (workflow-local) key/value store DEPRECATED: state is used by deprecated workflows feature

func (*Sdk) GetConfig

func (s *Sdk) GetConfig(key string) (string, error)

GetConfig returns a value from the config (user-specific) key/value store

func (*Sdk) GetConfigPath

func (*Sdk) GetConfigPath() string

GetConfigPath returns the path to the config directory (local to this particular op) DEPRECATED: incompatible with current config API

func (*Sdk) GetHostOS

func (*Sdk) GetHostOS() string

GetHostOS returns the current host OS.

func (*Sdk) GetInterfaceType

func (*Sdk) GetInterfaceType() string

GetInterfaceType returns the interface type that the op is attached to

func (*Sdk) GetSecret

func (*Sdk) GetSecret(key string, options ...GetSecretOption) (string, error)

GetSecret requests a secret from the secret store by key.

If the secret exists, it is returned, with the daemon notifying the user that it is in use. Otherwise, the user is prompted to provide a replacement.

func (*Sdk) GetState

func (s *Sdk) GetState(key string) (interface{}, error)

GetState returns a value from the state (workflow-local) key/value store DEPRECATED: state is used by deprecated workflows feature

func (*Sdk) GetStatePath

func (*Sdk) GetStatePath() string

GetStatePath returns the path to the state directory (local to this particular workflow) DEPRECATED: use `HomeDir` instead.

func (*Sdk) HomeDir

func (*Sdk) HomeDir() string

HomeDir returns the location of the user home directory

func (*Sdk) Log added in v2.2.2

func (*Sdk) Log(message string) error

Log prints out formatted log. message can be built using "fmt.Sprintf()"

func (*Sdk) SetConfig

func (s *Sdk) SetConfig(key string, value string) error

SetConfig sets a value in the config (user-specific) key/value store

func (*Sdk) SetSecret

func (*Sdk) SetSecret(key string, value string) (string, error)

SetSecret sets a particular value into the secret store

If the secret already exists, the user is prompted on whether to overwrite it.

func (*Sdk) SetState

func (s *Sdk) SetState(key string, value interface{}) error

SetState sets a value in the state (workflow-local) key/value store DEPRECATED: state is used by deprecated workflows feature

func (*Sdk) Start

func (*Sdk) Start(workflowName string) error

The event, tags, and payload will be logged.

func (*Sdk) Team added in v2.2.3

func (*Sdk) Team() (TeamInfo, error)

Team returns the team info for the current user running the Op.

func (*Sdk) Track

func (*Sdk) Track(tags []string, event string, metadata map[string]interface{}) error

Track sends an event to the CTO.ai analytics system. This is the public facing API to enable developers to send data that they want to be tracked by cto.ai

Example:

s := ctoai.NewSdk()
err := s.Track([]string{"sdk", "go", "tracked"}, "testing", map[string]interface{}{
    "user": "name",
})

The event, tags, and payload will be logged.

func (*Sdk) User

func (*Sdk) User() (UserInfo, error)

User returns the user info for the current user running the Op.

type SecretOption

type SecretOption func(*daemon.SecretPromptBody)

func OptSecretFlag

func OptSecretFlag(flag string) SecretOption

OptSecretFlag sets the flag value for the secret prompt.

The flag value is used to match command line arguments to prompts.

type TeamInfo added in v2.2.3

type TeamInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

TeamInfo contains user info returned by daemon.

type UserInfo

type UserInfo struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Email    string `json:"email"`
}

UserInfo contains user info returned by daemon.

type Ux

type Ux struct{}

Ux is the object that contains the UX methods

func NewUx

func NewUx() *Ux

NewUx creates a new Ux object and returns it

func (*Ux) Bold

func (*Ux) Bold(text string) string

Bold adds formatting for boldface type to the given text

func (*Ux) Italic

func (*Ux) Italic(text string) string

Italic adds formatting for italic type to the given text

func (*Ux) Print

func (*Ux) Print(text string) error

Print prints text to the output interface (i.e. terminal/slack).

Example:

u := ctoai.NewUx()
err := u.Print("testing")
if err != nil {
    panic(err)
}

Output:

testing

func (*Ux) ProgressBarAdvance

func (*Ux) ProgressBarAdvance(increment int) error

ProgressBarAdvance adds onto a progressbar that is already present on the interface (i.e. terminal or slack).

The increment indicates the additional length (out of total length) that will be filled.

Example:

...
[progressbar animation with 1/5 of the bar filled here] Downloading...
err := u.ProgressBarAdvance(1)
if err != nil {
    panic(err)
}

Output: [progressbar animation with 2/5 of the bar filled here] Downloading...

func (*Ux) ProgressBarStart

func (*Ux) ProgressBarStart(length, initial int, message string) error

ProgressBarStart presents a progressbar on the output interface (i.e. terminal or slack) that will stay present until the progressbar stop method is called.

The input length is the total length of the progress bar, e.g. if you have 5 steps in your logic, then a unit length of 5 might be and appropriate length.

The initial length indicates the unit length (out of total length) that is initially filled at the start.

Example:

u := ctoai.NewUx()
err := u.ProgressBarStart(5, 1, "Downloading...")
if err != nil {
    panic(err)
}

Output: [progressbar animation with 1/5 of the bar filled here] Downloading...

func (*Ux) ProgressBarStop

func (*Ux) ProgressBarStop(message string) error

ProgressBarStop completes a progressbar that is already present on the interface (i.e. terminal or slack).

The text will change the initial text (set from the ux.ProgressBarStart method).

Example:

...
[progressbar animation with 2/5 of the bar filled here] Downloading...
err := u.ProgressBarStop("Done!")
if err != nil {
    panic(err)
}

Output: [progressbar animation with 5/5 of the bar filled here] Done!

func (*Ux) SpinnerStart

func (*Ux) SpinnerStart(text string) error

SpinnerStart presents a spinner on the output interface (i.e. terminal or slack) that to spin until the SpinnerStop method is called.

Example:

u := ctoai.NewUx()
err := u.SpinnerStart("Starting process...")
if err != nil {
    panic(err)
}

Output: [spinner emoji w/ spinner animation here] Starting process...

func (*Ux) SpinnerStop

func (*Ux) SpinnerStop(text string) error

SpinnerStop stops a spinner that has been previously started on the interface (i.e. terminal or slack).

Example:

... //previous spinner started here

err := u.SpinnerStop("Done!")
if err != nil {
    panic(err)
}

Output: [spinner completed completed here] Done!

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL