Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhilsbhat committed Jan 14, 2024
0 parents commit 8b7c4a4
Show file tree
Hide file tree
Showing 20 changed files with 921 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.idea
/vendor
*.tar.gz
/dist
cover.out
cover.html
74 changes: 74 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
linters:
disable-all: false
enable-all: true
disable:
- gci
- gochecknoglobals
- tagliatelle
- exhaustivestruct
- nolintlint
- exhaustruct
- forbidigo
- paralleltest
- cyclop
- ireturn
- wrapcheck
- interfacebloat
- forcetypeassert
- dupl
- goconst
- maligned
- depguard
- tagalign

issues:
exclude-rules:
- path: _test\.go
linters:
- gomnd

# https://github.com/go-critic/go-critic/issues/926
- linters:
- gocritic
text: "unnecessaryDefer:"

linters-settings:
funlen:
lines: 160

lll:
line-length: 165

dupl:
threshold: 450

gocognit:
min-complexity: 78

nestif:
min-complexity: 20


run:
concurrency: 10
timeout: 10m
issues-exit-code: 1
tests: true
skip-dirs:
- scripts/
- vendor/
- docs/

skip-files:
- Makefile
- README.md
- Dockerfile

severity:
default-severity: error

service:
golangci-lint-version: 1.27.x
prepare:
- make local.check
28 changes: 28 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This is an example .goreleaser.yml file with some sane defaults.
# Make sure to check the documentation at http://goreleaser.com
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy

builds:
- skip: true

archives:
- format: 'tar.gz'
id: source-code
- format: 'zip'
id: source-code-2

checksum:
name_template: 'checksums.txt'

snapshot:
name_template: "{{ .Tag }}"

changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Nikhil Bhat

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 48 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
GOFMT_FILES?=$(shell find . -not -path "./vendor/*" -type f -name '*.go')
BUILD_ENVIRONMENT?=${ENVIRONMENT}
GOVERSION?=$(shell go version | awk '{printf $$3}')
APP_DIR?=$(shell git rev-parse --show-toplevel)
SOURCE_PACKAGES?=$(shell go list -mod=vendor ./... | grep -v "vendor" | grep -v "mocks")
TEST_FILES?=$(shell go list ./... | grep -v /vendor/ | grep -v examples)

# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
ifeq (,$(shell go env GOBIN))
GOBIN=$(shell go env GOPATH)/bin
else
GOBIN=$(shell go env GOBIN)
endif

.PHONY: help
help: ## Prints help (only for targets with comments)
@grep -E '^[a-zA-Z0-9._-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

local.fmt: ## Lints all the go code in the application.
@gofmt -w $(GOFMT_FILES)
$(GOBIN)/gofumpt -l -w $(GOFMT_FILES)
$(GOBIN)/goimports -w $(GOFMT_FILES)
$(GOBIN)/gci write $(GOFMT_FILES) --skip-generated

local.check: local.fmt ## Loads all the dependencies to vendor directory
@go mod vendor
@go mod tidy

local.build: local.check ## Generates the artifact with the help of 'go build'
GOVERSION=${GOVERSION} BUILD_ENVIRONMENT=${BUILD_ENVIRONMENT} goreleaser build --rm-dist

publish: local.check ## Builds and publishes the app
GOVERSION=${GOVERSION} BUILD_ENVIRONMENT=${BUILD_ENVIRONMENT} PLUGIN_PATH=${APP_DIR} goreleaser release --rm-dist

mock.publish: local.check ## Builds and mocks app release
GOVERSION=${GOVERSION} BUILD_ENVIRONMENT=${BUILD_ENVIRONMENT} PLUGIN_PATH=${APP_DIR} goreleaser release --skip-publish --rm-dist

lint: ## Lint's application for errors, it is a linters aggregator (https://github.com/golangci/golangci-lint).
if [ -z "${DEV}" ]; then golangci-lint run --color always ; else docker run --rm -v $(APP_DIR):/app -w /app golangci/golangci-lint:v1.46.2-alpine golangci-lint run --color always ; fi

report: ## Publishes the go-report of the appliction (uses go-reportcard)
if [ -z "${DEV}" ]; then goreportcard -v ; else docker run --rm -v $(APP_DIR):/app -w /app basnik/goreportcard-cli:latest goreportcard-cli -v ; fi

test: ## runs test cases
@time go test $(TEST_FILES) -mod=vendor -coverprofile cover.out && go tool cover -html=cover.out -o cover.html && open cover.html

generate.mocks: ## Generates mocks to those methods that has comments //go:generate
@go generate ${SOURCE_PACKAGES}
Empty file added README.md
Empty file.
73 changes: 73 additions & 0 deletions content/content.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package content

import (
"encoding/csv"
"encoding/json"
"strings"

"github.com/goccy/go-yaml"
"github.com/sirupsen/logrus"
)

// Object implements method that check for file content type.
type Object string

const (
FileTypeYAML = "yaml"
FileTypeJSON = "json"
FileTypeCSV = "csv"
FileTypeUnknown = "unknown"
)

// IsJSON checks if the passed content of JSON.
func IsJSON(content string) bool {
var js interface{}

return json.Unmarshal([]byte(content), &js) == nil
}

// IsYAML checks if the passed content of YAML.
func IsYAML(content string) bool {
var yml interface{}

return yaml.Unmarshal([]byte(content), &yml) == nil
}

// IsCSV checks if the passed content of CSV.
func IsCSV(content string) bool {
csvReader := csv.NewReader(strings.NewReader(content))
_, err := csvReader.ReadAll()

return err == nil
}

// CheckFileType checks the file type of the content passed, it validates for YAML/JSON.
func (obj Object) CheckFileType(log *logrus.Logger) string {
log.Debug("identifying the input file type, allowed types are YAML/JSON/CSV")

if IsCSV(string(obj)) {
log.Debug("input file type identified as CSV")

return FileTypeCSV
}

if IsJSON(string(obj)) {
log.Debug("input file type identified as JSON")

return FileTypeJSON
}

if IsYAML(string(obj)) {
log.Debug("input file type identified as YAML")

return FileTypeYAML
}

log.Debug("input file type identified as UNKNOWN")

return FileTypeUnknown
}

func (obj Object) String() string {
return string(obj)
}
98 changes: 98 additions & 0 deletions content/content_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package content_test

import (
"bytes"
"fmt"
"github.com/nikhilsbhat/common/renderer"
"os"
"testing"

"github.com/nikhilsbhat/common/content"
goCdLogger "github.com/nikhilsbhat/gocd-sdk-go/pkg/logger"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)

var log *logrus.Logger

//nolint:gochecknoinits
func init() {
logger := logrus.New()
logger.SetLevel(goCdLogger.GetLoglevel("info"))
logger.WithField("gocd-cli", true)
logger.SetFormatter(&logrus.JSONFormatter{})
log = logger
}

func TestObject_CheckFileType(t *testing.T) {
t.Run("should validate content as json", func(t *testing.T) {
obj := content.Object(`{"name": "testing"}`)

actual := obj.CheckFileType(log)
assert.Equal(t, "json", actual)
})

t.Run("should validate content as unknown since malformed json passed", func(t *testing.T) {
obj := content.Object(`{"name": "testing"`)

actual := obj.CheckFileType(log)
assert.Equal(t, "unknown", actual)
})

t.Run("should validate content as yaml", func(t *testing.T) {
obj := content.Object(`---
name: "testing"`)

actual := obj.CheckFileType(log)
assert.Equal(t, "yaml", actual)
})

t.Run("should validate content as unknown since malformed yaml passed", func(t *testing.T) {
obj := content.Object(`{"name": "testing"`)

actual := obj.CheckFileType(log)
assert.Equal(t, "unknown", actual)
})

t.Run("should validate content as csv", func(t *testing.T) {
fileData, err := os.ReadFile("../fixtures/sample.csv")
assert.NoError(t, err)

obj := content.Object(fileData)
actual := obj.CheckFileType(log)
assert.Equal(t, "csv", actual)
})

t.Run("should fail while validating content as csv", func(t *testing.T) {
fileData, err := os.ReadFile("../fixtures/sample_faulty.csv")
assert.NoError(t, err)

obj := content.Object(fileData)
actual := obj.CheckFileType(log)
assert.Equal(t, "yaml", actual)
})

t.Run("should validate table content as table", func(t *testing.T) {
data := [][]string{
{"sn", "cat", "value"},
{"A", "The Good", "500"},
{"B", "The Very very Bad Man", "288"},
{"C", "The Ugly", "120"},
{"D", "The Gopher", "800"},
}

logger := logrus.New()
strReader := new(bytes.Buffer)

render := renderer.GetRenderer(strReader, logger, false, false, false, true)

err := render.Render(data)
assert.NoError(t, err)

fmt.Printf("value: %s\n", strReader.String())

obj := content.Object(strReader.String())
actual := obj.CheckFileType(log)
assert.Equal(t, "csv", actual)
})
}
5 changes: 5 additions & 0 deletions fixtures/sample.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Identifier,First name,Last name
901242,Rachel,Booker
207074,Laura,Grey
408129,Craig,Johnson
934600,Mary,Jenkins
7 changes: 7 additions & 0 deletions fixtures/sample.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"employee": {
"name": "sonoo",
"salary": 56000,
"married": true
}
}
19 changes: 19 additions & 0 deletions fixtures/sample.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
doe: "a deer, a female deer"
ray: "a drop of golden sun"
pi: 3.14159
xmas: true
french-hens: 3
calling-birds:
- huey
- dewey
- louie
- fred
xmas-fifth-day:
calling-birds: four
french-hens: 3
golden-rings: 5
partridges:
count: 1
location: "a pear tree"
turtle-doves: two
Loading

0 comments on commit 8b7c4a4

Please sign in to comment.