about summary refs log tree commit diff stats
path: root/internal/fetcher/nixpkgs-channel.go
blob: 6f8ca6319d13339d7265b36051d6fd8cdf0427fd (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package fetcher

import (
	"context"
	"fmt"
	"net/url"

	"go.alanpearce.eu/searchix/internal/config"
	"go.alanpearce.eu/searchix/internal/index"

	"github.com/pkg/errors"
	"go.alanpearce.eu/x/log"
)

type NixpkgsChannelFetcher struct {
	Source *config.Source
	Logger *log.Logger
}

func makeChannelURL(channel string, subPath string) (string, error) {
	url, err := url.JoinPath("https://channels.nixos.org/", channel, subPath)

	return url, errors.WithMessagef(err, "error creating URL")
}

func NewNixpkgsChannelFetcher(
	source *config.Source,
	logger *log.Logger,
) (*NixpkgsChannelFetcher, error) {
	switch source.Importer {
	case config.Options, config.Packages:
		return &NixpkgsChannelFetcher{
			Source: source,
			Logger: logger,
		}, nil
	default:
		return nil, fmt.Errorf("unsupported importer type %s", source.Importer)
	}
}

const (
	revisionFilename = "git-revision"
	optionsFilename  = "options.json.br"
	packagesFileName = "packages.json.br"
)

func (i *NixpkgsChannelFetcher) FetchIfNeeded(
	ctx context.Context,
	sourceMeta *index.SourceMeta,
) (f FetchedFiles, err error) {

	filesToFetch := make([]string, 2)
	filesToFetch[0] = revisionFilename
	switch i.Source.Importer {
	case config.Packages:
		filesToFetch[1] = packagesFileName
	case config.Options:
		filesToFetch[1] = optionsFilename
	}

	var fetchURL string
	for _, filename := range filesToFetch {
		fetchURL, err = makeChannelURL(i.Source.Channel, filename)
		if err != nil {
			return
		}

		i.Logger.Debug("attempting to fetch file", "url", fetchURL)
		body, mtime, err := fetchFileIfNeeded(ctx, i.Logger, sourceMeta.Updated, fetchURL)
		if err != nil {
			i.Logger.Warn("failed to fetch file", "url", fetchURL, "error", err)

			return f, err
		}
		// don't bother to issue requests for the later files
		if mtime.Before(sourceMeta.Updated) {
			break
		}
		sourceMeta.Updated = mtime

		switch filename {
		case revisionFilename:
			f.Revision = body
		case optionsFilename:
			f.Options = body
		case packagesFileName:
			f.Packages = body
		default:
			return f, errors.Errorf("unknown file kind %s", filename)
		}
	}

	return
}