Skip to content

Commit

Permalink
Merge pull request #11 from smartrecruiters/download-upload
Browse files Browse the repository at this point in the history
Introduced upload and download commands
  • Loading branch information
jaroslaw-bochniak authored Jul 13, 2022
2 parents 356ebbc + b41d3ae commit c8a5305
Show file tree
Hide file tree
Showing 469 changed files with 62,475 additions and 27,564 deletions.
4 changes: 2 additions & 2 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ brews:
# Git author used to commit to the repository.
# Defaults are shown.
commit_author:
name: CoreTeam
email: core@smartrecruiters.com
name: CnC
email: cnc@smartrecruiters.com

# Your app's homepage.
# Default is empty.
Expand Down
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
language: go
go: '1.17'
go: '1.18.4'

before_install:
- go install golang.org/x/lint/golint@latest
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
FILES := $(shell find . -type f -name '*.go' -not -path "./vendor/*")

APP_NAME=rabbitr
VERSION=1.3.3
VERSION=1.4.0

.PHONY: all test build fmt install release ci lint install-lint

Expand Down
48 changes: 29 additions & 19 deletions cmd/commons/application_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
// ServerCoordinates describes server configuration parameters
type ServerCoordinates struct {
APIURL string `json:"apiUrl"`
AmqpURL string `json:"amqpUrl"`
Username string `json:"username"`
Password string `json:"password"`
}
Expand All @@ -36,23 +37,32 @@ func (cfg *Config) GetServerNames() []string {
return serverNames
}

// GetServerPassword returns password for a server
func (cfg *Config) GetServerPassword(serverName string) string {
server := cfg.Servers[serverName]
if server == nil {
return ""
}
return server.Password
}

var cachedConfig *Config
var once sync.Once

// GetCachedApplicationConfig returns cached application config
func GetCachedApplicationConfig() Config {
func GetCachedApplicationConfig(server string) Config {
once.Do(func() {
cfg, err := GetApplicationConfig()
cfg, err := GetApplicationConfig(server)
AbortIfError(err)
cachedConfig = &cfg
})
return *cachedConfig
}

// GetApplicationConfig returns fresh application config read from a file
func GetApplicationConfig() (Config, error) {
func GetApplicationConfig(server string) (Config, error) {
var cfg Config
err := getApplicationConfig(&cfg, ApplicationName)
err := getApplicationConfig(&cfg, ApplicationName, server)
if err != nil {
return cfg, err
}
Expand All @@ -61,9 +71,9 @@ func GetApplicationConfig() (Config, error) {
}

// UpdateApplicationConfig writes application config to a file
func UpdateApplicationConfig(cfg Config) error {
func UpdateApplicationConfig(cfg Config, serverName string) error {
if IsOSX() {
err := storePasswordsInKeyChain(&cfg)
err := storePasswordInKeyChain(serverName, cfg.GetServerPassword(serverName))
if err != nil {
return err
}
Expand All @@ -72,7 +82,7 @@ func UpdateApplicationConfig(cfg Config) error {
return updateApplicationConfig(cfg, ApplicationName)
}

func getApplicationConfig(configStructure *Config, applicationName string) error {
func getApplicationConfig(configStructure *Config, applicationName, server string) error {
cfgPath, err := getAppConfigFilePath(applicationName)
if err != nil {
return err
Expand All @@ -95,7 +105,7 @@ func getApplicationConfig(configStructure *Config, applicationName string) error

// for MacOS try to obtain passwords from keychain
if IsOSX() {
return fillPasswordsFromKeyChain(configStructure)
return fillPasswordsFromKeyChain(configStructure, server)
}

return nil
Expand Down Expand Up @@ -143,8 +153,11 @@ func updateApplicationConfig(configStructure interface{}, applicationName string
return ioutil.WriteFile(appCfgPath, configJSON, 0644)
}

func fillPasswordsFromKeyChain(configStructure *Config) error {
func fillPasswordsFromKeyChain(configStructure *Config, server string) error {
for serverName, coordinates := range configStructure.Servers {
if len(server) > 0 && serverName != server {
continue
}
srvPass, err := keyring.Get(ApplicationName, serverName)
if err != nil && err != keyring.ErrNotFound {
return err
Expand All @@ -157,17 +170,14 @@ func fillPasswordsFromKeyChain(configStructure *Config) error {
return nil
}

func storePasswordsInKeyChain(configStructure *Config) error {
func storePasswordInKeyChain(serverName, password string) error {
var result error
for serverName, coordinates := range configStructure.Servers {
err := keyring.Set(ApplicationName, serverName, coordinates.Password)
if err != nil {
Debugf("Error storing password in keychain for %s, %s", serverName, err)
result = err
} else {
Debugf("Password for %s stored in keychain successfully", serverName)
coordinates.Password = ""
}
err := keyring.Set(ApplicationName, serverName, password)
if err != nil {
Debugf("Error storing password in keychain for %s, %s", serverName, err)
result = err
} else {
Debugf("Password for %s stored in keychain successfully", serverName)
}
return result
}
20 changes: 20 additions & 0 deletions cmd/commons/cli_commons.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ func AskForIntIf(testFn func(int) bool, value int, msg string) int {
return value
}

// LessOrEqualThanZeroValidator checks if provided int is > 0
func LessOrEqualThanZeroValidator(i int) bool {
return i <= 0
}

// AskForPasswordIfEmpty prompts user for a password in case it was not provided beforehand
func AskForPasswordIfEmpty(value, name string) string {
value = strings.TrimSpace(value)
Expand Down Expand Up @@ -137,6 +142,12 @@ func IsURL(str string) bool {
return err == nil && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https")
}

// IsAmqpURL returns true if provided value is an amqp url
func IsAmqpURL(str string) bool {
u, err := url.Parse(str)
return err == nil && u.Host != "" && (u.Scheme == "amqp" || u.Scheme == "amqps")
}

// IsURLValidator returns validator for checking urls
func IsURLValidator(value interface{}) error {
text := strings.TrimSpace(value.(string))
Expand All @@ -145,3 +156,12 @@ func IsURLValidator(value interface{}) error {
}
return nil
}

// IsAmqpURLValidator returns validator for checking amqp urls
func IsAmqpURLValidator(value interface{}) error {
text := strings.TrimSpace(value.(string))
if !IsAmqpURL(text) {
return errors.New("please provide valid AMQP URL")
}
return nil
}
72 changes: 65 additions & 7 deletions cmd/commons/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,47 @@ import (
"fmt"
"io"
"log"
"net/http"
"os"
"runtime"
"strings"
"text/tabwriter"
)

var (
errLog = log.New(os.Stderr, "[ERROR] ", log.LstdFlags|log.Lmsgprefix)
infoLog = log.New(os.Stdout, "", 0)
)

// AbortIfTrue aborts the program execution depending on a provided condition and logs provided message
func AbortIfTrue(condition bool, message string) {
if condition {
log.Fatal(message)
errLog.Fatal(message)
}
}

// AbortIfError aborts the program execution depending on a provided error and logs provided messages
func AbortIfError(err error, messages ...interface{}) {
if err != nil {
if len(messages) > 0 {
log.Fatal(messages...)
errLog.Fatal(messages...)
} else {
log.Fatal(err)
errLog.Fatal(err)
}
}
}

// AbortIfErrorWithMsg aborts the program execution depending on a provided error and logs provided message
func AbortIfErrorWithMsg(msg string, err error) {
if err != nil {
log.Fatalf(msg, err.Error())
errLog.Fatalf(msg, err.Error())
}
}

// PrintIfTrue prints provided message depending on a condition
func PrintIfTrue(condition bool, msg string) {
if condition {
log.Println(msg)
infoLog.Println(msg)
}
}

Expand All @@ -51,7 +58,7 @@ func PrintToWriterIfErrorWithMsg(w *tabwriter.Writer, msg string, err error) {
// PrintIfErrorWithMsg prints provided message depending on a provided error
func PrintIfErrorWithMsg(msg string, err error) {
if err != nil {
log.Printf(msg, err.Error())
errLog.Printf(msg, err.Error())
}
}

Expand All @@ -70,11 +77,62 @@ func Fprintf(w io.Writer, format string, a ...interface{}) {
// PrintIfError prints error if it was provided
func PrintIfError(err error) {
if err != nil {
log.Printf(err.Error())
errLog.Printf(err.Error())
}
}

// IsOSX checks if running system is OSX
func IsOSX() bool {
return strings.Contains(runtime.GOOS, "darwin")
}

// GetStringOrDefault returns value or default value
func GetStringOrDefault(value, defaultValue string) string {
if value != "" {
return value
}
return defaultValue
}

// GetStringOrDefaultIfValue returns returnValue or default value depending on the valueToCheck
func GetStringOrDefaultIfValue(valueToCheck, returnValue, defaultValue string) string {
if valueToCheck != "" {
return returnValue
}
return defaultValue
}

// HandleGeneralResponse handles general response from rabbit client.
// Prints response code and error details if able.
func HandleGeneralResponse(messagePrefix string, res *http.Response) {
if res == nil {
return
}
Fprintf(os.Stdout, messagePrefix+", Response code: %d\t\n", res.StatusCode)
PrintResponseBodyToWriterIfError(os.Stdout, res)
}

// HandleGeneralResponseWithWriter handles general response from rabbit client.
// Prints response code and error details if able.
// Writes output to the provided writer.
func HandleGeneralResponseWithWriter(w *tabwriter.Writer, res *http.Response) {
if res == nil {
return
}
Fprintf(w, "Response code: %d\t", res.StatusCode)
PrintResponseBodyToWriterIfError(w, res)
}

// PrintResponseBodyToWriterIfError prints response body to provided writer
// for responses with code >= 400 to obtain as much error details as possible.
func PrintResponseBodyToWriterIfError(w io.Writer, res *http.Response) {
if res == nil || res.StatusCode < 400 {
return
}
buf := new(strings.Builder)
_, err := io.Copy(buf, res.Body)
if err != nil {
Fprintf(w, err.Error())
}
Fprintf(w, buf.String())
}
10 changes: 9 additions & 1 deletion cmd/commons/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
var (
// IsDebugEnabled is true when the DEBUG env var is not empty.
IsDebugEnabled = os.Getenv("DEBUG") != ""
debugLog = log.New(os.Stdout, "[DEBUG] ", log.LstdFlags|log.Lmsgprefix)
)

// MessageProvider allows for definition of MessageProvider that will be invoked in order to obtain the message before logging it.
Expand All @@ -21,6 +22,13 @@ func Debug(message string) {
printfMsg(message)
}

// DebugIfError prints message when debug mode is enabled and error has occured.
func DebugIfError(err error) {
if err != nil {
printfMsg(err.Error())
}
}

// Debugf prints message when debug mode is enabled. Substitutes format with provided arguments. Works like fmt.Sprintf.
func Debugf(message string, args ...interface{}) {
printfMsg(message, args...)
Expand All @@ -36,6 +44,6 @@ func LazyDebug(getMsgFn MessageProvider) {
// printfMsg prints the message if logging is enabled.
func printfMsg(msg string, v ...interface{}) {
if IsDebugEnabled {
log.Print(color.CyanString(fmt.Sprintf(msg, v...)))
debugLog.Print(color.CyanString(fmt.Sprintf(msg, v...)))
}
}
8 changes: 8 additions & 0 deletions cmd/commons/fileutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,11 @@ func MakeDir(path string) (err error) {
}
return err
}

// FileExists checks whatever file under given path exists
func FileExists(path string) bool {
if _, err := os.Stat(path); err == nil {
return true
}
return false
}
Loading

0 comments on commit c8a5305

Please sign in to comment.