File: apt.go

package info (click to toggle)
golang-github-juju-utils 0.0~git20171220.f38c0b0-5
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,748 kB
  • sloc: makefile: 20
file content (88 lines) | stat: -rw-r--r-- 2,286 bytes parent folder | download | duplicates (2)
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
// Copyright 2015 Canonical Ltd.
// Copyright 2015 Cloudbase Solutions SRL
// Licensed under the LGPLv3, see LICENCE file for details.

package manager

import (
	"bytes"
	"fmt"
	"os/exec"
	"regexp"
	"strings"

	"github.com/juju/errors"
	"github.com/juju/utils/proxy"
)

// proxyRe is a regexp which matches all proxy-related configuration options in
// the apt configuration file.
var proxyRE = regexp.MustCompile(`(?im)^\s*Acquire::(?P<protocol>[a-z]+)::Proxy\s+"(?P<proxy>[^"]+)";\s*$`)

// apt is the PackageManager implementation for deb-based systems.
type apt struct {
	basePackageManager
}

// Search is defined on the PackageManager interface.
func (apt *apt) Search(pack string) (bool, error) {
	out, _, err := RunCommandWithRetry(apt.cmder.SearchCmd(pack), nil)
	if err != nil {
		return false, err
	}

	// apt-cache search --names-only package returns no output
	// if the search was unsuccesful
	if out == "" {
		return false, nil
	}
	return true, nil
}

// Install is defined on the PackageManager interface.
func (apt *apt) Install(packs ...string) error {
	fatalErr := func(output string) error {
		// If we couldn't find the package don't retry.
		// apt-get will report "Unable to locate package"
		if strings.Contains(output, "Unable to locate package") {
			return errors.New("unable to locate package")
		}
		return nil
	}
	_, _, err := RunCommandWithRetry(apt.cmder.InstallCmd(packs...), fatalErr)
	return err
}

// GetProxySettings is defined on the PackageManager interface.
func (apt *apt) GetProxySettings() (proxy.Settings, error) {
	var res proxy.Settings

	args := strings.Fields(apt.cmder.GetProxyCmd())
	if len(args) <= 1 {
		return proxy.Settings{}, fmt.Errorf("expected at least 2 arguments, got %d %v", len(args), args)
	}

	cmd := exec.Command(args[0], args[1:]...)
	out, err := CommandOutput(cmd)

	if err != nil {
		logger.Errorf("command failed: %v\nargs: %#v\n%s",
			err, args, string(out))
		return res, fmt.Errorf("command failed: %v", err)
	}

	output := string(bytes.Join(proxyRE.FindAll(out, -1), []byte("\n")))

	for _, match := range proxyRE.FindAllStringSubmatch(output, -1) {
		switch match[1] {
		case "http":
			res.Http = match[2]
		case "https":
			res.Https = match[2]
		case "ftp":
			res.Ftp = match[2]
		}
	}

	return res, nil
}