summaryrefslogtreecommitdiff
path: root/main.go
blob: 9c30e3393dc74b0e053d0bc8e0e6a1bd20f9a246 (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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"slices"
	"strings"
)

func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "Usage: %s <path> <path>\n\nSee the vdf(1) manual page for more information.\n", os.Args[0])
		os.Exit(1)
	}
	err := innerMain(os.Stdout, os.Args[1], os.Args[2])
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s", err)
		os.Exit(1)
	}
}

func innerMain(w io.Writer, oldRoot string, newRoot string) error {
	// We resolve symlinks so that we can filter out the roots from the dependencies.
	oldRoot, err := filepath.EvalSymlinks(oldRoot)
	if err != nil {
		return fmt.Errorf("failed to eval symlinks in %q: %v", oldRoot, err)
	}
	newRoot, err = filepath.EvalSymlinks(newRoot)
	if err != nil {
		return fmt.Errorf("failed to eval symlinks in %q: %v", newRoot, err)
	}

	oldPathInfos, err := queryPaths(oldRoot)
	if err != nil {
		return err
	}
	newPathInfos, err := queryPaths(newRoot)
	if err != nil {
		return err
	}

	var nameRe *regexp.Regexp
	if strings.HasSuffix(oldRoot, ".drv") && strings.HasSuffix(newRoot, ".drv") {
		nameRe = derivationNameRe
	} else if strings.HasSuffix(oldRoot, ".drv") || strings.HasSuffix(newRoot, ".drv") {
		return fmt.Errorf("error: one derivation path given (either both paths should be output paths or both should be derivation paths)")
	} else {
		nameRe = outputNameRe
	}

	var oldDependencies []Dependency
	for path := range oldPathInfos {
		if path == oldRoot {
			continue
		}
		output, err := parseStorePath(nameRe, path)
		if err != nil {
			return err
		}
		oldDependencies = append(oldDependencies, *output)
	}

	var newDependencies []Dependency
	for path := range newPathInfos {
		if path == newRoot {
			continue
		}
		output, err := parseStorePath(nameRe, path)
		if err != nil {
			return err
		}
		newDependencies = append(newDependencies, *output)
	}

	// TODO: exclude package names defined in TOML config

	added, removed, changed := comparePackages(oldDependencies, newDependencies)

	systemPathPath := findReference(newPathInfos[newRoot], "system-path")
	etcPath := findReference(newPathInfos[newRoot], "etc")

	directDependencies := make(map[string]bool)
	if systemPathPath != nil && etcPath != nil {
		// We assume this is a NixOS system.

		// Detect environment.systemPackages as direct dependencies.
		for _, path := range newPathInfos[*systemPathPath].References {
			directDependencies[path] = true
		}

		// Detect users.users.<name>.packages as direct dependencies.
		for _, path := range newPathInfos[*etcPath].References {
			name, _ := stripDigest(filepath.Base(path))
			if name == "user-environment" {
				for _, path := range newPathInfos[path].References {
					directDependencies[path] = true
				}
			}
		}
	} else {
		for _, path := range newPathInfos[newRoot].References {
			directDependencies[path] = true
		}

	}

	printChanges(w, added, removed, changed, directDependencies)

	return nil
}

type PathInfo struct {
	References []string `json:"references"`
}

func queryPaths(path string) (map[string]PathInfo, error) {
	// We're using the experimental CLI because the stable CLI does not support JSON output.
	cmd := exec.Command("nix", "path-info", "--json", "--recursive", "--extra-experimental-features", "nix-command", "--", path)

	var stderr bytes.Buffer
	cmd.Stderr = &stderr

	output, err := cmd.Output()
	if err != nil {
		return nil, fmt.Errorf(
			"error: nix path-info --json failed: %v\n    %s",
			err, strings.TrimSpace(stderr.String()))
	}

	var paths map[string]PathInfo
	if err := json.Unmarshal(output, &paths); err != nil {
		return nil, fmt.Errorf("error parsing JSON: %v", err)
	}
	return paths, nil
}

func findReference(info PathInfo, name string) *string {
	pathIdx := slices.IndexFunc(info.References, func(path string) bool {
		pathName, _ := stripDigest(filepath.Base(path))
		return pathName == name
	})
	if pathIdx == -1 {
		return nil
	}
	return &info.References[pathIdx]
}

var digestRe = regexp.MustCompile(`^[a-z0-9]{32}-`)

func stripDigest(name string) (string, error) {
	indices := digestRe.FindStringIndex(name)
	if indices == nil {
		return name, fmt.Errorf("path %q did not start with digest", name)
	}
	return name[indices[1]:], nil
}

type Dependency struct {
	Name    string
	Version string
	Output  string
	Path    string
}

// We assume that versions start with a digit (nixpkgs also requires this.)
// We only recognize outputs after a version and assume it starts with a non-digit and doesn't contain a dash.
var outputNameRe = regexp.MustCompile(`(.+?)(?:-([0-9].*?)(?:-([^0-9].+))?)?$`)

// For derivations there is no output name and we strip .drv if it exists.
var derivationNameRe = regexp.MustCompile(`(.+?)(?:-([0-9].*?)())?(?:\.drv)?$`)

func parseStorePath(nameRe *regexp.Regexp, path string) (*Dependency, error) {
	name, err := stripDigest(filepath.Base(path))
	if err != nil {
		return nil, fmt.Errorf("path %s did not start with digest", path)
	}
	// fixed output derivations have a name starting with two digests
	name, _ = stripDigest(name)
	matches := nameRe.FindStringSubmatch(name)
	if matches == nil {
		return nil, fmt.Errorf("path %s did not match regex", path)
	}
	return &Dependency{
		Name:    matches[1],
		Version: matches[2],
		Output:  matches[3],
		Path:    path,
	}, nil
}

type VersionChange struct {
	Name        string
	Output      string
	OldVersions []Version
	NewVersions []Version
}

type Version struct {
	Version string
	Paths   []string
}

func (vc *Dependency) nameOutput() NameOutput {
	return NameOutput{vc.Name, vc.Output}
}

type NameOutput struct {
	Name   string
	Output string
}

func comparePackages(oldDependencies, newDependencies []Dependency) ([]Dependency, []Dependency, []VersionChange) {
	// For one package name there can be different versions in the same dependency tree.
	oldMap := make(map[NameOutput][]Dependency)
	newMap := make(map[NameOutput][]Dependency)

	for _, dep := range oldDependencies {
		versions, exists := oldMap[dep.nameOutput()]
		if exists {
			oldMap[dep.nameOutput()] = append(versions, dep)
		} else {
			oldMap[dep.nameOutput()] = []Dependency{dep}
		}
	}

	for _, dep := range newDependencies {
		versions, exists := newMap[dep.nameOutput()]
		if exists {
			newMap[dep.nameOutput()] = append(versions, dep)
		} else {
			newMap[dep.nameOutput()] = []Dependency{dep}
		}
	}

	var added []Dependency
	var removed []Dependency
	var changed []VersionChange

	for nameOut, newDeps := range newMap {
		if oldDeps, exists := oldMap[nameOut]; exists {
			// There can be different paths in the same dependency tree with the same package name and version.
			oldVersions := groupByVersion(oldDeps)
			newVersions := groupByVersion(newDeps)

			if !slices.EqualFunc(newVersions, oldVersions, sameVersion) {
				changed = append(changed, VersionChange{
					Name:        nameOut.Name,
					Output:      nameOut.Output,
					OldVersions: oldVersions,
					NewVersions: newVersions,
				})
			}
		} else {
			added = append(added, newDeps...)
		}
	}

	for nameOut, oldDeps := range oldMap {
		if _, exists := newMap[nameOut]; !exists {
			removed = append(removed, oldDeps...)
		}
	}

	return added, removed, changed
}

func groupByVersion(deps []Dependency) []Version {
	versionMap := make(map[string][]string)
	for _, dep := range deps {
		if dep.Version == "" {
			continue
		}
		paths, exists := versionMap[dep.Version]
		if exists {
			versionMap[dep.Version] = append(paths, dep.Path)
		} else {
			versionMap[dep.Version] = []string{dep.Path}
		}
	}
	versions := make([]Version, 0, len(versionMap))
	for version, paths := range versionMap {
		versions = append(versions, Version{version, paths})
	}
	slices.SortFunc(versions, func(a Version, b Version) int {
		return strings.Compare(a.Version, b.Version)
	})
	return versions
}

func sameVersion(v1, v2 Version) bool {
	return v1.Version == v2.Version
}

func printChanges(w io.Writer, added, removed []Dependency, changed []VersionChange, newDirectDeps map[string]bool) {
	if len(changed) > 0 {
		fmt.Fprintln(w, "Version changed:")
		// TODO: grouping changes into categories defined in TOML config
		changedSelected := make([]VersionChange, 0)
		changedUnselected := make([]VersionChange, 0)
		for _, change := range changed {
			// If any path of any new version is a direct dependency in the new dependency tree
			// we show the whole version change in the direct dependency section because figuring
			// out which old version exactly changed to which new version is non-trivial
			// since there can be several versions.
			if slices.IndexFunc(change.NewVersions, func(v Version) bool {
				for _, path := range v.Paths {
					_, exists := newDirectDeps[path]
					if exists {
						return true
					}
				}
				return false
			}) != -1 {
				changedSelected = append(changedSelected, change)
			} else {
				changedUnselected = append(changedUnselected, change)
			}
		}
		printVersionChanges(w, filterVersionChanges(changedSelected))
		if len(changedSelected) > 0 && len(changedUnselected) > 0 {
			fmt.Fprintln(w)
		}
		printVersionChanges(w, filterVersionChanges(changedUnselected))
	}
	if len(added) > 0 {
		if len(changed) > 0 {
			fmt.Fprintln(w)
		}
		fmt.Fprintln(w, "Added packages:")
		printDependencyList(w, added)
	}
	if len(removed) > 0 {
		if len(added) > 0 || len(changed) > 0 {
			fmt.Fprintln(w)
		}
		fmt.Fprintln(w, "Removed packages:")
		printDependencyList(w, removed)
	}
}

func filterVersionChanges(versionChanges []VersionChange) []VersionChange {
	slices.SortFunc(versionChanges, func(a, b VersionChange) int {
		if a.Name == b.Name {
			return strings.Compare(a.Output, b.Output)
		}
		return strings.Compare(a.Name, b.Name)
	})
	var outChange VersionChange
	filteredVersionChanges := []VersionChange{}
	for _, change := range versionChanges {
		if change.Name == outChange.Name &&
			slices.EqualFunc(change.OldVersions, outChange.OldVersions, sameVersion) &&
			slices.EqualFunc(change.NewVersions, outChange.NewVersions, sameVersion) {
			continue
		}

		filteredVersionChanges = append(filteredVersionChanges, change)

		if change.Output == "" {
			outChange = change
		}
	}
	return filteredVersionChanges
}

func printVersionChanges(w io.Writer, changed []VersionChange) {
	for _, change := range changed {
		// TODO: link changelogs defined in TOML config
		fmt.Fprintf(w, "  %s%s: %s -> %s\n", change.Name, formatOutput(change.Output),
			strings.Join(mapSlice(change.OldVersions, version), ", "),
			strings.Join(mapSlice(change.NewVersions, version), ", "),
		)
	}
}

func version(v Version) string {
	return v.Version
}

func printDependencyList(w io.Writer, deps []Dependency) {
	slices.SortFunc(deps, func(a, b Dependency) int {
		if a.Name == b.Name {
			return strings.Compare(a.Output, b.Output)
		}
		return strings.Compare(a.Name, b.Name)
	})
	for _, dep := range deps {
		fmt.Fprintf(w, "  %s%s %s\n", dep.Name, formatOutput(dep.Output), dep.Version)
	}
}

func formatOutput(output string) string {
	if output == "" {
		return ""
	} else {
		return fmt.Sprintf("(%s)", output)
	}
}

func mapSlice[T, U any](slice []T, fn func(T) U) []U {
	result := make([]U, len(slice))
	for i, v := range slice {
		result[i] = fn(v)
	}
	return result
}