summaryrefslogtreecommitdiffstats
path: root/gitlab.go
blob: 81fcf846a97fcd0e76a59fa3b2ae98952cc62b1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main

import (
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/url"
	"strings"
)

// isGitLabURL tests a string to determine if it is a well-structured GitLab URL.
func isGitLabURL(s string) (string, bool) {
	if strings.HasPrefix(s, "gitlab.com/") {
		s = "https://" + s
	}

	u, err := url.ParseRequestURI(s)
	if err != nil {
		return "", false
	}

	return u.String(), strings.ToLower(u.Host) == "gitlab.com"
}

// findGitLabREADME tries to find the correct README filename in a repository using GitLab API.
func findGitLabREADME(s string) (*source, error) {
	sSplit := strings.Split(s, "/")
	owner, repo := sSplit[3], sSplit[4]

	projectPath := url.QueryEscape(owner + "/" + repo)

	type readme struct {
		ReadmeUrl string `json:"readme_url"`
	}

	apiURL := "https://gitlab.com/api/v4/projects/" + projectPath

	// nolint:bodyclose
	// it is closed on the caller
	res, err := http.Get(apiURL)
	if err != nil {
		return nil, err
	}

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	var result readme
	jsonErr := json.Unmarshal(body, &result)
	if jsonErr != nil {
		return nil, err
	}

	readmeRawUrl := strings.Replace(result.ReadmeUrl, "blob", "raw", -1)

	if res.StatusCode == http.StatusOK {
		// nolint:bodyclose
		// it is closed on the caller
		resp, err := http.Get(readmeRawUrl)
		if err != nil {
			return nil, err
		}

		if resp.StatusCode == http.StatusOK {
			return &source{resp.Body, readmeRawUrl}, nil
		}
	}

	return nil, errors.New("can't find README in GitLab repository")
}