Skip to content

Commit

Permalink
refactor package
Browse files Browse the repository at this point in the history
  • Loading branch information
MarvinJWendt committed Nov 27, 2023
1 parent 7e1788b commit 0456ac9
Show file tree
Hide file tree
Showing 9 changed files with 265 additions and 130 deletions.
4 changes: 2 additions & 2 deletions .github/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ repository:
# See https://developer.github.com/v3/repos/#edit for all available settings.

# A short description of the repository that will show up on GitHub
description: 📦 Template repository for AtomicGo repositories
description: ✨ The most sophisticated utils package for Go

# A comma-separated list of topics to set on the repository
topics: atomicgo, go, golang, golang-library
topics: atomicgo, go, golang, golang-library, utils

# Either `true` to make the repository private, or `false` to make it public.
private: false
Expand Down
17 changes: 0 additions & 17 deletions examples_test.go

This file was deleted.

72 changes: 72 additions & 0 deletions file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package utils

import (
"fmt"
"io"
"net/http"
"os"
)

// ReadFile reads the given file and returns its content.
func ReadFile(path string) (string, error) {
res, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(res), nil

Check failure on line 16 in file.go

View workflow job for this annotation

GitHub Actions / lint

return statements should not be cuddled if block has more than two lines (wsl)
}

// WriteFile writes the given content to the given file.
// Accepts a string or a byte slice.
func WriteFile[T string | []byte](path string, content T) error {
return os.WriteFile(path, []byte(content), 0644)

Check failure on line 22 in file.go

View workflow job for this annotation

GitHub Actions / lint

G306: Expect WriteFile permissions to be 0600 or less (gosec)
}

// AppendToFile appends the given content to the given file.
// Accepts a string or a byte slice.
func AppendToFile[T string | []byte](path string, content T) error {
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()

if _, err = f.Write([]byte(content)); err != nil {

Check failure on line 34 in file.go

View workflow job for this annotation

GitHub Actions / lint

preferStringWriter: f.WriteString(content) should be preferred to the f.Write([]byte(content)) (gocritic)
return err
}

return nil
}

// FileExists returns true if the given file exists.
func FileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}

// DownloadFile downloads the given URL to the given path.
// If the file already exists, it will be overwritten.
func DownloadFile(url, path string) error {
out, err := os.Create(path)
if err != nil {
return err
}
defer out.Close()

resp, err := http.Get(url)

Check failure on line 56 in file.go

View workflow job for this annotation

GitHub Actions / lint

G107: Potential HTTP request made with variable url (gosec)
if err != nil {
return err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}

_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}

return nil
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module atomicgo.dev/utils

go 1.21

require atomicgo.dev/constraints v0.0.1 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
atomicgo.dev/constraints v0.0.1 h1:LoHu+UgL+3yhU800V2flSZiYdKR87e7JwMlCiLzw828=
atomicgo.dev/constraints v0.0.1/go.mod h1:u5zlCj1ynQWZDDM2/FTBoxRQmJXax1DJ+kpDiByzLhU=
82 changes: 82 additions & 0 deletions to.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package utils

import (
"atomicgo.dev/constraints"
"encoding/json"
"fmt"
"strconv"
"strings"
)

// ToJSON converts the given value to a JSON string.
func ToJSON(v any) (string, error) {
r, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(r), nil

Check failure on line 17 in to.go

View workflow job for this annotation

GitHub Actions / lint

return statements should not be cuddled if block has more than two lines (wsl)
}

func ToPrettyJSON(v any, indent ...string) (string, error) {

Check warning on line 20 in to.go

View workflow job for this annotation

GitHub Actions / lint

exported: exported function ToPrettyJSON should have comment or be unexported (revive)
if len(indent) == 0 {
indent = append(indent, " ")
}

r, err := json.MarshalIndent(v, "", indent[0])
if err != nil {
return "", err
}
return string(r), nil

Check failure on line 29 in to.go

View workflow job for this annotation

GitHub Actions / lint

return statements should not be cuddled if block has more than two lines (wsl)
}

// ToString converts the given value to a string.
func ToString(v any) string {
return fmt.Sprint(v)
}

// ToInt converts the given value to an int.
// If the value is a float, it will be rounded to the nearest integer. (Rounds up if the decimal is 0.5 or higher)

Check failure on line 38 in to.go

View workflow job for this annotation

GitHub Actions / lint

Comment should end in a period (godot)
func ToInt[T string | constraints.Number](v T) int {
switch v := any(v).(type) {
case int:
return v
case int8:
return int(v)
case int16:
return int(v)
case int32:
return int(v)
case int64:
return int(v)
case uint:
return int(v)
case uint8:
return int(v)
case uint16:
return int(v)
case uint32:
return int(v)
case uint64:
return int(v)
case float32:
v += 0.5
return int(v)
case float64:
v += 0.5
return int(v)
case string:
var i int

if !strings.Contains(v, ".") {
i, _ = strconv.Atoi(v)
} else {
f, _ := strconv.ParseFloat(v, 64)
f += 0.5 // Round up
i = int(f)
}

return i
default:
return 0
}
}
63 changes: 63 additions & 0 deletions to_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package utils_test

import (
"atomicgo.dev/utils"
"fmt"
)

type Person struct {
Name string
Age int
}

func ExampleToJSON() {
var person = Person{"John Doe", 42}

json, _ := utils.ToJSON(person)
fmt.Println(json)

// Output:
// {"Name":"John Doe","Age":42}
}

func ExampleToInt() {
fmt.Println(utils.ToInt(1337))
fmt.Println(utils.ToInt(1337.4))
fmt.Println(utils.ToInt(1337.5))
fmt.Println(utils.ToInt(1337.6))
fmt.Println(utils.ToInt("1337"))
fmt.Println(utils.ToInt("1337.4"))
fmt.Println(utils.ToInt("1337.5"))
fmt.Println(utils.ToInt("1337.6"))

// Output:
// 1337
// 1337
// 1338
// 1338
// 1337
// 1337
// 1338
// 1338
}

func ExampleToString() {
person := Person{"John Doe", 42}

fmt.Println(utils.ToString(person))

// Output:
// {John Doe 42}
}

func ExampleToPrettyJSON() {
person := Person{Name: "John Doe", Age: 42}
prettyJson, _ := utils.ToPrettyJSON(person)

Check warning on line 55 in to_test.go

View workflow job for this annotation

GitHub Actions / lint

var-naming: var prettyJson should be prettyJSON (revive)
fmt.Println(prettyJson)

// Output:
// {
// "Name": "John Doe",
// "Age": 42
// }
}
Loading

0 comments on commit 0456ac9

Please sign in to comment.