WIP: Refactor entire project #16

Draft
tom wants to merge 23 commits from make_linters_happy into main
6 changed files with 34 additions and 6 deletions
Showing only changes of commit 20a47d9abc - Show all commits

View file

@ -43,7 +43,7 @@ func Parse() *AppSettings {
) )
validateFlags(ctx) validateFlags(ctx)
settings := &AppSettings{ return &AppSettings{
Force: cliStruct.Force, Force: cliStruct.Force,
GrafanaURL: cliStruct.GrafanaURL, GrafanaURL: cliStruct.GrafanaURL,
GrafanaToken: cliStruct.GrafanaToken, GrafanaToken: cliStruct.GrafanaToken,
@ -54,34 +54,42 @@ func Parse() *AppSettings {
GitPass: cliStruct.GitPass, GitPass: cliStruct.GitPass,
GPGKey: cliStruct.GPGKey, GPGKey: cliStruct.GPGKey,
} }
return settings
} }
func validateFlags(cliCtx *kong.Context) { func validateFlags(cliCtx *kong.Context) {
var flagsValid = true flagsValid := true
var messages = []string{} messages := []string{}
if cliStruct.GrafanaURL == "" { if cliStruct.GrafanaURL == "" {
messages = append(messages, "error: invalid grafana URL, must not be blank") messages = append(messages, "error: invalid grafana URL, must not be blank")
flagsValid = false flagsValid = false
} }
if cliStruct.GrafanaToken == "" { if cliStruct.GrafanaToken == "" {
messages = append(messages, "error: invalid auth token for grafana, must not be blank") messages = append(messages, "error: invalid auth token for grafana, must not be blank")
flagsValid = false flagsValid = false
} }
if cliStruct.GitRepoURL == "" { if cliStruct.GitRepoURL == "" {
messages = append(messages, "error: invalid repo url for git, must not be blank") messages = append(messages, "error: invalid repo url for git, must not be blank")
flagsValid = false flagsValid = false
} }
if cliStruct.GitUser == "" { if cliStruct.GitUser == "" {
messages = append(messages, "error: invalid username for git, must not be blank") messages = append(messages, "error: invalid username for git, must not be blank")
flagsValid = false flagsValid = false
} }
if cliStruct.GitPass == "" { if cliStruct.GitPass == "" {
messages = append(messages, "error: invalid password for git, must not be blank") messages = append(messages, "error: invalid password for git, must not be blank")
flagsValid = false flagsValid = false
} }
if !flagsValid { if !flagsValid {
cliCtx.PrintUsage(false) if err := cliCtx.PrintUsage(false); err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Println() fmt.Println()
for i := 0; i < len(messages); i++ { for i := 0; i < len(messages); i++ {
fmt.Println(messages[i]) fmt.Println(messages[i])

View file

@ -73,6 +73,7 @@ func main() {
gitdata.UpdateContent([]byte(output)) gitdata.UpdateContent([]byte(output))
gitdata.UpdateCommitter() gitdata.UpdateCommitter()
if err = gitdata.CreateCommit(); err != nil { if err = gitdata.CreateCommit(); err != nil {
log.Fatalf("Error creating commit for dashboard %s version %d: %v", dashboard.Title, info.Version, err) log.Fatalf("Error creating commit for dashboard %s version %d: %v", dashboard.Title, info.Version, err)
} }

View file

@ -110,6 +110,7 @@ func (p *Payload) GetRepo(repoURL, user, password string) (err error) {
func (p *Payload) IsVersionCommitted(branch string) bool { func (p *Payload) IsVersionCommitted(branch string) bool {
refName := plumbing.NewBranchReferenceName(branch) refName := plumbing.NewBranchReferenceName(branch)
ref, err := p.Repository.Reference(refName, false) ref, err := p.Repository.Reference(refName, false)
if err != nil { if err != nil {
return false return false

View file

@ -49,11 +49,14 @@ func (c *Client) getRawDashboardByUID(ctx context.Context, path string) ([]byte,
if code != 200 { if code != 200 {
return raw, BoardProperties{}, fmt.Errorf("HTTP error %d: returns %s", code, raw) return raw, BoardProperties{}, fmt.Errorf("HTTP error %d: returns %s", code, raw)
} }
var result struct { var result struct {
Meta BoardProperties `json:"meta"` Meta BoardProperties `json:"meta"`
} }
dec := json.NewDecoder(bytes.NewReader(raw)) dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber() dec.UseNumber()
if err := dec.Decode(&result); err != nil { if err := dec.Decode(&result); err != nil {
return raw, BoardProperties{}, fmt.Errorf("failed unmarshalling dashboard from path %s: %v", path, err) return raw, BoardProperties{}, fmt.Errorf("failed unmarshalling dashboard from path %s: %v", path, err)
} }
@ -62,6 +65,7 @@ func (c *Client) getRawDashboardByUID(ctx context.Context, path string) ([]byte,
func (c *Client) getRawDashboardFromVersion(ctx context.Context, path string) ([]byte, DashboardVersion, error) { func (c *Client) getRawDashboardFromVersion(ctx context.Context, path string) ([]byte, DashboardVersion, error) {
var versionInfo DashboardVersion var versionInfo DashboardVersion
raw, code, err := c.get(ctx, fmt.Sprintf("api/dashboards/%s", path), nil) raw, code, err := c.get(ctx, fmt.Sprintf("api/dashboards/%s", path), nil)
if err != nil { if err != nil {
return nil, versionInfo, err return nil, versionInfo, err
@ -69,8 +73,10 @@ func (c *Client) getRawDashboardFromVersion(ctx context.Context, path string) ([
if code != 200 { if code != 200 {
return raw, versionInfo, fmt.Errorf("HTTP error %d: returns %s", code, raw) return raw, versionInfo, fmt.Errorf("HTTP error %d: returns %s", code, raw)
} }
dec := json.NewDecoder(bytes.NewReader(raw)) dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber() dec.UseNumber()
if err := dec.Decode(&versionInfo); err != nil { if err := dec.Decode(&versionInfo); err != nil {
return raw, versionInfo, fmt.Errorf("failed unmarshalling dashboard from path %s: %v", path, err) return raw, versionInfo, fmt.Errorf("failed unmarshalling dashboard from path %s: %v", path, err)
} }
@ -80,6 +86,7 @@ func (c *Client) getRawDashboardFromVersion(ctx context.Context, path string) ([
func queryParams(params ...QueryParam) url.Values { func queryParams(params ...QueryParam) url.Values {
u := url.URL{} u := url.URL{}
q := u.Query() q := u.Query()
for _, p := range params { for _, p := range params {
p(&q) p(&q)
} }
@ -99,6 +106,7 @@ func (c *Client) GetDashboardVersionsByDashboardUID(ctx context.Context, uid str
if code != 200 { if code != 200 {
return nil, fmt.Errorf("HTTP error %d: returns %s", code, raw) return nil, fmt.Errorf("HTTP error %d: returns %s", code, raw)
} }
var versions []DashboardVersion var versions []DashboardVersion
err = json.Unmarshal(raw, &versions) err = json.Unmarshal(raw, &versions)

View file

@ -20,13 +20,14 @@ type Client struct {
} }
func NewClient(apiURL, authString string, client *http.Client) (*Client, error) { func NewClient(apiURL, authString string, client *http.Client) (*Client, error) {
basicAuth := strings.Contains(authString, ":")
baseURL, err := url.Parse(apiURL) baseURL, err := url.Parse(apiURL)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var key string var key string
basicAuth := strings.Contains(authString, ":")
if len(authString) > 0 { if len(authString) > 0 {
if !basicAuth { if !basicAuth {
key = fmt.Sprintf("Bearer %s", authString) key = fmt.Sprintf("Bearer %s", authString)
@ -47,24 +48,30 @@ func NewClient(apiURL, authString string, client *http.Client) (*Client, error)
func (c *Client) doRequest(ctx context.Context, method, query string, params url.Values, buf io.Reader) ([]byte, int, error) { func (c *Client) doRequest(ctx context.Context, method, query string, params url.Values, buf io.Reader) ([]byte, int, error) {
u, _ := url.Parse(c.baseURL) u, _ := url.Parse(c.baseURL)
u.Path = path.Join(u.Path, query) u.Path = path.Join(u.Path, query)
if params != nil { if params != nil {
u.RawQuery = params.Encode() u.RawQuery = params.Encode()
} }
req, err := http.NewRequest(method, u.String(), buf) req, err := http.NewRequest(method, u.String(), buf)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
req = req.WithContext(ctx) req = req.WithContext(ctx)
if !c.basicAuth && len(c.key) > 0 { if !c.basicAuth && len(c.key) > 0 {
req.Header.Set("Authorization", c.key) req.Header.Set("Authorization", c.key)
} }
req.Header.Set("Accept", "application/json") req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "grafana-backuper") req.Header.Set("User-Agent", "grafana-backuper")
resp, err := c.client.Do(req) resp, err := c.client.Do(req)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
data, err := io.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
resp.Body.Close() resp.Body.Close()
return data, resp.StatusCode, err return data, resp.StatusCode, err

View file

@ -47,15 +47,18 @@ func (c *Client) Search(ctx context.Context, params ...SearchParam) ([]FoundBoar
) )
u := url.URL{} u := url.URL{}
q := u.Query() q := u.Query()
for _, p := range params { for _, p := range params {
p(&q) p(&q)
} }
if raw, code, err = c.get(ctx, "api/search", q); err != nil { if raw, code, err = c.get(ctx, "api/search", q); err != nil {
return nil, err return nil, err
} }
if code != 200 { if code != 200 {
return nil, fmt.Errorf("HTTP error %d: returns %s", code, raw) return nil, fmt.Errorf("HTTP error %d: returns %s", code, raw)
} }
err = json.Unmarshal(raw, &boards) err = json.Unmarshal(raw, &boards)
return boards, err return boards, err
} }