Skip to content

Commit

Permalink
Merge pull request #140 from hibare/dev
Browse files Browse the repository at this point in the history
Use GoCommon
  • Loading branch information
hibare authored Aug 15, 2023
2 parents 272a650 + 0ab034d commit f64e22b
Show file tree
Hide file tree
Showing 17 changed files with 100 additions and 367 deletions.
10 changes: 7 additions & 3 deletions cmd/clean/clean.go → cmd/config/clean.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
package clean
package config

import (
log "github.com/sirupsen/logrus"

"github.com/hibare/GoS3Backup/internal/config"
"github.com/spf13/cobra"
)

var CleanCmd = &cobra.Command{
var CleanConfigCmd = &cobra.Command{
Use: "clean",
Short: "Command to clean up program config",
Run: func(cmd *cobra.Command, args []string) {
config.CleanConfig()
if err := config.CleanConfig(); err != nil {
log.Fatalf("Error: %v", err)
}
},
}
15 changes: 15 additions & 0 deletions cmd/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package config

import (
"github.com/spf13/cobra"
)

var ConfigCmd = &cobra.Command{
Use: "config",
Short: "Manage Application Config",
}

func init() {
ConfigCmd.AddCommand(InitConfigCmd)
ConfigCmd.AddCommand(CleanConfigCmd)
}
21 changes: 21 additions & 0 deletions cmd/config/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package config

import (
"fmt"

"github.com/hibare/GoS3Backup/internal/config"
"github.com/spf13/cobra"
)

var InitConfigCmd = &cobra.Command{
Use: "init",
Short: "Initialize application config",
Run: func(cmd *cobra.Command, args []string) {
if err := config.InitConfig(); err != nil {
fmt.Println(err)
} else {
fmt.Printf("\n\nConfig file path: %s\n", config.BC.ConfigFilePath)
fmt.Printf("Empty config file is loaded at above location. Edit config as per your needs.\n\n")
}
},
}
24 changes: 0 additions & 24 deletions cmd/init/init.go

This file was deleted.

17 changes: 11 additions & 6 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import (

"github.com/go-co-op/gocron"
"github.com/hibare/GoS3Backup/cmd/backup"
"github.com/hibare/GoS3Backup/cmd/clean"
initialize "github.com/hibare/GoS3Backup/cmd/init"
configCmd "github.com/hibare/GoS3Backup/cmd/config"
backup_int "github.com/hibare/GoS3Backup/internal/backup"
"github.com/hibare/GoS3Backup/internal/config"
"github.com/hibare/GoS3Backup/internal/constants"
Expand All @@ -23,7 +22,6 @@ var rootCmd = &cobra.Command{
Long: "",
Version: version.CurrentVersion,
Run: func(cmd *cobra.Command, args []string) {
go version.CheckLatestRelease()

s := gocron.NewScheduler(time.UTC)

Expand All @@ -38,7 +36,7 @@ var rootCmd = &cobra.Command{

// Schedule version check job
if _, err := s.Cron(constants.VersioCheckCron).Do(func() {
version.CheckLatestRelease()
version.V.CheckUpdate()
}); err != nil {
log.Warnf("Failed to scedule version check job: %v", err)
}
Expand All @@ -55,9 +53,16 @@ func Execute() {
}

func init() {
rootCmd.AddCommand(initialize.InitCmd)
rootCmd.AddCommand(clean.CleanCmd)
rootCmd.AddCommand(configCmd.ConfigCmd)
rootCmd.AddCommand(backup.BackupCmd)

cobra.OnInitialize(logging.SetupLogger, config.LoadConfig)

initialVersionCheck := func() {
version.V.CheckUpdate()
if version.V.NewVersionAvailable {
log.Info(version.V.GetUpdateNotification())
}
}
go initialVersionCheck()
}
7 changes: 5 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ go 1.20
require (
github.com/aws/aws-sdk-go v1.44.322
github.com/go-co-op/gocron v1.31.1
github.com/hibare/GoCommon v1.0.0
github.com/jedib0t/go-pretty/v6 v6.4.6
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.7.0
github.com/spf13/viper v1.16.0
gopkg.in/yaml.v3 v3.0.1
)

require (
Expand All @@ -27,9 +26,13 @@ require (
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.16.0 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
go.uber.org/atomic v1.9.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

// replace github.com/hibare/GoCommon => ../GoCommon
4 changes: 3 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hibare/GoCommon v1.0.0 h1:N/VZi2YDt3UCTHwknDFvEsHhKULuTkr4ACaIh6n1bLA=
github.com/hibare/GoCommon v1.0.0/go.mod h1:W7koBLJyuFIQCeCuDx7+p8mDTU6UtMtZ7X6m2UHq4KI=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
Expand Down Expand Up @@ -198,8 +200,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8=
github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
Expand Down
3 changes: 2 additions & 1 deletion internal/backup/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
log "github.com/sirupsen/logrus"

commonDateTimes "github.com/hibare/GoCommon/pkg/datetime"
"github.com/hibare/GoS3Backup/internal/config"
"github.com/hibare/GoS3Backup/internal/constants"
"github.com/hibare/GoS3Backup/internal/notifiers"
Expand Down Expand Up @@ -69,7 +70,7 @@ func ListBackups() []string {
keys = utils.TrimPrefix(keys, prefix)

// Sort datetime strings by descending order
sortedKeys := utils.SortDateTimes(keys)
sortedKeys := commonDateTimes.SortDateTimes(keys)

return sortedKeys
}
Expand Down
112 changes: 23 additions & 89 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
package config

import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"

commonConfig "github.com/hibare/GoCommon/pkg/config"
commonUtils "github.com/hibare/GoCommon/pkg/utils"
"github.com/hibare/GoS3Backup/internal/constants"
"github.com/hibare/GoS3Backup/internal/utils"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)

type S3Config struct {
Expand Down Expand Up @@ -50,24 +43,14 @@ type Config struct {

var Current *Config

func LoadConfig() {
configRootDir := GetConfigRootDir()
preCheckConfigPath(configRootDir)

viper.SetConfigName(constants.ConfigFilename)
viper.AddConfigPath(configRootDir)
viper.SetConfigType(constants.ConfigFileExtension)
var BC commonConfig.BaseConfig

// Load the configuration file
err := viper.ReadInConfig()
func LoadConfig() {
current, err := BC.ReadYAMLConfig(Current)
if err != nil {
log.Fatalf("Error reading config file: %v", err)
}

// Unmarshal the configuration file into a struct
if err := viper.Unmarshal(&Current); err != nil {
log.Fatalf("Error parsing YAML data: %v", err)
}
Current = current.(*Config)

// Set default DateTimeLayout if missing
if Current.Backup.DateTimeLayout == "" {
Expand All @@ -87,81 +70,32 @@ func LoadConfig() {
Current.Backup.Cron = constants.DefaultCron
}

Current.Backup.Hostname = utils.GetHostname()
Current.Backup.Hostname = commonUtils.GetHostname()
}

func CleanConfig() {
configRootDir := GetConfigRootDir()
if info, err := os.Stat(configRootDir); err != nil && os.IsExist(err) {
log.Fatalf("Error %s", err)
} else if !info.IsDir() {
log.Fatalf("Config directory is not a directory: %s", configRootDir)
return
} else {
if err := os.RemoveAll(configRootDir); err != nil {
log.Fatalf("Error removing config directory: %v", err)
}
}
func CleanConfig() error {
return BC.CleanConfig()
}

func GetConfigRootDir() string {
var configRootDir string

switch os := runtime.GOOS; os {
case "linux":
configRootDir = constants.ConfigRootLinux
case "windows":
configRootDir = constants.ConfigRootWindows
case "darwin":
configRootDir = constants.ConfigRootDarwin
default:
log.Fatalf("Unsupported operating system: %s", os)
func InitConfig() error {
if Current == nil {
Current = &Config{}
}

return filepath.Join(configRootDir, strings.ToLower(constants.ProgramIdentifier))
}
if err := BC.WriteYAMLConfig(Current); err != nil {
return err
}

func GetConfigFilePath(configRootDir string) string {
return filepath.Join(configRootDir, fmt.Sprintf("%s.%s", constants.ConfigFilename, constants.ConfigFileExtension))
return nil
}

func preCheckConfigPath(configRootDir string) {

configPath := GetConfigFilePath(configRootDir)

if info, err := os.Stat(configRootDir); os.IsNotExist(err) {
log.Warnf("Config directory does not exist, creating: %s", configRootDir)
if err := os.MkdirAll(configRootDir, 0755); err != nil {
log.Fatalf("Error creating config directory: %v", err)
return
}
} else if !info.IsDir() {
log.Fatalf("Config directory is not a directory: %s", configRootDir)
return
func init() {
BC = commonConfig.BaseConfig{
ProgramIdentifier: constants.ProgramIdentifier,
OS: commonConfig.ActualOS{},
}

if info, err := os.Stat(configPath); os.IsNotExist(err) {
log.Warnf("Config file does not exist, creating: %s", configPath)
file, err := os.Create(configPath)
if err != nil {
log.Fatalf("Error creating config file: %v", err)
return
}
defer file.Close()

// Marshal empty config
yamlBytes, err := yaml.Marshal(Config{})
if err != nil {
log.Fatalf("Error marshaling config: %v", err)
}

// Write the YAML output to a file
if _, err := file.Write(yamlBytes); err != nil {
log.Fatalf("Error writing config file: %v", err)
}

} else if info.IsDir() {
log.Fatalf("Expected file, found directory: %s", configPath)
return
if err := BC.Init(); err != nil {
panic(err)
}

}
5 changes: 0 additions & 5 deletions internal/constants/constants.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
package constants

const (
ConfigRootLinux = "/etc/"
ConfigRootWindows = "C:\\ProgramData\\"
ConfigRootDarwin = "/Library/Application Support/"
ConfigFilename = "config"
ConfigFileExtension = "yaml"
ProgramIdentifier = "GoS3Backup"
DefaultDateTimeLayout = "20060102150405"
DefaultRetentionCount = 30
Expand Down
5 changes: 2 additions & 3 deletions internal/notifiers/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,9 @@ type DiscordComponent struct {
}

func (d *DiscordWebhookMessage) AddFooter() {
isUpdate, LatestVersion := version.IsNewVersionAvailable()
if isUpdate {
if version.V.NewVersionAvailable {
footer := DiscordEmbedFooter{
Text: fmt.Sprintf(version.UpdateNotificationMessage, LatestVersion),
Text: version.V.GetUpdateNotification(),
}
d.Embeds[0].Footer = footer
}
Expand Down
6 changes: 3 additions & 3 deletions internal/s3/s3.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
commonFiles "github.com/hibare/GoCommon/pkg/file"
"github.com/hibare/GoS3Backup/internal/config"
"github.com/hibare/GoS3Backup/internal/utils"
log "github.com/sirupsen/logrus"
)

Expand All @@ -35,7 +35,7 @@ func Upload(sess *session.Session, bucket, prefix, baseDir string) (int, int, in
client := s3.New(sess)
baseDirParentPath := filepath.Dir(baseDir)

files, dirs := utils.ListFilesDirs(baseDir, nil)
files, dirs := commonFiles.ListFilesDirs(baseDir, nil)

totalFiles = len(files)
totalDirs = len(dirs)
Expand Down Expand Up @@ -68,7 +68,7 @@ func Upload(sess *session.Session, bucket, prefix, baseDir string) (int, int, in
func UploadZip(sess *session.Session, bucket, prefix, baseDir string) (int, int, int) {
totalFiles, totalDirs, successFiles := 0, 0, 0

err, zipPath, totalFiles, totalDirs, successFiles := utils.ArchiveDir(baseDir)
zipPath, totalFiles, totalDirs, successFiles, err := commonFiles.ArchiveDir(baseDir)

if err != nil {
log.Errorf("Error creating zip file: %v", err)
Expand Down
Loading

0 comments on commit f64e22b

Please sign in to comment.