/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/info.py

  • Committer: Martin
  • Date: 2017-06-10 01:57:00 UTC
  • mto: This revision was merged to the branch mainline in revision 6679.
  • Revision ID: gzlist@googlemail.com-20170610015700-o3xeuyaqry2obiay
Go back to native str for urls and many other py3 changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2010 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
from __future__ import absolute_import
 
18
 
 
19
__all__ = ['show_bzrdir_info']
 
20
 
 
21
import time
 
22
import sys
 
23
 
 
24
from . import (
 
25
    bzrdir,
 
26
    controldir,
 
27
    errors,
 
28
    hooks as _mod_hooks,
 
29
    osutils,
 
30
    urlutils,
 
31
    )
 
32
from .errors import (NoWorkingTree, NotBranchError,
 
33
                           NoRepositoryPresent, NotLocalUrl)
 
34
from .missing import find_unmerged
 
35
from .sixish import (
 
36
    BytesIO,
 
37
    )
 
38
 
 
39
 
 
40
def plural(n, base='', pl=None):
 
41
    if n == 1:
 
42
        return base
 
43
    elif pl is not None:
 
44
        return pl
 
45
    else:
 
46
        return 's'
 
47
 
 
48
 
 
49
class LocationList(object):
 
50
 
 
51
    def __init__(self, base_path):
 
52
        self.locs = []
 
53
        self.base_path = base_path
 
54
 
 
55
    def add_url(self, label, url):
 
56
        """Add a URL to the list, converting it to a path if possible"""
 
57
        if url is None:
 
58
            return
 
59
        try:
 
60
            path = urlutils.local_path_from_url(url)
 
61
        except errors.InvalidURL:
 
62
            self.locs.append((label, url))
 
63
        else:
 
64
            self.add_path(label, path)
 
65
 
 
66
    def add_path(self, label, path):
 
67
        """Add a path, converting it to a relative path if possible"""
 
68
        try:
 
69
            path = osutils.relpath(self.base_path, path)
 
70
        except errors.PathNotChild:
 
71
            pass
 
72
        else:
 
73
            if path == '':
 
74
                path = '.'
 
75
        if path != '/':
 
76
            path = path.rstrip('/')
 
77
        self.locs.append((label, path))
 
78
 
 
79
    def get_lines(self):
 
80
        max_len = max(len(l) for l, u in self.locs)
 
81
        return ["  %*s: %s\n" % (max_len, l, u) for l, u in self.locs ]
 
82
 
 
83
 
 
84
def gather_location_info(repository=None, branch=None, working=None,
 
85
        control=None):
 
86
    locs = {}
 
87
    if branch is not None:
 
88
        branch_path = branch.user_url
 
89
        master_path = branch.get_bound_location()
 
90
        if master_path is None:
 
91
            master_path = branch_path
 
92
    else:
 
93
        branch_path = None
 
94
        master_path = None
 
95
        try:
 
96
            if control is not None and control.get_branch_reference():
 
97
                locs['checkout of branch'] = control.get_branch_reference()
 
98
        except NotBranchError:
 
99
            pass
 
100
    if working:
 
101
        working_path = working.user_url
 
102
        if working_path != branch_path:
 
103
            locs['light checkout root'] = working_path
 
104
        if master_path != branch_path:
 
105
            if repository.is_shared():
 
106
                locs['repository checkout root'] = branch_path
 
107
            else:
 
108
                locs['checkout root'] = branch_path
 
109
        if working_path != master_path:
 
110
            locs['checkout of branch'] = master_path
 
111
        elif repository.is_shared():
 
112
            locs['repository branch'] = branch_path
 
113
        elif branch_path is not None:
 
114
            # standalone
 
115
            locs['branch root'] = branch_path
 
116
    else:
 
117
        working_path = None
 
118
        if repository is not None and repository.is_shared():
 
119
            # lightweight checkout of branch in shared repository
 
120
            if branch_path is not None:
 
121
                locs['repository branch'] = branch_path
 
122
        elif branch_path is not None:
 
123
            # standalone
 
124
            locs['branch root'] = branch_path
 
125
        elif repository is not None:
 
126
            locs['repository'] = repository.user_url
 
127
        elif control is not None:
 
128
            locs['control directory'] = control.user_url
 
129
        else:
 
130
            # Really, at least a control directory should be
 
131
            # passed in for this method to be useful.
 
132
            pass
 
133
        if master_path != branch_path:
 
134
            locs['bound to branch'] = master_path
 
135
    if repository is not None and repository.is_shared():
 
136
        # lightweight checkout of branch in shared repository
 
137
        locs['shared repository'] = repository.user_url
 
138
    order = ['control directory', 'light checkout root',
 
139
             'repository checkout root', 'checkout root',
 
140
             'checkout of branch', 'shared repository',
 
141
             'repository', 'repository branch', 'branch root',
 
142
             'bound to branch']
 
143
    return [(n, locs[n]) for n in order if n in locs]
 
144
 
 
145
 
 
146
def _show_location_info(locs, outfile):
 
147
    """Show known locations for working, branch and repository."""
 
148
    outfile.write('Location:\n')
 
149
    path_list = LocationList(osutils.getcwd())
 
150
    for name, loc in locs:
 
151
        path_list.add_url(name, loc)
 
152
    outfile.writelines(path_list.get_lines())
 
153
 
 
154
 
 
155
def _gather_related_branches(branch):
 
156
    locs = LocationList(osutils.getcwd())
 
157
    locs.add_url('public branch', branch.get_public_branch())
 
158
    locs.add_url('push branch', branch.get_push_location())
 
159
    locs.add_url('parent branch', branch.get_parent())
 
160
    locs.add_url('submit branch', branch.get_submit_branch())
 
161
    try:
 
162
        locs.add_url('stacked on', branch.get_stacked_on_url())
 
163
    except (errors.UnstackableBranchFormat, errors.UnstackableRepositoryFormat,
 
164
        errors.NotStacked):
 
165
        pass
 
166
    return locs
 
167
 
 
168
 
 
169
def _show_related_info(branch, outfile):
 
170
    """Show parent and push location of branch."""
 
171
    locs = _gather_related_branches(branch)
 
172
    if len(locs.locs) > 0:
 
173
        outfile.write('\n')
 
174
        outfile.write('Related branches:\n')
 
175
        outfile.writelines(locs.get_lines())
 
176
 
 
177
 
 
178
def _show_control_dir_info(control, outfile):
 
179
    """Show control dir information."""
 
180
    if control._format.colocated_branches:
 
181
        outfile.write('\n')
 
182
        outfile.write('Control directory:\n')
 
183
        outfile.write('         %d branches\n' % len(control.list_branches()))
 
184
 
 
185
 
 
186
def _show_format_info(control=None, repository=None, branch=None,
 
187
                      working=None, outfile=None):
 
188
    """Show known formats for control, working, branch and repository."""
 
189
    outfile.write('\n')
 
190
    outfile.write('Format:\n')
 
191
    if control:
 
192
        outfile.write('       control: %s\n' %
 
193
            control._format.get_format_description())
 
194
    if working:
 
195
        outfile.write('  working tree: %s\n' %
 
196
            working._format.get_format_description())
 
197
    if branch:
 
198
        outfile.write('        branch: %s\n' %
 
199
            branch._format.get_format_description())
 
200
    if repository:
 
201
        outfile.write('    repository: %s\n' %
 
202
            repository._format.get_format_description())
 
203
 
 
204
 
 
205
def _show_locking_info(repository=None, branch=None, working=None,
 
206
        outfile=None):
 
207
    """Show locking status of working, branch and repository."""
 
208
    if (repository and repository.get_physical_lock_status() or
 
209
        (branch and branch.get_physical_lock_status()) or
 
210
        (working and working.get_physical_lock_status())):
 
211
        outfile.write('\n')
 
212
        outfile.write('Lock status:\n')
 
213
        if working:
 
214
            if working.get_physical_lock_status():
 
215
                status = 'locked'
 
216
            else:
 
217
                status = 'unlocked'
 
218
            outfile.write('  working tree: %s\n' % status)
 
219
        if branch:
 
220
            if branch.get_physical_lock_status():
 
221
                status = 'locked'
 
222
            else:
 
223
                status = 'unlocked'
 
224
            outfile.write('        branch: %s\n' % status)
 
225
        if repository:
 
226
            if repository.get_physical_lock_status():
 
227
                status = 'locked'
 
228
            else:
 
229
                status = 'unlocked'
 
230
            outfile.write('    repository: %s\n' % status)
 
231
 
 
232
 
 
233
def _show_missing_revisions_branch(branch, outfile):
 
234
    """Show missing master revisions in branch."""
 
235
    # Try with inaccessible branch ?
 
236
    master = branch.get_master_branch()
 
237
    if master:
 
238
        local_extra, remote_extra = find_unmerged(branch, master)
 
239
        if remote_extra:
 
240
            outfile.write('\n')
 
241
            outfile.write(('Branch is out of date: missing %d '
 
242
                'revision%s.\n') % (len(remote_extra),
 
243
                plural(len(remote_extra))))
 
244
 
 
245
 
 
246
def _show_missing_revisions_working(working, outfile):
 
247
    """Show missing revisions in working tree."""
 
248
    branch = working.branch
 
249
    basis = working.basis_tree()
 
250
    try:
 
251
        branch_revno, branch_last_revision = branch.last_revision_info()
 
252
    except errors.UnsupportedOperation:
 
253
        return
 
254
    try:
 
255
        tree_last_id = working.get_parent_ids()[0]
 
256
    except IndexError:
 
257
        tree_last_id = None
 
258
 
 
259
    if branch_revno and tree_last_id != branch_last_revision:
 
260
        tree_last_revno = branch.revision_id_to_revno(tree_last_id)
 
261
        missing_count = branch_revno - tree_last_revno
 
262
        outfile.write('\n')
 
263
        outfile.write(('Working tree is out of date: missing %d '
 
264
            'revision%s.\n') % (missing_count, plural(missing_count)))
 
265
 
 
266
 
 
267
def _show_working_stats(working, outfile):
 
268
    """Show statistics about a working tree."""
 
269
    basis = working.basis_tree()
 
270
    delta = working.changes_from(basis, want_unchanged=True)
 
271
 
 
272
    outfile.write('\n')
 
273
    outfile.write('In the working tree:\n')
 
274
    outfile.write('  %8s unchanged\n' % len(delta.unchanged))
 
275
    outfile.write('  %8d modified\n' % len(delta.modified))
 
276
    outfile.write('  %8d added\n' % len(delta.added))
 
277
    outfile.write('  %8d removed\n' % len(delta.removed))
 
278
    outfile.write('  %8d renamed\n' % len(delta.renamed))
 
279
 
 
280
    ignore_cnt = unknown_cnt = 0
 
281
    for path in working.extras():
 
282
        if working.is_ignored(path):
 
283
            ignore_cnt += 1
 
284
        else:
 
285
            unknown_cnt += 1
 
286
    outfile.write('  %8d unknown\n' % unknown_cnt)
 
287
    outfile.write('  %8d ignored\n' % ignore_cnt)
 
288
 
 
289
    dir_cnt = 0
 
290
    root_id = working.get_root_id()
 
291
    for path, entry in working.iter_entries_by_dir():
 
292
        if entry.kind == 'directory' and entry.file_id != root_id:
 
293
            dir_cnt += 1
 
294
    outfile.write('  %8d versioned %s\n' % (dir_cnt,
 
295
        plural(dir_cnt, 'subdirectory', 'subdirectories')))
 
296
 
 
297
 
 
298
def _show_branch_stats(branch, verbose, outfile):
 
299
    """Show statistics about a branch."""
 
300
    try:
 
301
        revno, head = branch.last_revision_info()
 
302
    except errors.UnsupportedOperation:
 
303
        return {}
 
304
    outfile.write('\n')
 
305
    outfile.write('Branch history:\n')
 
306
    outfile.write('  %8d revision%s\n' % (revno, plural(revno)))
 
307
    stats = branch.repository.gather_stats(head, committers=verbose)
 
308
    if verbose:
 
309
        committers = stats['committers']
 
310
        outfile.write('  %8d committer%s\n' % (committers,
 
311
            plural(committers)))
 
312
    if revno:
 
313
        timestamp, timezone = stats['firstrev']
 
314
        age = int((time.time() - timestamp) / 3600 / 24)
 
315
        outfile.write('  %8d day%s old\n' % (age, plural(age)))
 
316
        outfile.write('   first revision: %s\n' %
 
317
            osutils.format_date(timestamp, timezone))
 
318
        timestamp, timezone = stats['latestrev']
 
319
        outfile.write('  latest revision: %s\n' %
 
320
            osutils.format_date(timestamp, timezone))
 
321
    return stats
 
322
 
 
323
 
 
324
def _show_repository_info(repository, outfile):
 
325
    """Show settings of a repository."""
 
326
    if repository.make_working_trees():
 
327
        outfile.write('\n')
 
328
        outfile.write('Create working tree for new branches inside '
 
329
            'the repository.\n')
 
330
 
 
331
 
 
332
def _show_repository_stats(repository, stats, outfile):
 
333
    """Show statistics about a repository."""
 
334
    f = BytesIO()
 
335
    if 'revisions' in stats:
 
336
        revisions = stats['revisions']
 
337
        f.write('  %8d revision%s\n' % (revisions, plural(revisions)))
 
338
    if 'size' in stats:
 
339
        f.write('  %8d KiB\n' % (stats['size']/1024))
 
340
    for hook in hooks['repository']:
 
341
        hook(repository, stats, f)
 
342
    if f.getvalue() != "":
 
343
        outfile.write('\n')
 
344
        outfile.write('Repository:\n')
 
345
        outfile.write(f.getvalue())
 
346
 
 
347
 
 
348
def show_bzrdir_info(a_bzrdir, verbose=False, outfile=None):
 
349
    """Output to stdout the 'info' for a_bzrdir."""
 
350
    if outfile is None:
 
351
        outfile = sys.stdout
 
352
    try:
 
353
        tree = a_bzrdir.open_workingtree(
 
354
            recommend_upgrade=False)
 
355
    except (NoWorkingTree, NotLocalUrl, NotBranchError):
 
356
        tree = None
 
357
        try:
 
358
            branch = a_bzrdir.open_branch(name="")
 
359
        except NotBranchError:
 
360
            branch = None
 
361
            try:
 
362
                repository = a_bzrdir.open_repository()
 
363
            except NoRepositoryPresent:
 
364
                lockable = None
 
365
                repository = None
 
366
            else:
 
367
                lockable = repository
 
368
        else:
 
369
            repository = branch.repository
 
370
            lockable = branch
 
371
    else:
 
372
        branch = tree.branch
 
373
        repository = branch.repository
 
374
        lockable = tree
 
375
 
 
376
    if lockable is not None:
 
377
        lockable.lock_read()
 
378
    try:
 
379
        show_component_info(a_bzrdir, repository, branch, tree, verbose,
 
380
                            outfile)
 
381
    finally:
 
382
        if lockable is not None:
 
383
            lockable.unlock()
 
384
 
 
385
 
 
386
def show_component_info(control, repository, branch=None, working=None,
 
387
    verbose=1, outfile=None):
 
388
    """Write info about all bzrdir components to stdout"""
 
389
    if outfile is None:
 
390
        outfile = sys.stdout
 
391
    if verbose is False:
 
392
        verbose = 1
 
393
    if verbose is True:
 
394
        verbose = 2
 
395
    layout = describe_layout(repository, branch, working, control)
 
396
    format = describe_format(control, repository, branch, working)
 
397
    outfile.write("%s (format: %s)\n" % (layout, format))
 
398
    _show_location_info(
 
399
        gather_location_info(control=control, repository=repository,
 
400
            branch=branch, working=working),
 
401
        outfile)
 
402
    if branch is not None:
 
403
        _show_related_info(branch, outfile)
 
404
    if verbose == 0:
 
405
        return
 
406
    _show_format_info(control, repository, branch, working, outfile)
 
407
    _show_locking_info(repository, branch, working, outfile)
 
408
    _show_control_dir_info(control, outfile)
 
409
    if branch is not None:
 
410
        _show_missing_revisions_branch(branch, outfile)
 
411
    if working is not None:
 
412
        _show_missing_revisions_working(working, outfile)
 
413
        _show_working_stats(working, outfile)
 
414
    elif branch is not None:
 
415
        _show_missing_revisions_branch(branch, outfile)
 
416
    if branch is not None:
 
417
        show_committers = verbose >= 2
 
418
        stats = _show_branch_stats(branch, show_committers, outfile)
 
419
    elif repository is not None:
 
420
        stats = repository.gather_stats()
 
421
    if branch is None and working is None and repository is not None:
 
422
        _show_repository_info(repository, outfile)
 
423
    if repository is not None:
 
424
        _show_repository_stats(repository, stats, outfile)
 
425
 
 
426
 
 
427
def describe_layout(repository=None, branch=None, tree=None, control=None):
 
428
    """Convert a control directory layout into a user-understandable term
 
429
 
 
430
    Common outputs include "Standalone tree", "Repository branch" and
 
431
    "Checkout".  Uncommon outputs include "Unshared repository with trees"
 
432
    and "Empty control directory"
 
433
    """
 
434
    if branch is None and control is not None:
 
435
        try:
 
436
            branch_reference = control.get_branch_reference()
 
437
        except NotBranchError:
 
438
            pass
 
439
        else:
 
440
            if branch_reference is not None:
 
441
                return "Dangling branch reference"
 
442
    if repository is None:
 
443
        return 'Empty control directory'
 
444
    if branch is None and tree is None:
 
445
        if repository.is_shared():
 
446
            phrase = 'Shared repository'
 
447
        else:
 
448
            phrase = 'Unshared repository'
 
449
        extra = []
 
450
        if repository.make_working_trees():
 
451
            extra.append('trees')
 
452
        if len(control.get_branches()) > 0:
 
453
            extra.append('colocated branches')
 
454
        if extra:
 
455
            phrase += ' with ' + " and ".join(extra)
 
456
        return phrase
 
457
    else:
 
458
        if repository.is_shared():
 
459
            independence = "Repository "
 
460
        else:
 
461
            independence = "Standalone "
 
462
        if tree is not None:
 
463
            phrase = "tree"
 
464
        else:
 
465
            phrase = "branch"
 
466
        if branch is None and tree is not None:
 
467
            phrase = "branchless tree"
 
468
        else:
 
469
            if (tree is not None and tree.user_url !=
 
470
                branch.user_url):
 
471
                independence = ''
 
472
                phrase = "Lightweight checkout"
 
473
            elif branch.get_bound_location() is not None:
 
474
                if independence == 'Standalone ':
 
475
                    independence = ''
 
476
                if tree is None:
 
477
                    phrase = "Bound branch"
 
478
                else:
 
479
                    phrase = "Checkout"
 
480
        if independence != "":
 
481
            phrase = phrase.lower()
 
482
        return "%s%s" % (independence, phrase)
 
483
 
 
484
 
 
485
def describe_format(control, repository, branch, tree):
 
486
    """Determine the format of an existing control directory
 
487
 
 
488
    Several candidates may be found.  If so, the names are returned as a
 
489
    single string, separated by ' or '.
 
490
 
 
491
    If no matching candidate is found, "unnamed" is returned.
 
492
    """
 
493
    candidates  = []
 
494
    if (branch is not None and tree is not None and
 
495
        branch.user_url != tree.user_url):
 
496
        branch = None
 
497
        repository = None
 
498
    non_aliases = set(controldir.format_registry.keys())
 
499
    non_aliases.difference_update(controldir.format_registry.aliases())
 
500
    for key in non_aliases:
 
501
        format = controldir.format_registry.make_bzrdir(key)
 
502
        if isinstance(format, bzrdir.BzrDirMetaFormat1):
 
503
            if (tree and format.workingtree_format !=
 
504
                tree._format):
 
505
                continue
 
506
            if (branch and format.get_branch_format() !=
 
507
                branch._format):
 
508
                continue
 
509
            if (repository and format.repository_format !=
 
510
                repository._format):
 
511
                continue
 
512
        if format.__class__ is not control._format.__class__:
 
513
            continue
 
514
        candidates.append(key)
 
515
    if len(candidates) == 0:
 
516
        return 'unnamed'
 
517
    candidates.sort()
 
518
    new_candidates = [c for c in candidates if not
 
519
        controldir.format_registry.get_info(c).hidden]
 
520
    if len(new_candidates) > 0:
 
521
        # If there are any non-hidden formats that match, only return those to
 
522
        # avoid listing hidden formats except when only a hidden format will
 
523
        # do.
 
524
        candidates = new_candidates
 
525
    return ' or '.join(candidates)
 
526
 
 
527
 
 
528
class InfoHooks(_mod_hooks.Hooks):
 
529
    """Hooks for the info command."""
 
530
 
 
531
    def __init__(self):
 
532
        super(InfoHooks, self).__init__("breezy.info", "hooks")
 
533
        self.add_hook('repository',
 
534
            "Invoked when displaying the statistics for a repository. "
 
535
            "repository is called with a statistics dictionary as returned "
 
536
            "by the repository and a file-like object to write to.", (1, 15))
 
537
 
 
538
 
 
539
hooks = InfoHooks()