1// Copyright 2020 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package fake
6
7import (
8	"fmt"
9
10	"golang.org/x/tools/internal/proxydir"
11)
12
13// WriteProxy creates a new proxy file tree using the txtar-encoded content,
14// and returns its URL.
15func WriteProxy(tmpdir string, files map[string][]byte) (string, error) {
16	type moduleVersion struct {
17		modulePath, version string
18	}
19	// Transform into the format expected by the proxydir package.
20	filesByModule := make(map[moduleVersion]map[string][]byte)
21	for name, data := range files {
22		modulePath, version, suffix := splitModuleVersionPath(name)
23		mv := moduleVersion{modulePath, version}
24		if _, ok := filesByModule[mv]; !ok {
25			filesByModule[mv] = make(map[string][]byte)
26		}
27		filesByModule[mv][suffix] = data
28	}
29	for mv, files := range filesByModule {
30		if err := proxydir.WriteModuleVersion(tmpdir, mv.modulePath, mv.version, files); err != nil {
31			return "", fmt.Errorf("error writing %s@%s: %v", mv.modulePath, mv.version, err)
32		}
33	}
34	return proxydir.ToURL(tmpdir), nil
35}
36