~abentley/bzrtools/bzrtools.dev

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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# Copyright (C) 2004 Aaron Bentley
# <aaron.bentley@utoronto.ca>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

__docformat__ = "restructuredtext"
__doc__ = "Utility functionality not part of core Arch"

import errors
import os
import pybaz as arch
import string
import urllib
import urllib2
import re

import arch_core
import arch_compound
import util

def iter_alias(my_file):
    """
    Iterate through aliases in the supplied file.

    :param my_file: The name of the file to read.  May include ~/ notation.
    :type my_file: string
    :rtype: iterator of list of string
    """
    tmp = os.path.expanduser(my_file)
    if not os.access(tmp, os.R_OK) or not os.path.isfile(tmp):
        return
    for line in open(tmp):
        line=line.rstrip("\n")
        if line.startswith("#") or len(line)==0 or line.isspace():
            continue
        parts=string.split(line, "=")
        parts[0]=parts[0].strip()
        parts[1]=parts[1].strip()
        if len(parts)!=2:
            raise errors.CantParseAlias(line)
        if parts[1][0]=="\"":
            if parts[1][-1]=="\"":
                parts[1]=parts[1][1:-1]
            else:
                raise errors.CantParseAlias(line)
        check_alias(line, parts)
        yield parts


def check_alias(line, parts):
    """Ensures that a given alias name is suitable for use"""
    if '@' in parts[0] or '/' in parts[0] or '--' in parts[0]:
        raise errors.ForbiddenAliasSyntax(line)


def iter_all_alias(tree):
    """
    Iterate all relevent aliases.

    An alias name may appear more than once in the output.  The last value
    to appear is the one that should be used.  Iterates through ~/.aba/aliases
    and per-tree aliases.

    :param tree: The working tree to seek aliases in (may be None)
    :type tree: `arch.ArchSourceTree`
    :rtype: iterator of list of string
    """
    for parts in iter_alias("~/.aba/aliases"):
        yield parts
    if tree==None:
        return;
    treefile=None
    tmp=str(tree)+"/{arch}/+aliases"
    if os.access(tmp, os.R_OK) and os.path.isfile(tmp):
        treefile=tmp
    if treefile is None:
        tmp=str(tree)+"/{arch}/=aliases"
        if os.access(tmp, os.R_OK) and os.path.isfile(tmp):
            treefile=tmp
    if treefile!=None:
        for parts in iter_alias(treefile):
            yield parts


def compact_alias(spec, tree):
    aliases = []
    for parts in iter_all_alias(tree):
        if spec.startswith(parts[1]):
            newalias=parts[0]+spec[len(parts[1]):]
            aliases.append(newalias)
    return aliases


def shortest_alias(spec, tree):
    """Convenience function to return the shortest alias for a spec.

    :param spec: The spec to compact
    :type spec: Convertible to str
    :param tree: The working tree to use for local alias lookup
    :type tree: `arch.WorkingTree`
    :return: The shortest alias, or None if no aliases were found
    :rtype: str or NoneType
    """
    aliases = compact_alias(str(spec), tree)
    return util.shortest(aliases)
 
 
def alias_or_version(version, tree, full=True):
    """Return the shortest alias or version name for a version.

    :param version: The spec to compact
    :type version: `arch.Version`
    :param tree: The working tree to use for local alias lookup
    :type tree: `arch.WorkingTree`
    :param full: Use the full version name (use nonarch if false).
    :type full: bool
    :return: The shortest alias, or the version name
    :rtype: str
    """
    alias = shortest_alias(version, tree)
    if alias is not None:
        return alias
    elif full:
        return version.fullname
    else:
        return version.nonarch


def iter_partners(tree, skip_version=None):
    """Generate an iterator of partner versions.
    If the tree contains {arch}/+partner-versions, it is used.  Otherwise,
    {arch}/=partner-versions is used.

    :param tree: The tree to find partner versions for
    :type tree: `arch.ArchSourceTree`
    :return: An iterator of partner versions for the tree
    :rtype: iterator of `arch.Version`
    """
    partnerfile=str(tree)+"/{arch}/+partner-versions"
    if not os.access(partnerfile, os.R_OK) or not os.path.isfile(partnerfile):
        partnerfile=str(tree)+"/{arch}/=partner-versions"
        if not os.access(partnerfile, os.R_OK) or not \
            os.path.isfile(partnerfile):
                return

    for line in open(partnerfile):
        version = arch.Version(line.rstrip("\n"))
        if version == skip_version:
            continue
        yield version


def iter_partner_revisions(tree, skip_version):
    """Iterates through the archive-latest revisions of all partner versions.

    :param tree: The tree to get revisions for
    :type tree: `arch.ArchSourceTree`
    :param skip_version: A version to skip (typically the tree version)
    :type skip_version: `arch.Version`
    """
    for partner in iter_partners(tree, skip_version):
        arch_compound.ensure_archive_registered(partner.archive)
        try:
            yield partner.iter_revisions(True).next()
        except StopIteration, e:
            continue


def sc_lookup(archive):
    """Uses James Blackwell's mirror stats page to look up archive locations.

    :param archive: The Archive to find a location for
    :type archive: str or `arch.Archive`
    :return: home and mirror archive (either or both may be none)
    :rtype: tuple of str or NoneType
    """
    try:
        mirrorpage = urllib2.urlopen("http://sourcecontrol.net/?m=mirrorstats")
    except Exception, e:
        raise LookupError(e, archive, "sourcecontrol.net")
    expression = re.compile("Name : <a href=\"[^\"]*\">%s</a>" % archive)
    for line in mirrorpage:
        if expression.search(line) is not None:
            home = re.search("Home : <a href=\"([^\"]*)\">", line)
            if home is not None:
                home = home.group(1)
            mirror = re.search("Mirror: <a href=\"([^\"]*)\">", line)
            if mirror is not None:
                mirror = mirror.group(1)
            return (home,mirror)
    return (None, None)


def bh_lookup(archive):
    """Uses Gergely Nagy's archive registry to look up archive locations.

    :param archive: The Archive to find a location for
    :type archive: str or `arch.Archive`
    :return: home and mirror archive (either or both may be none)
    :rtype: tuple of str or NoneType
    """
    url = "http://bonehunter.rulez.org/~arch-registry/%s"\
        % str(archive)
    try:
        page = urllib2.urlopen(url)
    except Exception, e:
        raise LookupError(e, archive, "http://bonehunter.rulez.org")
    for line in page:
        if line.startswith("Archive not found"):
            return None
        loc = line
        break
    if loc is not None:
         loc = loc.rstrip("\n")
    if len(loc) == 0:
        loc = None
    return loc


def bh_submit(archive, location):
    """Submit an archive location to Gergely Nagy's archive registry.

    :param archive: The Archive to find a location for
    :type archive: str or `arch.Archive`
    :param location: The location to use for the archive
    :type location: str
    """
    data = urllib.urlencode({"name": str(archive), "location": location})
    url = "http://bonehunter.rulez.org/~arch-registry/submit.cgi"
    result = urllib2.urlopen(url, data).next().rstrip()
    if result != "Archive %s registered with location %s." % \
        (str(archive), location):
        raise errors.SubmitError(str(archive), location, url, result)

def iter_micro(tree, my_version=None):
    if my_version is None:
        my_version = tree.tree_version
    for version in iter_partners(tree, tree.tree_version):
        miss = arch_core.iter_missing(tree, version) 
        for log in arch_compound.iter_log_match(miss, "Microbranch", 
                                                str(my_version)):
            yield log


def submit_version(tree):
    """Determine the submit version of this tree
    
    :param tree: The tree to determine the version of
    :type tree: `arch.ArchSourceTree`
    :return: The submit version, or None
    :rtype: `arch.Version`
    """
    submit_file = tree+"/{arch}/+submit-version"
    if not os.access(submit_file, os.R_OK):
        return None
    line = open(submit_file).next()
    return arch.Version(line.rstrip("\n"))


def submit_revision(tree):
    """If this tree has new merges from the submit version, return latest

    :param tree: The tree to determine the revision of
    :type tree: `arch.ArchSourceTree`
    :return: the latest submit revision merged, or None
    :rtype: `arch.Revision`
    """
    submit_ver = submit_version(tree)
    if submit_ver is not None:
        for log in arch_core.iter_new_merges(tree, tree.tree_version, True):
            if log.revision.version == submit_ver:
                return log.revision
    return None
    

def comp_revision(tree):
    """Return the base revision to compare with.  For most trees, this is just
    the latest revision of the tree version, but for submit trees with submit
    version merges, it's different.
    :param tree: The tree to determine the revision of
    :type tree: `arch.ArchSourceTree`
    :return: the latest submit revision merged, or None
    :rtype: `arch.Revision`
    """
    submit_rev = submit_revision(tree)
    if submit_rev is not None:
        return submit_rev
    else:
        try:
            return arch_compound.tree_latest(tree)
        except errors.NoVersionRevisions, e:
            raise errors.CantDetermineRevision("", "This tree shows no commits"
                                                   " for version %s" % 
                                                   e.version)


def log_template_path(tree):
    """Return the path of the template to use for commit logs, if any.  Tries
    tree and .arch-params.
    
    :param tree: The tree to find the template for
    :type tree: `arch.WorkingTree`
    :return: The path or None if no template exists
    :rtype: str or NoneType
    """
    template = tree+"/{arch}/=log-template"
    if os.path.exists(template):
        return template

    else:
        template = os.path.expanduser("~/.arch-params/=log-template")
        if os.path.exists(template):
            return template
        else:
            return None

def version_difference(version, compare_version):
    """Compares two versions, and returns the part of the name that differs
    :param version: The version to describe
    :type version: `arch.Version`
    :param compare_version: The version to compare to
    :type compare_version: `arch.Version`
    """
    if version.archive == compare_version.archive:
        p_version = arch.NameParser(version)
        pc_version = arch.NameParser(compare_version)
        if p_version.get_category() != pc_version.get_category():
            return version.nonarch
        elif p_version.get_branch() != pc_version.get_branch() and\
            p_version.get_branch() != "":
            return "%s--%s" % (p_version.get_branch(), 
                               p_version.get_version())
        else:
            return p_version.get_version()

    elif version.nonarch == compare_version.nonarch:
        return str(version.archive)
    else:
        return str(version)


def merge_summary(new_merges, tree_version):
    """Produce a nice summary line for a merge commit log.
    :param new_merges: iterator of newly-merged logs
    :type new_merges: iter of `arch.Patchlog`
    :param tree_version: The tree version to produce a summary for
    :type tree_version: `arch.Version`
    :return: the summary, or "" if there were no new merges.
    :rtype: str
    """
    if len(new_merges) == 0:
        return ""
    if len(new_merges) == 1:
        summary = new_merges[0].summary
    else:
        summary = "Merge"

    log_credits = []
    for merge in new_merges:
        if arch.my_id() != merge.creator:
            credit = re.sub("<.*>", "", merge.creator).rstrip(" ");
        else:
            credit = version_difference(merge.revision.version, 
                                        tree_version)
        if not credit in log_credits:
            log_credits.append(credit)
    return ("%s (%s)") % (summary, ", ".join(log_credits))
    
# arch-tag: 56d164d9-53ad-40f4-af41-985f505ea8d8