repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
session-manager-plugin | aws | Go | // Package ini is an LL(1) parser for configuration files.
//
// Example:
// sections, err := ini.OpenFile("/path/to/file")
// if err != nil {
// panic(err)
// }
//
// profile := "foo"
// section, ok := sections.GetSection(profile)
// if !ok {
// fmt.Printf("section %q could not be found", profile)
// }
//
// Below is the BNF that describes this parser
// Grammar:
// stmt -> section | stmt'
// stmt' -> epsilon | expr
// expr -> value (stmt)* | equal_expr (stmt)*
// equal_expr -> value ( ':' | '=' ) equal_expr'
// equal_expr' -> number | string | quoted_string
// quoted_string -> " quoted_string'
// quoted_string' -> string quoted_string_end
// quoted_string_end -> "
//
// section -> [ section'
// section' -> section_value section_close
// section_value -> number | string_subset | boolean | quoted_string_subset
// quoted_string_subset -> " quoted_string_subset'
// quoted_string_subset' -> string_subset quoted_string_end
// quoted_string_subset -> "
// section_close -> ]
//
// value -> number | string_subset | boolean
// string -> ? UTF-8 Code-Points except '\n' (U+000A) and '\r\n' (U+000D U+000A) ?
// string_subset -> ? Code-points excepted by <string> grammar except ':' (U+003A), '=' (U+003D), '[' (U+005B), and ']' (U+005D) ?
//
// SkipState will skip (NL WS)+
//
// comment -> # comment' | ; comment'
// comment' -> epsilon | value
package ini
| 43 |
session-manager-plugin | aws | Go | package ini
// emptyToken is used to satisfy the Token interface
var emptyToken = newToken(TokenNone, []rune{}, NoneType)
| 5 |
session-manager-plugin | aws | Go | package ini
// newExpression will return an expression AST.
// Expr represents an expression
//
// grammar:
// expr -> string | number
func newExpression(tok Token) AST {
return newASTWithRootToken(ASTKindExpr, tok)
}
func newEqualExpr(left AST, tok Token) AST {
return newASTWithRootToken(ASTKindEqualExpr, tok, left)
}
// EqualExprKey will return a LHS value in the equal expr
func EqualExprKey(ast AST) string {
children := ast.GetChildren()
if len(children) == 0 || ast.Kind != ASTKindEqualExpr {
return ""
}
return string(children[0].Root.Raw())
}
| 25 |
session-manager-plugin | aws | Go | // +build gofuzz
package ini
import (
"bytes"
)
func Fuzz(data []byte) int {
b := bytes.NewReader(data)
if _, err := Parse(b); err != nil {
return 0
}
return 1
}
| 18 |
session-manager-plugin | aws | Go | // +build fuzz
// fuzz test data is stored in Amazon S3.
package ini_test
import (
"path/filepath"
"testing"
"github.com/aws/aws-sdk-go/internal/ini"
)
// TestFuzz is used to test for crashes and not validity of the input
func TestFuzz(t *testing.T) {
paths, err := filepath.Glob("testdata/fuzz/*")
if err != nil {
t.Errorf("expected no error, but received %v", err)
}
if paths == nil {
t.Errorf("expected fuzz files, but received none")
}
for _, path := range paths {
t.Run(path, func(t *testing.T) {
ini.OpenFile(path)
})
}
}
| 30 |
session-manager-plugin | aws | Go | package ini
import (
"io"
"os"
"github.com/aws/aws-sdk-go/aws/awserr"
)
// OpenFile takes a path to a given file, and will open and parse
// that file.
func OpenFile(path string) (Sections, error) {
f, err := os.Open(path)
if err != nil {
return Sections{}, awserr.New(ErrCodeUnableToReadFile, "unable to open file", err)
}
defer f.Close()
return Parse(f)
}
// Parse will parse the given file using the shared config
// visitor.
func Parse(f io.Reader) (Sections, error) {
tree, err := ParseAST(f)
if err != nil {
return Sections{}, err
}
v := NewDefaultVisitor()
if err = Walk(tree, v); err != nil {
return Sections{}, err
}
return v.Sections, nil
}
// ParseBytes will parse the given bytes and return the parsed sections.
func ParseBytes(b []byte) (Sections, error) {
tree, err := ParseASTBytes(b)
if err != nil {
return Sections{}, err
}
v := NewDefaultVisitor()
if err = Walk(tree, v); err != nil {
return Sections{}, err
}
return v.Sections, nil
}
| 52 |
session-manager-plugin | aws | Go | package ini
import (
"bytes"
"io"
"io/ioutil"
"github.com/aws/aws-sdk-go/aws/awserr"
)
const (
// ErrCodeUnableToReadFile is used when a file is failed to be
// opened or read from.
ErrCodeUnableToReadFile = "FailedRead"
)
// TokenType represents the various different tokens types
type TokenType int
func (t TokenType) String() string {
switch t {
case TokenNone:
return "none"
case TokenLit:
return "literal"
case TokenSep:
return "sep"
case TokenOp:
return "op"
case TokenWS:
return "ws"
case TokenNL:
return "newline"
case TokenComment:
return "comment"
case TokenComma:
return "comma"
default:
return ""
}
}
// TokenType enums
const (
TokenNone = TokenType(iota)
TokenLit
TokenSep
TokenComma
TokenOp
TokenWS
TokenNL
TokenComment
)
type iniLexer struct{}
// Tokenize will return a list of tokens during lexical analysis of the
// io.Reader.
func (l *iniLexer) Tokenize(r io.Reader) ([]Token, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, awserr.New(ErrCodeUnableToReadFile, "unable to read file", err)
}
return l.tokenize(b)
}
func (l *iniLexer) tokenize(b []byte) ([]Token, error) {
runes := bytes.Runes(b)
var err error
n := 0
tokenAmount := countTokens(runes)
tokens := make([]Token, tokenAmount)
count := 0
for len(runes) > 0 && count < tokenAmount {
switch {
case isWhitespace(runes[0]):
tokens[count], n, err = newWSToken(runes)
case isComma(runes[0]):
tokens[count], n = newCommaToken(), 1
case isComment(runes):
tokens[count], n, err = newCommentToken(runes)
case isNewline(runes):
tokens[count], n, err = newNewlineToken(runes)
case isSep(runes):
tokens[count], n, err = newSepToken(runes)
case isOp(runes):
tokens[count], n, err = newOpToken(runes)
default:
tokens[count], n, err = newLitToken(runes)
}
if err != nil {
return nil, err
}
count++
runes = runes[n:]
}
return tokens[:count], nil
}
func countTokens(runes []rune) int {
count, n := 0, 0
var err error
for len(runes) > 0 {
switch {
case isWhitespace(runes[0]):
_, n, err = newWSToken(runes)
case isComma(runes[0]):
_, n = newCommaToken(), 1
case isComment(runes):
_, n, err = newCommentToken(runes)
case isNewline(runes):
_, n, err = newNewlineToken(runes)
case isSep(runes):
_, n, err = newSepToken(runes)
case isOp(runes):
_, n, err = newOpToken(runes)
default:
_, n, err = newLitToken(runes)
}
if err != nil {
return 0
}
count++
runes = runes[n:]
}
return count + 1
}
// Token indicates a metadata about a given value.
type Token struct {
t TokenType
ValueType ValueType
base int
raw []rune
}
var emptyValue = Value{}
func newToken(t TokenType, raw []rune, v ValueType) Token {
return Token{
t: t,
raw: raw,
ValueType: v,
}
}
// Raw return the raw runes that were consumed
func (tok Token) Raw() []rune {
return tok.raw
}
// Type returns the token type
func (tok Token) Type() TokenType {
return tok.t
}
| 166 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"bytes"
"io"
"reflect"
"testing"
)
func TestTokenize(t *testing.T) {
numberToken := newToken(TokenLit, []rune("123"), IntegerType)
numberToken.base = 10
cases := []struct {
r io.Reader
expectedTokens []Token
expectedError bool
}{
{
r: bytes.NewBuffer([]byte(`x = 123`)),
expectedTokens: []Token{
newToken(TokenLit, []rune("x"), StringType),
newToken(TokenWS, []rune(" "), NoneType),
newToken(TokenOp, []rune("="), NoneType),
newToken(TokenWS, []rune(" "), NoneType),
numberToken,
},
},
{
r: bytes.NewBuffer([]byte(`[ foo ]`)),
expectedTokens: []Token{
newToken(TokenSep, []rune("["), NoneType),
newToken(TokenWS, []rune(" "), NoneType),
newToken(TokenLit, []rune("foo"), StringType),
newToken(TokenWS, []rune(" "), NoneType),
newToken(TokenSep, []rune("]"), NoneType),
},
},
}
for _, c := range cases {
lex := iniLexer{}
tokens, err := lex.Tokenize(c.r)
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("expected %t, but received %t", e, a)
}
if e, a := c.expectedTokens, tokens; !reflect.DeepEqual(e, a) {
t.Errorf("expected %v, but received %v", e, a)
}
}
}
| 55 |
session-manager-plugin | aws | Go | package ini
import (
"fmt"
"io"
)
// ParseState represents the current state of the parser.
type ParseState uint
// State enums for the parse table
const (
InvalidState ParseState = iota
// stmt -> value stmt'
StatementState
// stmt' -> MarkComplete | op stmt
StatementPrimeState
// value -> number | string | boolean | quoted_string
ValueState
// section -> [ section'
OpenScopeState
// section' -> value section_close
SectionState
// section_close -> ]
CloseScopeState
// SkipState will skip (NL WS)+
SkipState
// SkipTokenState will skip any token and push the previous
// state onto the stack.
SkipTokenState
// comment -> # comment' | ; comment'
// comment' -> MarkComplete | value
CommentState
// MarkComplete state will complete statements and move that
// to the completed AST list
MarkCompleteState
// TerminalState signifies that the tokens have been fully parsed
TerminalState
)
// parseTable is a state machine to dictate the grammar above.
var parseTable = map[ASTKind]map[TokenType]ParseState{
ASTKindStart: {
TokenLit: StatementState,
TokenSep: OpenScopeState,
TokenWS: SkipTokenState,
TokenNL: SkipTokenState,
TokenComment: CommentState,
TokenNone: TerminalState,
},
ASTKindCommentStatement: {
TokenLit: StatementState,
TokenSep: OpenScopeState,
TokenWS: SkipTokenState,
TokenNL: SkipTokenState,
TokenComment: CommentState,
TokenNone: MarkCompleteState,
},
ASTKindExpr: {
TokenOp: StatementPrimeState,
TokenLit: ValueState,
TokenSep: OpenScopeState,
TokenWS: ValueState,
TokenNL: SkipState,
TokenComment: CommentState,
TokenNone: MarkCompleteState,
},
ASTKindEqualExpr: {
TokenLit: ValueState,
TokenSep: ValueState,
TokenOp: ValueState,
TokenWS: SkipTokenState,
TokenNL: SkipState,
TokenNone: SkipState,
},
ASTKindStatement: {
TokenLit: SectionState,
TokenSep: CloseScopeState,
TokenWS: SkipTokenState,
TokenNL: SkipTokenState,
TokenComment: CommentState,
TokenNone: MarkCompleteState,
},
ASTKindExprStatement: {
TokenLit: ValueState,
TokenSep: ValueState,
TokenOp: ValueState,
TokenWS: ValueState,
TokenNL: MarkCompleteState,
TokenComment: CommentState,
TokenNone: TerminalState,
TokenComma: SkipState,
},
ASTKindSectionStatement: {
TokenLit: SectionState,
TokenOp: SectionState,
TokenSep: CloseScopeState,
TokenWS: SectionState,
TokenNL: SkipTokenState,
},
ASTKindCompletedSectionStatement: {
TokenWS: SkipTokenState,
TokenNL: SkipTokenState,
TokenLit: StatementState,
TokenSep: OpenScopeState,
TokenComment: CommentState,
TokenNone: MarkCompleteState,
},
ASTKindSkipStatement: {
TokenLit: StatementState,
TokenSep: OpenScopeState,
TokenWS: SkipTokenState,
TokenNL: SkipTokenState,
TokenComment: CommentState,
TokenNone: TerminalState,
},
}
// ParseAST will parse input from an io.Reader using
// an LL(1) parser.
func ParseAST(r io.Reader) ([]AST, error) {
lexer := iniLexer{}
tokens, err := lexer.Tokenize(r)
if err != nil {
return []AST{}, err
}
return parse(tokens)
}
// ParseASTBytes will parse input from a byte slice using
// an LL(1) parser.
func ParseASTBytes(b []byte) ([]AST, error) {
lexer := iniLexer{}
tokens, err := lexer.tokenize(b)
if err != nil {
return []AST{}, err
}
return parse(tokens)
}
func parse(tokens []Token) ([]AST, error) {
start := Start
stack := newParseStack(3, len(tokens))
stack.Push(start)
s := newSkipper()
loop:
for stack.Len() > 0 {
k := stack.Pop()
var tok Token
if len(tokens) == 0 {
// this occurs when all the tokens have been processed
// but reduction of what's left on the stack needs to
// occur.
tok = emptyToken
} else {
tok = tokens[0]
}
step := parseTable[k.Kind][tok.Type()]
if s.ShouldSkip(tok) {
// being in a skip state with no tokens will break out of
// the parse loop since there is nothing left to process.
if len(tokens) == 0 {
break loop
}
// if should skip is true, we skip the tokens until should skip is set to false.
step = SkipTokenState
}
switch step {
case TerminalState:
// Finished parsing. Push what should be the last
// statement to the stack. If there is anything left
// on the stack, an error in parsing has occurred.
if k.Kind != ASTKindStart {
stack.MarkComplete(k)
}
break loop
case SkipTokenState:
// When skipping a token, the previous state was popped off the stack.
// To maintain the correct state, the previous state will be pushed
// onto the stack.
stack.Push(k)
case StatementState:
if k.Kind != ASTKindStart {
stack.MarkComplete(k)
}
expr := newExpression(tok)
stack.Push(expr)
case StatementPrimeState:
if tok.Type() != TokenOp {
stack.MarkComplete(k)
continue
}
if k.Kind != ASTKindExpr {
return nil, NewParseError(
fmt.Sprintf("invalid expression: expected Expr type, but found %T type", k),
)
}
k = trimSpaces(k)
expr := newEqualExpr(k, tok)
stack.Push(expr)
case ValueState:
// ValueState requires the previous state to either be an equal expression
// or an expression statement.
switch k.Kind {
case ASTKindEqualExpr:
// assigning a value to some key
k.AppendChild(newExpression(tok))
stack.Push(newExprStatement(k))
case ASTKindExpr:
k.Root.raw = append(k.Root.raw, tok.Raw()...)
stack.Push(k)
case ASTKindExprStatement:
root := k.GetRoot()
children := root.GetChildren()
if len(children) == 0 {
return nil, NewParseError(
fmt.Sprintf("invalid expression: AST contains no children %s", k.Kind),
)
}
rhs := children[len(children)-1]
if rhs.Root.ValueType != QuotedStringType {
rhs.Root.ValueType = StringType
rhs.Root.raw = append(rhs.Root.raw, tok.Raw()...)
}
children[len(children)-1] = rhs
root.SetChildren(children)
stack.Push(k)
}
case OpenScopeState:
if !runeCompare(tok.Raw(), openBrace) {
return nil, NewParseError("expected '['")
}
// If OpenScopeState is not at the start, we must mark the previous ast as complete
//
// for example: if previous ast was a skip statement;
// we should mark it as complete before we create a new statement
if k.Kind != ASTKindStart {
stack.MarkComplete(k)
}
stmt := newStatement()
stack.Push(stmt)
case CloseScopeState:
if !runeCompare(tok.Raw(), closeBrace) {
return nil, NewParseError("expected ']'")
}
k = trimSpaces(k)
stack.Push(newCompletedSectionStatement(k))
case SectionState:
var stmt AST
switch k.Kind {
case ASTKindStatement:
// If there are multiple literals inside of a scope declaration,
// then the current token's raw value will be appended to the Name.
//
// This handles cases like [ profile default ]
//
// k will represent a SectionStatement with the children representing
// the label of the section
stmt = newSectionStatement(tok)
case ASTKindSectionStatement:
k.Root.raw = append(k.Root.raw, tok.Raw()...)
stmt = k
default:
return nil, NewParseError(
fmt.Sprintf("invalid statement: expected statement: %v", k.Kind),
)
}
stack.Push(stmt)
case MarkCompleteState:
if k.Kind != ASTKindStart {
stack.MarkComplete(k)
}
if stack.Len() == 0 {
stack.Push(start)
}
case SkipState:
stack.Push(newSkipStatement(k))
s.Skip()
case CommentState:
if k.Kind == ASTKindStart {
stack.Push(k)
} else {
stack.MarkComplete(k)
}
stmt := newCommentStatement(tok)
stack.Push(stmt)
default:
return nil, NewParseError(
fmt.Sprintf("invalid state with ASTKind %v and TokenType %v",
k, tok.Type()))
}
if len(tokens) > 0 {
tokens = tokens[1:]
}
}
// this occurs when a statement has not been completed
if stack.top > 1 {
return nil, NewParseError(fmt.Sprintf("incomplete ini expression"))
}
// returns a sublist which excludes the start symbol
return stack.List(), nil
}
// trimSpaces will trim spaces on the left and right hand side of
// the literal.
func trimSpaces(k AST) AST {
// trim left hand side of spaces
for i := 0; i < len(k.Root.raw); i++ {
if !isWhitespace(k.Root.raw[i]) {
break
}
k.Root.raw = k.Root.raw[1:]
i--
}
// trim right hand side of spaces
for i := len(k.Root.raw) - 1; i >= 0; i-- {
if !isWhitespace(k.Root.raw[i]) {
break
}
k.Root.raw = k.Root.raw[:len(k.Root.raw)-1]
}
return k
}
| 351 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"bytes"
"fmt"
"io"
"reflect"
"testing"
)
func TestParser(t *testing.T) {
xID, _, _ := newLitToken([]rune("x = 1234"))
s3ID, _, _ := newLitToken([]rune("s3 = 1234"))
fooSlashes, _, _ := newLitToken([]rune("//foo"))
regionID, _, _ := newLitToken([]rune("region"))
regionLit, _, _ := newLitToken([]rune(`"us-west-2"`))
regionNoQuotesLit, _, _ := newLitToken([]rune("us-west-2"))
credentialID, _, _ := newLitToken([]rune("credential_source"))
ec2MetadataLit, _, _ := newLitToken([]rune("Ec2InstanceMetadata"))
outputID, _, _ := newLitToken([]rune("output"))
outputLit, _, _ := newLitToken([]rune("json"))
sepInValueID, _, _ := newLitToken([]rune("sepInValue"))
sepInValueLit := newToken(TokenOp, []rune("=:[foo]]bar["), StringType)
equalOp, _, _ := newOpToken([]rune("= 1234"))
equalColonOp, _, _ := newOpToken([]rune(": 1234"))
numLit, _, _ := newLitToken([]rune("1234"))
defaultID, _, _ := newLitToken([]rune("default"))
assumeID, _, _ := newLitToken([]rune("assumerole"))
defaultProfileStmt := newSectionStatement(defaultID)
assumeProfileStmt := newSectionStatement(assumeID)
fooSlashesExpr := newExpression(fooSlashes)
xEQ1234 := newEqualExpr(newExpression(xID), equalOp)
xEQ1234.AppendChild(newExpression(numLit))
xEQColon1234 := newEqualExpr(newExpression(xID), equalColonOp)
xEQColon1234.AppendChild(newExpression(numLit))
regionEQRegion := newEqualExpr(newExpression(regionID), equalOp)
regionEQRegion.AppendChild(newExpression(regionLit))
noQuotesRegionEQRegion := newEqualExpr(newExpression(regionID), equalOp)
noQuotesRegionEQRegion.AppendChild(newExpression(regionNoQuotesLit))
credEQExpr := newEqualExpr(newExpression(credentialID), equalOp)
credEQExpr.AppendChild(newExpression(ec2MetadataLit))
outputEQExpr := newEqualExpr(newExpression(outputID), equalOp)
outputEQExpr.AppendChild(newExpression(outputLit))
sepInValueExpr := newEqualExpr(newExpression(sepInValueID), equalOp)
sepInValueExpr.AppendChild(newExpression(sepInValueLit))
cases := []struct {
name string
r io.Reader
expectedStack []AST
expectedError bool
}{
{
name: "semicolon comment",
r: bytes.NewBuffer([]byte(`;foo`)),
expectedStack: []AST{
newCommentStatement(newToken(TokenComment, []rune(";foo"), NoneType)),
},
},
{
name: "0==0",
r: bytes.NewBuffer([]byte(`0==0`)),
expectedStack: []AST{
func() AST {
equalExpr := newEqualExpr(newExpression(newToken(TokenLit, []rune("0"), StringType)), equalOp)
equalExpr.AppendChild(newExpression(newToken(TokenOp, []rune("=0"), StringType)))
return newExprStatement(equalExpr)
}(),
},
},
{
name: "0=:0",
r: bytes.NewBuffer([]byte(`0=:0`)),
expectedStack: []AST{
func() AST {
equalExpr := newEqualExpr(newExpression(newToken(TokenLit, []rune("0"), StringType)), equalOp)
equalExpr.AppendChild(newExpression(newToken(TokenOp, []rune(":0"), StringType)))
return newExprStatement(equalExpr)
}(),
},
},
{
name: "0:=0",
r: bytes.NewBuffer([]byte(`0:=0`)),
expectedStack: []AST{
func() AST {
equalExpr := newEqualExpr(newExpression(newToken(TokenLit, []rune("0"), StringType)), equalColonOp)
equalExpr.AppendChild(newExpression(newToken(TokenOp, []rune("=0"), StringType)))
return newExprStatement(equalExpr)
}(),
},
},
{
name: "0::0",
r: bytes.NewBuffer([]byte(`0::0`)),
expectedStack: []AST{
func() AST {
equalExpr := newEqualExpr(newExpression(newToken(TokenLit, []rune("0"), StringType)), equalColonOp)
equalExpr.AppendChild(newExpression(newToken(TokenOp, []rune(":0"), StringType)))
return newExprStatement(equalExpr)
}(),
},
},
{
name: "section with variable",
r: bytes.NewBuffer([]byte(`[ default ]x`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
newExpression(xID),
},
},
{
name: "# comment",
r: bytes.NewBuffer([]byte(`# foo`)),
expectedStack: []AST{
newCommentStatement(newToken(TokenComment, []rune("# foo"), NoneType)),
},
},
{
name: "// not a comment",
r: bytes.NewBuffer([]byte(`//foo`)),
expectedStack: []AST{
fooSlashesExpr,
},
},
{
name: "multiple comments",
r: bytes.NewBuffer([]byte(`;foo
# baz
`)),
expectedStack: []AST{
newCommentStatement(newToken(TokenComment, []rune(";foo"), NoneType)),
newCommentStatement(newToken(TokenComment, []rune("# baz"), NoneType)),
},
},
{
name: "comment followed by skip state",
r: bytes.NewBuffer([]byte(`;foo
//foo
# baz
`)),
expectedStack: []AST{
newCommentStatement(newToken(TokenComment, []rune(";foo"), NoneType)),
},
},
{
name: "assignment",
r: bytes.NewBuffer([]byte(`x = 1234`)),
expectedStack: []AST{
newExprStatement(xEQ1234),
},
},
{
name: "assignment spaceless",
r: bytes.NewBuffer([]byte(`x=1234`)),
expectedStack: []AST{
newExprStatement(xEQ1234),
},
},
{
name: "assignment :",
r: bytes.NewBuffer([]byte(`x : 1234`)),
expectedStack: []AST{
newExprStatement(xEQColon1234),
},
},
{
name: "assignment : no spaces",
r: bytes.NewBuffer([]byte(`x:1234`)),
expectedStack: []AST{
newExprStatement(xEQColon1234),
},
},
{
name: "section expression",
r: bytes.NewBuffer([]byte(`[ default ]`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
},
},
{
name: "section expression no spaces",
r: bytes.NewBuffer([]byte(`[default]`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
},
},
{
name: "section statement",
r: bytes.NewBuffer([]byte(`[default]
region="us-west-2"`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
newExprStatement(regionEQRegion),
},
},
{
name: "complex section statement",
r: bytes.NewBuffer([]byte(`[default]
region = us-west-2
credential_source = Ec2InstanceMetadata
output = json
[assumerole]
output = json
region = us-west-2
`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
newExprStatement(noQuotesRegionEQRegion),
newExprStatement(credEQExpr),
newExprStatement(outputEQExpr),
newCompletedSectionStatement(
assumeProfileStmt,
),
newExprStatement(outputEQExpr),
newExprStatement(noQuotesRegionEQRegion),
},
},
{
name: "complex section statement with nested params",
r: bytes.NewBuffer([]byte(`[default]
s3 =
foo=bar
bar=baz
region = us-west-2
credential_source = Ec2InstanceMetadata
output = json
[assumerole]
output = json
region = us-west-2
`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
newSkipStatement(newEqualExpr(newExpression(s3ID), equalOp)),
newExprStatement(noQuotesRegionEQRegion),
newExprStatement(credEQExpr),
newExprStatement(outputEQExpr),
newCompletedSectionStatement(
assumeProfileStmt,
),
newExprStatement(outputEQExpr),
newExprStatement(noQuotesRegionEQRegion),
},
},
{
name: "complex section statement",
r: bytes.NewBuffer([]byte(`[default]
region = us-west-2
credential_source = Ec2InstanceMetadata
s3 =
foo=bar
bar=baz
output = json
[assumerole]
output = json
region = us-west-2
`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
newExprStatement(noQuotesRegionEQRegion),
newExprStatement(credEQExpr),
newSkipStatement(newEqualExpr(newExpression(s3ID), equalOp)),
newExprStatement(outputEQExpr),
newCompletedSectionStatement(
assumeProfileStmt,
),
newExprStatement(outputEQExpr),
newExprStatement(noQuotesRegionEQRegion),
},
},
{
name: "missing section statement",
r: bytes.NewBuffer([]byte(
`[default]
s3 =
[assumerole]
output = json
`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
newSkipStatement(newEqualExpr(newExpression(s3ID), equalOp)),
newCompletedSectionStatement(
assumeProfileStmt,
),
newExprStatement(outputEQExpr),
},
},
{
name: "missing right hand expression in the last statement in the file",
r: bytes.NewBuffer([]byte(
`[default]
region = us-west-2
s3 =`)),
expectedStack: []AST{
newCompletedSectionStatement(
defaultProfileStmt,
),
newExprStatement(noQuotesRegionEQRegion),
},
},
{
name: "token seperators [ and ] in values",
r: bytes.NewBuffer([]byte(
`[default]
sepInValue = =:[foo]]bar[
output = json
[assumerole]
sepInValue==:[foo]]bar[
output = json
`)),
expectedStack: []AST{
newCompletedSectionStatement(defaultProfileStmt),
newExprStatement(sepInValueExpr),
newExprStatement(outputEQExpr),
newCompletedSectionStatement(assumeProfileStmt),
newExprStatement(sepInValueExpr),
newExprStatement(outputEQExpr),
},
},
}
for i, c := range cases {
t.Run(c.name, func(t *testing.T) {
stack, err := ParseAST(c.r)
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("%d: expected %t, but received %t with error %v", i, e, a, err)
}
if e, a := len(c.expectedStack), len(stack); e != a {
t.Errorf("expected same length %d, but received %d", e, a)
}
if e, a := c.expectedStack, stack; !reflect.DeepEqual(e, a) {
buf := bytes.Buffer{}
buf.WriteString("expected:\n")
for j := 0; j < len(e); j++ {
buf.WriteString(fmt.Sprintf("\t%d: %v\n", j, e[j]))
}
buf.WriteString("\nreceived:\n")
for j := 0; j < len(a); j++ {
buf.WriteString(fmt.Sprintf("\t%d: %v\n", j, a[j]))
}
t.Errorf("%s", buf.String())
}
})
}
}
| 385 |
session-manager-plugin | aws | Go | package ini
import (
"fmt"
"strconv"
"strings"
)
var (
runesTrue = []rune("true")
runesFalse = []rune("false")
)
var literalValues = [][]rune{
runesTrue,
runesFalse,
}
func isBoolValue(b []rune) bool {
for _, lv := range literalValues {
if isLitValue(lv, b) {
return true
}
}
return false
}
func isLitValue(want, have []rune) bool {
if len(have) < len(want) {
return false
}
for i := 0; i < len(want); i++ {
if want[i] != have[i] {
return false
}
}
return true
}
// isNumberValue will return whether not the leading characters in
// a byte slice is a number. A number is delimited by whitespace or
// the newline token.
//
// A number is defined to be in a binary, octal, decimal (int | float), hex format,
// or in scientific notation.
func isNumberValue(b []rune) bool {
negativeIndex := 0
helper := numberHelper{}
needDigit := false
for i := 0; i < len(b); i++ {
negativeIndex++
switch b[i] {
case '-':
if helper.IsNegative() || negativeIndex != 1 {
return false
}
helper.Determine(b[i])
needDigit = true
continue
case 'e', 'E':
if err := helper.Determine(b[i]); err != nil {
return false
}
negativeIndex = 0
needDigit = true
continue
case 'b':
if helper.numberFormat == hex {
break
}
fallthrough
case 'o', 'x':
needDigit = true
if i == 0 {
return false
}
fallthrough
case '.':
if err := helper.Determine(b[i]); err != nil {
return false
}
needDigit = true
continue
}
if i > 0 && (isNewline(b[i:]) || isWhitespace(b[i])) {
return !needDigit
}
if !helper.CorrectByte(b[i]) {
return false
}
needDigit = false
}
return !needDigit
}
func isValid(b []rune) (bool, int, error) {
if len(b) == 0 {
// TODO: should probably return an error
return false, 0, nil
}
return isValidRune(b[0]), 1, nil
}
func isValidRune(r rune) bool {
return r != ':' && r != '=' && r != '[' && r != ']' && r != ' ' && r != '\n'
}
// ValueType is an enum that will signify what type
// the Value is
type ValueType int
func (v ValueType) String() string {
switch v {
case NoneType:
return "NONE"
case DecimalType:
return "FLOAT"
case IntegerType:
return "INT"
case StringType:
return "STRING"
case BoolType:
return "BOOL"
}
return ""
}
// ValueType enums
const (
NoneType = ValueType(iota)
DecimalType
IntegerType
StringType
QuotedStringType
BoolType
)
// Value is a union container
type Value struct {
Type ValueType
raw []rune
integer int64
decimal float64
boolean bool
str string
}
func newValue(t ValueType, base int, raw []rune) (Value, error) {
v := Value{
Type: t,
raw: raw,
}
var err error
switch t {
case DecimalType:
v.decimal, err = strconv.ParseFloat(string(raw), 64)
case IntegerType:
if base != 10 {
raw = raw[2:]
}
v.integer, err = strconv.ParseInt(string(raw), base, 64)
case StringType:
v.str = string(raw)
case QuotedStringType:
v.str = string(raw[1 : len(raw)-1])
case BoolType:
v.boolean = runeCompare(v.raw, runesTrue)
}
// issue 2253
//
// if the value trying to be parsed is too large, then we will use
// the 'StringType' and raw value instead.
if nerr, ok := err.(*strconv.NumError); ok && nerr.Err == strconv.ErrRange {
v.Type = StringType
v.str = string(raw)
err = nil
}
return v, err
}
// Append will append values and change the type to a string
// type.
func (v *Value) Append(tok Token) {
r := tok.Raw()
if v.Type != QuotedStringType {
v.Type = StringType
r = tok.raw[1 : len(tok.raw)-1]
}
if tok.Type() != TokenLit {
v.raw = append(v.raw, tok.Raw()...)
} else {
v.raw = append(v.raw, r...)
}
}
func (v Value) String() string {
switch v.Type {
case DecimalType:
return fmt.Sprintf("decimal: %f", v.decimal)
case IntegerType:
return fmt.Sprintf("integer: %d", v.integer)
case StringType:
return fmt.Sprintf("string: %s", string(v.raw))
case QuotedStringType:
return fmt.Sprintf("quoted string: %s", string(v.raw))
case BoolType:
return fmt.Sprintf("bool: %t", v.boolean)
default:
return "union not set"
}
}
func newLitToken(b []rune) (Token, int, error) {
n := 0
var err error
token := Token{}
if b[0] == '"' {
n, err = getStringValue(b)
if err != nil {
return token, n, err
}
token = newToken(TokenLit, b[:n], QuotedStringType)
} else if isNumberValue(b) {
var base int
base, n, err = getNumericalValue(b)
if err != nil {
return token, 0, err
}
value := b[:n]
vType := IntegerType
if contains(value, '.') || hasExponent(value) {
vType = DecimalType
}
token = newToken(TokenLit, value, vType)
token.base = base
} else if isBoolValue(b) {
n, err = getBoolValue(b)
token = newToken(TokenLit, b[:n], BoolType)
} else {
n, err = getValue(b)
token = newToken(TokenLit, b[:n], StringType)
}
return token, n, err
}
// IntValue returns an integer value
func (v Value) IntValue() int64 {
return v.integer
}
// FloatValue returns a float value
func (v Value) FloatValue() float64 {
return v.decimal
}
// BoolValue returns a bool value
func (v Value) BoolValue() bool {
return v.boolean
}
func isTrimmable(r rune) bool {
switch r {
case '\n', ' ':
return true
}
return false
}
// StringValue returns the string value
func (v Value) StringValue() string {
switch v.Type {
case StringType:
return strings.TrimFunc(string(v.raw), isTrimmable)
case QuotedStringType:
// preserve all characters in the quotes
return string(removeEscapedCharacters(v.raw[1 : len(v.raw)-1]))
default:
return strings.TrimFunc(string(v.raw), isTrimmable)
}
}
func contains(runes []rune, c rune) bool {
for i := 0; i < len(runes); i++ {
if runes[i] == c {
return true
}
}
return false
}
func runeCompare(v1 []rune, v2 []rune) bool {
if len(v1) != len(v2) {
return false
}
for i := 0; i < len(v1); i++ {
if v1[i] != v2[i] {
return false
}
}
return true
}
| 325 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"reflect"
"testing"
)
func TestIsNumberValue(t *testing.T) {
cases := []struct {
name string
b []rune
expected bool
}{
{
"integer",
[]rune("123"),
true,
},
{
"negative integer",
[]rune("-123"),
true,
},
{
"decimal",
[]rune("123.456"),
true,
},
{
"small e exponent",
[]rune("1e234"),
true,
},
{
"big E exponent",
[]rune("1E234"),
true,
},
{
"error case exponent base 16",
[]rune("1ea4"),
false,
},
{
"error case negative",
[]rune("1-23"),
false,
},
{
"error case multiple negative",
[]rune("-1-23"),
false,
},
{
"error case end negative",
[]rune("123-"),
false,
},
{
"error case non-number",
[]rune("a"),
false,
},
{
"utf8 whitespace",
[]rune("00"),
true,
},
}
for i, c := range cases {
t.Run(c.name, func(t *testing.T) {
if e, a := c.expected, isNumberValue(c.b); e != a {
t.Errorf("%d: expected %t, but received %t", i+1, e, a)
}
})
}
}
// TODO: test errors
func TestNewLiteralToken(t *testing.T) {
cases := []struct {
name string
b []rune
expectedRead int
expectedToken Token
expectedError bool
}{
{
name: "numbers",
b: []rune("123"),
expectedRead: 3,
expectedToken: newToken(TokenLit,
[]rune("123"),
IntegerType,
),
},
{
name: "decimal",
b: []rune("123.456"),
expectedRead: 7,
expectedToken: newToken(TokenLit,
[]rune("123.456"),
DecimalType,
),
},
{
name: "two numbers",
b: []rune("123 456"),
expectedRead: 3,
expectedToken: newToken(TokenLit,
[]rune("123"),
IntegerType,
),
},
{
name: "number followed by alpha",
b: []rune("123 abc"),
expectedRead: 3,
expectedToken: newToken(TokenLit,
[]rune("123"),
IntegerType,
),
},
{
name: "quoted string followed by number",
b: []rune(`"Hello" 123`),
expectedRead: 7,
expectedToken: newToken(TokenLit,
[]rune("Hello"),
QuotedStringType,
),
},
{
name: "quoted string",
b: []rune(`"Hello World"`),
expectedRead: 13,
expectedToken: newToken(TokenLit,
[]rune("Hello World"),
QuotedStringType,
),
},
{
name: "boolean true",
b: []rune("true"),
expectedRead: 4,
expectedToken: newToken(TokenLit,
[]rune("true"),
BoolType,
),
},
{
name: "boolean false",
b: []rune("false"),
expectedRead: 5,
expectedToken: newToken(TokenLit,
[]rune("false"),
BoolType,
),
},
{
name: "utf8 whitespace",
b: []rune("00"),
expectedRead: 1,
expectedToken: newToken(TokenLit,
[]rune("0"),
IntegerType,
),
},
{
name: "utf8 whitespace expr",
b: []rune("0=00"),
expectedRead: 1,
expectedToken: newToken(TokenLit,
[]rune("0"),
StringType,
),
},
}
for i, c := range cases {
t.Run(c.name, func(t *testing.T) {
tok, n, err := newLitToken(c.b)
if e, a := c.expectedToken.ValueType, tok.ValueType; !reflect.DeepEqual(e, a) {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedRead, n; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
})
}
}
| 201 |
session-manager-plugin | aws | Go | package ini
func isNewline(b []rune) bool {
if len(b) == 0 {
return false
}
if b[0] == '\n' {
return true
}
if len(b) < 2 {
return false
}
return b[0] == '\r' && b[1] == '\n'
}
func newNewlineToken(b []rune) (Token, int, error) {
i := 1
if b[0] == '\r' && isNewline(b[1:]) {
i++
}
if !isNewline([]rune(b[:i])) {
return emptyToken, 0, NewParseError("invalid new line token")
}
return newToken(TokenNL, b[:i], NoneType), i, nil
}
| 31 |
session-manager-plugin | aws | Go | package ini
import (
"bytes"
"fmt"
"strconv"
)
const (
none = numberFormat(iota)
binary
octal
decimal
hex
exponent
)
type numberFormat int
// numberHelper is used to dictate what format a number is in
// and what to do for negative values. Since -1e-4 is a valid
// number, we cannot just simply check for duplicate negatives.
type numberHelper struct {
numberFormat numberFormat
negative bool
negativeExponent bool
}
func (b numberHelper) Exists() bool {
return b.numberFormat != none
}
func (b numberHelper) IsNegative() bool {
return b.negative || b.negativeExponent
}
func (b *numberHelper) Determine(c rune) error {
if b.Exists() {
return NewParseError(fmt.Sprintf("multiple number formats: 0%v", string(c)))
}
switch c {
case 'b':
b.numberFormat = binary
case 'o':
b.numberFormat = octal
case 'x':
b.numberFormat = hex
case 'e', 'E':
b.numberFormat = exponent
case '-':
if b.numberFormat != exponent {
b.negative = true
} else {
b.negativeExponent = true
}
case '.':
b.numberFormat = decimal
default:
return NewParseError(fmt.Sprintf("invalid number character: %v", string(c)))
}
return nil
}
func (b numberHelper) CorrectByte(c rune) bool {
switch {
case b.numberFormat == binary:
if !isBinaryByte(c) {
return false
}
case b.numberFormat == octal:
if !isOctalByte(c) {
return false
}
case b.numberFormat == hex:
if !isHexByte(c) {
return false
}
case b.numberFormat == decimal:
if !isDigit(c) {
return false
}
case b.numberFormat == exponent:
if !isDigit(c) {
return false
}
case b.negativeExponent:
if !isDigit(c) {
return false
}
case b.negative:
if !isDigit(c) {
return false
}
default:
if !isDigit(c) {
return false
}
}
return true
}
func (b numberHelper) Base() int {
switch b.numberFormat {
case binary:
return 2
case octal:
return 8
case hex:
return 16
default:
return 10
}
}
func (b numberHelper) String() string {
buf := bytes.Buffer{}
i := 0
switch b.numberFormat {
case binary:
i++
buf.WriteString(strconv.Itoa(i) + ": binary format\n")
case octal:
i++
buf.WriteString(strconv.Itoa(i) + ": octal format\n")
case hex:
i++
buf.WriteString(strconv.Itoa(i) + ": hex format\n")
case exponent:
i++
buf.WriteString(strconv.Itoa(i) + ": exponent format\n")
default:
i++
buf.WriteString(strconv.Itoa(i) + ": integer format\n")
}
if b.negative {
i++
buf.WriteString(strconv.Itoa(i) + ": negative format\n")
}
if b.negativeExponent {
i++
buf.WriteString(strconv.Itoa(i) + ": negative exponent format\n")
}
return buf.String()
}
| 153 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"testing"
)
func TestNumberHelper(t *testing.T) {
cases := []struct {
b []rune
determineIndex int
expectedExists []bool
expectedErrors []bool
expectedCorrects []bool
expectedNegative bool
expectedBase int
}{
{
b: []rune("-10"),
determineIndex: 0,
expectedExists: []bool{
false,
false,
false,
},
expectedErrors: []bool{
false,
false,
false,
},
expectedCorrects: []bool{
true,
true,
true,
},
expectedNegative: true,
expectedBase: 10,
},
{
b: []rune("0x10"),
determineIndex: 1,
expectedExists: []bool{
false,
false,
true,
true,
},
expectedErrors: []bool{
false,
false,
false,
false,
},
expectedCorrects: []bool{
true,
true,
true,
true,
},
expectedNegative: false,
expectedBase: 16,
},
{
b: []rune("0b101"),
determineIndex: 1,
expectedExists: []bool{
false,
false,
true,
true,
true,
},
expectedErrors: []bool{
false,
false,
false,
false,
false,
},
expectedCorrects: []bool{
true,
true,
true,
true,
true,
},
expectedNegative: false,
expectedBase: 2,
},
{
b: []rune("0o271"),
determineIndex: 1,
expectedExists: []bool{
false,
false,
true,
true,
true,
},
expectedErrors: []bool{
false,
false,
false,
false,
false,
},
expectedCorrects: []bool{
true,
true,
true,
true,
true,
},
expectedNegative: false,
expectedBase: 8,
},
{
b: []rune("99"),
determineIndex: -1,
expectedExists: []bool{
false,
false,
},
expectedErrors: []bool{
false,
false,
},
expectedCorrects: []bool{
true,
true,
},
expectedNegative: false,
expectedBase: 10,
},
{
b: []rune("0o2o71"),
determineIndex: 1,
expectedExists: []bool{
false,
false,
true,
true,
true,
true,
},
expectedErrors: []bool{
false,
false,
false,
false,
false,
true,
},
expectedCorrects: []bool{
true,
true,
true,
false,
true,
true,
},
expectedNegative: false,
expectedBase: 8,
},
}
for _, c := range cases {
helper := numberHelper{}
for i := 0; i < len(c.b); i++ {
if e, a := c.expectedExists[i], helper.Exists(); e != a {
t.Errorf("expected %t, but received %t", e, a)
}
if i == c.determineIndex {
if e, a := c.expectedErrors[i], helper.Determine(c.b[i]) != nil; e != a {
t.Errorf("expected %t, but received %t", e, a)
}
} else {
if e, a := c.expectedCorrects[i], helper.CorrectByte(c.b[i]); e != a {
t.Errorf("expected %t, but received %t", e, a)
}
}
}
if e, a := c.expectedNegative, helper.IsNegative(); e != a {
t.Errorf("expected %t, but received %t", e, a)
}
if e, a := c.expectedBase, helper.Base(); e != a {
t.Errorf("expected %d, but received %d", e, a)
}
}
}
| 197 |
session-manager-plugin | aws | Go | package ini
import (
"fmt"
)
var (
equalOp = []rune("=")
equalColonOp = []rune(":")
)
func isOp(b []rune) bool {
if len(b) == 0 {
return false
}
switch b[0] {
case '=':
return true
case ':':
return true
default:
return false
}
}
func newOpToken(b []rune) (Token, int, error) {
tok := Token{}
switch b[0] {
case '=':
tok = newToken(TokenOp, equalOp, NoneType)
case ':':
tok = newToken(TokenOp, equalColonOp, NoneType)
default:
return tok, 0, NewParseError(fmt.Sprintf("unexpected op type, %v", b[0]))
}
return tok, 1, nil
}
| 40 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"reflect"
"testing"
)
func TestIsOp(t *testing.T) {
cases := []struct {
b []rune
expected bool
}{
{
b: []rune(``),
},
{
b: []rune("123"),
},
{
b: []rune(`"wee"`),
},
{
b: []rune("="),
expected: true,
},
{
b: []rune(":"),
expected: true,
},
}
for i, c := range cases {
if e, a := c.expected, isOp(c.b); e != a {
t.Errorf("%d: expected %t, but received %t", i+0, e, a)
}
}
}
func TestNewOp(t *testing.T) {
cases := []struct {
b []rune
expectedRead int
expectedError bool
expectedToken Token
}{
{
b: []rune("="),
expectedRead: 1,
expectedToken: newToken(TokenOp, []rune("="), NoneType),
},
{
b: []rune(":"),
expectedRead: 1,
expectedToken: newToken(TokenOp, []rune(":"), NoneType),
},
}
for i, c := range cases {
tok, n, err := newOpToken(c.b)
if e, a := c.expectedToken, tok; !reflect.DeepEqual(e, a) {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedRead, n; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
}
}
| 76 |
session-manager-plugin | aws | Go | package ini
import "fmt"
const (
// ErrCodeParseError is returned when a parsing error
// has occurred.
ErrCodeParseError = "INIParseError"
)
// ParseError is an error which is returned during any part of
// the parsing process.
type ParseError struct {
msg string
}
// NewParseError will return a new ParseError where message
// is the description of the error.
func NewParseError(message string) *ParseError {
return &ParseError{
msg: message,
}
}
// Code will return the ErrCodeParseError
func (err *ParseError) Code() string {
return ErrCodeParseError
}
// Message returns the error's message
func (err *ParseError) Message() string {
return err.msg
}
// OrigError return nothing since there will never be any
// original error.
func (err *ParseError) OrigError() error {
return nil
}
func (err *ParseError) Error() string {
return fmt.Sprintf("%s: %s", err.Code(), err.Message())
}
| 44 |
session-manager-plugin | aws | Go | package ini
import (
"bytes"
"fmt"
)
// ParseStack is a stack that contains a container, the stack portion,
// and the list which is the list of ASTs that have been successfully
// parsed.
type ParseStack struct {
top int
container []AST
list []AST
index int
}
func newParseStack(sizeContainer, sizeList int) ParseStack {
return ParseStack{
container: make([]AST, sizeContainer),
list: make([]AST, sizeList),
}
}
// Pop will return and truncate the last container element.
func (s *ParseStack) Pop() AST {
s.top--
return s.container[s.top]
}
// Push will add the new AST to the container
func (s *ParseStack) Push(ast AST) {
s.container[s.top] = ast
s.top++
}
// MarkComplete will append the AST to the list of completed statements
func (s *ParseStack) MarkComplete(ast AST) {
s.list[s.index] = ast
s.index++
}
// List will return the completed statements
func (s ParseStack) List() []AST {
return s.list[:s.index]
}
// Len will return the length of the container
func (s *ParseStack) Len() int {
return s.top
}
func (s ParseStack) String() string {
buf := bytes.Buffer{}
for i, node := range s.list {
buf.WriteString(fmt.Sprintf("%d: %v\n", i+1, node))
}
return buf.String()
}
| 61 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"reflect"
"testing"
)
func newMockAST(v []rune) AST {
return newASTWithRootToken(ASTKindNone, Token{raw: v})
}
func TestStack(t *testing.T) {
cases := []struct {
asts []AST
expected []AST
}{
{
asts: []AST{
newMockAST([]rune("0")),
newMockAST([]rune("1")),
newMockAST([]rune("2")),
newMockAST([]rune("3")),
newMockAST([]rune("4")),
},
expected: []AST{
newMockAST([]rune("0")),
newMockAST([]rune("1")),
newMockAST([]rune("2")),
newMockAST([]rune("3")),
newMockAST([]rune("4")),
},
},
}
for _, c := range cases {
p := newParseStack(10, 10)
for _, ast := range c.asts {
p.Push(ast)
p.MarkComplete(ast)
}
if e, a := len(c.expected), p.Len(); e != a {
t.Errorf("expected the same legnth with %d, but received %d", e, a)
}
for i := len(c.expected) - 1; i >= 0; i-- {
if e, a := c.expected[i], p.Pop(); !reflect.DeepEqual(e, a) {
t.Errorf("stack element %d invalid: expected %v, but received %v", i, e, a)
}
}
if e, a := len(c.expected), p.index; e != a {
t.Errorf("expected %d, but received %d", e, a)
}
if e, a := c.asts, p.list[:p.index]; !reflect.DeepEqual(e, a) {
t.Errorf("expected %v, but received %v", e, a)
}
}
}
| 62 |
session-manager-plugin | aws | Go | package ini
import (
"fmt"
)
var (
emptyRunes = []rune{}
)
func isSep(b []rune) bool {
if len(b) == 0 {
return false
}
switch b[0] {
case '[', ']':
return true
default:
return false
}
}
var (
openBrace = []rune("[")
closeBrace = []rune("]")
)
func newSepToken(b []rune) (Token, int, error) {
tok := Token{}
switch b[0] {
case '[':
tok = newToken(TokenSep, openBrace, NoneType)
case ']':
tok = newToken(TokenSep, closeBrace, NoneType)
default:
return tok, 0, NewParseError(fmt.Sprintf("unexpected sep type, %v", b[0]))
}
return tok, 1, nil
}
| 42 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"reflect"
"testing"
)
func TestIsSep(t *testing.T) {
cases := []struct {
b []rune
expected bool
}{
{
b: []rune(``),
},
{
b: []rune(`"wee"`),
},
{
b: []rune("["),
expected: true,
},
{
b: []rune("]"),
expected: true,
},
}
for i, c := range cases {
if e, a := c.expected, isSep(c.b); e != a {
t.Errorf("%d: expected %t, but received %t", i+0, e, a)
}
}
}
func TestNewSep(t *testing.T) {
cases := []struct {
b []rune
expectedRead int
expectedError bool
expectedToken Token
}{
{
b: []rune("["),
expectedRead: 1,
expectedToken: newToken(TokenSep, []rune("["), NoneType),
},
{
b: []rune("]"),
expectedRead: 1,
expectedToken: newToken(TokenSep, []rune("]"), NoneType),
},
}
for i, c := range cases {
tok, n, err := newSepToken(c.b)
if e, a := c.expectedToken, tok; !reflect.DeepEqual(e, a) {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedRead, n; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
}
}
| 73 |
session-manager-plugin | aws | Go | package ini
// skipper is used to skip certain blocks of an ini file.
// Currently skipper is used to skip nested blocks of ini
// files. See example below
//
// [ foo ]
// nested = ; this section will be skipped
// a=b
// c=d
// bar=baz ; this will be included
type skipper struct {
shouldSkip bool
TokenSet bool
prevTok Token
}
func newSkipper() skipper {
return skipper{
prevTok: emptyToken,
}
}
func (s *skipper) ShouldSkip(tok Token) bool {
// should skip state will be modified only if previous token was new line (NL);
// and the current token is not WhiteSpace (WS).
if s.shouldSkip &&
s.prevTok.Type() == TokenNL &&
tok.Type() != TokenWS {
s.Continue()
return false
}
s.prevTok = tok
return s.shouldSkip
}
func (s *skipper) Skip() {
s.shouldSkip = true
}
func (s *skipper) Continue() {
s.shouldSkip = false
// empty token is assigned as we return to default state, when should skip is false
s.prevTok = emptyToken
}
| 46 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"reflect"
"testing"
)
func TestSkipper(t *testing.T) {
idTok, _, _ := newLitToken([]rune("id"))
nlTok := newToken(TokenNL, []rune("\n"), NoneType)
cases := []struct {
name string
Fn func(s *skipper)
param Token
expected bool
expectedShouldSkip bool
expectedPrevTok Token
}{
{
name: "empty case",
Fn: func(s *skipper) {
},
param: emptyToken,
expectedPrevTok: emptyToken,
},
{
name: "skip case",
Fn: func(s *skipper) {
s.Skip()
},
param: idTok,
expectedShouldSkip: true,
expected: true,
expectedPrevTok: emptyToken,
},
{
name: "continue case",
Fn: func(s *skipper) {
s.Continue()
},
param: emptyToken,
expectedPrevTok: emptyToken,
},
{
name: "skip then continue case",
Fn: func(s *skipper) {
s.Skip()
s.Continue()
},
param: emptyToken,
expectedPrevTok: emptyToken,
},
{
name: "do not skip case",
Fn: func(s *skipper) {
s.Skip()
s.prevTok = nlTok
},
param: idTok,
expectedShouldSkip: true,
expectedPrevTok: nlTok,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := newSkipper()
c.Fn(&s)
if e, a := c.expectedShouldSkip, s.shouldSkip; e != a {
t.Errorf("%s: expected %t, but received %t", c.name, e, a)
}
if e, a := c.expectedPrevTok, s.prevTok; !reflect.DeepEqual(e, a) {
t.Errorf("%s: expected %v, but received %v", c.name, e, a)
}
if e, a := c.expected, s.ShouldSkip(c.param); e != a {
t.Errorf("%s: expected %t, but received %t", c.name, e, a)
}
})
}
}
| 88 |
session-manager-plugin | aws | Go | package ini
// Statement is an empty AST mostly used for transitioning states.
func newStatement() AST {
return newAST(ASTKindStatement, AST{})
}
// SectionStatement represents a section AST
func newSectionStatement(tok Token) AST {
return newASTWithRootToken(ASTKindSectionStatement, tok)
}
// ExprStatement represents a completed expression AST
func newExprStatement(ast AST) AST {
return newAST(ASTKindExprStatement, ast)
}
// CommentStatement represents a comment in the ini definition.
//
// grammar:
// comment -> #comment' | ;comment'
// comment' -> epsilon | value
func newCommentStatement(tok Token) AST {
return newAST(ASTKindCommentStatement, newExpression(tok))
}
// CompletedSectionStatement represents a completed section
func newCompletedSectionStatement(ast AST) AST {
return newAST(ASTKindCompletedSectionStatement, ast)
}
// SkipStatement is used to skip whole statements
func newSkipStatement(ast AST) AST {
return newAST(ASTKindSkipStatement, ast)
}
| 36 |
session-manager-plugin | aws | Go | package ini
import (
"reflect"
"testing"
)
func TestTrimSpaces(t *testing.T) {
cases := []struct {
name string
node AST
expectedNode AST
}{
{
name: "simple case",
node: AST{
Root: Token{
raw: []rune("foo"),
},
},
expectedNode: AST{
Root: Token{
raw: []rune("foo"),
},
},
},
{
name: "LHS case",
node: AST{
Root: Token{
raw: []rune(" foo"),
},
},
expectedNode: AST{
Root: Token{
raw: []rune("foo"),
},
},
},
{
name: "RHS case",
node: AST{
Root: Token{
raw: []rune("foo "),
},
},
expectedNode: AST{
Root: Token{
raw: []rune("foo"),
},
},
},
{
name: "both sides case",
node: AST{
Root: Token{
raw: []rune(" foo "),
},
},
expectedNode: AST{
Root: Token{
raw: []rune("foo"),
},
},
},
}
for _, c := range cases {
node := trimSpaces(c.node)
if e, a := c.expectedNode, node; !reflect.DeepEqual(e, a) {
t.Errorf("%s: expected %v, but received %v", c.name, e, a)
}
}
}
| 76 |
session-manager-plugin | aws | Go | package ini
import (
"fmt"
)
// getStringValue will return a quoted string and the amount
// of bytes read
//
// an error will be returned if the string is not properly formatted
func getStringValue(b []rune) (int, error) {
if b[0] != '"' {
return 0, NewParseError("strings must start with '\"'")
}
endQuote := false
i := 1
for ; i < len(b) && !endQuote; i++ {
if escaped := isEscaped(b[:i], b[i]); b[i] == '"' && !escaped {
endQuote = true
break
} else if escaped {
/*c, err := getEscapedByte(b[i])
if err != nil {
return 0, err
}
b[i-1] = c
b = append(b[:i], b[i+1:]...)
i--*/
continue
}
}
if !endQuote {
return 0, NewParseError("missing '\"' in string value")
}
return i + 1, nil
}
// getBoolValue will return a boolean and the amount
// of bytes read
//
// an error will be returned if the boolean is not of a correct
// value
func getBoolValue(b []rune) (int, error) {
if len(b) < 4 {
return 0, NewParseError("invalid boolean value")
}
n := 0
for _, lv := range literalValues {
if len(lv) > len(b) {
continue
}
if isLitValue(lv, b) {
n = len(lv)
}
}
if n == 0 {
return 0, NewParseError("invalid boolean value")
}
return n, nil
}
// getNumericalValue will return a numerical string, the amount
// of bytes read, and the base of the number
//
// an error will be returned if the number is not of a correct
// value
func getNumericalValue(b []rune) (int, int, error) {
if !isDigit(b[0]) {
return 0, 0, NewParseError("invalid digit value")
}
i := 0
helper := numberHelper{}
loop:
for negativeIndex := 0; i < len(b); i++ {
negativeIndex++
if !isDigit(b[i]) {
switch b[i] {
case '-':
if helper.IsNegative() || negativeIndex != 1 {
return 0, 0, NewParseError("parse error '-'")
}
n := getNegativeNumber(b[i:])
i += (n - 1)
helper.Determine(b[i])
continue
case '.':
if err := helper.Determine(b[i]); err != nil {
return 0, 0, err
}
case 'e', 'E':
if err := helper.Determine(b[i]); err != nil {
return 0, 0, err
}
negativeIndex = 0
case 'b':
if helper.numberFormat == hex {
break
}
fallthrough
case 'o', 'x':
if i == 0 && b[i] != '0' {
return 0, 0, NewParseError("incorrect base format, expected leading '0'")
}
if i != 1 {
return 0, 0, NewParseError(fmt.Sprintf("incorrect base format found %s at %d index", string(b[i]), i))
}
if err := helper.Determine(b[i]); err != nil {
return 0, 0, err
}
default:
if isWhitespace(b[i]) {
break loop
}
if isNewline(b[i:]) {
break loop
}
if !(helper.numberFormat == hex && isHexByte(b[i])) {
if i+2 < len(b) && !isNewline(b[i:i+2]) {
return 0, 0, NewParseError("invalid numerical character")
} else if !isNewline([]rune{b[i]}) {
return 0, 0, NewParseError("invalid numerical character")
}
break loop
}
}
}
}
return helper.Base(), i, nil
}
// isDigit will return whether or not something is an integer
func isDigit(b rune) bool {
return b >= '0' && b <= '9'
}
func hasExponent(v []rune) bool {
return contains(v, 'e') || contains(v, 'E')
}
func isBinaryByte(b rune) bool {
switch b {
case '0', '1':
return true
default:
return false
}
}
func isOctalByte(b rune) bool {
switch b {
case '0', '1', '2', '3', '4', '5', '6', '7':
return true
default:
return false
}
}
func isHexByte(b rune) bool {
if isDigit(b) {
return true
}
return (b >= 'A' && b <= 'F') ||
(b >= 'a' && b <= 'f')
}
func getValue(b []rune) (int, error) {
i := 0
for i < len(b) {
if isNewline(b[i:]) {
break
}
if isOp(b[i:]) {
break
}
valid, n, err := isValid(b[i:])
if err != nil {
return 0, err
}
if !valid {
break
}
i += n
}
return i, nil
}
// getNegativeNumber will return a negative number from a
// byte slice. This will iterate through all characters until
// a non-digit has been found.
func getNegativeNumber(b []rune) int {
if b[0] != '-' {
return 0
}
i := 1
for ; i < len(b); i++ {
if !isDigit(b[i]) {
return i
}
}
return i
}
// isEscaped will return whether or not the character is an escaped
// character.
func isEscaped(value []rune, b rune) bool {
if len(value) == 0 {
return false
}
switch b {
case '\'': // single quote
case '"': // quote
case 'n': // newline
case 't': // tab
case '\\': // backslash
default:
return false
}
return value[len(value)-1] == '\\'
}
func getEscapedByte(b rune) (rune, error) {
switch b {
case '\'': // single quote
return '\'', nil
case '"': // quote
return '"', nil
case 'n': // newline
return '\n', nil
case 't': // table
return '\t', nil
case '\\': // backslash
return '\\', nil
default:
return b, NewParseError(fmt.Sprintf("invalid escaped character %c", b))
}
}
func removeEscapedCharacters(b []rune) []rune {
for i := 0; i < len(b); i++ {
if isEscaped(b[:i], b[i]) {
c, err := getEscapedByte(b[i])
if err != nil {
return b
}
b[i-1] = c
b = append(b[:i], b[i+1:]...)
i--
}
}
return b
}
| 285 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"testing"
)
func TestStringValue(t *testing.T) {
cases := []struct {
b []rune
expectedRead int
expectedError bool
expectedValue string
}{
{
b: []rune(`"foo"`),
expectedRead: 5,
expectedValue: `"foo"`,
},
{
b: []rune(`"123 !$_ 456 abc"`),
expectedRead: 17,
expectedValue: `"123 !$_ 456 abc"`,
},
{
b: []rune("foo"),
expectedError: true,
},
{
b: []rune(` "foo"`),
expectedError: true,
},
}
for i, c := range cases {
n, err := getStringValue(c.b)
if e, a := c.expectedValue, string(c.b[:n]); e != a {
t.Errorf("%d: expected %v, but received %v", i, e, a)
}
if e, a := c.expectedRead, n; e != a {
t.Errorf("%d: expected %v, but received %v", i, e, a)
}
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("%d: expected %v, but received %v", i, e, a)
}
}
}
func TestBoolValue(t *testing.T) {
cases := []struct {
b []rune
expectedRead int
expectedError bool
expectedValue string
}{
{
b: []rune("true"),
expectedRead: 4,
expectedValue: "true",
},
{
b: []rune("false"),
expectedRead: 5,
expectedValue: "false",
},
{
b: []rune(`"false"`),
expectedError: true,
},
}
for _, c := range cases {
n, err := getBoolValue(c.b)
if e, a := c.expectedValue, string(c.b[:n]); e != a {
t.Errorf("expected %v, but received %v", e, a)
}
if e, a := c.expectedRead, n; e != a {
t.Errorf("expected %v, but received %v", e, a)
}
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("expected %v, but received %v", e, a)
}
}
}
func TestNumericalValue(t *testing.T) {
cases := []struct {
b []rune
expectedRead int
expectedError bool
expectedValue string
expectedBase int
}{
{
b: []rune("1.2"),
expectedRead: 3,
expectedValue: "1.2",
expectedBase: 10,
},
{
b: []rune("123"),
expectedRead: 3,
expectedValue: "123",
expectedBase: 10,
},
{
b: []rune("0x123A"),
expectedRead: 6,
expectedValue: "0x123A",
expectedBase: 16,
},
{
b: []rune("0b101"),
expectedRead: 5,
expectedValue: "0b101",
expectedBase: 2,
},
{
b: []rune("0o7"),
expectedRead: 3,
expectedValue: "0o7",
expectedBase: 8,
},
{
b: []rune(`"123"`),
expectedError: true,
},
{
b: []rune("0xo123"),
expectedError: true,
},
{
b: []rune("123A"),
expectedError: true,
},
}
for i, c := range cases {
base, n, err := getNumericalValue(c.b)
if e, a := c.expectedValue, string(c.b[:n]); e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedRead, n; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedError, err != nil; e != a {
t.Errorf("%d: expected %v, but received %v", i+1, e, a)
}
if e, a := c.expectedBase, base; e != a {
t.Errorf("%d: expected %d, but received %d", i+1, e, a)
}
}
}
| 165 |
session-manager-plugin | aws | Go | package ini
import (
"fmt"
"sort"
)
// Visitor is an interface used by walkers that will
// traverse an array of ASTs.
type Visitor interface {
VisitExpr(AST) error
VisitStatement(AST) error
}
// DefaultVisitor is used to visit statements and expressions
// and ensure that they are both of the correct format.
// In addition, upon visiting this will build sections and populate
// the Sections field which can be used to retrieve profile
// configuration.
type DefaultVisitor struct {
scope string
Sections Sections
}
// NewDefaultVisitor return a DefaultVisitor
func NewDefaultVisitor() *DefaultVisitor {
return &DefaultVisitor{
Sections: Sections{
container: map[string]Section{},
},
}
}
// VisitExpr visits expressions...
func (v *DefaultVisitor) VisitExpr(expr AST) error {
t := v.Sections.container[v.scope]
if t.values == nil {
t.values = values{}
}
switch expr.Kind {
case ASTKindExprStatement:
opExpr := expr.GetRoot()
switch opExpr.Kind {
case ASTKindEqualExpr:
children := opExpr.GetChildren()
if len(children) <= 1 {
return NewParseError("unexpected token type")
}
rhs := children[1]
// The right-hand value side the equality expression is allowed to contain '[', ']', ':', '=' in the values.
// If the token is not either a literal or one of the token types that identifies those four additional
// tokens then error.
if !(rhs.Root.Type() == TokenLit || rhs.Root.Type() == TokenOp || rhs.Root.Type() == TokenSep) {
return NewParseError("unexpected token type")
}
key := EqualExprKey(opExpr)
v, err := newValue(rhs.Root.ValueType, rhs.Root.base, rhs.Root.Raw())
if err != nil {
return err
}
t.values[key] = v
default:
return NewParseError(fmt.Sprintf("unsupported expression %v", expr))
}
default:
return NewParseError(fmt.Sprintf("unsupported expression %v", expr))
}
v.Sections.container[v.scope] = t
return nil
}
// VisitStatement visits statements...
func (v *DefaultVisitor) VisitStatement(stmt AST) error {
switch stmt.Kind {
case ASTKindCompletedSectionStatement:
child := stmt.GetRoot()
if child.Kind != ASTKindSectionStatement {
return NewParseError(fmt.Sprintf("unsupported child statement: %T", child))
}
name := string(child.Root.Raw())
v.Sections.container[name] = Section{}
v.scope = name
default:
return NewParseError(fmt.Sprintf("unsupported statement: %s", stmt.Kind))
}
return nil
}
// Sections is a map of Section structures that represent
// a configuration.
type Sections struct {
container map[string]Section
}
// GetSection will return section p. If section p does not exist,
// false will be returned in the second parameter.
func (t Sections) GetSection(p string) (Section, bool) {
v, ok := t.container[p]
return v, ok
}
// values represents a map of union values.
type values map[string]Value
// List will return a list of all sections that were successfully
// parsed.
func (t Sections) List() []string {
keys := make([]string, len(t.container))
i := 0
for k := range t.container {
keys[i] = k
i++
}
sort.Strings(keys)
return keys
}
// Section contains a name and values. This represent
// a sectioned entry in a configuration file.
type Section struct {
Name string
values values
}
// Has will return whether or not an entry exists in a given section
func (t Section) Has(k string) bool {
_, ok := t.values[k]
return ok
}
// ValueType will returned what type the union is set to. If
// k was not found, the NoneType will be returned.
func (t Section) ValueType(k string) (ValueType, bool) {
v, ok := t.values[k]
return v.Type, ok
}
// Bool returns a bool value at k
func (t Section) Bool(k string) bool {
return t.values[k].BoolValue()
}
// Int returns an integer value at k
func (t Section) Int(k string) int64 {
return t.values[k].IntValue()
}
// Float64 returns a float value at k
func (t Section) Float64(k string) float64 {
return t.values[k].FloatValue()
}
// String returns the string value at k
func (t Section) String(k string) string {
_, ok := t.values[k]
if !ok {
return ""
}
return t.values[k].StringValue()
}
| 170 |
session-manager-plugin | aws | Go | package ini
// Walk will traverse the AST using the v, the Visitor.
func Walk(tree []AST, v Visitor) error {
for _, node := range tree {
switch node.Kind {
case ASTKindExpr,
ASTKindExprStatement:
if err := v.VisitExpr(node); err != nil {
return err
}
case ASTKindStatement,
ASTKindCompletedSectionStatement,
ASTKindNestedSectionStatement,
ASTKindCompletedNestedSectionStatement:
if err := v.VisitStatement(node); err != nil {
return err
}
}
}
return nil
}
| 26 |
session-manager-plugin | aws | Go | // +build go1.7
package ini
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
)
func TestValidDataFiles(t *testing.T) {
const expectedFileSuffix = "_expected"
filepath.Walk("./testdata/valid", func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, expectedFileSuffix) {
return nil
}
if info.IsDir() {
return nil
}
f, err := os.Open(path)
if err != nil {
t.Errorf("%s: unexpected error, %v", path, err)
}
defer f.Close()
tree, err := ParseAST(f)
if err != nil {
t.Errorf("%s: unexpected parse error, %v", path, err)
}
v := NewDefaultVisitor()
err = Walk(tree, v)
if err != nil {
t.Errorf("%s: unexpected walk error, %v", path, err)
}
expectedPath := path + "_expected"
e := map[string]interface{}{}
b, err := ioutil.ReadFile(expectedPath)
if err != nil {
// ignore files that do not have an expected file
return nil
}
err = json.Unmarshal(b, &e)
if err != nil {
t.Errorf("unexpected error during deserialization, %v", err)
}
for profile, tableIface := range e {
p, ok := v.Sections.GetSection(profile)
if !ok {
t.Fatal("could not find profile " + profile)
}
table := tableIface.(map[string]interface{})
for k, v := range table {
switch e := v.(type) {
case string:
a := p.String(k)
if e != a {
t.Errorf("%s: expected %v, but received %v for profile %v", path, e, a, profile)
}
case int:
a := p.Int(k)
if int64(e) != a {
t.Errorf("%s: expected %v, but received %v", path, e, a)
}
case float64:
v := p.values[k]
if v.Type == IntegerType {
a := p.Int(k)
if int64(e) != a {
t.Errorf("%s: expected %v, but received %v", path, e, a)
}
} else {
a := p.Float64(k)
if e != a {
t.Errorf("%s: expected %v, but received %v", path, e, a)
}
}
default:
t.Errorf("unexpected type: %T", e)
}
}
}
return nil
})
}
func TestInvalidDataFiles(t *testing.T) {
cases := []struct {
path string
expectedParseError bool
expectedWalkError bool
}{
{
path: "./testdata/invalid/bad_syntax_1",
expectedParseError: true,
},
{
path: "./testdata/invalid/bad_syntax_2",
expectedParseError: true,
},
{
path: "./testdata/invalid/incomplete_section_profile",
expectedParseError: true,
},
{
path: "./testdata/invalid/syntax_error_comment",
expectedParseError: true,
},
{
path: "./testdata/invalid/invalid_keys",
expectedParseError: true,
},
{
path: "./testdata/invalid/bad_section_name",
expectedParseError: true,
},
}
for i, c := range cases {
t.Run(c.path, func(t *testing.T) {
f, err := os.Open(c.path)
if err != nil {
t.Errorf("unexpected error, %v", err)
}
defer f.Close()
tree, err := ParseAST(f)
if err != nil && !c.expectedParseError {
t.Errorf("%d: unexpected error, %v", i+1, err)
} else if err == nil && c.expectedParseError {
t.Errorf("%d: expected error, but received none", i+1)
}
if c.expectedParseError {
return
}
v := NewDefaultVisitor()
err = Walk(tree, v)
if err == nil && c.expectedWalkError {
t.Errorf("%d: expected error, but received none", i+1)
}
})
}
}
| 157 |
session-manager-plugin | aws | Go | package ini
import (
"unicode"
)
// isWhitespace will return whether or not the character is
// a whitespace character.
//
// Whitespace is defined as a space or tab.
func isWhitespace(c rune) bool {
return unicode.IsSpace(c) && c != '\n' && c != '\r'
}
func newWSToken(b []rune) (Token, int, error) {
i := 0
for ; i < len(b); i++ {
if !isWhitespace(b[i]) {
break
}
}
return newToken(TokenWS, b[:i], NoneType), i, nil
}
| 25 |
session-manager-plugin | aws | Go | package s3err
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
// RequestFailure provides additional S3 specific metadata for the request
// failure.
type RequestFailure struct {
awserr.RequestFailure
hostID string
}
// NewRequestFailure returns a request failure error decordated with S3
// specific metadata.
func NewRequestFailure(err awserr.RequestFailure, hostID string) *RequestFailure {
return &RequestFailure{RequestFailure: err, hostID: hostID}
}
func (r RequestFailure) Error() string {
extra := fmt.Sprintf("status code: %d, request id: %s, host id: %s",
r.StatusCode(), r.RequestID(), r.hostID)
return awserr.SprintError(r.Code(), r.Message(), extra, r.OrigErr())
}
func (r RequestFailure) String() string {
return r.Error()
}
// HostID returns the HostID request response value.
func (r RequestFailure) HostID() string {
return r.hostID
}
// RequestFailureWrapperHandler returns a handler to rap an
// awserr.RequestFailure with the S3 request ID 2 from the response.
func RequestFailureWrapperHandler() request.NamedHandler {
return request.NamedHandler{
Name: "awssdk.s3.errorHandler",
Fn: func(req *request.Request) {
reqErr, ok := req.Error.(awserr.RequestFailure)
if !ok || reqErr == nil {
return
}
hostID := req.HTTPResponse.Header.Get("X-Amz-Id-2")
if req.Error == nil {
return
}
req.Error = NewRequestFailure(reqErr, hostID)
},
}
}
| 58 |
session-manager-plugin | aws | Go | package s3shared
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/s3shared/arn"
)
const (
invalidARNErrorErrCode = "InvalidARNError"
configurationErrorErrCode = "ConfigurationError"
)
// InvalidARNError denotes the error for Invalid ARN
type InvalidARNError struct {
message string
resource arn.Resource
origErr error
}
// Error returns the InvalidARNError
func (e InvalidARNError) Error() string {
var extra string
if e.resource != nil {
extra = "ARN: " + e.resource.String()
}
return awserr.SprintError(e.Code(), e.Message(), extra, e.origErr)
}
// Code returns the invalid ARN error code
func (e InvalidARNError) Code() string {
return invalidARNErrorErrCode
}
// Message returns the message for Invalid ARN error
func (e InvalidARNError) Message() string {
return e.message
}
// OrigErr is the original error wrapped by Invalid ARN Error
func (e InvalidARNError) OrigErr() error {
return e.origErr
}
// NewInvalidARNError denotes invalid arn error
func NewInvalidARNError(resource arn.Resource, err error) InvalidARNError {
return InvalidARNError{
message: "invalid ARN",
origErr: err,
resource: resource,
}
}
// NewInvalidARNWithCustomEndpointError ARN not supported for custom clients endpoints
func NewInvalidARNWithCustomEndpointError(resource arn.Resource, err error) InvalidARNError {
return InvalidARNError{
message: "resource ARN not supported with custom client endpoints",
origErr: err,
resource: resource,
}
}
// NewInvalidARNWithUnsupportedPartitionError ARN not supported for the target partition
func NewInvalidARNWithUnsupportedPartitionError(resource arn.Resource, err error) InvalidARNError {
return InvalidARNError{
message: "resource ARN not supported for the target ARN partition",
origErr: err,
resource: resource,
}
}
// NewInvalidARNWithFIPSError ARN not supported for FIPS region
//
// Deprecated: FIPS will not appear in the ARN region component.
func NewInvalidARNWithFIPSError(resource arn.Resource, err error) InvalidARNError {
return InvalidARNError{
message: "resource ARN not supported for FIPS region",
resource: resource,
origErr: err,
}
}
// ConfigurationError is used to denote a client configuration error
type ConfigurationError struct {
message string
resource arn.Resource
clientPartitionID string
clientRegion string
origErr error
}
// Error returns the Configuration error string
func (e ConfigurationError) Error() string {
extra := fmt.Sprintf("ARN: %s, client partition: %s, client region: %s",
e.resource, e.clientPartitionID, e.clientRegion)
return awserr.SprintError(e.Code(), e.Message(), extra, e.origErr)
}
// Code returns configuration error's error-code
func (e ConfigurationError) Code() string {
return configurationErrorErrCode
}
// Message returns the configuration error message
func (e ConfigurationError) Message() string {
return e.message
}
// OrigErr is the original error wrapped by Configuration Error
func (e ConfigurationError) OrigErr() error {
return e.origErr
}
// NewClientPartitionMismatchError stub
func NewClientPartitionMismatchError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "client partition does not match provided ARN partition",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
// NewClientRegionMismatchError denotes cross region access error
func NewClientRegionMismatchError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "client region does not match provided ARN region",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
// NewFailedToResolveEndpointError denotes endpoint resolving error
func NewFailedToResolveEndpointError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "endpoint resolver failed to find an endpoint for the provided ARN region",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
// NewClientConfiguredForFIPSError denotes client config error for unsupported cross region FIPS access
func NewClientConfiguredForFIPSError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "client configured for fips but cross-region resource ARN provided",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
// NewFIPSConfigurationError denotes a configuration error when a client or request is configured for FIPS
func NewFIPSConfigurationError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "use of ARN is not supported when client or request is configured for FIPS",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
// NewClientConfiguredForAccelerateError denotes client config error for unsupported S3 accelerate
func NewClientConfiguredForAccelerateError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "client configured for S3 Accelerate but is not supported with resource ARN",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
// NewClientConfiguredForCrossRegionFIPSError denotes client config error for unsupported cross region FIPS request
func NewClientConfiguredForCrossRegionFIPSError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "client configured for FIPS with cross-region enabled but is supported with cross-region resource ARN",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
// NewClientConfiguredForDualStackError denotes client config error for unsupported S3 Dual-stack
func NewClientConfiguredForDualStackError(resource arn.Resource, clientPartitionID, clientRegion string, err error) ConfigurationError {
return ConfigurationError{
message: "client configured for S3 Dual-stack but is not supported with resource ARN",
origErr: err,
resource: resource,
clientPartitionID: clientPartitionID,
clientRegion: clientRegion,
}
}
| 203 |
session-manager-plugin | aws | Go | package s3shared
import (
"strings"
"github.com/aws/aws-sdk-go/aws"
awsarn "github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/s3shared/arn"
)
// ResourceRequest represents the request and arn resource
type ResourceRequest struct {
Resource arn.Resource
Request *request.Request
}
// ARN returns the resource ARN
func (r ResourceRequest) ARN() awsarn.ARN {
return r.Resource.GetARN()
}
// AllowCrossRegion returns a bool value to denote if S3UseARNRegion flag is set
func (r ResourceRequest) AllowCrossRegion() bool {
return aws.BoolValue(r.Request.Config.S3UseARNRegion)
}
// UseFIPS returns true if request config region is FIPS
func (r ResourceRequest) UseFIPS() bool {
return IsFIPS(aws.StringValue(r.Request.Config.Region))
}
// ResourceConfiguredForFIPS returns true if resource ARNs region is FIPS
//
// Deprecated: FIPS pseudo-regions will not be in the ARN
func (r ResourceRequest) ResourceConfiguredForFIPS() bool {
return IsFIPS(r.ARN().Region)
}
// IsCrossPartition returns true if client is configured for another partition, than
// the partition that resource ARN region resolves to.
func (r ResourceRequest) IsCrossPartition() bool {
return r.Request.ClientInfo.PartitionID != r.Resource.GetARN().Partition
}
// IsCrossRegion returns true if ARN region is different than client configured region
func (r ResourceRequest) IsCrossRegion() bool {
return IsCrossRegion(r.Request, r.Resource.GetARN().Region)
}
// HasCustomEndpoint returns true if custom client endpoint is provided
func (r ResourceRequest) HasCustomEndpoint() bool {
return len(aws.StringValue(r.Request.Config.Endpoint)) > 0
}
// IsFIPS returns true if region is a fips region
func IsFIPS(clientRegion string) bool {
return strings.HasPrefix(clientRegion, "fips-") || strings.HasSuffix(clientRegion, "-fips")
}
// IsCrossRegion returns true if request signing region is not same as configured region
func IsCrossRegion(req *request.Request, otherRegion string) bool {
return req.ClientInfo.SigningRegion != otherRegion
}
| 65 |
session-manager-plugin | aws | Go | package arn
import (
"strings"
"github.com/aws/aws-sdk-go/aws/arn"
)
// AccessPointARN provides representation
type AccessPointARN struct {
arn.ARN
AccessPointName string
}
// GetARN returns the base ARN for the Access Point resource
func (a AccessPointARN) GetARN() arn.ARN {
return a.ARN
}
// ParseAccessPointResource attempts to parse the ARN's resource as an
// AccessPoint resource.
//
// Supported Access point resource format:
// - Access point format: arn:{partition}:s3:{region}:{accountId}:accesspoint/{accesspointName}
// - example: arn.aws.s3.us-west-2.012345678901:accesspoint/myaccesspoint
//
func ParseAccessPointResource(a arn.ARN, resParts []string) (AccessPointARN, error) {
if len(a.Region) == 0 {
return AccessPointARN{}, InvalidARNError{ARN: a, Reason: "region not set"}
}
if len(a.AccountID) == 0 {
return AccessPointARN{}, InvalidARNError{ARN: a, Reason: "account-id not set"}
}
if len(resParts) == 0 {
return AccessPointARN{}, InvalidARNError{ARN: a, Reason: "resource-id not set"}
}
if len(resParts) > 1 {
return AccessPointARN{}, InvalidARNError{ARN: a, Reason: "sub resource not supported"}
}
resID := resParts[0]
if len(strings.TrimSpace(resID)) == 0 {
return AccessPointARN{}, InvalidARNError{ARN: a, Reason: "resource-id not set"}
}
return AccessPointARN{
ARN: a,
AccessPointName: resID,
}, nil
}
| 51 |
session-manager-plugin | aws | Go | // +build go1.7
package arn
import (
"reflect"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws/arn"
)
func TestParseAccessPointResource(t *testing.T) {
cases := map[string]struct {
ARN arn.ARN
ExpectErr string
ExpectARN AccessPointARN
}{
"region not set": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
AccountID: "012345678901",
Resource: "accesspoint/myendpoint",
},
ExpectErr: "region not set",
},
"account-id not set": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
Resource: "accesspoint/myendpoint",
},
ExpectErr: "account-id not set",
},
"resource-id not set": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "accesspoint",
},
ExpectErr: "resource-id not set",
},
"resource-id empty": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "accesspoint:",
},
ExpectErr: "resource-id not set",
},
"resource not supported": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "accesspoint/endpoint/object/key",
},
ExpectErr: "sub resource not supported",
},
"valid resource-id": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "accesspoint/endpoint",
},
ExpectARN: AccessPointARN{
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "accesspoint/endpoint",
},
AccessPointName: "endpoint",
},
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
resParts := SplitResource(c.ARN.Resource)
a, err := ParseAccessPointResource(c.ARN, resParts[1:])
if len(c.ExpectErr) == 0 && err != nil {
t.Fatalf("expect no error but got %v", err)
} else if len(c.ExpectErr) != 0 && err == nil {
t.Fatalf("expect error %q, but got nil", c.ExpectErr)
} else if len(c.ExpectErr) != 0 && err != nil {
if e, a := c.ExpectErr, err.Error(); !strings.Contains(a, e) {
t.Fatalf("expect error %q, got %q", e, a)
}
return
}
if e, a := c.ExpectARN, a; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
| 110 |
session-manager-plugin | aws | Go | package arn
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws/arn"
)
var supportedServiceARN = []string{
"s3",
"s3-outposts",
"s3-object-lambda",
}
func isSupportedServiceARN(service string) bool {
for _, name := range supportedServiceARN {
if name == service {
return true
}
}
return false
}
// Resource provides the interfaces abstracting ARNs of specific resource
// types.
type Resource interface {
GetARN() arn.ARN
String() string
}
// ResourceParser provides the function for parsing an ARN's resource
// component into a typed resource.
type ResourceParser func(arn.ARN) (Resource, error)
// ParseResource parses an AWS ARN into a typed resource for the S3 API.
func ParseResource(s string, resParser ResourceParser) (resARN Resource, err error) {
a, err := arn.Parse(s)
if err != nil {
return nil, err
}
if len(a.Partition) == 0 {
return nil, InvalidARNError{ARN: a, Reason: "partition not set"}
}
if !isSupportedServiceARN(a.Service) {
return nil, InvalidARNError{ARN: a, Reason: "service is not supported"}
}
if strings.HasPrefix(a.Region, "fips-") || strings.HasSuffix(a.Region, "-fips") {
return nil, InvalidARNError{ARN: a, Reason: "FIPS region not allowed in ARN"}
}
if len(a.Resource) == 0 {
return nil, InvalidARNError{ARN: a, Reason: "resource not set"}
}
return resParser(a)
}
// SplitResource splits the resource components by the ARN resource delimiters.
func SplitResource(v string) []string {
var parts []string
var offset int
for offset <= len(v) {
idx := strings.IndexAny(v[offset:], "/:")
if idx < 0 {
parts = append(parts, v[offset:])
break
}
parts = append(parts, v[offset:idx+offset])
offset += idx + 1
}
return parts
}
// IsARN returns whether the given string is an ARN
func IsARN(s string) bool {
return arn.IsARN(s)
}
// InvalidARNError provides the error for an invalid ARN error.
type InvalidARNError struct {
ARN arn.ARN
Reason string
}
// Error returns a string denoting the occurred InvalidARNError
func (e InvalidARNError) Error() string {
return fmt.Sprintf("invalid Amazon %s ARN, %s, %s", e.ARN.Service, e.Reason, e.ARN.String())
}
| 95 |
session-manager-plugin | aws | Go | // +build go1.7
package arn
import (
"reflect"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws/arn"
)
func TestParseResource(t *testing.T) {
cases := map[string]struct {
Input string
MappedResources map[string]func(arn.ARN, []string) (Resource, error)
Expect Resource
ExpectErr string
}{
"Empty ARN": {
Input: "",
ExpectErr: "arn: invalid prefix",
},
"No Partition": {
Input: "arn::sqs:us-west-2:012345678901:accesspoint",
ExpectErr: "partition not set",
},
"Not S3 ARN": {
Input: "arn:aws:sqs:us-west-2:012345678901:accesspoint",
ExpectErr: "service is not supported",
},
"No Resource": {
Input: "arn:aws:s3:us-west-2:012345678901:",
ExpectErr: "resource not set",
},
"Unknown Resource Type": {
Input: "arn:aws:s3:us-west-2:012345678901:myresource",
ExpectErr: "unknown resource type",
},
"Unknown BucketARN Resource Type": {
Input: "arn:aws:s3:us-west-2:012345678901:bucket_name:mybucket",
ExpectErr: "unknown resource type",
},
"Unknown Resource Type with Resource and Sub-Resource": {
Input: "arn:aws:s3:us-west-2:012345678901:somethingnew:myresource/subresource",
ExpectErr: "unknown resource type",
},
"Access Point with sub resource": {
Input: "arn:aws:s3:us-west-2:012345678901:accesspoint:myresource/subresource",
MappedResources: map[string]func(arn.ARN, []string) (Resource, error){
"accesspoint": func(a arn.ARN, parts []string) (Resource, error) {
return ParseAccessPointResource(a, parts)
},
},
ExpectErr: "resource not supported",
},
"AccessPoint Resource Type": {
Input: "arn:aws:s3:us-west-2:012345678901:accesspoint:myendpoint",
MappedResources: map[string]func(arn.ARN, []string) (Resource, error){
"accesspoint": func(a arn.ARN, parts []string) (Resource, error) {
return ParseAccessPointResource(a, parts)
},
},
Expect: AccessPointARN{
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "accesspoint:myendpoint",
},
AccessPointName: "myendpoint",
},
},
"AccessPoint Resource Type With Path Syntax": {
Input: "arn:aws:s3:us-west-2:012345678901:accesspoint/myendpoint",
MappedResources: map[string]func(arn.ARN, []string) (Resource, error){
"accesspoint": func(a arn.ARN, parts []string) (Resource, error) {
return ParseAccessPointResource(a, parts)
},
},
Expect: AccessPointARN{
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "accesspoint/myendpoint",
},
AccessPointName: "myendpoint",
},
},
"invalid FIPS pseudo region in ARN (prefix)": {
Input: "arn:aws:s3:fips-us-west-2:012345678901:accesspoint/myendpoint",
ExpectErr: "FIPS region not allowed in ARN",
},
"invalid FIPS pseudo region in ARN (suffix)": {
Input: "arn:aws:s3:us-west-2-fips:012345678901:accesspoint/myendpoint",
ExpectErr: "FIPS region not allowed in ARN",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
parsed, err := ParseResource(c.Input, mappedResourceParser(c.MappedResources))
if len(c.ExpectErr) == 0 && err != nil {
t.Fatalf("expect no error but got %v", err)
} else if len(c.ExpectErr) != 0 && err == nil {
t.Fatalf("expect error but got nil")
} else if len(c.ExpectErr) != 0 && err != nil {
if e, a := c.ExpectErr, err.Error(); !strings.Contains(a, e) {
t.Fatalf("expect error %q, got %q", e, a)
}
return
}
if e, a := c.Expect, parsed; !reflect.DeepEqual(e, a) {
t.Errorf("Expect %v, got %v", e, a)
}
})
}
}
func mappedResourceParser(kinds map[string]func(arn.ARN, []string) (Resource, error)) ResourceParser {
return func(a arn.ARN) (Resource, error) {
parts := SplitResource(a.Resource)
fn, ok := kinds[parts[0]]
if !ok {
return nil, InvalidARNError{ARN: a, Reason: "unknown resource type"}
}
return fn(a, parts[1:])
}
}
func TestSplitResource(t *testing.T) {
cases := []struct {
Input string
Expect []string
}{
{
Input: "accesspoint:myendpoint",
Expect: []string{"accesspoint", "myendpoint"},
},
{
Input: "accesspoint/myendpoint",
Expect: []string{"accesspoint", "myendpoint"},
},
{
Input: "accesspoint",
Expect: []string{"accesspoint"},
},
{
Input: "accesspoint:",
Expect: []string{"accesspoint", ""},
},
{
Input: "accesspoint: ",
Expect: []string{"accesspoint", " "},
},
{
Input: "accesspoint:endpoint/object/key",
Expect: []string{"accesspoint", "endpoint", "object", "key"},
},
}
for _, c := range cases {
t.Run(c.Input, func(t *testing.T) {
parts := SplitResource(c.Input)
if e, a := c.Expect, parts; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
| 177 |
session-manager-plugin | aws | Go | package arn
import (
"strings"
"github.com/aws/aws-sdk-go/aws/arn"
)
// OutpostARN interface that should be satisfied by outpost ARNs
type OutpostARN interface {
Resource
GetOutpostID() string
}
// ParseOutpostARNResource will parse a provided ARNs resource using the appropriate ARN format
// and return a specific OutpostARN type
//
// Currently supported outpost ARN formats:
// * Outpost AccessPoint ARN format:
// - ARN format: arn:{partition}:s3-outposts:{region}:{accountId}:outpost/{outpostId}/accesspoint/{accesspointName}
// - example: arn:aws:s3-outposts:us-west-2:012345678901:outpost/op-1234567890123456/accesspoint/myaccesspoint
//
// * Outpost Bucket ARN format:
// - ARN format: arn:{partition}:s3-outposts:{region}:{accountId}:outpost/{outpostId}/bucket/{bucketName}
// - example: arn:aws:s3-outposts:us-west-2:012345678901:outpost/op-1234567890123456/bucket/mybucket
//
// Other outpost ARN formats may be supported and added in the future.
//
func ParseOutpostARNResource(a arn.ARN, resParts []string) (OutpostARN, error) {
if len(a.Region) == 0 {
return nil, InvalidARNError{ARN: a, Reason: "region not set"}
}
if len(a.AccountID) == 0 {
return nil, InvalidARNError{ARN: a, Reason: "account-id not set"}
}
// verify if outpost id is present and valid
if len(resParts) == 0 || len(strings.TrimSpace(resParts[0])) == 0 {
return nil, InvalidARNError{ARN: a, Reason: "outpost resource-id not set"}
}
// verify possible resource type exists
if len(resParts) < 3 {
return nil, InvalidARNError{
ARN: a, Reason: "incomplete outpost resource type. Expected bucket or access-point resource to be present",
}
}
// Since we know this is a OutpostARN fetch outpostID
outpostID := strings.TrimSpace(resParts[0])
switch resParts[1] {
case "accesspoint":
accesspointARN, err := ParseAccessPointResource(a, resParts[2:])
if err != nil {
return OutpostAccessPointARN{}, err
}
return OutpostAccessPointARN{
AccessPointARN: accesspointARN,
OutpostID: outpostID,
}, nil
case "bucket":
bucketName, err := parseBucketResource(a, resParts[2:])
if err != nil {
return nil, err
}
return OutpostBucketARN{
ARN: a,
BucketName: bucketName,
OutpostID: outpostID,
}, nil
default:
return nil, InvalidARNError{ARN: a, Reason: "unknown resource set for outpost ARN"}
}
}
// OutpostAccessPointARN represents outpost access point ARN.
type OutpostAccessPointARN struct {
AccessPointARN
OutpostID string
}
// GetOutpostID returns the outpost id of outpost access point arn
func (o OutpostAccessPointARN) GetOutpostID() string {
return o.OutpostID
}
// OutpostBucketARN represents the outpost bucket ARN.
type OutpostBucketARN struct {
arn.ARN
BucketName string
OutpostID string
}
// GetOutpostID returns the outpost id of outpost bucket arn
func (o OutpostBucketARN) GetOutpostID() string {
return o.OutpostID
}
// GetARN retrives the base ARN from outpost bucket ARN resource
func (o OutpostBucketARN) GetARN() arn.ARN {
return o.ARN
}
// parseBucketResource attempts to parse the ARN's bucket resource and retrieve the
// bucket resource id.
//
// parseBucketResource only parses the bucket resource id.
//
func parseBucketResource(a arn.ARN, resParts []string) (bucketName string, err error) {
if len(resParts) == 0 {
return bucketName, InvalidARNError{ARN: a, Reason: "bucket resource-id not set"}
}
if len(resParts) > 1 {
return bucketName, InvalidARNError{ARN: a, Reason: "sub resource not supported"}
}
bucketName = strings.TrimSpace(resParts[0])
if len(bucketName) == 0 {
return bucketName, InvalidARNError{ARN: a, Reason: "bucket resource-id not set"}
}
return bucketName, err
}
| 127 |
session-manager-plugin | aws | Go | // +build go1.7
package arn
import (
"reflect"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws/arn"
)
func TestParseOutpostAccessPointARNResource(t *testing.T) {
cases := map[string]struct {
ARN arn.ARN
ExpectErr string
ExpectARN OutpostAccessPointARN
}{
"region not set": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
AccountID: "012345678901",
Resource: "outpost/myoutpost/accesspoint/myendpoint",
},
ExpectErr: "region not set",
},
"account-id not set": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
Resource: "outpost/myoutpost/accesspoint/myendpoint",
},
ExpectErr: "account-id not set",
},
"resource-id not set": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "myoutpost",
},
ExpectErr: "resource-id not set",
},
"resource-id empty": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost:",
},
ExpectErr: "resource-id not set",
},
"resource not supported": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/accesspoint/endpoint/object/key",
},
ExpectErr: "sub resource not supported",
},
"access-point not defined": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/endpoint/object/key",
},
ExpectErr: "unknown resource set for outpost ARN",
},
"valid resource-id": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/accesspoint/myaccesspoint",
},
ExpectARN: OutpostAccessPointARN{
AccessPointARN: AccessPointARN{
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/accesspoint/myaccesspoint",
},
AccessPointName: "myaccesspoint",
},
OutpostID: "myoutpost",
},
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
resParts := SplitResource(c.ARN.Resource)
a, err := ParseOutpostARNResource(c.ARN, resParts[1:])
if len(c.ExpectErr) == 0 && err != nil {
t.Fatalf("expect no error but got %v", err)
} else if len(c.ExpectErr) != 0 && err == nil {
t.Fatalf("expect error %q, but got nil", c.ExpectErr)
} else if len(c.ExpectErr) != 0 && err != nil {
if e, a := c.ExpectErr, err.Error(); !strings.Contains(a, e) {
t.Fatalf("expect error %q, got %q", e, a)
}
return
}
if e, a := c.ExpectARN, a; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
func TestParseOutpostBucketARNResource(t *testing.T) {
cases := map[string]struct {
ARN arn.ARN
ExpectErr string
ExpectARN OutpostBucketARN
}{
"region not set": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
AccountID: "012345678901",
Resource: "outpost/myoutpost/bucket/mybucket",
},
ExpectErr: "region not set",
},
"resource-id empty": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost:",
},
ExpectErr: "resource-id not set",
},
"resource not supported": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/bucket/mybucket/object/key",
},
ExpectErr: "sub resource not supported",
},
"bucket not defined": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/endpoint/object/key",
},
ExpectErr: "unknown resource set for outpost ARN",
},
"valid resource-id": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/bucket/mybucket",
},
ExpectARN: OutpostBucketARN{
ARN: arn.ARN{
Partition: "aws",
Service: "s3-outposts",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "outpost/myoutpost/bucket/mybucket",
},
BucketName: "mybucket",
OutpostID: "myoutpost",
},
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
resParts := SplitResource(c.ARN.Resource)
a, err := ParseOutpostARNResource(c.ARN, resParts[1:])
if len(c.ExpectErr) == 0 && err != nil {
t.Fatalf("expect no error but got %v", err)
} else if len(c.ExpectErr) != 0 && err == nil {
t.Fatalf("expect error %q, but got nil", c.ExpectErr)
} else if len(c.ExpectErr) != 0 && err != nil {
if e, a := c.ExpectErr, err.Error(); !strings.Contains(a, e) {
t.Fatalf("expect error %q, got %q", e, a)
}
return
}
if e, a := c.ExpectARN, a; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
func TestParseBucketResource(t *testing.T) {
cases := map[string]struct {
ARN arn.ARN
ExpectErr string
ExpectBucketName string
}{
"resource-id empty": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "bucket:",
},
ExpectErr: "bucket resource-id not set",
},
"resource not supported": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "bucket/mybucket/object/key",
},
ExpectErr: "sub resource not supported",
},
"valid resource-id": {
ARN: arn.ARN{
Partition: "aws",
Service: "s3",
Region: "us-west-2",
AccountID: "012345678901",
Resource: "bucket/mybucket",
},
ExpectBucketName: "mybucket",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
resParts := SplitResource(c.ARN.Resource)
a, err := parseBucketResource(c.ARN, resParts[1:])
if len(c.ExpectErr) == 0 && err != nil {
t.Fatalf("expect no error but got %v", err)
} else if len(c.ExpectErr) != 0 && err == nil {
t.Fatalf("expect error %q, but got nil", c.ExpectErr)
} else if len(c.ExpectErr) != 0 && err != nil {
if e, a := c.ExpectErr, err.Error(); !strings.Contains(a, e) {
t.Fatalf("expect error %q, got %q", e, a)
}
return
}
if e, a := c.ExpectBucketName, a; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
| 274 |
session-manager-plugin | aws | Go | package arn
// S3ObjectLambdaARN represents an ARN for the s3-object-lambda service
type S3ObjectLambdaARN interface {
Resource
isS3ObjectLambdasARN()
}
// S3ObjectLambdaAccessPointARN is an S3ObjectLambdaARN for the Access Point resource type
type S3ObjectLambdaAccessPointARN struct {
AccessPointARN
}
func (s S3ObjectLambdaAccessPointARN) isS3ObjectLambdasARN() {}
| 16 |
session-manager-plugin | aws | Go | package s3err
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
// RequestFailure provides additional S3 specific metadata for the request
// failure.
type RequestFailure struct {
awserr.RequestFailure
hostID string
}
// NewRequestFailure returns a request failure error decordated with S3
// specific metadata.
func NewRequestFailure(err awserr.RequestFailure, hostID string) *RequestFailure {
return &RequestFailure{RequestFailure: err, hostID: hostID}
}
func (r RequestFailure) Error() string {
extra := fmt.Sprintf("status code: %d, request id: %s, host id: %s",
r.StatusCode(), r.RequestID(), r.hostID)
return awserr.SprintError(r.Code(), r.Message(), extra, r.OrigErr())
}
func (r RequestFailure) String() string {
return r.Error()
}
// HostID returns the HostID request response value.
func (r RequestFailure) HostID() string {
return r.hostID
}
// RequestFailureWrapperHandler returns a handler to rap an
// awserr.RequestFailure with the S3 request ID 2 from the response.
func RequestFailureWrapperHandler() request.NamedHandler {
return request.NamedHandler{
Name: "awssdk.s3.errorHandler",
Fn: func(req *request.Request) {
reqErr, ok := req.Error.(awserr.RequestFailure)
if !ok || reqErr == nil {
return
}
hostID := req.HTTPResponse.Header.Get("X-Amz-Id-2")
if req.Error == nil {
return
}
req.Error = NewRequestFailure(reqErr, hostID)
},
}
}
| 58 |
session-manager-plugin | aws | Go | package sdkio
const (
// Byte is 8 bits
Byte int64 = 1
// KibiByte (KiB) is 1024 Bytes
KibiByte = Byte * 1024
// MebiByte (MiB) is 1024 KiB
MebiByte = KibiByte * 1024
// GibiByte (GiB) is 1024 MiB
GibiByte = MebiByte * 1024
)
| 13 |
session-manager-plugin | aws | Go | // +build !go1.7
package sdkio
// Copy of Go 1.7 io package's Seeker constants.
const (
SeekStart = 0 // seek relative to the origin of the file
SeekCurrent = 1 // seek relative to the current offset
SeekEnd = 2 // seek relative to the end
)
| 11 |
session-manager-plugin | aws | Go | // +build go1.7
package sdkio
import "io"
// Alias for Go 1.7 io package Seeker constants
const (
SeekStart = io.SeekStart // seek relative to the origin of the file
SeekCurrent = io.SeekCurrent // seek relative to the current offset
SeekEnd = io.SeekEnd // seek relative to the end
)
| 13 |
session-manager-plugin | aws | Go | // +build go1.10
package sdkmath
import "math"
// Round returns the nearest integer, rounding half away from zero.
//
// Special cases are:
// Round(±0) = ±0
// Round(±Inf) = ±Inf
// Round(NaN) = NaN
func Round(x float64) float64 {
return math.Round(x)
}
| 16 |
session-manager-plugin | aws | Go | // +build !go1.10
package sdkmath
import "math"
// Copied from the Go standard library's (Go 1.12) math/floor.go for use in
// Go version prior to Go 1.10.
const (
uvone = 0x3FF0000000000000
mask = 0x7FF
shift = 64 - 11 - 1
bias = 1023
signMask = 1 << 63
fracMask = 1<<shift - 1
)
// Round returns the nearest integer, rounding half away from zero.
//
// Special cases are:
// Round(±0) = ±0
// Round(±Inf) = ±Inf
// Round(NaN) = NaN
//
// Copied from the Go standard library's (Go 1.12) math/floor.go for use in
// Go version prior to Go 1.10.
func Round(x float64) float64 {
// Round is a faster implementation of:
//
// func Round(x float64) float64 {
// t := Trunc(x)
// if Abs(x-t) >= 0.5 {
// return t + Copysign(1, x)
// }
// return t
// }
bits := math.Float64bits(x)
e := uint(bits>>shift) & mask
if e < bias {
// Round abs(x) < 1 including denormals.
bits &= signMask // +-0
if e == bias-1 {
bits |= uvone // +-1
}
} else if e < bias+shift {
// Round any abs(x) >= 1 containing a fractional component [0,1).
//
// Numbers with larger exponents are returned unchanged since they
// must be either an integer, infinity, or NaN.
const half = 1 << (shift - 1)
e -= bias
bits += half >> e
bits &^= fracMask >> e
}
return math.Float64frombits(bits)
}
| 57 |
session-manager-plugin | aws | Go | package sdkrand
import (
"math/rand"
"sync"
"time"
)
// lockedSource is a thread-safe implementation of rand.Source
type lockedSource struct {
lk sync.Mutex
src rand.Source
}
func (r *lockedSource) Int63() (n int64) {
r.lk.Lock()
n = r.src.Int63()
r.lk.Unlock()
return
}
func (r *lockedSource) Seed(seed int64) {
r.lk.Lock()
r.src.Seed(seed)
r.lk.Unlock()
}
// SeededRand is a new RNG using a thread safe implementation of rand.Source
var SeededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())})
| 30 |
session-manager-plugin | aws | Go | // +build go1.6
package sdkrand
import "math/rand"
// Read provides the stub for math.Rand.Read method support for go version's
// 1.6 and greater.
func Read(r *rand.Rand, p []byte) (int, error) {
return r.Read(p)
}
| 12 |
session-manager-plugin | aws | Go | // +build !go1.6
package sdkrand
import "math/rand"
// Read backfills Go 1.6's math.Rand.Reader for Go 1.5
func Read(r *rand.Rand, p []byte) (n int, err error) {
// Copy of Go standard libraries math package's read function not added to
// standard library until Go 1.6.
var pos int8
var val int64
for n = 0; n < len(p); n++ {
if pos == 0 {
val = r.Int63()
pos = 7
}
p[n] = byte(val)
val >>= 8
pos--
}
return n, err
}
| 25 |
session-manager-plugin | aws | Go | package sdktesting
import (
"os"
"runtime"
"strings"
)
// StashEnv stashes the current environment variables except variables listed in envToKeepx
// Returns an function to pop out old environment
func StashEnv(envToKeep ...string) func() {
if runtime.GOOS == "windows" {
envToKeep = append(envToKeep, "ComSpec")
envToKeep = append(envToKeep, "SYSTEM32")
envToKeep = append(envToKeep, "SYSTEMROOT")
}
envToKeep = append(envToKeep, "PATH")
extraEnv := getEnvs(envToKeep)
originalEnv := os.Environ()
os.Clearenv() // clear env
for key, val := range extraEnv {
os.Setenv(key, val)
}
return func() {
popEnv(originalEnv)
}
}
func getEnvs(envs []string) map[string]string {
extraEnvs := make(map[string]string)
for _, env := range envs {
if val, ok := os.LookupEnv(env); ok && len(val) > 0 {
extraEnvs[env] = val
}
}
return extraEnvs
}
// PopEnv takes the list of the environment values and injects them into the
// process's environment variable data. Clears any existing environment values
// that may already exist.
func popEnv(env []string) {
os.Clearenv()
for _, e := range env {
p := strings.SplitN(e, "=", 2)
k, v := p[0], ""
if len(p) > 1 {
v = p[1]
}
os.Setenv(k, v)
}
}
| 54 |
session-manager-plugin | aws | Go | package sdkuri
import (
"path"
"strings"
)
// PathJoin will join the elements of the path delimited by the "/"
// character. Similar to path.Join with the exception the trailing "/"
// character is preserved if present.
func PathJoin(elems ...string) string {
if len(elems) == 0 {
return ""
}
hasTrailing := strings.HasSuffix(elems[len(elems)-1], "/")
str := path.Join(elems...)
if hasTrailing && str != "/" {
str += "/"
}
return str
}
| 24 |
session-manager-plugin | aws | Go | package sdkuri
import "testing"
func TestPathJoin(t *testing.T) {
cases := []struct {
Elems []string
Expect string
}{
{Elems: []string{"/"}, Expect: "/"},
{Elems: []string{}, Expect: ""},
{Elems: []string{"blah", "el", "blah/"}, Expect: "blah/el/blah/"},
{Elems: []string{"/asd", "asdfa", "asdfasd/"}, Expect: "/asd/asdfa/asdfasd/"},
{Elems: []string{"asdfa", "asdfa", "asdfads"}, Expect: "asdfa/asdfa/asdfads"},
}
for _, c := range cases {
if e, a := c.Expect, PathJoin(c.Elems...); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
}
| 22 |
session-manager-plugin | aws | Go | package shareddefaults
const (
// ECSCredsProviderEnvVar is an environmental variable key used to
// determine which path needs to be hit.
ECSCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
)
// ECSContainerCredentialsURI is the endpoint to retrieve container
// credentials. This can be overridden to test to ensure the credential process
// is behaving correctly.
var ECSContainerCredentialsURI = "http://169.254.170.2"
| 13 |
session-manager-plugin | aws | Go | package shareddefaults
import (
"os"
"path/filepath"
"runtime"
)
// SharedCredentialsFilename returns the SDK's default file path
// for the shared credentials file.
//
// Builds the shared config file path based on the OS's platform.
//
// - Linux/Unix: $HOME/.aws/credentials
// - Windows: %USERPROFILE%\.aws\credentials
func SharedCredentialsFilename() string {
return filepath.Join(UserHomeDir(), ".aws", "credentials")
}
// SharedConfigFilename returns the SDK's default file path for
// the shared config file.
//
// Builds the shared config file path based on the OS's platform.
//
// - Linux/Unix: $HOME/.aws/config
// - Windows: %USERPROFILE%\.aws\config
func SharedConfigFilename() string {
return filepath.Join(UserHomeDir(), ".aws", "config")
}
// UserHomeDir returns the home directory for the user the process is
// running under.
func UserHomeDir() string {
if runtime.GOOS == "windows" { // Windows
return os.Getenv("USERPROFILE")
}
// *nix
return os.Getenv("HOME")
}
| 41 |
session-manager-plugin | aws | Go | // +build !windows
package shareddefaults_test
import (
"os"
"path/filepath"
"testing"
"github.com/aws/aws-sdk-go/internal/sdktesting"
"github.com/aws/aws-sdk-go/internal/shareddefaults"
)
func TestSharedCredsFilename(t *testing.T) {
restoreEnvFn := sdktesting.StashEnv()
defer restoreEnvFn()
os.Setenv("HOME", "home_dir")
os.Setenv("USERPROFILE", "profile_dir")
expect := filepath.Join("home_dir", ".aws", "credentials")
name := shareddefaults.SharedCredentialsFilename()
if e, a := expect, name; e != a {
t.Errorf("expect %q shared creds filename, got %q", e, a)
}
}
func TestSharedConfigFilename(t *testing.T) {
restoreEnvFn := sdktesting.StashEnv()
defer restoreEnvFn()
os.Setenv("HOME", "home_dir")
os.Setenv("USERPROFILE", "profile_dir")
expect := filepath.Join("home_dir", ".aws", "config")
name := shareddefaults.SharedConfigFilename()
if e, a := expect, name; e != a {
t.Errorf("expect %q shared config filename, got %q", e, a)
}
}
| 43 |
session-manager-plugin | aws | Go | // +build windows
package shareddefaults_test
import (
"os"
"path/filepath"
"testing"
"github.com/aws/aws-sdk-go/internal/sdktesting"
"github.com/aws/aws-sdk-go/internal/shareddefaults"
)
func TestSharedCredsFilename(t *testing.T) {
restoreEnvFn := sdktesting.StashEnv()
defer restoreEnvFn()
os.Setenv("HOME", "home_dir")
os.Setenv("USERPROFILE", "profile_dir")
expect := filepath.Join("profile_dir", ".aws", "credentials")
name := shareddefaults.SharedCredentialsFilename()
if e, a := expect, name; e != a {
t.Errorf("expect %q shared creds filename, got %q", e, a)
}
}
func TestSharedConfigFilename(t *testing.T) {
restoreEnvFn := sdktesting.StashEnv()
defer restoreEnvFn()
os.Setenv("HOME", "home_dir")
os.Setenv("USERPROFILE", "profile_dir")
expect := filepath.Join("profile_dir", ".aws", "config")
name := shareddefaults.SharedConfigFilename()
if e, a := expect, name; e != a {
t.Errorf("expect %q shared config filename, got %q", e, a)
}
}
| 43 |
session-manager-plugin | aws | Go | package smithytesting
import (
"bytes"
"fmt"
"reflect"
"github.com/aws/aws-sdk-go/internal/smithytesting/xml"
)
// XMLEqual asserts two XML documents by sorting the XML and comparing the
// strings It returns an error in case of mismatch or in case of malformed XML
// found while sorting. In case of mismatched XML, the error string will
// contain the diff between the two XML documents.
func XMLEqual(expectBytes, actualBytes []byte) error {
actualString, err := xml.SortXML(bytes.NewBuffer(actualBytes), true)
if err != nil {
return err
}
expectString, err := xml.SortXML(bytes.NewBuffer(expectBytes), true)
if err != nil {
return err
}
if !reflect.DeepEqual(expectString, actualString) {
return fmt.Errorf("unexpected XML mismatch\nexpect: %+v\nactual: %+v",
expectString, actualString)
}
return nil
}
| 33 |
session-manager-plugin | aws | Go | // +build go1.9
package smithytesting
import (
"strings"
"testing"
)
func TestEqualXMLUtil(t *testing.T) {
cases := map[string]struct {
expectedXML string
actualXML string
expectErr string
}{
"empty": {
expectedXML: ``,
actualXML: ``,
},
"emptyWithDiff": {
expectedXML: ``,
actualXML: `<Root></Root>`,
expectErr: "XML mismatch",
},
"simpleXML": {
expectedXML: `<Root></Root>`,
actualXML: `<Root></Root>`,
},
"simpleXMLWithDiff": {
expectedXML: `<Root></Root>`,
actualXML: `<Root>abc</Root>`,
expectErr: "XML mismatch",
},
"nestedXML": {
expectedXML: `<Root><abc>123</abc><cde>xyz</cde></Root>`,
actualXML: `<Root><abc>123</abc><cde>xyz</cde></Root>`,
},
"nestedXMLWithExpectedDiff": {
expectedXML: `<Root><abc>123</abc><cde>xyz</cde><pqr>234</pqr></Root>`,
actualXML: `<Root><abc>123</abc><cde>xyz</cde></Root>`,
expectErr: "XML mismatch",
},
"nestedXMLWithActualDiff": {
expectedXML: `<Root><abc>123</abc><cde>xyz</cde></Root>`,
actualXML: `<Root><abc>123</abc><cde>xyz</cde><pqr>234</pqr></Root>`,
expectErr: "XML mismatch",
},
"Array": {
expectedXML: `<Root><list><member><nested>xyz</nested></member><member><nested>abc</nested></member></list></Root>`,
actualXML: `<Root><list><member><nested>xyz</nested></member><member><nested>abc</nested></member></list></Root>`,
},
"ArrayWithSecondDiff": {
expectedXML: `<Root><list><member><nested>xyz</nested></member><member><nested>123</nested></member></list></Root>`,
actualXML: `<Root><list><member><nested>xyz</nested></member><member><nested>345</nested></member></list></Root>`,
expectErr: "XML mismatch",
},
"ArrayWithFirstDiff": {
expectedXML: `<Root><list><member><nested>abc</nested></member><member><nested>345</nested></member></list></Root>`,
actualXML: `<Root><list><member><nested>xyz</nested></member><member><nested>345</nested></member></list></Root>`,
expectErr: "XML mismatch",
},
"ArrayWithMixedDiff": {
expectedXML: `<Root><list><member><nested>345</nested></member><member><nested>xyz</nested></member></list></Root>`,
actualXML: `<Root><list><member><nested>xyz</nested></member><member><nested>345</nested></member></list></Root>`,
},
"ArrayWithRepetitiveMembers": {
expectedXML: `<Root><list><member><nested>xyz</nested></member><member><nested>xyz</nested></member></list></Root>`,
actualXML: `<Root><list><member><nested>xyz</nested></member><member><nested>xyz</nested></member></list></Root>`,
},
"Map": {
expectedXML: `<Root><map><entry><key>abc</key><value>123</value></entry><entry><key>cde</key><value>356</value></entry></map></Root>`,
actualXML: `<Root><map><entry><key>abc</key><value>123</value></entry><entry><key>cde</key><value>356</value></entry></map></Root>`,
},
"MapWithFirstDiff": {
expectedXML: `<Root><map><entry><key>bcf</key><value>123</value></entry><entry><key>cde</key><value>356</value></entry></map></Root>`,
actualXML: `<Root><map><entry><key>abc</key><value>123</value></entry><entry><key>cde</key><value>356</value></entry></map></Root>`,
expectErr: "XML mismatch",
},
"MapWithSecondDiff": {
expectedXML: `<Root><map><entry><key>abc</key><value>123</value></entry><entry><key>cde</key><value>abc</value></entry></map></Root>`,
actualXML: `<Root><map><entry><key>abc</key><value>123</value></entry><entry><key>cde</key><value>356</value></entry></map></Root>`,
expectErr: "XML mismatch",
},
"MapWithMixedDiff": {
expectedXML: `<Root><map><entry><key>cde</key><value>356</value></entry><entry><key>abc</key><value>123</value></entry></map></Root>`,
actualXML: `<Root><map><entry><key>abc</key><value>123</value></entry><entry><key>cde</key><value>356</value></entry></map></Root>`,
},
"MismatchCheckforKeyValue": {
expectedXML: `<Root><map><entry><key>cde</key><value>abc</value></entry><entry><key>abc</key><value>356</value></entry></map></Root>`,
actualXML: `<Root><map><entry><key>abc</key><value>123</value></entry><entry><key>cde</key><value>356</value></entry></map></Root>`,
expectErr: "XML mismatch",
},
"MixMapAndListNestedXML": {
expectedXML: `<Root><list>mem1</list><list>mem2</list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><alpha><x>gamma</x></alpha></nested></v></map></Root>`,
actualXML: `<Root><list>mem1</list><list>mem2</list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><alpha><x>gamma</x></alpha></nested></v></map></Root>`,
},
"MixMapAndListNestedXMLWithDiff": {
expectedXML: `<Root><list>mem1</list><list>mem2</list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><alpha><x>gamma</x></alpha></nested></v></map></Root>`,
actualXML: `<Root><list>mem1</list><list>mem2</list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><beta><x>gamma</x></beta></nested></v></map></Root>`,
expectErr: "XML mismatch",
},
"xmlWithNamespaceAndAttr": {
expectedXML: `<Root xmlns:ab="https://example.com" attr="apple">value</Root>`,
actualXML: `<Root xmlns:ab="https://example.com" attr="apple">value</Root>`,
},
"xmlUnorderedAttributes": {
expectedXML: `<Root atr="banana" attrNew="apple">v</Root>`,
actualXML: `<Root attrNew="apple" atr="banana">v</Root>`,
},
"xmlAttributesWithDiff": {
expectedXML: `<Root atr="someAtr" attrNew="apple">v</Root>`,
actualXML: `<Root attrNew="apple" atr="banana">v</Root>`,
expectErr: "XML mismatch",
},
"xmlUnorderedNamespaces": {
expectedXML: `<Root xmlns:ab="https://example.com" xmlns:baz="https://example2.com">v</Root>`,
actualXML: `<Root xmlns:baz="https://example2.com" xmlns:ab="https://example.com">v</Root>`,
},
"xmlNamespaceWithDiff": {
expectedXML: `<Root xmlns:ab="https://example-diff.com" xmlns:baz="https://example2.com">v</Root>`,
actualXML: `<Root xmlns:baz="https://example2.com" xmlns:ab="https://example.com">v</Root>`,
expectErr: "XML mismatch",
},
"NestedWithNamespaceAndAttributes": {
expectedXML: `<Root xmlns:ab="https://example.com" xmlns:un="https://example2.com" attr="test" attr2="test2"><ab:list>mem1</ab:list><ab:list>mem2</ab:list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><alpha><x>gamma</x></alpha></nested></v></map></Root>`,
actualXML: `<Root xmlns:ab="https://example.com" xmlns:un="https://example2.com" attr="test" attr2="test2"><ab:list>mem1</ab:list><ab:list>mem2</ab:list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><alpha><x>gamma</x></alpha></nested></v></map></Root>`,
},
"NestedWithNamespaceAndAttributesWithDiff": {
expectedXML: `<Root xmlns:ab="https://example.com" xmlns:un="https://example2.com" attr="test" attr2="test2"><list>mem2</list><ab:list>mem2</ab:list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><alpha><x>gamma</x></alpha></nested></v></map></Root>`,
actualXML: `<Root xmlns:ab="https://example.com" xmlns:un="https://example2.com" attr="test" attr2="test2"><list>mem1</list><ab:list>mem2</ab:list><map><k>abc</k><v><nested><enorm>abc</enorm></nested></v><k>xyz</k><v><nested><alpha><x>gamma</x></alpha></nested></v></map></Root>`,
expectErr: "XML mismatch",
},
"MalformedXML": {
expectedXML: `<Root><fmap><key>a</key><key2>a2</key2><value>v</value></fmap><fmap><key>b</key><key2>b2</key2><value>w</value></fmap></Root>`,
actualXML: `<Root><fmap><key>a</key><key2>a2</key2><value>v</value></fmap><fmap><key>b</key><key2>b2</key2><value>w</value></fmap></Root>`,
expectErr: "malformed xml",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
actual := []byte(c.actualXML)
expected := []byte(c.expectedXML)
err := XMLEqual(actual, expected)
if err != nil {
if len(c.expectErr) == 0 {
t.Fatalf("expected no error while parsing xml, got %v", err)
} else if !strings.Contains(err.Error(), c.expectErr) {
t.Fatalf("expected expected XML err to contain %s, got %s", c.expectErr, err.Error())
}
} else if len(c.expectErr) != 0 {
t.Fatalf("expected error %s, got none", c.expectErr)
}
})
}
}
| 158 |
session-manager-plugin | aws | Go | // Package xml is XML testing package that supports XML comparison utility.
// The package consists of ToStruct and StructToXML utils that help sort XML
// elements as per their nesting level. ToStruct function converts an XML
// document into a sorted tree node structure, while StructToXML converts the
// sorted XML nodes into a sorted XML document. SortXML function should be
// used to sort an XML document. It can be configured to ignore indentation
package xml
| 8 |
session-manager-plugin | aws | Go | package xml
import (
"bytes"
"encoding/xml"
"io"
"strings"
)
type xmlAttrSlice []xml.Attr
func (x xmlAttrSlice) Len() int {
return len(x)
}
func (x xmlAttrSlice) Less(i, j int) bool {
spaceI, spaceJ := x[i].Name.Space, x[j].Name.Space
localI, localJ := x[i].Name.Local, x[j].Name.Local
valueI, valueJ := x[i].Value, x[j].Value
spaceCmp := strings.Compare(spaceI, spaceJ)
localCmp := strings.Compare(localI, localJ)
valueCmp := strings.Compare(valueI, valueJ)
if spaceCmp == -1 || (spaceCmp == 0 && (localCmp == -1 || (localCmp == 0 && valueCmp == -1))) {
return true
}
return false
}
func (x xmlAttrSlice) Swap(i, j int) {
x[i], x[j] = x[j], x[i]
}
// SortXML sorts the reader's XML elements
func SortXML(r io.Reader, ignoreIndentation bool) (string, error) {
var buf bytes.Buffer
d := xml.NewDecoder(r)
root, err := ToStruct(d, nil, ignoreIndentation)
if err != nil {
return buf.String(), err
}
e := xml.NewEncoder(&buf)
err = StructToXML(e, root, true)
return buf.String(), err
}
| 49 |
session-manager-plugin | aws | Go | package xml
import (
"bytes"
"reflect"
"testing"
)
func TestSortXML(t *testing.T) {
xmlInput := bytes.NewReader([]byte(`<Root><cde>xyz</cde><abc>123</abc><xyz><item>1</item></xyz></Root>`))
sortedXML, err := SortXML(xmlInput, false)
expectedsortedXML := `<Root><abc>123</abc><cde>xyz</cde><xyz><item>1</item></xyz></Root>`
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if !reflect.DeepEqual(sortedXML, expectedsortedXML) {
t.Errorf("expect match\nexpect: %+v\nactual: %+v\n", expectedsortedXML, sortedXML)
}
}
| 21 |
session-manager-plugin | aws | Go | package xml
import (
"encoding/xml"
"fmt"
"io"
"sort"
"strings"
)
// A Node contains the values to be encoded or decoded.
type Node struct {
Name xml.Name `json:",omitempty"`
Children map[string][]*Node `json:",omitempty"`
Text string `json:",omitempty"`
Attr []xml.Attr `json:",omitempty"`
namespaces map[string]string
parent *Node
}
// NewXMLElement returns a pointer to a new Node initialized to default values.
func NewXMLElement(name xml.Name) *Node {
return &Node{
Name: name,
Children: map[string][]*Node{},
Attr: []xml.Attr{},
}
}
// AddChild adds child to the Node.
func (n *Node) AddChild(child *Node) {
child.parent = n
if _, ok := n.Children[child.Name.Local]; !ok {
// flattened will have multiple children with same tag name
n.Children[child.Name.Local] = []*Node{}
}
n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child)
}
// ToStruct converts a xml.Decoder stream to Node with nested values.
func ToStruct(d *xml.Decoder, s *xml.StartElement, ignoreIndentation bool) (*Node, error) {
out := &Node{}
for {
tok, err := d.Token()
if err != nil {
if err == io.EOF {
break
} else {
return out, err
}
}
if tok == nil {
break
}
switch typed := tok.(type) {
case xml.CharData:
text := string(typed.Copy())
if ignoreIndentation {
text = strings.TrimSpace(text)
}
if len(text) != 0 {
out.Text = text
}
case xml.StartElement:
el := typed.Copy()
out.Attr = el.Attr
if out.Children == nil {
out.Children = map[string][]*Node{}
}
name := typed.Name.Local
slice := out.Children[name]
if slice == nil {
slice = []*Node{}
}
node, e := ToStruct(d, &el, ignoreIndentation)
out.findNamespaces()
if e != nil {
return out, e
}
node.Name = typed.Name
node.findNamespaces()
// Add attributes onto the node
node.Attr = el.Attr
tempOut := *out
// Save into a temp variable, simply because out gets squashed during
// loop iterations
node.parent = &tempOut
slice = append(slice, node)
out.Children[name] = slice
case xml.EndElement:
if s != nil && s.Name.Local == typed.Name.Local { // matching end token
return out, nil
}
out = &Node{}
}
}
return out, nil
}
func (n *Node) findNamespaces() {
ns := map[string]string{}
for _, a := range n.Attr {
if a.Name.Space == "xmlns" {
ns[a.Value] = a.Name.Local
}
}
n.namespaces = ns
}
func (n *Node) findElem(name string) (string, bool) {
for node := n; node != nil; node = node.parent {
for _, a := range node.Attr {
namespace := a.Name.Space
if v, ok := node.namespaces[namespace]; ok {
namespace = v
}
if name == fmt.Sprintf("%s:%s", namespace, a.Name.Local) {
return a.Value, true
}
}
}
return "", false
}
// StructToXML writes an Node to a xml.Encoder as tokens.
func StructToXML(e *xml.Encoder, node *Node, sorted bool) error {
var err error
// Sort Attributes
attrs := node.Attr
if sorted {
sortedAttrs := make([]xml.Attr, len(attrs))
for _, k := range node.Attr {
sortedAttrs = append(sortedAttrs, k)
}
sort.Sort(xmlAttrSlice(sortedAttrs))
attrs = sortedAttrs
}
st := xml.StartElement{Name: node.Name, Attr: attrs}
e.EncodeToken(st)
// return fmt.Errorf("encoder string : %s, %s, %s", node.Name.Local, node.Name.Space, st.Attr)
if node.Text != "" {
e.EncodeToken(xml.CharData([]byte(node.Text)))
} else if sorted {
sortedNames := []string{}
for k := range node.Children {
sortedNames = append(sortedNames, k)
}
sort.Strings(sortedNames)
for _, k := range sortedNames {
// we should sort the []*xml.Node for each key if len >1
flattenedNodes := node.Children[k]
// Meaning this has multiple nodes
if len(flattenedNodes) > 1 {
// sort flattened nodes
flattenedNodes, err = sortFlattenedNodes(flattenedNodes)
if err != nil {
return err
}
}
for _, v := range flattenedNodes {
err = StructToXML(e, v, sorted)
if err != nil {
return err
}
}
}
} else {
for _, c := range node.Children {
for _, v := range c {
err = StructToXML(e, v, sorted)
if err != nil {
return err
}
}
}
}
e.EncodeToken(xml.EndElement{Name: node.Name})
return e.Flush()
}
// sortFlattenedNodes sorts nodes with nodes having same element tag
// but overall different values. The function will return list of pointer to
// Node and an error.
//
// Overall sort order is followed is:
// Nodes with concrete value (no nested node as value) are given precedence
// and are added to list after sorting them
//
// Next nested nodes within a flattened list are given precedence.
//
// Next nodes within a flattened map are sorted based on either key or value
// which ever has lower value and then added to the global sorted list.
// If value was initially chosen, but has nested nodes; key will be chosen as comparable
// as it is unique and will always have concrete data ie. string.
func sortFlattenedNodes(nodes []*Node) ([]*Node, error) {
var sortedNodes []*Node
// concreteNodeMap stores concrete value associated with a list of nodes
// This is possible in case multiple members of a flatList has same values.
concreteNodeMap := make(map[string][]*Node, 0)
// flatListNodeMap stores flat list or wrapped list members associated with a list of nodes
// This will have only flattened list with members that are Nodes and not concrete values.
flatListNodeMap := make(map[string][]*Node, 0)
// flatMapNodeMap stores flat map or map entry members associated with a list of nodes
// This will have only flattened map concrete value members. It is possible to limit this
// to concrete value as map key is expected to be concrete.
flatMapNodeMap := make(map[string][]*Node, 0)
// nodes with concrete value are prioritized and appended based on sorting order
sortedNodesWithConcreteValue := []string{}
// list with nested nodes are second in priority and appended based on sorting order
sortedNodesWithListValue := []string{}
// map are last in priority and appended based on sorting order
sortedNodesWithMapValue := []string{}
for _, node := range nodes {
// node has no children element, then we consider it as having concrete value
if len(node.Children) == 0 {
sortedNodesWithConcreteValue = append(sortedNodesWithConcreteValue, node.Text)
if v, ok := concreteNodeMap[node.Text]; ok {
concreteNodeMap[node.Text] = append(v, node)
} else {
concreteNodeMap[node.Text] = []*Node{node}
}
}
// if node has a single child, then it is a flattened list node
if len(node.Children) == 1 {
for _, nestedNodes := range node.Children {
nestedNodeName := nestedNodes[0].Name.Local
// append to sorted node name for list value
sortedNodesWithListValue = append(sortedNodesWithListValue, nestedNodeName)
if v, ok := flatListNodeMap[nestedNodeName]; ok {
flatListNodeMap[nestedNodeName] = append(v, nestedNodes[0])
} else {
flatListNodeMap[nestedNodeName] = []*Node{nestedNodes[0]}
}
}
}
// if node has two children, then it is a flattened map node
if len(node.Children) == 2 {
nestedPair := []*Node{}
for _, k := range node.Children {
nestedPair = append(nestedPair, k[0])
}
comparableValues := []string{nestedPair[0].Name.Local, nestedPair[1].Name.Local}
sort.Strings(comparableValues)
comparableValue := comparableValues[0]
for _, nestedNode := range nestedPair {
if comparableValue == nestedNode.Name.Local && len(nestedNode.Children) != 0 {
// if value was selected and is nested node, skip it and use key instead
comparableValue = comparableValues[1]
continue
}
// now we are certain there is no nested node
if comparableValue == nestedNode.Name.Local {
// get chardata for comparison
comparableValue = nestedNode.Text
sortedNodesWithMapValue = append(sortedNodesWithMapValue, comparableValue)
if v, ok := flatMapNodeMap[comparableValue]; ok {
flatMapNodeMap[comparableValue] = append(v, node)
} else {
flatMapNodeMap[comparableValue] = []*Node{node}
}
break
}
}
}
// we don't support multiple same name nodes in an xml doc except for in flattened maps, list.
if len(node.Children) > 2 {
return nodes, fmt.Errorf("malformed xml: multiple nodes with same key name exist, " +
"but are not associated with flattened maps (2 children) or list (0 or 1 child)")
}
}
// sort concrete value node name list and append corresponding nodes
// to sortedNodes
sort.Strings(sortedNodesWithConcreteValue)
for _, name := range sortedNodesWithConcreteValue {
for _, node := range concreteNodeMap[name] {
sortedNodes = append(sortedNodes, node)
}
}
// sort nested nodes with a list and append corresponding nodes
// to sortedNodes
sort.Strings(sortedNodesWithListValue)
for _, name := range sortedNodesWithListValue {
// if two nested nodes have same name, then sort them separately.
if len(flatListNodeMap[name]) > 1 {
// return nodes, fmt.Errorf("flat list node name are %s %v", flatListNodeMap[name][0].Name.Local, len(flatListNodeMap[name]))
nestedFlattenedList, err := sortFlattenedNodes(flatListNodeMap[name])
if err != nil {
return nodes, err
}
// append the identical but sorted nodes
for _, nestedNode := range nestedFlattenedList {
sortedNodes = append(sortedNodes, nestedNode)
}
} else {
// append the sorted nodes
sortedNodes = append(sortedNodes, flatListNodeMap[name][0])
}
}
// sorted nodes with a map and append corresponding nodes to sortedNodes
sort.Strings(sortedNodesWithMapValue)
for _, name := range sortedNodesWithMapValue {
sortedNodes = append(sortedNodes, flatMapNodeMap[name][0])
}
return sortedNodes, nil
}
| 340 |
session-manager-plugin | aws | Go | package strings
import (
"strings"
)
// HasPrefixFold tests whether the string s begins with prefix, interpreted as UTF-8 strings,
// under Unicode case-folding.
func HasPrefixFold(s, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(s[0:len(prefix)], prefix)
}
| 12 |
session-manager-plugin | aws | Go | // +build go1.7
package strings
import (
"strings"
"testing"
)
func TestHasPrefixFold(t *testing.T) {
type args struct {
s string
prefix string
}
tests := map[string]struct {
args args
want bool
}{
"empty strings and prefix": {
args: args{
s: "",
prefix: "",
},
want: true,
},
"strings starts with prefix": {
args: args{
s: "some string",
prefix: "some",
},
want: true,
},
"prefix longer then string": {
args: args{
s: "some",
prefix: "some string",
},
},
"equal length string and prefix": {
args: args{
s: "short string",
prefix: "short string",
},
want: true,
},
"different cases": {
args: args{
s: "ShOrT StRING",
prefix: "short",
},
want: true,
},
"empty prefix not empty string": {
args: args{
s: "ShOrT StRING",
prefix: "",
},
want: true,
},
"mixed-case prefixes": {
args: args{
s: "SoMe String",
prefix: "sOme",
},
want: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
if got := HasPrefixFold(tt.args.s, tt.args.prefix); got != tt.want {
t.Errorf("HasPrefixFold() = %v, want %v", got, tt.want)
}
})
}
}
func BenchmarkHasPrefixFold(b *testing.B) {
HasPrefixFold("SoME string", "sOmE")
}
func BenchmarkHasPrefix(b *testing.B) {
strings.HasPrefix(strings.ToLower("SoME string"), strings.ToLower("sOmE"))
}
| 84 |
session-manager-plugin | aws | Go | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package singleflight provides a duplicate function call suppression
// mechanism.
package singleflight
import "sync"
// call is an in-flight or completed singleflight.Do call
type call struct {
wg sync.WaitGroup
// These fields are written once before the WaitGroup is done
// and are only read after the WaitGroup is done.
val interface{}
err error
// forgotten indicates whether Forget was called with this call's key
// while the call was still in flight.
forgotten bool
// These fields are read and written with the singleflight
// mutex held before the WaitGroup is done, and are read but
// not written after the WaitGroup is done.
dups int
chans []chan<- Result
}
// Group represents a class of work and forms a namespace in
// which units of work can be executed with duplicate suppression.
type Group struct {
mu sync.Mutex // protects m
m map[string]*call // lazily initialized
}
// Result holds the results of Do, so they can be passed
// on a channel.
type Result struct {
Val interface{}
Err error
Shared bool
}
// Do executes and returns the results of the given function, making
// sure that only one execution is in-flight for a given key at a
// time. If a duplicate comes in, the duplicate caller waits for the
// original to complete and receives the same results.
// The return value shared indicates whether v was given to multiple callers.
func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
g.mu.Unlock()
c.wg.Wait()
return c.val, c.err, true
}
c := new(call)
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
g.doCall(c, key, fn)
return c.val, c.err, c.dups > 0
}
// DoChan is like Do but returns a channel that will receive the
// results when they are ready.
func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result {
ch := make(chan Result, 1)
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
c.chans = append(c.chans, ch)
g.mu.Unlock()
return ch
}
c := &call{chans: []chan<- Result{ch}}
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
go g.doCall(c, key, fn)
return ch
}
// doCall handles the single call for a key.
func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
c.val, c.err = fn()
c.wg.Done()
g.mu.Lock()
if !c.forgotten {
delete(g.m, key)
}
for _, ch := range c.chans {
ch <- Result{c.val, c.err, c.dups > 0}
}
g.mu.Unlock()
}
// Forget tells the singleflight to forget about a key. Future calls
// to Do for this key will call the function rather than waiting for
// an earlier call to complete.
func (g *Group) Forget(key string) {
g.mu.Lock()
if c, ok := g.m[key]; ok {
c.forgotten = true
}
delete(g.m, key)
g.mu.Unlock()
}
| 121 |
session-manager-plugin | aws | Go | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package singleflight
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestDo(t *testing.T) {
t.Skip("singleflight tests not stable")
var g Group
v, err, _ := g.Do("key", func() (interface{}, error) {
return "bar", nil
})
if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want {
t.Errorf("Do = %v; want %v", got, want)
}
if err != nil {
t.Errorf("Do error = %v", err)
}
}
func TestDoErr(t *testing.T) {
t.Skip("singleflight tests not stable")
var g Group
someErr := errors.New("Some error")
v, err, _ := g.Do("key", func() (interface{}, error) {
return nil, someErr
})
if err != someErr {
t.Errorf("Do error = %v; want someErr %v", err, someErr)
}
if v != nil {
t.Errorf("unexpected non-nil value %#v", v)
}
}
func TestDoDupSuppress(t *testing.T) {
t.Skip("singleflight tests not stable")
var g Group
var wg1, wg2 sync.WaitGroup
c := make(chan string, 1)
var calls int32
fn := func() (interface{}, error) {
if atomic.AddInt32(&calls, 1) == 1 {
// First invocation.
wg1.Done()
}
v := <-c
c <- v // pump; make available for any future calls
time.Sleep(10 * time.Millisecond) // let more goroutines enter Do
return v, nil
}
const n = 10
wg1.Add(1)
for i := 0; i < n; i++ {
wg1.Add(1)
wg2.Add(1)
go func() {
defer wg2.Done()
wg1.Done()
v, err, _ := g.Do("key", fn)
if err != nil {
t.Errorf("Do error: %v", err)
return
}
if s, _ := v.(string); s != "bar" {
t.Errorf("Do = %T %v; want %q", v, v, "bar")
}
}()
}
wg1.Wait()
// At least one goroutine is in fn now and all of them have at
// least reached the line before the Do.
c <- "bar"
wg2.Wait()
if got := atomic.LoadInt32(&calls); got <= 0 || got >= n {
t.Errorf("number of calls = %d; want over 0 and less than %d", got, n)
}
}
// Test that singleflight behaves correctly after Forget called.
// See https://github.com/golang/go/issues/31420
func TestForget(t *testing.T) {
t.Skip("singleflight tests not stable")
var g Group
var firstStarted, firstFinished sync.WaitGroup
firstStarted.Add(1)
firstFinished.Add(1)
firstCh := make(chan struct{})
go func() {
g.Do("key", func() (i interface{}, e error) {
firstStarted.Done()
<-firstCh
firstFinished.Done()
return
})
}()
firstStarted.Wait()
g.Forget("key") // from this point no two function using same key should be executed concurrently
var secondStarted int32
var secondFinished int32
var thirdStarted int32
secondCh := make(chan struct{})
secondRunning := make(chan struct{})
go func() {
g.Do("key", func() (i interface{}, e error) {
defer func() {
}()
atomic.AddInt32(&secondStarted, 1)
// Notify that we started
secondCh <- struct{}{}
// Wait other get above signal
<-secondRunning
<-secondCh
atomic.AddInt32(&secondFinished, 1)
return 2, nil
})
}()
close(firstCh)
firstFinished.Wait() // wait for first execution (which should not affect execution after Forget)
<-secondCh
// Notify second that we got the signal that it started
secondRunning <- struct{}{}
if atomic.LoadInt32(&secondStarted) != 1 {
t.Fatal("Second execution should be executed due to usage of forget")
}
if atomic.LoadInt32(&secondFinished) == 1 {
t.Fatal("Second execution should be still active")
}
close(secondCh)
result, _, _ := g.Do("key", func() (i interface{}, e error) {
atomic.AddInt32(&thirdStarted, 1)
return 3, nil
})
if atomic.LoadInt32(&thirdStarted) != 0 {
t.Error("Third call should not be started because was started during second execution")
}
if result != 2 {
t.Errorf("We should receive result produced by second call, expected: 2, got %d", result)
}
}
| 164 |
session-manager-plugin | aws | Go | // +build awsinclude
package apis
import (
"os/exec"
"strings"
"testing"
)
func TestCollidingFolders(t *testing.T) {
m := map[string]struct{}{}
folders, err := getFolderNames()
if err != nil {
t.Error(err)
}
for _, folder := range folders {
lcName := strings.ToLower(folder)
if _, ok := m[lcName]; ok {
t.Errorf("folder %q collision detected", folder)
}
m[lcName] = struct{}{}
}
}
func getFolderNames() ([]string, error) {
cmd := exec.Command("git", "ls-tree", "-d", "--name-only", "HEAD")
output, err := cmd.Output()
if err != nil {
return nil, err
}
return strings.Split(string(output), "\n"), nil
}
| 36 |
session-manager-plugin | aws | Go | // +build awsinclude
package apis
| 4 |
session-manager-plugin | aws | Go | // Package endpoints contains the models for endpoints that should be used
// to generate endpoint definition files for the SDK.
package endpoints
//go:generate go run -tags codegen ../../private/model/cli/gen-endpoints/main.go -model ./endpoints.json -out ../../aws/endpoints/defaults.go
//go:generate gofmt -s -w ../../aws/endpoints
| 7 |
session-manager-plugin | aws | Go | package checksum
import (
"crypto/md5"
"encoding/base64"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
const contentMD5Header = "Content-Md5"
// AddBodyContentMD5Handler computes and sets the HTTP Content-MD5 header for requests that
// require it.
func AddBodyContentMD5Handler(r *request.Request) {
// if Content-MD5 header is already present, return
if v := r.HTTPRequest.Header.Get(contentMD5Header); len(v) != 0 {
return
}
// if S3DisableContentMD5Validation flag is set, return
if aws.BoolValue(r.Config.S3DisableContentMD5Validation) {
return
}
// if request is presigned, return
if r.IsPresigned() {
return
}
// if body is not seekable, return
if !aws.IsReaderSeekable(r.Body) {
if r.Config.Logger != nil {
r.Config.Logger.Log(fmt.Sprintf(
"Unable to compute Content-MD5 for unseekable body, S3.%s",
r.Operation.Name))
}
return
}
h := md5.New()
if _, err := aws.CopySeekableBody(h, r.Body); err != nil {
r.Error = awserr.New("ContentMD5", "failed to compute body MD5", err)
return
}
// encode the md5 checksum in base64 and set the request header.
v := base64.StdEncoding.EncodeToString(h.Sum(nil))
r.HTTPRequest.Header.Set(contentMD5Header, v)
}
| 54 |
session-manager-plugin | aws | Go | // +build codegen
// Package api represents API abstractions for rendering service generated files.
package api
import (
"bytes"
"fmt"
"path"
"regexp"
"sort"
"strings"
"text/template"
"unicode"
)
// SDKImportRoot is the root import path of the SDK.
const SDKImportRoot = "github.com/aws/aws-sdk-go"
// An API defines a service API's definition. and logic to serialize the definition.
type API struct {
Metadata Metadata
Operations map[string]*Operation
Shapes map[string]*Shape
Waiters []Waiter
Documentation string
Examples Examples
SmokeTests SmokeTestSuite
IgnoreUnsupportedAPIs bool
// Set to true to avoid removing unused shapes
NoRemoveUnusedShapes bool
// Set to true to avoid renaming to 'Input/Output' postfixed shapes
NoRenameToplevelShapes bool
// Set to true to ignore service/request init methods (for testing)
NoInitMethods bool
// Set to true to ignore String() and GoString methods (for generated tests)
NoStringerMethods bool
// Set to true to not generate API service name constants
NoConstServiceNames bool
// Set to true to not generate validation shapes
NoValidataShapeMethods bool
// Set to true to not generate struct field accessors
NoGenStructFieldAccessors bool
BaseImportPath string
initialized bool
imports map[string]bool
name string
path string
BaseCrosslinkURL string
HasEventStream bool `json:"-"`
EndpointDiscoveryOp *Operation
HasEndpointARN bool `json:"-"`
HasOutpostID bool `json:"-"`
HasAccountIdWithARN bool `json:"-"`
WithGeneratedTypedErrors bool
}
// A Metadata is the metadata about an API's definition.
type Metadata struct {
APIVersion string
EndpointPrefix string
SigningName string
ServiceAbbreviation string
ServiceFullName string
SignatureVersion string
JSONVersion string
TargetPrefix string
Protocol string
ProtocolSettings ProtocolSettings
UID string
EndpointsID string
ServiceID string
NoResolveEndpoint bool
}
// ProtocolSettings define how the SDK should handle requests in the context
// of of a protocol.
type ProtocolSettings struct {
HTTP2 string `json:"h2,omitempty"`
}
// PackageName name of the API package
func (a *API) PackageName() string {
return strings.ToLower(a.StructName())
}
// ImportPath returns the client's full import path
func (a *API) ImportPath() string {
return path.Join(a.BaseImportPath, a.PackageName())
}
// InterfacePackageName returns the package name for the interface.
func (a *API) InterfacePackageName() string {
return a.PackageName() + "iface"
}
var stripServiceNamePrefixes = []string{
"Amazon",
"AWS",
}
// StructName returns the struct name for a given API.
func (a *API) StructName() string {
if len(a.name) != 0 {
return a.name
}
name := a.Metadata.ServiceAbbreviation
if len(name) == 0 {
name = a.Metadata.ServiceFullName
}
name = strings.TrimSpace(name)
// Strip out prefix names not reflected in service client symbol names.
for _, prefix := range stripServiceNamePrefixes {
if strings.HasPrefix(name, prefix) {
name = name[len(prefix):]
break
}
}
// Replace all Non-letter/number values with space
runes := []rune(name)
for i := 0; i < len(runes); i++ {
if r := runes[i]; !(unicode.IsNumber(r) || unicode.IsLetter(r)) {
runes[i] = ' '
}
}
name = string(runes)
// Title case name so its readable as a symbol.
name = strings.Title(name)
// Strip out spaces.
name = strings.Replace(name, " ", "", -1)
a.name = name
return a.name
}
// UseInitMethods returns if the service's init method should be rendered.
func (a *API) UseInitMethods() bool {
return !a.NoInitMethods
}
// NiceName returns the human friendly API name.
func (a *API) NiceName() string {
if a.Metadata.ServiceAbbreviation != "" {
return a.Metadata.ServiceAbbreviation
}
return a.Metadata.ServiceFullName
}
// ProtocolPackage returns the package name of the protocol this API uses.
func (a *API) ProtocolPackage() string {
switch a.Metadata.Protocol {
case "json":
return "jsonrpc"
case "ec2":
return "ec2query"
default:
return strings.Replace(a.Metadata.Protocol, "-", "", -1)
}
}
// OperationNames returns a slice of API operations supported.
func (a *API) OperationNames() []string {
i, names := 0, make([]string, len(a.Operations))
for n := range a.Operations {
names[i] = n
i++
}
sort.Strings(names)
return names
}
// OperationList returns a slice of API operation pointers
func (a *API) OperationList() []*Operation {
list := make([]*Operation, len(a.Operations))
for i, n := range a.OperationNames() {
list[i] = a.Operations[n]
}
return list
}
// OperationHasOutputPlaceholder returns if any of the API operation input
// or output shapes are place holders.
func (a *API) OperationHasOutputPlaceholder() bool {
for _, op := range a.Operations {
if op.OutputRef.Shape.Placeholder {
return true
}
}
return false
}
// ShapeNames returns a slice of names for each shape used by the API.
func (a *API) ShapeNames() []string {
i, names := 0, make([]string, len(a.Shapes))
for n := range a.Shapes {
names[i] = n
i++
}
sort.Strings(names)
return names
}
// ShapeList returns a slice of shape pointers used by the API.
//
// Will exclude error shapes from the list of shapes returned.
func (a *API) ShapeList() []*Shape {
list := make([]*Shape, 0, len(a.Shapes))
for _, n := range a.ShapeNames() {
// Ignore non-eventstream exception shapes in list.
if s := a.Shapes[n]; !(s.Exception && len(s.EventFor) == 0) {
list = append(list, s)
}
}
return list
}
// ShapeListErrors returns a list of the errors defined by the API model
func (a *API) ShapeListErrors() []*Shape {
list := []*Shape{}
for _, n := range a.ShapeNames() {
// Ignore error shapes in list
if s := a.Shapes[n]; s.Exception {
list = append(list, s)
}
}
return list
}
// resetImports resets the import map to default values.
func (a *API) resetImports() {
a.imports = map[string]bool{}
}
// importsGoCode returns the generated Go import code.
func (a *API) importsGoCode() string {
if len(a.imports) == 0 {
return ""
}
corePkgs, extPkgs := []string{}, []string{}
for i := range a.imports {
if strings.Contains(i, ".") {
extPkgs = append(extPkgs, i)
} else {
corePkgs = append(corePkgs, i)
}
}
sort.Strings(corePkgs)
sort.Strings(extPkgs)
code := "import (\n"
for _, i := range corePkgs {
code += fmt.Sprintf("\t%q\n", i)
}
if len(corePkgs) > 0 {
code += "\n"
}
for _, i := range extPkgs {
code += fmt.Sprintf("\t%q\n", i)
}
code += ")\n\n"
return code
}
// A tplAPI is the top level template for the API
var tplAPI = template.Must(template.New("api").Parse(`
{{- range $_, $o := .OperationList }}
{{ $o.GoCode }}
{{- end }}
{{- range $_, $s := $.Shapes }}
{{- if and $s.IsInternal (eq $s.Type "structure") (not $s.Exception) }}
{{ $s.GoCode }}
{{- else if and $s.Exception (or $.WithGeneratedTypedErrors $s.EventFor) }}
{{ $s.GoCode }}
{{- end }}
{{- end }}
{{- range $_, $s := $.Shapes }}
{{- if $s.IsEnum }}
{{ $s.GoCode }}
{{- end }}
{{- end }}
`))
// AddImport adds the import path to the generated file's import.
func (a *API) AddImport(v string) error {
a.imports[v] = true
return nil
}
// AddSDKImport adds a SDK package import to the generated file's import.
func (a *API) AddSDKImport(v ...string) error {
e := make([]string, 0, 5)
e = append(e, SDKImportRoot)
e = append(e, v...)
a.imports[path.Join(e...)] = true
return nil
}
// APIGoCode renders the API in Go code. Returning it as a string
func (a *API) APIGoCode() string {
a.resetImports()
a.AddSDKImport("aws")
a.AddSDKImport("aws/awsutil")
a.AddSDKImport("aws/request")
if a.HasEndpointARN {
a.AddImport("fmt")
if a.PackageName() == "s3" || a.PackageName() == "s3control" {
a.AddSDKImport("internal/s3shared/arn")
} else {
a.AddSDKImport("service", a.PackageName(), "internal", "arn")
}
}
var buf bytes.Buffer
err := tplAPI.Execute(&buf, a)
if err != nil {
panic(err)
}
code := a.importsGoCode() + strings.TrimSpace(buf.String())
return code
}
var noCrossLinkServices = map[string]struct{}{
"apigateway": {},
"budgets": {},
"cloudsearch": {},
"cloudsearchdomain": {},
"elastictranscoder": {},
"elasticsearchservice": {},
"glacier": {},
"importexport": {},
"iot": {},
"iotdataplane": {},
"machinelearning": {},
"rekognition": {},
"sdb": {},
"swf": {},
}
// HasCrosslinks will return whether or not a service has crosslinking .
func HasCrosslinks(service string) bool {
_, ok := noCrossLinkServices[service]
return !ok
}
// GetCrosslinkURL returns the crosslinking URL for the shape based on the name and
// uid provided. Empty string is returned if no crosslink link could be determined.
func (a *API) GetCrosslinkURL(params ...string) string {
baseURL := a.BaseCrosslinkURL
uid := a.Metadata.UID
if a.Metadata.UID == "" || a.BaseCrosslinkURL == "" {
return ""
}
if !HasCrosslinks(strings.ToLower(a.PackageName())) {
return ""
}
return strings.Join(append([]string{baseURL, "goto", "WebAPI", uid}, params...), "/")
}
// ServiceIDFromUID will parse the service id from the uid and return
// the service id that was found.
func ServiceIDFromUID(uid string) string {
found := 0
i := len(uid) - 1
for ; i >= 0; i-- {
if uid[i] == '-' {
found++
}
// Terminate after the date component is found, e.g. es-2017-11-11
if found == 3 {
break
}
}
return uid[0:i]
}
// APIName returns the API's service name.
func (a *API) APIName() string {
return a.name
}
var tplServiceDoc = template.Must(template.New("service docs").
Parse(`
// Package {{ .PackageName }} provides the client and types for making API
// requests to {{ .Metadata.ServiceFullName }}.
{{ if .Documentation -}}
//
{{ .Documentation }}
{{ end -}}
{{ $crosslinkURL := $.GetCrosslinkURL -}}
{{ if $crosslinkURL -}}
//
// See {{ $crosslinkURL }} for more information on this service.
{{ end -}}
//
// See {{ .PackageName }} package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/{{ .PackageName }}/
//
// Using the Client
//
// To contact {{ .Metadata.ServiceFullName }} with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the {{ .Metadata.ServiceFullName }} client {{ .StructName }} for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/{{ .PackageName }}/#New
`))
var serviceIDRegex = regexp.MustCompile("[^a-zA-Z0-9 ]+")
var prefixDigitRegex = regexp.MustCompile("^[0-9]+")
// ServiceID will return a unique identifier specific to a service.
func ServiceID(a *API) string {
if len(a.Metadata.ServiceID) > 0 {
return a.Metadata.ServiceID
}
name := a.Metadata.ServiceAbbreviation
if len(name) == 0 {
name = a.Metadata.ServiceFullName
}
name = strings.Replace(name, "Amazon", "", -1)
name = strings.Replace(name, "AWS", "", -1)
name = serviceIDRegex.ReplaceAllString(name, "")
name = prefixDigitRegex.ReplaceAllString(name, "")
name = strings.TrimSpace(name)
return name
}
// A tplService defines the template for the service generated code.
var tplService = template.Must(template.New("service").Funcs(template.FuncMap{
"ServiceNameConstValue": ServiceName,
"ServiceNameValue": func(a *API) string {
if !a.NoConstServiceNames {
return "ServiceName"
}
return fmt.Sprintf("%q", ServiceName(a))
},
"EndpointsIDConstValue": func(a *API) string {
if a.NoConstServiceNames {
return fmt.Sprintf("%q", a.Metadata.EndpointsID)
}
if a.Metadata.EndpointsID == ServiceName(a) {
return "ServiceName"
}
return fmt.Sprintf("%q", a.Metadata.EndpointsID)
},
"EndpointsIDValue": func(a *API) string {
if a.NoConstServiceNames {
return fmt.Sprintf("%q", a.Metadata.EndpointsID)
}
return "EndpointsID"
},
"ServiceIDVar": func(a *API) string {
if a.NoConstServiceNames {
return fmt.Sprintf("%q", ServiceID(a))
}
return "ServiceID"
},
"ServiceID": ServiceID,
}).Parse(`
// {{ .StructName }} provides the API operation methods for making requests to
// {{ .Metadata.ServiceFullName }}. See this package's package overview docs
// for details on the service.
//
// {{ .StructName }} methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type {{ .StructName }} struct {
*client.Client
{{- if .EndpointDiscoveryOp }}
endpointCache *crr.EndpointCache
{{ end -}}
}
{{ if .UseInitMethods }}// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
{{ end }}
{{ if not .NoConstServiceNames -}}
// Service information constants
const (
ServiceName = "{{ ServiceNameConstValue . }}" // Name of service.
EndpointsID = {{ EndpointsIDConstValue . }} // ID to lookup a service endpoint with.
ServiceID = "{{ ServiceID . }}" // ServiceID is a unique identifier of a specific service.
)
{{- end }}
// New creates a new instance of the {{ .StructName }} client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a {{ .StructName }} client from just a session.
// svc := {{ .PackageName }}.New(mySession)
//
// // Create a {{ .StructName }} client with additional configuration
// svc := {{ .PackageName }}.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *{{ .StructName }} {
{{ if .Metadata.NoResolveEndpoint -}}
var c client.Config
if v, ok := p.(client.ConfigNoResolveEndpointProvider); ok {
c = v.ClientConfigNoResolveEndpoint(cfgs...)
} else {
c = p.ClientConfig({{ EndpointsIDValue . }}, cfgs...)
}
{{- else -}}
c := p.ClientConfig({{ EndpointsIDValue . }}, cfgs...)
{{- end }}
{{- if .Metadata.SigningName }}
if c.SigningNameDerived || len(c.SigningName) == 0{
c.SigningName = "{{ .Metadata.SigningName }}"
}
{{- end }}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *{{ .StructName }} {
svc := &{{ .StructName }}{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: {{ ServiceNameValue . }},
ServiceID : {{ ServiceIDVar . }},
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "{{ .Metadata.APIVersion }}",
{{ if and (.Metadata.JSONVersion) (eq .Metadata.Protocol "json") -}}
JSONVersion: "{{ .Metadata.JSONVersion }}",
{{- end }}
{{ if and (.Metadata.TargetPrefix) (eq .Metadata.Protocol "json") -}}
TargetPrefix: "{{ .Metadata.TargetPrefix }}",
{{- end }}
},
handlers,
),
}
{{- if .EndpointDiscoveryOp }}
svc.endpointCache = crr.NewEndpointCache(10)
{{- end }}
// Handlers
svc.Handlers.Sign.PushBackNamed(
{{- if eq .Metadata.SignatureVersion "v2" -}}
v2.SignRequestHandler
{{- else if or (eq .Metadata.SignatureVersion "s3") (eq .Metadata.SignatureVersion "s3v4") -}}
v4.BuildNamedHandler(v4.SignRequestHandler.Name, func(s *v4.Signer) {
s.DisableURIPathEscaping = true
})
{{- else -}}
v4.SignRequestHandler
{{- end -}}
)
{{- if eq .Metadata.SignatureVersion "v2" }}
svc.Handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler)
{{- end }}
svc.Handlers.Build.PushBackNamed({{ .ProtocolPackage }}.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed({{ .ProtocolPackage }}.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed({{ .ProtocolPackage }}.UnmarshalMetaHandler)
{{- if and $.WithGeneratedTypedErrors (gt (len $.ShapeListErrors) 0) }}
{{- $_ := $.AddSDKImport "private/protocol" }}
svc.Handlers.UnmarshalError.PushBackNamed(
protocol.NewUnmarshalErrorHandler({{ .ProtocolPackage }}.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(),
)
{{- else }}
svc.Handlers.UnmarshalError.PushBackNamed({{ .ProtocolPackage }}.UnmarshalErrorHandler)
{{- end }}
{{- if .HasEventStream }}
svc.Handlers.BuildStream.PushBackNamed({{ .ProtocolPackage }}.BuildHandler)
svc.Handlers.UnmarshalStream.PushBackNamed({{ .ProtocolPackage }}.UnmarshalHandler)
{{- end }}
{{- if .UseInitMethods }}
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
{{- end }}
return svc
}
// newRequest creates a new request for a {{ .StructName }} operation and runs any
// custom request initialization.
func (c *{{ .StructName }}) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
{{- if .UseInitMethods }}
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
{{- end }}
return req
}
`))
// ServicePackageDoc generates the contents of the doc file for the service.
//
// Will also read in the custom doc templates for the service if found.
func (a *API) ServicePackageDoc() string {
a.imports = map[string]bool{}
var buf bytes.Buffer
if err := tplServiceDoc.Execute(&buf, a); err != nil {
panic(err)
}
return buf.String()
}
// ServiceGoCode renders service go code. Returning it as a string.
func (a *API) ServiceGoCode() string {
a.resetImports()
a.AddSDKImport("aws")
a.AddSDKImport("aws/client")
a.AddSDKImport("aws/client/metadata")
a.AddSDKImport("aws/request")
if a.Metadata.SignatureVersion == "v2" {
a.AddSDKImport("private/signer/v2")
a.AddSDKImport("aws/corehandlers")
} else {
a.AddSDKImport("aws/signer/v4")
}
a.AddSDKImport("private/protocol", a.ProtocolPackage())
if a.EndpointDiscoveryOp != nil {
a.AddSDKImport("aws/crr")
}
var buf bytes.Buffer
err := tplService.Execute(&buf, a)
if err != nil {
panic(err)
}
code := a.importsGoCode() + buf.String()
return code
}
// ExampleGoCode renders service example code. Returning it as a string.
func (a *API) ExampleGoCode() string {
exs := []string{}
imports := map[string]bool{}
for _, o := range a.OperationList() {
o.imports = map[string]bool{}
exs = append(exs, o.Example())
for k, v := range o.imports {
imports[k] = v
}
}
code := fmt.Sprintf("import (\n%q\n%q\n%q\n\n%q\n%q\n%q\n",
"bytes",
"fmt",
"time",
SDKImportRoot+"/aws",
SDKImportRoot+"/aws/session",
a.ImportPath(),
)
for k := range imports {
code += fmt.Sprintf("%q\n", k)
}
code += ")\n\n"
code += "var _ time.Duration\nvar _ bytes.Buffer\n\n"
code += strings.Join(exs, "\n\n")
return code
}
// A tplInterface defines the template for the service interface type.
var tplInterface = template.Must(template.New("interface").Parse(`
// {{ .StructName }}API provides an interface to enable mocking the
// {{ .PackageName }}.{{ .StructName }} service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
// // myFunc uses an SDK service client to make a request to
// // {{.Metadata.ServiceFullName}}. {{ $opts := .OperationList }}{{ $opt := index $opts 0 }}
// func myFunc(svc {{ .InterfacePackageName }}.{{ .StructName }}API) bool {
// // Make svc.{{ $opt.ExportedName }} request
// }
//
// func main() {
// sess := session.New()
// svc := {{ .PackageName }}.New(sess)
//
// myFunc(svc)
// }
//
// In your _test.go file:
//
// // Define a mock struct to be used in your unit tests of myFunc.
// type mock{{ .StructName }}Client struct {
// {{ .InterfacePackageName }}.{{ .StructName }}API
// }
// func (m *mock{{ .StructName }}Client) {{ $opt.ExportedName }}(input {{ $opt.InputRef.GoTypeWithPkgName }}) ({{ $opt.OutputRef.GoTypeWithPkgName }}, error) {
// // mock response/functionality
// }
//
// func TestMyFunc(t *testing.T) {
// // Setup Test
// mockSvc := &mock{{ .StructName }}Client{}
//
// myfunc(mockSvc)
//
// // Verify myFunc's functionality
// }
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type {{ .StructName }}API interface {
{{ range $_, $o := .OperationList }}
{{ $o.InterfaceSignature }}
{{ end }}
{{ range $_, $w := .Waiters }}
{{ $w.InterfaceSignature }}
{{ end }}
}
var _ {{ .StructName }}API = (*{{ .PackageName }}.{{ .StructName }})(nil)
`))
// InterfaceGoCode returns the go code for the service's API operations as an
// interface{}. Assumes that the interface is being created in a different
// package than the service API's package.
func (a *API) InterfaceGoCode() string {
a.resetImports()
a.AddSDKImport("aws")
a.AddSDKImport("aws/request")
a.AddImport(a.ImportPath())
var buf bytes.Buffer
err := tplInterface.Execute(&buf, a)
if err != nil {
panic(err)
}
code := a.importsGoCode() + strings.TrimSpace(buf.String())
return code
}
// NewAPIGoCodeWithPkgName returns a string of instantiating the API prefixed
// with its package name. Takes a string depicting the Config.
func (a *API) NewAPIGoCodeWithPkgName(cfg string) string {
return fmt.Sprintf("%s.New(%s)", a.PackageName(), cfg)
}
// computes the validation chain for all input shapes
func (a *API) addShapeValidations() {
for _, o := range a.Operations {
resolveShapeValidations(o.InputRef.Shape)
}
}
// Updates the source shape and all nested shapes with the validations that
// could possibly be needed.
func resolveShapeValidations(s *Shape, ancestry ...*Shape) {
for _, a := range ancestry {
if a == s {
return
}
}
children := []string{}
for _, name := range s.MemberNames() {
ref := s.MemberRefs[name]
if s.IsRequired(name) && !s.Validations.Has(ref, ShapeValidationRequired) {
s.Validations = append(s.Validations, ShapeValidation{
Name: name, Ref: ref, Type: ShapeValidationRequired,
})
}
if ref.Shape.Min != 0 && !s.Validations.Has(ref, ShapeValidationMinVal) {
s.Validations = append(s.Validations, ShapeValidation{
Name: name, Ref: ref, Type: ShapeValidationMinVal,
})
}
if !ref.CanBeEmpty() && !s.Validations.Has(ref, ShapeValidationMinVal) {
s.Validations = append(s.Validations, ShapeValidation{
Name: name, Ref: ref, Type: ShapeValidationMinVal,
})
}
switch ref.Shape.Type {
case "map", "list", "structure":
children = append(children, name)
}
}
ancestry = append(ancestry, s)
for _, name := range children {
ref := s.MemberRefs[name]
// Since this is a grab bag we will just continue since
// we can't validate because we don't know the valued shape.
if ref.JSONValue || (s.UsedAsInput && ref.Shape.IsEventStream) {
continue
}
nestedShape := ref.Shape.NestedShape()
var v *ShapeValidation
if len(nestedShape.Validations) > 0 {
v = &ShapeValidation{
Name: name, Ref: ref, Type: ShapeValidationNested,
}
} else {
resolveShapeValidations(nestedShape, ancestry...)
if len(nestedShape.Validations) > 0 {
v = &ShapeValidation{
Name: name, Ref: ref, Type: ShapeValidationNested,
}
}
}
if v != nil && !s.Validations.Has(v.Ref, v.Type) {
s.Validations = append(s.Validations, *v)
}
}
ancestry = ancestry[:len(ancestry)-1]
}
// A tplAPIErrors is the top level template for the API
var tplAPIErrors = template.Must(template.New("api").Parse(`
const (
{{- range $_, $s := $.ShapeListErrors }}
// {{ $s.ErrorCodeName }} for service response error code
// {{ printf "%q" $s.ErrorName }}.
{{ if $s.Docstring -}}
//
{{ $s.Docstring }}
{{ end -}}
{{ $s.ErrorCodeName }} = {{ printf "%q" $s.ErrorName }}
{{- end }}
)
{{- if $.WithGeneratedTypedErrors }}
{{- $_ := $.AddSDKImport "private/protocol" }}
var exceptionFromCode = map[string]func(protocol.ResponseMetadata)error {
{{- range $_, $s := $.ShapeListErrors }}
"{{ $s.ErrorName }}": newError{{ $s.ShapeName }},
{{- end }}
}
{{- end }}
`))
// APIErrorsGoCode returns the Go code for the errors.go file.
func (a *API) APIErrorsGoCode() string {
a.resetImports()
var buf bytes.Buffer
err := tplAPIErrors.Execute(&buf, a)
if err != nil {
panic(err)
}
return a.importsGoCode() + strings.TrimSpace(buf.String())
}
// removeOperation removes an operation, its input/output shapes, as well as
// any references/shapes that are unique to this operation.
func (a *API) removeOperation(name string) {
debugLogger.Logln("removing operation,", name)
op := a.Operations[name]
delete(a.Operations, name)
delete(a.Examples, name)
a.removeShape(op.InputRef.Shape)
a.removeShape(op.OutputRef.Shape)
}
// removeShape removes the given shape, and all form member's reference target
// shapes. Will also remove member reference targeted shapes if those shapes do
// not have any additional references.
func (a *API) removeShape(s *Shape) {
debugLogger.Logln("removing shape,", s.ShapeName)
delete(a.Shapes, s.ShapeName)
for name, ref := range s.MemberRefs {
a.removeShapeRef(ref)
delete(s.MemberRefs, name)
}
for _, ref := range []*ShapeRef{&s.MemberRef, &s.KeyRef, &s.ValueRef} {
if ref.Shape == nil {
continue
}
a.removeShapeRef(ref)
*ref = ShapeRef{}
}
}
// removeShapeRef removes the shape reference from its target shape. If the
// reference was the last reference to the target shape, the shape will also be
// removed.
func (a *API) removeShapeRef(ref *ShapeRef) {
if ref.Shape == nil {
return
}
ref.Shape.removeRef(ref)
if len(ref.Shape.refs) == 0 {
a.removeShape(ref.Shape)
}
}
// writeInputOutputLocationName writes the ShapeName to the
// shapes LocationName in the event that there is no LocationName
// specified.
func (a *API) writeInputOutputLocationName() {
for _, o := range a.Operations {
setInput := len(o.InputRef.LocationName) == 0 && a.Metadata.Protocol == "rest-xml"
setOutput := len(o.OutputRef.LocationName) == 0 && (a.Metadata.Protocol == "rest-xml" || a.Metadata.Protocol == "ec2")
if setInput {
o.InputRef.LocationName = o.InputRef.Shape.OrigShapeName
}
if setOutput {
o.OutputRef.LocationName = o.OutputRef.Shape.OrigShapeName
}
}
}
func (a *API) addHeaderMapDocumentation() {
for _, shape := range a.Shapes {
if !shape.UsedAsOutput {
continue
}
for _, shapeRef := range shape.MemberRefs {
if shapeRef.Location == "headers" {
if dLen := len(shapeRef.Documentation); dLen > 0 {
if shapeRef.Documentation[dLen-1] != '\n' {
shapeRef.Documentation += "\n"
}
shapeRef.Documentation += "//"
}
shapeRef.Documentation += `
// By default unmarshaled keys are written as a map keys in following canonicalized format:
// the first letter and any letter following a hyphen will be capitalized, and the rest as lowercase.
// Set ` + "`aws.Config.LowerCaseHeaderMaps`" + ` to ` + "`true`" + ` to write unmarshaled keys to the map as lowercase.
`
}
}
}
}
func getDeprecatedMessage(msg string, name string) string {
if len(msg) == 0 {
return name + " has been deprecated"
}
return msg
}
| 1,029 |
session-manager-plugin | aws | Go | // +build go1.8,codegen
package api
import (
"testing"
)
func TestAPI_StructName(t *testing.T) {
origAliases := serviceAliaseNames
defer func() { serviceAliaseNames = origAliases }()
cases := map[string]struct {
Aliases map[string]string
Metadata Metadata
StructName string
}{
"FullName": {
Metadata: Metadata{
ServiceFullName: "Amazon Service Name-100",
},
StructName: "ServiceName100",
},
"Abbreviation": {
Metadata: Metadata{
ServiceFullName: "Amazon Service Name-100",
ServiceAbbreviation: "AWS SN100",
},
StructName: "SN100",
},
"Lowercase Name": {
Metadata: Metadata{
EndpointPrefix: "other",
ServiceFullName: "AWS Lowercase service",
ServiceAbbreviation: "lowercase",
},
StructName: "Lowercase",
},
"Lowercase Name Mixed": {
Metadata: Metadata{
EndpointPrefix: "other",
ServiceFullName: "AWS Lowercase service",
ServiceAbbreviation: "lowercase name Goes heRe",
},
StructName: "LowercaseNameGoesHeRe",
},
"Alias": {
Aliases: map[string]string{
"elasticloadbalancing": "ELB",
},
Metadata: Metadata{
ServiceFullName: "Elastic Load Balancing",
},
StructName: "ELB",
},
}
for k, c := range cases {
t.Run(k, func(t *testing.T) {
serviceAliaseNames = c.Aliases
a := API{
Metadata: c.Metadata,
}
a.Setup()
if e, o := c.StructName, a.StructName(); e != o {
t.Errorf("expect %v structName, got %v", e, o)
}
})
}
}
| 74 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
type service struct {
srcName string
dstName string
serviceVersion string
}
var mergeServices = map[string]service{
"dynamodbstreams": {
dstName: "dynamodb",
srcName: "streams.dynamodb",
},
"wafregional": {
dstName: "waf",
srcName: "waf-regional",
serviceVersion: "2015-08-24",
},
}
var serviceAliaseNames = map[string]string{
"costandusagereportservice": "CostandUsageReportService",
"elasticloadbalancing": "ELB",
"elasticloadbalancingv2": "ELBV2",
"config": "ConfigService",
}
func (a *API) setServiceAliaseName() {
if newName, ok := serviceAliaseNames[a.PackageName()]; ok {
a.name = newName
}
}
// customizationPasses Executes customization logic for the API by package name.
func (a *API) customizationPasses() error {
var svcCustomizations = map[string]func(*API) error{
"s3": s3Customizations,
"s3control": s3ControlCustomizations,
"cloudfront": cloudfrontCustomizations,
"rds": rdsCustomizations,
"neptune": neptuneCustomizations,
"docdb": docdbCustomizations,
// Disable endpoint resolving for services that require customer
// to provide endpoint them selves.
"cloudsearchdomain": disableEndpointResolving,
"iotdataplane": disableEndpointResolving,
// MTurk smoke test is invalid. The service requires AWS account to be
// linked to Amazon Mechanical Turk Account.
"mturk": supressSmokeTest,
// Backfill the authentication type for cognito identity and sts.
// Removes the need for the customizations in these services.
"cognitoidentity": backfillAuthType(NoneAuthType,
"GetId",
"GetOpenIdToken",
"UnlinkIdentity",
"GetCredentialsForIdentity",
),
"sts": backfillAuthType(NoneAuthType,
"AssumeRoleWithSAML",
"AssumeRoleWithWebIdentity",
),
}
for k := range mergeServices {
svcCustomizations[k] = mergeServicesCustomizations
}
if fn := svcCustomizations[a.PackageName()]; fn != nil {
err := fn(a)
if err != nil {
return fmt.Errorf("service customization pass failure for %s: %v", a.PackageName(), err)
}
}
return nil
}
func supressSmokeTest(a *API) error {
a.SmokeTests.TestCases = []SmokeTestCase{}
return nil
}
// Customizes the API generation to replace values specific to S3.
func s3Customizations(a *API) error {
// back-fill signing name as 's3'
a.Metadata.SigningName = "s3"
var strExpires *Shape
var keepContentMD5Ref = map[string]struct{}{
"PutObjectInput": {},
"UploadPartInput": {},
}
for name, s := range a.Shapes {
// Remove ContentMD5 members unless specified otherwise.
if _, keep := keepContentMD5Ref[name]; !keep {
if _, have := s.MemberRefs["ContentMD5"]; have {
delete(s.MemberRefs, "ContentMD5")
}
}
// Generate getter methods for API operation fields used by customizations.
for _, refName := range []string{"Bucket", "SSECustomerKey", "CopySourceSSECustomerKey"} {
if ref, ok := s.MemberRefs[refName]; ok {
ref.GenerateGetter = true
}
}
// Generate a endpointARN method for the BucketName shape if this is used as an operation input
if s.UsedAsInput {
if s.ShapeName == "CreateBucketInput" {
// For all operations but CreateBucket the BucketName shape
// needs to be decorated.
continue
}
var endpointARNShape *ShapeRef
for _, ref := range s.MemberRefs {
if ref.OrigShapeName != "BucketName" || ref.Shape.Type != "string" {
continue
}
if endpointARNShape != nil {
return fmt.Errorf("more then one BucketName shape present on shape")
}
ref.EndpointARN = true
endpointARNShape = ref
}
if endpointARNShape != nil {
s.HasEndpointARNMember = true
a.HasEndpointARN = true
}
}
// Decorate member references that are modeled with the wrong type.
// Specifically the case where a member was modeled as a string, but is
// expected to sent across the wire as a base64 value.
//
// e.g. S3's SSECustomerKey and CopySourceSSECustomerKey
for _, refName := range []string{
"SSECustomerKey",
"CopySourceSSECustomerKey",
} {
if ref, ok := s.MemberRefs[refName]; ok {
ref.CustomTags = append(ref.CustomTags, ShapeTag{
"marshal-as", "blob",
})
}
}
// Expires should be a string not time.Time since the format is not
// enforced by S3, and any value can be set to this field outside of the SDK.
if strings.HasSuffix(name, "Output") {
if ref, ok := s.MemberRefs["Expires"]; ok {
if strExpires == nil {
newShape := *ref.Shape
strExpires = &newShape
strExpires.Type = "string"
strExpires.refs = []*ShapeRef{}
}
ref.Shape.removeRef(ref)
ref.Shape = strExpires
ref.Shape.refs = append(ref.Shape.refs, &s.MemberRef)
}
}
}
s3CustRemoveHeadObjectModeledErrors(a)
return nil
}
// S3 HeadObject API call incorrect models NoSuchKey as valid
// error code that can be returned. This operation does not
// return error codes, all error codes are derived from HTTP
// status codes.
//
// aws/aws-sdk-go#1208
func s3CustRemoveHeadObjectModeledErrors(a *API) {
op, ok := a.Operations["HeadObject"]
if !ok {
return
}
op.Documentation += `
//
// See http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#RESTErrorResponses
// for more information on returned errors.`
op.ErrorRefs = []ShapeRef{}
}
// S3 service operations with an AccountId need accessors to be generated for
// them so the fields can be dynamically accessed without reflection.
func s3ControlCustomizations(a *API) error {
for _, s := range a.Shapes {
// Generate a endpointARN method for the BucketName shape if this is used as an operation input
if s.UsedAsInput {
if s.ShapeName == "CreateBucketInput" || s.ShapeName == "ListRegionalBucketsInput" {
// For operations CreateBucketInput and ListRegionalBuckets the OutpostID shape
// needs to be decorated
var outpostIDMemberShape *ShapeRef
for memberName, ref := range s.MemberRefs {
if memberName != "OutpostId" || ref.Shape.Type != "string" {
continue
}
if outpostIDMemberShape != nil {
return fmt.Errorf("more then one OutpostID shape present on shape")
}
ref.OutpostIDMember = true
outpostIDMemberShape = ref
}
if outpostIDMemberShape != nil {
s.HasOutpostIDMember = true
a.HasOutpostID = true
}
continue
}
// List of input shapes that use accesspoint names as arnable fields
accessPointNameArnables := map[string]struct{}{
"GetAccessPointInput": {},
"DeleteAccessPointInput": {},
"PutAccessPointPolicyInput": {},
"GetAccessPointPolicyInput": {},
"DeleteAccessPointPolicyInput": {},
}
var endpointARNShape *ShapeRef
for _, ref := range s.MemberRefs {
// Operations that have AccessPointName field that takes in an ARN as input
if _, ok := accessPointNameArnables[s.ShapeName]; ok {
if ref.OrigShapeName != "AccessPointName" || ref.Shape.Type != "string" {
continue
}
} else if ref.OrigShapeName != "BucketName" || ref.Shape.Type != "string" {
// All other operations currently allow BucketName field to take in ARN.
// Exceptions for these are CreateBucket and ListRegionalBucket which use
// Outpost id and are handled above separately.
continue
}
if endpointARNShape != nil {
return fmt.Errorf("more then one member present on shape takes arn as input")
}
ref.EndpointARN = true
endpointARNShape = ref
}
if endpointARNShape != nil {
s.HasEndpointARNMember = true
a.HasEndpointARN = true
for _, ref := range s.MemberRefs {
// check for account id customization
if ref.OrigShapeName == "AccountId" && ref.Shape.Type == "string" {
ref.AccountIDMemberWithARN = true
s.HasAccountIdMemberWithARN = true
a.HasAccountIdWithARN = true
}
}
}
}
}
return nil
}
// cloudfrontCustomizations customized the API generation to replace values
// specific to CloudFront.
func cloudfrontCustomizations(a *API) error {
// MaxItems members should always be integers
for _, s := range a.Shapes {
if ref, ok := s.MemberRefs["MaxItems"]; ok {
ref.ShapeName = "Integer"
ref.Shape = a.Shapes["Integer"]
}
}
return nil
}
// mergeServicesCustomizations references any duplicate shapes from DynamoDB
func mergeServicesCustomizations(a *API) error {
info := mergeServices[a.PackageName()]
p := strings.Replace(a.path, info.srcName, info.dstName, -1)
if info.serviceVersion != "" {
index := strings.LastIndex(p, string(filepath.Separator))
files, _ := ioutil.ReadDir(p[:index])
if len(files) > 1 {
panic("New version was introduced")
}
p = p[:index] + "/" + info.serviceVersion
}
file := filepath.Join(p, "api-2.json")
serviceAPI := API{}
serviceAPI.Attach(file)
serviceAPI.Setup()
for n := range a.Shapes {
if _, ok := serviceAPI.Shapes[n]; ok {
a.Shapes[n].resolvePkg = SDKImportRoot + "/service/" + info.dstName
}
}
return nil
}
// rdsCustomizations are customization for the service/rds. This adds
// non-modeled fields used for presigning.
func rdsCustomizations(a *API) error {
inputs := []string{
"CopyDBSnapshotInput",
"CreateDBInstanceReadReplicaInput",
"CopyDBClusterSnapshotInput",
"CreateDBClusterInput",
"StartDBInstanceAutomatedBackupsReplicationInput",
}
generatePresignedURL(a, inputs)
return nil
}
// neptuneCustomizations are customization for the service/neptune. This adds
// non-modeled fields used for presigning.
func neptuneCustomizations(a *API) error {
inputs := []string{
"CopyDBClusterSnapshotInput",
"CreateDBClusterInput",
}
generatePresignedURL(a, inputs)
return nil
}
// neptuneCustomizations are customization for the service/neptune. This adds
// non-modeled fields used for presigning.
func docdbCustomizations(a *API) error {
inputs := []string{
"CopyDBClusterSnapshotInput",
"CreateDBClusterInput",
}
generatePresignedURL(a, inputs)
return nil
}
func generatePresignedURL(a *API, inputShapes []string) {
for _, input := range inputShapes {
if ref, ok := a.Shapes[input]; ok {
ref.MemberRefs["SourceRegion"] = &ShapeRef{
Documentation: docstring(`SourceRegion is the source region where the resource exists. This is not sent over the wire and is only used for presigning. This value should always have the same region as the source ARN.`),
ShapeName: "String",
Shape: a.Shapes["String"],
Ignore: true,
}
ref.MemberRefs["DestinationRegion"] = &ShapeRef{
Documentation: docstring(`DestinationRegion is used for presigning the request to a given region.`),
ShapeName: "String",
Shape: a.Shapes["String"],
}
}
}
}
func disableEndpointResolving(a *API) error {
a.Metadata.NoResolveEndpoint = true
return nil
}
func backfillAuthType(typ AuthType, opNames ...string) func(*API) error {
return func(a *API) error {
for _, opName := range opNames {
op, ok := a.Operations[opName]
if !ok {
panic("unable to backfill auth-type for unknown operation " + opName)
}
if v := op.AuthType; len(v) != 0 {
fmt.Fprintf(os.Stderr, "unable to backfill auth-type for %s, already set, %s", opName, v)
continue
}
op.AuthType = typ
}
return nil
}
}
| 399 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bufio"
"encoding/json"
"fmt"
"html"
"io"
"os"
"regexp"
"strings"
xhtml "golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
type apiDocumentation struct {
Operations map[string]string
Service string
Shapes map[string]shapeDocumentation
}
type shapeDocumentation struct {
Base string
Refs map[string]string
}
// AttachDocs attaches documentation from a JSON filename.
func (a *API) AttachDocs(filename string) error {
var d apiDocumentation
f, err := os.Open(filename)
defer f.Close()
if err != nil {
return err
}
err = json.NewDecoder(f).Decode(&d)
if err != nil {
return fmt.Errorf("failed to decode %s, err: %v", filename, err)
}
return d.setup(a)
}
func (d *apiDocumentation) setup(a *API) error {
a.Documentation = docstring(d.Service)
for opName, doc := range d.Operations {
if _, ok := a.Operations[opName]; !ok {
return fmt.Errorf("%s, doc op %q not found in API op set",
a.name, opName)
}
a.Operations[opName].Documentation = docstring(doc)
}
for shapeName, docShape := range d.Shapes {
if s, ok := a.Shapes[shapeName]; ok {
s.Documentation = docstring(docShape.Base)
}
for ref, doc := range docShape.Refs {
if doc == "" {
continue
}
parts := strings.Split(ref, "$")
if len(parts) != 2 {
fmt.Fprintf(os.Stderr,
"Shape Doc %s has unexpected reference format, %q\n",
shapeName, ref)
continue
}
if s, ok := a.Shapes[parts[0]]; ok && len(s.MemberRefs) != 0 {
if m, ok := s.MemberRefs[parts[1]]; ok && m.ShapeName == shapeName {
m.Documentation = docstring(doc)
}
}
}
}
return nil
}
var reNewline = regexp.MustCompile(`\r?\n`)
var reMultiSpace = regexp.MustCompile(`\s+`)
var reComments = regexp.MustCompile(`<!--.*?-->`)
var reFullnameBlock = regexp.MustCompile(`<fullname>(.+?)<\/fullname>`)
var reFullname = regexp.MustCompile(`<fullname>(.*?)</fullname>`)
var reExamples = regexp.MustCompile(`<examples?>.+?<\/examples?>`)
var reEndNL = regexp.MustCompile(`\n+$`)
// docstring rewrites a string to insert godocs formatting.
func docstring(doc string) string {
doc = strings.TrimSpace(doc)
if doc == "" {
return ""
}
doc = reNewline.ReplaceAllString(doc, "")
doc = reMultiSpace.ReplaceAllString(doc, " ")
doc = reComments.ReplaceAllString(doc, "")
var fullname string
parts := reFullnameBlock.FindStringSubmatch(doc)
if len(parts) > 1 {
fullname = parts[1]
}
// Remove full name block from doc string
doc = reFullname.ReplaceAllString(doc, "")
doc = reExamples.ReplaceAllString(doc, "")
doc = generateDoc(doc)
doc = reEndNL.ReplaceAllString(doc, "")
doc = html.UnescapeString(doc)
// Replace doc with full name if doc is empty.
if len(doc) == 0 {
doc = fullname
}
return commentify(doc)
}
const (
indent = " "
)
// commentify converts a string to a Go comment
func commentify(doc string) string {
if len(doc) == 0 {
return ""
}
lines := strings.Split(doc, "\n")
out := make([]string, 0, len(lines))
for i := 0; i < len(lines); i++ {
line := lines[i]
if i > 0 && line == "" && lines[i-1] == "" {
continue
}
out = append(out, line)
}
if len(out) > 0 {
out[0] = "// " + out[0]
return strings.Join(out, "\n// ")
}
return ""
}
func wrap(text string, length int) string {
var b strings.Builder
s := bufio.NewScanner(strings.NewReader(text))
for s.Scan() {
line := s.Text()
// cleanup the line's spaces
var i int
for i = 0; i < len(line); i++ {
c := line[i]
// Ignore leading spaces, e.g indents.
if !(c == ' ' || c == '\t') {
break
}
}
line = line[:i] + strings.Join(strings.Fields(line[i:]), " ")
splitLine(&b, line, length)
}
return strings.TrimRight(b.String(), "\n")
}
func splitLine(w stringWriter, line string, length int) {
leading := getLeadingWhitespace(line)
line = line[len(leading):]
length -= len(leading)
const splitOn = " "
for len(line) > length {
// Find the next whitespace to the length
idx := strings.Index(line[length:], splitOn)
if idx == -1 {
break
}
offset := length + idx
if v := line[offset+len(splitOn):]; len(v) == 1 && strings.ContainsAny(v, `,.!?'"`) {
// Workaround for long lines with space before the punctuation mark.
break
}
w.WriteString(leading)
w.WriteString(line[:offset])
w.WriteByte('\n')
line = strings.TrimLeft(line[offset+len(splitOn):], " \t")
}
if len(line) > 0 {
w.WriteString(leading)
w.WriteString(line)
}
// Add the newline back in that was stripped out by scanner.
w.WriteByte('\n')
}
func getLeadingWhitespace(v string) string {
var o strings.Builder
for _, c := range v {
if c == ' ' || c == '\t' {
o.WriteRune(c)
} else {
break
}
}
return o.String()
}
// generateDoc will generate the proper doc string for html encoded or plain text doc entries.
func generateDoc(htmlSrc string) string {
tokenizer := xhtml.NewTokenizer(strings.NewReader(htmlSrc))
var builder strings.Builder
if err := encodeHTMLToText(&builder, tokenizer); err != nil {
panic(fmt.Sprintf("failed to generated docs, %v", err))
}
return wrap(strings.Trim(builder.String(), "\n"), 72)
}
type stringWriter interface {
Write([]byte) (int, error)
WriteByte(byte) error
WriteRune(rune) (int, error)
WriteString(string) (int, error)
}
func encodeHTMLToText(w stringWriter, z *xhtml.Tokenizer) error {
encoder := newHTMLTokenEncoder(w)
defer encoder.Flush()
for {
tt := z.Next()
if tt == xhtml.ErrorToken {
if err := z.Err(); err == io.EOF {
return nil
} else if err != nil {
return err
}
}
if err := encoder.Encode(z.Token()); err != nil {
return err
}
}
}
type htmlTokenHandler interface {
OnStartTagToken(xhtml.Token) htmlTokenHandler
OnEndTagToken(xhtml.Token, bool)
OnSelfClosingTagToken(xhtml.Token)
OnTextTagToken(xhtml.Token)
}
type htmlTokenEncoder struct {
w stringWriter
depth int
handlers []tokenHandlerItem
baseHandler tokenHandlerItem
}
type tokenHandlerItem struct {
handler htmlTokenHandler
depth int
}
func newHTMLTokenEncoder(w stringWriter) *htmlTokenEncoder {
baseHandler := newBlockTokenHandler(w)
baseHandler.rootBlock = true
return &htmlTokenEncoder{
w: w,
baseHandler: tokenHandlerItem{
handler: baseHandler,
},
}
}
func (e *htmlTokenEncoder) Flush() error {
e.baseHandler.handler.OnEndTagToken(xhtml.Token{Type: xhtml.TextToken}, true)
return nil
}
func (e *htmlTokenEncoder) Encode(token xhtml.Token) error {
h := e.baseHandler
if len(e.handlers) != 0 {
h = e.handlers[len(e.handlers)-1]
}
switch token.Type {
case xhtml.StartTagToken:
e.depth++
next := h.handler.OnStartTagToken(token)
if next != nil {
e.handlers = append(e.handlers, tokenHandlerItem{
handler: next,
depth: e.depth,
})
}
case xhtml.EndTagToken:
handlerBlockClosing := e.depth == h.depth
h.handler.OnEndTagToken(token, handlerBlockClosing)
// Remove all but the root handler as the handler is no longer needed.
if handlerBlockClosing {
e.handlers = e.handlers[:len(e.handlers)-1]
}
e.depth--
case xhtml.SelfClosingTagToken:
h.handler.OnSelfClosingTagToken(token)
case xhtml.TextToken:
h.handler.OnTextTagToken(token)
}
return nil
}
type baseTokenHandler struct {
w stringWriter
}
func (e *baseTokenHandler) OnStartTagToken(token xhtml.Token) htmlTokenHandler { return nil }
func (e *baseTokenHandler) OnEndTagToken(token xhtml.Token, blockClosing bool) {}
func (e *baseTokenHandler) OnSelfClosingTagToken(token xhtml.Token) {}
func (e *baseTokenHandler) OnTextTagToken(token xhtml.Token) {
e.w.WriteString(token.Data)
}
type blockTokenHandler struct {
baseTokenHandler
rootBlock bool
origWriter stringWriter
strBuilder *strings.Builder
started bool
newlineBeforeNextBlock bool
}
func newBlockTokenHandler(w stringWriter) *blockTokenHandler {
strBuilder := &strings.Builder{}
return &blockTokenHandler{
origWriter: w,
strBuilder: strBuilder,
baseTokenHandler: baseTokenHandler{
w: strBuilder,
},
}
}
func (e *blockTokenHandler) OnStartTagToken(token xhtml.Token) htmlTokenHandler {
e.started = true
if e.newlineBeforeNextBlock {
e.w.WriteString("\n")
e.newlineBeforeNextBlock = false
}
switch token.DataAtom {
case atom.A:
return newLinkTokenHandler(e.w, token)
case atom.Ul:
e.w.WriteString("\n")
e.newlineBeforeNextBlock = true
return newListTokenHandler(e.w)
case atom.Div, atom.Dt, atom.P, atom.H1, atom.H2, atom.H3, atom.H4, atom.H5, atom.H6:
e.w.WriteString("\n")
e.newlineBeforeNextBlock = true
return newBlockTokenHandler(e.w)
case atom.Pre, atom.Code:
if e.rootBlock {
e.w.WriteString("\n")
e.w.WriteString(indent)
e.newlineBeforeNextBlock = true
}
return newBlockTokenHandler(e.w)
}
return nil
}
func (e *blockTokenHandler) OnEndTagToken(token xhtml.Token, blockClosing bool) {
if !blockClosing {
return
}
e.origWriter.WriteString(e.strBuilder.String())
if e.newlineBeforeNextBlock {
e.origWriter.WriteString("\n")
e.newlineBeforeNextBlock = false
}
e.strBuilder.Reset()
}
func (e *blockTokenHandler) OnTextTagToken(token xhtml.Token) {
if e.newlineBeforeNextBlock {
e.w.WriteString("\n")
e.newlineBeforeNextBlock = false
}
if !e.started {
token.Data = strings.TrimLeft(token.Data, " \t\n")
}
if len(token.Data) != 0 {
e.started = true
}
e.baseTokenHandler.OnTextTagToken(token)
}
type linkTokenHandler struct {
baseTokenHandler
linkToken xhtml.Token
}
func newLinkTokenHandler(w stringWriter, token xhtml.Token) *linkTokenHandler {
return &linkTokenHandler{
baseTokenHandler: baseTokenHandler{
w: w,
},
linkToken: token,
}
}
func (e *linkTokenHandler) OnEndTagToken(token xhtml.Token, blockClosing bool) {
if !blockClosing {
return
}
if href, ok := getHTMLTokenAttr(e.linkToken.Attr, "href"); ok && len(href) != 0 {
fmt.Fprintf(e.w, " (%s)", strings.TrimSpace(href))
}
}
type listTokenHandler struct {
baseTokenHandler
items int
}
func newListTokenHandler(w stringWriter) *listTokenHandler {
return &listTokenHandler{
baseTokenHandler: baseTokenHandler{
w: w,
},
}
}
func (e *listTokenHandler) OnStartTagToken(token xhtml.Token) htmlTokenHandler {
switch token.DataAtom {
case atom.Li:
if e.items >= 1 {
e.w.WriteString("\n\n")
}
e.items++
return newListItemTokenHandler(e.w)
}
return nil
}
func (e *listTokenHandler) OnTextTagToken(token xhtml.Token) {
// Squash whitespace between list and items
}
type listItemTokenHandler struct {
baseTokenHandler
origWriter stringWriter
strBuilder *strings.Builder
}
func newListItemTokenHandler(w stringWriter) *listItemTokenHandler {
strBuilder := &strings.Builder{}
return &listItemTokenHandler{
origWriter: w,
strBuilder: strBuilder,
baseTokenHandler: baseTokenHandler{
w: strBuilder,
},
}
}
func (e *listItemTokenHandler) OnStartTagToken(token xhtml.Token) htmlTokenHandler {
switch token.DataAtom {
case atom.P:
return newBlockTokenHandler(e.w)
}
return nil
}
func (e *listItemTokenHandler) OnEndTagToken(token xhtml.Token, blockClosing bool) {
if !blockClosing {
return
}
e.origWriter.WriteString(indent + "* ")
e.origWriter.WriteString(strings.TrimSpace(e.strBuilder.String()))
}
type trimSpaceTokenHandler struct {
baseTokenHandler
origWriter stringWriter
strBuilder *strings.Builder
}
func newTrimSpaceTokenHandler(w stringWriter) *trimSpaceTokenHandler {
strBuilder := &strings.Builder{}
return &trimSpaceTokenHandler{
origWriter: w,
strBuilder: strBuilder,
baseTokenHandler: baseTokenHandler{
w: strBuilder,
},
}
}
func (e *trimSpaceTokenHandler) OnEndTagToken(token xhtml.Token, blockClosing bool) {
if !blockClosing {
return
}
e.origWriter.WriteString(strings.TrimSpace(e.strBuilder.String()))
}
func getHTMLTokenAttr(attr []xhtml.Attribute, name string) (string, bool) {
for _, a := range attr {
if strings.EqualFold(a.Key, name) {
return a.Val, true
}
}
return "", false
}
| 547 |
session-manager-plugin | aws | Go | // +build go1.8,codegen
package api
import (
"testing"
)
func TestDocstring(t *testing.T) {
cases := map[string]struct {
In string
Expect string
}{
"non HTML": {
In: "Testing 1 2 3",
Expect: "// Testing 1 2 3",
},
"link": {
In: `<a href="https://example.com">a link</a>`,
Expect: "// a link (https://example.com)",
},
"link with space": {
In: `<a href=" https://example.com">a link</a>`,
Expect: "// a link (https://example.com)",
},
"list HTML 01": {
In: "<ul><li>Testing 1 2 3</li> <li>FooBar</li></ul>",
Expect: "// * Testing 1 2 3\n// \n// * FooBar",
},
"list HTML 02": {
In: "<ul> <li>Testing 1 2 3</li> <li>FooBar</li> </ul>",
Expect: "// * Testing 1 2 3\n// \n// * FooBar",
},
"list HTML leading spaces": {
In: " <ul> <li>Testing 1 2 3</li> <li>FooBar</li> </ul>",
Expect: "// * Testing 1 2 3\n// \n// * FooBar",
},
"list HTML paragraph": {
In: "<ul> <li> <p>Testing 1 2 3</p> </li><li> <p>FooBar</p></li></ul>",
Expect: "// * Testing 1 2 3\n// \n// * FooBar",
},
"inline code HTML": {
In: "<ul> <li><code>Testing</code>: 1 2 3</li> <li>FooBar</li> </ul>",
Expect: "// * Testing: 1 2 3\n// \n// * FooBar",
},
"complex list paragraph": {
In: "<ul> <li><p><code>FOO</code> Bar</p></li><li><p><code>Xyz</code> ABC</p></li></ul>",
Expect: "// * FOO Bar\n// \n// * Xyz ABC",
},
"inline code in paragraph": {
In: "<p><code>Testing</code>: 1 2 3</p>",
Expect: "// Testing: 1 2 3",
},
"root pre": {
In: "<pre><code>Testing</code></pre>",
Expect: "// Testing",
},
"paragraph": {
In: "<p>Testing 1 2 3</p>",
Expect: "// Testing 1 2 3",
},
"wrap lines": {
In: "<span data-target-type=\"operation\" data-service=\"secretsmanager\" data-target=\"CreateSecret\">CreateSecret</span> <span data-target-type=\"structure\" data-service=\"secretsmanager\" data-target=\"SecretListEntry\">SecretListEntry</span> <span data-target-type=\"structure\" data-service=\"secretsmanager\" data-target=\"CreateSecret$SecretName\">SecretName</span> <span data-target-type=\"structure\" data-service=\"secretsmanager\" data-target=\"SecretListEntry$KmsKeyId\">KmsKeyId</span>",
Expect: "// CreateSecret SecretListEntry SecretName KmsKeyId",
},
"links with spaces": {
In: "<p> Deletes the replication configuration from the bucket. For information about replication configuration, see <a href=\" https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html\">Cross-Region Replication (CRR)</a> in the <i>Amazon S3 Developer Guide</i>. </p>",
Expect: "// Deletes the replication configuration from the bucket. For information about\n// replication configuration, see Cross-Region Replication (CRR) (https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html)\n// in the Amazon S3 Developer Guide.",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
t.Log("Input", c.In)
actual := docstring(c.In)
if e, a := c.Expect, actual; e != a {
t.Errorf("expect %q, got %q", e, a)
}
})
}
}
| 82 |
session-manager-plugin | aws | Go | package api
import "text/template"
const endpointARNShapeTmplDef = `
{{- define "endpointARNShapeTmpl" }}
{{ range $_, $name := $.MemberNames -}}
{{ $elem := index $.MemberRefs $name -}}
{{ if $elem.EndpointARN -}}
func (s *{{ $.ShapeName }}) getEndpointARN() (arn.Resource, error) {
if s.{{ $name }} == nil {
return nil, fmt.Errorf("member {{ $name }} is nil")
}
return parseEndpointARN(*s.{{ $name }})
}
func (s *{{ $.ShapeName }}) hasEndpointARN() bool {
if s.{{ $name }} == nil {
return false
}
return arn.IsARN(*s.{{ $name }})
}
// updateArnableField updates the value of the input field that
// takes an ARN as an input. This method is useful to backfill
// the parsed resource name from ARN into the input member.
// It returns a pointer to a modified copy of input and an error.
// Note that original input is not modified.
func (s {{ $.ShapeName }}) updateArnableField(v string) (interface{}, error) {
if s.{{ $name }} == nil {
return nil, fmt.Errorf("member {{ $name }} is nil")
}
s.{{ $name }} = aws.String(v)
return &s, nil
}
{{ end -}}
{{ end }}
{{ end }}
`
var endpointARNShapeTmpl = template.Must(
template.New("endpointARNShapeTmpl").
Parse(endpointARNShapeTmplDef),
)
const outpostIDShapeTmplDef = `
{{- define "outpostIDShapeTmpl" }}
{{ range $_, $name := $.MemberNames -}}
{{ $elem := index $.MemberRefs $name -}}
{{ if $elem.OutpostIDMember -}}
func (s *{{ $.ShapeName }}) getOutpostID() (string, error) {
if s.{{ $name }} == nil {
return "", fmt.Errorf("member {{ $name }} is nil")
}
return *s.{{ $name }}, nil
}
func (s *{{ $.ShapeName }}) hasOutpostID() bool {
if s.{{ $name }} == nil {
return false
}
return true
}
{{ end -}}
{{ end }}
{{ end }}
`
var outpostIDShapeTmpl = template.Must(
template.New("outpostIDShapeTmpl").
Parse(outpostIDShapeTmplDef),
)
const accountIDWithARNShapeTmplDef = `
{{- define "accountIDWithARNShapeTmpl" }}
{{ range $_, $name := $.MemberNames -}}
{{ $elem := index $.MemberRefs $name -}}
{{ if $elem.AccountIDMemberWithARN -}}
// updateAccountID returns a pointer to a modified copy of input,
// if account id is not provided, we update the account id in modified input
// if account id is provided, but doesn't match with the one in ARN, we throw an error
// if account id is not updated, we return nil. Note that original input is not modified.
func (s {{ $.ShapeName }}) updateAccountID(accountId string) (interface{}, error) {
if s.{{ $name }} == nil {
s.{{ $name }} = aws.String(accountId)
return &s, nil
} else if *s.{{ $name }} != accountId {
return &s, fmt.Errorf("Account ID mismatch, the Account ID cannot be specified in an ARN and in the accountId field")
}
return nil, nil
}
{{ end -}}
{{ end }}
{{ end }}
`
var accountIDWithARNShapeTmpl = template.Must(
template.New("accountIDWithARNShapeTmpl").
Parse(accountIDWithARNShapeTmplDef),
)
| 101 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"fmt"
"text/template"
)
func setupEndpointHostPrefix(op *Operation) {
op.API.AddSDKImport("private/protocol")
buildHandler := fmt.Sprintf("protocol.NewHostPrefixHandler(%q, ",
op.Endpoint.HostPrefix)
if op.InputRef.Shape.HasHostLabelMembers() {
buildHandler += "input.hostLabels"
} else {
buildHandler += "nil"
}
buildHandler += ")"
op.CustomBuildHandlers = append(op.CustomBuildHandlers,
buildHandler,
"protocol.ValidateEndpointHostHandler",
)
}
// HasHostLabelMembers returns true if the shape contains any members which are
// decorated with the hostLabel trait.
func (s *Shape) HasHostLabelMembers() bool {
for _, ref := range s.MemberRefs {
if ref.HostLabel {
return true
}
}
return false
}
var hostLabelsShapeTmpl = template.Must(
template.New("hostLabelsShapeTmpl").
Parse(hostLabelsShapeTmplDef),
)
const hostLabelsShapeTmplDef = `
{{- define "hostLabelsShapeTmpl" }}
func (s *{{ $.ShapeName }}) hostLabels() map[string]string {
return map[string]string{
{{- range $name, $ref := $.MemberRefs }}
{{- if $ref.HostLabel }}
"{{ $name }}": aws.StringValue(s.{{ $name }}),
{{- end }}
{{- end }}
}
}
{{- end }}
`
| 60 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"fmt"
"text/template"
)
// EventStreamAPI provides details about the event stream async API and
// associated EventStream shapes.
type EventStreamAPI struct {
API *API
Operation *Operation
Name string
InputStream *EventStream
OutputStream *EventStream
RequireHTTP2 bool
// The eventstream generated code was generated with an older model that
// does not scale with bi-directional models. This drives the need to
// expose the output shape's event stream member as an exported member.
Legacy bool
}
func (es *EventStreamAPI) StreamInputEventTypeGetterName() string {
return "eventTypeFor" + es.Name + "InputEvent"
}
func (es *EventStreamAPI) StreamOutputUnmarshalerForEventName() string {
return "eventTypeFor" + es.Name + "OutputEvent"
}
// EventStream represents a single eventstream group (input/output) and the
// modeled events that are known for the stream.
type EventStream struct {
Name string
Shape *Shape
Events []*Event
Exceptions []*Event
}
func (es *EventStream) EventGroupName() string {
return es.Name + "Event"
}
func (es *EventStream) StreamWriterAPIName() string {
return es.Name + "Writer"
}
func (es *EventStream) StreamWriterImplName() string {
return "write" + es.Name
}
func (es *EventStream) StreamEventTypeGetterName() string {
return "eventTypeFor" + es.Name + "Event"
}
func (es *EventStream) StreamReaderAPIName() string {
return es.Name + "Reader"
}
func (es *EventStream) StreamReaderImplName() string {
return "read" + es.Name
}
func (es *EventStream) StreamReaderImplConstructorName() string {
return "newRead" + es.Name
}
func (es *EventStream) StreamUnmarshalerForEventName() string {
return "unmarshalerFor" + es.Name + "Event"
}
func (es *EventStream) StreamUnknownEventName() string {
return es.Name + "UnknownEvent"
}
// Event is a single EventStream event that can be sent or received in an
// EventStream.
type Event struct {
Name string
Shape *Shape
For *EventStream
Private bool
}
// ShapeDoc returns the docstring for the EventStream API.
func (esAPI *EventStreamAPI) ShapeDoc() string {
tmpl := template.Must(template.New("eventStreamShapeDoc").Parse(`
{{- $.Name }} provides handling of EventStreams for
the {{ $.Operation.ExportedName }} API.
{{- if $.OutputStream }}
Use this type to receive {{ $.OutputStream.Name }} events. The events
can be read from the stream.
The events that can be received are:
{{- range $_, $event := $.OutputStream.Events }}
* {{ $event.Shape.ShapeName }}
{{- end }}
{{- end }}
{{- if $.InputStream }}
Use this type to send {{ $.InputStream.Name }} events. The events
can be written to the stream.
The events that can be sent are:
{{ range $_, $event := $.InputStream.Events -}}
* {{ $event.Shape.ShapeName }}
{{- end }}
{{- end }}`))
var w bytes.Buffer
if err := tmpl.Execute(&w, esAPI); err != nil {
panic(fmt.Sprintf("failed to generate eventstream shape template for %v, %v",
esAPI.Operation.ExportedName, err))
}
return commentify(w.String())
}
func hasEventStream(topShape *Shape) bool {
for _, ref := range topShape.MemberRefs {
if ref.Shape.IsEventStream {
return true
}
}
return false
}
func eventStreamAPIShapeRefDoc(refName string) string {
return commentify(fmt.Sprintf("Use %s to use the API's stream.", refName))
}
func (a *API) setupEventStreams() error {
streams := EventStreams{}
for opName, op := range a.Operations {
inputRef := getEventStreamMember(op.InputRef.Shape)
outputRef := getEventStreamMember(op.OutputRef.Shape)
if inputRef == nil && outputRef == nil {
continue
}
if inputRef != nil && outputRef == nil {
return fmt.Errorf("event stream input only stream not supported for protocol %s, %s, %v",
a.NiceName(), opName, a.Metadata.Protocol)
}
switch a.Metadata.Protocol {
case `rest-json`, `rest-xml`, `json`:
default:
return UnsupportedAPIModelError{
Err: fmt.Errorf("EventStream not supported for protocol %s, %s, %v",
a.NiceName(), opName, a.Metadata.Protocol),
}
}
var inputStream *EventStream
if inputRef != nil {
inputStream = streams.GetStream(op.InputRef.Shape, inputRef.Shape)
inputStream.Shape.IsInputEventStream = true
}
var outputStream *EventStream
if outputRef != nil {
outputStream = streams.GetStream(op.OutputRef.Shape, outputRef.Shape)
outputStream.Shape.IsOutputEventStream = true
}
requireHTTP2 := op.API.Metadata.ProtocolSettings.HTTP2 == "eventstream" &&
inputStream != nil && outputStream != nil
a.HasEventStream = true
op.EventStreamAPI = &EventStreamAPI{
API: a,
Operation: op,
Name: op.ExportedName + "EventStream",
InputStream: inputStream,
OutputStream: outputStream,
Legacy: isLegacyEventStream(op),
RequireHTTP2: requireHTTP2,
}
op.OutputRef.Shape.OutputEventStreamAPI = op.EventStreamAPI
if s, ok := a.Shapes[op.EventStreamAPI.Name]; ok {
newName := op.EventStreamAPI.Name + "Data"
if _, ok := a.Shapes[newName]; ok {
panic(fmt.Sprintf(
"%s: attempting to rename %s to %s, but shape with that name already exists",
a.NiceName(), op.EventStreamAPI.Name, newName))
}
s.Rename(newName)
}
}
return nil
}
// EventStreams is a map of streams for the API shared across all operations.
// Ensurs that no stream is duplicated.
type EventStreams map[*Shape]*EventStream
// GetStream returns an EventStream for the operations top level shape, and
// member reference to the stream shape.
func (es *EventStreams) GetStream(topShape *Shape, streamShape *Shape) *EventStream {
var stream *EventStream
if v, ok := (*es)[streamShape]; ok {
stream = v
} else {
stream = setupEventStream(streamShape)
(*es)[streamShape] = stream
}
if topShape.API.Metadata.Protocol == "json" {
if topShape.EventFor == nil {
topShape.EventFor = map[string]*EventStream{}
}
topShape.EventFor[stream.Name] = stream
}
return stream
}
var legacyEventStream = map[string]map[string]struct{}{
"s3": {
"SelectObjectContent": struct{}{},
},
"kinesis": {
"SubscribeToShard": struct{}{},
},
}
func isLegacyEventStream(op *Operation) bool {
if s, ok := legacyEventStream[op.API.PackageName()]; ok {
if _, ok = s[op.ExportedName]; ok {
return true
}
}
return false
}
func (e EventStreamAPI) OutputMemberName() string {
if e.Legacy {
return "EventStream"
}
return "eventStream"
}
func getEventStreamMember(topShape *Shape) *ShapeRef {
for _, ref := range topShape.MemberRefs {
if !ref.Shape.IsEventStream {
continue
}
return ref
}
return nil
}
func setupEventStream(s *Shape) *EventStream {
eventStream := &EventStream{
Name: s.ShapeName,
Shape: s,
}
s.EventStream = eventStream
for _, eventRefName := range s.MemberNames() {
eventRef := s.MemberRefs[eventRefName]
if !(eventRef.Shape.IsEvent || eventRef.Shape.Exception) {
panic(fmt.Sprintf("unexpected non-event member reference %s.%s",
s.ShapeName, eventRefName))
}
updateEventPayloadRef(eventRef.Shape)
if eventRef.Shape.EventFor == nil {
eventRef.Shape.EventFor = map[string]*EventStream{}
}
eventRef.Shape.EventFor[eventStream.Name] = eventStream
// Exceptions and events are two different lists to allow the SDK
// to easily generate code with the two handled differently.
event := &Event{
Name: eventRefName,
Shape: eventRef.Shape,
For: eventStream,
}
if eventRef.Shape.Exception {
eventStream.Exceptions = append(eventStream.Exceptions, event)
} else {
eventStream.Events = append(eventStream.Events, event)
}
}
return eventStream
}
func updateEventPayloadRef(parent *Shape) {
refName := parent.PayloadRefName()
if len(refName) == 0 {
return
}
payloadRef := parent.MemberRefs[refName]
if payloadRef.Shape.Type == "blob" {
return
}
if len(payloadRef.LocationName) != 0 {
return
}
payloadRef.LocationName = refName
}
| 321 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"fmt"
"io"
"strings"
"text/template"
)
func renderEventStreamAPI(w io.Writer, op *Operation) error {
// Imports needed by the EventStream APIs.
op.API.AddImport("fmt")
op.API.AddImport("bytes")
op.API.AddImport("io")
op.API.AddImport("time")
op.API.AddSDKImport("aws")
op.API.AddSDKImport("aws/awserr")
op.API.AddSDKImport("aws/request")
op.API.AddSDKImport("private/protocol/eventstream")
op.API.AddSDKImport("private/protocol/eventstream/eventstreamapi")
w.Write([]byte(`
var _ awserr.Error
`))
return eventStreamAPITmpl.Execute(w, op)
}
// Template for an EventStream API Shape that will provide read/writing events
// across the EventStream. This is a special shape that's only public members
// are the Events channel and a Close and Err method.
//
// Executed in the context of a Shape.
var eventStreamAPITmpl = template.Must(
template.New("eventStreamAPITmplDef").
Funcs(template.FuncMap{
"unexported": func(v string) string {
return strings.ToLower(string(v[0])) + v[1:]
},
}).
Parse(eventStreamAPITmplDef),
)
const eventStreamAPITmplDef = `
{{- $esapi := $.EventStreamAPI }}
{{- $outputStream := $esapi.OutputStream }}
{{- $inputStream := $esapi.InputStream }}
// {{ $esapi.Name }} provides the event stream handling for the {{ $.ExportedName }}.
//
// For testing and mocking the event stream this type should be initialized via
// the New{{ $esapi.Name }} constructor function. Using the functional options
// to pass in nested mock behavior.
type {{ $esapi.Name }} struct {
{{- if $inputStream }}
// Writer is the EventStream writer for the {{ $inputStream.Name }}
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Writer.
//
// Must not be nil.
Writer {{ $inputStream.StreamWriterAPIName }}
inputWriter io.WriteCloser
{{- if eq .API.Metadata.Protocol "json" }}
input {{ $.InputRef.GoType }}
{{- end }}
{{- end }}
{{- if $outputStream }}
// Reader is the EventStream reader for the {{ $outputStream.Name }}
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Reader.
//
// Must not be nil.
Reader {{ $outputStream.StreamReaderAPIName }}
outputReader io.ReadCloser
{{- if eq .API.Metadata.Protocol "json" }}
output {{ $.OutputRef.GoType }}
{{- end }}
{{- end }}
{{- if $esapi.Legacy }}
// StreamCloser is the io.Closer for the EventStream connection. For HTTP
// EventStream this is the response Body. The stream will be closed when
// the Close method of the EventStream is called.
StreamCloser io.Closer
{{- end }}
done chan struct{}
closeOnce sync.Once
err *eventstreamapi.OnceError
}
// New{{ $esapi.Name }} initializes an {{ $esapi.Name }}.
// This function should only be used for testing and mocking the {{ $esapi.Name }}
// stream within your application.
{{- if $inputStream }}
//
// The Writer member must be set before writing events to the stream.
{{- end }}
{{- if $outputStream }}
//
// The Reader member must be set before reading events from the stream.
{{- end }}
{{- if $esapi.Legacy }}
//
// The StreamCloser member should be set to the underlying io.Closer,
// (e.g. http.Response.Body), that will be closed when the stream Close method
// is called.
{{- end }}
//
// es := New{{ $esapi.Name }}(func(o *{{ $esapi.Name}}{
{{- if $inputStream }}
// es.Writer = myMockStreamWriter
{{- end }}
{{- if $outputStream }}
// es.Reader = myMockStreamReader
{{- end }}
{{- if $esapi.Legacy }}
// es.StreamCloser = myMockStreamCloser
{{- end }}
// })
func New{{ $esapi.Name }}(opts ...func(*{{ $esapi.Name}})) *{{ $esapi.Name }} {
es := &{{ $esapi.Name }} {
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
for _, fn := range opts {
fn(es)
}
return es
}
{{- if $esapi.Legacy }}
func (es *{{ $esapi.Name }}) setStreamCloser(r *request.Request) {
es.StreamCloser = r.HTTPResponse.Body
}
{{- end }}
func (es *{{ $esapi.Name }}) runOnStreamPartClose(r *request.Request) {
if es.done == nil {
return
}
go es.waitStreamPartClose()
}
func (es *{{ $esapi.Name }}) waitStreamPartClose() {
{{- if $inputStream }}
var inputErrCh <-chan struct{}
if v, ok := es.Writer.(interface{ErrorSet() <-chan struct{}}); ok {
inputErrCh = v.ErrorSet()
}
{{- end }}
{{- if $outputStream }}
var outputErrCh <-chan struct{}
if v, ok := es.Reader.(interface{ErrorSet() <-chan struct{}}); ok {
outputErrCh = v.ErrorSet()
}
var outputClosedCh <- chan struct{}
if v, ok := es.Reader.(interface{Closed() <-chan struct{}}); ok {
outputClosedCh = v.Closed()
}
{{- end }}
select {
case <-es.done:
{{- if $inputStream }}
case <-inputErrCh:
es.err.SetError(es.Writer.Err())
es.Close()
{{- end }}
{{- if $outputStream }}
case <-outputErrCh:
es.err.SetError(es.Reader.Err())
es.Close()
case <-outputClosedCh:
if err := es.Reader.Err(); err != nil {
es.err.SetError(es.Reader.Err())
}
es.Close()
{{- end }}
}
}
{{- if $inputStream }}
{{- if eq .API.Metadata.Protocol "json" }}
func {{ $esapi.StreamInputEventTypeGetterName }}(event {{ $inputStream.EventGroupName }}) (string, error) {
if _, ok := event.({{ $.InputRef.GoType }}); ok {
return "initial-request", nil
}
return {{ $inputStream.StreamEventTypeGetterName }}(event)
}
{{- end }}
func (es *{{ $esapi.Name }}) setupInputPipe(r *request.Request) {
inputReader, inputWriter := io.Pipe()
r.SetStreamingBody(inputReader)
es.inputWriter = inputWriter
}
// Closes the input-pipe writer
func (es *{{ $esapi.Name }}) closeInputPipe() error {
if es.inputWriter != nil {
return es.inputWriter.Close()
}
return nil
}
// Send writes the event to the stream blocking until the event is written.
// Returns an error if the event was not written.
//
// These events are:
// {{ range $_, $event := $inputStream.Events }}
// * {{ $event.Shape.ShapeName }}
{{- end }}
func (es *{{ $esapi.Name }}) Send(ctx aws.Context, event {{ $inputStream.EventGroupName }}) error {
return es.Writer.Send(ctx, event)
}
func (es *{{ $esapi.Name }}) runInputStream(r *request.Request) {
var opts []func(*eventstream.Encoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.EncodeWithLogger(r.Config.Logger))
}
var encoder eventstreamapi.Encoder = eventstream.NewEncoder(es.inputWriter, opts...)
var closer aws.MultiCloser
{{- if $.ShouldSignRequestBody }}
{{- $_ := $.API.AddSDKImport "aws/signer/v4" }}
sigSeed, err := v4.GetSignedRequestSignature(r.HTTPRequest)
if err != nil {
r.Error = awserr.New(request.ErrCodeSerialization,
"unable to get initial request's signature", err)
return
}
signer := eventstreamapi.NewSignEncoder(
v4.NewStreamSigner(r.ClientInfo.SigningRegion, r.ClientInfo.SigningName,
sigSeed, r.Config.Credentials),
encoder,
)
encoder = signer
closer = append(closer, signer)
{{- end }}
closer = append(closer, es.inputWriter)
eventWriter := eventstreamapi.NewEventWriter(encoder,
protocol.HandlerPayloadMarshal{
Marshalers: r.Handlers.BuildStream,
},
{{- if eq .API.Metadata.Protocol "json" }}
{{ $esapi.StreamInputEventTypeGetterName }},
{{- else }}
{{ $inputStream.StreamEventTypeGetterName }},
{{- end }}
)
es.Writer = &{{ $inputStream.StreamWriterImplName }}{
StreamWriter: eventstreamapi.NewStreamWriter(eventWriter, closer),
}
}
{{- if eq .API.Metadata.Protocol "json" }}
func (es *{{ $esapi.Name }}) sendInitialEvent(r *request.Request) {
if err := es.Send(es.input); err != nil {
r.Error = err
}
}
{{- end }}
{{- end }}
{{- if $outputStream }}
{{- if eq .API.Metadata.Protocol "json" }}
type {{ $esapi.StreamOutputUnmarshalerForEventName }} struct {
unmarshalerForEvent func(string) (eventstreamapi.Unmarshaler, error)
output {{ $.OutputRef.GoType }}
}
func (e {{ $esapi.StreamOutputUnmarshalerForEventName }}) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
if eventType == "initial-response" {
return e.output, nil
}
return e.unmarshalerForEvent(eventType)
}
{{- end }}
// Events returns a channel to read events from.
//
// These events are:
// {{ range $_, $event := $outputStream.Events }}
// * {{ $event.Shape.ShapeName }}
{{- end }}
// * {{ $outputStream.StreamUnknownEventName }}
func (es *{{ $esapi.Name }}) Events() <-chan {{ $outputStream.EventGroupName }} {
return es.Reader.Events()
}
func (es *{{ $esapi.Name }}) runOutputStream(r *request.Request) {
var opts []func(*eventstream.Decoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger))
}
unmarshalerForEvent := {{ $outputStream.StreamUnmarshalerForEventName }}{
metadata: protocol.ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
},
}.UnmarshalerForEventName
{{- if eq .API.Metadata.Protocol "json" }}
unmarshalerForEvent = {{ $esapi.StreamOutputUnmarshalerForEventName }}{
unmarshalerForEvent: unmarshalerForEvent,
output: es.output,
}.UnmarshalerForEventName
{{- end }}
decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...)
eventReader := eventstreamapi.NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: r.Handlers.UnmarshalStream,
},
unmarshalerForEvent,
)
es.outputReader = r.HTTPResponse.Body
es.Reader = {{ $outputStream.StreamReaderImplConstructorName }}(eventReader)
}
{{- if eq .API.Metadata.Protocol "json" }}
func (es *{{ $esapi.Name }}) recvInitialEvent(r *request.Request) {
// Wait for the initial response event, which must be the first
// event to be received from the API.
select {
case event, ok := <- es.Events():
if !ok {
return
}
v, ok := event.({{ $.OutputRef.GoType }})
if !ok || v == nil {
r.Error = awserr.New(
request.ErrCodeSerialization,
fmt.Sprintf("invalid event, %T, expect %T, %v",
event, ({{ $.OutputRef.GoType }})(nil), v),
nil,
)
return
}
*es.output = *v
es.output.{{ $.EventStreamAPI.OutputMemberName }} = es
}
}
{{- end }}
{{- end }}
// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
{{- if $inputStream }}
//
// Will close the underlying EventStream writer, and no more events can be
// sent.
{{- end }}
{{- if $outputStream }}
//
// You can use the closing of the Reader's Events channel to terminate your
// application's read from the API's stream.
{{- end }}
//
func (es *{{ $esapi.Name }}) Close() (err error) {
es.closeOnce.Do(es.safeClose)
return es.Err()
}
func (es *{{ $esapi.Name }}) safeClose() {
if es.done != nil {
close(es.done)
}
{{- if $inputStream }}
t := time.NewTicker(time.Second)
defer t.Stop()
writeCloseDone := make(chan error)
go func() {
if err := es.Writer.Close(); err != nil {
es.err.SetError(err)
}
close(writeCloseDone)
}()
select {
case <-t.C:
case <-writeCloseDone:
}
if err := es.closeInputPipe(); err != nil {
es.err.SetError(err)
}
{{- end }}
{{- if $outputStream }}
es.Reader.Close()
if es.outputReader != nil {
es.outputReader.Close()
}
{{- end }}
{{- if $esapi.Legacy }}
es.StreamCloser.Close()
{{- end }}
}
// Err returns any error that occurred while reading or writing EventStream
// Events from the service API's response. Returns nil if there were no errors.
func (es *{{ $esapi.Name }}) Err() error {
if err := es.err.Err(); err != nil {
return err
}
{{- if $inputStream }}
if err := es.Writer.Err(); err != nil {
return err
}
{{- end }}
{{- if $outputStream }}
if err := es.Reader.Err(); err != nil {
return err
}
{{- end }}
return nil
}
`
func renderEventStreamShape(w io.Writer, s *Shape) error {
// Imports needed by the EventStream APIs.
s.API.AddImport("fmt")
s.API.AddImport("bytes")
s.API.AddImport("io")
s.API.AddImport("sync")
s.API.AddSDKImport("aws")
s.API.AddSDKImport("aws/awserr")
s.API.AddSDKImport("private/protocol/eventstream")
s.API.AddSDKImport("private/protocol/eventstream/eventstreamapi")
return eventStreamShapeTmpl.Execute(w, s)
}
var eventStreamShapeTmpl = func() *template.Template {
t := template.Must(
template.New("eventStreamShapeTmplDef").
Parse(eventStreamShapeTmplDef),
)
template.Must(
t.AddParseTree(
"eventStreamShapeWriterTmpl", eventStreamShapeWriterTmpl.Tree),
)
template.Must(
t.AddParseTree(
"eventStreamShapeReaderTmpl", eventStreamShapeReaderTmpl.Tree),
)
return t
}()
const eventStreamShapeTmplDef = `
{{- $eventStream := $.EventStream }}
{{- $eventStreamEventGroup := printf "%sEvent" $eventStream.Name }}
// {{ $eventStreamEventGroup }} groups together all EventStream
// events writes for {{ $eventStream.Name }}.
//
// These events are:
// {{ range $_, $event := $eventStream.Events }}
// * {{ $event.Shape.ShapeName }}
{{- end }}
type {{ $eventStreamEventGroup }} interface {
event{{ $eventStream.Name }}()
eventstreamapi.Marshaler
eventstreamapi.Unmarshaler
}
{{- if $.IsInputEventStream }}
{{- template "eventStreamShapeWriterTmpl" $ }}
{{- end }}
{{- if $.IsOutputEventStream }}
{{- template "eventStreamShapeReaderTmpl" $ }}
{{- end }}
`
// EventStreamHeaderTypeMap provides the mapping of a EventStream Header's
// Value type to the shape reference's member type.
type EventStreamHeaderTypeMap struct {
Header string
Member string
}
// Returns if the event has any members which are not the event's blob payload,
// nor a header.
func eventHasNonBlobPayloadMembers(s *Shape) bool {
num := len(s.MemberRefs)
for _, ref := range s.MemberRefs {
if ref.IsEventHeader || (ref.IsEventPayload && (ref.Shape.Type == "blob" || ref.Shape.Type == "string")) {
num--
}
}
return num > 0
}
func setEventHeaderValueForType(s *Shape, memVar string) string {
switch s.Type {
case "blob":
return fmt.Sprintf("eventstream.BytesValue(%s)", memVar)
case "string":
return fmt.Sprintf("eventstream.StringValue(*%s)", memVar)
case "boolean":
return fmt.Sprintf("eventstream.BoolValue(*%s)", memVar)
case "byte":
return fmt.Sprintf("eventstream.Int8Value(int8(*%s))", memVar)
case "short":
return fmt.Sprintf("eventstream.Int16Value(int16(*%s))", memVar)
case "integer":
return fmt.Sprintf("eventstream.Int32Value(int32(*%s))", memVar)
case "long":
return fmt.Sprintf("eventstream.Int64Value(*%s)", memVar)
case "float":
return fmt.Sprintf("eventstream.Float32Value(float32(*%s))", memVar)
case "double":
return fmt.Sprintf("eventstream.Float64Value(*%s)", memVar)
case "timestamp":
return fmt.Sprintf("eventstream.TimestampValue(*%s)", memVar)
default:
panic(fmt.Sprintf("value type %s not supported for event headers, %s", s.Type, s.ShapeName))
}
}
func shapeMessageType(s *Shape) string {
if s.Exception {
return "eventstreamapi.ExceptionMessageType"
}
return "eventstreamapi.EventMessageType"
}
var eventStreamEventShapeTmplFuncs = template.FuncMap{
"EventStreamHeaderTypeMap": func(ref *ShapeRef) EventStreamHeaderTypeMap {
switch ref.Shape.Type {
case "boolean":
return EventStreamHeaderTypeMap{Header: "bool", Member: "bool"}
case "byte":
return EventStreamHeaderTypeMap{Header: "int8", Member: "int64"}
case "short":
return EventStreamHeaderTypeMap{Header: "int16", Member: "int64"}
case "integer":
return EventStreamHeaderTypeMap{Header: "int32", Member: "int64"}
case "long":
return EventStreamHeaderTypeMap{Header: "int64", Member: "int64"}
case "timestamp":
return EventStreamHeaderTypeMap{Header: "time.Time", Member: "time.Time"}
case "blob":
return EventStreamHeaderTypeMap{Header: "[]byte", Member: "[]byte"}
case "string":
return EventStreamHeaderTypeMap{Header: "string", Member: "string"}
case "uuid":
return EventStreamHeaderTypeMap{Header: "[]byte", Member: "[]byte"}
default:
panic("unsupported EventStream header type, " + ref.Shape.Type)
}
},
"EventHeaderValueForType": setEventHeaderValueForType,
"ShapeMessageType": shapeMessageType,
"HasNonBlobPayloadMembers": eventHasNonBlobPayloadMembers,
}
// Template for an EventStream Event shape. This is a normal API shape that is
// decorated as an EventStream Event.
//
// Executed in the context of a Shape.
var eventStreamEventShapeTmpl = template.Must(template.New("eventStreamEventShapeTmpl").
Funcs(eventStreamEventShapeTmplFuncs).Parse(`
{{ range $_, $eventStream := $.EventFor }}
// The {{ $.ShapeName }} is and event in the {{ $eventStream.Name }} group of events.
func (s *{{ $.ShapeName }}) event{{ $eventStream.Name }}() {}
{{ end }}
// UnmarshalEvent unmarshals the EventStream Message into the {{ $.ShapeName }} value.
// This method is only used internally within the SDK's EventStream handling.
func (s *{{ $.ShapeName }}) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
{{- range $memName, $memRef := $.MemberRefs }}
{{- if $memRef.IsEventHeader }}
if hv := msg.Headers.Get("{{ $memName }}"); hv != nil {
{{ $types := EventStreamHeaderTypeMap $memRef -}}
v := hv.Get().({{ $types.Header }})
{{- if ne $types.Header $types.Member }}
m := {{ $types.Member }}(v)
s.{{ $memName }} = {{ if $memRef.UseIndirection }}&{{ end }}m
{{- else }}
s.{{ $memName }} = {{ if $memRef.UseIndirection }}&{{ end }}v
{{- end }}
}
{{- else if (and ($memRef.IsEventPayload) (eq $memRef.Shape.Type "blob")) }}
s.{{ $memName }} = make([]byte, len(msg.Payload))
copy(s.{{ $memName }}, msg.Payload)
{{- else if (and ($memRef.IsEventPayload) (eq $memRef.Shape.Type "string")) }}
s.{{ $memName }} = aws.String(string(msg.Payload))
{{- end }}
{{- end }}
{{- if HasNonBlobPayloadMembers $ }}
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
{{- end }}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *{{ $.ShapeName}}) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue({{ ShapeMessageType $ }}))
{{- range $memName, $memRef := $.MemberRefs }}
{{- if $memRef.IsEventHeader }}
{{ $memVar := printf "s.%s" $memName -}}
{{ $typedMem := EventHeaderValueForType $memRef.Shape $memVar -}}
msg.Headers.Set("{{ $memName }}", {{ $typedMem }})
{{- else if (and ($memRef.IsEventPayload) (eq $memRef.Shape.Type "blob")) }}
msg.Headers.Set(":content-type", eventstream.StringValue("application/octet-stream"))
msg.Payload = s.{{ $memName }}
{{- else if (and ($memRef.IsEventPayload) (eq $memRef.Shape.Type "string")) }}
msg.Payload = []byte(aws.StringValue(s.{{ $memName }}))
{{- end }}
{{- end }}
{{- if HasNonBlobPayloadMembers $ }}
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
{{- end }}
return msg, err
}
`))
| 666 |
session-manager-plugin | aws | Go | // +build codegen
package api
import "text/template"
var eventStreamShapeReaderTmpl = template.Must(template.New("eventStreamShapeReaderTmpl").
Funcs(template.FuncMap{}).
Parse(`
{{- $es := $.EventStream }}
// {{ $es.StreamReaderAPIName }} provides the interface for reading to the stream. The
// default implementation for this interface will be {{ $.ShapeName }}.
//
// The reader's Close method must allow multiple concurrent calls.
//
// These events are:
// {{ range $_, $event := $es.Events }}
// * {{ $event.Shape.ShapeName }}
{{- end }}
// * {{ $es.StreamUnknownEventName }}
type {{ $es.StreamReaderAPIName }} interface {
// Returns a channel of events as they are read from the event stream.
Events() <-chan {{ $es.EventGroupName }}
// Close will stop the reader reading events from the stream.
Close() error
// Returns any error that has occurred while reading from the event stream.
Err() error
}
type {{ $es.StreamReaderImplName }} struct {
eventReader *eventstreamapi.EventReader
stream chan {{ $es.EventGroupName }}
err *eventstreamapi.OnceError
done chan struct{}
closeOnce sync.Once
}
func {{ $es.StreamReaderImplConstructorName }}(eventReader *eventstreamapi.EventReader) *{{ $es.StreamReaderImplName }} {
r := &{{ $es.StreamReaderImplName }}{
eventReader: eventReader,
stream: make(chan {{ $es.EventGroupName }}),
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
go r.readEventStream()
return r
}
// Close will close the underlying event stream reader.
func (r *{{ $es.StreamReaderImplName }}) Close() error {
r.closeOnce.Do(r.safeClose)
return r.Err()
}
func (r *{{ $es.StreamReaderImplName }}) ErrorSet() <-chan struct{} {
return r.err.ErrorSet()
}
func (r *{{ $es.StreamReaderImplName }}) Closed() <-chan struct{} {
return r.done
}
func (r *{{ $es.StreamReaderImplName }}) safeClose() {
close(r.done)
}
func (r *{{ $es.StreamReaderImplName }}) Err() error {
return r.err.Err()
}
func (r *{{ $es.StreamReaderImplName }}) Events() <-chan {{ $es.EventGroupName }} {
return r.stream
}
func (r *{{ $es.StreamReaderImplName }}) readEventStream() {
defer r.Close()
defer close(r.stream)
for {
event, err := r.eventReader.ReadEvent()
if err != nil {
if err == io.EOF {
return
}
select {
case <-r.done:
// If closed already ignore the error
return
default:
}
if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok {
continue
}
r.err.SetError(err)
return
}
select {
case r.stream <- event.({{ $es.EventGroupName }}):
case <-r.done:
return
}
}
}
type {{ $es.StreamUnmarshalerForEventName }} struct {
metadata protocol.ResponseMetadata
}
func (u {{ $es.StreamUnmarshalerForEventName }}) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
switch eventType {
{{- range $_, $event := $es.Events }}
case {{ printf "%q" $event.Name }}:
return &{{ $event.Shape.ShapeName }}{}, nil
{{- end }}
{{- range $_, $event := $es.Exceptions }}
case {{ printf "%q" $event.Name }}:
return newError{{ $event.Shape.ShapeName }}(u.metadata).(eventstreamapi.Unmarshaler), nil
{{- end }}
default:
return &{{ $es.StreamUnknownEventName }}{Type: eventType}, nil
}
}
// {{ $es.StreamUnknownEventName }} provides a failsafe event for the
// {{ $es.Name }} group of events when an unknown event is received.
type {{ $es.StreamUnknownEventName }} struct {
Type string
Message eventstream.Message
}
// The {{ $es.StreamUnknownEventName }} is and event in the {{ $es.Name }}
// group of events.
func (s *{{ $es.StreamUnknownEventName }}) event{{ $es.Name }}() {}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (e *{{ $es.StreamUnknownEventName }}) MarshalEvent(pm protocol.PayloadMarshaler) (
msg eventstream.Message, err error,
) {
return e.Message.Clone(), nil
}
// UnmarshalEvent unmarshals the EventStream Message into the {{ $.ShapeName }} value.
// This method is only used internally within the SDK's EventStream handling.
func (e *{{ $es.StreamUnknownEventName }}) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Message = msg.Clone()
return nil
}
`))
| 159 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"text/template"
)
var eventStreamReaderTestTmpl = template.Must(
template.New("eventStreamReaderTestTmpl").Funcs(template.FuncMap{
"ValueForType": valueForType,
"HasNonBlobPayloadMembers": eventHasNonBlobPayloadMembers,
"EventHeaderValueForType": setEventHeaderValueForType,
"Map": templateMap,
"OptionalAddInt": func(do bool, a, b int) int {
if !do {
return a
}
return a + b
},
"HasNonEventStreamMember": func(s *Shape) bool {
for _, ref := range s.MemberRefs {
if !ref.Shape.IsEventStream {
return true
}
}
return false
},
}).Parse(`
{{ range $opName, $op := $.Operations }}
{{ if $op.EventStreamAPI }}
{{ if $op.EventStreamAPI.OutputStream }}
{{ template "event stream outputStream tests" $op.EventStreamAPI }}
{{ end }}
{{ end }}
{{ end }}
type loopReader struct {
source *bytes.Reader
}
func (c *loopReader) Read(p []byte) (int, error) {
if c.source.Len() == 0 {
c.source.Seek(0, 0)
}
return c.source.Read(p)
}
{{ define "event stream outputStream tests" }}
func Test{{ $.Operation.ExportedName }}_Read(t *testing.T) {
expectEvents, eventMsgs := mock{{ $.Operation.ExportedName }}ReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
{{- if HasNonEventStreamMember $.Operation.OutputRef.Shape }}
expectResp := expectEvents[0].(*{{ $.Operation.OutputRef.Shape.ShapeName }})
{{- range $name, $ref := $.Operation.OutputRef.Shape.MemberRefs }}
{{- if not $ref.Shape.IsEventStream }}
if e, a := expectResp.{{ $name }}, resp.{{ $name }}; !reflect.DeepEqual(e,a) {
t.Errorf("expect %v, got %v", e, a)
}
{{- end }}
{{- end }}
{{- end }}
// Trim off response output type pseudo event so only event messages remain.
expectEvents = expectEvents[1:]
{{ end }}
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func Test{{ $.Operation.ExportedName }}_ReadClose(t *testing.T) {
_, eventMsgs := mock{{ $.Operation.ExportedName }}ReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
{{ if gt (len $.OutputStream.Events) 0 -}}
// Assert calling Err before close does not close the stream.
resp.GetStream().Err()
select {
case _, ok := <-resp.GetStream().Events():
if !ok {
t.Fatalf("expect stream not to be closed, but was")
}
default:
}
{{- end }}
resp.GetStream().Close()
<-resp.GetStream().Events()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func Test{{ $.Operation.ExportedName }}_ReadUnknownEvent(t *testing.T) {
expectEvents, eventMsgs := mock{{ $.Operation.ExportedName }}ReadEvents()
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
eventOffset := 1
{{- else }}
var eventOffset int
{{- end }}
unknownEvent := eventstream.Message{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("UnknownEventName"),
},
},
Payload: []byte("some unknown event"),
}
eventMsgs = append(eventMsgs[:eventOffset],
append([]eventstream.Message{unknownEvent}, eventMsgs[eventOffset:]...)...)
expectEvents = append(expectEvents[:eventOffset],
append([]{{ $.OutputStream.Name }}Event{
&{{ $.OutputStream.StreamUnknownEventName }}{
Type: "UnknownEventName",
Message: unknownEvent,
},
},
expectEvents[eventOffset:]...)...)
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
// Trim off response output type pseudo event so only event messages remain.
expectEvents = expectEvents[1:]
{{ end }}
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func Benchmark{{ $.Operation.ExportedName }}_Read(b *testing.B) {
_, eventMsgs := mock{{ $.Operation.ExportedName }}ReadEvents()
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
for _, msg := range eventMsgs {
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
}
stream := &loopReader{source: bytes.NewReader(buf.Bytes())}
sess := unit.Session
svc := New(sess, &aws.Config{
Endpoint: aws.String("https://example.com"),
DisableParamValidation: aws.Bool(true),
})
svc.Handlers.Send.Swap(corehandlers.SendHandler.Name,
request.NamedHandler{Name: "mockSend",
Fn: func(r *request.Request) {
r.HTTPResponse = &http.Response{
Status: "200 OK",
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(stream),
}
},
},
)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
b.Fatalf("failed to create request, %v", err)
}
defer resp.GetStream().Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err = resp.GetStream().Err(); err != nil {
b.Fatalf("expect no error, got %v", err)
}
event := <-resp.GetStream().Events()
if event == nil {
b.Fatalf("expect event, got nil, %v, %d", resp.GetStream().Err(), i)
}
}
}
func mock{{ $.Operation.ExportedName }}ReadEvents() (
[]{{ $.OutputStream.Name }}Event,
[]eventstream.Message,
) {
expectEvents := []{{ $.OutputStream.Name }}Event {
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
{{- template "set event type" $.Operation.OutputRef.Shape }}
{{- end }}
{{- range $_, $event := $.OutputStream.Events }}
{{- template "set event type" $event.Shape }}
{{- end }}
}
var marshalers request.HandlerList
marshalers.PushBackNamed({{ $.API.ProtocolPackage }}.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
{{- template "set event message" Map "idx" 0 "parentShape" $.Operation.OutputRef.Shape "eventName" "initial-response" }}
{{- end }}
{{- range $idx, $event := $.OutputStream.Events }}
{{- $offsetIdx := OptionalAddInt (eq $.Operation.API.Metadata.Protocol "json") $idx 1 }}
{{- template "set event message" Map "idx" $offsetIdx "parentShape" $event.Shape "eventName" $event.Name }}
{{- end }}
}
return expectEvents, eventMsgs
}
{{- if $.OutputStream.Exceptions }}
func Test{{ $.Operation.ExportedName }}_ReadException(t *testing.T) {
expectEvents := []{{ $.OutputStream.Name }}Event {
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
{{- template "set event type" $.Operation.OutputRef.Shape }}
{{- end }}
{{- $exception := index $.OutputStream.Exceptions 0 }}
{{- template "set event type" $exception.Shape }}
}
var marshalers request.HandlerList
marshalers.PushBackNamed({{ $.API.ProtocolPackage }}.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
eventMsgs := []eventstream.Message{
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
{{- template "set event message" Map "idx" 0 "parentShape" $.Operation.OutputRef.Shape "eventName" "initial-response" }}
{{- end }}
{{- $offsetIdx := OptionalAddInt (eq $.Operation.API.Metadata.Protocol "json") 0 1 }}
{{- $exception := index $.OutputStream.Exceptions 0 }}
{{- template "set event message" Map "idx" $offsetIdx "parentShape" $exception.Shape "eventName" $exception.Name }}
}
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
<-resp.GetStream().Events()
err = resp.GetStream().Err()
if err == nil {
t.Fatalf("expect err, got none")
}
expectErr := {{ ValueForType $exception.Shape nil }}
aerr, ok := err.(awserr.Error)
if !ok {
t.Errorf("expect exception, got %T, %#v", err, err)
}
if e, a := expectErr.Code(), aerr.Code(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr.Message(), aerr.Message(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr, aerr; !reflect.DeepEqual(e, a) {
t.Errorf("expect error %+#v, got %+#v", e, a)
}
}
{{- range $_, $exception := $.OutputStream.Exceptions }}
var _ awserr.Error = (*{{ $exception.Shape.ShapeName }})(nil)
{{- end }}
{{ end }}
{{ end }}
{{/* Params: *Shape */}}
{{ define "set event type" }}
&{{ $.ShapeName }}{
{{- if $.Exception }}
RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
{{- end }}
{{- range $memName, $memRef := $.MemberRefs }}
{{- if not $memRef.Shape.IsEventStream }}
{{ $memName }}: {{ ValueForType $memRef.Shape nil }},
{{- end }}
{{- end }}
},
{{- end }}
{{/* Params: idx:int, parentShape:*Shape, eventName:string */}}
{{ define "set event message" }}
{
Headers: eventstream.Headers{
{{- if $.parentShape.Exception }}
eventstreamtest.EventExceptionTypeHeader,
{
Name: eventstreamapi.ExceptionTypeHeader,
Value: eventstream.StringValue("{{ $.eventName }}"),
},
{{- else }}
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("{{ $.eventName }}"),
},
{{- end }}
{{- range $memName, $memRef := $.parentShape.MemberRefs }}
{{- template "set event message header" Map "idx" $.idx "parentShape" $.parentShape "memName" $memName "memRef" $memRef }}
{{- end }}
},
{{- template "set event message payload" Map "idx" $.idx "parentShape" $.parentShape }}
},
{{- end }}
{{/* Params: idx:int, parentShape:*Shape, memName:string, memRef:*ShapeRef */}}
{{ define "set event message header" }}
{{- if $.memRef.IsEventHeader }}
{
Name: "{{ $.memName }}",
{{- $shapeValueVar := printf "expectEvents[%d].(%s).%s" $.idx $.parentShape.GoType $.memName }}
Value: {{ EventHeaderValueForType $.memRef.Shape $shapeValueVar }},
},
{{- end }}
{{- end }}
{{/* Params: idx:int, parentShape:*Shape, memName:string, memRef:*ShapeRef */}}
{{ define "set event message payload" }}
{{- $payloadMemName := $.parentShape.PayloadRefName }}
{{- if HasNonBlobPayloadMembers $.parentShape }}
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[{{ $.idx }}]),
{{- else if $payloadMemName }}
{{- $shapeType := (index $.parentShape.MemberRefs $payloadMemName).Shape.Type }}
{{- if eq $shapeType "blob" }}
Payload: expectEvents[{{ $.idx }}].({{ $.parentShape.GoType }}).{{ $payloadMemName }},
{{- else if eq $shapeType "string" }}
Payload: []byte(*expectEvents[{{ $.idx }}].({{ $.parentShape.GoType }}).{{ $payloadMemName }}),
{{- end }}
{{- end }}
{{- end }}
`))
| 440 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"fmt"
"strings"
)
// APIEventStreamTestGoCode generates Go code for EventStream operation tests.
func (a *API) APIEventStreamTestGoCode() string {
var buf bytes.Buffer
a.resetImports()
a.AddImport("bytes")
a.AddImport("io/ioutil")
a.AddImport("net/http")
a.AddImport("reflect")
a.AddImport("testing")
a.AddImport("time")
a.AddImport("context")
a.AddImport("strings")
a.AddImport("sync")
a.AddSDKImport("aws")
a.AddSDKImport("aws/corehandlers")
a.AddSDKImport("aws/request")
a.AddSDKImport("aws/awserr")
a.AddSDKImport("awstesting/unit")
a.AddSDKImport("private/protocol")
a.AddSDKImport("private/protocol/", a.ProtocolPackage())
a.AddSDKImport("private/protocol/eventstream")
a.AddSDKImport("private/protocol/eventstream/eventstreamapi")
a.AddSDKImport("private/protocol/eventstream/eventstreamtest")
unused := `
var _ time.Time
var _ awserr.Error
var _ context.Context
var _ sync.WaitGroup
var _ strings.Reader
`
if err := eventStreamReaderTestTmpl.Execute(&buf, a); err != nil {
panic(err)
}
if err := eventStreamWriterTestTmpl.Execute(&buf, a); err != nil {
panic(err)
}
return a.importsGoCode() + unused + strings.TrimSpace(buf.String())
}
func templateMap(args ...interface{}) map[string]interface{} {
if len(args)%2 != 0 {
panic(fmt.Sprintf("invalid map call, non-even args %v", args))
}
m := map[string]interface{}{}
for i := 0; i < len(args); i += 2 {
k, ok := args[i].(string)
if !ok {
panic(fmt.Sprintf("invalid map call, arg is not string, %T, %v", args[i], args[i]))
}
m[k] = args[i+1]
}
return m
}
func valueForType(s *Shape, visited []string) string {
if isShapeVisited(visited, s.ShapeName) {
return "nil"
}
visited = append(visited, s.ShapeName)
switch s.Type {
case "blob":
return `[]byte("blob value goes here")`
case "string":
return `aws.String("string value goes here")`
case "boolean":
return `aws.Bool(true)`
case "byte":
return `aws.Int64(1)`
case "short":
return `aws.Int64(12)`
case "integer":
return `aws.Int64(123)`
case "long":
return `aws.Int64(1234)`
case "float":
return `aws.Float64(123.4)`
case "double":
return `aws.Float64(123.45)`
case "timestamp":
return `aws.Time(time.Unix(1396594860, 0).UTC())`
case "structure":
w := bytes.NewBuffer(nil)
fmt.Fprintf(w, "&%s{\n", s.ShapeName)
if s.Exception {
fmt.Fprintf(w, `RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
`)
}
for _, refName := range s.MemberNames() {
fmt.Fprintf(w, "%s: %s,\n", refName, valueForType(s.MemberRefs[refName].Shape, visited))
}
fmt.Fprintf(w, "}")
return w.String()
case "list":
w := bytes.NewBuffer(nil)
fmt.Fprintf(w, "%s{\n", s.GoType())
if !isShapeVisited(visited, s.MemberRef.Shape.ShapeName) {
for i := 0; i < 3; i++ {
fmt.Fprintf(w, "%s,\n", valueForType(s.MemberRef.Shape, visited))
}
}
fmt.Fprintf(w, "}")
return w.String()
case "map":
w := bytes.NewBuffer(nil)
fmt.Fprintf(w, "%s{\n", s.GoType())
if !isShapeVisited(visited, s.ValueRef.Shape.ShapeName) {
for _, k := range []string{"a", "b", "c"} {
fmt.Fprintf(w, "%q: %s,\n", k, valueForType(s.ValueRef.Shape, visited))
}
}
fmt.Fprintf(w, "}")
return w.String()
default:
panic(fmt.Sprintf("valueForType does not support %s, %s", s.ShapeName, s.Type))
}
}
func isShapeVisited(visited []string, name string) bool {
for _, v := range visited {
if v == name {
return true
}
}
return false
}
| 149 |
session-manager-plugin | aws | Go | // +build codegen
package api
import "text/template"
var eventStreamShapeWriterTmpl = template.Must(template.New("eventStreamShapeWriterTmpl").
Funcs(template.FuncMap{}).
Parse(`
{{- $es := $.EventStream }}
// {{ $es.StreamWriterAPIName }} provides the interface for writing events to the stream.
// The default implementation for this interface will be {{ $.ShapeName }}.
//
// The writer's Close method must allow multiple concurrent calls.
//
// These events are:
// {{ range $_, $event := $es.Events }}
// * {{ $event.Shape.ShapeName }}
{{- end }}
type {{ $es.StreamWriterAPIName }} interface {
// Sends writes events to the stream blocking until the event has been
// written. An error is returned if the write fails.
Send(aws.Context, {{ $es.EventGroupName }}) error
// Close will stop the writer writing to the event stream.
Close() error
// Returns any error that has occurred while writing to the event stream.
Err() error
}
type {{ $es.StreamWriterImplName }} struct {
*eventstreamapi.StreamWriter
}
func (w *{{ $es.StreamWriterImplName }}) Send(ctx aws.Context, event {{ $es.EventGroupName }}) error {
return w.StreamWriter.Send(ctx, event)
}
func {{ $es.StreamEventTypeGetterName }}(event eventstreamapi.Marshaler) (string, error) {
switch event.(type) {
{{- range $_, $event := $es.Events }}
case *{{ $event.Shape.ShapeName }}:
return {{ printf "%q" $event.Name }}, nil
{{- end }}
{{- range $_, $event := $es.Exceptions }}
case *{{ $event.Shape.ShapeName }}:
return {{ printf "%q" $event.Name }}, nil
{{- end }}
default:
return "", awserr.New(
request.ErrCodeSerialization,
fmt.Sprintf("unknown event type, %T, for {{ $es.Name }}", event),
nil,
)
}
}
`))
| 60 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"text/template"
)
var eventStreamWriterTestTmpl = template.Must(
template.New("eventStreamWriterTestTmpl").Funcs(template.FuncMap{
"ValueForType": valueForType,
"HasNonBlobPayloadMembers": eventHasNonBlobPayloadMembers,
"EventHeaderValueForType": setEventHeaderValueForType,
"Map": templateMap,
"OptionalAddInt": func(do bool, a, b int) int {
if !do {
return a
}
return a + b
},
"HasNonEventStreamMember": func(s *Shape) bool {
for _, ref := range s.MemberRefs {
if !ref.Shape.IsEventStream {
return true
}
}
return false
},
}).Parse(`
{{ range $opName, $op := $.Operations }}
{{ if $op.EventStreamAPI }}
{{ if $op.EventStreamAPI.InputStream }}
{{ template "event stream inputStream tests" $op.EventStreamAPI }}
{{ end }}
{{ end }}
{{ end }}
{{ define "event stream inputStream tests" }}
func Test{{ $.Operation.ExportedName }}_Write(t *testing.T) {
clientEvents, expectedClientEvents := mock{{ $.Operation.ExportedName }}WriteEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
&eventstreamtest.ServeEventStream{
T: t,
ClientEvents: expectedClientEvents,
BiDirectional: true,
},
true)
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
stream := resp.GetStream()
for _, event := range clientEvents {
err = stream.Send(context.Background(), event)
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
}
if err := stream.Close(); err != nil {
t.Errorf("expect no error, got %v", err)
}
}
func Test{{ $.Operation.ExportedName }}_WriteClose(t *testing.T) {
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{T: t, BiDirectional: true},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
// Assert calling Err before close does not close the stream.
resp.GetStream().Err()
{{ $eventShape := index $.InputStream.Events 0 }}
err = resp.GetStream().Send(context.Background(), &{{ $eventShape.Shape.ShapeName }}{})
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
resp.GetStream().Close()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func Test{{ $.Operation.ExportedName }}_WriteError(t *testing.T) {
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
BiDirectional: true,
ForceCloseAfter: time.Millisecond * 500,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
{{ $eventShape := index $.InputStream.Events 0 }}
for {
err = resp.GetStream().Send(context.Background(), &{{ $eventShape.Shape.ShapeName }}{})
if err != nil {
if strings.Contains("unable to send event", err.Error()) {
t.Errorf("expected stream closed error, got %v", err)
}
break
}
}
}
func Test{{ $.Operation.ExportedName }}_ReadWrite(t *testing.T) {
expectedServiceEvents, serviceEvents := mock{{ $.Operation.ExportedName }}ReadEvents()
clientEvents, expectedClientEvents := mock{{ $.Operation.ExportedName }}WriteEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
&eventstreamtest.ServeEventStream{
T: t,
ClientEvents: expectedClientEvents,
Events: serviceEvents,
BiDirectional: true,
},
true)
defer cleanupFn()
svc := New(sess)
resp, err := svc.{{ $.Operation.ExportedName }}(nil)
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
stream := resp.GetStream()
defer stream.Close()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectedServiceEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
}()
for _, event := range clientEvents {
err = stream.Send(context.Background(), event)
if err != nil {
t.Errorf("expect no error, got %v", err)
}
}
resp.GetStream().Close()
wg.Wait()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func mock{{ $.Operation.ExportedName }}WriteEvents() (
[]{{ $.InputStream.Name }}Event,
[]eventstream.Message,
) {
inputEvents := []{{ $.InputStream.Name }}Event {
{{- if eq $.Operation.API.Metadata.Protocol "json" }}
{{- template "set event type" $.Operation.InputRef.Shape }}
{{- end }}
{{- range $_, $event := $.InputStream.Events }}
{{- template "set event type" $event.Shape }}
{{- end }}
}
var marshalers request.HandlerList
marshalers.PushBackNamed({{ $.API.ProtocolPackage }}.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{
{{- range $idx, $event := $.InputStream.Events }}
{{- template "set event message" Map "idx" $idx "parentShape" $event.Shape "eventName" $event.Name }}
{{- end }}
}
return inputEvents, eventMsgs
}
{{ end }}
{{/* Params: *Shape */}}
{{ define "set event type" }}
&{{ $.ShapeName }}{
{{- range $memName, $memRef := $.MemberRefs }}
{{- if not $memRef.Shape.IsEventStream }}
{{ $memName }}: {{ ValueForType $memRef.Shape nil }},
{{- end }}
{{- end }}
},
{{- end }}
{{/* Params: idx:int, parentShape:*Shape, eventName:string */}}
{{ define "set event message" }}
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{{- range $memName, $memRef := $.parentShape.MemberRefs }}
{{- template "set event message header" Map "idx" $.idx "parentShape" $.parentShape "memName" $memName "memRef" $memRef }}
{{- end }}
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("{{ $.eventName }}"),
},
},
{{- template "set event message payload" Map "idx" $.idx "parentShape" $.parentShape }}
},
{{- end }}
{{/* Params: idx:int, parentShape:*Shape, memName:string, memRef:*ShapeRef */}}
{{ define "set event message header" }}
{{- if (and ($.memRef.IsEventPayload) (eq $.memRef.Shape.Type "blob")) }}
{
Name: ":content-type",
Value: eventstream.StringValue("application/octet-stream"),
},
{{- else if $.memRef.IsEventHeader }}
{
Name: "{{ $.memName }}",
{{- $shapeValueVar := printf "inputEvents[%d].(%s).%s" $.idx $.parentShape.GoType $.memName }}
Value: {{ EventHeaderValueForType $.memRef.Shape $shapeValueVar }},
},
{{- end }}
{{- end }}
{{/* Params: idx:int, parentShape:*Shape, memName:string, memRef:*ShapeRef */}}
{{ define "set event message payload" }}
{{- $payloadMemName := $.parentShape.PayloadRefName }}
{{- if HasNonBlobPayloadMembers $.parentShape }}
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, inputEvents[{{ $.idx }}]),
{{- else if $payloadMemName }}
{{- $shapeType := (index $.parentShape.MemberRefs $payloadMemName).Shape.Type }}
{{- if eq $shapeType "blob" }}
Payload: inputEvents[{{ $.idx }}].({{ $.parentShape.GoType }}).{{ $payloadMemName }},
{{- else if eq $shapeType "string" }}
Payload: []byte(*inputEvents[{{ $.idx }}].({{ $.parentShape.GoType }}).{{ $payloadMemName }}),
{{- end }}
{{- end }}
{{- end }}
`))
| 280 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"text/template"
"github.com/aws/aws-sdk-go/private/util"
)
type Examples map[string][]Example
// ExamplesDefinition is the structural representation of the examples-1.json file
type ExamplesDefinition struct {
*API `json:"-"`
Examples Examples `json:"examples"`
}
// Example is a single entry within the examples-1.json file.
type Example struct {
API *API `json:"-"`
Operation *Operation `json:"-"`
OperationName string `json:"-"`
Index string `json:"-"`
Builder examplesBuilder `json:"-"`
VisitedErrors map[string]struct{} `json:"-"`
Title string `json:"title"`
Description string `json:"description"`
ID string `json:"id"`
Comments Comments `json:"comments"`
Input map[string]interface{} `json:"input"`
Output map[string]interface{} `json:"output"`
}
type Comments struct {
Input map[string]interface{} `json:"input"`
Output map[string]interface{} `json:"output"`
}
var exampleFuncMap = template.FuncMap{
"commentify": commentify,
"wrap": wrap,
"generateExampleInput": generateExampleInput,
"generateTypes": generateTypes,
}
var exampleCustomizations = map[string]template.FuncMap{}
var exampleTmpls = template.Must(template.New("example").Funcs(exampleFuncMap).Parse(`
{{ generateTypes . }}
{{ commentify (wrap .Title 80) }}
//
{{ commentify (wrap .Description 80) }}
func Example{{ .API.StructName }}_{{ .MethodName }}() {
svc := {{ .API.PackageName }}.New(session.New())
input := {{ generateExampleInput . }}
result, err := svc.{{ .OperationName }}(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
{{ range $_, $ref := .Operation.ErrorRefs -}}
{{ if not ($.HasVisitedError $ref) -}}
case {{ .API.PackageName }}.{{ $ref.Shape.ErrorCodeName }}:
fmt.Println({{ .API.PackageName }}.{{ $ref.Shape.ErrorCodeName }}, aerr.Error())
{{ end -}}
{{ end -}}
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
`))
// Names will return the name of the example. This will also be the name of the operation
// that is to be tested.
func (exs Examples) Names() []string {
names := make([]string, 0, len(exs))
for k := range exs {
names = append(names, k)
}
sort.Strings(names)
return names
}
func (exs Examples) GoCode() string {
buf := bytes.NewBuffer(nil)
for _, opName := range exs.Names() {
examples := exs[opName]
for _, ex := range examples {
buf.WriteString(util.GoFmt(ex.GoCode()))
buf.WriteString("\n")
}
}
return buf.String()
}
// ExampleCode will generate the example code for the given Example shape.
// TODO: Can delete
func (ex Example) GoCode() string {
var buf bytes.Buffer
m := exampleFuncMap
if fMap, ok := exampleCustomizations[ex.API.PackageName()]; ok {
m = fMap
}
tmpl := exampleTmpls.Funcs(m)
if err := tmpl.ExecuteTemplate(&buf, "example", &ex); err != nil {
panic(err)
}
return strings.TrimSpace(buf.String())
}
func generateExampleInput(ex Example) string {
if ex.Operation.HasInput() {
return fmt.Sprintf("&%s{\n%s\n}",
ex.Builder.GoType(&ex.Operation.InputRef, true),
ex.Builder.BuildShape(&ex.Operation.InputRef, ex.Input, false),
)
}
return ""
}
// generateTypes will generate no types for default examples, but customizations may
// require their own defined types.
func generateTypes(ex Example) string {
return ""
}
// correctType will cast the value to the correct type when printing the string.
// This is due to the json decoder choosing numbers to be floats, but the shape may
// actually be an int. To counter this, we pass the shape's type and properly do the
// casting here.
func correctType(memName string, t string, value interface{}) string {
if value == nil {
return ""
}
v := ""
switch value.(type) {
case string:
v = value.(string)
case int:
v = fmt.Sprintf("%d", value.(int))
case float64:
if t == "integer" || t == "long" || t == "int64" {
v = fmt.Sprintf("%d", int(value.(float64)))
} else {
v = fmt.Sprintf("%f", value.(float64))
}
case bool:
v = fmt.Sprintf("%t", value.(bool))
}
return convertToCorrectType(memName, t, v)
}
func convertToCorrectType(memName, t, v string) string {
return fmt.Sprintf("%s: %s,\n", memName, getValue(t, v))
}
func getValue(t, v string) string {
if t[0] == '*' {
t = t[1:]
}
switch t {
case "string":
return fmt.Sprintf("aws.String(%q)", v)
case "integer", "long", "int64":
return fmt.Sprintf("aws.Int64(%s)", v)
case "float", "float64", "double":
return fmt.Sprintf("aws.Float64(%s)", v)
case "boolean":
return fmt.Sprintf("aws.Bool(%s)", v)
default:
panic("Unsupported type: " + t)
}
}
// AttachExamples will create a new ExamplesDefinition from the examples file
// and reference the API object.
func (a *API) AttachExamples(filename string) error {
p := ExamplesDefinition{API: a}
f, err := os.Open(filename)
defer f.Close()
if err != nil {
return err
}
err = json.NewDecoder(f).Decode(&p)
if err != nil {
return fmt.Errorf("failed to decode %s, err: %v", filename, err)
}
return p.setup()
}
var examplesBuilderCustomizations = map[string]examplesBuilder{
"wafregional": NewWAFregionalExamplesBuilder(),
}
func (p *ExamplesDefinition) setup() error {
var builder examplesBuilder
ok := false
if builder, ok = examplesBuilderCustomizations[p.API.PackageName()]; !ok {
builder = NewExamplesBuilder()
}
keys := p.Examples.Names()
for _, n := range keys {
examples := p.Examples[n]
for i, e := range examples {
n = p.ExportableName(n)
e.OperationName = n
e.API = p.API
e.Index = fmt.Sprintf("shared%02d", i)
e.Builder = builder
e.VisitedErrors = map[string]struct{}{}
op := p.API.Operations[e.OperationName]
e.OperationName = p.ExportableName(e.OperationName)
e.Operation = op
p.Examples[n][i] = e
}
}
p.API.Examples = p.Examples
return nil
}
var exampleHeader = template.Must(template.New("exampleHeader").Parse(`
import (
{{ .Builder.Imports .API }}
)
var _ time.Duration
var _ strings.Reader
var _ aws.Config
func parseTime(layout, value string) *time.Time {
t, err := time.Parse(layout, value)
if err != nil {
panic(err)
}
return &t
}
`))
type exHeader struct {
Builder examplesBuilder
API *API
}
// ExamplesGoCode will return a code representation of the entry within the
// examples.json file.
func (a *API) ExamplesGoCode() string {
var buf bytes.Buffer
var builder examplesBuilder
ok := false
if builder, ok = examplesBuilderCustomizations[a.PackageName()]; !ok {
builder = NewExamplesBuilder()
}
if err := exampleHeader.ExecuteTemplate(&buf, "exampleHeader", &exHeader{builder, a}); err != nil {
panic(err)
}
code := a.Examples.GoCode()
if len(code) == 0 {
return ""
}
buf.WriteString(code)
return buf.String()
}
// TODO: In the operation docuentation where we list errors, this needs to be done
// there as well.
func (ex *Example) HasVisitedError(errRef *ShapeRef) bool {
errName := errRef.Shape.ErrorCodeName()
_, ok := ex.VisitedErrors[errName]
ex.VisitedErrors[errName] = struct{}{}
return ok
}
func (ex *Example) MethodName() string {
return fmt.Sprintf("%s_%s", ex.OperationName, ex.Index)
}
| 307 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"fmt"
"github.com/aws/aws-sdk-go/private/protocol"
)
type examplesBuilder interface {
BuildShape(*ShapeRef, map[string]interface{}, bool) string
BuildList(string, string, *ShapeRef, []interface{}) string
BuildComplex(string, string, *ShapeRef, *Shape, map[string]interface{}) string
GoType(*ShapeRef, bool) string
Imports(*API) string
}
type defaultExamplesBuilder struct {
ShapeValueBuilder
}
// NewExamplesBuilder returns an initialized example builder for generating
// example input API shapes from a model.
func NewExamplesBuilder() defaultExamplesBuilder {
b := defaultExamplesBuilder{
ShapeValueBuilder: NewShapeValueBuilder(),
}
b.ParseTimeString = parseExampleTimeString
return b
}
func (builder defaultExamplesBuilder) Imports(a *API) string {
return `"fmt"
"strings"
"time"
"` + SDKImportRoot + `/aws"
"` + SDKImportRoot + `/aws/awserr"
"` + SDKImportRoot + `/aws/session"
"` + a.ImportPath() + `"
`
}
// Returns a string which assigns the value of a time member by calling
// parseTime function defined in the file
func parseExampleTimeString(ref *ShapeRef, memName, v string) string {
if ref.Location == "header" {
return fmt.Sprintf("%s: parseTime(%q, %q),\n", memName, protocol.RFC822TimeFormat, v)
}
switch ref.API.Metadata.Protocol {
case "json", "rest-json", "rest-xml", "ec2", "query":
return fmt.Sprintf("%s: parseTime(%q, %q),\n", memName, protocol.ISO8601TimeFormat, v)
default:
panic("Unsupported time type: " + ref.API.Metadata.Protocol)
}
}
| 59 |
session-manager-plugin | aws | Go | // +build codegen
package api
type wafregionalExamplesBuilder struct {
defaultExamplesBuilder
}
func NewWAFregionalExamplesBuilder() wafregionalExamplesBuilder {
return wafregionalExamplesBuilder{defaultExamplesBuilder: NewExamplesBuilder()}
}
func (builder wafregionalExamplesBuilder) Imports(a *API) string {
return `"fmt"
"strings"
"time"
"` + SDKImportRoot + `/aws"
"` + SDKImportRoot + `/aws/awserr"
"` + SDKImportRoot + `/aws/session"
"` + SDKImportRoot + `/service/waf"
"` + SDKImportRoot + `/service/` + a.PackageName() + `"
`
}
| 24 |
session-manager-plugin | aws | Go | // +build go1.10,codegen
package api
import (
"encoding/json"
"testing"
)
func buildAPI() *API {
a := &API{}
stringShape := &Shape{
API: a,
ShapeName: "string",
Type: "string",
}
stringShapeRef := &ShapeRef{
API: a,
ShapeName: "string",
Shape: stringShape,
}
intShape := &Shape{
API: a,
ShapeName: "int",
Type: "int",
}
intShapeRef := &ShapeRef{
API: a,
ShapeName: "int",
Shape: intShape,
}
nestedComplexShape := &Shape{
API: a,
ShapeName: "NestedComplexShape",
MemberRefs: map[string]*ShapeRef{
"NestedField": stringShapeRef,
},
Type: "structure",
}
nestedComplexShapeRef := &ShapeRef{
API: a,
ShapeName: "NestedComplexShape",
Shape: nestedComplexShape,
}
nestedListShape := &Shape{
API: a,
ShapeName: "NestedListShape",
MemberRef: *nestedComplexShapeRef,
Type: "list",
}
nestedListShapeRef := &ShapeRef{
API: a,
ShapeName: "NestedListShape",
Shape: nestedListShape,
}
complexShape := &Shape{
API: a,
ShapeName: "ComplexShape",
MemberRefs: map[string]*ShapeRef{
"Field": stringShapeRef,
"List": nestedListShapeRef,
},
Type: "structure",
}
complexShapeRef := &ShapeRef{
API: a,
ShapeName: "ComplexShape",
Shape: complexShape,
}
listShape := &Shape{
API: a,
ShapeName: "ListShape",
MemberRef: *complexShapeRef,
Type: "list",
}
listShapeRef := &ShapeRef{
API: a,
ShapeName: "ListShape",
Shape: listShape,
}
listsShape := &Shape{
API: a,
ShapeName: "ListsShape",
MemberRef: *listShapeRef,
Type: "list",
}
listsShapeRef := &ShapeRef{
API: a,
ShapeName: "ListsShape",
Shape: listsShape,
}
input := &Shape{
API: a,
ShapeName: "FooInput",
MemberRefs: map[string]*ShapeRef{
"BarShape": stringShapeRef,
"ComplexField": complexShapeRef,
"ListField": listShapeRef,
"ListsField": listsShapeRef,
},
Type: "structure",
}
output := &Shape{
API: a,
ShapeName: "FooOutput",
MemberRefs: map[string]*ShapeRef{
"BazShape": intShapeRef,
"ComplexField": complexShapeRef,
"ListField": listShapeRef,
"ListsField": listsShapeRef,
},
Type: "structure",
}
inputRef := ShapeRef{
API: a,
ShapeName: "FooInput",
Shape: input,
}
outputRef := ShapeRef{
API: a,
ShapeName: "FooOutput",
Shape: output,
}
operations := map[string]*Operation{
"Foo": {
API: a,
Name: "Foo",
ExportedName: "Foo",
InputRef: inputRef,
OutputRef: outputRef,
},
}
a.Operations = operations
a.Shapes = map[string]*Shape{
"FooInput": input,
"FooOutput": output,
"string": stringShape,
"int": intShape,
"NestedComplexShape": nestedComplexShape,
"NestedListShape": nestedListShape,
"ComplexShape": complexShape,
"ListShape": listShape,
"ListsShape": listsShape,
}
a.Metadata = Metadata{
ServiceAbbreviation: "FooService",
}
a.BaseImportPath = "github.com/aws/aws-sdk-go/service/"
a.Setup()
return a
}
func TestExampleGeneration(t *testing.T) {
example := `
{
"version": "1.0",
"examples": {
"Foo": [
{
"input": {
"BarShape": "Hello world",
"ComplexField": {
"Field": "bar",
"List": [
{
"NestedField": "qux"
}
]
},
"ListField": [
{
"Field": "baz"
}
],
"ListsField": [
[
{
"Field": "baz"
}
]
]
},
"output": {
"BazShape": 1
},
"comments": {
"input": {
},
"output": {
}
},
"description": "Foo bar baz qux",
"title": "I pity the foo"
}
]
}
}
`
a := buildAPI()
def := &ExamplesDefinition{}
err := json.Unmarshal([]byte(example), def)
if err != nil {
t.Error(err)
}
def.API = a
def.setup()
expected := `
import (
"fmt"
"strings"
"time"
"` + SDKImportRoot + `/aws"
"` + SDKImportRoot + `/aws/awserr"
"` + SDKImportRoot + `/aws/session"
"` + SDKImportRoot + `/service/fooservice"
)
var _ time.Duration
var _ strings.Reader
var _ aws.Config
func parseTime(layout, value string) *time.Time {
t, err := time.Parse(layout, value)
if err != nil {
panic(err)
}
return &t
}
// I pity the foo
//
// Foo bar baz qux
func ExampleFooService_Foo_shared00() {
svc := fooservice.New(session.New())
input := &fooservice.FooInput{
BarShape: aws.String("Hello world"),
ComplexField: &fooservice.ComplexShape{
Field: aws.String("bar"),
List: []*fooservice.NestedComplexShape{
{
NestedField: aws.String("qux"),
},
},
},
ListField: []*fooservice.ComplexShape{
{
Field: aws.String("baz"),
},
},
ListsField: [][]*fooservice.ComplexShape{
{
{
Field: aws.String("baz"),
},
},
},
}
result, err := svc.Foo(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
`
if expected != a.ExamplesGoCode() {
t.Errorf("Expected:\n%s\nReceived:\n%s\n", expected, a.ExamplesGoCode())
}
}
func TestBuildShape(t *testing.T) {
a := buildAPI()
cases := []struct {
defs map[string]interface{}
expected string
}{
{
defs: map[string]interface{}{
"barShape": "Hello World",
},
expected: "BarShape: aws.String(\"Hello World\"),\n",
},
{
defs: map[string]interface{}{
"BarShape": "Hello World",
},
expected: "BarShape: aws.String(\"Hello World\"),\n",
},
}
for _, c := range cases {
ref := a.Operations["Foo"].InputRef
shapeStr := defaultExamplesBuilder{}.BuildShape(&ref, c.defs, false)
if c.expected != shapeStr {
t.Errorf("Expected:\n%s\nReceived:\n%s", c.expected, shapeStr)
}
}
}
| 331 |
session-manager-plugin | aws | Go | // +build codegen
package api
import "strings"
// ExportableName a name which is exportable as a value or name in Go code
func (a *API) ExportableName(name string) string {
if name == "" {
return name
}
return strings.ToUpper(name[0:1]) + name[1:]
}
| 15 |
session-manager-plugin | aws | Go | // +build codegen
package api
// IoSuffix represents map of service to shape names that
// are suffixed with `Input`, `Output` string and are not
// Input or Output shapes used by any operation within
// the service enclosure.
type IoSuffix map[string]map[string]struct{}
// LegacyIoSuffix returns if the shape names are legacy
// names that contain "Input" and "Output" name as suffix.
func (i IoSuffix) LegacyIOSuffix(a *API, shapeName string) bool {
names, ok := i[a.name]
if !ok {
return false
}
_, ok = names[shapeName]
return ok
}
// legacyIOSuffixed is the list of known shapes that have "Input" and "Output"
// as suffix in shape name, but are not the actual input, output shape
// for a corresponding service operation.
var legacyIOSuffixed = IoSuffix{
"TranscribeService": {
"RedactionOutput": struct{}{},
},
"Textract": {"HumanLoopActivationOutput": struct{}{}},
"Synthetics": {
"CanaryRunConfigInput": struct{}{},
"CanaryScheduleOutput": struct{}{},
"VpcConfigInput": struct{}{},
"VpcConfigOutput": struct{}{},
"CanaryCodeOutput": struct{}{},
"CanaryCodeInput": struct{}{},
"CanaryRunConfigOutput": struct{}{},
"CanaryScheduleInput": struct{}{},
},
"SWF": {"FunctionInput": struct{}{}},
"SFN": {
"InvalidOutput": struct{}{},
"InvalidExecutionInput": struct{}{},
"SensitiveDataJobInput": struct{}{},
},
"SSM": {
"CommandPluginOutput": struct{}{},
"MaintenanceWindowStepFunctionsInput": struct{}{},
"InvocationTraceOutput": struct{}{},
},
"SSMIncidents": {"RegionMapInput": struct{}{}},
"SMS": {
"AppValidationOutput": struct{}{},
"ServerValidationOutput": struct{}{},
"ValidationOutput": struct{}{},
"SSMOutput": struct{}{},
},
"ServiceDiscovery": {"InvalidInput": struct{}{}},
"ServiceCatalog": {
"RecordOutput": struct{}{},
"ProvisioningArtifactOutput": struct{}{},
},
"Schemas": {
"GetDiscoveredSchemaVersionItemInput": struct{}{},
"__listOfGetDiscoveredSchemaVersionItemInput": struct{}{},
},
"SageMaker": {
"ProcessingOutput": struct{}{},
"TaskInput": struct{}{},
"TransformOutput": struct{}{},
"ModelBiasJobInput": struct{}{},
"TransformInput": struct{}{},
"LabelingJobOutput": struct{}{},
"DataQualityJobInput": struct{}{},
"MonitoringOutput": struct{}{},
"MonitoringS3Output": struct{}{},
"MonitoringInput": struct{}{},
"ProcessingS3Output": struct{}{},
"ModelQualityJobInput": struct{}{},
"ProcessingInput": struct{}{},
"ProcessingFeatureStoreOutput": struct{}{},
"ModelExplainabilityJobInput": struct{}{},
"ProcessingS3Input": struct{}{},
"MonitoringGroundTruthS3Input": struct{}{},
"EdgePresetDeploymentOutput": struct{}{},
"EndpointInput": struct{}{},
},
"AugmentedAIRuntime": {"HumanLoopOutput": struct{}{}, "HumanLoopInput": struct{}{}},
"S3": {
"ParquetInput": struct{}{},
"CSVOutput": struct{}{},
"JSONOutput": struct{}{},
"JSONInput": struct{}{},
"CSVInput": struct{}{},
},
"Route53Domains": {"InvalidInput": struct{}{}},
"Route53": {"InvalidInput": struct{}{}},
"RoboMaker": {"S3KeyOutput": struct{}{}},
"Rekognition": {
"StreamProcessorInput": struct{}{},
"HumanLoopActivationOutput": struct{}{},
"StreamProcessorOutput": struct{}{},
},
"Proton": {"TemplateVersionSourceInput": struct{}{}, "CompatibleEnvironmentTemplateInput": struct{}{}},
"Personalize": {
"BatchInferenceJobInput": struct{}{},
"BatchInferenceJobOutput": struct{}{},
"DatasetExportJobOutput": struct{}{},
},
"MWAA": {
"ModuleLoggingConfigurationInput": struct{}{},
"LoggingConfigurationInput": struct{}{},
"UpdateNetworkConfigurationInput": struct{}{},
},
"MQ": {"LdapServerMetadataOutput": struct{}{}, "LdapServerMetadataInput": struct{}{}},
"MediaLive": {
"InputDeviceConfiguredInput": struct{}{},
"__listOfOutput": struct{}{},
"Input": struct{}{},
"__listOfInput": struct{}{},
"Output": struct{}{},
"InputDeviceActiveInput": struct{}{},
},
"MediaConvert": {
"Input": struct{}{},
"__listOfOutput": struct{}{},
"Output": struct{}{},
"__listOfInput": struct{}{},
},
"MediaConnect": {"Output": struct{}{}, "__listOfOutput": struct{}{}},
"Lambda": {
"LayerVersionContentOutput": struct{}{},
"LayerVersionContentInput": struct{}{},
},
"KinesisAnalyticsV2": {
"KinesisStreamsInput": struct{}{},
"KinesisFirehoseInput": struct{}{},
"LambdaOutput": struct{}{},
"Output": struct{}{},
"KinesisFirehoseOutput": struct{}{},
"Input": struct{}{},
"KinesisStreamsOutput": struct{}{},
},
"KinesisAnalytics": {
"Output": struct{}{},
"KinesisFirehoseInput": struct{}{},
"LambdaOutput": struct{}{},
"KinesisFirehoseOutput": struct{}{},
"KinesisStreamsInput": struct{}{},
"Input": struct{}{},
"KinesisStreamsOutput": struct{}{},
},
"IoTEvents": {"Input": struct{}{}},
"IoT": {"PutItemInput": struct{}{}},
"Honeycode": {"CellInput": struct{}{}, "RowDataInput": struct{}{}},
"Glue": {
"TableInput": struct{}{},
"UserDefinedFunctionInput": struct{}{},
"DatabaseInput": struct{}{},
"PartitionInput": struct{}{},
"ConnectionInput": struct{}{},
},
"Glacier": {
"CSVInput": struct{}{},
"CSVOutput": struct{}{},
"InventoryRetrievalJobInput": struct{}{},
},
"FIS": {
"CreateExperimentTemplateTargetInput": struct{}{},
"CreateExperimentTemplateStopConditionInput": struct{}{},
"UpdateExperimentTemplateStopConditionInput": struct{}{},
"CreateExperimentTemplateActionInput": struct{}{},
"UpdateExperimentTemplateTargetInput": struct{}{},
},
"Firehose": {"DeliveryStreamEncryptionConfigurationInput": struct{}{}},
"CloudWatchEvents": {"TransformerInput": struct{}{}, "TargetInput": struct{}{}},
"EventBridge": {"TransformerInput": struct{}{}, "TargetInput": struct{}{}},
"ElasticsearchService": {
"AutoTuneOptionsOutput": struct{}{},
"SAMLOptionsInput": struct{}{},
"AdvancedSecurityOptionsInput": struct{}{},
"SAMLOptionsOutput": struct{}{},
"AutoTuneOptionsInput": struct{}{},
},
"ElasticTranscoder": {
"JobOutput": struct{}{},
"CreateJobOutput": struct{}{},
"JobInput": struct{}{},
},
"ElastiCache": {
"UserGroupIdListInput": struct{}{},
"PasswordListInput": struct{}{},
"UserIdListInput": struct{}{},
},
"ECRPublic": {"RepositoryCatalogDataInput": struct{}{}},
"DeviceFarm": {"TestGridUrlExpiresInSecondsInput": struct{}{}},
"GlueDataBrew": {"Output": struct{}{}, "Input": struct{}{}, "OverwriteOutput": struct{}{}},
"CodePipeline": {"ActionExecutionInput": struct{}{}, "ActionExecutionOutput": struct{}{}},
"CodeBuild": {"ValueInput": struct{}{}, "KeyInput": struct{}{}},
"CloudFormation": {"Output": struct{}{}},
"Backup": {
"PlanInput": struct{}{},
"RulesInput": struct{}{},
"RuleInput": struct{}{},
},
"ApplicationInsights": {"StatesInput": struct{}{}},
"ApiGatewayV2": {
"TlsConfigInput": struct{}{},
"MutualTlsAuthenticationInput": struct{}{},
},
"APIGateway": {"MutualTlsAuthenticationInput": struct{}{}},
}
| 248 |
session-manager-plugin | aws | Go | package api
type stutterNames struct {
Operations map[string]string
Shapes map[string]string
ShapeOrder []string
}
var legacyStutterNames = map[string]stutterNames{
"WorkSpaces": {
Shapes: map[string]string{
"WorkspacesIpGroup": "IpGroup",
"WorkspacesIpGroupsList": "IpGroupsList",
},
},
"WorkMail": {
Shapes: map[string]string{
"WorkMailIdentifier": "Identifier",
},
},
"WAF": {
Shapes: map[string]string{
"WAFInvalidPermissionPolicyException": "InvalidPermissionPolicyException",
"WAFInvalidOperationException": "InvalidOperationException",
"WAFInternalErrorException": "InternalErrorException",
"WAFDisallowedNameException": "DisallowedNameException",
"WAFReferencedItemException": "ReferencedItemException",
"WAFInvalidParameterException": "InvalidParameterException",
"WAFLimitsExceededException": "LimitsExceededException",
"WAFNonexistentContainerException": "NonexistentContainerException",
"WAFInvalidAccountException": "InvalidAccountException",
"WAFSubscriptionNotFoundException": "SubscriptionNotFoundException",
"WAFBadRequestException": "BadRequestException",
"WAFNonexistentItemException": "NonexistentItemException",
"WAFServiceLinkedRoleErrorException": "ServiceLinkedRoleErrorException",
"WAFNonEmptyEntityException": "NonEmptyEntityException",
"WAFTagOperationInternalErrorException": "TagOperationInternalErrorException",
"WAFStaleDataException": "StaleDataException",
"WAFTagOperationException": "TagOperationException",
"WAFInvalidRegexPatternException": "InvalidRegexPatternException",
},
},
"Translate": {
Operations: map[string]string{
"TranslateText": "Text",
},
Shapes: map[string]string{
"TranslateTextRequest": "TextRequest",
"TranslateTextResponse": "TextResponse",
},
},
"Storage Gateway": {
Shapes: map[string]string{
"StorageGatewayError": "Error",
},
},
"Snowball": {
Shapes: map[string]string{
"SnowballType": "Type",
"SnowballCapacity": "Capacity",
},
},
"S3": {
Shapes: map[string]string{
"S3KeyFilter": "KeyFilter",
"S3Location": "Location",
},
},
"Rekognition": {
Shapes: map[string]string{
"RekognitionUniqueId": "UniqueId",
},
},
"QuickSight": {
Shapes: map[string]string{
"QuickSightUserNotFoundException": "UserNotFoundException",
},
},
"Marketplace Commerce Analytics": {
Shapes: map[string]string{
"MarketplaceCommerceAnalyticsException": "Exception",
},
},
"KMS": {
Shapes: map[string]string{
"KMSInternalException": "InternalException",
"KMSInvalidStateException": "InvalidStateException",
},
},
"Kinesis Analytics": {
Shapes: map[string]string{
"KinesisAnalyticsARN": "ARN",
},
},
"IoT Events": {
ShapeOrder: []string{
"Action",
"IotEventsAction",
},
Shapes: map[string]string{
"Action": "ActionData",
"IotEventsAction": "Action",
},
},
"Inspector": {
Shapes: map[string]string{
"InspectorServiceAttributes": "ServiceAttributes",
"InspectorEvent": "Event",
},
},
"GuardDuty": {
Shapes: map[string]string{
"GuardDutyArn": "Arn",
},
},
"GroundStation": {
Shapes: map[string]string{
"GroundStationList": "List",
"GroundStationData": "Data",
},
},
"Glue": {
ShapeOrder: []string{
"Table",
"GlueTable",
"GlueTables",
"GlueResourceArn",
"GlueEncryptionException",
},
Shapes: map[string]string{
"Table": "TableData",
"GlueTable": "Table",
"GlueTables": "Tables",
"GlueResourceArn": "ResourceArn",
"GlueEncryptionException": "EncryptionException",
},
},
"Glacier": {
Shapes: map[string]string{
"GlacierJobDescription": "JobDescription",
},
},
"Elastic Beanstalk": {
Shapes: map[string]string{
"ElasticBeanstalkServiceException": "ServiceException",
},
},
"Direct Connect": {
Shapes: map[string]string{
"DirectConnectClientException": "ClientException",
"DirectConnectGatewayAssociationProposalId": "GatewayAssociationProposalId",
"DirectConnectGatewayAssociationProposalState": "GatewayAssociationProposalState",
"DirectConnectGatewayAttachmentType": "GatewayAttachmentType",
"DirectConnectGatewayAttachmentList": "GatewayAttachmentList",
"DirectConnectGatewayAssociationProposalList": "GatewayAssociationProposalList",
"DirectConnectGatewayAssociationId": "GatewayAssociationId",
"DirectConnectGatewayList": "GatewayList",
"DirectConnectGatewayName": "GatewayName",
"DirectConnectGatewayAttachment": "GatewayAttachment",
"DirectConnectServerException": "ServerException",
"DirectConnectGatewayState": "GatewayState",
"DirectConnectGateway": "Gateway",
"DirectConnectGatewayId": "GatewayId",
"DirectConnectGatewayAttachmentState": "GatewayAttachmentState",
"DirectConnectGatewayAssociation": "GatewayAssociation",
"DirectConnectGatewayAssociationProposal": "GatewayAssociationProposal",
"DirectConnectGatewayAssociationState": "GatewayAssociationState",
"DirectConnectGatewayAssociationList": "GatewayAssociationList",
},
},
"Comprehend": {
Shapes: map[string]string{
"ComprehendArnName": "ArnName",
"ComprehendArn": "Arn",
},
},
"Cognito Identity": {
Shapes: map[string]string{
"CognitoIdentityProviderList": "ProviderList",
"CognitoIdentityProviderName": "ProviderName",
"CognitoIdentityProviderClientId": "ProviderClientId",
"CognitoIdentityProviderTokenCheck": "ProviderTokenCheck",
"CognitoIdentityProvider": "Provider",
},
},
"CloudTrail": {
Shapes: map[string]string{
"CloudTrailAccessNotEnabledException": "AccessNotEnabledException",
"CloudTrailARNInvalidException": "ARNInvalidException",
},
},
"CloudFront": {
Shapes: map[string]string{
"CloudFrontOriginAccessIdentitySummaryList": "OriginAccessIdentitySummaryList",
"CloudFrontOriginAccessIdentity": "OriginAccessIdentity",
"CloudFrontOriginAccessIdentityAlreadyExists": "OriginAccessIdentityAlreadyExists",
"CloudFrontOriginAccessIdentityConfig": "OriginAccessIdentityConfig",
"CloudFrontOriginAccessIdentitySummary": "OriginAccessIdentitySummary",
"CloudFrontOriginAccessIdentityList": "OriginAccessIdentityList",
"CloudFrontOriginAccessIdentityInUse": "OriginAccessIdentityInUse",
},
},
"Backup": {
Shapes: map[string]string{
"BackupPlan": "Plan",
"BackupRule": "Rule",
"BackupSelectionName": "SelectionName",
"BackupSelectionsList": "SelectionsList",
"BackupVaultEvents": "VaultEvents",
"BackupRuleName": "RuleName",
"BackupVaultName": "VaultName",
"BackupJob": "Job",
"BackupJobState": "JobState",
"BackupJobsList": "JobsList",
"BackupVaultEvent": "VaultEvent",
"BackupPlanVersionsList": "PlanVersionsList",
"BackupPlansListMember": "PlansListMember",
"BackupSelection": "Selection",
"BackupVaultList": "VaultList",
"BackupVaultListMember": "VaultListMember",
"BackupPlanInput": "PlanInput",
"BackupRules": "Rules",
"BackupPlansList": "PlansList",
"BackupPlanTemplatesList": "PlanTemplatesList",
"BackupRuleInput": "RuleInput",
"BackupPlanTemplatesListMember": "PlanTemplatesListMember",
"BackupRulesInput": "RulesInput",
"BackupSelectionsListMember": "SelectionsListMember",
"BackupPlanName": "PlanName",
},
},
"Auto Scaling": {
Shapes: map[string]string{
"AutoScalingGroupDesiredCapacity": "GroupDesiredCapacity",
"AutoScalingGroupNames": "GroupNames",
"AutoScalingGroupsType": "GroupsType",
"AutoScalingNotificationTypes": "NotificationTypes",
"AutoScalingGroupNamesType": "GroupNamesType",
"AutoScalingInstancesType": "InstancesType",
"AutoScalingInstanceDetails": "InstanceDetails",
"AutoScalingGroupMaxSize": "GroupMaxSize",
"AutoScalingGroups": "Groups",
"AutoScalingGroupMinSize": "GroupMinSize",
"AutoScalingGroup": "Group",
},
},
"AppStream": {
Shapes: map[string]string{
"AppstreamAgentVersion": "AgentVersion",
},
},
}
| 253 |
session-manager-plugin | aws | Go | package api
type persistAPIType struct {
output bool
input bool
}
type persistAPITypes map[string]map[string]persistAPIType
func (ts persistAPITypes) Lookup(serviceName, opName string) persistAPIType {
service, ok := shamelist[serviceName]
if !ok {
return persistAPIType{}
}
return service[opName]
}
func (ts persistAPITypes) Input(serviceName, opName string) bool {
return ts.Lookup(serviceName, opName).input
}
func (ts persistAPITypes) Output(serviceName, opName string) bool {
return ts.Lookup(serviceName, opName).output
}
// shamelist is used to not rename certain operation's input and output shapes.
// We need to maintain backwards compatibility with pre-existing services. Since
// not generating unique input/output shapes is not desired, we will generate
// unique input/output shapes for new operations.
var shamelist = persistAPITypes{
"APIGateway": {
"CreateApiKey": {
output: true,
},
"CreateAuthorizer": {
output: true,
},
"CreateBasePathMapping": {
output: true,
},
"CreateDeployment": {
output: true,
},
"CreateDocumentationPart": {
output: true,
},
"CreateDocumentationVersion": {
output: true,
},
"CreateDomainName": {
output: true,
},
"CreateModel": {
output: true,
},
"CreateResource": {
output: true,
},
"CreateRestApi": {
output: true,
},
"CreateStage": {
output: true,
},
"CreateUsagePlan": {
output: true,
},
"CreateUsagePlanKey": {
output: true,
},
"GenerateClientCertificate": {
output: true,
},
"GetAccount": {
output: true,
},
"GetApiKey": {
output: true,
},
"GetAuthorizer": {
output: true,
},
"GetBasePathMapping": {
output: true,
},
"GetClientCertificate": {
output: true,
},
"GetDeployment": {
output: true,
},
"GetDocumentationPart": {
output: true,
},
"GetDocumentationVersion": {
output: true,
},
"GetDomainName": {
output: true,
},
"GetIntegration": {
output: true,
},
"GetIntegrationResponse": {
output: true,
},
"GetMethod": {
output: true,
},
"GetMethodResponse": {
output: true,
},
"GetModel": {
output: true,
},
"GetResource": {
output: true,
},
"GetRestApi": {
output: true,
},
"GetSdkType": {
output: true,
},
"GetStage": {
output: true,
},
"GetUsage": {
output: true,
},
"GetUsagePlan": {
output: true,
},
"GetUsagePlanKey": {
output: true,
},
"ImportRestApi": {
output: true,
},
"PutIntegration": {
output: true,
},
"PutIntegrationResponse": {
output: true,
},
"PutMethod": {
output: true,
},
"PutMethodResponse": {
output: true,
},
"PutRestApi": {
output: true,
},
"UpdateAccount": {
output: true,
},
"UpdateApiKey": {
output: true,
},
"UpdateAuthorizer": {
output: true,
},
"UpdateBasePathMapping": {
output: true,
},
"UpdateClientCertificate": {
output: true,
},
"UpdateDeployment": {
output: true,
},
"UpdateDocumentationPart": {
output: true,
},
"UpdateDocumentationVersion": {
output: true,
},
"UpdateDomainName": {
output: true,
},
"UpdateIntegration": {
output: true,
},
"UpdateIntegrationResponse": {
output: true,
},
"UpdateMethod": {
output: true,
},
"UpdateMethodResponse": {
output: true,
},
"UpdateModel": {
output: true,
},
"UpdateResource": {
output: true,
},
"UpdateRestApi": {
output: true,
},
"UpdateStage": {
output: true,
},
"UpdateUsage": {
output: true,
},
"UpdateUsagePlan": {
output: true,
},
},
"AutoScaling": {
"ResumeProcesses": {
input: true,
},
"SuspendProcesses": {
input: true,
},
},
"CognitoIdentity": {
"CreateIdentityPool": {
output: true,
},
"DescribeIdentity": {
output: true,
},
"DescribeIdentityPool": {
output: true,
},
"UpdateIdentityPool": {
input: true,
output: true,
},
},
"DirectConnect": {
"AllocateConnectionOnInterconnect": {
output: true,
},
"AllocateHostedConnection": {
output: true,
},
"AllocatePrivateVirtualInterface": {
output: true,
},
"AllocatePublicVirtualInterface": {
output: true,
},
"AssociateConnectionWithLag": {
output: true,
},
"AssociateHostedConnection": {
output: true,
},
"AssociateVirtualInterface": {
output: true,
},
"CreateConnection": {
output: true,
},
"CreateInterconnect": {
output: true,
},
"CreateLag": {
output: true,
},
"CreatePrivateVirtualInterface": {
output: true,
},
"CreatePublicVirtualInterface": {
output: true,
},
"DeleteConnection": {
output: true,
},
"DeleteLag": {
output: true,
},
"DescribeConnections": {
output: true,
},
"DescribeConnectionsOnInterconnect": {
output: true,
},
"DescribeHostedConnections": {
output: true,
},
"DescribeLoa": {
output: true,
},
"DisassociateConnectionFromLag": {
output: true,
},
"UpdateLag": {
output: true,
},
},
"EC2": {
"AttachVolume": {
output: true,
},
"CreateSnapshot": {
output: true,
},
"CreateVolume": {
output: true,
},
"DetachVolume": {
output: true,
},
"RunInstances": {
output: true,
},
},
"EFS": {
"CreateFileSystem": {
output: true,
},
"CreateMountTarget": {
output: true,
},
},
"ElastiCache": {
"AddTagsToResource": {
output: true,
},
"ListTagsForResource": {
output: true,
},
"ModifyCacheParameterGroup": {
output: true,
},
"RemoveTagsFromResource": {
output: true,
},
"ResetCacheParameterGroup": {
output: true,
},
},
"ElasticBeanstalk": {
"ComposeEnvironments": {
output: true,
},
"CreateApplication": {
output: true,
},
"CreateApplicationVersion": {
output: true,
},
"CreateConfigurationTemplate": {
output: true,
},
"CreateEnvironment": {
output: true,
},
"DescribeEnvironments": {
output: true,
},
"TerminateEnvironment": {
output: true,
},
"UpdateApplication": {
output: true,
},
"UpdateApplicationVersion": {
output: true,
},
"UpdateConfigurationTemplate": {
output: true,
},
"UpdateEnvironment": {
output: true,
},
},
"ElasticTranscoder": {
"CreateJob": {
output: true,
},
},
"Glacier": {
"DescribeJob": {
output: true,
},
"UploadArchive": {
output: true,
},
"CompleteMultipartUpload": {
output: true,
},
},
"IAM": {
"GetContextKeysForCustomPolicy": {
output: true,
},
"GetContextKeysForPrincipalPolicy": {
output: true,
},
"SimulateCustomPolicy": {
output: true,
},
"SimulatePrincipalPolicy": {
output: true,
},
},
"Kinesis": {
"DisableEnhancedMonitoring": {
output: true,
},
"EnableEnhancedMonitoring": {
output: true,
},
},
"KMS": {
"ListGrants": {
output: true,
},
"ListRetirableGrants": {
output: true,
},
},
"Lambda": {
"CreateAlias": {
output: true,
},
"CreateEventSourceMapping": {
output: true,
},
"CreateFunction": {
output: true,
},
"DeleteEventSourceMapping": {
output: true,
},
"GetAlias": {
output: true,
},
"GetEventSourceMapping": {
output: true,
},
"GetFunctionConfiguration": {
output: true,
},
"PublishVersion": {
output: true,
},
"UpdateAlias": {
output: true,
},
"UpdateEventSourceMapping": {
output: true,
},
"UpdateFunctionCode": {
output: true,
},
"UpdateFunctionConfiguration": {
output: true,
},
},
"MQ": {
"CreateBroker": {
input: true,
output: true,
},
"CreateConfiguration": {
input: true,
output: true,
},
"CreateUser": {
input: true,
},
"DeleteBroker": {
output: true,
},
"DescribeBroker": {
output: true,
},
"DescribeUser": {
output: true,
},
"DescribeConfigurationRevision": {
output: true,
},
"ListBrokers": {
output: true,
},
"ListConfigurations": {
output: true,
},
"ListConfigurationRevisions": {
output: true,
},
"ListUsers": {
output: true,
},
"UpdateBroker": {
input: true,
output: true,
},
"UpdateConfiguration": {
input: true,
output: true,
},
"UpdateUser": {
input: true,
},
},
"RDS": {
"ModifyDBClusterParameterGroup": {
output: true,
},
"ModifyDBParameterGroup": {
output: true,
},
"ResetDBClusterParameterGroup": {
output: true,
},
"ResetDBParameterGroup": {
output: true,
},
},
"Redshift": {
"DescribeLoggingStatus": {
output: true,
},
"DisableLogging": {
output: true,
},
"EnableLogging": {
output: true,
},
"ModifyClusterParameterGroup": {
output: true,
},
"ResetClusterParameterGroup": {
output: true,
},
},
"S3": {
"GetBucketNotification": {
input: true,
output: true,
},
"GetBucketNotificationConfiguration": {
input: true,
output: true,
},
},
"ServerlessApplicationRepository": {
"CreateApplication": {
input: true,
},
"CreateApplicationVersion": {
input: true,
},
"CreateCloudFormationChangeSet": {
input: true,
},
"UpdateApplication": {
input: true,
},
},
"SWF": {
"CountClosedWorkflowExecutions": {
output: true,
},
"CountOpenWorkflowExecutions": {
output: true,
},
"CountPendingActivityTasks": {
output: true,
},
"CountPendingDecisionTasks": {
output: true,
},
"ListClosedWorkflowExecutions": {
output: true,
},
"ListOpenWorkflowExecutions": {
output: true,
},
},
}
| 584 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
)
// APIs provides a set of API models loaded by API package name.
type APIs map[string]*API
// Loader provides the loading of APIs from files.
type Loader struct {
// The base Go import path the loaded models will be appended to.
BaseImport string
// Allows ignoring API models that are unsupported by the SDK without
// failing the load of other supported APIs.
IgnoreUnsupportedAPIs bool
}
// Load loads the API model files from disk returning the map of API package.
// Returns error if multiple API model resolve to the same package name.
func (l Loader) Load(modelPaths []string) (APIs, error) {
apis := APIs{}
for _, modelPath := range modelPaths {
a, err := loadAPI(modelPath, l.BaseImport, func(a *API) {
a.IgnoreUnsupportedAPIs = l.IgnoreUnsupportedAPIs
})
if err != nil {
return nil, fmt.Errorf("failed to load API, %v, %v", modelPath, err)
}
if len(a.Operations) == 0 {
if l.IgnoreUnsupportedAPIs {
fmt.Fprintf(os.Stderr, "API has no operations, ignoring model %s, %v\n",
modelPath, a.ImportPath())
continue
}
}
importPath := a.ImportPath()
if _, ok := apis[importPath]; ok {
return nil, fmt.Errorf(
"package names must be unique attempted to load %v twice. Second model file: %v",
importPath, modelPath)
}
apis[importPath] = a
}
return apis, nil
}
// attempts to load a model from disk into the import specified. Additional API
// options are invoked before to the API's Setup being called.
func loadAPI(modelPath, baseImport string, opts ...func(*API)) (*API, error) {
a := &API{
BaseImportPath: baseImport,
BaseCrosslinkURL: "https://docs.aws.amazon.com",
}
modelFile := filepath.Base(modelPath)
modelDir := filepath.Dir(modelPath)
err := attachModelFiles(modelDir,
modelLoader{modelFile, a.Attach, true},
modelLoader{"docs-2.json", a.AttachDocs, false},
modelLoader{"paginators-1.json", a.AttachPaginators, false},
modelLoader{"waiters-2.json", a.AttachWaiters, false},
modelLoader{"examples-1.json", a.AttachExamples, false},
modelLoader{"smoke.json", a.AttachSmokeTests, false},
)
if err != nil {
return nil, err
}
for _, opt := range opts {
opt(a)
}
if err = a.Setup(); err != nil {
return nil, err
}
return a, nil
}
type modelLoader struct {
Filename string
Loader func(string) error
Required bool
}
func attachModelFiles(modelPath string, modelFiles ...modelLoader) error {
for _, m := range modelFiles {
filepath := filepath.Join(modelPath, m.Filename)
_, err := os.Stat(filepath)
if os.IsNotExist(err) && !m.Required {
continue
} else if err != nil {
return fmt.Errorf("failed to load model file %v, %v", m.Filename, err)
}
if err = m.Loader(filepath); err != nil {
return fmt.Errorf("model load failed, %s, %v", modelPath, err)
}
}
return nil
}
// ExpandModelGlobPath returns a slice of model paths expanded from the glob
// pattern passed in. Returns the path of the model file to be loaded. Includes
// all versions of a service model.
//
// e.g:
// models/apis/*/*/api-2.json
//
// Or with specific model file:
// models/apis/service/version/api-2.json
func ExpandModelGlobPath(globs ...string) ([]string, error) {
modelPaths := []string{}
for _, g := range globs {
filepaths, err := filepath.Glob(g)
if err != nil {
return nil, err
}
for _, p := range filepaths {
modelPaths = append(modelPaths, p)
}
}
return modelPaths, nil
}
// TrimModelServiceVersions sorts the model paths by service version then
// returns recent model versions, and model version excluded.
//
// Uses the third from last path element to determine unique service. Only one
// service version will be included.
//
// models/apis/service/version/api-2.json
func TrimModelServiceVersions(modelPaths []string) (include, exclude []string) {
sort.Strings(modelPaths)
// Remove old API versions from list
m := map[string]struct{}{}
for i := len(modelPaths) - 1; i >= 0; i-- {
// service name is 2nd-to-last component
parts := strings.Split(modelPaths[i], string(filepath.Separator))
svc := parts[len(parts)-3]
if _, ok := m[svc]; ok {
// Removed unused service version
exclude = append(exclude, modelPaths[i])
continue
}
include = append(include, modelPaths[i])
m[svc] = struct{}{}
}
return include, exclude
}
// Attach opens a file by name, and unmarshal its JSON data.
// Will proceed to setup the API if not already done so.
func (a *API) Attach(filename string) error {
a.path = filepath.Dir(filename)
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
if err := json.NewDecoder(f).Decode(a); err != nil {
return fmt.Errorf("failed to decode %s, err: %v", filename, err)
}
return nil
}
// AttachString will unmarshal a raw JSON string, and setup the
// API if not already done so.
func (a *API) AttachString(str string) error {
json.Unmarshal([]byte(str), a)
if a.initialized {
return nil
}
return a.Setup()
}
// Setup initializes the API.
func (a *API) Setup() error {
a.setServiceAliaseName()
a.setMetadataEndpointsKey()
a.writeShapeNames()
a.resolveReferences()
a.backfillErrorMembers()
if !a.NoRemoveUnusedShapes {
a.removeUnusedShapes()
}
a.fixStutterNames()
if err := a.validateShapeNames(); err != nil {
log.Fatalf(err.Error())
}
a.renameExportable()
a.applyShapeNameAliases()
a.renameIOSuffixedShapeNames()
a.createInputOutputShapes()
a.writeInputOutputLocationName()
a.renameAPIPayloadShapes()
a.renameCollidingFields()
a.updateTopLevelShapeReferences()
if err := a.setupEventStreams(); err != nil {
return err
}
a.findEndpointDiscoveryOp()
a.injectUnboundedOutputStreaming()
// Enables generated types for APIs using REST-JSON and JSONRPC protocols.
// Other protocols will be added as supported.
a.enableGeneratedTypedErrors()
if err := a.customizationPasses(); err != nil {
return err
}
a.addHeaderMapDocumentation()
if !a.NoRemoveUnusedShapes {
a.removeUnusedShapes()
}
if !a.NoValidataShapeMethods {
a.addShapeValidations()
}
a.initialized = true
return nil
}
// UnsupportedAPIModelError provides wrapping of an error causing the API to
// fail to load because the SDK does not support the API service defined.
type UnsupportedAPIModelError struct {
Err error
}
func (e UnsupportedAPIModelError) Error() string {
return fmt.Sprintf("service API is not supported, %v", e.Err)
}
| 263 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"path/filepath"
"reflect"
"strconv"
"testing"
)
func TestResolvedReferences(t *testing.T) {
json := `{
"operations": {
"OperationName": {
"input": { "shape": "TestName" }
}
},
"shapes": {
"TestName": {
"type": "structure",
"members": {
"memberName1": { "shape": "OtherTest" },
"memberName2": { "shape": "OtherTest" }
}
},
"OtherTest": { "type": "string" }
}
}`
a := API{}
a.AttachString(json)
if len(a.Shapes["OtherTest"].refs) != 2 {
t.Errorf("Expected %d, but received %d", 2, len(a.Shapes["OtherTest"].refs))
}
}
func TestTrimModelServiceVersions(t *testing.T) {
cases := []struct {
Paths []string
Include []string
Exclude []string
}{
{
Paths: []string{
filepath.Join("foo", "baz", "2018-01-02", "api-2.json"),
filepath.Join("foo", "baz", "2019-01-02", "api-2.json"),
filepath.Join("foo", "baz", "2017-01-02", "api-2.json"),
filepath.Join("foo", "bar", "2019-01-02", "api-2.json"),
filepath.Join("foo", "bar", "2013-04-02", "api-2.json"),
filepath.Join("foo", "bar", "2019-01-03", "api-2.json"),
},
Include: []string{
filepath.Join("foo", "baz", "2019-01-02", "api-2.json"),
filepath.Join("foo", "bar", "2019-01-03", "api-2.json"),
},
Exclude: []string{
filepath.Join("foo", "baz", "2018-01-02", "api-2.json"),
filepath.Join("foo", "baz", "2017-01-02", "api-2.json"),
filepath.Join("foo", "bar", "2019-01-02", "api-2.json"),
filepath.Join("foo", "bar", "2013-04-02", "api-2.json"),
},
},
}
for i, c := range cases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
include, exclude := TrimModelServiceVersions(c.Paths)
if e, a := c.Include, include; !reflect.DeepEqual(e, a) {
t.Errorf("expect include %v, got %v", e, a)
}
if e, a := c.Exclude, exclude; !reflect.DeepEqual(e, a) {
t.Errorf("expect exclude %v, got %v", e, a)
}
})
}
}
| 77 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"fmt"
"io"
"sync"
)
var debugLogger *logger
var initDebugLoggerOnce sync.Once
// logger provides a basic logging
type logger struct {
w io.Writer
}
// LogDebug initialize's the debug logger for the components in the api
// package to log debug lines to.
//
// Panics if called multiple times.
//
// Must be used prior to any model loading or code gen.
func LogDebug(w io.Writer) {
var initialized bool
initDebugLoggerOnce.Do(func() {
debugLogger = &logger{
w: w,
}
initialized = true
})
if !initialized && debugLogger != nil {
panic("LogDebug called multiple times. Can only be called once")
}
}
// Logf logs using the fmt printf pattern. Appends a new line to the end of the
// logged statement.
func (l *logger) Logf(format string, args ...interface{}) {
if l == nil {
return
}
fmt.Fprintf(l.w, format+"\n", args...)
}
// Logln logs using the fmt println pattern.
func (l *logger) Logln(args ...interface{}) {
if l == nil {
return
}
fmt.Fprintln(l.w, args...)
}
| 55 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"fmt"
"regexp"
"sort"
"strings"
"text/template"
)
// An Operation defines a specific API Operation.
type Operation struct {
API *API `json:"-"`
ExportedName string
Name string
Documentation string
HTTP HTTPInfo
Host string `json:"host"`
InputRef ShapeRef `json:"input"`
OutputRef ShapeRef `json:"output"`
ErrorRefs []ShapeRef `json:"errors"`
Paginator *Paginator
Deprecated bool `json:"deprecated"`
DeprecatedMsg string `json:"deprecatedMessage"`
AuthType AuthType `json:"authtype"`
imports map[string]bool
CustomBuildHandlers []string
EventStreamAPI *EventStreamAPI
IsEndpointDiscoveryOp bool `json:"endpointoperation"`
EndpointDiscovery *EndpointDiscovery `json:"endpointdiscovery"`
Endpoint *EndpointTrait `json:"endpoint"`
IsHttpChecksumRequired bool `json:"httpChecksumRequired"`
}
// EndpointTrait provides the structure of the modeled endpoint trait, and its
// properties.
type EndpointTrait struct {
// Specifies the hostPrefix template to prepend to the operation's request
// endpoint host.
HostPrefix string `json:"hostPrefix"`
}
// EndpointDiscovery represents a map of key values pairs that represents
// metadata about how a given API will make a call to the discovery endpoint.
type EndpointDiscovery struct {
// Required indicates that for a given operation that endpoint is required.
// Any required endpoint discovery operation cannot have endpoint discovery
// turned off.
Required bool `json:"required"`
}
// OperationForMethod returns the API operation name that corresponds to the
// client method name provided.
func (a *API) OperationForMethod(name string) *Operation {
for _, op := range a.Operations {
for _, m := range op.Methods() {
if m == name {
return op
}
}
}
return nil
}
// A HTTPInfo defines the method of HTTP request for the Operation.
type HTTPInfo struct {
Method string
RequestURI string
ResponseCode uint
}
// Methods Returns a list of method names that will be generated.
func (o *Operation) Methods() []string {
methods := []string{
o.ExportedName,
o.ExportedName + "Request",
o.ExportedName + "WithContext",
}
if o.Paginator != nil {
methods = append(methods, []string{
o.ExportedName + "Pages",
o.ExportedName + "PagesWithContext",
}...)
}
return methods
}
// HasInput returns if the Operation accepts an input parameter
func (o *Operation) HasInput() bool {
return o.InputRef.ShapeName != ""
}
// HasOutput returns if the Operation accepts an output parameter
func (o *Operation) HasOutput() bool {
return o.OutputRef.ShapeName != ""
}
// AuthType provides the enumeration of AuthType trait.
type AuthType string
// Enumeration values for AuthType trait
const (
NoneAuthType AuthType = "none"
V4UnsignedBodyAuthType AuthType = "v4-unsigned-body"
)
// ShouldSignRequestBody returns if the operation request body should be signed
// or not.
func (o *Operation) ShouldSignRequestBody() bool {
switch o.AuthType {
case NoneAuthType, V4UnsignedBodyAuthType:
return false
default:
return true
}
}
// GetSigner returns the signer that should be used for a API request.
func (o *Operation) GetSigner() string {
buf := bytes.NewBuffer(nil)
switch o.AuthType {
case NoneAuthType:
o.API.AddSDKImport("aws/credentials")
buf.WriteString("req.Config.Credentials = credentials.AnonymousCredentials")
case V4UnsignedBodyAuthType:
o.API.AddSDKImport("aws/signer/v4")
buf.WriteString("req.Handlers.Sign.Remove(v4.SignRequestHandler)\n")
buf.WriteString("handler := v4.BuildNamedHandler(\"v4.CustomSignerHandler\", v4.WithUnsignedPayload)\n")
buf.WriteString("req.Handlers.Sign.PushFrontNamed(handler)")
}
return buf.String()
}
// HasAccountIDMemberWithARN returns true if an account id member exists for an input shape that may take in an ARN.
func (o *Operation) HasAccountIDMemberWithARN() bool {
return o.InputRef.Shape.HasAccountIdMemberWithARN
}
// operationTmpl defines a template for rendering an API Operation
var operationTmpl = template.Must(template.New("operation").Funcs(template.FuncMap{
"EnableStopOnSameToken": enableStopOnSameToken,
"GetDeprecatedMsg": getDeprecatedMessage,
}).Parse(`
const op{{ .ExportedName }} = "{{ .Name }}"
// {{ .ExportedName }}Request generates a "aws/request.Request" representing the
// client's request for the {{ .ExportedName }} operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See {{ .ExportedName }} for more information on using the {{ .ExportedName }}
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the {{ .ExportedName }}Request method.
// req, resp := client.{{ .ExportedName }}Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
{{ $crosslinkURL := $.API.GetCrosslinkURL $.ExportedName -}}
{{ if ne $crosslinkURL "" -}}
//
// See also, {{ $crosslinkURL }}
{{ end -}}
{{- if .Deprecated }}//
// Deprecated: {{ GetDeprecatedMsg .DeprecatedMsg .ExportedName }}
{{ end -}}
func (c *{{ .API.StructName }}) {{ .ExportedName }}Request(` +
`input {{ .InputRef.GoType }}) (req *request.Request, output {{ .OutputRef.GoType }}) {
{{ if (or .Deprecated (or .InputRef.Deprecated .OutputRef.Deprecated)) }}if c.Client.Config.Logger != nil {
c.Client.Config.Logger.Log("This operation, {{ .ExportedName }}, has been deprecated")
}
op := &request.Operation{ {{ else }} op := &request.Operation{ {{ end }}
Name: op{{ .ExportedName }},
{{ if ne .HTTP.Method "" }}HTTPMethod: "{{ .HTTP.Method }}",
{{ end }}HTTPPath: {{ if ne .HTTP.RequestURI "" }}"{{ .HTTP.RequestURI }}"{{ else }}"/"{{ end }},
{{ if .Paginator }}Paginator: &request.Paginator{
InputTokens: {{ .Paginator.InputTokensString }},
OutputTokens: {{ .Paginator.OutputTokensString }},
LimitToken: "{{ .Paginator.LimitKey }}",
TruncationToken: "{{ .Paginator.MoreResults }}",
},
{{ end }}
}
if input == nil {
input = &{{ .InputRef.GoTypeElem }}{}
}
output = &{{ .OutputRef.GoTypeElem }}{}
req = c.newRequest(op, input, output)
{{- if ne .AuthType "" }}
{{ .GetSigner }}
{{- end }}
{{- if .HasAccountIDMemberWithARN }}
// update account id or check if provided input for account id member matches
// the account id present in ARN
req.Handlers.Validate.PushFrontNamed(updateAccountIDWithARNHandler)
{{- end }}
{{- if .ShouldDiscardResponse -}}
{{- $_ := .API.AddSDKImport "private/protocol" }}
{{- $_ := .API.AddSDKImport "private/protocol" .API.ProtocolPackage }}
req.Handlers.Unmarshal.Swap({{ .API.ProtocolPackage }}.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
{{- else }}
{{- if $.EventStreamAPI }}
{{- $esapi := $.EventStreamAPI }}
{{- if $esapi.RequireHTTP2 }}
req.Handlers.UnmarshalMeta.PushBack(
protocol.RequireHTTPMinProtocol{Major:2}.Handler,
)
{{- end }}
es := New{{ $esapi.Name }}()
{{- if $esapi.Legacy }}
req.Handlers.Unmarshal.PushBack(es.setStreamCloser)
{{- end }}
output.{{ $esapi.OutputMemberName }} = es
{{- $inputStream := $esapi.InputStream }}
{{- $outputStream := $esapi.OutputStream }}
{{- $_ := .API.AddSDKImport "private/protocol" .API.ProtocolPackage }}
{{- $_ := .API.AddSDKImport "private/protocol/rest" }}
{{- if $inputStream }}
req.Handlers.Sign.PushFront(es.setupInputPipe)
req.Handlers.UnmarshalError.PushBackNamed(request.NamedHandler{
Name: "InputPipeCloser",
Fn: func (r *request.Request) {
err := es.closeInputPipe()
if err != nil {
r.Error = awserr.New(eventstreamapi.InputWriterCloseErrorCode, err.Error(), r.Error)
}
},
})
req.Handlers.Build.PushBack(request.WithSetRequestHeaders(map[string]string{
"Content-Type": "application/vnd.amazon.eventstream",
"X-Amz-Content-Sha256": "STREAMING-AWS4-HMAC-SHA256-EVENTS",
}))
req.Handlers.Build.Swap({{ .API.ProtocolPackage }}.BuildHandler.Name, rest.BuildHandler)
req.Handlers.Send.Swap(client.LogHTTPRequestHandler.Name, client.LogHTTPRequestHeaderHandler)
req.Handlers.Unmarshal.PushBack(es.runInputStream)
{{- if eq .API.Metadata.Protocol "json" }}
es.input = input
req.Handlers.Unmarshal.PushBack(es.sendInitialEvent)
{{- end }}
{{- end }}
{{- if $outputStream }}
req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler)
req.Handlers.Unmarshal.Swap({{ .API.ProtocolPackage }}.UnmarshalHandler.Name, rest.UnmarshalHandler)
req.Handlers.Unmarshal.PushBack(es.runOutputStream)
{{- if eq .API.Metadata.Protocol "json" }}
es.output = output
req.Handlers.Unmarshal.PushBack(es.recvInitialEvent)
{{- end }}
{{- end }}
req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose)
{{- end }}
{{- end }}
{{- if .EndpointDiscovery }}
// if custom endpoint for the request is set to a non empty string,
// we skip the endpoint discovery workflow.
if req.Config.Endpoint == nil || *req.Config.Endpoint == "" {
{{- if not .EndpointDiscovery.Required }}
if aws.BoolValue(req.Config.EnableEndpointDiscovery) {
{{- end }}
de := discoverer{{ .API.EndpointDiscoveryOp.Name }}{
Required: {{ .EndpointDiscovery.Required }},
EndpointCache: c.endpointCache,
Params: map[string]*string{
"op": aws.String(req.Operation.Name),
{{- range $key, $ref := .InputRef.Shape.MemberRefs -}}
{{- if $ref.EndpointDiscoveryID -}}
{{- if ne (len $ref.LocationName) 0 -}}
"{{ $ref.LocationName }}": input.{{ $key }},
{{- else }}
"{{ $key }}": input.{{ $key }},
{{- end }}
{{- end }}
{{- end }}
},
Client: c,
}
for k, v := range de.Params {
if v == nil {
delete(de.Params, k)
}
}
req.Handlers.Build.PushFrontNamed(request.NamedHandler{
Name: "crr.endpointdiscovery",
Fn: de.Handler,
})
{{- if not .EndpointDiscovery.Required }}
}
{{- end }}
}
{{- end }}
{{- range $_, $handler := $.CustomBuildHandlers }}
req.Handlers.Build.PushBackNamed({{ $handler }})
{{- end }}
{{- if .IsHttpChecksumRequired }}
{{- $_ := .API.AddSDKImport "private/checksum" }}
req.Handlers.Build.PushBackNamed(request.NamedHandler{
Name: "contentMd5Handler",
Fn: checksum.AddBodyContentMD5Handler,
})
{{- end }}
return
}
// {{ .ExportedName }} API operation for {{ .API.Metadata.ServiceFullName }}.
{{- if .Documentation }}
//
{{ .Documentation }}
{{- end }}
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for {{ .API.Metadata.ServiceFullName }}'s
// API operation {{ .ExportedName }} for usage and error information.
{{- if .ErrorRefs }}
//
// Returned Error {{ if $.API.WithGeneratedTypedErrors }}Types{{ else }}Codes{{ end }}:
{{- range $_, $err := .ErrorRefs -}}
{{- if $.API.WithGeneratedTypedErrors }}
// * {{ $err.ShapeName }}
{{- else }}
// * {{ $err.Shape.ErrorCodeName }} "{{ $err.Shape.ErrorName}}"
{{- end }}
{{- if $err.Docstring }}
{{ $err.IndentedDocstring }}
{{- end }}
//
{{- end }}
{{- end }}
{{ $crosslinkURL := $.API.GetCrosslinkURL $.ExportedName -}}
{{ if ne $crosslinkURL "" -}}
// See also, {{ $crosslinkURL }}
{{ end -}}
{{- if .Deprecated }}//
// Deprecated: {{ GetDeprecatedMsg .DeprecatedMsg .ExportedName }}
{{ end -}}
func (c *{{ .API.StructName }}) {{ .ExportedName }}(` +
`input {{ .InputRef.GoType }}) ({{ .OutputRef.GoType }}, error) {
req, out := c.{{ .ExportedName }}Request(input)
return out, req.Send()
}
// {{ .ExportedName }}WithContext is the same as {{ .ExportedName }} with the addition of
// the ability to pass a context and additional request options.
//
// See {{ .ExportedName }} for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
{{ if .Deprecated }}//
// Deprecated: {{ GetDeprecatedMsg .DeprecatedMsg (printf "%s%s" .ExportedName "WithContext") }}
{{ end -}}
func (c *{{ .API.StructName }}) {{ .ExportedName }}WithContext(` +
`ctx aws.Context, input {{ .InputRef.GoType }}, opts ...request.Option) ` +
`({{ .OutputRef.GoType }}, error) {
req, out := c.{{ .ExportedName }}Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
{{ if .Paginator }}
// {{ .ExportedName }}Pages iterates over the pages of a {{ .ExportedName }} operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See {{ .ExportedName }} method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a {{ .ExportedName }} operation.
// pageNum := 0
// err := client.{{ .ExportedName }}Pages(params,
// func(page {{ .OutputRef.Shape.GoTypeWithPkgName }}, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
{{ if .Deprecated }}//
// Deprecated: {{ GetDeprecatedMsg .DeprecatedMsg (printf "%s%s" .ExportedName "Pages") }}
{{ end -}}
func (c *{{ .API.StructName }}) {{ .ExportedName }}Pages(` +
`input {{ .InputRef.GoType }}, fn func({{ .OutputRef.GoType }}, bool) bool) error {
return c.{{ .ExportedName }}PagesWithContext(aws.BackgroundContext(), input, fn)
}
// {{ .ExportedName }}PagesWithContext same as {{ .ExportedName }}Pages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
{{ if .Deprecated }}//
// Deprecated: {{ GetDeprecatedMsg .DeprecatedMsg (printf "%s%s" .ExportedName "PagesWithContext") }}
{{ end -}}
func (c *{{ .API.StructName }}) {{ .ExportedName }}PagesWithContext(` +
`ctx aws.Context, ` +
`input {{ .InputRef.GoType }}, ` +
`fn func({{ .OutputRef.GoType }}, bool) bool, ` +
`opts ...request.Option) error {
p := request.Pagination {
{{ if EnableStopOnSameToken .API.PackageName -}}EndPageOnSameToken: true,
{{ end -}}
NewRequest: func() (*request.Request, error) {
var inCpy {{ .InputRef.GoType }}
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.{{ .ExportedName }}Request(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().({{ .OutputRef.GoType }}), !p.HasNextPage()) {
break
}
}
return p.Err()
}
{{ end }}
{{- if .IsEndpointDiscoveryOp }}
type discoverer{{ .ExportedName }} struct {
Client *{{ .API.StructName }}
Required bool
EndpointCache *crr.EndpointCache
Params map[string]*string
Key string
req *request.Request
}
func (d *discoverer{{ .ExportedName }}) Discover() (crr.Endpoint, error) {
input := &{{ .API.EndpointDiscoveryOp.InputRef.ShapeName }}{
{{ if .API.EndpointDiscoveryOp.InputRef.Shape.HasMember "Operation" -}}
Operation: d.Params["op"],
{{ end -}}
{{ if .API.EndpointDiscoveryOp.InputRef.Shape.HasMember "Identifiers" -}}
Identifiers: d.Params,
{{ end -}}
}
resp, err := d.Client.{{ .API.EndpointDiscoveryOp.Name }}(input)
if err != nil {
return crr.Endpoint{}, err
}
endpoint := crr.Endpoint{
Key: d.Key,
}
for _, e := range resp.Endpoints {
if e.Address == nil {
continue
}
address := *e.Address
var scheme string
if idx := strings.Index(address, "://"); idx != -1 {
scheme = address[:idx]
}
if len(scheme) == 0 {
address = fmt.Sprintf("%s://%s", d.req.HTTPRequest.URL.Scheme, address)
}
cachedInMinutes := aws.Int64Value(e.CachePeriodInMinutes)
u, err := url.Parse(address)
if err != nil {
continue
}
addr := crr.WeightedAddress{
URL: u,
Expired: time.Now().Add(time.Duration(cachedInMinutes) * time.Minute),
}
endpoint.Add(addr)
}
d.EndpointCache.Add(endpoint)
return endpoint, nil
}
func (d *discoverer{{ .ExportedName }}) Handler(r *request.Request) {
endpointKey := crr.BuildEndpointKey(d.Params)
d.Key = endpointKey
d.req = r
endpoint, err := d.EndpointCache.Get(d, endpointKey, d.Required)
if err != nil {
r.Error = err
return
}
if endpoint.URL != nil && len(endpoint.URL.String()) > 0 {
r.HTTPRequest.URL = endpoint.URL
}
}
{{- end }}
`))
// GoCode returns a string of rendered GoCode for this Operation
func (o *Operation) GoCode() string {
var buf bytes.Buffer
if o.API.EndpointDiscoveryOp != nil {
o.API.AddSDKImport("aws/crr")
o.API.AddImport("time")
o.API.AddImport("net/url")
o.API.AddImport("fmt")
o.API.AddImport("strings")
}
if o.Endpoint != nil && len(o.Endpoint.HostPrefix) != 0 {
setupEndpointHostPrefix(o)
}
if err := operationTmpl.Execute(&buf, o); err != nil {
panic(fmt.Sprintf("failed to render operation, %v, %v", o.ExportedName, err))
}
if o.EventStreamAPI != nil {
o.API.AddSDKImport("aws/client")
o.API.AddSDKImport("private/protocol")
o.API.AddSDKImport("private/protocol/rest")
o.API.AddSDKImport("private/protocol", o.API.ProtocolPackage())
if err := renderEventStreamAPI(&buf, o); err != nil {
panic(fmt.Sprintf("failed to render EventStreamAPI for %v, %v", o.ExportedName, err))
}
}
return strings.TrimSpace(buf.String())
}
// tplInfSig defines the template for rendering an Operation's signature within an Interface definition.
var tplInfSig = template.Must(template.New("opsig").Parse(`
{{ .ExportedName }}({{ .InputRef.GoTypeWithPkgName }}) ({{ .OutputRef.GoTypeWithPkgName }}, error)
{{ .ExportedName }}WithContext(aws.Context, {{ .InputRef.GoTypeWithPkgName }}, ...request.Option) ({{ .OutputRef.GoTypeWithPkgName }}, error)
{{ .ExportedName }}Request({{ .InputRef.GoTypeWithPkgName }}) (*request.Request, {{ .OutputRef.GoTypeWithPkgName }})
{{ if .Paginator -}}
{{ .ExportedName }}Pages({{ .InputRef.GoTypeWithPkgName }}, func({{ .OutputRef.GoTypeWithPkgName }}, bool) bool) error
{{ .ExportedName }}PagesWithContext(aws.Context, {{ .InputRef.GoTypeWithPkgName }}, func({{ .OutputRef.GoTypeWithPkgName }}, bool) bool, ...request.Option) error
{{- end }}
`))
// InterfaceSignature returns a string representing the Operation's interface{}
// functional signature.
func (o *Operation) InterfaceSignature() string {
var buf bytes.Buffer
err := tplInfSig.Execute(&buf, o)
if err != nil {
panic(err)
}
return strings.TrimSpace(buf.String())
}
// tplExample defines the template for rendering an Operation example
var tplExample = template.Must(template.New("operationExample").Parse(`
func Example{{ .API.StructName }}_{{ .ExportedName }}() {
sess := session.Must(session.NewSession())
svc := {{ .API.PackageName }}.New(sess)
{{ .ExampleInput }}
resp, err := svc.{{ .ExportedName }}(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
`))
// Example returns a string of the rendered Go code for the Operation
func (o *Operation) Example() string {
var buf bytes.Buffer
err := tplExample.Execute(&buf, o)
if err != nil {
panic(err)
}
return strings.TrimSpace(buf.String())
}
// ExampleInput return a string of the rendered Go code for an example's input parameters
func (o *Operation) ExampleInput() string {
if len(o.InputRef.Shape.MemberRefs) == 0 {
if strings.Contains(o.InputRef.GoTypeElem(), ".") {
o.imports[SDKImportRoot+"service/"+strings.Split(o.InputRef.GoTypeElem(), ".")[0]] = true
return fmt.Sprintf("var params *%s", o.InputRef.GoTypeElem())
}
return fmt.Sprintf("var params *%s.%s",
o.API.PackageName(), o.InputRef.GoTypeElem())
}
e := example{o, map[string]int{}}
return "params := " + e.traverseAny(o.InputRef.Shape, false, false)
}
// ShouldDiscardResponse returns if the operation should discard the response
// returned by the service.
func (o *Operation) ShouldDiscardResponse() bool {
s := o.OutputRef.Shape
return s.Placeholder || len(s.MemberRefs) == 0
}
// A example provides
type example struct {
*Operation
visited map[string]int
}
// traverseAny returns rendered Go code for the shape.
func (e *example) traverseAny(s *Shape, required, payload bool) string {
str := ""
e.visited[s.ShapeName]++
switch s.Type {
case "structure":
str = e.traverseStruct(s, required, payload)
case "list":
str = e.traverseList(s, required, payload)
case "map":
str = e.traverseMap(s, required, payload)
case "jsonvalue":
str = "aws.JSONValue{\"key\": \"value\"}"
if required {
str += " // Required"
}
default:
str = e.traverseScalar(s, required, payload)
}
e.visited[s.ShapeName]--
return str
}
var reType = regexp.MustCompile(`\b([A-Z])`)
// traverseStruct returns rendered Go code for a structure type shape.
func (e *example) traverseStruct(s *Shape, required, payload bool) string {
var buf bytes.Buffer
if s.resolvePkg != "" {
e.imports[s.resolvePkg] = true
buf.WriteString("&" + s.GoTypeElem() + "{")
} else {
buf.WriteString("&" + s.API.PackageName() + "." + s.GoTypeElem() + "{")
}
if required {
buf.WriteString(" // Required")
}
buf.WriteString("\n")
req := make([]string, len(s.Required))
copy(req, s.Required)
sort.Strings(req)
if e.visited[s.ShapeName] < 2 {
for _, n := range req {
m := s.MemberRefs[n].Shape
p := n == s.Payload && (s.MemberRefs[n].Streaming || m.Streaming)
buf.WriteString(n + ": " + e.traverseAny(m, true, p) + ",")
if m.Type != "list" && m.Type != "structure" && m.Type != "map" {
buf.WriteString(" // Required")
}
buf.WriteString("\n")
}
for _, n := range s.MemberNames() {
if s.IsRequired(n) {
continue
}
m := s.MemberRefs[n].Shape
p := n == s.Payload && (s.MemberRefs[n].Streaming || m.Streaming)
buf.WriteString(n + ": " + e.traverseAny(m, false, p) + ",\n")
}
} else {
buf.WriteString("// Recursive values...\n")
}
buf.WriteString("}")
return buf.String()
}
// traverseMap returns rendered Go code for a map type shape.
func (e *example) traverseMap(s *Shape, required, payload bool) string {
var buf bytes.Buffer
t := ""
if s.resolvePkg != "" {
e.imports[s.resolvePkg] = true
t = s.GoTypeElem()
} else {
t = reType.ReplaceAllString(s.GoTypeElem(), s.API.PackageName()+".$1")
}
buf.WriteString(t + "{")
if required {
buf.WriteString(" // Required")
}
buf.WriteString("\n")
if e.visited[s.ShapeName] < 2 {
m := s.ValueRef.Shape
buf.WriteString("\"Key\": " + e.traverseAny(m, true, false) + ",")
if m.Type != "list" && m.Type != "structure" && m.Type != "map" {
buf.WriteString(" // Required")
}
buf.WriteString("\n// More values...\n")
} else {
buf.WriteString("// Recursive values...\n")
}
buf.WriteString("}")
return buf.String()
}
// traverseList returns rendered Go code for a list type shape.
func (e *example) traverseList(s *Shape, required, payload bool) string {
var buf bytes.Buffer
t := ""
if s.resolvePkg != "" {
e.imports[s.resolvePkg] = true
t = s.GoTypeElem()
} else {
t = reType.ReplaceAllString(s.GoTypeElem(), s.API.PackageName()+".$1")
}
buf.WriteString(t + "{")
if required {
buf.WriteString(" // Required")
}
buf.WriteString("\n")
if e.visited[s.ShapeName] < 2 {
m := s.MemberRef.Shape
buf.WriteString(e.traverseAny(m, true, false) + ",")
if m.Type != "list" && m.Type != "structure" && m.Type != "map" {
buf.WriteString(" // Required")
}
buf.WriteString("\n// More values...\n")
} else {
buf.WriteString("// Recursive values...\n")
}
buf.WriteString("}")
return buf.String()
}
// traverseScalar returns an AWS Type string representation initialized to a value.
// Will panic if s is an unsupported shape type.
func (e *example) traverseScalar(s *Shape, required, payload bool) string {
str := ""
switch s.Type {
case "integer", "long":
str = `aws.Int64(1)`
case "float", "double":
str = `aws.Float64(1.0)`
case "string", "character":
str = `aws.String("` + s.ShapeName + `")`
case "blob":
if payload {
str = `bytes.NewReader([]byte("PAYLOAD"))`
} else {
str = `[]byte("PAYLOAD")`
}
case "boolean":
str = `aws.Bool(true)`
case "timestamp":
str = `aws.Time(time.Now())`
default:
panic("unsupported shape " + s.Type)
}
return str
}
| 838 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"encoding/json"
"fmt"
"os"
)
// Paginator keeps track of pagination configuration for an API operation.
type Paginator struct {
InputTokens interface{} `json:"input_token"`
OutputTokens interface{} `json:"output_token"`
LimitKey string `json:"limit_key"`
MoreResults string `json:"more_results"`
}
// InputTokensString returns output tokens formatted as a list
func (p *Paginator) InputTokensString() string {
str := p.InputTokens.([]string)
return fmt.Sprintf("%#v", str)
}
// OutputTokensString returns output tokens formatted as a list
func (p *Paginator) OutputTokensString() string {
str := p.OutputTokens.([]string)
return fmt.Sprintf("%#v", str)
}
// used for unmarshaling from the paginators JSON file
type paginationDefinitions struct {
*API
Pagination map[string]Paginator
}
// AttachPaginators attaches pagination configuration from filename to the API.
func (a *API) AttachPaginators(filename string) error {
p := paginationDefinitions{API: a}
f, err := os.Open(filename)
defer f.Close()
if err != nil {
return err
}
err = json.NewDecoder(f).Decode(&p)
if err != nil {
return fmt.Errorf("failed to decode %s, err: %v", filename, err)
}
return p.setup()
}
// setup runs post-processing on the paginator configuration.
func (p *paginationDefinitions) setup() error {
for n, e := range p.Pagination {
if e.InputTokens == nil || e.OutputTokens == nil {
continue
}
paginator := e
switch t := paginator.InputTokens.(type) {
case string:
paginator.InputTokens = []string{t}
case []interface{}:
toks := []string{}
for _, e := range t {
s := e.(string)
toks = append(toks, s)
}
paginator.InputTokens = toks
}
switch t := paginator.OutputTokens.(type) {
case string:
paginator.OutputTokens = []string{t}
case []interface{}:
toks := []string{}
for _, e := range t {
s := e.(string)
toks = append(toks, s)
}
paginator.OutputTokens = toks
}
if o, ok := p.Operations[n]; ok {
o.Paginator = &paginator
} else {
return fmt.Errorf("unknown operation for paginator, %s", n)
}
}
return nil
}
func enableStopOnSameToken(service string) bool {
switch service {
case "cloudwatchlogs":
return true
default:
return false
}
}
| 103 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/aws/aws-sdk-go/private/util"
)
// A paramFiller provides string formatting for a shape and its types.
type paramFiller struct {
prefixPackageName bool
}
// typeName returns the type name of a shape.
func (f paramFiller) typeName(shape *Shape) string {
if f.prefixPackageName && shape.Type == "structure" {
return "*" + shape.API.PackageName() + "." + shape.GoTypeElem()
}
return shape.GoType()
}
// ParamsStructFromJSON returns a JSON string representation of a structure.
func ParamsStructFromJSON(value interface{}, shape *Shape, prefixPackageName bool) string {
f := paramFiller{prefixPackageName: prefixPackageName}
return util.GoFmt(f.paramsStructAny(value, shape))
}
// paramsStructAny returns the string representation of any value.
func (f paramFiller) paramsStructAny(value interface{}, shape *Shape) string {
if value == nil {
return ""
}
switch shape.Type {
case "structure":
if value != nil {
vmap := value.(map[string]interface{})
return f.paramsStructStruct(vmap, shape)
}
case "list":
vlist := value.([]interface{})
return f.paramsStructList(vlist, shape)
case "map":
vmap := value.(map[string]interface{})
return f.paramsStructMap(vmap, shape)
case "string", "character":
v := reflect.Indirect(reflect.ValueOf(value))
if v.IsValid() {
return fmt.Sprintf("aws.String(%#v)", v.Interface())
}
case "blob":
v := reflect.Indirect(reflect.ValueOf(value))
if v.IsValid() && shape.Streaming {
return fmt.Sprintf("bytes.NewReader([]byte(%#v))", v.Interface())
} else if v.IsValid() {
return fmt.Sprintf("[]byte(%#v)", v.Interface())
}
case "boolean":
v := reflect.Indirect(reflect.ValueOf(value))
if v.IsValid() {
return fmt.Sprintf("aws.Bool(%#v)", v.Interface())
}
case "integer", "long":
v := reflect.Indirect(reflect.ValueOf(value))
if v.IsValid() {
return fmt.Sprintf("aws.Int64(%v)", v.Interface())
}
case "float", "double":
v := reflect.Indirect(reflect.ValueOf(value))
if v.IsValid() {
return fmt.Sprintf("aws.Float64(%v)", v.Interface())
}
case "timestamp":
v := reflect.Indirect(reflect.ValueOf(value))
if v.IsValid() {
return fmt.Sprintf("aws.Time(time.Unix(%d, 0))", int(v.Float()))
}
case "jsonvalue":
v, err := json.Marshal(value)
if err != nil {
panic("failed to marshal JSONValue, " + err.Error())
}
const tmpl = `func() aws.JSONValue {
var m aws.JSONValue
if err := json.Unmarshal([]byte(%q), &m); err != nil {
panic("failed to unmarshal JSONValue, "+err.Error())
}
return m
}()`
return fmt.Sprintf(tmpl, string(v))
default:
panic("Unhandled type " + shape.Type)
}
return ""
}
// paramsStructStruct returns the string representation of a structure
func (f paramFiller) paramsStructStruct(value map[string]interface{}, shape *Shape) string {
out := "&" + f.typeName(shape)[1:] + "{\n"
for _, n := range shape.MemberNames() {
ref := shape.MemberRefs[n]
name := findParamMember(value, n)
if val := f.paramsStructAny(value[name], ref.Shape); val != "" {
out += fmt.Sprintf("%s: %s,\n", n, val)
}
}
out += "}"
return out
}
// paramsStructMap returns the string representation of a map of values
func (f paramFiller) paramsStructMap(value map[string]interface{}, shape *Shape) string {
out := f.typeName(shape) + "{\n"
keys := util.SortedKeys(value)
for _, k := range keys {
v := value[k]
out += fmt.Sprintf("%q: %s,\n", k, f.paramsStructAny(v, shape.ValueRef.Shape))
}
out += "}"
return out
}
// paramsStructList returns the string representation of slice of values
func (f paramFiller) paramsStructList(value []interface{}, shape *Shape) string {
out := f.typeName(shape) + "{\n"
for _, v := range value {
out += fmt.Sprintf("%s,\n", f.paramsStructAny(v, shape.MemberRef.Shape))
}
out += "}"
return out
}
// findParamMember searches a map for a key ignoring case. Returns the map key if found.
func findParamMember(value map[string]interface{}, key string) string {
for actualKey := range value {
if strings.EqualFold(key, actualKey) {
return actualKey
}
}
return ""
}
| 148 |
Subsets and Splits