package helper import ( "context" "encoding/json" "errors" "fmt" "git.ar21.de/yolokube/grafana-backuper/internal/config" "git.ar21.de/yolokube/grafana-backuper/pkg/git" "git.ar21.de/yolokube/grafana-backuper/pkg/grafana" ) var ErrAlreadyCommited = errors.New("already committed") func CreateCommitMsg(d *grafana.DashboardVersion, title, uid string) string { commitMsg := fmt.Sprintf("%s: Update %s to version %d", title, uid, d.ID) if d.Message != "" { commitMsg += fmt.Sprintf(" => %s", d.Message) } return commitMsg } func CommitVersion( dashboard *grafana.Dashboard, dashboardVersion *grafana.DashboardVersion, dashboardInfo *grafana.SearchResult, project *git.Project, cfg *config.Config, signer git.SignKey, force bool, ) (string, error) { commitMsg := CreateCommitMsg(dashboardVersion, dashboardInfo.Title, dashboardInfo.UID) if !force && project.CommitExists(dashboardVersion.DashboardUID, dashboardVersion.ID) { return commitMsg, ErrAlreadyCommited } UpdateDashboardInfo(dashboard, dashboardVersion) data, err := json.MarshalIndent(grafana.SchemaFromDashboardMeta(dashboard), "", " ") if err != nil { return commitMsg, err } commitOpts := []git.CommitOption{ git.WithAuthor(dashboardVersion.CreatedBy, ""), git.WithFileContent(data, dashboardInfo.Title, dashboard.FolderTitle), git.WithSigner(signer), } if cfg.GitUser != "" { commitOpts = append(commitOpts, git.WithCommitter(cfg.GitUser, cfg.GitEmail)) } commit := project.NewCommit(commitOpts...) return commitMsg, commit.Create(commitMsg) } func PrepareProject(ctx context.Context, c *config.Config) (*git.Project, error) { project := git.NewProject( c.GitRepo, git.WithBasicAuth(c.GitUser, c.GitPass), git.WithBranch(c.GitBranch), git.WithOutputWriter(c.Output), ) if err := project.Clone(ctx); err != nil { return nil, err } if err := project.Checkout(); err != nil { return nil, err } if err := project.Pull(ctx); err != nil { return nil, err } return project, nil } func UpdateDashboardInfo(d *grafana.Dashboard, dv *grafana.DashboardVersion) { d.Dashboard = dv.Data d.UpdatedBy = dv.CreatedBy d.Updated = dv.Created d.Version = dv.Version }