~thomir-deactivatedaccount/charm-haproxy/make-config-less-insane

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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# Copyright 2010-2013 Canonical Ltd. All rights reserved.
import os
import re
import sys
import errno
import hashlib
import subprocess
import optparse

from os import curdir
from bzrlib.branch import Branch
from bzrlib.plugin import load_plugins
load_plugins()
from bzrlib.plugins.launchpad import account as lp_account

if 'GlobalConfig' in dir(lp_account):
    from bzrlib.config import LocationConfig as LocationConfiguration
    _ = LocationConfiguration
else:
    from bzrlib.config import LocationStack as LocationConfiguration
    _ = LocationConfiguration


def get_branch_config(config_file):
    """
    Retrieves the sourcedeps configuration for an source dir.
    Returns a dict of (branch, revspec) tuples, keyed by branch name.
    """
    branches = {}
    with open(config_file, 'r') as stream:
        for line in stream:
            line = line.split('#')[0].strip()
            bzr_match = re.match(r'(\S+)\s+'
                                 'lp:([^;]+)'
                                 '(?:;revno=(\d+))?', line)
            if bzr_match:
                name, branch, revno = bzr_match.group(1, 2, 3)
                if revno is None:
                    revspec = -1
                else:
                    revspec = revno
                branches[name] = (branch, revspec)
                continue
            dir_match = re.match(r'(\S+)\s+'
                                 '\(directory\)', line)
            if dir_match:
                name = dir_match.group(1)
                branches[name] = None
    return branches


def main(config_file, parent_dir, target_dir, verbose):
    """Do the deed."""

    try:
        os.makedirs(parent_dir)
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise

    branches = sorted(get_branch_config(config_file).items())
    for branch_name, spec in branches:
        if spec is None:
            # It's a directory, just create it and move on.
            destination_path = os.path.join(target_dir, branch_name)
            if not os.path.isdir(destination_path):
                os.makedirs(destination_path)
            continue

        (quoted_branch_spec, revspec) = spec
        revno = int(revspec)

        # qualify mirror branch name with hash of remote repo path to deal
        # with changes to the remote branch URL over time
        branch_spec_digest = hashlib.sha1(quoted_branch_spec).hexdigest()
        branch_directory = branch_spec_digest

        source_path = os.path.join(parent_dir, branch_directory)
        destination_path = os.path.join(target_dir, branch_name)

        # Remove leftover symlinks/stray files.
        try:
            os.remove(destination_path)
        except OSError, e:
            if e.errno != errno.EISDIR and e.errno != errno.ENOENT:
                raise

        lp_url = "lp:" + quoted_branch_spec

        # Create the local mirror branch if it doesn't already exist
        if verbose:
            sys.stderr.write('%30s: ' % (branch_name,))
            sys.stderr.flush()

        fresh = False
        if not os.path.exists(source_path):
            subprocess.check_call(['bzr', 'branch', '-q', '--no-tree',
                                   '--', lp_url, source_path])
            fresh = True

        if not fresh:
            source_branch = Branch.open(source_path)
            if revno == -1:
                orig_branch = Branch.open(lp_url)
                fresh = source_branch.revno() == orig_branch.revno()
            else:
                fresh = source_branch.revno() == revno

        # Freshen the source branch if required.
        if not fresh:
            subprocess.check_call(['bzr', 'pull', '-q', '--overwrite', '-r',
                                   str(revno), '-d', source_path,
                                   '--', lp_url])

        if os.path.exists(destination_path):
            # Overwrite the destination with the appropriate revision.
            subprocess.check_call(['bzr', 'clean-tree', '--force', '-q',
                                   '--ignored', '-d', destination_path])
            subprocess.check_call(['bzr', 'pull', '-q', '--overwrite',
                                   '-r', str(revno),
                                   '-d', destination_path, '--', source_path])
        else:
            # Create a new branch.
            subprocess.check_call(['bzr', 'branch', '-q', '--hardlink',
                                   '-r', str(revno),
                                   '--', source_path, destination_path])

        # Check the state of the destination branch.
        destination_branch = Branch.open(destination_path)
        destination_revno = destination_branch.revno()

        if verbose:
            sys.stderr.write('checked out %4s of %s\n' %
                             ("r" + str(destination_revno), lp_url))
            sys.stderr.flush()

        if revno != -1 and destination_revno != revno:
            raise RuntimeError("Expected revno %d but got revno %d" %
                               (revno, destination_revno))

if __name__ == '__main__':
    parser = optparse.OptionParser(
        usage="%prog [options]",
        description=(
            "Add a lightweight checkout in <target> for each "
            "corresponding file in <parent>."),
        add_help_option=False)
    parser.add_option(
        '-p', '--parent', dest='parent',
        default=None,
        help=("The directory of the parent tree."),
        metavar="DIR")
    parser.add_option(
        '-t', '--target', dest='target', default=curdir,
        help=("The directory of the target tree."),
        metavar="DIR")
    parser.add_option(
        '-c', '--config', dest='config', default=None,
        help=("The config file to be used for config-manager."),
        metavar="DIR")
    parser.add_option(
        '-q', '--quiet', dest='verbose', action='store_false',
        help="Be less verbose.")
    parser.add_option(
        '-v', '--verbose', dest='verbose', action='store_true',
        help="Be more verbose.")
    parser.add_option(
        '-h', '--help', action='help',
        help="Show this help message and exit.")
    parser.set_defaults(verbose=True)

    options, args = parser.parse_args()

    if options.parent is None:
        options.parent = os.environ.get(
            "SOURCEDEPS_DIR",
            os.path.join(curdir, ".sourcecode"))

    if options.target is None:
        parser.error(
            "Target directory not specified.")

    if options.config is None:
        config = [arg for arg in args
                  if arg != "update"]
        if not config or len(config) > 1:
            parser.error("Config not specified")
        options.config = config[0]

    sys.exit(main(config_file=options.config,
                  parent_dir=options.parent,
                  target_dir=options.target,
                  verbose=options.verbose))