gomod2nix/builder/symlink/symlink.go

111 lines
2.3 KiB
Go
Raw Normal View History

2020-07-23 09:11:31 +00:00
package main
import (
"encoding/json"
2022-05-20 08:31:44 +00:00
"fmt"
2020-07-23 09:11:31 +00:00
"io/ioutil"
"os"
"path/filepath"
"sort"
)
2022-05-28 13:49:49 +00:00
type Package struct {
GoPackagePath string `json:"-"`
Version string `json:"version"`
Hash string `json:"hash"`
ReplacedPath string `json:"replaced,omitempty"`
2020-07-23 09:11:31 +00:00
}
// type Output struct {
// SchemaVersion int `json:"schema"`
// Mod map[string]*Package `json:"mod"`
// }
2020-07-23 09:11:31 +00:00
func main() {
// var output Output
2020-07-23 09:11:31 +00:00
sources := make(map[string]string)
pkgs := make(map[string]*Package)
{
b, err := ioutil.ReadFile(os.Getenv("sourcesPath"))
if err != nil {
panic(err)
}
err = json.Unmarshal(b, &sources)
if err != nil {
panic(err)
}
2020-07-23 09:11:31 +00:00
}
{
b, err := ioutil.ReadFile(os.Getenv("jsonPath"))
if err != nil {
panic(err)
}
2020-07-23 09:11:31 +00:00
err = json.Unmarshal(b, &pkgs)
if err != nil {
panic(err)
}
2020-07-23 09:11:31 +00:00
}
keys := make([]string, 0, len(pkgs))
for key := range pkgs {
keys = append(keys, key)
}
sort.Strings(keys)
// Iterate, in reverse order
for i := len(keys) - 1; i >= 0; i-- {
key := keys[i]
src := sources[key]
paths := []string{key}
for _, path := range paths {
vendorDir := filepath.Join("vendor", filepath.Dir(path))
if err := os.MkdirAll(vendorDir, 0755); err != nil {
panic(err)
}
2020-07-23 09:11:31 +00:00
if _, err := os.Stat(filepath.Join("vendor", path)); err == nil {
files, err := ioutil.ReadDir(src)
if err != nil {
panic(err)
}
for _, f := range files {
innerSrc := filepath.Join(src, f.Name())
dst := filepath.Join("vendor", path, f.Name())
if err := os.Symlink(innerSrc, dst); err != nil {
// assume it's an existing directory, try to link the directory content instead.
// TODO should we do this recursively
files, err := ioutil.ReadDir(innerSrc)
if err != nil {
panic(err)
}
for _, f := range files {
if err := os.Symlink(filepath.Join(innerSrc, f.Name()), filepath.Join(dst, f.Name())); err != nil {
2022-05-20 08:31:44 +00:00
fmt.Println("ignore symlink error", filepath.Join(innerSrc, f.Name()), filepath.Join(dst, f.Name()))
}
}
}
2020-07-23 09:11:31 +00:00
}
continue
}
// If the file doesn't already exist, just create a simple symlink
err := os.Symlink(src, filepath.Join("vendor", path))
if err != nil {
panic(err)
}
}
}
}