91 lines
1.8 KiB
Go
91 lines
1.8 KiB
Go
package repo
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/go-git/go-git/v5"
|
|
"github.com/sirupsen/logrus"
|
|
"io/ioutil"
|
|
"os"
|
|
"path"
|
|
"time"
|
|
)
|
|
|
|
type Repo struct {
|
|
URL string
|
|
Token string
|
|
Branch string
|
|
Path string
|
|
Frequency time.Duration
|
|
ConfigMap map[string]string
|
|
}
|
|
|
|
type Repos []*Repo
|
|
|
|
func (repo *Repo) clone() error {
|
|
logrus.Infof("Cloning %s into %s", repo.Branch, repo.Path)
|
|
_, err := git.PlainClone(repo.Path, false, &git.CloneOptions{
|
|
URL: repo.URL,
|
|
})
|
|
if err != nil {
|
|
logrus.Errorf("Error while cloning %s: %v", repo.URL, err)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (repo *Repo) setConfigMap() error {
|
|
data, err := repo.readFile("drone-config-map.json")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = json.Unmarshal(data, &repo.ConfigMap)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
logrus.Printf("%+v", repo.ConfigMap)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (repo *Repo) readFile(fileName string) ([]byte, error) {
|
|
if _, err := os.Stat(path.Join(repo.Path, fileName)); err == nil {
|
|
data, err := ioutil.ReadFile(path.Join(repo.Path, fileName))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return data, nil
|
|
}
|
|
return nil, fmt.Errorf("File %s not found in %s", fileName, repo.Path)
|
|
}
|
|
|
|
func (repos *Repos) GetConfiguration(git_http_url string) (string, error) {
|
|
fmt.Println(git_http_url)
|
|
for _, repo := range *repos {
|
|
if file, found := repo.ConfigMap[git_http_url]; found {
|
|
data, err := repo.readFile(file)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return bytes.NewBuffer(data).String(), nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
func (r *Repos) Init() {
|
|
os.RemoveAll("/tmp/drone-yaml-server")
|
|
for _, repo := range *r {
|
|
if repo.Branch == "" {
|
|
repo.Branch = "main"
|
|
}
|
|
if repo.Path == "" {
|
|
repo.Path = fmt.Sprintf("/tmp/drone-yaml-server/%x", sha256.Sum256([]byte(fmt.Sprintf("%s%s", repo.URL, repo.Branch))))
|
|
}
|
|
|
|
repo.clone()
|
|
repo.setConfigMap()
|
|
}
|
|
}
|