Debian Codegraph @

hgext/relink.py

raw
1 # Mercurial extension to provide 'hg relink' command
2 #
3 # Copyright (C) 2007 Brendan Cully <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 """recreates hardlinks between repository clones"""
9
10 from __future__ import annotations
11
12 import os
13 import stat
14
15 from mercurial.i18n import _
16 from mercurial import (
17 error,
18 registrar,
19 util,
20 )
21 from mercurial.repo import (
22 factory as repo_factory,
23 )
24 from mercurial.utils import (
25 stringutil,
26 urlutil,
27 )
28
29 cmdtable = {}
30 command = registrar.command(cmdtable)
31 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
32 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
33 # be specifying the version(s) of Mercurial they are tested with, or
34 # leave the attribute unspecified.
35 testedwith = b'ships-with-hg-core'
36
37
38 @command(
39 b'relink', [], _(b'[ORIGIN]'), helpcategory=command.CATEGORY_MAINTENANCE
40 )
41 def relink(ui, repo, origin=None, **opts):
42 """recreate hardlinks between two repositories
43
44 When repositories are cloned locally, their data files will be
45 hardlinked so that they only use the space of a single repository.
46
47 Unfortunately, subsequent pulls into either repository will break
48 hardlinks for any files touched by the new changesets, even if
49 both repositories end up pulling the same changes.
50
51 Similarly, passing --rev to "hg clone" will fail to use any
52 hardlinks, falling back to a complete copy of the source
53 repository.
54
55 This command lets you recreate those hardlinks and reclaim that
56 wasted space.
57
58 This repository will be relinked to share space with ORIGIN, which
59 must be on the same local disk. If ORIGIN is omitted, looks for
60 "default-relink", then "default", in [paths].
61
62 Do not attempt any read operations on this repository while the
63 command is running. (Both repositories will be locked against
64 writes.)
65 """
66 if not hasattr(util, 'samefile') or not hasattr(util, 'samedevice'):
67 raise error.Abort(_(b'hardlinks are not supported on this system'))
68
69 if origin is None and b'default-relink' in ui.paths:
70 origin = b'default-relink'
71 path = urlutil.get_unique_pull_path_obj(b'relink', ui, origin)
72 src = repo_factory.repository(repo.baseui, path.loc)
73 ui.status(_(b'relinking %s to %s\n') % (src.store.path, repo.store.path))
74 if repo.root == src.root:
75 ui.status(_(b'there is nothing to relink\n'))
76 return
77
78 if not util.samedevice(src.store.path, repo.store.path):
79 # No point in continuing
80 raise error.Abort(_(b'source and destination are on different devices'))
81
82 with repo.lock(), src.lock():
83 candidates = sorted(collect(src, ui))
84 targets = prune(candidates, src.store.path, repo.store.path, ui)
85 do_relink(src.store.path, repo.store.path, targets, ui)
86
87
88 def collect(src, ui):
89 seplen = len(os.path.sep)
90 candidates = []
91 live = len(src[b'tip'].manifest())
92 # Your average repository has some files which were deleted before
93 # the tip revision. We account for that by assuming that there are
94 # 3 tracked files for every 2 live files as of the tip version of
95 # the repository.
96 #
97 # mozilla-central as of 2010-06-10 had a ratio of just over 7:5.
98 total = live * 3 // 2
99 src = src.store.path
100 progress = ui.makeprogress(_(b'collecting'), unit=_(b'files'), total=total)
101 pos = 0
102 ui.status(
103 _(b"tip has %d files, estimated total number of files: %d\n")
104 % (live, total)
105 )
106 for dirpath, dirnames, filenames in os.walk(src):
107 dirnames.sort()
108 relpath = dirpath[len(src) + seplen :]
109 for filename in sorted(filenames):
110 if filename[-2:] not in (b'.d', b'.i'):
111 continue
112 st = os.stat(os.path.join(dirpath, filename))
113 if not stat.S_ISREG(st.st_mode):
114 continue
115 pos += 1
116 candidates.append((os.path.join(relpath, filename), st))
117 progress.update(pos, item=filename)
118
119 progress.complete()
120 ui.status(_(b'collected %d candidate storage files\n') % len(candidates))
121 return candidates
122
123
124 def prune(candidates, src, dst, ui):
125 def linkfilter(src, dst, st):
126 try:
127 ts = os.stat(dst)
128 except OSError:
129 # Destination doesn't have this file?
130 return False
131 if util.samefile(src, dst):
132 return False
133 if not util.samedevice(src, dst):
134 # No point in continuing
135 raise error.Abort(
136 _(b'source and destination are on different devices')
137 )
138 if st.st_size != ts.st_size:
139 return False
140 return st
141
142 targets = []
143 progress = ui.makeprogress(
144 _(b'pruning'), unit=_(b'files'), total=len(candidates)
145 )
146 pos = 0
147 for fn, st in candidates:
148 pos += 1
149 srcpath = os.path.join(src, fn)
150 tgt = os.path.join(dst, fn)
151 ts = linkfilter(srcpath, tgt, st)
152 if not ts:
153 ui.debug(b'not linkable: %s\n' % fn)
154 continue
155 targets.append((fn, ts.st_size))
156 progress.update(pos, item=fn)
157
158 progress.complete()
159 ui.status(
160 _(b'pruned down to %d probably relinkable files\n') % len(targets)
161 )
162 return targets
163
164
165 def do_relink(src, dst, files, ui):
166 def relinkfile(src, dst):
167 bak = dst + b'.bak'
168 os.rename(dst, bak)
169 try:
170 util.oslink(src, dst)
171 except OSError:
172 os.rename(bak, dst)
173 raise
174 os.remove(bak)
175
176 CHUNKLEN = 65536
177 relinked = 0
178 savedbytes = 0
179
180 progress = ui.makeprogress(
181 _(b'relinking'), unit=_(b'files'), total=len(files)
182 )
183 pos = 0
184 for f, sz in files:
185 pos += 1
186 source = os.path.join(src, f)
187 tgt = os.path.join(dst, f)
188 # Binary mode, so that read() works correctly, especially on Windows
189 with open(source, 'rb') as sfp, open(tgt, 'rb') as dfp:
190 sin = sfp.read(CHUNKLEN)
191 while sin:
192 din = dfp.read(CHUNKLEN)
193 if sin != din:
194 break
195 sin = sfp.read(CHUNKLEN)
196
197 if sin:
198 ui.debug(b'not linkable: %s\n' % f)
199 continue
200 try:
201 relinkfile(source, tgt)
202 progress.update(pos, item=f)
203 relinked += 1
204 savedbytes += sz
205 except OSError as inst:
206 ui.warn(b'%s: %s\n' % (tgt, stringutil.forcebytestr(inst)))
207
208 progress.complete()
209
210 ui.status(
211 _(b'relinked %d files (%s reclaimed)\n')
212 % (relinked, util.bytecount(savedbytes))
213 )