From b9de391d0f62c12f1443272c626bad66fe43934b Mon Sep 17 00:00:00 2001 From: poniatowski-bot Date: Tue, 6 Aug 2024 12:48:09 +0000 Subject: [PATCH] Automated commit by Forgejo CI/CD [v1.5.4] - Personal CI/CD Bot --- CHANGELOG | 8 ++--- VERSION | 2 +- cmd/zehd/main.go | 14 ++++++++ pkg/backendconnector/backendConnector.go | 22 ++++++++++++ pkg/caching/caching.go | 20 +++++++++++ pkg/caching/cachingHelpers.go | 44 ++++++++++++++++++++++++ pkg/caching/git.go | 3 ++ pkg/caching/gitHelpers.go | 36 ++++++++++++++++--- pkg/caching/handlers.go | 18 ++++++++++ pkg/datacapturing/dataCapturing.go | 5 +++ pkg/env/env.go | 25 ++++++++++++++ pkg/pkg.go | 11 ++++++ 12 files changed, 199 insertions(+), 9 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 5f80bb8..b34079a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,4 +1,4 @@ -## [1.5.2] - 28-07-2024 -### Updated -- made the config initialization more visual (orange for default and green for configured) -- fixed a bug, where it only fetched the code and not merge it (ala pull), I renamed the private function from gitFetcher() to gitPull(), instead of creating a private pull function to be called in gitFetcher() +## [1.5.4] - 05-08-2024 +### Update +- added git dir check in gitClone, as the first output makes it look horrible +- adding whitespace... for those who are "idiomatically" inclined and finds it hard to read diff --git a/VERSION b/VERSION index 4cda8f1..94fe62c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.5.2 +1.5.4 diff --git a/cmd/zehd/main.go b/cmd/zehd/main.go index 86bf29f..1308f68 100644 --- a/cmd/zehd/main.go +++ b/cmd/zehd/main.go @@ -23,13 +23,16 @@ import ( func main() { isReady := &atomic.Value{} isReady.Store(false) + // Starting liveness probe fmt.Printf(" Starting liveness probe...") http.HandleFunc("/k8s/api/health", kubernetes.Healthz) fmt.Println(" Done.") + // cloning repo from git source, if specified. fmt.Println(" Checking git repo:") fmt.Printf(" Cloning") + if len(pkg.GitLink) == 0 { fmt.Printf("... Skipped.\n") } else { @@ -41,6 +44,7 @@ func main() { fmt.Println(" Done.") } } + // init caching via go func(){check files for changes and figure out a way to pass them to handler} fmt.Printf(" Building and Caching templates...") cache := &caching.Pages{} @@ -59,6 +63,7 @@ func main() { } }() fmt.Println(" Done.") + // JS and CSS handling/serving fmt.Printf(" Serving Static paths:\n") fmt.Printf(" CSS...") @@ -68,6 +73,7 @@ func main() { } else { fmt.Println(" Disabled.") } + fmt.Printf(" JS... ") if pkg.Javascript != pkg.Disable { http.Handle("/"+pkg.Javascript+"/", http.StripPrefix("/"+pkg.Javascript+"/", http.FileServer(http.Dir(pkg.TemplatesDir+pkg.Javascript)))) @@ -75,6 +81,7 @@ func main() { } else { fmt.Println(" Disabled.") } + fmt.Printf(" Images... ") if pkg.Images != pkg.Disable { http.Handle("/"+pkg.Images+"/", http.StripPrefix("/"+pkg.Images+"/", http.FileServer(http.Dir(pkg.TemplatesDir+pkg.Images)))) @@ -82,6 +89,7 @@ func main() { } else { fmt.Println(" Disabled.") } + fmt.Printf(" Downloads... ") if pkg.Downloads != pkg.Disable { http.Handle("/"+pkg.Downloads+"/", http.StripPrefix("/"+pkg.Downloads+"/", http.FileServer(http.Dir(pkg.TemplatesDir+pkg.Downloads)))) @@ -89,12 +97,14 @@ func main() { } else { fmt.Println(" Disabled.") } + // Initialize the database and determine if collector should be enabled fmt.Printf(" Initializing Database...") errEnv := godotenv.Load("/usr/local/env/.env") if errEnv != nil { boillog.LogIt("DatabaseExists", "ERROR", "error loading .env variables") } + pkg.CollectionError = backendconnector.DatabaseInit() if pkg.CollectionError != nil { log.Println(" Failed.") @@ -102,15 +112,19 @@ func main() { } else { fmt.Println(" Done.") } + // Page serving section fmt.Printf(" Initializing Routes...") http.HandleFunc("/favicon.ico", pkg.FaviconHandler) // favicon http.HandleFunc("/", cache.HandlerFunc) fmt.Println(" Done.") + // Starting readiness probe fmt.Printf(" Starting readiness probe...") http.HandleFunc("/k8s/api/ready", kubernetes.Readyz(isReady)) fmt.Println(" Done.") + + // Starting server fmt.Printf(" Starting HTTP server on %v port %v...\n", env.EnvHostname(), strings.TrimLeft(env.EnvPort(), ":")) fmt.Println("<======================================================================================>") err := http.ListenAndServe(env.EnvPort(), nil) diff --git a/pkg/backendconnector/backendConnector.go b/pkg/backendconnector/backendConnector.go index d55879d..8104a4d 100644 --- a/pkg/backendconnector/backendConnector.go +++ b/pkg/backendconnector/backendConnector.go @@ -18,8 +18,10 @@ import ( // DatabaseInit Initialize the database with tables, if the check returns false func DatabaseInit() error { defer boillog.TrackTime("db-init", time.Now()) + var databaseInfo DatabaseExistsInfo databaseInfo.DatabaseExists() + if databaseInfo.Tables == "exists" { boillog.LogIt("DatabaseInit", "INFO", "database already exists") } else { @@ -50,17 +52,21 @@ func DatabaseInit() error { // DatabaseExists Check if database exists and has existing tables func (dbInfo *DatabaseExistsInfo) DatabaseExists() { defer boillog.TrackTime("db-exists", time.Now()) + backendURL := os.Getenv("BACKEND") + if len(backendURL) == 0 { dbInfo.Connection = "no env var" return } + response, errHTTPGet := http.Get(backendURL + "/database/exist") if errHTTPGet != nil { dbInfo.Connection = "failed" boillog.LogIt("DatabaseExists", "ERROR", "unable to reach backend on "+backendURL) return } + defer func() { errClose := response.Body.Close() if errClose != nil { @@ -70,26 +76,35 @@ func (dbInfo *DatabaseExistsInfo) DatabaseExists() { } }() + body, _ := io.ReadAll(response.Body) + dbInfo.Tables = string(body) // TODO reading results from here + boillog.LogIt("DatabaseInit", "INFO", "received: \""+dbInfo.Tables+"\" from "+backendURL+"(GET request)") } func (dbInfo *DatabaseExistsInfo) DatabaseCreate() { // create post request defer boillog.TrackTime("create-db", time.Now()) + backendURL := os.Getenv("BACKEND") + if len(backendURL) == 0 { dbInfo.Connection = "no env var" boillog.LogIt("DatabaseCreate", "WARNING", "no backend to send data to, please add backend url as env variable") return } + dbInfo.Tables = "create" + req, _ := json.Marshal(dbInfo) + response, errHTTPGet := http.Post(backendURL+"/database/exist", "application/json", bytes.NewBuffer(req)) if errHTTPGet != nil { boillog.LogIt("DatabaseCreate", "ERROR", "unable to reach backend") } + defer func() { errClose := response.Body.Close() if errClose != nil { @@ -101,12 +116,16 @@ func (dbInfo *DatabaseExistsInfo) DatabaseCreate() { // DBConnector Function to insert request data into the database func (rD *RequestData) DBConnector(waitGroup *sync.WaitGroup) { defer boillog.TrackTime("db-connector", time.Now()) + waitGroup.Add(1) + jsonToBackend, errMarshal := json.Marshal(rD) if errMarshal != nil { boillog.LogIt("DBConnector", "ERROR", "unable to marshal json request") } + backendURL := os.Getenv("BACKEND") + if len(backendURL) == 0 { boillog.LogIt("DBConnector", "WARNING", "no backend to send data to, please add backend url as env variable") } else { @@ -114,17 +133,20 @@ func (rD *RequestData) DBConnector(waitGroup *sync.WaitGroup) { if errResp != nil { boillog.LogIt("DBConnector", "ERROR", "unable to send json request, response error received") } + defer func() { errClose := resp.Body.Close() if errClose != nil { boillog.LogIt("DBConnector", "ERROR", "unable to close response body") } }() + if resp.StatusCode == 200 { log.Println("User data sent to database successfully") } else if resp.StatusCode == 500 { boillog.LogIt("DBConnector", "WARNING", "no backend to send data to, please add backend url as env variable") } } + waitGroup.Done() } diff --git a/pkg/caching/caching.go b/pkg/caching/caching.go index 7e58f89..52ae064 100644 --- a/pkg/caching/caching.go +++ b/pkg/caching/caching.go @@ -15,54 +15,74 @@ import ( // CachePages Method that walks the specified or default directories and caches the templates func (pages *Pages) CachePages() error { defer boillog.TrackTime("cacher", time.Now()) + if len(pkg.GitLink) != 0 { err := Git("refresh") if err != nil { boillog.LogIt("CachePages", "ERROR", err.Error()) + return err } + + return nil } errchdir := os.Chdir(pkg.TemplatesDir + pkg.TemplateType) if errchdir != nil { boillog.LogIt("cachepages", "error", "chdir returned an error: "+fmt.Sprintln(errchdir)) } + err := filepath.WalkDir(pkg.TemplatesDir+pkg.TemplateType, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } + if d.IsDir() { return nil } + pathtoremove := pkg.TemplatesDir + pkg.TemplateType + indextoremove := strings.Index(path, pathtoremove) if indextoremove == -1 { boillog.LogIt("cachepages", "error", "directory not found") } + croppedtemplatepath := strings.TrimPrefix(path[indextoremove+len(pathtoremove):], "/") + var filetype string + switch filepath.Ext(path) { case ".gohtml": filetype = ".gohtml" + case ".html": filetype = ".html" + case ".md": filetype = ".md" + case ".org": filetype = ".org" + default: filetype = "invalid" } + name := strings.TrimSuffix(croppedtemplatepath, filepath.Ext(path)) + tmpl, err := templateBuilder(croppedtemplatepath, filetype) if err != nil { return fmt.Errorf("failed to build template for file %q: %v", path, err) } + pages.RouteMap[name] = tmpl + return nil }) if err != nil { boillog.LogIt("cachepages", "error", "walkdir returned an error: "+fmt.Sprintln(err)) return err } + return nil } diff --git a/pkg/caching/cachingHelpers.go b/pkg/caching/cachingHelpers.go index ed445a8..3475f2c 100644 --- a/pkg/caching/cachingHelpers.go +++ b/pkg/caching/cachingHelpers.go @@ -18,35 +18,52 @@ import ( // pageBuilder Private helper function that builds HTML/goHTML pages and returns the templates func pageBuilder(templatePath, layoutPath string) (*template.Template, error) { defer boillog.TrackTime("page-builder", time.Now()) + funcmytemplates := funcmytemplate.Add() + templates := template.New("layout") + _, err := os.Stat(layoutPath) if err != nil { templates, err = templates.Funcs(funcmytemplates).ParseFiles(templatePath) } else { templates, err = templates.Funcs(funcmytemplates).ParseFiles(layoutPath, templatePath) } + if err != nil { return nil, err } + + if templates == nil { + return nil, fmt.Errorf("template is nil") + } + return templates, nil } // convertOrgToTemplate Private helper function that builds org-mode pages and returns the templates func convertOrgToTemplate(orgPath, layoutPath string) (*template.Template, error) { defer boillog.TrackTime("org-converter", time.Now()) + var errReturn error + funcmytemplates := funcmytemplate.Add() + templates := template.New("") + _, notFoundErr := os.Stat(layoutPath) if notFoundErr != nil { orgBytes, err := os.ReadFile(orgPath) if err != nil { return nil, err } + htmlBytes := blackfriday.Run(orgBytes) + html := string(htmlBytes) + html = fmt.Sprintf(`{{define "org"}}%s{{end}}`, html) + templates, err = templates.Funcs(funcmytemplates).Parse(html) if err != nil { return nil, err @@ -57,37 +74,50 @@ func convertOrgToTemplate(orgPath, layoutPath string) (*template.Template, error return nil, err } htmlBytes := blackfriday.Run(orgBytes) + html := string(htmlBytes) + html = fmt.Sprintf(`{{define "org"}}%s{{end}}`, html) + templates, err = templates.Funcs(funcmytemplates).ParseFiles(layoutPath) if err != nil { errReturn = err } + templates, err = templates.Funcs(funcmytemplates).Parse(html) if err != nil { errReturn = err } } + if errReturn != nil { return nil, errReturn } + return templates, nil } // convertMarkdownToTemplate Private helper function that builds markdown pages and returns the templates func convertMarkdownToTemplate(markdownPath, layoutPath string) (*template.Template, error) { defer boillog.TrackTime("md-converter", time.Now()) + var errReturn error + funcmytemplates := funcmytemplate.Add() + templates := template.New("") + _, notFoundErr := os.Stat(layoutPath) if notFoundErr != nil { markdownBytes, err := os.ReadFile(layoutPath) if err != nil { return nil, err } + html := string(markdown.ToHTML(markdownBytes, nil, nil)) + html = fmt.Sprintf(`{{define "markdown"}}%s{{end}}`, html) + templates, err = templates.Funcs(funcmytemplates).Parse(html) if err != nil { return nil, err @@ -97,12 +127,16 @@ func convertMarkdownToTemplate(markdownPath, layoutPath string) (*template.Templ if err != nil { return nil, err } + html := string(markdown.ToHTML(markdownBytes, nil, nil)) + html = fmt.Sprintf(`{{define "markdown"}}%s{{end}}`, html) + templates, err = templates.Funcs(funcmytemplates).ParseFiles(layoutPath) if err != nil { errReturn = err } + templates, err = templates.Funcs(funcmytemplates).Parse(html) if err != nil { errReturn = err @@ -111,35 +145,45 @@ func convertMarkdownToTemplate(markdownPath, layoutPath string) (*template.Templ if errReturn != nil { return nil, errReturn } + return templates, nil } // templateBuilder Private function for building templates, which is called by CachePages func templateBuilder(page, filetype string) (*template.Template, error) { defer boillog.TrackTime("template-builder", time.Now()) + if filetype == "invalid" { return nil, errors.New("invalid filetype: " + page) } + layoutpage := pkg.TemplatesDir + "layout." + pkg.TemplateType + templatepage := pkg.TemplatesDir + pkg.TemplateType + "/" + page + _, notfounderr := os.Stat(templatepage) if notfounderr != nil { if os.IsNotExist(notfounderr) { return nil, errors.New("template does not exist: " + page) } } + var parseerr error var templates *template.Template + switch filetype { case ".org": templates, parseerr = convertOrgToTemplate(templatepage, layoutpage) + case ".md": templates, parseerr = convertMarkdownToTemplate(templatepage, layoutpage) + default: templates, parseerr = pageBuilder(templatepage, layoutpage) } if parseerr != nil { return nil, errors.New("error parsing templates: " + fmt.Sprintln(parseerr)) } + return templates, nil } diff --git a/pkg/caching/git.go b/pkg/caching/git.go index 6cf03fa..25897c3 100644 --- a/pkg/caching/git.go +++ b/pkg/caching/git.go @@ -11,13 +11,16 @@ func Git(action string) error { if err != nil { return err } + case "refresh": err := gitPull() if err != nil { return err } + default: return fmt.Errorf("unknown error encountered, possible buffer overflow") } + return nil } diff --git a/pkg/caching/gitHelpers.go b/pkg/caching/gitHelpers.go index d67074d..33cca6f 100644 --- a/pkg/caching/gitHelpers.go +++ b/pkg/caching/gitHelpers.go @@ -29,11 +29,15 @@ func gitCloner() error { } } - _, err = git.PlainClone(pkg.TemplatesDir, false, cloneOptions) - if err != nil { - boillog.LogIt("gitCloner", "WARNING", err.Error()) + if !isGitRepo(pkg.TemplatesDir) { + _, err = git.PlainClone(pkg.TemplatesDir, false, cloneOptions) + if err != nil { + boillog.LogIt("gitCloner", "WARNING", err.Error()) + return err + } } - return err + + return nil } func gitPull() error { @@ -42,21 +46,25 @@ func gitPull() error { boillog.LogIt("gitPull", "ERROR", "Failed to open repository: "+err.Error()) return err } + w, err := r.Worktree() if err != nil { boillog.LogIt("gitPull", "ERROR", "Failed to get worktree: "+err.Error()) return err } + pullOptions := &git.PullOptions{ RemoteName: "origin", InsecureSkipTLS: true, } + if len(pkg.GitUsername) > 0 && len(pkg.GitToken) > 0 { pullOptions.Auth = &http.BasicAuth{ Username: pkg.GitUsername, Password: pkg.GitToken, } } + err = w.Pull(pullOptions) if err != nil { if err == git.NoErrAlreadyUpToDate { @@ -70,6 +78,7 @@ func gitPull() error { return nil } boillog.LogIt("gitPull", "WARNING", "Failed to pull updates: "+err.Error()) + return err } ref, err := r.Head() @@ -80,6 +89,7 @@ func gitPull() error { commitHash := ref.Hash().String() boillog.LogIt("gitPull", "INFO", fmt.Sprintf("Repository updated successfully to commit %s", commitHash)) + return nil } @@ -88,6 +98,7 @@ func makeDir() error { if err != nil { if os.IsExist(err) { boillog.LogIt("gitCloner", "INFO", error.Error(err)) + return nil } else if os.IsPermission(err) { boillog.LogIt("gitCloner", "ERROR", error.Error(err)) @@ -97,8 +108,10 @@ func makeDir() error { switch errno { case unix.ENOSPC: boillog.LogIt("gitCloner", "ERROR", "No space left on device.") + case unix.EROFS: boillog.LogIt("gitCloner", "ERROR", "Read-only file system.") + default: boillog.LogIt("gitCloner", "ERROR", "Unknown error: "+error.Error(err)) } @@ -109,7 +122,22 @@ func makeDir() error { boillog.LogIt("gitCloner", "ERROR", "Unexpected error type: "+error.Error(err)) } } + return err } + return nil } + +func isGitRepo(path string) bool { + if _, err := os.Stat(path); os.IsNotExist(err) { + return false + } + + gitDir := path + ".git" + if _, err := os.Stat(gitDir); os.IsNotExist(err) { + return false + } + + return true +} diff --git a/pkg/caching/handlers.go b/pkg/caching/handlers.go index dfaa14e..f6aa92d 100644 --- a/pkg/caching/handlers.go +++ b/pkg/caching/handlers.go @@ -20,6 +20,7 @@ func (pages *Pages) HandlerFunc(w http.ResponseWriter, r *http.Request) { } else { go datacapturing.CollectData(r) } + // Handle command line curl/wget and give their IP address back. if strings.Contains(r.Header.Get("User-Agent"), "curl") || strings.Contains(r.Header.Get("User-Agent"), "Wget") || @@ -30,9 +31,11 @@ func (pages *Pages) HandlerFunc(w http.ResponseWriter, r *http.Request) { _, ipErr := fmt.Fprintf(w, "userip: %q is not IP:port\n", r.RemoteAddr) if ipErr != nil { log.Println(ipErr) + return } } + userIP := net.ParseIP(ipAddress) if userIP == nil { _, err := fmt.Fprintf(w, "userip: %q is not IP:port", r.RemoteAddr) @@ -40,12 +43,15 @@ func (pages *Pages) HandlerFunc(w http.ResponseWriter, r *http.Request) { log.Println(err) } boillog.LogIt("handlerFunc", "ERROR", "user_ip: "+r.RemoteAddr+" is not IP:port") + return } + _, errWrite := fmt.Fprintf(w, "Your IP is: %s\n", ipAddress) if errWrite != nil { log.Println(errWrite) } + forward := r.Header.Get("X-FORWARDED-FOR") if forward != "" { _, errWrite := fmt.Fprintf(w, "Forwarded for: %s\n", forward) @@ -53,9 +59,12 @@ func (pages *Pages) HandlerFunc(w http.ResponseWriter, r *http.Request) { log.Println(errWrite) } } + return } + w.Header().Set("Content-Type", "text/html") + pageNotFound := false switch r.Method { @@ -63,29 +72,38 @@ func (pages *Pages) HandlerFunc(w http.ResponseWriter, r *http.Request) { templates, ok := pages.RouteMap[strings.Trim(r.URL.Path, "/")] if r.URL.Path == "/" || r.URL.Path == "" { templates = pages.RouteMap["welcome"] + if templates == nil { + templates = pages.RouteMap["index"] + } } else { if !ok { if pages.RouteMap["404"] == nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) boillog.LogIt("500", "ERROR", " --> welcome."+pkg.TemplateType+" not found") + return } + templates = pages.RouteMap["404"] boillog.LogIt("404", "ERROR", "user_ip ["+r.RemoteAddr+"] : Page requested not found") pageNotFound = true } } + if pageNotFound { w.WriteHeader(http.StatusNotFound) } + tmplErr := templates.ExecuteTemplate(w, "layout", nil) if tmplErr != nil { log.Println(tmplErr.Error()) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) boillog.LogIt("500", "ERROR", "user_ip ["+r.RemoteAddr+"] : Issue sending 'layout'") } + case "POST": fmt.Println("Feature not implemented yet...") + default: http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) boillog.LogIt("405", "ERROR", "user_ip ["+r.RemoteAddr+"] : Method not allowed") diff --git a/pkg/datacapturing/dataCapturing.go b/pkg/datacapturing/dataCapturing.go index 6de6916..3f2a66f 100644 --- a/pkg/datacapturing/dataCapturing.go +++ b/pkg/datacapturing/dataCapturing.go @@ -18,6 +18,7 @@ import ( // CollectData Collects all data from http request, parses it and sends it to the database func CollectData(r *http.Request) { defer boillog.TrackTime("data-collector", time.Now()) + var rD backendconnector.RequestData var errHostname error var waitGroup sync.WaitGroup @@ -46,11 +47,13 @@ func CollectData(r *http.Request) { if errHostname != nil { boillog.LogIt("CollectData", "ERROR", "unable to get frontend hostname") } + // do checks on data obtained netIP := net.ParseIP(rD.IP) if netIP == nil { boillog.LogIt("CollectData", "WARNING", "remoteAddr ["+rD.IP+"] : no valid ip found") } + splitIPs := strings.Split(rD.XForwardFor, ",") for _, ip := range splitIPs { netIPs := net.ParseIP(ip) @@ -58,7 +61,9 @@ func CollectData(r *http.Request) { boillog.LogIt("CollectData", "WARNING", "x-forward-for ["+ip+"] : no valid ip found") } } + // send data to database go rD.DBConnector(&waitGroup) + waitGroup.Wait() } diff --git a/pkg/env/env.go b/pkg/env/env.go index 69543af..4e4748f 100644 --- a/pkg/env/env.go +++ b/pkg/env/env.go @@ -11,9 +11,11 @@ import ( // EnvPort get the port from environment variables or return the default (80) func EnvPort() string { port := os.Getenv("PORT") + if len(port) == 0 { port = "80" } + return ":" + port } @@ -31,78 +33,96 @@ func EnvHostname() string { // EnvCacheRefresh get the cache refresh from environment variables or return the default (60) func EnvCacheRefresh() (string, int) { var score int + timer := os.Getenv("REFRESHCACHE") + if len(timer) == 0 { timer = "60" score = 1 // default } else { score = 2 // configured (doesn't matter what it is...) } + return timer, score } // EnvTemplateDir get the templates directory from environment variables or return the default (/var/frontend/templates/) func EnvTemplateDir() (string, int) { var score int + templateDir := os.Getenv("TEMPLATEDIRECTORY") + if len(templateDir) == 0 { templateDir = "/var/frontend/templates/" score = 1 // default } else { score = 2 // configured (doesn't matter what it is...) } + return templateDir, score } // EnvTemplateType get the templates type from environment variables or return the default (.gohtml) func EnvTemplateType() (string, int) { var score int + templateType := os.Getenv("TEMPLATETYPE") + if len(templateType) == 0 { templateType = "gohtml" score = 1 } else { score = 2 } + return templateType, score } // EnvGitLink get the git repo from environment variables or return the default which is empty func EnvGitLink() (string, int) { var score int + gitlink := os.Getenv("GITLINK") + if len(gitlink) == 0 { gitlink = "" score = 1 } else { score = 2 } + return gitlink, score } // EnvGitToken get the git token from environment variables or return the default which is empty func EnvGitToken() (string, int) { var score int + gitToken := os.Getenv("GITTOKEN") + if len(gitToken) == 0 { gitToken = "" score = 1 } else { score = 2 } + return gitToken, score } // EnvGitUsername get the git username from environment variables or return the default which is empty func EnvGitUsername() (string, int) { var score int + gitUsername := os.Getenv("GITUSERNAME") + if len(gitUsername) == 0 { gitUsername = "" score = 1 } else { score = 2 } + return gitUsername, score } @@ -110,9 +130,11 @@ func EnvGitUsername() (string, int) { func EnvPathDefiner(path string) (string, int) { var score int var pathReturn string + switch path { case "css": pathReturn = os.Getenv("CSSPATH") + if len(pathReturn) == 0 { pathReturn = "css" score = 1 @@ -122,6 +144,7 @@ func EnvPathDefiner(path string) (string, int) { case "js": pathReturn = os.Getenv("JSPATH") + if len(pathReturn) == 0 { pathReturn = "js" score = 1 @@ -131,6 +154,7 @@ func EnvPathDefiner(path string) (string, int) { case "images": pathReturn = os.Getenv("IMAGESPATH") + if len(pathReturn) == 0 { pathReturn = "images" score = 1 @@ -140,6 +164,7 @@ func EnvPathDefiner(path string) (string, int) { case "downloads": pathReturn = os.Getenv("DOWNLOADSPATH") + if len(pathReturn) == 0 { pathReturn = "downloads" score = 1 diff --git a/pkg/pkg.go b/pkg/pkg.go index 7a32560..39f4d43 100644 --- a/pkg/pkg.go +++ b/pkg/pkg.go @@ -25,11 +25,14 @@ const Disable = "unused-path" // TODO: might change this later func init() { fmt.Println("Loading Configuration via Environment Variables.") + orange := "\033[48;5;208m" // Orange background green := "\033[42m" // Green background reset := "\033[0m" // Reset to default + orangeBlock := orange + " " + reset greenBlock := green + " " + reset + config := []struct { value *string getValue func() (string, int) @@ -45,8 +48,10 @@ func init() { {&GitUsername, env.EnvGitUsername}, {&GitToken, env.EnvGitToken}, } + configScoreTotal := 0 score := 0 + for _, c := range config { *c.value, score = c.getValue() switch score { @@ -57,17 +62,23 @@ func init() { } configScoreTotal += score } + fmt.Println("") + switch { case configScoreTotal == 20: fmt.Println(" [--- Fully configured. ---]") + case configScoreTotal > 15: fmt.Println(" [--- Mostly configured, defaults set on some settings. ---]") + case configScoreTotal > 10: fmt.Println(" [--- Partially configured, defaults set on most settings. ---]") + case configScoreTotal == len(config): fmt.Println(" [--- Using defaults. ---]") } + fmt.Println("<======================================================================================>") }