summaryrefslogtreecommitdiffstats
path: root/github.go
blob: b824cf55f4f96dcaea369659f1c29620019a1064 (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
package main

import (
	"errors"
	"net/http"
	"net/url"
	"strings"
)

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

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

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

// findGitHubREADME tries to find the correct README filename in a repository.
func findGitHubREADME(s string) (*source, error) {
	u, err := url.ParseRequestURI(s)
	if err != nil {
		return nil, err
	}
	u.Host = "raw.githubusercontent.com"

	for _, r := range readmeNames {
		v := u
		v.Path += "/master/" + r

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

		if resp.StatusCode == http.StatusOK {
			return &source{resp.Body, v.String()}, nil
		}
	}

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