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
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package diff import ( "os" "testing" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) func TestIntrinsicFuncConverters(t *testing.T) { testCases := map[string]struct { curr string old string wanted func() diffNode }{ "no diff in Ref vs !Ref": { old: `Value: !Sub 'blah'`, curr: `Value: Fn::Sub: 'blah'`, }, "detect diff in Ref and !Ref": { old: ` hummingbird: Ref: pineapple1`, curr: `hummingbird: !Ref pineapple2`, wanted: func() diffNode { leaf := &keyNode{ keyValue: "Ref", oldV: yamlScalarNode("pineapple1"), newV: yamlScalarNode("pineapple2"), } return &keyNode{ childNodes: []diffNode{&keyNode{ keyValue: "hummingbird", childNodes: []diffNode{leaf}, }}, } }, }, "no diff in Fn::Base64 vs !Base64": { old: `Value: Fn::Base64: "AWS CloudFormation"`, curr: `Value: !Base64 AWS CloudFormation`, }, "detect diff in Fn::Base64 amd !Base64": { old: `Basement: Fn::Base64: 1`, curr: `Basement: !Base64 2`, wanted: func() diffNode { leaf := &keyNode{ keyValue: "Fn::Base64", oldV: yamlScalarNode("1"), newV: yamlScalarNode("2"), } return &keyNode{ childNodes: []diffNode{&keyNode{ keyValue: "Basement", childNodes: []diffNode{leaf}, }}, } }, }, "no diff in Fn::Cidr vs !Cidr": { old: `CidrBlock: Fn::Cidr: - 192.168.0.0/24 - 6 - 5`, curr: `CidrBlock: !Cidr ["192.168.0.0/24", 6, 5 ]`, }, "detect diff in Fn::Cidr vs !Cidr": { old: `cedar: !Cidr ["192.168.0.0/16", 6, 4 ]`, curr: `cedar: Fn::Cidr: - 192.168.0.0/24 - 6 - 5`, wanted: func() diffNode { changedCIDR := &seqItemNode{ keyNode: keyNode{ oldV: yamlScalarNode("192.168.0.0/16", withStyle(yaml.DoubleQuotedStyle)), newV: yamlScalarNode("192.168.0.0/24"), }, } unchanged := &unchangedNode{count: 1} changedNum := &seqItemNode{ keyNode: keyNode{ oldV: yamlScalarNode("4"), newV: yamlScalarNode("5"), }, } return &keyNode{ childNodes: []diffNode{&keyNode{ keyValue: "cedar", childNodes: []diffNode{&keyNode{ keyValue: "Fn::Cidr", childNodes: []diffNode{changedCIDR, unchanged, changedNum}, }}, }}, } }, }, "no diff in Fn::FindInMap vs !FindInMap": { old: ` ImageId: Fn::FindInMap: - RegionMap - !Ref 'AWS::Region' - HVM64`, curr: ` ImageId: !FindInMap - RegionMap - !Ref 'AWS::Region' - HVM64`, }, "detect diff in Fn::FindInMap vs !FindInMap": { old: ` ImageId: Fn::FindInMap: - RegionMap - !Ref 'AWS::Region' - HVM64`, curr: ` ImageId: !FindInMap - Chizu - !Ref 'AWS::Region' - HVM64`, wanted: func() diffNode { changedMapName := &seqItemNode{ keyNode: keyNode{ oldV: yamlScalarNode("RegionMap"), newV: yamlScalarNode("Chizu"), }, } unchanged := &unchangedNode{count: 2} leaf := &keyNode{ keyValue: "ImageId", childNodes: []diffNode{&keyNode{ keyValue: "Fn::FindInMap", childNodes: []diffNode{changedMapName, unchanged}, }}, } return &keyNode{ childNodes: []diffNode{leaf}, } }, }, "no diff in Fn::GetAtt vs !GetAtt when comparing list to scalar": { old: `SourceSecurityGroupOwnerId: Fn::GetAtt: - myELB - SourceSecurityGroup.OwnerAlias`, curr: `SourceSecurityGroupOwnerId: !GetAtt myELB.SourceSecurityGroup.OwnerAlias`, }, "diff in Fn::GetAtt vs !GetAtt when comparing list to scalar": { old: `SourceSecurityGroupOwnerId: !GetAtt myELB.SourceSecurityGroup.OwnerAlias`, curr: `SourceSecurityGroupOwnerId: Fn::GetAtt: - theirELB - SourceSecurityGroup.OwnerAlias`, wanted: func() diffNode { changedLogicalID := &seqItemNode{ keyNode: keyNode{ oldV: yamlScalarNode("myELB"), newV: yamlScalarNode("theirELB"), }, } unchanged := &unchangedNode{count: 1} return &keyNode{ childNodes: []diffNode{&keyNode{ keyValue: "SourceSecurityGroupOwnerId", childNodes: []diffNode{&keyNode{ keyValue: "Fn::GetAtt", childNodes: []diffNode{changedLogicalID, unchanged}, }}, }}, } }, }, "no diff in Fn::GetAtt vs !GetAtt when comparing list to list": { old: `SourceSecurityGroupOwnerId: !GetAtt [myELB, SourceSecurityGroup]`, curr: `SourceSecurityGroupOwnerId: Fn::GetAtt: - myELB - SourceSecurityGroup`, }, "diff in Fn::GetAtt vs !GetAtt when comparing list to list": { old: `SourceSecurityGroupOwnerId: !GetAtt [myELB, SourceSecurityGroup.OwnerAlias]`, curr: `SourceSecurityGroupOwnerId: Fn::GetAtt: - theirELB - SourceSecurityGroup.OwnerAlias`, wanted: func() diffNode { changedLogicalID := &seqItemNode{ keyNode: keyNode{ oldV: yamlScalarNode("myELB"), newV: yamlScalarNode("theirELB"), }, } unchanged := &unchangedNode{count: 1} return &keyNode{ childNodes: []diffNode{&keyNode{ keyValue: "SourceSecurityGroupOwnerId", childNodes: []diffNode{&keyNode{ keyValue: "Fn::GetAtt", childNodes: []diffNode{changedLogicalID, unchanged}, }}, }}, } }, }, "no diff in Fn::GetAtt vs !GetAtt when comparing scalar to scalar": { old: `SourceSecurityGroupOwnerId: Fn::GetAtt: myELB.SourceSecurityGroup`, curr: `SourceSecurityGroupOwnerId: !GetAtt myELB.SourceSecurityGroup`, }, "diff in Fn::GetAtt vs !GetAtt when comparing scalar to scalar": { old: `SourceSecurityGroupOwnerId: !GetAtt myELB.SourceSecurityGroup.OwnerAlias`, curr: `SourceSecurityGroupOwnerId: Fn::GetAtt: theirELB.SourceSecurityGroup.OwnerAlias`, wanted: func() diffNode { return &keyNode{ childNodes: []diffNode{&keyNode{ keyValue: "SourceSecurityGroupOwnerId", childNodes: []diffNode{&keyNode{ keyValue: "Fn::GetAtt", oldV: yamlScalarNode("myELB.SourceSecurityGroup.OwnerAlias"), newV: yamlScalarNode("theirELB.SourceSecurityGroup.OwnerAlias")}}, }}, } }, }, "no diff in Fn::GetAtt vs !GetAtt when comparing scalar to scalar both with tags": { old: ` SecurityGroups: - !GetAtt PublicHTTPLoadBalancerSecurityGroup.GroupId`, curr: ` SecurityGroups: - !GetAtt PublicHTTPLoadBalancerSecurityGroup.GroupId`, }, "no diff in Fn::GetAZs vs !GetAZ": { old: `AvailabilityZone: !GetAZs ""`, curr: `AvailabilityZone: Fn::GetAZs: ""`, }, "detect diff in Fn::GetAZs vs !GetAZ": { old: `AvailabilityZone: Fn::Select: - 0 - Fn::GetAZs: "amazon"`, curr: `AvailabilityZone: !Select [0, !GetAZs 'arizona']`, wanted: func() diffNode { unchanged := &unchangedNode{count: 1} changedAZName := &seqItemNode{ keyNode{ childNodes: []diffNode{ &keyNode{ keyValue: "Fn::GetAZs", oldV: yamlScalarNode("amazon", withStyle(yaml.DoubleQuotedStyle)), newV: yamlScalarNode("arizona", withStyle(yaml.SingleQuotedStyle)), }, }, }, } leaf := &keyNode{ keyValue: "AvailabilityZone", childNodes: []diffNode{&keyNode{ keyValue: "Fn::Select", childNodes: []diffNode{unchanged, changedAZName}, }}, } return &keyNode{ childNodes: []diffNode{leaf}, } }, }, "no diff in Fn::ImportValue vs !ImportValue": { old: ` V: Fn::ImportValue: sharedValueToImport`, curr: ` V: !ImportValue sharedValueToImport`, }, "detect diff in Fn::ImportValue vs !ImportValue": { old: ` TestImportValue: Fn::ImportValue: pineapple1`, curr: ` TestImportValue: !ImportValue pineapple2`, wanted: func() diffNode { leaf := &keyNode{ keyValue: "Fn::ImportValue", oldV: yamlScalarNode("pineapple1"), newV: yamlScalarNode("pineapple2"), } return &keyNode{ childNodes: []diffNode{ &keyNode{ keyValue: "TestImportValue", childNodes: []diffNode{leaf}, }, }, } }, }, "no diff in Fn::Join vs !Join": { old: ` V: Fn::Join: ['', ['arn:',!Ref AWS::Partition, ':s3:::elasticbeanstalk-*-',!Ref AWS::AccountId ]]`, curr: ` V: !Join - '' - - 'arn:' - !Ref AWS::Partition - ':s3:::elasticbeanstalk-*-' - !Ref AWS::AccountId`, }, "detect diff in Fn::Join vs !Join": { old: ` TestJoin: Fn::Join: ['', ['arn:',!Ref AWS::Partition, ':s3:::elasticbeanstalk-*-pineapple1',!Ref AWS::AccountId ]]`, curr: ` TestJoin: !Join - '' - - 'arn:' - !Ref AWS::Partition - ':s3:::elasticbeanstalk-*-pineapple2' - !Ref AWS::AccountId`, wanted: func() diffNode { leaf := &seqItemNode{ keyNode{ oldV: yamlScalarNode(":s3:::elasticbeanstalk-*-pineapple1", withStyle(yaml.SingleQuotedStyle)), newV: yamlScalarNode(":s3:::elasticbeanstalk-*-pineapple2", withStyle(yaml.SingleQuotedStyle)), }, } joinElementsNode := &seqItemNode{ keyNode{ childNodes: []diffNode{&unchangedNode{count: 2}, leaf, &unchangedNode{count: 1}}, }, } joinNode := &keyNode{ keyValue: "Fn::Join", childNodes: []diffNode{&unchangedNode{count: 1}, joinElementsNode}, } return &keyNode{ childNodes: []diffNode{ &keyNode{ keyValue: "TestJoin", childNodes: []diffNode{ joinNode, }, }, }, } }, }, "no diff in Fn::Select vs !Select": { old: `CidrBlock: !Select [ 0, !Ref DbSubnetIpBlocks ]`, curr: `CidrBlock: Fn::Select: - 0 - !Ref DbSubnetIpBlocks`, }, "detect diff in Fn::Select vs !Select": { old: `TestSelect: !Select [ 1, !Ref DbSubnetIpBlocks ]`, curr: `TestSelect: Fn::Select: - 2 - !Ref DbSubnetIpBlocks`, wanted: func() diffNode { leaf := &seqItemNode{ keyNode{ oldV: yamlScalarNode("1"), newV: yamlScalarNode("2"), }, } return &keyNode{ childNodes: []diffNode{ &keyNode{ keyValue: "TestSelect", childNodes: []diffNode{ &keyNode{ keyValue: "Fn::Select", childNodes: []diffNode{leaf, &unchangedNode{1}}, }, }, }, }, } }, }, "no diff in Fn::Split vs !Split": { old: `V: !Split [ "|" , "a||c|" ]`, curr: ` V: Fn::Split: [ "|" , "a||c|" ]`, }, "detect diff in Fn::Split vs !Split": { old: `TestSplit: !Split [ "|" , "a||c|pineapple1" ]`, curr: ` TestSplit: Fn::Split: [ "|" , "a||c|pineapple2" ]`, wanted: func() diffNode { leaf := &seqItemNode{ keyNode{ oldV: yamlScalarNode("a||c|pineapple1", withStyle(yaml.DoubleQuotedStyle)), newV: yamlScalarNode("a||c|pineapple2", withStyle(yaml.DoubleQuotedStyle)), }, } return &keyNode{ childNodes: []diffNode{ &keyNode{ keyValue: "TestSplit", childNodes: []diffNode{ &keyNode{ keyValue: "Fn::Split", childNodes: []diffNode{&unchangedNode{count: 1}, leaf}, }, }, }, }, } }, }, "no diff in Fn::Sub vs !Sub": { old: ` Name: !Sub - 'www.${Domain}' - Domain: !Ref RootDomainName`, curr: ` Name: Fn::Sub: - 'www.${Domain}' - Domain: !Ref RootDomainName`, }, "detect diff in Fn::Sub vs !Sub": { old: ` TestSub: !Sub - 'www.${Domain}.pineapple1' - Domain: !Ref RootDomainName`, curr: ` TestSub: Fn::Sub: - 'www.${Domain}.pineapple2' - Domain: !Ref RootDomainName`, wanted: func() diffNode { leaf := &seqItemNode{ keyNode{ oldV: yamlScalarNode("www.${Domain}.pineapple1", withStyle(yaml.SingleQuotedStyle)), newV: yamlScalarNode("www.${Domain}.pineapple2", withStyle(yaml.SingleQuotedStyle)), }, } return &keyNode{ childNodes: []diffNode{ &keyNode{ keyValue: "TestSub", childNodes: []diffNode{ &keyNode{ keyValue: "Fn::Sub", childNodes: []diffNode{leaf, &unchangedNode{1}}, }, }, }, }, } }, }, // "no diff in Fn::Transform vs !Transform": {// TODO(lou1415926) // old: ` // Fn::Transform: // Name : macro name // Parameters : // Key : value`, // curr: ` // Transform: // Name: macro name // Parameters: // Key: value`, // }, "do not match unexpected keys": { old: ` Stuff: Sub: not_an_intrinsic_function`, curr: ` Stuff: !Sub this_is_one`, wanted: func() diffNode { return &keyNode{ childNodes: []diffNode{ &keyNode{ keyValue: "Stuff", oldV: yamlNode("Sub: not_an_intrinsic_function", t), newV: yamlNode("!Sub this_is_one", t), }, }, } }, }, "no diff in Condition vs !Condition": { old: `ALB: - Condition: CreateALB`, curr: `ALB: - !Condition CreateALB`, }, "no diff in Fn::And vs !And": { old: ` ALB: Fn::And: [this, that]`, curr: ` ALB: !And - this - that`, }, "no diff in Fn::Equals vs !Equals": { old: ` UseProdCondition: Fn::Equals: [!Ref EnvironmentType, prod]`, curr: ` UseProdCondition: !Equals [!Ref EnvironmentType, prod]`, }, "no diff in Fn::If vs !If": { old: ` SecurityGroups: - !If [CreateNewSecurityGroup, !Ref NewSecurityGroup, !Ref ExistingSecurityGroup]`, curr: ` SecurityGroups: - Fn::If: [CreateNewSecurityGroup, !Ref NewSecurityGroup, !Ref ExistingSecurityGroup]`, }, "no diff in Fn::Not vs !Not": { old: ` MyNotCondition: !Not [!Equals [!Ref EnvironmentType, prod]]`, curr: ` MyNotCondition: Fn::Not: [!Equals [!Ref EnvironmentType, prod]]`, }, "no diff in Fn::Or vs !Or": { old: ` MyOrCondition: Fn::Or: [!Equals [sg-mysggroup, !Ref ASecurityGroup], Condition: SomeOtherCondition]`, curr: ` MyOrCondition: !Or [!Equals [sg-mysggroup, !Ref ASecurityGroup], Condition: SomeOtherCondition]`, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { got, err := From(tc.old).Parse([]byte(tc.curr), &getAttConverter{}, &intrinsicFuncMapTagConverter{}) require.NoError(t, err) got.Write(os.Stdout) if tc.wanted != nil { require.True(t, equalTree(got, Tree{tc.wanted()}, t), "should get the expected tree") } else { require.True(t, equalTree(got, Tree{}, t), "should get the expected tree") } }) } }
563
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package diff import ( "fmt" "io" "github.com/aws/copilot-cli/internal/pkg/term/color" "github.com/dustin/go-humanize/english" ) const ( prefixAdd = "+" prefixDel = "-" prefixMod = "~" ) const indentInc = 4 // treeWriter writes the string representation of a diff tree. type treeWriter struct { tree Tree writer io.Writer } // write uses the writer to writeTree the string representation of the diff tree stemmed from the root. func (s *treeWriter) write() error { if s.tree.root == nil { return nil // Return without writing anything. } if len(s.tree.root.children()) == 0 { return s.writeLeaf(s.tree.root, &documentFormatter{}) } for _, child := range s.tree.root.children() { if err := s.writeTree(child, 0); err != nil { return err } } return nil } func (s *treeWriter) writeTree(node diffNode, indent int) error { if node == nil { return nil } var formatter formatter switch node := node.(type) { case *unchangedNode: content := fmt.Sprintf("(%s)", english.Plural(node.unchangedCount(), "unchanged item", "unchanged items")) content = process(content, indentByFn(indent)) _, err := s.writer.Write([]byte(color.Faint.Sprint(content + "\n"))) return err case *seqItemNode: formatter = &seqItemFormatter{indent} default: formatter = &keyedFormatter{indent} } if len(node.children()) == 0 { return s.writeLeaf(node, formatter) } if kn, ok := node.(*keyNode); ok { // Collapse all key nodes with exactly one diff. node = joinNodes(kn) } if _, err := s.writer.Write([]byte(formatter.formatPath(node))); err != nil { return err } for _, child := range node.children() { err := s.writeTree(child, formatter.nextIndent()) if err != nil { return err } } return nil } func (s *treeWriter) writeLeaf(node diffNode, formatter formatter) error { switch { case node.oldYAML() != nil && node.newYAML() != nil: return s.writeMod(node, formatter) case node.oldYAML() != nil: return s.writeDel(node, formatter) default: return s.writeInsert(node, formatter) } } func (s *treeWriter) writeMod(node diffNode, formatter formatter) error { if node.oldYAML().Kind != node.newYAML().Kind { if err := s.writeDel(node, formatter); err != nil { return err } return s.writeInsert(node, formatter) } content, err := formatter.formatMod(node) if err != nil { return err } _, err = s.writer.Write([]byte(color.Yellow.Sprint(content + "\n"))) return err } func (s *treeWriter) writeDel(node diffNode, formatter formatter) error { content, err := formatter.formatDel(node) if err != nil { return err } _, err = s.writer.Write([]byte(color.Red.Sprint(content + "\n"))) return err } func (s *treeWriter) writeInsert(node diffNode, formatter formatter) error { content, err := formatter.formatInsert(node) if err != nil { return err } _, err = s.writer.Write([]byte(color.Green.Sprint(content + "\n"))) return err } // joinNodes collapses all keyNode on a Tree path into one keyNode, as long as there is only modification under the key. // For example, if only the `DesiredCount` of an ECS service is changed, then the returned path becomes // `/Resources/Service/Properties`. If multiple entries of an ECS service is changed, then the returned // path is `/Resources/Service`. func joinNodes(curr *keyNode) *keyNode { key := curr.key() for { if len(curr.children()) != 1 { break } peek := curr.children()[0] if len(peek.children()) == 0 { break } if _, ok := peek.(*keyNode); !ok { break } key = key + "/" + peek.key() curr = peek.(*keyNode) } return &keyNode{ keyValue: key, childNodes: curr.children(), } }
147
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package diff import ( "strings" "testing" "github.com/stretchr/testify/require" ) func Test_Integration_Parse_Write(t *testing.T) { testCases := map[string]struct { curr string old string wanted string }{ "add a map": { curr: ` Mary: Height: cm: 168 Weight: kg: 52`, old: ` Mary: Height: cm: 168`, wanted: ` ~ Mary: + Weight: + kg: 52 `, }, "remove a map": { curr: ` Mary: Height: cm: 168`, old: ` Mary: Height: cm: 168 Weight: kg: 52`, wanted: ` ~ Mary: - Weight: - kg: 52 `, }, "change keyed values": { curr: ` Mary: Height: cm: truly: really: 168 inch: really: 5.2`, old: ` Mary: Height: cm: truly: really: 190 inch: really: 6`, wanted: ` ~ Mary/Height: ~ cm/truly: ~ really: 190 -> 168 ~ inch: ~ really: 6 -> 5.2 `, }, "list does not change": { old: `Alphabet: [a,b,c,d]`, curr: `Alphabet: [a,b,c,d]`, }, "list with insertion": { old: `DanceCompetition: [dog,bear,cat]`, curr: `DanceCompetition: [dog,bear,mouse,cat]`, wanted: ` ~ DanceCompetition: (2 unchanged items) + - mouse (1 unchanged item) `, }, "list with deletion": { old: `PotatoChipCommittee: [dog,bear,cat,mouse]`, curr: `PotatoChipCommittee: [dog,bear,mouse]`, wanted: ` ~ PotatoChipCommittee: (2 unchanged items) - - cat (1 unchanged item) `, }, "list with a scalar value changed": { old: `DogsFavoriteShape: [triangle,circle,rectangle]`, curr: `DogsFavoriteShape: [triangle,ellipse,rectangle]`, wanted: ` ~ DogsFavoriteShape: (1 unchanged item) ~ - circle -> ellipse (1 unchanged item) `, }, "change a list with nested lists": { old: ` StrawberryPopularitySurvey: - Name: Dog LikeStrawberry: ver much - Name: Bear LikeStrawberry: meh Reason(s): - Not sweet enough - Juicy though - IsHoney: IsIt: no - Name: Cat LikeStrawberry: ew`, curr: ` StrawberryPopularitySurvey: - Name: Dog LikeStrawberry: ver much - Name: Bear LikeStrawberry: ok ChangeOfMind: yeah Reason(s): - Not sweet enough but acceptable now - Juicy though - IsHoney: IsIt: no, but it's fine - Name: Cat LikeStrawberry: ew`, wanted: ` ~ StrawberryPopularitySurvey: (1 unchanged item) ~ - (changed item) + ChangeOfMind: yeah ~ LikeStrawberry: meh -> ok ~ Reason(s): ~ - Not sweet enough -> Not sweet enough but acceptable now (1 unchanged item) ~ - (changed item) ~ IsHoney: ~ IsIt: no -> no, but it's fine (1 unchanged item) `, }, "change a list with nested maps": { old: ` StrawberryPopularitySurvey: - Name: Dog LikeStrawberry: ver much - Name: Bear LikeStrawberry: Flavor: meh Texture: UnderRoomTemperature: acceptable Frozen: too hard - Name: Cat LikeStrawberry: ew`, curr: ` StrawberryPopularitySurvey: - Name: Dog LikeStrawberry: ver much - Name: Bear LikeStrawberry: Flavor: meh Texture: UnderRoomTemperature: noice Frozen: too hard ChangeOfMind: yeah - Name: Cat LikeStrawberry: ew`, wanted: ` ~ StrawberryPopularitySurvey: (1 unchanged item) ~ - (changed item) + ChangeOfMind: yeah ~ LikeStrawberry/Texture: ~ UnderRoomTemperature: acceptable -> noice (1 unchanged item) `, }, "change a map to scalar": { curr: ` Mary: Dialogue: "Said bear: 'I know I'm supposed to keep an eye on you"`, old: ` Mary: Dialogue: Bear: "I know I'm supposed to keep an eye on you"`, wanted: ` ~ Mary: - Dialogue: - Bear: "I know I'm supposed to keep an eye on you" + Dialogue: "Said bear: 'I know I'm supposed to keep an eye on you" `, }, "change a list to scalar": { curr: ` Mary: Dialogue: "Said bear: 'I know I'm supposed to keep an eye on you; Said Dog: 'ikr'"`, old: ` Mary: Dialogue: - Bear: "I know I'm supposed to keep an eye on you" Tone: disappointed - Dog: "ikr" Tone: pleased`, wanted: ` ~ Mary: - Dialogue: - - Bear: "I know I'm supposed to keep an eye on you" - Tone: disappointed - - Dog: "ikr" - Tone: pleased + Dialogue: "Said bear: 'I know I'm supposed to keep an eye on you; Said Dog: 'ikr'" `, }, "change a map to list": { curr: ` Mary: Dialogue: - Bear: "I know I'm supposed to keep an eye on you" Tone: disappointed - Dog: "ikr" Tone: pleased`, old: ` Mary: Dialogue: Bear: (disappointed) "I know I'm supposed to keep an eye on you" Dog: (pleased) "ikr"`, wanted: ` ~ Mary: - Dialogue: - Bear: (disappointed) "I know I'm supposed to keep an eye on you" - Dog: (pleased) "ikr" + Dialogue: + - Bear: "I know I'm supposed to keep an eye on you" + Tone: disappointed + - Dog: "ikr" + Tone: pleased `, }, "list with scalar insertion, deletion and value changed": { old: `DogsFavoriteShape: [irregular,triangle,circle,rectangle]`, curr: `DogsFavoriteShape: [triangle,ellipse,rectangle,food-shape]`, wanted: ` ~ DogsFavoriteShape: - - irregular (1 unchanged item) ~ - circle -> ellipse (1 unchanged item) + - food-shape `, }, "from is empty": { curr: `Mary: likes animals`, old: ` `, wanted: `+ Mary: likes animals `, }, "to is empty": { curr: ` `, old: `Mary: likes animals`, wanted: `- Mary: likes animals `, }, "from and to are both empty": { curr: ` `, old: ` `, }, "no diff": { curr: ` Mary: Height: cm: 190 CanFight: yes FavoriteWord: muscle`, old: ` Mary: Height: cm: 190 CanFight: yes FavoriteWord: muscle`, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { gotTree, err := From(tc.old).Parse([]byte(tc.curr)) require.NoError(t, err) buf := strings.Builder{} err = gotTree.Write(&buf) out := buf.String() require.NoError(t, err) require.Equal(t, strings.TrimPrefix(tc.wanted, "\n"), out) }) } } func Test_Integration_Parse_Write_WithCFNIgnorer(t *testing.T) { testCases := map[string]struct { curr string old string overrider overrider wanted string }{ "ignore metadata manifest": { old: `Description: CloudFormation environment template for infrastructure shared among Copilot workloads. Metadata: Version: v1.26.0 Manifest: I don't see any difference.`, curr: `Description: CloudFormation environment template for infrastructure shared among Copilot workloads. Metadata: Version: v1.27.0 Manifest: There is definitely a difference.`, wanted: ` ~ Metadata: ~ Version: v1.26.0 -> v1.27.0 `, }, "produces diff": { old: ` Conditions: IsDefaultRootPath: !Equals [!Ref RulePath, "/"] Resources: HTTPRuleWithDomainPriorityAction: Properties: RulePath: !Ref RulePath Service: Properties: ServiceRegistries: - Port: !Ref ContainerPort TargetGroup: Properties: Port: !Ref ContainerPort `, curr: ` Conditions: IsGovCloud: !Equals [!Ref "AWS::Partition", "aws-us-gov"] Resources: HTTPRuleWithDomainPriorityAction: Properties: RulePath: ["/"] Service: Properties: ServiceConnectConfiguration: !If - IsGovCloud - !Ref AWS::NoValue - Enabled: False ServiceRegistries: - Port: !Ref TargetPort TargetGroup: Properties: Port: 80 `, wanted: ` ~ Conditions: - IsDefaultRootPath: !Equals [!Ref RulePath, "/"] + IsGovCloud: !Equals [!Ref "AWS::Partition", "aws-us-gov"] ~ Resources: ~ HTTPRuleWithDomainPriorityAction/Properties: - RulePath: !Ref RulePath + RulePath: ["/"] ~ Service/Properties: + ServiceConnectConfiguration: !If + - IsGovCloud + - !Ref AWS::NoValue + - Enabled: False ~ ServiceRegistries: ~ - (changed item) ~ Port: !Ref ContainerPort -> !Ref TargetPort ~ TargetGroup/Properties: ~ Port: !Ref ContainerPort -> 80 `, }, "no diff": { old: `Description: CloudFormation environment template for infrastructure shared among Copilot workloads. Metadata: Manifest: I don't see any difference.`, curr: `Description: CloudFormation environment template for infrastructure shared among Copilot workloads. Metadata: Manifest: There is definitely a difference.`, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { gotTree, err := From(tc.old).ParseWithCFNOverriders([]byte(tc.curr)) require.NoError(t, err) buf := strings.Builder{} err = gotTree.Write(&buf) require.NoError(t, err) require.Equal(t, strings.TrimPrefix(tc.wanted, "\n"), buf.String()) }) } }
407
copilot-cli
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: ./internal/pkg/template/template.go // Package mocks is a generated GoMock package. package mocks import ( fs "io/fs" reflect "reflect" template "github.com/aws/copilot-cli/internal/pkg/template" gomock "github.com/golang/mock/gomock" ) // MockReader is a mock of Reader interface. type MockReader struct { ctrl *gomock.Controller recorder *MockReaderMockRecorder } // MockReaderMockRecorder is the mock recorder for MockReader. type MockReaderMockRecorder struct { mock *MockReader } // NewMockReader creates a new mock instance. func NewMockReader(ctrl *gomock.Controller) *MockReader { mock := &MockReader{ctrl: ctrl} mock.recorder = &MockReaderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockReader) EXPECT() *MockReaderMockRecorder { return m.recorder } // Read mocks base method. func (m *MockReader) Read(path string) (*template.Content, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Read", path) ret0, _ := ret[0].(*template.Content) ret1, _ := ret[1].(error) return ret0, ret1 } // Read indicates an expected call of Read. func (mr *MockReaderMockRecorder) Read(path interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockReader)(nil).Read), path) } // MockParser is a mock of Parser interface. type MockParser struct { ctrl *gomock.Controller recorder *MockParserMockRecorder } // MockParserMockRecorder is the mock recorder for MockParser. type MockParserMockRecorder struct { mock *MockParser } // NewMockParser creates a new mock instance. func NewMockParser(ctrl *gomock.Controller) *MockParser { mock := &MockParser{ctrl: ctrl} mock.recorder = &MockParserMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockParser) EXPECT() *MockParserMockRecorder { return m.recorder } // Parse mocks base method. func (m *MockParser) Parse(path string, data interface{}, options ...template.ParseOption) (*template.Content, error) { m.ctrl.T.Helper() varargs := []interface{}{path, data} for _, a := range options { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Parse", varargs...) ret0, _ := ret[0].(*template.Content) ret1, _ := ret[1].(error) return ret0, ret1 } // Parse indicates an expected call of Parse. func (mr *MockParserMockRecorder) Parse(path, data interface{}, options ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{path, data}, options...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Parse", reflect.TypeOf((*MockParser)(nil).Parse), varargs...) } // MockReadParser is a mock of ReadParser interface. type MockReadParser struct { ctrl *gomock.Controller recorder *MockReadParserMockRecorder } // MockReadParserMockRecorder is the mock recorder for MockReadParser. type MockReadParserMockRecorder struct { mock *MockReadParser } // NewMockReadParser creates a new mock instance. func NewMockReadParser(ctrl *gomock.Controller) *MockReadParser { mock := &MockReadParser{ctrl: ctrl} mock.recorder = &MockReadParserMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockReadParser) EXPECT() *MockReadParserMockRecorder { return m.recorder } // Parse mocks base method. func (m *MockReadParser) Parse(path string, data interface{}, options ...template.ParseOption) (*template.Content, error) { m.ctrl.T.Helper() varargs := []interface{}{path, data} for _, a := range options { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Parse", varargs...) ret0, _ := ret[0].(*template.Content) ret1, _ := ret[1].(error) return ret0, ret1 } // Parse indicates an expected call of Parse. func (mr *MockReadParserMockRecorder) Parse(path, data interface{}, options ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{path, data}, options...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Parse", reflect.TypeOf((*MockReadParser)(nil).Parse), varargs...) } // Read mocks base method. func (m *MockReadParser) Read(path string) (*template.Content, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Read", path) ret0, _ := ret[0].(*template.Content) ret1, _ := ret[1].(error) return ret0, ret1 } // Read indicates an expected call of Read. func (mr *MockReadParserMockRecorder) Read(path interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockReadParser)(nil).Read), path) } // MockosFS is a mock of osFS interface. type MockosFS struct { ctrl *gomock.Controller recorder *MockosFSMockRecorder } // MockosFSMockRecorder is the mock recorder for MockosFS. type MockosFSMockRecorder struct { mock *MockosFS } // NewMockosFS creates a new mock instance. func NewMockosFS(ctrl *gomock.Controller) *MockosFS { mock := &MockosFS{ctrl: ctrl} mock.recorder = &MockosFSMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockosFS) EXPECT() *MockosFSMockRecorder { return m.recorder } // Open mocks base method. func (m *MockosFS) Open(name string) (fs.File, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Open", name) ret0, _ := ret[0].(fs.File) ret1, _ := ret[1].(error) return ret0, ret1 } // Open indicates an expected call of Open. func (mr *MockosFSMockRecorder) Open(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Open", reflect.TypeOf((*MockosFS)(nil).Open), name) } // ReadDir mocks base method. func (m *MockosFS) ReadDir(name string) ([]fs.DirEntry, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReadDir", name) ret0, _ := ret[0].([]fs.DirEntry) ret1, _ := ret[1].(error) return ret0, ret1 } // ReadDir indicates an expected call of ReadDir. func (mr *MockosFSMockRecorder) ReadDir(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadDir", reflect.TypeOf((*MockosFS)(nil).ReadDir), name) } // ReadFile mocks base method. func (m *MockosFS) ReadFile(name string) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReadFile", name) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(error) return ret0, ret1 } // ReadFile indicates an expected call of ReadFile. func (mr *MockosFSMockRecorder) ReadFile(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadFile", reflect.TypeOf((*MockosFS)(nil).ReadFile), name) }
221
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package override provides functionality to replace content from vended templates. package override import ( "bytes" "fmt" "gopkg.in/yaml.v3" ) // CloudFormationTemplate overrides the given CloudFormation template by applying // the override rules. func CloudFormationTemplate(overrideRules []Rule, origTemp []byte) ([]byte, error) { content, err := unmarshalYAML(origTemp) if err != nil { return nil, err } ruleNodes, err := parseRules(overrideRules) if err != nil { return nil, err } if err := applyRules(ruleNodes, content); err != nil { return nil, err } output, err := marshalYAML(content) if err != nil { return nil, err } return output, nil } func parseRules(rules []Rule) ([]nodeUpserter, error) { var ruleNodes []nodeUpserter for _, r := range rules { if err := r.validate(); err != nil { return nil, err } node, err := r.parse() if err != nil { return nil, err } ruleNodes = append(ruleNodes, node) } return ruleNodes, nil } func unmarshalYAML(temp []byte) (*yaml.Node, error) { var node yaml.Node if err := yaml.Unmarshal(temp, &node); err != nil { return nil, fmt.Errorf("unmarshal YAML template: %w", err) } return &node, nil } func marshalYAML(content *yaml.Node) ([]byte, error) { var out bytes.Buffer yamlEncoder := yaml.NewEncoder(&out) yamlEncoder.SetIndent(2) if err := yamlEncoder.Encode(content); err != nil { return nil, fmt.Errorf("marshal YAML template: %w", err) } return out.Bytes(), nil } func applyRules(rules []nodeUpserter, content *yaml.Node) error { contentNode, err := getTemplateDocument(content) if err != nil { return err } for _, rule := range rules { if err := applyRule(rule, contentNode); err != nil { return err } } return nil } // getTemplateDocument gets the document content of the unmarshalled YMAL template node func getTemplateDocument(content *yaml.Node) (*yaml.Node, error) { if content != nil && len(content.Content) != 0 { return content.Content[0], nil } return nil, fmt.Errorf("cannot apply override rule on empty YAML template") } func applyRule(ruleSegment nodeUpserter, content *yaml.Node) error { if ruleSegment == nil || content == nil { return nil } var err error var nextContentNode *yaml.Node for { if nextContentNode, err = ruleSegment.Upsert(content); err != nil { return err } if ruleSegment.Next() == nil { break } content = nextContentNode ruleSegment = ruleSegment.Next() } return nil }
107
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package override import ( "fmt" "os" "path/filepath" "testing" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) func newTaskDefPropertyRule(rule Rule) Rule { return Rule{ Path: fmt.Sprintf("Resources.TaskDefinition.Properties.%s", rule.Path), Value: rule.Value, } } func requiresCompatibilitiesRule() Rule { return newTaskDefPropertyRule(Rule{ Path: "RequiresCompatibilities[-]", Value: yaml.Node{ Kind: yaml.ScalarNode, Tag: nodeTagStr, Value: "EC2", }, }) } func linuxParametersCapabilitiesRule() Rule { node1 := yaml.Node{ Kind: yaml.ScalarNode, Style: yaml.DoubleQuotedStyle, Tag: nodeTagStr, Value: "AUDIT_CONTROL", } node2 := yaml.Node{ Kind: yaml.ScalarNode, Style: yaml.DoubleQuotedStyle, Tag: nodeTagStr, Value: "AUDIT_WRITE", } return newTaskDefPropertyRule(Rule{ Path: "ContainerDefinitions[0].LinuxParameters.Capabilities.Add", Value: yaml.Node{ Kind: yaml.SequenceNode, Style: yaml.FlowStyle, Tag: nodeTagSeq, Content: []*yaml.Node{&node1, &node2}, }, }) } func linuxParametersCapabilitiesInitProcessEnabledRule() Rule { return newTaskDefPropertyRule(Rule{ Path: "ContainerDefinitions[0].LinuxParameters.Capabilities.InitProcessEnabled", Value: yaml.Node{ Kind: yaml.ScalarNode, Tag: nodeTagBool, Value: "true", }, }) } func ulimitsRule() Rule { return newTaskDefPropertyRule(Rule{ Path: "ContainerDefinitions[0].Ulimits[-].HardLimit", Value: yaml.Node{ Kind: yaml.ScalarNode, Style: yaml.TaggedStyle, Tag: "!Ref", Value: "ParamName", }, }) } func logGroupRule() Rule { return newTaskDefPropertyRule(Rule{ Path: "ContainerDefinitions[0].LogConfiguration.Options.awslogs-group", Value: yaml.Node{ Kind: yaml.ScalarNode, Value: "/copilot/${COPILOT_APPLICATION_NAME}-${COPILOT_ENVIRONMENT_NAME}", }, }) } func exposeExtraPortRule() Rule { return newTaskDefPropertyRule(Rule{ Path: "ContainerDefinitions[0].PortMappings[-].ContainerPort", Value: yaml.Node{ Kind: 8, Tag: nodeTagInt, Value: "5000", }, }) } func referBadSeqIndexRule() Rule { return newTaskDefPropertyRule(Rule{ Path: "ContainerDefinitions[0].PortMappings[1].ContainerPort", Value: yaml.Node{ Kind: 8, Tag: nodeTagInt, Value: "5000", }, }) } func referBadSeqIndexWithNoKeyRule() Rule { return newTaskDefPropertyRule(Rule{ Path: "ContainerDefinitions[0].VolumesFrom[1].SourceContainer", Value: yaml.Node{ Kind: 8, Tag: nodeTagStr, Value: "foo", }, }) } func Test_CloudFormationTemplate(t *testing.T) { testCases := map[string]struct { inRules []Rule inTplFileName string wantedError error wantedTplFileName string }{ "invalid CFN template": { inTplFileName: "empty.yml", wantedError: fmt.Errorf("cannot apply override rule on empty YAML template"), }, "error when referring to bad sequence index": { inTplFileName: "backend_svc.yml", inRules: []Rule{ referBadSeqIndexRule(), }, wantedError: fmt.Errorf("cannot specify PortMappings[1] because the current length is 1. Use [%s] to append to the sequence instead", seqAppendToLastSymbol), }, "error when referring to bad sequence index when sequence key doesn't exist": { inTplFileName: "backend_svc.yml", inRules: []Rule{ referBadSeqIndexWithNoKeyRule(), }, wantedError: fmt.Errorf("cannot specify VolumesFrom[1] because VolumesFrom does not exist. Use VolumesFrom[%s] to append to the sequence instead", seqAppendToLastSymbol), }, "success with ulimits": { inTplFileName: "backend_svc.yml", inRules: []Rule{ ulimitsRule(), }, wantedTplFileName: "ulimits.yml", }, "success with different log group name": { inTplFileName: "backend_svc.yml", inRules: []Rule{ logGroupRule(), }, wantedTplFileName: "loggroup.yml", }, "success with extra port": { inTplFileName: "backend_svc.yml", inRules: []Rule{ exposeExtraPortRule(), }, wantedTplFileName: "extra_port.yml", }, "success with linux parameters": { inTplFileName: "backend_svc.yml", inRules: []Rule{ linuxParametersCapabilitiesRule(), linuxParametersCapabilitiesInitProcessEnabledRule(), }, wantedTplFileName: "linux_parameters.yml", }, "success with requires compatibilities": { inTplFileName: "backend_svc.yml", inRules: []Rule{ requiresCompatibilitiesRule(), }, wantedTplFileName: "requires_compatibilities.yml", }, "success with multiple override rules": { inTplFileName: "backend_svc.yml", inRules: []Rule{ ulimitsRule(), exposeExtraPortRule(), linuxParametersCapabilitiesRule(), linuxParametersCapabilitiesInitProcessEnabledRule(), requiresCompatibilitiesRule(), }, wantedTplFileName: "multiple_overrides.yml", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { in, err := os.ReadFile(filepath.Join("testdata", "original", tc.inTplFileName)) require.NoError(t, err) got, gotErr := CloudFormationTemplate(tc.inRules, in) if tc.wantedError != nil { require.EqualError(t, gotErr, tc.wantedError.Error()) } else { wantedContent, err := os.ReadFile(filepath.Join("testdata", "outputs", tc.wantedTplFileName)) require.NoError(t, err) require.NoError(t, gotErr) require.Equal(t, string(wantedContent), string(got)) } }) } }
218
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package override import ( "fmt" "regexp" "strconv" "strings" "gopkg.in/yaml.v3" ) const ( // PathSegmentSeparator is the separator for path segments. PathSegmentSeparator = "." // seqAppendToLastSymbol is the symbol used to add a node to the tail of a list. seqAppendToLastSymbol = "-" ) // Subset of YAML tag values: http://yaml.org/type/ // These are the type of nodes that can be upserted. const ( nodeTagBool = "!!bool" nodeTagInt = "!!int" nodeTagStr = "!!str" nodeTagSeq = "!!seq" nodeTagMap = "!!map" ) var ( // pathSegmentRegexp checks for map key or single sequence reference. // For example: ContainerDefinitions[0], PortMapping[-], or Ulimits. // There are three capture groups in this regex: ([a-zA-Z0-9_-]+), (\[(\d+|%s)\]), and (\d+|%s). pathSegmentRegexp = regexp.MustCompile(fmt.Sprintf(`^([a-zA-Z0-9_-]+)(\[(\d+|%s)\])?$`, seqAppendToLastSymbol)) ) // nodeUpserter is the interface to insert or update a series of nodes to a YAML file. type nodeUpserter interface { Upsert(content *yaml.Node) (*yaml.Node, error) Next() nodeUpserter } // Rule is the override rule override package uses. type Rule struct { Path string // example: "ContainerDefinitions[0].Ulimits[-].HardLimit" Value yaml.Node } func (r Rule) validate() error { if r.Path == "" { return fmt.Errorf("rule path is empty") } pathSegments := strings.Split(r.Path, PathSegmentSeparator) for _, pathSegment := range pathSegments { if !pathSegmentRegexp.MatchString(pathSegment) { return fmt.Errorf(`invalid override path segment "%s": segments must be of the form "array[0]", "array[%s]" or "key"`, pathSegment, seqAppendToLastSymbol) } } return nil } func (r Rule) parse() (nodeUpserter, error) { pathSegments := strings.SplitN(r.Path, PathSegmentSeparator, 2) segment, err := parsePathSegment(pathSegments[0]) if err != nil { return nil, err } baseNode := upsertNode{ key: segment.key, } if len(pathSegments) < 2 { // This is the last segment. baseNode.valueToInsert = &r.Value return newNodeUpserter(baseNode, segment) } subRule := Rule{ Path: pathSegments[1], Value: r.Value, } nextNode, err := subRule.parse() if err != nil { return nil, err } baseNode.next = nextNode return newNodeUpserter(baseNode, segment) } func newNodeUpserter(baseNode upsertNode, segment pathSegment) (nodeUpserter, error) { if segment.index == "" { // The indexMatch capture group is empty string, meaning that the path segment doesn't contain "[<index>]". return &mapUpsertNode{ upsertNode: baseNode, }, nil } if segment.index == seqAppendToLastSymbol { return &seqIdxUpsertNode{ appendToLast: true, upsertNode: baseNode, }, nil } index, err := strconv.Atoi(segment.index) if err != nil { // This error also shouldn't occur given that `validate()` has passed. return nil, fmt.Errorf("convert index %s to integer: %w", segment.raw, err) } return &seqIdxUpsertNode{ index: index, upsertNode: baseNode, }, nil } type pathSegment struct { raw string // The raw path segment, e.g. ContainerDefinitions[0]. key string // The key of the segment, e.g. ContainerDefinitions. index string // The index, if any, of the segment, e.g. 0. It is an empty string if the path is not a slice segment. } func parsePathSegment(rawPathSegment string) (pathSegment, error) { subMatches := pathSegmentRegexp.FindStringSubmatch(rawPathSegment) if len(subMatches) == 0 { // This error shouldn't occur given that `validate()` has passed. return pathSegment{}, fmt.Errorf(`invalid path segment "%s"`, rawPathSegment) } // https://pkg.go.dev/regexp#Regexp.FindStringSubmatch return pathSegment{ raw: rawPathSegment, key: subMatches[1], // The first capture group - "([a-zA-Z0-9_-]+)". Example match: "ContainerDefinitions". index: subMatches[3], // The third capture group - "(\d+|%s)". Example matches: "1", "-". }, nil } // upsertNode represents a node that needs to be upserted at the given key. // If multiple intermediary mapping nodes need to be created then `next` is not nil. type upsertNode struct { key string valueToInsert *yaml.Node next nodeUpserter } // Next returns the next node. func (m *upsertNode) Next() nodeUpserter { return m.next } // mapUpsertNode represents a map node that needs to be upserted at the given key. type mapUpsertNode struct { upsertNode } // Upsert upserts a node into given yaml content. // If the key already exists then return the node at the given key. // Otherwise, creates a new mapping node with the given key and returns it. func (m *mapUpsertNode) Upsert(parentContent *yaml.Node) (*yaml.Node, error) { // If it contains the value to insert, upsert the value to the yaml. if m.valueToInsert != nil { m.upsertValue(parentContent) return nil, nil } for i := 0; i < len(parentContent.Content); i += 2 { // The content of a map always come in pairs. If the node pair exists, return the map node. // Note that the rest of code massively uses yaml node tree. // Please refer to https://www.efekarakus.com/2020/05/30/deep-dive-go-yaml-cfn.html if parentContent.Content[i].Value == m.key { return parentContent.Content[i+1], nil } } // If the node pair doesn't exist, create the label node first and then a map node. // Finally we return the created map node. newLabelNode := &yaml.Node{ Kind: yaml.ScalarNode, Tag: nodeTagStr, Value: m.key, } parentContent.Content = append(parentContent.Content, newLabelNode) newValNode := &yaml.Node{ Kind: yaml.MappingNode, Tag: nodeTagMap, } parentContent.Content = append(parentContent.Content, newValNode) return newValNode, nil } func (m *mapUpsertNode) upsertValue(content *yaml.Node) { // If the node pair exists, substitute with the value node. for i := 0; i < len(content.Content); i += 2 { if m.key == content.Content[i].Value { content.Content[i+1] = m.valueToInsert return } } // Otherwise, we create the label node then append the value node. newLabelNode := &yaml.Node{ Kind: yaml.ScalarNode, Tag: nodeTagStr, Value: m.key, } content.Content = append(content.Content, newLabelNode) content.Content = append(content.Content, m.valueToInsert) } // seqIdxUpsertNode represents a sequence node that needs to be upserted at index. type seqIdxUpsertNode struct { index int appendToLast bool upsertNode } // Upsert upserts a node into given yaml content. func (s *seqIdxUpsertNode) Upsert(parentContent *yaml.Node) (*yaml.Node, error) { // If it contains the value to insert, upsert the value to the yaml. if s.valueToInsert != nil { return nil, s.upsertValue(parentContent) } // If the node pair exists, we check if we need to append the node to the end. // If so, create a map node and return it since we want to go deeper to upsert the value. // Here we assume it is not possible for the yaml we want to override to have nested sequence: // Mapping01: // - - foo // - bar // - - boo // The example above will be translated to "Mapping01[0][1]" to refer to "bar". // If not check if the given index is within the sequence range. for i := 0; i < len(parentContent.Content); i += 2 { if parentContent.Content[i].Value == s.key { seqNode := parentContent.Content[i+1] if s.appendToLast { newMapNode := &yaml.Node{ Kind: yaml.MappingNode, Tag: nodeTagMap, } seqNode.Content = append(seqNode.Content, newMapNode) return newMapNode, nil } if s.index < len(seqNode.Content) { return seqNode.Content[s.index], nil } else { return nil, fmt.Errorf("cannot specify %s[%d] because the current length is %d. Use [%s] to append to the sequence instead", s.key, s.index, len(seqNode.Content), seqAppendToLastSymbol) } } } // If the node pair doesn't exist, check if "appendToLast" is specified. // Then, create the sequence node pair and a map node. // After that, return the created map node, since we want to go deeper to upsert the value. if !s.appendToLast { return nil, fmt.Errorf("cannot specify %s[%d] because %s does not exist. Use %s[%s] to append to the sequence instead", s.key, s.index, s.key, s.key, seqAppendToLastSymbol) } newLabelNode := &yaml.Node{ Kind: yaml.ScalarNode, Tag: nodeTagStr, Value: s.key, } parentContent.Content = append(parentContent.Content, newLabelNode) newValNode := &yaml.Node{ Kind: yaml.SequenceNode, Tag: nodeTagSeq, } parentContent.Content = append(parentContent.Content, newValNode) newMapNode := &yaml.Node{ Kind: yaml.MappingNode, Tag: nodeTagMap, } newValNode.Content = append(newValNode.Content, newMapNode) return newMapNode, nil } func (s *seqIdxUpsertNode) upsertValue(content *yaml.Node) error { for i := 0; i < len(content.Content); i += 2 { if content.Content[i].Value == s.key { seqNode := content.Content[i+1] if s.appendToLast { seqNode.Content = append(seqNode.Content, s.valueToInsert) return nil } if s.index < len(seqNode.Content) { seqNode.Content[s.index] = s.valueToInsert return nil } return fmt.Errorf("cannot specify %s[%d] because the current length is %d. Use [%s] to append to the sequence instead", s.key, s.index, len(seqNode.Content), seqAppendToLastSymbol) } } newLabelNode := &yaml.Node{ Kind: yaml.ScalarNode, Tag: nodeTagStr, Value: s.key, } content.Content = append(content.Content, newLabelNode) newValNode := &yaml.Node{ Kind: yaml.SequenceNode, Tag: nodeTagSeq, Content: []*yaml.Node{s.valueToInsert}, } content.Content = append(content.Content, newValNode) return nil }
303
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package override import ( "fmt" "testing" "gopkg.in/yaml.v3" "github.com/stretchr/testify/require" ) func Test_parseRules(t *testing.T) { testCases := map[string]struct { inRules []Rule wantedNodeUpserter func() []nodeUpserter wantedError error }{ "error when empty rule path": { inRules: []Rule{ { Path: "", }, }, wantedError: fmt.Errorf("rule path is empty"), }, "error when invalid rule path with nested sequence": { inRules: []Rule{ { Path: "ContainerDefinition[0][0]", }, }, wantedError: fmt.Errorf("invalid override path segment \"ContainerDefinition[0][0]\": segments must be of the form \"array[0]\", \"array[-]\" or \"key\""), }, "error when invalid rule path with bad sequence index": { inRules: []Rule{ { Path: "ContainerDefinition[0-]", }, }, wantedError: fmt.Errorf("invalid override path segment \"ContainerDefinition[0-]\": segments must be of the form \"array[0]\", \"array[-]\" or \"key\""), }, "success": { inRules: []Rule{ { Path: "ContainerDefinitions[0].Ulimits[-].HardLimit", Value: yaml.Node{ Value: "testNode", }, }, }, wantedNodeUpserter: func() []nodeUpserter { node3 := &mapUpsertNode{ upsertNode: upsertNode{ key: "HardLimit", valueToInsert: &yaml.Node{ Value: "testNode", }, }, } node2 := &seqIdxUpsertNode{ upsertNode: upsertNode{ key: "Ulimits", next: node3, }, appendToLast: true, } node1 := &seqIdxUpsertNode{ upsertNode: upsertNode{ key: "ContainerDefinitions", next: node2, }, index: 0, } return []nodeUpserter{node1} }, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { got, err := parseRules(tc.inRules) if tc.wantedError != nil { require.EqualError(t, err, tc.wantedError.Error()) } else { require.NoError(t, err) require.ElementsMatch(t, tc.wantedNodeUpserter(), got) } }) } }
99
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package templatetest provides test doubles for embedded templates. package templatetest import ( "bytes" "github.com/aws/copilot-cli/internal/pkg/template" ) // Stub stubs template.New and simulates successful read and parse calls. type Stub struct{} // Read returns a dummy template.Content with "data" in it. func (fs Stub) Read(_ string) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // Parse returns a dummy template.Content with "data" in it. func (fs Stub) Parse(_ string, _ interface{}, _ ...template.ParseOption) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseBackendService returns a dummy template.Content with "data" in it. func (fs Stub) ParseBackendService(_ template.WorkloadOpts) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseEnv returns a dummy template.Content with "data" in it. func (fs Stub) ParseEnv(_ *template.EnvOpts) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseEnvBootstrap returns a dummy template.Content with "data" in it. func (fs Stub) ParseEnvBootstrap(data *template.EnvOpts, options ...template.ParseOption) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseLoadBalancedWebService returns a dummy template.Content with "data" in it. func (fs Stub) ParseLoadBalancedWebService(_ template.WorkloadOpts) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseRequestDrivenWebService returns a dummy template.Content with "data" in it. func (fs Stub) ParseRequestDrivenWebService(_ template.WorkloadOpts) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseScheduledJob returns a dummy template.Content with "data" in it. func (fs Stub) ParseScheduledJob(_ template.WorkloadOpts) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseWorkerService returns a dummy template.Content with "data" in it. func (fs Stub) ParseWorkerService(_ template.WorkloadOpts) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil } // ParseStaticSite returns a dummy template.Content with "data" in it. func (fs Stub) ParseStaticSite(_ template.WorkloadOpts) (*template.Content, error) { return &template.Content{ Buffer: bytes.NewBufferString("data"), }, nil }
85
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package color provides functionality to displayed colored text on the terminal. package color import ( "os" "strings" "github.com/AlecAivazis/survey/v2/core" "github.com/fatih/color" ) // Predefined colors. // Refer to https://en.wikipedia.org/wiki/ANSI_escape_code to validate if colors would // be visible on white or black screen backgrounds. var ( Grey = color.New(color.FgWhite) DarkGray = color.New(color.FgBlack) Red = color.New(color.FgHiRed) DullRed = color.New(color.FgRed) Green = color.New(color.FgHiGreen) Yellow = color.New(color.FgHiYellow) Magenta = color.New(color.FgMagenta) Blue = color.New(color.FgHiBlue) DullGreen = color.New(color.FgGreen) DullBlue = color.New(color.FgBlue) HiBlue = color.New(color.FgHiBlue) Cyan = color.New(color.FgCyan) HiCyan = color.New(color.FgHiCyan) Bold = color.New(color.Bold) Faint = color.New(color.Faint) BoldFgYellow = color.New(color.FgYellow).Add(color.Bold) ) const colorEnvVar = "COLOR" var lookupEnv = os.LookupEnv // DisableColorBasedOnEnvVar determines whether the CLI will produce color // output based on the environment variable, COLOR. func DisableColorBasedOnEnvVar() { value, exists := lookupEnv(colorEnvVar) if !exists { // if the COLOR environment variable is not set // then follow the settings in the color library // since it's dynamically set based on the type of terminal // and whether stdout is connected to a terminal or not. core.DisableColor = color.NoColor return } if strings.ToLower(value) == "false" { core.DisableColor = true color.NoColor = true } else if strings.ToLower(value) == "true" { core.DisableColor = false color.NoColor = false } } // Help colors the string to denote that it's auxiliary helpful information, and returns it. func Help(s string) string { return Faint.Sprint(s) } // Emphasize colors the string to denote that it as important, and returns it. func Emphasize(s string) string { return Bold.Sprint(s) } // HighlightUserInput colors the string to denote it as an input from standard input, and returns it. func HighlightUserInput(s string) string { return Emphasize(s) } // HighlightResource colors the string to denote it as a resource created by the CLI, and returns it. func HighlightResource(s string) string { return HiBlue.Sprint(s) } // HighlightCode wraps the string s with the ` character, colors it to denote it's code, and returns it. func HighlightCode(s string) string { return HiCyan.Sprintf("`%s`", s) } // HighlightCodeBlock wraps the string s with ``` characters, colors it to denote it's a multi-line code block, and returns it. func HighlightCodeBlock(s string) string { return HiCyan.Sprintf("```\n%s\n```", s) } // Prod colors the string to mark it is a prod environment. func Prod(s string) string { return BoldFgYellow.Sprint(s) }
99
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package color import ( "testing" "github.com/AlecAivazis/survey/v2/core" "github.com/fatih/color" "github.com/stretchr/testify/require" ) type envVar struct { env map[string]string } func (e *envVar) lookupEnv(key string) (string, bool) { v, ok := e.env[key] return v, ok } func TestColorEnvVarSetToFalse(t *testing.T) { env := &envVar{ env: map[string]string{colorEnvVar: "false"}, } lookupEnv = env.lookupEnv DisableColorBasedOnEnvVar() require.True(t, core.DisableColor, "expected to be true when COLOR is disabled") require.True(t, color.NoColor, "expected to be true when COLOR is disabled") } func TestColorEnvVarSetToTrue(t *testing.T) { env := &envVar{ env: map[string]string{colorEnvVar: "true"}, } lookupEnv = env.lookupEnv DisableColorBasedOnEnvVar() require.False(t, core.DisableColor, "expected to be false when COLOR is enabled") require.False(t, color.NoColor, "expected to be true when COLOR is enabled") } func TestColorEnvVarNotSet(t *testing.T) { env := &envVar{ env: make(map[string]string), } lookupEnv = env.lookupEnv DisableColorBasedOnEnvVar() require.Equal(t, core.DisableColor, color.NoColor, "expected to be the same as color.NoColor") }
57
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package cursor provides functionality to interact with the terminal cursor. package cursor import ( "io" "os" "github.com/AlecAivazis/survey/v2/terminal" ) type cursor interface { Up(n int) Down(n int) Hide() Show() } // fakeFileWriter is a terminal.FileWriter. // If the underlying writer w does not implement Fd() then a dummy value is returned. type fakeFileWriter struct { w io.Writer } // Write delegates to the internal writer. func (w *fakeFileWriter) Write(p []byte) (int, error) { return w.w.Write(p) } // Fd is required to be implemented to satisfy the terminal.FileWriter interface. // If the underlying writer is a file, like os.Stdout, then invoke it. Otherwise, this method allows us to create // a Cursor that can write to any io.Writer like a bytes.Buffer by returning a dummy value. func (w *fakeFileWriter) Fd() uintptr { if v, ok := w.w.(terminal.FileWriter); ok { return v.Fd() } return 0 } // Cursor represents the terminal's cursor. type Cursor struct { c cursor } // New creates a new cursor that writes to stderr. func New() *Cursor { return &Cursor{ c: &terminal.Cursor{ Out: os.Stderr, }, } } // NewWithWriter creates a new cursor that writes to out. func NewWithWriter(out io.Writer) *Cursor { return &Cursor{ c: &terminal.Cursor{ Out: &fakeFileWriter{w: out}, }, } } // Hide makes the cursor invisible. func (c *Cursor) Hide() { c.c.Hide() } // Show makes the cursor visible. func (c *Cursor) Show() { c.c.Show() } // EraseLine deletes the contents of the current line. func (c *Cursor) EraseLine() { if cur, ok := c.c.(*terminal.Cursor); ok { terminal.EraseLine(cur.Out, terminal.ERASE_LINE_ALL) } } // EraseLine erases a line from a FileWriter. func EraseLine(fw terminal.FileWriter) { terminal.EraseLine(fw, terminal.ERASE_LINE_ALL) } // EraseLinesAbove erases a line and moves the cursor up from fw, repeated n times. func EraseLinesAbove(fw terminal.FileWriter, n int) { c := Cursor{ c: &terminal.Cursor{ Out: fw, }, } for i := 0; i < n; i += 1 { EraseLine(fw) c.Up(1) } EraseLine(fw) // Erase the nth line as well. }
100
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cursor import ( "io" "strings" "testing" "github.com/AlecAivazis/survey/v2/terminal" "github.com/stretchr/testify/require" ) // TestEraseLine is POSIX-only since the implementation in the underlying library is completely different on Windows. func TestEraseLine(t *testing.T) { testCases := map[string]struct { inWriter func(writer io.Writer) terminal.FileWriter shouldErase bool }{ "should erase a line if the writer is a file": { inWriter: func(writer io.Writer) terminal.FileWriter { return &fakeFileWriter{w: writer} }, shouldErase: true, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN buf := new(strings.Builder) // WHEN EraseLine(tc.inWriter(buf)) // THEN isErased := buf.String() != "" require.Equal(t, tc.shouldErase, isErased) }) } }
43
copilot-cli
aws
Go
//go:build !windows // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cursor // Up moves the cursor n lines. func (c *Cursor) Up(n int) { c.c.Up(n) } // Down moves the cursor n lines. func (c *Cursor) Down(n int) { c.c.Down(n) }
17
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cursor // Up moves the cursor n lines. func (c *Cursor) Up(n int) { c.c.Down(n) } // Down moves the cursor n lines. func (c *Cursor) Down(n int) { c.c.Up(n) }
15
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package log is a wrapper around the fmt package to print messages to the terminal. package log import ( "fmt" "io" "github.com/fatih/color" ) // Decorated io.Writers around standard error and standard output that work on Windows. var ( DiagnosticWriter = color.Error OutputWriter = color.Output ) // Colored string formatting functions. var ( successSprintf = color.HiGreenString errorSprintf = color.HiRedString warningSprintf = color.YellowString debugSprintf = color.New(color.Faint).Sprintf ) // Log message prefixes. const ( warningPrefix = "Note:" ) // Success prefixes the message with a green "✔ Success!", and writes to standard error. func Success(args ...interface{}) { success(DiagnosticWriter, args...) } // Successln prefixes the message with a green "✔ Success!", and writes to standard error with a new line. func Successln(args ...interface{}) { successln(DiagnosticWriter, args...) } // Successf formats according to the specifier, prefixes the message with a green "✔ Success!", and writes to standard error. func Successf(format string, args ...interface{}) { successf(DiagnosticWriter, format, args...) } // Ssuccess prefixes the message with a green "✔ Success!", and returns it. func Ssuccess(args ...interface{}) string { return fmt.Sprintf("%s %s", successSprintf(successPrefix), fmt.Sprint(args...)) } // Ssuccessln prefixes the message with a green "✔ Success!", appends a new line, and returns it. func Ssuccessln(args ...interface{}) string { msg := fmt.Sprintf("%s %s", successSprintf(successPrefix), fmt.Sprint(args...)) return fmt.Sprintln(msg) } // Ssuccessf formats according to the specifier, prefixes the message with a green "✔ Success!", and returns it. func Ssuccessf(format string, args ...interface{}) string { wrappedFormat := fmt.Sprintf("%s %s", successSprintf(successPrefix), format) return fmt.Sprintf(wrappedFormat, args...) } // Error prefixes the message with a red "✘ Error!", and writes to standard error. func Error(args ...interface{}) { err(DiagnosticWriter, args...) } // Errorln prefixes the message with a red "✘ Error!", and writes to standard error with a new line. func Errorln(args ...interface{}) { errln(DiagnosticWriter, args...) } // Errorf formats according to the specifier, prefixes the message with a red "✘ Error!", and writes to standard error. func Errorf(format string, args ...interface{}) { errf(DiagnosticWriter, format, args...) } // Serror prefixes the message with a red "✘ Error!", and returns it. func Serror(args ...interface{}) string { return fmt.Sprintf("%s %s", errorSprintf(errorPrefix), fmt.Sprint(args...)) } // Serrorln prefixes the message with a red "✘ Error!", appends a new line, and returns it. func Serrorln(args ...interface{}) string { msg := fmt.Sprintf("%s %s", errorSprintf(errorPrefix), fmt.Sprint(args...)) return fmt.Sprintln(msg) } // Serrorf formats according to the specifier, prefixes the message with a red "✘ Error!", and returns it. func Serrorf(format string, args ...interface{}) string { wrappedFormat := fmt.Sprintf("%s %s", errorSprintf(errorPrefix), format) return fmt.Sprintf(wrappedFormat, args...) } // Warning prefixes the message with a "Note:", colors the *entire* message in yellow, writes to standard error. func Warning(args ...interface{}) { warning(DiagnosticWriter, args...) } // Warningln prefixes the message with a "Note:", colors the *entire* message in yellow, writes to standard error with a new line. func Warningln(args ...interface{}) { warningln(DiagnosticWriter, args...) } // Warningf formats according to the specifier, prefixes the message with a "Note:", colors the *entire* message in yellow, and writes to standard error. func Warningf(format string, args ...interface{}) { warningf(DiagnosticWriter, format, args...) } // Info writes the message to standard error with the default color. func Info(args ...interface{}) { info(DiagnosticWriter, args...) } // Infoln writes the message to standard error with the default color and new line. func Infoln(args ...interface{}) { infoln(DiagnosticWriter, args...) } // Infof formats according to the specifier, and writes to standard error with the default color. func Infof(format string, args ...interface{}) { infof(DiagnosticWriter, format, args...) } // Debug writes the message to standard error in grey. func Debug(args ...interface{}) { debug(DiagnosticWriter, args...) } // Debugln writes the message to standard error in grey and with a new line. func Debugln(args ...interface{}) { debugln(DiagnosticWriter, args...) } // Debugf formats according to the specifier, colors the message in grey, and writes to standard error. func Debugf(format string, args ...interface{}) { debugf(DiagnosticWriter, format, args...) } func success(w io.Writer, args ...interface{}) { msg := fmt.Sprintf("%s %s", successSprintf(successPrefix), fmt.Sprint(args...)) fmt.Fprint(w, msg) } func successln(w io.Writer, args ...interface{}) { msg := fmt.Sprintf("%s %s", successSprintf(successPrefix), fmt.Sprint(args...)) fmt.Fprintln(w, msg) } func successf(w io.Writer, format string, args ...interface{}) { wrappedFormat := fmt.Sprintf("%s %s", successSprintf(successPrefix), format) fmt.Fprintf(w, wrappedFormat, args...) } func err(w io.Writer, args ...interface{}) { msg := fmt.Sprintf("%s %s", errorSprintf(errorPrefix), fmt.Sprint(args...)) fmt.Fprint(w, msg) } func errln(w io.Writer, args ...interface{}) { msg := fmt.Sprintf("%s %s", errorSprintf(errorPrefix), fmt.Sprint(args...)) fmt.Fprintln(w, msg) } func errf(w io.Writer, format string, args ...interface{}) { wrappedFormat := fmt.Sprintf("%s %s", errorSprintf(errorPrefix), format) fmt.Fprintf(w, wrappedFormat, args...) } func warning(w io.Writer, args ...interface{}) { msg := fmt.Sprint(args...) fmt.Fprint(w, warningSprintf(fmt.Sprintf("%s %s", warningPrefix, msg))) } func warningln(w io.Writer, args ...interface{}) { msg := fmt.Sprint(args...) fmt.Fprintln(w, warningSprintf(fmt.Sprintf("%s %s", warningPrefix, msg))) } func warningf(w io.Writer, format string, args ...interface{}) { wrappedFormat := fmt.Sprintf("%s %s", warningPrefix, format) fmt.Fprint(w, warningSprintf(wrappedFormat, args...)) } func info(w io.Writer, args ...interface{}) { fmt.Fprint(w, args...) } func infoln(w io.Writer, args ...interface{}) { fmt.Fprintln(w, args...) } func infof(w io.Writer, format string, args ...interface{}) { fmt.Fprintf(w, format, args...) } func debug(w io.Writer, args ...interface{}) { fmt.Fprint(w, debugSprintf(fmt.Sprint(args...))) } func debugln(w io.Writer, args ...interface{}) { fmt.Fprintln(w, debugSprintf(fmt.Sprint(args...))) } func debugf(w io.Writer, format string, args ...interface{}) { fmt.Fprint(w, debugSprintf(format, args...)) }
210
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package log import ( "io" ) // Logger represents a logging object that writes to an io.Writer lines of outputs. type Logger struct { w io.Writer } // New creates a new Logger. func New(w io.Writer) *Logger { return &Logger{ w: w, } } // Success writes args prefixed with a "✔ Success!". func (l *Logger) Success(args ...interface{}) { success(l.w, args...) } // Successln writes args prefixed with a "✔ Success!" and a new line. func (l *Logger) Successln(args ...interface{}) { successln(l.w, args...) } // Successf formats according to the specifier, prefixes the message with a "✔ Success!", and writes it. func (l *Logger) Successf(format string, args ...interface{}) { successf(l.w, format, args...) } // Error writes args prefixed with "✘ Error!". func (l *Logger) Error(args ...interface{}) { err(l.w, args...) } // Errorln writes args prefixed with a "✘ Error!" and a new line. func (l *Logger) Errorln(args ...interface{}) { errln(l.w, args...) } // Errorf formats according to the specifier, prefixes the message with a "✘ Error!", and writes it. func (l *Logger) Errorf(format string, args ...interface{}) { errf(l.w, format, args...) } // Warning writes args prefixed with "Note:". func (l *Logger) Warning(args ...interface{}) { warning(l.w, args...) } // Warningln writes args prefixed with a "Note:" and a new line. func (l *Logger) Warningln(args ...interface{}) { warningln(l.w, args...) } // Warningf formats according to the specifier, prefixes the message with a "Note:", and writes it. func (l *Logger) Warningf(format string, args ...interface{}) { warningf(l.w, format, args...) } // Info writes the message. func (l *Logger) Info(args ...interface{}) { info(l.w, args...) } // Infoln writes the message with a new line. func (l *Logger) Infoln(args ...interface{}) { infoln(l.w, args...) } // Infof formats according to the specifier, and writes the message. func (l *Logger) Infof(format string, args ...interface{}) { infof(l.w, format, args...) } // Debug writes the message. func (l *Logger) Debug(args ...interface{}) { debug(l.w, args...) } // Debugln writes the message and with a new line. func (l *Logger) Debugln(args ...interface{}) { debugln(l.w, args...) } // Debugf formats according to the specifier, and writes the message. func (l *Logger) Debugf(format string, args ...interface{}) { debugf(l.w, format, args...) }
96
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package log import ( "fmt" "strings" "testing" "github.com/stretchr/testify/require" ) func TestLogger_Success(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Success("hello", " world") // THEN require.Equal(t, b.String(), fmt.Sprintf("%s hello world", successPrefix)) } func TestLogger_Successln(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Successln("hello", " world") // THEN require.Equal(t, b.String(), fmt.Sprintf("%s hello world\n", successPrefix)) } func TestLogger_Successf(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Successf("%s %s\n", "hello", "world") // THEN require.Equal(t, b.String(), fmt.Sprintf("%s hello world\n", successPrefix)) } func TestLogger_Error(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Error("hello", " world") // THEN require.Contains(t, b.String(), fmt.Sprintf("%s hello world", errorPrefix)) } func TestLogger_Errorln(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Errorln("hello", " world") // THEN require.Contains(t, b.String(), fmt.Sprintf("%s hello world\n", errorPrefix)) } func TestLogger_Errorf(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Errorf("%s %s\n", "hello", "world") // THEN require.Contains(t, b.String(), fmt.Sprintf("%s hello world\n", errorPrefix)) } func TestLogger_Warning(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Warning("hello", " world") // THEN require.Contains(t, b.String(), "Note:") require.Contains(t, b.String(), "hello world") } func TestLogger_Warningln(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Warningln("hello", " world") // THEN require.Contains(t, b.String(), "Note:") require.Contains(t, b.String(), "hello world\n") } func TestLogger_Warningf(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Warningf("%s %s\n", "hello", "world") // THEN require.Contains(t, b.String(), "Note:") require.Contains(t, b.String(), "hello world\n") } func TestLogger_Info(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Info("hello", " world") // THEN require.Equal(t, "hello world", b.String()) } func TestLogger_Infoln(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Infoln("hello", "world") // THEN require.Equal(t, "hello world\n", b.String()) } func TestLogger_Infof(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Infof("%s %s\n", "hello", "world") // THEN require.Equal(t, "hello world\n", b.String()) } func TestLogger_Debug(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Debug("hello", " world") // THEN require.Contains(t, b.String(), "hello world") } func TestLogger_Debugln(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Debugln("hello", " world") // THEN require.Contains(t, b.String(), "hello world\n") } func TestLogger_Debugf(t *testing.T) { // GIVEN b := &strings.Builder{} logger := New(b) // WHEN logger.Debugf("%s %s\n", "hello", "world") // THEN require.Contains(t, b.String(), "hello world\n") }
196
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package log import ( "fmt" "strings" "testing" "github.com/stretchr/testify/require" ) func TestSuccess(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Success("hello", " world") // THEN require.Equal(t, b.String(), fmt.Sprintf("%s hello world", successPrefix)) } func TestSuccessln(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Successln("hello", " world") // THEN require.Equal(t, b.String(), fmt.Sprintf("%s hello world\n", successPrefix)) } func TestSuccessf(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Successf("%s %s\n", "hello", "world") // THEN require.Equal(t, b.String(), fmt.Sprintf("%s hello world\n", successPrefix)) } func TestSsuccess(t *testing.T) { s := Ssuccess("hello", " world") require.Equal(t, s, fmt.Sprintf("%s hello world", successPrefix)) } func TestSsuccessln(t *testing.T) { s := Ssuccessln("hello", " world") // THEN require.Equal(t, s, fmt.Sprintf("%s hello world\n", successPrefix)) } func TestSsuccessf(t *testing.T) { s := Ssuccessf("%s %s\n", "hello", "world") require.Equal(t, s, fmt.Sprintf("%s hello world\n", successPrefix)) } func TestError(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Error("hello", " world") // THEN require.Contains(t, b.String(), fmt.Sprintf("%s hello world", errorPrefix)) } func TestErrorln(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Errorln("hello", " world") // THEN require.Contains(t, b.String(), fmt.Sprintf("%s hello world\n", errorPrefix)) } func TestErrorf(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Errorf("%s %s\n", "hello", "world") // THEN require.Contains(t, b.String(), fmt.Sprintf("%s hello world\n", errorPrefix)) } func TestSerror(t *testing.T) { s := Serror("hello", " world") require.Contains(t, s, fmt.Sprintf("%s hello world", errorPrefix)) } func TestSerrorln(t *testing.T) { s := Serrorln("hello", " world") require.Contains(t, s, fmt.Sprintf("%s hello world\n", errorPrefix)) } func TestSerrorf(t *testing.T) { s := Serrorf("%s %s\n", "hello", "world") require.Contains(t, s, fmt.Sprintf("%s hello world\n", errorPrefix)) } func TestWarning(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Warning("hello", " world") // THEN require.Contains(t, b.String(), "Note:") require.Contains(t, b.String(), "hello world") } func TestWarningln(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Warningln("hello", " world") // THEN require.Contains(t, b.String(), "Note:") require.Contains(t, b.String(), "hello world\n") } func TestWarningf(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Warningf("%s %s\n", "hello", "world") // THEN require.Contains(t, b.String(), "Note:") require.Contains(t, b.String(), "hello world\n") } func TestInfo(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Info("hello", " world") // THEN require.Equal(t, "hello world", b.String()) } func TestInfoln(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Infoln("hello", "world") // THEN require.Equal(t, "hello world\n", b.String()) } func TestInfof(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Infof("%s %s\n", "hello", "world") // THEN require.Equal(t, "hello world\n", b.String()) } func TestDebug(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Debug("hello", " world") // THEN require.Contains(t, b.String(), "hello world") } func TestDebugln(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Debugln("hello", " world") // THEN require.Contains(t, b.String(), "hello world\n") } func TestDebugf(t *testing.T) { // GIVEN b := &strings.Builder{} DiagnosticWriter = b // WHEN Debugf("%s %s\n", "hello", "world") // THEN require.Contains(t, b.String(), "hello world\n") }
233
copilot-cli
aws
Go
//go:build !windows // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package log // Log message prefixes. const ( successPrefix = "✔" errorPrefix = "✘" )
13
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package log const ( successPrefix = "√" errorPrefix = "X" )
10
copilot-cli
aws
Go
//go:build !windows // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( spin "github.com/briandowns/spinner" ) var charset = spin.CharSets[14]
13
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress var charset = []string{"/", "-", "\\"}
7
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "bytes" "context" "fmt" "io" "strings" "sync" "time" "github.com/aws/copilot-cli/internal/pkg/aws/cloudformation" "github.com/aws/copilot-cli/internal/pkg/stream" "golang.org/x/sync/errgroup" ) // StackSubscriber is the interface to subscribe to a CloudFormation stack event stream. type StackSubscriber interface { Subscribe() <-chan stream.StackEvent } // StackSetSubscriber is the interface to subscribe channels to a CloudFormation stack set event stream. type StackSetSubscriber interface { Subscribe() <-chan stream.StackSetOpEvent } // ResourceRendererOpts is optional configuration for a listening CloudFormation resource renderer. type ResourceRendererOpts struct { StartEvent *stream.StackEvent // Specify the starting event for the resource instead of "[not started]". RenderOpts RenderOptions } // ECSServiceRendererCfg holds required configuration for initializing an ECS service renderer. type ECSServiceRendererCfg struct { Streamer StackSubscriber ECSClient stream.ECSServiceDescriber CWClient stream.CloudWatchDescriber LogicalID string Description string } // ECSServiceRendererOpts holds optional configuration for a listening ECS service renderer. type ECSServiceRendererOpts struct { Group *errgroup.Group Ctx context.Context RenderOpts RenderOptions } // ListeningChangeSetRenderer returns a component that listens for CloudFormation // resource events from a stack mutated with a changeSet until the streamer stops. func ListeningChangeSetRenderer(streamer StackSubscriber, stackName, description string, changes []Renderer, opts RenderOptions) DynamicRenderer { return &dynamicTreeComponent{ Root: ListeningResourceRenderer(streamer, stackName, description, ResourceRendererOpts{ RenderOpts: opts, }), Children: changes, } } // ListeningStackRenderer returns a component that listens for CloudFormation resource events // from a stack mutated with CreateStack or UpdateStack until the stack is completed. func ListeningStackRenderer(streamer StackSubscriber, stackName, description string, resourceDescriptions map[string]string, opts RenderOptions) DynamicRenderer { return listeningStackComponent(streamer, stackName, description, resourceDescriptions, opts) } // ListeningStackSetRenderer renders a component that listens for CloudFormation stack set events until the streamer stops. func ListeningStackSetRenderer(streamer StackSetSubscriber, title string, opts RenderOptions) DynamicRenderer { comp := &stackSetComponent{ stream: streamer.Subscribe(), done: make(chan struct{}), style: opts, title: title, separator: '\t', statuses: []cfnStatus{notStartedStackStatus}, stopWatch: newStopWatch(), } go comp.Listen() return comp } // ListeningResourceRenderer returns a tab-separated component that listens for // CloudFormation stack events for a particular resource. func ListeningResourceRenderer(streamer StackSubscriber, logicalID, description string, opts ResourceRendererOpts) DynamicRenderer { return listeningResourceComponent(streamer, logicalID, description, opts) } // ListeningECSServiceResourceRenderer is a ListeningResourceRenderer for the ECS service cloudformation resource // and a ListeningRollingUpdateRenderer to render deployments. func ListeningECSServiceResourceRenderer(cfg ECSServiceRendererCfg, opts ECSServiceRendererOpts) DynamicRenderer { g := new(errgroup.Group) ctx := context.Background() if opts.Group != nil { g = opts.Group } if opts.Ctx != nil { ctx = opts.Ctx } comp := &ecsServiceResourceComponent{ cfnStream: cfg.Streamer.Subscribe(), ecsDescriber: cfg.ECSClient, cwDescriber: cfg.CWClient, logicalID: cfg.LogicalID, group: g, ctx: ctx, renderOpts: opts.RenderOpts, resourceRenderer: ListeningResourceRenderer(cfg.Streamer, cfg.LogicalID, cfg.Description, ResourceRendererOpts{ RenderOpts: opts.RenderOpts, }), done: make(chan struct{}), } comp.newDeploymentRender = comp.newListeningRollingUpdateRenderer go comp.Listen() return comp } // regularResourceComponent can display a simple CloudFormation stack resource event. type regularResourceComponent struct { logicalID string // The LogicalID defined in the template for the resource. description string // The human friendly explanation of the resource. statuses []cfnStatus // In-order history of the CloudFormation status of the resource throughout the deployment. stopWatch *stopWatch // Timer to measure how long the operation takes to complete. padding int // Leading spaces before rendering the resource. separator rune // Character used to separate columns of text. stream <-chan stream.StackEvent done chan struct{} mu sync.Mutex } func listeningResourceComponent(streamer StackSubscriber, logicalID, description string, opts ResourceRendererOpts) *regularResourceComponent { comp := &regularResourceComponent{ logicalID: logicalID, description: description, statuses: []cfnStatus{notStartedStackStatus}, stopWatch: newStopWatch(), stream: streamer.Subscribe(), done: make(chan struct{}), padding: opts.RenderOpts.Padding, separator: '\t', } if startEvent := opts.StartEvent; startEvent != nil { updateComponentStatus(&comp.mu, &comp.statuses, cfnStatus{ value: cloudformation.StackStatus(startEvent.ResourceStatus), reason: startEvent.ResourceStatusReason, }) updateComponentTimer(&comp.mu, comp.statuses, comp.stopWatch) } go comp.Listen() return comp } // Listen updates the resource's status if a CloudFormation stack resource event is received. func (c *regularResourceComponent) Listen() { for ev := range c.stream { if c.logicalID != ev.LogicalResourceID { continue } updateComponentStatus(&c.mu, &c.statuses, cfnStatus{ value: cloudformation.StackStatus(ev.ResourceStatus), reason: ev.ResourceStatusReason, }) updateComponentTimer(&c.mu, c.statuses, c.stopWatch) } close(c.done) // No more events will be processed. } // Render prints the resource as a singleLineComponent and returns the number of lines written and the error if any. func (c *regularResourceComponent) Render(out io.Writer) (numLines int, err error) { c.mu.Lock() defer c.mu.Unlock() components := cfnLineItemComponents(c.description, c.separator, c.statuses, c.stopWatch, c.padding) return renderComponents(out, components) } // Done returns a channel that's closed when there are no more events to Listen. func (c *regularResourceComponent) Done() <-chan struct{} { return c.done } // stackComponent is a DynamicRenderer that can display CloudFormation stack events as they stream in. type stackComponent struct { // Required inputs. cfnStream <-chan stream.StackEvent stack StackSubscriber resourceDescriptions map[string]string // Optional inputs. renderOpts RenderOptions // Sub-components. resources []Renderer seenResources map[string]bool done chan struct{} mu sync.Mutex // Replaced in tests. addRenderer func(stream.StackEvent, string) } func listeningStackComponent(streamer StackSubscriber, stackName, description string, resourceDescriptions map[string]string, opts RenderOptions) *stackComponent { comp := &stackComponent{ cfnStream: streamer.Subscribe(), stack: streamer, resourceDescriptions: resourceDescriptions, renderOpts: opts, resources: []Renderer{ // Add the stack as a resource to track. ListeningResourceRenderer(streamer, stackName, description, ResourceRendererOpts{ RenderOpts: opts, }), }, seenResources: map[string]bool{ stackName: true, }, done: make(chan struct{}), } comp.addRenderer = comp.addResourceRenderer go comp.Listen() return comp } // Listen consumes stack events from the stream. // On new resource events, if the resource's LogicalID has a description // then the resource is added to the list of sub-components to render. func (c *stackComponent) Listen() { for ev := range c.cfnStream { logicalID := ev.LogicalResourceID if _, ok := c.seenResources[logicalID]; ok { continue } c.seenResources[logicalID] = true description, ok := c.resourceDescriptions[logicalID] if !ok { continue } c.addRenderer(ev, description) } // Close the done channel once all the renderers are done listening. for _, r := range c.resources { if dr, ok := r.(DynamicRenderer); ok { <-dr.Done() } } close(c.done) } // Render renders all resources in the stack to out. func (c *stackComponent) Render(out io.Writer) (numLines int, err error) { c.mu.Lock() defer c.mu.Unlock() return renderComponents(out, c.resources) } // Done returns a channel that's closed when there are no more events to Listen. func (c *stackComponent) Done() <-chan struct{} { return c.done } func (c *stackComponent) addResourceRenderer(ev stream.StackEvent, description string) { c.mu.Lock() defer c.mu.Unlock() opts := ResourceRendererOpts{ StartEvent: &ev, RenderOpts: NestedRenderOptions(c.renderOpts), } c.resources = append(c.resources, ListeningResourceRenderer(c.stack, ev.LogicalResourceID, description, opts)) } // stackSetComponent is a DynamicRenderer that can display stack set operation events. type stackSetComponent struct { stream <-chan stream.StackSetOpEvent done chan struct{} style RenderOptions title string separator rune mu sync.Mutex statuses []cfnStatus stopWatch *stopWatch } // Listen consumes stack set operation events and updates the status until the streamer closes the channel. func (c *stackSetComponent) Listen() { for ev := range c.stream { updateComponentStatus(&c.mu, &c.statuses, cfnStatus{ value: ev.Operation.Status, reason: ev.Operation.Reason, }) updateComponentTimer(&c.mu, c.statuses, c.stopWatch) } close(c.done) } // Render renders the stack set status updates to out and returns the total number of lines written and error if any. func (c *stackSetComponent) Render(out io.Writer) (int, error) { c.mu.Lock() defer c.mu.Unlock() components := cfnLineItemComponents(c.title, c.separator, c.statuses, c.stopWatch, c.style.Padding) return renderComponents(out, components) } // Done returns a channel that's closed when there are no more events to Listen. func (c *stackSetComponent) Done() <-chan struct{} { return c.done } // ecsServiceResourceComponent can display an ECS service created with CloudFormation. type ecsServiceResourceComponent struct { // Required inputs. cfnStream <-chan stream.StackEvent // Subscribed stream to initialize the deploymentRenderer. ecsDescriber stream.ECSServiceDescriber // Client needed to create an ECSDeploymentStreamer. cwDescriber stream.CloudWatchDescriber // Client needed to create a CloudwatchAlarmStreamer. logicalID string // LogicalID for the service. // Optional inputs. group *errgroup.Group // Existing group to catch ECSDeploymentStreamer errors. ctx context.Context // Context for the ECSDeploymentStreamer. renderOpts RenderOptions // Sub-components. resourceRenderer DynamicRenderer deploymentRenderer Renderer done chan struct{} mu sync.Mutex newDeploymentRender func(string, time.Time) DynamicRenderer // Overriden in tests. } // Listen creates deploymentRenderers if the service is being created, or updated. // It closes the Done channel if the CFN resource is Done and the deploymentRenderers are also Done. func (c *ecsServiceResourceComponent) Listen() { renderers := []DynamicRenderer{c.resourceRenderer} for ev := range c.cfnStream { if c.logicalID != ev.LogicalResourceID { continue } if cloudformation.StackStatus(ev.ResourceStatus).UpsertInProgress() { if ev.PhysicalResourceID == "" { // New service creates receive two "CREATE_IN_PROGRESS" events. // The first event doesn't have a service name yet, the second one has. continue } // Start a deployment renderer if a service deployment is happening. renderer := c.newDeploymentRender(ev.PhysicalResourceID, ev.Timestamp) c.mu.Lock() c.deploymentRenderer = renderer c.mu.Unlock() renderers = append(renderers, renderer) } } // Close the done channel once all the renderers are done listening. for _, r := range renderers { <-r.Done() } close(c.done) } // Render writes the status of the CloudFormation ECS service resource, followed with details around the // service deployment if a deployment is happening. func (c *ecsServiceResourceComponent) Render(out io.Writer) (numLines int, err error) { c.mu.Lock() defer c.mu.Unlock() buf := new(bytes.Buffer) nl, err := c.resourceRenderer.Render(buf) if err != nil { return 0, err } numLines += nl var deploymentRenderer Renderer = &noopComponent{} if c.deploymentRenderer != nil { deploymentRenderer = c.deploymentRenderer } sw := &suffixWriter{ buf: buf, suffix: []byte{'\t', '\t'}, // Add two columns to the deployment renderer so that it aligns with resources. } nl, err = deploymentRenderer.Render(sw) if err != nil { return 0, err } numLines += nl if _, err = buf.WriteTo(out); err != nil { return 0, err } return numLines, nil } // Done returns a channel that's closed when there are no more events to Listen. func (c *ecsServiceResourceComponent) Done() <-chan struct{} { return c.done } func (c *ecsServiceResourceComponent) newListeningRollingUpdateRenderer(serviceARN string, startTime time.Time) DynamicRenderer { cluster, service := parseServiceARN(serviceARN) streamer := stream.NewECSDeploymentStreamer(c.ecsDescriber, c.cwDescriber, cluster, service, startTime) renderer := ListeningRollingUpdateRenderer(streamer, NestedRenderOptions(c.renderOpts)) c.group.Go(func() error { return stream.Stream(c.ctx, streamer) }) return renderer } func updateComponentStatus(mu *sync.Mutex, statuses *[]cfnStatus, newStatus cfnStatus) { mu.Lock() defer mu.Unlock() *statuses = append(*statuses, newStatus) } func updateComponentTimer(mu *sync.Mutex, statuses []cfnStatus, sw *stopWatch) { mu.Lock() defer mu.Unlock() // There is always at least two elements {notStartedStatus, <new event>} curStatus, nextStatus := statuses[len(statuses)-2], statuses[len(statuses)-1] switch { case nextStatus.value.InProgress(): // It's possible that CloudFormation sends multiple "CREATE_IN_PROGRESS" events back to back, // we don't want to reset the timer then. if curStatus.value.InProgress() { return } sw.reset() sw.start() default: if curStatus == notStartedStackStatus { // The resource went from [not started] to a finished state immediately. // So start the timer and then immediately finish it. sw.start() } sw.stop() } } func cfnLineItemComponents(description string, separator rune, statuses []cfnStatus, sw *stopWatch, padding int) []Renderer { columns := []string{fmt.Sprintf("- %s", description), prettifyLatestStackStatus(statuses), prettifyElapsedTime(sw)} components := []Renderer{ &singleLineComponent{ Text: strings.Join(columns, string(separator)), Padding: padding, }, } for _, failureReason := range failureReasons(statuses) { for _, text := range splitByLength(failureReason, maxCellLength) { components = append(components, &singleLineComponent{ Text: strings.Join([]string{colorFailureReason(text), "", ""}, string(separator)), Padding: padding + nestedComponentPadding, }) } } return components }
470
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "context" "strings" "testing" "time" "github.com/aws/copilot-cli/internal/pkg/aws/cloudformation/stackset" "github.com/aws/copilot-cli/internal/pkg/aws/cloudformation" "github.com/aws/copilot-cli/internal/pkg/stream" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" ) var ( testDate = time.Date(2021, 1, 6, 0, 0, 0, 0, time.UTC) ) type fakeClock struct { index int wantedValues []time.Time numCalls int } func (c *fakeClock) now() time.Time { t := c.wantedValues[c.index%len(c.wantedValues)] c.index += 1 c.numCalls += 1 return t } func TestStackComponent_Listen(t *testing.T) { // GIVEN ch := make(chan stream.StackEvent) done := make(chan struct{}) wantedRenderers := []Renderer{ &mockDynamicRenderer{ content: "load balancer", }, &mockDynamicRenderer{ content: "fancy role", }, } var actualRenderers []Renderer comp := &stackComponent{ cfnStream: ch, resourceDescriptions: map[string]string{ "ALB": "load balancer", "Role": "fancy role", }, seenResources: map[string]bool{}, done: done, addRenderer: func(event stream.StackEvent, _ string) { if event.LogicalResourceID == "ALB" { actualRenderers = append(actualRenderers, wantedRenderers[0]) } else { actualRenderers = append(actualRenderers, wantedRenderers[1]) } }, } // WHEN go comp.Listen() go func() { ch <- stream.StackEvent{ LogicalResourceID: "ALB", ResourceStatus: "CREATE_IN_PROGRESS", } ch <- stream.StackEvent{ LogicalResourceID: "Role", ResourceStatus: "CREATE_IN_PROGRESS", } // Should not create another renderer. ch <- stream.StackEvent{ LogicalResourceID: "ALB", ResourceStatus: "CREATE_COMPLETE", } // Should not create another renderer. ch <- stream.StackEvent{ LogicalResourceID: "Role", ResourceStatus: "CREATE_COMPLETE", } close(ch) }() // THEN <-done require.Equal(t, wantedRenderers, actualRenderers) } func TestStackComponent_Render(t *testing.T) { // GIVEN comp := &stackComponent{ resources: []Renderer{ &mockDynamicRenderer{content: "hello\n"}, &mockDynamicRenderer{content: "world\n"}, }, } buf := new(strings.Builder) // WHEN nl, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 2, nl, "expected a line for each renderer") require.Equal(t, `hello world `, buf.String(), "expected each renderer to be rendered") } func TestStackSetComponent_Listen(t *testing.T) { t.Run("should update statuses and timer when an operation event is received", func(t *testing.T) { // GIVEN ch := make(chan stream.StackSetOpEvent) done := make(chan struct{}) clock := &fakeClock{ wantedValues: []time.Time{testDate, testDate.Add(10 * time.Second)}, } r := &stackSetComponent{ stream: ch, done: done, statuses: []cfnStatus{notStartedStackStatus}, stopWatch: &stopWatch{ clock: clock, }, } // WHEN go r.Listen() go func() { // emulate the streamer. ch <- stream.StackSetOpEvent{ Operation: stackset.Operation{ Status: "RUNNING", }, } ch <- stream.StackSetOpEvent{ Operation: stackset.Operation{ Status: "SUCCEEDED", }, } close(ch) }() // THEN <-r.Done() require.ElementsMatch(t, []cfnStatus{ notStartedStackStatus, { value: stackset.OpStatus("RUNNING"), }, { value: stackset.OpStatus("SUCCEEDED"), }, }, r.statuses) _, hasStarted := r.stopWatch.elapsed() require.True(t, hasStarted, "the stopwatch should have started") }) } func TestStackSetComponent_Render(t *testing.T) { t.Run("renders a stack set operation that succeeded", func(t *testing.T) { // GIVEN r := &stackSetComponent{ title: "Update stack set demo-infrastructure", statuses: []cfnStatus{ notStartedStackStatus, { value: stackset.OpStatus("SUCCEEDED"), }, }, stopWatch: &stopWatch{ startTime: testDate, stopTime: testDate.Add(1*time.Minute + 10*time.Second + 100*time.Millisecond), started: true, stopped: true, }, separator: '\t', } buf := new(strings.Builder) // WHEN nl, err := r.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 1, nl, "expected to be rendered as a single line component") require.Equal(t, "- Update stack set demo-infrastructure\t[succeeded]\t[70.1s]\n", buf.String()) }) t.Run("renders a stack set operation that failed", func(t *testing.T) { // GIVEN r := &stackSetComponent{ title: "Update stack set demo-infrastructure", statuses: []cfnStatus{ notStartedStackStatus, { value: stackset.OpStatus("RUNNING"), }, { value: stackset.OpStatus("FAILED"), reason: "The Operation 1 has failed to create", }, }, stopWatch: &stopWatch{ startTime: testDate, stopTime: testDate, started: true, stopped: true, }, separator: '\t', } buf := new(strings.Builder) // WHEN nl, err := r.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 2, nl, "expected 2 entries to be printed to the terminal") require.Equal(t, "- Update stack set demo-infrastructure\t[failed]\t[0.0s]\n"+ " The Operation 1 has failed to create\t\t\n", buf.String()) }) } func TestRegularResourceComponent_Listen(t *testing.T) { t.Run("should not add status if no events are received for the logical ID", func(t *testing.T) { // GIVEN ch := make(chan stream.StackEvent) done := make(chan struct{}) comp := &regularResourceComponent{ logicalID: "EnvironmentManagerRole", statuses: []cfnStatus{notStartedStackStatus}, stopWatch: &stopWatch{ clock: &fakeClock{ wantedValues: []time.Time{testDate}, }, }, stream: ch, done: done, } // WHEN go comp.Listen() go func() { ch <- stream.StackEvent{ LogicalResourceID: "ServiceDiscoveryNamespace", ResourceStatus: "CREATE_COMPLETE", } close(ch) // Close to notify that no more events will be sent. }() // THEN <-done // Wait for listen to exit. require.ElementsMatch(t, []cfnStatus{notStartedStackStatus}, comp.statuses) _, hasStarted := comp.stopWatch.elapsed() require.False(t, hasStarted, "the stopwatch should not have started") }) t.Run("should add status when an event is received for the resource", func(t *testing.T) { // GIVEN ch := make(chan stream.StackEvent) done := make(chan struct{}) comp := &regularResourceComponent{ logicalID: "EnvironmentManagerRole", statuses: []cfnStatus{notStartedStackStatus}, stopWatch: &stopWatch{ clock: &fakeClock{ wantedValues: []time.Time{testDate}, }, }, stream: ch, done: done, } // WHEN go comp.Listen() go func() { ch <- stream.StackEvent{ LogicalResourceID: "EnvironmentManagerRole", ResourceStatus: "CREATE_FAILED", ResourceStatusReason: "This IAM role already exists.", } ch <- stream.StackEvent{ LogicalResourceID: "phonetool-test", ResourceStatus: "ROLLBACK_COMPLETE", } close(ch) // Close to notify that no more events will be sent. }() // THEN <-done // Wait for listen to exit. require.ElementsMatch(t, []cfnStatus{ notStartedStackStatus, { value: cloudformation.StackStatus("CREATE_FAILED"), reason: "This IAM role already exists.", }, }, comp.statuses) elapsed, hasStarted := comp.stopWatch.elapsed() require.True(t, hasStarted, "the stopwatch should have started when an event was received") require.Equal(t, time.Duration(0), elapsed) }) t.Run("should keep timer running if multiple in progress events are received", func(t *testing.T) { // GIVEN ch := make(chan stream.StackEvent) done := make(chan struct{}) fc := &fakeClock{ wantedValues: []time.Time{testDate, testDate.Add(10 * time.Second)}, } comp := &regularResourceComponent{ logicalID: "EnvironmentManagerRole", statuses: []cfnStatus{notStartedStackStatus}, stopWatch: &stopWatch{ clock: fc, }, stream: ch, done: done, } // WHEN go comp.Listen() go func() { ch <- stream.StackEvent{ LogicalResourceID: "EnvironmentManagerRole", ResourceStatus: "CREATE_IN_PROGRESS", } ch <- stream.StackEvent{ LogicalResourceID: "EnvironmentManagerRole", ResourceStatus: "CREATE_IN_PROGRESS", } close(ch) // Close to notify that no more events will be sent. }() // THEN <-done // Wait for listen to exit. _, hasStarted := comp.stopWatch.elapsed() require.True(t, hasStarted, "the stopwatch should have started when an event was received") require.Equal(t, 2, fc.numCalls, "stop watch should retrieve the current time only twice, start should not be called twice") }) } func TestRegularResourceComponent_Render(t *testing.T) { t.Run("renders a resource that was created succesfully immediately", func(t *testing.T) { // GIVEN comp := &regularResourceComponent{ description: "An ECS cluster to hold your services", statuses: []cfnStatus{ notStartedStackStatus, { value: cloudformation.StackStatus("CREATE_COMPLETE"), }, }, stopWatch: &stopWatch{ startTime: testDate, stopTime: testDate.Add(1*time.Minute + 10*time.Second + 100*time.Millisecond), started: true, stopped: true, }, separator: '\t', } buf := new(strings.Builder) // WHEN nl, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 1, nl, "expected to be rendered as a single line component") require.Equal(t, "- An ECS cluster to hold your services\t[create complete]\t[70.1s]\n", buf.String()) }) t.Run("renders a resource that is in progress", func(t *testing.T) { // GIVEN comp := &regularResourceComponent{ description: "An ECS cluster to hold your services", statuses: []cfnStatus{ notStartedStackStatus, { value: cloudformation.StackStatus("CREATE_IN_PROGRESS"), }, }, stopWatch: &stopWatch{ startTime: testDate, started: true, clock: &fakeClock{ wantedValues: []time.Time{testDate.Add(10 * time.Second)}, }, }, separator: '\t', } buf := new(strings.Builder) // WHEN nl, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 1, nl, "expected to be rendered as a single line component") require.Equal(t, "- An ECS cluster to hold your services\t[create in progress]\t[10.0s]\n", buf.String()) }) t.Run("splits long failure reason into multiple lines", func(t *testing.T) { // GIVEN comp := &regularResourceComponent{ description: `The environment stack "phonetool-test" contains your shared resources between services`, statuses: []cfnStatus{ notStartedStackStatus, { value: cloudformation.StackStatus("CREATE_IN_PROGRESS"), }, { value: cloudformation.StackStatus("CREATE_FAILED"), reason: "The following resource(s) failed to create: [PublicSubnet2, CloudformationExecutionRole, " + "PrivateSubnet1, InternetGatewayAttachment, PublicSubnet1, ServiceDiscoveryNamespace," + " PrivateSubnet2], EnvironmentSecurityGroup, PublicRouteTable]. Rollback requested by user.", }, { value: cloudformation.StackStatus("DELETE_COMPLETE"), }, }, stopWatch: &stopWatch{ startTime: testDate, stopTime: testDate, started: true, stopped: true, }, separator: '\t', } buf := new(strings.Builder) // WHEN nl, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 5, nl, "expected 3 entries to be printed to the terminal") require.Equal(t, "- The environment stack \"phonetool-test\" contains your shared resources between services\t[delete complete]\t[0.0s]\n"+ " The following resource(s) failed to create: [PublicSubnet2, Cloudforma\t\t\n"+ " tionExecutionRole, PrivateSubnet1, InternetGatewayAttachment, PublicSu\t\t\n"+ " bnet1, ServiceDiscoveryNamespace, PrivateSubnet2], EnvironmentSecurity\t\t\n"+ " Group, PublicRouteTable]. Rollback requested by user.\t\t\n", buf.String()) }) t.Run("renders multiple failure reasons", func(t *testing.T) { // GIVEN comp := &regularResourceComponent{ description: `The environment stack "phonetool-test" contains your shared resources between services`, statuses: []cfnStatus{ notStartedStackStatus, { value: cloudformation.StackStatus("CREATE_IN_PROGRESS"), }, { value: cloudformation.StackStatus("CREATE_FAILED"), reason: "Resource creation cancelled", }, { value: cloudformation.StackStatus("DELETE_FAILED"), reason: "Resource cannot be deleted", }, }, stopWatch: &stopWatch{ startTime: testDate, stopTime: testDate, started: true, stopped: true, }, separator: '\t', } buf := new(strings.Builder) // WHEN nl, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 3, nl, "expected 3 entries to be printed to the terminal") require.Equal(t, "- The environment stack \"phonetool-test\" contains your shared resources between services\t[delete failed]\t[0.0s]\n"+ " Resource creation cancelled\t\t\n"+ " Resource cannot be deleted\t\t\n", buf.String()) }) } func TestEcsServiceResourceComponent_Listen(t *testing.T) { t.Run("should create a deployment renderer if the service goes into in progress", func(t *testing.T) { // GIVEN ch := make(chan stream.StackEvent) deployDone := make(chan struct{}) resourceDone := make(chan struct{}) c := &ecsServiceResourceComponent{ cfnStream: ch, logicalID: "Service", group: new(errgroup.Group), ctx: context.Background(), done: make(chan struct{}), resourceRenderer: &mockDynamicRenderer{ done: resourceDone, }, newDeploymentRender: func(s string, t time.Time) DynamicRenderer { return &mockDynamicRenderer{ done: deployDone, } }, } // WHEN go c.Listen() go func() { ch <- stream.StackEvent{ LogicalResourceID: "Service", PhysicalResourceID: "", ResourceStatus: "CREATE_IN_PROGRESS", } ch <- stream.StackEvent{ LogicalResourceID: "Service", PhysicalResourceID: "arn:aws:ecs:us-west-2:1111:service/webapp-test-Cluster/webapp-test-frontend", ResourceStatus: "CREATE_IN_PROGRESS", } // Close channels to notify that the ecs service deployment is done. close(deployDone) close(resourceDone) close(ch) }() // THEN <-c.done // Wait for listen to exit. require.NotNil(t, c.deploymentRenderer, "expected the deployment renderer to be initialized") }) t.Run("should not create a deployment renderer if the service never goes in create or update in progress", func(t *testing.T) { // GIVEN ch := make(chan stream.StackEvent) deployDone := make(chan struct{}) resourceDone := make(chan struct{}) c := &ecsServiceResourceComponent{ cfnStream: ch, logicalID: "Service", group: new(errgroup.Group), ctx: context.Background(), done: make(chan struct{}), resourceRenderer: &mockDynamicRenderer{ done: resourceDone, }, newDeploymentRender: func(s string, t time.Time) DynamicRenderer { return &mockDynamicRenderer{ done: deployDone, } }, } // WHEN go c.Listen() go func() { ch <- stream.StackEvent{ LogicalResourceID: "Service", PhysicalResourceID: "arn:aws:ecs:us-west-2:1111:service/webapp-test-Cluster/webapp-test-frontend", ResourceStatus: "CREATE_COMPLETE", } ch <- stream.StackEvent{ LogicalResourceID: "Service", PhysicalResourceID: "arn:aws:ecs:us-west-2:1111:service/webapp-test-Cluster/webapp-test-frontend", ResourceStatus: "DELETE_IN_PROGRESS", } ch <- stream.StackEvent{ LogicalResourceID: "Service", PhysicalResourceID: "arn:aws:ecs:us-west-2:1111:service/webapp-test-Cluster/webapp-test-frontend", ResourceStatus: "DELETE_COMPLETE", } // Close channels to notify that the ecs service deployment is done. close(deployDone) close(resourceDone) close(ch) }() // THEN <-c.done // Wait for listen to exit. require.Nil(t, c.deploymentRenderer, "expected the deployment renderer to be nil") }) } func TestEcsServiceResourceComponent_Render(t *testing.T) { t.Run("renders only the resource renderer if there is no deployment in progress", func(t *testing.T) { // GIVEN buf := new(strings.Builder) c := &ecsServiceResourceComponent{ resourceRenderer: &mockDynamicRenderer{ content: "resource\n", }, } // WHEN nl, err := c.Render(buf) // THEN require.Nil(t, err) require.Equal(t, 1, nl) require.Equal(t, "resource\n", buf.String()) }) t.Run("renders both resource and deployment if deployment in progress", func(t *testing.T) { // GIVEN buf := new(strings.Builder) c := &ecsServiceResourceComponent{ resourceRenderer: &mockDynamicRenderer{ content: "resource\n", }, deploymentRenderer: &mockDynamicRenderer{ content: "deployment\n", }, } // WHEN nl, err := c.Render(buf) // THEN require.Nil(t, err) require.Equal(t, 2, nl) require.Equal(t, "resource\n"+ "deployment\t\t\n", buf.String()) }) }
623
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "bytes" "fmt" "io" "strings" "text/tabwriter" ) const ( nestedComponentPadding = 2 // Leading space characters for rendering a nested component. ) // noopComponent satisfies the Renderer interface but does not write anything. type noopComponent struct{} // Render does not do anything. // It returns 0 and nil for the error. func (c *noopComponent) Render(_ io.Writer) (numLines int, err error) { return 0, nil } // LineRenderer returns a Renderer that can display a single line of text. func LineRenderer(text string, padding int) Renderer { return &singleLineComponent{ Text: text, Padding: padding, } } // singleLineComponent can display a single line of text. type singleLineComponent struct { Text string // Line of text to print. Padding int // Number of spaces prior to the text. } // Render writes the Text with a newline to out and returns 1 for the number of lines written. // In case of an error, returns 0 and the error. func (c *singleLineComponent) Render(out io.Writer) (numLines int, err error) { _, err = fmt.Fprintf(out, "%s%s\n", strings.Repeat(" ", c.Padding), c.Text) if err != nil { return 0, err } return 1, err } // treeComponent can display a node and its Children. type treeComponent struct { Root Renderer Children []Renderer } // Render writes the Root and its Children in order to out. Returns the total number of lines written. // In case of an error, returns 0 and the error. func (c *treeComponent) Render(out io.Writer) (numLines int, err error) { return renderComponents(out, append([]Renderer{c.Root}, c.Children...)) } // dynamicTreeComponent is a treeComponent that can notify that it's done updating once the Root node is done. type dynamicTreeComponent struct { Root DynamicRenderer Children []Renderer } // Render creates a treeComponent and renders it. func (c *dynamicTreeComponent) Render(out io.Writer) (numLines int, err error) { comp := &treeComponent{ Root: c.Root, Children: c.Children, } return comp.Render(out) } // Done return a channel that is closed when the children and root are done. func (c *dynamicTreeComponent) Done() <-chan struct{} { done := make(chan struct{}) go func() { for _, child := range c.Children { if dr, ok := child.(DynamicRenderer); ok { <-dr.Done() // Wait for children to be closed. } } <-c.Root.Done() // Then wait for the root to be closed. close(done) }() return done } // tableComponent can display a table. type tableComponent struct { Title string // The table's label. Header []string // Titles for the columns. Rows [][]string // The table's data. Padding int // Number of leading spaces before writing the Title. MinCellWidth int // Minimum number of characters per table cell. GapWidth int // Number of characters between columns. ColumnChar byte // Character that separates columns. } // newTableComponent returns a small table component with no padding, that uses the space character ' ' to // separate columns, and has two spaces between columns. func newTableComponent(title string, header []string, rows [][]string) *tableComponent { return &tableComponent{ Title: title, Header: header, Rows: rows, Padding: 0, MinCellWidth: 2, GapWidth: 2, ColumnChar: ' ', } } // Render writes the table to out. // If there are no rows, the table is not rendered. func (c *tableComponent) Render(out io.Writer) (numLines int, err error) { if len(c.Rows) == 0 { return 0, nil } // Write the table's title. buf := new(bytes.Buffer) if _, err := buf.WriteString(fmt.Sprintf("%s%s\n", strings.Repeat(" ", c.Padding), c.Title)); err != nil { return 0, fmt.Errorf("write title %s to buffer: %w", c.Title, err) } numLines += 1 // Write rows. tw := tabwriter.NewWriter(buf, c.MinCellWidth, c.GapWidth, c.MinCellWidth, c.ColumnChar, noAdditionalFormatting) rows := append([][]string{c.Header}, c.Rows...) for _, row := range rows { // Pad the table to the right under the Title. line := fmt.Sprintf("%s%s\n", strings.Repeat(" ", c.Padding+nestedComponentPadding), strings.Join(row, "\t")) if _, err := tw.Write([]byte(line)); err != nil { return 0, fmt.Errorf("write row %s to tabwriter: %w", line, err) } } if err := tw.Flush(); err != nil { return 0, fmt.Errorf("flush tabwriter: %w", err) } numLines += len(rows) // Flush everything to out. if _, err := buf.WriteTo(out); err != nil { return 0, fmt.Errorf("write buffer to out: %w", err) } return numLines, nil } func renderComponents(out io.Writer, components []Renderer) (numLines int, err error) { buf := new(bytes.Buffer) for _, comp := range components { nl, err := comp.Render(buf) if err != nil { return 0, err } numLines += nl } if _, err := buf.WriteTo(out); err != nil { return 0, err } return numLines, nil }
169
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "strings" "testing" "github.com/stretchr/testify/require" ) func TestNoopComponent_Render(t *testing.T) { // GIVEN buf := new(strings.Builder) c := &noopComponent{} // WHEN nl, err := c.Render(buf) // THEN require.Equal(t, 0, nl, "expected no lines to be written") require.NoError(t, err, "expected err to be nil") require.Equal(t, "", buf.String(), "expected the content to be empty") } func TestSingleLineComponent_Render(t *testing.T) { testCases := map[string]struct { inText string inPadding int wantedOut string }{ "should print padded text with new line": { inText: "hello world", inPadding: 4, wantedOut: " hello world\n", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN comp := &singleLineComponent{ Text: tc.inText, Padding: tc.inPadding, } buf := new(strings.Builder) // WHEN nl, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 1, nl, "expected only a single line to be written by a single line component") require.Equal(t, tc.wantedOut, buf.String()) }) } } func TestTreeComponent_Render(t *testing.T) { testCases := map[string]struct { inNode Renderer inChildren []Renderer wantedNumLines int wantedOut string }{ "should render all the nodes": { inNode: &singleLineComponent{ Text: "is", }, inChildren: []Renderer{ &singleLineComponent{ Text: "this", }, &singleLineComponent{ Text: "working?", }, }, wantedNumLines: 3, wantedOut: `is this working? `, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN comp := &treeComponent{ Root: tc.inNode, Children: tc.inChildren, } buf := new(strings.Builder) // WHEN nl, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, tc.wantedNumLines, nl) require.Equal(t, tc.wantedOut, buf.String()) }) } } func TestDynamicTreeComponent_Render(t *testing.T) { // GIVEN comp := dynamicTreeComponent{ Root: &mockDynamicRenderer{ content: "hello", }, Children: []Renderer{ &mockDynamicRenderer{ content: " world", }, }, } buf := new(strings.Builder) // WHEN _, err := comp.Render(buf) // THEN require.NoError(t, err) require.Equal(t, "hello world", buf.String()) } func TestDynamicTreeComponent_Done(t *testing.T) { // GIVEN root := &mockDynamicRenderer{ done: make(chan struct{}), } child := &mockDynamicRenderer{ done: make(chan struct{}), } comp := dynamicTreeComponent{ Root: root, Children: []Renderer{child, &noopComponent{}}, } // WHEN go func() { // Close all nodes in the tree. close(child.done) close(root.done) }() // THEN <-comp.Done() // Should successfully exit instead of hanging. } func TestTableComponent_Render(t *testing.T) { testCases := map[string]struct { inTitle string inHeader []string inRows [][]string inPadding int wantedNumLines int wantedOut string }{ "should not write anything if there are no rows": { inTitle: "Fancy table", inHeader: []string{"col1", "col2"}, wantedNumLines: 0, wantedOut: "", }, "should render a sample table": { inTitle: "Deployments", inHeader: []string{"", "Revision", "Rollout", "Desired", "Running", "Failed", "Pending"}, inRows: [][]string{ {"PRIMARY", "3", "[in progress]", "10", "0", "0", "10"}, {"ACTIVE", "2", "[completed]", "10", "10", "0", "0"}, }, wantedNumLines: 4, wantedOut: `Deployments Revision Rollout Desired Running Failed Pending PRIMARY 3 [in progress] 10 0 0 10 ACTIVE 2 [completed] 10 10 0 0 `, }, "should render a sample table with with padding": { inTitle: "Person", inHeader: []string{"First", "Last"}, inRows: [][]string{ {"Cookie", "Monster"}, }, inPadding: 3, wantedNumLines: 3, wantedOut: ` Person First Last Cookie Monster `, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN buf := new(strings.Builder) table := newTableComponent(tc.inTitle, tc.inHeader, tc.inRows) table.Padding = tc.inPadding // WHEN numLines, err := table.Render(buf) // THEN require.NoError(t, err) require.Equal(t, tc.wantedNumLines, numLines, "expected number of lines to match") require.Equal(t, tc.wantedOut, buf.String(), "expected table content to match") }) } }
222
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "bytes" "fmt" "github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch" "io" "strconv" "sync" "github.com/aws/copilot-cli/internal/pkg/aws/ecs" "github.com/aws/copilot-cli/internal/pkg/stream" "github.com/aws/copilot-cli/internal/pkg/term/color" ) const ( maxServiceEventsToDisplay = 5 // Total number of events we want to display at most for ECS service events. ) // ECSServiceSubscriber is the interface to subscribe channels to ECS service descriptions. type ECSServiceSubscriber interface { Subscribe() <-chan stream.ECSService } // ListeningRollingUpdateRenderer renders ECS rolling update deployments. func ListeningRollingUpdateRenderer(streamer ECSServiceSubscriber, opts RenderOptions) DynamicRenderer { c := &rollingUpdateComponent{ padding: opts.Padding, maxLenFailureMsgs: maxServiceEventsToDisplay, stream: streamer.Subscribe(), done: make(chan struct{}), } go c.Listen() return c } type rollingUpdateComponent struct { // Data to render. deployments []stream.ECSDeployment failureMsgs []string alarms []cloudwatch.AlarmStatus // Style configuration for the component. padding int maxLenFailureMsgs int stream <-chan stream.ECSService // Channel where deployment events are received. done chan struct{} // Channel that's closed when there are no more events to listen on. mu sync.Mutex // Lock used to mutate data to render. } // Listen updates the deployment statuses and failure event messages as events are streamed. func (c *rollingUpdateComponent) Listen() { for ev := range c.stream { c.mu.Lock() c.deployments = ev.Deployments c.failureMsgs = append(c.failureMsgs, ev.LatestFailureEvents...) if len(c.failureMsgs) > c.maxLenFailureMsgs { c.failureMsgs = c.failureMsgs[len(c.failureMsgs)-c.maxLenFailureMsgs:] } c.alarms = ev.Alarms c.mu.Unlock() } close(c.done) } // Render prints first the deployments as a tableComponent and then the failure messages as singleLineComponents. func (c *rollingUpdateComponent) Render(out io.Writer) (numLines int, err error) { c.mu.Lock() defer c.mu.Unlock() buf := new(bytes.Buffer) nl, err := c.renderDeployments(buf) if err != nil { return 0, err } numLines += nl nl, err = c.renderFailureMsgs(buf) if err != nil { return 0, err } numLines += nl nl, err = c.renderAlarms(buf) if err != nil { return 0, err } numLines += nl if _, err := buf.WriteTo(out); err != nil { return 0, fmt.Errorf("render rolling update component to writer: %w", err) } return numLines, nil } // Done returns a channel that's closed when there are no more events to listen. func (c *rollingUpdateComponent) Done() <-chan struct{} { return c.done } func (c *rollingUpdateComponent) renderDeployments(out io.Writer) (numLines int, err error) { header := []string{"", "Revision", "Rollout", "Desired", "Running", "Failed", "Pending"} var rows [][]string for _, d := range c.deployments { rows = append(rows, []string{ d.Status, d.TaskDefRevision, prettifyRolloutStatus(d.RolloutState), strconv.Itoa(d.DesiredCount), strconv.Itoa(d.RunningCount), strconv.Itoa(d.FailedCount), strconv.Itoa(d.PendingCount), }) } table := newTableComponent(color.Faint.Sprintf("Deployments"), header, rows) table.Padding = c.padding nl, err := table.Render(out) if err != nil { return 0, fmt.Errorf("render deployments table: %w", err) } return nl, err } func (c *rollingUpdateComponent) renderFailureMsgs(out io.Writer) (numLines int, err error) { if len(c.failureMsgs) == 0 { return 0, nil } title := "Latest failure event" if l := len(c.failureMsgs); l > 1 { title = fmt.Sprintf("Latest %d failure events", l) } title = fmt.Sprintf("%s%s", color.DullRed.Sprintf("✘ "), color.Faint.Sprintf(title)) components := []Renderer{ &singleLineComponent{}, // Add an empty line before rendering failure events. &singleLineComponent{ Text: title, Padding: c.padding, }, } for _, msg := range reverseStrings(c.failureMsgs) { for i, truncatedMsg := range splitByLength(msg, maxCellLength) { pretty := fmt.Sprintf(" %s", truncatedMsg) if i == 0 { pretty = fmt.Sprintf("- %s", truncatedMsg) } components = append(components, &singleLineComponent{ Text: pretty, Padding: c.padding + nestedComponentPadding, }) } } return renderComponents(out, components) } func (c *rollingUpdateComponent) renderAlarms(out io.Writer) (numLines int, err error) { if len(c.alarms) == 0 { return 0, nil } header := []string{"Name", "State"} var rows [][]string for _, a := range c.alarms { rows = append(rows, []string{ a.Name, prettifyAlarmState(a.Status), }) } table := newTableComponent(color.Faint.Sprintf("Alarms"), header, rows) table.Padding = c.padding components := []Renderer{ &singleLineComponent{}, // Add an empty line before rendering alarms table. table, } return renderComponents(out, components) } func reverseStrings(arr []string) []string { reversed := make([]string, len(arr)) copy(reversed, arr) for i := len(reversed)/2 - 1; i >= 0; i-- { opp := len(reversed) - 1 - i reversed[i], reversed[opp] = reversed[opp], reversed[i] } return reversed } // parseServiceARN returns the cluster name and service name from a service ARN. func parseServiceARN(arn string) (cluster, service string) { parsed := ecs.ServiceArn(arn) // Errors can't happen on valid ARNs. cluster, _ = parsed.ClusterName() service, _ = parsed.ServiceName() return cluster, service }
201
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch" "github.com/aws/copilot-cli/internal/pkg/stream" "github.com/stretchr/testify/require" "strings" "testing" ) func TestRollingUpdateComponent_Listen(t *testing.T) { t.Run("should update deployments to latest event and respect max number of failed msgs", func(t *testing.T) { // GIVEN events := make(chan stream.ECSService) done := make(chan struct{}) c := &rollingUpdateComponent{ padding: 0, maxLenFailureMsgs: 2, stream: events, done: done, } // WHEN go c.Listen() go func() { events <- stream.ECSService{ Deployments: []stream.ECSDeployment{ { Status: "PRIMARY", TaskDefRevision: "2", DesiredCount: 10, PendingCount: 10, RolloutState: "IN_PROGRESS", }, { Status: "ACTIVE", TaskDefRevision: "1", DesiredCount: 10, RunningCount: 10, RolloutState: "COMPLETED", }, }, LatestFailureEvents: []string{"event1", "event2", "event3"}, } events <- stream.ECSService{ Deployments: []stream.ECSDeployment{ { Status: "PRIMARY", TaskDefRevision: "2", DesiredCount: 10, RunningCount: 10, RolloutState: "COMPLETED", }, }, LatestFailureEvents: []string{"event4"}, } close(events) }() // THEN <-done // Listen should have closed the channel. require.Equal(t, []stream.ECSDeployment{ { Status: "PRIMARY", TaskDefRevision: "2", DesiredCount: 10, RunningCount: 10, RolloutState: "COMPLETED", }, }, c.deployments, "expected only the latest deployment to be stored") require.Equal(t, []string{"event3", "event4"}, c.failureMsgs, "expected max len failure msgs to be respected") }) } func TestRollingUpdateComponent_Render(t *testing.T) { testCases := map[string]struct { inDeployments []stream.ECSDeployment inFailureMsgs []string inAlarms []cloudwatch.AlarmStatus wantedNumLines int wantedOut string }{ "should render only deployments if there are no failure messages": { inDeployments: []stream.ECSDeployment{ { Status: "PRIMARY", TaskDefRevision: "2", DesiredCount: 10, RunningCount: 10, RolloutState: "COMPLETED", }, }, wantedNumLines: 3, wantedOut: `Deployments Revision Rollout Desired Running Failed Pending PRIMARY 2 [completed] 10 10 0 0 `, }, "should render a single failure event": { inFailureMsgs: []string{"(service my-svc) (task 1234) failed container health checks."}, wantedNumLines: 3, wantedOut: ` ✘ Latest failure event - (service my-svc) (task 1234) failed container health checks. `, }, "should split really long failure event messages": { inFailureMsgs: []string{ "(service webapp-test-frontend-Service-ss036XlczgjO) (port 80) is unhealthy in (target-group arn:aws:elasticloadbalancing:us-west-2:1111: targetgroup/aaaaaaaaaaaa) due to (reason some-error).", }, wantedNumLines: 5, wantedOut: ` ✘ Latest failure event - (service webapp-test-frontend-Service-ss036XlczgjO) (port 80) is unhea lthy in (target-group arn:aws:elasticloadbalancing:us-west-2:1111: tar getgroup/aaaaaaaaaaaa) due to (reason some-error). `, }, "should render multiple failure messages in reverse order": { inFailureMsgs: []string{ "(service my-svc) (task 1234) failed container health checks.", "(service my-svc) (task 5678) failed container health checks.", }, wantedNumLines: 4, wantedOut: ` ✘ Latest 2 failure events - (service my-svc) (task 5678) failed container health checks. - (service my-svc) (task 1234) failed container health checks. `, }, "should render rollback alarms and their statuses": { inAlarms: []cloudwatch.AlarmStatus{ { Name: "alarm1", Status: "OK", }, { Name: "alarm2", Status: "ALARM", }, }, wantedNumLines: 5, wantedOut: ` Alarms Name State alarm1 [OK] alarm2 [ALARM] `, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN buf := new(strings.Builder) c := &rollingUpdateComponent{ deployments: tc.inDeployments, failureMsgs: tc.inFailureMsgs, alarms: tc.inAlarms, } // WHEN nl, err := c.Render(buf) // THEN require.NoError(t, err) require.Equal(t, tc.wantedNumLines, nl, "number of lines expected did not match") require.Equal(t, tc.wantedOut, buf.String(), "the content written did not match") }) } }
178
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "context" "io" ) // EnvControllerConfig holds the required parameters to create an environment controller component. type EnvControllerConfig struct { // Common configuration. Description string RenderOpts RenderOptions // Env controller action configuration. ActionStreamer StackSubscriber ActionLogicalID string // Env stack configuration. EnvStreamer StackSubscriber CancelEnvStream context.CancelFunc EnvStackName string EnvResources map[string]string } // ListeningEnvControllerRenderer returns a component that listens and can render CloudFormation resource events // from the EnvControllerAction and the environment stack. func ListeningEnvControllerRenderer(conf EnvControllerConfig) DynamicRenderer { return &envControllerComponent{ cancelEnvStream: conf.CancelEnvStream, actionComponent: listeningResourceComponent( conf.ActionStreamer, conf.ActionLogicalID, conf.Description, ResourceRendererOpts{ RenderOpts: conf.RenderOpts, }), stackComponent: listeningStackComponent( conf.EnvStreamer, conf.EnvStackName, conf.Description, conf.EnvResources, conf.RenderOpts, ), } } type envControllerComponent struct { cancelEnvStream context.CancelFunc // Function that cancels streaming events from the environment stack. actionComponent *regularResourceComponent stackComponent *stackComponent } // Render renders the environment stack if there are any stack event, otherwise // renders the EnvControllerAction as a resource component. func (c *envControllerComponent) Render(out io.Writer) (numLines int, err error) { if c.hasStackEvents() { return c.stackComponent.Render(out) } return c.actionComponent.Render(out) } // Done returns a channel that's closed when: // If the environment stack has any updates, then when both the env stack and action are done updating. // If there are no stack updates, then when the action is done updating. func (c *envControllerComponent) Done() <-chan struct{} { done := make(chan struct{}) go func() { // Wait for the env controller action to be done first. <-c.actionComponent.Done() // When the env controller action is done updating, we check if the env stack had any updates. // If there were no updates, then we notify the stack streamer that it should stop trying to stream events // because the env controller action never triggered an env stack update. if !c.hasStackEvents() { c.cancelEnvStream() } <-c.stackComponent.Done() close(done) }() return done } func (c *envControllerComponent) hasStackEvents() bool { c.stackComponent.mu.Lock() defer c.stackComponent.mu.Unlock() return len(c.stackComponent.resources) > 1 }
94
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "strings" "testing" "time" "github.com/aws/copilot-cli/internal/pkg/aws/cloudformation" "github.com/stretchr/testify/require" ) func TestEnvControllerComponent_Render(t *testing.T) { t.Run("renders the environment stack component if there are any stack updates", func(t *testing.T) { // GIVEN c := &envControllerComponent{ actionComponent: &regularResourceComponent{}, stackComponent: &stackComponent{ resources: []Renderer{ &mockDynamicRenderer{content: "env-stack\n"}, &mockDynamicRenderer{content: "alb\n"}, &mockDynamicRenderer{content: "nat\n"}, }, }, } buf := new(strings.Builder) // WHEN nl, err := c.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 3, nl) require.Equal(t, `env-stack alb nat `, buf.String()) }) t.Run("renders the env controller action resource if there are no environment stack updates", func(t *testing.T) { // GIVEN c := &envControllerComponent{ actionComponent: &regularResourceComponent{ description: "Env controller action", statuses: []cfnStatus{ notStartedStackStatus, { value: cloudformation.StackStatus("CREATE_IN_PROGRESS"), }, }, stopWatch: &stopWatch{ startTime: testDate, started: true, clock: &fakeClock{ wantedValues: []time.Time{testDate.Add(10 * time.Second)}, }, }, separator: '\t', }, stackComponent: &stackComponent{ resources: []Renderer{ &mockDynamicRenderer{content: "env-stack\n"}, }, }, } buf := new(strings.Builder) // WHEN nl, err := c.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 1, nl) require.Equal(t, "- Env controller action\t[create in progress]\t[10.0s]\n", buf.String()) }) } func TestEnvControllerComponent_Done(t *testing.T) { t.Run("should cancel environment stack streamer if there are no stack event updates after the action is done", func(t *testing.T) { // GIVEN actionDone := make(chan struct{}) stackDone := make(chan struct{}) var isCanceled bool c := &envControllerComponent{ cancelEnvStream: func() { isCanceled = true }, actionComponent: &regularResourceComponent{ done: actionDone, }, stackComponent: &stackComponent{ resources: []Renderer{ &mockDynamicRenderer{content: "env-stack\n"}, // Only the env stack is present, no other updates. }, done: stackDone, }, } // WHEN done := c.Done() go func() { close(actionDone) close(stackDone) }() // THEN select { case <-time.After(5 * time.Second): require.Fail(t, "done channel is not closed, test deadline exceeded") case <-done: require.True(t, isCanceled, "stack streamer should have been canceled when component is done") return } }) t.Run("should not cancel stack streamer if it is emitting events", func(t *testing.T) { // GIVEN actionDone := make(chan struct{}) stackDone := make(chan struct{}) c := &envControllerComponent{ cancelEnvStream: func() { require.Fail(t, "stack streamer should not be canceled.") }, actionComponent: &regularResourceComponent{ done: actionDone, }, stackComponent: &stackComponent{ resources: []Renderer{ &mockDynamicRenderer{content: "env-stack\n"}, &mockDynamicRenderer{content: "alb\n"}, // The streamer is emitting update events. }, done: stackDone, }, } // WHEN done := c.Done() go func() { close(actionDone) close(stackDone) }() // THEN select { case <-time.After(5 * time.Second): require.Fail(t, "done channel is not closed, test deadline exceeded") case <-done: return } }) }
153
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "context" "io" "time" "github.com/aws/copilot-cli/internal/pkg/term/cursor" ) // Renderer is the interface to print a component to a writer. // It returns the number of lines printed and the error if any. type Renderer interface { Render(out io.Writer) (numLines int, err error) } // DynamicRenderer is a Renderer that can notify that its internal states are Done updating. // DynamicRenderer is implemented by components that listen to events from a streamer and update their state. type DynamicRenderer interface { Renderer Done() <-chan struct{} } // RenderOptions holds optional style configuration for renderers. type RenderOptions struct { Padding int // Leading spaces before rendering the component. } // NestedRenderOptions takes a RenderOptions and returns the same RenderOptions but with additional padding. func NestedRenderOptions(opts RenderOptions) RenderOptions { return RenderOptions{ Padding: opts.Padding + nestedComponentPadding, } } // Render renders r periodically to out and returns the last number of lines written to out. // Render stops when there the ctx is canceled or r is done listening to new events. // While Render is executing, the terminal cursor is hidden and updates are written in-place. func Render(ctx context.Context, out FileWriteFlusher, r DynamicRenderer) (int, error) { defer out.Flush() // Make sure every buffered text in out is written before exiting. cursor := cursor.NewWithWriter(out) cursor.Hide() defer cursor.Show() var writtenLines int for { select { case <-ctx.Done(): return writtenLines, ctx.Err() case <-r.Done(): return EraseAndRender(out, r, writtenLines) case <-time.After(renderInterval): nl, err := EraseAndRender(out, r, writtenLines) if err != nil { return nl, err } writtenLines = nl } } } // EraseAndRender erases prevNumLines from out and then renders r. func EraseAndRender(out FileWriteFlusher, r Renderer, prevNumLines int) (int, error) { cursor.EraseLinesAbove(out, prevNumLines) if err := out.Flush(); err != nil { return 0, err } nl, err := r.Render(out) if err != nil { return 0, err } if err := out.Flush(); err != nil { return 0, err } return nl, err } // MultiRenderer returns a Renderer that's the concatenation of the input renderers. // The renderers are rendered sequentially, and the MultiRenderer is only Done once all renderers are Done. func MultiRenderer(renderers ...DynamicRenderer) DynamicRenderer { mr := &multiRenderer{ renderers: renderers, done: make(chan struct{}), } go mr.listen() return mr } type multiRenderer struct { renderers []DynamicRenderer done chan struct{} } // Render sequentially renders the renderers to out and returns the sum of the number of lines written. func (mr *multiRenderer) Render(out io.Writer) (int, error) { var sum int for _, r := range mr.renderers { nl, err := r.Render(out) if err != nil { return 0, err } sum += nl } return sum, nil } // Done returns a channel that's closed when there are no more events to Listen. func (mr *multiRenderer) Done() <-chan struct{} { return mr.done } func (mr *multiRenderer) listen() { for _, r := range mr.renderers { <-r.Done() } close(mr.done) }
122
copilot-cli
aws
Go
//go:build !windows // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "os" "time" ) var ( renderInterval = 100 * time.Millisecond // How frequently Render should be invoked. ) func init() { // The CI environment variable is set to "true" by default by GitHub actions and GitLab. if os.Getenv("CI") == "true" { renderInterval = 30 * time.Second } }
23
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "os" "time" ) var ( // Windows flickers too frequently if the interval is too short. renderInterval = 500 * time.Millisecond // How frequently Render should be invoked. ) func init() { if os.Getenv("CI") == "true" { renderInterval = 30 * time.Second } }
21
copilot-cli
aws
Go
//go:build !windows // This test is not compatible with Windows because it makes POSIX-centric assumptions about terminal output. // // On Windows, these terminal features involve system calls instead of writing escape sequences, which means // that this test case doesn't actually test what it's trying to do on Windows and instead just makes a bunch // of invalid system calls, in addition to having intermittent timing issues. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "bytes" "context" "errors" "io" "strings" "testing" "time" "github.com/aws/copilot-cli/internal/pkg/term/cursor" "github.com/stretchr/testify/require" ) type mockDynamicRenderer struct { content string done chan struct{} err error } func (m *mockDynamicRenderer) Render(out io.Writer) (int, error) { if m.err != nil { return 0, m.err } out.Write([]byte(m.content)) return 1, nil } func (m *mockDynamicRenderer) Done() <-chan struct{} { return m.done } type mockFileWriteFlusher struct { buf bytes.Buffer wrapper io.Writer } func (m *mockFileWriteFlusher) Write(p []byte) (n int, err error) { return m.buf.Write(p) } func (m *mockFileWriteFlusher) Fd() uintptr { return 0 } func (m *mockFileWriteFlusher) Flush() error { if _, err := m.buf.WriteTo(m.wrapper); err != nil { return err } return nil } type mockFileWriter struct { io.Writer } func (m *mockFileWriter) Fd() uintptr { return 0 } func TestRender(t *testing.T) { renderInterval = 100 * time.Millisecond // Ensure that even when CI=true we are testing with default interval. t.Run("stops the renderer when context is canceled", func(t *testing.T) { t.Parallel() // GIVEN ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond) defer cancel() actual := new(strings.Builder) r := &mockDynamicRenderer{ content: "hi\n", done: make(chan struct{}), } out := &mockFileWriteFlusher{ wrapper: actual, } // WHEN _, err := Render(ctx, out, r) // THEN require.EqualError(t, err, ctx.Err().Error(), "expected the context to be canceled") require.Contains(t, actual.String(), "hi\n", "expected Render to be invoked until the context was canceled") }) t.Run("keeps rendering until the renderer is done", func(t *testing.T) { t.Parallel() // GIVEN actual := new(strings.Builder) done := make(chan struct{}) r := &mockDynamicRenderer{ content: "hi\n", done: done, } out := &mockFileWriteFlusher{ wrapper: actual, } go func() { <-time.After(350 * time.Millisecond) close(done) }() // WHEN nl, err := Render(context.Background(), out, r) // THEN require.NoError(t, err) require.Equal(t, 1, nl) // We should be doing the following operations in order: // 1. Hide the cursor. // 2. Write "hi\n", erase the line, and move the cursor up (Repeated x3 times) // 3. The <-ctx.Done() is called so we should write one last time "hi\n" and the cursor should be shown. wanted := new(strings.Builder) wantedFW := &mockFileWriter{ Writer: wanted, } c := cursor.NewWithWriter(wantedFW) c.Hide() cursor.EraseLine(wantedFW) wanted.WriteString("hi\n") cursor.EraseLine(wantedFW) c.Up(1) cursor.EraseLine(wantedFW) wanted.WriteString("hi\n") cursor.EraseLine(wantedFW) c.Up(1) cursor.EraseLine(wantedFW) wanted.WriteString("hi\n") cursor.EraseLine(wantedFW) c.Up(1) cursor.EraseLine(wantedFW) wanted.WriteString("hi\n") c.Show() require.Equal(t, wanted.String(), actual.String(), "expected the content printed to match") }) } func TestNestedRenderOptions(t *testing.T) { // GIVEN opts := RenderOptions{} // WHEN actual := NestedRenderOptions(opts) // THEN require.Equal(t, RenderOptions{ Padding: 2, }, actual) } func TestEraseAndRender(t *testing.T) { // GIVEN wanted := new(strings.Builder) file := &mockFileWriter{ Writer: wanted, } cur := cursor.NewWithWriter(file) for i := 0; i < 10; i++ { cursor.EraseLine(file) cur.Up(1) } cursor.EraseLine(file) wanted.WriteString("hello\n") // WHEN actual := new(strings.Builder) nl, err := EraseAndRender(&mockFileWriteFlusher{ wrapper: actual, }, &singleLineComponent{Text: "hello"}, 10) // Erase 10 lines, and then write "hello\n" // THEN require.NoError(t, err) require.Equal(t, 1, nl, `only hello\n should have been written`) require.Equal(t, wanted.String(), actual.String()) } func TestMultiRenderer(t *testing.T) { t.Run("returns the error if a renderer fails to render", func(t *testing.T) { // GIVEN renderers := []DynamicRenderer{ &mockDynamicRenderer{ content: "hello", done: make(chan struct{}), }, &mockDynamicRenderer{ err: errors.New("some error"), done: make(chan struct{}), }, } buf := new(strings.Builder) mr := MultiRenderer(renderers...) // WHEN _, err := mr.Render(buf) // THEN require.EqualError(t, err, "some error") }) t.Run("returns the total number of lines on successful render", func(t *testing.T) { renderers := []DynamicRenderer{ &mockDynamicRenderer{ content: "hello\n", done: make(chan struct{}), }, &mockDynamicRenderer{ content: "from\n", done: make(chan struct{}), }, &mockDynamicRenderer{ content: "copilot\n", done: make(chan struct{}), }, } buf := new(strings.Builder) mr := MultiRenderer(renderers...) // WHEN nl, err := mr.Render(buf) // THEN require.NoError(t, err) require.Equal(t, 3, nl, "expected all 3 lines to be written") require.Equal(t, "hello\nfrom\ncopilot\n", buf.String()) }) t.Run("ensure Done exits once all the renderers are Done", func(t *testing.T) { renderers := []DynamicRenderer{ &mockDynamicRenderer{ done: make(chan struct{}), }, &mockDynamicRenderer{ done: make(chan struct{}), }, &mockDynamicRenderer{ done: make(chan struct{}), }, } mr := MultiRenderer(renderers...) // WHEN go func() { for _, r := range renderers { if dr, ok := r.(*mockDynamicRenderer); ok { close(dr.done) } } }() // THEN select { case <-time.After(5 * time.Second): require.Fail(t, "testcase should not timeout") case <-mr.Done(): // Should exit the test within timeout. } }) }
270
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "fmt" "io" "os" "time" "github.com/briandowns/spinner" ) // Events display settings. const ( minCellWidth = 20 // minimum number of characters in a table's cell. tabWidth = 4 // number of characters in between columns. cellPaddingWidth = 2 // number of padding characters added by default to a cell. paddingChar = ' ' // character in between columns. noAdditionalFormatting = 0 maxCellLength = 70 // Number of characters we want to display at most in a cell before wrapping it to the next line. ) // startStopper is the interface to interact with the spinner. type startStopper interface { Start() Stop() } // Spinner represents an indicator that an asynchronous operation is taking place. // // For short operations, less than 4 seconds, display only the spinner with the Start and Stop methods. // For longer operations, display intermediate progress events using the Events method. type Spinner struct { spin startStopper } // NewSpinner returns a spinner that outputs to w. func NewSpinner(w io.Writer) *Spinner { interval := 125 * time.Millisecond if os.Getenv("CI") == "true" { interval = 30 * time.Second } s := spinner.New(charset, interval, spinner.WithHiddenCursor(true)) s.Writer = w return &Spinner{ spin: s, } } // Start starts the spinner suffixed with a label. func (s *Spinner) Start(label string) { s.suffix(fmt.Sprintf(" %s", label)) s.spin.Start() } // Stop stops the spinner and replaces it with a label. func (s *Spinner) Stop(label string) { s.finalMSG(fmt.Sprint(label)) s.spin.Stop() } func (s *Spinner) lock() { if spinner, ok := s.spin.(*spinner.Spinner); ok { spinner.Lock() } } func (s *Spinner) unlock() { if spinner, ok := s.spin.(*spinner.Spinner); ok { spinner.Unlock() } } func (s *Spinner) suffix(label string) { s.lock() defer s.unlock() if spinner, ok := s.spin.(*spinner.Spinner); ok { spinner.Suffix = label } } func (s *Spinner) finalMSG(label string) { s.lock() defer s.unlock() if spinner, ok := s.spin.(*spinner.Spinner); ok { spinner.FinalMSG = label } }
91
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "os" "strings" "testing" "time" "github.com/aws/copilot-cli/internal/pkg/term/progress/mocks" spin "github.com/briandowns/spinner" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) func TestNew(t *testing.T) { t.Run("it should initialize the spin spinner", func(t *testing.T) { buf := new(strings.Builder) got := NewSpinner(buf) wantedInterval := 125 * time.Millisecond if os.Getenv("CI") == "true" { wantedInterval = 30 * time.Second } v, ok := got.spin.(*spin.Spinner) require.True(t, ok) require.Equal(t, buf, v.Writer) require.Equal(t, wantedInterval, v.Delay) }) } func TestSpinner_Start(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSpinner := mocks.NewMockstartStopper(ctrl) s := &Spinner{ spin: mockSpinner, } mockSpinner.EXPECT().Start() s.Start("start") } func TestSpinner_Stop(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSpinner := mocks.NewMockstartStopper(ctrl) s := &Spinner{ spin: mockSpinner, } mockSpinner.EXPECT().Stop() // WHEN s.Stop("stop") }
61
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "fmt" "strings" "github.com/aws/copilot-cli/internal/pkg/term/color" ) var ( notStartedStackStatus = cfnStatus{ value: notStartedResult{}, } alarmOKState = "OK" inAlarmState = "ALARM" ) type result interface { IsSuccess() bool IsFailure() bool InProgress() bool fmt.Stringer } // notStartedResult represents an unbegun status that implements the result interface. type notStartedResult struct{} // IsSuccess is false for a non-started state. func (r notStartedResult) IsSuccess() bool { return false } // IsFailure is false for a non-started state. func (r notStartedResult) IsFailure() bool { return false } // InProgress is false for a non-started state. func (r notStartedResult) InProgress() bool { return false } // String implements the fmt.Stringer interface. func (r notStartedResult) String() string { return "not started" } type cfnStatus struct { value result reason string } func prettifyLatestStackStatus(statuses []cfnStatus) string { color := colorStackStatus(statuses) latest := statuses[len(statuses)-1].value.String() pretty := strings.ToLower(strings.ReplaceAll(latest, "_", " ")) return color("[%s]", pretty) } func prettifyRolloutStatus(rollout string) string { pretty := strings.ToLower(strings.ReplaceAll(rollout, "_", " ")) return fmt.Sprintf("[%s]", pretty) } func prettifyElapsedTime(sw *stopWatch) string { elapsed, hasStarted := sw.elapsed() if !hasStarted { return "" } return color.Faint.Sprintf("[%.1fs]", elapsed.Seconds()) } func prettifyAlarmState(state string) string { var pretty string switch state { case alarmOKState: pretty = color.Green.Sprintf("[%s]", state) case inAlarmState: pretty = color.Red.Sprintf("[%s]", state) default: pretty = fmt.Sprintf("[%s]", state) } return pretty } func failureReasons(statuses []cfnStatus) []string { var reasons []string for _, status := range statuses { if !status.value.IsFailure() { continue } if status.reason == "" { continue } reasons = append(reasons, status.reason) } return reasons } func splitByLength(s string, maxLength int) []string { numItems := len(s)/maxLength + 1 var ss []string for i := 0; i < numItems; i += 1 { if i == numItems-1 { ss = append(ss, s[i*maxLength:]) continue } ss = append(ss, s[i*maxLength:(i+1)*maxLength]) } return ss } // colorStackStatus returns a function to colorize a stack status based on past events. // If there was any failure in the history of the stack, then color the status as red. // If the latest event is a success, then it's green. // Otherwise, it's fainted. func colorStackStatus(statuses []cfnStatus) func(format string, a ...interface{}) string { hasPastFailure := false for _, status := range statuses { if status.value.IsFailure() { hasPastFailure = true break } } latestStatus := statuses[len(statuses)-1] if latestStatus.value.IsSuccess() && !hasPastFailure { return color.Green.Sprintf } if hasPastFailure { return color.Red.Sprintf } return color.Faint.Sprintf } func colorFailureReason(text string) string { return color.DullRed.Sprint(text) }
143
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import "time" type clock interface { now() time.Time } type realClock struct{} func (c realClock) now() time.Time { return time.Now() } type stopWatch struct { startTime time.Time stopTime time.Time started bool stopped bool clock clock } func newStopWatch() *stopWatch { return &stopWatch{ clock: realClock{}, } } // start records the current time when the watch started. // If the watch is already in progress, then calling start multiple times does nothing. func (sw *stopWatch) start() { if sw.started { return } sw.startTime = sw.clock.now() sw.started = true } // stop records the current time when the watch stopped. // If the watch never started, then calling stop doesn't do anything. // If the watch is already stopped, then calling stop another time doesn't do anything. func (sw *stopWatch) stop() { if !sw.started { return } if sw.stopped { return } sw.stopTime = sw.clock.now() sw.stopped = true } // reset should be called before starting a timer always. func (sw *stopWatch) reset() { sw.startTime = time.Time{} sw.stopTime = time.Time{} sw.stopped = false sw.started = false } // elapsed returns the time since starting the stopWatch. // If the stopWatch never started, then returns false for the boolean. func (sw *stopWatch) elapsed() (time.Duration, bool) { if !sw.started { // The stopWatch didn't start, so no time elapsed. return 0, false } if sw.stopped { return sw.stopTime.Sub(sw.startTime), true } return sw.clock.now().Sub(sw.startTime), true }
76
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "io" "text/tabwriter" ) // FileWriter is the interface grouping an io.Writer with the file descriptor method Fd. // Files in the OS, like os.Stderr, implement the FileWriter interface. type FileWriter interface { io.Writer Fd() uintptr } // WriteFlusher is the interface grouping an io.Writer with the Flush method. // Flush allows writing buffered writes from Writer all at once. type WriteFlusher interface { io.Writer Flush() error } // FileWriteFlusher is the interface that groups a FileWriter and WriteFlusher. type FileWriteFlusher interface { FileWriter WriteFlusher } // TabbedFileWriter is a FileWriter that also implements the WriteFlusher interface. // A TabbedFileWriter can properly align text separated by the '\t' character. type TabbedFileWriter struct { FileWriter WriteFlusher } func (w *TabbedFileWriter) Write(p []byte) (n int, err error) { return w.WriteFlusher.Write(p) } // NewTabbedFileWriter takes a file as input and returns a FileWriteFlusher that can // properly write tab-separated text to it. func NewTabbedFileWriter(fw FileWriter) *TabbedFileWriter { return &TabbedFileWriter{ FileWriter: fw, WriteFlusher: tabwriter.NewWriter(fw, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting), } } // suffixWriter is an io.Writer that adds the suffix before a new line character. type suffixWriter struct { buf io.Writer suffix []byte } // Write adds a suffix before each new line character in p. func (w *suffixWriter) Write(p []byte) (n int, err error) { var withSuffix []byte for _, b := range p { suffix := []byte{b} if b == '\n' { suffix = append(w.suffix, b) } withSuffix = append(withSuffix, suffix...) } if _, err := w.buf.Write(withSuffix); err != nil { return 0, err } return len(p), nil }
72
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package progress import ( "strings" "testing" "github.com/stretchr/testify/require" ) func TestSuffixWriter_Write(t *testing.T) { testCases := map[string]struct { inText string suffix []byte wantedText string }{ "should wrap every new line with the suffix": { inText: `The AWS Copilot CLI is a tool for developers to build, release and operate production ready containerized applications on Amazon ECS and AWS Fargate. `, suffix: []byte{'\t', '\t'}, wantedText: "The AWS Copilot CLI is a tool for developers to build, release\t\t\n" + "and operate production ready containerized applications\t\t\n" + "on Amazon ECS and AWS Fargate.\t\t\n", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN buf := new(strings.Builder) sw := &suffixWriter{ buf: buf, suffix: tc.suffix, } // WHEN _, err := sw.Write([]byte(tc.inText)) // THEN require.NoError(t, err) require.Equal(t, tc.wantedText, buf.String()) }) } }
51
copilot-cli
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: ./internal/pkg/term/progress/render.go // Package mocks is a generated GoMock package. package mocks import ( io "io" reflect "reflect" gomock "github.com/golang/mock/gomock" ) // MockRenderer is a mock of Renderer interface. type MockRenderer struct { ctrl *gomock.Controller recorder *MockRendererMockRecorder } // MockRendererMockRecorder is the mock recorder for MockRenderer. type MockRendererMockRecorder struct { mock *MockRenderer } // NewMockRenderer creates a new mock instance. func NewMockRenderer(ctrl *gomock.Controller) *MockRenderer { mock := &MockRenderer{ctrl: ctrl} mock.recorder = &MockRendererMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockRenderer) EXPECT() *MockRendererMockRecorder { return m.recorder } // Render mocks base method. func (m *MockRenderer) Render(out io.Writer) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Render", out) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Render indicates an expected call of Render. func (mr *MockRendererMockRecorder) Render(out interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Render", reflect.TypeOf((*MockRenderer)(nil).Render), out) } // MockDynamicRenderer is a mock of DynamicRenderer interface. type MockDynamicRenderer struct { ctrl *gomock.Controller recorder *MockDynamicRendererMockRecorder } // MockDynamicRendererMockRecorder is the mock recorder for MockDynamicRenderer. type MockDynamicRendererMockRecorder struct { mock *MockDynamicRenderer } // NewMockDynamicRenderer creates a new mock instance. func NewMockDynamicRenderer(ctrl *gomock.Controller) *MockDynamicRenderer { mock := &MockDynamicRenderer{ctrl: ctrl} mock.recorder = &MockDynamicRendererMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockDynamicRenderer) EXPECT() *MockDynamicRendererMockRecorder { return m.recorder } // Done mocks base method. func (m *MockDynamicRenderer) Done() <-chan struct{} { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Done") ret0, _ := ret[0].(<-chan struct{}) return ret0 } // Done indicates an expected call of Done. func (mr *MockDynamicRendererMockRecorder) Done() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Done", reflect.TypeOf((*MockDynamicRenderer)(nil).Done)) } // Render mocks base method. func (m *MockDynamicRenderer) Render(out io.Writer) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Render", out) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Render indicates an expected call of Render. func (mr *MockDynamicRendererMockRecorder) Render(out interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Render", reflect.TypeOf((*MockDynamicRenderer)(nil).Render), out) }
103
copilot-cli
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: ./internal/pkg/term/progress/spinner.go // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" gomock "github.com/golang/mock/gomock" ) // MockstartStopper is a mock of startStopper interface. type MockstartStopper struct { ctrl *gomock.Controller recorder *MockstartStopperMockRecorder } // MockstartStopperMockRecorder is the mock recorder for MockstartStopper. type MockstartStopperMockRecorder struct { mock *MockstartStopper } // NewMockstartStopper creates a new mock instance. func NewMockstartStopper(ctrl *gomock.Controller) *MockstartStopper { mock := &MockstartStopper{ctrl: ctrl} mock.recorder = &MockstartStopperMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockstartStopper) EXPECT() *MockstartStopperMockRecorder { return m.recorder } // Start mocks base method. func (m *MockstartStopper) Start() { m.ctrl.T.Helper() m.ctrl.Call(m, "Start") } // Start indicates an expected call of Start. func (mr *MockstartStopperMockRecorder) Start() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockstartStopper)(nil).Start)) } // Stop mocks base method. func (m *MockstartStopper) Stop() { m.ctrl.T.Helper() m.ctrl.Call(m, "Stop") } // Stop indicates an expected call of Stop. func (mr *MockstartStopperMockRecorder) Stop() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockstartStopper)(nil).Stop)) }
59
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package summarybar provides renderers for summary bar. package summarybar import ( "bytes" "errors" "fmt" "io" "math" "sort" "strings" "github.com/aws/copilot-cli/internal/pkg/term/progress" ) var errTotalIsZero = errors.New("the data sums up to zero") // summaryBarComponent returns a summary bar given data and the string representations of each data category. type summaryBarComponent struct { data []Datum width int emptyRep string } // Datum is the basic unit of summary bar. // Each Datum is composed of a value and a representation. The value will be represented with the representation in the // rendered summary bar. type Datum struct { Representation string Value int } // Opt configures an option for summaryBarComponent. type Opt func(*summaryBarComponent) // WithWidth is an opt that configures the width for summaryBarComponent. func WithWidth(width int) Opt { return func(c *summaryBarComponent) { c.width = width } } // WithEmptyRep is an opt that configures the empty representation for summaryBarComponent. func WithEmptyRep(representation string) Opt { return func(c *summaryBarComponent) { c.emptyRep = representation } } // New returns a summaryBarComponent configured against opts. func New(data []Datum, opts ...Opt) progress.Renderer { component := &summaryBarComponent{ data: data, } for _, opt := range opts { opt(component) } return component } // Render writes the summary bar to ouT without a new line. func (c *summaryBarComponent) Render(out io.Writer) (numLines int, err error) { if c.width <= 0 { return 0, fmt.Errorf("invalid width %d for summary bar", c.width) } if hasNegativeValue(c.data) { return 0, fmt.Errorf("input data contains negative values") } var data []int var representations []string for _, d := range c.data { data = append(data, d.Value) representations = append(representations, d.Representation) } buf := new(bytes.Buffer) portions, err := c.calculatePortions(data) if err != nil { if !errors.Is(err, errTotalIsZero) { return 0, err } if _, err := buf.WriteString(fmt.Sprint(strings.Repeat(c.emptyRep, c.width))); err != nil { return 0, fmt.Errorf("write empty bar to buffer: %w", err) } if _, err := buf.WriteTo(out); err != nil { return 0, fmt.Errorf("write buffer to out: %w", err) } return 0, nil } var bar string for idx, p := range portions { bar += fmt.Sprint(strings.Repeat(representations[idx], p)) } if _, err := buf.WriteString(bar); err != nil { return 0, fmt.Errorf("write bar to buffer: %w", err) } if _, err := buf.WriteTo(out); err != nil { return 0, fmt.Errorf("write buffer to out: %w", err) } return 0, nil } func (c *summaryBarComponent) calculatePortions(data []int) ([]int, error) { type estimation struct { index int dec float64 portion int } var sum int for _, v := range data { sum += v } if sum <= 0 { return nil, errTotalIsZero } // We first underestimate how many units each data value would take in the summary bar of length Length. // Then we distribute the rest of the units to each estimation. var underestimations []estimation for idx, v := range data { rawFraction := (float64)(v) / (float64)(sum) * (float64)(c.width) _, decPart := math.Modf(rawFraction) underestimations = append(underestimations, estimation{ dec: decPart, portion: (int)(math.Max(math.Floor(rawFraction), 0)), index: idx, }) } // Calculate the sum of the underestimated units and see how far we are from filling the bar of length `Length`. var currLength int for _, underestimated := range underestimations { currLength += underestimated.portion } unitsLeft := c.width - currLength // Sort by decimal places from larger to smaller. sort.SliceStable(underestimations, func(i, j int) bool { return underestimations[i].dec > underestimations[j].dec }) // Distribute extra values first to portions with larger decimal places. out := make([]int, len(data)) for _, d := range underestimations { if unitsLeft > 0 { d.portion += 1 unitsLeft -= 1 } out[d.index] = d.portion } return out, nil } func hasNegativeValue(data []Datum) bool { for _, d := range data { if d.Value < 0 { return true } } return false }
171
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package summarybar import ( "errors" "strings" "testing" "github.com/stretchr/testify/require" ) func Test_New(t *testing.T) { testCases := map[string]struct { inData []Datum inWidth int inEmptyRep string inOpts []Opt wantedSummaryBarComponent *summaryBarComponent wantedError error }{ "returns wanted bar component with no opts": { inData: []Datum{ { Value: 1, Representation: "W", }, { Value: 2, Representation: "H", }, { Value: 3, Representation: "A", }, }, wantedSummaryBarComponent: &summaryBarComponent{ width: 0, data: []Datum{ { Value: 1, Representation: "W", }, { Value: 2, Representation: "H", }, { Value: 3, Representation: "A", }, }, emptyRep: "", }, }, "returns wanted bar component with width": { inData: []Datum{ { Value: 1, Representation: "W", }, }, inOpts: []Opt{WithWidth(20)}, wantedSummaryBarComponent: &summaryBarComponent{ width: 20, data: []Datum{ { Value: 1, Representation: "W", }, }, emptyRep: "", }, }, "returns wanted bar component with empty representation": { inData: []Datum{ { Value: 1, Representation: "W", }, }, inOpts: []Opt{ WithEmptyRep("@"), }, wantedSummaryBarComponent: &summaryBarComponent{ width: 0, data: []Datum{ { Value: 1, Representation: "W", }, }, emptyRep: "@", }, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { component := New(tc.inData, tc.inOpts...) require.Equal(t, component, tc.wantedSummaryBarComponent) }) } } func TestSummaryBarComponent_Render(t *testing.T) { testCases := map[string]struct { inData []Datum inWidth int inEmptyRep string wantedError error wantedOut string }{ "error if width <= 0": { inData: []Datum{}, wantedError: errors.New("invalid width 0 for summary bar"), }, "error if data contains negative values": { inWidth: 10, inData: []Datum{ { Value: 1, Representation: "W", }, { Value: 0, Representation: "H", }, { Value: -1, Representation: "A", }, }, wantedError: errors.New("input data contains negative values"), }, "output empty bar if data is empty": { inWidth: 10, inEmptyRep: "@", inData: []Datum{}, wantedOut: "@@@@@@@@@@", }, "output empty bar if data sum up to 0": { inWidth: 10, inEmptyRep: "@", inData: []Datum{ { Value: 0, Representation: "W", }, { Value: 0, Representation: "H", }, { Value: 0, Representation: "A", }, }, wantedOut: "@@@@@@@@@@", }, "output correct bar when data sums up to length": { inWidth: 10, inEmptyRep: "@", inData: []Datum{ { Value: 1, Representation: "W", }, { Value: 5, Representation: "H", }, { Value: 4, Representation: "A", }, }, wantedOut: "WHHHHHAAAA", }, "output correct bar when data doesn't sum up to length": { inWidth: 10, inEmptyRep: "@", inData: []Datum{ { Value: 4, Representation: "W", }, { Value: 2, Representation: "H", }, { Value: 2, Representation: "A", }, { Value: 1, Representation: "T", }, }, wantedOut: "WWWWWHHAAT", }, "output correct bar when data sum exceeds length": { inWidth: 10, inEmptyRep: "@", inData: []Datum{ { Value: 4, Representation: "W", }, { Value: 3, Representation: "H", }, { Value: 6, Representation: "A", }, { Value: 3, Representation: "T", }, }, wantedOut: "WWHHAAAATT", }, "output correct bar when data is roughly uniform": { inWidth: 10, inEmptyRep: "@", inData: []Datum{ { Value: 2, Representation: "W", }, { Value: 3, Representation: "H", }, { Value: 3, Representation: "A", }, { Value: 3, Representation: "T", }, }, wantedOut: "WWHHHAAATT", }, "output correct bar when data is heavily skewed": { inWidth: 10, inEmptyRep: "@", inData: []Datum{ { Value: 23, Representation: "W", }, { Value: 3, Representation: "H", }, { Value: 3, Representation: "A", }, { Value: 3, Representation: "T", }, }, wantedOut: "WWWWWWWHAT", }, "output correct bar when data is extremely heavily skewed": { inWidth: 10, inEmptyRep: "@", inData: []Datum{ { Value: 233, Representation: "W", }, { Value: 3, Representation: "H", }, { Value: 3, Representation: "A", }, { Value: 3, Representation: "T", }, }, wantedOut: "WWWWWWWWWW", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { bar := summaryBarComponent{ data: tc.inData, width: tc.inWidth, emptyRep: tc.inEmptyRep, } buf := new(strings.Builder) _, err := bar.Render(buf) if tc.wantedError != nil { require.EqualError(t, err, tc.wantedError.Error()) } else { require.Equal(t, buf.String(), tc.wantedOut) } }) } }
317
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package prompt provides functionality to retrieve free-form text, selection, // and confirmation input from the user via a terminal. package prompt import ( "errors" "os" "strings" "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/core" "github.com/AlecAivazis/survey/v2/terminal" "github.com/aws/copilot-cli/internal/pkg/term/color" ) func init() { survey.ConfirmQuestionTemplate = `{{if not .Answer}} {{end}} {{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}} {{- if eq $i 0}} {{ $line }} {{ else }} {{ $line }} {{ end }}{{- end }}{{color "reset"}}{{end}} {{- color .Config.Icons.Question.Format }}{{if not .Answer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}} {{- color "default"}}{{ .Message }} {{color "reset"}} {{- if .Answer}} {{- color "default"}}{{.Answer}}{{color "reset"}}{{"\n"}} {{- else }} {{- if and .Help (not .ShowHelp)}}{{color "white"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}} {{- color "default"}}{{if .Default}}(Y/n) {{else}}(y/N) {{end}}{{color "reset"}} {{- end}}` survey.SelectQuestionTemplate = `{{if not .Answer}} {{end}} {{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}} {{- if eq $i 0}} {{ $line }} {{ else }} {{ $line }} {{ end }}{{- end }}{{color "reset"}}{{end}} {{- color .Config.Icons.Question.Format }}{{if not .ShowAnswer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}} {{- color "default"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}} {{- if .ShowAnswer}}{{color "default"}} {{parseAnswer .Answer}}{{color "reset"}}{{"\n"}} {{- else}} {{- " "}}{{- color "white"}}[Use arrows to move, type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}} {{- "\n"}} {{- range $ix, $choice := .PageEntries}} {{- if eq $ix $.SelectedIndex }}{{color "default+b" }} {{ $.Config.Icons.SelectFocus.Text }} {{else}}{{color "default"}} {{end}} {{- $choice.Value}} {{- color "reset"}}{{"\n"}} {{- end}} {{- end}}` survey.InputQuestionTemplate = `{{if not .ShowAnswer}} {{end}} {{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}} {{- if eq $i 0}} {{ $line }} {{ else }} {{ $line }} {{ end }}{{- end }}{{color "reset"}}{{end}} {{- color .Config.Icons.Question.Format }}{{if not .ShowAnswer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}} {{- color "default"}}{{ .Message }} {{color "reset"}} {{- if .ShowAnswer}} {{- color "default"}}{{.Answer}}{{color "reset"}}{{"\n"}} {{- else }} {{- if and .Help (not .ShowHelp)}}{{color "white"}}[{{ print .Config.HelpInput }} for help]{{color "reset"}} {{end}} {{- if .Default}}{{color "default"}}({{.Default}}) {{color "reset"}}{{end}} {{- .Answer -}} {{- end}}` survey.PasswordQuestionTemplate = ` {{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}} {{- if eq $i 0}} {{ $line }} {{ else }} {{ $line }} {{ end }}{{- end }}{{color "reset"}}{{end}} {{- color .Config.Icons.Question.Format }} {{ .Config.Icons.Question.Text }}{{color "reset"}} {{- color "default"}}{{ .Message }} {{color "reset"}} {{- if and .Help (not .ShowHelp)}}{{color "white"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}}` survey.MultiSelectQuestionTemplate = `{{if not .Answer}} {{end}} {{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}} {{- if eq $i 0}} {{ $line }} {{ else }} {{ $line }} {{ end }}{{- end }}{{color "reset"}}{{end}} {{- color .Config.Icons.Question.Format }}{{if not .ShowAnswer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}} {{- color "default"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}} {{- if .ShowAnswer}}{{color "default"}} {{parseAnswers .Answer}}{{color "reset"}}{{"\n"}} {{- else }} {{- " "}}{{- color "white"}}[Use arrows to move, space to select, type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}} {{- "\n"}} {{- range $ix, $option := .PageEntries}} {{- if eq $ix $.SelectedIndex }}{{color "default+b" }} {{ $.Config.Icons.SelectFocus.Text }}{{color "reset"}}{{else}} {{end}} {{- if index $.Checked $option.Index }}{{color "default+b" }} {{ $.Config.Icons.MarkedOption.Text }} {{else}}{{color "default" }} {{ $.Config.Icons.UnmarkedOption.Text }} {{end}} {{- color "reset"}} {{- " "}}{{$option.Value}}{{"\n"}} {{- end}} {{- end}}` split := func(s string, sep string) []string { return strings.Split(s, sep) } core.TemplateFuncsWithColor["split"] = split core.TemplateFuncsWithColor["parseAnswer"] = parseValueFromOptionFmt core.TemplateFuncsWithColor["parseAnswers"] = parseValuesFromOptions core.TemplateFuncsNoColor["split"] = split core.TemplateFuncsNoColor["parseAnswer"] = parseValueFromOptionFmt core.TemplateFuncsNoColor["parseAnswers"] = parseValuesFromOptions } // ErrEmptyOptions indicates the input options list was empty. var ErrEmptyOptions = errors.New("list of provided options is empty") // Prompt abstracts the survey.Askone function. type Prompt func(survey.Prompt, interface{}, ...survey.AskOpt) error // ValidatorFunc defines the function signature for validating inputs. type ValidatorFunc func(interface{}) error // New returns a Prompt with default configuration. func New() Prompt { return survey.AskOne } type prompter interface { Prompt(config *survey.PromptConfig) (interface{}, error) Cleanup(*survey.PromptConfig, interface{}) error Error(*survey.PromptConfig, error) error WithStdio(terminal.Stdio) } type prompt struct { prompter FinalMessage string // Text to display after the user selects an answer. } // Cleanup does a final render with the user's chosen value. // This method overrides survey.Select's Cleanup method by assigning the prompt's message to be the final message. func (p *prompt) Cleanup(config *survey.PromptConfig, val interface{}) error { if p.FinalMessage == "" { return p.prompter.Cleanup(config, val) // Delegate to the parent Cleanup. } // Update the message of the underlying struct. switch typedPrompt := p.prompter.(type) { case *survey.Select: typedPrompt.Message = p.FinalMessage case *survey.Input: typedPrompt.Message = p.FinalMessage case *passwordPrompt: typedPrompt.Message = p.FinalMessage case *survey.Confirm: typedPrompt.Message = p.FinalMessage case *survey.MultiSelect: typedPrompt.Message = p.FinalMessage } return p.prompter.Cleanup(config, val) } // Get prompts the user for free-form text input. func (p Prompt) Get(message, help string, validator ValidatorFunc, promptOpts ...PromptConfig) (string, error) { input := &survey.Input{ Message: message, } if help != "" { input.Help = color.Help(help) } prompt := &prompt{ prompter: input, } for _, opt := range promptOpts { opt(prompt) } var result string var err error if validator == nil { err = p(prompt, &result, stdio(), icons()) } else { err = p(prompt, &result, stdio(), validators(validator), icons()) } return result, err } type passwordPrompt struct { *survey.Password } // Cleanup renders a new template that's left-shifted when the user answers the prompt. func (pp *passwordPrompt) Cleanup(config *survey.PromptConfig, val interface{}) error { // The user already entered their password, move the cursor one level up to override the prompt. pp.Password.NewCursor().PreviousLine(1) // survey.Password unlike other survey structs doesn't have an "Answer" field. Therefore, we can't use a single // template like other prompts. Instead, when Cleanup is called, we render a new template // that behaves as if the question is answered. return pp.Password.Render(` {{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }}{{color "reset"}} {{- color "default"}}{{ .Message }} {{color "reset"}} `, survey.PasswordTemplateData{ Password: *pp.Password, Config: config, ShowHelp: false, }) } // GetSecret prompts the user for sensitive input. Wraps survey.Password func (p Prompt) GetSecret(message, help string, promptOpts ...PromptConfig) (string, error) { passwd := &passwordPrompt{ Password: &survey.Password{ Message: message, }, } if help != "" { passwd.Help = color.Help(help) } prompt := &prompt{ prompter: passwd, } for _, opt := range promptOpts { opt(prompt) } var result string err := p(prompt, &result, stdio(), icons()) return result, err } // Confirm prompts the user with a yes/no option. func (p Prompt) Confirm(message, help string, promptCfgs ...PromptConfig) (bool, error) { confirm := &survey.Confirm{ Message: message, } if help != "" { confirm.Help = color.Help(help) } prompt := &prompt{ prompter: confirm, } for _, cfg := range promptCfgs { cfg(prompt) } var result bool err := p(prompt, &result, stdio(), icons()) return result, err } // PromptConfig is a functional option to configure the prompt. type PromptConfig func(*prompt) // WithDefaultInput sets a default message for an input prompt. func WithDefaultInput(s string) PromptConfig { return func(p *prompt) { if get, ok := p.prompter.(*survey.Input); ok { get.Default = s } } } // WithFinalMessage sets a final message that replaces the question prompt once the user enters an answer. func WithFinalMessage(msg string) PromptConfig { return func(p *prompt) { p.FinalMessage = color.Emphasize(msg) } } // WithConfirmFinalMessage sets a short final message for to confirm the user's input. func WithConfirmFinalMessage() PromptConfig { return func(p *prompt) { p.FinalMessage = color.Emphasize("Sure?") } } // WithDefaultSelections selects the options to be checked by default for a multiselect prompt. func WithDefaultSelections(options []string) PromptConfig { return func(p *prompt) { if confirm, ok := p.prompter.(*survey.MultiSelect); ok { confirm.Default = options } } } // WithTrueDefault sets the default for a confirm prompt to true. func WithTrueDefault() PromptConfig { return func(p *prompt) { if confirm, ok := p.prompter.(*survey.Confirm); ok { confirm.Default = true } } } func stdio() survey.AskOpt { return survey.WithStdio(os.Stdin, os.Stderr, os.Stderr) } func icons() survey.AskOpt { return survey.WithIcons(func(icons *survey.IconSet) { // The question mark "?" icon to denote a prompt will be colored in bold. icons.Question.Text = "" icons.Question.Format = "default+b" // Survey uses https://github.com/mgutz/ansi to set colors which unfortunately doesn't support the "Faint" style. // We are setting the help text to be fainted in the individual prompt methods instead. icons.Help.Text = "" icons.Help.Format = "default" }) } // RequireNonEmpty returns an error if v is a zero-value. func RequireNonEmpty(v interface{}) error { return survey.Required(v) } // RequireMinItems enforces at least min elements to be selected from MultiSelect. func RequireMinItems(min int) ValidatorFunc { return (ValidatorFunc)(survey.MinItems(min)) } func validators(validatorFunc ValidatorFunc) survey.AskOpt { return survey.WithValidator(survey.ComposeValidators(survey.Required, survey.Validator(validatorFunc))) }
325
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package prompt import ( "fmt" "testing" "github.com/AlecAivazis/survey/v2" "github.com/stretchr/testify/require" ) func TestPrompt_Get(t *testing.T) { mockError := fmt.Errorf("error") mockInput := "yes" mockDefaultInput := "yes" mockMessage := "mockMessage" mockHelpMessage := "mockHelpMessage" mockFinalMessage := "mockFinalMessage" testCases := map[string]struct { inValidator ValidatorFunc inPrompt Prompt wantValue string wantError error }{ "should return users input": { inValidator: func(ans interface{}) error { return nil }, inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { internalPrompt, ok := p.(*prompt) require.True(t, ok, "input prompt should be type *prompt") require.Equal(t, mockFinalMessage, internalPrompt.FinalMessage) input, ok := internalPrompt.prompter.(*survey.Input) require.True(t, ok, "internal prompt should be type *survey.Input") require.Equal(t, mockMessage, input.Message) require.Equal(t, mockHelpMessage, input.Help) require.Equal(t, mockDefaultInput, input.Default) result, ok := out.(*string) require.True(t, ok, "type to write user input to should be a string") *result = mockInput require.Equal(t, 3, len(opts)) return nil }, wantValue: mockInput, wantError: nil, }, "should echo error": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { return mockError }, wantError: mockError, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { gotValue, gotError := tc.inPrompt.Get(mockMessage, mockHelpMessage, tc.inValidator, WithDefaultInput(mockDefaultInput), WithFinalMessage(mockFinalMessage)) require.Equal(t, tc.wantValue, gotValue) require.Equal(t, tc.wantError, gotError) }) } } func TestPrompt_GetSecret(t *testing.T) { mockError := fmt.Errorf("error") mockMessage := "What's your super secret password?" mockSecret := "password" testCases := map[string]struct { inPrompt Prompt wantValue string wantError error }{ "should return true": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { internalPrompt, ok := p.(*prompt) require.True(t, ok, "input prompt should be type *prompt") require.Empty(t, internalPrompt.FinalMessage) passwd, ok := internalPrompt.prompter.(*passwordPrompt) require.True(t, ok, "internal prompt should be type *passwordPrompt") require.Equal(t, mockMessage, passwd.Message) require.Empty(t, passwd.Help) result, ok := out.(*string) require.True(t, ok, "type to write user input to should be a string") *result = mockSecret require.Equal(t, 2, len(opts)) return nil }, wantValue: mockSecret, wantError: nil, }, "should echo error": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { return mockError }, wantError: mockError, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { gotValue, gotError := tc.inPrompt.GetSecret(mockMessage, "") require.Equal(t, tc.wantValue, gotValue) require.Equal(t, tc.wantError, gotError) }) } } func TestPrompt_Confirm(t *testing.T) { mockError := fmt.Errorf("error") mockMessage := "Is devx awesome?" mockHelpMessage := "Yes." mockFinalMessage := "Awesome" testCases := map[string]struct { inPrompt Prompt wantValue bool wantError error }{ "should return true": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { internalPrompt, ok := p.(*prompt) require.True(t, ok, "input prompt should be type *prompt") require.Equal(t, mockFinalMessage, internalPrompt.FinalMessage) confirm, ok := internalPrompt.prompter.(*survey.Confirm) require.True(t, ok, "internal prompt should be type *survey.Confirm") require.Equal(t, mockMessage, confirm.Message) require.Equal(t, mockHelpMessage, confirm.Help) require.True(t, confirm.Default) result, ok := out.(*bool) require.True(t, ok, "type to write user input to should be a bool") *result = true require.Equal(t, 2, len(opts)) return nil }, wantValue: true, wantError: nil, }, "should echo error": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { return mockError }, wantError: mockError, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { gotValue, gotError := tc.inPrompt.Confirm(mockMessage, mockHelpMessage, WithTrueDefault(), WithFinalMessage(mockFinalMessage)) require.Equal(t, tc.wantValue, gotValue) require.Equal(t, tc.wantError, gotError) }) } }
183
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package prompt import ( "fmt" "regexp" "strings" "text/tabwriter" "github.com/AlecAivazis/survey/v2" "github.com/aws/copilot-cli/internal/pkg/term/color" ) // Configuration while spacing text with a tabwriter. const ( minCellWidth = 20 // minimum number of characters in a table's cell. tabWidth = 4 // number of characters in between columns. cellPaddingWidth = 2 // number of padding characters added by default to a cell. paddingChar = ' ' // character in between columns. noAdditionalFormatting = 0 ) // SGR(Select Graphic Rendition) is used to colorize outputs in terminals. // Example matches: // '\x1b[2m' (for Faint output) // '\x1b[1;31m' (for bold, red output) const ( sgrStart = "\x1b\\[" // SGR sequences start with "ESC[". sgrEnd = "m" // SGR sequences end with "m". sgrParameter = "[0-9]{1,3}" // SGR parameter values range from 0 to 107. ) var ( sgrParameterGroups = fmt.Sprintf("%s(;%s)*", sgrParameter, sgrParameter) // One or more SGR parameters separated by ";" sgr = fmt.Sprintf("%s(%s)?%s", sgrStart, sgrParameterGroups, sgrEnd) // A complete SGR sequence: \x1b\\[([0-9]{1,2,3}(;[0-9]{1,2,3})*)?m ) var regexpSGR = regexp.MustCompile(sgr) // Option represents a choice with a hint for clarification. type Option struct { Value string // The actual value represented by the option. FriendlyText string // An optional FriendlyText displayed in place of Value. Hint string // An optional Hint displayed alongside the Value or FriendlyText. } // String implements the fmt.Stringer interface. func (o Option) String() string { text := o.Value if o.FriendlyText != "" { text = o.FriendlyText } if o.Hint == "" { return fmt.Sprintf("%s\t", text) } return fmt.Sprintf("%s\t%s", text, color.Faint.Sprintf("(%s)", o.Hint)) } // SelectOption prompts the user to select one option from options and returns the Value of the option. func (p Prompt) SelectOption(message, help string, opts []Option, promptCfgs ...PromptConfig) (value string, err error) { if len(opts) <= 0 { return "", ErrEmptyOptions } prettified, err := prettifyOptions(opts) if err != nil { return "", err } result, err := p.SelectOne(message, help, prettified.choices, promptCfgs...) if err != nil { return "", err } return prettified.choice2Value[result], nil } // MultiSelectOptions prompts the user to select multiple options and returns the value field from the options. func (p Prompt) MultiSelectOptions(message, help string, opts []Option, promptCfgs ...PromptConfig) ([]string, error) { if len(opts) <= 0 { return nil, ErrEmptyOptions } prettified, err := prettifyOptions(opts) if err != nil { return nil, err } choices, err := p.MultiSelect(message, help, prettified.choices, nil, promptCfgs...) if err != nil { return nil, err } values := make([]string, len(choices)) for i, choice := range choices { values[i] = prettified.choice2Value[choice] } return values, nil } // SelectOne prompts the user with a list of options to choose from with the arrow keys. func (p Prompt) SelectOne(message, help string, options []string, promptCfgs ...PromptConfig) (string, error) { if len(options) <= 0 { return "", ErrEmptyOptions } sel := &survey.Select{ Message: message, Options: options, Default: options[0], } if help != "" { sel.Help = color.Help(help) } prompt := &prompt{ prompter: sel, } for _, cfg := range promptCfgs { cfg(prompt) } var result string err := p(prompt, &result, stdio(), icons()) return result, err } // MultiSelect prompts the user with a list of options to choose from with the arrow keys and enter key. func (p Prompt) MultiSelect(message, help string, options []string, validator ValidatorFunc, promptCfgs ...PromptConfig) ([]string, error) { if len(options) <= 0 { // returns nil slice if error return nil, ErrEmptyOptions } multiselect := &survey.MultiSelect{ Message: message, Options: options, Default: options[0], } if help != "" { multiselect.Help = color.Help(help) } prompt := &prompt{ prompter: multiselect, } for _, cfg := range promptCfgs { cfg(prompt) } var result []string var err error if validator == nil { err = p(prompt, &result, stdio(), icons()) } else { err = p(prompt, &result, stdio(), validators(validator), icons()) } return result, err } type prettyOptions struct { choices []string choice2Value map[string]string } func prettifyOptions(opts []Option) (prettyOptions, error) { buf := new(strings.Builder) tw := tabwriter.NewWriter(buf, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting) var lines []string for _, opt := range opts { lines = append(lines, opt.String()) } if _, err := tw.Write([]byte(strings.Join(lines, "\n"))); err != nil { return prettyOptions{}, fmt.Errorf("render options: %v", err) } if err := tw.Flush(); err != nil { return prettyOptions{}, fmt.Errorf("flush tabwriter options: %v", err) } choices := strings.Split(buf.String(), "\n") choice2Value := make(map[string]string) for idx, choice := range choices { choice2Value[choice] = opts[idx].Value } return prettyOptions{ choices: choices, choice2Value: choice2Value, }, nil } func parseValueFromOptionFmt(formatted string) string { if idx := strings.Index(formatted, "("); idx != -1 { s := regexpSGR.ReplaceAllString(formatted[:idx], "") return strings.TrimSpace(s) } return strings.TrimSpace(formatted) } func parseValuesFromOptions(formatted string) string { options := strings.Split(formatted, ", ") out := make([]string, len(options)) for i, option := range options { out[i] = parseValueFromOptionFmt(option) } return strings.Join(out, ", ") }
202
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package prompt import ( "fmt" "testing" "github.com/AlecAivazis/survey/v2" "github.com/stretchr/testify/require" ) func TestOption_String(t *testing.T) { testCases := map[string]struct { input Option wanted string }{ "should render the value with a tab if there is no hint": { input: Option{ Value: "Help me decide!", }, wanted: "Help me decide!\t", }, "should render a hint in parenthesis separated by a tab": { input: Option{ Value: "Load Balanced Web Service", Hint: "ELB -> ECS on Fargate", }, wanted: "Load Balanced Web Service\t(ELB -> ECS on Fargate)", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { require.Equal(t, tc.wanted, tc.input.String()) }) } } func TestPrompt_SelectOption(t *testing.T) { t.Run("should return ErrEmptyOptions if there are no options", func(t *testing.T) { _, err := New().SelectOption("to be or not to be?", "this is the question", nil) require.EqualError(t, err, ErrEmptyOptions.Error()) }) t.Run("should return value without hint", func(t *testing.T) { // GIVEN var p Prompt = func(p survey.Prompt, out interface{}, _ ...survey.AskOpt) error { sel := p.(*prompt).prompter.(*survey.Select) require.ElementsMatch(t, []string{ "Load Balanced Web Service (ELB -> ECS on Fargate)", "Backend Service (ECS on Fargate)", "Scheduled Job (CW Event -> StateMachine -> Fargate)", }, sel.Options) result := out.(*string) *result = "Load Balanced Web Service (ELB -> ECS on Fargate)" return nil } opts := []Option{ { Value: "Load Balanced Web Service", Hint: "ELB -> ECS on Fargate", }, { Value: "Backend Service", Hint: "ECS on Fargate", }, { Value: "Scheduled Job", Hint: "CW Event -> StateMachine -> Fargate", }, } // WHEN actual, err := p.SelectOption("Which workload type?", "choose!", opts) // THEN require.NoError(t, err) require.Equal(t, "Load Balanced Web Service", actual) }) t.Run("should return value without extra spaces when there are no hints", func(t *testing.T) { // GIVEN var p Prompt = func(p survey.Prompt, out interface{}, _ ...survey.AskOpt) error { sel := p.(*prompt).prompter.(*survey.Select) require.ElementsMatch(t, []string{ "Load Balanced Web Service (ELB -> ECS on Fargate)", "Help me decide! ", "Backend Service (ECS on Fargate)", }, sel.Options) result := out.(*string) *result = "Help me decide! " return nil } opts := []Option{ { Value: "Load Balanced Web Service", Hint: "ELB -> ECS on Fargate", }, { Value: "Help me decide!", }, { Value: "Backend Service", Hint: "ECS on Fargate", }, } // WHEN actual, err := p.SelectOption("Which workload type?", "choose!", opts) // THEN require.NoError(t, err) require.Equal(t, "Help me decide!", actual) }) t.Run("should return value instead of friendly text", func(t *testing.T) { // GIVEN var p Prompt = func(p survey.Prompt, out interface{}, _ ...survey.AskOpt) error { sel := p.(*prompt).prompter.(*survey.Select) require.ElementsMatch(t, []string{ "Friendly Load Balanced Web Service (ELB -> ECS on Fargate)", "Friendly Backend Service (ECS on Fargate)", "Friendly Scheduled Job (CW Event -> StateMachine -> Fargate)", }, sel.Options) result := out.(*string) *result = "Friendly Load Balanced Web Service (ELB -> ECS on Fargate)" return nil } opts := []Option{ { Value: "Load Balanced Web Service", Hint: "ELB -> ECS on Fargate", FriendlyText: "Friendly Load Balanced Web Service", }, { Value: "Backend Service", Hint: "ECS on Fargate", FriendlyText: "Friendly Backend Service", }, { Value: "Scheduled Job", Hint: "CW Event -> StateMachine -> Fargate", FriendlyText: "Friendly Scheduled Job", }, } // WHEN actual, err := p.SelectOption("Which workload type?", "choose!", opts) // THEN require.NoError(t, err) require.Equal(t, "Load Balanced Web Service", actual) }) t.Run("should return value instead of friendly text without extra spaces when there are no hints", func(t *testing.T) { // GIVEN var p Prompt = func(p survey.Prompt, out interface{}, _ ...survey.AskOpt) error { sel := p.(*prompt).prompter.(*survey.Select) require.ElementsMatch(t, []string{ "Load Balanced Web Service (ELB -> ECS on Fargate)", "Friend! Help me decide! ", "Backend Service (ECS on Fargate)", }, sel.Options) result := out.(*string) *result = "Friend! Help me decide! " return nil } opts := []Option{ { Value: "Load Balanced Web Service", Hint: "ELB -> ECS on Fargate", }, { Value: "Help me decide!", FriendlyText: "Friend! Help me decide!", }, { Value: "Backend Service", Hint: "ECS on Fargate", }, } // WHEN actual, err := p.SelectOption("Which workload type?", "choose!", opts) // THEN require.NoError(t, err) require.Equal(t, "Help me decide!", actual) }) } func TestPrompt_MultiSelectOptions(t *testing.T) { // GIVEN var p Prompt = func(p survey.Prompt, out interface{}, _ ...survey.AskOpt) error { sel := p.(*prompt).prompter.(*survey.MultiSelect) require.ElementsMatch(t, []string{ "Service (AWS::ECS::Service)", "DiscoveryService (AWS::ServiceDiscovery::Service)", "PublicNetworkLoadBalancer (AWS::ElasticLoadBalancingV2::LoadBalancer)", }, sel.Options) result := out.(*[]string) *result = []string{ "Service (AWS::ECS::Service)", "PublicNetworkLoadBalancer (AWS::ElasticLoadBalancingV2::LoadBalancer)", } return nil } opts := []Option{ { Value: "Service", Hint: "AWS::ECS::Service", }, { Value: "DiscoveryService", Hint: "AWS::ServiceDiscovery::Service", }, { Value: "PublicNetworkLoadBalancer", Hint: "AWS::ElasticLoadBalancingV2::LoadBalancer", }, } // WHEN actual, err := p.MultiSelectOptions("Which resource?", "choose!", opts) // THEN require.NoError(t, err) require.Equal(t, []string{"Service", "PublicNetworkLoadBalancer"}, actual) } func TestPrompt_SelectOne(t *testing.T) { mockError := fmt.Errorf("error") mockMessage := "Which droid is best droid?" testCases := map[string]struct { inPrompt Prompt inOpts []string wantValue string wantError error }{ "should return users input": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { internalPrompt, ok := p.(*prompt) require.True(t, ok, "input prompt should be type *prompt") require.Empty(t, internalPrompt.FinalMessage) sel, ok := internalPrompt.prompter.(*survey.Select) require.True(t, ok, "internal prompt should be type *survey.Select") require.Equal(t, mockMessage, sel.Message) require.Empty(t, sel.Help) require.NotEmpty(t, sel.Options) result, ok := out.(*string) require.True(t, ok, "type to write user input to should be a string") *result = sel.Options[0] require.Equal(t, 2, len(opts)) return nil }, inOpts: []string{"r2d2", "c3po", "bb8"}, wantValue: "r2d2", wantError: nil, }, "should echo error": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { return mockError }, inOpts: []string{"apple", "orange", "banana"}, wantError: mockError, }, "should return error if input options list is empty": { inOpts: []string{}, wantError: ErrEmptyOptions, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { gotValue, gotError := tc.inPrompt.SelectOne(mockMessage, "", tc.inOpts) require.Equal(t, tc.wantValue, gotValue) require.Equal(t, tc.wantError, gotError) }) } } func TestPrompt_MultiSelect(t *testing.T) { mockError := fmt.Errorf("error") mockMessage := "Which dogs are best?" mockFinalMessage := "Best dogs:" testCases := map[string]struct { inPrompt Prompt inOpts []string wantValue []string wantError error }{ "should return users input": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { internalPrompt, ok := p.(*prompt) require.True(t, ok, "input prompt should be type *prompt") require.Equal(t, mockFinalMessage, internalPrompt.FinalMessage) sel, ok := internalPrompt.prompter.(*survey.MultiSelect) require.True(t, ok, "internal prompt should be type *survey.MultiSelect") require.Equal(t, mockMessage, sel.Message) require.Empty(t, sel.Help) require.NotEmpty(t, sel.Options) result, ok := out.(*[]string) require.True(t, ok, "type to write user input to should be a string") *result = sel.Options require.Equal(t, 2, len(opts)) return nil }, inOpts: []string{"bowie", "clyde", "keno", "cava", "meow"}, wantValue: []string{"bowie", "clyde", "keno", "cava", "meow"}, wantError: nil, }, "should echo error": { inPrompt: func(p survey.Prompt, out interface{}, opts ...survey.AskOpt) error { return mockError }, inOpts: []string{"apple", "orange", "banana"}, wantError: mockError, }, "should return error if input options list is empty": { inOpts: []string{}, wantError: ErrEmptyOptions, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { gotValue, gotError := tc.inPrompt.MultiSelect(mockMessage, "", tc.inOpts, nil, WithFinalMessage(mockFinalMessage)) require.Equal(t, tc.wantValue, gotValue) require.Equal(t, tc.wantError, gotError) }) } }
349
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "fmt" "sort" "strings" "github.com/aws/copilot-cli/internal/pkg/template" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "gopkg.in/yaml.v3" ) // CFNSelector represents a selector for a CloudFormation template. type CFNSelector struct { prompt Prompter } // NewCFNSelector initializes a CFNSelector. func NewCFNSelector(prompt Prompter) *CFNSelector { return &CFNSelector{ prompt: prompt, } } // Resources prompts the user to multiselect resources from a CloudFormation template body. // By default, the prompt filters out any custom resource in the template. func (sel *CFNSelector) Resources(msg, finalMsg, help, body string) ([]template.CFNResource, error) { tpl := struct { Resources map[string]struct { Type string `yaml:"Type"` } `yaml:"Resources"` }{} if err := yaml.Unmarshal([]byte(body), &tpl); err != nil { return nil, fmt.Errorf("unmarshal CloudFormation template: %v", err) } // Prompt for a selection. var options []prompt.Option for name, resource := range tpl.Resources { if resource.Type == "AWS::Lambda::Function" || strings.HasPrefix(resource.Type, "Custom::") { continue } options = append(options, prompt.Option{ Value: name, Hint: resource.Type, }) } sort.Slice(options, func(i, j int) bool { // Sort options by resource type, if they're the same resource type then sort by logicalID. if options[i].Hint == options[j].Hint { return options[i].Value < options[j].Value } return options[i].Hint < options[j].Hint }) logicalIDs, err := sel.prompt.MultiSelectOptions(msg, help, options, prompt.WithFinalMessage(finalMsg)) if err != nil { return nil, fmt.Errorf("select CloudFormation resources: %v", err) } // Transform to template.CFNResource out := make([]template.CFNResource, len(logicalIDs)) for i, logicalID := range logicalIDs { out[i] = template.CFNResource{ Type: template.CFNType(tpl.Resources[logicalID].Type), LogicalID: logicalID, } } return out, nil }
72
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "errors" "testing" "github.com/aws/copilot-cli/internal/pkg/template" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "github.com/aws/copilot-cli/internal/pkg/term/selector/mocks" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) func TestCFNSelector_Resources(t *testing.T) { t.Run("should return a wrapped error if prompting fails", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() // GIVEN mockPrompt := mocks.NewMockPrompter(ctrl) mockPrompt.EXPECT(). MultiSelectOptions(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, errors.New("some error")) sel := NewCFNSelector(mockPrompt) // WHEN _, err := sel.Resources("", "", "", "") // THEN require.EqualError(t, err, "select CloudFormation resources: some error") }) t.Run("should filter out custom resource when prompting", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() // GIVEN mockPrompt := mocks.NewMockPrompter(ctrl) mockPrompt.EXPECT(). MultiSelectOptions(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). DoAndReturn(func(_, _ string, opts []prompt.Option, _ ...prompt.PromptConfig) ([]string, error) { require.ElementsMatch(t, []prompt.Option{ { Value: "LogGroup", Hint: "AWS::Logs::LogGroup", }, { Value: "AutoScalingTarget", Hint: "AWS::ApplicationAutoScaling::ScalableTarget", }, }, opts) return nil, nil }) body := ` Resources: LogGroup: Type: AWS::Logs::LogGroup DynamicDesiredCountFunction: Type: AWS::Lambda::Function DynamicDesiredCountAction: Type: Custom::DynamicDesiredCountFunction AutoScalingTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget ` sel := NewCFNSelector(mockPrompt) // WHEN _, err := sel.Resources("", "", "", body) // THEN require.NoError(t, err) }) t.Run("should transform selected options", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() // GIVEN mockPrompt := mocks.NewMockPrompter(ctrl) mockPrompt.EXPECT(). MultiSelectOptions(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return([]string{"LogGroup", "Service"}, nil) body := ` Resources: LogGroup: Type: AWS::Logs::LogGroup AutoScalingTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Service: Type: AWS::ECS::Service ` sel := NewCFNSelector(mockPrompt) // WHEN actual, err := sel.Resources("", "", "", body) // THEN require.NoError(t, err) require.ElementsMatch(t, []template.CFNResource{ { Type: "AWS::Logs::LogGroup", LogicalID: "LogGroup", }, { Type: "AWS::ECS::Service", LogicalID: "Service", }, }, actual) }) }
113
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "fmt" "strings" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/copilot-cli/internal/pkg/aws/sessions" "github.com/aws/copilot-cli/internal/pkg/term/prompt" ) const ( tempCredsOption = "Enter temporary credentials" accessKeyIDPrompt = "What's your AWS Access Key ID?" secretAccessKeyPrompt = "What's your AWS Secret Access Key?" sessionTokenPrompt = "What's your AWS Session Token?" ) // Names wraps the method that returns a list of names. type Names interface { Names() []string } // SessionProvider wraps the methods to create AWS sessions. type SessionProvider interface { Default() (*session.Session, error) FromProfile(name string) (*session.Session, error) FromStaticCreds(accessKeyID, secretAccessKey, sessionToken string) (*session.Session, error) } // CredsSelect prompts users for credentials. type CredsSelect struct { Prompt Prompter Profile Names Session SessionProvider } // Creds prompts users to choose either use temporary credentials or choose from one of their existing AWS named profiles. func (s *CredsSelect) Creds(msg, help string) (*session.Session, error) { profileFrom := make(map[string]string) options := []string{tempCredsOption} for _, name := range s.Profile.Names() { pretty := fmt.Sprintf("[profile %s]", name) options = append(options, pretty) profileFrom[pretty] = name } selected, err := s.Prompt.SelectOne( msg, help, options, prompt.WithFinalMessage("Credential source:")) if err != nil { return nil, fmt.Errorf("select credential source: %w", err) } if selected == tempCredsOption { return s.askTempCreds() } sess, err := s.Session.FromProfile(profileFrom[selected]) if err != nil { return nil, fmt.Errorf("create session from profile %s: %w", profileFrom[selected], err) } return sess, nil } func (s *CredsSelect) askTempCreds() (*session.Session, error) { defaultAccessKey, defaultSecretAccessKey, defaultSessToken := defaultCreds(s.Session) accessKeyID, err := s.askWithMaskedDefault(accessKeyIDPrompt, defaultAccessKey, prompt.RequireNonEmpty, prompt.WithFinalMessage("AWS Access Key ID:")) if err != nil { return nil, fmt.Errorf("get access key id: %w", err) } secretAccessKey, err := s.askWithMaskedDefault(secretAccessKeyPrompt, defaultSecretAccessKey, prompt.RequireNonEmpty, prompt.WithFinalMessage("AWS Secret Access Key:")) if err != nil { return nil, fmt.Errorf("get secret access key: %w", err) } sessionToken, err := s.askWithMaskedDefault(sessionTokenPrompt, defaultSessToken, nil, prompt.WithFinalMessage("AWS Session Token:")) if err != nil { return nil, fmt.Errorf("get session token: %w", err) } sess, err := s.Session.FromStaticCreds(accessKeyID, secretAccessKey, sessionToken) if err != nil { return nil, fmt.Errorf("create session from temporary credentials: %w", err) } return sess, nil } func (s *CredsSelect) askWithMaskedDefault(msg, defaultValue string, f prompt.ValidatorFunc, opts ...prompt.PromptConfig) (string, error) { accessKeyId, err := s.Prompt.Get(msg, "", f, append([]prompt.PromptConfig{prompt.WithDefaultInput(mask(defaultValue))}, opts...)...) if err != nil { return "", err } if accessKeyId == mask(defaultValue) { // Return the original default instead of the masked value. return defaultValue, nil } return accessKeyId, nil } // defaultCreds returns the credential values from the default session. // If an error occurs, returns empty strings. func defaultCreds(session SessionProvider) (accessKeyID, secretAccessKey, sessionToken string) { // If we cannot retrieve default creds, return empty credentials as default instead of an error. defaultSess, err := session.Default() if err != nil { return } v, err := sessions.Creds(defaultSess) if err != nil { return } return v.AccessKeyID, v.SecretAccessKey, v.SessionToken } // mask hides the value of s with "*"s except the last 4 characters. // Taken from the AWS CLI, see: // https://github.com/aws/aws-cli/blob/4ff0cbacbac69a21d4dd701921fe0759cf7852ed/awscli/customizations/configure/__init__.py#L38-L42 // TODO(efekarakus): Move the masking logic to be part of the prompt package. func mask(s string) string { if s == "" { return "" } hint := s if len(hint) >= 4 { hint = hint[len(hint)-4:] } return fmt.Sprintf("%s%s", strings.Repeat("*", 16), hint) }
135
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/copilot-cli/internal/pkg/term/selector/mocks" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) // mockProvider implements the AWS SDK's credentials.Provider interface. type mockProvider struct { value credentials.Value err error } func (m mockProvider) Retrieve() (credentials.Value, error) { if m.err != nil { return credentials.Value{}, m.err } return m.value, nil } func (m mockProvider) IsExpired() bool { return false } func TestCredsSelect_Creds(t *testing.T) { testCases := map[string]struct { inMsg string inHelp string given func(ctrl *gomock.Controller) *CredsSelect wantedErr error }{ "should create a session from a named profile": { inMsg: "message", inHelp: "help", given: func(ctrl *gomock.Controller) *CredsSelect { profile := mocks.NewMockNames(ctrl) profile.EXPECT().Names().Return([]string{"test", "prod"}) prompter := mocks.NewMockPrompter(ctrl) prompter.EXPECT().SelectOne("message", "help", []string{ "Enter temporary credentials", "[profile test]", "[profile prod]", }, gomock.Any()).Return("[profile prod]", nil) provider := mocks.NewMockSessionProvider(ctrl) provider.EXPECT().FromProfile("prod").Return(&session.Session{}, nil) return &CredsSelect{ Prompt: prompter, Profile: profile, Session: provider, } }, }, "should create a session from temporary credentials with masked prompt": { given: func(ctrl *gomock.Controller) *CredsSelect { profile := mocks.NewMockNames(ctrl) profile.EXPECT().Names().Return(nil) prompter := mocks.NewMockPrompter(ctrl) prompter.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("Enter temporary credentials", nil) provider := mocks.NewMockSessionProvider(ctrl) provider.EXPECT().Default().Return(&session.Session{ Config: &aws.Config{ Credentials: credentials.NewCredentials(mockProvider{ value: credentials.Value{ AccessKeyID: "11111", SecretAccessKey: "22222", SessionToken: "33333", }, }), }, }, nil) prompter.EXPECT().Get("What's your AWS Access Key ID?", "", gomock.Any(), gomock.Any()). Return("****************1111", nil) prompter.EXPECT().Get("What's your AWS Secret Access Key?", "", gomock.Any(), gomock.Any()). Return("****************2222", nil) prompter.EXPECT().Get("What's your AWS Session Token?", "", nil, gomock.Any()). Return("****************3333", nil) provider.EXPECT().FromStaticCreds("11111", "22222", "33333"). Return(&session.Session{}, nil) return &CredsSelect{ Prompt: prompter, Profile: profile, Session: provider, } }, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() sel := tc.given(ctrl) _, err := sel.Creds(tc.inMsg, tc.inHelp) if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.NoError(t, err) } }) } }
122
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package selector provides functionality for users to select an application, environment, or service name. package selector import ( "fmt" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "github.com/aws/copilot-cli/internal/pkg/aws/ec2" ) // VPCSubnetLister list VPCs and subnets. type VPCSubnetLister interface { ListVPCs() ([]ec2.VPC, error) ListVPCSubnets(vpcID string) (*ec2.VPCSubnets, error) } // EC2Select is a selector for Ec2 resources. type EC2Select struct { prompt Prompter ec2Svc VPCSubnetLister } // NewEC2Select returns a new selector that chooses Ec2 resources. func NewEC2Select(prompt Prompter, ec2Client VPCSubnetLister) *EC2Select { return &EC2Select{ prompt: prompt, ec2Svc: ec2Client, } } // VPC has the user select an available VPC. func (s *EC2Select) VPC(msg, help string) (string, error) { vpcs, err := s.ec2Svc.ListVPCs() if err != nil { return "", fmt.Errorf("list VPC ID: %w", err) } if len(vpcs) == 0 { return "", ErrVPCNotFound } var options []string for _, vpc := range vpcs { stringifiedVPC := vpc.String() options = append(options, stringifiedVPC) } vpc, err := s.prompt.SelectOne( msg, help, options, prompt.WithFinalMessage("VPC:")) if err != nil { return "", fmt.Errorf("select VPC: %w", err) } extractedVPC, err := ec2.ExtractVPC(vpc) if err != nil { return "", fmt.Errorf("extract VPC ID: %w", err) } return extractedVPC.ID, nil } // SubnetsInput holds the arguments for the subnet selector. type SubnetsInput struct { Msg string Help string VPCID string IsPublic bool } // Subnets has the user multiselect subnets given the VPC ID. func (s *EC2Select) Subnets(in SubnetsInput) ([]string, error) { return s.selectFromVPCSubnets(in) } func (s *EC2Select) selectFromVPCSubnets(in SubnetsInput) ([]string, error) { allSubnets, err := s.ec2Svc.ListVPCSubnets(in.VPCID) if err != nil { return nil, fmt.Errorf("list subnets for VPC %s: %w", in.VPCID, err) } if in.IsPublic { return s.selectSubnets(in.Msg, in.Help, allSubnets.Public, prompt.WithFinalMessage("Public subnets:")) } return s.selectSubnets(in.Msg, in.Help, allSubnets.Private, prompt.WithFinalMessage("Private subnets:")) } func (s *EC2Select) selectSubnets(msg, help string, subnets []ec2.Subnet, opts ...prompt.PromptConfig) ([]string, error) { if len(subnets) == 0 { return nil, ErrSubnetsNotFound } var options []string for _, subnet := range subnets { stringifiedSubnet := subnet.String() options = append(options, stringifiedSubnet) } selectedSubnets, err := s.prompt.MultiSelect( msg, help, options, nil, opts...) if err != nil { return nil, err } var extractedSubnets []string for _, s := range selectedSubnets { extractedSubnet, err := ec2.ExtractSubnet(s) if err != nil { return nil, fmt.Errorf("extract subnet ID: %w", err) } extractedSubnets = append(extractedSubnets, extractedSubnet.ID) } return extractedSubnets, nil }
115
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "errors" "fmt" "testing" "github.com/aws/copilot-cli/internal/pkg/aws/ec2" "github.com/aws/copilot-cli/internal/pkg/term/selector/mocks" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) type ec2SelectMocks struct { prompt *mocks.MockPrompter ec2Svc *mocks.MockVPCSubnetLister } func TestEc2Select_VPC(t *testing.T) { mockErr := errors.New("some error") testCases := map[string]struct { setupMocks func(mocks ec2SelectMocks) wantErr error wantVPC string }{ "return error if fail to list VPCs": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCs().Return(nil, mockErr) }, wantErr: fmt.Errorf("list VPC ID: some error"), }, "return error if no VPC found": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCs().Return([]ec2.VPC{}, nil) }, wantErr: ErrVPCNotFound, }, "return error if fail to select a VPC": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCs().Return([]ec2.VPC{ { Resource: ec2.Resource{ ID: "mockVPC1", }, }, { Resource: ec2.Resource{ ID: "mockVPC2", }, }, }, nil) m.prompt.EXPECT().SelectOne("Select a VPC", "Help text", []string{"mockVPC1", "mockVPC2"}, gomock.Any()). Return("", mockErr) }, wantErr: fmt.Errorf("select VPC: some error"), }, "success": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCs().Return([]ec2.VPC{ { Resource: ec2.Resource{ ID: "mockVPCID1", }, }, { Resource: ec2.Resource{ ID: "mockVPCID2", Name: "mockVPC2Name", }, }, }, nil) m.prompt.EXPECT().SelectOne("Select a VPC", "Help text", []string{"mockVPCID1", "mockVPCID2 (mockVPC2Name)"}, gomock.Any()). Return("mockVPC1", nil) }, wantVPC: "mockVPC1", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockec2Svc := mocks.NewMockVPCSubnetLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := ec2SelectMocks{ ec2Svc: mockec2Svc, prompt: mockprompt, } tc.setupMocks(mocks) sel := EC2Select{ prompt: mockprompt, ec2Svc: mockec2Svc, } vpc, err := sel.VPC("Select a VPC", "Help text") if tc.wantErr != nil { require.EqualError(t, tc.wantErr, err.Error()) } else { require.Equal(t, tc.wantVPC, vpc) } }) } } func TestEc2Select_Subnets(t *testing.T) { mockErr := errors.New("some error") mockVPC := "mockVPC" testCases := map[string]struct { setupMocks func(mocks ec2SelectMocks) wantErr error wantSubnets []string }{ "return error if fail to list subnets": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCSubnets(mockVPC).Return(nil, mockErr) }, wantErr: fmt.Errorf("list subnets for VPC mockVPC: some error"), }, "return error if no subnets found": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCSubnets(mockVPC).Return(&ec2.VPCSubnets{ Private: []ec2.Subnet{ { Resource: ec2.Resource{ ID: "mockSubnetID", }, }, }, }, nil) }, wantErr: ErrSubnetsNotFound, }, "return error if fail to select": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCSubnets(mockVPC).Return(&ec2.VPCSubnets{ Public: []ec2.Subnet{ { Resource: ec2.Resource{ ID: "mockSubnetID", }, }, }, }, nil) m.prompt.EXPECT().MultiSelect("Select a subnet", "Help text", gomock.Any(), nil, gomock.Any()). Return(nil, mockErr) }, wantErr: fmt.Errorf("some error"), }, "success": { setupMocks: func(m ec2SelectMocks) { m.ec2Svc.EXPECT().ListVPCSubnets(mockVPC).Return(&ec2.VPCSubnets{ Private: []ec2.Subnet{ { Resource: ec2.Resource{ ID: "mockSubnetID1", }, }, }, Public: []ec2.Subnet{ { Resource: ec2.Resource{ ID: "mockSubnetID2", }, }, { Resource: ec2.Resource{ ID: "mockSubnetID3", Name: "mockSubnetName3", }, }, }, }, nil) m.prompt.EXPECT().MultiSelect("Select a subnet", "Help text", []string{"mockSubnetID2", "mockSubnetID3 (mockSubnetName3)"}, nil, gomock.Any()). Return([]string{"mockSubnetID2", "mockSubnetID3 (mockSubnetName3)"}, nil) }, wantSubnets: []string{"mockSubnetID2", "mockSubnetID3"}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockec2Svc := mocks.NewMockVPCSubnetLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := ec2SelectMocks{ ec2Svc: mockec2Svc, prompt: mockprompt, } tc.setupMocks(mocks) sel := EC2Select{ prompt: mockprompt, ec2Svc: mockec2Svc, } mockInput := SubnetsInput{ Msg: "Select a subnet", Help: "Help text", VPCID: mockVPC, IsPublic: true, } subnets, err := sel.selectFromVPCSubnets(mockInput) if tc.wantErr != nil { require.EqualError(t, tc.wantErr, err.Error()) } else { require.Equal(t, tc.wantSubnets, subnets) } }) } }
222
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "errors" "fmt" "github.com/aws/copilot-cli/internal/pkg/term/color" ) var ( // ErrLocalEnvsNotFound is returned when there are no environment manifests in the workspace. ErrLocalEnvsNotFound = errors.New("no environments found") // ErrVPCNotFound is returned when no existing VPCs are found. ErrVPCNotFound = errors.New("no existing VPCs found") // ErrSubnetsNotFound is returned when no existing subnets are found. ErrSubnetsNotFound = errors.New("no existing subnets found") ) // errNoWorkloadInApp occurs when there is no workload in an application. type errNoWorkloadInApp struct { appName string } func (e *errNoWorkloadInApp) Error() string { return fmt.Sprintf("no workloads found in app %s", e.appName) } // RecommendActions gives suggestions to fix the error. func (e *errNoWorkloadInApp) RecommendActions() string { return fmt.Sprintf("Couldn't find any workloads associated with app %s, try initializing one: %s.", color.HighlightUserInput(e.appName), color.HighlightCode("copilot [svc/job] init")) } // errNoJobInApp occurs when there is no job in an application. type errNoJobInApp struct { appName string } func (e *errNoJobInApp) Error() string { return fmt.Sprintf("no jobs found in app %s", e.appName) } // RecommendActions gives suggestions to fix the error. func (e *errNoJobInApp) RecommendActions() string { return fmt.Sprintf("Couldn't find any jobs associated with app %s, try initializing one: %s.", color.HighlightUserInput(e.appName), color.HighlightCode("copilot job init")) } // errNoServiceInApp occurs when there is no service in an application. type errNoServiceInApp struct { appName string } func (e *errNoServiceInApp) Error() string { return fmt.Sprintf("no services found in app %s", e.appName) } // RecommendActions gives suggestions to fix the error. func (e *errNoServiceInApp) RecommendActions() string { return fmt.Sprintf("Couldn't find any services associated with app %s, try initializing one: %s.", color.HighlightUserInput(e.appName), color.HighlightCode("copilot svc init")) }
69
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "testing" "github.com/stretchr/testify/require" ) func TestErrNoWorkloadInApp_Error(t *testing.T) { err := &errNoWorkloadInApp{ appName: "mockApp", } require.Equal(t, "no workloads found in app mockApp", err.Error()) } func TestErrNoWorkloadInApp_RecommendActions(t *testing.T) { err := &errNoWorkloadInApp{ appName: "mockApp", } require.Equal(t, "Couldn't find any workloads associated with app mockApp, try initializing one: `copilot [svc/job] init`.", err.RecommendActions()) } func TestErrNoJobInApp_Error(t *testing.T) { err := &errNoJobInApp{ appName: "mockApp", } require.Equal(t, "no jobs found in app mockApp", err.Error()) } func TestErrNoJobInApp_RecommendActions(t *testing.T) { err := &errNoJobInApp{ appName: "mockApp", } require.Equal(t, "Couldn't find any jobs associated with app mockApp, try initializing one: `copilot job init`.", err.RecommendActions()) } func TestErrNoServiceInApp_Error(t *testing.T) { err := &errNoServiceInApp{ appName: "mockApp", } require.Equal(t, "no services found in app mockApp", err.Error()) } func TestErrNoServiceInApp_RecommendActions(t *testing.T) { err := &errNoServiceInApp{ appName: "mockApp", } require.Equal(t, "Couldn't find any services associated with app mockApp, try initializing one: `copilot svc init`.", err.RecommendActions()) }
53
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "fmt" "github.com/aws/copilot-cli/internal/pkg/workspace" "os" "path/filepath" "sort" "strings" "github.com/aws/copilot-cli/internal/pkg/term/log" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "github.com/lnquy/cron" "github.com/spf13/afero" ) const ( dockerfileName = "dockerfile" dockerignoreName = ".dockerignore" ) // staticSelector selects from a list of static options. type staticSelector struct { prompt Prompter } // NewStaticSelector constructs a staticSelector. func NewStaticSelector(prompt Prompter) *staticSelector { return &staticSelector{ prompt: prompt, } } // Schedule asks the user to select either a rate, preset cron, or custom cron. func (s *staticSelector) Schedule(scheduleTypePrompt, scheduleTypeHelp string, scheduleValidator, rateValidator prompt.ValidatorFunc) (string, error) { scheduleType, err := s.prompt.SelectOne( scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, prompt.WithFinalMessage("Schedule type:"), ) if err != nil { return "", fmt.Errorf("get schedule type: %w", err) } switch scheduleType { case rate: return s.askRate(rateValidator) case fixedSchedule: return s.askCron(scheduleValidator) default: return "", fmt.Errorf("unrecognized schedule type %s", scheduleType) } } func (s *staticSelector) askRate(rateValidator prompt.ValidatorFunc) (string, error) { rateInput, err := s.prompt.Get( ratePrompt, rateHelp, rateValidator, prompt.WithDefaultInput("1h30m"), prompt.WithFinalMessage("Rate:"), ) if err != nil { return "", fmt.Errorf("get schedule rate: %w", err) } return fmt.Sprintf(every, rateInput), nil } func (s *staticSelector) askCron(scheduleValidator prompt.ValidatorFunc) (string, error) { cronInput, err := s.prompt.SelectOption( schedulePrompt, scheduleHelp, presetSchedules, prompt.WithFinalMessage("Fixed schedule:"), ) if err != nil { return "", fmt.Errorf("get preset schedule: %w", err) } if cronInput != custom { return presetScheduleToDefinitionString(cronInput), nil } var customSchedule, humanCron string cronDescriptor, err := cron.NewDescriptor() if err != nil { return "", fmt.Errorf("get custom schedule: %w", err) } for { customSchedule, err = s.prompt.Get( customSchedulePrompt, customScheduleHelp, scheduleValidator, prompt.WithDefaultInput("0 * * * *"), prompt.WithFinalMessage("Custom schedule:"), ) if err != nil { return "", fmt.Errorf("get custom schedule: %w", err) } // Break if the customer has specified an easy to read cron definition string if strings.HasPrefix(customSchedule, "@") { break } humanCron, err = cronDescriptor.ToDescription(customSchedule, cron.Locale_en) if err != nil { return "", fmt.Errorf("convert cron to human string: %w", err) } log.Infoln(fmt.Sprintf("Your job will run at the following times: %s", humanCron)) ok, err := s.prompt.Confirm( humanReadableCronConfirmPrompt, humanReadableCronConfirmHelp, ) if err != nil { return "", fmt.Errorf("confirm cron schedule: %w", err) } if ok { break } } return customSchedule, nil } // localFileSelector selects from a local file system where a workspace does not necessarily exist. type localFileSelector struct { prompt Prompter ws *workspace.Workspace fs *afero.Afero workingDirAbs string } // NewLocalFileSelector constructs a LocalFileSelector. func NewLocalFileSelector(prompt Prompter, fs afero.Fs, ws *workspace.Workspace) (*localFileSelector, error) { workingDirAbs, err := os.Getwd() if err != nil { return nil, fmt.Errorf("get working directory: %w", err) } return &localFileSelector{ prompt: prompt, ws: ws, fs: &afero.Afero{Fs: fs}, workingDirAbs: workingDirAbs, }, nil } // StaticSources asks the user to select from a list of directories and files. func (s *localFileSelector) StaticSources(selPrompt, selHelp, customPathPrompt, customPathHelp string, pathValidator prompt.ValidatorFunc) ([]string, error) { dirsAndFiles, err := s.listDirsAndFiles() if err != nil { return nil, err } if len(dirsAndFiles) == 0 { log.Warningln("No directories or files were found in your workspace. Enter a relative path with the 'custom path' option if you'd like to use a hidden file.") } dirsAndFiles = append(dirsAndFiles, staticSourceUseCustomPrompt) var results []string var askCustom bool var selections []string selections, err = s.prompt.MultiSelect( selPrompt, selHelp, dirsAndFiles, nil, prompt.WithFinalMessage(staticAssetsFinalMsg), ) if err != nil { return nil, fmt.Errorf("select directories and/or files: %w", err) } for _, selection := range selections { if selection == staticSourceUseCustomPrompt { askCustom = true continue } results = append(results, selection) } if !askCustom { return results, nil } customPaths, err := AskCustomPaths(s.prompt, customPathPrompt, customPathHelp, pathValidator) if err != nil { return nil, err } results = append(results, customPaths...) return results, nil } // dockerfileSelector selects from a local file system where a workspace does not necessarily exist. type dockerfileSelector struct { prompt Prompter fs *afero.Afero workingDirAbs string } // NewDockerfileSelector constructs a DockerfileSelector. func NewDockerfileSelector(prompt Prompter, fs afero.Fs) (*dockerfileSelector, error) { workingDirAbs, err := os.Getwd() if err != nil { return nil, fmt.Errorf("get working directory: %w", err) } return &dockerfileSelector{ prompt: prompt, fs: &afero.Afero{Fs: fs}, workingDirAbs: workingDirAbs, }, nil } // Dockerfile asks the user to select from a list of Dockerfiles in the current // directory or one level down. If no dockerfiles are found, it asks for a custom path. func (s *dockerfileSelector) Dockerfile(selPrompt, notFoundPrompt, selHelp, notFoundHelp string, pathValidator prompt.ValidatorFunc) (string, error) { dockerfiles, err := s.listDockerfiles() if err != nil { return "", err } var sel string dockerfiles = append(dockerfiles, []string{dockerfilePromptUseCustom, DockerfilePromptUseImage}...) sel, err = s.prompt.SelectOne( selPrompt, selHelp, dockerfiles, prompt.WithFinalMessage(dockerfileFinalMsg), ) if err != nil { return "", fmt.Errorf("select Dockerfile: %w", err) } if sel != dockerfilePromptUseCustom { return sel, nil } sel, err = s.prompt.Get( notFoundPrompt, notFoundHelp, pathValidator, prompt.WithFinalMessage(dockerfileFinalMsg)) if err != nil { return "", fmt.Errorf("get custom Dockerfile path: %w", err) } return sel, nil } // listDockerfiles returns the list of Dockerfiles within the current // working directory and a subdirectory level below. If an error occurs while // reading directories, or no Dockerfiles found returns the error. func (s *dockerfileSelector) listDockerfiles() ([]string, error) { wdFiles, err := s.fs.ReadDir(s.workingDirAbs) if err != nil { return nil, fmt.Errorf("read directory: %w", err) } var dockerfiles = make([]string, 0) for _, wdFile := range wdFiles { // Add current file if it is a Dockerfile and not a directory; otherwise continue. if !wdFile.IsDir() { fname := wdFile.Name() if strings.Contains(strings.ToLower(fname), dockerfileName) && !strings.HasSuffix(strings.ToLower(fname), dockerignoreName) { path := filepath.Dir(fname) + "/" + fname dockerfiles = append(dockerfiles, path) } continue } // Add sub-directories containing a Dockerfile one level below current directory. subFiles, err := s.fs.ReadDir(wdFile.Name()) if err != nil { // swallow errors for unreadable directories continue } for _, f := range subFiles { // NOTE: ignore directories in sub-directories. if f.IsDir() { continue } fname := f.Name() if strings.Contains(strings.ToLower(fname), dockerfileName) && !strings.HasSuffix(strings.ToLower(fname), dockerignoreName) { path := wdFile.Name() + "/" + f.Name() dockerfiles = append(dockerfiles, path) } } } sort.Strings(dockerfiles) return dockerfiles, nil } // listDirsAndFiles returns the list of directories and files within the presumed // project root and two subdirectory levels below. func (s *localFileSelector) listDirsAndFiles() ([]string, error) { return s.getDirAndFileNames(s.ws.ProjectRoot(), 3) } // getDirAndFileNames recursively fetches directory and file names to the depth indicated. // Hidden files and the copilot dir are excluded. func (s *localFileSelector) getDirAndFileNames(dir string, depth int) ([]string, error) { wdDirsAndFiles, err := s.fs.ReadDir(dir) if err != nil { return nil, fmt.Errorf("read directory: %w", err) } var names []string for _, file := range wdDirsAndFiles { name := file.Name() if strings.HasPrefix(name, ".") || name == "copilot" { continue } relPathName := filepath.Join(dir, name) wsRelPathName, err := s.ws.Rel(relPathName) if err != nil { return nil, fmt.Errorf("get path relative to workspace for %q: %w", relPathName, err) } names = append(names, wsRelPathName) if depth > 0 && file.IsDir() { subNames, err := s.getDirAndFileNames(relPathName, depth-1) if err != nil { return nil, err } names = append(names, subNames...) } } return names, nil } // AskCustomPaths prompts for user input of filepaths, which are then validated. func AskCustomPaths(prompter Prompter, customPathPrompt, customPathHelp string, pathValidator prompt.ValidatorFunc) ([]string, error) { var paths []string for { customPath, err := prompter.Get( customPathPrompt, customPathHelp, pathValidator, prompt.WithFinalMessage(customPathFinalMsg)) if err != nil { return nil, fmt.Errorf("get custom directory or file path: %w", err) } paths = append(paths, customPath) another, err := prompter.Confirm( staticSourceAnotherCustomPathPrompt, staticSourceAnotherCustomPathHelp, prompt.WithFinalMessage(anotherFinalMsg), ) if err != nil { return nil, fmt.Errorf("confirm another custom path: %w", err) } if !another { break } } return paths, nil } func presetScheduleToDefinitionString(input string) string { return fmt.Sprintf("@%s", strings.ToLower(input)) }
354
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "errors" "fmt" "github.com/aws/copilot-cli/internal/pkg/workspace" "os" "testing" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "github.com/aws/copilot-cli/internal/pkg/term/selector/mocks" "github.com/golang/mock/gomock" "github.com/spf13/afero" "github.com/stretchr/testify/require" ) func TestConfigurationSelector_Schedule(t *testing.T) { scheduleTypePrompt := "HAY WHAT SCHEDULE" scheduleTypeHelp := "NO" testCases := map[string]struct { mockPrompt func(*mocks.MockPrompter) wantedSchedule string wantedErr error }{ "error asking schedule type": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return("", errors.New("some error")), ) }, wantedErr: errors.New("get schedule type: some error"), }, "ask for rate": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(rate, nil), m.EXPECT().Get(ratePrompt, rateHelp, gomock.Any(), gomock.Any()).Return("1h30m", nil), ) }, wantedSchedule: "@every 1h30m", }, "error getting rate": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(rate, nil), m.EXPECT().Get(ratePrompt, rateHelp, gomock.Any(), gomock.Any()).Return("", fmt.Errorf("some error")), ) }, wantedErr: errors.New("get schedule rate: some error"), }, "ask for cron": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(fixedSchedule, nil), m.EXPECT().SelectOption(schedulePrompt, scheduleHelp, presetSchedules, gomock.Any()).Return("Daily", nil), ) }, wantedSchedule: "@daily", }, "error getting cron": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(fixedSchedule, nil), m.EXPECT().SelectOption(schedulePrompt, scheduleHelp, presetSchedules, gomock.Any()).Return("", errors.New("some error")), ) }, wantedErr: errors.New("get preset schedule: some error"), }, "ask for custom schedule": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(fixedSchedule, nil), m.EXPECT().SelectOption(schedulePrompt, scheduleHelp, presetSchedules, gomock.Any()).Return("Custom", nil), m.EXPECT().Get(customSchedulePrompt, customScheduleHelp, gomock.Any(), gomock.Any()).Return("0 * * * *", nil), m.EXPECT().Confirm(humanReadableCronConfirmPrompt, humanReadableCronConfirmHelp).Return(true, nil), ) }, wantedSchedule: "0 * * * *", }, "error getting custom schedule": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(fixedSchedule, nil), m.EXPECT().SelectOption(schedulePrompt, scheduleHelp, presetSchedules, gomock.Any()).Return("Custom", nil), m.EXPECT().Get(customSchedulePrompt, customScheduleHelp, gomock.Any(), gomock.Any()).Return("", errors.New("some error")), ) }, wantedErr: errors.New("get custom schedule: some error"), }, "error confirming custom schedule": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(fixedSchedule, nil), m.EXPECT().SelectOption(schedulePrompt, scheduleHelp, presetSchedules, gomock.Any()).Return("Custom", nil), m.EXPECT().Get(customSchedulePrompt, customScheduleHelp, gomock.Any(), gomock.Any()).Return("0 * * * *", nil), m.EXPECT().Confirm(humanReadableCronConfirmPrompt, humanReadableCronConfirmHelp).Return(false, errors.New("some error")), ) }, wantedErr: errors.New("confirm cron schedule: some error"), }, "custom schedule using valid definition string results in no confirm": { mockPrompt: func(m *mocks.MockPrompter) { gomock.InOrder( m.EXPECT().SelectOne(scheduleTypePrompt, scheduleTypeHelp, scheduleTypes, gomock.Any()).Return(fixedSchedule, nil), m.EXPECT().SelectOption(schedulePrompt, scheduleHelp, presetSchedules, gomock.Any()).Return("Custom", nil), m.EXPECT().Get(customSchedulePrompt, customScheduleHelp, gomock.Any(), gomock.Any()).Return("@hourly", nil), ) }, wantedSchedule: "@hourly", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN ctrl := gomock.NewController(t) defer ctrl.Finish() p := mocks.NewMockPrompter(ctrl) tc.mockPrompt(p) sel := staticSelector{ prompt: p, } var mockValidator prompt.ValidatorFunc = func(interface{}) error { return nil } // WHEN schedule, err := sel.Schedule(scheduleTypePrompt, scheduleTypeHelp, mockValidator, mockValidator) // THEN if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.Equal(t, tc.wantedSchedule, schedule) } }) } } func TestLocalFileSelector_Dockerfile(t *testing.T) { testCases := map[string]struct { mockPrompt func(*mocks.MockPrompter) mockFileSystem func(fs afero.Fs) wantedErr error wantedDockerfile string }{ "choose an existing Dockerfile": { mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.MkdirAll("frontend", 0755) _ = mockFS.MkdirAll("backend", 0755) _ = afero.WriteFile(mockFS, "Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "frontend/Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "backend/my.dockerfile", []byte("FROM nginx"), 0644) }, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().SelectOne( gomock.Any(), gomock.Any(), gomock.Eq([]string{ "./Dockerfile", "backend/my.dockerfile", "frontend/Dockerfile", dockerfilePromptUseCustom, DockerfilePromptUseImage, }), gomock.Any(), ).Return("frontend/Dockerfile", nil) }, wantedDockerfile: "frontend/Dockerfile", }, "prompts user for custom path": { mockFileSystem: func(mockFS afero.Fs) {}, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().SelectOne( gomock.Any(), gomock.Any(), gomock.Eq([]string{ dockerfilePromptUseCustom, DockerfilePromptUseImage, }), gomock.Any(), ).Return("Enter custom path for your Dockerfile", nil) m.EXPECT().Get( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), ).Return("crazy/path/Dockerfile", nil) }, wantedDockerfile: "crazy/path/Dockerfile", }, "returns an error if fail to select Dockerfile": { mockFileSystem: func(mockFS afero.Fs) {}, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().SelectOne( gomock.Any(), gomock.Any(), gomock.Eq([]string{ dockerfilePromptUseCustom, DockerfilePromptUseImage, }), gomock.Any(), ).Return("", errors.New("some error")) }, wantedErr: fmt.Errorf("select Dockerfile: some error"), }, "returns an error if fail to get custom Dockerfile path": { mockFileSystem: func(mockFS afero.Fs) { _ = afero.WriteFile(mockFS, "Dockerfile", []byte("FROM nginx"), 0644) }, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().SelectOne( gomock.Any(), gomock.Any(), gomock.Eq([]string{ "./Dockerfile", dockerfilePromptUseCustom, DockerfilePromptUseImage, }), gomock.Any(), ).Return("Enter custom path for your Dockerfile", nil) m.EXPECT().Get( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), ).Return("", errors.New("some error")) }, wantedErr: fmt.Errorf("get custom Dockerfile path: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN ctrl := gomock.NewController(t) defer ctrl.Finish() p := mocks.NewMockPrompter(ctrl) fs := &afero.Afero{Fs: afero.NewMemMapFs()} tc.mockFileSystem(fs) tc.mockPrompt(p) sel := dockerfileSelector{ prompt: p, fs: fs, } mockPromptText := "prompt" mockHelpText := "help" // WHEN dockerfile, err := sel.Dockerfile( mockPromptText, mockPromptText, mockHelpText, mockHelpText, func(v interface{}) error { return nil }, ) // THEN if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.Equal(t, tc.wantedDockerfile, dockerfile) } }) } } func TestLocalFileSelector_StaticSources(t *testing.T) { wd, _ := os.Getwd() mockFS := func(mockFS afero.Fs) { _ = mockFS.MkdirAll(wd+"this/path/to/projectRoot/copilot", 0755) _ = mockFS.MkdirAll(wd+"this/path/to/projectRoot/frontend", 0755) _ = mockFS.MkdirAll(wd+"this/path/to/projectRoot/backend", 0755) _ = mockFS.MkdirAll(wd+"this/path/to/projectRoot/friend", 0755) _ = mockFS.MkdirAll(wd+"this/path/to/projectRoot/trend", 0755) _ = afero.WriteFile(mockFS, wd+"this/path/to/projectRoot/myFile", []byte("cool stuff"), 0644) _ = afero.WriteFile(mockFS, wd+"this/path/to/projectRoot/frontend/feFile", []byte("css and stuff"), 0644) _ = afero.WriteFile(mockFS, wd+"this/path/to/projectRoot/backend/beFile", []byte("content stuff"), 0644) } testCases := map[string]struct { mockPrompt func(*mocks.MockPrompter) mockFileSystem func(fs afero.Fs) wantedErr error wantedDirOrFiles []string }{ "successfully choose existing files, dirs, and multiple write-in paths": { mockFileSystem: mockFS, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().MultiSelect( gomock.Any(), gomock.Any(), gomock.Eq([]string{ "backend", "backend/beFile", "friend", "frontend", "frontend/feFile", "myFile", "trend", staticSourceUseCustomPrompt, }), gomock.Any(), gomock.Any(), ).Return([]string{"myFile", "frontend", "backend/beFile", staticSourceUseCustomPrompt}, nil) m.EXPECT().Get( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("friend", nil) m.EXPECT().Confirm( gomock.Any(), gomock.Any(), gomock.Any()).Return(true, nil) m.EXPECT().Get( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("trend", nil) m.EXPECT().Confirm( gomock.Any(), gomock.Any(), gomock.Any()).Return(false, nil) }, wantedDirOrFiles: []string{"myFile", "frontend", "backend/beFile", "friend", "trend"}, }, "error with multiselect": { mockFileSystem: mockFS, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().MultiSelect( gomock.Any(), gomock.Any(), gomock.Eq([]string{ "backend", "backend/beFile", "friend", "frontend", "frontend/feFile", "myFile", "trend", staticSourceUseCustomPrompt, }), gomock.Any(), gomock.Any(), ).Return(nil, errors.New("some error")) }, wantedErr: errors.New("select directories and/or files: some error"), }, "error entering custom path": { mockFileSystem: mockFS, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().MultiSelect( gomock.Any(), gomock.Any(), gomock.Eq([]string{ "backend", "backend/beFile", "friend", "frontend", "frontend/feFile", "myFile", "trend", staticSourceUseCustomPrompt, }), gomock.Any(), gomock.Any(), ).Return([]string{staticSourceUseCustomPrompt}, nil) m.EXPECT().Get( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("", errors.New("some error")) }, wantedErr: fmt.Errorf("get custom directory or file path: some error"), }, "error confirming whether not to prompt for another custom path": { mockFileSystem: mockFS, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().MultiSelect( gomock.Any(), gomock.Any(), gomock.Eq([]string{ "backend", "backend/beFile", "friend", "frontend", "frontend/feFile", "myFile", "trend", staticSourceUseCustomPrompt, }), gomock.Any(), gomock.Any(), ).Return([]string{staticSourceUseCustomPrompt}, nil) m.EXPECT().Get( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("friend", nil) m.EXPECT().Confirm( gomock.Any(), gomock.Any(), gomock.Any()).Return(false, errors.New("some error")) }, wantedErr: fmt.Errorf("confirm another custom path: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN ctrl := gomock.NewController(t) defer ctrl.Finish() cwd, _ := os.Getwd() p := mocks.NewMockPrompter(ctrl) w := &workspace.Workspace{ CopilotDirAbs: cwd + "this/path/to/projectRoot/copilot", } fs := &afero.Afero{Fs: afero.NewMemMapFs()} tc.mockFileSystem(fs) tc.mockPrompt(p) sel := localFileSelector{ prompt: p, ws: w, fs: fs, workingDirAbs: "this/path/to/projectRoot", } mockPromptText := "prompt" mockHelpText := "help" // WHEN sourceFiles, err := sel.StaticSources( mockPromptText, mockPromptText, mockHelpText, mockHelpText, nil, ) // THEN if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.Equal(t, tc.wantedDirOrFiles, sourceFiles) } }) } } func TestLocalFileSelector_listDockerfiles(t *testing.T) { testCases := map[string]struct { workingDirAbs string mockFileSystem func(mockFS afero.Fs) wantedErr error dockerfiles []string }{ "find Dockerfiles": { mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.MkdirAll("frontend", 0755) _ = mockFS.MkdirAll("backend", 0755) _ = afero.WriteFile(mockFS, "Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "frontend/Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "backend/Dockerfile", []byte("FROM nginx"), 0644) }, dockerfiles: []string{"./Dockerfile", "backend/Dockerfile", "frontend/Dockerfile"}, }, "exclude dockerignore files": { mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.MkdirAll("frontend", 0755) _ = mockFS.MkdirAll("backend", 0755) _ = afero.WriteFile(mockFS, "Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "frontend/Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "frontend/Dockerfile.dockerignore", []byte("*/temp*"), 0644) _ = afero.WriteFile(mockFS, "backend/Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "backend/Dockerfile.dockerignore", []byte("*/temp*"), 0644) }, wantedErr: nil, dockerfiles: []string{"./Dockerfile", "backend/Dockerfile", "frontend/Dockerfile"}, }, "exclude Dockerfiles in parent directories of the working dir": { workingDirAbs: "/app", mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.MkdirAll("/app", 0755) _ = afero.WriteFile(mockFS, "/app/Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "frontend/Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "backend/my.dockerfile", []byte("FROM nginx"), 0644) }, dockerfiles: []string{"./Dockerfile"}, }, "nonstandard Dockerfile names": { mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.MkdirAll("frontend", 0755) _ = mockFS.MkdirAll("dockerfiles", 0755) _ = afero.WriteFile(mockFS, "Dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "frontend/dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "Job.dockerfile", []byte("FROM nginx"), 0644) _ = afero.WriteFile(mockFS, "Job.dockerfile.dockerignore", []byte("*/temp*"), 0644) }, dockerfiles: []string{"./Dockerfile", "./Job.dockerfile", "frontend/dockerfile"}, }, "no Dockerfiles": { mockFileSystem: func(mockFS afero.Fs) {}, dockerfiles: []string{}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN fs := &afero.Afero{Fs: afero.NewMemMapFs()} tc.mockFileSystem(fs) s := &dockerfileSelector{ workingDirAbs: tc.workingDirAbs, fs: &afero.Afero{ Fs: fs, }, } got, err := s.listDockerfiles() if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.NoError(t, err) require.Equal(t, tc.dockerfiles, got) } }) } } func TestLocalFileSelector_listDirsAndFiles(t *testing.T) { wd, _ := os.Getwd() testCases := map[string]struct { mockFileSystem func(mockFS afero.Fs) wantedErr error dirsAndFiles []string }{ "drill down two (and only two) levels": { mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.MkdirAll(wd+"/projectRoot/lobby/copilot", 0755) _ = mockFS.MkdirAll(wd+"/projectRoot/lobby/basement/subBasement/subSubBasement/subSubSubBasement", 0755) _ = afero.WriteFile(mockFS, wd+"/projectRoot/lobby/file", []byte("cool stuff"), 0644) _ = afero.WriteFile(mockFS, wd+"/projectRoot/lobby/basement/file", []byte("more cool stuff"), 0644) _ = afero.WriteFile(mockFS, wd+"/projectRoot/lobby/basement/subBasement/file", []byte("unreachable cool stuff"), 0644) }, dirsAndFiles: []string{"lobby", "lobby/basement", "lobby/basement/file", "lobby/basement/subBasement", "lobby/basement/subBasement/file", "lobby/basement/subBasement/subSubBasement", "lobby/file"}, }, "exclude hidden files and copilot dir": { mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.MkdirAll(wd+"/projectRoot/lobby/basement/subBasement/subSubBasement", 0755) _ = mockFS.Mkdir(wd+"/projectRoot/lobby/copilot", 0755) _ = afero.WriteFile(mockFS, wd+"/projectRoot/lobby/.file", []byte("cool stuff"), 0644) _ = afero.WriteFile(mockFS, wd+"/projectRoot/lobby/basement/file", []byte("more cool stuff"), 0644) _ = afero.WriteFile(mockFS, wd+"/projectRoot/lobby/basement/subBasement/file", []byte("unreachable cool stuff"), 0644) }, wantedErr: nil, dirsAndFiles: []string{"lobby", "lobby/basement", "lobby/basement/file", "lobby/basement/subBasement", "lobby/basement/subBasement/file", "lobby/basement/subBasement/subSubBasement"}, }, "no dirs or files found": { mockFileSystem: func(mockFS afero.Fs) { _ = mockFS.Mkdir(wd+"/projectRoot/copilot", 0755) }, dirsAndFiles: nil, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN fs := &afero.Afero{Fs: afero.NewMemMapFs()} cwd, _ := os.Getwd() w := &workspace.Workspace{ CopilotDirAbs: cwd + "/projectRoot/copilot", } tc.mockFileSystem(fs) s := &localFileSelector{ fs: &afero.Afero{ Fs: fs, }, ws: w, workingDirAbs: "", } got, err := s.listDirsAndFiles() if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.NoError(t, err) require.Equal(t, tc.dirsAndFiles, got) } }) } }
577
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package selector provides functionality for users to select an application, environment, or service name. package selector import ( "errors" "fmt" "sort" "strings" awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs" "github.com/aws/copilot-cli/internal/pkg/config" "github.com/aws/copilot-cli/internal/pkg/deploy" "github.com/aws/copilot-cli/internal/pkg/ecs" "github.com/aws/copilot-cli/internal/pkg/term/color" "github.com/aws/copilot-cli/internal/pkg/term/log" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "github.com/aws/copilot-cli/internal/pkg/workspace" ) const ( svcWorkloadType = "service" jobWorkloadType = "job" every = "@every %s" rate = "Rate" fixedSchedule = "Fixed Schedule" custom = "Custom" hourly = "Hourly" daily = "Daily" weekly = "Weekly" monthly = "Monthly" yearly = "Yearly" pipelineEscapeOpt = "[No additional environments]" fmtCopilotTaskGroup = "copilot-%s" ) const ( // dockerfilePromptUseCustom is the option for using Dockerfile with custom path. dockerfilePromptUseCustom = "Enter custom path for your Dockerfile" // DockerfilePromptUseImage is the option for using existing image instead of Dockerfile. DockerfilePromptUseImage = "Use an existing image instead" ratePrompt = "How long would you like to wait between executions?" rateHelp = `You can specify the time as a duration string. (For example, 2m, 1h30m, 24h)` schedulePrompt = "What schedule would you like to use?" scheduleHelp = `Predefined schedules run at midnight or the top of the hour. For example, "Daily" runs at midnight. "Weekly" runs at midnight on Mondays.` customSchedulePrompt = "What custom cron schedule would you like to use?" customScheduleHelp = `Custom schedules can be defined using the following cron: Minute | Hour | Day of Month | Month | Day of Week For example: 0 17 ? * MON-FRI (5 pm on weekdays) 0 0 1 */3 * (on the first of the month, quarterly)` humanReadableCronConfirmPrompt = "Would you like to use this schedule?" humanReadableCronConfirmHelp = `Confirm whether the schedule looks right to you. (Y)es will continue execution. (N)o will allow you to input a different schedule.` staticSourceUseCustomPrompt = "Enter custom path to your static site dir/file" staticSourceAnotherCustomPathPrompt = "Would you like to enter another path?" staticSourceAnotherCustomPathHelp = "You may add multiple custom paths. Enter 'y' to type another." ) // Final messages displayed after prompting. const ( appNameFinalMessage = "Application:" envNameFinalMessage = "Environment:" svcNameFinalMsg = "Service name:" jobNameFinalMsg = "Job name:" deployedJobFinalMsg = "Job:" deployedSvcFinalMsg = "Service:" taskFinalMsg = "Task:" workloadFinalMsg = "Name:" dockerfileFinalMsg = "Dockerfile:" topicFinalMsg = "Topic subscriptions:" pipelineFinalMsg = "Pipeline:" staticAssetsFinalMsg = "Source(s):" customPathFinalMsg = "Custom Path to Source:" anotherFinalMsg = "Another:" ) var scheduleTypes = []string{ rate, fixedSchedule, } var presetSchedules = []prompt.Option{ {Value: custom, Hint: ""}, {Value: hourly, Hint: "At minute 0"}, {Value: daily, Hint: "At midnight UTC"}, {Value: weekly, Hint: "At midnight on Sunday UTC"}, {Value: monthly, Hint: "At midnight, first day of month UTC"}, {Value: yearly, Hint: "At midnight, Jan 1st UTC"}, } // Prompter wraps the methods to ask for inputs from the terminal. type Prompter interface { Get(message, help string, validator prompt.ValidatorFunc, promptOpts ...prompt.PromptConfig) (string, error) SelectOne(message, help string, options []string, promptOpts ...prompt.PromptConfig) (string, error) SelectOption(message, help string, opts []prompt.Option, promptCfgs ...prompt.PromptConfig) (value string, err error) MultiSelectOptions(message, help string, opts []prompt.Option, promptCfgs ...prompt.PromptConfig) ([]string, error) MultiSelect(message, help string, options []string, validator prompt.ValidatorFunc, promptOpts ...prompt.PromptConfig) ([]string, error) Confirm(message, help string, promptOpts ...prompt.PromptConfig) (bool, error) } type appEnvLister interface { ListEnvironments(appName string) ([]*config.Environment, error) ListApplications() ([]*config.Application, error) } type configWorkloadLister interface { ListServices(appName string) ([]*config.Workload, error) ListJobs(appName string) ([]*config.Workload, error) ListWorkloads(appName string) ([]*config.Workload, error) } type configLister interface { appEnvLister configWorkloadLister } type wsWorkloadLister interface { ListServices() ([]string, error) ListJobs() ([]string, error) ListWorkloads() ([]string, error) } type wsEnvironmentsLister interface { ListEnvironments() ([]string, error) } type wsPipelinesLister interface { ListPipelines() ([]workspace.PipelineManifest, error) } // codePipelineLister lists deployed pipelines. type codePipelineLister interface { ListDeployedPipelines(appName string) ([]deploy.Pipeline, error) } // workspaceRetriever wraps methods to get workload names, app names, and Dockerfiles from the workspace. type workspaceRetriever interface { wsWorkloadLister wsEnvironmentsLister Summary() (*workspace.Summary, error) } // deployedWorkloadsRetriever retrieves information about deployed services or jobs. type deployedWorkloadsRetriever interface { ListDeployedServices(appName string, envName string) ([]string, error) ListDeployedJobs(appName, envName string) ([]string, error) IsServiceDeployed(appName string, envName string, svcName string) (bool, error) IsJobDeployed(appName, envName, jobName string) (bool, error) ListSNSTopics(appName string, envName string) ([]deploy.Topic, error) } // taskStackDescriber wraps cloudformation client methods to describe task stacks type taskStackDescriber interface { ListDefaultTaskStacks() ([]deploy.TaskStackInfo, error) ListTaskStacks(appName, envName string) ([]deploy.TaskStackInfo, error) } // taskLister wraps methods of listing tasks. type taskLister interface { ListActiveAppEnvTasks(opts ecs.ListActiveAppEnvTasksOpts) ([]*awsecs.Task, error) ListActiveDefaultClusterTasks(filter ecs.ListTasksFilter) ([]*awsecs.Task, error) } // AppEnvSelector prompts users to select the name of an application or environment. type AppEnvSelector struct { prompt Prompter appEnvLister appEnvLister } // ConfigSelector is an application and environment selector, but can also choose a service from the config store. type ConfigSelector struct { *AppEnvSelector workloadLister configWorkloadLister } // LocalWorkloadSelector is an application and environment selector, but can also choose a service from the workspace. type LocalWorkloadSelector struct { *ConfigSelector ws workspaceRetriever } // LocalEnvironmentSelector is an application and environment selector, but can also choose an environment from the workspace. type LocalEnvironmentSelector struct { *AppEnvSelector ws workspaceRetriever } // WorkspaceSelector selects from local workspace. type WorkspaceSelector struct { prompt Prompter ws workspaceRetriever } // WsPipelineSelector is a workspace pipeline selector. type WsPipelineSelector struct { prompt Prompter ws wsPipelinesLister } // CodePipelineSelector is a selector for deployed pipelines. type CodePipelineSelector struct { prompt Prompter pipelineLister codePipelineLister } // AppPipelineSelector is a selector for deployed pipelines and apps. type AppPipelineSelector struct { *AppEnvSelector *CodePipelineSelector } // DeploySelector is a service and environment selector from the deploy store. type DeploySelector struct { *ConfigSelector deployStoreSvc deployedWorkloadsRetriever name string env string filters []DeployedWorkloadFilter } // CFTaskSelector is a selector based on CF methods to get deployed one off tasks. type CFTaskSelector struct { *AppEnvSelector cfStore taskStackDescriber app string env string defaultCluster bool } // NewCFTaskSelect constructs a CFTaskSelector. func NewCFTaskSelect(prompt Prompter, store configLister, cf taskStackDescriber) *CFTaskSelector { return &CFTaskSelector{ AppEnvSelector: NewAppEnvSelector(prompt, store), cfStore: cf, } } // GetDeployedTaskOpts sets up optional parameters for GetDeployedTaskOpts function. type GetDeployedTaskOpts func(*CFTaskSelector) // TaskWithAppEnv sets up the env name for TaskSelector. func TaskWithAppEnv(app, env string) GetDeployedTaskOpts { return func(in *CFTaskSelector) { in.app = app in.env = env } } // TaskWithDefaultCluster sets up whether CFTaskSelector should use only the default cluster. func TaskWithDefaultCluster() GetDeployedTaskOpts { return func(in *CFTaskSelector) { in.defaultCluster = true } } // TaskSelector is a Copilot running task selector. type TaskSelector struct { prompt Prompter lister taskLister app string env string defaultCluster bool taskGroup string taskID string } // NewAppEnvSelector returns a selector that chooses applications or environments. func NewAppEnvSelector(prompt Prompter, store appEnvLister) *AppEnvSelector { return &AppEnvSelector{ prompt: prompt, appEnvLister: store, } } // NewConfigSelector returns a new selector that chooses applications, environments, or services from the config store. func NewConfigSelector(prompt Prompter, store configLister) *ConfigSelector { return &ConfigSelector{ AppEnvSelector: NewAppEnvSelector(prompt, store), workloadLister: store, } } // NewLocalWorkloadSelector returns a new selector that chooses applications and environments from the config store, but // services from the local workspace. func NewLocalWorkloadSelector(prompt Prompter, store configLister, ws workspaceRetriever) *LocalWorkloadSelector { return &LocalWorkloadSelector{ ConfigSelector: NewConfigSelector(prompt, store), ws: ws, } } // NewLocalEnvironmentSelector returns a new selector that chooses applications from the config store, but an environment // from the local workspace. func NewLocalEnvironmentSelector(prompt Prompter, store configLister, ws workspaceRetriever) *LocalEnvironmentSelector { return &LocalEnvironmentSelector{ AppEnvSelector: NewAppEnvSelector(prompt, store), ws: ws, } } // NewWorkspaceSelector returns a new selector that prompts for local information. func NewWorkspaceSelector(prompt Prompter, ws workspaceRetriever) *WorkspaceSelector { return &WorkspaceSelector{ prompt: prompt, ws: ws, } } // NewWsPipelineSelector returns a new selector with pipelines from the local workspace. func NewWsPipelineSelector(prompt Prompter, ws wsPipelinesLister) *WsPipelineSelector { return &WsPipelineSelector{ prompt: prompt, ws: ws, } } // NewAppPipelineSelector returns new selectors with deployed pipelines and apps. func NewAppPipelineSelector(prompt Prompter, store configLister, lister codePipelineLister) *AppPipelineSelector { return &AppPipelineSelector{ AppEnvSelector: NewAppEnvSelector(prompt, store), CodePipelineSelector: &CodePipelineSelector{ prompt: prompt, pipelineLister: lister, }, } } // NewDeploySelect returns a new selector that chooses services and environments from the deploy store. func NewDeploySelect(prompt Prompter, configStore configLister, deployStore deployedWorkloadsRetriever) *DeploySelector { return &DeploySelector{ ConfigSelector: NewConfigSelector(prompt, configStore), deployStoreSvc: deployStore, } } // NewTaskSelector returns a new selector that chooses a running task. func NewTaskSelector(prompt Prompter, lister taskLister) *TaskSelector { return &TaskSelector{ prompt: prompt, lister: lister, } } // TaskOpts sets up optional parameters for Task function. type TaskOpts func(*TaskSelector) // WithAppEnv sets up the app name and env name for TaskSelector. func WithAppEnv(app, env string) TaskOpts { return func(in *TaskSelector) { in.app = app in.env = env } } // WithDefault uses default cluster for TaskSelector. func WithDefault() TaskOpts { return func(in *TaskSelector) { in.defaultCluster = true } } // WithTaskGroup sets up the task group name for TaskSelector. func WithTaskGroup(taskGroup string) TaskOpts { return func(in *TaskSelector) { if taskGroup != "" { in.taskGroup = fmt.Sprintf(fmtCopilotTaskGroup, taskGroup) } } } // WithTaskID sets up the task ID for TaskSelector. func WithTaskID(id string) TaskOpts { return func(in *TaskSelector) { in.taskID = id } } // RunningTask has the user select a running task. Callers can provide either app and env names, // or use default cluster. func (s *TaskSelector) RunningTask(msg, help string, opts ...TaskOpts) (*awsecs.Task, error) { var tasks []*awsecs.Task var err error for _, opt := range opts { opt(s) } filter := ecs.ListTasksFilter{ TaskGroup: s.taskGroup, TaskID: s.taskID, CopilotOnly: true, } if s.defaultCluster { tasks, err = s.lister.ListActiveDefaultClusterTasks(filter) if err != nil { return nil, fmt.Errorf("list active tasks for default cluster: %w", err) } } if s.app != "" && s.env != "" { tasks, err = s.lister.ListActiveAppEnvTasks(ecs.ListActiveAppEnvTasksOpts{ App: s.app, Env: s.env, ListTasksFilter: filter, }) if err != nil { return nil, fmt.Errorf("list active tasks in environment %s: %w", s.env, err) } } var taskStrList []string taskStrMap := make(map[string]*awsecs.Task) for _, task := range tasks { taskStr := task.String() taskStrList = append(taskStrList, taskStr) taskStrMap[taskStr] = task } if len(taskStrList) == 0 { return nil, fmt.Errorf("no running tasks found") } // return if only one running task found if len(taskStrList) == 1 { log.Infof("Found only one running task %s\n", color.HighlightUserInput(taskStrList[0])) return taskStrMap[taskStrList[0]], nil } task, err := s.prompt.SelectOne( msg, help, taskStrList, prompt.WithFinalMessage(taskFinalMsg), ) if err != nil { return nil, fmt.Errorf("select running task: %w", err) } return taskStrMap[task], nil } // GetDeployedWorkloadOpts sets up optional parameters for GetDeployedWorkloadOpts function. type GetDeployedWorkloadOpts func(*DeploySelector) // DeployedWorkloadFilter determines if a service or job should be included in the results. type DeployedWorkloadFilter func(*DeployedWorkload) (bool, error) // WithName sets up the wkld name for DeploySelector. func WithName(name string) GetDeployedWorkloadOpts { return func(in *DeploySelector) { in.name = name } } // WithEnv sets up the env name for DeploySelector. func WithEnv(env string) GetDeployedWorkloadOpts { return func(in *DeploySelector) { in.env = env } } // WithWkldFilter sets up filters for DeploySelector func WithWkldFilter(filter DeployedWorkloadFilter) GetDeployedWorkloadOpts { return func(in *DeploySelector) { in.filters = append(in.filters, filter) } } // WithServiceTypesFilter sets up a ServiceType filter for DeploySelector func WithServiceTypesFilter(svcTypes []string) GetDeployedWorkloadOpts { return WithWkldFilter(func(svc *DeployedWorkload) (bool, error) { for _, svcType := range svcTypes { if svc.Type == svcType { return true, nil } } return false, nil }) } // DeployedWorkload contains the name and environment name of the deployed workload. type DeployedWorkload struct { Name string Env string Type string } // String returns a string representation of the workload's name and environment. func (w *DeployedWorkload) String() string { return fmt.Sprintf("%s (%s)", w.Name, w.Env) } // DeployedJob contains the name and environment of the deployed job. type DeployedJob struct { Name string Env string } // String returns a string representation of the job's name and environment. func (j *DeployedJob) String() string { return fmt.Sprintf("%s (%s)", j.Name, j.Env) } // DeployedService contains the name and environment of the deployed service. type DeployedService struct { Name string Env string SvcType string } // String returns a string representation of the service's name and environment. func (s *DeployedService) String() string { return fmt.Sprintf("%s (%s)", s.Name, s.Env) } // Task has the user select a task. Callers can provide an environment, an app, or a "use default cluster" option // to filter the returned tasks. func (s *CFTaskSelector) Task(msg, help string, opts ...GetDeployedTaskOpts) (string, error) { for _, opt := range opts { opt(s) } if s.defaultCluster && (s.env != "" || s.app != "") { // Error for callers return "", fmt.Errorf("cannot specify both default cluster and env") } if !s.defaultCluster && (s.env == "" && s.app == "") { return "", fmt.Errorf("must specify either app and env or default cluster") } var tasks []deploy.TaskStackInfo var err error if s.defaultCluster { defaultTasks, err := s.cfStore.ListDefaultTaskStacks() if err != nil { return "", fmt.Errorf("get tasks in default cluster: %w", err) } tasks = append(tasks, defaultTasks...) } if s.env != "" && s.app != "" { envTasks, err := s.cfStore.ListTaskStacks(s.app, s.env) if err != nil { return "", fmt.Errorf("get tasks in environment %s: %w", s.env, err) } tasks = append(tasks, envTasks...) } choices := make([]string, len(tasks)) for n, task := range tasks { choices[n] = task.TaskName() } if len(choices) == 0 { return "", fmt.Errorf("no deployed tasks found in selected cluster") } // Return if there's only one option. if len(choices) == 1 { log.Infof("Found only one deployed task: %s\n", color.HighlightUserInput(choices[0])) return choices[0], nil } choice, err := s.prompt.SelectOne(msg, help, choices, prompt.WithFinalMessage(taskFinalMsg)) if err != nil { return "", fmt.Errorf("select task for deletion: %w", err) } return choice, nil } // DeployedJob has the user select a deployed job. Callers can provide either a particular environment, // a particular job to filter on, or both. func (s *DeploySelector) DeployedJob(msg, help string, app string, opts ...GetDeployedWorkloadOpts) (*DeployedJob, error) { j, err := s.deployedWorkload(jobWorkloadType, msg, help, app, opts...) if err != nil { return nil, err } return &DeployedJob{ Name: j.Name, Env: j.Env, }, nil } // DeployedService has the user select a deployed service. Callers can provide either a particular environment, // a particular service to filter on, or both. func (s *DeploySelector) DeployedService(msg, help string, app string, opts ...GetDeployedWorkloadOpts) (*DeployedService, error) { svc, err := s.deployedWorkload(svcWorkloadType, msg, help, app, opts...) if err != nil { return nil, err } return &DeployedService{ Name: svc.Name, Env: svc.Env, SvcType: svc.Type, }, nil } func (s *DeploySelector) deployedWorkload(workloadType string, msg, help string, app string, opts ...GetDeployedWorkloadOpts) (*DeployedWorkload, error) { for _, opt := range opts { opt(s) } var isWorkloadDeployed func(string, string, string) (bool, error) var listDeployedWorkloads func(string, string) ([]string, error) var finalMessage string switch workloadType { case svcWorkloadType: isWorkloadDeployed = s.deployStoreSvc.IsServiceDeployed listDeployedWorkloads = s.deployStoreSvc.ListDeployedServices finalMessage = deployedSvcFinalMsg case jobWorkloadType: isWorkloadDeployed = s.deployStoreSvc.IsJobDeployed listDeployedWorkloads = s.deployStoreSvc.ListDeployedJobs finalMessage = deployedJobFinalMsg default: return nil, fmt.Errorf("unrecognized workload type %s", workloadType) } var err error var envNames []string wkldTypes := map[string]string{} workloads, err := s.workloadLister.ListWorkloads(app) if err != nil { return nil, fmt.Errorf("list %ss: %w", workloadType, err) } for _, wkld := range workloads { wkldTypes[wkld.Name] = wkld.Type } if s.env != "" { envNames = append(envNames, s.env) } else { envNames, err = s.retrieveEnvironments(app) if err != nil { return nil, fmt.Errorf("list environments: %w", err) } } wkldEnvs := []*DeployedWorkload{} for _, envName := range envNames { var wkldNames []string if s.name != "" { deployed, err := isWorkloadDeployed(app, envName, s.name) if err != nil { return nil, fmt.Errorf("check if %s %s is deployed in environment %s: %w", workloadType, s.name, envName, err) } if !deployed { continue } wkldNames = append(wkldNames, s.name) } else { wkldNames, err = listDeployedWorkloads(app, envName) if err != nil { return nil, fmt.Errorf("list deployed %ss for environment %s: %w", workloadType, envName, err) } } for _, wkldName := range wkldNames { wkldEnv := &DeployedWorkload{ Name: wkldName, Env: envName, Type: wkldTypes[wkldName], } wkldEnvs = append(wkldEnvs, wkldEnv) } } if len(wkldEnvs) == 0 { return nil, fmt.Errorf("no deployed %ss found in application %s", workloadType, color.HighlightUserInput(app)) } if wkldEnvs, err = s.filterWorkloads(wkldEnvs); err != nil { return nil, err } if len(wkldEnvs) == 0 { return nil, fmt.Errorf("no matching deployed %ss found in application %s", workloadType, color.HighlightUserInput(app)) } // return if only one deployed workload found var deployedWkld *DeployedWorkload if len(wkldEnvs) == 1 { deployedWkld = wkldEnvs[0] if s.name == "" && s.env == "" { log.Infof("Found only one deployed %s %s in environment %s\n", workloadType, color.HighlightUserInput(deployedWkld.Name), color.HighlightUserInput(deployedWkld.Env)) } if (s.name != "") != (s.env != "") { log.Infof("%s %s found in environment %s\n", strings.ToTitle(workloadType), color.HighlightUserInput(deployedWkld.Name), color.HighlightUserInput(deployedWkld.Env)) } return deployedWkld, nil } wkldEnvNames := make([]string, len(wkldEnvs)) wkldEnvNameMap := map[string]*DeployedWorkload{} for i, svc := range wkldEnvs { wkldEnvNames[i] = svc.String() wkldEnvNameMap[wkldEnvNames[i]] = svc } wkldEnvName, err := s.prompt.SelectOne( msg, help, wkldEnvNames, prompt.WithFinalMessage(finalMessage), ) if err != nil { return nil, fmt.Errorf("select deployed %ss for application %s: %w", workloadType, app, err) } deployedWkld = wkldEnvNameMap[wkldEnvName] return deployedWkld, nil } func (s *DeploySelector) filterWorkloads(inWorkloads []*DeployedWorkload) ([]*DeployedWorkload, error) { outWorkloads := inWorkloads for _, filter := range s.filters { if result, err := filterDeployedServices(filter, outWorkloads); err != nil { return nil, err } else { outWorkloads = result } } return outWorkloads, nil } // Service fetches all services in the workspace and then prompts the user to select one. func (s *LocalWorkloadSelector) Service(msg, help string) (string, error) { summary, err := s.ws.Summary() if err != nil { return "", fmt.Errorf("read workspace summary: %w", err) } wsServiceNames, err := s.retrieveWorkspaceServices() if err != nil { return "", fmt.Errorf("retrieve services from workspace: %w", err) } storeServiceNames, err := s.ConfigSelector.workloadLister.ListServices(summary.Application) if err != nil { return "", fmt.Errorf("retrieve services from store: %w", err) } serviceNames := filterWlsByName(storeServiceNames, wsServiceNames) if len(serviceNames) == 0 { return "", errors.New("no services found") } if len(serviceNames) == 1 { log.Infof("Only found one service, defaulting to: %s\n", color.HighlightUserInput(serviceNames[0])) return serviceNames[0], nil } selectedServiceName, err := s.prompt.SelectOne(msg, help, serviceNames, prompt.WithFinalMessage(svcNameFinalMsg)) if err != nil { return "", fmt.Errorf("select service: %w", err) } return selectedServiceName, nil } // Job fetches all jobs in the workspace and then prompts the user to select one. func (s *LocalWorkloadSelector) Job(msg, help string) (string, error) { summary, err := s.ws.Summary() if err != nil { return "", fmt.Errorf("read workspace summary: %w", err) } wsJobNames, err := s.retrieveWorkspaceJobs() if err != nil { return "", fmt.Errorf("retrieve jobs from workspace: %w", err) } storeJobNames, err := s.ConfigSelector.workloadLister.ListJobs(summary.Application) if err != nil { return "", fmt.Errorf("retrieve jobs from store: %w", err) } jobNames := filterWlsByName(storeJobNames, wsJobNames) if len(jobNames) == 0 { return "", errors.New("no jobs found") } if len(jobNames) == 1 { log.Infof("Only found one job, defaulting to: %s\n", color.HighlightUserInput(jobNames[0])) return jobNames[0], nil } selectedJobName, err := s.prompt.SelectOne(msg, help, jobNames, prompt.WithFinalMessage(jobNameFinalMsg)) if err != nil { return "", fmt.Errorf("select job: %w", err) } return selectedJobName, nil } // Workload fetches all jobs and services in an app and prompts the user to select one. func (s *LocalWorkloadSelector) Workload(msg, help string) (wl string, err error) { summary, err := s.ws.Summary() if err != nil { return "", fmt.Errorf("read workspace summary: %w", err) } wsWlNames, err := s.retrieveWorkspaceWorkloads() if err != nil { return "", fmt.Errorf("retrieve jobs and services from workspace: %w", err) } storeWls, err := s.ConfigSelector.workloadLister.ListWorkloads(summary.Application) if err != nil { return "", fmt.Errorf("retrieve jobs and services from store: %w", err) } wlNames := filterWlsByName(storeWls, wsWlNames) if len(wlNames) == 0 { return "", errors.New("no jobs or services found") } if len(wlNames) == 1 { log.Infof("Only found one workload, defaulting to: %s\n", color.HighlightUserInput(wlNames[0])) return wlNames[0], nil } selectedWlName, err := s.prompt.SelectOne(msg, help, wlNames, prompt.WithFinalMessage(workloadFinalMsg)) if err != nil { return "", fmt.Errorf("select workload: %w", err) } return selectedWlName, nil } // LocalEnvironment fetches all environments belong to the app in the workspace and prompts the user to select one. func (s *LocalEnvironmentSelector) LocalEnvironment(msg, help string) (wl string, err error) { summary, err := s.ws.Summary() if err != nil { return "", fmt.Errorf("read workspace summary: %w", err) } wsEnvNames, err := s.ws.ListEnvironments() if err != nil { return "", fmt.Errorf("retrieve environments from workspace: %w", err) } envs, err := s.appEnvLister.ListEnvironments(summary.Application) if err != nil { return "", fmt.Errorf("retrieve environments from store: %w", err) } filteredEnvNames := filterEnvsByName(envs, wsEnvNames) if len(filteredEnvNames) == 0 { return "", ErrLocalEnvsNotFound } if len(filteredEnvNames) == 1 { log.Infof("Only found one environment, defaulting to: %s\n", color.HighlightUserInput(filteredEnvNames[0])) return filteredEnvNames[0], nil } selectedEnvName, err := s.prompt.SelectOne(msg, help, filteredEnvNames, prompt.WithFinalMessage(workloadFinalMsg)) if err != nil { return "", fmt.Errorf("select environment: %w", err) } return selectedEnvName, nil } func filterEnvsByName(envs []*config.Environment, wantedNames []string) []string { // TODO: refactor this and `filterWlsByName` when generic supports using common struct fields: https://github.com/golang/go/issues/48522 isWanted := make(map[string]bool) for _, name := range wantedNames { isWanted[name] = true } var filtered []string for _, wl := range envs { if _, ok := isWanted[wl.Name]; !ok { continue } filtered = append(filtered, wl.Name) } return filtered } func filterWlsByName(wls []*config.Workload, wantedNames []string) []string { isWanted := make(map[string]bool) for _, name := range wantedNames { isWanted[name] = true } var filtered []string for _, wl := range wls { if _, ok := isWanted[wl.Name]; !ok { continue } filtered = append(filtered, wl.Name) } return filtered } // WsPipeline fetches all the pipelines in a workspace and prompts the user to select one. func (s *WsPipelineSelector) WsPipeline(msg, help string) (*workspace.PipelineManifest, error) { pipelines, err := s.ws.ListPipelines() if err != nil { return nil, fmt.Errorf("list pipelines: %w", err) } if len(pipelines) == 0 { return nil, errors.New("no pipelines found") } var pipelineNames []string for _, pipeline := range pipelines { pipelineNames = append(pipelineNames, pipeline.Name) } if len(pipelineNames) == 1 { log.Infof("Only found one pipeline; defaulting to: %s\n", color.HighlightUserInput(pipelineNames[0])) return &workspace.PipelineManifest{ Name: pipelines[0].Name, Path: pipelines[0].Path, }, nil } selectedPipeline, err := s.prompt.SelectOne(msg, help, pipelineNames, prompt.WithFinalMessage(pipelineFinalMsg)) if err != nil { return nil, fmt.Errorf("select pipeline: %w", err) } return &workspace.PipelineManifest{ Name: selectedPipeline, Path: s.pipelinePath(pipelines, selectedPipeline), }, nil } // DeployedPipeline fetches all the pipelines in a workspace and prompts the user to select one. func (s *CodePipelineSelector) DeployedPipeline(msg, help, app string) (deploy.Pipeline, error) { pipelines, err := s.pipelineLister.ListDeployedPipelines(app) if err != nil { return deploy.Pipeline{}, fmt.Errorf("list deployed pipelines: %w", err) } if len(pipelines) == 0 { return deploy.Pipeline{}, errors.New("no deployed pipelines found") } if len(pipelines) == 1 { log.Infof("Only one deployed pipeline found; defaulting to: %s\n", color.HighlightUserInput(pipelines[0].Name)) return pipelines[0], nil } var pipelineNames []string pipelineNameToInfo := make(map[string]deploy.Pipeline) for _, pipeline := range pipelines { pipelineNames = append(pipelineNames, pipeline.Name) pipelineNameToInfo[pipeline.Name] = pipeline } selectedPipeline, err := s.prompt.SelectOne(msg, help, pipelineNames, prompt.WithFinalMessage(pipelineFinalMsg)) if err != nil { return deploy.Pipeline{}, fmt.Errorf("select pipeline: %w", err) } return pipelineNameToInfo[selectedPipeline], nil } // Service fetches all services in an app and prompts the user to select one. func (s *ConfigSelector) Service(msg, help, app string) (string, error) { services, err := s.retrieveServices(app) if err != nil { return "", err } if len(services) == 0 { return "", &errNoServiceInApp{appName: app} } if len(services) == 1 { log.Infof("Only found one service, defaulting to: %s\n", color.HighlightUserInput(services[0])) return services[0], nil } selectedSvcName, err := s.prompt.SelectOne(msg, help, services, prompt.WithFinalMessage(svcNameFinalMsg)) if err != nil { return "", fmt.Errorf("select service: %w", err) } return selectedSvcName, nil } // Job fetches all jobs in an app and prompts the user to select one. func (s *ConfigSelector) Job(msg, help, app string) (string, error) { jobs, err := s.retrieveJobs(app) if err != nil { return "", err } if len(jobs) == 0 { return "", &errNoJobInApp{appName: app} } if len(jobs) == 1 { log.Infof("Only found one job, defaulting to: %s\n", color.HighlightUserInput(jobs[0])) return jobs[0], nil } selectedJobName, err := s.prompt.SelectOne(msg, help, jobs, prompt.WithFinalMessage(jobNameFinalMsg)) if err != nil { return "", fmt.Errorf("select job: %w", err) } return selectedJobName, nil } // Workload fetches all workloads in an app and prompts the user to select one. func (s *ConfigSelector) Workload(msg, help, app string) (string, error) { services, err := s.retrieveServices(app) if err != nil { return "", err } jobs, err := s.retrieveJobs(app) if err != nil { return "", err } workloads := append(services, jobs...) if len(workloads) == 0 { return "", &errNoWorkloadInApp{appName: app} } if len(workloads) == 1 { log.Infof("Only found one workload, defaulting to: %s\n", color.HighlightUserInput(workloads[0])) return workloads[0], nil } selectedWorkloadName, err := s.prompt.SelectOne(msg, help, workloads, prompt.WithFinalMessage("Workload name:")) if err != nil { return "", fmt.Errorf("select workload: %w", err) } return selectedWorkloadName, nil } // Environment fetches all the environments in an app and prompts the user to select one. func (s *AppEnvSelector) Environment(msg, help, app string, additionalOpts ...string) (string, error) { envs, err := s.retrieveEnvironments(app) if err != nil { return "", fmt.Errorf("get environments for app %s from metadata store: %w", app, err) } envs = append(envs, additionalOpts...) if len(envs) == 0 { log.Infof("Couldn't find any environments associated with app %s, try initializing one: %s\n", color.HighlightUserInput(app), color.HighlightCode("copilot env init")) return "", fmt.Errorf("no environments found in app %s", app) } if len(envs) == 1 { log.Infof("Only found one environment, defaulting to: %s\n", color.HighlightUserInput(envs[0])) return envs[0], nil } selectedEnvName, err := s.prompt.SelectOne(msg, help, envs, prompt.WithFinalMessage(envNameFinalMessage)) if err != nil { return "", fmt.Errorf("select environment: %w", err) } return selectedEnvName, nil } // Environments fetches all the environments in an app and prompts the user to select one OR MORE. // The List of options decreases as envs are chosen. Chosen envs displayed above with the finalMsg. func (s *AppEnvSelector) Environments(prompt, help, app string, finalMsgFunc func(int) prompt.PromptConfig) ([]string, error) { envs, err := s.retrieveEnvironments(app) if err != nil { return nil, fmt.Errorf("get environments for app %s from metadata store: %w", app, err) } if len(envs) == 0 { log.Infof("Couldn't find any environments associated with app %s, try initializing one: %s\n", color.HighlightUserInput(app), color.HighlightCode("copilot env init")) return nil, fmt.Errorf("no environments found in app %s", app) } envs = append(envs, pipelineEscapeOpt) var selectedEnvs []string usedEnvs := make(map[string]bool) for i := 1; i < len(envs); i++ { var availableEnvs []string for _, env := range envs { // Check if environment has already been added to pipeline if _, ok := usedEnvs[env]; !ok { availableEnvs = append(availableEnvs, env) } } selectedEnv, err := s.prompt.SelectOne(prompt, help, availableEnvs, finalMsgFunc(i)) if err != nil { return nil, fmt.Errorf("select environments: %w", err) } if selectedEnv == pipelineEscapeOpt { break } selectedEnvs = append(selectedEnvs, selectedEnv) usedEnvs[selectedEnv] = true } return selectedEnvs, nil } // Application fetches all the apps in an account/region and prompts the user to select one. func (s *AppEnvSelector) Application(msg, help string, additionalOpts ...string) (string, error) { appNames, err := s.retrieveApps() if err != nil { return "", err } if len(appNames) == 0 { log.Infof("Couldn't find any applications in this region and account. Try initializing one with %s\n", color.HighlightCode("copilot app init")) return "", fmt.Errorf("no apps found") } if len(appNames) == 1 { log.Infof("Only found one application, defaulting to: %s\n", color.HighlightUserInput(appNames[0])) return appNames[0], nil } appNames = append(appNames, additionalOpts...) app, err := s.prompt.SelectOne(msg, help, appNames, prompt.WithFinalMessage(appNameFinalMessage)) if err != nil { return "", fmt.Errorf("select application: %w", err) } return app, nil } // Topics asks the user to select from all Copilot-managed SNS topics *which are deployed // across all environments* and returns the topic structs. func (s *DeploySelector) Topics(promptMsg, help, app string) ([]deploy.Topic, error) { envs, err := s.appEnvLister.ListEnvironments(app) if err != nil { return nil, fmt.Errorf("list environments: %w", err) } if len(envs) == 0 { log.Infoln("No environments are currently deployed. Skipping subscription selection.") return nil, nil } envTopics := make(map[string][]deploy.Topic, len(envs)) for _, env := range envs { topics, err := s.deployStoreSvc.ListSNSTopics(app, env.Name) if err != nil { return nil, fmt.Errorf("list SNS topics: %w", err) } envTopics[env.Name] = topics } // Get only topics deployed in all environments. // Computes the intersection of the `envTopics` lists. overallTopics := make(map[string]deploy.Topic) // Initialize the list of topics. for _, topic := range envTopics[envs[0].Name] { overallTopics[topic.String()] = topic } // Then do the pairwise intersection of all other envs. for _, env := range envs[1:] { topics := envTopics[env.Name] overallTopics = intersect(overallTopics, topics) } if len(overallTopics) == 0 { log.Infoln("No SNS topics are currently deployed in all environments. You can customize subscriptions in your manifest.") return nil, nil } // Create the list of options. var topicDescriptions []string for t := range overallTopics { topicDescriptions = append(topicDescriptions, t) } // Sort descriptions by ARN, which implies sorting by workload name and then by topic name due to // behavior of `intersect`. That is, the `overallTopics` map is guaranteed to contain topics // referencing the same environment. sort.Slice(topicDescriptions, func(i, j int) bool { return overallTopics[topicDescriptions[i]].ARN() < overallTopics[topicDescriptions[j]].ARN() }) selectedTopics, err := s.prompt.MultiSelect( promptMsg, help, topicDescriptions, nil, prompt.WithFinalMessage(topicFinalMsg), ) if err != nil { return nil, fmt.Errorf("select SNS topics: %w", err) } // Get the topics from the topic descriptions again. var topics []deploy.Topic for _, t := range selectedTopics { topics = append(topics, overallTopics[t]) } return topics, nil } func (s *AppEnvSelector) retrieveApps() ([]string, error) { apps, err := s.appEnvLister.ListApplications() if err != nil { return nil, fmt.Errorf("list applications: %w", err) } appNames := make([]string, len(apps)) for ind, app := range apps { appNames[ind] = app.Name } return appNames, nil } func (s *AppEnvSelector) retrieveEnvironments(app string) ([]string, error) { envs, err := s.appEnvLister.ListEnvironments(app) if err != nil { return nil, fmt.Errorf("list environments: %w", err) } envsNames := make([]string, len(envs)) for ind, env := range envs { envsNames[ind] = env.Name } return envsNames, nil } func (s *ConfigSelector) retrieveServices(app string) ([]string, error) { services, err := s.workloadLister.ListServices(app) if err != nil { return nil, fmt.Errorf("list services: %w", err) } serviceNames := make([]string, len(services)) for ind, service := range services { serviceNames[ind] = service.Name } return serviceNames, nil } func (s *ConfigSelector) retrieveJobs(app string) ([]string, error) { jobs, err := s.workloadLister.ListJobs(app) if err != nil { return nil, fmt.Errorf("list jobs: %w", err) } jobNames := make([]string, len(jobs)) for ind, job := range jobs { jobNames[ind] = job.Name } return jobNames, nil } func (s *LocalWorkloadSelector) retrieveWorkspaceServices() ([]string, error) { localServiceNames, err := s.ws.ListServices() if err != nil { return nil, err } return localServiceNames, nil } func (s *LocalWorkloadSelector) retrieveWorkspaceJobs() ([]string, error) { localJobNames, err := s.ws.ListJobs() if err != nil { return nil, err } return localJobNames, nil } func (s *LocalWorkloadSelector) retrieveWorkspaceWorkloads() ([]string, error) { localWlNames, err := s.ws.ListWorkloads() if err != nil { return nil, err } return localWlNames, nil } func (s *WsPipelineSelector) pipelinePath(pipelines []workspace.PipelineManifest, name string) string { for _, pipeline := range pipelines { if pipeline.Name == name { return pipeline.Path } } return "" } func filterDeployedServices(filter DeployedWorkloadFilter, inServices []*DeployedWorkload) ([]*DeployedWorkload, error) { outServices := []*DeployedWorkload{} for _, svc := range inServices { if include, err := filter(svc); err != nil { return nil, err } else if include { outServices = append(outServices, svc) } } return outServices, nil } func intersect(firstMap map[string]deploy.Topic, secondArr []deploy.Topic) map[string]deploy.Topic { out := make(map[string]deploy.Topic) for _, topic := range secondArr { if _, ok := firstMap[topic.String()]; ok { out[topic.String()] = topic } } return out }
1,254
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package selector import ( "errors" "fmt" "testing" "github.com/aws/aws-sdk-go/aws" awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs" "github.com/aws/copilot-cli/internal/pkg/config" "github.com/aws/copilot-cli/internal/pkg/deploy" "github.com/aws/copilot-cli/internal/pkg/ecs" "github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "github.com/aws/copilot-cli/internal/pkg/term/selector/mocks" "github.com/aws/copilot-cli/internal/pkg/workspace" "github.com/dustin/go-humanize" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) type deploySelectMocks struct { deploySvc *mocks.MockdeployedWorkloadsRetriever configSvc *mocks.MockconfigLister prompt *mocks.MockPrompter } func TestDeploySelect_Topics(t *testing.T) { const ( testApp = "mockApp" testEnv = "mockEnv" prodEnv = "mockProdEnv" ) mockTopic, _ := deploy.NewTopic("arn:aws:sns:us-west-2:123456789012:mockApp-mockEnv-mockWkld-orders", testApp, testEnv, "mockWkld") mockTopic2, _ := deploy.NewTopic("arn:aws:sns:us-west-2:123456789012:mockApp-mockEnv-mockWkld-events", testApp, testEnv, "mockWkld") testCases := map[string]struct { setupMocks func(mocks deploySelectMocks) wantErr error wantTopics []deploy.Topic }{ "return error if fail to retrieve topics from deploy": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListEnvironments(testApp).Return( []*config.Environment{{Name: testEnv}}, nil, ) m.deploySvc. EXPECT(). ListSNSTopics(testApp, testEnv). Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("list SNS topics: some error"), }, "return error if fail to select topics": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListEnvironments(testApp).Return( []*config.Environment{{Name: testEnv}}, nil, ) m.deploySvc. EXPECT(). ListSNSTopics(testApp, testEnv). Return([]deploy.Topic{*mockTopic}, nil) m.prompt. EXPECT(). MultiSelect("Select a deployed topic", "Help text", []string{"orders (mockWkld)"}, nil, gomock.Any()). Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("select SNS topics: some error"), }, "success": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListEnvironments(testApp).Return( []*config.Environment{{Name: testEnv}, {Name: prodEnv}}, nil, ) m.deploySvc. EXPECT(). ListSNSTopics(testApp, testEnv). Return([]deploy.Topic{*mockTopic, *mockTopic2}, nil) m.deploySvc. EXPECT(). ListSNSTopics(testApp, prodEnv). Return([]deploy.Topic{*mockTopic}, nil) m.prompt. EXPECT(). MultiSelect("Select a deployed topic", "Help text", []string{"orders (mockWkld)"}, nil, gomock.Any()). Return([]string{"orders (mockWkld)"}, nil) }, wantTopics: []deploy.Topic{*mockTopic}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockdeploySvc := mocks.NewMockdeployedWorkloadsRetriever(ctrl) mockconfigSvc := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := deploySelectMocks{ deploySvc: mockdeploySvc, configSvc: mockconfigSvc, prompt: mockprompt, } tc.setupMocks(mocks) sel := DeploySelector{ ConfigSelector: &ConfigSelector{ AppEnvSelector: &AppEnvSelector{ appEnvLister: mockconfigSvc, prompt: mockprompt, }, workloadLister: mockconfigSvc, }, deployStoreSvc: mockdeploySvc, } topics, err := sel.Topics("Select a deployed topic", "Help text", testApp) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.wantTopics, topics) } }) } } func TestIntersect(t *testing.T) { mockTopic1Env1, _ := deploy.NewTopic("arn:aws:sns:us-west-2:123456789012:mockApp-mockEnv1-mockWkld-orders", "mockApp", "mockEnv1", "mockWkld") mockTopic1Env2, _ := deploy.NewTopic("arn:aws:sns:us-west-2:123456789012:mockApp-mockEnv2-mockWkld-orders", "mockApp", "mockEnv2", "mockWkld") mockTopic2Env1, _ := deploy.NewTopic("arn:aws:sns:us-west-2:123456789012:mockApp-mockEnv1-mockWkld2-events", "mockApp", "mockEnv1", "mockWkld2") mockTopic2Env2, _ := deploy.NewTopic("arn:aws:sns:us-west-2:123456789012:mockApp-mockEnv2-mockWkld2-events", "mockApp", "mockEnv2", "mockWkld2") testCases := map[string]struct { inArray []deploy.Topic inMap map[string]deploy.Topic wantedMap map[string]deploy.Topic }{ "with no common entries": { inArray: []deploy.Topic{ *mockTopic1Env1, }, inMap: map[string]deploy.Topic{ mockTopic2Env2.String(): *mockTopic2Env2, }, wantedMap: map[string]deploy.Topic{}, }, "with common entries": { inArray: []deploy.Topic{ *mockTopic1Env1, *mockTopic2Env1, }, inMap: map[string]deploy.Topic{ mockTopic2Env2.String(): *mockTopic2Env2, mockTopic1Env2.String(): *mockTopic1Env2, }, wantedMap: map[string]deploy.Topic{ mockTopic2Env1.String(): *mockTopic2Env1, mockTopic1Env1.String(): *mockTopic1Env1, }, }, "with one common entry, extra entry in array": { inArray: []deploy.Topic{ *mockTopic1Env1, *mockTopic2Env1, }, inMap: map[string]deploy.Topic{ mockTopic2Env2.String(): *mockTopic2Env2, }, wantedMap: map[string]deploy.Topic{ mockTopic2Env1.String(): *mockTopic2Env1, }, }, "with one common entry, extra entry in map": { inArray: []deploy.Topic{ *mockTopic1Env1, }, inMap: map[string]deploy.Topic{ mockTopic2Env2.String(): *mockTopic2Env2, mockTopic1Env2.String(): *mockTopic1Env2, }, wantedMap: map[string]deploy.Topic{ mockTopic1Env1.String(): *mockTopic1Env1, }, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN // WHEN out := intersect(tc.inMap, tc.inArray) // THEN require.Equal(t, out, tc.wantedMap) }) } } func TestDeploySelect_Service(t *testing.T) { const testApp = "mockApp" testCases := map[string]struct { setupMocks func(mocks deploySelectMocks) svc string env string opts []GetDeployedWorkloadOpts wantErr error wantEnv string wantSvc string wantSvcType string }{ "return error if fail to retrieve environment": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("list environments: list environments: some error"), }, "return error if fail to list deployed services": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test"). Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("list deployed services for environment test: some error"), }, "return error if no deployed services found": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test"). Return([]string{}, nil) }, wantErr: fmt.Errorf("no deployed services found in application %s", testApp), }, "return error if fail to select": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test"). Return([]string{"mockSvc1", "mockSvc2"}, nil) m.prompt. EXPECT(). SelectOne("Select a deployed service", "Help text", []string{"mockSvc1 (test)", "mockSvc2 (test)"}, gomock.Any()). Return("", errors.New("some error")) }, wantErr: fmt.Errorf("select deployed services for application %s: some error", testApp), }, "success": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{ { App: testApp, Name: "mockSvc1", Type: "mockSvcType1", }, { App: testApp, Name: "mockSvc2", Type: "mockSvcType2", }, }, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test"). Return([]string{"mockSvc1", "mockSvc2"}, nil) m.prompt. EXPECT(). SelectOne("Select a deployed service", "Help text", []string{"mockSvc1 (test)", "mockSvc2 (test)"}, gomock.Any()). Return("mockSvc1 (test)", nil) }, wantEnv: "test", wantSvc: "mockSvc1", wantSvcType: "mockSvcType1", }, "skip with only one deployed service": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{ { App: testApp, Name: "mockSvc", Type: "mockSvcType", }, }, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test"). Return([]string{"mockSvc"}, nil) }, wantEnv: "test", wantSvc: "mockSvc", wantSvcType: "mockSvcType", }, "return error if fail to check if service passed in by flag is deployed or not": { env: "test", svc: "mockSvc", setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.deploySvc. EXPECT(). IsServiceDeployed(testApp, "test", "mockSvc"). Return(false, errors.New("some error")) }, wantErr: fmt.Errorf("check if service mockSvc is deployed in environment test: some error"), }, "success with flags": { env: "test", svc: "mockSvc", setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.deploySvc. EXPECT(). IsServiceDeployed(testApp, "test", "mockSvc"). Return(true, nil) }, wantEnv: "test", wantSvc: "mockSvc", }, "filter deployed services": { opts: []GetDeployedWorkloadOpts{ WithWkldFilter(func(svc *DeployedWorkload) (bool, error) { return svc.Env == "test1", nil }), WithServiceTypesFilter([]string{manifestinfo.BackendServiceType}), }, setupMocks: func(m deploySelectMocks) { m.configSvc. EXPECT(). ListWorkloads(testApp). Return([]*config.Workload{ { App: testApp, Name: "mockSvc1", Type: manifestinfo.BackendServiceType, }, { App: testApp, Name: "mockSvc2", Type: manifestinfo.BackendServiceType, }, { App: testApp, Name: "mockSvc3", Type: manifestinfo.LoadBalancedWebServiceType, }, { App: testApp, Name: "mockJob1", Type: manifestinfo.ScheduledJobType, }, }, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ {Name: "test1"}, {Name: "test2"}, }, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test1"). Return([]string{"mockSvc1", "mockSvc2", "mockSvc3"}, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test2"). Return([]string{"mockSvc1", "mockSvc2", "mockSvc3"}, nil) m.prompt. EXPECT(). SelectOne("Select a deployed service", "Help text", []string{"mockSvc1 (test1)", "mockSvc2 (test1)"}, gomock.Any()). Return("mockSvc1 (test1)", nil) }, wantEnv: "test1", wantSvc: "mockSvc1", wantSvcType: manifestinfo.BackendServiceType, }, "filter returns error": { opts: []GetDeployedWorkloadOpts{ WithWkldFilter(func(svc *DeployedWorkload) (bool, error) { return svc.Env == "test1", fmt.Errorf("filter error") }), }, setupMocks: func(m deploySelectMocks) { m.configSvc. EXPECT(). ListWorkloads(testApp). Return([]*config.Workload{ { App: testApp, Name: "mockSvc1", Type: manifestinfo.BackendServiceType, }, { App: testApp, Name: "mockSvc2", Type: manifestinfo.BackendServiceType, }, { App: testApp, Name: "mockSvc3", Type: manifestinfo.LoadBalancedWebServiceType, }, }, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ {Name: "test1"}, {Name: "test2"}, }, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test1"). Return([]string{"mockSvc1", "mockSvc2", "mockSvc3"}, nil) m.deploySvc. EXPECT(). ListDeployedServices(testApp, "test2"). Return([]string{"mockSvc1", "mockSvc2", "mockSvc3"}, nil) }, wantErr: fmt.Errorf("filter error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockdeploySvc := mocks.NewMockdeployedWorkloadsRetriever(ctrl) mockconfigSvc := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := deploySelectMocks{ deploySvc: mockdeploySvc, configSvc: mockconfigSvc, prompt: mockprompt, } tc.setupMocks(mocks) sel := DeploySelector{ ConfigSelector: &ConfigSelector{ AppEnvSelector: &AppEnvSelector{ appEnvLister: mockconfigSvc, prompt: mockprompt, }, workloadLister: mockconfigSvc, }, deployStoreSvc: mockdeploySvc, } opts := append([]GetDeployedWorkloadOpts{WithEnv(tc.env), WithName(tc.svc)}, tc.opts...) gotDeployed, err := sel.DeployedService("Select a deployed service", "Help text", testApp, opts...) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.wantSvc, gotDeployed.Name) require.Equal(t, tc.wantSvcType, gotDeployed.SvcType) require.Equal(t, tc.wantEnv, gotDeployed.Env) } }) } } func TestDeploySelect_Job(t *testing.T) { const testApp = "mockApp" testCases := map[string]struct { setupMocks func(mocks deploySelectMocks) job string env string opts []GetDeployedWorkloadOpts wantErr error wantEnv string wantJob string }{ "return error if fail to retrieve environment": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("list environments: list environments: some error"), }, "return error if fail to list deployed job": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test"). Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("list deployed jobs for environment test: some error"), }, "return error if no deployed jobs found": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test"). Return([]string{}, nil) }, wantErr: fmt.Errorf("no deployed jobs found in application %s", testApp), }, "return error if fail to select": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test"). Return([]string{"mockJob1", "mockJob2"}, nil) m.prompt. EXPECT(). SelectOne("Select a deployed job", "Help text", []string{"mockJob1 (test)", "mockJob2 (test)"}, gomock.Any()). Return("", errors.New("some error")) }, wantErr: fmt.Errorf("select deployed jobs for application %s: some error", testApp), }, "success": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test"). Return([]string{"mockJob1", "mockJob2"}, nil) m.prompt. EXPECT(). SelectOne("Select a deployed job", "Help text", []string{"mockJob1 (test)", "mockJob2 (test)"}, gomock.Any()). Return("mockJob1 (test)", nil) }, wantEnv: "test", wantJob: "mockJob1", }, "skip with only one deployed job": { setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ { Name: "test", }, }, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test"). Return([]string{"mockJob"}, nil) }, wantEnv: "test", wantJob: "mockJob", }, "return error if fail to check if job passed in by flag is deployed or not": { env: "test", job: "mockJob", setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.deploySvc. EXPECT(). IsJobDeployed(testApp, "test", "mockJob"). Return(false, errors.New("some error")) }, wantErr: fmt.Errorf("check if job mockJob is deployed in environment test: some error"), }, "success with flags": { env: "test", job: "mockJob", setupMocks: func(m deploySelectMocks) { m.configSvc.EXPECT().ListWorkloads(testApp).Return([]*config.Workload{}, nil) m.deploySvc. EXPECT(). IsJobDeployed(testApp, "test", "mockJob"). Return(true, nil) }, wantEnv: "test", wantJob: "mockJob", }, "filter deployed jobs": { opts: []GetDeployedWorkloadOpts{ WithWkldFilter(func(job *DeployedWorkload) (bool, error) { return job.Env == "test2", nil }), WithServiceTypesFilter([]string{manifestinfo.ScheduledJobType}), }, setupMocks: func(m deploySelectMocks) { m.configSvc. EXPECT(). ListWorkloads(testApp). Return([]*config.Workload{ { App: testApp, Name: "mockSvc1", Type: manifestinfo.BackendServiceType, }, { App: testApp, Name: "mockSvc2", Type: manifestinfo.BackendServiceType, }, { App: testApp, Name: "mockJob1", Type: manifestinfo.ScheduledJobType, }, { App: testApp, Name: "mockJob2", Type: manifestinfo.ScheduledJobType, }, }, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ {Name: "test1"}, {Name: "test2"}, }, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test1"). Return([]string{"mockJob1"}, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test2"). Return([]string{"mockJob1", "mockJob2"}, nil) m.prompt. EXPECT(). SelectOne("Select a deployed job", "Help text", []string{"mockJob1 (test2)", "mockJob2 (test2)"}, gomock.Any()). Return("mockJob1 (test2)", nil) }, wantEnv: "test2", wantJob: "mockJob1", }, "filter returns error": { opts: []GetDeployedWorkloadOpts{ WithWkldFilter(func(job *DeployedWorkload) (bool, error) { return job.Env == "test1", fmt.Errorf("filter error") }), }, setupMocks: func(m deploySelectMocks) { m.configSvc. EXPECT(). ListWorkloads(testApp). Return([]*config.Workload{ { App: testApp, Name: "mockJob1", Type: manifestinfo.ScheduledJobType, }, { App: testApp, Name: "mockJob2", Type: manifestinfo.ScheduledJobType, }, { App: testApp, Name: "mockSvc3", Type: manifestinfo.LoadBalancedWebServiceType, }, }, nil) m.configSvc. EXPECT(). ListEnvironments(testApp). Return([]*config.Environment{ {Name: "test1"}, {Name: "test2"}, }, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test1"). Return([]string{"mockJob1", "mockJob2"}, nil) m.deploySvc. EXPECT(). ListDeployedJobs(testApp, "test2"). Return([]string{"mockJob1", "mockJob2"}, nil) }, wantErr: fmt.Errorf("filter error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockdeploySvc := mocks.NewMockdeployedWorkloadsRetriever(ctrl) mockconfigSvc := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := deploySelectMocks{ deploySvc: mockdeploySvc, configSvc: mockconfigSvc, prompt: mockprompt, } tc.setupMocks(mocks) sel := DeploySelector{ ConfigSelector: &ConfigSelector{ AppEnvSelector: &AppEnvSelector{ appEnvLister: mockconfigSvc, prompt: mockprompt, }, workloadLister: mockconfigSvc, }, deployStoreSvc: mockdeploySvc, } opts := append([]GetDeployedWorkloadOpts{WithEnv(tc.env), WithName(tc.job)}, tc.opts...) gotDeployed, err := sel.DeployedJob("Select a deployed job", "Help text", testApp, opts...) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.NoError(t, err) require.Equal(t, tc.wantJob, gotDeployed.Name) require.Equal(t, tc.wantEnv, gotDeployed.Env) } }) } } type workspaceSelectMocks struct { ws *mocks.MockworkspaceRetriever prompt *mocks.MockPrompter configLister *mocks.MockconfigLister } func TestWorkspaceSelect_Service(t *testing.T) { testCases := map[string]struct { setupMocks func(mocks workspaceSelectMocks) wantErr error want string }{ "with no workspace services and no store services": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListServices().Return( []string{}, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{}, nil).Times(1) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no services found"), }, "with one workspace service but no store services": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListServices().Return( []string{ "service1", }, nil). Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{}, nil).Times(1) }, wantErr: fmt.Errorf("no services found"), }, "with one store service but no workspace services": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListServices().Return( []string{}, nil). Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{ { App: "app-name", Name: "service1", Type: "load balanced web service", }, }, nil).Times(1) }, wantErr: fmt.Errorf("no services found"), }, "with only one service in both workspace and store (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListServices().Return( []string{ "service1", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{ { App: "app-name", Name: "service1", Type: "load balanced web service", }, }, nil).Times(1) m.prompt. EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "service1", }, "with multiple workspace services but only one store service (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListServices().Return( []string{ "service1", "service2", "service3", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{ { App: "app-name", Name: "service1", Type: "load balanced web service", }, }, nil).Times(1) m.prompt. EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "service1", }, "with multiple store services but only one workspace service (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListServices().Return( []string{ "service3", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{ { App: "app-name", Name: "service1", Type: "load balanced web service", }, { App: "app-name", Name: "service2", Type: "load balanced web service", }, { App: "app-name", Name: "service3", Type: "load balanced web service", }, }, nil).Times(1) m.prompt. EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "service3", }, "with multiple workspace services and multiple store services, of which multiple overlap": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListServices().Return( []string{ "service1", "service2", "service3", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{ { App: "app-name", Name: "service2", Type: "load balanced web service", }, { App: "app-name", Name: "service3", Type: "load balanced web service", }, { App: "app-name", Name: "service4", Type: "load balanced web service", }, }, nil).Times(1) m.prompt. EXPECT(). SelectOne( gomock.Eq("Select a service"), gomock.Eq("Help text"), gomock.Eq([]string{"service2", "service3"}), gomock.Any()). Return("service2", nil).Times(1) }, want: "service2", }, "with error retrieving services from workspace": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListServices().Return( []string{""}, errors.New("some error")) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) }, wantErr: errors.New("retrieve services from workspace: some error"), }, "with error retrieving services from store": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListServices().Return( []string{ "service1", "service2", }, nil). Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( nil, errors.New("some error")) }, wantErr: errors.New("retrieve services from store: some error"), }, "with error selecting services": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListServices().Return( []string{ "service1", "service2", }, nil). Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListServices("app-name").Return( []*config.Workload{ { App: "app-name", Name: "service1", Type: "load balanced web service", }, { App: "app-name", Name: "service2", Type: "load balanced web service", }, }, nil).Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"service1", "service2"}), gomock.Any()). Return("", fmt.Errorf("error selecting")). Times(1) }, wantErr: fmt.Errorf("select service: error selecting"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockwsRetriever := mocks.NewMockworkspaceRetriever(ctrl) MockconfigLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := workspaceSelectMocks{ ws: mockwsRetriever, configLister: MockconfigLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := LocalWorkloadSelector{ ConfigSelector: &ConfigSelector{ AppEnvSelector: &AppEnvSelector{ prompt: mockprompt, appEnvLister: MockconfigLister, }, workloadLister: MockconfigLister, }, ws: mockwsRetriever, } got, err := sel.Service("Select a service", "Help text") if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } func TestWorkspaceSelect_Job(t *testing.T) { testCases := map[string]struct { setupMocks func(mocks workspaceSelectMocks) wantErr error want string }{ "with no workspace jobs and no store jobs": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListJobs().Return( []string{}, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( []*config.Workload{}, nil).Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no jobs found"), }, "with one workspace job but no store jobs": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListJobs().Return( []string{ "job1", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( []*config.Workload{}, nil).Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no jobs found"), }, "with one store job but no workspace jobs": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListJobs().Return( []string{}, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( []*config.Workload{ { App: "app-name", Name: "job1", Type: "Scheduled Job", }, }, nil).Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no jobs found"), }, "with only one in both workspace and store (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListJobs().Return( []string{ "resizer", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( []*config.Workload{ { App: "app-name", Name: "resizer", Type: "Scheduled Job", }, }, nil).Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "resizer", }, "with multiple workspace jobs but only one store job (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListJobs().Return( []string{ "job1", "job2", "job3", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( []*config.Workload{ { App: "app-name", Name: "job2", Type: "Scheduled Job", }, }, nil).Times(1) m.prompt. EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "job2", }, "with multiple store jobs but only one workspace job (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListJobs().Return( []string{ "job3", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( []*config.Workload{ { App: "app-name", Name: "job1", Type: "Scheduled Job", }, { App: "app-name", Name: "job2", Type: "Scheduled Job", }, { App: "app-name", Name: "job3", Type: "Scheduled Job", }, }, nil).Times(1) m.prompt. EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "job3", }, "with multiple workspace jobs and multiple store jobs, of which multiple overlap": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListJobs().Return( []string{ "job1", "job2", "job3", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister. EXPECT(). ListJobs("app-name"). Return( []*config.Workload{ { App: "app-name", Name: "job2", Type: "Scheduled Job", }, { App: "app-name", Name: "job3", Type: "Scheduled Job", }, { App: "app-name", Name: "job4", Type: "Scheduled Job", }, }, nil).Times(1) m.prompt. EXPECT(). SelectOne( gomock.Eq("Select a job"), gomock.Eq("Help text"), gomock.Eq([]string{"job2", "job3"}), gomock.Any()). Return("job2", nil). Times(1) }, want: "job2", }, "with error retrieving jobs from workspace": { setupMocks: func(m workspaceSelectMocks) { m.ws. EXPECT().ListJobs().Return( []string{""}, errors.New("some error")) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) }, wantErr: errors.New("retrieve jobs from workspace: some error"), }, "with error retrieving jobs from store": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListJobs().Return( []string{ "service1", "service2", }, nil). Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( nil, errors.New("some error")) }, wantErr: errors.New("retrieve jobs from store: some error"), }, "with error selecting jobs": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().ListJobs().Return( []string{ "resizer1", "resizer2", }, nil).Times(1) m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "app-name", }, nil) m.configLister.EXPECT().ListJobs("app-name").Return( []*config.Workload{ { App: "app-name", Name: "resizer1", Type: "Scheduled Job", }, { App: "app-name", Name: "resizer2", Type: "Scheduled Job", }, }, nil).Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"resizer1", "resizer2"}), gomock.Any()). Return("", fmt.Errorf("error selecting")). Times(1) }, wantErr: fmt.Errorf("select job: error selecting"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockwsRetriever := mocks.NewMockworkspaceRetriever(ctrl) MockconfigLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := workspaceSelectMocks{ ws: mockwsRetriever, configLister: MockconfigLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := LocalWorkloadSelector{ ConfigSelector: &ConfigSelector{ AppEnvSelector: &AppEnvSelector{ prompt: mockprompt, appEnvLister: MockconfigLister, }, workloadLister: MockconfigLister, }, ws: mockwsRetriever, } got, err := sel.Job("Select a job", "Help text") if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } func TestWorkspaceSelect_EnvironmentsInWorkspace(t *testing.T) { testCases := map[string]struct { setupMocks func(mocks workspaceSelectMocks) wantErr error want string }{ "fail to retrieve workspace app name": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return(nil, errors.New("some error")) }, wantErr: errors.New("read workspace summary: some error"), }, "fail to list environments in workspace": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return(nil, errors.New("some error")) }, wantErr: errors.New("retrieve environments from workspace: some error"), }, "fail to list environments in store": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{"mockEnv1", "mockEnv2"}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return(nil, errors.New("some error")) }, wantErr: errors.New("retrieve environments from store: some error"), }, "fail to select an environment": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{"mockEnv1", "mockEnv2"}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{ { App: "mockApp", Name: "mockEnv1", }, { App: "mockApp", Name: "mockEnv2", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"mockEnv1", "mockEnv2"}), gomock.Any()). Return("", errors.New("some error")). Times(1) }, wantErr: fmt.Errorf("select environment: some error"), }, "with no workspace environments and no store environments": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, wantErr: fmt.Errorf("no environments found"), }, "with one workspace environment but no store environment": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{"mockEnv"}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, wantErr: fmt.Errorf("no environments found"), }, "with one store environment but no workspace environments": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{ { App: "mockApp", Name: "mockEnv", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, wantErr: fmt.Errorf("no environments found"), }, "with only one in both workspace and store (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{"mockEnv"}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{ { App: "mockApp", Name: "mockEnv", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, want: "mockEnv", }, "with multiple workspace environments but only one store environment (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{"mockEnv1", "mockEnv2"}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{ { App: "mockApp", Name: "mockEnv1", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, want: "mockEnv1", }, "with multiple store environments but only one workspace environment (skips prompting)": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{"mockEnv1"}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{ { App: "mockApp", Name: "mockEnv1", }, { App: "mockApp", Name: "mockEnv2", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, want: "mockEnv1", }, "with multiple workspace environments and multiple store environments, of which multiple overlap": { setupMocks: func(m workspaceSelectMocks) { m.ws.EXPECT().Summary().Return( &workspace.Summary{ Application: "mockApp", }, nil) m.ws.EXPECT().ListEnvironments().Return([]string{"mockEnv1", "mockEnv2", "mockEnv3"}, nil).Times(1) m.configLister.EXPECT().ListEnvironments("mockApp").Return([]*config.Environment{ { App: "mockApp", Name: "mockEnv1", }, { App: "mockApp", Name: "mockEnv2", }, { App: "mockApp", Name: "mockEnv4", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"mockEnv1", "mockEnv2"}), gomock.Any()). Return("mockEnv1", nil). Times(1) }, want: "mockEnv1", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() m := workspaceSelectMocks{ ws: mocks.NewMockworkspaceRetriever(ctrl), configLister: mocks.NewMockconfigLister(ctrl), prompt: mocks.NewMockPrompter(ctrl), } tc.setupMocks(m) sel := LocalEnvironmentSelector{ AppEnvSelector: &AppEnvSelector{ prompt: m.prompt, appEnvLister: m.configLister, }, ws: m.ws, } got, err := sel.LocalEnvironment("Select an environment", "Help text") if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.NoError(t, err) require.Equal(t, tc.want, got) } }) } } type configSelectMocks struct { workloadLister *mocks.MockconfigLister prompt *mocks.MockPrompter } func TestConfigSelect_Service(t *testing.T) { appName := "myapp" testCases := map[string]struct { setupMocks func(m configSelectMocks) wantErr error want string }{ "with no services": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListServices(gomock.Eq(appName)). Return([]*config.Workload{}, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no services found in app myapp"), }, "with only one service (skips prompting)": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListServices(gomock.Eq(appName)). Return([]*config.Workload{ { App: appName, Name: "service1", Type: "load balanced web service", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "service1", }, "with multiple services": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListServices(gomock.Eq(appName)). Return([]*config.Workload{ { App: appName, Name: "service1", Type: "load balanced web service", }, { App: appName, Name: "service2", Type: "backend service", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne( gomock.Eq("Select a service"), gomock.Eq("Help text"), gomock.Eq([]string{"service1", "service2"}), gomock.Any()). Return("service2", nil). Times(1) }, want: "service2", }, "with error selecting services": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListServices(gomock.Eq(appName)). Return([]*config.Workload{ { App: appName, Name: "service1", Type: "load balanced web service", }, { App: appName, Name: "service2", Type: "backend service", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"service1", "service2"}), gomock.Any()). Return("", fmt.Errorf("error selecting")). Times(1) }, wantErr: fmt.Errorf("select service: error selecting"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockconfigLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := configSelectMocks{ workloadLister: mockconfigLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := ConfigSelector{ AppEnvSelector: &AppEnvSelector{ prompt: mockprompt, }, workloadLister: mockconfigLister, } got, err := sel.Service("Select a service", "Help text", appName) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } func TestConfigSelect_Job(t *testing.T) { appName := "myapp" testCases := map[string]struct { setupMocks func(m configSelectMocks) wantErr error want string }{ "with no jobs": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListJobs(gomock.Eq(appName)). Return([]*config.Workload{}, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no jobs found in app myapp"), }, "with only one job (skips prompting)": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListJobs(gomock.Eq(appName)). Return([]*config.Workload{ { App: appName, Name: "job1", Type: "load balanced web service", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "job1", }, "with multiple jobs": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListJobs(gomock.Eq(appName)). Return([]*config.Workload{ { App: appName, Name: "job1", Type: "load balanced web service", }, { App: appName, Name: "job2", Type: "backend service", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne( gomock.Eq("Select a job"), gomock.Eq("Help text"), gomock.Eq([]string{"job1", "job2"}), gomock.Any()). Return("job2", nil). Times(1) }, want: "job2", }, "with error selecting jobs": { setupMocks: func(m configSelectMocks) { m.workloadLister. EXPECT(). ListJobs(gomock.Eq(appName)). Return([]*config.Workload{ { App: appName, Name: "job1", Type: "load balanced web service", }, { App: appName, Name: "job2", Type: "backend service", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"job1", "job2"}), gomock.Any()). Return("", fmt.Errorf("error selecting")). Times(1) }, wantErr: fmt.Errorf("select job: error selecting"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockconfigLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := configSelectMocks{ workloadLister: mockconfigLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := ConfigSelector{ AppEnvSelector: &AppEnvSelector{ prompt: mockprompt, }, workloadLister: mockconfigLister, } got, err := sel.Job("Select a job", "Help text", appName) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } func TestConfigSelect_Workload(t *testing.T) { appName := "myapp" testCases := map[string]struct { setupMocks func(m configSelectMocks) wantErr error want string }{ "with no workloads": { setupMocks: func(m configSelectMocks) { m.workloadLister.EXPECT().ListServices(gomock.Eq(appName)).Return([]*config.Workload{}, nil) m.workloadLister.EXPECT().ListJobs(gomock.Eq(appName)).Return([]*config.Workload{}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, wantErr: fmt.Errorf("no workloads found in app myapp"), }, "with only one service (skips prompting)": { setupMocks: func(m configSelectMocks) { m.workloadLister.EXPECT().ListServices(gomock.Eq(appName)).Return([]*config.Workload{ { App: appName, Name: "service1", Type: "load balanced web service", }, }, nil) m.workloadLister.EXPECT().ListJobs(gomock.Eq(appName)).Return([]*config.Workload{}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0) }, want: "service1", }, "with multiple workloads": { setupMocks: func(m configSelectMocks) { m.workloadLister.EXPECT().ListServices(gomock.Eq(appName)).Return([]*config.Workload{ { App: appName, Name: "service1", Type: "load balanced web service", }, { App: appName, Name: "service2", Type: "backend service", }, }, nil) m.workloadLister.EXPECT().ListJobs(gomock.Eq(appName)).Return([]*config.Workload{ { App: appName, Name: "job1", Type: "scheduled job", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"service1", "service2", "job1"}), gomock.Any()).Return("service2", nil).Times(1) }, want: "service2", }, "with error selecting services": { setupMocks: func(m configSelectMocks) { m.workloadLister.EXPECT().ListServices(gomock.Eq(appName)).Return([]*config.Workload{ { App: appName, Name: "service1", Type: "load balanced web service", }, { App: appName, Name: "service2", Type: "backend service", }, }, nil) m.workloadLister.EXPECT().ListJobs(gomock.Eq(appName)).Return([]*config.Workload{ { App: appName, Name: "job1", Type: "scheduled job", }, }, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"service1", "service2", "job1"}), gomock.Any()).Return("", errors.New("some error")).Times(1) }, wantErr: fmt.Errorf("select workload: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockconfigLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := configSelectMocks{ workloadLister: mockconfigLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := ConfigSelector{ AppEnvSelector: &AppEnvSelector{ prompt: mockprompt, }, workloadLister: mockconfigLister, } got, err := sel.Workload("Select a service", "Help text", appName) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } type environmentMocks struct { envLister *mocks.MockconfigLister prompt *mocks.MockPrompter } func TestSelect_Environment(t *testing.T) { appName := "myapp" additionalOpt1, additionalOpt2 := "opt1", "opt2" testCases := map[string]struct { inAdditionalOpts []string setupMocks func(m environmentMocks) wantErr error want string }{ "with no environments": { setupMocks: func(m environmentMocks) { m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{}, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no environments found in app myapp"), }, "with only one environment (skips prompting)": { setupMocks: func(m environmentMocks) { m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{ { App: appName, Name: "env1", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "env1", }, "with multiple environments": { setupMocks: func(m environmentMocks) { m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{ { App: appName, Name: "env1", }, { App: appName, Name: "env2", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an environment"), gomock.Eq("Help text"), gomock.Eq([]string{"env1", "env2"}), gomock.Any()). Return("env2", nil). Times(1) }, want: "env2", }, "with error selecting environments": { setupMocks: func(m environmentMocks) { m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{ { App: appName, Name: "env1", }, { App: appName, Name: "env2", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"env1", "env2"}), gomock.Any()). Return("", fmt.Errorf("error selecting")). Times(1) }, wantErr: fmt.Errorf("select environment: error selecting"), }, "no environment but with one additional option": { inAdditionalOpts: []string{additionalOpt1}, setupMocks: func(m environmentMocks) { m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{}, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: additionalOpt1, }, "no environment but with multiple additional options": { inAdditionalOpts: []string{additionalOpt1, additionalOpt2}, setupMocks: func(m environmentMocks) { m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{}, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), []string{additionalOpt1, additionalOpt2}, gomock.Any()). Times(1). Return(additionalOpt2, nil) }, want: additionalOpt2, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockenvLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := environmentMocks{ envLister: mockenvLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := AppEnvSelector{ prompt: mockprompt, appEnvLister: mockenvLister, } got, err := sel.Environment("Select an environment", "Help text", appName, tc.inAdditionalOpts...) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } func TestSelect_Environments(t *testing.T) { appName := "myapp" hardcodedOpt := "[No additional environments]" testCases := map[string]struct { setupMocks func(m environmentMocks) wantErr error want []string }{ "with no environments": { setupMocks: func(m environmentMocks) { gomock.InOrder( m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{}, nil). Times(1), m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0), ) }, wantErr: fmt.Errorf("no environments found in app myapp"), }, "with one environment": { setupMocks: func(m environmentMocks) { gomock.InOrder( m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{ { App: appName, Name: "env1", }, }, nil). Times(1), m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"env1", hardcodedOpt}), gomock.Any()). Return("env1", nil). Times(1), ) }, want: []string{"env1"}, }, "with multiple environments (selection list reduces with each iteration, returns envs in order selected)": { setupMocks: func(m environmentMocks) { gomock.InOrder( m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{ { App: appName, Name: "env1", }, { App: appName, Name: "env2", }, { App: appName, Name: "env3", }, }, nil). Times(1), m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an environment"), gomock.Eq("Help text"), gomock.Eq([]string{"env1", "env2", "env3", hardcodedOpt}), gomock.Any()). Return("env2", nil). Times(1), m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an environment"), gomock.Eq("Help text"), gomock.Eq([]string{"env1", "env3", hardcodedOpt}), gomock.Any()). Return("env1", nil). Times(1), m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an environment"), gomock.Eq("Help text"), gomock.Eq([]string{"env3", hardcodedOpt}), gomock.Any()). Return("env3", nil). Times(1), ) }, want: []string{"env2", "env1", "env3"}, }, "stops prompting when user selects '[No additional environments]'; quit opt not in env list": { setupMocks: func(m environmentMocks) { gomock.InOrder( m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{ { App: appName, Name: "env1", }, { App: appName, Name: "env2", }, { App: appName, Name: "env3", }, }, nil). Times(1), m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an environment"), gomock.Eq("Help text"), gomock.Eq([]string{"env1", "env2", "env3", hardcodedOpt}), gomock.Any()). Return("env2", nil). Times(1), m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an environment"), gomock.Eq("Help text"), gomock.Eq([]string{"env1", "env3", hardcodedOpt}), gomock.Any()). Return("env1", nil). Times(1), m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an environment"), gomock.Eq("Help text"), gomock.Eq([]string{"env3", hardcodedOpt}), gomock.Any()). Return(hardcodedOpt, nil). Times(1), ) }, want: []string{"env2", "env1"}, }, "with error selecting environments": { setupMocks: func(m environmentMocks) { gomock.InOrder( m.envLister. EXPECT(). ListEnvironments(gomock.Eq(appName)). Return([]*config.Environment{ { App: appName, Name: "env1", }, { App: appName, Name: "env2", }, }, nil). Times(1), m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"env1", "env2", hardcodedOpt}), gomock.Any()). Return("", fmt.Errorf("error selecting")). Times(1), ) }, wantErr: fmt.Errorf("select environments: error selecting"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockenvLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := environmentMocks{ envLister: mockenvLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := AppEnvSelector{ prompt: mockprompt, appEnvLister: mockenvLister, } got, err := sel.Environments("Select an environment", "Help text", appName, func(order int) prompt.PromptConfig { return prompt.WithFinalMessage(fmt.Sprintf("%s stage:", humanize.Ordinal(order))) }) if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } type applicationMocks struct { appLister *mocks.MockconfigLister prompt *mocks.MockPrompter } func TestSelect_Application(t *testing.T) { testCases := map[string]struct { setupMocks func(m applicationMocks) wantErr error want string }{ "with no apps": { setupMocks: func(m applicationMocks) { m.appLister. EXPECT(). ListApplications(). Return([]*config.Application{}, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantErr: fmt.Errorf("no apps found"), }, "with only one app (skips prompting)": { setupMocks: func(m applicationMocks) { m.appLister. EXPECT(). ListApplications(). Return([]*config.Application{ { Name: "app1", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, want: "app1", }, "with multiple apps": { setupMocks: func(m applicationMocks) { m.appLister. EXPECT(). ListApplications(). Return([]*config.Application{ { Name: "app1", }, { Name: "app2", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne( gomock.Eq("Select an app"), gomock.Eq("Help text"), gomock.Eq([]string{"app1", "app2"}), gomock.Any()). Return("app2", nil). Times(1) }, want: "app2", }, "with error selecting apps": { setupMocks: func(m applicationMocks) { m.appLister. EXPECT(). ListApplications(). Return([]*config.Application{ { Name: "app1", }, { Name: "app2", }, }, nil). Times(1) m.prompt. EXPECT(). SelectOne(gomock.Any(), gomock.Any(), gomock.Eq([]string{"app1", "app2"}), gomock.Any()). Return("", fmt.Errorf("error selecting")). Times(1) }, wantErr: fmt.Errorf("select application: error selecting"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockappLister := mocks.NewMockconfigLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := applicationMocks{ appLister: mockappLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := AppEnvSelector{ prompt: mockprompt, appEnvLister: mockappLister, } got, err := sel.Application("Select an app", "Help text") if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.Equal(t, tc.want, got) } }) } } type wsPipelineSelectMocks struct { prompt *mocks.MockPrompter ws *mocks.MockwsPipelinesLister } func TestWorkspaceSelect_WsPipeline(t *testing.T) { mockPipelineManifests := []workspace.PipelineManifest{ { Name: "betaManifest", Path: "/copilot/pipelines/beta/manifest.yml", }, { Name: "legacyInCopiDir", Path: "/copilot/pipeline.yml", }, { Name: "prodManifest", Path: "/copilot/pipelines/prod/manifest.yml", }, } singlePipelineManifest := &workspace.PipelineManifest{ Name: "betaManifest", Path: "/copilot/pipelines/beta/manifest.yml", } testCases := map[string]struct { setupMocks func(mocks wsPipelineSelectMocks) wantedErr error wantedPipeline *workspace.PipelineManifest }{ "with no workspace pipelines": { setupMocks: func(m wsPipelineSelectMocks) { m.ws.EXPECT().ListPipelines().Return(nil, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantedErr: fmt.Errorf("no pipelines found"), }, "don't prompt to select if only one workspace pipeline": { setupMocks: func(m wsPipelineSelectMocks) { m.ws.EXPECT().ListPipelines().Return([]workspace.PipelineManifest{ { Name: "betaManifest", Path: "/copilot/pipelines/beta/manifest.yml", }}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantedPipeline: &workspace.PipelineManifest{ Name: "betaManifest", Path: "/copilot/pipelines/beta/manifest.yml", }, }, "with multiple workspace pipelines": { setupMocks: func(m wsPipelineSelectMocks) { m.ws.EXPECT().ListPipelines().Return(mockPipelineManifests, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("betaManifest", nil) }, wantedPipeline: singlePipelineManifest, }, "with error selecting": { setupMocks: func(m wsPipelineSelectMocks) { m.ws.EXPECT().ListPipelines().Return(mockPipelineManifests, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("", errors.New("some error")) }, wantedErr: errors.New("select pipeline: some error"), }, "wrap error from ListPipelines": { setupMocks: func(m wsPipelineSelectMocks) { m.ws.EXPECT().ListPipelines().Return(nil, errors.New("some error")) }, wantedErr: errors.New("list pipelines: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockwsPipelinesLister := mocks.NewMockwsPipelinesLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := wsPipelineSelectMocks{ prompt: mockprompt, ws: mockwsPipelinesLister, } tc.setupMocks(mocks) sel := WsPipelineSelector{ prompt: mockprompt, ws: mockwsPipelinesLister, } got, err := sel.WsPipeline("Select a pipeline", "Help text") if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.Equal(t, tc.wantedPipeline, got) } }) } } type codePipelineSelectMocks struct { prompt *mocks.MockPrompter cp *mocks.MockcodePipelineLister } func TestCodePipelineSelect_DeployedPipeline(t *testing.T) { const ( mockAppName = "coolapp" mockPipelineResourceName = "pipeline-coolapp-my-pipeline-repo-ABCDERANDOMRANDOM" mockPipelineName = "my-pipeline-repo" mockLegacyPipelineName = "bad-goose" mockLegacyPipelineResourceName = mockLegacyPipelineName // legacy pipeline's resource name is the same as the pipeline name ) mockPipeline := deploy.Pipeline{ AppName: mockAppName, ResourceName: mockPipelineResourceName, Name: mockPipelineName, IsLegacy: false, } mockLegacyPipeline := deploy.Pipeline{ AppName: mockAppName, ResourceName: mockLegacyPipelineResourceName, Name: mockLegacyPipelineName, IsLegacy: true, } testCases := map[string]struct { setupMocks func(mocks codePipelineSelectMocks) wantedErr error wantedPipeline deploy.Pipeline }{ "with no workspace pipelines": { setupMocks: func(m codePipelineSelectMocks) { m.cp.EXPECT().ListDeployedPipelines(mockAppName).Return([]deploy.Pipeline{}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantedErr: fmt.Errorf("no deployed pipelines found"), }, "don't prompt to select if only one workspace pipeline": { setupMocks: func(m codePipelineSelectMocks) { m.cp.EXPECT().ListDeployedPipelines(mockAppName).Return([]deploy.Pipeline{mockPipeline}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Times(0) }, wantedPipeline: mockPipeline, }, "with multiple workspace pipelines": { setupMocks: func(m codePipelineSelectMocks) { m.cp.EXPECT().ListDeployedPipelines(mockAppName).Return([]deploy.Pipeline{mockPipeline, mockLegacyPipeline}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("bad-goose", nil) }, wantedPipeline: mockLegacyPipeline, }, "with error selecting": { setupMocks: func(m codePipelineSelectMocks) { m.cp.EXPECT().ListDeployedPipelines(mockAppName).Return([]deploy.Pipeline{mockPipeline, mockLegacyPipeline}, nil) m.prompt.EXPECT().SelectOne(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("", errors.New("some error")) }, wantedErr: errors.New("select pipeline: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockCodePipelinesLister := mocks.NewMockcodePipelineLister(ctrl) mockPrompt := mocks.NewMockPrompter(ctrl) mocks := codePipelineSelectMocks{ prompt: mockPrompt, cp: mockCodePipelinesLister, } tc.setupMocks(mocks) sel := CodePipelineSelector{ prompt: mockPrompt, pipelineLister: mockCodePipelinesLister, } got, err := sel.DeployedPipeline("Select a pipeline", "Help text", mockAppName) if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.Equal(t, tc.wantedPipeline, got) } }) } } func TestSelect_CFTask(t *testing.T) { taskPrompt := "TASK PLX" taskHelp := "NO" testTasks := []string{"abc", "db-migrate"} testDefaultTask := "db-migrate" testCases := map[string]struct { inDefaultCluster string inOpts []GetDeployedTaskOpts mockStore func(*mocks.MockconfigLister) mockPrompt func(*mocks.MockPrompter) mockCF func(*mocks.MocktaskStackDescriber) wantedErr error wantedTask string }{ "choose an existing task": { inOpts: []GetDeployedTaskOpts{ TaskWithAppEnv("phonetool", "prod-iad"), }, mockStore: func(m *mocks.MockconfigLister) {}, mockCF: func(m *mocks.MocktaskStackDescriber) { m.EXPECT().ListTaskStacks("phonetool", "prod-iad").Return([]deploy.TaskStackInfo{ { StackName: "copilot-abc", App: "phonetool", Env: "prod-iad", }, { StackName: "copilot-db-migrate", App: "phonetool", Env: "prod-iad", }, }, nil) }, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().SelectOne( gomock.Any(), gomock.Any(), []string{ "abc", "db-migrate", }, gomock.Any(), ).Return("abc", nil) }, wantedErr: nil, wantedTask: testTasks[0], }, "error when retrieving stacks": { inOpts: []GetDeployedTaskOpts{ TaskWithAppEnv("phonetool", "prod-iad"), }, mockStore: func(m *mocks.MockconfigLister) {}, mockCF: func(m *mocks.MocktaskStackDescriber) { m.EXPECT().ListTaskStacks("phonetool", "prod-iad").Return(nil, errors.New("some error")) }, mockPrompt: func(m *mocks.MockPrompter) {}, wantedErr: errors.New("get tasks in environment prod-iad: some error"), }, "with default cluster task": { inOpts: []GetDeployedTaskOpts{ TaskWithDefaultCluster(), }, mockStore: func(m *mocks.MockconfigLister) {}, mockCF: func(m *mocks.MocktaskStackDescriber) { m.EXPECT().ListDefaultTaskStacks().Return([]deploy.TaskStackInfo{ { StackName: "task-oneoff", }, { StackName: "copilot-db-migrate", }, }, nil) }, mockPrompt: func(m *mocks.MockPrompter) { m.EXPECT().SelectOne( gomock.Any(), gomock.Any(), []string{ "oneoff", "db-migrate", }, gomock.Any(), ).Return("db-migrate", nil) }, wantedErr: nil, wantedTask: testDefaultTask, }, "with error getting default cluster tasks": { inOpts: []GetDeployedTaskOpts{ TaskWithDefaultCluster(), }, mockStore: func(m *mocks.MockconfigLister) {}, mockCF: func(m *mocks.MocktaskStackDescriber) { m.EXPECT().ListDefaultTaskStacks().Return(nil, errors.New("some error")) }, mockPrompt: func(m *mocks.MockPrompter) {}, wantedErr: errors.New("get tasks in default cluster: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN ctrl := gomock.NewController(t) defer ctrl.Finish() p := mocks.NewMockPrompter(ctrl) s := mocks.NewMockconfigLister(ctrl) cf := mocks.NewMocktaskStackDescriber(ctrl) tc.mockPrompt(p) tc.mockCF(cf) tc.mockStore(s) sel := CFTaskSelector{ AppEnvSelector: &AppEnvSelector{ prompt: p, appEnvLister: s, }, cfStore: cf, } // WHEN choice, err := sel.Task(taskPrompt, taskHelp, tc.inOpts...) // THEN if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.Equal(t, tc.wantedTask, choice) } }) } } type taskSelectMocks struct { taskLister *mocks.MocktaskLister prompt *mocks.MockPrompter } func TestTaskSelect_Task(t *testing.T) { const ( mockApp = "mockApp" mockEnv = "mockEnv" mockPromptText = "Select a running task" mockHelpText = "Help text" ) mockTask1 := &awsecs.Task{ TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/4082490ee6c245e09d2145010aa1ba8d"), TaskDefinitionArn: aws.String("arn:aws:ecs:us-west-2:123456789:task-definition/sample-fargate:2"), } mockTask2 := &awsecs.Task{ TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/0aa1ba8d4082490ee6c245e09d214501"), TaskDefinitionArn: aws.String("arn:aws:ecs:us-west-2:123456789:task-definition/sample-fargate:3"), } mockErr := errors.New("some error") testCases := map[string]struct { setupMocks func(mocks taskSelectMocks) app string env string useDefault bool wantErr error wantTask *awsecs.Task }{ "return error if fail to list active cluster tasks": { useDefault: true, setupMocks: func(m taskSelectMocks) { m.taskLister.EXPECT().ListActiveDefaultClusterTasks(ecs.ListTasksFilter{CopilotOnly: true}).Return(nil, mockErr) }, wantErr: fmt.Errorf("list active tasks for default cluster: some error"), }, "return error if fail to list active app env tasks": { app: mockApp, env: mockEnv, setupMocks: func(m taskSelectMocks) { m.taskLister.EXPECT().ListActiveAppEnvTasks(ecs.ListActiveAppEnvTasksOpts{ App: mockApp, Env: mockEnv, ListTasksFilter: ecs.ListTasksFilter{ CopilotOnly: true, }, }).Return(nil, mockErr) }, wantErr: fmt.Errorf("list active tasks in environment mockEnv: some error"), }, "return error if no running tasks found": { app: mockApp, env: mockEnv, setupMocks: func(m taskSelectMocks) { m.taskLister.EXPECT().ListActiveAppEnvTasks(ecs.ListActiveAppEnvTasksOpts{ App: mockApp, Env: mockEnv, ListTasksFilter: ecs.ListTasksFilter{ CopilotOnly: true, }, }).Return([]*awsecs.Task{}, nil) }, wantErr: fmt.Errorf("no running tasks found"), }, "return error if fail to select a task": { app: mockApp, env: mockEnv, setupMocks: func(m taskSelectMocks) { m.taskLister.EXPECT().ListActiveAppEnvTasks(ecs.ListActiveAppEnvTasksOpts{ App: mockApp, Env: mockEnv, ListTasksFilter: ecs.ListTasksFilter{ CopilotOnly: true, }, }).Return([]*awsecs.Task{mockTask1, mockTask2}, nil) m.prompt.EXPECT().SelectOne(mockPromptText, mockHelpText, []string{ "4082490e (sample-fargate:2)", "0aa1ba8d (sample-fargate:3)", }, gomock.Any()).Return("", mockErr) }, wantErr: fmt.Errorf("select running task: some error"), }, "success with one running task": { app: mockApp, env: mockEnv, setupMocks: func(m taskSelectMocks) { m.taskLister.EXPECT().ListActiveAppEnvTasks(ecs.ListActiveAppEnvTasksOpts{ App: mockApp, Env: mockEnv, ListTasksFilter: ecs.ListTasksFilter{ CopilotOnly: true, }, }).Return([]*awsecs.Task{mockTask1}, nil) }, wantTask: mockTask1, }, "success": { app: mockApp, env: mockEnv, setupMocks: func(m taskSelectMocks) { m.taskLister.EXPECT().ListActiveAppEnvTasks(ecs.ListActiveAppEnvTasksOpts{ App: mockApp, Env: mockEnv, ListTasksFilter: ecs.ListTasksFilter{ CopilotOnly: true, }, }).Return([]*awsecs.Task{mockTask1, mockTask2}, nil) m.prompt.EXPECT().SelectOne(mockPromptText, mockHelpText, []string{ "4082490e (sample-fargate:2)", "0aa1ba8d (sample-fargate:3)", }, gomock.Any()).Return("0aa1ba8d (sample-fargate:3)", nil) }, wantTask: mockTask2, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mocktaskLister := mocks.NewMocktaskLister(ctrl) mockprompt := mocks.NewMockPrompter(ctrl) mocks := taskSelectMocks{ taskLister: mocktaskLister, prompt: mockprompt, } tc.setupMocks(mocks) sel := TaskSelector{ lister: mocktaskLister, prompt: mockprompt, } var gotTask *awsecs.Task var err error if tc.useDefault { gotTask, err = sel.RunningTask(mockPromptText, mockHelpText, WithAppEnv(tc.app, tc.env), WithDefault()) } else { gotTask, err = sel.RunningTask(mockPromptText, mockHelpText, WithAppEnv(tc.app, tc.env)) } if tc.wantErr != nil { require.EqualError(t, err, tc.wantErr.Error()) } else { require.NoError(t, tc.wantErr) require.Equal(t, tc.wantTask, gotTask) } }) } }
2,980
copilot-cli
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: ./internal/pkg/term/selector/creds.go // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" session "github.com/aws/aws-sdk-go/aws/session" gomock "github.com/golang/mock/gomock" ) // MockNames is a mock of Names interface. type MockNames struct { ctrl *gomock.Controller recorder *MockNamesMockRecorder } // MockNamesMockRecorder is the mock recorder for MockNames. type MockNamesMockRecorder struct { mock *MockNames } // NewMockNames creates a new mock instance. func NewMockNames(ctrl *gomock.Controller) *MockNames { mock := &MockNames{ctrl: ctrl} mock.recorder = &MockNamesMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockNames) EXPECT() *MockNamesMockRecorder { return m.recorder } // Names mocks base method. func (m *MockNames) Names() []string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Names") ret0, _ := ret[0].([]string) return ret0 } // Names indicates an expected call of Names. func (mr *MockNamesMockRecorder) Names() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Names", reflect.TypeOf((*MockNames)(nil).Names)) } // MockSessionProvider is a mock of SessionProvider interface. type MockSessionProvider struct { ctrl *gomock.Controller recorder *MockSessionProviderMockRecorder } // MockSessionProviderMockRecorder is the mock recorder for MockSessionProvider. type MockSessionProviderMockRecorder struct { mock *MockSessionProvider } // NewMockSessionProvider creates a new mock instance. func NewMockSessionProvider(ctrl *gomock.Controller) *MockSessionProvider { mock := &MockSessionProvider{ctrl: ctrl} mock.recorder = &MockSessionProviderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSessionProvider) EXPECT() *MockSessionProviderMockRecorder { return m.recorder } // Default mocks base method. func (m *MockSessionProvider) Default() (*session.Session, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Default") ret0, _ := ret[0].(*session.Session) ret1, _ := ret[1].(error) return ret0, ret1 } // Default indicates an expected call of Default. func (mr *MockSessionProviderMockRecorder) Default() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Default", reflect.TypeOf((*MockSessionProvider)(nil).Default)) } // FromProfile mocks base method. func (m *MockSessionProvider) FromProfile(name string) (*session.Session, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FromProfile", name) ret0, _ := ret[0].(*session.Session) ret1, _ := ret[1].(error) return ret0, ret1 } // FromProfile indicates an expected call of FromProfile. func (mr *MockSessionProviderMockRecorder) FromProfile(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FromProfile", reflect.TypeOf((*MockSessionProvider)(nil).FromProfile), name) } // FromStaticCreds mocks base method. func (m *MockSessionProvider) FromStaticCreds(accessKeyID, secretAccessKey, sessionToken string) (*session.Session, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FromStaticCreds", accessKeyID, secretAccessKey, sessionToken) ret0, _ := ret[0].(*session.Session) ret1, _ := ret[1].(error) return ret0, ret1 } // FromStaticCreds indicates an expected call of FromStaticCreds. func (mr *MockSessionProviderMockRecorder) FromStaticCreds(accessKeyID, secretAccessKey, sessionToken interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FromStaticCreds", reflect.TypeOf((*MockSessionProvider)(nil).FromStaticCreds), accessKeyID, secretAccessKey, sessionToken) }
118
copilot-cli
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: ./internal/pkg/term/selector/ec2.go // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" ec2 "github.com/aws/copilot-cli/internal/pkg/aws/ec2" gomock "github.com/golang/mock/gomock" ) // MockVPCSubnetLister is a mock of VPCSubnetLister interface. type MockVPCSubnetLister struct { ctrl *gomock.Controller recorder *MockVPCSubnetListerMockRecorder } // MockVPCSubnetListerMockRecorder is the mock recorder for MockVPCSubnetLister. type MockVPCSubnetListerMockRecorder struct { mock *MockVPCSubnetLister } // NewMockVPCSubnetLister creates a new mock instance. func NewMockVPCSubnetLister(ctrl *gomock.Controller) *MockVPCSubnetLister { mock := &MockVPCSubnetLister{ctrl: ctrl} mock.recorder = &MockVPCSubnetListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockVPCSubnetLister) EXPECT() *MockVPCSubnetListerMockRecorder { return m.recorder } // ListVPCSubnets mocks base method. func (m *MockVPCSubnetLister) ListVPCSubnets(vpcID string) (*ec2.VPCSubnets, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListVPCSubnets", vpcID) ret0, _ := ret[0].(*ec2.VPCSubnets) ret1, _ := ret[1].(error) return ret0, ret1 } // ListVPCSubnets indicates an expected call of ListVPCSubnets. func (mr *MockVPCSubnetListerMockRecorder) ListVPCSubnets(vpcID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListVPCSubnets", reflect.TypeOf((*MockVPCSubnetLister)(nil).ListVPCSubnets), vpcID) } // ListVPCs mocks base method. func (m *MockVPCSubnetLister) ListVPCs() ([]ec2.VPC, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListVPCs") ret0, _ := ret[0].([]ec2.VPC) ret1, _ := ret[1].(error) return ret0, ret1 } // ListVPCs indicates an expected call of ListVPCs. func (mr *MockVPCSubnetListerMockRecorder) ListVPCs() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListVPCs", reflect.TypeOf((*MockVPCSubnetLister)(nil).ListVPCs)) }
66
copilot-cli
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: ./internal/pkg/term/selector/selector.go // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" ecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs" config "github.com/aws/copilot-cli/internal/pkg/config" deploy "github.com/aws/copilot-cli/internal/pkg/deploy" ecs0 "github.com/aws/copilot-cli/internal/pkg/ecs" prompt "github.com/aws/copilot-cli/internal/pkg/term/prompt" workspace "github.com/aws/copilot-cli/internal/pkg/workspace" gomock "github.com/golang/mock/gomock" ) // MockPrompter is a mock of Prompter interface. type MockPrompter struct { ctrl *gomock.Controller recorder *MockPrompterMockRecorder } // MockPrompterMockRecorder is the mock recorder for MockPrompter. type MockPrompterMockRecorder struct { mock *MockPrompter } // NewMockPrompter creates a new mock instance. func NewMockPrompter(ctrl *gomock.Controller) *MockPrompter { mock := &MockPrompter{ctrl: ctrl} mock.recorder = &MockPrompterMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockPrompter) EXPECT() *MockPrompterMockRecorder { return m.recorder } // Confirm mocks base method. func (m *MockPrompter) Confirm(message, help string, promptOpts ...prompt.PromptConfig) (bool, error) { m.ctrl.T.Helper() varargs := []interface{}{message, help} for _, a := range promptOpts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Confirm", varargs...) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // Confirm indicates an expected call of Confirm. func (mr *MockPrompterMockRecorder) Confirm(message, help interface{}, promptOpts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{message, help}, promptOpts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Confirm", reflect.TypeOf((*MockPrompter)(nil).Confirm), varargs...) } // Get mocks base method. func (m *MockPrompter) Get(message, help string, validator prompt.ValidatorFunc, promptOpts ...prompt.PromptConfig) (string, error) { m.ctrl.T.Helper() varargs := []interface{}{message, help, validator} for _, a := range promptOpts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Get", varargs...) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // Get indicates an expected call of Get. func (mr *MockPrompterMockRecorder) Get(message, help, validator interface{}, promptOpts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{message, help, validator}, promptOpts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockPrompter)(nil).Get), varargs...) } // MultiSelect mocks base method. func (m *MockPrompter) MultiSelect(message, help string, options []string, validator prompt.ValidatorFunc, promptOpts ...prompt.PromptConfig) ([]string, error) { m.ctrl.T.Helper() varargs := []interface{}{message, help, options, validator} for _, a := range promptOpts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "MultiSelect", varargs...) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // MultiSelect indicates an expected call of MultiSelect. func (mr *MockPrompterMockRecorder) MultiSelect(message, help, options, validator interface{}, promptOpts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{message, help, options, validator}, promptOpts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MultiSelect", reflect.TypeOf((*MockPrompter)(nil).MultiSelect), varargs...) } // MultiSelectOptions mocks base method. func (m *MockPrompter) MultiSelectOptions(message, help string, opts []prompt.Option, promptCfgs ...prompt.PromptConfig) ([]string, error) { m.ctrl.T.Helper() varargs := []interface{}{message, help, opts} for _, a := range promptCfgs { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "MultiSelectOptions", varargs...) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // MultiSelectOptions indicates an expected call of MultiSelectOptions. func (mr *MockPrompterMockRecorder) MultiSelectOptions(message, help, opts interface{}, promptCfgs ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{message, help, opts}, promptCfgs...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MultiSelectOptions", reflect.TypeOf((*MockPrompter)(nil).MultiSelectOptions), varargs...) } // SelectOne mocks base method. func (m *MockPrompter) SelectOne(message, help string, options []string, promptOpts ...prompt.PromptConfig) (string, error) { m.ctrl.T.Helper() varargs := []interface{}{message, help, options} for _, a := range promptOpts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "SelectOne", varargs...) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // SelectOne indicates an expected call of SelectOne. func (mr *MockPrompterMockRecorder) SelectOne(message, help, options interface{}, promptOpts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{message, help, options}, promptOpts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SelectOne", reflect.TypeOf((*MockPrompter)(nil).SelectOne), varargs...) } // SelectOption mocks base method. func (m *MockPrompter) SelectOption(message, help string, opts []prompt.Option, promptCfgs ...prompt.PromptConfig) (string, error) { m.ctrl.T.Helper() varargs := []interface{}{message, help, opts} for _, a := range promptCfgs { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "SelectOption", varargs...) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // SelectOption indicates an expected call of SelectOption. func (mr *MockPrompterMockRecorder) SelectOption(message, help, opts interface{}, promptCfgs ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{message, help, opts}, promptCfgs...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SelectOption", reflect.TypeOf((*MockPrompter)(nil).SelectOption), varargs...) } // MockappEnvLister is a mock of appEnvLister interface. type MockappEnvLister struct { ctrl *gomock.Controller recorder *MockappEnvListerMockRecorder } // MockappEnvListerMockRecorder is the mock recorder for MockappEnvLister. type MockappEnvListerMockRecorder struct { mock *MockappEnvLister } // NewMockappEnvLister creates a new mock instance. func NewMockappEnvLister(ctrl *gomock.Controller) *MockappEnvLister { mock := &MockappEnvLister{ctrl: ctrl} mock.recorder = &MockappEnvListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockappEnvLister) EXPECT() *MockappEnvListerMockRecorder { return m.recorder } // ListApplications mocks base method. func (m *MockappEnvLister) ListApplications() ([]*config.Application, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListApplications") ret0, _ := ret[0].([]*config.Application) ret1, _ := ret[1].(error) return ret0, ret1 } // ListApplications indicates an expected call of ListApplications. func (mr *MockappEnvListerMockRecorder) ListApplications() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListApplications", reflect.TypeOf((*MockappEnvLister)(nil).ListApplications)) } // ListEnvironments mocks base method. func (m *MockappEnvLister) ListEnvironments(appName string) ([]*config.Environment, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListEnvironments", appName) ret0, _ := ret[0].([]*config.Environment) ret1, _ := ret[1].(error) return ret0, ret1 } // ListEnvironments indicates an expected call of ListEnvironments. func (mr *MockappEnvListerMockRecorder) ListEnvironments(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListEnvironments", reflect.TypeOf((*MockappEnvLister)(nil).ListEnvironments), appName) } // MockconfigWorkloadLister is a mock of configWorkloadLister interface. type MockconfigWorkloadLister struct { ctrl *gomock.Controller recorder *MockconfigWorkloadListerMockRecorder } // MockconfigWorkloadListerMockRecorder is the mock recorder for MockconfigWorkloadLister. type MockconfigWorkloadListerMockRecorder struct { mock *MockconfigWorkloadLister } // NewMockconfigWorkloadLister creates a new mock instance. func NewMockconfigWorkloadLister(ctrl *gomock.Controller) *MockconfigWorkloadLister { mock := &MockconfigWorkloadLister{ctrl: ctrl} mock.recorder = &MockconfigWorkloadListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockconfigWorkloadLister) EXPECT() *MockconfigWorkloadListerMockRecorder { return m.recorder } // ListJobs mocks base method. func (m *MockconfigWorkloadLister) ListJobs(appName string) ([]*config.Workload, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListJobs", appName) ret0, _ := ret[0].([]*config.Workload) ret1, _ := ret[1].(error) return ret0, ret1 } // ListJobs indicates an expected call of ListJobs. func (mr *MockconfigWorkloadListerMockRecorder) ListJobs(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListJobs", reflect.TypeOf((*MockconfigWorkloadLister)(nil).ListJobs), appName) } // ListServices mocks base method. func (m *MockconfigWorkloadLister) ListServices(appName string) ([]*config.Workload, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListServices", appName) ret0, _ := ret[0].([]*config.Workload) ret1, _ := ret[1].(error) return ret0, ret1 } // ListServices indicates an expected call of ListServices. func (mr *MockconfigWorkloadListerMockRecorder) ListServices(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockconfigWorkloadLister)(nil).ListServices), appName) } // ListWorkloads mocks base method. func (m *MockconfigWorkloadLister) ListWorkloads(appName string) ([]*config.Workload, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListWorkloads", appName) ret0, _ := ret[0].([]*config.Workload) ret1, _ := ret[1].(error) return ret0, ret1 } // ListWorkloads indicates an expected call of ListWorkloads. func (mr *MockconfigWorkloadListerMockRecorder) ListWorkloads(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWorkloads", reflect.TypeOf((*MockconfigWorkloadLister)(nil).ListWorkloads), appName) } // MockconfigLister is a mock of configLister interface. type MockconfigLister struct { ctrl *gomock.Controller recorder *MockconfigListerMockRecorder } // MockconfigListerMockRecorder is the mock recorder for MockconfigLister. type MockconfigListerMockRecorder struct { mock *MockconfigLister } // NewMockconfigLister creates a new mock instance. func NewMockconfigLister(ctrl *gomock.Controller) *MockconfigLister { mock := &MockconfigLister{ctrl: ctrl} mock.recorder = &MockconfigListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockconfigLister) EXPECT() *MockconfigListerMockRecorder { return m.recorder } // ListApplications mocks base method. func (m *MockconfigLister) ListApplications() ([]*config.Application, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListApplications") ret0, _ := ret[0].([]*config.Application) ret1, _ := ret[1].(error) return ret0, ret1 } // ListApplications indicates an expected call of ListApplications. func (mr *MockconfigListerMockRecorder) ListApplications() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListApplications", reflect.TypeOf((*MockconfigLister)(nil).ListApplications)) } // ListEnvironments mocks base method. func (m *MockconfigLister) ListEnvironments(appName string) ([]*config.Environment, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListEnvironments", appName) ret0, _ := ret[0].([]*config.Environment) ret1, _ := ret[1].(error) return ret0, ret1 } // ListEnvironments indicates an expected call of ListEnvironments. func (mr *MockconfigListerMockRecorder) ListEnvironments(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListEnvironments", reflect.TypeOf((*MockconfigLister)(nil).ListEnvironments), appName) } // ListJobs mocks base method. func (m *MockconfigLister) ListJobs(appName string) ([]*config.Workload, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListJobs", appName) ret0, _ := ret[0].([]*config.Workload) ret1, _ := ret[1].(error) return ret0, ret1 } // ListJobs indicates an expected call of ListJobs. func (mr *MockconfigListerMockRecorder) ListJobs(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListJobs", reflect.TypeOf((*MockconfigLister)(nil).ListJobs), appName) } // ListServices mocks base method. func (m *MockconfigLister) ListServices(appName string) ([]*config.Workload, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListServices", appName) ret0, _ := ret[0].([]*config.Workload) ret1, _ := ret[1].(error) return ret0, ret1 } // ListServices indicates an expected call of ListServices. func (mr *MockconfigListerMockRecorder) ListServices(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockconfigLister)(nil).ListServices), appName) } // ListWorkloads mocks base method. func (m *MockconfigLister) ListWorkloads(appName string) ([]*config.Workload, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListWorkloads", appName) ret0, _ := ret[0].([]*config.Workload) ret1, _ := ret[1].(error) return ret0, ret1 } // ListWorkloads indicates an expected call of ListWorkloads. func (mr *MockconfigListerMockRecorder) ListWorkloads(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWorkloads", reflect.TypeOf((*MockconfigLister)(nil).ListWorkloads), appName) } // MockwsWorkloadLister is a mock of wsWorkloadLister interface. type MockwsWorkloadLister struct { ctrl *gomock.Controller recorder *MockwsWorkloadListerMockRecorder } // MockwsWorkloadListerMockRecorder is the mock recorder for MockwsWorkloadLister. type MockwsWorkloadListerMockRecorder struct { mock *MockwsWorkloadLister } // NewMockwsWorkloadLister creates a new mock instance. func NewMockwsWorkloadLister(ctrl *gomock.Controller) *MockwsWorkloadLister { mock := &MockwsWorkloadLister{ctrl: ctrl} mock.recorder = &MockwsWorkloadListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockwsWorkloadLister) EXPECT() *MockwsWorkloadListerMockRecorder { return m.recorder } // ListJobs mocks base method. func (m *MockwsWorkloadLister) ListJobs() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListJobs") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListJobs indicates an expected call of ListJobs. func (mr *MockwsWorkloadListerMockRecorder) ListJobs() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListJobs", reflect.TypeOf((*MockwsWorkloadLister)(nil).ListJobs)) } // ListServices mocks base method. func (m *MockwsWorkloadLister) ListServices() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListServices") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListServices indicates an expected call of ListServices. func (mr *MockwsWorkloadListerMockRecorder) ListServices() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockwsWorkloadLister)(nil).ListServices)) } // ListWorkloads mocks base method. func (m *MockwsWorkloadLister) ListWorkloads() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListWorkloads") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListWorkloads indicates an expected call of ListWorkloads. func (mr *MockwsWorkloadListerMockRecorder) ListWorkloads() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWorkloads", reflect.TypeOf((*MockwsWorkloadLister)(nil).ListWorkloads)) } // MockwsEnvironmentsLister is a mock of wsEnvironmentsLister interface. type MockwsEnvironmentsLister struct { ctrl *gomock.Controller recorder *MockwsEnvironmentsListerMockRecorder } // MockwsEnvironmentsListerMockRecorder is the mock recorder for MockwsEnvironmentsLister. type MockwsEnvironmentsListerMockRecorder struct { mock *MockwsEnvironmentsLister } // NewMockwsEnvironmentsLister creates a new mock instance. func NewMockwsEnvironmentsLister(ctrl *gomock.Controller) *MockwsEnvironmentsLister { mock := &MockwsEnvironmentsLister{ctrl: ctrl} mock.recorder = &MockwsEnvironmentsListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockwsEnvironmentsLister) EXPECT() *MockwsEnvironmentsListerMockRecorder { return m.recorder } // ListEnvironments mocks base method. func (m *MockwsEnvironmentsLister) ListEnvironments() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListEnvironments") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListEnvironments indicates an expected call of ListEnvironments. func (mr *MockwsEnvironmentsListerMockRecorder) ListEnvironments() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListEnvironments", reflect.TypeOf((*MockwsEnvironmentsLister)(nil).ListEnvironments)) } // MockwsPipelinesLister is a mock of wsPipelinesLister interface. type MockwsPipelinesLister struct { ctrl *gomock.Controller recorder *MockwsPipelinesListerMockRecorder } // MockwsPipelinesListerMockRecorder is the mock recorder for MockwsPipelinesLister. type MockwsPipelinesListerMockRecorder struct { mock *MockwsPipelinesLister } // NewMockwsPipelinesLister creates a new mock instance. func NewMockwsPipelinesLister(ctrl *gomock.Controller) *MockwsPipelinesLister { mock := &MockwsPipelinesLister{ctrl: ctrl} mock.recorder = &MockwsPipelinesListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockwsPipelinesLister) EXPECT() *MockwsPipelinesListerMockRecorder { return m.recorder } // ListPipelines mocks base method. func (m *MockwsPipelinesLister) ListPipelines() ([]workspace.PipelineManifest, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListPipelines") ret0, _ := ret[0].([]workspace.PipelineManifest) ret1, _ := ret[1].(error) return ret0, ret1 } // ListPipelines indicates an expected call of ListPipelines. func (mr *MockwsPipelinesListerMockRecorder) ListPipelines() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListPipelines", reflect.TypeOf((*MockwsPipelinesLister)(nil).ListPipelines)) } // MockcodePipelineLister is a mock of codePipelineLister interface. type MockcodePipelineLister struct { ctrl *gomock.Controller recorder *MockcodePipelineListerMockRecorder } // MockcodePipelineListerMockRecorder is the mock recorder for MockcodePipelineLister. type MockcodePipelineListerMockRecorder struct { mock *MockcodePipelineLister } // NewMockcodePipelineLister creates a new mock instance. func NewMockcodePipelineLister(ctrl *gomock.Controller) *MockcodePipelineLister { mock := &MockcodePipelineLister{ctrl: ctrl} mock.recorder = &MockcodePipelineListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockcodePipelineLister) EXPECT() *MockcodePipelineListerMockRecorder { return m.recorder } // ListDeployedPipelines mocks base method. func (m *MockcodePipelineLister) ListDeployedPipelines(appName string) ([]deploy.Pipeline, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListDeployedPipelines", appName) ret0, _ := ret[0].([]deploy.Pipeline) ret1, _ := ret[1].(error) return ret0, ret1 } // ListDeployedPipelines indicates an expected call of ListDeployedPipelines. func (mr *MockcodePipelineListerMockRecorder) ListDeployedPipelines(appName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeployedPipelines", reflect.TypeOf((*MockcodePipelineLister)(nil).ListDeployedPipelines), appName) } // MockworkspaceRetriever is a mock of workspaceRetriever interface. type MockworkspaceRetriever struct { ctrl *gomock.Controller recorder *MockworkspaceRetrieverMockRecorder } // MockworkspaceRetrieverMockRecorder is the mock recorder for MockworkspaceRetriever. type MockworkspaceRetrieverMockRecorder struct { mock *MockworkspaceRetriever } // NewMockworkspaceRetriever creates a new mock instance. func NewMockworkspaceRetriever(ctrl *gomock.Controller) *MockworkspaceRetriever { mock := &MockworkspaceRetriever{ctrl: ctrl} mock.recorder = &MockworkspaceRetrieverMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockworkspaceRetriever) EXPECT() *MockworkspaceRetrieverMockRecorder { return m.recorder } // ListEnvironments mocks base method. func (m *MockworkspaceRetriever) ListEnvironments() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListEnvironments") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListEnvironments indicates an expected call of ListEnvironments. func (mr *MockworkspaceRetrieverMockRecorder) ListEnvironments() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListEnvironments", reflect.TypeOf((*MockworkspaceRetriever)(nil).ListEnvironments)) } // ListJobs mocks base method. func (m *MockworkspaceRetriever) ListJobs() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListJobs") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListJobs indicates an expected call of ListJobs. func (mr *MockworkspaceRetrieverMockRecorder) ListJobs() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListJobs", reflect.TypeOf((*MockworkspaceRetriever)(nil).ListJobs)) } // ListServices mocks base method. func (m *MockworkspaceRetriever) ListServices() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListServices") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListServices indicates an expected call of ListServices. func (mr *MockworkspaceRetrieverMockRecorder) ListServices() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockworkspaceRetriever)(nil).ListServices)) } // ListWorkloads mocks base method. func (m *MockworkspaceRetriever) ListWorkloads() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListWorkloads") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListWorkloads indicates an expected call of ListWorkloads. func (mr *MockworkspaceRetrieverMockRecorder) ListWorkloads() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWorkloads", reflect.TypeOf((*MockworkspaceRetriever)(nil).ListWorkloads)) } // Summary mocks base method. func (m *MockworkspaceRetriever) Summary() (*workspace.Summary, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Summary") ret0, _ := ret[0].(*workspace.Summary) ret1, _ := ret[1].(error) return ret0, ret1 } // Summary indicates an expected call of Summary. func (mr *MockworkspaceRetrieverMockRecorder) Summary() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Summary", reflect.TypeOf((*MockworkspaceRetriever)(nil).Summary)) } // MockdeployedWorkloadsRetriever is a mock of deployedWorkloadsRetriever interface. type MockdeployedWorkloadsRetriever struct { ctrl *gomock.Controller recorder *MockdeployedWorkloadsRetrieverMockRecorder } // MockdeployedWorkloadsRetrieverMockRecorder is the mock recorder for MockdeployedWorkloadsRetriever. type MockdeployedWorkloadsRetrieverMockRecorder struct { mock *MockdeployedWorkloadsRetriever } // NewMockdeployedWorkloadsRetriever creates a new mock instance. func NewMockdeployedWorkloadsRetriever(ctrl *gomock.Controller) *MockdeployedWorkloadsRetriever { mock := &MockdeployedWorkloadsRetriever{ctrl: ctrl} mock.recorder = &MockdeployedWorkloadsRetrieverMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockdeployedWorkloadsRetriever) EXPECT() *MockdeployedWorkloadsRetrieverMockRecorder { return m.recorder } // IsJobDeployed mocks base method. func (m *MockdeployedWorkloadsRetriever) IsJobDeployed(appName, envName, jobName string) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IsJobDeployed", appName, envName, jobName) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // IsJobDeployed indicates an expected call of IsJobDeployed. func (mr *MockdeployedWorkloadsRetrieverMockRecorder) IsJobDeployed(appName, envName, jobName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsJobDeployed", reflect.TypeOf((*MockdeployedWorkloadsRetriever)(nil).IsJobDeployed), appName, envName, jobName) } // IsServiceDeployed mocks base method. func (m *MockdeployedWorkloadsRetriever) IsServiceDeployed(appName, envName, svcName string) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IsServiceDeployed", appName, envName, svcName) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // IsServiceDeployed indicates an expected call of IsServiceDeployed. func (mr *MockdeployedWorkloadsRetrieverMockRecorder) IsServiceDeployed(appName, envName, svcName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsServiceDeployed", reflect.TypeOf((*MockdeployedWorkloadsRetriever)(nil).IsServiceDeployed), appName, envName, svcName) } // ListDeployedJobs mocks base method. func (m *MockdeployedWorkloadsRetriever) ListDeployedJobs(appName, envName string) ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListDeployedJobs", appName, envName) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListDeployedJobs indicates an expected call of ListDeployedJobs. func (mr *MockdeployedWorkloadsRetrieverMockRecorder) ListDeployedJobs(appName, envName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeployedJobs", reflect.TypeOf((*MockdeployedWorkloadsRetriever)(nil).ListDeployedJobs), appName, envName) } // ListDeployedServices mocks base method. func (m *MockdeployedWorkloadsRetriever) ListDeployedServices(appName, envName string) ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListDeployedServices", appName, envName) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } // ListDeployedServices indicates an expected call of ListDeployedServices. func (mr *MockdeployedWorkloadsRetrieverMockRecorder) ListDeployedServices(appName, envName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeployedServices", reflect.TypeOf((*MockdeployedWorkloadsRetriever)(nil).ListDeployedServices), appName, envName) } // ListSNSTopics mocks base method. func (m *MockdeployedWorkloadsRetriever) ListSNSTopics(appName, envName string) ([]deploy.Topic, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListSNSTopics", appName, envName) ret0, _ := ret[0].([]deploy.Topic) ret1, _ := ret[1].(error) return ret0, ret1 } // ListSNSTopics indicates an expected call of ListSNSTopics. func (mr *MockdeployedWorkloadsRetrieverMockRecorder) ListSNSTopics(appName, envName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSNSTopics", reflect.TypeOf((*MockdeployedWorkloadsRetriever)(nil).ListSNSTopics), appName, envName) } // MocktaskStackDescriber is a mock of taskStackDescriber interface. type MocktaskStackDescriber struct { ctrl *gomock.Controller recorder *MocktaskStackDescriberMockRecorder } // MocktaskStackDescriberMockRecorder is the mock recorder for MocktaskStackDescriber. type MocktaskStackDescriberMockRecorder struct { mock *MocktaskStackDescriber } // NewMocktaskStackDescriber creates a new mock instance. func NewMocktaskStackDescriber(ctrl *gomock.Controller) *MocktaskStackDescriber { mock := &MocktaskStackDescriber{ctrl: ctrl} mock.recorder = &MocktaskStackDescriberMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MocktaskStackDescriber) EXPECT() *MocktaskStackDescriberMockRecorder { return m.recorder } // ListDefaultTaskStacks mocks base method. func (m *MocktaskStackDescriber) ListDefaultTaskStacks() ([]deploy.TaskStackInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListDefaultTaskStacks") ret0, _ := ret[0].([]deploy.TaskStackInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // ListDefaultTaskStacks indicates an expected call of ListDefaultTaskStacks. func (mr *MocktaskStackDescriberMockRecorder) ListDefaultTaskStacks() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDefaultTaskStacks", reflect.TypeOf((*MocktaskStackDescriber)(nil).ListDefaultTaskStacks)) } // ListTaskStacks mocks base method. func (m *MocktaskStackDescriber) ListTaskStacks(appName, envName string) ([]deploy.TaskStackInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListTaskStacks", appName, envName) ret0, _ := ret[0].([]deploy.TaskStackInfo) ret1, _ := ret[1].(error) return ret0, ret1 } // ListTaskStacks indicates an expected call of ListTaskStacks. func (mr *MocktaskStackDescriberMockRecorder) ListTaskStacks(appName, envName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListTaskStacks", reflect.TypeOf((*MocktaskStackDescriber)(nil).ListTaskStacks), appName, envName) } // MocktaskLister is a mock of taskLister interface. type MocktaskLister struct { ctrl *gomock.Controller recorder *MocktaskListerMockRecorder } // MocktaskListerMockRecorder is the mock recorder for MocktaskLister. type MocktaskListerMockRecorder struct { mock *MocktaskLister } // NewMocktaskLister creates a new mock instance. func NewMocktaskLister(ctrl *gomock.Controller) *MocktaskLister { mock := &MocktaskLister{ctrl: ctrl} mock.recorder = &MocktaskListerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MocktaskLister) EXPECT() *MocktaskListerMockRecorder { return m.recorder } // ListActiveAppEnvTasks mocks base method. func (m *MocktaskLister) ListActiveAppEnvTasks(opts ecs0.ListActiveAppEnvTasksOpts) ([]*ecs.Task, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListActiveAppEnvTasks", opts) ret0, _ := ret[0].([]*ecs.Task) ret1, _ := ret[1].(error) return ret0, ret1 } // ListActiveAppEnvTasks indicates an expected call of ListActiveAppEnvTasks. func (mr *MocktaskListerMockRecorder) ListActiveAppEnvTasks(opts interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListActiveAppEnvTasks", reflect.TypeOf((*MocktaskLister)(nil).ListActiveAppEnvTasks), opts) } // ListActiveDefaultClusterTasks mocks base method. func (m *MocktaskLister) ListActiveDefaultClusterTasks(filter ecs0.ListTasksFilter) ([]*ecs.Task, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListActiveDefaultClusterTasks", filter) ret0, _ := ret[0].([]*ecs.Task) ret1, _ := ret[1].(error) return ret0, ret1 } // ListActiveDefaultClusterTasks indicates an expected call of ListActiveDefaultClusterTasks. func (mr *MocktaskListerMockRecorder) ListActiveDefaultClusterTasks(filter interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListActiveDefaultClusterTasks", reflect.TypeOf((*MocktaskLister)(nil).ListActiveDefaultClusterTasks), filter) }
864
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package syncbuffer provides a goroutine safe bytes.Buffer as well printing functionality to the terminal. package syncbuffer import ( "bytes" "errors" "io" "strings" "sync" ) // SyncBuffer is a synchronized buffer that can be used to store output data and coordinate between multiple goroutines. type SyncBuffer struct { bufMu sync.Mutex // bufMu is a mutex protects buf. buf bytes.Buffer // buf is the buffer that stores the data. done chan struct{} // is closed after MarkDone() is called. } // New creates and returns a new SyncBuffer object with an initialized 'done' channel. func New() *SyncBuffer { return &SyncBuffer{ done: make(chan struct{}), } } // Write appends the given bytes to the buffer. func (b *SyncBuffer) Write(p []byte) (n int, err error) { b.bufMu.Lock() defer b.bufMu.Unlock() return b.buf.Write(p) } // IsDone returns true if the Done channel has been closed, otherwise return false. func (b *SyncBuffer) IsDone() bool { select { case <-b.done: return true default: return false } } // MarkDone closes the Done channel. func (b *SyncBuffer) MarkDone() { close(b.done) } // LabeledSyncBuffer is a struct that combines a SyncBuffer with a string label. type LabeledSyncBuffer struct { label string *SyncBuffer } // WithLabel creates and returns a new LabeledSyncBuffer with the given label and SyncBuffer. func (buf *SyncBuffer) WithLabel(label string) *LabeledSyncBuffer { return &LabeledSyncBuffer{ label: label, SyncBuffer: buf, } } // Copy reads all the content of an io.Reader into a SyncBuffer and an error if copy is failed. func (buf *SyncBuffer) Copy(r io.Reader) error { defer buf.MarkDone() _, err := io.Copy(buf, r) if err != nil && !errors.Is(err, io.EOF) { return err } return nil } // lines returns an empty slice if the buffer is empty. // Otherwise, it returns a slice of all the lines stored in the buffer. func (b *SyncBuffer) lines() []string { b.bufMu.Lock() defer b.bufMu.Unlock() lines := b.buf.String() if len(lines) == 0 { return nil } return splitLinesAndTrimSpaces(lines) } // splitLinesAndTrimSpaces splits the input string into lines // and trims the leading and trailing spaces and returns slice of strings. func splitLinesAndTrimSpaces(input string) []string { lines := strings.Split(input, "\n") for i, line := range lines { lines[i] = strings.TrimSpace(line) } return lines }
96
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package syncbuffer import ( "errors" "fmt" "io" "testing" "github.com/stretchr/testify/require" ) func TestSyncBuffer_Write(t *testing.T) { testCases := map[string]struct { input []byte wantedOutput string }{ "append to custom buffer with simple input": { input: []byte("hello world"), wantedOutput: "hello world", }, "append to custom buffer with empty input": { input: []byte(""), wantedOutput: "", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN sb := New() // WHEN sb.Write(tc.input) // THEN require.Equal(t, tc.wantedOutput, sb.buf.String()) }) } } func TestSyncBuffer_IsDone(t *testing.T) { testCases := map[string]struct { buffer *SyncBuffer wantedDone bool }{ "Buffer is done": { buffer: New(), wantedDone: true, }, "Buffer is not done": { buffer: New(), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN if tc.wantedDone { tc.buffer.MarkDone() } // WHEN actual := tc.buffer.IsDone() // THEN require.Equal(t, tc.wantedDone, actual) }) } } type mockReader struct { data []byte err error } func (r *mockReader) Read(p []byte) (int, error) { if len(r.data) == 0 { return 0, r.err } n := copy(p, r.data) r.data = r.data[n:] return n, io.EOF } func TestCopy(t *testing.T) { testCases := map[string]struct { reader io.Reader wantedOutput string wantedError error }{ "copy data from file reader to buffer": { reader: &mockReader{ data: []byte("Building your container image"), }, wantedOutput: "Building your container image", }, "return an error when failed to copy data to buffer": { reader: &mockReader{err: fmt.Errorf("some error")}, wantedError: fmt.Errorf("some error"), }, "return an EOF error": { reader: &mockReader{ data: []byte("Building your container image"), err: errors.New("EOF"), }, wantedOutput: "Building your container image", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { buf := New() gotErr := buf.Copy(tc.reader) if tc.wantedError != nil { require.EqualError(t, tc.wantedError, gotErr.Error()) } }) } } func TestSyncBuffer_WithLabel(t *testing.T) { mockSyncBuf := New() testCases := map[string]struct { label string wanted *LabeledSyncBuffer }{ "if the label is provided": { label: "title", wanted: mockSyncBuf.WithLabel("title"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // THEN labeledSyncBuf := mockSyncBuf.WithLabel(tc.label) // THEN require.Equal(t, tc.wanted, labeledSyncBuf) }) } }
147
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package syncbuffer provides a goroutine safe bytes.Buffer as well printing functionality to the terminal. package syncbuffer import ( "fmt" "io" "math" "strings" "github.com/aws/copilot-cli/internal/pkg/term/cursor" "golang.org/x/term" ) // printAllLinesInBuf represents to print the entire contents in the buffer. const ( printAllLinesInBuf = -1 ) const ( defaultTerminalWidth = 80 ) // FileWriter is the interface to write to a file. type FileWriter interface { io.Writer Fd() uintptr } // LabeledTermPrinter is a printer to display label and logs to the terminal. type LabeledTermPrinter struct { term FileWriter // term writes logs to the terminal FileWriter. buffers []*LabeledSyncBuffer // buffers stores logs before writing to the terminal. numLines int // number of lines that has to be written from each buffer. padding int // Leading spaces before rendering to terminal. prevWrittenLines int // number of lines written from all the buffers. } // LabeledTermPrinterOption is a type alias to configure LabeledTermPrinter. type LabeledTermPrinterOption func(ltp *LabeledTermPrinter) // NewLabeledTermPrinter returns a LabeledTermPrinter that can print to the terminal filewriter from buffers. func NewLabeledTermPrinter(fw FileWriter, bufs []*LabeledSyncBuffer, opts ...LabeledTermPrinterOption) *LabeledTermPrinter { ltp := &LabeledTermPrinter{ term: fw, buffers: bufs, numLines: printAllLinesInBuf, // By default set numlines to -1 to print all from buffers. } for _, opt := range opts { opt(ltp) } return ltp } // WithNumLines sets the numlines of LabeledTermPrinter. func WithNumLines(n int) LabeledTermPrinterOption { return func(ltp *LabeledTermPrinter) { ltp.numLines = n } } // WithPadding sets the padding of LabeledTermPrinter. func WithPadding(n int) LabeledTermPrinterOption { return func(ltp *LabeledTermPrinter) { ltp.padding = n } } // IsDone returns true if all the buffers are done. func (ltp *LabeledTermPrinter) IsDone() bool { for _, buf := range ltp.buffers { if !buf.IsDone() { return false } } return true } // Print prints the label and the last N lines of logs from each buffer // to the LabeledTermPrinter fileWriter and erases the previous output. // If numLines is -1 then print all the values from buffers. func (ltp *LabeledTermPrinter) Print() { if ltp.numLines == printAllLinesInBuf { ltp.printAll() return } if ltp.prevWrittenLines > 0 { cursor.EraseLinesAbove(ltp.term, ltp.prevWrittenLines) } ltp.prevWrittenLines = 0 for _, buf := range ltp.buffers { logs := buf.lines() outputLogs := ltp.lastNLines(logs) ltp.prevWrittenLines += ltp.writeLines(buf.label, outputLogs) } } // printAll writes the entire contents of all the buffers to the file writer. // If one of the buffer gets done then print entire content of the buffer. // Until all the buffers are written to file writer. func (ltp *LabeledTermPrinter) printAll() { for idx := 0; idx < len(ltp.buffers); idx++ { if !ltp.buffers[idx].IsDone() { continue } outputLogs := ltp.buffers[idx].lines() ltp.writeLines(ltp.buffers[idx].label, outputLogs) ltp.buffers = append(ltp.buffers[:idx], ltp.buffers[idx+1:]...) idx-- } } // lastNLines returns the last N lines of the given logs where N is the value of tp.numLines. // If the logs slice contains fewer than N lines, all lines are returned. // If the given input logs are empty then return slice of empty strings. func (ltp *LabeledTermPrinter) lastNLines(logs []string) []string { var start int if len(logs) > ltp.numLines { start = len(logs) - ltp.numLines } end := len(logs) // Extract the last N lines logLines := make([]string, ltp.numLines) idx := 0 for start < end { logLines[idx] = logs[start] start++ idx++ } return logLines } // writeLines writes a label and output logs to the terminal associated with the TermPrinter. // Returns the number of lines needed to erase based on terminal width. func (ltp *LabeledTermPrinter) writeLines(label string, lines []string) int { var numLines float64 writeLine := func(line string) { fmt.Fprintln(ltp.term, line) if len(line) == 0 { numLines++ return } numLines += math.Ceil(float64(len(line)) / float64(terminalWidth(ltp.term))) } writeLine(label) for _, line := range lines { writeLine(fmt.Sprintf("%s%s", strings.Repeat(" ", ltp.padding), line)) } return int(numLines) } // terminalWidth returns the width of the terminal associated with the given FileWriter. // If the FileWriter is not associated with a terminal, it returns a default terminal width. func terminalWidth(fw FileWriter) int { terminalWidth := defaultTerminalWidth if term.IsTerminal(int(fw.Fd())) { // Swallow the error as we do not want propogate the error up to call stack. if width, _, err := term.GetSize(int(fw.Fd())); err == nil { terminalWidth = width } } return terminalWidth }
167
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package syncbuffer import ( "bytes" "io" "testing" "github.com/stretchr/testify/require" ) type mockFileWriter struct { io.Writer } func (m mockFileWriter) Fd() uintptr { return 0 } func TestLabeledTermPrinter_Print(t *testing.T) { testCases := map[string]struct { inNumLines int inPadding int printAll bool wanted string }{ "display label with given numLines": { inNumLines: 2, inPadding: 5, wanted: `Building your container image 1 line3 from image1 line4 from image1 Building your container image 2 line3 from image2 line4 from image2 `, }, "display all the lines if numLines set to -1": { inNumLines: -1, inPadding: 5, printAll: true, wanted: `Building your container image 1 line1 from image1 line2 from image1 line3 from image1 line4 from image1 Building your container image 2 line1 from image2 line2 from image2 line3 from image2 line4 from image2 `, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN mockBuffer1 := []byte(`line1 from image1 line2 from image1 line3 from image1 line4 from image1`) mockSyncBuf1 := New() mockSyncBuf1.Write(mockBuffer1) buf2 := []byte(`line1 from image2 line2 from image2 line3 from image2 line4 from image2`) mockSyncBuf2 := New() mockSyncBuf2.Write(buf2) var mockLabeledSyncbufs []*LabeledSyncBuffer mockLabeledSyncbufs = append(mockLabeledSyncbufs, mockSyncBuf1.WithLabel("Building your container image 1"), mockSyncBuf2.WithLabel("Building your container image 2")) termOut := &bytes.Buffer{} ltp := LabeledTermPrinter{ term: mockFileWriter{termOut}, buffers: mockLabeledSyncbufs, numLines: tc.inNumLines, padding: tc.inPadding, } // WHEN for _, buf := range ltp.buffers { buf.MarkDone() } ltp.Print() // checking multiple calls to Print will result in // printing a buffer only once when it enters printAll. if tc.printAll { for i := 0; i < 3; i++ { ltp.Print() } } // THEN require.Equal(t, tc.wanted, termOut.String()) }) } } func TestLabeledTermPrinter_IsDone(t *testing.T) { testCases := map[string]struct { mockSyncBuf1 *SyncBuffer mockSyncBuf2 *SyncBuffer wanted bool }{ "return false if all buffers are not done": { mockSyncBuf1: New(), mockSyncBuf2: New(), wanted: false, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN var mockLabeledSyncBufs []*LabeledSyncBuffer mockLabeledSyncBufs = append(mockLabeledSyncBufs, tc.mockSyncBuf1.WithLabel("title 1"), tc.mockSyncBuf2.WithLabel("title 2")) ltp := LabeledTermPrinter{ term: mockFileWriter{}, buffers: mockLabeledSyncBufs, } mockLabeledSyncBufs[0].MarkDone() // WHEN got := ltp.IsDone() //THEN require.Equal(t, tc.wanted, got) }) } }
138
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package version holds variables for generating version information package version const ( // LegacyAppTemplate is the version associated with the application template before we started versioning. LegacyAppTemplate = "v0.0.0" // AppTemplateMinAlias is the least version number available for HTTPS alias. AppTemplateMinAlias = "v1.0.0" // AppTemplateMinStaticSite is the minimum app version required to deploy a static site. AppTemplateMinStaticSite = "v1.2.0" // LegacyEnvTemplate is the version associated with the environment template before we started versioning. LegacyEnvTemplate = "v0.0.0" // EnvTemplateBootstrap is the version of an environment template that contains only bootstrap resources. EnvTemplateBootstrap = "bootstrap" ) // Version is this binary's version. Set with linker flags when building Copilot. var Version string // LatestTemplateVersion is the latest version number available for Copilot templates. func LatestTemplateVersion() string { return Version }
27
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package workspace import ( "errors" "fmt" "path/filepath" "github.com/aws/copilot-cli/internal/pkg/term/color" ) // ErrNoPipelineInWorkspace means there was no pipeline manifest in the workspace dir. var ErrNoPipelineInWorkspace = errors.New("no pipeline manifest found in the workspace") // ErrFileExists means we tried to create an existing file. type ErrFileExists struct { FileName string } func (e *ErrFileExists) Error() string { return fmt.Sprintf("file %s already exists", e.FileName) } // ErrFileNotExists means we tried to read a non-existing file. type ErrFileNotExists struct { FileName string } func (e *ErrFileNotExists) Error() string { return fmt.Sprintf("file %s does not exists", e.FileName) } // ErrWorkspaceNotFound means we couldn't locate a workspace root. type ErrWorkspaceNotFound struct { CurrentDirectory string ManifestDirectoryName string NumberOfLevelsChecked int } func (e *ErrWorkspaceNotFound) Error() string { return fmt.Sprintf("couldn't find a directory called %s up to %d levels up from %s", e.ManifestDirectoryName, e.NumberOfLevelsChecked, e.CurrentDirectory) } // RecommendActions suggests steps clients can take to mitigate the copilot/ directory not found error. func (_ *ErrWorkspaceNotFound) RecommendActions() string { return fmt.Sprintf("Run %s to create an application.", color.HighlightCode("copilot app init")) } // empty denotes that this error represents an empty workspace. func (_ *ErrWorkspaceNotFound) empty() {} // ErrNoAssociatedApplication means we couldn't locate a workspace summary file. type ErrNoAssociatedApplication struct{} func (e *ErrNoAssociatedApplication) Error() string { return "couldn't find an application associated with this workspace" } // RecommendActions suggests steps clients can take to mitigate the .workspace file not found error. func (_ *ErrNoAssociatedApplication) RecommendActions() string { return fmt.Sprintf(`The "copilot" directory is not associated with an application. Run %s to create or use an application.`, color.HighlightCode("copilot app init")) } // empty denotes that this error represents an empty workspace. func (_ *ErrNoAssociatedApplication) empty() {} // errHasExistingApplication means we tried to create a workspace that belongs to another application. type errHasExistingApplication struct { existingAppName string basePath string summaryPath string } func (e *errHasExistingApplication) Error() string { relPath, _ := filepath.Rel(e.basePath, e.summaryPath) if relPath == "" { relPath = e.summaryPath } return fmt.Sprintf("workspace is already registered with application %s under %s", e.existingAppName, relPath) } // IsEmptyErr returns true if the error is related to an empty workspace. func IsEmptyErr(err error) bool { var emptyWs interface { empty() } return errors.As(err, &emptyWs) }
95
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package workspace import ( "errors" "fmt" "testing" "github.com/stretchr/testify/require" ) func TestIsEmptyErr(t *testing.T) { testCases := map[string]struct { err error wanted bool }{ "should return true when ErrWorkspaceNotFound": { err: &ErrWorkspaceNotFound{}, wanted: true, }, "should return true when ErrNoAssociatedApplication": { err: &ErrNoAssociatedApplication{}, wanted: true, }, "should return true when an empty workspace error is wrapped": { err: fmt.Errorf("burrito: %w", &ErrNoAssociatedApplication{}), wanted: true, }, "should return false when a random error": { err: errors.New("unexpected"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { require.Equal(t, tc.wanted, IsEmptyErr(tc.err)) }) } }
42
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package workspace contains functionality to manage a user's local workspace. This includes // creating an application directory, reading and writing a summary file to associate the workspace with the application, // and managing infrastructure-as-code files. The typical workspace will be structured like: // // . // ├── copilot (application directory) // │ ├── .workspace (workspace summary) // │ ├── my-service // │ │ └── manifest.yml (service manifest) // | | environments // | | └── test // │ │ └── manifest.yml (environment manifest for the environment test) // │ ├── buildspec.yml (legacy buildspec for the pipeline's build stage) // │ ├── pipeline.yml (legacy pipeline manifest) // │ ├── pipelines // │ │ ├── pipeline-app-beta // │ │ │ ├── buildspec.yml (buildspec for the pipeline 'pipeline-app-beta') // │ ┴ ┴ └── manifest.yml (pipeline manifest for the pipeline 'pipeline-app-beta') // └── my-service-src (customer service code) package workspace import ( "encoding" "errors" "fmt" "os" "path/filepath" "sort" "sync" "github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo" "github.com/aws/copilot-cli/internal/pkg/term/log" "github.com/aws/copilot-cli/internal/pkg/manifest" "github.com/spf13/afero" "gopkg.in/yaml.v3" ) const ( // CopilotDirName is the name of the directory where generated infrastructure code for an application will be stored. CopilotDirName = "copilot" // SummaryFileName is the name of the file that is associated with the application. SummaryFileName = ".workspace" // AddonsParametersFileName is the name of the file that define extra parameters for an addon. AddonsParametersFileName = "addons.parameters.yml" addonsDirName = "addons" overridesDirName = "overrides" pipelinesDirName = "pipelines" environmentsDirName = "environments" maximumParentDirsToSearch = 5 legacyPipelineFileName = "pipeline.yml" manifestFileName = "manifest.yml" buildspecFileName = "buildspec.yml" ) // Summary is a description of what's associated with this workspace. type Summary struct { Application string `yaml:"application"` // Name of the application. Path string `yaml:"-"` // Absolute path to the summary file. } // Workspace typically represents a Git repository where the user has its infrastructure-as-code files as well as source files. type Workspace struct { workingDirAbs string CopilotDirAbs string // TODO: make private by adding mocks for selector unit testing. // These fields should be accessed via the Summary method and not directly. summary *Summary summaryErr error summarizeOnce sync.Once fs *afero.Afero logger func(format string, args ...interface{}) } var getWd = os.Getwd // Use returns an existing workspace, searching for a copilot/ directory from the current wd, // up to 5 levels above. It returns ErrWorkspaceNotFound if no copilot/ directory is found. func Use(fs afero.Fs) (*Workspace, error) { workingDirAbs, err := getWd() if err != nil { return nil, fmt.Errorf("get working directory: %w", err) } ws := &Workspace{ workingDirAbs: workingDirAbs, fs: &afero.Afero{Fs: fs}, logger: log.Infof, } copilotDirPath, err := ws.copilotDirPath() if err != nil { return nil, err } ws.CopilotDirAbs = copilotDirPath if _, err := ws.Summary(); err != nil { // If there is an issue retrieving the summary, then the workspace is not usable. return nil, err } return ws, nil } // Create creates a new Workspace in the current working directory for appName with summary if it doesn't already exist. func Create(appName string, fs afero.Fs) (*Workspace, error) { workingDirAbs, err := getWd() if err != nil { return nil, fmt.Errorf("get working directory: %w", err) } ws := &Workspace{ workingDirAbs: workingDirAbs, fs: &afero.Afero{Fs: fs}, logger: log.Infof, } // Check if a workspace already exists. copilotDirPath, err := ws.copilotDirPath() var errWSNotFound *ErrWorkspaceNotFound if err != nil && !errors.As(err, &errWSNotFound) { return nil, err } if err == nil { ws.CopilotDirAbs = copilotDirPath // If so, grab the summary. summary, err := ws.Summary() if err == nil { // If a summary exists, but is registered to a different application, throw an error. if summary.Application != appName { return nil, &errHasExistingApplication{ existingAppName: summary.Application, basePath: ws.workingDirAbs, summaryPath: summary.Path, } } // Otherwise our work is all done. return ws, nil } var notFound *ErrNoAssociatedApplication if !errors.As(err, &notFound) { return nil, err } } // Create a workspace, including both the dir and workspace file. CopilotDirAbs, err := ws.createCopilotDir() if err != nil { return nil, err } ws.CopilotDirAbs = CopilotDirAbs ws.summary, ws.summaryErr = ws.writeSummary(appName) if ws.summaryErr != nil { return nil, err } return ws, nil } // ProjectRoot returns a path to the presumed root of the project, the directory that contains the copilot dir and .workspace file. func (ws *Workspace) ProjectRoot() string { return filepath.Dir(ws.CopilotDirAbs) } // Summary returns a summary of the workspace. The method assumes that the workspace exists and the path is known. func (ws *Workspace) Summary() (*Summary, error) { ws.summarizeOnce.Do(func() { summaryPath := filepath.Join(ws.CopilotDirAbs, SummaryFileName) // Assume `CopilotDirAbs` is always present. if ok, _ := ws.fs.Exists(summaryPath); !ok { ws.summaryErr = &ErrNoAssociatedApplication{} return } f, err := ws.fs.ReadFile(summaryPath) if err != nil { ws.summaryErr = err return } ws.summary = &Summary{ Path: summaryPath, } ws.summaryErr = yaml.Unmarshal(f, ws.summary) }) return ws.summary, ws.summaryErr } // WorkloadExists returns true if a workload exists in the workspace. func (ws *Workspace) WorkloadExists(name string) (bool, error) { path := filepath.Join(ws.CopilotDirAbs, name, manifestFileName) exists, err := ws.fs.Exists(path) if err != nil { return false, fmt.Errorf("check if %s exists: %w", path, err) } return exists, nil } // HasEnvironments returns true if the workspace manages environments. func (ws *Workspace) HasEnvironments() (bool, error) { path := filepath.Join(ws.CopilotDirAbs, environmentsDirName) exists, err := ws.fs.Exists(path) if err != nil { return false, fmt.Errorf("check if %s exists: %w", path, err) } return exists, nil } // ListServices returns the names of the services in the workspace. func (ws *Workspace) ListServices() ([]string, error) { return ws.listWorkloads(func(wlType string) bool { for _, t := range manifestinfo.ServiceTypes() { if wlType == t { return true } } return false }) } // ListJobs returns the names of all jobs in the workspace. func (ws *Workspace) ListJobs() ([]string, error) { return ws.listWorkloads(func(wlType string) bool { for _, t := range manifestinfo.JobTypes() { if wlType == t { return true } } return false }) } // ListWorkloads returns the name of all the workloads in the workspace (could be unregistered in SSM). func (ws *Workspace) ListWorkloads() ([]string, error) { return ws.listWorkloads(func(wlType string) bool { return true }) } // PipelineManifest holds identifying information about a pipeline manifest file. type PipelineManifest struct { Name string // Name of the pipeline inside the manifest file. Path string // Absolute path to the manifest file for the pipeline. } // ListPipelines returns all pipelines in the workspace. func (ws *Workspace) ListPipelines() ([]PipelineManifest, error) { var manifests []PipelineManifest addManifest := func(manifestPath string) { manifest, err := ws.ReadPipelineManifest(manifestPath) switch { case errors.Is(err, ErrNoPipelineInWorkspace): // no file at manifestPath, ignore it return case err != nil: ws.logger("Unable to read pipeline manifest at '%s': %s\n", manifestPath, err) return } manifests = append(manifests, PipelineManifest{ Name: manifest.Name, Path: manifestPath, }) } // add the legacy pipeline addManifest(ws.pipelineManifestLegacyPath()) // add each file that matches pipelinesDir/*/manifest.yml pipelinesDir := ws.pipelinesDirPath() exists, err := ws.fs.Exists(pipelinesDir) switch { case err != nil: return nil, fmt.Errorf("check if pipelines directory exists at %q: %w", pipelinesDir, err) case !exists: // there is at most 1 manifest (the legacy one), so we don't need to sort return manifests, nil } files, err := ws.fs.ReadDir(pipelinesDir) if err != nil { return nil, fmt.Errorf("read directory %q: %w", pipelinesDir, err) } for _, dir := range files { if dir.IsDir() { addManifest(filepath.Join(pipelinesDir, dir.Name(), manifestFileName)) } } // sort manifests alphabetically by Name sort.Slice(manifests, func(i, j int) bool { return manifests[i].Name < manifests[j].Name }) return manifests, nil } // listWorkloads returns the name of all workloads (either services or jobs) in the workspace. func (ws *Workspace) listWorkloads(match func(string) bool) ([]string, error) { files, err := ws.fs.ReadDir(ws.CopilotDirAbs) if err != nil { return nil, fmt.Errorf("read directory %s: %w", ws.CopilotDirAbs, err) } var names []string for _, f := range files { if !f.IsDir() { continue } if exists, _ := ws.fs.Exists(filepath.Join(ws.CopilotDirAbs, f.Name(), manifestFileName)); !exists { // Swallow the error because we don't want to include any services that we don't have permissions to read. continue } manifestBytes, err := ws.ReadWorkloadManifest(f.Name()) if err != nil { return nil, fmt.Errorf("read manifest for workload %s: %w", f.Name(), err) } wlType, err := manifestBytes.WorkloadType() if err != nil { return nil, err } if match(wlType) { names = append(names, f.Name()) } } return names, nil } // ListEnvironments returns the name of the environments in the workspace. func (ws *Workspace) ListEnvironments() ([]string, error) { envPath := filepath.Join(ws.CopilotDirAbs, environmentsDirName) files, err := ws.fs.ReadDir(envPath) if err != nil { return nil, fmt.Errorf("read directory %s: %w", envPath, err) } var names []string for _, f := range files { if !f.IsDir() { continue } if exists, _ := ws.fs.Exists(filepath.Join(ws.CopilotDirAbs, environmentsDirName, f.Name(), manifestFileName)); !exists { // Swallow the error because we don't want to include any environments that we don't have permissions to read. continue } names = append(names, f.Name()) } return names, nil } // ReadWorkloadManifest returns the contents of the workload's manifest under copilot/{name}/manifest.yml. func (ws *Workspace) ReadWorkloadManifest(mftDirName string) (WorkloadManifest, error) { raw, err := ws.read(mftDirName, manifestFileName) if err != nil { return nil, err } mft := WorkloadManifest(raw) if err := ws.manifestNameMatchWithDir(mft, mftDirName); err != nil { return nil, err } return mft, nil } // ReadEnvironmentManifest returns the contents of the environment's manifest under copilot/environments/{name}/manifest.yml. func (ws *Workspace) ReadEnvironmentManifest(mftDirName string) (EnvironmentManifest, error) { raw, err := ws.read(environmentsDirName, mftDirName, manifestFileName) if err != nil { return nil, err } mft := EnvironmentManifest(raw) if err := ws.manifestNameMatchWithDir(mft, mftDirName); err != nil { return nil, err } typ, err := retrieveTypeFromManifest(mft) if err != nil { return nil, err } if typ != manifest.Environmentmanifestinfo { return nil, fmt.Errorf(`manifest %s has type of "%s", not "%s"`, mftDirName, typ, manifest.Environmentmanifestinfo) } return mft, nil } // ReadPipelineManifest returns the contents of the pipeline manifest under the given path. func (ws *Workspace) ReadPipelineManifest(path string) (*manifest.Pipeline, error) { manifestExists, err := ws.fs.Exists(path) if err != nil { return nil, err } if !manifestExists { return nil, ErrNoPipelineInWorkspace } data, err := ws.fs.ReadFile(path) if err != nil { return nil, fmt.Errorf("read pipeline manifest: %w", err) } pipelineManifest, err := manifest.UnmarshalPipeline(data) if err != nil { return nil, fmt.Errorf("unmarshal pipeline manifest: %w", err) } return pipelineManifest, nil } // WriteServiceManifest writes the service's manifest under the copilot/{name}/ directory. func (ws *Workspace) WriteServiceManifest(marshaler encoding.BinaryMarshaler, name string) (string, error) { data, err := marshaler.MarshalBinary() if err != nil { return "", fmt.Errorf("marshal service %s manifest to binary: %w", name, err) } return ws.write(data, name, manifestFileName) } // WriteJobManifest writes the job's manifest under the copilot/{name}/ directory. func (ws *Workspace) WriteJobManifest(marshaler encoding.BinaryMarshaler, name string) (string, error) { data, err := marshaler.MarshalBinary() if err != nil { return "", fmt.Errorf("marshal job %s manifest to binary: %w", name, err) } return ws.write(data, name, manifestFileName) } // WritePipelineBuildspec writes the pipeline buildspec under the copilot/pipelines/{name}/ directory. // If successful returns the full path of the file, otherwise returns an empty string and the error. func (ws *Workspace) WritePipelineBuildspec(marshaler encoding.BinaryMarshaler, name string) (string, error) { data, err := marshaler.MarshalBinary() if err != nil { return "", fmt.Errorf("marshal pipeline buildspec to binary: %w", err) } return ws.write(data, pipelinesDirName, name, buildspecFileName) } // WritePipelineManifest writes the pipeline manifest under the copilot/pipelines/{name}/ directory. // If successful returns the full path of the file, otherwise returns an empty string and the error. func (ws *Workspace) WritePipelineManifest(marshaler encoding.BinaryMarshaler, name string) (string, error) { data, err := marshaler.MarshalBinary() if err != nil { return "", fmt.Errorf("marshal pipeline manifest to binary: %w", err) } return ws.write(data, pipelinesDirName, name, manifestFileName) } // WriteEnvironmentManifest writes the environment manifest under the copilot/environments/{name}/ directory. // If successful returns the full path of the file, otherwise returns an empty string and the error. func (ws *Workspace) WriteEnvironmentManifest(marshaler encoding.BinaryMarshaler, name string) (string, error) { data, err := marshaler.MarshalBinary() if err != nil { return "", fmt.Errorf("marshal environment manifest to binary: %w", err) } return ws.write(data, environmentsDirName, name, manifestFileName) } // DeleteWorkspaceFile removes the .workspace file under copilot/ directory. // This will be called during app delete, we do not want to delete any other generated files. func (ws *Workspace) DeleteWorkspaceFile() error { return ws.fs.Remove(filepath.Join(ws.CopilotDirAbs, SummaryFileName)) } // EnvAddonsAbsPath returns the absolute path for the addons/ directory of environments. func (ws *Workspace) EnvAddonsAbsPath() string { return filepath.Join(ws.CopilotDirAbs, environmentsDirName, addonsDirName) } // EnvAddonFileAbsPath returns the absolute path of an addon file for environments. func (ws *Workspace) EnvAddonFileAbsPath(fName string) string { return filepath.Join(ws.EnvAddonsAbsPath(), fName) } // WorkloadAddonsAbsPath returns the absolute path for the addons/ directory file path of a given workload. func (ws *Workspace) WorkloadAddonsAbsPath(name string) string { return filepath.Join(ws.CopilotDirAbs, name, addonsDirName) } // WorkloadAddonFileAbsPath returns the absolute path of an addon file for a given workload. func (ws *Workspace) WorkloadAddonFileAbsPath(wkldName, fName string) string { return filepath.Join(ws.WorkloadAddonsAbsPath(wkldName), fName) } // WorkloadAddonFilePath returns the path under the workspace of an addon file for a given workload. func (ws *Workspace) WorkloadAddonFilePath(wkldName, fName string) string { return filepath.Join(wkldName, addonsDirName, fName) } // EnvAddonFilePath returns the path under the workspace of an addon file for environments. func (ws *Workspace) EnvAddonFilePath(fName string) string { return filepath.Join(environmentsDirName, addonsDirName, fName) } // EnvOverridesPath returns the default path to the overrides/ directory for environments. func (ws *Workspace) EnvOverridesPath() string { return filepath.Join(ws.CopilotDirAbs, environmentsDirName, overridesDirName) } // WorkloadOverridesPath returns the default path to the overrides/ directory for a given workload. func (ws *Workspace) WorkloadOverridesPath(name string) string { return filepath.Join(ws.CopilotDirAbs, name, overridesDirName) } // ListFiles returns a list of file paths to all the files under the dir. func (ws *Workspace) ListFiles(dirPath string) ([]string, error) { var names []string files, err := ws.fs.ReadDir(dirPath) if err != nil { return nil, err } for _, f := range files { names = append(names, f.Name()) } return names, nil } // ReadFile returns the content of a file. // Returns ErrFileNotExists if the file does not exist. func (ws *Workspace) ReadFile(fPath string) ([]byte, error) { exist, err := ws.fs.Exists(fPath) if err != nil { return nil, fmt.Errorf("check if file %s exists: %w", fPath, err) } if !exist { return nil, &ErrFileNotExists{FileName: fPath} } return ws.fs.ReadFile(fPath) } // Write writes the content under the path relative to "copilot/" directory. // If successful returns the full path of the file, otherwise an empty string and an error. func (ws *Workspace) Write(content encoding.BinaryMarshaler, path string) (string, error) { data, err := content.MarshalBinary() if err != nil { return "", fmt.Errorf("marshal binary content: %w", err) } return ws.write(data, path) } // FileStat wraps the os.Stat function. type FileStat interface { Stat(name string) (os.FileInfo, error) } // IsInGitRepository returns true if the current working directory is a git repository. func IsInGitRepository(fs FileStat) bool { _, err := fs.Stat(".git") return !os.IsNotExist(err) } // pipelineManifestLegacyPath returns the path to pipeline manifests before multiple pipelines (and the copilot/pipelines/ dir) were enabled. func (ws *Workspace) pipelineManifestLegacyPath() string { return filepath.Join(ws.CopilotDirAbs, legacyPipelineFileName) } func (ws *Workspace) writeSummary(appName string) (*Summary, error) { summaryPath := ws.summaryPath() summary := Summary{ Application: appName, Path: summaryPath, } serializedWorkspaceSummary, err := yaml.Marshal(summary) if err != nil { return nil, err } return &summary, ws.fs.WriteFile(summaryPath, serializedWorkspaceSummary, 0644) } func (ws *Workspace) pipelinesDirPath() string { return filepath.Join(ws.CopilotDirAbs, pipelinesDirName) } func (ws *Workspace) summaryPath() string { return filepath.Join(ws.CopilotDirAbs, SummaryFileName) } func (ws *Workspace) createCopilotDir() (string, error) { // First check to see if a manifest directory already exists existingWorkspace, _ := ws.copilotDirPath() if existingWorkspace != "" { return existingWorkspace, nil } if err := ws.fs.Mkdir(CopilotDirName, 0755); err != nil { return "", err } return filepath.Join(ws.workingDirAbs, CopilotDirName), nil } // Path returns the absolute path to the workspace. func (ws *Workspace) Path() string { return filepath.Dir(ws.CopilotDirAbs) } // Rel returns the relative path to path from the workspace copilot directory. func (ws *Workspace) Rel(path string) (string, error) { fullPath, err := filepath.Abs(path) if err != nil { return "", fmt.Errorf("make path absolute: %w", err) } return filepath.Rel(filepath.Dir(ws.CopilotDirAbs), fullPath) } // copilotDirPath tries to find the current app's copilot directory from the workspace working directory. func (ws *Workspace) copilotDirPath() (string, error) { // Are we in the application's copilot directory already? // // Note: This code checks for *any* directory named "copilot", but this might not work // correctly if we're in some subdirectory of the app that the user might have happened // to name "copilot". Our docs warn users and suggest creating another "copilot" dir closer to the wd. if filepath.Base(ws.workingDirAbs) == CopilotDirName { return ws.workingDirAbs, nil } // We might be in the application directory or in a subdirectory of the application // directory that contains the "copilot" directory. // // Keep on searching the parent directories for that copilot directory (though only // up to a finite limit, to avoid infinite recursion!) searchingDir := ws.workingDirAbs for try := 0; try < maximumParentDirsToSearch; try++ { currentDirectoryPath := filepath.Join(searchingDir, CopilotDirName) inCurrentDirPath, err := ws.fs.DirExists(currentDirectoryPath) if err != nil { return "", err } if inCurrentDirPath { return currentDirectoryPath, nil } searchingDir = filepath.Dir(searchingDir) } return "", &ErrWorkspaceNotFound{ CurrentDirectory: ws.workingDirAbs, ManifestDirectoryName: CopilotDirName, NumberOfLevelsChecked: maximumParentDirsToSearch, } } // write flushes the data to a file under the copilot directory joined by path elements. func (ws *Workspace) write(data []byte, elem ...string) (string, error) { pathElems := append([]string{ws.CopilotDirAbs}, elem...) filename := filepath.Join(pathElems...) if err := ws.fs.MkdirAll(filepath.Dir(filename), 0755 /* -rwxr-xr-x */); err != nil { return "", fmt.Errorf("create directories for file %s: %w", filename, err) } exist, err := ws.fs.Exists(filename) if err != nil { return "", fmt.Errorf("check if manifest file %s exists: %w", filename, err) } if exist { return "", &ErrFileExists{FileName: filename} } if err := ws.fs.WriteFile(filename, data, 0644 /* -rw-r--r-- */); err != nil { return "", fmt.Errorf("write manifest file: %w", err) } return filename, nil } // read returns the contents of the file under the copilot directory joined by path elements. func (ws *Workspace) read(elem ...string) ([]byte, error) { pathElems := append([]string{ws.CopilotDirAbs}, elem...) filename := filepath.Join(pathElems...) exist, err := ws.fs.Exists(filename) if err != nil { return nil, fmt.Errorf("check if manifest file %s exists: %w", filename, err) } if !exist { return nil, &ErrFileNotExists{FileName: filename} } return ws.fs.ReadFile(filename) } func (ws *Workspace) manifestNameMatchWithDir(mft namedManifest, mftDirName string) error { mftName, err := mft.name() if err != nil { return err } if mftName != mftDirName { return fmt.Errorf("name of the manifest %q and directory %q do not match", mftName, mftDirName) } return nil } // WorkloadManifest represents raw local workload manifest. type WorkloadManifest []byte func (w WorkloadManifest) name() (string, error) { return retrieveNameFromManifest(w) } // WorkloadType returns the workload type of the manifest. func (w WorkloadManifest) WorkloadType() (string, error) { return retrieveTypeFromManifest(w) } // EnvironmentManifest represents raw local environment manifest. type EnvironmentManifest []byte func (e EnvironmentManifest) name() (string, error) { return retrieveNameFromManifest(e) } type namedManifest interface { name() (string, error) } func retrieveNameFromManifest(in []byte) (string, error) { wl := struct { Name string `yaml:"name"` }{} if err := yaml.Unmarshal(in, &wl); err != nil { return "", fmt.Errorf(`unmarshal manifest file to retrieve "name": %w`, err) } return wl.Name, nil } func retrieveTypeFromManifest(in []byte) (string, error) { wl := struct { Type string `yaml:"type"` }{} if err := yaml.Unmarshal(in, &wl); err != nil { return "", fmt.Errorf(`unmarshal manifest file to retrieve "type": %w`, err) } return wl.Type, nil }
719
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package workspace import ( "errors" "fmt" "os" "path/filepath" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/require" ) // mockBinaryMarshaler implements the encoding.BinaryMarshaler interface. type mockBinaryMarshaler struct { content []byte err error } func (m mockBinaryMarshaler) MarshalBinary() (data []byte, err error) { if m.err != nil { return nil, m.err } return m.content, nil } func TestWorkspace_Path(t *testing.T) { const workspaceDir = "test" testCases := map[string]struct { expectedPath string workingDir string mockFileSystem func(fs afero.Fs) }{ "same directory level": { expectedPath: workspaceDir, workingDir: filepath.FromSlash("test/"), mockFileSystem: func(fs afero.Fs) { fs.MkdirAll("test/copilot", 0755) }, }, "same directory": { expectedPath: workspaceDir, workingDir: filepath.FromSlash("test/copilot"), mockFileSystem: func(fs afero.Fs) { fs.MkdirAll("test/copilot", 0755) }, }, "several levels deep": { expectedPath: workspaceDir, workingDir: filepath.FromSlash("test/1/2/3/4"), mockFileSystem: func(fs afero.Fs) { fs.MkdirAll("test/copilot", 0755) fs.MkdirAll("test/1/2/3/4", 0755) }, }, "uses precomputed manifest path": { expectedPath: workspaceDir, workingDir: filepath.FromSlash("/"), mockFileSystem: func(fs afero.Fs) {}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // Create an empty FileSystem fs := afero.NewMemMapFs() // Set it up tc.mockFileSystem(fs) ws := Workspace{ workingDirAbs: tc.workingDir, fs: &afero.Afero{Fs: fs}, CopilotDirAbs: filepath.FromSlash("test/copilot"), } workspacePath := ws.Path() require.Equal(t, tc.expectedPath, workspacePath) }) } } func TestWorkspace_Summary(t *testing.T) { testCases := map[string]struct { workingDir string mockFileSystem func(fs afero.Fs) expectedSummary Summary expectedError error }{ "existing workspace summary": { workingDir: "test/", mockFileSystem: func(fs afero.Fs) { fs.MkdirAll("test/copilot", 0755) afero.WriteFile(fs, "test/copilot/.workspace", []byte(fmt.Sprintf("---\napplication: %s", "DavidsApp")), 0644) }, expectedSummary: Summary{ Application: "DavidsApp", Path: filepath.FromSlash("test/copilot/.workspace"), }, }, "existing workspace summary in a parent dir": { workingDir: "test/app", mockFileSystem: func(fs afero.Fs) { fs.MkdirAll("test/copilot", 0755) afero.WriteFile(fs, "test/copilot/.workspace", []byte(fmt.Sprintf("---\napplication: %s", "DavidsApp")), 0644) }, expectedSummary: Summary{ Application: "DavidsApp", Path: filepath.FromSlash("test/copilot/.workspace"), }, }, "no existing workspace summary": { workingDir: "test/", mockFileSystem: func(fs afero.Fs) { fs.MkdirAll("test/copilot", 0755) }, expectedError: &ErrNoAssociatedApplication{}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // Create an empty FileSystem fs := afero.NewMemMapFs() // Set it up tc.mockFileSystem(fs) ws := Workspace{ CopilotDirAbs: filepath.Join("test", CopilotDirName), workingDirAbs: tc.workingDir, fs: &afero.Afero{Fs: fs}, } summary, err := ws.Summary() if tc.expectedError == nil { require.NoError(t, err) require.Equal(t, tc.expectedSummary, *summary) } else { require.Equal(t, tc.expectedError.Error(), err.Error()) } }) } } func TestWorkspace_Create(t *testing.T) { wd, err := os.Getwd() require.NoError(t, err) parent := filepath.Dir(wd) testCases := map[string]struct { appName string mockFileSystem func() afero.Fs expectedError error expectedCopilotDirAbs string }{ "successful no-op with existing workspace and summary": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/copilot", wd), 0755) _ = afero.WriteFile(fs, fmt.Sprintf("%s/copilot/.workspace", wd), []byte(fmt.Sprintf("---\napplication: %s", "DavidsApp")), 0644) fs = afero.NewReadOnlyFs(fs) // No write/ return fs }, expectedCopilotDirAbs: fmt.Sprintf("%s/copilot", wd), }, "successful no-op with existing workspace and summary in a parent directory": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/copilot", parent), 0755) _ = afero.WriteFile(fs, fmt.Sprintf("%s/copilot/.workspace", parent), []byte(fmt.Sprintf("---\napplication: %s", "DavidsApp")), 0644) fs = afero.NewReadOnlyFs(fs) // No write. return fs }, expectedCopilotDirAbs: fmt.Sprintf("%s/copilot", parent), }, "error if workspace exists but associated with different application": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/copilot", wd), 0755) _ = afero.WriteFile(fs, fmt.Sprintf("%s/copilot/.workspace", wd), []byte(fmt.Sprintf("---\napplication: %s", "DavidsOtherApp")), 0644) fs = afero.NewReadOnlyFs(fs) // No write. return fs }, expectedError: fmt.Errorf("workspace is already registered with application DavidsOtherApp under %s", filepath.FromSlash("copilot/.workspace")), }, "successfully create a work summary if workspace existing but no workspace summary": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/copilot", wd), 0755) return fs }, expectedCopilotDirAbs: fmt.Sprintf("%s/copilot", wd), }, "successfully create both workspace and summary if neither exists": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { return afero.NewMemMapFs() }, expectedCopilotDirAbs: fmt.Sprintf("%s/copilot", wd), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // Set up filesystem. gotWS, err := Create(tc.appName, tc.mockFileSystem()) if tc.expectedError == nil { // an operation not permitted error means // we tried to write to the filesystem, but // the test indicated that we expected no writes. require.NoError(t, err) // Validate that the stored copilot dir path is correct. require.Equal(t, tc.expectedCopilotDirAbs, gotWS.CopilotDirAbs) // Validate that the workspace dir is created. exist, err := gotWS.fs.Exists(tc.expectedCopilotDirAbs) require.NoError(t, err) require.True(t, exist) // Validate that the summary file is associated with the app. gotSummary, err := gotWS.Summary() require.NoError(t, err) require.Equal(t, tc.appName, gotSummary.Application) } else { require.Equal(t, tc.expectedError.Error(), err.Error()) } }) } } func TestWorkspace_Use(t *testing.T) { wd, err := os.Getwd() require.NoError(t, err) parent := filepath.Dir(wd) testCases := map[string]struct { appName string mockFileSystem func() afero.Fs expectedError error expectedCopilotDirAbs string }{ "returns the existing workspace that has the summary": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/copilot", wd), 0755) _ = afero.WriteFile(fs, fmt.Sprintf("%s/copilot/.workspace", wd), []byte(fmt.Sprintf("---\napplication: %s", "DavidsApp")), 0644) fs = afero.NewReadOnlyFs(fs) // No write/ return fs }, expectedCopilotDirAbs: fmt.Sprintf("%s/copilot", wd), }, "returns the existing workspace and workspace summary in a parent directory": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/copilot", parent), 0755) _ = afero.WriteFile(fs, fmt.Sprintf("%s/copilot/.workspace", parent), []byte(fmt.Sprintf("---\napplication: %s", "DavidsApp")), 0644) fs = afero.NewReadOnlyFs(fs) // No write. return fs }, expectedCopilotDirAbs: fmt.Sprintf("%s/copilot", parent), }, "returns an ErrNoAssociatedApplication error when there is existing copilot/ directory that does not have a workspace summary": { appName: "DavidsApp", mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/copilot", wd), 0755) return fs }, expectedCopilotDirAbs: fmt.Sprintf("%s/copilot", wd), expectedError: &ErrNoAssociatedApplication{}, }, "ErrWorkspaceNotFound if there is no workspace": { mockFileSystem: func() afero.Fs { fs := afero.NewMemMapFs() _ = fs.MkdirAll(fmt.Sprintf("%s/webhook", wd), 0755) return fs }, expectedError: &ErrWorkspaceNotFound{ CurrentDirectory: wd, ManifestDirectoryName: CopilotDirName, NumberOfLevelsChecked: maximumParentDirsToSearch, }, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // Set up filesystem. gotWS, err := Use(tc.mockFileSystem()) if tc.expectedError == nil { // an operation not permitted error means // we tried to write to the filesystem, but // the test indicated that we expected no writes. require.NoError(t, err) // Validate that the stored copilot dir path is correct. require.Equal(t, tc.expectedCopilotDirAbs, gotWS.CopilotDirAbs) // Validate that the workspace dir is there. exist, err := gotWS.fs.Exists(tc.expectedCopilotDirAbs) require.NoError(t, err) require.True(t, exist) } else { require.Equal(t, tc.expectedError.Error(), err.Error()) } }) } } func TestWorkspace_WorkloadExists(t *testing.T) { t.Run("returns true if workload exists in the workspace", func(t *testing.T) { fs := afero.NewMemMapFs() _, _ = fs.Create("/copilot/api/manifest.yml") ws := &Workspace{ CopilotDirAbs: "/copilot", fs: &afero.Afero{ Fs: fs, }, } got, err := ws.WorkloadExists("api") require.NoError(t, err) require.True(t, got) }) t.Run("returns false if workload does not in the workspace", func(t *testing.T) { fs := afero.NewMemMapFs() _, _ = fs.Create("a/copilot/api/manifest.yml") ws := &Workspace{ CopilotDirAbs: "b/copilot", fs: &afero.Afero{ Fs: fs, }, } got, err := ws.WorkloadExists("api") require.NoError(t, err) require.False(t, got) }) } func TestWorkspace_EnvironmentsExist(t *testing.T) { t.Run("returns true if environments are managed in the workspace", func(t *testing.T) { // GIVEN defer func() { getWd = os.Getwd }() getWd = func() (dir string, err error) { return "/copilot", nil } fs := afero.NewMemMapFs() _, _ = fs.Create("/copilot/environments/") _, _ = fs.Create("/copilot/.workspace") ws, err := Use(fs) // Then require.NoError(t, err) got, err := ws.HasEnvironments() require.NoError(t, err) require.True(t, got) }) t.Run("returns false if environments are not managed in the workspace", func(t *testing.T) { // GIVEN defer func() { getWd = os.Getwd }() getWd = func() (dir string, err error) { return "b/copilot", nil } fs := afero.NewMemMapFs() _, _ = fs.Create("b/copilot/.workspace") _, _ = fs.Create("a/copilot/environments/") _, _ = fs.Create("a/copilot/.workspace") ws, err := Use(fs) // Then require.NoError(t, err) got, err := ws.HasEnvironments() require.NoError(t, err) require.False(t, got) }) } func TestWorkspace_ListServices(t *testing.T) { testCases := map[string]struct { copilotDir string fs func() afero.Fs wantedNames []string wantedErr error }{ "read not-existing directory": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() return fs }, wantedErr: fmt.Errorf("read directory /copilot: open %s: file does not exist", filepath.FromSlash("/copilot")), }, "return error if directory name and manifest name do not match": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") fs.Mkdir("/copilot/users", 0755) manifest, _ := fs.Create("/copilot/users/manifest.yml") defer manifest.Close() manifest.Write([]byte(`name: payment type: Load Balanced Web Service`)) // Missing manifest.yml. fs.Mkdir("/copilot/inventory", 0755) return fs }, wantedErr: fmt.Errorf(`read manifest for workload users: name of the manifest "payment" and directory "users" do not match`), }, "retrieve only directories with manifest files": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") // Valid service directory structure. fs.Mkdir("/copilot/users", 0755) manifest, _ := fs.Create("/copilot/users/manifest.yml") defer manifest.Close() manifest.Write([]byte(`name: users type: Load Balanced Web Service`)) // Valid service directory structure. fs.MkdirAll("/copilot/payments/addons", 0755) manifest2, _ := fs.Create("/copilot/payments/manifest.yml") defer manifest2.Close() manifest2.Write([]byte(`name: payments type: Load Balanced Web Service`)) // Missing manifest.yml. fs.Mkdir("/copilot/inventory", 0755) return fs }, wantedNames: []string{"users", "payments"}, }, "retrieve only workload names of the correct type": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") // Valid service directory structure. fs.Mkdir("/copilot/users", 0755) manifest, _ := fs.Create("/copilot/users/manifest.yml") defer manifest.Close() manifest.Write([]byte(`name: users type: Scheduled Job`)) // Valid service directory structure. fs.MkdirAll("/copilot/payments/addons", 0755) manifest2, _ := fs.Create("/copilot/payments/manifest.yml") defer manifest2.Close() manifest2.Write([]byte(`name: payments type: Load Balanced Web Service`)) // Missing manifest.yml. fs.Mkdir("/copilot/inventory", 0755) return fs }, wantedNames: []string{"payments"}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: tc.copilotDir, fs: &afero.Afero{ Fs: tc.fs(), }, } names, err := ws.ListServices() if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.NoError(t, err) require.ElementsMatch(t, tc.wantedNames, names) } }) } } func TestWorkspace_ListJobs(t *testing.T) { testCases := map[string]struct { copilotDir string fs func() afero.Fs wantedNames []string wantedErr error }{ "read not-existing directory": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() return fs }, wantedErr: fmt.Errorf("read directory /copilot: open %s: file does not exist", filepath.FromSlash("/copilot")), }, "retrieve only directories with manifest files": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") // Valid service directory structure. fs.Mkdir("/copilot/users", 0755) manifest, _ := fs.Create("/copilot/users/manifest.yml") defer manifest.Close() manifest.Write([]byte(`name: users type: Scheduled Job`)) // Valid service directory structure. fs.MkdirAll("/copilot/payments/addons", 0755) manifest2, _ := fs.Create("/copilot/payments/manifest.yml") defer manifest2.Close() manifest2.Write([]byte(`name: payments type: Scheduled Job`)) // Missing manifest.yml. fs.Mkdir("/copilot/inventory", 0755) return fs }, wantedNames: []string{"users", "payments"}, }, "retrieve only workload names of the correct type": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") // Valid service directory structure. fs.Mkdir("/copilot/users", 0755) manifest, _ := fs.Create("/copilot/users/manifest.yml") defer manifest.Close() manifest.Write([]byte(`name: users type: Scheduled Job`)) // Valid service directory structure. fs.MkdirAll("/copilot/payments/addons", 0755) manifest2, _ := fs.Create("/copilot/payments/manifest.yml") defer manifest2.Close() manifest2.Write([]byte(`name: payments type: Load Balanced Web Service`)) // Missing manifest.yml. fs.Mkdir("/copilot/inventory", 0755) return fs }, wantedNames: []string{"users"}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: tc.copilotDir, fs: &afero.Afero{ Fs: tc.fs(), }, } names, err := ws.ListJobs() if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.ElementsMatch(t, tc.wantedNames, names) } }) } } func TestWorkspace_ListWorkloads(t *testing.T) { testCases := map[string]struct { copilotDir string fs func() afero.Fs wantedNames []string wantedErr error }{ "retrieve only directories with manifest files": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") fs.Create("/copilot/pipeline.yml") fs.Mkdir("/copilot/frontend", 0755) frontendManifest, _ := fs.Create("/copilot/frontend/manifest.yml") defer frontendManifest.Close() frontendManifest.Write([]byte(`name: frontend type: Load Balanced Web Service`)) fs.Mkdir("/copilot/users", 0755) userManifest, _ := fs.Create("/copilot/users/manifest.yml") defer userManifest.Close() userManifest.Write([]byte(`name: users type: Backend Service`)) fs.MkdirAll("/copilot/report/addons", 0755) reportManifest, _ := fs.Create("/copilot/report/manifest.yml") defer reportManifest.Close() reportManifest.Write([]byte(`name: report type: Scheduled Job`)) // Missing manifest.yml. fs.Mkdir("/copilot/inventory", 0755) return fs }, wantedNames: []string{"frontend", "users", "report"}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: tc.copilotDir, fs: &afero.Afero{ Fs: tc.fs(), }, } names, err := ws.ListWorkloads() if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.ElementsMatch(t, tc.wantedNames, names) } }) } } func TestWorkspace_ListEnvironments(t *testing.T) { testCases := map[string]struct { copilotDir string fs func() afero.Fs wantedNames []string wantedErr error }{ "environments directory does not exist": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) return fs }, wantedErr: fmt.Errorf("read directory %s: open %s: file does not exist", filepath.FromSlash("/copilot/environments"), filepath.FromSlash("/copilot/environments")), }, "retrieve only env directories with manifest files": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) // Environments. fs.Mkdir("/copilot/environments/test", 0755) fs.Create("/copilot/environments/test/manifest.yml") fs.Mkdir("/copilot/environments/dev", 0755) fs.Create("/copilot/environments/dev/manifest.yml") // Missing manifest.yml. fs.Mkdir("/copilot/environments/prod", 0755) // Legacy pipeline files. fs.Create("/copilot/buildspec.yml") fs.Create("/copilot/pipeline.yml") // Services. fs.Mkdir("/copilot/frontend", 0755) fs.Create("/copilot/frontend/manifest.yml") return fs }, wantedNames: []string{"test", "dev"}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: tc.copilotDir, fs: &afero.Afero{ Fs: tc.fs(), }, } names, err := ws.ListEnvironments() if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.ElementsMatch(t, tc.wantedNames, names) } }) } } func TestWorkspace_ListPipelines(t *testing.T) { testCases := map[string]struct { copilotDir string fs func() afero.Fs wantedPipelines []PipelineManifest wantedErr error wantedLog string }{ "success finding legacy pipeline (copilot/pipeline.yml) and pipelines (copilot/pipelines/*/manifest.yml)": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") legacyInCopiDirManifest, _ := fs.Create("/copilot/pipeline.yml") defer legacyInCopiDirManifest.Close() legacyInCopiDirManifest.Write([]byte(` name: legacyInCopiDir version: 1 `)) fs.Mkdir("/copilot/pipelines", 0755) fs.Create("/copilot/pipelines/randomFileToIgnore.yml") fs.Create("/copilot/pipelines/beta/buildspec.yml") betaPipelineManifest, _ := fs.Create("/copilot/pipelines/beta/manifest.yml") defer betaPipelineManifest.Close() betaPipelineManifest.Write([]byte(` name: betaManifest version: 1 `)) fs.Create("/copilot/pipelines/prod/buildspec.yml") prodPipelineManifest, _ := fs.Create("/copilot/pipelines/prod/manifest.yml") defer prodPipelineManifest.Close() prodPipelineManifest.Write([]byte(` name: prodManifest version: 1 `)) return fs }, wantedPipelines: []PipelineManifest{ { Name: "betaManifest", Path: filepath.FromSlash("/copilot/pipelines/beta/manifest.yml"), }, { Name: "legacyInCopiDir", Path: filepath.FromSlash("/copilot/pipeline.yml"), }, { Name: "prodManifest", Path: filepath.FromSlash("/copilot/pipelines/prod/manifest.yml"), }, }, wantedErr: nil, }, "success finding legacy pipeline if it is the only pipeline": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Create("/copilot/buildspec.yml") legacyInCopiDirManifest, _ := fs.Create("/copilot/pipeline.yml") defer legacyInCopiDirManifest.Close() legacyInCopiDirManifest.Write([]byte(` name: legacyInCopiDir version: 1 `)) return fs }, wantedPipelines: []PipelineManifest{ { Name: "legacyInCopiDir", Path: filepath.FromSlash("/copilot/pipeline.yml"), }, }, wantedErr: nil, }, "success finding pipelines without any legacy pipelines": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Mkdir("/copilot/pipelines", 0755) fs.Create("/copilot/pipelines/beta/buildspec.yml") betaPipelineManifest, _ := fs.Create("/copilot/pipelines/beta/manifest.yml") defer betaPipelineManifest.Close() betaPipelineManifest.Write([]byte(` name: betaManifest version: 1 `)) fs.Create("/copilot/pipelines/prod/buildspec.yml") prodPipelineManifest, _ := fs.Create("/copilot/pipelines/prod/manifest.yml") defer prodPipelineManifest.Close() prodPipelineManifest.Write([]byte(` name: prodManifest version: 1 `)) return fs }, wantedPipelines: []PipelineManifest{ { Name: "betaManifest", Path: filepath.FromSlash("/copilot/pipelines/beta/manifest.yml"), }, { Name: "prodManifest", Path: filepath.FromSlash("/copilot/pipelines/prod/manifest.yml"), }, }, wantedErr: nil, }, "ignores missing manifest files": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Mkdir("/copilot/pipelines", 0755) fs.Mkdir("/copilot/pipelines/beta", 0755) fs.Mkdir("/copilot/pipelines/prod", 0755) return fs }, wantedPipelines: nil, wantedErr: nil, }, "ignores pipeline manifest with invalid version": { copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir("/copilot", 0755) fs.Mkdir("/copilot/pipelines", 0755) fs.Mkdir("/copilot/pipelines/beta", 0755) fs.Create("/copilot/pipelines/beta/buildspec.yml") betaPipelineManifest, _ := fs.Create("/copilot/pipelines/beta/manifest.yml") defer betaPipelineManifest.Close() betaPipelineManifest.Write([]byte(` name: betaManifest version: invalidVersionShouldBe~int `)) fs.Mkdir("/copilot/pipelines/prod", 0755) fs.Create("/copilot/pipelines/prod/buildspec.yml") prodPipelineManifest, _ := fs.Create("/copilot/pipelines/prod/manifest.yml") defer prodPipelineManifest.Close() prodPipelineManifest.Write([]byte(` name: prodManifest version: 1 `)) return fs }, wantedPipelines: []PipelineManifest{ { Name: "prodManifest", Path: filepath.FromSlash("/copilot/pipelines/prod/manifest.yml"), }, }, wantedErr: nil, wantedLog: fmt.Sprintf("Unable to read pipeline manifest at '%s': unmarshal pipeline manifest: yaml: unmarshal errors:\n line 3: cannot unmarshal !!str `invalid...` into manifest.PipelineSchemaMajorVersion\n", filepath.FromSlash("/copilot/pipelines/beta/manifest.yml")), }, } for name, tc := range testCases { var log string logCollector := func(format string, a ...interface{}) { log += fmt.Sprintf(format, a...) } t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: tc.copilotDir, fs: &afero.Afero{ Fs: tc.fs(), }, logger: logCollector, } pipelines, err := ws.ListPipelines() if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } else { require.NoError(t, err) require.Equal(t, tc.wantedPipelines, pipelines) } require.Equal(t, tc.wantedLog, log) }) } } func TestIsInGitRepository(t *testing.T) { testCases := map[string]struct { given func() FileStat wanted bool }{ "return false if directory does not contain a .git directory": { given: func() FileStat { fs := afero.NewMemMapFs() return fs }, wanted: false, }, "return true if directory has a .git directory": { given: func() FileStat { fs := afero.NewMemMapFs() fs.MkdirAll(".git", 0755) return fs }, wanted: true, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { fs := tc.given() actual := IsInGitRepository(fs) require.Equal(t, tc.wanted, actual) }) } } func TestWorkspace_EnvAddonsAbsPath(t *testing.T) { mockWorkingDirAbs := "/app" testCases := map[string]struct { fs func() afero.Fs wantedPath string }{ "returns the correct env addons path": { fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/environments/addons/", 0755) return fs }, wantedPath: "/copilot/environments/addons", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: "/copilot/", workingDirAbs: mockWorkingDirAbs, fs: &afero.Afero{ Fs: tc.fs(), }, } got := ws.EnvAddonsAbsPath() require.Equal(t, tc.wantedPath, got) }) } } func TestWorkspace_WorkloadAddonFilePath(t *testing.T) { ws := &Workspace{} require.Equal(t, filepath.FromSlash("webhook/addons/db.yml"), ws.WorkloadAddonFilePath("webhook", "db.yml")) } func TestWorkspace_EnvAddonFilePath(t *testing.T) { ws := &Workspace{} require.Equal(t, filepath.FromSlash("environments/addons/db.yml"), ws.EnvAddonFilePath("db.yml")) } func TestWorkspace_EnvOverridesPath(t *testing.T) { // GIVEN defer func() { getWd = os.Getwd }() getWd = func() (dir string, err error) { return ".", nil } fs := afero.NewMemMapFs() ws, err := Create("demo", fs) // THEN require.NoError(t, err) require.Equal(t, filepath.Join("copilot", "environments", "overrides"), ws.EnvOverridesPath()) } func TestWorkspace_WorkloadOverridesPath(t *testing.T) { // GIVEN defer func() { getWd = os.Getwd }() getWd = func() (dir string, err error) { return ".", nil } fs := afero.NewMemMapFs() ws, err := Create("demo", fs) // THEN require.NoError(t, err) require.Equal(t, filepath.Join("copilot", "frontend", "overrides"), ws.WorkloadOverridesPath("frontend")) } func TestWorkspace_EnvAddonFileAbsPath(t *testing.T) { mockWorkingDirAbs := "/app" testCases := map[string]struct { fName string fs func() afero.Fs wantedPath string wantedErr error }{ "returns the correct env addon file path": { fName: "db.yml", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/environments/addons/db.yml", 0755) return fs }, wantedPath: "/copilot/environments/addons/db.yml", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: "/copilot", workingDirAbs: mockWorkingDirAbs, fs: &afero.Afero{ Fs: tc.fs(), }, } got := ws.EnvAddonFileAbsPath(tc.fName) require.Equal(t, tc.wantedPath, got) }) } } func TestWorkspace_WorkloadAddonsAbsPath(t *testing.T) { mockWorkingDirAbs := "/app" testCases := map[string]struct { fs func() afero.Fs wantedPath string }{ "returns the correct workload addons path": { fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/mockSvc/addons/", 0755) return fs }, wantedPath: "/copilot/mockSvc/addons", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: "/copilot/", workingDirAbs: mockWorkingDirAbs, fs: &afero.Afero{ Fs: tc.fs(), }, } got := ws.WorkloadAddonsAbsPath("mockSvc") require.Equal(t, tc.wantedPath, got) }) } } func TestWorkspace_WorkloadAddonFileAbsPath(t *testing.T) { mockWorkingDirAbs := "/app" testCases := map[string]struct { svc string fName string fs func() afero.Fs wantedPath string wantedErr error }{ "returns the correct env addon file path": { svc: "webhook", fName: "db.yml", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/webhook/addons/db.yml", 0755) return fs }, wantedPath: "/copilot/webhook/addons/db.yml", }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: "/copilot/", workingDirAbs: mockWorkingDirAbs, fs: &afero.Afero{ Fs: tc.fs(), }, } got := ws.WorkloadAddonFileAbsPath(tc.svc, tc.fName) require.Equal(t, tc.wantedPath, got) }) } } func TestWorkspace_ListFiles(t *testing.T) { testCases := map[string]struct { inDirPath string fs func() afero.Fs wantedFileNames []string wantedErr error }{ "dir not exist": { inDirPath: "/copilot/webhook/addons", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/webhook/", 0755) return fs }, wantedErr: &os.PathError{ Op: "open", Path: filepath.FromSlash("/copilot/webhook/addons"), Err: os.ErrNotExist, }, }, "retrieves file names": { inDirPath: "/copilot/webhook/addons", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/webhook/addons", 0755) params, _ := fs.Create("/copilot/webhook/addons/params.yml") outputs, _ := fs.Create("/copilot/webhook/addons/outputs.yml") defer params.Close() defer outputs.Close() return fs }, wantedFileNames: []string{"outputs.yml", "params.yml"}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN ws := &Workspace{ CopilotDirAbs: "copilot/", fs: &afero.Afero{ Fs: tc.fs(), }, } // WHEN actualFileNames, actualErr := ws.ListFiles(tc.inDirPath) // THEN require.Equal(t, tc.wantedErr, actualErr) require.Equal(t, tc.wantedFileNames, actualFileNames) }) } } func TestWorkspace_ReadFile(t *testing.T) { testCases := map[string]struct { fPath string fs func() afero.Fs wantedData []byte wantedErr error }{ "return error if file does not exist": { fPath: "/copilot/api/addons/db.yml", fs: func() afero.Fs { fs := afero.NewMemMapFs() return fs }, wantedErr: fmt.Errorf("file %s does not exists", filepath.FromSlash("/copilot/api/addons/db.yml")), }, "read existing file": { fPath: "/copilot/environments/addons/db.yml", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/environments/addons", 0755) f, _ := fs.Create("/copilot/environments/addons/db.yml") defer f.Close() f.Write([]byte("mydb")) return fs }, wantedData: []byte("mydb"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: "/copilot", fs: &afero.Afero{ Fs: tc.fs(), }, } data, err := ws.ReadFile(tc.fPath) if tc.wantedErr == nil { require.NoError(t, err) require.Equal(t, tc.wantedData, data) } else { require.EqualError(t, err, tc.wantedErr.Error()) } }) } } func TestWorkspace_Write(t *testing.T) { testCases := map[string]struct { marshaler mockBinaryMarshaler path string wantedPath string wantedErr error }{ "writes addons file with content": { marshaler: mockBinaryMarshaler{ content: []byte("hello"), }, path: filepath.FromSlash("webhook/addons/s3.yml"), wantedPath: filepath.FromSlash("/copilot/webhook/addons/s3.yml"), }, "wraps error if cannot marshal to binary": { marshaler: mockBinaryMarshaler{ err: errors.New("some error"), }, path: filepath.FromSlash("webhook/addons/s3.yml"), wantedErr: errors.New("marshal binary content: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN fs := afero.NewMemMapFs() utils := &afero.Afero{ Fs: fs, } utils.MkdirAll(filepath.Join("/", "copilot", "webhook"), 0755) ws := &Workspace{ workingDirAbs: "/", CopilotDirAbs: "/copilot", fs: utils, } // WHEN actualPath, actualErr := ws.Write(tc.marshaler, tc.path) // THEN if tc.wantedErr != nil { require.EqualError(t, actualErr, tc.wantedErr.Error(), "expected the same error") } else { require.Equal(t, tc.wantedPath, actualPath, "expected the same path") out, err := utils.ReadFile(tc.wantedPath) require.NoError(t, err) require.Equal(t, tc.marshaler.content, out, "expected the contents of the file to match") } }) } } func TestWorkspace_ReadWorkloadManifest(t *testing.T) { const ( mockCopilotDir = "/copilot" mockWorkloadName = "webhook" ) testCases := map[string]struct { elems []string mockFS func() afero.Fs wantedData WorkloadManifest wantedErr error wantedErrPrefix string }{ "return error if directory does not exist": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() return fs }, wantedErr: fmt.Errorf("file %s does not exists", filepath.FromSlash("/copilot/webhook/manifest.yml")), }, "fail to read name from manifest": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/webhook/", 0755) f, _ := fs.Create("/copilot/webhook/manifest.yml") defer f.Close() f.Write([]byte(`hello`)) return fs }, wantedErrPrefix: `unmarshal manifest file to retrieve "name"`, }, "name from manifest does not match with dir": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/webhook/", 0755) f, _ := fs.Create("/copilot/webhook/manifest.yml") defer f.Close() f.Write([]byte(`name: not-webhook`)) return fs }, wantedErr: errors.New(`name of the manifest "not-webhook" and directory "webhook" do not match`), }, "read existing file": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/webhook/", 0755) f, _ := fs.Create("/copilot/webhook/manifest.yml") defer f.Close() f.Write([]byte(`name: webhook type: Load Balanced Web Service flavor: vanilla`)) return fs }, wantedData: []byte(`name: webhook type: Load Balanced Web Service flavor: vanilla`), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: mockCopilotDir, fs: &afero.Afero{ Fs: tc.mockFS(), }, } data, err := ws.ReadWorkloadManifest(mockWorkloadName) if tc.wantedErr == nil && tc.wantedErrPrefix == "" { require.NoError(t, err) require.Equal(t, tc.wantedData, data) } if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } if tc.wantedErrPrefix != "" { require.ErrorContains(t, err, tc.wantedErrPrefix) } }) } } func TestWorkspace_ReadEnvironmentManifest(t *testing.T) { const mockEnvironmentName = "test" testCases := map[string]struct { elems []string mockFS func() afero.Fs wantedData EnvironmentManifest wantedErr error wantedErrPrefix string }{ "return error if directory does not exist": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() return fs }, wantedErr: fmt.Errorf("file %s does not exists", filepath.FromSlash("/copilot/environments/test/manifest.yml")), }, "fail to read name from manifest": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/environments/test/", 0755) f, _ := fs.Create("/copilot/environments/test/manifest.yml") defer f.Close() f.Write([]byte(`hello`)) return fs }, wantedErrPrefix: `unmarshal manifest file to retrieve "name"`, }, "name from manifest does not match with dir": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/environments/test", 0755) f, _ := fs.Create("/copilot/environments/test/manifest.yml") defer f.Close() f.Write([]byte(`name: not-test`)) return fs }, wantedErr: errors.New(`name of the manifest "not-test" and directory "test" do not match`), }, "type from manifest is not environment": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/environments/test", 0755) f, _ := fs.Create("/copilot/environments/test/manifest.yml") defer f.Close() f.Write([]byte(`name: test type: Load Balanced flavor: vanilla`)) return fs }, wantedErr: errors.New(`manifest test has type of "Load Balanced", not "Environment"`), }, "read existing file": { mockFS: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/environments/test/", 0755) f, _ := fs.Create("/copilot/environments/test/manifest.yml") defer f.Close() f.Write([]byte(`name: test type: Environment flavor: vanilla`)) return fs }, wantedData: []byte(`name: test type: Environment flavor: vanilla`), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: "/copilot", fs: &afero.Afero{ Fs: tc.mockFS(), }, } data, err := ws.ReadEnvironmentManifest(mockEnvironmentName) if tc.wantedErr == nil && tc.wantedErrPrefix == "" { require.NoError(t, err) require.Equal(t, tc.wantedData, data) } if tc.wantedErr != nil { require.EqualError(t, err, tc.wantedErr.Error()) } if tc.wantedErrPrefix != "" { require.ErrorContains(t, err, tc.wantedErrPrefix) } }) } } func TestWorkspace_ReadPipelineManifest(t *testing.T) { copilotDir := "/copilot" testCases := map[string]struct { fs func() afero.Fs expectedError error }{ "reads existing pipeline manifest": { fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll(copilotDir, 0755) manifest, _ := fs.Create("/copilot/pipelines/my-pipeline/manifest.yml") defer manifest.Close() manifest.Write([]byte(` name: somePipelineName version: 1 `)) return fs }, expectedError: nil, }, "when no pipeline file exists": { fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.Mkdir(copilotDir, 0755) return fs }, expectedError: ErrNoPipelineInWorkspace, }, "error unmarshaling pipeline manifest": { fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll(copilotDir, 0755) manifest, _ := fs.Create("/copilot/pipelines/my-pipeline/manifest.yml") defer manifest.Close() manifest.Write([]byte(` name: somePipelineName version: 0 `)) return fs }, expectedError: errors.New("unmarshal pipeline manifest: pipeline manifest contains invalid schema version: 0"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN fs := tc.fs() ws := &Workspace{ CopilotDirAbs: copilotDir, fs: &afero.Afero{Fs: fs}, } // WHEN _, err := ws.ReadPipelineManifest("/copilot/pipelines/my-pipeline/manifest.yml") // THEN if tc.expectedError != nil { require.Equal(t, tc.expectedError.Error(), err.Error()) } else { require.NoError(t, err) } }) } } func TestWorkspace_DeleteWorkspaceFile(t *testing.T) { testCases := map[string]struct { copilotDir string fs func() afero.Fs }{ ".workspace should be deleted": { copilotDir: "/path/to/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/path/to/copilot", 0755) fs.Create("/path/to/copilot/.workspace") return fs }, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN fs := tc.fs() ws := &Workspace{ CopilotDirAbs: tc.copilotDir, fs: &afero.Afero{ Fs: fs, }, } // WHEN err := ws.DeleteWorkspaceFile() // THEN require.NoError(t, err) // There should be no more .workspace file under the copilot/ directory. path := filepath.Join(tc.copilotDir, ".workspace") _, existErr := fs.Stat(path) expectedErr := &os.PathError{ Op: "open", Path: path, Err: os.ErrNotExist, } require.EqualError(t, existErr, expectedErr.Error()) }) } } func TestWorkspace_read(t *testing.T) { testCases := map[string]struct { elems []string copilotDir string fs func() afero.Fs wantedData []byte wantedErr error }{ "return error if file does not exist": { elems: []string{"webhook", "manifest.yml"}, copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() return fs }, wantedErr: fmt.Errorf("file %s does not exists", filepath.FromSlash("/copilot/webhook/manifest.yml")), }, "read existing file": { elems: []string{"webhook", "manifest.yml"}, copilotDir: "/copilot", fs: func() afero.Fs { fs := afero.NewMemMapFs() fs.MkdirAll("/copilot/webhook/", 0755) f, _ := fs.Create("/copilot/webhook/manifest.yml") defer f.Close() f.Write([]byte("hello")) return fs }, wantedData: []byte("hello"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { ws := &Workspace{ CopilotDirAbs: tc.copilotDir, fs: &afero.Afero{ Fs: tc.fs(), }, } data, err := ws.read(tc.elems...) if tc.wantedErr == nil { require.NoError(t, err) require.Equal(t, tc.wantedData, data) } else { require.EqualError(t, err, tc.wantedErr.Error()) } }) } } func TestWorkspace_write(t *testing.T) { testCases := map[string]struct { elems []string wantedPath string wantedErr error }{ "create file under nested directories": { elems: []string{"webhook", "addons", "policy.yml"}, wantedPath: filepath.FromSlash("/copilot/webhook/addons/policy.yml"), }, "create file under copilot directory": { elems: []string{legacyPipelineFileName}, wantedPath: filepath.FromSlash("/copilot/pipeline.yml"), }, "return ErrFileExists if file already exists": { elems: []string{"manifest.yml"}, wantedErr: &ErrFileExists{FileName: filepath.FromSlash("/copilot/manifest.yml")}, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN fs := afero.NewMemMapFs() utils := &afero.Afero{ Fs: fs, } utils.MkdirAll("/copilot", 0755) utils.WriteFile("/copilot/manifest.yml", []byte{}, 0644) ws := &Workspace{ workingDirAbs: "/", CopilotDirAbs: "/copilot", fs: utils, } // WHEN actualPath, actualErr := ws.write(nil, tc.elems...) // THEN if tc.wantedErr != nil { require.EqualError(t, actualErr, tc.wantedErr.Error(), "expected the same error") } else { require.Equal(t, tc.wantedPath, actualPath, "expected the same path") } }) } }
1,689
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package client import ( "fmt" "os" "os/exec" "path/filepath" "github.com/onsi/ginkgo/v2" "github.com/onsi/gomega/gexec" ) // NewCLI returns a wrapper around CLI. func NewCLI(path string) (*CLI, error) { // These tests should be run in a dockerfile so that // your file system and docker image repo isn't polluted // with test data and files. Since this is going to run // from Docker, the binary will be located in the root bin. cliPath := filepath.Join("/", "bin", "copilot") if os.Getenv("DRYRUN") == "true" { cliPath = filepath.Join("..", "..", "bin", "local", "copilot") } if path != "" { cliPath = path } if _, err := os.Stat(cliPath); err != nil { return nil, err } return &CLI{ path: cliPath, }, nil } // CLI is a wrapper around os.execs. type CLI struct { path string } // Run executes a command. func (cli *CLI) Run(commands ...string) (string, error) { return cli.exec(exec.Command(cli.path, commands...)) } func (cli *CLI) exec(command *exec.Cmd) (string, error) { // Turn off colors command.Env = append(os.Environ(), "COLOR=false", "CI=true") sess, err := gexec.Start(command, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter) if err != nil { return "", err } contents := sess.Wait(100000000).Out.Contents() if exitCode := sess.ExitCode(); exitCode != 0 { return string(sess.Err.Contents()), fmt.Errorf("received non 0 exit code") } return string(contents), nil }
62
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package client import ( "encoding/json" ) type wkldDescription struct { Name string `json:"name"` Type string `json:"type"` AppName string `json:"app"` } // SvcListOutput contains summaries of services. type SvcListOutput struct { Services []wkldDescription `json:"services"` } // ToSvcListOutput unmarshal a JSON string to a SvcListOutput struct. func ToSvcListOutput(jsonInput string) (*SvcListOutput, error) { var output SvcListOutput return &output, json.Unmarshal([]byte(jsonInput), &output) } // SvcShowOutput contains detailed information about a service. type SvcShowOutput struct { SvcName string `json:"service"` Type string `json:"type"` AppName string `json:"application"` Configs []svcShowConfigurations `json:"configurations"` ServiceDiscoveries []svcShowServiceDiscoveries `json:"serviceDiscovery"` Routes []svcShowRoutes `json:"routes"` Variables []svcShowVariables `json:"variables"` Resources map[string][]*svcShowResourceInfo `json:"resources"` } type svcShowConfigurations struct { Environment string `json:"environment"` Port string `json:"port"` Tasks string `json:"tasks"` CPU string `json:"cpu"` Memory string `json:"memory"` } type svcShowRoutes struct { Environment string `json:"environment"` URL string `json:"url"` } type svcShowServiceDiscoveries struct { Environment []string `json:"environment"` Namespace string `json:"namespace"` } type svcShowVariables struct { Environment string `json:"environment"` Name string `json:"name"` Value string `json:"value"` } type svcShowResourceInfo struct { Type string `json:"type"` PhysicalID string `json:"physicalID"` } // ToSvcShowOutput unmarshal a JSON string to a SvcShowOutput struct. func ToSvcShowOutput(jsonInput string) (*SvcShowOutput, error) { var output SvcShowOutput return &output, json.Unmarshal([]byte(jsonInput), &output) } // JobListOutput contains summaries of jobs. type JobListOutput struct { Jobs []wkldDescription `json:"jobs"` } // ToJobListOutput unmarshal a JSON string to a JobListOutput struct. func ToJobListOutput(jsonInput string) (*JobListOutput, error) { var output JobListOutput return &output, json.Unmarshal([]byte(jsonInput), &output) }
84
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package multi_svc_app_test import ( "fmt" "os" "testing" "time" "github.com/aws/copilot-cli/regression/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var ( toCLI *client.CLI fromCLI *client.CLI appName string ) // The Addons suite runs creates a new application with additional resources. func TestMultiSvcApp(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Regression For Multi Svc App Suite") } var _ = BeforeSuite(func() { var err error toCLI, err = client.NewCLI(os.Getenv("REGRESSION_TEST_TO_PATH")) Expect(err).NotTo(HaveOccurred()) fromCLI, err = client.NewCLI(os.Getenv("REGRESSION_TEST_FROM_PATH")) Expect(err).NotTo(HaveOccurred()) appName = fmt.Sprintf("regression-multisvcapp-%d", time.Now().Unix()) }) var _ = AfterSuite(func() { _, err := toCLI.Run("app", "delete", "--yes") Expect(err).NotTo(HaveOccurred()) })
46
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package multi_svc_app_test import ( "fmt" "net/http" "os" "io" "path/filepath" "github.com/aws/copilot-cli/regression/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("regression", func() { var cli *client.CLI var expectedWorkloadResponse = make(map[string]string) deployWorkloadSpecs := func() { var routeURLs = make(map[string]string) It("workload deploy should succeed", func() { for _, svcName := range []string{"front-end", "back-end", "www"} { _, err := cli.Run("svc", "deploy", "--name", svcName, "--env", "test", ) Expect(err).NotTo(HaveOccurred()) } _, jobDeployErr := cli.Run("job", "deploy", "--name", "query", "--env", "test", ) Expect(jobDeployErr).NotTo(HaveOccurred()) }) It("load-balanced web services should be able to make a GET request", func() { for _, svcName := range []string{"front-end", "www"} { out, err := cli.Run("svc", "show", "--app", appName, "--name", svcName, "--json") Expect(err).NotTo(HaveOccurred()) svc, err := client.ToSvcShowOutput(out) Expect(err).NotTo(HaveOccurred()) By("Having the correct number of routes in svc show") Expect(len(svc.Routes)).To(Equal(1)) route := svc.Routes[0] By("Having the correct environment associated with the route") Expect(route.Environment).To(Equal("test")) routeURLs[svcName] = route.URL By("Being able to make a GET request to the API") var resp *http.Response var fetchErr error Eventually(func() (int, error) { resp, fetchErr = http.Get(routeURLs[svcName]) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) By("Having their names as the value in response body") bodyBytes, err := io.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(string(bodyBytes)).To(Equal(expectedWorkloadResponse[svcName])) } }) It("service discovery should be enabled and working", func() { // The front-end service is set up to have a path called // "/front-end/service-discovery-test" - this route // calls a function which makes a call via the service // discovery endpoint, "back-end.local". If that back-end // call succeeds, the back-end returns a response // "back-end-service-discovery". This should be forwarded // back to us via the front-end api. // [test] -- http req -> [front-end] -- service-discovery -> [back-end] By("Being able to call the service discovery endpoint from front-end") url := routeURLs["front-end"] resp, fetchErr := http.Get(fmt.Sprintf("%s/service-discovery-test/", url)) Expect(fetchErr).NotTo(HaveOccurred()) Expect(resp.StatusCode).To(Equal(200)) By("Getting the expected response body") bodyBytes, err := io.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(string(bodyBytes)).To(Equal(expectedWorkloadResponse["back-end-service-discovery"])) }) It("job should have run", func() { // Job should have run. We check this by hitting the "job-checker" path, which tells us the value // of the "TEST_JOB_CHECK_VAR" in the frontend service, which will have been updated by a GET on // /job-setter Eventually(func() (string, error) { resp, fetchErr := http.Get(fmt.Sprintf("%s/job-checker/", routeURLs["front-end"])) if fetchErr != nil { return "", fetchErr } bodyBytes, err := io.ReadAll(resp.Body) if err != nil { return "", err } return string(bodyBytes), nil }, "4m", "10s").Should(Equal("yes")) // This is shorthand for "error is nil and resp is yes" }) } deployEnvironmentSpecs := func() { It("should succeed", func() { _, envDeployErr := cli.Run("env", "deploy", "--name", "test", "--app", appName, "--force", ) Expect(envDeployErr).NotTo(HaveOccurred()) }) } When("Using the old CLI", func() { BeforeEach(func() { cli = fromCLI expectedWorkloadResponse = map[string]string{ "front-end": "front-end", "www": "www", "back-end-service-discovery": "back-end-service-discovery", } }) When("Creating a new app", func() { It("app init succeeds", func() { _, initErr := cli.Run("app", "init", appName) Expect(initErr).NotTo(HaveOccurred()) }) It("app init creates an copilot directory and workspace file", func() { Expect("./copilot").Should(BeADirectory()) Expect("./copilot/.workspace").Should(BeAnExistingFile()) }) It("app ls includes new app", func() { Eventually(func() (string, error) { return cli.Run("app", "ls") }, "30s", "50s").Should(ContainSubstring(appName)) }) }) When("Adding a new environment", func() { It("should succeed", func() { _, testEnvInitErr := cli.Run("env", "init", "--name", "test", "--app", appName, "--profile", "default", "--default-config", ) Expect(testEnvInitErr).NotTo(HaveOccurred()) }) }) When("Deploying a new environment", deployEnvironmentSpecs) When("Adding workloads", func() { It("workload init should succeed", func() { _, err := cli.Run("svc", "init", "--name", "front-end", "--svc-type", "Load Balanced Web Service", "--dockerfile", fmt.Sprintf("./%s/Dockerfile", "front-end")) Expect(err).NotTo(HaveOccurred()) _, err = cli.Run("svc", "init", "--name", "www", "--svc-type", "Load Balanced Web Service", "--port", "80", "--dockerfile", fmt.Sprintf("./%s/Dockerfile", "www")) Expect(err).NotTo(HaveOccurred()) _, err = cli.Run("svc", "init", "--name", "back-end", "--svc-type", "Backend Service", "--port", "80", "--dockerfile", fmt.Sprintf("./%s/Dockerfile", "back-end")) Expect(err).NotTo(HaveOccurred()) _, err = cli.Run("job", "init", "--name", "query", "--schedule", "@every 1m", "--dockerfile", fmt.Sprintf("./%s/Dockerfile", "query")) Expect(err).NotTo(HaveOccurred()) }) It("workload init should create manifests", func() { Expect("./copilot/front-end/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/www/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/back-end/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/query/manifest.yml").Should(BeAnExistingFile()) }) It("workload ls should list the service", func() { out, err := cli.Run("svc", "ls", "--app", appName, "--json") Expect(err).NotTo(HaveOccurred()) svcList, err := client.ToSvcListOutput(out) Expect(err).NotTo(HaveOccurred()) out, err = cli.Run("job", "ls", "--app", appName, "--json") Expect(err).NotTo(HaveOccurred()) jobList, err := client.ToJobListOutput(out) Expect(err).NotTo(HaveOccurred()) By("Having an expected number of services or jobs") Expect(len(svcList.Services)).To(Equal(3)) Expect(len(jobList.Jobs)).To(Equal(1)) }) }) When("Deploying workloads", deployWorkloadSpecs) }) When("Updating application code", func() { It("should succeed", func() { files := make(map[string]string) for _, svcName := range []string{"front-end", "www", "back-end"} { files[filepath.Join(svcName, "main.go")] = filepath.Join(svcName, "swap", "main.go") } files[filepath.Join("query", "entrypoint.sh")] = filepath.Join("query", "swap", "entrypoint.sh") err := swapFiles(files) Expect(err).NotTo(HaveOccurred()) }) }) When("Using the new CLI", func() { BeforeEach(func() { cli = toCLI expectedWorkloadResponse = map[string]string{ "front-end": "front-end oraoraora", "www": "www oraoraora", "back-end-service-discovery": "back-end-service-discovery oraoraora", } }) When("Deploying workloads", deployWorkloadSpecs) When("Deploying the environment", deployEnvironmentSpecs) }) When("Swapping back the application code", func() { It("should succeed", func() { files := make(map[string]string) for _, svcName := range []string{"front-end", "www", "back-end"} { files[filepath.Join(svcName, "swap", "main.go")] = filepath.Join(svcName, "main.go") } files[filepath.Join("query", "swap", "entrypoint.sh")] = filepath.Join("query", "entrypoint.sh") _ = swapFiles(files) // Best-effort: do not consider the test suite fails if an error occurs. }) }) }) func swapFiles(files map[string]string) error { for fileA, fileB := range files { if err := os.Rename(fileA, fmt.Sprintf("%s.tmp", fileA)); err != nil { return err } if err := os.Rename(fileB, fileA); err != nil { return err } if err := os.Rename(fmt.Sprintf("%s.tmp", fileA), fileB); err != nil { return err } } return nil }
276
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "log" "net/http" "github.com/julienschmidt/httprouter" ) // HealthCheck just returns true if the service is up. func HealthCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("🚑 healthcheck ok!") w.WriteHeader(http.StatusOK) } // SimpleGet just returns true no matter what. func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("back-end")) } // ServiceDiscoveryGet just returns true no matter what. func ServiceDiscoveryGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get on ServiceDiscovery endpoint Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("back-end-service-discovery")) } func main() { router := httprouter.New() router.GET("/back-end/", SimpleGet) router.GET("/service-discovery/", ServiceDiscoveryGet) // Health Check router.GET("/", HealthCheck) log.Fatal(http.ListenAndServe(":80", router)) }
43
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "log" "net/http" "github.com/julienschmidt/httprouter" ) // HealthCheck just returns true if the service is up. func HealthCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("🚑 healthcheck ok!") w.WriteHeader(http.StatusOK) } // SimpleGet just returns true no matter what. func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("back-end oraoraora")) // NOTE: response body appended with "oraoraora" } // ServiceDiscoveryGet just returns true no matter what. func ServiceDiscoveryGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get on ServiceDiscovery endpoint Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("back-end-service-discovery oraoraora")) // NOTE: response body appended with "oraoraora" } func main() { router := httprouter.New() router.GET("/back-end/", SimpleGet) router.GET("/service-discovery/", ServiceDiscoveryGet) // Health Check router.GET("/", HealthCheck) log.Fatal(http.ListenAndServe(":80", router)) }
43
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "github.com/julienschmidt/httprouter" ) // SimpleGet just returns true no matter what. func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("front-end")) } // ServiceDiscoveryGet calls the back-end service, via service-discovery. // This call should succeed and return the value from the backend service. // This test assumes the backend app is called "back-end". The 'service-discovery' endpoint // of the back-end service is unreachable from the LB, so the only way to get it is // through service discovery. The response should be `back-end-service-discovery` func ServiceDiscoveryGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { endpoint := fmt.Sprintf("http://back-end.%s/service-discovery/", os.Getenv("COPILOT_SERVICE_DISCOVERY_ENDPOINT")) resp, err := http.Get(endpoint) if err != nil { log.Printf("🚨 could call service discovery endpoint: err=%s\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Println("Get on ServiceDiscovery endpoint Succeeded") defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) w.WriteHeader(http.StatusOK) w.Write(body) } // GetJobCheck returns the value of the environment variable TEST_JOB_CHECK_VAR. func GetJobCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get /job-checker/ succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte(os.Getenv("TEST_JOB_CHECK_VAR"))) } // SetJobCheck updates the environment variable TEST_JOB_CHECK_VAR in the container to "yes" func SetJobCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get /job-setter/ succeeded") err := os.Setenv("TEST_JOB_CHECK_VAR", "yes") if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func main() { router := httprouter.New() router.GET("/", SimpleGet) router.GET("/service-discovery-test", ServiceDiscoveryGet) router.GET("/job-checker/", GetJobCheck) router.GET("/job-setter/", SetJobCheck) log.Println("Listening on port 80...") log.Fatal(http.ListenAndServe(":80", router)) }
71
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "github.com/julienschmidt/httprouter" ) // SimpleGet just returns true no matter what. func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("front-end oraoraora")) // NOTE: The response body has "oraoraora" appended } // ServiceDiscoveryGet calls the back-end service, via service-discovery. // This call should succeed and return the value from the backend service. // This test assumes the backend app is called "back-end". The 'service-discovery' endpoint // of the back-end service is unreachable from the LB, so the only way to get it is // through service discovery. The response should be `back-end-service-discovery` func ServiceDiscoveryGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { endpoint := fmt.Sprintf("http://back-end.%s/service-discovery/", os.Getenv("COPILOT_SERVICE_DISCOVERY_ENDPOINT")) resp, err := http.Get(endpoint) if err != nil { log.Printf("🚨 could call service discovery endpoint: err=%s\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Println("Get on ServiceDiscovery endpoint Succeeded") defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) w.WriteHeader(http.StatusOK) w.Write(body) } // GetJobCheck returns the value of the environment variable TEST_JOB_CHECK_VAR. func GetJobCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get /job-checker/ succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte(os.Getenv("TEST_JOB_CHECK_VAR"))) } // SetJobCheck updates the environment variable TEST_JOB_CHECK_VAR in the container to "yes" func SetJobCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get /job-setter/ succeeded") err := os.Setenv("TEST_JOB_CHECK_VAR", "yes") if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func main() { router := httprouter.New() router.GET("/", SimpleGet) router.GET("/service-discovery-test", ServiceDiscoveryGet) router.GET("/job-checker/", GetJobCheck) router.GET("/oraoraora-setter/", SetJobCheck) // NOTE: "oraoraora-setter" replaces "job-setter log.Println("Listening on port 80...") log.Fatal(http.ListenAndServe(":80", router)) }
71
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "log" "net/http" "github.com/julienschmidt/httprouter" ) // SimpleGet just returns true no matter what. func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("www")) } func healthCheckHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Health Check Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("www")) } func main() { router := httprouter.New() router.GET("/", healthCheckHandler) router.GET("/www/", SimpleGet) log.Fatal(http.ListenAndServe(":80", router)) }
32
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "log" "net/http" "github.com/julienschmidt/httprouter" ) // SimpleGet just returns true no matter what. func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Get Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("www oraoraora")) // The response is different now. } func healthCheckHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { log.Println("Health Check Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte("www")) } func main() { router := httprouter.New() router.GET("/", healthCheckHandler) router.GET("/www/", SimpleGet) log.Fatal(http.ListenAndServe(":80", router)) }
32
ec2-macos-init
aws
Go
package main import ( "flag" "os" "path/filepath" "github.com/aws/ec2-macos-init/internal/paths" "github.com/aws/ec2-macos-init/lib/ec2macosinit" ) // clean removes old instance history. It has two options: // current - This is the option when -all isn't provided. It only removes the current instance's history. // all - When -all is provided, all instance history is removed. func clean(baseDir string, c *ec2macosinit.InitConfig) { // Define flags cleanFlags := flag.NewFlagSet("clean", flag.ExitOnError) cleanAll := cleanFlags.Bool("all", false, "Optional; Remove all instance history. Default is false.") // Parse flags err := cleanFlags.Parse(os.Args[2:]) if err != nil { c.Log.Fatalf(64, "Unable to parse arguments: %s", err) } // Clean all or clean the current instance historyPath := paths.AllInstancesHistory(baseDir) if *cleanAll { c.Log.Info("Removing all instance history") // Read instance history directory dir, err := os.ReadDir(historyPath) if err != nil { c.Log.Fatalf(66, "Unable to read instance history located at %s: %s", historyPath, err) } for _, d := range dir { // Remove everything err := os.RemoveAll(filepath.Join(historyPath, d.Name())) if err != nil { c.Log.Fatalf(1, "Unable to remove instance history: %s", err) } } } else { c.Log.Infof("Getting current instance ID from IMDS") // Instance ID is needed, run setup err = SetupInstanceID(c) if err != nil { c.Log.Fatalf(75, "Unable to get instance ID: %s", err) } c.Log.Infof("Removing history for the current instance [%s]", c.IMDS.InstanceID) // Remove current instance history err := os.RemoveAll(paths.InstanceHistory(baseDir, c.IMDS.InstanceID)) if err != nil { c.Log.Fatalf(1, "Unable to remove instance history: %s", err) } } c.Log.Info("Clean complete") }
59
ec2-macos-init
aws
Go
package main import ( "fmt" "log" "os" "path/filepath" "runtime" "github.com/aws/ec2-macos-init/internal/paths" "github.com/aws/ec2-macos-init/lib/ec2macosinit" ) const ( loggingTag = "ec2-macOS-init" ) func main() { const baseDir = paths.DefaultBaseDirectory // Set up logging logger, err := ec2macosinit.NewLogger(loggingTag, true, true) if err != nil { log.Fatalf("Unable to start logging: %s", err) } // Check runtime OS if !(runtime.GOOS == "darwin") { logger.Fatal(1, "Can only be run from macOS!") } // Check that this is being run by a user with root permissions if !runningAsRoot() { logger.Fatal(64, "Must be run with root permissions!") } // Check for no command if len(os.Args) < 2 { logger.Info("Must provide a command!") printUsage(baseDir) os.Exit(2) } // Setup InitConfig config := &ec2macosinit.InitConfig{ HistoryPath: paths.AllInstancesHistory(baseDir), HistoryFilename: paths.HistoryJSON, Log: logger, } // Command switch switch command := os.Args[1]; command { case "run": run(baseDir, config) case "clean": clean(baseDir, config) case "version": printVersion() os.Exit(0) default: logger.Errorf("%s is not a valid command", command) printUsage(baseDir) os.Exit(2) } } // printUsage prints the help text for this program. func printUsage(baseDir string) { fmt.Println("Usage: ec2-macos-init <command> <arguments>") fmt.Println("Commands are:") fmt.Println(" run - Run init using configuration located in " + filepath.Join(baseDir, paths.InitTOML)) fmt.Println(" clean - Remove instance history from disk") fmt.Println(" version - Print version information") fmt.Println("For more help: ec2-macos-init <command> -h") } // runningAsRoot checks to see if the init application is being run as // root. func runningAsRoot() bool { // must effectively be root return os.Geteuid() == 0 }
83
ec2-macos-init
aws
Go
package main import ( "errors" "fmt" "path/filepath" "sync" "time" "github.com/aws/ec2-macos-init/internal/paths" "github.com/aws/ec2-macos-init/lib/ec2macosinit" ) // run is the main runner for ec2-macOS-init. It handles orchestration of the following major pieces: // 1. Setup instance ID - IMDS must be up and provide an instance ID for later parts of run to work. // 2. Read init config - Read the init.toml configuration file into the application. // 3. Validate init config and identify modules - The config then undergoes basic validation and modules are identified. // 4. Prioritize modules - Modules are sorted by priority into a 2D slice of modules to be run in the correct order later. // 5. Read instance run history - The history of prior runs is read into the application for comparison of Run type settings. // 6. Process each module by priority level - All modules are run in priority groups. Each module in a priority level // is started in its own goroutine and the group waits for everything in that group to finish. If any module in that // group fails and has FatalOnError set, the entire application exits early. // 7. Write history file - After any run, a history.json file is written to the instance history directory for future runs. func run(baseDir string, c *ec2macosinit.InitConfig) { c.Log.Info("Fetching instance ID from IMDS...") // An instance ID from IMDS is a prerequisite for run() to be able to check instance history err := SetupInstanceID(c) if err != nil { c.Log.Fatalf(computeExitCode(c, 1), "Unable to get instance ID: %s", err) } c.Log.Infof("Running on instance %s", c.IMDS.InstanceID) // Mark start time startTime := time.Now() // Read init config c.Log.Info("Reading init config...") err = c.ReadConfig(filepath.Join(baseDir, paths.InitTOML)) if err != nil { c.Log.Fatalf(computeExitCode(c, 66), "Error while reading init config file: %s", err) } c.Log.Info("Successfully read init config") // Validate init config and identify modules c.Log.Info("Validating config...") err = c.ValidateAndIdentify() if err != nil { c.Log.Fatalf(computeExitCode(c, 65), "Error found during init config validation: %s", err) } c.Log.Info("Successfully validated config") // Prioritize modules c.Log.Info("Prioritizing modules...") err = c.PrioritizeModules() if err != nil { c.Log.Fatalf(computeExitCode(c, 1), "Error preparing and identifying modules: %s", err) } c.Log.Info("Successfully prioritized modules") // Create instance history directories c.Log.Info("Creating instance history directories for current instance...") err = c.CreateDirectories() if err != nil { c.Log.Fatalf(computeExitCode(c, 73), "Error creating instance history directories: %s", err) } c.Log.Info("Successfully created directories") // Read instance run history c.Log.Info("Getting instance history...") err = c.GetInstanceHistory() if err != nil { var herr ec2macosinit.HistoryError // If GetInstanceHistory() returns a HistoryError, there was invalid JSON in the history file // Catch this specific error to inform the user of the error and provide a way to remediate it. if errors.As(err, &herr) { c.Log.Warn("There was an error getting instance history") c.Log.Info("The history JSON files might be invalid and need to be restored or removed.") c.Log.Info("Run 'sudo ec2-macos-init clean' to remove all history files.") } c.Log.Fatalf(computeExitCode(c, 1), "Error getting instance history: %s", err) } c.Log.Info("Successfully gathered instance history") // Process each module by priority level var aggregateFatal bool var aggFatalModuleName string for i := 0; i < len(c.ModulesByPriority); i++ { c.Log.Infof("Processing priority level %d (%d modules)...\n", i+1, len(c.ModulesByPriority[i])) wg := sync.WaitGroup{} // Start every module within the priority level group for j := 0; j < len(c.ModulesByPriority[i]); j++ { wg.Add(1) go func(m *ec2macosinit.Module, h *[]ec2macosinit.History) { // Run module if it should be run if m.ShouldRun(c.IMDS.InstanceID, *h) { c.Log.Infof("Running module [%s] (type: %s, group: %d)\n", m.Name, m.Type, m.PriorityGroup) ctx := &ec2macosinit.ModuleContext{ Logger: c.Log, IMDS: &c.IMDS, BaseDirectory: baseDir, } // Run appropriate module var message string var err error switch t := m.Type; t { case "command": message, err = m.CommandModule.Do(ctx) case "motd": message, err = m.MOTDModule.Do(ctx) case "sshkeys": message, err = m.SSHKeysModule.Do(ctx) case "userdata": message, err = m.UserDataModule.Do(ctx) case "networkcheck": message, err = m.NetworkCheckModule.Do(ctx) case "systemconfig": message, err = m.SystemConfigModule.Do(ctx) case "usermanagement": message, err = m.UserManagementModule.Do(ctx) default: message = "unknown module type" err = fmt.Errorf("unknown module type") } if err != nil { c.Log.Infof("Error while running module [%s] (type: %s, group: %d) with message: %s and err: %s\n", m.Name, m.Type, m.PriorityGroup, message, err) if m.FatalOnError { aggregateFatal = true aggFatalModuleName = m.Name } } else { // Module was successfully completed m.Success = true c.Log.Infof("Successfully completed module [%s] (type: %s, group: %d) with message: %s\n", m.Name, m.Type, m.PriorityGroup, message) } } else { // In the case that we choose not to run a module, it is because the module has already succeeded // in a prior run. For this reason, we need to pass through the success of the module to history. m.Success = true c.Log.Infof("Skipping module [%s] (type: %s, group: %d) due to Run type setting\n", m.Name, m.Type, m.PriorityGroup) } wg.Done() }(&c.ModulesByPriority[i][j], &c.InstanceHistory) } wg.Wait() c.Log.Infof("Successfully completed processing of priority level %d\n", i+1) // If any module failed which had FatalOnError set, trigger an aggregate fail if aggregateFatal { break } } // Write history file c.Log.Infof("Writing instance history for instance %s...", c.IMDS.InstanceID) err = c.WriteHistoryFile() if err != nil { c.Log.Fatalf(computeExitCode(c, 73), "Error writing instance history file: %s", err) } c.Log.Info("Successfully wrote instance history") // If any module triggered an aggregate fatal, exit 1 if aggregateFatal { c.Log.Fatalf(computeExitCode(c, 1), "Exiting after %s due to failure in module [%s] with FatalOnError set", time.Since(startTime).String(), aggFatalModuleName) } // Log completion and total run time c.Log.Infof("EC2 macOS Init completed in %s", time.Since(startTime).String()) } // computeExitCode checks to see if the number of fatal retries has been exceeded. If not, it increments the counter, // stored in a temporary file, and returns the requested exit code. If the count is exceeded, it returns 0 to avoid // launchd restarting forever due to the KeepAlive setting. func computeExitCode(c *ec2macosinit.InitConfig, e int) (exitCode int) { // Check if other runs have happened this boot and return data about them exceeded, err := c.RetriesExceeded() if err != nil { c.Log.Errorf("Error while getting retry information: %s", err) return 1 } // If the count has exceed the limit, return 0 if exceeded { c.Log.Errorf("Number of fatal retries (%d) exceeded, exiting 0 to avoid infinite runs", c.FatalCounts.Count) return 0 } c.Log.Infof("Fatal [%d/%d] of this boot", c.FatalCounts.Count, ec2macosinit.PerBootFatalLimit) // Increment the counter in the temporary file before returning err = c.FatalCounts.IncrementFatalCount() if err != nil { c.Log.Errorf("Unable to write fatal counts to file: %s", err) } // Return the requested exit code return e }
199
ec2-macos-init
aws
Go
package main import ( "fmt" "math" "time" "github.com/aws/ec2-macos-init/lib/ec2macosinit" ) const ( attemptInterval = 1 // every 1s logInterval = 10.0 // every 10s setupMaxAttempts = 600 // fail after 10m ) // SetupInstanceID is used to setup the instance ID (and IMDSv2 token) the first time. It retries at a fixed interval // up to the maximum number of attempts. This is expected to fail many times on first boot when this runs before // networking is fully up. func SetupInstanceID(c *ec2macosinit.InitConfig) (err error) { var attempt int // While instance ID is empty for c.IMDS.InstanceID == "" { // Attempt to get the instance ID err = c.IMDS.UpdateInstanceID() if err != nil { // Fail out if attempts exceeds maximum if attempt > setupMaxAttempts { return fmt.Errorf("error getting instance ID from IMDS: %s\n", err) } // Log according to the log interval if math.Mod(float64(attempt), logInterval) == 0.0 { c.Log.Warnf("Unable to get instance ID - IMDS may not be available yet...retrying every %ds [%d/%d]", attemptInterval, attempt, setupMaxAttempts) } attempt++ // increment attempts // Sleep for attempt interval time.Sleep(attemptInterval * time.Second) } } return nil }
46
ec2-macos-init
aws
Go
package main import "fmt" var ( // CommitDate is the date of the commit used at build time. CommitDate string // Version is the ec2-macos-init release version for this build. Version string = "0.0.0-dev" ) // printVersion prints the output for the version command. func printVersion() { const gitHubLink = "https://github.com/aws/ec2-macos-init" fmt.Printf("\nEC2 macOS Init\n"+ "Version: %s [%s]\n"+ "%s\n"+ "Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n", Version, CommitDate, gitHubLink, ) }
23
ec2-macos-init
aws
Go
package paths import "path/filepath" const ( // DefaultBaseDirectory is the root directory in which other paths are based upon. DefaultBaseDirectory = "/usr/local/aws/ec2-macos-init" ) const ( // InitTOML is the filename of the configuration for ec2-macos-init. InitTOML = "init.toml" // HistoryJSON is the filename of the per-instance persisted history state, // used to store on disk. HistoryJSON = "history.json" ) const ( // instancesHistoryDirname is the name of the directory under which history // files are stored. See path builders below for usages. instancesHistoryDirname = "instances" ) // AllInstancesHistory returns the path where all instances' history is, // relative to given base directory. func AllInstancesHistory(base string) string { return filepath.Join(base, instancesHistoryDirname) } // InstanceHistory returns the path where the *specified* instance (given by its // instance ID) is. func InstanceHistory(base string, instanceID string) string { return filepath.Join(base, instancesHistoryDirname, instanceID) }
35
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "strings" ) // CommandModule contains contains all necessary configuration fields for running a Command module. type CommandModule struct { Cmd []string `toml:"Cmd"` RunAsUser string `toml:"RunAsUser"` EnvironmentVars []string `toml:"EnvironmentVars"` } // Do for CommandModule runs a command with the values set in the config file. func (c *CommandModule) Do(ctx *ModuleContext) (message string, err error) { out, err := executeCommand(c.Cmd, c.RunAsUser, c.EnvironmentVars) if err != nil { return "", fmt.Errorf("ec2macosinit: error executing command [%s] with stdout [%s] and stderr [%s]: %s", c.Cmd, strings.TrimSuffix(out.stdout, "\n"), strings.TrimSuffix(out.stderr, "\n"), err) } return fmt.Sprintf("successfully ran command [%s] with stdout [%s] and stderr [%s]", c.Cmd, strings.TrimSuffix(out.stdout, "\n"), strings.TrimSuffix(out.stderr, "\n")), nil }
25
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "os" "github.com/BurntSushi/toml" ) // InitConfig contains all fields expected from an init.toml file as well as things shared by all parts // of the application. type InitConfig struct { HistoryFilename string HistoryPath string IMDS IMDSConfig InstanceHistory []History Log *Logger Modules []Module `toml:"Module"` ModulesByPriority [][]Module FatalCounts FatalCount } // Number of runs resulting in fatal exits in a single boot before giving up const PerBootFatalLimit = 100 // ReadConfig reads the configuration file and decodes it into the InitConfig struct. func (c *InitConfig) ReadConfig(fileLocation string) (err error) { // Read file rawConfig, err := os.ReadFile(fileLocation) if err != nil { return fmt.Errorf("ec2macosinit: error reading config file located at %s: %s\n", fileLocation, err) } // Decode from TOML to InitConfig struct _, err = toml.Decode(string(rawConfig), c) if err != nil { return fmt.Errorf("ec2macosinit: error decoding config: %s\n", err) } return nil } // ValidateConfig validates all modules and identifies type. func (c *InitConfig) ValidateAndIdentify() (err error) { // Create keySet to store used keys keySet := map[string]struct{}{} // Loop through every module and check a few things... for i := 0; i < len(c.Modules); i++ { // Identify module type err := c.Modules[i].identifyModule() if err != nil { return fmt.Errorf("ec2macosinit: error while identifying module: %s\n", err) } // Validate individual module err = c.Modules[i].validateModule() if err != nil { return fmt.Errorf("ec2macosinit: error found in module (type: %s, priority: %d): %s\n", c.Modules[i].Type, c.Modules[i].PriorityGroup, err) } // Check that key name is unique for the current configuration if _, ok := keySet[c.Modules[i].Name]; !ok { // Key hasn't been used yet - add key to the set keySet[c.Modules[i].Name] = struct{}{} } else { return fmt.Errorf("ec2macosinit: duplicate name found in config:%s\n", c.Modules[i].Name) } } return nil } // PrepareModules takes all modules and sorts them according to priority into the ModulesByPriority slice. func (c *InitConfig) PrioritizeModules() (err error) { for _, m := range c.Modules { // Expand capacity of ModulesByPriority, as needed for m.PriorityGroup > cap(c.ModulesByPriority) { c.ModulesByPriority = append(c.ModulesByPriority, []Module{}) } // If needed, expand ModulesByPriority to needed length if m.PriorityGroup > len(c.ModulesByPriority) { c.ModulesByPriority = c.ModulesByPriority[:m.PriorityGroup] } // Append module at correct priority level c.ModulesByPriority[m.PriorityGroup-1] = append(c.ModulesByPriority[m.PriorityGroup-1], m) } return nil } // RetriesExceeded checks if the number of previous fatal exits exceeds the limit. func (c *InitConfig) RetriesExceeded() (exceeded bool, err error) { // Check for the existence of the temporary file and get the current fatal count err = c.FatalCounts.readFatalCount() if err != nil { return false, fmt.Errorf("ec2macosinit: unable to read fatal counts: %s", err) } // If there have been more than the limit of fatal exits, return true if c.FatalCounts.Count > PerBootFatalLimit { return true, nil } // Otherwise, continue return false, nil }
106
ec2-macos-init
aws
Go
package ec2macosinit import ( "encoding/json" "fmt" "os" ) // FatalCount contains a Count for tracking the number of Fatal exits for this boot type FatalCount struct { Count int `json:"count"` } // fatalCountFile is the file that contains the fatal counter, this is cleared on reboot const fatalCountFile = "/tmp/.ec2-macos-init-fatal-counts.json" // readFatalCount reads the file contents into FatalCount or returns an initialized counter. func (r *FatalCount) readFatalCount() (err error) { // Check if fatal count file exists, if not, create it but leave it empty, then return 0, otherwise read and return _, err = os.Stat(fatalCountFile) if !os.IsNotExist(err) { err = r.readFatalFile() if err != nil { return fmt.Errorf("ec2macosinit: Failed to read %s: %s", fatalCountFile, err) } } else { // Take initial values for first run *r = FatalCount{1} } return nil } // IncrementFatalCount takes the current count, increments it, and saves to the temporary file. func (r *FatalCount) IncrementFatalCount() (err error) { // Get the current count err = r.readFatalCount() if err != nil { return fmt.Errorf("ec2macosinit: unable to read run count file: %s", err) } r.Count++ // Increment the counter in the struct // Marshall the FatalCount struct to json rcBytes, err := json.Marshal(r) if err != nil { return fmt.Errorf("ec2macosinit: failed to save run counts: %s", err) } // Write the bytes to the counter file err = os.WriteFile(fatalCountFile, rcBytes, 0644) if err != nil { return fmt.Errorf("ec2macosinit: failed to save run counts: %s", err) } return nil } // readFatalFile reads the temporary file for count. func (r *FatalCount) readFatalFile() (err error) { // Read the contents into bytes countsBytes, err := os.ReadFile(fatalCountFile) if err != nil { return fmt.Errorf("ec2macosinit: Failed to read %s: %s", fatalCountFile, err) } // Unmarshal to the struct err = json.Unmarshal(countsBytes, &r) if err != nil { return fmt.Errorf("ec2macosinit: Failed to parse json: %s", err) } return nil }
75
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "net/http" "strconv" ) const ( imdsBase = "http://169.254.169.254/latest/" imdsTokenTTL = 21600 tokenEndpoint = "api/token" tokenRequestTTLHeader = "X-aws-ec2-metadata-token-ttl-seconds" tokenHeader = "X-aws-ec2-metadata-token" ) // IMDS config contains the current instance ID and a place for the IMDSv2 token to be stored. // Using IMDSv2: // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#instance-metadata-v2-how-it-works type IMDSConfig struct { token string InstanceID string } // getIMDSProperty gets a given endpoint property from IMDS. func (i *IMDSConfig) getIMDSProperty(endpoint string) (value string, httpResponseCode int, err error) { // Check that an IMDSv2 token exists - get one if it doesn't if i.token == "" { err = i.getNewToken() if err != nil { return "", 0, fmt.Errorf("ec2macosinit: error while getting new IMDS token: %s\n", err) } } // Create request client := &http.Client{} req, err := http.NewRequest(http.MethodGet, imdsBase+endpoint, nil) if err != nil { return "", 0, fmt.Errorf("ec2macosinit: error while creating new HTTP request: %s\n", err) } req.Header.Set(tokenHeader, i.token) // set IMDSv2 token // Make request resp, err := client.Do(req) if err != nil { return "", 0, fmt.Errorf("ec2macosinit: error while requesting IMDS property: %s\n", err) } // Convert returned io.ReadCloser to string value, err = ioReadCloserToString(resp.Body) if err != nil { return "", 0, fmt.Errorf("ec2macosinit: error reading response body: %s\n", err) } return value, resp.StatusCode, nil } // getNewToken gets a new IMDSv2 token from the IMDS API. func (i *IMDSConfig) getNewToken() (err error) { // Create request client := &http.Client{} req, err := http.NewRequest(http.MethodPut, imdsBase+tokenEndpoint, nil) if err != nil { return fmt.Errorf("ec2macosinit: error while creating new HTTP request: %s\n", err) } req.Header.Set(tokenRequestTTLHeader, strconv.FormatInt(int64(imdsTokenTTL), 10)) // Make request resp, err := client.Do(req) if err != nil { return fmt.Errorf("ec2macosinit: error while requesting new token: %s\n", err) } // Validate response code if resp.StatusCode != 200 { return fmt.Errorf("ec2macosinit: received a non-200 status code from IMDS: %d - %s\n", resp.StatusCode, resp.Status, ) } // Set returned value i.token, err = ioReadCloserToString(resp.Body) if err != nil { return fmt.Errorf("ec2macosinit: error reading response body: %s\n", err) } return nil } // UpdateInstanceID is a wrapper for getIMDSProperty that gets the current instance ID for the attached config. func (i *IMDSConfig) UpdateInstanceID() (err error) { // If instance ID is already set, this doesn't need to be run if i.InstanceID != "" { return nil } // Get IMDS property "meta-data/instance-id" i.InstanceID, _, err = i.getIMDSProperty("meta-data/instance-id") if err != nil { return fmt.Errorf("ec2macosinit: error getting instance ID from IMDS: %s\n", err) } // Validate that an ID was returned if i.InstanceID == "" { return fmt.Errorf("ec2macosinit: an empty instance ID was returned from IMDS\n") } return nil }
111
ec2-macos-init
aws
Go
package ec2macosinit import ( "encoding/json" "fmt" "os" "path/filepath" "time" ) // This is unused for now but will allow us to modify the version of this history in the future. const historyVersion = 1 // History contains an instance ID, run time and a slice of individual module histories. type History struct { InstanceID string `json:"instanceID"` RunTime time.Time `json:"runTime"` ModuleHistories []ModuleHistory `json:"moduleHistory"` Version int `json:"version"` } // ModuleHistory contains a key of the configuration struct for future comparison and whether that run was successful. type ModuleHistory struct { Key string `json:"key"` Success bool `json:"success"` } // HistoryError wraps a normal error and gives the caller insight into the type of error. // The caller can check the type of error and handle different types of error differently. // Currently HistoryError only handles errors for invalid JSON but the struct is flexible // and can be adjusted to handle several different errors differently. type HistoryError struct { err error } func (h HistoryError) Unwrap() error { return h.err } func (h HistoryError) Error() string { return h.err.Error() } // GetInstanceHistory takes a path to instance history directory and a file name for history files and searches for // any files that match. Then, for each file, it calls readHistoryFile() to read the file and add it to the // InstanceHistory struct. func (c *InitConfig) GetInstanceHistory() (err error) { // Read instance history directory dirs, err := os.ReadDir(c.HistoryPath) if err != nil { return fmt.Errorf("ec2macosinit: unable to read instance history directory: %w", err) } // For each directory, check for a history file and call readHistoryFile() for _, dir := range dirs { if dir.IsDir() { historyFile := filepath.Join(c.HistoryPath, dir.Name(), c.HistoryFilename) if info, err := os.Stat(historyFile); err == nil { // Check to make sure info is a file and not a directory. if !info.Mode().IsRegular() { continue } // If there is an error getting the history file or if the history file is empty do not append to Instance History if info.Size() == 0 { c.Log.Warnf("The history file exists at %s but is empty. Skipping this file...", historyFile) continue } history, err := readHistoryFile(historyFile) if err != nil { return fmt.Errorf("ec2macosinit: error while reading history file at %s: %w", historyFile, err) } // Append the returned History struct to the InstanceHistory slice c.InstanceHistory = append(c.InstanceHistory, history) } } } return nil } // readHistoryFile takes an instance history file and returns a History struct containing the same information. func readHistoryFile(file string) (history History, err error) { // Read file historyBytes, err := os.ReadFile(file) if err != nil { return History{}, fmt.Errorf("ec2macosinit: error reading config file located at %s: %w", file, err) } // Unmarshal to struct err = json.Unmarshal(historyBytes, &history) if err != nil { return History{}, HistoryError{err: err} } return history, nil } // WriteHistoryFile takes ModulesByPriority and writes it to a given history path and filename as JSON. func (c *InitConfig) WriteHistoryFile() (err error) { history := History{ InstanceID: c.IMDS.InstanceID, RunTime: time.Now(), Version: historyVersion, } // Copy relevant fields from InitConfig to History struct for _, p := range c.ModulesByPriority { for _, m := range p { history.ModuleHistories = append( history.ModuleHistories, ModuleHistory{ Key: m.generateHistoryKey(), Success: m.Success, }, ) } } // Marshal to JSON historyBytes, err := json.Marshal(history) if err != nil { return fmt.Errorf("ec2macosinit: unable to write history file: %w", err) } // Ensure the path exists and create it if it doesn't err = c.CreateDirectories() if err != nil { return fmt.Errorf("ec2macosinit: unable to write history file: :%w", err) } // Write history JSON file path := filepath.Join(c.HistoryPath, c.IMDS.InstanceID, c.HistoryFilename) err = safeWrite(path, historyBytes) if err != nil { return fmt.Errorf("ec2macosinit: unable to write history file: %w", err) } return nil } // safeWrite writes data to the desired file path or not at all. This function // protects against partially written or unflushed data intended for the file. func safeWrite(path string, data []byte) error { f, err := os.CreateTemp(filepath.Dir(path), fmt.Sprintf(".%s.*", filepath.Base(path))) if err != nil { return err } defer os.Remove(f.Name()) defer f.Close() _, err = f.Write(data) if err != nil { return err } err = f.Sync() if err != nil { return err } return os.Rename(f.Name(), path) } // CreateDirectories creates the instance directory, if it doesn't exist and a directory for the running instance. func (c *InitConfig) CreateDirectories() (err error) { if _, err := os.Stat(filepath.Join(c.HistoryPath, c.IMDS.InstanceID)); os.IsNotExist(err) { err := os.MkdirAll(filepath.Join(c.HistoryPath, c.IMDS.InstanceID), 0755) if err != nil { return fmt.Errorf("ec2macosinit: unable to create directory: %w", err) } } return nil }
172
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "log" "log/syslog" "os" ) // Logger contains booleans for where to log, a tag used in syslog and the syslog Writer itself. type Logger struct { LogToStdout bool LogToSystemLog bool Tag string SystemLog *syslog.Writer } // NewLogger creates a new logger. Logger writes using the LOG_LOCAL0 facility by default if system logging is enabled. func NewLogger(tag string, systemLog bool, stdout bool) (logger *Logger, err error) { // Set up system logging, if enabled syslogger := &syslog.Writer{} if systemLog { syslogger, err = syslog.New(syslog.LOG_LOCAL0, tag) if err != nil { return &Logger{}, fmt.Errorf("ec2macosinit: unable to create new syslog logger: %s\n", err) } } // Set log to use microseconds, if stdout is enabled if stdout { log.SetFlags(log.LstdFlags | log.Lmicroseconds) } return &Logger{LogToSystemLog: systemLog, LogToStdout: stdout, Tag: tag, SystemLog: syslogger}, nil } // Info writes info to stdout and/or the system log. func (l *Logger) Info(v ...interface{}) { if l.LogToStdout { log.Print(v...) } if l.LogToSystemLog { _ = l.SystemLog.Info(fmt.Sprint(v...)) } } // Infof writes formatted info to stdout and/or the system log. func (l *Logger) Infof(format string, v ...interface{}) { if l.LogToStdout { log.Printf(format, v...) } if l.LogToSystemLog { _ = l.SystemLog.Info(fmt.Sprintf(format, v...)) } } // Warn writes a warning to stdout and/or the system log. func (l *Logger) Warn(v ...interface{}) { if l.LogToStdout { log.Print(v...) } if l.LogToSystemLog { _ = l.SystemLog.Warning(fmt.Sprint(v...)) } } // Warnf writes a formatted warning to stdout and/or the system log. func (l *Logger) Warnf(format string, v ...interface{}) { if l.LogToStdout { log.Printf(format, v...) } if l.LogToSystemLog { _ = l.SystemLog.Warning(fmt.Sprintf(format, v...)) } } // Error writes an error to stdout and/or the system log. func (l *Logger) Error(v ...interface{}) { if l.LogToStdout { log.Print(v...) } if l.LogToSystemLog { _ = l.SystemLog.Err(fmt.Sprint(v...)) } } // Errorf writes a formatted error to stdout and/or the system log. func (l *Logger) Errorf(format string, v ...interface{}) { if l.LogToStdout { log.Printf(format, v...) } if l.LogToSystemLog { _ = l.SystemLog.Err(fmt.Sprintf(format, v...)) } } // Fatal writes an error to stdout and/or the system log then exits with requested code. func (l *Logger) Fatal(e int, v ...interface{}) { l.Error(v...) os.Exit(e) } // Fatalf writes a formatted error to stdout and/or the system log then exits with requested code. func (l *Logger) Fatalf(e int, format string, v ...interface{}) { l.Errorf(format, v...) os.Exit(e) }
107
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "strconv" "strings" "github.com/aws/ec2-macos-init/internal/paths" "github.com/google/go-cmp/cmp" ) // Module contains a few fields common to all Module types and containers for the configuration of any // potential module type. type Module struct { Type string Success bool Name string `toml:"Name"` PriorityGroup int `toml:"PriorityGroup"` FatalOnError bool `toml:"FatalOnError"` RunOnce bool `toml:"RunOnce"` RunPerBoot bool `toml:"RunPerBoot"` RunPerInstance bool `toml:"RunPerInstance"` CommandModule CommandModule `toml:"Command"` MOTDModule MOTDModule `toml:"MOTD"` SSHKeysModule SSHKeysModule `toml:"SSHKeys"` UserDataModule UserDataModule `toml:"UserData"` NetworkCheckModule NetworkCheckModule `toml:"NetworkCheck"` SystemConfigModule SystemConfigModule `toml:"SystemConfig"` UserManagementModule UserManagementModule `toml:"UserManagement"` } // ModuleContext contains fields that may need to be passed to the Do function for modules. type ModuleContext struct { Logger *Logger IMDS *IMDSConfig BaseDirectory string } // InstanceHistoryPath provides the history storage path for the current // instance. func (m ModuleContext) InstanceHistoryPath() string { if m.IMDS == nil || strings.TrimSpace(m.IMDS.InstanceID) == "" { // do *not* allow callers of this method to continue program run as // operation without this data may cause history to be lost and // subsequent ec2-macos-init runs to operate inappropriately. panic("no instance-id available") } return paths.InstanceHistory(m.BaseDirectory, m.IMDS.InstanceID) } // validateModule performs the following checks: // 1. Check that there is exactly one Run type set // 2. Check that Priority is set and is not less than 1 func (m *Module) validateModule() (err error) { // Check that there is exactly one Run type set var runs int8 if m.RunOnce { runs++ } if m.RunPerBoot { runs++ } if m.RunPerInstance { runs++ } if runs != 1 { return fmt.Errorf("ec2macosinit: incorrect number of run types\n") } // Check that Priority is set and not 0 or negative (must be 1 or greater) if m.PriorityGroup < 1 { return fmt.Errorf("ec2macosinit: module priority is unset or less than 1\n") } return nil } // identifyModule assigns a type to a module by comparing the empty struct for that module with the value provided. // This approach requires that a given module only have a single Type. func (m *Module) identifyModule() (err error) { if !cmp.Equal(m.CommandModule, CommandModule{}) { m.Type = "command" return nil } if !cmp.Equal(m.MOTDModule, MOTDModule{}) { m.Type = "motd" return nil } if !cmp.Equal(m.SSHKeysModule, SSHKeysModule{}) { m.Type = "sshkeys" return nil } if !cmp.Equal(m.UserDataModule, UserDataModule{}) { m.Type = "userdata" return nil } if !cmp.Equal(m.NetworkCheckModule, NetworkCheckModule{}) { m.Type = "networkcheck" return nil } if !cmp.Equal(m.SystemConfigModule, SystemConfigModule{}) { m.Type = "systemconfig" return nil } if !cmp.Equal(m.UserManagementModule, UserManagementModule{}) { m.Type = "usermanagement" return nil } return fmt.Errorf("ec2macosinit: unable to identify module type\n") } // generateHistoryKey takes a module and generates a key to be used in the instance history for that module. // History Key Format: key = m.PriorityLevel_RunType_m.Type_m.Name func (m *Module) generateHistoryKey() (key string) { // Generate key var runType string if m.RunOnce { runType = "RunOnce" } if m.RunPerInstance { runType = "RunPerInstance" } if m.RunPerBoot { runType = "RunPerBoot" } return strconv.Itoa(m.PriorityGroup) + "_" + runType + "_" + m.Type + "_" + m.Name } // ShouldRun determines if a module should be run, given a current instance ID and history. There are three cases: // 1. RunPerBoot - The module should run every boot, no matter what. The simplest case. // 2. RunPerInstance - The module should run once on every instance. Here we must look for the current instance ID // in the instance history and if found, compare the current module's key with all successfully run keys. If // not found, run the module. If found and unsuccessful, run the module. If found and successful, skip. // 3. RunOnce - The module should run once, ever. The process here is similar to RunPerInstance except the key must // be searched for in every instance history. If not found, run the module. If found and unsuccessful, run the // module. If found and successful, skip. func (m *Module) ShouldRun(instanceID string, history []History) (shouldRun bool) { // RunPerBoot runs every time if m.RunPerBoot { return true } // The rest will use the history key key := m.generateHistoryKey() // RunPerInstance only runs if the module's key doesn't exist in the current instance history and has // not run successfully. if m.RunPerInstance { // Check each instance in the instance history for _, instance := range history { if instanceID == instance.InstanceID { // If the current instance matches an ID in the history, check every module history for that instance for _, moduleHistory := range instance.ModuleHistories { if key == moduleHistory.Key && moduleHistory.Success { // If there is a matching key and it completed successfully, it doesn't need to be run return false } } // If there is an instance that matches and no keys match, run the module return true } } // If no instances match the instance history, run the module return true } // RunOnce only runs if the module's key doesn't exist in any instance history if m.RunOnce { for _, instance := range history { // Check every module history for that instance for _, moduleHistory := range instance.ModuleHistories { if key == moduleHistory.Key && moduleHistory.Success { // If there is a matching key and it completed successfully, it doesn't need to be run return false } } } // If no instances match the instance history, run the module return true } // Default here is false, though this position should never be reached. Preference is to not run actions which // may be potentially mutating but are misconfigured. return false }
188
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "testing" "time" ) func TestModule_validateModule(t *testing.T) { tests := []struct { name string fields Module wantErr bool }{ { name: "Bad case: 0 Run Types set", fields: Module{}, wantErr: true, }, { name: "Bad case: 3 Run Types set", fields: Module{ RunOnce: true, RunPerBoot: true, RunPerInstance: true, }, wantErr: true, }, { name: "Bad case: 1 Run Type set, priority unset", fields: Module{ RunOnce: true, }, wantErr: true, }, { name: "Good case: 1 Run Type set, PriorityGroup > 1", fields: Module{ PriorityGroup: 2, RunOnce: true, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := tt.fields.validateModule(); (err != nil) != tt.wantErr { t.Errorf("validateModule() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestModule_identifyModule(t *testing.T) { tests := []struct { name string fields Module wantType string wantErr bool }{ { name: "Bad case: unidentified or empty module", fields: Module{}, wantErr: true, }, { name: "Good case: Command Module", fields: Module{ CommandModule: CommandModule{ RunAsUser: "ec2-user", }, }, wantType: "command", wantErr: false, }, { name: "Good case: SSHKeys Module", fields: Module{ SSHKeysModule: SSHKeysModule{ User: "ec2-user", }, }, wantType: "sshkeys", wantErr: false, }, { name: "Good case: UserData Module", fields: Module{ UserDataModule: UserDataModule{ ExecuteUserData: true, }, }, wantType: "userdata", wantErr: false, }, { name: "Good case: NetworkCheck Module", fields: Module{ NetworkCheckModule: NetworkCheckModule{ PingCount: 3, }, }, wantType: "networkcheck", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := tt.fields.identifyModule(); (err != nil) != tt.wantErr { t.Errorf("identifyModule() error = %v, wantErr %v", err, tt.wantErr) } else if tt.wantType != tt.fields.Type { t.Errorf("identifyModule() Type = %v, wantType %v", tt.fields.Type, tt.wantType) } }) } } func TestModule_generateHistoryKey(t *testing.T) { tests := []struct { name string fields Module wantKey string }{ { name: "Key with RunOnce", fields: Module{ Type: "testmodule", Name: "test1", PriorityGroup: 1, RunOnce: true, }, wantKey: "1_RunOnce_testmodule_test1", }, { name: "Key with RunPerBoot", fields: Module{ Type: "testmodule", Name: "test2", PriorityGroup: 2, RunPerBoot: true, }, wantKey: "2_RunPerBoot_testmodule_test2", }, { name: "Key with RunPerInstance", fields: Module{ Type: "testmodule", Name: "test3", PriorityGroup: 3, RunPerInstance: true, }, wantKey: "3_RunPerInstance_testmodule_test3", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if gotKey := tt.fields.generateHistoryKey(); gotKey != tt.wantKey { t.Errorf("generateHistoryKey() = %v, want %v", gotKey, tt.wantKey) } }) } } func TestModule_ShouldRun(t *testing.T) { type args struct { instanceID string history []History } tests := []struct { name string fields Module args args wantShouldRun bool }{ { name: "No Run Type set", fields: Module{}, args: args{}, wantShouldRun: false, }, { name: "RunPerBoot Module", fields: Module{ RunPerBoot: true, }, args: args{}, wantShouldRun: true, }, { name: "RunPerInstance - No matches", fields: Module{ // key will be 2_RunPerInstance_testType_testName Name: "testName", PriorityGroup: 2, RunPerInstance: true, Type: "testType", }, args: args{ instanceID: "i-1234567890ab", history: []History{ { InstanceID: "i-ba0987654321", RunTime: time.Time{}, ModuleHistories: []ModuleHistory{}, }, }, }, wantShouldRun: true, }, { name: "RunPerInstance - Instance match with no keys", fields: Module{ // key will be 2_RunPerInstance_testType_testName Name: "testName", PriorityGroup: 2, RunPerInstance: true, Type: "testType", }, args: args{ instanceID: "i-1234567890ab", history: []History{ { InstanceID: "i-1234567890ab", RunTime: time.Time{}, ModuleHistories: []ModuleHistory{}, }, }, }, wantShouldRun: true, }, { name: "RunPerInstance - Instance match with key match", fields: Module{ // key will be 2_RunPerInstance_testType_testName Name: "testName", PriorityGroup: 2, RunPerInstance: true, Type: "testType", }, args: args{ instanceID: "i-1234567890ab", history: []History{ { InstanceID: "i-1234567890ab", RunTime: time.Time{}, ModuleHistories: []ModuleHistory{ { Key: "2_RunPerInstance_testType_testName", Success: true, }, }, }, }, }, wantShouldRun: false, }, { name: "RunOnce - No matches", fields: Module{ // key will be 2_RunOnce_testType_testName Name: "testName", PriorityGroup: 2, RunOnce: true, Type: "testType", }, args: args{ instanceID: "i-1234567890ab", history: []History{ { InstanceID: "i-ba0987654321", RunTime: time.Time{}, ModuleHistories: []ModuleHistory{}, }, }, }, wantShouldRun: true, }, { name: "RunOnce - Key match", fields: Module{ // key will be 2_RunOnce_testType_testName Name: "testName", PriorityGroup: 2, RunOnce: true, Type: "testType", }, args: args{ instanceID: "i-1234567890ab", history: []History{ { InstanceID: "i-1234567890ab", RunTime: time.Time{}, ModuleHistories: []ModuleHistory{ { Key: "2_RunOnce_testType_testName", Success: true, }, }, }, }, }, wantShouldRun: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if gotShouldRun := tt.fields.ShouldRun(tt.args.instanceID, tt.args.history); gotShouldRun != tt.wantShouldRun { t.Errorf("ShouldRun() = %v, want %v", gotShouldRun, tt.wantShouldRun) fmt.Println(tt.fields.generateHistoryKey()) } }) } }
309
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "os" "regexp" "strings" ) const ( motdFile = "/etc/motd" ) // MOTDModule contains all necessary configuration fields for running a MOTD module. type MOTDModule struct { UpdateName bool `toml:"UpdateName"` // UpdateName specifies if the MOTDModule should run or not } // Do for MOTDModule gets the OS's current product version and maps the name of the OS to that version. It then writes // a string with the OS name and product version to /etc/motd. func (c *MOTDModule) Do(ctx *ModuleContext) (message string, err error) { if !c.UpdateName { return "Not requested to update MOTD", nil } // Create the macOS string macosStr := "macOS" // Create regex pattern to be replaced in the motd file motdMacOSExpression, err := regexp.Compile("macOS.*") if err != nil { return "", fmt.Errorf("ec2macosinit: error compiling motd regex pattern: %s", err) } // Get the os product version number osProductVersion, err := getOSProductVersion() if err != nil { return "", fmt.Errorf("ec2macosinit: error while getting product version: %s", err) } // Get the version name using the os product version number versionName := getVersionName(osProductVersion) // Create the version string to be written to the motd file var motdString string if versionName != "" { motdString = fmt.Sprintf("%s %s %s", macosStr, versionName, osProductVersion) } else { motdString = fmt.Sprintf("%s %s", macosStr, osProductVersion) } // Read in the raw contents of the motd file rawFileContents, err := os.ReadFile(motdFile) if err != nil { return "", fmt.Errorf("ec2macosinit: error reading motd file: %s", err) } // Use the regexp object to replace all instances of the pattern with the updated motd version string replacedContents := motdMacOSExpression.ReplaceAll(rawFileContents, []byte(motdString)) // Write the updated contents back to the motd file err = os.WriteFile(motdFile, replacedContents, 0644) if err != nil { return "", fmt.Errorf("ec2macosinit: error writing updated motd back to file: %s", err) } return fmt.Sprintf("successfully updated motd file [%s] with version string [%s]", motdFile, motdString), nil } // getVersionName maps os product version numbers to version names. A version name will be returned if the mapping is // known, otherwise it returns an empty string. func getVersionName(osProductVersion string) (versionName string) { // Map product version number to version name switch { case strings.HasPrefix(osProductVersion, "10.14"): versionName = "Mojave" case strings.HasPrefix(osProductVersion, "10.15"): versionName = "Catalina" case strings.HasPrefix(osProductVersion, "11"): versionName = "Big Sur" case strings.HasPrefix(osProductVersion, "12"): versionName = "Monterey" case strings.HasPrefix(osProductVersion, "13"): versionName = "Ventura" } return versionName }
89
ec2-macos-init
aws
Go
package ec2macosinit import ( "fmt" "net" "strings" "time" "github.com/digineo/go-ping" ) const ( pingCountDefault = 3 pingPayloadSize = 56 ) // NetworkCheckModule contains contains all necessary configuration fields for running a NetworkCheck module. type NetworkCheckModule struct { PingCount int `toml:"PingCount"` } // Do for NetworkCheck Module gets the default gateway and pings it to check if the network is up. func (c *NetworkCheckModule) Do(ctx *ModuleContext) (message string, err error) { // Get default gateway out, err := executeCommand([]string{"/bin/zsh", "-c", "route -n get default | grep gateway"}, "", []string{}) if err != nil { return "", fmt.Errorf("ec2macosinit: error while running route command to get default gateway with stderr [%s]: %s\n", out.stderr, err) } gatewayFields := strings.Fields(out.stdout) if len(gatewayFields) != 2 { return "", fmt.Errorf("ec2macosinit: unexpected output from route command: %s\n", out.stdout) } // Resolve IP address defaultGatewayIP, err := net.ResolveIPAddr("ip4", gatewayFields[1]) if err != nil { return "", fmt.Errorf("ec2macosinit: error resolving default gateway IP address: %s\n", err) } // Ping default gateway pinger, err := ping.New("0.0.0.0", "") if err != nil { return "", fmt.Errorf("ec2macosinit: error setting up new pinger: %s\n", err) } // If PingCount is unset, default to 3 if c.PingCount == 0 { c.PingCount = pingCountDefault } pinger.SetPayloadSize(pingPayloadSize) rtt, err := pinger.PingAttempts(defaultGatewayIP, time.Second, int(c.PingCount)) if err != nil { // If network is not up, this will error with an i/o timeout return "", fmt.Errorf("ec2macosinit: error pinging default gateway: %s\n", err) } return fmt.Sprintf("successfully pinged default gateway with a RTT of %v", rtt), nil }
58
ec2-macos-init
aws
Go
package ec2macosinit import ( "bufio" "fmt" "os" "path/filepath" "strings" ) // SSHKeysModule contains all necessary configuration fields for running an SSH Keys module. type SSHKeysModule struct { DedupKeys bool `toml:"DedupKeys"` GetIMDSOpenSSHKey bool `toml:"GetIMDSOpenSSHKey"` StaticOpenSSHKeys []string `toml:"StaticOpenSSHKeys"` OverwriteAuthorizedKeys bool `toml:"OverwriteAuthorizedKeys"` User string `toml:"User"` } // Do for the SSHKeysModule does some brief validation, gets the IMDS key (if configured), appends static keys (if // configured), and then writes them to the authorized_keys file for the user. func (c *SSHKeysModule) Do(ctx *ModuleContext) (message string, err error) { // If we're not getting the key from IMDS and there are no keys provided, there's nothing to do here if !c.GetIMDSOpenSSHKey && len(c.StaticOpenSSHKeys) == 0 { return "nothing to do", nil } // If user is undefined, default to ec2-user if c.User == "" { c.User = "ec2-user" } // Verify that user exists exists, err := userExists(c.User) if err != nil { return "", fmt.Errorf("ec2macosinit: error while checking if user %s exists: %s\n", c.User, err) } if !exists { // if the user doesn't exist, error out return "", fmt.Errorf("ec2macosinit: user %s does not exist\n", c.User) } // Set directory and authorized_keys file authorizedKeysDir := filepath.Join("/Users", c.User, ".ssh") authorizedKeysFile := filepath.Join(authorizedKeysDir, "authorized_keys") if _, err := os.Stat(authorizedKeysDir); os.IsNotExist(err) { // If directory doesn't exist, create it err := os.MkdirAll(authorizedKeysDir, 0700) if err != nil { return "", fmt.Errorf("ec2macosinit: unable to create directory [%s]: %s\n", authorizedKeysDir, err) } } // Get IMDS key keySet := map[string]struct{}{} if c.GetIMDSOpenSSHKey { // Get IMDS property "meta-data/public-keys/0/openssh-key" imdsKey, respCode, err := ctx.IMDS.getIMDSProperty("meta-data/public-keys/0/openssh-key") if err != nil { return "", fmt.Errorf("ec2macosinit: error getting openSSH key from IMDS: %s\n", err) } if respCode == 200 { // 200 = ok keySet[strings.TrimSpace(imdsKey)] = struct{}{} } else if respCode != 404 { // 404 is the only other allowable response code as it indicates no key was provided - if not 404 error out return "", fmt.Errorf("ec2macosinit: received an unexpected response code from IMDS: %d - %s\n", respCode, err) } } // Add all unique provided static keys if len(c.StaticOpenSSHKeys) > 0 { for _, k := range c.StaticOpenSSHKeys { keySet[strings.TrimSpace(k)] = struct{}{} } } // If authorized_keys file exists and deduplication is requested, read file and add to set if _, err := os.Stat(authorizedKeysFile); err == nil && c.DedupKeys { file, err := os.Open(authorizedKeysFile) if err != nil { return "", fmt.Errorf("ec2macosinit: unable to open %s: %s\n", authorizedKeysFile, err) } defer file.Close() // Read file and add each line to set scanner := bufio.NewScanner(file) for scanner.Scan() { keySet[strings.TrimSpace(scanner.Text())] = struct{}{} } if err := scanner.Err(); err != nil { return "", fmt.Errorf("ec2macosinit: error while reading %s: %s\n", authorizedKeysFile, err) } // Set OverwriteAuthorizedKeys to true so that duplicate keys are overwritten c.OverwriteAuthorizedKeys = true } // Check if there's anything else to do if len(keySet) == 0 && !c.OverwriteAuthorizedKeys { return "no keys found and not overwriting authorized_keys", nil } // Add all keys to a slice var keys []string for k := range keySet { keys = append(keys, k) } // Write to authorized_keys file var f *os.File if !c.OverwriteAuthorizedKeys { // Append to authorized_keys f, err = os.OpenFile(authorizedKeysFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) } else { // Overwrite (truncate) authorized_keys f, err = os.OpenFile(authorizedKeysFile, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0600) } if err != nil { f.Close() return "", fmt.Errorf("ec2macosinit: error while opening authorized_keys file: %s\n", err) } if _, err := f.WriteString(strings.Join(keys, "\n") + "\n"); err != nil { return "", fmt.Errorf("ec2macosinit: error while writing to authorized_keys file: %s\n", err) } f.Close() // Get UID and GID for user uid, gid, err := getUIDandGID(c.User) if err != nil && c.User == "ec2-user" { // Use default values for ec2-user uid = 501 gid = 20 } else if err != nil { return "", fmt.Errorf("ec2macosinit: error while getting user info: %s\n", err) } // Fix file ownership and directory permissions err = os.Chown(authorizedKeysDir, uid, gid) if err != nil { return "", fmt.Errorf("ec2macosinit: unable to change ownership of .ssh directory: %s\n", err) } err = os.Chown(authorizedKeysFile, uid, gid) if err != nil { return "", fmt.Errorf("ec2macosinit: unable to change ownership of authorized_keys file: %s\n", err) } return fmt.Sprintf("successfully added %d keys to authorized_users", len(keys)), nil }
146