| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
package configstore |
| 11 |
|
| 12 |
import ( |
| 13 |
"bytes" |
| 14 |
"encoding/json" |
| 15 |
"fmt" |
| 16 |
"os" |
| 17 |
"os/exec" |
| 18 |
"path/filepath" |
| 19 |
|
| 20 |
"golang.org/x/telemetry/internal/telemetry" |
| 21 |
) |
| 22 |
|
| 23 |
const ( |
| 24 |
ModulePath = "golang.org/x/telemetry/config" |
| 25 |
configFileName = "config.json" |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
var needNoConsole = func(cmd *exec.Cmd) {} |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
func Download(version string, envOverlay []string) (*telemetry.UploadConfig, string, error) { |
| 38 |
if version == "" { |
| 39 |
version = "latest" |
| 40 |
} |
| 41 |
modVer := ModulePath + "@" + version |
| 42 |
var stdout, stderr bytes.Buffer |
| 43 |
cmd := exec.Command("go", "mod", "download", "-json", modVer) |
| 44 |
needNoConsole(cmd) |
| 45 |
cmd.Env = append(os.Environ(), envOverlay...) |
| 46 |
cmd.Stdout = &stdout |
| 47 |
cmd.Stderr = &stderr |
| 48 |
if err := cmd.Run(); err != nil { |
| 49 |
var info struct { |
| 50 |
Error string |
| 51 |
} |
| 52 |
if err := json.Unmarshal(stdout.Bytes(), &info); err == nil && info.Error != "" { |
| 53 |
return nil, "", fmt.Errorf("failed to download config module: %v", info.Error) |
| 54 |
} |
| 55 |
return nil, "", fmt.Errorf("failed to download config module: %w\n%s", err, &stderr) |
| 56 |
} |
| 57 |
|
| 58 |
var info struct { |
| 59 |
Dir string |
| 60 |
Version string |
| 61 |
Error string |
| 62 |
} |
| 63 |
if err := json.Unmarshal(stdout.Bytes(), &info); err != nil || info.Dir == "" { |
| 64 |
return nil, "", fmt.Errorf("failed to download config module (invalid JSON): %w", err) |
| 65 |
} |
| 66 |
data, err := os.ReadFile(filepath.Join(info.Dir, configFileName)) |
| 67 |
if err != nil { |
| 68 |
return nil, "", fmt.Errorf("invalid config module: %w", err) |
| 69 |
} |
| 70 |
cfg := new(telemetry.UploadConfig) |
| 71 |
if err := json.Unmarshal(data, cfg); err != nil { |
| 72 |
return nil, "", fmt.Errorf("invalid config: %w", err) |
| 73 |
} |
| 74 |
return cfg, info.Version, nil |
| 75 |
} |