about summary refs log tree commit diff
path: root/external/main.go
blob: aac966172b3420cfda04a96129fa3f107c1eb461 (plain) (blame)
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
// Copyright 2019 Google LLC.
// SPDX-License-Identifier: Apache-2.0

// This tool analyses external (i.e. not built with `buildGo.nix`) Go
// packages to determine a build plan that Nix can import.
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"go/build"
	"io/ioutil"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"
)

// Path to a JSON file describing all standard library import paths.
// This file is generated and set here by Nix during the build
// process.
var stdlibList string

// pkg describes a single Go package within the specified source
// directory.
//
// Return information includes the local (relative from project root)
// and external (none-stdlib) dependencies of this package.
type pkg struct {
	Name        string     `json:"name"`
	Locator     []string   `json:"locator"`
	Files       []string   `json:"files"`
	LocalDeps   [][]string `json:"localDeps"`
	ForeignDeps []string   `json:"foreignDeps"`
}

// findGoDirs returns a filepath.WalkFunc that identifies all
// directories that contain Go source code in a certain tree.
func findGoDirs(at string) ([]string, error) {
	dirSet := make(map[string]bool)

	err := filepath.Walk(at, func(path string, info os.FileInfo, err error) error {
		// Skip folders that are guaranteed to not be relevant
		if info.IsDir() && (info.Name() == "testdata" || info.Name() == ".git") {
			return filepath.SkipDir
		}

		// If the current file is a Go file, then the directory is popped
		// (i.e. marked as a Go directory).
		if !info.IsDir() && strings.HasSuffix(info.Name(), ".go") && !strings.HasSuffix(info.Name(), "_test.go") {
			dirSet[filepath.Dir(path)] = true
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	goDirs := []string{}
	for k, _ := range dirSet {
		goDirs = append(goDirs, k)
	}

	return goDirs, nil
}

// analysePackage loads and analyses the imports of a single Go
// package, returning the data that is required by the Nix code to
// generate a derivation for this package.
func analysePackage(root, source, importpath string, stdlib map[string]bool) (pkg, error) {
	ctx := build.Default

	p, err := ctx.ImportDir(source, build.IgnoreVendor)
	if err != nil {
		return pkg{}, err
	}

	local := [][]string{}
	foreign := []string{}

	for _, i := range p.Imports {
		if stdlib[i] {
			continue
		}

		if strings.HasPrefix(i, importpath) {
			local = append(local, strings.Split(strings.TrimPrefix(i, importpath+"/"), "/"))
		} else {
			foreign = append(foreign, i)
		}
	}

	prefix := strings.TrimPrefix(source, root+"/")

	locator := []string{}
	if len(prefix) != len(source) {
		locator = strings.Split(prefix, "/")
	} else {
		// Otherwise, the locator is empty since its the root package and
		// no prefix should be added to files.
		prefix = ""
	}

	files := []string{}
	for _, f := range p.GoFiles {
		files = append(files, path.Join(prefix, f))
	}

	return pkg{
		Name:        path.Join(importpath, prefix),
		Locator:     locator,
		Files:       files,
		LocalDeps:   local,
		ForeignDeps: foreign,
	}, nil
}

func loadStdlibPkgs(from string) (pkgs map[string]bool, err error) {
	f, err := ioutil.ReadFile(from)
	if err != nil {
		return
	}

	err = json.Unmarshal(f, &pkgs)
	return
}

func main() {
	source := flag.String("source", "", "path to directory with sources to process")
	path := flag.String("path", "", "import path for the package")

	flag.Parse()

	if *source == "" {
		log.Fatalf("-source flag must be specified")
	}

	stdlibPkgs, err := loadStdlibPkgs(stdlibList)
	if err != nil {
		log.Fatalf("failed to load standard library index from %q: %s\n", stdlibList, err)
	}

	goDirs, err := findGoDirs(*source)
	if err != nil {
		log.Fatalf("failed to walk source directory '%s': %s\n", source, err)
	}

	all := []pkg{}
	for _, d := range goDirs {
		analysed, err := analysePackage(*source, d, *path, stdlibPkgs)
		if err != nil {
			log.Fatalf("failed to analyse package at %q: %s", d, err)
		}
		all = append(all, analysed)
	}

	j, _ := json.Marshal(all)
	fmt.Println(string(j))
}