Skip to content

Commit 17aaddc

Browse files
committed
fix(app): fixes lint issues and test cases
Signed-off-by: Mohit Nagaraj <[email protected]>
1 parent f1b7b00 commit 17aaddc

File tree

19 files changed

+290
-219
lines changed

19 files changed

+290
-219
lines changed

CONTRIBUTING.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,11 @@ Or you may configure your IDE, for example, Visual Studio Code to automatically
5252

5353

5454
#### Tests
55-
Users can now test their code on their local machine against the CI checks implemented using `make run-tests`.
55+
Users can now test their code on their local machine against the CI checks implemented using `make test`.
5656

5757
To test code changes on your local machine, run the following command:
5858
```
59-
make run-tests
59+
make test
6060
```
6161

6262
#### Building Docker image

broker/nats/nats.go

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package nats
22

33
import (
4+
"encoding/json"
45
"log"
56
"strings"
67
"sync"
@@ -25,8 +26,8 @@ type Options struct {
2526

2627
// Nats will implement Nats subscribe and publish functionality
2728
type Nats struct {
28-
ec *nats.EncodedConn
29-
wg *sync.WaitGroup
29+
conn *nats.Conn
30+
wg *sync.WaitGroup
3031
}
3132

3233
// New - constructor
@@ -57,55 +58,66 @@ func New(opts Options) (broker.Handler, error) {
5758
return nil, ErrConnect(err)
5859
}
5960

60-
ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
61-
if err != nil {
62-
return nil, ErrEncodedConn(err)
63-
}
64-
65-
return &Nats{ec: ec}, nil
61+
return &Nats{conn: nc, wg: &sync.WaitGroup{}}, nil
6662
}
63+
6764
func (n *Nats) ConnectedEndpoints() (endpoints []string) {
68-
for _, server := range n.ec.Conn.Servers() {
65+
for _, server := range n.conn.Servers() {
6966
endpoints = append(endpoints, strings.TrimPrefix(server, "nats://"))
7067
}
7168
return
7269
}
7370

7471
func (n *Nats) Info() string {
75-
if n.ec == nil || n.ec.Conn == nil {
72+
if n.conn == nil {
7673
return broker.NotConnected
7774
}
78-
return n.ec.Conn.Opts.Name
75+
return n.conn.Opts.Name
7976
}
8077

8178
func (n *Nats) CloseConnection() {
82-
n.ec.Close()
79+
if n.conn != nil {
80+
if err := n.conn.Drain(); err != nil {
81+
log.Printf("nats: drain error: %v", err)
82+
}
83+
n.conn.Close()
84+
}
8385
}
8486

87+
8588
// Publish - to publish messages
8689
func (n *Nats) Publish(subject string, message *broker.Message) error {
87-
err := n.ec.Publish(subject, message)
90+
b, err := json.Marshal(message)
8891
if err != nil {
8992
return ErrPublish(err)
9093
}
91-
return nil
94+
return n.conn.Publish(subject, b)
9295
}
9396

9497
// PublishWithChannel - to publish messages with channel
9598
func (n *Nats) PublishWithChannel(subject string, msgch chan *broker.Message) error {
96-
err := n.ec.BindSendChan(subject, msgch)
97-
if err != nil {
98-
return ErrPublish(err)
99-
}
100-
return nil
99+
go func() {
100+
for msg := range msgch {
101+
b, err := json.Marshal(msg)
102+
if err != nil {
103+
log.Printf("nats: JSON marshal error: %v", err)
104+
continue
105+
}
106+
if err := n.conn.Publish(subject, b); err != nil {
107+
log.Printf("nats: publish error for subject %s: %v", subject, err)
108+
}
109+
}
110+
}()
111+
return nil
101112
}
102113

114+
103115
// Subscribe - for subscribing messages
104116
// TODO Ques: Do we want to unsubscribe
105117
// TODO will the method-user just subsribe, how will it handle the received messages?
106118
func (n *Nats) Subscribe(subject, queue string, message []byte) error {
107119
n.wg.Add(1)
108-
_, err := n.ec.QueueSubscribe(subject, queue, func(msg *nats.Msg) {
120+
_, err := n.conn.QueueSubscribe(subject, queue, func(msg *nats.Msg) {
109121
message = msg.Data
110122
n.wg.Done()
111123
})
@@ -119,7 +131,12 @@ func (n *Nats) Subscribe(subject, queue string, message []byte) error {
119131

120132
// SubscribeWithChannel will publish all the messages received to the given channel
121133
func (n *Nats) SubscribeWithChannel(subject, queue string, msgch chan *broker.Message) error {
122-
_, err := n.ec.BindRecvQueueChan(subject, queue, msgch)
134+
_, err := n.conn.QueueSubscribe(subject, queue, func(m *nats.Msg) {
135+
var msg broker.Message
136+
if err := json.Unmarshal(m.Data, &msg); err == nil {
137+
msgch <- &msg
138+
}
139+
})
123140
if err != nil {
124141
return ErrQueueSubscribe(err)
125142
}
@@ -153,8 +170,5 @@ func (in *Nats) DeepCopyObject() broker.Handler {
153170
// Check if the connection object is empty
154171
func (in *Nats) IsEmpty() bool {
155172
empty := &Nats{}
156-
if in == nil || *in == *empty {
157-
return true
158-
}
159-
return false
173+
return in == nil || *in == *empty
160174
}

converter/tests/helm_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,9 @@ func extractManifestFromChart(chartData []byte) (bool, string) {
139139
}
140140
if strings.HasSuffix(hdr.Name, "templates/manifest.yaml") {
141141
buf := new(bytes.Buffer)
142-
io.Copy(buf, tr)
142+
if _, err := io.Copy(buf, tr); err != nil {
143+
return false, ""
144+
}
143145
return true, buf.String()
144146
}
145147
}

files/error.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,12 @@ func ErrUnsupportedExtensionForOperation(operation string, fileName string, file
6767
return errors.New(ErrUnsupportedExtensionForOperationCode, errors.Critical, sdescription, ldescription, probableCause, remedy)
6868
}
6969

70-
func ErrUnsupportedExtension(fileName string, fileExt string, supportedExtensionsMap map[string]bool) error {
71-
supportedExtensions := slices.Collect(maps.Keys(supportedExtensionsMap))
70+
func ErrUnsupportedExtension(fileName string, fileExt string, supportedExtensions []string) error {
71+
extList := strings.Join(supportedExtensions, ", ")
7272

7373
sdescription := []string{
7474
fmt.Sprintf("The file '%s' has an unsupported extension: '%s'.", fileName, fileExt),
75-
fmt.Sprintf("Supported file extensions are: %s.", strings.Join(supportedExtensions, ", ")),
75+
fmt.Sprintf("Supported file extensions are: %s.", extList),
7676
}
7777

7878
ldescription := []string{
@@ -380,7 +380,7 @@ func ErrInvalidModel(operation string, filename string, err error) error {
380380
// check prefix as random numeric suffix is appended to archive during file handling (eg: .tar becomes .tar263831)
381381
return ErrInvalidModelArchive(filename, err)
382382
default:
383-
supportedExtensions := slices.Collect(maps.Keys(ValidIacExtensions))
383+
supportedExtensions := slices.Clone(ValidIacExtensions)
384384
supportedExtensions = slices.DeleteFunc(supportedExtensions, func(ext string) bool {
385385
return ext == ".zip"
386386
})

files/sanitization.go

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"bytes"
77
"compress/gzip"
88
"encoding/json"
9+
"slices"
910

1011
"fmt"
1112
"io"
@@ -25,24 +26,23 @@ type SanitizedFile struct {
2526
ExtractedContentPath string
2627
}
2728

28-
var ValidIacExtensions = map[string]bool{
29-
".yml": true,
30-
".yaml": true,
31-
".json": true,
32-
".tar": true,
33-
".tar.gz": true,
34-
".tar.tgz": true,
35-
".zip": true,
36-
".gz": true,
37-
".tgz": true,
29+
var ValidIacExtensions = []string{
30+
".yaml",
31+
".tar",
32+
".tar.gz",
33+
".tgz",
34+
".zip",
35+
".json",
36+
".yml",
3837
}
3938

40-
func SanitizeFile(data []byte, fileName string, tempDir string, validExts map[string]bool) (SanitizedFile, error) {
39+
func SanitizeFile(data []byte, fileName string, tempDir string, validExts []string) (SanitizedFile, error) {
4140

4241
ext := filepath.Ext(fileName)
42+
// Handle .gz special case
43+
ext2 := filepath.Ext(strings.TrimSuffix(fileName, ".gz"))
4344

44-
// 1. Check if file has supported extension
45-
if !validExts[ext] && !validExts[filepath.Ext(strings.TrimSuffix(fileName, ".gz"))] {
45+
if !slices.Contains(validExts, ext) && !slices.Contains(validExts, ext2) {
4646
return SanitizedFile{}, ErrUnsupportedExtension(fileName, ext, validExts)
4747
}
4848
switch ext {

files/tests/sanitization_test.go

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"path/filepath"
66
"testing"
77

8-
"github.com/meshery/meshkit/errors"
98
"github.com/meshery/meshkit/files"
109
coreV1 "github.com/meshery/schemas/models/v1alpha1/core"
1110
)
@@ -16,7 +15,7 @@ func TestSanitizeFile(t *testing.T) {
1615
filePath string
1716
expectedExt string
1817
expectError bool
19-
expectedErrCode string
18+
expectedErrMsg string
2019
expectedContent map[string]interface{}
2120
expectedType coreV1.IaCFileTypes
2221
}{
@@ -43,10 +42,10 @@ func TestSanitizeFile(t *testing.T) {
4342
expectedType: "",
4443
},
4544
{
46-
name: "Unsupported extension",
47-
filePath: "./samples/valid.txt",
48-
expectError: true,
49-
expectedErrCode: files.ErrUnsupportedExtensionCode,
45+
name: "Unsupported extension",
46+
filePath: "./samples/valid.txt",
47+
expectError: true,
48+
expectedErrMsg: "The file 'valid.txt' could not be processed because the extension '.txt' is not supported by the system..The system is designed to handle files with the following extensions: .yaml, .tar, .tar.gz, .tgz, .zip, .json, .yml.",
5049
},
5150
{
5251
name: "Valid compressed extension",
@@ -86,14 +85,14 @@ func TestSanitizeFile(t *testing.T) {
8685
name: "Can Identify Kubernetes Manifest",
8786
filePath: "./samples/valid_manifest.yml",
8887
expectedExt: ".yml",
89-
expectedType: coreV1.K8sManifest,
88+
expectedType: coreV1.K8sManifest,
9089
},
9190

9291
{
9392
name: "Can Identify Kubernetes Manifest With Crds",
9493
filePath: "./samples/manifest-with-crds.yml",
9594
expectedExt: ".yml",
96-
expectedType: coreV1.K8sManifest,
95+
expectedType: coreV1.K8sManifest,
9796
},
9897

9998
{
@@ -136,18 +135,20 @@ expectedType: coreV1.K8sManifest,
136135
// },
137136
}
138137

139-
validExts := map[string]bool{
140-
".json": true,
141-
".yml": true,
142-
".yaml": true,
143-
".tar": true,
144-
".tar.gz": true,
145-
".tgz": true,
146-
".zip": true,
138+
validExts := []string{
139+
".yaml",
140+
".tar",
141+
".tar.gz",
142+
".tgz",
143+
".zip",
144+
".json",
145+
".yml",
147146
}
148147

149-
tempDir, _ := os.MkdirTemp(" ", "temp-tests")
148+
tempDir, _ := os.MkdirTemp("", "temp-tests")
149+
os.Setenv("MESHERY_CONTENT_PATH", tempDir)
150150
defer os.RemoveAll(tempDir)
151+
defer os.Unsetenv("MESHERY_CONTENT_PATH")
151152
// tempDir := "./temp"
152153

153154
for _, tc := range testCases {
@@ -166,8 +167,8 @@ expectedType: coreV1.K8sManifest,
166167
if tc.expectError {
167168
if err == nil {
168169
t.Error("Expected error, got nil")
169-
} else if tc.expectedErrCode != "" && errors.GetCode(err) != tc.expectedErrCode {
170-
t.Errorf("Expected error message %q, got %q", tc.expectedErrCode, err.Error())
170+
} else if tc.expectedErrMsg != "" && err.Error() != tc.expectedErrMsg {
171+
t.Errorf("Expected error message %q, got %q", tc.expectedErrMsg, err.Error())
171172
}
172173
return
173174
}

generators/artifacthub/package.go

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ func (pkg AhPackage) GetName() string {
4949
func (pkg AhPackage) GenerateComponents(group string) ([]_component.ComponentDefinition, error) {
5050
components := make([]_component.ComponentDefinition, 0)
5151
// TODO: Move this to the configuration
52-
5352
if pkg.ChartUrl == "" {
5453
return components, ErrChartUrlEmpty(pkg.Name, "ArtifactHub")
5554
}
@@ -107,15 +106,29 @@ func (pkg *AhPackage) UpdatePackageData() error {
107106
if pkgEntry == nil || !ok {
108107
return ErrGetChartUrl(fmt.Errorf("Cannot extract chartUrl from repository helm index"))
109108
}
110-
urls, ok := pkgEntry.([]interface{})[0].(map[interface{}]interface{})["urls"]
111-
if urls == nil || !ok {
109+
urlField, ok := pkgEntry.([]interface{})[0].(map[interface{}]interface{})["urls"]
110+
if urlField == nil || !ok {
112111
return ErrGetChartUrl(fmt.Errorf("Cannot extract chartUrl from repository helm index"))
113112
}
114-
chartUrl, ok := urls.([]interface{})[0].(string)
115-
if !ok || chartUrl == "" {
113+
var chartUrl string
114+
for i, u := range urlField.([]interface{}) {
115+
s, _ := u.(string)
116+
if s == "" {
117+
continue
118+
}
119+
if i == 0 {
120+
chartUrl = s
121+
}
122+
if strings.HasPrefix(s, "http") {
123+
chartUrl = s
124+
break
125+
}
126+
}
127+
if chartUrl == "" {
116128
return ErrGetChartUrl(fmt.Errorf("Cannot extract chartUrl from repository helm index"))
117129
}
118-
if !strings.HasPrefix(chartUrl, "http") {
130+
131+
if !strings.HasPrefix(chartUrl, "http") && !strings.HasPrefix(chartUrl, "oci://") {
119132
if !strings.HasSuffix(pkg.RepoUrl, "/") {
120133
pkg.RepoUrl = pkg.RepoUrl + "/"
121134
}

generators/artifacthub/package_manager.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ func (ahpm ArtifactHubPackageManager) GetPackage() (models.Package, error) {
2222
}
2323
// update package information
2424
for i, ap := range pkgs {
25-
_ = ap.UpdatePackageData()
25+
if err := ap.UpdatePackageData(); err != nil {
26+
return nil, err
27+
}
2628
pkgs[i] = ap
2729
}
2830

generators/artifacthub/package_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ func TestGetChartUrl(t *testing.T) {
1717
}{
1818
// these might change in the future, so the tests have to be changed as well when the urls change
1919
// because the urls will change with every new version update to the package
20-
{AhPackage{Name: "consul", Repository: "bitnami", Organization: "", RepoUrl: "https://charts.bitnami.com/bitnami"}, "https://charts.bitnami.com/bitnami/consul"},
20+
{AhPackage{Name: "consul", Repository: "bitnami", Organization: "", RepoUrl: "https://charts.bitnami.com/bitnami"}, "oci://registry-1.docker.io/bitnamicharts/consul"},
2121
{AhPackage{Name: "crossplane-types", Repository: "crossplane", Organization: "", RepoUrl: "https://charts.crossplane.io/master"}, "https://charts.crossplane.io/master/crossplane-types-0.13.0-rc.191.g3a18fb7.tgz"},
2222
}
2323
for _, tt := range tests {

generators/github/package_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func TestGenerateCompFromGitHub(t *testing.T) {
4141
{ // Source pointing to a directly downloadable file (not a repo per se)
4242
ghPackageManager: GitHubPackageManager{
4343
PackageName: "k8s-config-connector",
44-
SourceURL: "https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-config-connector/master/crds/alloydb_v1beta1_alloydbbackup.yaml/1.113.0",
44+
SourceURL: "https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-config-connector/master/crds/alloydb_v1beta1_alloydbbackup.yaml",
4545
},
4646
want: 1,
4747
},
@@ -56,7 +56,7 @@ func TestGenerateCompFromGitHub(t *testing.T) {
5656
{ // Source pointing to a zip containing manifests but no CRDs
5757
ghPackageManager: GitHubPackageManager{
5858
PackageName: "acm-controller",
59-
SourceURL: "https://github.com/MUzairS15/WASM-filters/raw/main/test.tar.gz/v0.7.12",
59+
SourceURL: "https://github.com/MUzairS15/WASM-filters/raw/main/test.tar.gz",
6060
},
6161
want: 0,
6262
},

0 commit comments

Comments
 (0)