about summary refs log tree commit diff stats
path: root/internal/importer/channel.go
blob: 3c199ccbde080cd4e55a4c401fafc0f8503ab7b3 (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 importer

import (
	"context"
	"fmt"
	"log/slog"
	"os"
	"os/exec"
	"path"
	"searchix/internal/file"
	"searchix/internal/search"
	"strconv"
	"strings"

	"github.com/pkg/errors"
)

type ChannelImporter struct {
	DataPath   string
	Source     *Source
	SourceFile string
	Logger     *slog.Logger
	indexPath  string
}

func (i *ChannelImporter) FetchIfNeeded(parent context.Context) (bool, error) {
	ctx, cancel := context.WithTimeout(parent, i.Source.FetchTimeout)
	defer cancel()

	dest := i.DataPath

	before, err := os.Readlink(dest)
	if file.NeedNotExist(err) != nil {
		return false, errors.WithMessagef(err, "could not call readlink on file %s", dest)
	}
	i.Logger.Debug("stat before", "name", before)

	args := []string{
		"--no-build-output",
		"--timeout",
		strconv.Itoa(int(i.Source.FetchTimeout.Seconds() - 1)),
		fmt.Sprintf("<%s/%s>", i.Source.Channel, i.Source.ImportPath),
		"--attr",
		i.Source.Attribute,
		"--out-link",
		dest,
	}

	i.Logger.Debug("nix-build command", "args", args)
	cmd := exec.CommandContext(ctx, "nix-build", args...)
	out, err := cmd.Output()
	if err != nil {
		return false, errors.WithMessage(err, "failed to run nix-build (--dry-run)")
	}
	i.Logger.Debug("nix-build", "output", strings.TrimSpace(string(out)))

	outPath := path.Join(dest, i.Source.OutputPath)
	i.Logger.Debug(
		"checking output path",
		"outputPath",
		outPath,
		"dest",
		dest,
		"source",
		i.Source.OutputPath,
	)
	after, err := os.Readlink(dest)
	if err := file.NeedNotExist(err); err != nil {
		return false, errors.WithMessagef(
			err,
			"failed to stat output file from nix-build, filename: %s",
			outPath,
		)
	}
	i.Logger.Debug("stat after", "name", after)

	return before != after, nil
}

func (i *ChannelImporter) Import(parent context.Context, indexer *search.WriteIndex) (bool, error) {
	if i.Source.OutputPath == "" {
		return false, errors.New("no output path specified")
	}

	filename := path.Join(i.DataPath, i.SourceFile, i.Source.OutputPath)
	i.Logger.Debug("preparing import run", "revision", i.Source.Repo.Revision, "filename", filename)

	return processOptions(parent, indexer, &importConfig{
		IndexPath: i.indexPath,
		Source:    i.Source,
		Filename:  filename,
		Logger:    i.Logger,
	})
}