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
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// go-deps-check reports go-deps.nix pins that differ from the version the
// go.work workspace resolves for the same module. See go-deps-check(1).
package main

import (
	"bytes"
	_ "embed"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
)

//go:embed probe.nix
var probeNix []byte

var (
	flagRoot    = flag.String("C", "", "repository root (default: the nearest parent directory holding go.work)")
	flagVerbose = flag.Bool("v", false, "also list pins that match, and pins no workspace module uses")
)

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: go-deps-check [-C root] [-v]\n")
		flag.PrintDefaults()
	}
	flag.Parse()
	if flag.NArg() != 0 {
		flag.Usage()
		os.Exit(2)
	}
	mismatches, err := run()
	if err != nil {
		fmt.Fprintf(os.Stderr, "go-deps-check: %v\n", err)
		os.Exit(2)
	}
	if mismatches > 0 {
		os.Exit(1)
	}
}

// A pin as probe.nix reports it.
type pin struct {
	File string // repository-relative go-deps.nix
	Name string // attribute name
	Path string // Go import path handed to buildGo.external
	Rev  string // tag or commit the fetcher is given
	Repo string // owner/repo or URL, for messages
}

type module struct {
	Path    string
	Version string
	Main    bool
}

func run() (mismatches int, err error) {
	root, err := findRoot()
	if err != nil {
		return 0, err
	}

	files, err := depsFiles(root)
	if err != nil {
		return 0, err
	}
	pins, err := readPins(root, files)
	if err != nil {
		return 0, err
	}
	mods, err := workspaceModules(root)
	if err != nil {
		return 0, err
	}

	for _, p := range pins {
		m, ok := owningModule(mods, p.Path, p.Rev)
		if !ok {
			if *flagVerbose {
				fmt.Printf("unused   %s: %s (%s) %s — no workspace module needs it\n", p.File, p.Name, p.Path, p.Rev)
			}
			continue
		}
		same, err := sameVersion(root, m, p.Rev)
		if err != nil {
			return 0, fmt.Errorf("%s: %s: %w", p.File, p.Name, err)
		}
		if same {
			if *flagVerbose {
				fmt.Printf("ok       %s: %s %s = %s\n", p.File, p.Name, p.Rev, m.Version)
			}
			continue
		}
		mismatches++
		fmt.Printf("mismatch %s: %s (%s) pinned %s, workspace has %s %s\n",
			p.File, p.Name, p.Path, p.Rev, m.Path, m.Version)
	}
	if mismatches > 0 {
		fmt.Fprintf(os.Stderr, "%d pin(s) differ from go.work; bump them in go-deps.nix\n", mismatches)
	}
	return mismatches, nil
}

func findRoot() (string, error) {
	if *flagRoot != "" {
		return filepath.Abs(*flagRoot)
	}
	dir, err := os.Getwd()
	if err != nil {
		return "", err
	}
	for {
		if _, err := os.Stat(filepath.Join(dir, "go.work")); err == nil {
			return dir, nil
		}
		parent := filepath.Dir(dir)
		if parent == dir {
			return "", fmt.Errorf("no go.work in any parent directory; use -C")
		}
		dir = parent
	}
}

// depsFiles lists the go-deps.nix files that must follow the workspace: those
// in a directory go.work uses, or in a parent of one (the shared
// users/Profpatsch/go-deps.nix). A go-deps.nix anywhere else belongs to a
// project outside the workspace, which resolves its own versions or none at
// all, so its pins do not answer to go.work.
func depsFiles(root string) ([]string, error) {
	out, err := command(root, "git", "ls-files", "-z", "--", "*go-deps.nix", "go-deps.nix")
	if err != nil {
		return nil, err
	}
	work, err := command(root, "go", "work", "edit", "-json")
	if err != nil {
		return nil, err
	}
	var w struct{ Use []struct{ DiskPath string } }
	if err := json.Unmarshal(work, &w); err != nil {
		return nil, fmt.Errorf("parsing go work edit -json: %w", err)
	}
	used := map[string]bool{}
	for _, u := range w.Use {
		used[filepath.Clean(u.DiskPath)] = true
	}

	var files []string
	for _, f := range strings.Split(strings.TrimRight(string(out), "\x00"), "\x00") {
		if f == "" {
			continue
		}
		if !coversWorkspace(filepath.Dir(f), used) {
			if *flagVerbose {
				fmt.Printf("skip     %s — its directory is not in go.work\n", f)
			}
			continue
		}
		files = append(files, f)
	}
	return files, nil
}

func coversWorkspace(dir string, used map[string]bool) bool {
	for u := range used {
		if u == dir || dir == "." || strings.HasPrefix(u, dir+"/") {
			return true
		}
	}
	return false
}

func readPins(root string, files []string) ([]pin, error) {
	tmp, err := os.MkdirTemp("", "go-deps-check")
	if err != nil {
		return nil, err
	}
	defer os.RemoveAll(tmp)
	probe := filepath.Join(tmp, "probe.nix")
	if err := os.WriteFile(probe, probeNix, 0o644); err != nil {
		return nil, err
	}

	var pins []pin
	for _, f := range files {
		abs := filepath.Join(root, f)
		out, err := command(root, "nix-instantiate", "--eval", "--strict", "--json",
			probe, "--arg", "file", abs)
		if err != nil {
			return nil, fmt.Errorf("evaluating %s: %w", f, err)
		}
		var raw []struct{ Name, Path, Src string }
		if err := json.Unmarshal(out, &raw); err != nil {
			return nil, fmt.Errorf("%s: %w", f, err)
		}
		for _, r := range raw {
			p, err := parsePin(f, r.Name, r.Path, r.Src)
			if err != nil {
				return nil, err
			}
			pins = append(pins, p)
		}
	}
	sort.SliceStable(pins, func(i, j int) bool { return pins[i].File < pins[j].File })
	return pins, nil
}

// pinRe finds the fetcher arguments probe.nix encoded into a src string. The
// src may be only that (a plain fetch), have a subdirectory appended
// ("…/ansi"), or sit inside a runCommand script.
var pinRe = regexp.MustCompile(`pin:(\{[^}]*\})`)

func parsePin(file, name, path, src string) (pin, error) {
	m := pinRe.FindStringSubmatch(src)
	if m == nil {
		return pin{}, fmt.Errorf("%s: %s: cannot find the fetcher in src %q (a fetcher probe.nix does not stub?)", file, name, src)
	}
	var a struct{ Kind, Owner, Repo, URL, Rev string }
	if err := json.Unmarshal([]byte(m[1]), &a); err != nil {
		return pin{}, fmt.Errorf("%s: %s: %w", file, name, err)
	}
	repo := a.URL
	if repo == "" {
		repo = a.Kind + ":" + a.Owner + "/" + a.Repo
	}
	return pin{File: file, Name: name, Path: path, Rev: a.Rev, Repo: repo}, nil
}

func workspaceModules(root string) ([]module, error) {
	out, err := command(root, "go", "list", "-m", "-json", "all")
	if err != nil {
		return nil, err
	}
	var mods []module
	dec := json.NewDecoder(bytes.NewReader(out))
	for dec.More() {
		var m module
		if err := dec.Decode(&m); err != nil {
			return nil, fmt.Errorf("parsing go list -m -json: %w", err)
		}
		if !m.Main && m.Version != "" {
			mods = append(mods, m)
		}
	}
	return mods, nil
}

// owningModule finds the module a pin stands for: the longest module path
// that is the pin's import path or a prefix of it. A pin may name a package
// inside a module (github.com/muesli/ansi/compressor) or a nested module of a
// repository (github.com/charmbracelet/x/ansi).
//
// Failing that, a pin may name the repository root and fetch a nested
// module's tag: path go.opentelemetry.io/auto at rev sdk/v1.2.1 is module
// go.opentelemetry.io/auto/sdk. The tag's directory prefix is the subpath.
func owningModule(mods []module, path, rev string) (module, bool) {
	var best module
	found := false
	for _, m := range mods {
		if (path == m.Path || strings.HasPrefix(path, m.Path+"/")) && len(m.Path) > len(best.Path) {
			best, found = m, true
		}
	}
	if found {
		return best, true
	}
	if i := strings.LastIndex(rev, "/"); i > 0 {
		nested := path + "/" + rev[:i]
		for _, m := range mods {
			if m.Path == nested {
				return m, true
			}
		}
	}
	return module{}, false
}

var (
	hexRe    = regexp.MustCompile(`^[0-9a-f]{7,40}$`)
	pseudoRe = regexp.MustCompile(`-([0-9a-f]{12})(\+incompatible)?$`)
)

// sameVersion reports whether a pin's rev is the module version.
//
// A tag compares by name, after dropping a subdirectory prefix: nested
// modules are tagged "ansi/v0.10.1" in the repository but are version v0.10.1
// to Go. A commit compares with the hash in a pseudo-version by prefix; when
// the module is at a real tag, the commit is checked against the one Go
// recorded for that tag in the module cache.
func sameVersion(root string, m module, rev string) (bool, error) {
	v := strings.TrimSuffix(m.Version, "+incompatible")
	if !hexRe.MatchString(rev) {
		return rev[strings.LastIndex(rev, "/")+1:] == v, nil
	}
	if pm := pseudoRe.FindStringSubmatch(m.Version); pm != nil {
		return hashPrefix(rev, pm[1]), nil
	}
	out, err := command(root, "go", "mod", "download", "-json", m.Path+"@"+m.Version)
	if err != nil {
		return false, err
	}
	var d struct{ Origin struct{ Hash string } }
	if err := json.Unmarshal(out, &d); err != nil {
		return false, err
	}
	if d.Origin.Hash == "" {
		return false, fmt.Errorf("pinned by commit %s, but the module cache records no commit for %s@%s", rev, m.Path, m.Version)
	}
	return hashPrefix(rev, d.Origin.Hash), nil
}

func hashPrefix(a, b string) bool {
	n := min(len(a), len(b))
	return a[:n] == b[:n]
}

func command(dir, name string, args ...string) ([]byte, error) {
	cmd := exec.Command(name, args...)
	cmd.Dir = dir
	var stderr bytes.Buffer
	cmd.Stderr = &stderr
	out, err := cmd.Output()
	if err != nil {
		return nil, fmt.Errorf("%s %s: %w\n%s", name, strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
	}
	return out, nil
}