Add save/load for client config
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
2022-01-21 02:40:33 +01:00
parent d583db5450
commit ff8c6aca64
5 changed files with 80 additions and 2 deletions

View File

@@ -8,20 +8,61 @@ import (
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
"git.t-juice.club/torjus/gpaste/api"
"git.t-juice.club/torjus/gpaste/files"
"github.com/google/uuid"
"github.com/kirsle/configdir"
)
type Client struct {
BaseURL string
AuthToken string
BaseURL string `json:"base_url"`
AuthToken string `json:"auth_token"`
httpClient http.Client
}
func (c *Client) WriteConfigToWriter(w io.Writer) error {
encoder := json.NewEncoder(w)
return encoder.Encode(c)
}
func (c *Client) WriteConfig() error {
dir := configdir.LocalConfig("gpaste")
// Ensure dir exists
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return err
}
path := filepath.Join(dir, "client.json")
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
return c.WriteConfigToWriter(f)
}
func (c *Client) LoadConfig() error {
dir := configdir.LocalCache("gpaste")
path := filepath.Join(dir, "client.json")
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
return c.LoadConfigFromReader(f)
}
func (c *Client) LoadConfigFromReader(r io.Reader) error {
decoder := json.NewDecoder(r)
return decoder.Decode(c)
}
func (c *Client) Login(ctx context.Context, username, password string) error {
url := fmt.Sprintf("%s/api/login", c.BaseURL)
// TODO: Change timeout

View File

@@ -1,6 +1,7 @@
package client_test
import (
"bytes"
"context"
"fmt"
"io"
@@ -15,6 +16,7 @@ import (
"git.t-juice.club/torjus/gpaste/files"
"git.t-juice.club/torjus/gpaste/users"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/google/uuid"
)
@@ -162,4 +164,31 @@ func TestClient(t *testing.T) {
t.Errorf("File contents does not match: %s", cmp.Diff(buf.String(), fileContents))
}
})
t.Run("Save", func(t *testing.T) {
c := client.Client{BaseURL: "http://example.org/gpaste", AuthToken: "tokenpls"}
expectedConfig := "{\"base_url\":\"http://example.org/gpaste\",\"auth_token\":\"tokenpls\"}\n"
buf := new(bytes.Buffer)
err := c.WriteConfigToWriter(buf)
if err != nil {
t.Fatalf("Error writing config: %s", err)
}
if diff := cmp.Diff(buf.String(), expectedConfig); diff != "" {
t.Errorf("Written config does not match expected: %s", diff)
}
})
t.Run("Load", func(t *testing.T) {
c := client.Client{}
config := "{\"base_url\":\"http://pasta.example.org\",\"auth_token\":\"tokenpls\"}\n"
expectedClient := client.Client{BaseURL: "http://pasta.example.org", AuthToken: "tokenpls"}
sr := strings.NewReader(config)
if err := c.LoadConfigFromReader(sr); err != nil {
t.Fatalf("Error reading config: %s", err)
}
if diff := cmp.Diff(c, expectedClient, cmpopts.IgnoreUnexported(client.Client{})); diff != "" {
t.Errorf("Client does not match expected: %s", diff)
}
})
}