tags.py
676 lines
| 22.9 KiB
| text/x-python
|
PythonLexer
/ mercurial / tags.py
|
r9149 | # tags.py - read tag info from local repository | ||
# | ||||
# Copyright 2009 Matt Mackall <mpm@selenic.com> | ||||
# Copyright 2009 Greg Ward <greg@gerg.ca> | ||||
# | ||||
# This software may be used and distributed according to the terms of the | ||||
|
r10263 | # GNU General Public License version 2 or any later version. | ||
|
r9149 | |||
|
r9151 | # Currently this module only deals with reading and caching tags. | ||
# Eventually, it could take care of updating (adding/removing/moving) | ||||
# tags too. | ||||
|
r9149 | |||
|
r25982 | from __future__ import absolute_import | ||
|
r14038 | import errno | ||
|
r9149 | |||
|
r25982 | from .node import ( | ||
bin, | ||||
hex, | ||||
nullid, | ||||
short, | ||||
) | ||||
|
r31668 | from .i18n import _ | ||
|
r25982 | from . import ( | ||
encoding, | ||||
error, | ||||
|
r31668 | match as matchmod, | ||
|
r31025 | scmutil, | ||
|
r25982 | util, | ||
) | ||||
|
r24735 | # Tags computation can be expensive and caches exist to make it fast in | ||
# the common case. | ||||
# | ||||
# The "hgtagsfnodes1" cache file caches the .hgtags filenode values for | ||||
# each revision in the repository. The file is effectively an array of | ||||
# fixed length records. Read the docs for "hgtagsfnodescache" for technical | ||||
# details. | ||||
# | ||||
# The .hgtags filenode cache grows in proportion to the length of the | ||||
# changelog. The file is truncated when the # changelog is stripped. | ||||
# | ||||
# The purpose of the filenode cache is to avoid the most expensive part | ||||
# of finding global tags, which is looking up the .hgtags filenode in the | ||||
# manifest for each head. This can take dozens or over 100ms for | ||||
# repositories with very large manifests. Multiplied by dozens or even | ||||
# hundreds of heads and there is a significant performance concern. | ||||
# | ||||
|
r24762 | # There also exist a separate cache file for each repository filter. | ||
# These "tags-*" files store information about the history of tags. | ||||
|
r24445 | # | ||
|
r24762 | # The tags cache files consists of a cache validation line followed by | ||
# a history of tags. | ||||
|
r24735 | # | ||
|
r24760 | # The cache validation line has the format: | ||
|
r24445 | # | ||
|
r24760 | # <tiprev> <tipnode> [<filteredhash>] | ||
|
r24445 | # | ||
|
r24760 | # <tiprev> is an integer revision and <tipnode> is a 40 character hex | ||
# node for that changeset. These redundantly identify the repository | ||||
# tip from the time the cache was written. In addition, <filteredhash>, | ||||
# if present, is a 40 character hex hash of the contents of the filtered | ||||
# revisions for this filter. If the set of filtered revs changes, the | ||||
# hash will change and invalidate the cache. | ||||
|
r24445 | # | ||
|
r24760 | # The history part of the tags cache consists of lines of the form: | ||
|
r24445 | # | ||
# <node> <tag> | ||||
# | ||||
# (This format is identical to that of .hgtags files.) | ||||
# | ||||
# <tag> is the tag name and <node> is the 40 character hex changeset | ||||
# the tag is associated with. | ||||
# | ||||
# Tags are written sorted by tag name. | ||||
# | ||||
# Tags associated with multiple changesets have an entry for each changeset. | ||||
# The most recent changeset (in terms of revlog ordering for the head | ||||
# setting it) for each tag is last. | ||||
|
r31706 | def findglobaltags(ui, repo): | ||
'''Find global tags in a repo: return (alltags, tagtypes) | ||||
|
r24445 | |||
"alltags" maps tag name to (node, hist) 2-tuples. | ||||
"tagtypes" maps tag name to tag type. Global tags always have the | ||||
"global" tag type. | ||||
The tags cache is read and updated as a side-effect of calling. | ||||
''' | ||||
|
r31706 | alltags = {} | ||
tagtypes = {} | ||||
|
r9152 | |||
|
r24760 | (heads, tagfnode, valid, cachetags, shouldwrite) = _readtagcache(ui, repo) | ||
|
r9152 | if cachetags is not None: | ||
assert not shouldwrite | ||||
# XXX is this really 100% correct? are there oddball special | ||||
# cases where a global tag should outrank a local tag but won't, | ||||
# because cachetags does not contain rank info? | ||||
_updatetags(cachetags, 'global', alltags, tagtypes) | ||||
|
r31706 | return alltags, tagtypes | ||
|
r9151 | |||
|
r24445 | seen = set() # set of fnode | ||
|
r9151 | fctx = None | ||
|
r24445 | for head in reversed(heads): # oldest to newest | ||
|
r9151 | assert head in repo.changelog.nodemap, \ | ||
"tag cache returned bogus head %s" % short(head) | ||||
fnode = tagfnode.get(head) | ||||
if fnode and fnode not in seen: | ||||
seen.add(fnode) | ||||
if not fctx: | ||||
fctx = repo.filectx('.hgtags', fileid=fnode) | ||||
else: | ||||
fctx = fctx.filectx(fnode) | ||||
filetags = _readtags(ui, repo, fctx.data().splitlines(), fctx) | ||||
_updatetags(filetags, 'global', alltags, tagtypes) | ||||
# and update the cache (if necessary) | ||||
if shouldwrite: | ||||
|
r24760 | _writetagcache(ui, repo, valid, alltags) | ||
|
r31706 | return alltags, tagtypes | ||
|
r9151 | |||
|
r9149 | def readlocaltags(ui, repo, alltags, tagtypes): | ||
|
r24445 | '''Read local tags in repo. Update alltags and tagtypes.''' | ||
|
r9149 | try: | ||
|
r23877 | data = repo.vfs.read("localtags") | ||
|
r25660 | except IOError as inst: | ||
|
r14038 | if inst.errno != errno.ENOENT: | ||
raise | ||||
return | ||||
# localtags is in the local encoding; re-encode to UTF-8 on | ||||
# input for consistency with the rest of this module. | ||||
filetags = _readtags( | ||||
ui, repo, data.splitlines(), "localtags", | ||||
recode=encoding.fromlocal) | ||||
|
r21823 | |||
# remove tags pointing to invalid nodes | ||||
cl = repo.changelog | ||||
for t in filetags.keys(): | ||||
try: | ||||
cl.rev(filetags[t][0]) | ||||
except (LookupError, ValueError): | ||||
del filetags[t] | ||||
|
r14038 | _updatetags(filetags, "local", alltags, tagtypes) | ||
|
r9149 | |||
|
r21892 | def _readtaghist(ui, repo, lines, fn, recode=None, calcnodelines=False): | ||
|
r9149 | '''Read tag definitions from a file (or any source of lines). | ||
|
r24445 | |||
|
r21892 | This function returns two sortdicts with similar information: | ||
|
r24445 | |||
|
r23139 | - the first dict, bintaghist, contains the tag information as expected by | ||
|
r21892 | the _readtags function, i.e. a mapping from tag name to (node, hist): | ||
- node is the node id from the last line read for that name, | ||||
- hist is the list of node ids previously associated with it (in file | ||||
|
r24445 | order). All node ids are binary, not hex. | ||
|
r21892 | - the second dict, hextaglines, is a mapping from tag name to a list of | ||
[hexnode, line number] pairs, ordered from the oldest to the newest node. | ||||
|
r24445 | |||
|
r21892 | When calcnodelines is False the hextaglines dict is not calculated (an | ||
empty dict is returned). This is done to improve this function's | ||||
performance in cases where the line numbers are not needed. | ||||
''' | ||||
|
r9149 | |||
|
r21892 | bintaghist = util.sortdict() | ||
hextaglines = util.sortdict() | ||||
|
r9149 | count = 0 | ||
|
r29038 | def dbg(msg): | ||
ui.debug("%s, line %s: %s\n" % (fn, count, msg)) | ||||
|
r9149 | |||
|
r21892 | for nline, line in enumerate(lines): | ||
|
r9149 | count += 1 | ||
if not line: | ||||
continue | ||||
try: | ||||
(nodehex, name) = line.split(" ", 1) | ||||
except ValueError: | ||||
|
r29038 | dbg("cannot parse entry") | ||
|
r9149 | continue | ||
|
r9152 | name = name.strip() | ||
if recode: | ||||
name = recode(name) | ||||
|
r9149 | try: | ||
nodebin = bin(nodehex) | ||||
except TypeError: | ||||
|
r29038 | dbg("node '%s' is not well formed" % nodehex) | ||
|
r9149 | continue | ||
# update filetags | ||||
|
r21892 | if calcnodelines: | ||
# map tag name to a list of line numbers | ||||
if name not in hextaglines: | ||||
hextaglines[name] = [] | ||||
hextaglines[name].append([nodehex, nline]) | ||||
continue | ||||
# map tag name to (node, hist) | ||||
if name not in bintaghist: | ||||
bintaghist[name] = [] | ||||
bintaghist[name].append(nodebin) | ||||
return bintaghist, hextaglines | ||||
def _readtags(ui, repo, lines, fn, recode=None, calcnodelines=False): | ||||
'''Read tag definitions from a file (or any source of lines). | ||||
|
r24445 | |||
Returns a mapping from tag name to (node, hist). | ||||
"node" is the node id from the last line read for that name. "hist" | ||||
is the list of node ids previously associated with it (in file order). | ||||
All node ids are binary, not hex. | ||||
''' | ||||
|
r21892 | filetags, nodelines = _readtaghist(ui, repo, lines, fn, recode=recode, | ||
calcnodelines=calcnodelines) | ||||
|
r26945 | # util.sortdict().__setitem__ is much slower at replacing then inserting | ||
# new entries. The difference can matter if there are thousands of tags. | ||||
# Create a new sortdict to avoid the performance penalty. | ||||
newtags = util.sortdict() | ||||
|
r21892 | for tag, taghist in filetags.items(): | ||
|
r26945 | newtags[tag] = (taghist[-1], taghist[:-1]) | ||
return newtags | ||||
|
r9149 | |||
def _updatetags(filetags, tagtype, alltags, tagtypes): | ||||
'''Incorporate the tag info read from one file into the two | ||||
dictionaries, alltags and tagtypes, that contain all tag | ||||
info (global across all heads plus local).''' | ||||
for name, nodehist in filetags.iteritems(): | ||||
if name not in alltags: | ||||
alltags[name] = nodehist | ||||
tagtypes[name] = tagtype | ||||
continue | ||||
# we prefer alltags[name] if: | ||||
|
r17424 | # it supersedes us OR | ||
# mutual supersedes and it has a higher rank | ||||
|
r9149 | # otherwise we win because we're tip-most | ||
anode, ahist = nodehist | ||||
bnode, bhist = alltags[name] | ||||
if (bnode != anode and anode in bhist and | ||||
(bnode not in ahist or len(bhist) > len(ahist))): | ||||
anode = bnode | ||||
|
r19108 | else: | ||
tagtypes[name] = tagtype | ||||
|
r9149 | ahist.extend([n for n in bhist if n not in ahist]) | ||
alltags[name] = anode, ahist | ||||
|
r24737 | def _filename(repo): | ||
"""name of a tagcache file for a given repo or repoview""" | ||||
|
r24762 | filename = 'cache/tags2' | ||
|
r24737 | if repo.filtername: | ||
filename = '%s-%s' % (filename, repo.filtername) | ||||
return filename | ||||
|
r24445 | def _readtagcache(ui, repo): | ||
'''Read the tag cache. | ||||
|
r9151 | |||
|
r24760 | Returns a tuple (heads, fnodes, validinfo, cachetags, shouldwrite). | ||
|
r24445 | |||
If the cache is completely up-to-date, "cachetags" is a dict of the | ||||
|
r24760 | form returned by _readtags() and "heads", "fnodes", and "validinfo" are | ||
None and "shouldwrite" is False. | ||||
|
r9151 | |||
|
r24445 | If the cache is not up to date, "cachetags" is None. "heads" is a list | ||
of all heads currently in the repository, ordered from tip to oldest. | ||||
|
r24760 | "validinfo" is a tuple describing cache validation info. This is used | ||
when writing the tags cache. "fnodes" is a mapping from head to .hgtags | ||||
filenode. "shouldwrite" is True. | ||||
|
r24445 | |||
If the cache is not up to date, the caller is responsible for reading tag | ||||
info from each returned head. (See findglobaltags().) | ||||
''' | ||||
|
r9151 | try: | ||
|
r24737 | cachefile = repo.vfs(_filename(repo), 'r') | ||
|
r11066 | # force reading the file for static-http | ||
cachelines = iter(cachefile) | ||||
|
r9151 | except IOError: | ||
cachefile = None | ||||
|
r24760 | cacherev = None | ||
cachenode = None | ||||
cachehash = None | ||||
|
r9151 | if cachefile: | ||
|
r12758 | try: | ||
|
r29216 | validline = next(cachelines) | ||
|
r24760 | validline = validline.split() | ||
cacherev = int(validline[0]) | ||||
cachenode = bin(validline[1]) | ||||
if len(validline) > 2: | ||||
cachehash = bin(validline[2]) | ||||
|
r14020 | except Exception: | ||
|
r24759 | # corruption of the cache, just recompute it. | ||
pass | ||||
|
r9151 | |||
tipnode = repo.changelog.tip() | ||||
tiprev = len(repo.changelog) - 1 | ||||
# Case 1 (common): tip is the same, so nothing has changed. | ||||
# (Unchanged tip trivially means no changesets have been added. | ||||
# But, thanks to localrepository.destroyed(), it also means none | ||||
# have been destroyed by strip or rollback.) | ||||
|
r24760 | if (cacherev == tiprev | ||
and cachenode == tipnode | ||||
and cachehash == scmutil.filteredhash(repo, tiprev)): | ||||
|
r11066 | tags = _readtags(ui, repo, cachelines, cachefile.name) | ||
|
r9152 | cachefile.close() | ||
|
r24760 | return (None, None, None, tags, False) | ||
|
r9152 | if cachefile: | ||
cachefile.close() # ignore rest of file | ||||
|
r9312 | |||
|
r24760 | valid = (tiprev, tipnode, scmutil.filteredhash(repo, tiprev)) | ||
|
r9151 | repoheads = repo.heads() | ||
# Case 2 (uncommon): empty repo; get out quickly and don't bother | ||||
# writing an empty cache. | ||||
if repoheads == [nullid]: | ||||
|
r24760 | return ([], {}, valid, {}, False) | ||
|
r9151 | |||
# Case 3 (uncommon): cache file missing or empty. | ||||
# Case 4 (uncommon): tip rev decreased. This should only happen | ||||
# when we're called from localrepository.destroyed(). Refresh the | ||||
# cache so future invocations will not see disappeared heads in the | ||||
# cache. | ||||
# Case 5 (common): tip has changed, so we've added/replaced heads. | ||||
|
r11352 | # As it happens, the code to handle cases 3, 4, 5 is the same. | ||
|
r9151 | |||
# N.B. in case 4 (nodes destroyed), "new head" really means "newly | ||||
# exposed". | ||||
|
r16730 | if not len(repo.file('.hgtags')): | ||
# No tags have ever been committed, so we can avoid a | ||||
# potentially expensive search. | ||||
|
r24761 | return ([], {}, valid, None, True) | ||
|
r16730 | |||
|
r21030 | |||
|
r9151 | # Now we have to lookup the .hgtags filenode for every new head. | ||
# This is the most expensive part of finding tags, so performance | ||||
# depends primarily on the size of newheads. Worst case: no cache | ||||
# file, so newheads == repoheads. | ||||
|
r31705 | cachefnode = _getfnodes(ui, repo, repoheads) | ||
# Caller has to iterate over all heads, but can use the filenodes in | ||||
# cachefnode to get to each .hgtags revision quickly. | ||||
return (repoheads, cachefnode, valid, None, True) | ||||
def _getfnodes(ui, repo, nodes): | ||||
"""return .hgtags fnodes for a list of changeset nodes | ||||
Return value is a {node: fnode} mapping. There will be no entry for nodes | ||||
without a '.hgtags' file. | ||||
""" | ||||
starttime = util.timer() | ||||
|
r24735 | fnodescache = hgtagsfnodescache(repo.unfiltered()) | ||
|
r24759 | cachefnode = {} | ||
|
r31705 | for head in reversed(nodes): | ||
|
r24735 | fnode = fnodescache.getfnode(head) | ||
if fnode != nullid: | ||||
|
r9151 | cachefnode[head] = fnode | ||
|
r24735 | |||
fnodescache.write() | ||||
|
r9151 | |||
|
r30975 | duration = util.timer() - starttime | ||
|
r21030 | ui.log('tagscache', | ||
|
r24735 | '%d/%d cache hits/lookups in %0.4f ' | ||
|
r21030 | 'seconds\n', | ||
|
r24735 | fnodescache.hitcount, fnodescache.lookupcount, duration) | ||
|
r31705 | return cachefnode | ||
|
r9151 | |||
|
r24760 | def _writetagcache(ui, repo, valid, cachetags): | ||
|
r24763 | filename = _filename(repo) | ||
|
r9366 | try: | ||
|
r24763 | cachefile = repo.vfs(filename, 'w', atomictemp=True) | ||
|
r9366 | except (OSError, IOError): | ||
return | ||||
|
r9151 | |||
|
r24763 | ui.log('tagscache', 'writing .hg/%s with %d tags\n', | ||
filename, len(cachetags)) | ||||
|
r21030 | |||
|
r24760 | if valid[2]: | ||
cachefile.write('%d %s %s\n' % (valid[0], hex(valid[1]), hex(valid[2]))) | ||||
else: | ||||
cachefile.write('%d %s\n' % (valid[0], hex(valid[1]))) | ||||
|
r9151 | |||
|
r9152 | # Tag names in the cache are in UTF-8 -- which is the whole reason | ||
# we keep them in UTF-8 throughout this module. If we converted | ||||
# them local encoding on input, we would lose info writing them to | ||||
# the cache. | ||||
|
r24143 | for (name, (node, hist)) in sorted(cachetags.iteritems()): | ||
|
r19646 | for n in hist: | ||
cachefile.write("%s %s\n" % (hex(n), name)) | ||||
|
r9152 | cachefile.write("%s %s\n" % (hex(node), name)) | ||
|
r14662 | try: | ||
|
r15057 | cachefile.close() | ||
|
r14662 | except (OSError, IOError): | ||
pass | ||||
|
r24735 | |||
|
r31669 | def tag(repo, names, node, message, local, user, date, editor=False): | ||
'''tag a revision with one or more symbolic names. | ||||
names is a list of strings or, when adding a single tag, names may be a | ||||
string. | ||||
if local is True, the tags are stored in a per-repository file. | ||||
otherwise, they are stored in the .hgtags file, and a new | ||||
changeset is committed with the change. | ||||
keyword arguments: | ||||
local: whether to store tags in non-version-controlled file | ||||
(default False) | ||||
message: commit message to use if committing | ||||
user: name of user to use if committing | ||||
date: date tuple to use if committing''' | ||||
if not local: | ||||
m = matchmod.exact(repo.root, '', ['.hgtags']) | ||||
if any(repo.status(match=m, unknown=True, ignored=True)): | ||||
raise error.Abort(_('working copy of .hgtags is changed'), | ||||
hint=_('please commit .hgtags manually')) | ||||
repo.tags() # instantiate the cache | ||||
_tag(repo.unfiltered(), names, node, message, local, user, date, | ||||
editor=editor) | ||||
|
r31668 | def _tag(repo, names, node, message, local, user, date, extra=None, | ||
editor=False): | ||||
if isinstance(names, str): | ||||
names = (names,) | ||||
branches = repo.branchmap() | ||||
for name in names: | ||||
repo.hook('pretag', throw=True, node=hex(node), tag=name, | ||||
local=local) | ||||
if name in branches: | ||||
repo.ui.warn(_("warning: tag %s conflicts with existing" | ||||
" branch name\n") % name) | ||||
def writetags(fp, names, munge, prevtags): | ||||
fp.seek(0, 2) | ||||
if prevtags and prevtags[-1] != '\n': | ||||
fp.write('\n') | ||||
for name in names: | ||||
if munge: | ||||
m = munge(name) | ||||
else: | ||||
m = name | ||||
if (repo._tagscache.tagtypes and | ||||
name in repo._tagscache.tagtypes): | ||||
old = repo.tags().get(name, nullid) | ||||
fp.write('%s %s\n' % (hex(old), m)) | ||||
fp.write('%s %s\n' % (hex(node), m)) | ||||
fp.close() | ||||
prevtags = '' | ||||
if local: | ||||
try: | ||||
fp = repo.vfs('localtags', 'r+') | ||||
except IOError: | ||||
fp = repo.vfs('localtags', 'a') | ||||
else: | ||||
prevtags = fp.read() | ||||
# local tags are stored in the current charset | ||||
writetags(fp, names, None, prevtags) | ||||
for name in names: | ||||
repo.hook('tag', node=hex(node), tag=name, local=local) | ||||
return | ||||
try: | ||||
fp = repo.wvfs('.hgtags', 'rb+') | ||||
except IOError as e: | ||||
if e.errno != errno.ENOENT: | ||||
raise | ||||
fp = repo.wvfs('.hgtags', 'ab') | ||||
else: | ||||
prevtags = fp.read() | ||||
# committed tags are stored in UTF-8 | ||||
writetags(fp, names, encoding.fromlocal, prevtags) | ||||
fp.close() | ||||
repo.invalidatecaches() | ||||
if '.hgtags' not in repo.dirstate: | ||||
repo[None].add(['.hgtags']) | ||||
m = matchmod.exact(repo.root, '', ['.hgtags']) | ||||
tagnode = repo.commit(message, user, date, extra=extra, match=m, | ||||
editor=editor) | ||||
for name in names: | ||||
repo.hook('tag', node=hex(node), tag=name, local=local) | ||||
return tagnode | ||||
|
r24735 | _fnodescachefile = 'cache/hgtagsfnodes1' | ||
_fnodesrecsize = 4 + 20 # changeset fragment + filenode | ||||
_fnodesmissingrec = '\xff' * 24 | ||||
class hgtagsfnodescache(object): | ||||
"""Persistent cache mapping revisions to .hgtags filenodes. | ||||
The cache is an array of records. Each item in the array corresponds to | ||||
a changelog revision. Values in the array contain the first 4 bytes of | ||||
the node hash and the 20 bytes .hgtags filenode for that revision. | ||||
The first 4 bytes are present as a form of verification. Repository | ||||
stripping and rewriting may change the node at a numeric revision in the | ||||
changelog. The changeset fragment serves as a verifier to detect | ||||
rewriting. This logic is shared with the rev branch cache (see | ||||
branchmap.py). | ||||
The instance holds in memory the full cache content but entries are | ||||
only parsed on read. | ||||
Instances behave like lists. ``c[i]`` works where i is a rev or | ||||
changeset node. Missing indexes are populated automatically on access. | ||||
""" | ||||
def __init__(self, repo): | ||||
assert repo.filtername is None | ||||
self._repo = repo | ||||
# Only for reporting purposes. | ||||
self.lookupcount = 0 | ||||
self.hitcount = 0 | ||||
|
r29039 | try: | ||
data = repo.vfs.read(_fnodescachefile) | ||||
except (OSError, IOError): | ||||
data = "" | ||||
|
r31346 | self._raw = bytearray(data) | ||
|
r24735 | |||
# The end state of self._raw is an array that is of the exact length | ||||
# required to hold a record for every revision in the repository. | ||||
# We truncate or extend the array as necessary. self._dirtyoffset is | ||||
# defined to be the start offset at which we need to write the output | ||||
# file. This offset is also adjusted when new entries are calculated | ||||
# for array members. | ||||
cllen = len(repo.changelog) | ||||
wantedlen = cllen * _fnodesrecsize | ||||
rawlen = len(self._raw) | ||||
self._dirtyoffset = None | ||||
if rawlen < wantedlen: | ||||
self._dirtyoffset = rawlen | ||||
self._raw.extend('\xff' * (wantedlen - rawlen)) | ||||
elif rawlen > wantedlen: | ||||
# There's no easy way to truncate array instances. This seems | ||||
# slightly less evil than copying a potentially large array slice. | ||||
for i in range(rawlen - wantedlen): | ||||
self._raw.pop() | ||||
self._dirtyoffset = len(self._raw) | ||||
|
r25380 | def getfnode(self, node, computemissing=True): | ||
|
r24735 | """Obtain the filenode of the .hgtags file at a specified revision. | ||
If the value is in the cache, the entry will be validated and returned. | ||||
|
r25380 | Otherwise, the filenode will be computed and returned unless | ||
"computemissing" is False, in which case None will be returned without | ||||
any potentially expensive computation being performed. | ||||
|
r24735 | |||
If an .hgtags does not exist at the specified revision, nullid is | ||||
returned. | ||||
""" | ||||
ctx = self._repo[node] | ||||
rev = ctx.rev() | ||||
self.lookupcount += 1 | ||||
offset = rev * _fnodesrecsize | ||||
|
r31346 | record = '%s' % self._raw[offset:offset + _fnodesrecsize] | ||
|
r24735 | properprefix = node[0:4] | ||
# Validate and return existing entry. | ||||
if record != _fnodesmissingrec: | ||||
fileprefix = record[0:4] | ||||
if fileprefix == properprefix: | ||||
self.hitcount += 1 | ||||
return record[4:] | ||||
# Fall through. | ||||
|
r25380 | # If we get here, the entry is either missing or invalid. | ||
if not computemissing: | ||||
return None | ||||
# Populate missing entry. | ||||
|
r24735 | try: | ||
fnode = ctx.filenode('.hgtags') | ||||
except error.LookupError: | ||||
# No .hgtags file on this revision. | ||||
fnode = nullid | ||||
|
r25381 | self._writeentry(offset, properprefix, fnode) | ||
return fnode | ||||
def setfnode(self, node, fnode): | ||||
"""Set the .hgtags filenode for a given changeset.""" | ||||
assert len(fnode) == 20 | ||||
ctx = self._repo[node] | ||||
# Do a lookup first to avoid writing if nothing has changed. | ||||
if self.getfnode(ctx.node(), computemissing=False) == fnode: | ||||
return | ||||
self._writeentry(ctx.rev() * _fnodesrecsize, node[0:4], fnode) | ||||
def _writeentry(self, offset, prefix, fnode): | ||||
|
r24735 | # Slices on array instances only accept other array. | ||
|
r31346 | entry = bytearray(prefix + fnode) | ||
|
r24735 | self._raw[offset:offset + _fnodesrecsize] = entry | ||
# self._dirtyoffset could be None. | ||||
self._dirtyoffset = min(self._dirtyoffset, offset) or 0 | ||||
def write(self): | ||||
"""Perform all necessary writes to cache file. | ||||
This may no-op if no writes are needed or if a write lock could | ||||
not be obtained. | ||||
""" | ||||
if self._dirtyoffset is None: | ||||
return | ||||
data = self._raw[self._dirtyoffset:] | ||||
if not data: | ||||
return | ||||
repo = self._repo | ||||
try: | ||||
lock = repo.wlock(wait=False) | ||||
|
r24806 | except error.LockError: | ||
|
r24735 | repo.ui.log('tagscache', | ||
|
r24806 | 'not writing .hg/%s because lock cannot be acquired\n' % | ||
|
r24735 | (_fnodescachefile)) | ||
return | ||||
try: | ||||
|
r25087 | f = repo.vfs.open(_fnodescachefile, 'ab') | ||
|
r24735 | try: | ||
|
r25087 | # if the file has been truncated | ||
actualoffset = f.tell() | ||||
if actualoffset < self._dirtyoffset: | ||||
self._dirtyoffset = actualoffset | ||||
data = self._raw[self._dirtyoffset:] | ||||
f.seek(self._dirtyoffset) | ||||
f.truncate() | ||||
|
r24735 | repo.ui.log('tagscache', | ||
|
r25087 | 'writing %d bytes to %s\n' % ( | ||
len(data), _fnodescachefile)) | ||||
f.write(data) | ||||
self._dirtyoffset = None | ||||
finally: | ||||
f.close() | ||||
|
r25660 | except (IOError, OSError) as inst: | ||
|
r25087 | repo.ui.log('tagscache', | ||
"couldn't write %s: %s\n" % ( | ||||
_fnodescachefile, inst)) | ||||
|
r24735 | finally: | ||
lock.release() | ||||