Show More
@@ -1,481 +1,481 b'' | |||||
1 | # narrowcommands.py - command modifications for narrowhg extension |
|
1 | # narrowcommands.py - command modifications for narrowhg extension | |
2 | # |
|
2 | # | |
3 | # Copyright 2017 Google, Inc. |
|
3 | # Copyright 2017 Google, Inc. | |
4 | # |
|
4 | # | |
5 | # This software may be used and distributed according to the terms of the |
|
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. |
|
6 | # GNU General Public License version 2 or any later version. | |
7 | from __future__ import absolute_import |
|
7 | from __future__ import absolute_import | |
8 |
|
8 | |||
9 | import itertools |
|
9 | import itertools | |
10 | import os |
|
10 | import os | |
11 |
|
11 | |||
12 | from mercurial.i18n import _ |
|
12 | from mercurial.i18n import _ | |
13 | from mercurial import ( |
|
13 | from mercurial import ( | |
14 | bundle2, |
|
14 | bundle2, | |
15 | cmdutil, |
|
15 | cmdutil, | |
16 | commands, |
|
16 | commands, | |
17 | discovery, |
|
17 | discovery, | |
18 | encoding, |
|
18 | encoding, | |
19 | error, |
|
19 | error, | |
20 | exchange, |
|
20 | exchange, | |
21 | extensions, |
|
21 | extensions, | |
22 | hg, |
|
22 | hg, | |
23 | merge, |
|
23 | merge, | |
24 | narrowspec, |
|
24 | narrowspec, | |
25 | node, |
|
25 | node, | |
26 | pycompat, |
|
26 | pycompat, | |
27 | registrar, |
|
27 | registrar, | |
28 | repair, |
|
28 | repair, | |
29 | repository, |
|
29 | repository, | |
30 | repoview, |
|
30 | repoview, | |
31 | sparse, |
|
31 | sparse, | |
32 | util, |
|
32 | util, | |
33 | wireprototypes, |
|
33 | wireprototypes, | |
34 | ) |
|
34 | ) | |
35 |
|
35 | |||
36 | table = {} |
|
36 | table = {} | |
37 | command = registrar.command(table) |
|
37 | command = registrar.command(table) | |
38 |
|
38 | |||
39 | def setup(): |
|
39 | def setup(): | |
40 | """Wraps user-facing mercurial commands with narrow-aware versions.""" |
|
40 | """Wraps user-facing mercurial commands with narrow-aware versions.""" | |
41 |
|
41 | |||
42 | entry = extensions.wrapcommand(commands.table, 'clone', clonenarrowcmd) |
|
42 | entry = extensions.wrapcommand(commands.table, 'clone', clonenarrowcmd) | |
43 | entry[1].append(('', 'narrow', None, |
|
43 | entry[1].append(('', 'narrow', None, | |
44 | _("create a narrow clone of select files"))) |
|
44 | _("create a narrow clone of select files"))) | |
45 | entry[1].append(('', 'depth', '', |
|
45 | entry[1].append(('', 'depth', '', | |
46 | _("limit the history fetched by distance from heads"))) |
|
46 | _("limit the history fetched by distance from heads"))) | |
47 | entry[1].append(('', 'narrowspec', '', |
|
47 | entry[1].append(('', 'narrowspec', '', | |
48 | _("read narrowspecs from file"))) |
|
48 | _("read narrowspecs from file"))) | |
49 | # TODO(durin42): unify sparse/narrow --include/--exclude logic a bit |
|
49 | # TODO(durin42): unify sparse/narrow --include/--exclude logic a bit | |
50 | if 'sparse' not in extensions.enabled(): |
|
50 | if 'sparse' not in extensions.enabled(): | |
51 | entry[1].append(('', 'include', [], |
|
51 | entry[1].append(('', 'include', [], | |
52 | _("specifically fetch this file/directory"))) |
|
52 | _("specifically fetch this file/directory"))) | |
53 | entry[1].append( |
|
53 | entry[1].append( | |
54 | ('', 'exclude', [], |
|
54 | ('', 'exclude', [], | |
55 | _("do not fetch this file/directory, even if included"))) |
|
55 | _("do not fetch this file/directory, even if included"))) | |
56 |
|
56 | |||
57 | entry = extensions.wrapcommand(commands.table, 'pull', pullnarrowcmd) |
|
57 | entry = extensions.wrapcommand(commands.table, 'pull', pullnarrowcmd) | |
58 | entry[1].append(('', 'depth', '', |
|
58 | entry[1].append(('', 'depth', '', | |
59 | _("limit the history fetched by distance from heads"))) |
|
59 | _("limit the history fetched by distance from heads"))) | |
60 |
|
60 | |||
61 | extensions.wrapcommand(commands.table, 'archive', archivenarrowcmd) |
|
61 | extensions.wrapcommand(commands.table, 'archive', archivenarrowcmd) | |
62 |
|
62 | |||
63 | def clonenarrowcmd(orig, ui, repo, *args, **opts): |
|
63 | def clonenarrowcmd(orig, ui, repo, *args, **opts): | |
64 | """Wraps clone command, so 'hg clone' first wraps localrepo.clone().""" |
|
64 | """Wraps clone command, so 'hg clone' first wraps localrepo.clone().""" | |
65 | opts = pycompat.byteskwargs(opts) |
|
65 | opts = pycompat.byteskwargs(opts) | |
66 | wrappedextraprepare = util.nullcontextmanager() |
|
66 | wrappedextraprepare = util.nullcontextmanager() | |
67 | narrowspecfile = opts['narrowspec'] |
|
67 | narrowspecfile = opts['narrowspec'] | |
68 |
|
68 | |||
69 | if narrowspecfile: |
|
69 | if narrowspecfile: | |
70 | filepath = os.path.join(encoding.getcwd(), narrowspecfile) |
|
70 | filepath = os.path.join(encoding.getcwd(), narrowspecfile) | |
71 | ui.status(_("reading narrowspec from '%s'\n") % filepath) |
|
71 | ui.status(_("reading narrowspec from '%s'\n") % filepath) | |
72 | try: |
|
72 | try: | |
73 | fdata = util.readfile(filepath) |
|
73 | fdata = util.readfile(filepath) | |
74 | except IOError as inst: |
|
74 | except IOError as inst: | |
75 | raise error.Abort(_("cannot read narrowspecs from '%s': %s") % |
|
75 | raise error.Abort(_("cannot read narrowspecs from '%s': %s") % | |
76 | (filepath, encoding.strtolocal(inst.strerror))) |
|
76 | (filepath, encoding.strtolocal(inst.strerror))) | |
77 |
|
77 | |||
78 | includes, excludes, profiles = sparse.parseconfig(ui, fdata, 'narrow') |
|
78 | includes, excludes, profiles = sparse.parseconfig(ui, fdata, 'narrow') | |
79 | if profiles: |
|
79 | if profiles: | |
80 | raise error.Abort(_("cannot specify other files using '%include' in" |
|
80 | raise error.Abort(_("cannot specify other files using '%include' in" | |
81 | " narrowspec")) |
|
81 | " narrowspec")) | |
82 |
|
82 | |||
83 | narrowspec.validatepatterns(includes) |
|
83 | narrowspec.validatepatterns(includes) | |
84 | narrowspec.validatepatterns(excludes) |
|
84 | narrowspec.validatepatterns(excludes) | |
85 |
|
85 | |||
86 | # narrowspec is passed so we should assume that user wants narrow clone |
|
86 | # narrowspec is passed so we should assume that user wants narrow clone | |
87 | opts['narrow'] = True |
|
87 | opts['narrow'] = True | |
88 | opts['include'].extend(includes) |
|
88 | opts['include'].extend(includes) | |
89 | opts['exclude'].extend(excludes) |
|
89 | opts['exclude'].extend(excludes) | |
90 |
|
90 | |||
91 | if opts['narrow']: |
|
91 | if opts['narrow']: | |
92 | def pullbundle2extraprepare_widen(orig, pullop, kwargs): |
|
92 | def pullbundle2extraprepare_widen(orig, pullop, kwargs): | |
93 | orig(pullop, kwargs) |
|
93 | orig(pullop, kwargs) | |
94 |
|
94 | |||
95 | if opts.get('depth'): |
|
95 | if opts.get('depth'): | |
96 | kwargs['depth'] = opts['depth'] |
|
96 | kwargs['depth'] = opts['depth'] | |
97 | wrappedextraprepare = extensions.wrappedfunction(exchange, |
|
97 | wrappedextraprepare = extensions.wrappedfunction(exchange, | |
98 | '_pullbundle2extraprepare', pullbundle2extraprepare_widen) |
|
98 | '_pullbundle2extraprepare', pullbundle2extraprepare_widen) | |
99 |
|
99 | |||
100 | with wrappedextraprepare: |
|
100 | with wrappedextraprepare: | |
101 | return orig(ui, repo, *args, **pycompat.strkwargs(opts)) |
|
101 | return orig(ui, repo, *args, **pycompat.strkwargs(opts)) | |
102 |
|
102 | |||
103 | def pullnarrowcmd(orig, ui, repo, *args, **opts): |
|
103 | def pullnarrowcmd(orig, ui, repo, *args, **opts): | |
104 | """Wraps pull command to allow modifying narrow spec.""" |
|
104 | """Wraps pull command to allow modifying narrow spec.""" | |
105 | wrappedextraprepare = util.nullcontextmanager() |
|
105 | wrappedextraprepare = util.nullcontextmanager() | |
106 | if repository.NARROW_REQUIREMENT in repo.requirements: |
|
106 | if repository.NARROW_REQUIREMENT in repo.requirements: | |
107 |
|
107 | |||
108 | def pullbundle2extraprepare_widen(orig, pullop, kwargs): |
|
108 | def pullbundle2extraprepare_widen(orig, pullop, kwargs): | |
109 | orig(pullop, kwargs) |
|
109 | orig(pullop, kwargs) | |
110 | if opts.get(r'depth'): |
|
110 | if opts.get(r'depth'): | |
111 | kwargs['depth'] = opts[r'depth'] |
|
111 | kwargs['depth'] = opts[r'depth'] | |
112 | wrappedextraprepare = extensions.wrappedfunction(exchange, |
|
112 | wrappedextraprepare = extensions.wrappedfunction(exchange, | |
113 | '_pullbundle2extraprepare', pullbundle2extraprepare_widen) |
|
113 | '_pullbundle2extraprepare', pullbundle2extraprepare_widen) | |
114 |
|
114 | |||
115 | with wrappedextraprepare: |
|
115 | with wrappedextraprepare: | |
116 | return orig(ui, repo, *args, **opts) |
|
116 | return orig(ui, repo, *args, **opts) | |
117 |
|
117 | |||
118 | def archivenarrowcmd(orig, ui, repo, *args, **opts): |
|
118 | def archivenarrowcmd(orig, ui, repo, *args, **opts): | |
119 | """Wraps archive command to narrow the default includes.""" |
|
119 | """Wraps archive command to narrow the default includes.""" | |
120 | if repository.NARROW_REQUIREMENT in repo.requirements: |
|
120 | if repository.NARROW_REQUIREMENT in repo.requirements: | |
121 | repo_includes, repo_excludes = repo.narrowpats |
|
121 | repo_includes, repo_excludes = repo.narrowpats | |
122 | includes = set(opts.get(r'include', [])) |
|
122 | includes = set(opts.get(r'include', [])) | |
123 | excludes = set(opts.get(r'exclude', [])) |
|
123 | excludes = set(opts.get(r'exclude', [])) | |
124 | includes, excludes, unused_invalid = narrowspec.restrictpatterns( |
|
124 | includes, excludes, unused_invalid = narrowspec.restrictpatterns( | |
125 | includes, excludes, repo_includes, repo_excludes) |
|
125 | includes, excludes, repo_includes, repo_excludes) | |
126 | if includes: |
|
126 | if includes: | |
127 | opts[r'include'] = includes |
|
127 | opts[r'include'] = includes | |
128 | if excludes: |
|
128 | if excludes: | |
129 | opts[r'exclude'] = excludes |
|
129 | opts[r'exclude'] = excludes | |
130 | return orig(ui, repo, *args, **opts) |
|
130 | return orig(ui, repo, *args, **opts) | |
131 |
|
131 | |||
132 | def pullbundle2extraprepare(orig, pullop, kwargs): |
|
132 | def pullbundle2extraprepare(orig, pullop, kwargs): | |
133 | repo = pullop.repo |
|
133 | repo = pullop.repo | |
134 | if repository.NARROW_REQUIREMENT not in repo.requirements: |
|
134 | if repository.NARROW_REQUIREMENT not in repo.requirements: | |
135 | return orig(pullop, kwargs) |
|
135 | return orig(pullop, kwargs) | |
136 |
|
136 | |||
137 | if wireprototypes.NARROWCAP not in pullop.remote.capabilities(): |
|
137 | if wireprototypes.NARROWCAP not in pullop.remote.capabilities(): | |
138 | raise error.Abort(_("server does not support narrow clones")) |
|
138 | raise error.Abort(_("server does not support narrow clones")) | |
139 | orig(pullop, kwargs) |
|
139 | orig(pullop, kwargs) | |
140 | kwargs['narrow'] = True |
|
140 | kwargs['narrow'] = True | |
141 | include, exclude = repo.narrowpats |
|
141 | include, exclude = repo.narrowpats | |
142 | kwargs['oldincludepats'] = include |
|
142 | kwargs['oldincludepats'] = include | |
143 | kwargs['oldexcludepats'] = exclude |
|
143 | kwargs['oldexcludepats'] = exclude | |
144 | if include: |
|
144 | if include: | |
145 | kwargs['includepats'] = include |
|
145 | kwargs['includepats'] = include | |
146 | if exclude: |
|
146 | if exclude: | |
147 | kwargs['excludepats'] = exclude |
|
147 | kwargs['excludepats'] = exclude | |
148 | # calculate known nodes only in ellipses cases because in non-ellipses cases |
|
148 | # calculate known nodes only in ellipses cases because in non-ellipses cases | |
149 | # we have all the nodes |
|
149 | # we have all the nodes | |
150 | if wireprototypes.ELLIPSESCAP in pullop.remote.capabilities(): |
|
150 | if wireprototypes.ELLIPSESCAP in pullop.remote.capabilities(): | |
151 | kwargs['known'] = [node.hex(ctx.node()) for ctx in |
|
151 | kwargs['known'] = [node.hex(ctx.node()) for ctx in | |
152 | repo.set('::%ln', pullop.common) |
|
152 | repo.set('::%ln', pullop.common) | |
153 | if ctx.node() != node.nullid] |
|
153 | if ctx.node() != node.nullid] | |
154 | if not kwargs['known']: |
|
154 | if not kwargs['known']: | |
155 | # Mercurial serializes an empty list as '' and deserializes it as |
|
155 | # Mercurial serializes an empty list as '' and deserializes it as | |
156 | # [''], so delete it instead to avoid handling the empty string on |
|
156 | # [''], so delete it instead to avoid handling the empty string on | |
157 | # the server. |
|
157 | # the server. | |
158 | del kwargs['known'] |
|
158 | del kwargs['known'] | |
159 |
|
159 | |||
160 | extensions.wrapfunction(exchange,'_pullbundle2extraprepare', |
|
160 | extensions.wrapfunction(exchange,'_pullbundle2extraprepare', | |
161 | pullbundle2extraprepare) |
|
161 | pullbundle2extraprepare) | |
162 |
|
162 | |||
163 | # This is an extension point for filesystems that need to do something other |
|
163 | # This is an extension point for filesystems that need to do something other | |
164 | # than just blindly unlink the files. It's not clear what arguments would be |
|
164 | # than just blindly unlink the files. It's not clear what arguments would be | |
165 | # useful, so we're passing in a fair number of them, some of them redundant. |
|
165 | # useful, so we're passing in a fair number of them, some of them redundant. | |
166 | def _narrowcleanupwdir(repo, oldincludes, oldexcludes, newincludes, newexcludes, |
|
166 | def _narrowcleanupwdir(repo, oldincludes, oldexcludes, newincludes, newexcludes, | |
167 | oldmatch, newmatch): |
|
167 | oldmatch, newmatch): | |
168 | for f in repo.dirstate: |
|
168 | for f in repo.dirstate: | |
169 | if not newmatch(f): |
|
169 | if not newmatch(f): | |
170 | repo.dirstate.drop(f) |
|
170 | repo.dirstate.drop(f) | |
171 | repo.wvfs.unlinkpath(f) |
|
171 | repo.wvfs.unlinkpath(f) | |
172 |
|
172 | |||
173 | def _narrow(ui, repo, remote, commoninc, oldincludes, oldexcludes, |
|
173 | def _narrow(ui, repo, remote, commoninc, oldincludes, oldexcludes, | |
174 | newincludes, newexcludes, force): |
|
174 | newincludes, newexcludes, force): | |
175 | oldmatch = narrowspec.match(repo.root, oldincludes, oldexcludes) |
|
175 | oldmatch = narrowspec.match(repo.root, oldincludes, oldexcludes) | |
176 | newmatch = narrowspec.match(repo.root, newincludes, newexcludes) |
|
176 | newmatch = narrowspec.match(repo.root, newincludes, newexcludes) | |
177 |
|
177 | |||
178 | # This is essentially doing "hg outgoing" to find all local-only |
|
178 | # This is essentially doing "hg outgoing" to find all local-only | |
179 | # commits. We will then check that the local-only commits don't |
|
179 | # commits. We will then check that the local-only commits don't | |
180 | # have any changes to files that will be untracked. |
|
180 | # have any changes to files that will be untracked. | |
181 | unfi = repo.unfiltered() |
|
181 | unfi = repo.unfiltered() | |
182 | outgoing = discovery.findcommonoutgoing(unfi, remote, |
|
182 | outgoing = discovery.findcommonoutgoing(unfi, remote, | |
183 | commoninc=commoninc) |
|
183 | commoninc=commoninc) | |
184 | ui.status(_('looking for local changes to affected paths\n')) |
|
184 | ui.status(_('looking for local changes to affected paths\n')) | |
185 | localnodes = [] |
|
185 | localnodes = [] | |
186 | for n in itertools.chain(outgoing.missing, outgoing.excluded): |
|
186 | for n in itertools.chain(outgoing.missing, outgoing.excluded): | |
187 | if any(oldmatch(f) and not newmatch(f) for f in unfi[n].files()): |
|
187 | if any(oldmatch(f) and not newmatch(f) for f in unfi[n].files()): | |
188 | localnodes.append(n) |
|
188 | localnodes.append(n) | |
189 | revstostrip = unfi.revs('descendants(%ln)', localnodes) |
|
189 | revstostrip = unfi.revs('descendants(%ln)', localnodes) | |
190 | hiddenrevs = repoview.filterrevs(repo, 'visible') |
|
190 | hiddenrevs = repoview.filterrevs(repo, 'visible') | |
191 | visibletostrip = list(repo.changelog.node(r) |
|
191 | visibletostrip = list(repo.changelog.node(r) | |
192 | for r in (revstostrip - hiddenrevs)) |
|
192 | for r in (revstostrip - hiddenrevs)) | |
193 | if visibletostrip: |
|
193 | if visibletostrip: | |
194 | ui.status(_('The following changeset(s) or their ancestors have ' |
|
194 | ui.status(_('The following changeset(s) or their ancestors have ' | |
195 | 'local changes not on the remote:\n')) |
|
195 | 'local changes not on the remote:\n')) | |
196 | maxnodes = 10 |
|
196 | maxnodes = 10 | |
197 | if ui.verbose or len(visibletostrip) <= maxnodes: |
|
197 | if ui.verbose or len(visibletostrip) <= maxnodes: | |
198 | for n in visibletostrip: |
|
198 | for n in visibletostrip: | |
199 | ui.status('%s\n' % node.short(n)) |
|
199 | ui.status('%s\n' % node.short(n)) | |
200 | else: |
|
200 | else: | |
201 | for n in visibletostrip[:maxnodes]: |
|
201 | for n in visibletostrip[:maxnodes]: | |
202 | ui.status('%s\n' % node.short(n)) |
|
202 | ui.status('%s\n' % node.short(n)) | |
203 | ui.status(_('...and %d more, use --verbose to list all\n') % |
|
203 | ui.status(_('...and %d more, use --verbose to list all\n') % | |
204 | (len(visibletostrip) - maxnodes)) |
|
204 | (len(visibletostrip) - maxnodes)) | |
205 | if not force: |
|
205 | if not force: | |
206 | raise error.Abort(_('local changes found'), |
|
206 | raise error.Abort(_('local changes found'), | |
207 | hint=_('use --force-delete-local-changes to ' |
|
207 | hint=_('use --force-delete-local-changes to ' | |
208 | 'ignore')) |
|
208 | 'ignore')) | |
209 |
|
209 | |||
210 | with ui.uninterruptible(): |
|
210 | with ui.uninterruptible(): | |
211 | if revstostrip: |
|
211 | if revstostrip: | |
212 | tostrip = [unfi.changelog.node(r) for r in revstostrip] |
|
212 | tostrip = [unfi.changelog.node(r) for r in revstostrip] | |
213 | if repo['.'].node() in tostrip: |
|
213 | if repo['.'].node() in tostrip: | |
214 | # stripping working copy, so move to a different commit first |
|
214 | # stripping working copy, so move to a different commit first | |
215 | urev = max(repo.revs('(::%n) - %ln + null', |
|
215 | urev = max(repo.revs('(::%n) - %ln + null', | |
216 | repo['.'].node(), visibletostrip)) |
|
216 | repo['.'].node(), visibletostrip)) | |
217 | hg.clean(repo, urev) |
|
217 | hg.clean(repo, urev) | |
218 | overrides = {('devel', 'strip-obsmarkers'): False} |
|
218 | overrides = {('devel', 'strip-obsmarkers'): False} | |
219 | with ui.configoverride(overrides, 'narrow'): |
|
219 | with ui.configoverride(overrides, 'narrow'): | |
220 | repair.strip(ui, unfi, tostrip, topic='narrow') |
|
220 | repair.strip(ui, unfi, tostrip, topic='narrow') | |
221 |
|
221 | |||
222 | todelete = [] |
|
222 | todelete = [] | |
223 | for f, f2, size in repo.store.datafiles(): |
|
223 | for f, f2, size in repo.store.datafiles(): | |
224 | if f.startswith('data/'): |
|
224 | if f.startswith('data/'): | |
225 | file = f[5:-2] |
|
225 | file = f[5:-2] | |
226 | if not newmatch(file): |
|
226 | if not newmatch(file): | |
227 | todelete.append(f) |
|
227 | todelete.append(f) | |
228 | elif f.startswith('meta/'): |
|
228 | elif f.startswith('meta/'): | |
229 | dir = f[5:-13] |
|
229 | dir = f[5:-13] | |
230 | dirs = ['.'] + sorted(util.dirs({dir})) + [dir] |
|
230 | dirs = ['.'] + sorted(util.dirs({dir})) + [dir] | |
231 | include = True |
|
231 | include = True | |
232 | for d in dirs: |
|
232 | for d in dirs: | |
233 | visit = newmatch.visitdir(d) |
|
233 | visit = newmatch.visitdir(d) | |
234 | if not visit: |
|
234 | if not visit: | |
235 | include = False |
|
235 | include = False | |
236 | break |
|
236 | break | |
237 | if visit == 'all': |
|
237 | if visit == 'all': | |
238 | break |
|
238 | break | |
239 | if not include: |
|
239 | if not include: | |
240 | todelete.append(f) |
|
240 | todelete.append(f) | |
241 |
|
241 | |||
242 | repo.destroying() |
|
242 | repo.destroying() | |
243 |
|
243 | |||
244 | with repo.transaction("narrowing"): |
|
244 | with repo.transaction("narrowing"): | |
245 | # Update narrowspec before removing revlogs, so repo won't be |
|
245 | # Update narrowspec before removing revlogs, so repo won't be | |
246 | # corrupt in case of crash |
|
246 | # corrupt in case of crash | |
247 | repo.setnarrowpats(newincludes, newexcludes) |
|
247 | repo.setnarrowpats(newincludes, newexcludes) | |
248 |
|
248 | |||
249 | for f in todelete: |
|
249 | for f in todelete: | |
250 | ui.status(_('deleting %s\n') % f) |
|
250 | ui.status(_('deleting %s\n') % f) | |
251 | util.unlinkpath(repo.svfs.join(f)) |
|
251 | util.unlinkpath(repo.svfs.join(f)) | |
252 | repo.store.markremoved(f) |
|
252 | repo.store.markremoved(f) | |
253 |
|
253 | |||
254 | _narrowcleanupwdir(repo, oldincludes, oldexcludes, newincludes, |
|
254 | _narrowcleanupwdir(repo, oldincludes, oldexcludes, newincludes, | |
255 | newexcludes, oldmatch, newmatch) |
|
255 | newexcludes, oldmatch, newmatch) | |
256 |
|
256 | |||
257 | repo.destroyed() |
|
257 | repo.destroyed() | |
258 |
|
258 | |||
259 | def _widen(ui, repo, remote, commoninc, oldincludes, oldexcludes, |
|
259 | def _widen(ui, repo, remote, commoninc, oldincludes, oldexcludes, | |
260 | newincludes, newexcludes): |
|
260 | newincludes, newexcludes): | |
261 | newmatch = narrowspec.match(repo.root, newincludes, newexcludes) |
|
261 | newmatch = narrowspec.match(repo.root, newincludes, newexcludes) | |
262 |
|
262 | |||
263 | # for now we assume that if a server has ellipses enabled, we will be |
|
263 | # for now we assume that if a server has ellipses enabled, we will be | |
264 | # exchanging ellipses nodes. In future we should add ellipses as a client |
|
264 | # exchanging ellipses nodes. In future we should add ellipses as a client | |
265 | # side requirement (maybe) to distinguish a client is shallow or not and |
|
265 | # side requirement (maybe) to distinguish a client is shallow or not and | |
266 | # then send that information to server whether we want ellipses or not. |
|
266 | # then send that information to server whether we want ellipses or not. | |
267 | # Theoretically a non-ellipses repo should be able to use narrow |
|
267 | # Theoretically a non-ellipses repo should be able to use narrow | |
268 | # functionality from an ellipses enabled server |
|
268 | # functionality from an ellipses enabled server | |
269 | ellipsesremote = wireprototypes.ELLIPSESCAP in remote.capabilities() |
|
269 | ellipsesremote = wireprototypes.ELLIPSESCAP in remote.capabilities() | |
270 |
|
270 | |||
271 | def pullbundle2extraprepare_widen(orig, pullop, kwargs): |
|
271 | def pullbundle2extraprepare_widen(orig, pullop, kwargs): | |
272 | orig(pullop, kwargs) |
|
272 | orig(pullop, kwargs) | |
273 | # The old{in,ex}cludepats have already been set by orig() |
|
273 | # The old{in,ex}cludepats have already been set by orig() | |
274 | kwargs['includepats'] = newincludes |
|
274 | kwargs['includepats'] = newincludes | |
275 | kwargs['excludepats'] = newexcludes |
|
275 | kwargs['excludepats'] = newexcludes | |
276 | wrappedextraprepare = extensions.wrappedfunction(exchange, |
|
276 | wrappedextraprepare = extensions.wrappedfunction(exchange, | |
277 | '_pullbundle2extraprepare', pullbundle2extraprepare_widen) |
|
277 | '_pullbundle2extraprepare', pullbundle2extraprepare_widen) | |
278 |
|
278 | |||
279 | # define a function that narrowbundle2 can call after creating the |
|
279 | # define a function that narrowbundle2 can call after creating the | |
280 | # backup bundle, but before applying the bundle from the server |
|
280 | # backup bundle, but before applying the bundle from the server | |
281 | def setnewnarrowpats(): |
|
281 | def setnewnarrowpats(): | |
282 | repo.setnarrowpats(newincludes, newexcludes) |
|
282 | repo.setnarrowpats(newincludes, newexcludes) | |
283 | repo.setnewnarrowpats = setnewnarrowpats |
|
283 | repo.setnewnarrowpats = setnewnarrowpats | |
284 | # silence the devel-warning of applying an empty changegroup |
|
284 | # silence the devel-warning of applying an empty changegroup | |
285 | overrides = {('devel', 'all-warnings'): False} |
|
285 | overrides = {('devel', 'all-warnings'): False} | |
286 |
|
286 | |||
287 | with ui.uninterruptible(): |
|
287 | with ui.uninterruptible(): | |
288 | common = commoninc[0] |
|
288 | common = commoninc[0] | |
289 | if ellipsesremote: |
|
289 | if ellipsesremote: | |
290 | ds = repo.dirstate |
|
290 | ds = repo.dirstate | |
291 | p1, p2 = ds.p1(), ds.p2() |
|
291 | p1, p2 = ds.p1(), ds.p2() | |
292 | with ds.parentchange(): |
|
292 | with ds.parentchange(): | |
293 | ds.setparents(node.nullid, node.nullid) |
|
293 | ds.setparents(node.nullid, node.nullid) | |
294 | with wrappedextraprepare,\ |
|
294 | with wrappedextraprepare,\ | |
295 | repo.ui.configoverride(overrides, 'widen'): |
|
295 | repo.ui.configoverride(overrides, 'widen'): | |
296 | exchange.pull(repo, remote, heads=common) |
|
296 | exchange.pull(repo, remote, heads=common) | |
297 | with ds.parentchange(): |
|
297 | with ds.parentchange(): | |
298 | ds.setparents(p1, p2) |
|
298 | ds.setparents(p1, p2) | |
299 | else: |
|
299 | else: | |
300 | with remote.commandexecutor() as e: |
|
300 | with remote.commandexecutor() as e: | |
301 | bundle = e.callcommand('narrow_widen', { |
|
301 | bundle = e.callcommand('narrow_widen', { | |
302 | 'oldincludes': oldincludes, |
|
302 | 'oldincludes': oldincludes, | |
303 | 'oldexcludes': oldexcludes, |
|
303 | 'oldexcludes': oldexcludes, | |
304 | 'newincludes': newincludes, |
|
304 | 'newincludes': newincludes, | |
305 | 'newexcludes': newexcludes, |
|
305 | 'newexcludes': newexcludes, | |
306 | 'cgversion': '03', |
|
306 | 'cgversion': '03', | |
307 | 'commonheads': common, |
|
307 | 'commonheads': common, | |
308 | 'known': [], |
|
308 | 'known': [], | |
309 | 'ellipses': False, |
|
309 | 'ellipses': False, | |
310 | }).result() |
|
310 | }).result() | |
311 |
|
311 | |||
312 | with repo.transaction('widening') as tr,\ |
|
312 | with repo.transaction('widening') as tr,\ | |
313 | repo.ui.configoverride(overrides, 'widen'): |
|
313 | repo.ui.configoverride(overrides, 'widen'): | |
314 | tgetter = lambda: tr |
|
314 | tgetter = lambda: tr | |
315 | bundle2.processbundle(repo, bundle, |
|
315 | bundle2.processbundle(repo, bundle, | |
316 | transactiongetter=tgetter) |
|
316 | transactiongetter=tgetter) | |
317 |
|
317 | |||
318 | repo.setnewnarrowpats() |
|
318 | repo.setnewnarrowpats() | |
319 | actions = merge.emptyactions() |
|
319 | actions = merge.emptyactions() | |
320 | addgaction = actions['g'].append |
|
320 | addgaction = actions['g'].append | |
321 |
|
321 | |||
322 | mf = repo['.'].manifest().matches(newmatch) |
|
322 | mf = repo['.'].manifest().matches(newmatch) | |
323 | for f, fn in mf.iteritems(): |
|
323 | for f, fn in mf.iteritems(): | |
324 | if f not in repo.dirstate: |
|
324 | if f not in repo.dirstate: | |
325 | addgaction((f, (mf.flags(f), False), |
|
325 | addgaction((f, (mf.flags(f), False), | |
326 | "add from widened narrow clone")) |
|
326 | "add from widened narrow clone")) | |
327 |
|
327 | |||
328 | merge.applyupdates(repo, actions, wctx=repo[None], |
|
328 | merge.applyupdates(repo, actions, wctx=repo[None], | |
329 | mctx=repo['.'], overwrite=False) |
|
329 | mctx=repo['.'], overwrite=False) | |
330 | merge.recordupdates(repo, actions, branchmerge=False) |
|
330 | merge.recordupdates(repo, actions, branchmerge=False) | |
331 |
|
331 | |||
332 | # TODO(rdamazio): Make new matcher format and update description |
|
332 | # TODO(rdamazio): Make new matcher format and update description | |
333 | @command('tracked', |
|
333 | @command('tracked', | |
334 | [('', 'addinclude', [], _('new paths to include')), |
|
334 | [('', 'addinclude', [], _('new paths to include')), | |
335 | ('', 'removeinclude', [], _('old paths to no longer include')), |
|
335 | ('', 'removeinclude', [], _('old paths to no longer include')), | |
336 | ('', 'addexclude', [], _('new paths to exclude')), |
|
336 | ('', 'addexclude', [], _('new paths to exclude')), | |
337 | ('', 'import-rules', '', _('import narrowspecs from a file')), |
|
337 | ('', 'import-rules', '', _('import narrowspecs from a file')), | |
338 | ('', 'removeexclude', [], _('old paths to no longer exclude')), |
|
338 | ('', 'removeexclude', [], _('old paths to no longer exclude')), | |
339 | ('', 'clear', False, _('whether to replace the existing narrowspec')), |
|
339 | ('', 'clear', False, _('whether to replace the existing narrowspec')), | |
340 | ('', 'force-delete-local-changes', False, |
|
340 | ('', 'force-delete-local-changes', False, | |
341 | _('forces deletion of local changes when narrowing')), |
|
341 | _('forces deletion of local changes when narrowing')), | |
342 | ('', 'update-working-copy', False, |
|
342 | ('', 'update-working-copy', False, | |
343 | _('update working copy when the store has changed')), |
|
343 | _('update working copy when the store has changed')), | |
344 | ] + commands.remoteopts, |
|
344 | ] + commands.remoteopts, | |
345 | _('[OPTIONS]... [REMOTE]'), |
|
345 | _('[OPTIONS]... [REMOTE]'), | |
346 | inferrepo=True) |
|
346 | inferrepo=True) | |
347 | def trackedcmd(ui, repo, remotepath=None, *pats, **opts): |
|
347 | def trackedcmd(ui, repo, remotepath=None, *pats, **opts): | |
348 | """show or change the current narrowspec |
|
348 | """show or change the current narrowspec | |
349 |
|
349 | |||
350 | With no argument, shows the current narrowspec entries, one per line. Each |
|
350 | With no argument, shows the current narrowspec entries, one per line. Each | |
351 | line will be prefixed with 'I' or 'X' for included or excluded patterns, |
|
351 | line will be prefixed with 'I' or 'X' for included or excluded patterns, | |
352 | respectively. |
|
352 | respectively. | |
353 |
|
353 | |||
354 | The narrowspec is comprised of expressions to match remote files and/or |
|
354 | The narrowspec is comprised of expressions to match remote files and/or | |
355 | directories that should be pulled into your client. |
|
355 | directories that should be pulled into your client. | |
356 | The narrowspec has *include* and *exclude* expressions, with excludes always |
|
356 | The narrowspec has *include* and *exclude* expressions, with excludes always | |
357 | trumping includes: that is, if a file matches an exclude expression, it will |
|
357 | trumping includes: that is, if a file matches an exclude expression, it will | |
358 | be excluded even if it also matches an include expression. |
|
358 | be excluded even if it also matches an include expression. | |
359 | Excluding files that were never included has no effect. |
|
359 | Excluding files that were never included has no effect. | |
360 |
|
360 | |||
361 | Each included or excluded entry is in the format described by |
|
361 | Each included or excluded entry is in the format described by | |
362 | 'hg help patterns'. |
|
362 | 'hg help patterns'. | |
363 |
|
363 | |||
364 | The options allow you to add or remove included and excluded expressions. |
|
364 | The options allow you to add or remove included and excluded expressions. | |
365 |
|
365 | |||
366 | If --clear is specified, then all previous includes and excludes are DROPPED |
|
366 | If --clear is specified, then all previous includes and excludes are DROPPED | |
367 | and replaced by the new ones specified to --addinclude and --addexclude. |
|
367 | and replaced by the new ones specified to --addinclude and --addexclude. | |
368 | If --clear is specified without any further options, the narrowspec will be |
|
368 | If --clear is specified without any further options, the narrowspec will be | |
369 | empty and will not match any files. |
|
369 | empty and will not match any files. | |
370 | """ |
|
370 | """ | |
371 | opts = pycompat.byteskwargs(opts) |
|
371 | opts = pycompat.byteskwargs(opts) | |
372 | if repository.NARROW_REQUIREMENT not in repo.requirements: |
|
372 | if repository.NARROW_REQUIREMENT not in repo.requirements: | |
373 | raise error.Abort(_('the narrow command is only supported on ' |
|
373 | raise error.Abort(_('the narrow command is only supported on ' | |
374 | 'respositories cloned with --narrow')) |
|
374 | 'respositories cloned with --narrow')) | |
375 |
|
375 | |||
376 | # Before supporting, decide whether it "hg tracked --clear" should mean |
|
376 | # Before supporting, decide whether it "hg tracked --clear" should mean | |
377 | # tracking no paths or all paths. |
|
377 | # tracking no paths or all paths. | |
378 | if opts['clear']: |
|
378 | if opts['clear']: | |
379 | raise error.Abort(_('the --clear option is not yet supported')) |
|
379 | raise error.Abort(_('the --clear option is not yet supported')) | |
380 |
|
380 | |||
381 | # import rules from a file |
|
381 | # import rules from a file | |
382 | newrules = opts.get('import_rules') |
|
382 | newrules = opts.get('import_rules') | |
383 | if newrules: |
|
383 | if newrules: | |
384 | try: |
|
384 | try: | |
385 | filepath = os.path.join(encoding.getcwd(), newrules) |
|
385 | filepath = os.path.join(encoding.getcwd(), newrules) | |
386 | fdata = util.readfile(filepath) |
|
386 | fdata = util.readfile(filepath) | |
387 | except IOError as inst: |
|
387 | except IOError as inst: | |
388 | raise error.Abort(_("cannot read narrowspecs from '%s': %s") % |
|
388 | raise error.Abort(_("cannot read narrowspecs from '%s': %s") % | |
389 | (filepath, encoding.strtolocal(inst.strerror))) |
|
389 | (filepath, encoding.strtolocal(inst.strerror))) | |
390 | includepats, excludepats, profiles = sparse.parseconfig(ui, fdata, |
|
390 | includepats, excludepats, profiles = sparse.parseconfig(ui, fdata, | |
391 | 'narrow') |
|
391 | 'narrow') | |
392 | if profiles: |
|
392 | if profiles: | |
393 | raise error.Abort(_("including other spec files using '%include' " |
|
393 | raise error.Abort(_("including other spec files using '%include' " | |
394 | "is not supported in narrowspec")) |
|
394 | "is not supported in narrowspec")) | |
395 | opts['addinclude'].extend(includepats) |
|
395 | opts['addinclude'].extend(includepats) | |
396 | opts['addexclude'].extend(excludepats) |
|
396 | opts['addexclude'].extend(excludepats) | |
397 |
|
397 | |||
398 | addedincludes = narrowspec.parsepatterns(opts['addinclude']) |
|
398 | addedincludes = narrowspec.parsepatterns(opts['addinclude']) | |
399 | removedincludes = narrowspec.parsepatterns(opts['removeinclude']) |
|
399 | removedincludes = narrowspec.parsepatterns(opts['removeinclude']) | |
400 | addedexcludes = narrowspec.parsepatterns(opts['addexclude']) |
|
400 | addedexcludes = narrowspec.parsepatterns(opts['addexclude']) | |
401 | removedexcludes = narrowspec.parsepatterns(opts['removeexclude']) |
|
401 | removedexcludes = narrowspec.parsepatterns(opts['removeexclude']) | |
402 |
|
402 | |||
403 | update_working_copy = opts['update_working_copy'] |
|
403 | update_working_copy = opts['update_working_copy'] | |
404 | only_show = not (addedincludes or removedincludes or addedexcludes or |
|
404 | only_show = not (addedincludes or removedincludes or addedexcludes or | |
405 | removedexcludes or newrules or update_working_copy) |
|
405 | removedexcludes or newrules or update_working_copy) | |
406 |
|
406 | |||
407 | oldincludes, oldexcludes = repo.narrowpats |
|
407 | oldincludes, oldexcludes = repo.narrowpats | |
408 |
|
408 | |||
409 | # filter the user passed additions and deletions into actual additions and |
|
409 | # filter the user passed additions and deletions into actual additions and | |
410 | # deletions of excludes and includes |
|
410 | # deletions of excludes and includes | |
411 | addedincludes -= oldincludes |
|
411 | addedincludes -= oldincludes | |
412 | removedincludes &= oldincludes |
|
412 | removedincludes &= oldincludes | |
413 | addedexcludes -= oldexcludes |
|
413 | addedexcludes -= oldexcludes | |
414 | removedexcludes &= oldexcludes |
|
414 | removedexcludes &= oldexcludes | |
415 |
|
415 | |||
416 | widening = addedincludes or removedexcludes |
|
416 | widening = addedincludes or removedexcludes | |
417 | narrowing = removedincludes or addedexcludes |
|
417 | narrowing = removedincludes or addedexcludes | |
418 |
|
418 | |||
419 | # Only print the current narrowspec. |
|
419 | # Only print the current narrowspec. | |
420 | if only_show: |
|
420 | if only_show: | |
421 | ui.pager('tracked') |
|
421 | ui.pager('tracked') | |
422 | fm = ui.formatter('narrow', opts) |
|
422 | fm = ui.formatter('narrow', opts) | |
423 | for i in sorted(oldincludes): |
|
423 | for i in sorted(oldincludes): | |
424 | fm.startitem() |
|
424 | fm.startitem() | |
425 | fm.write('status', '%s ', 'I', label='narrow.included') |
|
425 | fm.write('status', '%s ', 'I', label='narrow.included') | |
426 | fm.write('pat', '%s\n', i, label='narrow.included') |
|
426 | fm.write('pat', '%s\n', i, label='narrow.included') | |
427 | for i in sorted(oldexcludes): |
|
427 | for i in sorted(oldexcludes): | |
428 | fm.startitem() |
|
428 | fm.startitem() | |
429 | fm.write('status', '%s ', 'X', label='narrow.excluded') |
|
429 | fm.write('status', '%s ', 'X', label='narrow.excluded') | |
430 | fm.write('pat', '%s\n', i, label='narrow.excluded') |
|
430 | fm.write('pat', '%s\n', i, label='narrow.excluded') | |
431 | fm.end() |
|
431 | fm.end() | |
432 | return 0 |
|
432 | return 0 | |
433 |
|
433 | |||
434 | if update_working_copy: |
|
434 | if update_working_copy: | |
435 |
with repo.wlock(), repo.lock(), repo.transaction('narrow-wc') |
|
435 | with repo.wlock(), repo.lock(), repo.transaction('narrow-wc'): | |
436 | narrowspec.updateworkingcopy(repo) |
|
436 | narrowspec.updateworkingcopy(repo) | |
437 |
narrowspec.copytoworkingcopy(repo |
|
437 | narrowspec.copytoworkingcopy(repo) | |
438 | return 0 |
|
438 | return 0 | |
439 |
|
439 | |||
440 | if not widening and not narrowing: |
|
440 | if not widening and not narrowing: | |
441 | ui.status(_("nothing to widen or narrow\n")) |
|
441 | ui.status(_("nothing to widen or narrow\n")) | |
442 | return 0 |
|
442 | return 0 | |
443 |
|
443 | |||
444 | with repo.wlock(), repo.lock(): |
|
444 | with repo.wlock(), repo.lock(): | |
445 | cmdutil.bailifchanged(repo) |
|
445 | cmdutil.bailifchanged(repo) | |
446 |
|
446 | |||
447 | # Find the revisions we have in common with the remote. These will |
|
447 | # Find the revisions we have in common with the remote. These will | |
448 | # be used for finding local-only changes for narrowing. They will |
|
448 | # be used for finding local-only changes for narrowing. They will | |
449 | # also define the set of revisions to update for widening. |
|
449 | # also define the set of revisions to update for widening. | |
450 | remotepath = ui.expandpath(remotepath or 'default') |
|
450 | remotepath = ui.expandpath(remotepath or 'default') | |
451 | url, branches = hg.parseurl(remotepath) |
|
451 | url, branches = hg.parseurl(remotepath) | |
452 | ui.status(_('comparing with %s\n') % util.hidepassword(url)) |
|
452 | ui.status(_('comparing with %s\n') % util.hidepassword(url)) | |
453 | remote = hg.peer(repo, opts, url) |
|
453 | remote = hg.peer(repo, opts, url) | |
454 |
|
454 | |||
455 | # check narrow support before doing anything if widening needs to be |
|
455 | # check narrow support before doing anything if widening needs to be | |
456 | # performed. In future we should also abort if client is ellipses and |
|
456 | # performed. In future we should also abort if client is ellipses and | |
457 | # server does not support ellipses |
|
457 | # server does not support ellipses | |
458 | if widening and wireprototypes.NARROWCAP not in remote.capabilities(): |
|
458 | if widening and wireprototypes.NARROWCAP not in remote.capabilities(): | |
459 | raise error.Abort(_("server does not support narrow clones")) |
|
459 | raise error.Abort(_("server does not support narrow clones")) | |
460 |
|
460 | |||
461 | commoninc = discovery.findcommonincoming(repo, remote) |
|
461 | commoninc = discovery.findcommonincoming(repo, remote) | |
462 |
|
462 | |||
463 | if narrowing: |
|
463 | if narrowing: | |
464 | newincludes = oldincludes - removedincludes |
|
464 | newincludes = oldincludes - removedincludes | |
465 | newexcludes = oldexcludes | addedexcludes |
|
465 | newexcludes = oldexcludes | addedexcludes | |
466 | _narrow(ui, repo, remote, commoninc, oldincludes, oldexcludes, |
|
466 | _narrow(ui, repo, remote, commoninc, oldincludes, oldexcludes, | |
467 | newincludes, newexcludes, |
|
467 | newincludes, newexcludes, | |
468 | opts['force_delete_local_changes']) |
|
468 | opts['force_delete_local_changes']) | |
469 | # _narrow() updated the narrowspec and _widen() below needs to |
|
469 | # _narrow() updated the narrowspec and _widen() below needs to | |
470 | # use the updated values as its base (otherwise removed includes |
|
470 | # use the updated values as its base (otherwise removed includes | |
471 | # and addedexcludes will be lost in the resulting narrowspec) |
|
471 | # and addedexcludes will be lost in the resulting narrowspec) | |
472 | oldincludes = newincludes |
|
472 | oldincludes = newincludes | |
473 | oldexcludes = newexcludes |
|
473 | oldexcludes = newexcludes | |
474 |
|
474 | |||
475 | if widening: |
|
475 | if widening: | |
476 | newincludes = oldincludes | addedincludes |
|
476 | newincludes = oldincludes | addedincludes | |
477 | newexcludes = oldexcludes - removedexcludes |
|
477 | newexcludes = oldexcludes - removedexcludes | |
478 | _widen(ui, repo, remote, commoninc, oldincludes, oldexcludes, |
|
478 | _widen(ui, repo, remote, commoninc, oldincludes, oldexcludes, | |
479 | newincludes, newexcludes) |
|
479 | newincludes, newexcludes) | |
480 |
|
480 | |||
481 | return 0 |
|
481 | return 0 |
@@ -1,1229 +1,1229 b'' | |||||
1 | # hg.py - repository classes for mercurial |
|
1 | # hg.py - repository classes for mercurial | |
2 | # |
|
2 | # | |
3 | # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> |
|
3 | # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> | |
4 | # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com> |
|
4 | # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com> | |
5 | # |
|
5 | # | |
6 | # This software may be used and distributed according to the terms of the |
|
6 | # This software may be used and distributed according to the terms of the | |
7 | # GNU General Public License version 2 or any later version. |
|
7 | # GNU General Public License version 2 or any later version. | |
8 |
|
8 | |||
9 | from __future__ import absolute_import |
|
9 | from __future__ import absolute_import | |
10 |
|
10 | |||
11 | import errno |
|
11 | import errno | |
12 | import hashlib |
|
12 | import hashlib | |
13 | import os |
|
13 | import os | |
14 | import shutil |
|
14 | import shutil | |
15 | import stat |
|
15 | import stat | |
16 |
|
16 | |||
17 | from .i18n import _ |
|
17 | from .i18n import _ | |
18 | from .node import ( |
|
18 | from .node import ( | |
19 | nullid, |
|
19 | nullid, | |
20 | ) |
|
20 | ) | |
21 |
|
21 | |||
22 | from . import ( |
|
22 | from . import ( | |
23 | bookmarks, |
|
23 | bookmarks, | |
24 | bundlerepo, |
|
24 | bundlerepo, | |
25 | cacheutil, |
|
25 | cacheutil, | |
26 | cmdutil, |
|
26 | cmdutil, | |
27 | destutil, |
|
27 | destutil, | |
28 | discovery, |
|
28 | discovery, | |
29 | error, |
|
29 | error, | |
30 | exchange, |
|
30 | exchange, | |
31 | extensions, |
|
31 | extensions, | |
32 | httppeer, |
|
32 | httppeer, | |
33 | localrepo, |
|
33 | localrepo, | |
34 | lock, |
|
34 | lock, | |
35 | logcmdutil, |
|
35 | logcmdutil, | |
36 | logexchange, |
|
36 | logexchange, | |
37 | merge as mergemod, |
|
37 | merge as mergemod, | |
38 | narrowspec, |
|
38 | narrowspec, | |
39 | node, |
|
39 | node, | |
40 | phases, |
|
40 | phases, | |
41 | repository as repositorymod, |
|
41 | repository as repositorymod, | |
42 | scmutil, |
|
42 | scmutil, | |
43 | sshpeer, |
|
43 | sshpeer, | |
44 | statichttprepo, |
|
44 | statichttprepo, | |
45 | ui as uimod, |
|
45 | ui as uimod, | |
46 | unionrepo, |
|
46 | unionrepo, | |
47 | url, |
|
47 | url, | |
48 | util, |
|
48 | util, | |
49 | verify as verifymod, |
|
49 | verify as verifymod, | |
50 | vfs as vfsmod, |
|
50 | vfs as vfsmod, | |
51 | ) |
|
51 | ) | |
52 |
|
52 | |||
53 | release = lock.release |
|
53 | release = lock.release | |
54 |
|
54 | |||
55 | # shared features |
|
55 | # shared features | |
56 | sharedbookmarks = 'bookmarks' |
|
56 | sharedbookmarks = 'bookmarks' | |
57 |
|
57 | |||
58 | def _local(path): |
|
58 | def _local(path): | |
59 | path = util.expandpath(util.urllocalpath(path)) |
|
59 | path = util.expandpath(util.urllocalpath(path)) | |
60 | return (os.path.isfile(path) and bundlerepo or localrepo) |
|
60 | return (os.path.isfile(path) and bundlerepo or localrepo) | |
61 |
|
61 | |||
62 | def addbranchrevs(lrepo, other, branches, revs): |
|
62 | def addbranchrevs(lrepo, other, branches, revs): | |
63 | peer = other.peer() # a courtesy to callers using a localrepo for other |
|
63 | peer = other.peer() # a courtesy to callers using a localrepo for other | |
64 | hashbranch, branches = branches |
|
64 | hashbranch, branches = branches | |
65 | if not hashbranch and not branches: |
|
65 | if not hashbranch and not branches: | |
66 | x = revs or None |
|
66 | x = revs or None | |
67 | if revs: |
|
67 | if revs: | |
68 | y = revs[0] |
|
68 | y = revs[0] | |
69 | else: |
|
69 | else: | |
70 | y = None |
|
70 | y = None | |
71 | return x, y |
|
71 | return x, y | |
72 | if revs: |
|
72 | if revs: | |
73 | revs = list(revs) |
|
73 | revs = list(revs) | |
74 | else: |
|
74 | else: | |
75 | revs = [] |
|
75 | revs = [] | |
76 |
|
76 | |||
77 | if not peer.capable('branchmap'): |
|
77 | if not peer.capable('branchmap'): | |
78 | if branches: |
|
78 | if branches: | |
79 | raise error.Abort(_("remote branch lookup not supported")) |
|
79 | raise error.Abort(_("remote branch lookup not supported")) | |
80 | revs.append(hashbranch) |
|
80 | revs.append(hashbranch) | |
81 | return revs, revs[0] |
|
81 | return revs, revs[0] | |
82 |
|
82 | |||
83 | with peer.commandexecutor() as e: |
|
83 | with peer.commandexecutor() as e: | |
84 | branchmap = e.callcommand('branchmap', {}).result() |
|
84 | branchmap = e.callcommand('branchmap', {}).result() | |
85 |
|
85 | |||
86 | def primary(branch): |
|
86 | def primary(branch): | |
87 | if branch == '.': |
|
87 | if branch == '.': | |
88 | if not lrepo: |
|
88 | if not lrepo: | |
89 | raise error.Abort(_("dirstate branch not accessible")) |
|
89 | raise error.Abort(_("dirstate branch not accessible")) | |
90 | branch = lrepo.dirstate.branch() |
|
90 | branch = lrepo.dirstate.branch() | |
91 | if branch in branchmap: |
|
91 | if branch in branchmap: | |
92 | revs.extend(node.hex(r) for r in reversed(branchmap[branch])) |
|
92 | revs.extend(node.hex(r) for r in reversed(branchmap[branch])) | |
93 | return True |
|
93 | return True | |
94 | else: |
|
94 | else: | |
95 | return False |
|
95 | return False | |
96 |
|
96 | |||
97 | for branch in branches: |
|
97 | for branch in branches: | |
98 | if not primary(branch): |
|
98 | if not primary(branch): | |
99 | raise error.RepoLookupError(_("unknown branch '%s'") % branch) |
|
99 | raise error.RepoLookupError(_("unknown branch '%s'") % branch) | |
100 | if hashbranch: |
|
100 | if hashbranch: | |
101 | if not primary(hashbranch): |
|
101 | if not primary(hashbranch): | |
102 | revs.append(hashbranch) |
|
102 | revs.append(hashbranch) | |
103 | return revs, revs[0] |
|
103 | return revs, revs[0] | |
104 |
|
104 | |||
105 | def parseurl(path, branches=None): |
|
105 | def parseurl(path, branches=None): | |
106 | '''parse url#branch, returning (url, (branch, branches))''' |
|
106 | '''parse url#branch, returning (url, (branch, branches))''' | |
107 |
|
107 | |||
108 | u = util.url(path) |
|
108 | u = util.url(path) | |
109 | branch = None |
|
109 | branch = None | |
110 | if u.fragment: |
|
110 | if u.fragment: | |
111 | branch = u.fragment |
|
111 | branch = u.fragment | |
112 | u.fragment = None |
|
112 | u.fragment = None | |
113 | return bytes(u), (branch, branches or []) |
|
113 | return bytes(u), (branch, branches or []) | |
114 |
|
114 | |||
115 | schemes = { |
|
115 | schemes = { | |
116 | 'bundle': bundlerepo, |
|
116 | 'bundle': bundlerepo, | |
117 | 'union': unionrepo, |
|
117 | 'union': unionrepo, | |
118 | 'file': _local, |
|
118 | 'file': _local, | |
119 | 'http': httppeer, |
|
119 | 'http': httppeer, | |
120 | 'https': httppeer, |
|
120 | 'https': httppeer, | |
121 | 'ssh': sshpeer, |
|
121 | 'ssh': sshpeer, | |
122 | 'static-http': statichttprepo, |
|
122 | 'static-http': statichttprepo, | |
123 | } |
|
123 | } | |
124 |
|
124 | |||
125 | def _peerlookup(path): |
|
125 | def _peerlookup(path): | |
126 | u = util.url(path) |
|
126 | u = util.url(path) | |
127 | scheme = u.scheme or 'file' |
|
127 | scheme = u.scheme or 'file' | |
128 | thing = schemes.get(scheme) or schemes['file'] |
|
128 | thing = schemes.get(scheme) or schemes['file'] | |
129 | try: |
|
129 | try: | |
130 | return thing(path) |
|
130 | return thing(path) | |
131 | except TypeError: |
|
131 | except TypeError: | |
132 | # we can't test callable(thing) because 'thing' can be an unloaded |
|
132 | # we can't test callable(thing) because 'thing' can be an unloaded | |
133 | # module that implements __call__ |
|
133 | # module that implements __call__ | |
134 | if not util.safehasattr(thing, 'instance'): |
|
134 | if not util.safehasattr(thing, 'instance'): | |
135 | raise |
|
135 | raise | |
136 | return thing |
|
136 | return thing | |
137 |
|
137 | |||
138 | def islocal(repo): |
|
138 | def islocal(repo): | |
139 | '''return true if repo (or path pointing to repo) is local''' |
|
139 | '''return true if repo (or path pointing to repo) is local''' | |
140 | if isinstance(repo, bytes): |
|
140 | if isinstance(repo, bytes): | |
141 | try: |
|
141 | try: | |
142 | return _peerlookup(repo).islocal(repo) |
|
142 | return _peerlookup(repo).islocal(repo) | |
143 | except AttributeError: |
|
143 | except AttributeError: | |
144 | return False |
|
144 | return False | |
145 | return repo.local() |
|
145 | return repo.local() | |
146 |
|
146 | |||
147 | def openpath(ui, path): |
|
147 | def openpath(ui, path): | |
148 | '''open path with open if local, url.open if remote''' |
|
148 | '''open path with open if local, url.open if remote''' | |
149 | pathurl = util.url(path, parsequery=False, parsefragment=False) |
|
149 | pathurl = util.url(path, parsequery=False, parsefragment=False) | |
150 | if pathurl.islocal(): |
|
150 | if pathurl.islocal(): | |
151 | return util.posixfile(pathurl.localpath(), 'rb') |
|
151 | return util.posixfile(pathurl.localpath(), 'rb') | |
152 | else: |
|
152 | else: | |
153 | return url.open(ui, path) |
|
153 | return url.open(ui, path) | |
154 |
|
154 | |||
155 | # a list of (ui, repo) functions called for wire peer initialization |
|
155 | # a list of (ui, repo) functions called for wire peer initialization | |
156 | wirepeersetupfuncs = [] |
|
156 | wirepeersetupfuncs = [] | |
157 |
|
157 | |||
158 | def _peerorrepo(ui, path, create=False, presetupfuncs=None, |
|
158 | def _peerorrepo(ui, path, create=False, presetupfuncs=None, | |
159 | intents=None, createopts=None): |
|
159 | intents=None, createopts=None): | |
160 | """return a repository object for the specified path""" |
|
160 | """return a repository object for the specified path""" | |
161 | obj = _peerlookup(path).instance(ui, path, create, intents=intents, |
|
161 | obj = _peerlookup(path).instance(ui, path, create, intents=intents, | |
162 | createopts=createopts) |
|
162 | createopts=createopts) | |
163 | ui = getattr(obj, "ui", ui) |
|
163 | ui = getattr(obj, "ui", ui) | |
164 | for f in presetupfuncs or []: |
|
164 | for f in presetupfuncs or []: | |
165 | f(ui, obj) |
|
165 | f(ui, obj) | |
166 | ui.log(b'extension', b'- executing reposetup hooks\n') |
|
166 | ui.log(b'extension', b'- executing reposetup hooks\n') | |
167 | with util.timedcm('all reposetup') as allreposetupstats: |
|
167 | with util.timedcm('all reposetup') as allreposetupstats: | |
168 | for name, module in extensions.extensions(ui): |
|
168 | for name, module in extensions.extensions(ui): | |
169 | ui.log(b'extension', b' - running reposetup for %s\n', name) |
|
169 | ui.log(b'extension', b' - running reposetup for %s\n', name) | |
170 | hook = getattr(module, 'reposetup', None) |
|
170 | hook = getattr(module, 'reposetup', None) | |
171 | if hook: |
|
171 | if hook: | |
172 | with util.timedcm('reposetup %r', name) as stats: |
|
172 | with util.timedcm('reposetup %r', name) as stats: | |
173 | hook(ui, obj) |
|
173 | hook(ui, obj) | |
174 | ui.log(b'extension', b' > reposetup for %s took %s\n', |
|
174 | ui.log(b'extension', b' > reposetup for %s took %s\n', | |
175 | name, stats) |
|
175 | name, stats) | |
176 | ui.log(b'extension', b'> all reposetup took %s\n', allreposetupstats) |
|
176 | ui.log(b'extension', b'> all reposetup took %s\n', allreposetupstats) | |
177 | if not obj.local(): |
|
177 | if not obj.local(): | |
178 | for f in wirepeersetupfuncs: |
|
178 | for f in wirepeersetupfuncs: | |
179 | f(ui, obj) |
|
179 | f(ui, obj) | |
180 | return obj |
|
180 | return obj | |
181 |
|
181 | |||
182 | def repository(ui, path='', create=False, presetupfuncs=None, intents=None, |
|
182 | def repository(ui, path='', create=False, presetupfuncs=None, intents=None, | |
183 | createopts=None): |
|
183 | createopts=None): | |
184 | """return a repository object for the specified path""" |
|
184 | """return a repository object for the specified path""" | |
185 | peer = _peerorrepo(ui, path, create, presetupfuncs=presetupfuncs, |
|
185 | peer = _peerorrepo(ui, path, create, presetupfuncs=presetupfuncs, | |
186 | intents=intents, createopts=createopts) |
|
186 | intents=intents, createopts=createopts) | |
187 | repo = peer.local() |
|
187 | repo = peer.local() | |
188 | if not repo: |
|
188 | if not repo: | |
189 | raise error.Abort(_("repository '%s' is not local") % |
|
189 | raise error.Abort(_("repository '%s' is not local") % | |
190 | (path or peer.url())) |
|
190 | (path or peer.url())) | |
191 | return repo.filtered('visible') |
|
191 | return repo.filtered('visible') | |
192 |
|
192 | |||
193 | def peer(uiorrepo, opts, path, create=False, intents=None, createopts=None): |
|
193 | def peer(uiorrepo, opts, path, create=False, intents=None, createopts=None): | |
194 | '''return a repository peer for the specified path''' |
|
194 | '''return a repository peer for the specified path''' | |
195 | rui = remoteui(uiorrepo, opts) |
|
195 | rui = remoteui(uiorrepo, opts) | |
196 | return _peerorrepo(rui, path, create, intents=intents, |
|
196 | return _peerorrepo(rui, path, create, intents=intents, | |
197 | createopts=createopts).peer() |
|
197 | createopts=createopts).peer() | |
198 |
|
198 | |||
199 | def defaultdest(source): |
|
199 | def defaultdest(source): | |
200 | '''return default destination of clone if none is given |
|
200 | '''return default destination of clone if none is given | |
201 |
|
201 | |||
202 | >>> defaultdest(b'foo') |
|
202 | >>> defaultdest(b'foo') | |
203 | 'foo' |
|
203 | 'foo' | |
204 | >>> defaultdest(b'/foo/bar') |
|
204 | >>> defaultdest(b'/foo/bar') | |
205 | 'bar' |
|
205 | 'bar' | |
206 | >>> defaultdest(b'/') |
|
206 | >>> defaultdest(b'/') | |
207 | '' |
|
207 | '' | |
208 | >>> defaultdest(b'') |
|
208 | >>> defaultdest(b'') | |
209 | '' |
|
209 | '' | |
210 | >>> defaultdest(b'http://example.org/') |
|
210 | >>> defaultdest(b'http://example.org/') | |
211 | '' |
|
211 | '' | |
212 | >>> defaultdest(b'http://example.org/foo/') |
|
212 | >>> defaultdest(b'http://example.org/foo/') | |
213 | 'foo' |
|
213 | 'foo' | |
214 | ''' |
|
214 | ''' | |
215 | path = util.url(source).path |
|
215 | path = util.url(source).path | |
216 | if not path: |
|
216 | if not path: | |
217 | return '' |
|
217 | return '' | |
218 | return os.path.basename(os.path.normpath(path)) |
|
218 | return os.path.basename(os.path.normpath(path)) | |
219 |
|
219 | |||
220 | def sharedreposource(repo): |
|
220 | def sharedreposource(repo): | |
221 | """Returns repository object for source repository of a shared repo. |
|
221 | """Returns repository object for source repository of a shared repo. | |
222 |
|
222 | |||
223 | If repo is not a shared repository, returns None. |
|
223 | If repo is not a shared repository, returns None. | |
224 | """ |
|
224 | """ | |
225 | if repo.sharedpath == repo.path: |
|
225 | if repo.sharedpath == repo.path: | |
226 | return None |
|
226 | return None | |
227 |
|
227 | |||
228 | if util.safehasattr(repo, 'srcrepo') and repo.srcrepo: |
|
228 | if util.safehasattr(repo, 'srcrepo') and repo.srcrepo: | |
229 | return repo.srcrepo |
|
229 | return repo.srcrepo | |
230 |
|
230 | |||
231 | # the sharedpath always ends in the .hg; we want the path to the repo |
|
231 | # the sharedpath always ends in the .hg; we want the path to the repo | |
232 | source = repo.vfs.split(repo.sharedpath)[0] |
|
232 | source = repo.vfs.split(repo.sharedpath)[0] | |
233 | srcurl, branches = parseurl(source) |
|
233 | srcurl, branches = parseurl(source) | |
234 | srcrepo = repository(repo.ui, srcurl) |
|
234 | srcrepo = repository(repo.ui, srcurl) | |
235 | repo.srcrepo = srcrepo |
|
235 | repo.srcrepo = srcrepo | |
236 | return srcrepo |
|
236 | return srcrepo | |
237 |
|
237 | |||
238 | def share(ui, source, dest=None, update=True, bookmarks=True, defaultpath=None, |
|
238 | def share(ui, source, dest=None, update=True, bookmarks=True, defaultpath=None, | |
239 | relative=False): |
|
239 | relative=False): | |
240 | '''create a shared repository''' |
|
240 | '''create a shared repository''' | |
241 |
|
241 | |||
242 | if not islocal(source): |
|
242 | if not islocal(source): | |
243 | raise error.Abort(_('can only share local repositories')) |
|
243 | raise error.Abort(_('can only share local repositories')) | |
244 |
|
244 | |||
245 | if not dest: |
|
245 | if not dest: | |
246 | dest = defaultdest(source) |
|
246 | dest = defaultdest(source) | |
247 | else: |
|
247 | else: | |
248 | dest = ui.expandpath(dest) |
|
248 | dest = ui.expandpath(dest) | |
249 |
|
249 | |||
250 | if isinstance(source, bytes): |
|
250 | if isinstance(source, bytes): | |
251 | origsource = ui.expandpath(source) |
|
251 | origsource = ui.expandpath(source) | |
252 | source, branches = parseurl(origsource) |
|
252 | source, branches = parseurl(origsource) | |
253 | srcrepo = repository(ui, source) |
|
253 | srcrepo = repository(ui, source) | |
254 | rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None) |
|
254 | rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None) | |
255 | else: |
|
255 | else: | |
256 | srcrepo = source.local() |
|
256 | srcrepo = source.local() | |
257 | checkout = None |
|
257 | checkout = None | |
258 |
|
258 | |||
259 | shareditems = set() |
|
259 | shareditems = set() | |
260 | if bookmarks: |
|
260 | if bookmarks: | |
261 | shareditems.add(sharedbookmarks) |
|
261 | shareditems.add(sharedbookmarks) | |
262 |
|
262 | |||
263 | r = repository(ui, dest, create=True, createopts={ |
|
263 | r = repository(ui, dest, create=True, createopts={ | |
264 | 'sharedrepo': srcrepo, |
|
264 | 'sharedrepo': srcrepo, | |
265 | 'sharedrelative': relative, |
|
265 | 'sharedrelative': relative, | |
266 | 'shareditems': shareditems, |
|
266 | 'shareditems': shareditems, | |
267 | }) |
|
267 | }) | |
268 |
|
268 | |||
269 | postshare(srcrepo, r, defaultpath=defaultpath) |
|
269 | postshare(srcrepo, r, defaultpath=defaultpath) | |
270 | r = repository(ui, dest) |
|
270 | r = repository(ui, dest) | |
271 | _postshareupdate(r, update, checkout=checkout) |
|
271 | _postshareupdate(r, update, checkout=checkout) | |
272 | return r |
|
272 | return r | |
273 |
|
273 | |||
274 | def unshare(ui, repo): |
|
274 | def unshare(ui, repo): | |
275 | """convert a shared repository to a normal one |
|
275 | """convert a shared repository to a normal one | |
276 |
|
276 | |||
277 | Copy the store data to the repo and remove the sharedpath data. |
|
277 | Copy the store data to the repo and remove the sharedpath data. | |
278 |
|
278 | |||
279 | Returns a new repository object representing the unshared repository. |
|
279 | Returns a new repository object representing the unshared repository. | |
280 |
|
280 | |||
281 | The passed repository object is not usable after this function is |
|
281 | The passed repository object is not usable after this function is | |
282 | called. |
|
282 | called. | |
283 | """ |
|
283 | """ | |
284 |
|
284 | |||
285 | destlock = lock = None |
|
285 | destlock = lock = None | |
286 | lock = repo.lock() |
|
286 | lock = repo.lock() | |
287 | try: |
|
287 | try: | |
288 | # we use locks here because if we race with commit, we |
|
288 | # we use locks here because if we race with commit, we | |
289 | # can end up with extra data in the cloned revlogs that's |
|
289 | # can end up with extra data in the cloned revlogs that's | |
290 | # not pointed to by changesets, thus causing verify to |
|
290 | # not pointed to by changesets, thus causing verify to | |
291 | # fail |
|
291 | # fail | |
292 |
|
292 | |||
293 | destlock = copystore(ui, repo, repo.path) |
|
293 | destlock = copystore(ui, repo, repo.path) | |
294 |
|
294 | |||
295 | sharefile = repo.vfs.join('sharedpath') |
|
295 | sharefile = repo.vfs.join('sharedpath') | |
296 | util.rename(sharefile, sharefile + '.old') |
|
296 | util.rename(sharefile, sharefile + '.old') | |
297 |
|
297 | |||
298 | repo.requirements.discard('shared') |
|
298 | repo.requirements.discard('shared') | |
299 | repo.requirements.discard('relshared') |
|
299 | repo.requirements.discard('relshared') | |
300 | repo._writerequirements() |
|
300 | repo._writerequirements() | |
301 | finally: |
|
301 | finally: | |
302 | destlock and destlock.release() |
|
302 | destlock and destlock.release() | |
303 | lock and lock.release() |
|
303 | lock and lock.release() | |
304 |
|
304 | |||
305 | # Removing share changes some fundamental properties of the repo instance. |
|
305 | # Removing share changes some fundamental properties of the repo instance. | |
306 | # So we instantiate a new repo object and operate on it rather than |
|
306 | # So we instantiate a new repo object and operate on it rather than | |
307 | # try to keep the existing repo usable. |
|
307 | # try to keep the existing repo usable. | |
308 | newrepo = repository(repo.baseui, repo.root, create=False) |
|
308 | newrepo = repository(repo.baseui, repo.root, create=False) | |
309 |
|
309 | |||
310 | # TODO: figure out how to access subrepos that exist, but were previously |
|
310 | # TODO: figure out how to access subrepos that exist, but were previously | |
311 | # removed from .hgsub |
|
311 | # removed from .hgsub | |
312 | c = newrepo['.'] |
|
312 | c = newrepo['.'] | |
313 | subs = c.substate |
|
313 | subs = c.substate | |
314 | for s in sorted(subs): |
|
314 | for s in sorted(subs): | |
315 | c.sub(s).unshare() |
|
315 | c.sub(s).unshare() | |
316 |
|
316 | |||
317 | localrepo.poisonrepository(repo) |
|
317 | localrepo.poisonrepository(repo) | |
318 |
|
318 | |||
319 | return newrepo |
|
319 | return newrepo | |
320 |
|
320 | |||
321 | def postshare(sourcerepo, destrepo, defaultpath=None): |
|
321 | def postshare(sourcerepo, destrepo, defaultpath=None): | |
322 | """Called after a new shared repo is created. |
|
322 | """Called after a new shared repo is created. | |
323 |
|
323 | |||
324 | The new repo only has a requirements file and pointer to the source. |
|
324 | The new repo only has a requirements file and pointer to the source. | |
325 | This function configures additional shared data. |
|
325 | This function configures additional shared data. | |
326 |
|
326 | |||
327 | Extensions can wrap this function and write additional entries to |
|
327 | Extensions can wrap this function and write additional entries to | |
328 | destrepo/.hg/shared to indicate additional pieces of data to be shared. |
|
328 | destrepo/.hg/shared to indicate additional pieces of data to be shared. | |
329 | """ |
|
329 | """ | |
330 | default = defaultpath or sourcerepo.ui.config('paths', 'default') |
|
330 | default = defaultpath or sourcerepo.ui.config('paths', 'default') | |
331 | if default: |
|
331 | if default: | |
332 | template = ('[paths]\n' |
|
332 | template = ('[paths]\n' | |
333 | 'default = %s\n') |
|
333 | 'default = %s\n') | |
334 | destrepo.vfs.write('hgrc', util.tonativeeol(template % default)) |
|
334 | destrepo.vfs.write('hgrc', util.tonativeeol(template % default)) | |
335 | if repositorymod.NARROW_REQUIREMENT in sourcerepo.requirements: |
|
335 | if repositorymod.NARROW_REQUIREMENT in sourcerepo.requirements: | |
336 | with destrepo.wlock(): |
|
336 | with destrepo.wlock(): | |
337 |
narrowspec.copytoworkingcopy(destrepo |
|
337 | narrowspec.copytoworkingcopy(destrepo) | |
338 |
|
338 | |||
339 | def _postshareupdate(repo, update, checkout=None): |
|
339 | def _postshareupdate(repo, update, checkout=None): | |
340 | """Maybe perform a working directory update after a shared repo is created. |
|
340 | """Maybe perform a working directory update after a shared repo is created. | |
341 |
|
341 | |||
342 | ``update`` can be a boolean or a revision to update to. |
|
342 | ``update`` can be a boolean or a revision to update to. | |
343 | """ |
|
343 | """ | |
344 | if not update: |
|
344 | if not update: | |
345 | return |
|
345 | return | |
346 |
|
346 | |||
347 | repo.ui.status(_("updating working directory\n")) |
|
347 | repo.ui.status(_("updating working directory\n")) | |
348 | if update is not True: |
|
348 | if update is not True: | |
349 | checkout = update |
|
349 | checkout = update | |
350 | for test in (checkout, 'default', 'tip'): |
|
350 | for test in (checkout, 'default', 'tip'): | |
351 | if test is None: |
|
351 | if test is None: | |
352 | continue |
|
352 | continue | |
353 | try: |
|
353 | try: | |
354 | uprev = repo.lookup(test) |
|
354 | uprev = repo.lookup(test) | |
355 | break |
|
355 | break | |
356 | except error.RepoLookupError: |
|
356 | except error.RepoLookupError: | |
357 | continue |
|
357 | continue | |
358 | _update(repo, uprev) |
|
358 | _update(repo, uprev) | |
359 |
|
359 | |||
360 | def copystore(ui, srcrepo, destpath): |
|
360 | def copystore(ui, srcrepo, destpath): | |
361 | '''copy files from store of srcrepo in destpath |
|
361 | '''copy files from store of srcrepo in destpath | |
362 |
|
362 | |||
363 | returns destlock |
|
363 | returns destlock | |
364 | ''' |
|
364 | ''' | |
365 | destlock = None |
|
365 | destlock = None | |
366 | try: |
|
366 | try: | |
367 | hardlink = None |
|
367 | hardlink = None | |
368 | topic = _('linking') if hardlink else _('copying') |
|
368 | topic = _('linking') if hardlink else _('copying') | |
369 | with ui.makeprogress(topic, unit=_('files')) as progress: |
|
369 | with ui.makeprogress(topic, unit=_('files')) as progress: | |
370 | num = 0 |
|
370 | num = 0 | |
371 | srcpublishing = srcrepo.publishing() |
|
371 | srcpublishing = srcrepo.publishing() | |
372 | srcvfs = vfsmod.vfs(srcrepo.sharedpath) |
|
372 | srcvfs = vfsmod.vfs(srcrepo.sharedpath) | |
373 | dstvfs = vfsmod.vfs(destpath) |
|
373 | dstvfs = vfsmod.vfs(destpath) | |
374 | for f in srcrepo.store.copylist(): |
|
374 | for f in srcrepo.store.copylist(): | |
375 | if srcpublishing and f.endswith('phaseroots'): |
|
375 | if srcpublishing and f.endswith('phaseroots'): | |
376 | continue |
|
376 | continue | |
377 | dstbase = os.path.dirname(f) |
|
377 | dstbase = os.path.dirname(f) | |
378 | if dstbase and not dstvfs.exists(dstbase): |
|
378 | if dstbase and not dstvfs.exists(dstbase): | |
379 | dstvfs.mkdir(dstbase) |
|
379 | dstvfs.mkdir(dstbase) | |
380 | if srcvfs.exists(f): |
|
380 | if srcvfs.exists(f): | |
381 | if f.endswith('data'): |
|
381 | if f.endswith('data'): | |
382 | # 'dstbase' may be empty (e.g. revlog format 0) |
|
382 | # 'dstbase' may be empty (e.g. revlog format 0) | |
383 | lockfile = os.path.join(dstbase, "lock") |
|
383 | lockfile = os.path.join(dstbase, "lock") | |
384 | # lock to avoid premature writing to the target |
|
384 | # lock to avoid premature writing to the target | |
385 | destlock = lock.lock(dstvfs, lockfile) |
|
385 | destlock = lock.lock(dstvfs, lockfile) | |
386 | hardlink, n = util.copyfiles(srcvfs.join(f), dstvfs.join(f), |
|
386 | hardlink, n = util.copyfiles(srcvfs.join(f), dstvfs.join(f), | |
387 | hardlink, progress) |
|
387 | hardlink, progress) | |
388 | num += n |
|
388 | num += n | |
389 | if hardlink: |
|
389 | if hardlink: | |
390 | ui.debug("linked %d files\n" % num) |
|
390 | ui.debug("linked %d files\n" % num) | |
391 | else: |
|
391 | else: | |
392 | ui.debug("copied %d files\n" % num) |
|
392 | ui.debug("copied %d files\n" % num) | |
393 | return destlock |
|
393 | return destlock | |
394 | except: # re-raises |
|
394 | except: # re-raises | |
395 | release(destlock) |
|
395 | release(destlock) | |
396 | raise |
|
396 | raise | |
397 |
|
397 | |||
398 | def clonewithshare(ui, peeropts, sharepath, source, srcpeer, dest, pull=False, |
|
398 | def clonewithshare(ui, peeropts, sharepath, source, srcpeer, dest, pull=False, | |
399 | rev=None, update=True, stream=False): |
|
399 | rev=None, update=True, stream=False): | |
400 | """Perform a clone using a shared repo. |
|
400 | """Perform a clone using a shared repo. | |
401 |
|
401 | |||
402 | The store for the repository will be located at <sharepath>/.hg. The |
|
402 | The store for the repository will be located at <sharepath>/.hg. The | |
403 | specified revisions will be cloned or pulled from "source". A shared repo |
|
403 | specified revisions will be cloned or pulled from "source". A shared repo | |
404 | will be created at "dest" and a working copy will be created if "update" is |
|
404 | will be created at "dest" and a working copy will be created if "update" is | |
405 | True. |
|
405 | True. | |
406 | """ |
|
406 | """ | |
407 | revs = None |
|
407 | revs = None | |
408 | if rev: |
|
408 | if rev: | |
409 | if not srcpeer.capable('lookup'): |
|
409 | if not srcpeer.capable('lookup'): | |
410 | raise error.Abort(_("src repository does not support " |
|
410 | raise error.Abort(_("src repository does not support " | |
411 | "revision lookup and so doesn't " |
|
411 | "revision lookup and so doesn't " | |
412 | "support clone by revision")) |
|
412 | "support clone by revision")) | |
413 |
|
413 | |||
414 | # TODO this is batchable. |
|
414 | # TODO this is batchable. | |
415 | remoterevs = [] |
|
415 | remoterevs = [] | |
416 | for r in rev: |
|
416 | for r in rev: | |
417 | with srcpeer.commandexecutor() as e: |
|
417 | with srcpeer.commandexecutor() as e: | |
418 | remoterevs.append(e.callcommand('lookup', { |
|
418 | remoterevs.append(e.callcommand('lookup', { | |
419 | 'key': r, |
|
419 | 'key': r, | |
420 | }).result()) |
|
420 | }).result()) | |
421 | revs = remoterevs |
|
421 | revs = remoterevs | |
422 |
|
422 | |||
423 | # Obtain a lock before checking for or cloning the pooled repo otherwise |
|
423 | # Obtain a lock before checking for or cloning the pooled repo otherwise | |
424 | # 2 clients may race creating or populating it. |
|
424 | # 2 clients may race creating or populating it. | |
425 | pooldir = os.path.dirname(sharepath) |
|
425 | pooldir = os.path.dirname(sharepath) | |
426 | # lock class requires the directory to exist. |
|
426 | # lock class requires the directory to exist. | |
427 | try: |
|
427 | try: | |
428 | util.makedir(pooldir, False) |
|
428 | util.makedir(pooldir, False) | |
429 | except OSError as e: |
|
429 | except OSError as e: | |
430 | if e.errno != errno.EEXIST: |
|
430 | if e.errno != errno.EEXIST: | |
431 | raise |
|
431 | raise | |
432 |
|
432 | |||
433 | poolvfs = vfsmod.vfs(pooldir) |
|
433 | poolvfs = vfsmod.vfs(pooldir) | |
434 | basename = os.path.basename(sharepath) |
|
434 | basename = os.path.basename(sharepath) | |
435 |
|
435 | |||
436 | with lock.lock(poolvfs, '%s.lock' % basename): |
|
436 | with lock.lock(poolvfs, '%s.lock' % basename): | |
437 | if os.path.exists(sharepath): |
|
437 | if os.path.exists(sharepath): | |
438 | ui.status(_('(sharing from existing pooled repository %s)\n') % |
|
438 | ui.status(_('(sharing from existing pooled repository %s)\n') % | |
439 | basename) |
|
439 | basename) | |
440 | else: |
|
440 | else: | |
441 | ui.status(_('(sharing from new pooled repository %s)\n') % basename) |
|
441 | ui.status(_('(sharing from new pooled repository %s)\n') % basename) | |
442 | # Always use pull mode because hardlinks in share mode don't work |
|
442 | # Always use pull mode because hardlinks in share mode don't work | |
443 | # well. Never update because working copies aren't necessary in |
|
443 | # well. Never update because working copies aren't necessary in | |
444 | # share mode. |
|
444 | # share mode. | |
445 | clone(ui, peeropts, source, dest=sharepath, pull=True, |
|
445 | clone(ui, peeropts, source, dest=sharepath, pull=True, | |
446 | revs=rev, update=False, stream=stream) |
|
446 | revs=rev, update=False, stream=stream) | |
447 |
|
447 | |||
448 | # Resolve the value to put in [paths] section for the source. |
|
448 | # Resolve the value to put in [paths] section for the source. | |
449 | if islocal(source): |
|
449 | if islocal(source): | |
450 | defaultpath = os.path.abspath(util.urllocalpath(source)) |
|
450 | defaultpath = os.path.abspath(util.urllocalpath(source)) | |
451 | else: |
|
451 | else: | |
452 | defaultpath = source |
|
452 | defaultpath = source | |
453 |
|
453 | |||
454 | sharerepo = repository(ui, path=sharepath) |
|
454 | sharerepo = repository(ui, path=sharepath) | |
455 | destrepo = share(ui, sharerepo, dest=dest, update=False, bookmarks=False, |
|
455 | destrepo = share(ui, sharerepo, dest=dest, update=False, bookmarks=False, | |
456 | defaultpath=defaultpath) |
|
456 | defaultpath=defaultpath) | |
457 |
|
457 | |||
458 | # We need to perform a pull against the dest repo to fetch bookmarks |
|
458 | # We need to perform a pull against the dest repo to fetch bookmarks | |
459 | # and other non-store data that isn't shared by default. In the case of |
|
459 | # and other non-store data that isn't shared by default. In the case of | |
460 | # non-existing shared repo, this means we pull from the remote twice. This |
|
460 | # non-existing shared repo, this means we pull from the remote twice. This | |
461 | # is a bit weird. But at the time it was implemented, there wasn't an easy |
|
461 | # is a bit weird. But at the time it was implemented, there wasn't an easy | |
462 | # way to pull just non-changegroup data. |
|
462 | # way to pull just non-changegroup data. | |
463 | exchange.pull(destrepo, srcpeer, heads=revs) |
|
463 | exchange.pull(destrepo, srcpeer, heads=revs) | |
464 |
|
464 | |||
465 | _postshareupdate(destrepo, update) |
|
465 | _postshareupdate(destrepo, update) | |
466 |
|
466 | |||
467 | return srcpeer, peer(ui, peeropts, dest) |
|
467 | return srcpeer, peer(ui, peeropts, dest) | |
468 |
|
468 | |||
469 | # Recomputing branch cache might be slow on big repos, |
|
469 | # Recomputing branch cache might be slow on big repos, | |
470 | # so just copy it |
|
470 | # so just copy it | |
471 | def _copycache(srcrepo, dstcachedir, fname): |
|
471 | def _copycache(srcrepo, dstcachedir, fname): | |
472 | """copy a cache from srcrepo to destcachedir (if it exists)""" |
|
472 | """copy a cache from srcrepo to destcachedir (if it exists)""" | |
473 | srcbranchcache = srcrepo.vfs.join('cache/%s' % fname) |
|
473 | srcbranchcache = srcrepo.vfs.join('cache/%s' % fname) | |
474 | dstbranchcache = os.path.join(dstcachedir, fname) |
|
474 | dstbranchcache = os.path.join(dstcachedir, fname) | |
475 | if os.path.exists(srcbranchcache): |
|
475 | if os.path.exists(srcbranchcache): | |
476 | if not os.path.exists(dstcachedir): |
|
476 | if not os.path.exists(dstcachedir): | |
477 | os.mkdir(dstcachedir) |
|
477 | os.mkdir(dstcachedir) | |
478 | util.copyfile(srcbranchcache, dstbranchcache) |
|
478 | util.copyfile(srcbranchcache, dstbranchcache) | |
479 |
|
479 | |||
480 | def clone(ui, peeropts, source, dest=None, pull=False, revs=None, |
|
480 | def clone(ui, peeropts, source, dest=None, pull=False, revs=None, | |
481 | update=True, stream=False, branch=None, shareopts=None, |
|
481 | update=True, stream=False, branch=None, shareopts=None, | |
482 | storeincludepats=None, storeexcludepats=None, depth=None): |
|
482 | storeincludepats=None, storeexcludepats=None, depth=None): | |
483 | """Make a copy of an existing repository. |
|
483 | """Make a copy of an existing repository. | |
484 |
|
484 | |||
485 | Create a copy of an existing repository in a new directory. The |
|
485 | Create a copy of an existing repository in a new directory. The | |
486 | source and destination are URLs, as passed to the repository |
|
486 | source and destination are URLs, as passed to the repository | |
487 | function. Returns a pair of repository peers, the source and |
|
487 | function. Returns a pair of repository peers, the source and | |
488 | newly created destination. |
|
488 | newly created destination. | |
489 |
|
489 | |||
490 | The location of the source is added to the new repository's |
|
490 | The location of the source is added to the new repository's | |
491 | .hg/hgrc file, as the default to be used for future pulls and |
|
491 | .hg/hgrc file, as the default to be used for future pulls and | |
492 | pushes. |
|
492 | pushes. | |
493 |
|
493 | |||
494 | If an exception is raised, the partly cloned/updated destination |
|
494 | If an exception is raised, the partly cloned/updated destination | |
495 | repository will be deleted. |
|
495 | repository will be deleted. | |
496 |
|
496 | |||
497 | Arguments: |
|
497 | Arguments: | |
498 |
|
498 | |||
499 | source: repository object or URL |
|
499 | source: repository object or URL | |
500 |
|
500 | |||
501 | dest: URL of destination repository to create (defaults to base |
|
501 | dest: URL of destination repository to create (defaults to base | |
502 | name of source repository) |
|
502 | name of source repository) | |
503 |
|
503 | |||
504 | pull: always pull from source repository, even in local case or if the |
|
504 | pull: always pull from source repository, even in local case or if the | |
505 | server prefers streaming |
|
505 | server prefers streaming | |
506 |
|
506 | |||
507 | stream: stream raw data uncompressed from repository (fast over |
|
507 | stream: stream raw data uncompressed from repository (fast over | |
508 | LAN, slow over WAN) |
|
508 | LAN, slow over WAN) | |
509 |
|
509 | |||
510 | revs: revision to clone up to (implies pull=True) |
|
510 | revs: revision to clone up to (implies pull=True) | |
511 |
|
511 | |||
512 | update: update working directory after clone completes, if |
|
512 | update: update working directory after clone completes, if | |
513 | destination is local repository (True means update to default rev, |
|
513 | destination is local repository (True means update to default rev, | |
514 | anything else is treated as a revision) |
|
514 | anything else is treated as a revision) | |
515 |
|
515 | |||
516 | branch: branches to clone |
|
516 | branch: branches to clone | |
517 |
|
517 | |||
518 | shareopts: dict of options to control auto sharing behavior. The "pool" key |
|
518 | shareopts: dict of options to control auto sharing behavior. The "pool" key | |
519 | activates auto sharing mode and defines the directory for stores. The |
|
519 | activates auto sharing mode and defines the directory for stores. The | |
520 | "mode" key determines how to construct the directory name of the shared |
|
520 | "mode" key determines how to construct the directory name of the shared | |
521 | repository. "identity" means the name is derived from the node of the first |
|
521 | repository. "identity" means the name is derived from the node of the first | |
522 | changeset in the repository. "remote" means the name is derived from the |
|
522 | changeset in the repository. "remote" means the name is derived from the | |
523 | remote's path/URL. Defaults to "identity." |
|
523 | remote's path/URL. Defaults to "identity." | |
524 |
|
524 | |||
525 | storeincludepats and storeexcludepats: sets of file patterns to include and |
|
525 | storeincludepats and storeexcludepats: sets of file patterns to include and | |
526 | exclude in the repository copy, respectively. If not defined, all files |
|
526 | exclude in the repository copy, respectively. If not defined, all files | |
527 | will be included (a "full" clone). Otherwise a "narrow" clone containing |
|
527 | will be included (a "full" clone). Otherwise a "narrow" clone containing | |
528 | only the requested files will be performed. If ``storeincludepats`` is not |
|
528 | only the requested files will be performed. If ``storeincludepats`` is not | |
529 | defined but ``storeexcludepats`` is, ``storeincludepats`` is assumed to be |
|
529 | defined but ``storeexcludepats`` is, ``storeincludepats`` is assumed to be | |
530 | ``path:.``. If both are empty sets, no files will be cloned. |
|
530 | ``path:.``. If both are empty sets, no files will be cloned. | |
531 | """ |
|
531 | """ | |
532 |
|
532 | |||
533 | if isinstance(source, bytes): |
|
533 | if isinstance(source, bytes): | |
534 | origsource = ui.expandpath(source) |
|
534 | origsource = ui.expandpath(source) | |
535 | source, branches = parseurl(origsource, branch) |
|
535 | source, branches = parseurl(origsource, branch) | |
536 | srcpeer = peer(ui, peeropts, source) |
|
536 | srcpeer = peer(ui, peeropts, source) | |
537 | else: |
|
537 | else: | |
538 | srcpeer = source.peer() # in case we were called with a localrepo |
|
538 | srcpeer = source.peer() # in case we were called with a localrepo | |
539 | branches = (None, branch or []) |
|
539 | branches = (None, branch or []) | |
540 | origsource = source = srcpeer.url() |
|
540 | origsource = source = srcpeer.url() | |
541 | revs, checkout = addbranchrevs(srcpeer, srcpeer, branches, revs) |
|
541 | revs, checkout = addbranchrevs(srcpeer, srcpeer, branches, revs) | |
542 |
|
542 | |||
543 | if dest is None: |
|
543 | if dest is None: | |
544 | dest = defaultdest(source) |
|
544 | dest = defaultdest(source) | |
545 | if dest: |
|
545 | if dest: | |
546 | ui.status(_("destination directory: %s\n") % dest) |
|
546 | ui.status(_("destination directory: %s\n") % dest) | |
547 | else: |
|
547 | else: | |
548 | dest = ui.expandpath(dest) |
|
548 | dest = ui.expandpath(dest) | |
549 |
|
549 | |||
550 | dest = util.urllocalpath(dest) |
|
550 | dest = util.urllocalpath(dest) | |
551 | source = util.urllocalpath(source) |
|
551 | source = util.urllocalpath(source) | |
552 |
|
552 | |||
553 | if not dest: |
|
553 | if not dest: | |
554 | raise error.Abort(_("empty destination path is not valid")) |
|
554 | raise error.Abort(_("empty destination path is not valid")) | |
555 |
|
555 | |||
556 | destvfs = vfsmod.vfs(dest, expandpath=True) |
|
556 | destvfs = vfsmod.vfs(dest, expandpath=True) | |
557 | if destvfs.lexists(): |
|
557 | if destvfs.lexists(): | |
558 | if not destvfs.isdir(): |
|
558 | if not destvfs.isdir(): | |
559 | raise error.Abort(_("destination '%s' already exists") % dest) |
|
559 | raise error.Abort(_("destination '%s' already exists") % dest) | |
560 | elif destvfs.listdir(): |
|
560 | elif destvfs.listdir(): | |
561 | raise error.Abort(_("destination '%s' is not empty") % dest) |
|
561 | raise error.Abort(_("destination '%s' is not empty") % dest) | |
562 |
|
562 | |||
563 | createopts = {} |
|
563 | createopts = {} | |
564 | narrow = False |
|
564 | narrow = False | |
565 |
|
565 | |||
566 | if storeincludepats is not None: |
|
566 | if storeincludepats is not None: | |
567 | narrowspec.validatepatterns(storeincludepats) |
|
567 | narrowspec.validatepatterns(storeincludepats) | |
568 | narrow = True |
|
568 | narrow = True | |
569 |
|
569 | |||
570 | if storeexcludepats is not None: |
|
570 | if storeexcludepats is not None: | |
571 | narrowspec.validatepatterns(storeexcludepats) |
|
571 | narrowspec.validatepatterns(storeexcludepats) | |
572 | narrow = True |
|
572 | narrow = True | |
573 |
|
573 | |||
574 | if narrow: |
|
574 | if narrow: | |
575 | # Include everything by default if only exclusion patterns defined. |
|
575 | # Include everything by default if only exclusion patterns defined. | |
576 | if storeexcludepats and not storeincludepats: |
|
576 | if storeexcludepats and not storeincludepats: | |
577 | storeincludepats = {'path:.'} |
|
577 | storeincludepats = {'path:.'} | |
578 |
|
578 | |||
579 | createopts['narrowfiles'] = True |
|
579 | createopts['narrowfiles'] = True | |
580 |
|
580 | |||
581 | if depth: |
|
581 | if depth: | |
582 | createopts['shallowfilestore'] = True |
|
582 | createopts['shallowfilestore'] = True | |
583 |
|
583 | |||
584 | if srcpeer.capable(b'lfs-serve'): |
|
584 | if srcpeer.capable(b'lfs-serve'): | |
585 | # Repository creation honors the config if it disabled the extension, so |
|
585 | # Repository creation honors the config if it disabled the extension, so | |
586 | # we can't just announce that lfs will be enabled. This check avoids |
|
586 | # we can't just announce that lfs will be enabled. This check avoids | |
587 | # saying that lfs will be enabled, and then saying it's an unknown |
|
587 | # saying that lfs will be enabled, and then saying it's an unknown | |
588 | # feature. The lfs creation option is set in either case so that a |
|
588 | # feature. The lfs creation option is set in either case so that a | |
589 | # requirement is added. If the extension is explicitly disabled but the |
|
589 | # requirement is added. If the extension is explicitly disabled but the | |
590 | # requirement is set, the clone aborts early, before transferring any |
|
590 | # requirement is set, the clone aborts early, before transferring any | |
591 | # data. |
|
591 | # data. | |
592 | createopts['lfs'] = True |
|
592 | createopts['lfs'] = True | |
593 |
|
593 | |||
594 | if extensions.disabledext('lfs'): |
|
594 | if extensions.disabledext('lfs'): | |
595 | ui.status(_('(remote is using large file support (lfs), but it is ' |
|
595 | ui.status(_('(remote is using large file support (lfs), but it is ' | |
596 | 'explicitly disabled in the local configuration)\n')) |
|
596 | 'explicitly disabled in the local configuration)\n')) | |
597 | else: |
|
597 | else: | |
598 | ui.status(_('(remote is using large file support (lfs); lfs will ' |
|
598 | ui.status(_('(remote is using large file support (lfs); lfs will ' | |
599 | 'be enabled for this repository)\n')) |
|
599 | 'be enabled for this repository)\n')) | |
600 |
|
600 | |||
601 | shareopts = shareopts or {} |
|
601 | shareopts = shareopts or {} | |
602 | sharepool = shareopts.get('pool') |
|
602 | sharepool = shareopts.get('pool') | |
603 | sharenamemode = shareopts.get('mode') |
|
603 | sharenamemode = shareopts.get('mode') | |
604 | if sharepool and islocal(dest): |
|
604 | if sharepool and islocal(dest): | |
605 | sharepath = None |
|
605 | sharepath = None | |
606 | if sharenamemode == 'identity': |
|
606 | if sharenamemode == 'identity': | |
607 | # Resolve the name from the initial changeset in the remote |
|
607 | # Resolve the name from the initial changeset in the remote | |
608 | # repository. This returns nullid when the remote is empty. It |
|
608 | # repository. This returns nullid when the remote is empty. It | |
609 | # raises RepoLookupError if revision 0 is filtered or otherwise |
|
609 | # raises RepoLookupError if revision 0 is filtered or otherwise | |
610 | # not available. If we fail to resolve, sharing is not enabled. |
|
610 | # not available. If we fail to resolve, sharing is not enabled. | |
611 | try: |
|
611 | try: | |
612 | with srcpeer.commandexecutor() as e: |
|
612 | with srcpeer.commandexecutor() as e: | |
613 | rootnode = e.callcommand('lookup', { |
|
613 | rootnode = e.callcommand('lookup', { | |
614 | 'key': '0', |
|
614 | 'key': '0', | |
615 | }).result() |
|
615 | }).result() | |
616 |
|
616 | |||
617 | if rootnode != node.nullid: |
|
617 | if rootnode != node.nullid: | |
618 | sharepath = os.path.join(sharepool, node.hex(rootnode)) |
|
618 | sharepath = os.path.join(sharepool, node.hex(rootnode)) | |
619 | else: |
|
619 | else: | |
620 | ui.status(_('(not using pooled storage: ' |
|
620 | ui.status(_('(not using pooled storage: ' | |
621 | 'remote appears to be empty)\n')) |
|
621 | 'remote appears to be empty)\n')) | |
622 | except error.RepoLookupError: |
|
622 | except error.RepoLookupError: | |
623 | ui.status(_('(not using pooled storage: ' |
|
623 | ui.status(_('(not using pooled storage: ' | |
624 | 'unable to resolve identity of remote)\n')) |
|
624 | 'unable to resolve identity of remote)\n')) | |
625 | elif sharenamemode == 'remote': |
|
625 | elif sharenamemode == 'remote': | |
626 | sharepath = os.path.join( |
|
626 | sharepath = os.path.join( | |
627 | sharepool, node.hex(hashlib.sha1(source).digest())) |
|
627 | sharepool, node.hex(hashlib.sha1(source).digest())) | |
628 | else: |
|
628 | else: | |
629 | raise error.Abort(_('unknown share naming mode: %s') % |
|
629 | raise error.Abort(_('unknown share naming mode: %s') % | |
630 | sharenamemode) |
|
630 | sharenamemode) | |
631 |
|
631 | |||
632 | # TODO this is a somewhat arbitrary restriction. |
|
632 | # TODO this is a somewhat arbitrary restriction. | |
633 | if narrow: |
|
633 | if narrow: | |
634 | ui.status(_('(pooled storage not supported for narrow clones)\n')) |
|
634 | ui.status(_('(pooled storage not supported for narrow clones)\n')) | |
635 | sharepath = None |
|
635 | sharepath = None | |
636 |
|
636 | |||
637 | if sharepath: |
|
637 | if sharepath: | |
638 | return clonewithshare(ui, peeropts, sharepath, source, srcpeer, |
|
638 | return clonewithshare(ui, peeropts, sharepath, source, srcpeer, | |
639 | dest, pull=pull, rev=revs, update=update, |
|
639 | dest, pull=pull, rev=revs, update=update, | |
640 | stream=stream) |
|
640 | stream=stream) | |
641 |
|
641 | |||
642 | srclock = destlock = cleandir = None |
|
642 | srclock = destlock = cleandir = None | |
643 | srcrepo = srcpeer.local() |
|
643 | srcrepo = srcpeer.local() | |
644 | try: |
|
644 | try: | |
645 | abspath = origsource |
|
645 | abspath = origsource | |
646 | if islocal(origsource): |
|
646 | if islocal(origsource): | |
647 | abspath = os.path.abspath(util.urllocalpath(origsource)) |
|
647 | abspath = os.path.abspath(util.urllocalpath(origsource)) | |
648 |
|
648 | |||
649 | if islocal(dest): |
|
649 | if islocal(dest): | |
650 | cleandir = dest |
|
650 | cleandir = dest | |
651 |
|
651 | |||
652 | copy = False |
|
652 | copy = False | |
653 | if (srcrepo and srcrepo.cancopy() and islocal(dest) |
|
653 | if (srcrepo and srcrepo.cancopy() and islocal(dest) | |
654 | and not phases.hassecret(srcrepo)): |
|
654 | and not phases.hassecret(srcrepo)): | |
655 | copy = not pull and not revs |
|
655 | copy = not pull and not revs | |
656 |
|
656 | |||
657 | # TODO this is a somewhat arbitrary restriction. |
|
657 | # TODO this is a somewhat arbitrary restriction. | |
658 | if narrow: |
|
658 | if narrow: | |
659 | copy = False |
|
659 | copy = False | |
660 |
|
660 | |||
661 | if copy: |
|
661 | if copy: | |
662 | try: |
|
662 | try: | |
663 | # we use a lock here because if we race with commit, we |
|
663 | # we use a lock here because if we race with commit, we | |
664 | # can end up with extra data in the cloned revlogs that's |
|
664 | # can end up with extra data in the cloned revlogs that's | |
665 | # not pointed to by changesets, thus causing verify to |
|
665 | # not pointed to by changesets, thus causing verify to | |
666 | # fail |
|
666 | # fail | |
667 | srclock = srcrepo.lock(wait=False) |
|
667 | srclock = srcrepo.lock(wait=False) | |
668 | except error.LockError: |
|
668 | except error.LockError: | |
669 | copy = False |
|
669 | copy = False | |
670 |
|
670 | |||
671 | if copy: |
|
671 | if copy: | |
672 | srcrepo.hook('preoutgoing', throw=True, source='clone') |
|
672 | srcrepo.hook('preoutgoing', throw=True, source='clone') | |
673 | hgdir = os.path.realpath(os.path.join(dest, ".hg")) |
|
673 | hgdir = os.path.realpath(os.path.join(dest, ".hg")) | |
674 | if not os.path.exists(dest): |
|
674 | if not os.path.exists(dest): | |
675 | util.makedirs(dest) |
|
675 | util.makedirs(dest) | |
676 | else: |
|
676 | else: | |
677 | # only clean up directories we create ourselves |
|
677 | # only clean up directories we create ourselves | |
678 | cleandir = hgdir |
|
678 | cleandir = hgdir | |
679 | try: |
|
679 | try: | |
680 | destpath = hgdir |
|
680 | destpath = hgdir | |
681 | util.makedir(destpath, notindexed=True) |
|
681 | util.makedir(destpath, notindexed=True) | |
682 | except OSError as inst: |
|
682 | except OSError as inst: | |
683 | if inst.errno == errno.EEXIST: |
|
683 | if inst.errno == errno.EEXIST: | |
684 | cleandir = None |
|
684 | cleandir = None | |
685 | raise error.Abort(_("destination '%s' already exists") |
|
685 | raise error.Abort(_("destination '%s' already exists") | |
686 | % dest) |
|
686 | % dest) | |
687 | raise |
|
687 | raise | |
688 |
|
688 | |||
689 | destlock = copystore(ui, srcrepo, destpath) |
|
689 | destlock = copystore(ui, srcrepo, destpath) | |
690 | # copy bookmarks over |
|
690 | # copy bookmarks over | |
691 | srcbookmarks = srcrepo.vfs.join('bookmarks') |
|
691 | srcbookmarks = srcrepo.vfs.join('bookmarks') | |
692 | dstbookmarks = os.path.join(destpath, 'bookmarks') |
|
692 | dstbookmarks = os.path.join(destpath, 'bookmarks') | |
693 | if os.path.exists(srcbookmarks): |
|
693 | if os.path.exists(srcbookmarks): | |
694 | util.copyfile(srcbookmarks, dstbookmarks) |
|
694 | util.copyfile(srcbookmarks, dstbookmarks) | |
695 |
|
695 | |||
696 | dstcachedir = os.path.join(destpath, 'cache') |
|
696 | dstcachedir = os.path.join(destpath, 'cache') | |
697 | for cache in cacheutil.cachetocopy(srcrepo): |
|
697 | for cache in cacheutil.cachetocopy(srcrepo): | |
698 | _copycache(srcrepo, dstcachedir, cache) |
|
698 | _copycache(srcrepo, dstcachedir, cache) | |
699 |
|
699 | |||
700 | # we need to re-init the repo after manually copying the data |
|
700 | # we need to re-init the repo after manually copying the data | |
701 | # into it |
|
701 | # into it | |
702 | destpeer = peer(srcrepo, peeropts, dest) |
|
702 | destpeer = peer(srcrepo, peeropts, dest) | |
703 | srcrepo.hook('outgoing', source='clone', |
|
703 | srcrepo.hook('outgoing', source='clone', | |
704 | node=node.hex(node.nullid)) |
|
704 | node=node.hex(node.nullid)) | |
705 | else: |
|
705 | else: | |
706 | try: |
|
706 | try: | |
707 | # only pass ui when no srcrepo |
|
707 | # only pass ui when no srcrepo | |
708 | destpeer = peer(srcrepo or ui, peeropts, dest, create=True, |
|
708 | destpeer = peer(srcrepo or ui, peeropts, dest, create=True, | |
709 | createopts=createopts) |
|
709 | createopts=createopts) | |
710 | except OSError as inst: |
|
710 | except OSError as inst: | |
711 | if inst.errno == errno.EEXIST: |
|
711 | if inst.errno == errno.EEXIST: | |
712 | cleandir = None |
|
712 | cleandir = None | |
713 | raise error.Abort(_("destination '%s' already exists") |
|
713 | raise error.Abort(_("destination '%s' already exists") | |
714 | % dest) |
|
714 | % dest) | |
715 | raise |
|
715 | raise | |
716 |
|
716 | |||
717 | if revs: |
|
717 | if revs: | |
718 | if not srcpeer.capable('lookup'): |
|
718 | if not srcpeer.capable('lookup'): | |
719 | raise error.Abort(_("src repository does not support " |
|
719 | raise error.Abort(_("src repository does not support " | |
720 | "revision lookup and so doesn't " |
|
720 | "revision lookup and so doesn't " | |
721 | "support clone by revision")) |
|
721 | "support clone by revision")) | |
722 |
|
722 | |||
723 | # TODO this is batchable. |
|
723 | # TODO this is batchable. | |
724 | remoterevs = [] |
|
724 | remoterevs = [] | |
725 | for rev in revs: |
|
725 | for rev in revs: | |
726 | with srcpeer.commandexecutor() as e: |
|
726 | with srcpeer.commandexecutor() as e: | |
727 | remoterevs.append(e.callcommand('lookup', { |
|
727 | remoterevs.append(e.callcommand('lookup', { | |
728 | 'key': rev, |
|
728 | 'key': rev, | |
729 | }).result()) |
|
729 | }).result()) | |
730 | revs = remoterevs |
|
730 | revs = remoterevs | |
731 |
|
731 | |||
732 | checkout = revs[0] |
|
732 | checkout = revs[0] | |
733 | else: |
|
733 | else: | |
734 | revs = None |
|
734 | revs = None | |
735 | local = destpeer.local() |
|
735 | local = destpeer.local() | |
736 | if local: |
|
736 | if local: | |
737 | if narrow: |
|
737 | if narrow: | |
738 | with local.wlock(), local.lock(): |
|
738 | with local.wlock(), local.lock(): | |
739 | local.setnarrowpats(storeincludepats, storeexcludepats) |
|
739 | local.setnarrowpats(storeincludepats, storeexcludepats) | |
740 |
|
740 | |||
741 | u = util.url(abspath) |
|
741 | u = util.url(abspath) | |
742 | defaulturl = bytes(u) |
|
742 | defaulturl = bytes(u) | |
743 | local.ui.setconfig('paths', 'default', defaulturl, 'clone') |
|
743 | local.ui.setconfig('paths', 'default', defaulturl, 'clone') | |
744 | if not stream: |
|
744 | if not stream: | |
745 | if pull: |
|
745 | if pull: | |
746 | stream = False |
|
746 | stream = False | |
747 | else: |
|
747 | else: | |
748 | stream = None |
|
748 | stream = None | |
749 | # internal config: ui.quietbookmarkmove |
|
749 | # internal config: ui.quietbookmarkmove | |
750 | overrides = {('ui', 'quietbookmarkmove'): True} |
|
750 | overrides = {('ui', 'quietbookmarkmove'): True} | |
751 | with local.ui.configoverride(overrides, 'clone'): |
|
751 | with local.ui.configoverride(overrides, 'clone'): | |
752 | exchange.pull(local, srcpeer, revs, |
|
752 | exchange.pull(local, srcpeer, revs, | |
753 | streamclonerequested=stream, |
|
753 | streamclonerequested=stream, | |
754 | includepats=storeincludepats, |
|
754 | includepats=storeincludepats, | |
755 | excludepats=storeexcludepats, |
|
755 | excludepats=storeexcludepats, | |
756 | depth=depth) |
|
756 | depth=depth) | |
757 | elif srcrepo: |
|
757 | elif srcrepo: | |
758 | # TODO lift restriction once exchange.push() accepts narrow |
|
758 | # TODO lift restriction once exchange.push() accepts narrow | |
759 | # push. |
|
759 | # push. | |
760 | if narrow: |
|
760 | if narrow: | |
761 | raise error.Abort(_('narrow clone not available for ' |
|
761 | raise error.Abort(_('narrow clone not available for ' | |
762 | 'remote destinations')) |
|
762 | 'remote destinations')) | |
763 |
|
763 | |||
764 | exchange.push(srcrepo, destpeer, revs=revs, |
|
764 | exchange.push(srcrepo, destpeer, revs=revs, | |
765 | bookmarks=srcrepo._bookmarks.keys()) |
|
765 | bookmarks=srcrepo._bookmarks.keys()) | |
766 | else: |
|
766 | else: | |
767 | raise error.Abort(_("clone from remote to remote not supported") |
|
767 | raise error.Abort(_("clone from remote to remote not supported") | |
768 | ) |
|
768 | ) | |
769 |
|
769 | |||
770 | cleandir = None |
|
770 | cleandir = None | |
771 |
|
771 | |||
772 | destrepo = destpeer.local() |
|
772 | destrepo = destpeer.local() | |
773 | if destrepo: |
|
773 | if destrepo: | |
774 | template = uimod.samplehgrcs['cloned'] |
|
774 | template = uimod.samplehgrcs['cloned'] | |
775 | u = util.url(abspath) |
|
775 | u = util.url(abspath) | |
776 | u.passwd = None |
|
776 | u.passwd = None | |
777 | defaulturl = bytes(u) |
|
777 | defaulturl = bytes(u) | |
778 | destrepo.vfs.write('hgrc', util.tonativeeol(template % defaulturl)) |
|
778 | destrepo.vfs.write('hgrc', util.tonativeeol(template % defaulturl)) | |
779 | destrepo.ui.setconfig('paths', 'default', defaulturl, 'clone') |
|
779 | destrepo.ui.setconfig('paths', 'default', defaulturl, 'clone') | |
780 |
|
780 | |||
781 | if ui.configbool('experimental', 'remotenames'): |
|
781 | if ui.configbool('experimental', 'remotenames'): | |
782 | logexchange.pullremotenames(destrepo, srcpeer) |
|
782 | logexchange.pullremotenames(destrepo, srcpeer) | |
783 |
|
783 | |||
784 | if update: |
|
784 | if update: | |
785 | if update is not True: |
|
785 | if update is not True: | |
786 | with srcpeer.commandexecutor() as e: |
|
786 | with srcpeer.commandexecutor() as e: | |
787 | checkout = e.callcommand('lookup', { |
|
787 | checkout = e.callcommand('lookup', { | |
788 | 'key': update, |
|
788 | 'key': update, | |
789 | }).result() |
|
789 | }).result() | |
790 |
|
790 | |||
791 | uprev = None |
|
791 | uprev = None | |
792 | status = None |
|
792 | status = None | |
793 | if checkout is not None: |
|
793 | if checkout is not None: | |
794 | # Some extensions (at least hg-git and hg-subversion) have |
|
794 | # Some extensions (at least hg-git and hg-subversion) have | |
795 | # a peer.lookup() implementation that returns a name instead |
|
795 | # a peer.lookup() implementation that returns a name instead | |
796 | # of a nodeid. We work around it here until we've figured |
|
796 | # of a nodeid. We work around it here until we've figured | |
797 | # out a better solution. |
|
797 | # out a better solution. | |
798 | if len(checkout) == 20 and checkout in destrepo: |
|
798 | if len(checkout) == 20 and checkout in destrepo: | |
799 | uprev = checkout |
|
799 | uprev = checkout | |
800 | elif scmutil.isrevsymbol(destrepo, checkout): |
|
800 | elif scmutil.isrevsymbol(destrepo, checkout): | |
801 | uprev = scmutil.revsymbol(destrepo, checkout).node() |
|
801 | uprev = scmutil.revsymbol(destrepo, checkout).node() | |
802 | else: |
|
802 | else: | |
803 | if update is not True: |
|
803 | if update is not True: | |
804 | try: |
|
804 | try: | |
805 | uprev = destrepo.lookup(update) |
|
805 | uprev = destrepo.lookup(update) | |
806 | except error.RepoLookupError: |
|
806 | except error.RepoLookupError: | |
807 | pass |
|
807 | pass | |
808 | if uprev is None: |
|
808 | if uprev is None: | |
809 | try: |
|
809 | try: | |
810 | uprev = destrepo._bookmarks['@'] |
|
810 | uprev = destrepo._bookmarks['@'] | |
811 | update = '@' |
|
811 | update = '@' | |
812 | bn = destrepo[uprev].branch() |
|
812 | bn = destrepo[uprev].branch() | |
813 | if bn == 'default': |
|
813 | if bn == 'default': | |
814 | status = _("updating to bookmark @\n") |
|
814 | status = _("updating to bookmark @\n") | |
815 | else: |
|
815 | else: | |
816 | status = (_("updating to bookmark @ on branch %s\n") |
|
816 | status = (_("updating to bookmark @ on branch %s\n") | |
817 | % bn) |
|
817 | % bn) | |
818 | except KeyError: |
|
818 | except KeyError: | |
819 | try: |
|
819 | try: | |
820 | uprev = destrepo.branchtip('default') |
|
820 | uprev = destrepo.branchtip('default') | |
821 | except error.RepoLookupError: |
|
821 | except error.RepoLookupError: | |
822 | uprev = destrepo.lookup('tip') |
|
822 | uprev = destrepo.lookup('tip') | |
823 | if not status: |
|
823 | if not status: | |
824 | bn = destrepo[uprev].branch() |
|
824 | bn = destrepo[uprev].branch() | |
825 | status = _("updating to branch %s\n") % bn |
|
825 | status = _("updating to branch %s\n") % bn | |
826 | destrepo.ui.status(status) |
|
826 | destrepo.ui.status(status) | |
827 | _update(destrepo, uprev) |
|
827 | _update(destrepo, uprev) | |
828 | if update in destrepo._bookmarks: |
|
828 | if update in destrepo._bookmarks: | |
829 | bookmarks.activate(destrepo, update) |
|
829 | bookmarks.activate(destrepo, update) | |
830 | finally: |
|
830 | finally: | |
831 | release(srclock, destlock) |
|
831 | release(srclock, destlock) | |
832 | if cleandir is not None: |
|
832 | if cleandir is not None: | |
833 | shutil.rmtree(cleandir, True) |
|
833 | shutil.rmtree(cleandir, True) | |
834 | if srcpeer is not None: |
|
834 | if srcpeer is not None: | |
835 | srcpeer.close() |
|
835 | srcpeer.close() | |
836 | return srcpeer, destpeer |
|
836 | return srcpeer, destpeer | |
837 |
|
837 | |||
838 | def _showstats(repo, stats, quietempty=False): |
|
838 | def _showstats(repo, stats, quietempty=False): | |
839 | if quietempty and stats.isempty(): |
|
839 | if quietempty and stats.isempty(): | |
840 | return |
|
840 | return | |
841 | repo.ui.status(_("%d files updated, %d files merged, " |
|
841 | repo.ui.status(_("%d files updated, %d files merged, " | |
842 | "%d files removed, %d files unresolved\n") % ( |
|
842 | "%d files removed, %d files unresolved\n") % ( | |
843 | stats.updatedcount, stats.mergedcount, |
|
843 | stats.updatedcount, stats.mergedcount, | |
844 | stats.removedcount, stats.unresolvedcount)) |
|
844 | stats.removedcount, stats.unresolvedcount)) | |
845 |
|
845 | |||
846 | def updaterepo(repo, node, overwrite, updatecheck=None): |
|
846 | def updaterepo(repo, node, overwrite, updatecheck=None): | |
847 | """Update the working directory to node. |
|
847 | """Update the working directory to node. | |
848 |
|
848 | |||
849 | When overwrite is set, changes are clobbered, merged else |
|
849 | When overwrite is set, changes are clobbered, merged else | |
850 |
|
850 | |||
851 | returns stats (see pydoc mercurial.merge.applyupdates)""" |
|
851 | returns stats (see pydoc mercurial.merge.applyupdates)""" | |
852 | return mergemod.update(repo, node, branchmerge=False, force=overwrite, |
|
852 | return mergemod.update(repo, node, branchmerge=False, force=overwrite, | |
853 | labels=['working copy', 'destination'], |
|
853 | labels=['working copy', 'destination'], | |
854 | updatecheck=updatecheck) |
|
854 | updatecheck=updatecheck) | |
855 |
|
855 | |||
856 | def update(repo, node, quietempty=False, updatecheck=None): |
|
856 | def update(repo, node, quietempty=False, updatecheck=None): | |
857 | """update the working directory to node""" |
|
857 | """update the working directory to node""" | |
858 | stats = updaterepo(repo, node, False, updatecheck=updatecheck) |
|
858 | stats = updaterepo(repo, node, False, updatecheck=updatecheck) | |
859 | _showstats(repo, stats, quietempty) |
|
859 | _showstats(repo, stats, quietempty) | |
860 | if stats.unresolvedcount: |
|
860 | if stats.unresolvedcount: | |
861 | repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n")) |
|
861 | repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n")) | |
862 | return stats.unresolvedcount > 0 |
|
862 | return stats.unresolvedcount > 0 | |
863 |
|
863 | |||
864 | # naming conflict in clone() |
|
864 | # naming conflict in clone() | |
865 | _update = update |
|
865 | _update = update | |
866 |
|
866 | |||
867 | def clean(repo, node, show_stats=True, quietempty=False): |
|
867 | def clean(repo, node, show_stats=True, quietempty=False): | |
868 | """forcibly switch the working directory to node, clobbering changes""" |
|
868 | """forcibly switch the working directory to node, clobbering changes""" | |
869 | stats = updaterepo(repo, node, True) |
|
869 | stats = updaterepo(repo, node, True) | |
870 | repo.vfs.unlinkpath('graftstate', ignoremissing=True) |
|
870 | repo.vfs.unlinkpath('graftstate', ignoremissing=True) | |
871 | if show_stats: |
|
871 | if show_stats: | |
872 | _showstats(repo, stats, quietempty) |
|
872 | _showstats(repo, stats, quietempty) | |
873 | return stats.unresolvedcount > 0 |
|
873 | return stats.unresolvedcount > 0 | |
874 |
|
874 | |||
875 | # naming conflict in updatetotally() |
|
875 | # naming conflict in updatetotally() | |
876 | _clean = clean |
|
876 | _clean = clean | |
877 |
|
877 | |||
878 | def updatetotally(ui, repo, checkout, brev, clean=False, updatecheck=None): |
|
878 | def updatetotally(ui, repo, checkout, brev, clean=False, updatecheck=None): | |
879 | """Update the working directory with extra care for non-file components |
|
879 | """Update the working directory with extra care for non-file components | |
880 |
|
880 | |||
881 | This takes care of non-file components below: |
|
881 | This takes care of non-file components below: | |
882 |
|
882 | |||
883 | :bookmark: might be advanced or (in)activated |
|
883 | :bookmark: might be advanced or (in)activated | |
884 |
|
884 | |||
885 | This takes arguments below: |
|
885 | This takes arguments below: | |
886 |
|
886 | |||
887 | :checkout: to which revision the working directory is updated |
|
887 | :checkout: to which revision the working directory is updated | |
888 | :brev: a name, which might be a bookmark to be activated after updating |
|
888 | :brev: a name, which might be a bookmark to be activated after updating | |
889 | :clean: whether changes in the working directory can be discarded |
|
889 | :clean: whether changes in the working directory can be discarded | |
890 | :updatecheck: how to deal with a dirty working directory |
|
890 | :updatecheck: how to deal with a dirty working directory | |
891 |
|
891 | |||
892 | Valid values for updatecheck are (None => linear): |
|
892 | Valid values for updatecheck are (None => linear): | |
893 |
|
893 | |||
894 | * abort: abort if the working directory is dirty |
|
894 | * abort: abort if the working directory is dirty | |
895 | * none: don't check (merge working directory changes into destination) |
|
895 | * none: don't check (merge working directory changes into destination) | |
896 | * linear: check that update is linear before merging working directory |
|
896 | * linear: check that update is linear before merging working directory | |
897 | changes into destination |
|
897 | changes into destination | |
898 | * noconflict: check that the update does not result in file merges |
|
898 | * noconflict: check that the update does not result in file merges | |
899 |
|
899 | |||
900 | This returns whether conflict is detected at updating or not. |
|
900 | This returns whether conflict is detected at updating or not. | |
901 | """ |
|
901 | """ | |
902 | if updatecheck is None: |
|
902 | if updatecheck is None: | |
903 | updatecheck = ui.config('commands', 'update.check') |
|
903 | updatecheck = ui.config('commands', 'update.check') | |
904 | if updatecheck not in ('abort', 'none', 'linear', 'noconflict'): |
|
904 | if updatecheck not in ('abort', 'none', 'linear', 'noconflict'): | |
905 | # If not configured, or invalid value configured |
|
905 | # If not configured, or invalid value configured | |
906 | updatecheck = 'linear' |
|
906 | updatecheck = 'linear' | |
907 | with repo.wlock(): |
|
907 | with repo.wlock(): | |
908 | movemarkfrom = None |
|
908 | movemarkfrom = None | |
909 | warndest = False |
|
909 | warndest = False | |
910 | if checkout is None: |
|
910 | if checkout is None: | |
911 | updata = destutil.destupdate(repo, clean=clean) |
|
911 | updata = destutil.destupdate(repo, clean=clean) | |
912 | checkout, movemarkfrom, brev = updata |
|
912 | checkout, movemarkfrom, brev = updata | |
913 | warndest = True |
|
913 | warndest = True | |
914 |
|
914 | |||
915 | if clean: |
|
915 | if clean: | |
916 | ret = _clean(repo, checkout) |
|
916 | ret = _clean(repo, checkout) | |
917 | else: |
|
917 | else: | |
918 | if updatecheck == 'abort': |
|
918 | if updatecheck == 'abort': | |
919 | cmdutil.bailifchanged(repo, merge=False) |
|
919 | cmdutil.bailifchanged(repo, merge=False) | |
920 | updatecheck = 'none' |
|
920 | updatecheck = 'none' | |
921 | ret = _update(repo, checkout, updatecheck=updatecheck) |
|
921 | ret = _update(repo, checkout, updatecheck=updatecheck) | |
922 |
|
922 | |||
923 | if not ret and movemarkfrom: |
|
923 | if not ret and movemarkfrom: | |
924 | if movemarkfrom == repo['.'].node(): |
|
924 | if movemarkfrom == repo['.'].node(): | |
925 | pass # no-op update |
|
925 | pass # no-op update | |
926 | elif bookmarks.update(repo, [movemarkfrom], repo['.'].node()): |
|
926 | elif bookmarks.update(repo, [movemarkfrom], repo['.'].node()): | |
927 | b = ui.label(repo._activebookmark, 'bookmarks.active') |
|
927 | b = ui.label(repo._activebookmark, 'bookmarks.active') | |
928 | ui.status(_("updating bookmark %s\n") % b) |
|
928 | ui.status(_("updating bookmark %s\n") % b) | |
929 | else: |
|
929 | else: | |
930 | # this can happen with a non-linear update |
|
930 | # this can happen with a non-linear update | |
931 | b = ui.label(repo._activebookmark, 'bookmarks') |
|
931 | b = ui.label(repo._activebookmark, 'bookmarks') | |
932 | ui.status(_("(leaving bookmark %s)\n") % b) |
|
932 | ui.status(_("(leaving bookmark %s)\n") % b) | |
933 | bookmarks.deactivate(repo) |
|
933 | bookmarks.deactivate(repo) | |
934 | elif brev in repo._bookmarks: |
|
934 | elif brev in repo._bookmarks: | |
935 | if brev != repo._activebookmark: |
|
935 | if brev != repo._activebookmark: | |
936 | b = ui.label(brev, 'bookmarks.active') |
|
936 | b = ui.label(brev, 'bookmarks.active') | |
937 | ui.status(_("(activating bookmark %s)\n") % b) |
|
937 | ui.status(_("(activating bookmark %s)\n") % b) | |
938 | bookmarks.activate(repo, brev) |
|
938 | bookmarks.activate(repo, brev) | |
939 | elif brev: |
|
939 | elif brev: | |
940 | if repo._activebookmark: |
|
940 | if repo._activebookmark: | |
941 | b = ui.label(repo._activebookmark, 'bookmarks') |
|
941 | b = ui.label(repo._activebookmark, 'bookmarks') | |
942 | ui.status(_("(leaving bookmark %s)\n") % b) |
|
942 | ui.status(_("(leaving bookmark %s)\n") % b) | |
943 | bookmarks.deactivate(repo) |
|
943 | bookmarks.deactivate(repo) | |
944 |
|
944 | |||
945 | if warndest: |
|
945 | if warndest: | |
946 | destutil.statusotherdests(ui, repo) |
|
946 | destutil.statusotherdests(ui, repo) | |
947 |
|
947 | |||
948 | return ret |
|
948 | return ret | |
949 |
|
949 | |||
950 | def merge(repo, node, force=None, remind=True, mergeforce=False, labels=None, |
|
950 | def merge(repo, node, force=None, remind=True, mergeforce=False, labels=None, | |
951 | abort=False): |
|
951 | abort=False): | |
952 | """Branch merge with node, resolving changes. Return true if any |
|
952 | """Branch merge with node, resolving changes. Return true if any | |
953 | unresolved conflicts.""" |
|
953 | unresolved conflicts.""" | |
954 | if not abort: |
|
954 | if not abort: | |
955 | stats = mergemod.update(repo, node, branchmerge=True, force=force, |
|
955 | stats = mergemod.update(repo, node, branchmerge=True, force=force, | |
956 | mergeforce=mergeforce, labels=labels) |
|
956 | mergeforce=mergeforce, labels=labels) | |
957 | else: |
|
957 | else: | |
958 | ms = mergemod.mergestate.read(repo) |
|
958 | ms = mergemod.mergestate.read(repo) | |
959 | if ms.active(): |
|
959 | if ms.active(): | |
960 | # there were conflicts |
|
960 | # there were conflicts | |
961 | node = ms.localctx.hex() |
|
961 | node = ms.localctx.hex() | |
962 | else: |
|
962 | else: | |
963 | # there were no conficts, mergestate was not stored |
|
963 | # there were no conficts, mergestate was not stored | |
964 | node = repo['.'].hex() |
|
964 | node = repo['.'].hex() | |
965 |
|
965 | |||
966 | repo.ui.status(_("aborting the merge, updating back to" |
|
966 | repo.ui.status(_("aborting the merge, updating back to" | |
967 | " %s\n") % node[:12]) |
|
967 | " %s\n") % node[:12]) | |
968 | stats = mergemod.update(repo, node, branchmerge=False, force=True, |
|
968 | stats = mergemod.update(repo, node, branchmerge=False, force=True, | |
969 | labels=labels) |
|
969 | labels=labels) | |
970 |
|
970 | |||
971 | _showstats(repo, stats) |
|
971 | _showstats(repo, stats) | |
972 | if stats.unresolvedcount: |
|
972 | if stats.unresolvedcount: | |
973 | repo.ui.status(_("use 'hg resolve' to retry unresolved file merges " |
|
973 | repo.ui.status(_("use 'hg resolve' to retry unresolved file merges " | |
974 | "or 'hg merge --abort' to abandon\n")) |
|
974 | "or 'hg merge --abort' to abandon\n")) | |
975 | elif remind and not abort: |
|
975 | elif remind and not abort: | |
976 | repo.ui.status(_("(branch merge, don't forget to commit)\n")) |
|
976 | repo.ui.status(_("(branch merge, don't forget to commit)\n")) | |
977 | return stats.unresolvedcount > 0 |
|
977 | return stats.unresolvedcount > 0 | |
978 |
|
978 | |||
979 | def _incoming(displaychlist, subreporecurse, ui, repo, source, |
|
979 | def _incoming(displaychlist, subreporecurse, ui, repo, source, | |
980 | opts, buffered=False): |
|
980 | opts, buffered=False): | |
981 | """ |
|
981 | """ | |
982 | Helper for incoming / gincoming. |
|
982 | Helper for incoming / gincoming. | |
983 | displaychlist gets called with |
|
983 | displaychlist gets called with | |
984 | (remoterepo, incomingchangesetlist, displayer) parameters, |
|
984 | (remoterepo, incomingchangesetlist, displayer) parameters, | |
985 | and is supposed to contain only code that can't be unified. |
|
985 | and is supposed to contain only code that can't be unified. | |
986 | """ |
|
986 | """ | |
987 | source, branches = parseurl(ui.expandpath(source), opts.get('branch')) |
|
987 | source, branches = parseurl(ui.expandpath(source), opts.get('branch')) | |
988 | other = peer(repo, opts, source) |
|
988 | other = peer(repo, opts, source) | |
989 | ui.status(_('comparing with %s\n') % util.hidepassword(source)) |
|
989 | ui.status(_('comparing with %s\n') % util.hidepassword(source)) | |
990 | revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev')) |
|
990 | revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev')) | |
991 |
|
991 | |||
992 | if revs: |
|
992 | if revs: | |
993 | revs = [other.lookup(rev) for rev in revs] |
|
993 | revs = [other.lookup(rev) for rev in revs] | |
994 | other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other, |
|
994 | other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other, | |
995 | revs, opts["bundle"], opts["force"]) |
|
995 | revs, opts["bundle"], opts["force"]) | |
996 | try: |
|
996 | try: | |
997 | if not chlist: |
|
997 | if not chlist: | |
998 | ui.status(_("no changes found\n")) |
|
998 | ui.status(_("no changes found\n")) | |
999 | return subreporecurse() |
|
999 | return subreporecurse() | |
1000 | ui.pager('incoming') |
|
1000 | ui.pager('incoming') | |
1001 | displayer = logcmdutil.changesetdisplayer(ui, other, opts, |
|
1001 | displayer = logcmdutil.changesetdisplayer(ui, other, opts, | |
1002 | buffered=buffered) |
|
1002 | buffered=buffered) | |
1003 | displaychlist(other, chlist, displayer) |
|
1003 | displaychlist(other, chlist, displayer) | |
1004 | displayer.close() |
|
1004 | displayer.close() | |
1005 | finally: |
|
1005 | finally: | |
1006 | cleanupfn() |
|
1006 | cleanupfn() | |
1007 | subreporecurse() |
|
1007 | subreporecurse() | |
1008 | return 0 # exit code is zero since we found incoming changes |
|
1008 | return 0 # exit code is zero since we found incoming changes | |
1009 |
|
1009 | |||
1010 | def incoming(ui, repo, source, opts): |
|
1010 | def incoming(ui, repo, source, opts): | |
1011 | def subreporecurse(): |
|
1011 | def subreporecurse(): | |
1012 | ret = 1 |
|
1012 | ret = 1 | |
1013 | if opts.get('subrepos'): |
|
1013 | if opts.get('subrepos'): | |
1014 | ctx = repo[None] |
|
1014 | ctx = repo[None] | |
1015 | for subpath in sorted(ctx.substate): |
|
1015 | for subpath in sorted(ctx.substate): | |
1016 | sub = ctx.sub(subpath) |
|
1016 | sub = ctx.sub(subpath) | |
1017 | ret = min(ret, sub.incoming(ui, source, opts)) |
|
1017 | ret = min(ret, sub.incoming(ui, source, opts)) | |
1018 | return ret |
|
1018 | return ret | |
1019 |
|
1019 | |||
1020 | def display(other, chlist, displayer): |
|
1020 | def display(other, chlist, displayer): | |
1021 | limit = logcmdutil.getlimit(opts) |
|
1021 | limit = logcmdutil.getlimit(opts) | |
1022 | if opts.get('newest_first'): |
|
1022 | if opts.get('newest_first'): | |
1023 | chlist.reverse() |
|
1023 | chlist.reverse() | |
1024 | count = 0 |
|
1024 | count = 0 | |
1025 | for n in chlist: |
|
1025 | for n in chlist: | |
1026 | if limit is not None and count >= limit: |
|
1026 | if limit is not None and count >= limit: | |
1027 | break |
|
1027 | break | |
1028 | parents = [p for p in other.changelog.parents(n) if p != nullid] |
|
1028 | parents = [p for p in other.changelog.parents(n) if p != nullid] | |
1029 | if opts.get('no_merges') and len(parents) == 2: |
|
1029 | if opts.get('no_merges') and len(parents) == 2: | |
1030 | continue |
|
1030 | continue | |
1031 | count += 1 |
|
1031 | count += 1 | |
1032 | displayer.show(other[n]) |
|
1032 | displayer.show(other[n]) | |
1033 | return _incoming(display, subreporecurse, ui, repo, source, opts) |
|
1033 | return _incoming(display, subreporecurse, ui, repo, source, opts) | |
1034 |
|
1034 | |||
1035 | def _outgoing(ui, repo, dest, opts): |
|
1035 | def _outgoing(ui, repo, dest, opts): | |
1036 | path = ui.paths.getpath(dest, default=('default-push', 'default')) |
|
1036 | path = ui.paths.getpath(dest, default=('default-push', 'default')) | |
1037 | if not path: |
|
1037 | if not path: | |
1038 | raise error.Abort(_('default repository not configured!'), |
|
1038 | raise error.Abort(_('default repository not configured!'), | |
1039 | hint=_("see 'hg help config.paths'")) |
|
1039 | hint=_("see 'hg help config.paths'")) | |
1040 | dest = path.pushloc or path.loc |
|
1040 | dest = path.pushloc or path.loc | |
1041 | branches = path.branch, opts.get('branch') or [] |
|
1041 | branches = path.branch, opts.get('branch') or [] | |
1042 |
|
1042 | |||
1043 | ui.status(_('comparing with %s\n') % util.hidepassword(dest)) |
|
1043 | ui.status(_('comparing with %s\n') % util.hidepassword(dest)) | |
1044 | revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev')) |
|
1044 | revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev')) | |
1045 | if revs: |
|
1045 | if revs: | |
1046 | revs = [repo[rev].node() for rev in scmutil.revrange(repo, revs)] |
|
1046 | revs = [repo[rev].node() for rev in scmutil.revrange(repo, revs)] | |
1047 |
|
1047 | |||
1048 | other = peer(repo, opts, dest) |
|
1048 | other = peer(repo, opts, dest) | |
1049 | outgoing = discovery.findcommonoutgoing(repo, other, revs, |
|
1049 | outgoing = discovery.findcommonoutgoing(repo, other, revs, | |
1050 | force=opts.get('force')) |
|
1050 | force=opts.get('force')) | |
1051 | o = outgoing.missing |
|
1051 | o = outgoing.missing | |
1052 | if not o: |
|
1052 | if not o: | |
1053 | scmutil.nochangesfound(repo.ui, repo, outgoing.excluded) |
|
1053 | scmutil.nochangesfound(repo.ui, repo, outgoing.excluded) | |
1054 | return o, other |
|
1054 | return o, other | |
1055 |
|
1055 | |||
1056 | def outgoing(ui, repo, dest, opts): |
|
1056 | def outgoing(ui, repo, dest, opts): | |
1057 | def recurse(): |
|
1057 | def recurse(): | |
1058 | ret = 1 |
|
1058 | ret = 1 | |
1059 | if opts.get('subrepos'): |
|
1059 | if opts.get('subrepos'): | |
1060 | ctx = repo[None] |
|
1060 | ctx = repo[None] | |
1061 | for subpath in sorted(ctx.substate): |
|
1061 | for subpath in sorted(ctx.substate): | |
1062 | sub = ctx.sub(subpath) |
|
1062 | sub = ctx.sub(subpath) | |
1063 | ret = min(ret, sub.outgoing(ui, dest, opts)) |
|
1063 | ret = min(ret, sub.outgoing(ui, dest, opts)) | |
1064 | return ret |
|
1064 | return ret | |
1065 |
|
1065 | |||
1066 | limit = logcmdutil.getlimit(opts) |
|
1066 | limit = logcmdutil.getlimit(opts) | |
1067 | o, other = _outgoing(ui, repo, dest, opts) |
|
1067 | o, other = _outgoing(ui, repo, dest, opts) | |
1068 | if not o: |
|
1068 | if not o: | |
1069 | cmdutil.outgoinghooks(ui, repo, other, opts, o) |
|
1069 | cmdutil.outgoinghooks(ui, repo, other, opts, o) | |
1070 | return recurse() |
|
1070 | return recurse() | |
1071 |
|
1071 | |||
1072 | if opts.get('newest_first'): |
|
1072 | if opts.get('newest_first'): | |
1073 | o.reverse() |
|
1073 | o.reverse() | |
1074 | ui.pager('outgoing') |
|
1074 | ui.pager('outgoing') | |
1075 | displayer = logcmdutil.changesetdisplayer(ui, repo, opts) |
|
1075 | displayer = logcmdutil.changesetdisplayer(ui, repo, opts) | |
1076 | count = 0 |
|
1076 | count = 0 | |
1077 | for n in o: |
|
1077 | for n in o: | |
1078 | if limit is not None and count >= limit: |
|
1078 | if limit is not None and count >= limit: | |
1079 | break |
|
1079 | break | |
1080 | parents = [p for p in repo.changelog.parents(n) if p != nullid] |
|
1080 | parents = [p for p in repo.changelog.parents(n) if p != nullid] | |
1081 | if opts.get('no_merges') and len(parents) == 2: |
|
1081 | if opts.get('no_merges') and len(parents) == 2: | |
1082 | continue |
|
1082 | continue | |
1083 | count += 1 |
|
1083 | count += 1 | |
1084 | displayer.show(repo[n]) |
|
1084 | displayer.show(repo[n]) | |
1085 | displayer.close() |
|
1085 | displayer.close() | |
1086 | cmdutil.outgoinghooks(ui, repo, other, opts, o) |
|
1086 | cmdutil.outgoinghooks(ui, repo, other, opts, o) | |
1087 | recurse() |
|
1087 | recurse() | |
1088 | return 0 # exit code is zero since we found outgoing changes |
|
1088 | return 0 # exit code is zero since we found outgoing changes | |
1089 |
|
1089 | |||
1090 | def verify(repo): |
|
1090 | def verify(repo): | |
1091 | """verify the consistency of a repository""" |
|
1091 | """verify the consistency of a repository""" | |
1092 | ret = verifymod.verify(repo) |
|
1092 | ret = verifymod.verify(repo) | |
1093 |
|
1093 | |||
1094 | # Broken subrepo references in hidden csets don't seem worth worrying about, |
|
1094 | # Broken subrepo references in hidden csets don't seem worth worrying about, | |
1095 | # since they can't be pushed/pulled, and --hidden can be used if they are a |
|
1095 | # since they can't be pushed/pulled, and --hidden can be used if they are a | |
1096 | # concern. |
|
1096 | # concern. | |
1097 |
|
1097 | |||
1098 | # pathto() is needed for -R case |
|
1098 | # pathto() is needed for -R case | |
1099 | revs = repo.revs("filelog(%s)", |
|
1099 | revs = repo.revs("filelog(%s)", | |
1100 | util.pathto(repo.root, repo.getcwd(), '.hgsubstate')) |
|
1100 | util.pathto(repo.root, repo.getcwd(), '.hgsubstate')) | |
1101 |
|
1101 | |||
1102 | if revs: |
|
1102 | if revs: | |
1103 | repo.ui.status(_('checking subrepo links\n')) |
|
1103 | repo.ui.status(_('checking subrepo links\n')) | |
1104 | for rev in revs: |
|
1104 | for rev in revs: | |
1105 | ctx = repo[rev] |
|
1105 | ctx = repo[rev] | |
1106 | try: |
|
1106 | try: | |
1107 | for subpath in ctx.substate: |
|
1107 | for subpath in ctx.substate: | |
1108 | try: |
|
1108 | try: | |
1109 | ret = (ctx.sub(subpath, allowcreate=False).verify() |
|
1109 | ret = (ctx.sub(subpath, allowcreate=False).verify() | |
1110 | or ret) |
|
1110 | or ret) | |
1111 | except error.RepoError as e: |
|
1111 | except error.RepoError as e: | |
1112 | repo.ui.warn(('%d: %s\n') % (rev, e)) |
|
1112 | repo.ui.warn(('%d: %s\n') % (rev, e)) | |
1113 | except Exception: |
|
1113 | except Exception: | |
1114 | repo.ui.warn(_('.hgsubstate is corrupt in revision %s\n') % |
|
1114 | repo.ui.warn(_('.hgsubstate is corrupt in revision %s\n') % | |
1115 | node.short(ctx.node())) |
|
1115 | node.short(ctx.node())) | |
1116 |
|
1116 | |||
1117 | return ret |
|
1117 | return ret | |
1118 |
|
1118 | |||
1119 | def remoteui(src, opts): |
|
1119 | def remoteui(src, opts): | |
1120 | 'build a remote ui from ui or repo and opts' |
|
1120 | 'build a remote ui from ui or repo and opts' | |
1121 | if util.safehasattr(src, 'baseui'): # looks like a repository |
|
1121 | if util.safehasattr(src, 'baseui'): # looks like a repository | |
1122 | dst = src.baseui.copy() # drop repo-specific config |
|
1122 | dst = src.baseui.copy() # drop repo-specific config | |
1123 | src = src.ui # copy target options from repo |
|
1123 | src = src.ui # copy target options from repo | |
1124 | else: # assume it's a global ui object |
|
1124 | else: # assume it's a global ui object | |
1125 | dst = src.copy() # keep all global options |
|
1125 | dst = src.copy() # keep all global options | |
1126 |
|
1126 | |||
1127 | # copy ssh-specific options |
|
1127 | # copy ssh-specific options | |
1128 | for o in 'ssh', 'remotecmd': |
|
1128 | for o in 'ssh', 'remotecmd': | |
1129 | v = opts.get(o) or src.config('ui', o) |
|
1129 | v = opts.get(o) or src.config('ui', o) | |
1130 | if v: |
|
1130 | if v: | |
1131 | dst.setconfig("ui", o, v, 'copied') |
|
1131 | dst.setconfig("ui", o, v, 'copied') | |
1132 |
|
1132 | |||
1133 | # copy bundle-specific options |
|
1133 | # copy bundle-specific options | |
1134 | r = src.config('bundle', 'mainreporoot') |
|
1134 | r = src.config('bundle', 'mainreporoot') | |
1135 | if r: |
|
1135 | if r: | |
1136 | dst.setconfig('bundle', 'mainreporoot', r, 'copied') |
|
1136 | dst.setconfig('bundle', 'mainreporoot', r, 'copied') | |
1137 |
|
1137 | |||
1138 | # copy selected local settings to the remote ui |
|
1138 | # copy selected local settings to the remote ui | |
1139 | for sect in ('auth', 'hostfingerprints', 'hostsecurity', 'http_proxy'): |
|
1139 | for sect in ('auth', 'hostfingerprints', 'hostsecurity', 'http_proxy'): | |
1140 | for key, val in src.configitems(sect): |
|
1140 | for key, val in src.configitems(sect): | |
1141 | dst.setconfig(sect, key, val, 'copied') |
|
1141 | dst.setconfig(sect, key, val, 'copied') | |
1142 | v = src.config('web', 'cacerts') |
|
1142 | v = src.config('web', 'cacerts') | |
1143 | if v: |
|
1143 | if v: | |
1144 | dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied') |
|
1144 | dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied') | |
1145 |
|
1145 | |||
1146 | return dst |
|
1146 | return dst | |
1147 |
|
1147 | |||
1148 | # Files of interest |
|
1148 | # Files of interest | |
1149 | # Used to check if the repository has changed looking at mtime and size of |
|
1149 | # Used to check if the repository has changed looking at mtime and size of | |
1150 | # these files. |
|
1150 | # these files. | |
1151 | foi = [('spath', '00changelog.i'), |
|
1151 | foi = [('spath', '00changelog.i'), | |
1152 | ('spath', 'phaseroots'), # ! phase can change content at the same size |
|
1152 | ('spath', 'phaseroots'), # ! phase can change content at the same size | |
1153 | ('spath', 'obsstore'), |
|
1153 | ('spath', 'obsstore'), | |
1154 | ('path', 'bookmarks'), # ! bookmark can change content at the same size |
|
1154 | ('path', 'bookmarks'), # ! bookmark can change content at the same size | |
1155 | ] |
|
1155 | ] | |
1156 |
|
1156 | |||
1157 | class cachedlocalrepo(object): |
|
1157 | class cachedlocalrepo(object): | |
1158 | """Holds a localrepository that can be cached and reused.""" |
|
1158 | """Holds a localrepository that can be cached and reused.""" | |
1159 |
|
1159 | |||
1160 | def __init__(self, repo): |
|
1160 | def __init__(self, repo): | |
1161 | """Create a new cached repo from an existing repo. |
|
1161 | """Create a new cached repo from an existing repo. | |
1162 |
|
1162 | |||
1163 | We assume the passed in repo was recently created. If the |
|
1163 | We assume the passed in repo was recently created. If the | |
1164 | repo has changed between when it was created and when it was |
|
1164 | repo has changed between when it was created and when it was | |
1165 | turned into a cache, it may not refresh properly. |
|
1165 | turned into a cache, it may not refresh properly. | |
1166 | """ |
|
1166 | """ | |
1167 | assert isinstance(repo, localrepo.localrepository) |
|
1167 | assert isinstance(repo, localrepo.localrepository) | |
1168 | self._repo = repo |
|
1168 | self._repo = repo | |
1169 | self._state, self.mtime = self._repostate() |
|
1169 | self._state, self.mtime = self._repostate() | |
1170 | self._filtername = repo.filtername |
|
1170 | self._filtername = repo.filtername | |
1171 |
|
1171 | |||
1172 | def fetch(self): |
|
1172 | def fetch(self): | |
1173 | """Refresh (if necessary) and return a repository. |
|
1173 | """Refresh (if necessary) and return a repository. | |
1174 |
|
1174 | |||
1175 | If the cached instance is out of date, it will be recreated |
|
1175 | If the cached instance is out of date, it will be recreated | |
1176 | automatically and returned. |
|
1176 | automatically and returned. | |
1177 |
|
1177 | |||
1178 | Returns a tuple of the repo and a boolean indicating whether a new |
|
1178 | Returns a tuple of the repo and a boolean indicating whether a new | |
1179 | repo instance was created. |
|
1179 | repo instance was created. | |
1180 | """ |
|
1180 | """ | |
1181 | # We compare the mtimes and sizes of some well-known files to |
|
1181 | # We compare the mtimes and sizes of some well-known files to | |
1182 | # determine if the repo changed. This is not precise, as mtimes |
|
1182 | # determine if the repo changed. This is not precise, as mtimes | |
1183 | # are susceptible to clock skew and imprecise filesystems and |
|
1183 | # are susceptible to clock skew and imprecise filesystems and | |
1184 | # file content can change while maintaining the same size. |
|
1184 | # file content can change while maintaining the same size. | |
1185 |
|
1185 | |||
1186 | state, mtime = self._repostate() |
|
1186 | state, mtime = self._repostate() | |
1187 | if state == self._state: |
|
1187 | if state == self._state: | |
1188 | return self._repo, False |
|
1188 | return self._repo, False | |
1189 |
|
1189 | |||
1190 | repo = repository(self._repo.baseui, self._repo.url()) |
|
1190 | repo = repository(self._repo.baseui, self._repo.url()) | |
1191 | if self._filtername: |
|
1191 | if self._filtername: | |
1192 | self._repo = repo.filtered(self._filtername) |
|
1192 | self._repo = repo.filtered(self._filtername) | |
1193 | else: |
|
1193 | else: | |
1194 | self._repo = repo.unfiltered() |
|
1194 | self._repo = repo.unfiltered() | |
1195 | self._state = state |
|
1195 | self._state = state | |
1196 | self.mtime = mtime |
|
1196 | self.mtime = mtime | |
1197 |
|
1197 | |||
1198 | return self._repo, True |
|
1198 | return self._repo, True | |
1199 |
|
1199 | |||
1200 | def _repostate(self): |
|
1200 | def _repostate(self): | |
1201 | state = [] |
|
1201 | state = [] | |
1202 | maxmtime = -1 |
|
1202 | maxmtime = -1 | |
1203 | for attr, fname in foi: |
|
1203 | for attr, fname in foi: | |
1204 | prefix = getattr(self._repo, attr) |
|
1204 | prefix = getattr(self._repo, attr) | |
1205 | p = os.path.join(prefix, fname) |
|
1205 | p = os.path.join(prefix, fname) | |
1206 | try: |
|
1206 | try: | |
1207 | st = os.stat(p) |
|
1207 | st = os.stat(p) | |
1208 | except OSError: |
|
1208 | except OSError: | |
1209 | st = os.stat(prefix) |
|
1209 | st = os.stat(prefix) | |
1210 | state.append((st[stat.ST_MTIME], st.st_size)) |
|
1210 | state.append((st[stat.ST_MTIME], st.st_size)) | |
1211 | maxmtime = max(maxmtime, st[stat.ST_MTIME]) |
|
1211 | maxmtime = max(maxmtime, st[stat.ST_MTIME]) | |
1212 |
|
1212 | |||
1213 | return tuple(state), maxmtime |
|
1213 | return tuple(state), maxmtime | |
1214 |
|
1214 | |||
1215 | def copy(self): |
|
1215 | def copy(self): | |
1216 | """Obtain a copy of this class instance. |
|
1216 | """Obtain a copy of this class instance. | |
1217 |
|
1217 | |||
1218 | A new localrepository instance is obtained. The new instance should be |
|
1218 | A new localrepository instance is obtained. The new instance should be | |
1219 | completely independent of the original. |
|
1219 | completely independent of the original. | |
1220 | """ |
|
1220 | """ | |
1221 | repo = repository(self._repo.baseui, self._repo.origroot) |
|
1221 | repo = repository(self._repo.baseui, self._repo.origroot) | |
1222 | if self._filtername: |
|
1222 | if self._filtername: | |
1223 | repo = repo.filtered(self._filtername) |
|
1223 | repo = repo.filtered(self._filtername) | |
1224 | else: |
|
1224 | else: | |
1225 | repo = repo.unfiltered() |
|
1225 | repo = repo.unfiltered() | |
1226 | c = cachedlocalrepo(repo) |
|
1226 | c = cachedlocalrepo(repo) | |
1227 | c._state = self._state |
|
1227 | c._state = self._state | |
1228 | c.mtime = self.mtime |
|
1228 | c.mtime = self.mtime | |
1229 | return c |
|
1229 | return c |
@@ -1,3089 +1,3089 b'' | |||||
1 | # localrepo.py - read/write repository class for mercurial |
|
1 | # localrepo.py - read/write repository class for mercurial | |
2 | # |
|
2 | # | |
3 | # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> |
|
3 | # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> | |
4 | # |
|
4 | # | |
5 | # This software may be used and distributed according to the terms of the |
|
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. |
|
6 | # GNU General Public License version 2 or any later version. | |
7 |
|
7 | |||
8 | from __future__ import absolute_import |
|
8 | from __future__ import absolute_import | |
9 |
|
9 | |||
10 | import errno |
|
10 | import errno | |
11 | import hashlib |
|
11 | import hashlib | |
12 | import os |
|
12 | import os | |
13 | import random |
|
13 | import random | |
14 | import sys |
|
14 | import sys | |
15 | import time |
|
15 | import time | |
16 | import weakref |
|
16 | import weakref | |
17 |
|
17 | |||
18 | from .i18n import _ |
|
18 | from .i18n import _ | |
19 | from .node import ( |
|
19 | from .node import ( | |
20 | bin, |
|
20 | bin, | |
21 | hex, |
|
21 | hex, | |
22 | nullid, |
|
22 | nullid, | |
23 | nullrev, |
|
23 | nullrev, | |
24 | short, |
|
24 | short, | |
25 | ) |
|
25 | ) | |
26 | from . import ( |
|
26 | from . import ( | |
27 | bookmarks, |
|
27 | bookmarks, | |
28 | branchmap, |
|
28 | branchmap, | |
29 | bundle2, |
|
29 | bundle2, | |
30 | changegroup, |
|
30 | changegroup, | |
31 | changelog, |
|
31 | changelog, | |
32 | color, |
|
32 | color, | |
33 | context, |
|
33 | context, | |
34 | dirstate, |
|
34 | dirstate, | |
35 | dirstateguard, |
|
35 | dirstateguard, | |
36 | discovery, |
|
36 | discovery, | |
37 | encoding, |
|
37 | encoding, | |
38 | error, |
|
38 | error, | |
39 | exchange, |
|
39 | exchange, | |
40 | extensions, |
|
40 | extensions, | |
41 | filelog, |
|
41 | filelog, | |
42 | hook, |
|
42 | hook, | |
43 | lock as lockmod, |
|
43 | lock as lockmod, | |
44 | manifest, |
|
44 | manifest, | |
45 | match as matchmod, |
|
45 | match as matchmod, | |
46 | merge as mergemod, |
|
46 | merge as mergemod, | |
47 | mergeutil, |
|
47 | mergeutil, | |
48 | namespaces, |
|
48 | namespaces, | |
49 | narrowspec, |
|
49 | narrowspec, | |
50 | obsolete, |
|
50 | obsolete, | |
51 | pathutil, |
|
51 | pathutil, | |
52 | phases, |
|
52 | phases, | |
53 | pushkey, |
|
53 | pushkey, | |
54 | pycompat, |
|
54 | pycompat, | |
55 | repository, |
|
55 | repository, | |
56 | repoview, |
|
56 | repoview, | |
57 | revset, |
|
57 | revset, | |
58 | revsetlang, |
|
58 | revsetlang, | |
59 | scmutil, |
|
59 | scmutil, | |
60 | sparse, |
|
60 | sparse, | |
61 | store as storemod, |
|
61 | store as storemod, | |
62 | subrepoutil, |
|
62 | subrepoutil, | |
63 | tags as tagsmod, |
|
63 | tags as tagsmod, | |
64 | transaction, |
|
64 | transaction, | |
65 | txnutil, |
|
65 | txnutil, | |
66 | util, |
|
66 | util, | |
67 | vfs as vfsmod, |
|
67 | vfs as vfsmod, | |
68 | ) |
|
68 | ) | |
69 | from .utils import ( |
|
69 | from .utils import ( | |
70 | interfaceutil, |
|
70 | interfaceutil, | |
71 | procutil, |
|
71 | procutil, | |
72 | stringutil, |
|
72 | stringutil, | |
73 | ) |
|
73 | ) | |
74 |
|
74 | |||
75 | from .revlogutils import ( |
|
75 | from .revlogutils import ( | |
76 | constants as revlogconst, |
|
76 | constants as revlogconst, | |
77 | ) |
|
77 | ) | |
78 |
|
78 | |||
79 | release = lockmod.release |
|
79 | release = lockmod.release | |
80 | urlerr = util.urlerr |
|
80 | urlerr = util.urlerr | |
81 | urlreq = util.urlreq |
|
81 | urlreq = util.urlreq | |
82 |
|
82 | |||
83 | # set of (path, vfs-location) tuples. vfs-location is: |
|
83 | # set of (path, vfs-location) tuples. vfs-location is: | |
84 | # - 'plain for vfs relative paths |
|
84 | # - 'plain for vfs relative paths | |
85 | # - '' for svfs relative paths |
|
85 | # - '' for svfs relative paths | |
86 | _cachedfiles = set() |
|
86 | _cachedfiles = set() | |
87 |
|
87 | |||
88 | class _basefilecache(scmutil.filecache): |
|
88 | class _basefilecache(scmutil.filecache): | |
89 | """All filecache usage on repo are done for logic that should be unfiltered |
|
89 | """All filecache usage on repo are done for logic that should be unfiltered | |
90 | """ |
|
90 | """ | |
91 | def __get__(self, repo, type=None): |
|
91 | def __get__(self, repo, type=None): | |
92 | if repo is None: |
|
92 | if repo is None: | |
93 | return self |
|
93 | return self | |
94 | # proxy to unfiltered __dict__ since filtered repo has no entry |
|
94 | # proxy to unfiltered __dict__ since filtered repo has no entry | |
95 | unfi = repo.unfiltered() |
|
95 | unfi = repo.unfiltered() | |
96 | try: |
|
96 | try: | |
97 | return unfi.__dict__[self.sname] |
|
97 | return unfi.__dict__[self.sname] | |
98 | except KeyError: |
|
98 | except KeyError: | |
99 | pass |
|
99 | pass | |
100 | return super(_basefilecache, self).__get__(unfi, type) |
|
100 | return super(_basefilecache, self).__get__(unfi, type) | |
101 |
|
101 | |||
102 | def set(self, repo, value): |
|
102 | def set(self, repo, value): | |
103 | return super(_basefilecache, self).set(repo.unfiltered(), value) |
|
103 | return super(_basefilecache, self).set(repo.unfiltered(), value) | |
104 |
|
104 | |||
105 | class repofilecache(_basefilecache): |
|
105 | class repofilecache(_basefilecache): | |
106 | """filecache for files in .hg but outside of .hg/store""" |
|
106 | """filecache for files in .hg but outside of .hg/store""" | |
107 | def __init__(self, *paths): |
|
107 | def __init__(self, *paths): | |
108 | super(repofilecache, self).__init__(*paths) |
|
108 | super(repofilecache, self).__init__(*paths) | |
109 | for path in paths: |
|
109 | for path in paths: | |
110 | _cachedfiles.add((path, 'plain')) |
|
110 | _cachedfiles.add((path, 'plain')) | |
111 |
|
111 | |||
112 | def join(self, obj, fname): |
|
112 | def join(self, obj, fname): | |
113 | return obj.vfs.join(fname) |
|
113 | return obj.vfs.join(fname) | |
114 |
|
114 | |||
115 | class storecache(_basefilecache): |
|
115 | class storecache(_basefilecache): | |
116 | """filecache for files in the store""" |
|
116 | """filecache for files in the store""" | |
117 | def __init__(self, *paths): |
|
117 | def __init__(self, *paths): | |
118 | super(storecache, self).__init__(*paths) |
|
118 | super(storecache, self).__init__(*paths) | |
119 | for path in paths: |
|
119 | for path in paths: | |
120 | _cachedfiles.add((path, '')) |
|
120 | _cachedfiles.add((path, '')) | |
121 |
|
121 | |||
122 | def join(self, obj, fname): |
|
122 | def join(self, obj, fname): | |
123 | return obj.sjoin(fname) |
|
123 | return obj.sjoin(fname) | |
124 |
|
124 | |||
125 | def isfilecached(repo, name): |
|
125 | def isfilecached(repo, name): | |
126 | """check if a repo has already cached "name" filecache-ed property |
|
126 | """check if a repo has already cached "name" filecache-ed property | |
127 |
|
127 | |||
128 | This returns (cachedobj-or-None, iscached) tuple. |
|
128 | This returns (cachedobj-or-None, iscached) tuple. | |
129 | """ |
|
129 | """ | |
130 | cacheentry = repo.unfiltered()._filecache.get(name, None) |
|
130 | cacheentry = repo.unfiltered()._filecache.get(name, None) | |
131 | if not cacheentry: |
|
131 | if not cacheentry: | |
132 | return None, False |
|
132 | return None, False | |
133 | return cacheentry.obj, True |
|
133 | return cacheentry.obj, True | |
134 |
|
134 | |||
135 | class unfilteredpropertycache(util.propertycache): |
|
135 | class unfilteredpropertycache(util.propertycache): | |
136 | """propertycache that apply to unfiltered repo only""" |
|
136 | """propertycache that apply to unfiltered repo only""" | |
137 |
|
137 | |||
138 | def __get__(self, repo, type=None): |
|
138 | def __get__(self, repo, type=None): | |
139 | unfi = repo.unfiltered() |
|
139 | unfi = repo.unfiltered() | |
140 | if unfi is repo: |
|
140 | if unfi is repo: | |
141 | return super(unfilteredpropertycache, self).__get__(unfi) |
|
141 | return super(unfilteredpropertycache, self).__get__(unfi) | |
142 | return getattr(unfi, self.name) |
|
142 | return getattr(unfi, self.name) | |
143 |
|
143 | |||
144 | class filteredpropertycache(util.propertycache): |
|
144 | class filteredpropertycache(util.propertycache): | |
145 | """propertycache that must take filtering in account""" |
|
145 | """propertycache that must take filtering in account""" | |
146 |
|
146 | |||
147 | def cachevalue(self, obj, value): |
|
147 | def cachevalue(self, obj, value): | |
148 | object.__setattr__(obj, self.name, value) |
|
148 | object.__setattr__(obj, self.name, value) | |
149 |
|
149 | |||
150 |
|
150 | |||
151 | def hasunfilteredcache(repo, name): |
|
151 | def hasunfilteredcache(repo, name): | |
152 | """check if a repo has an unfilteredpropertycache value for <name>""" |
|
152 | """check if a repo has an unfilteredpropertycache value for <name>""" | |
153 | return name in vars(repo.unfiltered()) |
|
153 | return name in vars(repo.unfiltered()) | |
154 |
|
154 | |||
155 | def unfilteredmethod(orig): |
|
155 | def unfilteredmethod(orig): | |
156 | """decorate method that always need to be run on unfiltered version""" |
|
156 | """decorate method that always need to be run on unfiltered version""" | |
157 | def wrapper(repo, *args, **kwargs): |
|
157 | def wrapper(repo, *args, **kwargs): | |
158 | return orig(repo.unfiltered(), *args, **kwargs) |
|
158 | return orig(repo.unfiltered(), *args, **kwargs) | |
159 | return wrapper |
|
159 | return wrapper | |
160 |
|
160 | |||
161 | moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle', |
|
161 | moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle', | |
162 | 'unbundle'} |
|
162 | 'unbundle'} | |
163 | legacycaps = moderncaps.union({'changegroupsubset'}) |
|
163 | legacycaps = moderncaps.union({'changegroupsubset'}) | |
164 |
|
164 | |||
165 | @interfaceutil.implementer(repository.ipeercommandexecutor) |
|
165 | @interfaceutil.implementer(repository.ipeercommandexecutor) | |
166 | class localcommandexecutor(object): |
|
166 | class localcommandexecutor(object): | |
167 | def __init__(self, peer): |
|
167 | def __init__(self, peer): | |
168 | self._peer = peer |
|
168 | self._peer = peer | |
169 | self._sent = False |
|
169 | self._sent = False | |
170 | self._closed = False |
|
170 | self._closed = False | |
171 |
|
171 | |||
172 | def __enter__(self): |
|
172 | def __enter__(self): | |
173 | return self |
|
173 | return self | |
174 |
|
174 | |||
175 | def __exit__(self, exctype, excvalue, exctb): |
|
175 | def __exit__(self, exctype, excvalue, exctb): | |
176 | self.close() |
|
176 | self.close() | |
177 |
|
177 | |||
178 | def callcommand(self, command, args): |
|
178 | def callcommand(self, command, args): | |
179 | if self._sent: |
|
179 | if self._sent: | |
180 | raise error.ProgrammingError('callcommand() cannot be used after ' |
|
180 | raise error.ProgrammingError('callcommand() cannot be used after ' | |
181 | 'sendcommands()') |
|
181 | 'sendcommands()') | |
182 |
|
182 | |||
183 | if self._closed: |
|
183 | if self._closed: | |
184 | raise error.ProgrammingError('callcommand() cannot be used after ' |
|
184 | raise error.ProgrammingError('callcommand() cannot be used after ' | |
185 | 'close()') |
|
185 | 'close()') | |
186 |
|
186 | |||
187 | # We don't need to support anything fancy. Just call the named |
|
187 | # We don't need to support anything fancy. Just call the named | |
188 | # method on the peer and return a resolved future. |
|
188 | # method on the peer and return a resolved future. | |
189 | fn = getattr(self._peer, pycompat.sysstr(command)) |
|
189 | fn = getattr(self._peer, pycompat.sysstr(command)) | |
190 |
|
190 | |||
191 | f = pycompat.futures.Future() |
|
191 | f = pycompat.futures.Future() | |
192 |
|
192 | |||
193 | try: |
|
193 | try: | |
194 | result = fn(**pycompat.strkwargs(args)) |
|
194 | result = fn(**pycompat.strkwargs(args)) | |
195 | except Exception: |
|
195 | except Exception: | |
196 | pycompat.future_set_exception_info(f, sys.exc_info()[1:]) |
|
196 | pycompat.future_set_exception_info(f, sys.exc_info()[1:]) | |
197 | else: |
|
197 | else: | |
198 | f.set_result(result) |
|
198 | f.set_result(result) | |
199 |
|
199 | |||
200 | return f |
|
200 | return f | |
201 |
|
201 | |||
202 | def sendcommands(self): |
|
202 | def sendcommands(self): | |
203 | self._sent = True |
|
203 | self._sent = True | |
204 |
|
204 | |||
205 | def close(self): |
|
205 | def close(self): | |
206 | self._closed = True |
|
206 | self._closed = True | |
207 |
|
207 | |||
208 | @interfaceutil.implementer(repository.ipeercommands) |
|
208 | @interfaceutil.implementer(repository.ipeercommands) | |
209 | class localpeer(repository.peer): |
|
209 | class localpeer(repository.peer): | |
210 | '''peer for a local repo; reflects only the most recent API''' |
|
210 | '''peer for a local repo; reflects only the most recent API''' | |
211 |
|
211 | |||
212 | def __init__(self, repo, caps=None): |
|
212 | def __init__(self, repo, caps=None): | |
213 | super(localpeer, self).__init__() |
|
213 | super(localpeer, self).__init__() | |
214 |
|
214 | |||
215 | if caps is None: |
|
215 | if caps is None: | |
216 | caps = moderncaps.copy() |
|
216 | caps = moderncaps.copy() | |
217 | self._repo = repo.filtered('served') |
|
217 | self._repo = repo.filtered('served') | |
218 | self.ui = repo.ui |
|
218 | self.ui = repo.ui | |
219 | self._caps = repo._restrictcapabilities(caps) |
|
219 | self._caps = repo._restrictcapabilities(caps) | |
220 |
|
220 | |||
221 | # Begin of _basepeer interface. |
|
221 | # Begin of _basepeer interface. | |
222 |
|
222 | |||
223 | def url(self): |
|
223 | def url(self): | |
224 | return self._repo.url() |
|
224 | return self._repo.url() | |
225 |
|
225 | |||
226 | def local(self): |
|
226 | def local(self): | |
227 | return self._repo |
|
227 | return self._repo | |
228 |
|
228 | |||
229 | def peer(self): |
|
229 | def peer(self): | |
230 | return self |
|
230 | return self | |
231 |
|
231 | |||
232 | def canpush(self): |
|
232 | def canpush(self): | |
233 | return True |
|
233 | return True | |
234 |
|
234 | |||
235 | def close(self): |
|
235 | def close(self): | |
236 | self._repo.close() |
|
236 | self._repo.close() | |
237 |
|
237 | |||
238 | # End of _basepeer interface. |
|
238 | # End of _basepeer interface. | |
239 |
|
239 | |||
240 | # Begin of _basewirecommands interface. |
|
240 | # Begin of _basewirecommands interface. | |
241 |
|
241 | |||
242 | def branchmap(self): |
|
242 | def branchmap(self): | |
243 | return self._repo.branchmap() |
|
243 | return self._repo.branchmap() | |
244 |
|
244 | |||
245 | def capabilities(self): |
|
245 | def capabilities(self): | |
246 | return self._caps |
|
246 | return self._caps | |
247 |
|
247 | |||
248 | def clonebundles(self): |
|
248 | def clonebundles(self): | |
249 | return self._repo.tryread('clonebundles.manifest') |
|
249 | return self._repo.tryread('clonebundles.manifest') | |
250 |
|
250 | |||
251 | def debugwireargs(self, one, two, three=None, four=None, five=None): |
|
251 | def debugwireargs(self, one, two, three=None, four=None, five=None): | |
252 | """Used to test argument passing over the wire""" |
|
252 | """Used to test argument passing over the wire""" | |
253 | return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three), |
|
253 | return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three), | |
254 | pycompat.bytestr(four), |
|
254 | pycompat.bytestr(four), | |
255 | pycompat.bytestr(five)) |
|
255 | pycompat.bytestr(five)) | |
256 |
|
256 | |||
257 | def getbundle(self, source, heads=None, common=None, bundlecaps=None, |
|
257 | def getbundle(self, source, heads=None, common=None, bundlecaps=None, | |
258 | **kwargs): |
|
258 | **kwargs): | |
259 | chunks = exchange.getbundlechunks(self._repo, source, heads=heads, |
|
259 | chunks = exchange.getbundlechunks(self._repo, source, heads=heads, | |
260 | common=common, bundlecaps=bundlecaps, |
|
260 | common=common, bundlecaps=bundlecaps, | |
261 | **kwargs)[1] |
|
261 | **kwargs)[1] | |
262 | cb = util.chunkbuffer(chunks) |
|
262 | cb = util.chunkbuffer(chunks) | |
263 |
|
263 | |||
264 | if exchange.bundle2requested(bundlecaps): |
|
264 | if exchange.bundle2requested(bundlecaps): | |
265 | # When requesting a bundle2, getbundle returns a stream to make the |
|
265 | # When requesting a bundle2, getbundle returns a stream to make the | |
266 | # wire level function happier. We need to build a proper object |
|
266 | # wire level function happier. We need to build a proper object | |
267 | # from it in local peer. |
|
267 | # from it in local peer. | |
268 | return bundle2.getunbundler(self.ui, cb) |
|
268 | return bundle2.getunbundler(self.ui, cb) | |
269 | else: |
|
269 | else: | |
270 | return changegroup.getunbundler('01', cb, None) |
|
270 | return changegroup.getunbundler('01', cb, None) | |
271 |
|
271 | |||
272 | def heads(self): |
|
272 | def heads(self): | |
273 | return self._repo.heads() |
|
273 | return self._repo.heads() | |
274 |
|
274 | |||
275 | def known(self, nodes): |
|
275 | def known(self, nodes): | |
276 | return self._repo.known(nodes) |
|
276 | return self._repo.known(nodes) | |
277 |
|
277 | |||
278 | def listkeys(self, namespace): |
|
278 | def listkeys(self, namespace): | |
279 | return self._repo.listkeys(namespace) |
|
279 | return self._repo.listkeys(namespace) | |
280 |
|
280 | |||
281 | def lookup(self, key): |
|
281 | def lookup(self, key): | |
282 | return self._repo.lookup(key) |
|
282 | return self._repo.lookup(key) | |
283 |
|
283 | |||
284 | def pushkey(self, namespace, key, old, new): |
|
284 | def pushkey(self, namespace, key, old, new): | |
285 | return self._repo.pushkey(namespace, key, old, new) |
|
285 | return self._repo.pushkey(namespace, key, old, new) | |
286 |
|
286 | |||
287 | def stream_out(self): |
|
287 | def stream_out(self): | |
288 | raise error.Abort(_('cannot perform stream clone against local ' |
|
288 | raise error.Abort(_('cannot perform stream clone against local ' | |
289 | 'peer')) |
|
289 | 'peer')) | |
290 |
|
290 | |||
291 | def unbundle(self, bundle, heads, url): |
|
291 | def unbundle(self, bundle, heads, url): | |
292 | """apply a bundle on a repo |
|
292 | """apply a bundle on a repo | |
293 |
|
293 | |||
294 | This function handles the repo locking itself.""" |
|
294 | This function handles the repo locking itself.""" | |
295 | try: |
|
295 | try: | |
296 | try: |
|
296 | try: | |
297 | bundle = exchange.readbundle(self.ui, bundle, None) |
|
297 | bundle = exchange.readbundle(self.ui, bundle, None) | |
298 | ret = exchange.unbundle(self._repo, bundle, heads, 'push', url) |
|
298 | ret = exchange.unbundle(self._repo, bundle, heads, 'push', url) | |
299 | if util.safehasattr(ret, 'getchunks'): |
|
299 | if util.safehasattr(ret, 'getchunks'): | |
300 | # This is a bundle20 object, turn it into an unbundler. |
|
300 | # This is a bundle20 object, turn it into an unbundler. | |
301 | # This little dance should be dropped eventually when the |
|
301 | # This little dance should be dropped eventually when the | |
302 | # API is finally improved. |
|
302 | # API is finally improved. | |
303 | stream = util.chunkbuffer(ret.getchunks()) |
|
303 | stream = util.chunkbuffer(ret.getchunks()) | |
304 | ret = bundle2.getunbundler(self.ui, stream) |
|
304 | ret = bundle2.getunbundler(self.ui, stream) | |
305 | return ret |
|
305 | return ret | |
306 | except Exception as exc: |
|
306 | except Exception as exc: | |
307 | # If the exception contains output salvaged from a bundle2 |
|
307 | # If the exception contains output salvaged from a bundle2 | |
308 | # reply, we need to make sure it is printed before continuing |
|
308 | # reply, we need to make sure it is printed before continuing | |
309 | # to fail. So we build a bundle2 with such output and consume |
|
309 | # to fail. So we build a bundle2 with such output and consume | |
310 | # it directly. |
|
310 | # it directly. | |
311 | # |
|
311 | # | |
312 | # This is not very elegant but allows a "simple" solution for |
|
312 | # This is not very elegant but allows a "simple" solution for | |
313 | # issue4594 |
|
313 | # issue4594 | |
314 | output = getattr(exc, '_bundle2salvagedoutput', ()) |
|
314 | output = getattr(exc, '_bundle2salvagedoutput', ()) | |
315 | if output: |
|
315 | if output: | |
316 | bundler = bundle2.bundle20(self._repo.ui) |
|
316 | bundler = bundle2.bundle20(self._repo.ui) | |
317 | for out in output: |
|
317 | for out in output: | |
318 | bundler.addpart(out) |
|
318 | bundler.addpart(out) | |
319 | stream = util.chunkbuffer(bundler.getchunks()) |
|
319 | stream = util.chunkbuffer(bundler.getchunks()) | |
320 | b = bundle2.getunbundler(self.ui, stream) |
|
320 | b = bundle2.getunbundler(self.ui, stream) | |
321 | bundle2.processbundle(self._repo, b) |
|
321 | bundle2.processbundle(self._repo, b) | |
322 | raise |
|
322 | raise | |
323 | except error.PushRaced as exc: |
|
323 | except error.PushRaced as exc: | |
324 | raise error.ResponseError(_('push failed:'), |
|
324 | raise error.ResponseError(_('push failed:'), | |
325 | stringutil.forcebytestr(exc)) |
|
325 | stringutil.forcebytestr(exc)) | |
326 |
|
326 | |||
327 | # End of _basewirecommands interface. |
|
327 | # End of _basewirecommands interface. | |
328 |
|
328 | |||
329 | # Begin of peer interface. |
|
329 | # Begin of peer interface. | |
330 |
|
330 | |||
331 | def commandexecutor(self): |
|
331 | def commandexecutor(self): | |
332 | return localcommandexecutor(self) |
|
332 | return localcommandexecutor(self) | |
333 |
|
333 | |||
334 | # End of peer interface. |
|
334 | # End of peer interface. | |
335 |
|
335 | |||
336 | @interfaceutil.implementer(repository.ipeerlegacycommands) |
|
336 | @interfaceutil.implementer(repository.ipeerlegacycommands) | |
337 | class locallegacypeer(localpeer): |
|
337 | class locallegacypeer(localpeer): | |
338 | '''peer extension which implements legacy methods too; used for tests with |
|
338 | '''peer extension which implements legacy methods too; used for tests with | |
339 | restricted capabilities''' |
|
339 | restricted capabilities''' | |
340 |
|
340 | |||
341 | def __init__(self, repo): |
|
341 | def __init__(self, repo): | |
342 | super(locallegacypeer, self).__init__(repo, caps=legacycaps) |
|
342 | super(locallegacypeer, self).__init__(repo, caps=legacycaps) | |
343 |
|
343 | |||
344 | # Begin of baselegacywirecommands interface. |
|
344 | # Begin of baselegacywirecommands interface. | |
345 |
|
345 | |||
346 | def between(self, pairs): |
|
346 | def between(self, pairs): | |
347 | return self._repo.between(pairs) |
|
347 | return self._repo.between(pairs) | |
348 |
|
348 | |||
349 | def branches(self, nodes): |
|
349 | def branches(self, nodes): | |
350 | return self._repo.branches(nodes) |
|
350 | return self._repo.branches(nodes) | |
351 |
|
351 | |||
352 | def changegroup(self, nodes, source): |
|
352 | def changegroup(self, nodes, source): | |
353 | outgoing = discovery.outgoing(self._repo, missingroots=nodes, |
|
353 | outgoing = discovery.outgoing(self._repo, missingroots=nodes, | |
354 | missingheads=self._repo.heads()) |
|
354 | missingheads=self._repo.heads()) | |
355 | return changegroup.makechangegroup(self._repo, outgoing, '01', source) |
|
355 | return changegroup.makechangegroup(self._repo, outgoing, '01', source) | |
356 |
|
356 | |||
357 | def changegroupsubset(self, bases, heads, source): |
|
357 | def changegroupsubset(self, bases, heads, source): | |
358 | outgoing = discovery.outgoing(self._repo, missingroots=bases, |
|
358 | outgoing = discovery.outgoing(self._repo, missingroots=bases, | |
359 | missingheads=heads) |
|
359 | missingheads=heads) | |
360 | return changegroup.makechangegroup(self._repo, outgoing, '01', source) |
|
360 | return changegroup.makechangegroup(self._repo, outgoing, '01', source) | |
361 |
|
361 | |||
362 | # End of baselegacywirecommands interface. |
|
362 | # End of baselegacywirecommands interface. | |
363 |
|
363 | |||
364 | # Increment the sub-version when the revlog v2 format changes to lock out old |
|
364 | # Increment the sub-version when the revlog v2 format changes to lock out old | |
365 | # clients. |
|
365 | # clients. | |
366 | REVLOGV2_REQUIREMENT = 'exp-revlogv2.1' |
|
366 | REVLOGV2_REQUIREMENT = 'exp-revlogv2.1' | |
367 |
|
367 | |||
368 | # A repository with the sparserevlog feature will have delta chains that |
|
368 | # A repository with the sparserevlog feature will have delta chains that | |
369 | # can spread over a larger span. Sparse reading cuts these large spans into |
|
369 | # can spread over a larger span. Sparse reading cuts these large spans into | |
370 | # pieces, so that each piece isn't too big. |
|
370 | # pieces, so that each piece isn't too big. | |
371 | # Without the sparserevlog capability, reading from the repository could use |
|
371 | # Without the sparserevlog capability, reading from the repository could use | |
372 | # huge amounts of memory, because the whole span would be read at once, |
|
372 | # huge amounts of memory, because the whole span would be read at once, | |
373 | # including all the intermediate revisions that aren't pertinent for the chain. |
|
373 | # including all the intermediate revisions that aren't pertinent for the chain. | |
374 | # This is why once a repository has enabled sparse-read, it becomes required. |
|
374 | # This is why once a repository has enabled sparse-read, it becomes required. | |
375 | SPARSEREVLOG_REQUIREMENT = 'sparserevlog' |
|
375 | SPARSEREVLOG_REQUIREMENT = 'sparserevlog' | |
376 |
|
376 | |||
377 | # Functions receiving (ui, features) that extensions can register to impact |
|
377 | # Functions receiving (ui, features) that extensions can register to impact | |
378 | # the ability to load repositories with custom requirements. Only |
|
378 | # the ability to load repositories with custom requirements. Only | |
379 | # functions defined in loaded extensions are called. |
|
379 | # functions defined in loaded extensions are called. | |
380 | # |
|
380 | # | |
381 | # The function receives a set of requirement strings that the repository |
|
381 | # The function receives a set of requirement strings that the repository | |
382 | # is capable of opening. Functions will typically add elements to the |
|
382 | # is capable of opening. Functions will typically add elements to the | |
383 | # set to reflect that the extension knows how to handle that requirements. |
|
383 | # set to reflect that the extension knows how to handle that requirements. | |
384 | featuresetupfuncs = set() |
|
384 | featuresetupfuncs = set() | |
385 |
|
385 | |||
386 | def makelocalrepository(baseui, path, intents=None): |
|
386 | def makelocalrepository(baseui, path, intents=None): | |
387 | """Create a local repository object. |
|
387 | """Create a local repository object. | |
388 |
|
388 | |||
389 | Given arguments needed to construct a local repository, this function |
|
389 | Given arguments needed to construct a local repository, this function | |
390 | performs various early repository loading functionality (such as |
|
390 | performs various early repository loading functionality (such as | |
391 | reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that |
|
391 | reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that | |
392 | the repository can be opened, derives a type suitable for representing |
|
392 | the repository can be opened, derives a type suitable for representing | |
393 | that repository, and returns an instance of it. |
|
393 | that repository, and returns an instance of it. | |
394 |
|
394 | |||
395 | The returned object conforms to the ``repository.completelocalrepository`` |
|
395 | The returned object conforms to the ``repository.completelocalrepository`` | |
396 | interface. |
|
396 | interface. | |
397 |
|
397 | |||
398 | The repository type is derived by calling a series of factory functions |
|
398 | The repository type is derived by calling a series of factory functions | |
399 | for each aspect/interface of the final repository. These are defined by |
|
399 | for each aspect/interface of the final repository. These are defined by | |
400 | ``REPO_INTERFACES``. |
|
400 | ``REPO_INTERFACES``. | |
401 |
|
401 | |||
402 | Each factory function is called to produce a type implementing a specific |
|
402 | Each factory function is called to produce a type implementing a specific | |
403 | interface. The cumulative list of returned types will be combined into a |
|
403 | interface. The cumulative list of returned types will be combined into a | |
404 | new type and that type will be instantiated to represent the local |
|
404 | new type and that type will be instantiated to represent the local | |
405 | repository. |
|
405 | repository. | |
406 |
|
406 | |||
407 | The factory functions each receive various state that may be consulted |
|
407 | The factory functions each receive various state that may be consulted | |
408 | as part of deriving a type. |
|
408 | as part of deriving a type. | |
409 |
|
409 | |||
410 | Extensions should wrap these factory functions to customize repository type |
|
410 | Extensions should wrap these factory functions to customize repository type | |
411 | creation. Note that an extension's wrapped function may be called even if |
|
411 | creation. Note that an extension's wrapped function may be called even if | |
412 | that extension is not loaded for the repo being constructed. Extensions |
|
412 | that extension is not loaded for the repo being constructed. Extensions | |
413 | should check if their ``__name__`` appears in the |
|
413 | should check if their ``__name__`` appears in the | |
414 | ``extensionmodulenames`` set passed to the factory function and no-op if |
|
414 | ``extensionmodulenames`` set passed to the factory function and no-op if | |
415 | not. |
|
415 | not. | |
416 | """ |
|
416 | """ | |
417 | ui = baseui.copy() |
|
417 | ui = baseui.copy() | |
418 | # Prevent copying repo configuration. |
|
418 | # Prevent copying repo configuration. | |
419 | ui.copy = baseui.copy |
|
419 | ui.copy = baseui.copy | |
420 |
|
420 | |||
421 | # Working directory VFS rooted at repository root. |
|
421 | # Working directory VFS rooted at repository root. | |
422 | wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True) |
|
422 | wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True) | |
423 |
|
423 | |||
424 | # Main VFS for .hg/ directory. |
|
424 | # Main VFS for .hg/ directory. | |
425 | hgpath = wdirvfs.join(b'.hg') |
|
425 | hgpath = wdirvfs.join(b'.hg') | |
426 | hgvfs = vfsmod.vfs(hgpath, cacheaudited=True) |
|
426 | hgvfs = vfsmod.vfs(hgpath, cacheaudited=True) | |
427 |
|
427 | |||
428 | # The .hg/ path should exist and should be a directory. All other |
|
428 | # The .hg/ path should exist and should be a directory. All other | |
429 | # cases are errors. |
|
429 | # cases are errors. | |
430 | if not hgvfs.isdir(): |
|
430 | if not hgvfs.isdir(): | |
431 | try: |
|
431 | try: | |
432 | hgvfs.stat() |
|
432 | hgvfs.stat() | |
433 | except OSError as e: |
|
433 | except OSError as e: | |
434 | if e.errno != errno.ENOENT: |
|
434 | if e.errno != errno.ENOENT: | |
435 | raise |
|
435 | raise | |
436 |
|
436 | |||
437 | raise error.RepoError(_(b'repository %s not found') % path) |
|
437 | raise error.RepoError(_(b'repository %s not found') % path) | |
438 |
|
438 | |||
439 | # .hg/requires file contains a newline-delimited list of |
|
439 | # .hg/requires file contains a newline-delimited list of | |
440 | # features/capabilities the opener (us) must have in order to use |
|
440 | # features/capabilities the opener (us) must have in order to use | |
441 | # the repository. This file was introduced in Mercurial 0.9.2, |
|
441 | # the repository. This file was introduced in Mercurial 0.9.2, | |
442 | # which means very old repositories may not have one. We assume |
|
442 | # which means very old repositories may not have one. We assume | |
443 | # a missing file translates to no requirements. |
|
443 | # a missing file translates to no requirements. | |
444 | try: |
|
444 | try: | |
445 | requirements = set(hgvfs.read(b'requires').splitlines()) |
|
445 | requirements = set(hgvfs.read(b'requires').splitlines()) | |
446 | except IOError as e: |
|
446 | except IOError as e: | |
447 | if e.errno != errno.ENOENT: |
|
447 | if e.errno != errno.ENOENT: | |
448 | raise |
|
448 | raise | |
449 | requirements = set() |
|
449 | requirements = set() | |
450 |
|
450 | |||
451 | # The .hg/hgrc file may load extensions or contain config options |
|
451 | # The .hg/hgrc file may load extensions or contain config options | |
452 | # that influence repository construction. Attempt to load it and |
|
452 | # that influence repository construction. Attempt to load it and | |
453 | # process any new extensions that it may have pulled in. |
|
453 | # process any new extensions that it may have pulled in. | |
454 | if loadhgrc(ui, wdirvfs, hgvfs, requirements): |
|
454 | if loadhgrc(ui, wdirvfs, hgvfs, requirements): | |
455 | afterhgrcload(ui, wdirvfs, hgvfs, requirements) |
|
455 | afterhgrcload(ui, wdirvfs, hgvfs, requirements) | |
456 | extensions.loadall(ui) |
|
456 | extensions.loadall(ui) | |
457 | extensions.populateui(ui) |
|
457 | extensions.populateui(ui) | |
458 |
|
458 | |||
459 | # Set of module names of extensions loaded for this repository. |
|
459 | # Set of module names of extensions loaded for this repository. | |
460 | extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)} |
|
460 | extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)} | |
461 |
|
461 | |||
462 | supportedrequirements = gathersupportedrequirements(ui) |
|
462 | supportedrequirements = gathersupportedrequirements(ui) | |
463 |
|
463 | |||
464 | # We first validate the requirements are known. |
|
464 | # We first validate the requirements are known. | |
465 | ensurerequirementsrecognized(requirements, supportedrequirements) |
|
465 | ensurerequirementsrecognized(requirements, supportedrequirements) | |
466 |
|
466 | |||
467 | # Then we validate that the known set is reasonable to use together. |
|
467 | # Then we validate that the known set is reasonable to use together. | |
468 | ensurerequirementscompatible(ui, requirements) |
|
468 | ensurerequirementscompatible(ui, requirements) | |
469 |
|
469 | |||
470 | # TODO there are unhandled edge cases related to opening repositories with |
|
470 | # TODO there are unhandled edge cases related to opening repositories with | |
471 | # shared storage. If storage is shared, we should also test for requirements |
|
471 | # shared storage. If storage is shared, we should also test for requirements | |
472 | # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in |
|
472 | # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in | |
473 | # that repo, as that repo may load extensions needed to open it. This is a |
|
473 | # that repo, as that repo may load extensions needed to open it. This is a | |
474 | # bit complicated because we don't want the other hgrc to overwrite settings |
|
474 | # bit complicated because we don't want the other hgrc to overwrite settings | |
475 | # in this hgrc. |
|
475 | # in this hgrc. | |
476 | # |
|
476 | # | |
477 | # This bug is somewhat mitigated by the fact that we copy the .hg/requires |
|
477 | # This bug is somewhat mitigated by the fact that we copy the .hg/requires | |
478 | # file when sharing repos. But if a requirement is added after the share is |
|
478 | # file when sharing repos. But if a requirement is added after the share is | |
479 | # performed, thereby introducing a new requirement for the opener, we may |
|
479 | # performed, thereby introducing a new requirement for the opener, we may | |
480 | # will not see that and could encounter a run-time error interacting with |
|
480 | # will not see that and could encounter a run-time error interacting with | |
481 | # that shared store since it has an unknown-to-us requirement. |
|
481 | # that shared store since it has an unknown-to-us requirement. | |
482 |
|
482 | |||
483 | # At this point, we know we should be capable of opening the repository. |
|
483 | # At this point, we know we should be capable of opening the repository. | |
484 | # Now get on with doing that. |
|
484 | # Now get on with doing that. | |
485 |
|
485 | |||
486 | features = set() |
|
486 | features = set() | |
487 |
|
487 | |||
488 | # The "store" part of the repository holds versioned data. How it is |
|
488 | # The "store" part of the repository holds versioned data. How it is | |
489 | # accessed is determined by various requirements. The ``shared`` or |
|
489 | # accessed is determined by various requirements. The ``shared`` or | |
490 | # ``relshared`` requirements indicate the store lives in the path contained |
|
490 | # ``relshared`` requirements indicate the store lives in the path contained | |
491 | # in the ``.hg/sharedpath`` file. This is an absolute path for |
|
491 | # in the ``.hg/sharedpath`` file. This is an absolute path for | |
492 | # ``shared`` and relative to ``.hg/`` for ``relshared``. |
|
492 | # ``shared`` and relative to ``.hg/`` for ``relshared``. | |
493 | if b'shared' in requirements or b'relshared' in requirements: |
|
493 | if b'shared' in requirements or b'relshared' in requirements: | |
494 | sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n') |
|
494 | sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n') | |
495 | if b'relshared' in requirements: |
|
495 | if b'relshared' in requirements: | |
496 | sharedpath = hgvfs.join(sharedpath) |
|
496 | sharedpath = hgvfs.join(sharedpath) | |
497 |
|
497 | |||
498 | sharedvfs = vfsmod.vfs(sharedpath, realpath=True) |
|
498 | sharedvfs = vfsmod.vfs(sharedpath, realpath=True) | |
499 |
|
499 | |||
500 | if not sharedvfs.exists(): |
|
500 | if not sharedvfs.exists(): | |
501 | raise error.RepoError(_(b'.hg/sharedpath points to nonexistent ' |
|
501 | raise error.RepoError(_(b'.hg/sharedpath points to nonexistent ' | |
502 | b'directory %s') % sharedvfs.base) |
|
502 | b'directory %s') % sharedvfs.base) | |
503 |
|
503 | |||
504 | features.add(repository.REPO_FEATURE_SHARED_STORAGE) |
|
504 | features.add(repository.REPO_FEATURE_SHARED_STORAGE) | |
505 |
|
505 | |||
506 | storebasepath = sharedvfs.base |
|
506 | storebasepath = sharedvfs.base | |
507 | cachepath = sharedvfs.join(b'cache') |
|
507 | cachepath = sharedvfs.join(b'cache') | |
508 | else: |
|
508 | else: | |
509 | storebasepath = hgvfs.base |
|
509 | storebasepath = hgvfs.base | |
510 | cachepath = hgvfs.join(b'cache') |
|
510 | cachepath = hgvfs.join(b'cache') | |
511 | wcachepath = hgvfs.join(b'wcache') |
|
511 | wcachepath = hgvfs.join(b'wcache') | |
512 |
|
512 | |||
513 |
|
513 | |||
514 | # The store has changed over time and the exact layout is dictated by |
|
514 | # The store has changed over time and the exact layout is dictated by | |
515 | # requirements. The store interface abstracts differences across all |
|
515 | # requirements. The store interface abstracts differences across all | |
516 | # of them. |
|
516 | # of them. | |
517 | store = makestore(requirements, storebasepath, |
|
517 | store = makestore(requirements, storebasepath, | |
518 | lambda base: vfsmod.vfs(base, cacheaudited=True)) |
|
518 | lambda base: vfsmod.vfs(base, cacheaudited=True)) | |
519 | hgvfs.createmode = store.createmode |
|
519 | hgvfs.createmode = store.createmode | |
520 |
|
520 | |||
521 | storevfs = store.vfs |
|
521 | storevfs = store.vfs | |
522 | storevfs.options = resolvestorevfsoptions(ui, requirements, features) |
|
522 | storevfs.options = resolvestorevfsoptions(ui, requirements, features) | |
523 |
|
523 | |||
524 | # The cache vfs is used to manage cache files. |
|
524 | # The cache vfs is used to manage cache files. | |
525 | cachevfs = vfsmod.vfs(cachepath, cacheaudited=True) |
|
525 | cachevfs = vfsmod.vfs(cachepath, cacheaudited=True) | |
526 | cachevfs.createmode = store.createmode |
|
526 | cachevfs.createmode = store.createmode | |
527 | # The cache vfs is used to manage cache files related to the working copy |
|
527 | # The cache vfs is used to manage cache files related to the working copy | |
528 | wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True) |
|
528 | wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True) | |
529 | wcachevfs.createmode = store.createmode |
|
529 | wcachevfs.createmode = store.createmode | |
530 |
|
530 | |||
531 | # Now resolve the type for the repository object. We do this by repeatedly |
|
531 | # Now resolve the type for the repository object. We do this by repeatedly | |
532 | # calling a factory function to produces types for specific aspects of the |
|
532 | # calling a factory function to produces types for specific aspects of the | |
533 | # repo's operation. The aggregate returned types are used as base classes |
|
533 | # repo's operation. The aggregate returned types are used as base classes | |
534 | # for a dynamically-derived type, which will represent our new repository. |
|
534 | # for a dynamically-derived type, which will represent our new repository. | |
535 |
|
535 | |||
536 | bases = [] |
|
536 | bases = [] | |
537 | extrastate = {} |
|
537 | extrastate = {} | |
538 |
|
538 | |||
539 | for iface, fn in REPO_INTERFACES: |
|
539 | for iface, fn in REPO_INTERFACES: | |
540 | # We pass all potentially useful state to give extensions tons of |
|
540 | # We pass all potentially useful state to give extensions tons of | |
541 | # flexibility. |
|
541 | # flexibility. | |
542 | typ = fn()(ui=ui, |
|
542 | typ = fn()(ui=ui, | |
543 | intents=intents, |
|
543 | intents=intents, | |
544 | requirements=requirements, |
|
544 | requirements=requirements, | |
545 | features=features, |
|
545 | features=features, | |
546 | wdirvfs=wdirvfs, |
|
546 | wdirvfs=wdirvfs, | |
547 | hgvfs=hgvfs, |
|
547 | hgvfs=hgvfs, | |
548 | store=store, |
|
548 | store=store, | |
549 | storevfs=storevfs, |
|
549 | storevfs=storevfs, | |
550 | storeoptions=storevfs.options, |
|
550 | storeoptions=storevfs.options, | |
551 | cachevfs=cachevfs, |
|
551 | cachevfs=cachevfs, | |
552 | wcachevfs=wcachevfs, |
|
552 | wcachevfs=wcachevfs, | |
553 | extensionmodulenames=extensionmodulenames, |
|
553 | extensionmodulenames=extensionmodulenames, | |
554 | extrastate=extrastate, |
|
554 | extrastate=extrastate, | |
555 | baseclasses=bases) |
|
555 | baseclasses=bases) | |
556 |
|
556 | |||
557 | if not isinstance(typ, type): |
|
557 | if not isinstance(typ, type): | |
558 | raise error.ProgrammingError('unable to construct type for %s' % |
|
558 | raise error.ProgrammingError('unable to construct type for %s' % | |
559 | iface) |
|
559 | iface) | |
560 |
|
560 | |||
561 | bases.append(typ) |
|
561 | bases.append(typ) | |
562 |
|
562 | |||
563 | # type() allows you to use characters in type names that wouldn't be |
|
563 | # type() allows you to use characters in type names that wouldn't be | |
564 | # recognized as Python symbols in source code. We abuse that to add |
|
564 | # recognized as Python symbols in source code. We abuse that to add | |
565 | # rich information about our constructed repo. |
|
565 | # rich information about our constructed repo. | |
566 | name = pycompat.sysstr(b'derivedrepo:%s<%s>' % ( |
|
566 | name = pycompat.sysstr(b'derivedrepo:%s<%s>' % ( | |
567 | wdirvfs.base, |
|
567 | wdirvfs.base, | |
568 | b','.join(sorted(requirements)))) |
|
568 | b','.join(sorted(requirements)))) | |
569 |
|
569 | |||
570 | cls = type(name, tuple(bases), {}) |
|
570 | cls = type(name, tuple(bases), {}) | |
571 |
|
571 | |||
572 | return cls( |
|
572 | return cls( | |
573 | baseui=baseui, |
|
573 | baseui=baseui, | |
574 | ui=ui, |
|
574 | ui=ui, | |
575 | origroot=path, |
|
575 | origroot=path, | |
576 | wdirvfs=wdirvfs, |
|
576 | wdirvfs=wdirvfs, | |
577 | hgvfs=hgvfs, |
|
577 | hgvfs=hgvfs, | |
578 | requirements=requirements, |
|
578 | requirements=requirements, | |
579 | supportedrequirements=supportedrequirements, |
|
579 | supportedrequirements=supportedrequirements, | |
580 | sharedpath=storebasepath, |
|
580 | sharedpath=storebasepath, | |
581 | store=store, |
|
581 | store=store, | |
582 | cachevfs=cachevfs, |
|
582 | cachevfs=cachevfs, | |
583 | wcachevfs=wcachevfs, |
|
583 | wcachevfs=wcachevfs, | |
584 | features=features, |
|
584 | features=features, | |
585 | intents=intents) |
|
585 | intents=intents) | |
586 |
|
586 | |||
587 | def loadhgrc(ui, wdirvfs, hgvfs, requirements): |
|
587 | def loadhgrc(ui, wdirvfs, hgvfs, requirements): | |
588 | """Load hgrc files/content into a ui instance. |
|
588 | """Load hgrc files/content into a ui instance. | |
589 |
|
589 | |||
590 | This is called during repository opening to load any additional |
|
590 | This is called during repository opening to load any additional | |
591 | config files or settings relevant to the current repository. |
|
591 | config files or settings relevant to the current repository. | |
592 |
|
592 | |||
593 | Returns a bool indicating whether any additional configs were loaded. |
|
593 | Returns a bool indicating whether any additional configs were loaded. | |
594 |
|
594 | |||
595 | Extensions should monkeypatch this function to modify how per-repo |
|
595 | Extensions should monkeypatch this function to modify how per-repo | |
596 | configs are loaded. For example, an extension may wish to pull in |
|
596 | configs are loaded. For example, an extension may wish to pull in | |
597 | configs from alternate files or sources. |
|
597 | configs from alternate files or sources. | |
598 | """ |
|
598 | """ | |
599 | try: |
|
599 | try: | |
600 | ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base) |
|
600 | ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base) | |
601 | return True |
|
601 | return True | |
602 | except IOError: |
|
602 | except IOError: | |
603 | return False |
|
603 | return False | |
604 |
|
604 | |||
605 | def afterhgrcload(ui, wdirvfs, hgvfs, requirements): |
|
605 | def afterhgrcload(ui, wdirvfs, hgvfs, requirements): | |
606 | """Perform additional actions after .hg/hgrc is loaded. |
|
606 | """Perform additional actions after .hg/hgrc is loaded. | |
607 |
|
607 | |||
608 | This function is called during repository loading immediately after |
|
608 | This function is called during repository loading immediately after | |
609 | the .hg/hgrc file is loaded and before per-repo extensions are loaded. |
|
609 | the .hg/hgrc file is loaded and before per-repo extensions are loaded. | |
610 |
|
610 | |||
611 | The function can be used to validate configs, automatically add |
|
611 | The function can be used to validate configs, automatically add | |
612 | options (including extensions) based on requirements, etc. |
|
612 | options (including extensions) based on requirements, etc. | |
613 | """ |
|
613 | """ | |
614 |
|
614 | |||
615 | # Map of requirements to list of extensions to load automatically when |
|
615 | # Map of requirements to list of extensions to load automatically when | |
616 | # requirement is present. |
|
616 | # requirement is present. | |
617 | autoextensions = { |
|
617 | autoextensions = { | |
618 | b'largefiles': [b'largefiles'], |
|
618 | b'largefiles': [b'largefiles'], | |
619 | b'lfs': [b'lfs'], |
|
619 | b'lfs': [b'lfs'], | |
620 | } |
|
620 | } | |
621 |
|
621 | |||
622 | for requirement, names in sorted(autoextensions.items()): |
|
622 | for requirement, names in sorted(autoextensions.items()): | |
623 | if requirement not in requirements: |
|
623 | if requirement not in requirements: | |
624 | continue |
|
624 | continue | |
625 |
|
625 | |||
626 | for name in names: |
|
626 | for name in names: | |
627 | if not ui.hasconfig(b'extensions', name): |
|
627 | if not ui.hasconfig(b'extensions', name): | |
628 | ui.setconfig(b'extensions', name, b'', source='autoload') |
|
628 | ui.setconfig(b'extensions', name, b'', source='autoload') | |
629 |
|
629 | |||
630 | def gathersupportedrequirements(ui): |
|
630 | def gathersupportedrequirements(ui): | |
631 | """Determine the complete set of recognized requirements.""" |
|
631 | """Determine the complete set of recognized requirements.""" | |
632 | # Start with all requirements supported by this file. |
|
632 | # Start with all requirements supported by this file. | |
633 | supported = set(localrepository._basesupported) |
|
633 | supported = set(localrepository._basesupported) | |
634 |
|
634 | |||
635 | # Execute ``featuresetupfuncs`` entries if they belong to an extension |
|
635 | # Execute ``featuresetupfuncs`` entries if they belong to an extension | |
636 | # relevant to this ui instance. |
|
636 | # relevant to this ui instance. | |
637 | modules = {m.__name__ for n, m in extensions.extensions(ui)} |
|
637 | modules = {m.__name__ for n, m in extensions.extensions(ui)} | |
638 |
|
638 | |||
639 | for fn in featuresetupfuncs: |
|
639 | for fn in featuresetupfuncs: | |
640 | if fn.__module__ in modules: |
|
640 | if fn.__module__ in modules: | |
641 | fn(ui, supported) |
|
641 | fn(ui, supported) | |
642 |
|
642 | |||
643 | # Add derived requirements from registered compression engines. |
|
643 | # Add derived requirements from registered compression engines. | |
644 | for name in util.compengines: |
|
644 | for name in util.compengines: | |
645 | engine = util.compengines[name] |
|
645 | engine = util.compengines[name] | |
646 | if engine.revlogheader(): |
|
646 | if engine.revlogheader(): | |
647 | supported.add(b'exp-compression-%s' % name) |
|
647 | supported.add(b'exp-compression-%s' % name) | |
648 |
|
648 | |||
649 | return supported |
|
649 | return supported | |
650 |
|
650 | |||
651 | def ensurerequirementsrecognized(requirements, supported): |
|
651 | def ensurerequirementsrecognized(requirements, supported): | |
652 | """Validate that a set of local requirements is recognized. |
|
652 | """Validate that a set of local requirements is recognized. | |
653 |
|
653 | |||
654 | Receives a set of requirements. Raises an ``error.RepoError`` if there |
|
654 | Receives a set of requirements. Raises an ``error.RepoError`` if there | |
655 | exists any requirement in that set that currently loaded code doesn't |
|
655 | exists any requirement in that set that currently loaded code doesn't | |
656 | recognize. |
|
656 | recognize. | |
657 |
|
657 | |||
658 | Returns a set of supported requirements. |
|
658 | Returns a set of supported requirements. | |
659 | """ |
|
659 | """ | |
660 | missing = set() |
|
660 | missing = set() | |
661 |
|
661 | |||
662 | for requirement in requirements: |
|
662 | for requirement in requirements: | |
663 | if requirement in supported: |
|
663 | if requirement in supported: | |
664 | continue |
|
664 | continue | |
665 |
|
665 | |||
666 | if not requirement or not requirement[0:1].isalnum(): |
|
666 | if not requirement or not requirement[0:1].isalnum(): | |
667 | raise error.RequirementError(_(b'.hg/requires file is corrupt')) |
|
667 | raise error.RequirementError(_(b'.hg/requires file is corrupt')) | |
668 |
|
668 | |||
669 | missing.add(requirement) |
|
669 | missing.add(requirement) | |
670 |
|
670 | |||
671 | if missing: |
|
671 | if missing: | |
672 | raise error.RequirementError( |
|
672 | raise error.RequirementError( | |
673 | _(b'repository requires features unknown to this Mercurial: %s') % |
|
673 | _(b'repository requires features unknown to this Mercurial: %s') % | |
674 | b' '.join(sorted(missing)), |
|
674 | b' '.join(sorted(missing)), | |
675 | hint=_(b'see https://mercurial-scm.org/wiki/MissingRequirement ' |
|
675 | hint=_(b'see https://mercurial-scm.org/wiki/MissingRequirement ' | |
676 | b'for more information')) |
|
676 | b'for more information')) | |
677 |
|
677 | |||
678 | def ensurerequirementscompatible(ui, requirements): |
|
678 | def ensurerequirementscompatible(ui, requirements): | |
679 | """Validates that a set of recognized requirements is mutually compatible. |
|
679 | """Validates that a set of recognized requirements is mutually compatible. | |
680 |
|
680 | |||
681 | Some requirements may not be compatible with others or require |
|
681 | Some requirements may not be compatible with others or require | |
682 | config options that aren't enabled. This function is called during |
|
682 | config options that aren't enabled. This function is called during | |
683 | repository opening to ensure that the set of requirements needed |
|
683 | repository opening to ensure that the set of requirements needed | |
684 | to open a repository is sane and compatible with config options. |
|
684 | to open a repository is sane and compatible with config options. | |
685 |
|
685 | |||
686 | Extensions can monkeypatch this function to perform additional |
|
686 | Extensions can monkeypatch this function to perform additional | |
687 | checking. |
|
687 | checking. | |
688 |
|
688 | |||
689 | ``error.RepoError`` should be raised on failure. |
|
689 | ``error.RepoError`` should be raised on failure. | |
690 | """ |
|
690 | """ | |
691 | if b'exp-sparse' in requirements and not sparse.enabled: |
|
691 | if b'exp-sparse' in requirements and not sparse.enabled: | |
692 | raise error.RepoError(_(b'repository is using sparse feature but ' |
|
692 | raise error.RepoError(_(b'repository is using sparse feature but ' | |
693 | b'sparse is not enabled; enable the ' |
|
693 | b'sparse is not enabled; enable the ' | |
694 | b'"sparse" extensions to access')) |
|
694 | b'"sparse" extensions to access')) | |
695 |
|
695 | |||
696 | def makestore(requirements, path, vfstype): |
|
696 | def makestore(requirements, path, vfstype): | |
697 | """Construct a storage object for a repository.""" |
|
697 | """Construct a storage object for a repository.""" | |
698 | if b'store' in requirements: |
|
698 | if b'store' in requirements: | |
699 | if b'fncache' in requirements: |
|
699 | if b'fncache' in requirements: | |
700 | return storemod.fncachestore(path, vfstype, |
|
700 | return storemod.fncachestore(path, vfstype, | |
701 | b'dotencode' in requirements) |
|
701 | b'dotencode' in requirements) | |
702 |
|
702 | |||
703 | return storemod.encodedstore(path, vfstype) |
|
703 | return storemod.encodedstore(path, vfstype) | |
704 |
|
704 | |||
705 | return storemod.basicstore(path, vfstype) |
|
705 | return storemod.basicstore(path, vfstype) | |
706 |
|
706 | |||
707 | def resolvestorevfsoptions(ui, requirements, features): |
|
707 | def resolvestorevfsoptions(ui, requirements, features): | |
708 | """Resolve the options to pass to the store vfs opener. |
|
708 | """Resolve the options to pass to the store vfs opener. | |
709 |
|
709 | |||
710 | The returned dict is used to influence behavior of the storage layer. |
|
710 | The returned dict is used to influence behavior of the storage layer. | |
711 | """ |
|
711 | """ | |
712 | options = {} |
|
712 | options = {} | |
713 |
|
713 | |||
714 | if b'treemanifest' in requirements: |
|
714 | if b'treemanifest' in requirements: | |
715 | options[b'treemanifest'] = True |
|
715 | options[b'treemanifest'] = True | |
716 |
|
716 | |||
717 | # experimental config: format.manifestcachesize |
|
717 | # experimental config: format.manifestcachesize | |
718 | manifestcachesize = ui.configint(b'format', b'manifestcachesize') |
|
718 | manifestcachesize = ui.configint(b'format', b'manifestcachesize') | |
719 | if manifestcachesize is not None: |
|
719 | if manifestcachesize is not None: | |
720 | options[b'manifestcachesize'] = manifestcachesize |
|
720 | options[b'manifestcachesize'] = manifestcachesize | |
721 |
|
721 | |||
722 | # In the absence of another requirement superseding a revlog-related |
|
722 | # In the absence of another requirement superseding a revlog-related | |
723 | # requirement, we have to assume the repo is using revlog version 0. |
|
723 | # requirement, we have to assume the repo is using revlog version 0. | |
724 | # This revlog format is super old and we don't bother trying to parse |
|
724 | # This revlog format is super old and we don't bother trying to parse | |
725 | # opener options for it because those options wouldn't do anything |
|
725 | # opener options for it because those options wouldn't do anything | |
726 | # meaningful on such old repos. |
|
726 | # meaningful on such old repos. | |
727 | if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements: |
|
727 | if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements: | |
728 | options.update(resolverevlogstorevfsoptions(ui, requirements, features)) |
|
728 | options.update(resolverevlogstorevfsoptions(ui, requirements, features)) | |
729 |
|
729 | |||
730 | return options |
|
730 | return options | |
731 |
|
731 | |||
732 | def resolverevlogstorevfsoptions(ui, requirements, features): |
|
732 | def resolverevlogstorevfsoptions(ui, requirements, features): | |
733 | """Resolve opener options specific to revlogs.""" |
|
733 | """Resolve opener options specific to revlogs.""" | |
734 |
|
734 | |||
735 | options = {} |
|
735 | options = {} | |
736 | options[b'flagprocessors'] = {} |
|
736 | options[b'flagprocessors'] = {} | |
737 |
|
737 | |||
738 | if b'revlogv1' in requirements: |
|
738 | if b'revlogv1' in requirements: | |
739 | options[b'revlogv1'] = True |
|
739 | options[b'revlogv1'] = True | |
740 | if REVLOGV2_REQUIREMENT in requirements: |
|
740 | if REVLOGV2_REQUIREMENT in requirements: | |
741 | options[b'revlogv2'] = True |
|
741 | options[b'revlogv2'] = True | |
742 |
|
742 | |||
743 | if b'generaldelta' in requirements: |
|
743 | if b'generaldelta' in requirements: | |
744 | options[b'generaldelta'] = True |
|
744 | options[b'generaldelta'] = True | |
745 |
|
745 | |||
746 | # experimental config: format.chunkcachesize |
|
746 | # experimental config: format.chunkcachesize | |
747 | chunkcachesize = ui.configint(b'format', b'chunkcachesize') |
|
747 | chunkcachesize = ui.configint(b'format', b'chunkcachesize') | |
748 | if chunkcachesize is not None: |
|
748 | if chunkcachesize is not None: | |
749 | options[b'chunkcachesize'] = chunkcachesize |
|
749 | options[b'chunkcachesize'] = chunkcachesize | |
750 |
|
750 | |||
751 | deltabothparents = ui.configbool(b'storage', |
|
751 | deltabothparents = ui.configbool(b'storage', | |
752 | b'revlog.optimize-delta-parent-choice') |
|
752 | b'revlog.optimize-delta-parent-choice') | |
753 | options[b'deltabothparents'] = deltabothparents |
|
753 | options[b'deltabothparents'] = deltabothparents | |
754 |
|
754 | |||
755 | options[b'lazydeltabase'] = not scmutil.gddeltaconfig(ui) |
|
755 | options[b'lazydeltabase'] = not scmutil.gddeltaconfig(ui) | |
756 |
|
756 | |||
757 | chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan') |
|
757 | chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan') | |
758 | if 0 <= chainspan: |
|
758 | if 0 <= chainspan: | |
759 | options[b'maxdeltachainspan'] = chainspan |
|
759 | options[b'maxdeltachainspan'] = chainspan | |
760 |
|
760 | |||
761 | mmapindexthreshold = ui.configbytes(b'storage', b'mmap-threshold') |
|
761 | mmapindexthreshold = ui.configbytes(b'storage', b'mmap-threshold') | |
762 | if mmapindexthreshold is not None: |
|
762 | if mmapindexthreshold is not None: | |
763 | options[b'mmapindexthreshold'] = mmapindexthreshold |
|
763 | options[b'mmapindexthreshold'] = mmapindexthreshold | |
764 |
|
764 | |||
765 | withsparseread = ui.configbool(b'experimental', b'sparse-read') |
|
765 | withsparseread = ui.configbool(b'experimental', b'sparse-read') | |
766 | srdensitythres = float(ui.config(b'experimental', |
|
766 | srdensitythres = float(ui.config(b'experimental', | |
767 | b'sparse-read.density-threshold')) |
|
767 | b'sparse-read.density-threshold')) | |
768 | srmingapsize = ui.configbytes(b'experimental', |
|
768 | srmingapsize = ui.configbytes(b'experimental', | |
769 | b'sparse-read.min-gap-size') |
|
769 | b'sparse-read.min-gap-size') | |
770 | options[b'with-sparse-read'] = withsparseread |
|
770 | options[b'with-sparse-read'] = withsparseread | |
771 | options[b'sparse-read-density-threshold'] = srdensitythres |
|
771 | options[b'sparse-read-density-threshold'] = srdensitythres | |
772 | options[b'sparse-read-min-gap-size'] = srmingapsize |
|
772 | options[b'sparse-read-min-gap-size'] = srmingapsize | |
773 |
|
773 | |||
774 | sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements |
|
774 | sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements | |
775 | options[b'sparse-revlog'] = sparserevlog |
|
775 | options[b'sparse-revlog'] = sparserevlog | |
776 | if sparserevlog: |
|
776 | if sparserevlog: | |
777 | options[b'generaldelta'] = True |
|
777 | options[b'generaldelta'] = True | |
778 |
|
778 | |||
779 | maxchainlen = None |
|
779 | maxchainlen = None | |
780 | if sparserevlog: |
|
780 | if sparserevlog: | |
781 | maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH |
|
781 | maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH | |
782 | # experimental config: format.maxchainlen |
|
782 | # experimental config: format.maxchainlen | |
783 | maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen) |
|
783 | maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen) | |
784 | if maxchainlen is not None: |
|
784 | if maxchainlen is not None: | |
785 | options[b'maxchainlen'] = maxchainlen |
|
785 | options[b'maxchainlen'] = maxchainlen | |
786 |
|
786 | |||
787 | for r in requirements: |
|
787 | for r in requirements: | |
788 | if r.startswith(b'exp-compression-'): |
|
788 | if r.startswith(b'exp-compression-'): | |
789 | options[b'compengine'] = r[len(b'exp-compression-'):] |
|
789 | options[b'compengine'] = r[len(b'exp-compression-'):] | |
790 |
|
790 | |||
791 | if repository.NARROW_REQUIREMENT in requirements: |
|
791 | if repository.NARROW_REQUIREMENT in requirements: | |
792 | options[b'enableellipsis'] = True |
|
792 | options[b'enableellipsis'] = True | |
793 |
|
793 | |||
794 | return options |
|
794 | return options | |
795 |
|
795 | |||
796 | def makemain(**kwargs): |
|
796 | def makemain(**kwargs): | |
797 | """Produce a type conforming to ``ilocalrepositorymain``.""" |
|
797 | """Produce a type conforming to ``ilocalrepositorymain``.""" | |
798 | return localrepository |
|
798 | return localrepository | |
799 |
|
799 | |||
800 | @interfaceutil.implementer(repository.ilocalrepositoryfilestorage) |
|
800 | @interfaceutil.implementer(repository.ilocalrepositoryfilestorage) | |
801 | class revlogfilestorage(object): |
|
801 | class revlogfilestorage(object): | |
802 | """File storage when using revlogs.""" |
|
802 | """File storage when using revlogs.""" | |
803 |
|
803 | |||
804 | def file(self, path): |
|
804 | def file(self, path): | |
805 | if path[0] == b'/': |
|
805 | if path[0] == b'/': | |
806 | path = path[1:] |
|
806 | path = path[1:] | |
807 |
|
807 | |||
808 | return filelog.filelog(self.svfs, path) |
|
808 | return filelog.filelog(self.svfs, path) | |
809 |
|
809 | |||
810 | @interfaceutil.implementer(repository.ilocalrepositoryfilestorage) |
|
810 | @interfaceutil.implementer(repository.ilocalrepositoryfilestorage) | |
811 | class revlognarrowfilestorage(object): |
|
811 | class revlognarrowfilestorage(object): | |
812 | """File storage when using revlogs and narrow files.""" |
|
812 | """File storage when using revlogs and narrow files.""" | |
813 |
|
813 | |||
814 | def file(self, path): |
|
814 | def file(self, path): | |
815 | if path[0] == b'/': |
|
815 | if path[0] == b'/': | |
816 | path = path[1:] |
|
816 | path = path[1:] | |
817 |
|
817 | |||
818 | return filelog.narrowfilelog(self.svfs, path, self.narrowmatch()) |
|
818 | return filelog.narrowfilelog(self.svfs, path, self.narrowmatch()) | |
819 |
|
819 | |||
820 | def makefilestorage(requirements, features, **kwargs): |
|
820 | def makefilestorage(requirements, features, **kwargs): | |
821 | """Produce a type conforming to ``ilocalrepositoryfilestorage``.""" |
|
821 | """Produce a type conforming to ``ilocalrepositoryfilestorage``.""" | |
822 | features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE) |
|
822 | features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE) | |
823 | features.add(repository.REPO_FEATURE_STREAM_CLONE) |
|
823 | features.add(repository.REPO_FEATURE_STREAM_CLONE) | |
824 |
|
824 | |||
825 | if repository.NARROW_REQUIREMENT in requirements: |
|
825 | if repository.NARROW_REQUIREMENT in requirements: | |
826 | return revlognarrowfilestorage |
|
826 | return revlognarrowfilestorage | |
827 | else: |
|
827 | else: | |
828 | return revlogfilestorage |
|
828 | return revlogfilestorage | |
829 |
|
829 | |||
830 | # List of repository interfaces and factory functions for them. Each |
|
830 | # List of repository interfaces and factory functions for them. Each | |
831 | # will be called in order during ``makelocalrepository()`` to iteratively |
|
831 | # will be called in order during ``makelocalrepository()`` to iteratively | |
832 | # derive the final type for a local repository instance. We capture the |
|
832 | # derive the final type for a local repository instance. We capture the | |
833 | # function as a lambda so we don't hold a reference and the module-level |
|
833 | # function as a lambda so we don't hold a reference and the module-level | |
834 | # functions can be wrapped. |
|
834 | # functions can be wrapped. | |
835 | REPO_INTERFACES = [ |
|
835 | REPO_INTERFACES = [ | |
836 | (repository.ilocalrepositorymain, lambda: makemain), |
|
836 | (repository.ilocalrepositorymain, lambda: makemain), | |
837 | (repository.ilocalrepositoryfilestorage, lambda: makefilestorage), |
|
837 | (repository.ilocalrepositoryfilestorage, lambda: makefilestorage), | |
838 | ] |
|
838 | ] | |
839 |
|
839 | |||
840 | @interfaceutil.implementer(repository.ilocalrepositorymain) |
|
840 | @interfaceutil.implementer(repository.ilocalrepositorymain) | |
841 | class localrepository(object): |
|
841 | class localrepository(object): | |
842 | """Main class for representing local repositories. |
|
842 | """Main class for representing local repositories. | |
843 |
|
843 | |||
844 | All local repositories are instances of this class. |
|
844 | All local repositories are instances of this class. | |
845 |
|
845 | |||
846 | Constructed on its own, instances of this class are not usable as |
|
846 | Constructed on its own, instances of this class are not usable as | |
847 | repository objects. To obtain a usable repository object, call |
|
847 | repository objects. To obtain a usable repository object, call | |
848 | ``hg.repository()``, ``localrepo.instance()``, or |
|
848 | ``hg.repository()``, ``localrepo.instance()``, or | |
849 | ``localrepo.makelocalrepository()``. The latter is the lowest-level. |
|
849 | ``localrepo.makelocalrepository()``. The latter is the lowest-level. | |
850 | ``instance()`` adds support for creating new repositories. |
|
850 | ``instance()`` adds support for creating new repositories. | |
851 | ``hg.repository()`` adds more extension integration, including calling |
|
851 | ``hg.repository()`` adds more extension integration, including calling | |
852 | ``reposetup()``. Generally speaking, ``hg.repository()`` should be |
|
852 | ``reposetup()``. Generally speaking, ``hg.repository()`` should be | |
853 | used. |
|
853 | used. | |
854 | """ |
|
854 | """ | |
855 |
|
855 | |||
856 | # obsolete experimental requirements: |
|
856 | # obsolete experimental requirements: | |
857 | # - manifestv2: An experimental new manifest format that allowed |
|
857 | # - manifestv2: An experimental new manifest format that allowed | |
858 | # for stem compression of long paths. Experiment ended up not |
|
858 | # for stem compression of long paths. Experiment ended up not | |
859 | # being successful (repository sizes went up due to worse delta |
|
859 | # being successful (repository sizes went up due to worse delta | |
860 | # chains), and the code was deleted in 4.6. |
|
860 | # chains), and the code was deleted in 4.6. | |
861 | supportedformats = { |
|
861 | supportedformats = { | |
862 | 'revlogv1', |
|
862 | 'revlogv1', | |
863 | 'generaldelta', |
|
863 | 'generaldelta', | |
864 | 'treemanifest', |
|
864 | 'treemanifest', | |
865 | REVLOGV2_REQUIREMENT, |
|
865 | REVLOGV2_REQUIREMENT, | |
866 | SPARSEREVLOG_REQUIREMENT, |
|
866 | SPARSEREVLOG_REQUIREMENT, | |
867 | } |
|
867 | } | |
868 | _basesupported = supportedformats | { |
|
868 | _basesupported = supportedformats | { | |
869 | 'store', |
|
869 | 'store', | |
870 | 'fncache', |
|
870 | 'fncache', | |
871 | 'shared', |
|
871 | 'shared', | |
872 | 'relshared', |
|
872 | 'relshared', | |
873 | 'dotencode', |
|
873 | 'dotencode', | |
874 | 'exp-sparse', |
|
874 | 'exp-sparse', | |
875 | 'internal-phase' |
|
875 | 'internal-phase' | |
876 | } |
|
876 | } | |
877 |
|
877 | |||
878 | # list of prefix for file which can be written without 'wlock' |
|
878 | # list of prefix for file which can be written without 'wlock' | |
879 | # Extensions should extend this list when needed |
|
879 | # Extensions should extend this list when needed | |
880 | _wlockfreeprefix = { |
|
880 | _wlockfreeprefix = { | |
881 | # We migh consider requiring 'wlock' for the next |
|
881 | # We migh consider requiring 'wlock' for the next | |
882 | # two, but pretty much all the existing code assume |
|
882 | # two, but pretty much all the existing code assume | |
883 | # wlock is not needed so we keep them excluded for |
|
883 | # wlock is not needed so we keep them excluded for | |
884 | # now. |
|
884 | # now. | |
885 | 'hgrc', |
|
885 | 'hgrc', | |
886 | 'requires', |
|
886 | 'requires', | |
887 | # XXX cache is a complicatged business someone |
|
887 | # XXX cache is a complicatged business someone | |
888 | # should investigate this in depth at some point |
|
888 | # should investigate this in depth at some point | |
889 | 'cache/', |
|
889 | 'cache/', | |
890 | # XXX shouldn't be dirstate covered by the wlock? |
|
890 | # XXX shouldn't be dirstate covered by the wlock? | |
891 | 'dirstate', |
|
891 | 'dirstate', | |
892 | # XXX bisect was still a bit too messy at the time |
|
892 | # XXX bisect was still a bit too messy at the time | |
893 | # this changeset was introduced. Someone should fix |
|
893 | # this changeset was introduced. Someone should fix | |
894 | # the remainig bit and drop this line |
|
894 | # the remainig bit and drop this line | |
895 | 'bisect.state', |
|
895 | 'bisect.state', | |
896 | } |
|
896 | } | |
897 |
|
897 | |||
898 | def __init__(self, baseui, ui, origroot, wdirvfs, hgvfs, requirements, |
|
898 | def __init__(self, baseui, ui, origroot, wdirvfs, hgvfs, requirements, | |
899 | supportedrequirements, sharedpath, store, cachevfs, wcachevfs, |
|
899 | supportedrequirements, sharedpath, store, cachevfs, wcachevfs, | |
900 | features, intents=None): |
|
900 | features, intents=None): | |
901 | """Create a new local repository instance. |
|
901 | """Create a new local repository instance. | |
902 |
|
902 | |||
903 | Most callers should use ``hg.repository()``, ``localrepo.instance()``, |
|
903 | Most callers should use ``hg.repository()``, ``localrepo.instance()``, | |
904 | or ``localrepo.makelocalrepository()`` for obtaining a new repository |
|
904 | or ``localrepo.makelocalrepository()`` for obtaining a new repository | |
905 | object. |
|
905 | object. | |
906 |
|
906 | |||
907 | Arguments: |
|
907 | Arguments: | |
908 |
|
908 | |||
909 | baseui |
|
909 | baseui | |
910 | ``ui.ui`` instance that ``ui`` argument was based off of. |
|
910 | ``ui.ui`` instance that ``ui`` argument was based off of. | |
911 |
|
911 | |||
912 | ui |
|
912 | ui | |
913 | ``ui.ui`` instance for use by the repository. |
|
913 | ``ui.ui`` instance for use by the repository. | |
914 |
|
914 | |||
915 | origroot |
|
915 | origroot | |
916 | ``bytes`` path to working directory root of this repository. |
|
916 | ``bytes`` path to working directory root of this repository. | |
917 |
|
917 | |||
918 | wdirvfs |
|
918 | wdirvfs | |
919 | ``vfs.vfs`` rooted at the working directory. |
|
919 | ``vfs.vfs`` rooted at the working directory. | |
920 |
|
920 | |||
921 | hgvfs |
|
921 | hgvfs | |
922 | ``vfs.vfs`` rooted at .hg/ |
|
922 | ``vfs.vfs`` rooted at .hg/ | |
923 |
|
923 | |||
924 | requirements |
|
924 | requirements | |
925 | ``set`` of bytestrings representing repository opening requirements. |
|
925 | ``set`` of bytestrings representing repository opening requirements. | |
926 |
|
926 | |||
927 | supportedrequirements |
|
927 | supportedrequirements | |
928 | ``set`` of bytestrings representing repository requirements that we |
|
928 | ``set`` of bytestrings representing repository requirements that we | |
929 | know how to open. May be a supetset of ``requirements``. |
|
929 | know how to open. May be a supetset of ``requirements``. | |
930 |
|
930 | |||
931 | sharedpath |
|
931 | sharedpath | |
932 | ``bytes`` Defining path to storage base directory. Points to a |
|
932 | ``bytes`` Defining path to storage base directory. Points to a | |
933 | ``.hg/`` directory somewhere. |
|
933 | ``.hg/`` directory somewhere. | |
934 |
|
934 | |||
935 | store |
|
935 | store | |
936 | ``store.basicstore`` (or derived) instance providing access to |
|
936 | ``store.basicstore`` (or derived) instance providing access to | |
937 | versioned storage. |
|
937 | versioned storage. | |
938 |
|
938 | |||
939 | cachevfs |
|
939 | cachevfs | |
940 | ``vfs.vfs`` used for cache files. |
|
940 | ``vfs.vfs`` used for cache files. | |
941 |
|
941 | |||
942 | wcachevfs |
|
942 | wcachevfs | |
943 | ``vfs.vfs`` used for cache files related to the working copy. |
|
943 | ``vfs.vfs`` used for cache files related to the working copy. | |
944 |
|
944 | |||
945 | features |
|
945 | features | |
946 | ``set`` of bytestrings defining features/capabilities of this |
|
946 | ``set`` of bytestrings defining features/capabilities of this | |
947 | instance. |
|
947 | instance. | |
948 |
|
948 | |||
949 | intents |
|
949 | intents | |
950 | ``set`` of system strings indicating what this repo will be used |
|
950 | ``set`` of system strings indicating what this repo will be used | |
951 | for. |
|
951 | for. | |
952 | """ |
|
952 | """ | |
953 | self.baseui = baseui |
|
953 | self.baseui = baseui | |
954 | self.ui = ui |
|
954 | self.ui = ui | |
955 | self.origroot = origroot |
|
955 | self.origroot = origroot | |
956 | # vfs rooted at working directory. |
|
956 | # vfs rooted at working directory. | |
957 | self.wvfs = wdirvfs |
|
957 | self.wvfs = wdirvfs | |
958 | self.root = wdirvfs.base |
|
958 | self.root = wdirvfs.base | |
959 | # vfs rooted at .hg/. Used to access most non-store paths. |
|
959 | # vfs rooted at .hg/. Used to access most non-store paths. | |
960 | self.vfs = hgvfs |
|
960 | self.vfs = hgvfs | |
961 | self.path = hgvfs.base |
|
961 | self.path = hgvfs.base | |
962 | self.requirements = requirements |
|
962 | self.requirements = requirements | |
963 | self.supported = supportedrequirements |
|
963 | self.supported = supportedrequirements | |
964 | self.sharedpath = sharedpath |
|
964 | self.sharedpath = sharedpath | |
965 | self.store = store |
|
965 | self.store = store | |
966 | self.cachevfs = cachevfs |
|
966 | self.cachevfs = cachevfs | |
967 | self.wcachevfs = wcachevfs |
|
967 | self.wcachevfs = wcachevfs | |
968 | self.features = features |
|
968 | self.features = features | |
969 |
|
969 | |||
970 | self.filtername = None |
|
970 | self.filtername = None | |
971 |
|
971 | |||
972 | if (self.ui.configbool('devel', 'all-warnings') or |
|
972 | if (self.ui.configbool('devel', 'all-warnings') or | |
973 | self.ui.configbool('devel', 'check-locks')): |
|
973 | self.ui.configbool('devel', 'check-locks')): | |
974 | self.vfs.audit = self._getvfsward(self.vfs.audit) |
|
974 | self.vfs.audit = self._getvfsward(self.vfs.audit) | |
975 | # A list of callback to shape the phase if no data were found. |
|
975 | # A list of callback to shape the phase if no data were found. | |
976 | # Callback are in the form: func(repo, roots) --> processed root. |
|
976 | # Callback are in the form: func(repo, roots) --> processed root. | |
977 | # This list it to be filled by extension during repo setup |
|
977 | # This list it to be filled by extension during repo setup | |
978 | self._phasedefaults = [] |
|
978 | self._phasedefaults = [] | |
979 |
|
979 | |||
980 | color.setup(self.ui) |
|
980 | color.setup(self.ui) | |
981 |
|
981 | |||
982 | self.spath = self.store.path |
|
982 | self.spath = self.store.path | |
983 | self.svfs = self.store.vfs |
|
983 | self.svfs = self.store.vfs | |
984 | self.sjoin = self.store.join |
|
984 | self.sjoin = self.store.join | |
985 | if (self.ui.configbool('devel', 'all-warnings') or |
|
985 | if (self.ui.configbool('devel', 'all-warnings') or | |
986 | self.ui.configbool('devel', 'check-locks')): |
|
986 | self.ui.configbool('devel', 'check-locks')): | |
987 | if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs |
|
987 | if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs | |
988 | self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit) |
|
988 | self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit) | |
989 | else: # standard vfs |
|
989 | else: # standard vfs | |
990 | self.svfs.audit = self._getsvfsward(self.svfs.audit) |
|
990 | self.svfs.audit = self._getsvfsward(self.svfs.audit) | |
991 |
|
991 | |||
992 | self._dirstatevalidatewarned = False |
|
992 | self._dirstatevalidatewarned = False | |
993 |
|
993 | |||
994 | self._branchcaches = {} |
|
994 | self._branchcaches = {} | |
995 | self._revbranchcache = None |
|
995 | self._revbranchcache = None | |
996 | self._filterpats = {} |
|
996 | self._filterpats = {} | |
997 | self._datafilters = {} |
|
997 | self._datafilters = {} | |
998 | self._transref = self._lockref = self._wlockref = None |
|
998 | self._transref = self._lockref = self._wlockref = None | |
999 |
|
999 | |||
1000 | # A cache for various files under .hg/ that tracks file changes, |
|
1000 | # A cache for various files under .hg/ that tracks file changes, | |
1001 | # (used by the filecache decorator) |
|
1001 | # (used by the filecache decorator) | |
1002 | # |
|
1002 | # | |
1003 | # Maps a property name to its util.filecacheentry |
|
1003 | # Maps a property name to its util.filecacheentry | |
1004 | self._filecache = {} |
|
1004 | self._filecache = {} | |
1005 |
|
1005 | |||
1006 | # hold sets of revision to be filtered |
|
1006 | # hold sets of revision to be filtered | |
1007 | # should be cleared when something might have changed the filter value: |
|
1007 | # should be cleared when something might have changed the filter value: | |
1008 | # - new changesets, |
|
1008 | # - new changesets, | |
1009 | # - phase change, |
|
1009 | # - phase change, | |
1010 | # - new obsolescence marker, |
|
1010 | # - new obsolescence marker, | |
1011 | # - working directory parent change, |
|
1011 | # - working directory parent change, | |
1012 | # - bookmark changes |
|
1012 | # - bookmark changes | |
1013 | self.filteredrevcache = {} |
|
1013 | self.filteredrevcache = {} | |
1014 |
|
1014 | |||
1015 | # post-dirstate-status hooks |
|
1015 | # post-dirstate-status hooks | |
1016 | self._postdsstatus = [] |
|
1016 | self._postdsstatus = [] | |
1017 |
|
1017 | |||
1018 | # generic mapping between names and nodes |
|
1018 | # generic mapping between names and nodes | |
1019 | self.names = namespaces.namespaces() |
|
1019 | self.names = namespaces.namespaces() | |
1020 |
|
1020 | |||
1021 | # Key to signature value. |
|
1021 | # Key to signature value. | |
1022 | self._sparsesignaturecache = {} |
|
1022 | self._sparsesignaturecache = {} | |
1023 | # Signature to cached matcher instance. |
|
1023 | # Signature to cached matcher instance. | |
1024 | self._sparsematchercache = {} |
|
1024 | self._sparsematchercache = {} | |
1025 |
|
1025 | |||
1026 | def _getvfsward(self, origfunc): |
|
1026 | def _getvfsward(self, origfunc): | |
1027 | """build a ward for self.vfs""" |
|
1027 | """build a ward for self.vfs""" | |
1028 | rref = weakref.ref(self) |
|
1028 | rref = weakref.ref(self) | |
1029 | def checkvfs(path, mode=None): |
|
1029 | def checkvfs(path, mode=None): | |
1030 | ret = origfunc(path, mode=mode) |
|
1030 | ret = origfunc(path, mode=mode) | |
1031 | repo = rref() |
|
1031 | repo = rref() | |
1032 | if (repo is None |
|
1032 | if (repo is None | |
1033 | or not util.safehasattr(repo, '_wlockref') |
|
1033 | or not util.safehasattr(repo, '_wlockref') | |
1034 | or not util.safehasattr(repo, '_lockref')): |
|
1034 | or not util.safehasattr(repo, '_lockref')): | |
1035 | return |
|
1035 | return | |
1036 | if mode in (None, 'r', 'rb'): |
|
1036 | if mode in (None, 'r', 'rb'): | |
1037 | return |
|
1037 | return | |
1038 | if path.startswith(repo.path): |
|
1038 | if path.startswith(repo.path): | |
1039 | # truncate name relative to the repository (.hg) |
|
1039 | # truncate name relative to the repository (.hg) | |
1040 | path = path[len(repo.path) + 1:] |
|
1040 | path = path[len(repo.path) + 1:] | |
1041 | if path.startswith('cache/'): |
|
1041 | if path.startswith('cache/'): | |
1042 | msg = 'accessing cache with vfs instead of cachevfs: "%s"' |
|
1042 | msg = 'accessing cache with vfs instead of cachevfs: "%s"' | |
1043 | repo.ui.develwarn(msg % path, stacklevel=3, config="cache-vfs") |
|
1043 | repo.ui.develwarn(msg % path, stacklevel=3, config="cache-vfs") | |
1044 | if path.startswith('journal.') or path.startswith('undo.'): |
|
1044 | if path.startswith('journal.') or path.startswith('undo.'): | |
1045 | # journal is covered by 'lock' |
|
1045 | # journal is covered by 'lock' | |
1046 | if repo._currentlock(repo._lockref) is None: |
|
1046 | if repo._currentlock(repo._lockref) is None: | |
1047 | repo.ui.develwarn('write with no lock: "%s"' % path, |
|
1047 | repo.ui.develwarn('write with no lock: "%s"' % path, | |
1048 | stacklevel=3, config='check-locks') |
|
1048 | stacklevel=3, config='check-locks') | |
1049 | elif repo._currentlock(repo._wlockref) is None: |
|
1049 | elif repo._currentlock(repo._wlockref) is None: | |
1050 | # rest of vfs files are covered by 'wlock' |
|
1050 | # rest of vfs files are covered by 'wlock' | |
1051 | # |
|
1051 | # | |
1052 | # exclude special files |
|
1052 | # exclude special files | |
1053 | for prefix in self._wlockfreeprefix: |
|
1053 | for prefix in self._wlockfreeprefix: | |
1054 | if path.startswith(prefix): |
|
1054 | if path.startswith(prefix): | |
1055 | return |
|
1055 | return | |
1056 | repo.ui.develwarn('write with no wlock: "%s"' % path, |
|
1056 | repo.ui.develwarn('write with no wlock: "%s"' % path, | |
1057 | stacklevel=3, config='check-locks') |
|
1057 | stacklevel=3, config='check-locks') | |
1058 | return ret |
|
1058 | return ret | |
1059 | return checkvfs |
|
1059 | return checkvfs | |
1060 |
|
1060 | |||
1061 | def _getsvfsward(self, origfunc): |
|
1061 | def _getsvfsward(self, origfunc): | |
1062 | """build a ward for self.svfs""" |
|
1062 | """build a ward for self.svfs""" | |
1063 | rref = weakref.ref(self) |
|
1063 | rref = weakref.ref(self) | |
1064 | def checksvfs(path, mode=None): |
|
1064 | def checksvfs(path, mode=None): | |
1065 | ret = origfunc(path, mode=mode) |
|
1065 | ret = origfunc(path, mode=mode) | |
1066 | repo = rref() |
|
1066 | repo = rref() | |
1067 | if repo is None or not util.safehasattr(repo, '_lockref'): |
|
1067 | if repo is None or not util.safehasattr(repo, '_lockref'): | |
1068 | return |
|
1068 | return | |
1069 | if mode in (None, 'r', 'rb'): |
|
1069 | if mode in (None, 'r', 'rb'): | |
1070 | return |
|
1070 | return | |
1071 | if path.startswith(repo.sharedpath): |
|
1071 | if path.startswith(repo.sharedpath): | |
1072 | # truncate name relative to the repository (.hg) |
|
1072 | # truncate name relative to the repository (.hg) | |
1073 | path = path[len(repo.sharedpath) + 1:] |
|
1073 | path = path[len(repo.sharedpath) + 1:] | |
1074 | if repo._currentlock(repo._lockref) is None: |
|
1074 | if repo._currentlock(repo._lockref) is None: | |
1075 | repo.ui.develwarn('write with no lock: "%s"' % path, |
|
1075 | repo.ui.develwarn('write with no lock: "%s"' % path, | |
1076 | stacklevel=4) |
|
1076 | stacklevel=4) | |
1077 | return ret |
|
1077 | return ret | |
1078 | return checksvfs |
|
1078 | return checksvfs | |
1079 |
|
1079 | |||
1080 | def close(self): |
|
1080 | def close(self): | |
1081 | self._writecaches() |
|
1081 | self._writecaches() | |
1082 |
|
1082 | |||
1083 | def _writecaches(self): |
|
1083 | def _writecaches(self): | |
1084 | if self._revbranchcache: |
|
1084 | if self._revbranchcache: | |
1085 | self._revbranchcache.write() |
|
1085 | self._revbranchcache.write() | |
1086 |
|
1086 | |||
1087 | def _restrictcapabilities(self, caps): |
|
1087 | def _restrictcapabilities(self, caps): | |
1088 | if self.ui.configbool('experimental', 'bundle2-advertise'): |
|
1088 | if self.ui.configbool('experimental', 'bundle2-advertise'): | |
1089 | caps = set(caps) |
|
1089 | caps = set(caps) | |
1090 | capsblob = bundle2.encodecaps(bundle2.getrepocaps(self, |
|
1090 | capsblob = bundle2.encodecaps(bundle2.getrepocaps(self, | |
1091 | role='client')) |
|
1091 | role='client')) | |
1092 | caps.add('bundle2=' + urlreq.quote(capsblob)) |
|
1092 | caps.add('bundle2=' + urlreq.quote(capsblob)) | |
1093 | return caps |
|
1093 | return caps | |
1094 |
|
1094 | |||
1095 | def _writerequirements(self): |
|
1095 | def _writerequirements(self): | |
1096 | scmutil.writerequires(self.vfs, self.requirements) |
|
1096 | scmutil.writerequires(self.vfs, self.requirements) | |
1097 |
|
1097 | |||
1098 | # Don't cache auditor/nofsauditor, or you'll end up with reference cycle: |
|
1098 | # Don't cache auditor/nofsauditor, or you'll end up with reference cycle: | |
1099 | # self -> auditor -> self._checknested -> self |
|
1099 | # self -> auditor -> self._checknested -> self | |
1100 |
|
1100 | |||
1101 | @property |
|
1101 | @property | |
1102 | def auditor(self): |
|
1102 | def auditor(self): | |
1103 | # This is only used by context.workingctx.match in order to |
|
1103 | # This is only used by context.workingctx.match in order to | |
1104 | # detect files in subrepos. |
|
1104 | # detect files in subrepos. | |
1105 | return pathutil.pathauditor(self.root, callback=self._checknested) |
|
1105 | return pathutil.pathauditor(self.root, callback=self._checknested) | |
1106 |
|
1106 | |||
1107 | @property |
|
1107 | @property | |
1108 | def nofsauditor(self): |
|
1108 | def nofsauditor(self): | |
1109 | # This is only used by context.basectx.match in order to detect |
|
1109 | # This is only used by context.basectx.match in order to detect | |
1110 | # files in subrepos. |
|
1110 | # files in subrepos. | |
1111 | return pathutil.pathauditor(self.root, callback=self._checknested, |
|
1111 | return pathutil.pathauditor(self.root, callback=self._checknested, | |
1112 | realfs=False, cached=True) |
|
1112 | realfs=False, cached=True) | |
1113 |
|
1113 | |||
1114 | def _checknested(self, path): |
|
1114 | def _checknested(self, path): | |
1115 | """Determine if path is a legal nested repository.""" |
|
1115 | """Determine if path is a legal nested repository.""" | |
1116 | if not path.startswith(self.root): |
|
1116 | if not path.startswith(self.root): | |
1117 | return False |
|
1117 | return False | |
1118 | subpath = path[len(self.root) + 1:] |
|
1118 | subpath = path[len(self.root) + 1:] | |
1119 | normsubpath = util.pconvert(subpath) |
|
1119 | normsubpath = util.pconvert(subpath) | |
1120 |
|
1120 | |||
1121 | # XXX: Checking against the current working copy is wrong in |
|
1121 | # XXX: Checking against the current working copy is wrong in | |
1122 | # the sense that it can reject things like |
|
1122 | # the sense that it can reject things like | |
1123 | # |
|
1123 | # | |
1124 | # $ hg cat -r 10 sub/x.txt |
|
1124 | # $ hg cat -r 10 sub/x.txt | |
1125 | # |
|
1125 | # | |
1126 | # if sub/ is no longer a subrepository in the working copy |
|
1126 | # if sub/ is no longer a subrepository in the working copy | |
1127 | # parent revision. |
|
1127 | # parent revision. | |
1128 | # |
|
1128 | # | |
1129 | # However, it can of course also allow things that would have |
|
1129 | # However, it can of course also allow things that would have | |
1130 | # been rejected before, such as the above cat command if sub/ |
|
1130 | # been rejected before, such as the above cat command if sub/ | |
1131 | # is a subrepository now, but was a normal directory before. |
|
1131 | # is a subrepository now, but was a normal directory before. | |
1132 | # The old path auditor would have rejected by mistake since it |
|
1132 | # The old path auditor would have rejected by mistake since it | |
1133 | # panics when it sees sub/.hg/. |
|
1133 | # panics when it sees sub/.hg/. | |
1134 | # |
|
1134 | # | |
1135 | # All in all, checking against the working copy seems sensible |
|
1135 | # All in all, checking against the working copy seems sensible | |
1136 | # since we want to prevent access to nested repositories on |
|
1136 | # since we want to prevent access to nested repositories on | |
1137 | # the filesystem *now*. |
|
1137 | # the filesystem *now*. | |
1138 | ctx = self[None] |
|
1138 | ctx = self[None] | |
1139 | parts = util.splitpath(subpath) |
|
1139 | parts = util.splitpath(subpath) | |
1140 | while parts: |
|
1140 | while parts: | |
1141 | prefix = '/'.join(parts) |
|
1141 | prefix = '/'.join(parts) | |
1142 | if prefix in ctx.substate: |
|
1142 | if prefix in ctx.substate: | |
1143 | if prefix == normsubpath: |
|
1143 | if prefix == normsubpath: | |
1144 | return True |
|
1144 | return True | |
1145 | else: |
|
1145 | else: | |
1146 | sub = ctx.sub(prefix) |
|
1146 | sub = ctx.sub(prefix) | |
1147 | return sub.checknested(subpath[len(prefix) + 1:]) |
|
1147 | return sub.checknested(subpath[len(prefix) + 1:]) | |
1148 | else: |
|
1148 | else: | |
1149 | parts.pop() |
|
1149 | parts.pop() | |
1150 | return False |
|
1150 | return False | |
1151 |
|
1151 | |||
1152 | def peer(self): |
|
1152 | def peer(self): | |
1153 | return localpeer(self) # not cached to avoid reference cycle |
|
1153 | return localpeer(self) # not cached to avoid reference cycle | |
1154 |
|
1154 | |||
1155 | def unfiltered(self): |
|
1155 | def unfiltered(self): | |
1156 | """Return unfiltered version of the repository |
|
1156 | """Return unfiltered version of the repository | |
1157 |
|
1157 | |||
1158 | Intended to be overwritten by filtered repo.""" |
|
1158 | Intended to be overwritten by filtered repo.""" | |
1159 | return self |
|
1159 | return self | |
1160 |
|
1160 | |||
1161 | def filtered(self, name, visibilityexceptions=None): |
|
1161 | def filtered(self, name, visibilityexceptions=None): | |
1162 | """Return a filtered version of a repository""" |
|
1162 | """Return a filtered version of a repository""" | |
1163 | cls = repoview.newtype(self.unfiltered().__class__) |
|
1163 | cls = repoview.newtype(self.unfiltered().__class__) | |
1164 | return cls(self, name, visibilityexceptions) |
|
1164 | return cls(self, name, visibilityexceptions) | |
1165 |
|
1165 | |||
1166 | @repofilecache('bookmarks', 'bookmarks.current') |
|
1166 | @repofilecache('bookmarks', 'bookmarks.current') | |
1167 | def _bookmarks(self): |
|
1167 | def _bookmarks(self): | |
1168 | return bookmarks.bmstore(self) |
|
1168 | return bookmarks.bmstore(self) | |
1169 |
|
1169 | |||
1170 | @property |
|
1170 | @property | |
1171 | def _activebookmark(self): |
|
1171 | def _activebookmark(self): | |
1172 | return self._bookmarks.active |
|
1172 | return self._bookmarks.active | |
1173 |
|
1173 | |||
1174 | # _phasesets depend on changelog. what we need is to call |
|
1174 | # _phasesets depend on changelog. what we need is to call | |
1175 | # _phasecache.invalidate() if '00changelog.i' was changed, but it |
|
1175 | # _phasecache.invalidate() if '00changelog.i' was changed, but it | |
1176 | # can't be easily expressed in filecache mechanism. |
|
1176 | # can't be easily expressed in filecache mechanism. | |
1177 | @storecache('phaseroots', '00changelog.i') |
|
1177 | @storecache('phaseroots', '00changelog.i') | |
1178 | def _phasecache(self): |
|
1178 | def _phasecache(self): | |
1179 | return phases.phasecache(self, self._phasedefaults) |
|
1179 | return phases.phasecache(self, self._phasedefaults) | |
1180 |
|
1180 | |||
1181 | @storecache('obsstore') |
|
1181 | @storecache('obsstore') | |
1182 | def obsstore(self): |
|
1182 | def obsstore(self): | |
1183 | return obsolete.makestore(self.ui, self) |
|
1183 | return obsolete.makestore(self.ui, self) | |
1184 |
|
1184 | |||
1185 | @storecache('00changelog.i') |
|
1185 | @storecache('00changelog.i') | |
1186 | def changelog(self): |
|
1186 | def changelog(self): | |
1187 | return changelog.changelog(self.svfs, |
|
1187 | return changelog.changelog(self.svfs, | |
1188 | trypending=txnutil.mayhavepending(self.root)) |
|
1188 | trypending=txnutil.mayhavepending(self.root)) | |
1189 |
|
1189 | |||
1190 | @storecache('00manifest.i') |
|
1190 | @storecache('00manifest.i') | |
1191 | def manifestlog(self): |
|
1191 | def manifestlog(self): | |
1192 | rootstore = manifest.manifestrevlog(self.svfs) |
|
1192 | rootstore = manifest.manifestrevlog(self.svfs) | |
1193 | return manifest.manifestlog(self.svfs, self, rootstore, |
|
1193 | return manifest.manifestlog(self.svfs, self, rootstore, | |
1194 | self.narrowmatch()) |
|
1194 | self.narrowmatch()) | |
1195 |
|
1195 | |||
1196 | @repofilecache('dirstate') |
|
1196 | @repofilecache('dirstate') | |
1197 | def dirstate(self): |
|
1197 | def dirstate(self): | |
1198 | return self._makedirstate() |
|
1198 | return self._makedirstate() | |
1199 |
|
1199 | |||
1200 | def _makedirstate(self): |
|
1200 | def _makedirstate(self): | |
1201 | """Extension point for wrapping the dirstate per-repo.""" |
|
1201 | """Extension point for wrapping the dirstate per-repo.""" | |
1202 | sparsematchfn = lambda: sparse.matcher(self) |
|
1202 | sparsematchfn = lambda: sparse.matcher(self) | |
1203 |
|
1203 | |||
1204 | return dirstate.dirstate(self.vfs, self.ui, self.root, |
|
1204 | return dirstate.dirstate(self.vfs, self.ui, self.root, | |
1205 | self._dirstatevalidate, sparsematchfn) |
|
1205 | self._dirstatevalidate, sparsematchfn) | |
1206 |
|
1206 | |||
1207 | def _dirstatevalidate(self, node): |
|
1207 | def _dirstatevalidate(self, node): | |
1208 | try: |
|
1208 | try: | |
1209 | self.changelog.rev(node) |
|
1209 | self.changelog.rev(node) | |
1210 | return node |
|
1210 | return node | |
1211 | except error.LookupError: |
|
1211 | except error.LookupError: | |
1212 | if not self._dirstatevalidatewarned: |
|
1212 | if not self._dirstatevalidatewarned: | |
1213 | self._dirstatevalidatewarned = True |
|
1213 | self._dirstatevalidatewarned = True | |
1214 | self.ui.warn(_("warning: ignoring unknown" |
|
1214 | self.ui.warn(_("warning: ignoring unknown" | |
1215 | " working parent %s!\n") % short(node)) |
|
1215 | " working parent %s!\n") % short(node)) | |
1216 | return nullid |
|
1216 | return nullid | |
1217 |
|
1217 | |||
1218 | @storecache(narrowspec.FILENAME) |
|
1218 | @storecache(narrowspec.FILENAME) | |
1219 | def narrowpats(self): |
|
1219 | def narrowpats(self): | |
1220 | """matcher patterns for this repository's narrowspec |
|
1220 | """matcher patterns for this repository's narrowspec | |
1221 |
|
1221 | |||
1222 | A tuple of (includes, excludes). |
|
1222 | A tuple of (includes, excludes). | |
1223 | """ |
|
1223 | """ | |
1224 | return narrowspec.load(self) |
|
1224 | return narrowspec.load(self) | |
1225 |
|
1225 | |||
1226 | @storecache(narrowspec.FILENAME) |
|
1226 | @storecache(narrowspec.FILENAME) | |
1227 | def _narrowmatch(self): |
|
1227 | def _narrowmatch(self): | |
1228 | if repository.NARROW_REQUIREMENT not in self.requirements: |
|
1228 | if repository.NARROW_REQUIREMENT not in self.requirements: | |
1229 | return matchmod.always(self.root, '') |
|
1229 | return matchmod.always(self.root, '') | |
1230 | narrowspec.checkworkingcopynarrowspec(self) |
|
1230 | narrowspec.checkworkingcopynarrowspec(self) | |
1231 | include, exclude = self.narrowpats |
|
1231 | include, exclude = self.narrowpats | |
1232 | return narrowspec.match(self.root, include=include, exclude=exclude) |
|
1232 | return narrowspec.match(self.root, include=include, exclude=exclude) | |
1233 |
|
1233 | |||
1234 | def narrowmatch(self, match=None, includeexact=False): |
|
1234 | def narrowmatch(self, match=None, includeexact=False): | |
1235 | """matcher corresponding the the repo's narrowspec |
|
1235 | """matcher corresponding the the repo's narrowspec | |
1236 |
|
1236 | |||
1237 | If `match` is given, then that will be intersected with the narrow |
|
1237 | If `match` is given, then that will be intersected with the narrow | |
1238 | matcher. |
|
1238 | matcher. | |
1239 |
|
1239 | |||
1240 | If `includeexact` is True, then any exact matches from `match` will |
|
1240 | If `includeexact` is True, then any exact matches from `match` will | |
1241 | be included even if they're outside the narrowspec. |
|
1241 | be included even if they're outside the narrowspec. | |
1242 | """ |
|
1242 | """ | |
1243 | if match: |
|
1243 | if match: | |
1244 | if includeexact and not self._narrowmatch.always(): |
|
1244 | if includeexact and not self._narrowmatch.always(): | |
1245 | # do not exclude explicitly-specified paths so that they can |
|
1245 | # do not exclude explicitly-specified paths so that they can | |
1246 | # be warned later on |
|
1246 | # be warned later on | |
1247 | em = matchmod.exact(match._root, match._cwd, match.files()) |
|
1247 | em = matchmod.exact(match._root, match._cwd, match.files()) | |
1248 | nm = matchmod.unionmatcher([self._narrowmatch, em]) |
|
1248 | nm = matchmod.unionmatcher([self._narrowmatch, em]) | |
1249 | return matchmod.intersectmatchers(match, nm) |
|
1249 | return matchmod.intersectmatchers(match, nm) | |
1250 | return matchmod.intersectmatchers(match, self._narrowmatch) |
|
1250 | return matchmod.intersectmatchers(match, self._narrowmatch) | |
1251 | return self._narrowmatch |
|
1251 | return self._narrowmatch | |
1252 |
|
1252 | |||
1253 | def setnarrowpats(self, newincludes, newexcludes): |
|
1253 | def setnarrowpats(self, newincludes, newexcludes): | |
1254 | narrowspec.save(self, newincludes, newexcludes) |
|
1254 | narrowspec.save(self, newincludes, newexcludes) | |
1255 |
narrowspec.copytoworkingcopy(self |
|
1255 | narrowspec.copytoworkingcopy(self) | |
1256 | self.invalidate(clearfilecache=True) |
|
1256 | self.invalidate(clearfilecache=True) | |
1257 | # So the next access won't be considered a conflict |
|
1257 | # So the next access won't be considered a conflict | |
1258 | # TODO: It seems like there should be a way of doing this that |
|
1258 | # TODO: It seems like there should be a way of doing this that | |
1259 | # doesn't involve replacing these attributes. |
|
1259 | # doesn't involve replacing these attributes. | |
1260 | self.narrowpats = newincludes, newexcludes |
|
1260 | self.narrowpats = newincludes, newexcludes | |
1261 | self._narrowmatch = narrowspec.match(self.root, include=newincludes, |
|
1261 | self._narrowmatch = narrowspec.match(self.root, include=newincludes, | |
1262 | exclude=newexcludes) |
|
1262 | exclude=newexcludes) | |
1263 |
|
1263 | |||
1264 | def __getitem__(self, changeid): |
|
1264 | def __getitem__(self, changeid): | |
1265 | if changeid is None: |
|
1265 | if changeid is None: | |
1266 | return context.workingctx(self) |
|
1266 | return context.workingctx(self) | |
1267 | if isinstance(changeid, context.basectx): |
|
1267 | if isinstance(changeid, context.basectx): | |
1268 | return changeid |
|
1268 | return changeid | |
1269 | if isinstance(changeid, slice): |
|
1269 | if isinstance(changeid, slice): | |
1270 | # wdirrev isn't contiguous so the slice shouldn't include it |
|
1270 | # wdirrev isn't contiguous so the slice shouldn't include it | |
1271 | return [self[i] |
|
1271 | return [self[i] | |
1272 | for i in pycompat.xrange(*changeid.indices(len(self))) |
|
1272 | for i in pycompat.xrange(*changeid.indices(len(self))) | |
1273 | if i not in self.changelog.filteredrevs] |
|
1273 | if i not in self.changelog.filteredrevs] | |
1274 | try: |
|
1274 | try: | |
1275 | if isinstance(changeid, int): |
|
1275 | if isinstance(changeid, int): | |
1276 | node = self.changelog.node(changeid) |
|
1276 | node = self.changelog.node(changeid) | |
1277 | rev = changeid |
|
1277 | rev = changeid | |
1278 | elif changeid == 'null': |
|
1278 | elif changeid == 'null': | |
1279 | node = nullid |
|
1279 | node = nullid | |
1280 | rev = nullrev |
|
1280 | rev = nullrev | |
1281 | elif changeid == 'tip': |
|
1281 | elif changeid == 'tip': | |
1282 | node = self.changelog.tip() |
|
1282 | node = self.changelog.tip() | |
1283 | rev = self.changelog.rev(node) |
|
1283 | rev = self.changelog.rev(node) | |
1284 | elif changeid == '.': |
|
1284 | elif changeid == '.': | |
1285 | # this is a hack to delay/avoid loading obsmarkers |
|
1285 | # this is a hack to delay/avoid loading obsmarkers | |
1286 | # when we know that '.' won't be hidden |
|
1286 | # when we know that '.' won't be hidden | |
1287 | node = self.dirstate.p1() |
|
1287 | node = self.dirstate.p1() | |
1288 | rev = self.unfiltered().changelog.rev(node) |
|
1288 | rev = self.unfiltered().changelog.rev(node) | |
1289 | elif len(changeid) == 20: |
|
1289 | elif len(changeid) == 20: | |
1290 | try: |
|
1290 | try: | |
1291 | node = changeid |
|
1291 | node = changeid | |
1292 | rev = self.changelog.rev(changeid) |
|
1292 | rev = self.changelog.rev(changeid) | |
1293 | except error.FilteredLookupError: |
|
1293 | except error.FilteredLookupError: | |
1294 | changeid = hex(changeid) # for the error message |
|
1294 | changeid = hex(changeid) # for the error message | |
1295 | raise |
|
1295 | raise | |
1296 | except LookupError: |
|
1296 | except LookupError: | |
1297 | # check if it might have come from damaged dirstate |
|
1297 | # check if it might have come from damaged dirstate | |
1298 | # |
|
1298 | # | |
1299 | # XXX we could avoid the unfiltered if we had a recognizable |
|
1299 | # XXX we could avoid the unfiltered if we had a recognizable | |
1300 | # exception for filtered changeset access |
|
1300 | # exception for filtered changeset access | |
1301 | if (self.local() |
|
1301 | if (self.local() | |
1302 | and changeid in self.unfiltered().dirstate.parents()): |
|
1302 | and changeid in self.unfiltered().dirstate.parents()): | |
1303 | msg = _("working directory has unknown parent '%s'!") |
|
1303 | msg = _("working directory has unknown parent '%s'!") | |
1304 | raise error.Abort(msg % short(changeid)) |
|
1304 | raise error.Abort(msg % short(changeid)) | |
1305 | changeid = hex(changeid) # for the error message |
|
1305 | changeid = hex(changeid) # for the error message | |
1306 | raise |
|
1306 | raise | |
1307 |
|
1307 | |||
1308 | elif len(changeid) == 40: |
|
1308 | elif len(changeid) == 40: | |
1309 | node = bin(changeid) |
|
1309 | node = bin(changeid) | |
1310 | rev = self.changelog.rev(node) |
|
1310 | rev = self.changelog.rev(node) | |
1311 | else: |
|
1311 | else: | |
1312 | raise error.ProgrammingError( |
|
1312 | raise error.ProgrammingError( | |
1313 | "unsupported changeid '%s' of type %s" % |
|
1313 | "unsupported changeid '%s' of type %s" % | |
1314 | (changeid, type(changeid))) |
|
1314 | (changeid, type(changeid))) | |
1315 |
|
1315 | |||
1316 | return context.changectx(self, rev, node) |
|
1316 | return context.changectx(self, rev, node) | |
1317 |
|
1317 | |||
1318 | except (error.FilteredIndexError, error.FilteredLookupError): |
|
1318 | except (error.FilteredIndexError, error.FilteredLookupError): | |
1319 | raise error.FilteredRepoLookupError(_("filtered revision '%s'") |
|
1319 | raise error.FilteredRepoLookupError(_("filtered revision '%s'") | |
1320 | % pycompat.bytestr(changeid)) |
|
1320 | % pycompat.bytestr(changeid)) | |
1321 | except (IndexError, LookupError): |
|
1321 | except (IndexError, LookupError): | |
1322 | raise error.RepoLookupError( |
|
1322 | raise error.RepoLookupError( | |
1323 | _("unknown revision '%s'") % pycompat.bytestr(changeid)) |
|
1323 | _("unknown revision '%s'") % pycompat.bytestr(changeid)) | |
1324 | except error.WdirUnsupported: |
|
1324 | except error.WdirUnsupported: | |
1325 | return context.workingctx(self) |
|
1325 | return context.workingctx(self) | |
1326 |
|
1326 | |||
1327 | def __contains__(self, changeid): |
|
1327 | def __contains__(self, changeid): | |
1328 | """True if the given changeid exists |
|
1328 | """True if the given changeid exists | |
1329 |
|
1329 | |||
1330 | error.AmbiguousPrefixLookupError is raised if an ambiguous node |
|
1330 | error.AmbiguousPrefixLookupError is raised if an ambiguous node | |
1331 | specified. |
|
1331 | specified. | |
1332 | """ |
|
1332 | """ | |
1333 | try: |
|
1333 | try: | |
1334 | self[changeid] |
|
1334 | self[changeid] | |
1335 | return True |
|
1335 | return True | |
1336 | except error.RepoLookupError: |
|
1336 | except error.RepoLookupError: | |
1337 | return False |
|
1337 | return False | |
1338 |
|
1338 | |||
1339 | def __nonzero__(self): |
|
1339 | def __nonzero__(self): | |
1340 | return True |
|
1340 | return True | |
1341 |
|
1341 | |||
1342 | __bool__ = __nonzero__ |
|
1342 | __bool__ = __nonzero__ | |
1343 |
|
1343 | |||
1344 | def __len__(self): |
|
1344 | def __len__(self): | |
1345 | # no need to pay the cost of repoview.changelog |
|
1345 | # no need to pay the cost of repoview.changelog | |
1346 | unfi = self.unfiltered() |
|
1346 | unfi = self.unfiltered() | |
1347 | return len(unfi.changelog) |
|
1347 | return len(unfi.changelog) | |
1348 |
|
1348 | |||
1349 | def __iter__(self): |
|
1349 | def __iter__(self): | |
1350 | return iter(self.changelog) |
|
1350 | return iter(self.changelog) | |
1351 |
|
1351 | |||
1352 | def revs(self, expr, *args): |
|
1352 | def revs(self, expr, *args): | |
1353 | '''Find revisions matching a revset. |
|
1353 | '''Find revisions matching a revset. | |
1354 |
|
1354 | |||
1355 | The revset is specified as a string ``expr`` that may contain |
|
1355 | The revset is specified as a string ``expr`` that may contain | |
1356 | %-formatting to escape certain types. See ``revsetlang.formatspec``. |
|
1356 | %-formatting to escape certain types. See ``revsetlang.formatspec``. | |
1357 |
|
1357 | |||
1358 | Revset aliases from the configuration are not expanded. To expand |
|
1358 | Revset aliases from the configuration are not expanded. To expand | |
1359 | user aliases, consider calling ``scmutil.revrange()`` or |
|
1359 | user aliases, consider calling ``scmutil.revrange()`` or | |
1360 | ``repo.anyrevs([expr], user=True)``. |
|
1360 | ``repo.anyrevs([expr], user=True)``. | |
1361 |
|
1361 | |||
1362 | Returns a revset.abstractsmartset, which is a list-like interface |
|
1362 | Returns a revset.abstractsmartset, which is a list-like interface | |
1363 | that contains integer revisions. |
|
1363 | that contains integer revisions. | |
1364 | ''' |
|
1364 | ''' | |
1365 | tree = revsetlang.spectree(expr, *args) |
|
1365 | tree = revsetlang.spectree(expr, *args) | |
1366 | return revset.makematcher(tree)(self) |
|
1366 | return revset.makematcher(tree)(self) | |
1367 |
|
1367 | |||
1368 | def set(self, expr, *args): |
|
1368 | def set(self, expr, *args): | |
1369 | '''Find revisions matching a revset and emit changectx instances. |
|
1369 | '''Find revisions matching a revset and emit changectx instances. | |
1370 |
|
1370 | |||
1371 | This is a convenience wrapper around ``revs()`` that iterates the |
|
1371 | This is a convenience wrapper around ``revs()`` that iterates the | |
1372 | result and is a generator of changectx instances. |
|
1372 | result and is a generator of changectx instances. | |
1373 |
|
1373 | |||
1374 | Revset aliases from the configuration are not expanded. To expand |
|
1374 | Revset aliases from the configuration are not expanded. To expand | |
1375 | user aliases, consider calling ``scmutil.revrange()``. |
|
1375 | user aliases, consider calling ``scmutil.revrange()``. | |
1376 | ''' |
|
1376 | ''' | |
1377 | for r in self.revs(expr, *args): |
|
1377 | for r in self.revs(expr, *args): | |
1378 | yield self[r] |
|
1378 | yield self[r] | |
1379 |
|
1379 | |||
1380 | def anyrevs(self, specs, user=False, localalias=None): |
|
1380 | def anyrevs(self, specs, user=False, localalias=None): | |
1381 | '''Find revisions matching one of the given revsets. |
|
1381 | '''Find revisions matching one of the given revsets. | |
1382 |
|
1382 | |||
1383 | Revset aliases from the configuration are not expanded by default. To |
|
1383 | Revset aliases from the configuration are not expanded by default. To | |
1384 | expand user aliases, specify ``user=True``. To provide some local |
|
1384 | expand user aliases, specify ``user=True``. To provide some local | |
1385 | definitions overriding user aliases, set ``localalias`` to |
|
1385 | definitions overriding user aliases, set ``localalias`` to | |
1386 | ``{name: definitionstring}``. |
|
1386 | ``{name: definitionstring}``. | |
1387 | ''' |
|
1387 | ''' | |
1388 | if user: |
|
1388 | if user: | |
1389 | m = revset.matchany(self.ui, specs, |
|
1389 | m = revset.matchany(self.ui, specs, | |
1390 | lookup=revset.lookupfn(self), |
|
1390 | lookup=revset.lookupfn(self), | |
1391 | localalias=localalias) |
|
1391 | localalias=localalias) | |
1392 | else: |
|
1392 | else: | |
1393 | m = revset.matchany(None, specs, localalias=localalias) |
|
1393 | m = revset.matchany(None, specs, localalias=localalias) | |
1394 | return m(self) |
|
1394 | return m(self) | |
1395 |
|
1395 | |||
1396 | def url(self): |
|
1396 | def url(self): | |
1397 | return 'file:' + self.root |
|
1397 | return 'file:' + self.root | |
1398 |
|
1398 | |||
1399 | def hook(self, name, throw=False, **args): |
|
1399 | def hook(self, name, throw=False, **args): | |
1400 | """Call a hook, passing this repo instance. |
|
1400 | """Call a hook, passing this repo instance. | |
1401 |
|
1401 | |||
1402 | This a convenience method to aid invoking hooks. Extensions likely |
|
1402 | This a convenience method to aid invoking hooks. Extensions likely | |
1403 | won't call this unless they have registered a custom hook or are |
|
1403 | won't call this unless they have registered a custom hook or are | |
1404 | replacing code that is expected to call a hook. |
|
1404 | replacing code that is expected to call a hook. | |
1405 | """ |
|
1405 | """ | |
1406 | return hook.hook(self.ui, self, name, throw, **args) |
|
1406 | return hook.hook(self.ui, self, name, throw, **args) | |
1407 |
|
1407 | |||
1408 | @filteredpropertycache |
|
1408 | @filteredpropertycache | |
1409 | def _tagscache(self): |
|
1409 | def _tagscache(self): | |
1410 | '''Returns a tagscache object that contains various tags related |
|
1410 | '''Returns a tagscache object that contains various tags related | |
1411 | caches.''' |
|
1411 | caches.''' | |
1412 |
|
1412 | |||
1413 | # This simplifies its cache management by having one decorated |
|
1413 | # This simplifies its cache management by having one decorated | |
1414 | # function (this one) and the rest simply fetch things from it. |
|
1414 | # function (this one) and the rest simply fetch things from it. | |
1415 | class tagscache(object): |
|
1415 | class tagscache(object): | |
1416 | def __init__(self): |
|
1416 | def __init__(self): | |
1417 | # These two define the set of tags for this repository. tags |
|
1417 | # These two define the set of tags for this repository. tags | |
1418 | # maps tag name to node; tagtypes maps tag name to 'global' or |
|
1418 | # maps tag name to node; tagtypes maps tag name to 'global' or | |
1419 | # 'local'. (Global tags are defined by .hgtags across all |
|
1419 | # 'local'. (Global tags are defined by .hgtags across all | |
1420 | # heads, and local tags are defined in .hg/localtags.) |
|
1420 | # heads, and local tags are defined in .hg/localtags.) | |
1421 | # They constitute the in-memory cache of tags. |
|
1421 | # They constitute the in-memory cache of tags. | |
1422 | self.tags = self.tagtypes = None |
|
1422 | self.tags = self.tagtypes = None | |
1423 |
|
1423 | |||
1424 | self.nodetagscache = self.tagslist = None |
|
1424 | self.nodetagscache = self.tagslist = None | |
1425 |
|
1425 | |||
1426 | cache = tagscache() |
|
1426 | cache = tagscache() | |
1427 | cache.tags, cache.tagtypes = self._findtags() |
|
1427 | cache.tags, cache.tagtypes = self._findtags() | |
1428 |
|
1428 | |||
1429 | return cache |
|
1429 | return cache | |
1430 |
|
1430 | |||
1431 | def tags(self): |
|
1431 | def tags(self): | |
1432 | '''return a mapping of tag to node''' |
|
1432 | '''return a mapping of tag to node''' | |
1433 | t = {} |
|
1433 | t = {} | |
1434 | if self.changelog.filteredrevs: |
|
1434 | if self.changelog.filteredrevs: | |
1435 | tags, tt = self._findtags() |
|
1435 | tags, tt = self._findtags() | |
1436 | else: |
|
1436 | else: | |
1437 | tags = self._tagscache.tags |
|
1437 | tags = self._tagscache.tags | |
1438 | rev = self.changelog.rev |
|
1438 | rev = self.changelog.rev | |
1439 | for k, v in tags.iteritems(): |
|
1439 | for k, v in tags.iteritems(): | |
1440 | try: |
|
1440 | try: | |
1441 | # ignore tags to unknown nodes |
|
1441 | # ignore tags to unknown nodes | |
1442 | rev(v) |
|
1442 | rev(v) | |
1443 | t[k] = v |
|
1443 | t[k] = v | |
1444 | except (error.LookupError, ValueError): |
|
1444 | except (error.LookupError, ValueError): | |
1445 | pass |
|
1445 | pass | |
1446 | return t |
|
1446 | return t | |
1447 |
|
1447 | |||
1448 | def _findtags(self): |
|
1448 | def _findtags(self): | |
1449 | '''Do the hard work of finding tags. Return a pair of dicts |
|
1449 | '''Do the hard work of finding tags. Return a pair of dicts | |
1450 | (tags, tagtypes) where tags maps tag name to node, and tagtypes |
|
1450 | (tags, tagtypes) where tags maps tag name to node, and tagtypes | |
1451 | maps tag name to a string like \'global\' or \'local\'. |
|
1451 | maps tag name to a string like \'global\' or \'local\'. | |
1452 | Subclasses or extensions are free to add their own tags, but |
|
1452 | Subclasses or extensions are free to add their own tags, but | |
1453 | should be aware that the returned dicts will be retained for the |
|
1453 | should be aware that the returned dicts will be retained for the | |
1454 | duration of the localrepo object.''' |
|
1454 | duration of the localrepo object.''' | |
1455 |
|
1455 | |||
1456 | # XXX what tagtype should subclasses/extensions use? Currently |
|
1456 | # XXX what tagtype should subclasses/extensions use? Currently | |
1457 | # mq and bookmarks add tags, but do not set the tagtype at all. |
|
1457 | # mq and bookmarks add tags, but do not set the tagtype at all. | |
1458 | # Should each extension invent its own tag type? Should there |
|
1458 | # Should each extension invent its own tag type? Should there | |
1459 | # be one tagtype for all such "virtual" tags? Or is the status |
|
1459 | # be one tagtype for all such "virtual" tags? Or is the status | |
1460 | # quo fine? |
|
1460 | # quo fine? | |
1461 |
|
1461 | |||
1462 |
|
1462 | |||
1463 | # map tag name to (node, hist) |
|
1463 | # map tag name to (node, hist) | |
1464 | alltags = tagsmod.findglobaltags(self.ui, self) |
|
1464 | alltags = tagsmod.findglobaltags(self.ui, self) | |
1465 | # map tag name to tag type |
|
1465 | # map tag name to tag type | |
1466 | tagtypes = dict((tag, 'global') for tag in alltags) |
|
1466 | tagtypes = dict((tag, 'global') for tag in alltags) | |
1467 |
|
1467 | |||
1468 | tagsmod.readlocaltags(self.ui, self, alltags, tagtypes) |
|
1468 | tagsmod.readlocaltags(self.ui, self, alltags, tagtypes) | |
1469 |
|
1469 | |||
1470 | # Build the return dicts. Have to re-encode tag names because |
|
1470 | # Build the return dicts. Have to re-encode tag names because | |
1471 | # the tags module always uses UTF-8 (in order not to lose info |
|
1471 | # the tags module always uses UTF-8 (in order not to lose info | |
1472 | # writing to the cache), but the rest of Mercurial wants them in |
|
1472 | # writing to the cache), but the rest of Mercurial wants them in | |
1473 | # local encoding. |
|
1473 | # local encoding. | |
1474 | tags = {} |
|
1474 | tags = {} | |
1475 | for (name, (node, hist)) in alltags.iteritems(): |
|
1475 | for (name, (node, hist)) in alltags.iteritems(): | |
1476 | if node != nullid: |
|
1476 | if node != nullid: | |
1477 | tags[encoding.tolocal(name)] = node |
|
1477 | tags[encoding.tolocal(name)] = node | |
1478 | tags['tip'] = self.changelog.tip() |
|
1478 | tags['tip'] = self.changelog.tip() | |
1479 | tagtypes = dict([(encoding.tolocal(name), value) |
|
1479 | tagtypes = dict([(encoding.tolocal(name), value) | |
1480 | for (name, value) in tagtypes.iteritems()]) |
|
1480 | for (name, value) in tagtypes.iteritems()]) | |
1481 | return (tags, tagtypes) |
|
1481 | return (tags, tagtypes) | |
1482 |
|
1482 | |||
1483 | def tagtype(self, tagname): |
|
1483 | def tagtype(self, tagname): | |
1484 | ''' |
|
1484 | ''' | |
1485 | return the type of the given tag. result can be: |
|
1485 | return the type of the given tag. result can be: | |
1486 |
|
1486 | |||
1487 | 'local' : a local tag |
|
1487 | 'local' : a local tag | |
1488 | 'global' : a global tag |
|
1488 | 'global' : a global tag | |
1489 | None : tag does not exist |
|
1489 | None : tag does not exist | |
1490 | ''' |
|
1490 | ''' | |
1491 |
|
1491 | |||
1492 | return self._tagscache.tagtypes.get(tagname) |
|
1492 | return self._tagscache.tagtypes.get(tagname) | |
1493 |
|
1493 | |||
1494 | def tagslist(self): |
|
1494 | def tagslist(self): | |
1495 | '''return a list of tags ordered by revision''' |
|
1495 | '''return a list of tags ordered by revision''' | |
1496 | if not self._tagscache.tagslist: |
|
1496 | if not self._tagscache.tagslist: | |
1497 | l = [] |
|
1497 | l = [] | |
1498 | for t, n in self.tags().iteritems(): |
|
1498 | for t, n in self.tags().iteritems(): | |
1499 | l.append((self.changelog.rev(n), t, n)) |
|
1499 | l.append((self.changelog.rev(n), t, n)) | |
1500 | self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)] |
|
1500 | self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)] | |
1501 |
|
1501 | |||
1502 | return self._tagscache.tagslist |
|
1502 | return self._tagscache.tagslist | |
1503 |
|
1503 | |||
1504 | def nodetags(self, node): |
|
1504 | def nodetags(self, node): | |
1505 | '''return the tags associated with a node''' |
|
1505 | '''return the tags associated with a node''' | |
1506 | if not self._tagscache.nodetagscache: |
|
1506 | if not self._tagscache.nodetagscache: | |
1507 | nodetagscache = {} |
|
1507 | nodetagscache = {} | |
1508 | for t, n in self._tagscache.tags.iteritems(): |
|
1508 | for t, n in self._tagscache.tags.iteritems(): | |
1509 | nodetagscache.setdefault(n, []).append(t) |
|
1509 | nodetagscache.setdefault(n, []).append(t) | |
1510 | for tags in nodetagscache.itervalues(): |
|
1510 | for tags in nodetagscache.itervalues(): | |
1511 | tags.sort() |
|
1511 | tags.sort() | |
1512 | self._tagscache.nodetagscache = nodetagscache |
|
1512 | self._tagscache.nodetagscache = nodetagscache | |
1513 | return self._tagscache.nodetagscache.get(node, []) |
|
1513 | return self._tagscache.nodetagscache.get(node, []) | |
1514 |
|
1514 | |||
1515 | def nodebookmarks(self, node): |
|
1515 | def nodebookmarks(self, node): | |
1516 | """return the list of bookmarks pointing to the specified node""" |
|
1516 | """return the list of bookmarks pointing to the specified node""" | |
1517 | return self._bookmarks.names(node) |
|
1517 | return self._bookmarks.names(node) | |
1518 |
|
1518 | |||
1519 | def branchmap(self): |
|
1519 | def branchmap(self): | |
1520 | '''returns a dictionary {branch: [branchheads]} with branchheads |
|
1520 | '''returns a dictionary {branch: [branchheads]} with branchheads | |
1521 | ordered by increasing revision number''' |
|
1521 | ordered by increasing revision number''' | |
1522 | branchmap.updatecache(self) |
|
1522 | branchmap.updatecache(self) | |
1523 | return self._branchcaches[self.filtername] |
|
1523 | return self._branchcaches[self.filtername] | |
1524 |
|
1524 | |||
1525 | @unfilteredmethod |
|
1525 | @unfilteredmethod | |
1526 | def revbranchcache(self): |
|
1526 | def revbranchcache(self): | |
1527 | if not self._revbranchcache: |
|
1527 | if not self._revbranchcache: | |
1528 | self._revbranchcache = branchmap.revbranchcache(self.unfiltered()) |
|
1528 | self._revbranchcache = branchmap.revbranchcache(self.unfiltered()) | |
1529 | return self._revbranchcache |
|
1529 | return self._revbranchcache | |
1530 |
|
1530 | |||
1531 | def branchtip(self, branch, ignoremissing=False): |
|
1531 | def branchtip(self, branch, ignoremissing=False): | |
1532 | '''return the tip node for a given branch |
|
1532 | '''return the tip node for a given branch | |
1533 |
|
1533 | |||
1534 | If ignoremissing is True, then this method will not raise an error. |
|
1534 | If ignoremissing is True, then this method will not raise an error. | |
1535 | This is helpful for callers that only expect None for a missing branch |
|
1535 | This is helpful for callers that only expect None for a missing branch | |
1536 | (e.g. namespace). |
|
1536 | (e.g. namespace). | |
1537 |
|
1537 | |||
1538 | ''' |
|
1538 | ''' | |
1539 | try: |
|
1539 | try: | |
1540 | return self.branchmap().branchtip(branch) |
|
1540 | return self.branchmap().branchtip(branch) | |
1541 | except KeyError: |
|
1541 | except KeyError: | |
1542 | if not ignoremissing: |
|
1542 | if not ignoremissing: | |
1543 | raise error.RepoLookupError(_("unknown branch '%s'") % branch) |
|
1543 | raise error.RepoLookupError(_("unknown branch '%s'") % branch) | |
1544 | else: |
|
1544 | else: | |
1545 | pass |
|
1545 | pass | |
1546 |
|
1546 | |||
1547 | def lookup(self, key): |
|
1547 | def lookup(self, key): | |
1548 | return scmutil.revsymbol(self, key).node() |
|
1548 | return scmutil.revsymbol(self, key).node() | |
1549 |
|
1549 | |||
1550 | def lookupbranch(self, key): |
|
1550 | def lookupbranch(self, key): | |
1551 | if key in self.branchmap(): |
|
1551 | if key in self.branchmap(): | |
1552 | return key |
|
1552 | return key | |
1553 |
|
1553 | |||
1554 | return scmutil.revsymbol(self, key).branch() |
|
1554 | return scmutil.revsymbol(self, key).branch() | |
1555 |
|
1555 | |||
1556 | def known(self, nodes): |
|
1556 | def known(self, nodes): | |
1557 | cl = self.changelog |
|
1557 | cl = self.changelog | |
1558 | nm = cl.nodemap |
|
1558 | nm = cl.nodemap | |
1559 | filtered = cl.filteredrevs |
|
1559 | filtered = cl.filteredrevs | |
1560 | result = [] |
|
1560 | result = [] | |
1561 | for n in nodes: |
|
1561 | for n in nodes: | |
1562 | r = nm.get(n) |
|
1562 | r = nm.get(n) | |
1563 | resp = not (r is None or r in filtered) |
|
1563 | resp = not (r is None or r in filtered) | |
1564 | result.append(resp) |
|
1564 | result.append(resp) | |
1565 | return result |
|
1565 | return result | |
1566 |
|
1566 | |||
1567 | def local(self): |
|
1567 | def local(self): | |
1568 | return self |
|
1568 | return self | |
1569 |
|
1569 | |||
1570 | def publishing(self): |
|
1570 | def publishing(self): | |
1571 | # it's safe (and desirable) to trust the publish flag unconditionally |
|
1571 | # it's safe (and desirable) to trust the publish flag unconditionally | |
1572 | # so that we don't finalize changes shared between users via ssh or nfs |
|
1572 | # so that we don't finalize changes shared between users via ssh or nfs | |
1573 | return self.ui.configbool('phases', 'publish', untrusted=True) |
|
1573 | return self.ui.configbool('phases', 'publish', untrusted=True) | |
1574 |
|
1574 | |||
1575 | def cancopy(self): |
|
1575 | def cancopy(self): | |
1576 | # so statichttprepo's override of local() works |
|
1576 | # so statichttprepo's override of local() works | |
1577 | if not self.local(): |
|
1577 | if not self.local(): | |
1578 | return False |
|
1578 | return False | |
1579 | if not self.publishing(): |
|
1579 | if not self.publishing(): | |
1580 | return True |
|
1580 | return True | |
1581 | # if publishing we can't copy if there is filtered content |
|
1581 | # if publishing we can't copy if there is filtered content | |
1582 | return not self.filtered('visible').changelog.filteredrevs |
|
1582 | return not self.filtered('visible').changelog.filteredrevs | |
1583 |
|
1583 | |||
1584 | def shared(self): |
|
1584 | def shared(self): | |
1585 | '''the type of shared repository (None if not shared)''' |
|
1585 | '''the type of shared repository (None if not shared)''' | |
1586 | if self.sharedpath != self.path: |
|
1586 | if self.sharedpath != self.path: | |
1587 | return 'store' |
|
1587 | return 'store' | |
1588 | return None |
|
1588 | return None | |
1589 |
|
1589 | |||
1590 | def wjoin(self, f, *insidef): |
|
1590 | def wjoin(self, f, *insidef): | |
1591 | return self.vfs.reljoin(self.root, f, *insidef) |
|
1591 | return self.vfs.reljoin(self.root, f, *insidef) | |
1592 |
|
1592 | |||
1593 | def setparents(self, p1, p2=nullid): |
|
1593 | def setparents(self, p1, p2=nullid): | |
1594 | with self.dirstate.parentchange(): |
|
1594 | with self.dirstate.parentchange(): | |
1595 | copies = self.dirstate.setparents(p1, p2) |
|
1595 | copies = self.dirstate.setparents(p1, p2) | |
1596 | pctx = self[p1] |
|
1596 | pctx = self[p1] | |
1597 | if copies: |
|
1597 | if copies: | |
1598 | # Adjust copy records, the dirstate cannot do it, it |
|
1598 | # Adjust copy records, the dirstate cannot do it, it | |
1599 | # requires access to parents manifests. Preserve them |
|
1599 | # requires access to parents manifests. Preserve them | |
1600 | # only for entries added to first parent. |
|
1600 | # only for entries added to first parent. | |
1601 | for f in copies: |
|
1601 | for f in copies: | |
1602 | if f not in pctx and copies[f] in pctx: |
|
1602 | if f not in pctx and copies[f] in pctx: | |
1603 | self.dirstate.copy(copies[f], f) |
|
1603 | self.dirstate.copy(copies[f], f) | |
1604 | if p2 == nullid: |
|
1604 | if p2 == nullid: | |
1605 | for f, s in sorted(self.dirstate.copies().items()): |
|
1605 | for f, s in sorted(self.dirstate.copies().items()): | |
1606 | if f not in pctx and s not in pctx: |
|
1606 | if f not in pctx and s not in pctx: | |
1607 | self.dirstate.copy(None, f) |
|
1607 | self.dirstate.copy(None, f) | |
1608 |
|
1608 | |||
1609 | def filectx(self, path, changeid=None, fileid=None, changectx=None): |
|
1609 | def filectx(self, path, changeid=None, fileid=None, changectx=None): | |
1610 | """changeid must be a changeset revision, if specified. |
|
1610 | """changeid must be a changeset revision, if specified. | |
1611 | fileid can be a file revision or node.""" |
|
1611 | fileid can be a file revision or node.""" | |
1612 | return context.filectx(self, path, changeid, fileid, |
|
1612 | return context.filectx(self, path, changeid, fileid, | |
1613 | changectx=changectx) |
|
1613 | changectx=changectx) | |
1614 |
|
1614 | |||
1615 | def getcwd(self): |
|
1615 | def getcwd(self): | |
1616 | return self.dirstate.getcwd() |
|
1616 | return self.dirstate.getcwd() | |
1617 |
|
1617 | |||
1618 | def pathto(self, f, cwd=None): |
|
1618 | def pathto(self, f, cwd=None): | |
1619 | return self.dirstate.pathto(f, cwd) |
|
1619 | return self.dirstate.pathto(f, cwd) | |
1620 |
|
1620 | |||
1621 | def _loadfilter(self, filter): |
|
1621 | def _loadfilter(self, filter): | |
1622 | if filter not in self._filterpats: |
|
1622 | if filter not in self._filterpats: | |
1623 | l = [] |
|
1623 | l = [] | |
1624 | for pat, cmd in self.ui.configitems(filter): |
|
1624 | for pat, cmd in self.ui.configitems(filter): | |
1625 | if cmd == '!': |
|
1625 | if cmd == '!': | |
1626 | continue |
|
1626 | continue | |
1627 | mf = matchmod.match(self.root, '', [pat]) |
|
1627 | mf = matchmod.match(self.root, '', [pat]) | |
1628 | fn = None |
|
1628 | fn = None | |
1629 | params = cmd |
|
1629 | params = cmd | |
1630 | for name, filterfn in self._datafilters.iteritems(): |
|
1630 | for name, filterfn in self._datafilters.iteritems(): | |
1631 | if cmd.startswith(name): |
|
1631 | if cmd.startswith(name): | |
1632 | fn = filterfn |
|
1632 | fn = filterfn | |
1633 | params = cmd[len(name):].lstrip() |
|
1633 | params = cmd[len(name):].lstrip() | |
1634 | break |
|
1634 | break | |
1635 | if not fn: |
|
1635 | if not fn: | |
1636 | fn = lambda s, c, **kwargs: procutil.filter(s, c) |
|
1636 | fn = lambda s, c, **kwargs: procutil.filter(s, c) | |
1637 | # Wrap old filters not supporting keyword arguments |
|
1637 | # Wrap old filters not supporting keyword arguments | |
1638 | if not pycompat.getargspec(fn)[2]: |
|
1638 | if not pycompat.getargspec(fn)[2]: | |
1639 | oldfn = fn |
|
1639 | oldfn = fn | |
1640 | fn = lambda s, c, **kwargs: oldfn(s, c) |
|
1640 | fn = lambda s, c, **kwargs: oldfn(s, c) | |
1641 | l.append((mf, fn, params)) |
|
1641 | l.append((mf, fn, params)) | |
1642 | self._filterpats[filter] = l |
|
1642 | self._filterpats[filter] = l | |
1643 | return self._filterpats[filter] |
|
1643 | return self._filterpats[filter] | |
1644 |
|
1644 | |||
1645 | def _filter(self, filterpats, filename, data): |
|
1645 | def _filter(self, filterpats, filename, data): | |
1646 | for mf, fn, cmd in filterpats: |
|
1646 | for mf, fn, cmd in filterpats: | |
1647 | if mf(filename): |
|
1647 | if mf(filename): | |
1648 | self.ui.debug("filtering %s through %s\n" % (filename, cmd)) |
|
1648 | self.ui.debug("filtering %s through %s\n" % (filename, cmd)) | |
1649 | data = fn(data, cmd, ui=self.ui, repo=self, filename=filename) |
|
1649 | data = fn(data, cmd, ui=self.ui, repo=self, filename=filename) | |
1650 | break |
|
1650 | break | |
1651 |
|
1651 | |||
1652 | return data |
|
1652 | return data | |
1653 |
|
1653 | |||
1654 | @unfilteredpropertycache |
|
1654 | @unfilteredpropertycache | |
1655 | def _encodefilterpats(self): |
|
1655 | def _encodefilterpats(self): | |
1656 | return self._loadfilter('encode') |
|
1656 | return self._loadfilter('encode') | |
1657 |
|
1657 | |||
1658 | @unfilteredpropertycache |
|
1658 | @unfilteredpropertycache | |
1659 | def _decodefilterpats(self): |
|
1659 | def _decodefilterpats(self): | |
1660 | return self._loadfilter('decode') |
|
1660 | return self._loadfilter('decode') | |
1661 |
|
1661 | |||
1662 | def adddatafilter(self, name, filter): |
|
1662 | def adddatafilter(self, name, filter): | |
1663 | self._datafilters[name] = filter |
|
1663 | self._datafilters[name] = filter | |
1664 |
|
1664 | |||
1665 | def wread(self, filename): |
|
1665 | def wread(self, filename): | |
1666 | if self.wvfs.islink(filename): |
|
1666 | if self.wvfs.islink(filename): | |
1667 | data = self.wvfs.readlink(filename) |
|
1667 | data = self.wvfs.readlink(filename) | |
1668 | else: |
|
1668 | else: | |
1669 | data = self.wvfs.read(filename) |
|
1669 | data = self.wvfs.read(filename) | |
1670 | return self._filter(self._encodefilterpats, filename, data) |
|
1670 | return self._filter(self._encodefilterpats, filename, data) | |
1671 |
|
1671 | |||
1672 | def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs): |
|
1672 | def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs): | |
1673 | """write ``data`` into ``filename`` in the working directory |
|
1673 | """write ``data`` into ``filename`` in the working directory | |
1674 |
|
1674 | |||
1675 | This returns length of written (maybe decoded) data. |
|
1675 | This returns length of written (maybe decoded) data. | |
1676 | """ |
|
1676 | """ | |
1677 | data = self._filter(self._decodefilterpats, filename, data) |
|
1677 | data = self._filter(self._decodefilterpats, filename, data) | |
1678 | if 'l' in flags: |
|
1678 | if 'l' in flags: | |
1679 | self.wvfs.symlink(data, filename) |
|
1679 | self.wvfs.symlink(data, filename) | |
1680 | else: |
|
1680 | else: | |
1681 | self.wvfs.write(filename, data, backgroundclose=backgroundclose, |
|
1681 | self.wvfs.write(filename, data, backgroundclose=backgroundclose, | |
1682 | **kwargs) |
|
1682 | **kwargs) | |
1683 | if 'x' in flags: |
|
1683 | if 'x' in flags: | |
1684 | self.wvfs.setflags(filename, False, True) |
|
1684 | self.wvfs.setflags(filename, False, True) | |
1685 | else: |
|
1685 | else: | |
1686 | self.wvfs.setflags(filename, False, False) |
|
1686 | self.wvfs.setflags(filename, False, False) | |
1687 | return len(data) |
|
1687 | return len(data) | |
1688 |
|
1688 | |||
1689 | def wwritedata(self, filename, data): |
|
1689 | def wwritedata(self, filename, data): | |
1690 | return self._filter(self._decodefilterpats, filename, data) |
|
1690 | return self._filter(self._decodefilterpats, filename, data) | |
1691 |
|
1691 | |||
1692 | def currenttransaction(self): |
|
1692 | def currenttransaction(self): | |
1693 | """return the current transaction or None if non exists""" |
|
1693 | """return the current transaction or None if non exists""" | |
1694 | if self._transref: |
|
1694 | if self._transref: | |
1695 | tr = self._transref() |
|
1695 | tr = self._transref() | |
1696 | else: |
|
1696 | else: | |
1697 | tr = None |
|
1697 | tr = None | |
1698 |
|
1698 | |||
1699 | if tr and tr.running(): |
|
1699 | if tr and tr.running(): | |
1700 | return tr |
|
1700 | return tr | |
1701 | return None |
|
1701 | return None | |
1702 |
|
1702 | |||
1703 | def transaction(self, desc, report=None): |
|
1703 | def transaction(self, desc, report=None): | |
1704 | if (self.ui.configbool('devel', 'all-warnings') |
|
1704 | if (self.ui.configbool('devel', 'all-warnings') | |
1705 | or self.ui.configbool('devel', 'check-locks')): |
|
1705 | or self.ui.configbool('devel', 'check-locks')): | |
1706 | if self._currentlock(self._lockref) is None: |
|
1706 | if self._currentlock(self._lockref) is None: | |
1707 | raise error.ProgrammingError('transaction requires locking') |
|
1707 | raise error.ProgrammingError('transaction requires locking') | |
1708 | tr = self.currenttransaction() |
|
1708 | tr = self.currenttransaction() | |
1709 | if tr is not None: |
|
1709 | if tr is not None: | |
1710 | return tr.nest(name=desc) |
|
1710 | return tr.nest(name=desc) | |
1711 |
|
1711 | |||
1712 | # abort here if the journal already exists |
|
1712 | # abort here if the journal already exists | |
1713 | if self.svfs.exists("journal"): |
|
1713 | if self.svfs.exists("journal"): | |
1714 | raise error.RepoError( |
|
1714 | raise error.RepoError( | |
1715 | _("abandoned transaction found"), |
|
1715 | _("abandoned transaction found"), | |
1716 | hint=_("run 'hg recover' to clean up transaction")) |
|
1716 | hint=_("run 'hg recover' to clean up transaction")) | |
1717 |
|
1717 | |||
1718 | idbase = "%.40f#%f" % (random.random(), time.time()) |
|
1718 | idbase = "%.40f#%f" % (random.random(), time.time()) | |
1719 | ha = hex(hashlib.sha1(idbase).digest()) |
|
1719 | ha = hex(hashlib.sha1(idbase).digest()) | |
1720 | txnid = 'TXN:' + ha |
|
1720 | txnid = 'TXN:' + ha | |
1721 | self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid) |
|
1721 | self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid) | |
1722 |
|
1722 | |||
1723 | self._writejournal(desc) |
|
1723 | self._writejournal(desc) | |
1724 | renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()] |
|
1724 | renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()] | |
1725 | if report: |
|
1725 | if report: | |
1726 | rp = report |
|
1726 | rp = report | |
1727 | else: |
|
1727 | else: | |
1728 | rp = self.ui.warn |
|
1728 | rp = self.ui.warn | |
1729 | vfsmap = {'plain': self.vfs, 'store': self.svfs} # root of .hg/ |
|
1729 | vfsmap = {'plain': self.vfs, 'store': self.svfs} # root of .hg/ | |
1730 | # we must avoid cyclic reference between repo and transaction. |
|
1730 | # we must avoid cyclic reference between repo and transaction. | |
1731 | reporef = weakref.ref(self) |
|
1731 | reporef = weakref.ref(self) | |
1732 | # Code to track tag movement |
|
1732 | # Code to track tag movement | |
1733 | # |
|
1733 | # | |
1734 | # Since tags are all handled as file content, it is actually quite hard |
|
1734 | # Since tags are all handled as file content, it is actually quite hard | |
1735 | # to track these movement from a code perspective. So we fallback to a |
|
1735 | # to track these movement from a code perspective. So we fallback to a | |
1736 | # tracking at the repository level. One could envision to track changes |
|
1736 | # tracking at the repository level. One could envision to track changes | |
1737 | # to the '.hgtags' file through changegroup apply but that fails to |
|
1737 | # to the '.hgtags' file through changegroup apply but that fails to | |
1738 | # cope with case where transaction expose new heads without changegroup |
|
1738 | # cope with case where transaction expose new heads without changegroup | |
1739 | # being involved (eg: phase movement). |
|
1739 | # being involved (eg: phase movement). | |
1740 | # |
|
1740 | # | |
1741 | # For now, We gate the feature behind a flag since this likely comes |
|
1741 | # For now, We gate the feature behind a flag since this likely comes | |
1742 | # with performance impacts. The current code run more often than needed |
|
1742 | # with performance impacts. The current code run more often than needed | |
1743 | # and do not use caches as much as it could. The current focus is on |
|
1743 | # and do not use caches as much as it could. The current focus is on | |
1744 | # the behavior of the feature so we disable it by default. The flag |
|
1744 | # the behavior of the feature so we disable it by default. The flag | |
1745 | # will be removed when we are happy with the performance impact. |
|
1745 | # will be removed when we are happy with the performance impact. | |
1746 | # |
|
1746 | # | |
1747 | # Once this feature is no longer experimental move the following |
|
1747 | # Once this feature is no longer experimental move the following | |
1748 | # documentation to the appropriate help section: |
|
1748 | # documentation to the appropriate help section: | |
1749 | # |
|
1749 | # | |
1750 | # The ``HG_TAG_MOVED`` variable will be set if the transaction touched |
|
1750 | # The ``HG_TAG_MOVED`` variable will be set if the transaction touched | |
1751 | # tags (new or changed or deleted tags). In addition the details of |
|
1751 | # tags (new or changed or deleted tags). In addition the details of | |
1752 | # these changes are made available in a file at: |
|
1752 | # these changes are made available in a file at: | |
1753 | # ``REPOROOT/.hg/changes/tags.changes``. |
|
1753 | # ``REPOROOT/.hg/changes/tags.changes``. | |
1754 | # Make sure you check for HG_TAG_MOVED before reading that file as it |
|
1754 | # Make sure you check for HG_TAG_MOVED before reading that file as it | |
1755 | # might exist from a previous transaction even if no tag were touched |
|
1755 | # might exist from a previous transaction even if no tag were touched | |
1756 | # in this one. Changes are recorded in a line base format:: |
|
1756 | # in this one. Changes are recorded in a line base format:: | |
1757 | # |
|
1757 | # | |
1758 | # <action> <hex-node> <tag-name>\n |
|
1758 | # <action> <hex-node> <tag-name>\n | |
1759 | # |
|
1759 | # | |
1760 | # Actions are defined as follow: |
|
1760 | # Actions are defined as follow: | |
1761 | # "-R": tag is removed, |
|
1761 | # "-R": tag is removed, | |
1762 | # "+A": tag is added, |
|
1762 | # "+A": tag is added, | |
1763 | # "-M": tag is moved (old value), |
|
1763 | # "-M": tag is moved (old value), | |
1764 | # "+M": tag is moved (new value), |
|
1764 | # "+M": tag is moved (new value), | |
1765 | tracktags = lambda x: None |
|
1765 | tracktags = lambda x: None | |
1766 | # experimental config: experimental.hook-track-tags |
|
1766 | # experimental config: experimental.hook-track-tags | |
1767 | shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags') |
|
1767 | shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags') | |
1768 | if desc != 'strip' and shouldtracktags: |
|
1768 | if desc != 'strip' and shouldtracktags: | |
1769 | oldheads = self.changelog.headrevs() |
|
1769 | oldheads = self.changelog.headrevs() | |
1770 | def tracktags(tr2): |
|
1770 | def tracktags(tr2): | |
1771 | repo = reporef() |
|
1771 | repo = reporef() | |
1772 | oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads) |
|
1772 | oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads) | |
1773 | newheads = repo.changelog.headrevs() |
|
1773 | newheads = repo.changelog.headrevs() | |
1774 | newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads) |
|
1774 | newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads) | |
1775 | # notes: we compare lists here. |
|
1775 | # notes: we compare lists here. | |
1776 | # As we do it only once buiding set would not be cheaper |
|
1776 | # As we do it only once buiding set would not be cheaper | |
1777 | changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes) |
|
1777 | changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes) | |
1778 | if changes: |
|
1778 | if changes: | |
1779 | tr2.hookargs['tag_moved'] = '1' |
|
1779 | tr2.hookargs['tag_moved'] = '1' | |
1780 | with repo.vfs('changes/tags.changes', 'w', |
|
1780 | with repo.vfs('changes/tags.changes', 'w', | |
1781 | atomictemp=True) as changesfile: |
|
1781 | atomictemp=True) as changesfile: | |
1782 | # note: we do not register the file to the transaction |
|
1782 | # note: we do not register the file to the transaction | |
1783 | # because we needs it to still exist on the transaction |
|
1783 | # because we needs it to still exist on the transaction | |
1784 | # is close (for txnclose hooks) |
|
1784 | # is close (for txnclose hooks) | |
1785 | tagsmod.writediff(changesfile, changes) |
|
1785 | tagsmod.writediff(changesfile, changes) | |
1786 | def validate(tr2): |
|
1786 | def validate(tr2): | |
1787 | """will run pre-closing hooks""" |
|
1787 | """will run pre-closing hooks""" | |
1788 | # XXX the transaction API is a bit lacking here so we take a hacky |
|
1788 | # XXX the transaction API is a bit lacking here so we take a hacky | |
1789 | # path for now |
|
1789 | # path for now | |
1790 | # |
|
1790 | # | |
1791 | # We cannot add this as a "pending" hooks since the 'tr.hookargs' |
|
1791 | # We cannot add this as a "pending" hooks since the 'tr.hookargs' | |
1792 | # dict is copied before these run. In addition we needs the data |
|
1792 | # dict is copied before these run. In addition we needs the data | |
1793 | # available to in memory hooks too. |
|
1793 | # available to in memory hooks too. | |
1794 | # |
|
1794 | # | |
1795 | # Moreover, we also need to make sure this runs before txnclose |
|
1795 | # Moreover, we also need to make sure this runs before txnclose | |
1796 | # hooks and there is no "pending" mechanism that would execute |
|
1796 | # hooks and there is no "pending" mechanism that would execute | |
1797 | # logic only if hooks are about to run. |
|
1797 | # logic only if hooks are about to run. | |
1798 | # |
|
1798 | # | |
1799 | # Fixing this limitation of the transaction is also needed to track |
|
1799 | # Fixing this limitation of the transaction is also needed to track | |
1800 | # other families of changes (bookmarks, phases, obsolescence). |
|
1800 | # other families of changes (bookmarks, phases, obsolescence). | |
1801 | # |
|
1801 | # | |
1802 | # This will have to be fixed before we remove the experimental |
|
1802 | # This will have to be fixed before we remove the experimental | |
1803 | # gating. |
|
1803 | # gating. | |
1804 | tracktags(tr2) |
|
1804 | tracktags(tr2) | |
1805 | repo = reporef() |
|
1805 | repo = reporef() | |
1806 | if repo.ui.configbool('experimental', 'single-head-per-branch'): |
|
1806 | if repo.ui.configbool('experimental', 'single-head-per-branch'): | |
1807 | scmutil.enforcesinglehead(repo, tr2, desc) |
|
1807 | scmutil.enforcesinglehead(repo, tr2, desc) | |
1808 | if hook.hashook(repo.ui, 'pretxnclose-bookmark'): |
|
1808 | if hook.hashook(repo.ui, 'pretxnclose-bookmark'): | |
1809 | for name, (old, new) in sorted(tr.changes['bookmarks'].items()): |
|
1809 | for name, (old, new) in sorted(tr.changes['bookmarks'].items()): | |
1810 | args = tr.hookargs.copy() |
|
1810 | args = tr.hookargs.copy() | |
1811 | args.update(bookmarks.preparehookargs(name, old, new)) |
|
1811 | args.update(bookmarks.preparehookargs(name, old, new)) | |
1812 | repo.hook('pretxnclose-bookmark', throw=True, |
|
1812 | repo.hook('pretxnclose-bookmark', throw=True, | |
1813 | txnname=desc, |
|
1813 | txnname=desc, | |
1814 | **pycompat.strkwargs(args)) |
|
1814 | **pycompat.strkwargs(args)) | |
1815 | if hook.hashook(repo.ui, 'pretxnclose-phase'): |
|
1815 | if hook.hashook(repo.ui, 'pretxnclose-phase'): | |
1816 | cl = repo.unfiltered().changelog |
|
1816 | cl = repo.unfiltered().changelog | |
1817 | for rev, (old, new) in tr.changes['phases'].items(): |
|
1817 | for rev, (old, new) in tr.changes['phases'].items(): | |
1818 | args = tr.hookargs.copy() |
|
1818 | args = tr.hookargs.copy() | |
1819 | node = hex(cl.node(rev)) |
|
1819 | node = hex(cl.node(rev)) | |
1820 | args.update(phases.preparehookargs(node, old, new)) |
|
1820 | args.update(phases.preparehookargs(node, old, new)) | |
1821 | repo.hook('pretxnclose-phase', throw=True, txnname=desc, |
|
1821 | repo.hook('pretxnclose-phase', throw=True, txnname=desc, | |
1822 | **pycompat.strkwargs(args)) |
|
1822 | **pycompat.strkwargs(args)) | |
1823 |
|
1823 | |||
1824 | repo.hook('pretxnclose', throw=True, |
|
1824 | repo.hook('pretxnclose', throw=True, | |
1825 | txnname=desc, **pycompat.strkwargs(tr.hookargs)) |
|
1825 | txnname=desc, **pycompat.strkwargs(tr.hookargs)) | |
1826 | def releasefn(tr, success): |
|
1826 | def releasefn(tr, success): | |
1827 | repo = reporef() |
|
1827 | repo = reporef() | |
1828 | if success: |
|
1828 | if success: | |
1829 | # this should be explicitly invoked here, because |
|
1829 | # this should be explicitly invoked here, because | |
1830 | # in-memory changes aren't written out at closing |
|
1830 | # in-memory changes aren't written out at closing | |
1831 | # transaction, if tr.addfilegenerator (via |
|
1831 | # transaction, if tr.addfilegenerator (via | |
1832 | # dirstate.write or so) isn't invoked while |
|
1832 | # dirstate.write or so) isn't invoked while | |
1833 | # transaction running |
|
1833 | # transaction running | |
1834 | repo.dirstate.write(None) |
|
1834 | repo.dirstate.write(None) | |
1835 | else: |
|
1835 | else: | |
1836 | # discard all changes (including ones already written |
|
1836 | # discard all changes (including ones already written | |
1837 | # out) in this transaction |
|
1837 | # out) in this transaction | |
1838 | narrowspec.restorebackup(self, 'journal.narrowspec') |
|
1838 | narrowspec.restorebackup(self, 'journal.narrowspec') | |
1839 | narrowspec.restorewcbackup(self, 'journal.narrowspec.dirstate') |
|
1839 | narrowspec.restorewcbackup(self, 'journal.narrowspec.dirstate') | |
1840 | repo.dirstate.restorebackup(None, 'journal.dirstate') |
|
1840 | repo.dirstate.restorebackup(None, 'journal.dirstate') | |
1841 |
|
1841 | |||
1842 | repo.invalidate(clearfilecache=True) |
|
1842 | repo.invalidate(clearfilecache=True) | |
1843 |
|
1843 | |||
1844 | tr = transaction.transaction(rp, self.svfs, vfsmap, |
|
1844 | tr = transaction.transaction(rp, self.svfs, vfsmap, | |
1845 | "journal", |
|
1845 | "journal", | |
1846 | "undo", |
|
1846 | "undo", | |
1847 | aftertrans(renames), |
|
1847 | aftertrans(renames), | |
1848 | self.store.createmode, |
|
1848 | self.store.createmode, | |
1849 | validator=validate, |
|
1849 | validator=validate, | |
1850 | releasefn=releasefn, |
|
1850 | releasefn=releasefn, | |
1851 | checkambigfiles=_cachedfiles, |
|
1851 | checkambigfiles=_cachedfiles, | |
1852 | name=desc) |
|
1852 | name=desc) | |
1853 | tr.changes['origrepolen'] = len(self) |
|
1853 | tr.changes['origrepolen'] = len(self) | |
1854 | tr.changes['obsmarkers'] = set() |
|
1854 | tr.changes['obsmarkers'] = set() | |
1855 | tr.changes['phases'] = {} |
|
1855 | tr.changes['phases'] = {} | |
1856 | tr.changes['bookmarks'] = {} |
|
1856 | tr.changes['bookmarks'] = {} | |
1857 |
|
1857 | |||
1858 | tr.hookargs['txnid'] = txnid |
|
1858 | tr.hookargs['txnid'] = txnid | |
1859 | # note: writing the fncache only during finalize mean that the file is |
|
1859 | # note: writing the fncache only during finalize mean that the file is | |
1860 | # outdated when running hooks. As fncache is used for streaming clone, |
|
1860 | # outdated when running hooks. As fncache is used for streaming clone, | |
1861 | # this is not expected to break anything that happen during the hooks. |
|
1861 | # this is not expected to break anything that happen during the hooks. | |
1862 | tr.addfinalize('flush-fncache', self.store.write) |
|
1862 | tr.addfinalize('flush-fncache', self.store.write) | |
1863 | def txnclosehook(tr2): |
|
1863 | def txnclosehook(tr2): | |
1864 | """To be run if transaction is successful, will schedule a hook run |
|
1864 | """To be run if transaction is successful, will schedule a hook run | |
1865 | """ |
|
1865 | """ | |
1866 | # Don't reference tr2 in hook() so we don't hold a reference. |
|
1866 | # Don't reference tr2 in hook() so we don't hold a reference. | |
1867 | # This reduces memory consumption when there are multiple |
|
1867 | # This reduces memory consumption when there are multiple | |
1868 | # transactions per lock. This can likely go away if issue5045 |
|
1868 | # transactions per lock. This can likely go away if issue5045 | |
1869 | # fixes the function accumulation. |
|
1869 | # fixes the function accumulation. | |
1870 | hookargs = tr2.hookargs |
|
1870 | hookargs = tr2.hookargs | |
1871 |
|
1871 | |||
1872 | def hookfunc(): |
|
1872 | def hookfunc(): | |
1873 | repo = reporef() |
|
1873 | repo = reporef() | |
1874 | if hook.hashook(repo.ui, 'txnclose-bookmark'): |
|
1874 | if hook.hashook(repo.ui, 'txnclose-bookmark'): | |
1875 | bmchanges = sorted(tr.changes['bookmarks'].items()) |
|
1875 | bmchanges = sorted(tr.changes['bookmarks'].items()) | |
1876 | for name, (old, new) in bmchanges: |
|
1876 | for name, (old, new) in bmchanges: | |
1877 | args = tr.hookargs.copy() |
|
1877 | args = tr.hookargs.copy() | |
1878 | args.update(bookmarks.preparehookargs(name, old, new)) |
|
1878 | args.update(bookmarks.preparehookargs(name, old, new)) | |
1879 | repo.hook('txnclose-bookmark', throw=False, |
|
1879 | repo.hook('txnclose-bookmark', throw=False, | |
1880 | txnname=desc, **pycompat.strkwargs(args)) |
|
1880 | txnname=desc, **pycompat.strkwargs(args)) | |
1881 |
|
1881 | |||
1882 | if hook.hashook(repo.ui, 'txnclose-phase'): |
|
1882 | if hook.hashook(repo.ui, 'txnclose-phase'): | |
1883 | cl = repo.unfiltered().changelog |
|
1883 | cl = repo.unfiltered().changelog | |
1884 | phasemv = sorted(tr.changes['phases'].items()) |
|
1884 | phasemv = sorted(tr.changes['phases'].items()) | |
1885 | for rev, (old, new) in phasemv: |
|
1885 | for rev, (old, new) in phasemv: | |
1886 | args = tr.hookargs.copy() |
|
1886 | args = tr.hookargs.copy() | |
1887 | node = hex(cl.node(rev)) |
|
1887 | node = hex(cl.node(rev)) | |
1888 | args.update(phases.preparehookargs(node, old, new)) |
|
1888 | args.update(phases.preparehookargs(node, old, new)) | |
1889 | repo.hook('txnclose-phase', throw=False, txnname=desc, |
|
1889 | repo.hook('txnclose-phase', throw=False, txnname=desc, | |
1890 | **pycompat.strkwargs(args)) |
|
1890 | **pycompat.strkwargs(args)) | |
1891 |
|
1891 | |||
1892 | repo.hook('txnclose', throw=False, txnname=desc, |
|
1892 | repo.hook('txnclose', throw=False, txnname=desc, | |
1893 | **pycompat.strkwargs(hookargs)) |
|
1893 | **pycompat.strkwargs(hookargs)) | |
1894 | reporef()._afterlock(hookfunc) |
|
1894 | reporef()._afterlock(hookfunc) | |
1895 | tr.addfinalize('txnclose-hook', txnclosehook) |
|
1895 | tr.addfinalize('txnclose-hook', txnclosehook) | |
1896 | # Include a leading "-" to make it happen before the transaction summary |
|
1896 | # Include a leading "-" to make it happen before the transaction summary | |
1897 | # reports registered via scmutil.registersummarycallback() whose names |
|
1897 | # reports registered via scmutil.registersummarycallback() whose names | |
1898 | # are 00-txnreport etc. That way, the caches will be warm when the |
|
1898 | # are 00-txnreport etc. That way, the caches will be warm when the | |
1899 | # callbacks run. |
|
1899 | # callbacks run. | |
1900 | tr.addpostclose('-warm-cache', self._buildcacheupdater(tr)) |
|
1900 | tr.addpostclose('-warm-cache', self._buildcacheupdater(tr)) | |
1901 | def txnaborthook(tr2): |
|
1901 | def txnaborthook(tr2): | |
1902 | """To be run if transaction is aborted |
|
1902 | """To be run if transaction is aborted | |
1903 | """ |
|
1903 | """ | |
1904 | reporef().hook('txnabort', throw=False, txnname=desc, |
|
1904 | reporef().hook('txnabort', throw=False, txnname=desc, | |
1905 | **pycompat.strkwargs(tr2.hookargs)) |
|
1905 | **pycompat.strkwargs(tr2.hookargs)) | |
1906 | tr.addabort('txnabort-hook', txnaborthook) |
|
1906 | tr.addabort('txnabort-hook', txnaborthook) | |
1907 | # avoid eager cache invalidation. in-memory data should be identical |
|
1907 | # avoid eager cache invalidation. in-memory data should be identical | |
1908 | # to stored data if transaction has no error. |
|
1908 | # to stored data if transaction has no error. | |
1909 | tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats) |
|
1909 | tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats) | |
1910 | self._transref = weakref.ref(tr) |
|
1910 | self._transref = weakref.ref(tr) | |
1911 | scmutil.registersummarycallback(self, tr, desc) |
|
1911 | scmutil.registersummarycallback(self, tr, desc) | |
1912 | return tr |
|
1912 | return tr | |
1913 |
|
1913 | |||
1914 | def _journalfiles(self): |
|
1914 | def _journalfiles(self): | |
1915 | return ((self.svfs, 'journal'), |
|
1915 | return ((self.svfs, 'journal'), | |
1916 | (self.svfs, 'journal.narrowspec'), |
|
1916 | (self.svfs, 'journal.narrowspec'), | |
1917 | (self.vfs, 'journal.narrowspec.dirstate'), |
|
1917 | (self.vfs, 'journal.narrowspec.dirstate'), | |
1918 | (self.vfs, 'journal.dirstate'), |
|
1918 | (self.vfs, 'journal.dirstate'), | |
1919 | (self.vfs, 'journal.branch'), |
|
1919 | (self.vfs, 'journal.branch'), | |
1920 | (self.vfs, 'journal.desc'), |
|
1920 | (self.vfs, 'journal.desc'), | |
1921 | (self.vfs, 'journal.bookmarks'), |
|
1921 | (self.vfs, 'journal.bookmarks'), | |
1922 | (self.svfs, 'journal.phaseroots')) |
|
1922 | (self.svfs, 'journal.phaseroots')) | |
1923 |
|
1923 | |||
1924 | def undofiles(self): |
|
1924 | def undofiles(self): | |
1925 | return [(vfs, undoname(x)) for vfs, x in self._journalfiles()] |
|
1925 | return [(vfs, undoname(x)) for vfs, x in self._journalfiles()] | |
1926 |
|
1926 | |||
1927 | @unfilteredmethod |
|
1927 | @unfilteredmethod | |
1928 | def _writejournal(self, desc): |
|
1928 | def _writejournal(self, desc): | |
1929 | self.dirstate.savebackup(None, 'journal.dirstate') |
|
1929 | self.dirstate.savebackup(None, 'journal.dirstate') | |
1930 | narrowspec.savewcbackup(self, 'journal.narrowspec.dirstate') |
|
1930 | narrowspec.savewcbackup(self, 'journal.narrowspec.dirstate') | |
1931 | narrowspec.savebackup(self, 'journal.narrowspec') |
|
1931 | narrowspec.savebackup(self, 'journal.narrowspec') | |
1932 | self.vfs.write("journal.branch", |
|
1932 | self.vfs.write("journal.branch", | |
1933 | encoding.fromlocal(self.dirstate.branch())) |
|
1933 | encoding.fromlocal(self.dirstate.branch())) | |
1934 | self.vfs.write("journal.desc", |
|
1934 | self.vfs.write("journal.desc", | |
1935 | "%d\n%s\n" % (len(self), desc)) |
|
1935 | "%d\n%s\n" % (len(self), desc)) | |
1936 | self.vfs.write("journal.bookmarks", |
|
1936 | self.vfs.write("journal.bookmarks", | |
1937 | self.vfs.tryread("bookmarks")) |
|
1937 | self.vfs.tryread("bookmarks")) | |
1938 | self.svfs.write("journal.phaseroots", |
|
1938 | self.svfs.write("journal.phaseroots", | |
1939 | self.svfs.tryread("phaseroots")) |
|
1939 | self.svfs.tryread("phaseroots")) | |
1940 |
|
1940 | |||
1941 | def recover(self): |
|
1941 | def recover(self): | |
1942 | with self.lock(): |
|
1942 | with self.lock(): | |
1943 | if self.svfs.exists("journal"): |
|
1943 | if self.svfs.exists("journal"): | |
1944 | self.ui.status(_("rolling back interrupted transaction\n")) |
|
1944 | self.ui.status(_("rolling back interrupted transaction\n")) | |
1945 | vfsmap = {'': self.svfs, |
|
1945 | vfsmap = {'': self.svfs, | |
1946 | 'plain': self.vfs,} |
|
1946 | 'plain': self.vfs,} | |
1947 | transaction.rollback(self.svfs, vfsmap, "journal", |
|
1947 | transaction.rollback(self.svfs, vfsmap, "journal", | |
1948 | self.ui.warn, |
|
1948 | self.ui.warn, | |
1949 | checkambigfiles=_cachedfiles) |
|
1949 | checkambigfiles=_cachedfiles) | |
1950 | self.invalidate() |
|
1950 | self.invalidate() | |
1951 | return True |
|
1951 | return True | |
1952 | else: |
|
1952 | else: | |
1953 | self.ui.warn(_("no interrupted transaction available\n")) |
|
1953 | self.ui.warn(_("no interrupted transaction available\n")) | |
1954 | return False |
|
1954 | return False | |
1955 |
|
1955 | |||
1956 | def rollback(self, dryrun=False, force=False): |
|
1956 | def rollback(self, dryrun=False, force=False): | |
1957 | wlock = lock = dsguard = None |
|
1957 | wlock = lock = dsguard = None | |
1958 | try: |
|
1958 | try: | |
1959 | wlock = self.wlock() |
|
1959 | wlock = self.wlock() | |
1960 | lock = self.lock() |
|
1960 | lock = self.lock() | |
1961 | if self.svfs.exists("undo"): |
|
1961 | if self.svfs.exists("undo"): | |
1962 | dsguard = dirstateguard.dirstateguard(self, 'rollback') |
|
1962 | dsguard = dirstateguard.dirstateguard(self, 'rollback') | |
1963 |
|
1963 | |||
1964 | return self._rollback(dryrun, force, dsguard) |
|
1964 | return self._rollback(dryrun, force, dsguard) | |
1965 | else: |
|
1965 | else: | |
1966 | self.ui.warn(_("no rollback information available\n")) |
|
1966 | self.ui.warn(_("no rollback information available\n")) | |
1967 | return 1 |
|
1967 | return 1 | |
1968 | finally: |
|
1968 | finally: | |
1969 | release(dsguard, lock, wlock) |
|
1969 | release(dsguard, lock, wlock) | |
1970 |
|
1970 | |||
1971 | @unfilteredmethod # Until we get smarter cache management |
|
1971 | @unfilteredmethod # Until we get smarter cache management | |
1972 | def _rollback(self, dryrun, force, dsguard): |
|
1972 | def _rollback(self, dryrun, force, dsguard): | |
1973 | ui = self.ui |
|
1973 | ui = self.ui | |
1974 | try: |
|
1974 | try: | |
1975 | args = self.vfs.read('undo.desc').splitlines() |
|
1975 | args = self.vfs.read('undo.desc').splitlines() | |
1976 | (oldlen, desc, detail) = (int(args[0]), args[1], None) |
|
1976 | (oldlen, desc, detail) = (int(args[0]), args[1], None) | |
1977 | if len(args) >= 3: |
|
1977 | if len(args) >= 3: | |
1978 | detail = args[2] |
|
1978 | detail = args[2] | |
1979 | oldtip = oldlen - 1 |
|
1979 | oldtip = oldlen - 1 | |
1980 |
|
1980 | |||
1981 | if detail and ui.verbose: |
|
1981 | if detail and ui.verbose: | |
1982 | msg = (_('repository tip rolled back to revision %d' |
|
1982 | msg = (_('repository tip rolled back to revision %d' | |
1983 | ' (undo %s: %s)\n') |
|
1983 | ' (undo %s: %s)\n') | |
1984 | % (oldtip, desc, detail)) |
|
1984 | % (oldtip, desc, detail)) | |
1985 | else: |
|
1985 | else: | |
1986 | msg = (_('repository tip rolled back to revision %d' |
|
1986 | msg = (_('repository tip rolled back to revision %d' | |
1987 | ' (undo %s)\n') |
|
1987 | ' (undo %s)\n') | |
1988 | % (oldtip, desc)) |
|
1988 | % (oldtip, desc)) | |
1989 | except IOError: |
|
1989 | except IOError: | |
1990 | msg = _('rolling back unknown transaction\n') |
|
1990 | msg = _('rolling back unknown transaction\n') | |
1991 | desc = None |
|
1991 | desc = None | |
1992 |
|
1992 | |||
1993 | if not force and self['.'] != self['tip'] and desc == 'commit': |
|
1993 | if not force and self['.'] != self['tip'] and desc == 'commit': | |
1994 | raise error.Abort( |
|
1994 | raise error.Abort( | |
1995 | _('rollback of last commit while not checked out ' |
|
1995 | _('rollback of last commit while not checked out ' | |
1996 | 'may lose data'), hint=_('use -f to force')) |
|
1996 | 'may lose data'), hint=_('use -f to force')) | |
1997 |
|
1997 | |||
1998 | ui.status(msg) |
|
1998 | ui.status(msg) | |
1999 | if dryrun: |
|
1999 | if dryrun: | |
2000 | return 0 |
|
2000 | return 0 | |
2001 |
|
2001 | |||
2002 | parents = self.dirstate.parents() |
|
2002 | parents = self.dirstate.parents() | |
2003 | self.destroying() |
|
2003 | self.destroying() | |
2004 | vfsmap = {'plain': self.vfs, '': self.svfs} |
|
2004 | vfsmap = {'plain': self.vfs, '': self.svfs} | |
2005 | transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn, |
|
2005 | transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn, | |
2006 | checkambigfiles=_cachedfiles) |
|
2006 | checkambigfiles=_cachedfiles) | |
2007 | if self.vfs.exists('undo.bookmarks'): |
|
2007 | if self.vfs.exists('undo.bookmarks'): | |
2008 | self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True) |
|
2008 | self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True) | |
2009 | if self.svfs.exists('undo.phaseroots'): |
|
2009 | if self.svfs.exists('undo.phaseroots'): | |
2010 | self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True) |
|
2010 | self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True) | |
2011 | self.invalidate() |
|
2011 | self.invalidate() | |
2012 |
|
2012 | |||
2013 | parentgone = (parents[0] not in self.changelog.nodemap or |
|
2013 | parentgone = (parents[0] not in self.changelog.nodemap or | |
2014 | parents[1] not in self.changelog.nodemap) |
|
2014 | parents[1] not in self.changelog.nodemap) | |
2015 | if parentgone: |
|
2015 | if parentgone: | |
2016 | # prevent dirstateguard from overwriting already restored one |
|
2016 | # prevent dirstateguard from overwriting already restored one | |
2017 | dsguard.close() |
|
2017 | dsguard.close() | |
2018 |
|
2018 | |||
2019 | narrowspec.restorebackup(self, 'undo.narrowspec') |
|
2019 | narrowspec.restorebackup(self, 'undo.narrowspec') | |
2020 | narrowspec.restorewcbackup(self, 'undo.narrowspec.dirstate') |
|
2020 | narrowspec.restorewcbackup(self, 'undo.narrowspec.dirstate') | |
2021 | self.dirstate.restorebackup(None, 'undo.dirstate') |
|
2021 | self.dirstate.restorebackup(None, 'undo.dirstate') | |
2022 | try: |
|
2022 | try: | |
2023 | branch = self.vfs.read('undo.branch') |
|
2023 | branch = self.vfs.read('undo.branch') | |
2024 | self.dirstate.setbranch(encoding.tolocal(branch)) |
|
2024 | self.dirstate.setbranch(encoding.tolocal(branch)) | |
2025 | except IOError: |
|
2025 | except IOError: | |
2026 | ui.warn(_('named branch could not be reset: ' |
|
2026 | ui.warn(_('named branch could not be reset: ' | |
2027 | 'current branch is still \'%s\'\n') |
|
2027 | 'current branch is still \'%s\'\n') | |
2028 | % self.dirstate.branch()) |
|
2028 | % self.dirstate.branch()) | |
2029 |
|
2029 | |||
2030 | parents = tuple([p.rev() for p in self[None].parents()]) |
|
2030 | parents = tuple([p.rev() for p in self[None].parents()]) | |
2031 | if len(parents) > 1: |
|
2031 | if len(parents) > 1: | |
2032 | ui.status(_('working directory now based on ' |
|
2032 | ui.status(_('working directory now based on ' | |
2033 | 'revisions %d and %d\n') % parents) |
|
2033 | 'revisions %d and %d\n') % parents) | |
2034 | else: |
|
2034 | else: | |
2035 | ui.status(_('working directory now based on ' |
|
2035 | ui.status(_('working directory now based on ' | |
2036 | 'revision %d\n') % parents) |
|
2036 | 'revision %d\n') % parents) | |
2037 | mergemod.mergestate.clean(self, self['.'].node()) |
|
2037 | mergemod.mergestate.clean(self, self['.'].node()) | |
2038 |
|
2038 | |||
2039 | # TODO: if we know which new heads may result from this rollback, pass |
|
2039 | # TODO: if we know which new heads may result from this rollback, pass | |
2040 | # them to destroy(), which will prevent the branchhead cache from being |
|
2040 | # them to destroy(), which will prevent the branchhead cache from being | |
2041 | # invalidated. |
|
2041 | # invalidated. | |
2042 | self.destroyed() |
|
2042 | self.destroyed() | |
2043 | return 0 |
|
2043 | return 0 | |
2044 |
|
2044 | |||
2045 | def _buildcacheupdater(self, newtransaction): |
|
2045 | def _buildcacheupdater(self, newtransaction): | |
2046 | """called during transaction to build the callback updating cache |
|
2046 | """called during transaction to build the callback updating cache | |
2047 |
|
2047 | |||
2048 | Lives on the repository to help extension who might want to augment |
|
2048 | Lives on the repository to help extension who might want to augment | |
2049 | this logic. For this purpose, the created transaction is passed to the |
|
2049 | this logic. For this purpose, the created transaction is passed to the | |
2050 | method. |
|
2050 | method. | |
2051 | """ |
|
2051 | """ | |
2052 | # we must avoid cyclic reference between repo and transaction. |
|
2052 | # we must avoid cyclic reference between repo and transaction. | |
2053 | reporef = weakref.ref(self) |
|
2053 | reporef = weakref.ref(self) | |
2054 | def updater(tr): |
|
2054 | def updater(tr): | |
2055 | repo = reporef() |
|
2055 | repo = reporef() | |
2056 | repo.updatecaches(tr) |
|
2056 | repo.updatecaches(tr) | |
2057 | return updater |
|
2057 | return updater | |
2058 |
|
2058 | |||
2059 | @unfilteredmethod |
|
2059 | @unfilteredmethod | |
2060 | def updatecaches(self, tr=None, full=False): |
|
2060 | def updatecaches(self, tr=None, full=False): | |
2061 | """warm appropriate caches |
|
2061 | """warm appropriate caches | |
2062 |
|
2062 | |||
2063 | If this function is called after a transaction closed. The transaction |
|
2063 | If this function is called after a transaction closed. The transaction | |
2064 | will be available in the 'tr' argument. This can be used to selectively |
|
2064 | will be available in the 'tr' argument. This can be used to selectively | |
2065 | update caches relevant to the changes in that transaction. |
|
2065 | update caches relevant to the changes in that transaction. | |
2066 |
|
2066 | |||
2067 | If 'full' is set, make sure all caches the function knows about have |
|
2067 | If 'full' is set, make sure all caches the function knows about have | |
2068 | up-to-date data. Even the ones usually loaded more lazily. |
|
2068 | up-to-date data. Even the ones usually loaded more lazily. | |
2069 | """ |
|
2069 | """ | |
2070 | if tr is not None and tr.hookargs.get('source') == 'strip': |
|
2070 | if tr is not None and tr.hookargs.get('source') == 'strip': | |
2071 | # During strip, many caches are invalid but |
|
2071 | # During strip, many caches are invalid but | |
2072 | # later call to `destroyed` will refresh them. |
|
2072 | # later call to `destroyed` will refresh them. | |
2073 | return |
|
2073 | return | |
2074 |
|
2074 | |||
2075 | if tr is None or tr.changes['origrepolen'] < len(self): |
|
2075 | if tr is None or tr.changes['origrepolen'] < len(self): | |
2076 | # updating the unfiltered branchmap should refresh all the others, |
|
2076 | # updating the unfiltered branchmap should refresh all the others, | |
2077 | self.ui.debug('updating the branch cache\n') |
|
2077 | self.ui.debug('updating the branch cache\n') | |
2078 | branchmap.updatecache(self.filtered('served')) |
|
2078 | branchmap.updatecache(self.filtered('served')) | |
2079 |
|
2079 | |||
2080 | if full: |
|
2080 | if full: | |
2081 | rbc = self.revbranchcache() |
|
2081 | rbc = self.revbranchcache() | |
2082 | for r in self.changelog: |
|
2082 | for r in self.changelog: | |
2083 | rbc.branchinfo(r) |
|
2083 | rbc.branchinfo(r) | |
2084 | rbc.write() |
|
2084 | rbc.write() | |
2085 |
|
2085 | |||
2086 | # ensure the working copy parents are in the manifestfulltextcache |
|
2086 | # ensure the working copy parents are in the manifestfulltextcache | |
2087 | for ctx in self['.'].parents(): |
|
2087 | for ctx in self['.'].parents(): | |
2088 | ctx.manifest() # accessing the manifest is enough |
|
2088 | ctx.manifest() # accessing the manifest is enough | |
2089 |
|
2089 | |||
2090 | def invalidatecaches(self): |
|
2090 | def invalidatecaches(self): | |
2091 |
|
2091 | |||
2092 | if r'_tagscache' in vars(self): |
|
2092 | if r'_tagscache' in vars(self): | |
2093 | # can't use delattr on proxy |
|
2093 | # can't use delattr on proxy | |
2094 | del self.__dict__[r'_tagscache'] |
|
2094 | del self.__dict__[r'_tagscache'] | |
2095 |
|
2095 | |||
2096 | self.unfiltered()._branchcaches.clear() |
|
2096 | self.unfiltered()._branchcaches.clear() | |
2097 | self.invalidatevolatilesets() |
|
2097 | self.invalidatevolatilesets() | |
2098 | self._sparsesignaturecache.clear() |
|
2098 | self._sparsesignaturecache.clear() | |
2099 |
|
2099 | |||
2100 | def invalidatevolatilesets(self): |
|
2100 | def invalidatevolatilesets(self): | |
2101 | self.filteredrevcache.clear() |
|
2101 | self.filteredrevcache.clear() | |
2102 | obsolete.clearobscaches(self) |
|
2102 | obsolete.clearobscaches(self) | |
2103 |
|
2103 | |||
2104 | def invalidatedirstate(self): |
|
2104 | def invalidatedirstate(self): | |
2105 | '''Invalidates the dirstate, causing the next call to dirstate |
|
2105 | '''Invalidates the dirstate, causing the next call to dirstate | |
2106 | to check if it was modified since the last time it was read, |
|
2106 | to check if it was modified since the last time it was read, | |
2107 | rereading it if it has. |
|
2107 | rereading it if it has. | |
2108 |
|
2108 | |||
2109 | This is different to dirstate.invalidate() that it doesn't always |
|
2109 | This is different to dirstate.invalidate() that it doesn't always | |
2110 | rereads the dirstate. Use dirstate.invalidate() if you want to |
|
2110 | rereads the dirstate. Use dirstate.invalidate() if you want to | |
2111 | explicitly read the dirstate again (i.e. restoring it to a previous |
|
2111 | explicitly read the dirstate again (i.e. restoring it to a previous | |
2112 | known good state).''' |
|
2112 | known good state).''' | |
2113 | if hasunfilteredcache(self, r'dirstate'): |
|
2113 | if hasunfilteredcache(self, r'dirstate'): | |
2114 | for k in self.dirstate._filecache: |
|
2114 | for k in self.dirstate._filecache: | |
2115 | try: |
|
2115 | try: | |
2116 | delattr(self.dirstate, k) |
|
2116 | delattr(self.dirstate, k) | |
2117 | except AttributeError: |
|
2117 | except AttributeError: | |
2118 | pass |
|
2118 | pass | |
2119 | delattr(self.unfiltered(), r'dirstate') |
|
2119 | delattr(self.unfiltered(), r'dirstate') | |
2120 |
|
2120 | |||
2121 | def invalidate(self, clearfilecache=False): |
|
2121 | def invalidate(self, clearfilecache=False): | |
2122 | '''Invalidates both store and non-store parts other than dirstate |
|
2122 | '''Invalidates both store and non-store parts other than dirstate | |
2123 |
|
2123 | |||
2124 | If a transaction is running, invalidation of store is omitted, |
|
2124 | If a transaction is running, invalidation of store is omitted, | |
2125 | because discarding in-memory changes might cause inconsistency |
|
2125 | because discarding in-memory changes might cause inconsistency | |
2126 | (e.g. incomplete fncache causes unintentional failure, but |
|
2126 | (e.g. incomplete fncache causes unintentional failure, but | |
2127 | redundant one doesn't). |
|
2127 | redundant one doesn't). | |
2128 | ''' |
|
2128 | ''' | |
2129 | unfiltered = self.unfiltered() # all file caches are stored unfiltered |
|
2129 | unfiltered = self.unfiltered() # all file caches are stored unfiltered | |
2130 | for k in list(self._filecache.keys()): |
|
2130 | for k in list(self._filecache.keys()): | |
2131 | # dirstate is invalidated separately in invalidatedirstate() |
|
2131 | # dirstate is invalidated separately in invalidatedirstate() | |
2132 | if k == 'dirstate': |
|
2132 | if k == 'dirstate': | |
2133 | continue |
|
2133 | continue | |
2134 | if (k == 'changelog' and |
|
2134 | if (k == 'changelog' and | |
2135 | self.currenttransaction() and |
|
2135 | self.currenttransaction() and | |
2136 | self.changelog._delayed): |
|
2136 | self.changelog._delayed): | |
2137 | # The changelog object may store unwritten revisions. We don't |
|
2137 | # The changelog object may store unwritten revisions. We don't | |
2138 | # want to lose them. |
|
2138 | # want to lose them. | |
2139 | # TODO: Solve the problem instead of working around it. |
|
2139 | # TODO: Solve the problem instead of working around it. | |
2140 | continue |
|
2140 | continue | |
2141 |
|
2141 | |||
2142 | if clearfilecache: |
|
2142 | if clearfilecache: | |
2143 | del self._filecache[k] |
|
2143 | del self._filecache[k] | |
2144 | try: |
|
2144 | try: | |
2145 | delattr(unfiltered, k) |
|
2145 | delattr(unfiltered, k) | |
2146 | except AttributeError: |
|
2146 | except AttributeError: | |
2147 | pass |
|
2147 | pass | |
2148 | self.invalidatecaches() |
|
2148 | self.invalidatecaches() | |
2149 | if not self.currenttransaction(): |
|
2149 | if not self.currenttransaction(): | |
2150 | # TODO: Changing contents of store outside transaction |
|
2150 | # TODO: Changing contents of store outside transaction | |
2151 | # causes inconsistency. We should make in-memory store |
|
2151 | # causes inconsistency. We should make in-memory store | |
2152 | # changes detectable, and abort if changed. |
|
2152 | # changes detectable, and abort if changed. | |
2153 | self.store.invalidatecaches() |
|
2153 | self.store.invalidatecaches() | |
2154 |
|
2154 | |||
2155 | def invalidateall(self): |
|
2155 | def invalidateall(self): | |
2156 | '''Fully invalidates both store and non-store parts, causing the |
|
2156 | '''Fully invalidates both store and non-store parts, causing the | |
2157 | subsequent operation to reread any outside changes.''' |
|
2157 | subsequent operation to reread any outside changes.''' | |
2158 | # extension should hook this to invalidate its caches |
|
2158 | # extension should hook this to invalidate its caches | |
2159 | self.invalidate() |
|
2159 | self.invalidate() | |
2160 | self.invalidatedirstate() |
|
2160 | self.invalidatedirstate() | |
2161 |
|
2161 | |||
2162 | @unfilteredmethod |
|
2162 | @unfilteredmethod | |
2163 | def _refreshfilecachestats(self, tr): |
|
2163 | def _refreshfilecachestats(self, tr): | |
2164 | """Reload stats of cached files so that they are flagged as valid""" |
|
2164 | """Reload stats of cached files so that they are flagged as valid""" | |
2165 | for k, ce in self._filecache.items(): |
|
2165 | for k, ce in self._filecache.items(): | |
2166 | k = pycompat.sysstr(k) |
|
2166 | k = pycompat.sysstr(k) | |
2167 | if k == r'dirstate' or k not in self.__dict__: |
|
2167 | if k == r'dirstate' or k not in self.__dict__: | |
2168 | continue |
|
2168 | continue | |
2169 | ce.refresh() |
|
2169 | ce.refresh() | |
2170 |
|
2170 | |||
2171 | def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc, |
|
2171 | def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc, | |
2172 | inheritchecker=None, parentenvvar=None): |
|
2172 | inheritchecker=None, parentenvvar=None): | |
2173 | parentlock = None |
|
2173 | parentlock = None | |
2174 | # the contents of parentenvvar are used by the underlying lock to |
|
2174 | # the contents of parentenvvar are used by the underlying lock to | |
2175 | # determine whether it can be inherited |
|
2175 | # determine whether it can be inherited | |
2176 | if parentenvvar is not None: |
|
2176 | if parentenvvar is not None: | |
2177 | parentlock = encoding.environ.get(parentenvvar) |
|
2177 | parentlock = encoding.environ.get(parentenvvar) | |
2178 |
|
2178 | |||
2179 | timeout = 0 |
|
2179 | timeout = 0 | |
2180 | warntimeout = 0 |
|
2180 | warntimeout = 0 | |
2181 | if wait: |
|
2181 | if wait: | |
2182 | timeout = self.ui.configint("ui", "timeout") |
|
2182 | timeout = self.ui.configint("ui", "timeout") | |
2183 | warntimeout = self.ui.configint("ui", "timeout.warn") |
|
2183 | warntimeout = self.ui.configint("ui", "timeout.warn") | |
2184 | # internal config: ui.signal-safe-lock |
|
2184 | # internal config: ui.signal-safe-lock | |
2185 | signalsafe = self.ui.configbool('ui', 'signal-safe-lock') |
|
2185 | signalsafe = self.ui.configbool('ui', 'signal-safe-lock') | |
2186 |
|
2186 | |||
2187 | l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout, |
|
2187 | l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout, | |
2188 | releasefn=releasefn, |
|
2188 | releasefn=releasefn, | |
2189 | acquirefn=acquirefn, desc=desc, |
|
2189 | acquirefn=acquirefn, desc=desc, | |
2190 | inheritchecker=inheritchecker, |
|
2190 | inheritchecker=inheritchecker, | |
2191 | parentlock=parentlock, |
|
2191 | parentlock=parentlock, | |
2192 | signalsafe=signalsafe) |
|
2192 | signalsafe=signalsafe) | |
2193 | return l |
|
2193 | return l | |
2194 |
|
2194 | |||
2195 | def _afterlock(self, callback): |
|
2195 | def _afterlock(self, callback): | |
2196 | """add a callback to be run when the repository is fully unlocked |
|
2196 | """add a callback to be run when the repository is fully unlocked | |
2197 |
|
2197 | |||
2198 | The callback will be executed when the outermost lock is released |
|
2198 | The callback will be executed when the outermost lock is released | |
2199 | (with wlock being higher level than 'lock').""" |
|
2199 | (with wlock being higher level than 'lock').""" | |
2200 | for ref in (self._wlockref, self._lockref): |
|
2200 | for ref in (self._wlockref, self._lockref): | |
2201 | l = ref and ref() |
|
2201 | l = ref and ref() | |
2202 | if l and l.held: |
|
2202 | if l and l.held: | |
2203 | l.postrelease.append(callback) |
|
2203 | l.postrelease.append(callback) | |
2204 | break |
|
2204 | break | |
2205 | else: # no lock have been found. |
|
2205 | else: # no lock have been found. | |
2206 | callback() |
|
2206 | callback() | |
2207 |
|
2207 | |||
2208 | def lock(self, wait=True): |
|
2208 | def lock(self, wait=True): | |
2209 | '''Lock the repository store (.hg/store) and return a weak reference |
|
2209 | '''Lock the repository store (.hg/store) and return a weak reference | |
2210 | to the lock. Use this before modifying the store (e.g. committing or |
|
2210 | to the lock. Use this before modifying the store (e.g. committing or | |
2211 | stripping). If you are opening a transaction, get a lock as well.) |
|
2211 | stripping). If you are opening a transaction, get a lock as well.) | |
2212 |
|
2212 | |||
2213 | If both 'lock' and 'wlock' must be acquired, ensure you always acquires |
|
2213 | If both 'lock' and 'wlock' must be acquired, ensure you always acquires | |
2214 | 'wlock' first to avoid a dead-lock hazard.''' |
|
2214 | 'wlock' first to avoid a dead-lock hazard.''' | |
2215 | l = self._currentlock(self._lockref) |
|
2215 | l = self._currentlock(self._lockref) | |
2216 | if l is not None: |
|
2216 | if l is not None: | |
2217 | l.lock() |
|
2217 | l.lock() | |
2218 | return l |
|
2218 | return l | |
2219 |
|
2219 | |||
2220 | l = self._lock(self.svfs, "lock", wait, None, |
|
2220 | l = self._lock(self.svfs, "lock", wait, None, | |
2221 | self.invalidate, _('repository %s') % self.origroot) |
|
2221 | self.invalidate, _('repository %s') % self.origroot) | |
2222 | self._lockref = weakref.ref(l) |
|
2222 | self._lockref = weakref.ref(l) | |
2223 | return l |
|
2223 | return l | |
2224 |
|
2224 | |||
2225 | def _wlockchecktransaction(self): |
|
2225 | def _wlockchecktransaction(self): | |
2226 | if self.currenttransaction() is not None: |
|
2226 | if self.currenttransaction() is not None: | |
2227 | raise error.LockInheritanceContractViolation( |
|
2227 | raise error.LockInheritanceContractViolation( | |
2228 | 'wlock cannot be inherited in the middle of a transaction') |
|
2228 | 'wlock cannot be inherited in the middle of a transaction') | |
2229 |
|
2229 | |||
2230 | def wlock(self, wait=True): |
|
2230 | def wlock(self, wait=True): | |
2231 | '''Lock the non-store parts of the repository (everything under |
|
2231 | '''Lock the non-store parts of the repository (everything under | |
2232 | .hg except .hg/store) and return a weak reference to the lock. |
|
2232 | .hg except .hg/store) and return a weak reference to the lock. | |
2233 |
|
2233 | |||
2234 | Use this before modifying files in .hg. |
|
2234 | Use this before modifying files in .hg. | |
2235 |
|
2235 | |||
2236 | If both 'lock' and 'wlock' must be acquired, ensure you always acquires |
|
2236 | If both 'lock' and 'wlock' must be acquired, ensure you always acquires | |
2237 | 'wlock' first to avoid a dead-lock hazard.''' |
|
2237 | 'wlock' first to avoid a dead-lock hazard.''' | |
2238 | l = self._wlockref and self._wlockref() |
|
2238 | l = self._wlockref and self._wlockref() | |
2239 | if l is not None and l.held: |
|
2239 | if l is not None and l.held: | |
2240 | l.lock() |
|
2240 | l.lock() | |
2241 | return l |
|
2241 | return l | |
2242 |
|
2242 | |||
2243 | # We do not need to check for non-waiting lock acquisition. Such |
|
2243 | # We do not need to check for non-waiting lock acquisition. Such | |
2244 | # acquisition would not cause dead-lock as they would just fail. |
|
2244 | # acquisition would not cause dead-lock as they would just fail. | |
2245 | if wait and (self.ui.configbool('devel', 'all-warnings') |
|
2245 | if wait and (self.ui.configbool('devel', 'all-warnings') | |
2246 | or self.ui.configbool('devel', 'check-locks')): |
|
2246 | or self.ui.configbool('devel', 'check-locks')): | |
2247 | if self._currentlock(self._lockref) is not None: |
|
2247 | if self._currentlock(self._lockref) is not None: | |
2248 | self.ui.develwarn('"wlock" acquired after "lock"') |
|
2248 | self.ui.develwarn('"wlock" acquired after "lock"') | |
2249 |
|
2249 | |||
2250 | def unlock(): |
|
2250 | def unlock(): | |
2251 | if self.dirstate.pendingparentchange(): |
|
2251 | if self.dirstate.pendingparentchange(): | |
2252 | self.dirstate.invalidate() |
|
2252 | self.dirstate.invalidate() | |
2253 | else: |
|
2253 | else: | |
2254 | self.dirstate.write(None) |
|
2254 | self.dirstate.write(None) | |
2255 |
|
2255 | |||
2256 | self._filecache['dirstate'].refresh() |
|
2256 | self._filecache['dirstate'].refresh() | |
2257 |
|
2257 | |||
2258 | l = self._lock(self.vfs, "wlock", wait, unlock, |
|
2258 | l = self._lock(self.vfs, "wlock", wait, unlock, | |
2259 | self.invalidatedirstate, _('working directory of %s') % |
|
2259 | self.invalidatedirstate, _('working directory of %s') % | |
2260 | self.origroot, |
|
2260 | self.origroot, | |
2261 | inheritchecker=self._wlockchecktransaction, |
|
2261 | inheritchecker=self._wlockchecktransaction, | |
2262 | parentenvvar='HG_WLOCK_LOCKER') |
|
2262 | parentenvvar='HG_WLOCK_LOCKER') | |
2263 | self._wlockref = weakref.ref(l) |
|
2263 | self._wlockref = weakref.ref(l) | |
2264 | return l |
|
2264 | return l | |
2265 |
|
2265 | |||
2266 | def _currentlock(self, lockref): |
|
2266 | def _currentlock(self, lockref): | |
2267 | """Returns the lock if it's held, or None if it's not.""" |
|
2267 | """Returns the lock if it's held, or None if it's not.""" | |
2268 | if lockref is None: |
|
2268 | if lockref is None: | |
2269 | return None |
|
2269 | return None | |
2270 | l = lockref() |
|
2270 | l = lockref() | |
2271 | if l is None or not l.held: |
|
2271 | if l is None or not l.held: | |
2272 | return None |
|
2272 | return None | |
2273 | return l |
|
2273 | return l | |
2274 |
|
2274 | |||
2275 | def currentwlock(self): |
|
2275 | def currentwlock(self): | |
2276 | """Returns the wlock if it's held, or None if it's not.""" |
|
2276 | """Returns the wlock if it's held, or None if it's not.""" | |
2277 | return self._currentlock(self._wlockref) |
|
2277 | return self._currentlock(self._wlockref) | |
2278 |
|
2278 | |||
2279 | def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist): |
|
2279 | def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist): | |
2280 | """ |
|
2280 | """ | |
2281 | commit an individual file as part of a larger transaction |
|
2281 | commit an individual file as part of a larger transaction | |
2282 | """ |
|
2282 | """ | |
2283 |
|
2283 | |||
2284 | fname = fctx.path() |
|
2284 | fname = fctx.path() | |
2285 | fparent1 = manifest1.get(fname, nullid) |
|
2285 | fparent1 = manifest1.get(fname, nullid) | |
2286 | fparent2 = manifest2.get(fname, nullid) |
|
2286 | fparent2 = manifest2.get(fname, nullid) | |
2287 | if isinstance(fctx, context.filectx): |
|
2287 | if isinstance(fctx, context.filectx): | |
2288 | node = fctx.filenode() |
|
2288 | node = fctx.filenode() | |
2289 | if node in [fparent1, fparent2]: |
|
2289 | if node in [fparent1, fparent2]: | |
2290 | self.ui.debug('reusing %s filelog entry\n' % fname) |
|
2290 | self.ui.debug('reusing %s filelog entry\n' % fname) | |
2291 | if manifest1.flags(fname) != fctx.flags(): |
|
2291 | if manifest1.flags(fname) != fctx.flags(): | |
2292 | changelist.append(fname) |
|
2292 | changelist.append(fname) | |
2293 | return node |
|
2293 | return node | |
2294 |
|
2294 | |||
2295 | flog = self.file(fname) |
|
2295 | flog = self.file(fname) | |
2296 | meta = {} |
|
2296 | meta = {} | |
2297 | copy = fctx.renamed() |
|
2297 | copy = fctx.renamed() | |
2298 | if copy and copy[0] != fname: |
|
2298 | if copy and copy[0] != fname: | |
2299 | # Mark the new revision of this file as a copy of another |
|
2299 | # Mark the new revision of this file as a copy of another | |
2300 | # file. This copy data will effectively act as a parent |
|
2300 | # file. This copy data will effectively act as a parent | |
2301 | # of this new revision. If this is a merge, the first |
|
2301 | # of this new revision. If this is a merge, the first | |
2302 | # parent will be the nullid (meaning "look up the copy data") |
|
2302 | # parent will be the nullid (meaning "look up the copy data") | |
2303 | # and the second one will be the other parent. For example: |
|
2303 | # and the second one will be the other parent. For example: | |
2304 | # |
|
2304 | # | |
2305 | # 0 --- 1 --- 3 rev1 changes file foo |
|
2305 | # 0 --- 1 --- 3 rev1 changes file foo | |
2306 | # \ / rev2 renames foo to bar and changes it |
|
2306 | # \ / rev2 renames foo to bar and changes it | |
2307 | # \- 2 -/ rev3 should have bar with all changes and |
|
2307 | # \- 2 -/ rev3 should have bar with all changes and | |
2308 | # should record that bar descends from |
|
2308 | # should record that bar descends from | |
2309 | # bar in rev2 and foo in rev1 |
|
2309 | # bar in rev2 and foo in rev1 | |
2310 | # |
|
2310 | # | |
2311 | # this allows this merge to succeed: |
|
2311 | # this allows this merge to succeed: | |
2312 | # |
|
2312 | # | |
2313 | # 0 --- 1 --- 3 rev4 reverts the content change from rev2 |
|
2313 | # 0 --- 1 --- 3 rev4 reverts the content change from rev2 | |
2314 | # \ / merging rev3 and rev4 should use bar@rev2 |
|
2314 | # \ / merging rev3 and rev4 should use bar@rev2 | |
2315 | # \- 2 --- 4 as the merge base |
|
2315 | # \- 2 --- 4 as the merge base | |
2316 | # |
|
2316 | # | |
2317 |
|
2317 | |||
2318 | cfname = copy[0] |
|
2318 | cfname = copy[0] | |
2319 | crev = manifest1.get(cfname) |
|
2319 | crev = manifest1.get(cfname) | |
2320 | newfparent = fparent2 |
|
2320 | newfparent = fparent2 | |
2321 |
|
2321 | |||
2322 | if manifest2: # branch merge |
|
2322 | if manifest2: # branch merge | |
2323 | if fparent2 == nullid or crev is None: # copied on remote side |
|
2323 | if fparent2 == nullid or crev is None: # copied on remote side | |
2324 | if cfname in manifest2: |
|
2324 | if cfname in manifest2: | |
2325 | crev = manifest2[cfname] |
|
2325 | crev = manifest2[cfname] | |
2326 | newfparent = fparent1 |
|
2326 | newfparent = fparent1 | |
2327 |
|
2327 | |||
2328 | # Here, we used to search backwards through history to try to find |
|
2328 | # Here, we used to search backwards through history to try to find | |
2329 | # where the file copy came from if the source of a copy was not in |
|
2329 | # where the file copy came from if the source of a copy was not in | |
2330 | # the parent directory. However, this doesn't actually make sense to |
|
2330 | # the parent directory. However, this doesn't actually make sense to | |
2331 | # do (what does a copy from something not in your working copy even |
|
2331 | # do (what does a copy from something not in your working copy even | |
2332 | # mean?) and it causes bugs (eg, issue4476). Instead, we will warn |
|
2332 | # mean?) and it causes bugs (eg, issue4476). Instead, we will warn | |
2333 | # the user that copy information was dropped, so if they didn't |
|
2333 | # the user that copy information was dropped, so if they didn't | |
2334 | # expect this outcome it can be fixed, but this is the correct |
|
2334 | # expect this outcome it can be fixed, but this is the correct | |
2335 | # behavior in this circumstance. |
|
2335 | # behavior in this circumstance. | |
2336 |
|
2336 | |||
2337 | if crev: |
|
2337 | if crev: | |
2338 | self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev))) |
|
2338 | self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev))) | |
2339 | meta["copy"] = cfname |
|
2339 | meta["copy"] = cfname | |
2340 | meta["copyrev"] = hex(crev) |
|
2340 | meta["copyrev"] = hex(crev) | |
2341 | fparent1, fparent2 = nullid, newfparent |
|
2341 | fparent1, fparent2 = nullid, newfparent | |
2342 | else: |
|
2342 | else: | |
2343 | self.ui.warn(_("warning: can't find ancestor for '%s' " |
|
2343 | self.ui.warn(_("warning: can't find ancestor for '%s' " | |
2344 | "copied from '%s'!\n") % (fname, cfname)) |
|
2344 | "copied from '%s'!\n") % (fname, cfname)) | |
2345 |
|
2345 | |||
2346 | elif fparent1 == nullid: |
|
2346 | elif fparent1 == nullid: | |
2347 | fparent1, fparent2 = fparent2, nullid |
|
2347 | fparent1, fparent2 = fparent2, nullid | |
2348 | elif fparent2 != nullid: |
|
2348 | elif fparent2 != nullid: | |
2349 | # is one parent an ancestor of the other? |
|
2349 | # is one parent an ancestor of the other? | |
2350 | fparentancestors = flog.commonancestorsheads(fparent1, fparent2) |
|
2350 | fparentancestors = flog.commonancestorsheads(fparent1, fparent2) | |
2351 | if fparent1 in fparentancestors: |
|
2351 | if fparent1 in fparentancestors: | |
2352 | fparent1, fparent2 = fparent2, nullid |
|
2352 | fparent1, fparent2 = fparent2, nullid | |
2353 | elif fparent2 in fparentancestors: |
|
2353 | elif fparent2 in fparentancestors: | |
2354 | fparent2 = nullid |
|
2354 | fparent2 = nullid | |
2355 |
|
2355 | |||
2356 | # is the file changed? |
|
2356 | # is the file changed? | |
2357 | text = fctx.data() |
|
2357 | text = fctx.data() | |
2358 | if fparent2 != nullid or flog.cmp(fparent1, text) or meta: |
|
2358 | if fparent2 != nullid or flog.cmp(fparent1, text) or meta: | |
2359 | changelist.append(fname) |
|
2359 | changelist.append(fname) | |
2360 | return flog.add(text, meta, tr, linkrev, fparent1, fparent2) |
|
2360 | return flog.add(text, meta, tr, linkrev, fparent1, fparent2) | |
2361 | # are just the flags changed during merge? |
|
2361 | # are just the flags changed during merge? | |
2362 | elif fname in manifest1 and manifest1.flags(fname) != fctx.flags(): |
|
2362 | elif fname in manifest1 and manifest1.flags(fname) != fctx.flags(): | |
2363 | changelist.append(fname) |
|
2363 | changelist.append(fname) | |
2364 |
|
2364 | |||
2365 | return fparent1 |
|
2365 | return fparent1 | |
2366 |
|
2366 | |||
2367 | def checkcommitpatterns(self, wctx, vdirs, match, status, fail): |
|
2367 | def checkcommitpatterns(self, wctx, vdirs, match, status, fail): | |
2368 | """check for commit arguments that aren't committable""" |
|
2368 | """check for commit arguments that aren't committable""" | |
2369 | if match.isexact() or match.prefix(): |
|
2369 | if match.isexact() or match.prefix(): | |
2370 | matched = set(status.modified + status.added + status.removed) |
|
2370 | matched = set(status.modified + status.added + status.removed) | |
2371 |
|
2371 | |||
2372 | for f in match.files(): |
|
2372 | for f in match.files(): | |
2373 | f = self.dirstate.normalize(f) |
|
2373 | f = self.dirstate.normalize(f) | |
2374 | if f == '.' or f in matched or f in wctx.substate: |
|
2374 | if f == '.' or f in matched or f in wctx.substate: | |
2375 | continue |
|
2375 | continue | |
2376 | if f in status.deleted: |
|
2376 | if f in status.deleted: | |
2377 | fail(f, _('file not found!')) |
|
2377 | fail(f, _('file not found!')) | |
2378 | if f in vdirs: # visited directory |
|
2378 | if f in vdirs: # visited directory | |
2379 | d = f + '/' |
|
2379 | d = f + '/' | |
2380 | for mf in matched: |
|
2380 | for mf in matched: | |
2381 | if mf.startswith(d): |
|
2381 | if mf.startswith(d): | |
2382 | break |
|
2382 | break | |
2383 | else: |
|
2383 | else: | |
2384 | fail(f, _("no match under directory!")) |
|
2384 | fail(f, _("no match under directory!")) | |
2385 | elif f not in self.dirstate: |
|
2385 | elif f not in self.dirstate: | |
2386 | fail(f, _("file not tracked!")) |
|
2386 | fail(f, _("file not tracked!")) | |
2387 |
|
2387 | |||
2388 | @unfilteredmethod |
|
2388 | @unfilteredmethod | |
2389 | def commit(self, text="", user=None, date=None, match=None, force=False, |
|
2389 | def commit(self, text="", user=None, date=None, match=None, force=False, | |
2390 | editor=False, extra=None): |
|
2390 | editor=False, extra=None): | |
2391 | """Add a new revision to current repository. |
|
2391 | """Add a new revision to current repository. | |
2392 |
|
2392 | |||
2393 | Revision information is gathered from the working directory, |
|
2393 | Revision information is gathered from the working directory, | |
2394 | match can be used to filter the committed files. If editor is |
|
2394 | match can be used to filter the committed files. If editor is | |
2395 | supplied, it is called to get a commit message. |
|
2395 | supplied, it is called to get a commit message. | |
2396 | """ |
|
2396 | """ | |
2397 | if extra is None: |
|
2397 | if extra is None: | |
2398 | extra = {} |
|
2398 | extra = {} | |
2399 |
|
2399 | |||
2400 | def fail(f, msg): |
|
2400 | def fail(f, msg): | |
2401 | raise error.Abort('%s: %s' % (f, msg)) |
|
2401 | raise error.Abort('%s: %s' % (f, msg)) | |
2402 |
|
2402 | |||
2403 | if not match: |
|
2403 | if not match: | |
2404 | match = matchmod.always(self.root, '') |
|
2404 | match = matchmod.always(self.root, '') | |
2405 |
|
2405 | |||
2406 | if not force: |
|
2406 | if not force: | |
2407 | vdirs = [] |
|
2407 | vdirs = [] | |
2408 | match.explicitdir = vdirs.append |
|
2408 | match.explicitdir = vdirs.append | |
2409 | match.bad = fail |
|
2409 | match.bad = fail | |
2410 |
|
2410 | |||
2411 | wlock = lock = tr = None |
|
2411 | wlock = lock = tr = None | |
2412 | try: |
|
2412 | try: | |
2413 | wlock = self.wlock() |
|
2413 | wlock = self.wlock() | |
2414 | lock = self.lock() # for recent changelog (see issue4368) |
|
2414 | lock = self.lock() # for recent changelog (see issue4368) | |
2415 |
|
2415 | |||
2416 | wctx = self[None] |
|
2416 | wctx = self[None] | |
2417 | merge = len(wctx.parents()) > 1 |
|
2417 | merge = len(wctx.parents()) > 1 | |
2418 |
|
2418 | |||
2419 | if not force and merge and not match.always(): |
|
2419 | if not force and merge and not match.always(): | |
2420 | raise error.Abort(_('cannot partially commit a merge ' |
|
2420 | raise error.Abort(_('cannot partially commit a merge ' | |
2421 | '(do not specify files or patterns)')) |
|
2421 | '(do not specify files or patterns)')) | |
2422 |
|
2422 | |||
2423 | status = self.status(match=match, clean=force) |
|
2423 | status = self.status(match=match, clean=force) | |
2424 | if force: |
|
2424 | if force: | |
2425 | status.modified.extend(status.clean) # mq may commit clean files |
|
2425 | status.modified.extend(status.clean) # mq may commit clean files | |
2426 |
|
2426 | |||
2427 | # check subrepos |
|
2427 | # check subrepos | |
2428 | subs, commitsubs, newstate = subrepoutil.precommit( |
|
2428 | subs, commitsubs, newstate = subrepoutil.precommit( | |
2429 | self.ui, wctx, status, match, force=force) |
|
2429 | self.ui, wctx, status, match, force=force) | |
2430 |
|
2430 | |||
2431 | # make sure all explicit patterns are matched |
|
2431 | # make sure all explicit patterns are matched | |
2432 | if not force: |
|
2432 | if not force: | |
2433 | self.checkcommitpatterns(wctx, vdirs, match, status, fail) |
|
2433 | self.checkcommitpatterns(wctx, vdirs, match, status, fail) | |
2434 |
|
2434 | |||
2435 | cctx = context.workingcommitctx(self, status, |
|
2435 | cctx = context.workingcommitctx(self, status, | |
2436 | text, user, date, extra) |
|
2436 | text, user, date, extra) | |
2437 |
|
2437 | |||
2438 | # internal config: ui.allowemptycommit |
|
2438 | # internal config: ui.allowemptycommit | |
2439 | allowemptycommit = (wctx.branch() != wctx.p1().branch() |
|
2439 | allowemptycommit = (wctx.branch() != wctx.p1().branch() | |
2440 | or extra.get('close') or merge or cctx.files() |
|
2440 | or extra.get('close') or merge or cctx.files() | |
2441 | or self.ui.configbool('ui', 'allowemptycommit')) |
|
2441 | or self.ui.configbool('ui', 'allowemptycommit')) | |
2442 | if not allowemptycommit: |
|
2442 | if not allowemptycommit: | |
2443 | return None |
|
2443 | return None | |
2444 |
|
2444 | |||
2445 | if merge and cctx.deleted(): |
|
2445 | if merge and cctx.deleted(): | |
2446 | raise error.Abort(_("cannot commit merge with missing files")) |
|
2446 | raise error.Abort(_("cannot commit merge with missing files")) | |
2447 |
|
2447 | |||
2448 | ms = mergemod.mergestate.read(self) |
|
2448 | ms = mergemod.mergestate.read(self) | |
2449 | mergeutil.checkunresolved(ms) |
|
2449 | mergeutil.checkunresolved(ms) | |
2450 |
|
2450 | |||
2451 | if editor: |
|
2451 | if editor: | |
2452 | cctx._text = editor(self, cctx, subs) |
|
2452 | cctx._text = editor(self, cctx, subs) | |
2453 | edited = (text != cctx._text) |
|
2453 | edited = (text != cctx._text) | |
2454 |
|
2454 | |||
2455 | # Save commit message in case this transaction gets rolled back |
|
2455 | # Save commit message in case this transaction gets rolled back | |
2456 | # (e.g. by a pretxncommit hook). Leave the content alone on |
|
2456 | # (e.g. by a pretxncommit hook). Leave the content alone on | |
2457 | # the assumption that the user will use the same editor again. |
|
2457 | # the assumption that the user will use the same editor again. | |
2458 | msgfn = self.savecommitmessage(cctx._text) |
|
2458 | msgfn = self.savecommitmessage(cctx._text) | |
2459 |
|
2459 | |||
2460 | # commit subs and write new state |
|
2460 | # commit subs and write new state | |
2461 | if subs: |
|
2461 | if subs: | |
2462 | for s in sorted(commitsubs): |
|
2462 | for s in sorted(commitsubs): | |
2463 | sub = wctx.sub(s) |
|
2463 | sub = wctx.sub(s) | |
2464 | self.ui.status(_('committing subrepository %s\n') % |
|
2464 | self.ui.status(_('committing subrepository %s\n') % | |
2465 | subrepoutil.subrelpath(sub)) |
|
2465 | subrepoutil.subrelpath(sub)) | |
2466 | sr = sub.commit(cctx._text, user, date) |
|
2466 | sr = sub.commit(cctx._text, user, date) | |
2467 | newstate[s] = (newstate[s][0], sr) |
|
2467 | newstate[s] = (newstate[s][0], sr) | |
2468 | subrepoutil.writestate(self, newstate) |
|
2468 | subrepoutil.writestate(self, newstate) | |
2469 |
|
2469 | |||
2470 | p1, p2 = self.dirstate.parents() |
|
2470 | p1, p2 = self.dirstate.parents() | |
2471 | hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '') |
|
2471 | hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '') | |
2472 | try: |
|
2472 | try: | |
2473 | self.hook("precommit", throw=True, parent1=hookp1, |
|
2473 | self.hook("precommit", throw=True, parent1=hookp1, | |
2474 | parent2=hookp2) |
|
2474 | parent2=hookp2) | |
2475 | tr = self.transaction('commit') |
|
2475 | tr = self.transaction('commit') | |
2476 | ret = self.commitctx(cctx, True) |
|
2476 | ret = self.commitctx(cctx, True) | |
2477 | except: # re-raises |
|
2477 | except: # re-raises | |
2478 | if edited: |
|
2478 | if edited: | |
2479 | self.ui.write( |
|
2479 | self.ui.write( | |
2480 | _('note: commit message saved in %s\n') % msgfn) |
|
2480 | _('note: commit message saved in %s\n') % msgfn) | |
2481 | raise |
|
2481 | raise | |
2482 | # update bookmarks, dirstate and mergestate |
|
2482 | # update bookmarks, dirstate and mergestate | |
2483 | bookmarks.update(self, [p1, p2], ret) |
|
2483 | bookmarks.update(self, [p1, p2], ret) | |
2484 | cctx.markcommitted(ret) |
|
2484 | cctx.markcommitted(ret) | |
2485 | ms.reset() |
|
2485 | ms.reset() | |
2486 | tr.close() |
|
2486 | tr.close() | |
2487 |
|
2487 | |||
2488 | finally: |
|
2488 | finally: | |
2489 | lockmod.release(tr, lock, wlock) |
|
2489 | lockmod.release(tr, lock, wlock) | |
2490 |
|
2490 | |||
2491 | def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2): |
|
2491 | def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2): | |
2492 | # hack for command that use a temporary commit (eg: histedit) |
|
2492 | # hack for command that use a temporary commit (eg: histedit) | |
2493 | # temporary commit got stripped before hook release |
|
2493 | # temporary commit got stripped before hook release | |
2494 | if self.changelog.hasnode(ret): |
|
2494 | if self.changelog.hasnode(ret): | |
2495 | self.hook("commit", node=node, parent1=parent1, |
|
2495 | self.hook("commit", node=node, parent1=parent1, | |
2496 | parent2=parent2) |
|
2496 | parent2=parent2) | |
2497 | self._afterlock(commithook) |
|
2497 | self._afterlock(commithook) | |
2498 | return ret |
|
2498 | return ret | |
2499 |
|
2499 | |||
2500 | @unfilteredmethod |
|
2500 | @unfilteredmethod | |
2501 | def commitctx(self, ctx, error=False): |
|
2501 | def commitctx(self, ctx, error=False): | |
2502 | """Add a new revision to current repository. |
|
2502 | """Add a new revision to current repository. | |
2503 | Revision information is passed via the context argument. |
|
2503 | Revision information is passed via the context argument. | |
2504 |
|
2504 | |||
2505 | ctx.files() should list all files involved in this commit, i.e. |
|
2505 | ctx.files() should list all files involved in this commit, i.e. | |
2506 | modified/added/removed files. On merge, it may be wider than the |
|
2506 | modified/added/removed files. On merge, it may be wider than the | |
2507 | ctx.files() to be committed, since any file nodes derived directly |
|
2507 | ctx.files() to be committed, since any file nodes derived directly | |
2508 | from p1 or p2 are excluded from the committed ctx.files(). |
|
2508 | from p1 or p2 are excluded from the committed ctx.files(). | |
2509 | """ |
|
2509 | """ | |
2510 |
|
2510 | |||
2511 | tr = None |
|
2511 | tr = None | |
2512 | p1, p2 = ctx.p1(), ctx.p2() |
|
2512 | p1, p2 = ctx.p1(), ctx.p2() | |
2513 | user = ctx.user() |
|
2513 | user = ctx.user() | |
2514 |
|
2514 | |||
2515 | lock = self.lock() |
|
2515 | lock = self.lock() | |
2516 | try: |
|
2516 | try: | |
2517 | tr = self.transaction("commit") |
|
2517 | tr = self.transaction("commit") | |
2518 | trp = weakref.proxy(tr) |
|
2518 | trp = weakref.proxy(tr) | |
2519 |
|
2519 | |||
2520 | if ctx.manifestnode(): |
|
2520 | if ctx.manifestnode(): | |
2521 | # reuse an existing manifest revision |
|
2521 | # reuse an existing manifest revision | |
2522 | self.ui.debug('reusing known manifest\n') |
|
2522 | self.ui.debug('reusing known manifest\n') | |
2523 | mn = ctx.manifestnode() |
|
2523 | mn = ctx.manifestnode() | |
2524 | files = ctx.files() |
|
2524 | files = ctx.files() | |
2525 | elif ctx.files(): |
|
2525 | elif ctx.files(): | |
2526 | m1ctx = p1.manifestctx() |
|
2526 | m1ctx = p1.manifestctx() | |
2527 | m2ctx = p2.manifestctx() |
|
2527 | m2ctx = p2.manifestctx() | |
2528 | mctx = m1ctx.copy() |
|
2528 | mctx = m1ctx.copy() | |
2529 |
|
2529 | |||
2530 | m = mctx.read() |
|
2530 | m = mctx.read() | |
2531 | m1 = m1ctx.read() |
|
2531 | m1 = m1ctx.read() | |
2532 | m2 = m2ctx.read() |
|
2532 | m2 = m2ctx.read() | |
2533 |
|
2533 | |||
2534 | # check in files |
|
2534 | # check in files | |
2535 | added = [] |
|
2535 | added = [] | |
2536 | changed = [] |
|
2536 | changed = [] | |
2537 | removed = list(ctx.removed()) |
|
2537 | removed = list(ctx.removed()) | |
2538 | linkrev = len(self) |
|
2538 | linkrev = len(self) | |
2539 | self.ui.note(_("committing files:\n")) |
|
2539 | self.ui.note(_("committing files:\n")) | |
2540 | for f in sorted(ctx.modified() + ctx.added()): |
|
2540 | for f in sorted(ctx.modified() + ctx.added()): | |
2541 | self.ui.note(f + "\n") |
|
2541 | self.ui.note(f + "\n") | |
2542 | try: |
|
2542 | try: | |
2543 | fctx = ctx[f] |
|
2543 | fctx = ctx[f] | |
2544 | if fctx is None: |
|
2544 | if fctx is None: | |
2545 | removed.append(f) |
|
2545 | removed.append(f) | |
2546 | else: |
|
2546 | else: | |
2547 | added.append(f) |
|
2547 | added.append(f) | |
2548 | m[f] = self._filecommit(fctx, m1, m2, linkrev, |
|
2548 | m[f] = self._filecommit(fctx, m1, m2, linkrev, | |
2549 | trp, changed) |
|
2549 | trp, changed) | |
2550 | m.setflag(f, fctx.flags()) |
|
2550 | m.setflag(f, fctx.flags()) | |
2551 | except OSError as inst: |
|
2551 | except OSError as inst: | |
2552 | self.ui.warn(_("trouble committing %s!\n") % f) |
|
2552 | self.ui.warn(_("trouble committing %s!\n") % f) | |
2553 | raise |
|
2553 | raise | |
2554 | except IOError as inst: |
|
2554 | except IOError as inst: | |
2555 | errcode = getattr(inst, 'errno', errno.ENOENT) |
|
2555 | errcode = getattr(inst, 'errno', errno.ENOENT) | |
2556 | if error or errcode and errcode != errno.ENOENT: |
|
2556 | if error or errcode and errcode != errno.ENOENT: | |
2557 | self.ui.warn(_("trouble committing %s!\n") % f) |
|
2557 | self.ui.warn(_("trouble committing %s!\n") % f) | |
2558 | raise |
|
2558 | raise | |
2559 |
|
2559 | |||
2560 | # update manifest |
|
2560 | # update manifest | |
2561 | removed = [f for f in sorted(removed) if f in m1 or f in m2] |
|
2561 | removed = [f for f in sorted(removed) if f in m1 or f in m2] | |
2562 | drop = [f for f in removed if f in m] |
|
2562 | drop = [f for f in removed if f in m] | |
2563 | for f in drop: |
|
2563 | for f in drop: | |
2564 | del m[f] |
|
2564 | del m[f] | |
2565 | files = changed + removed |
|
2565 | files = changed + removed | |
2566 | md = None |
|
2566 | md = None | |
2567 | if not files: |
|
2567 | if not files: | |
2568 | # if no "files" actually changed in terms of the changelog, |
|
2568 | # if no "files" actually changed in terms of the changelog, | |
2569 | # try hard to detect unmodified manifest entry so that the |
|
2569 | # try hard to detect unmodified manifest entry so that the | |
2570 | # exact same commit can be reproduced later on convert. |
|
2570 | # exact same commit can be reproduced later on convert. | |
2571 | md = m1.diff(m, scmutil.matchfiles(self, ctx.files())) |
|
2571 | md = m1.diff(m, scmutil.matchfiles(self, ctx.files())) | |
2572 | if not files and md: |
|
2572 | if not files and md: | |
2573 | self.ui.debug('not reusing manifest (no file change in ' |
|
2573 | self.ui.debug('not reusing manifest (no file change in ' | |
2574 | 'changelog, but manifest differs)\n') |
|
2574 | 'changelog, but manifest differs)\n') | |
2575 | if files or md: |
|
2575 | if files or md: | |
2576 | self.ui.note(_("committing manifest\n")) |
|
2576 | self.ui.note(_("committing manifest\n")) | |
2577 | # we're using narrowmatch here since it's already applied at |
|
2577 | # we're using narrowmatch here since it's already applied at | |
2578 | # other stages (such as dirstate.walk), so we're already |
|
2578 | # other stages (such as dirstate.walk), so we're already | |
2579 | # ignoring things outside of narrowspec in most cases. The |
|
2579 | # ignoring things outside of narrowspec in most cases. The | |
2580 | # one case where we might have files outside the narrowspec |
|
2580 | # one case where we might have files outside the narrowspec | |
2581 | # at this point is merges, and we already error out in the |
|
2581 | # at this point is merges, and we already error out in the | |
2582 | # case where the merge has files outside of the narrowspec, |
|
2582 | # case where the merge has files outside of the narrowspec, | |
2583 | # so this is safe. |
|
2583 | # so this is safe. | |
2584 | mn = mctx.write(trp, linkrev, |
|
2584 | mn = mctx.write(trp, linkrev, | |
2585 | p1.manifestnode(), p2.manifestnode(), |
|
2585 | p1.manifestnode(), p2.manifestnode(), | |
2586 | added, drop, match=self.narrowmatch()) |
|
2586 | added, drop, match=self.narrowmatch()) | |
2587 | else: |
|
2587 | else: | |
2588 | self.ui.debug('reusing manifest form p1 (listed files ' |
|
2588 | self.ui.debug('reusing manifest form p1 (listed files ' | |
2589 | 'actually unchanged)\n') |
|
2589 | 'actually unchanged)\n') | |
2590 | mn = p1.manifestnode() |
|
2590 | mn = p1.manifestnode() | |
2591 | else: |
|
2591 | else: | |
2592 | self.ui.debug('reusing manifest from p1 (no file change)\n') |
|
2592 | self.ui.debug('reusing manifest from p1 (no file change)\n') | |
2593 | mn = p1.manifestnode() |
|
2593 | mn = p1.manifestnode() | |
2594 | files = [] |
|
2594 | files = [] | |
2595 |
|
2595 | |||
2596 | # update changelog |
|
2596 | # update changelog | |
2597 | self.ui.note(_("committing changelog\n")) |
|
2597 | self.ui.note(_("committing changelog\n")) | |
2598 | self.changelog.delayupdate(tr) |
|
2598 | self.changelog.delayupdate(tr) | |
2599 | n = self.changelog.add(mn, files, ctx.description(), |
|
2599 | n = self.changelog.add(mn, files, ctx.description(), | |
2600 | trp, p1.node(), p2.node(), |
|
2600 | trp, p1.node(), p2.node(), | |
2601 | user, ctx.date(), ctx.extra().copy()) |
|
2601 | user, ctx.date(), ctx.extra().copy()) | |
2602 | xp1, xp2 = p1.hex(), p2 and p2.hex() or '' |
|
2602 | xp1, xp2 = p1.hex(), p2 and p2.hex() or '' | |
2603 | self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1, |
|
2603 | self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1, | |
2604 | parent2=xp2) |
|
2604 | parent2=xp2) | |
2605 | # set the new commit is proper phase |
|
2605 | # set the new commit is proper phase | |
2606 | targetphase = subrepoutil.newcommitphase(self.ui, ctx) |
|
2606 | targetphase = subrepoutil.newcommitphase(self.ui, ctx) | |
2607 | if targetphase: |
|
2607 | if targetphase: | |
2608 | # retract boundary do not alter parent changeset. |
|
2608 | # retract boundary do not alter parent changeset. | |
2609 | # if a parent have higher the resulting phase will |
|
2609 | # if a parent have higher the resulting phase will | |
2610 | # be compliant anyway |
|
2610 | # be compliant anyway | |
2611 | # |
|
2611 | # | |
2612 | # if minimal phase was 0 we don't need to retract anything |
|
2612 | # if minimal phase was 0 we don't need to retract anything | |
2613 | phases.registernew(self, tr, targetphase, [n]) |
|
2613 | phases.registernew(self, tr, targetphase, [n]) | |
2614 | tr.close() |
|
2614 | tr.close() | |
2615 | return n |
|
2615 | return n | |
2616 | finally: |
|
2616 | finally: | |
2617 | if tr: |
|
2617 | if tr: | |
2618 | tr.release() |
|
2618 | tr.release() | |
2619 | lock.release() |
|
2619 | lock.release() | |
2620 |
|
2620 | |||
2621 | @unfilteredmethod |
|
2621 | @unfilteredmethod | |
2622 | def destroying(self): |
|
2622 | def destroying(self): | |
2623 | '''Inform the repository that nodes are about to be destroyed. |
|
2623 | '''Inform the repository that nodes are about to be destroyed. | |
2624 | Intended for use by strip and rollback, so there's a common |
|
2624 | Intended for use by strip and rollback, so there's a common | |
2625 | place for anything that has to be done before destroying history. |
|
2625 | place for anything that has to be done before destroying history. | |
2626 |
|
2626 | |||
2627 | This is mostly useful for saving state that is in memory and waiting |
|
2627 | This is mostly useful for saving state that is in memory and waiting | |
2628 | to be flushed when the current lock is released. Because a call to |
|
2628 | to be flushed when the current lock is released. Because a call to | |
2629 | destroyed is imminent, the repo will be invalidated causing those |
|
2629 | destroyed is imminent, the repo will be invalidated causing those | |
2630 | changes to stay in memory (waiting for the next unlock), or vanish |
|
2630 | changes to stay in memory (waiting for the next unlock), or vanish | |
2631 | completely. |
|
2631 | completely. | |
2632 | ''' |
|
2632 | ''' | |
2633 | # When using the same lock to commit and strip, the phasecache is left |
|
2633 | # When using the same lock to commit and strip, the phasecache is left | |
2634 | # dirty after committing. Then when we strip, the repo is invalidated, |
|
2634 | # dirty after committing. Then when we strip, the repo is invalidated, | |
2635 | # causing those changes to disappear. |
|
2635 | # causing those changes to disappear. | |
2636 | if '_phasecache' in vars(self): |
|
2636 | if '_phasecache' in vars(self): | |
2637 | self._phasecache.write() |
|
2637 | self._phasecache.write() | |
2638 |
|
2638 | |||
2639 | @unfilteredmethod |
|
2639 | @unfilteredmethod | |
2640 | def destroyed(self): |
|
2640 | def destroyed(self): | |
2641 | '''Inform the repository that nodes have been destroyed. |
|
2641 | '''Inform the repository that nodes have been destroyed. | |
2642 | Intended for use by strip and rollback, so there's a common |
|
2642 | Intended for use by strip and rollback, so there's a common | |
2643 | place for anything that has to be done after destroying history. |
|
2643 | place for anything that has to be done after destroying history. | |
2644 | ''' |
|
2644 | ''' | |
2645 | # When one tries to: |
|
2645 | # When one tries to: | |
2646 | # 1) destroy nodes thus calling this method (e.g. strip) |
|
2646 | # 1) destroy nodes thus calling this method (e.g. strip) | |
2647 | # 2) use phasecache somewhere (e.g. commit) |
|
2647 | # 2) use phasecache somewhere (e.g. commit) | |
2648 | # |
|
2648 | # | |
2649 | # then 2) will fail because the phasecache contains nodes that were |
|
2649 | # then 2) will fail because the phasecache contains nodes that were | |
2650 | # removed. We can either remove phasecache from the filecache, |
|
2650 | # removed. We can either remove phasecache from the filecache, | |
2651 | # causing it to reload next time it is accessed, or simply filter |
|
2651 | # causing it to reload next time it is accessed, or simply filter | |
2652 | # the removed nodes now and write the updated cache. |
|
2652 | # the removed nodes now and write the updated cache. | |
2653 | self._phasecache.filterunknown(self) |
|
2653 | self._phasecache.filterunknown(self) | |
2654 | self._phasecache.write() |
|
2654 | self._phasecache.write() | |
2655 |
|
2655 | |||
2656 | # refresh all repository caches |
|
2656 | # refresh all repository caches | |
2657 | self.updatecaches() |
|
2657 | self.updatecaches() | |
2658 |
|
2658 | |||
2659 | # Ensure the persistent tag cache is updated. Doing it now |
|
2659 | # Ensure the persistent tag cache is updated. Doing it now | |
2660 | # means that the tag cache only has to worry about destroyed |
|
2660 | # means that the tag cache only has to worry about destroyed | |
2661 | # heads immediately after a strip/rollback. That in turn |
|
2661 | # heads immediately after a strip/rollback. That in turn | |
2662 | # guarantees that "cachetip == currenttip" (comparing both rev |
|
2662 | # guarantees that "cachetip == currenttip" (comparing both rev | |
2663 | # and node) always means no nodes have been added or destroyed. |
|
2663 | # and node) always means no nodes have been added or destroyed. | |
2664 |
|
2664 | |||
2665 | # XXX this is suboptimal when qrefresh'ing: we strip the current |
|
2665 | # XXX this is suboptimal when qrefresh'ing: we strip the current | |
2666 | # head, refresh the tag cache, then immediately add a new head. |
|
2666 | # head, refresh the tag cache, then immediately add a new head. | |
2667 | # But I think doing it this way is necessary for the "instant |
|
2667 | # But I think doing it this way is necessary for the "instant | |
2668 | # tag cache retrieval" case to work. |
|
2668 | # tag cache retrieval" case to work. | |
2669 | self.invalidate() |
|
2669 | self.invalidate() | |
2670 |
|
2670 | |||
2671 | def status(self, node1='.', node2=None, match=None, |
|
2671 | def status(self, node1='.', node2=None, match=None, | |
2672 | ignored=False, clean=False, unknown=False, |
|
2672 | ignored=False, clean=False, unknown=False, | |
2673 | listsubrepos=False): |
|
2673 | listsubrepos=False): | |
2674 | '''a convenience method that calls node1.status(node2)''' |
|
2674 | '''a convenience method that calls node1.status(node2)''' | |
2675 | return self[node1].status(node2, match, ignored, clean, unknown, |
|
2675 | return self[node1].status(node2, match, ignored, clean, unknown, | |
2676 | listsubrepos) |
|
2676 | listsubrepos) | |
2677 |
|
2677 | |||
2678 | def addpostdsstatus(self, ps): |
|
2678 | def addpostdsstatus(self, ps): | |
2679 | """Add a callback to run within the wlock, at the point at which status |
|
2679 | """Add a callback to run within the wlock, at the point at which status | |
2680 | fixups happen. |
|
2680 | fixups happen. | |
2681 |
|
2681 | |||
2682 | On status completion, callback(wctx, status) will be called with the |
|
2682 | On status completion, callback(wctx, status) will be called with the | |
2683 | wlock held, unless the dirstate has changed from underneath or the wlock |
|
2683 | wlock held, unless the dirstate has changed from underneath or the wlock | |
2684 | couldn't be grabbed. |
|
2684 | couldn't be grabbed. | |
2685 |
|
2685 | |||
2686 | Callbacks should not capture and use a cached copy of the dirstate -- |
|
2686 | Callbacks should not capture and use a cached copy of the dirstate -- | |
2687 | it might change in the meanwhile. Instead, they should access the |
|
2687 | it might change in the meanwhile. Instead, they should access the | |
2688 | dirstate via wctx.repo().dirstate. |
|
2688 | dirstate via wctx.repo().dirstate. | |
2689 |
|
2689 | |||
2690 | This list is emptied out after each status run -- extensions should |
|
2690 | This list is emptied out after each status run -- extensions should | |
2691 | make sure it adds to this list each time dirstate.status is called. |
|
2691 | make sure it adds to this list each time dirstate.status is called. | |
2692 | Extensions should also make sure they don't call this for statuses |
|
2692 | Extensions should also make sure they don't call this for statuses | |
2693 | that don't involve the dirstate. |
|
2693 | that don't involve the dirstate. | |
2694 | """ |
|
2694 | """ | |
2695 |
|
2695 | |||
2696 | # The list is located here for uniqueness reasons -- it is actually |
|
2696 | # The list is located here for uniqueness reasons -- it is actually | |
2697 | # managed by the workingctx, but that isn't unique per-repo. |
|
2697 | # managed by the workingctx, but that isn't unique per-repo. | |
2698 | self._postdsstatus.append(ps) |
|
2698 | self._postdsstatus.append(ps) | |
2699 |
|
2699 | |||
2700 | def postdsstatus(self): |
|
2700 | def postdsstatus(self): | |
2701 | """Used by workingctx to get the list of post-dirstate-status hooks.""" |
|
2701 | """Used by workingctx to get the list of post-dirstate-status hooks.""" | |
2702 | return self._postdsstatus |
|
2702 | return self._postdsstatus | |
2703 |
|
2703 | |||
2704 | def clearpostdsstatus(self): |
|
2704 | def clearpostdsstatus(self): | |
2705 | """Used by workingctx to clear post-dirstate-status hooks.""" |
|
2705 | """Used by workingctx to clear post-dirstate-status hooks.""" | |
2706 | del self._postdsstatus[:] |
|
2706 | del self._postdsstatus[:] | |
2707 |
|
2707 | |||
2708 | def heads(self, start=None): |
|
2708 | def heads(self, start=None): | |
2709 | if start is None: |
|
2709 | if start is None: | |
2710 | cl = self.changelog |
|
2710 | cl = self.changelog | |
2711 | headrevs = reversed(cl.headrevs()) |
|
2711 | headrevs = reversed(cl.headrevs()) | |
2712 | return [cl.node(rev) for rev in headrevs] |
|
2712 | return [cl.node(rev) for rev in headrevs] | |
2713 |
|
2713 | |||
2714 | heads = self.changelog.heads(start) |
|
2714 | heads = self.changelog.heads(start) | |
2715 | # sort the output in rev descending order |
|
2715 | # sort the output in rev descending order | |
2716 | return sorted(heads, key=self.changelog.rev, reverse=True) |
|
2716 | return sorted(heads, key=self.changelog.rev, reverse=True) | |
2717 |
|
2717 | |||
2718 | def branchheads(self, branch=None, start=None, closed=False): |
|
2718 | def branchheads(self, branch=None, start=None, closed=False): | |
2719 | '''return a (possibly filtered) list of heads for the given branch |
|
2719 | '''return a (possibly filtered) list of heads for the given branch | |
2720 |
|
2720 | |||
2721 | Heads are returned in topological order, from newest to oldest. |
|
2721 | Heads are returned in topological order, from newest to oldest. | |
2722 | If branch is None, use the dirstate branch. |
|
2722 | If branch is None, use the dirstate branch. | |
2723 | If start is not None, return only heads reachable from start. |
|
2723 | If start is not None, return only heads reachable from start. | |
2724 | If closed is True, return heads that are marked as closed as well. |
|
2724 | If closed is True, return heads that are marked as closed as well. | |
2725 | ''' |
|
2725 | ''' | |
2726 | if branch is None: |
|
2726 | if branch is None: | |
2727 | branch = self[None].branch() |
|
2727 | branch = self[None].branch() | |
2728 | branches = self.branchmap() |
|
2728 | branches = self.branchmap() | |
2729 | if branch not in branches: |
|
2729 | if branch not in branches: | |
2730 | return [] |
|
2730 | return [] | |
2731 | # the cache returns heads ordered lowest to highest |
|
2731 | # the cache returns heads ordered lowest to highest | |
2732 | bheads = list(reversed(branches.branchheads(branch, closed=closed))) |
|
2732 | bheads = list(reversed(branches.branchheads(branch, closed=closed))) | |
2733 | if start is not None: |
|
2733 | if start is not None: | |
2734 | # filter out the heads that cannot be reached from startrev |
|
2734 | # filter out the heads that cannot be reached from startrev | |
2735 | fbheads = set(self.changelog.nodesbetween([start], bheads)[2]) |
|
2735 | fbheads = set(self.changelog.nodesbetween([start], bheads)[2]) | |
2736 | bheads = [h for h in bheads if h in fbheads] |
|
2736 | bheads = [h for h in bheads if h in fbheads] | |
2737 | return bheads |
|
2737 | return bheads | |
2738 |
|
2738 | |||
2739 | def branches(self, nodes): |
|
2739 | def branches(self, nodes): | |
2740 | if not nodes: |
|
2740 | if not nodes: | |
2741 | nodes = [self.changelog.tip()] |
|
2741 | nodes = [self.changelog.tip()] | |
2742 | b = [] |
|
2742 | b = [] | |
2743 | for n in nodes: |
|
2743 | for n in nodes: | |
2744 | t = n |
|
2744 | t = n | |
2745 | while True: |
|
2745 | while True: | |
2746 | p = self.changelog.parents(n) |
|
2746 | p = self.changelog.parents(n) | |
2747 | if p[1] != nullid or p[0] == nullid: |
|
2747 | if p[1] != nullid or p[0] == nullid: | |
2748 | b.append((t, n, p[0], p[1])) |
|
2748 | b.append((t, n, p[0], p[1])) | |
2749 | break |
|
2749 | break | |
2750 | n = p[0] |
|
2750 | n = p[0] | |
2751 | return b |
|
2751 | return b | |
2752 |
|
2752 | |||
2753 | def between(self, pairs): |
|
2753 | def between(self, pairs): | |
2754 | r = [] |
|
2754 | r = [] | |
2755 |
|
2755 | |||
2756 | for top, bottom in pairs: |
|
2756 | for top, bottom in pairs: | |
2757 | n, l, i = top, [], 0 |
|
2757 | n, l, i = top, [], 0 | |
2758 | f = 1 |
|
2758 | f = 1 | |
2759 |
|
2759 | |||
2760 | while n != bottom and n != nullid: |
|
2760 | while n != bottom and n != nullid: | |
2761 | p = self.changelog.parents(n)[0] |
|
2761 | p = self.changelog.parents(n)[0] | |
2762 | if i == f: |
|
2762 | if i == f: | |
2763 | l.append(n) |
|
2763 | l.append(n) | |
2764 | f = f * 2 |
|
2764 | f = f * 2 | |
2765 | n = p |
|
2765 | n = p | |
2766 | i += 1 |
|
2766 | i += 1 | |
2767 |
|
2767 | |||
2768 | r.append(l) |
|
2768 | r.append(l) | |
2769 |
|
2769 | |||
2770 | return r |
|
2770 | return r | |
2771 |
|
2771 | |||
2772 | def checkpush(self, pushop): |
|
2772 | def checkpush(self, pushop): | |
2773 | """Extensions can override this function if additional checks have |
|
2773 | """Extensions can override this function if additional checks have | |
2774 | to be performed before pushing, or call it if they override push |
|
2774 | to be performed before pushing, or call it if they override push | |
2775 | command. |
|
2775 | command. | |
2776 | """ |
|
2776 | """ | |
2777 |
|
2777 | |||
2778 | @unfilteredpropertycache |
|
2778 | @unfilteredpropertycache | |
2779 | def prepushoutgoinghooks(self): |
|
2779 | def prepushoutgoinghooks(self): | |
2780 | """Return util.hooks consists of a pushop with repo, remote, outgoing |
|
2780 | """Return util.hooks consists of a pushop with repo, remote, outgoing | |
2781 | methods, which are called before pushing changesets. |
|
2781 | methods, which are called before pushing changesets. | |
2782 | """ |
|
2782 | """ | |
2783 | return util.hooks() |
|
2783 | return util.hooks() | |
2784 |
|
2784 | |||
2785 | def pushkey(self, namespace, key, old, new): |
|
2785 | def pushkey(self, namespace, key, old, new): | |
2786 | try: |
|
2786 | try: | |
2787 | tr = self.currenttransaction() |
|
2787 | tr = self.currenttransaction() | |
2788 | hookargs = {} |
|
2788 | hookargs = {} | |
2789 | if tr is not None: |
|
2789 | if tr is not None: | |
2790 | hookargs.update(tr.hookargs) |
|
2790 | hookargs.update(tr.hookargs) | |
2791 | hookargs = pycompat.strkwargs(hookargs) |
|
2791 | hookargs = pycompat.strkwargs(hookargs) | |
2792 | hookargs[r'namespace'] = namespace |
|
2792 | hookargs[r'namespace'] = namespace | |
2793 | hookargs[r'key'] = key |
|
2793 | hookargs[r'key'] = key | |
2794 | hookargs[r'old'] = old |
|
2794 | hookargs[r'old'] = old | |
2795 | hookargs[r'new'] = new |
|
2795 | hookargs[r'new'] = new | |
2796 | self.hook('prepushkey', throw=True, **hookargs) |
|
2796 | self.hook('prepushkey', throw=True, **hookargs) | |
2797 | except error.HookAbort as exc: |
|
2797 | except error.HookAbort as exc: | |
2798 | self.ui.write_err(_("pushkey-abort: %s\n") % exc) |
|
2798 | self.ui.write_err(_("pushkey-abort: %s\n") % exc) | |
2799 | if exc.hint: |
|
2799 | if exc.hint: | |
2800 | self.ui.write_err(_("(%s)\n") % exc.hint) |
|
2800 | self.ui.write_err(_("(%s)\n") % exc.hint) | |
2801 | return False |
|
2801 | return False | |
2802 | self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key)) |
|
2802 | self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key)) | |
2803 | ret = pushkey.push(self, namespace, key, old, new) |
|
2803 | ret = pushkey.push(self, namespace, key, old, new) | |
2804 | def runhook(): |
|
2804 | def runhook(): | |
2805 | self.hook('pushkey', namespace=namespace, key=key, old=old, new=new, |
|
2805 | self.hook('pushkey', namespace=namespace, key=key, old=old, new=new, | |
2806 | ret=ret) |
|
2806 | ret=ret) | |
2807 | self._afterlock(runhook) |
|
2807 | self._afterlock(runhook) | |
2808 | return ret |
|
2808 | return ret | |
2809 |
|
2809 | |||
2810 | def listkeys(self, namespace): |
|
2810 | def listkeys(self, namespace): | |
2811 | self.hook('prelistkeys', throw=True, namespace=namespace) |
|
2811 | self.hook('prelistkeys', throw=True, namespace=namespace) | |
2812 | self.ui.debug('listing keys for "%s"\n' % namespace) |
|
2812 | self.ui.debug('listing keys for "%s"\n' % namespace) | |
2813 | values = pushkey.list(self, namespace) |
|
2813 | values = pushkey.list(self, namespace) | |
2814 | self.hook('listkeys', namespace=namespace, values=values) |
|
2814 | self.hook('listkeys', namespace=namespace, values=values) | |
2815 | return values |
|
2815 | return values | |
2816 |
|
2816 | |||
2817 | def debugwireargs(self, one, two, three=None, four=None, five=None): |
|
2817 | def debugwireargs(self, one, two, three=None, four=None, five=None): | |
2818 | '''used to test argument passing over the wire''' |
|
2818 | '''used to test argument passing over the wire''' | |
2819 | return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three), |
|
2819 | return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three), | |
2820 | pycompat.bytestr(four), |
|
2820 | pycompat.bytestr(four), | |
2821 | pycompat.bytestr(five)) |
|
2821 | pycompat.bytestr(five)) | |
2822 |
|
2822 | |||
2823 | def savecommitmessage(self, text): |
|
2823 | def savecommitmessage(self, text): | |
2824 | fp = self.vfs('last-message.txt', 'wb') |
|
2824 | fp = self.vfs('last-message.txt', 'wb') | |
2825 | try: |
|
2825 | try: | |
2826 | fp.write(text) |
|
2826 | fp.write(text) | |
2827 | finally: |
|
2827 | finally: | |
2828 | fp.close() |
|
2828 | fp.close() | |
2829 | return self.pathto(fp.name[len(self.root) + 1:]) |
|
2829 | return self.pathto(fp.name[len(self.root) + 1:]) | |
2830 |
|
2830 | |||
2831 | # used to avoid circular references so destructors work |
|
2831 | # used to avoid circular references so destructors work | |
2832 | def aftertrans(files): |
|
2832 | def aftertrans(files): | |
2833 | renamefiles = [tuple(t) for t in files] |
|
2833 | renamefiles = [tuple(t) for t in files] | |
2834 | def a(): |
|
2834 | def a(): | |
2835 | for vfs, src, dest in renamefiles: |
|
2835 | for vfs, src, dest in renamefiles: | |
2836 | # if src and dest refer to a same file, vfs.rename is a no-op, |
|
2836 | # if src and dest refer to a same file, vfs.rename is a no-op, | |
2837 | # leaving both src and dest on disk. delete dest to make sure |
|
2837 | # leaving both src and dest on disk. delete dest to make sure | |
2838 | # the rename couldn't be such a no-op. |
|
2838 | # the rename couldn't be such a no-op. | |
2839 | vfs.tryunlink(dest) |
|
2839 | vfs.tryunlink(dest) | |
2840 | try: |
|
2840 | try: | |
2841 | vfs.rename(src, dest) |
|
2841 | vfs.rename(src, dest) | |
2842 | except OSError: # journal file does not yet exist |
|
2842 | except OSError: # journal file does not yet exist | |
2843 | pass |
|
2843 | pass | |
2844 | return a |
|
2844 | return a | |
2845 |
|
2845 | |||
2846 | def undoname(fn): |
|
2846 | def undoname(fn): | |
2847 | base, name = os.path.split(fn) |
|
2847 | base, name = os.path.split(fn) | |
2848 | assert name.startswith('journal') |
|
2848 | assert name.startswith('journal') | |
2849 | return os.path.join(base, name.replace('journal', 'undo', 1)) |
|
2849 | return os.path.join(base, name.replace('journal', 'undo', 1)) | |
2850 |
|
2850 | |||
2851 | def instance(ui, path, create, intents=None, createopts=None): |
|
2851 | def instance(ui, path, create, intents=None, createopts=None): | |
2852 | localpath = util.urllocalpath(path) |
|
2852 | localpath = util.urllocalpath(path) | |
2853 | if create: |
|
2853 | if create: | |
2854 | createrepository(ui, localpath, createopts=createopts) |
|
2854 | createrepository(ui, localpath, createopts=createopts) | |
2855 |
|
2855 | |||
2856 | return makelocalrepository(ui, localpath, intents=intents) |
|
2856 | return makelocalrepository(ui, localpath, intents=intents) | |
2857 |
|
2857 | |||
2858 | def islocal(path): |
|
2858 | def islocal(path): | |
2859 | return True |
|
2859 | return True | |
2860 |
|
2860 | |||
2861 | def defaultcreateopts(ui, createopts=None): |
|
2861 | def defaultcreateopts(ui, createopts=None): | |
2862 | """Populate the default creation options for a repository. |
|
2862 | """Populate the default creation options for a repository. | |
2863 |
|
2863 | |||
2864 | A dictionary of explicitly requested creation options can be passed |
|
2864 | A dictionary of explicitly requested creation options can be passed | |
2865 | in. Missing keys will be populated. |
|
2865 | in. Missing keys will be populated. | |
2866 | """ |
|
2866 | """ | |
2867 | createopts = dict(createopts or {}) |
|
2867 | createopts = dict(createopts or {}) | |
2868 |
|
2868 | |||
2869 | if 'backend' not in createopts: |
|
2869 | if 'backend' not in createopts: | |
2870 | # experimental config: storage.new-repo-backend |
|
2870 | # experimental config: storage.new-repo-backend | |
2871 | createopts['backend'] = ui.config('storage', 'new-repo-backend') |
|
2871 | createopts['backend'] = ui.config('storage', 'new-repo-backend') | |
2872 |
|
2872 | |||
2873 | return createopts |
|
2873 | return createopts | |
2874 |
|
2874 | |||
2875 | def newreporequirements(ui, createopts): |
|
2875 | def newreporequirements(ui, createopts): | |
2876 | """Determine the set of requirements for a new local repository. |
|
2876 | """Determine the set of requirements for a new local repository. | |
2877 |
|
2877 | |||
2878 | Extensions can wrap this function to specify custom requirements for |
|
2878 | Extensions can wrap this function to specify custom requirements for | |
2879 | new repositories. |
|
2879 | new repositories. | |
2880 | """ |
|
2880 | """ | |
2881 | # If the repo is being created from a shared repository, we copy |
|
2881 | # If the repo is being created from a shared repository, we copy | |
2882 | # its requirements. |
|
2882 | # its requirements. | |
2883 | if 'sharedrepo' in createopts: |
|
2883 | if 'sharedrepo' in createopts: | |
2884 | requirements = set(createopts['sharedrepo'].requirements) |
|
2884 | requirements = set(createopts['sharedrepo'].requirements) | |
2885 | if createopts.get('sharedrelative'): |
|
2885 | if createopts.get('sharedrelative'): | |
2886 | requirements.add('relshared') |
|
2886 | requirements.add('relshared') | |
2887 | else: |
|
2887 | else: | |
2888 | requirements.add('shared') |
|
2888 | requirements.add('shared') | |
2889 |
|
2889 | |||
2890 | return requirements |
|
2890 | return requirements | |
2891 |
|
2891 | |||
2892 | if 'backend' not in createopts: |
|
2892 | if 'backend' not in createopts: | |
2893 | raise error.ProgrammingError('backend key not present in createopts; ' |
|
2893 | raise error.ProgrammingError('backend key not present in createopts; ' | |
2894 | 'was defaultcreateopts() called?') |
|
2894 | 'was defaultcreateopts() called?') | |
2895 |
|
2895 | |||
2896 | if createopts['backend'] != 'revlogv1': |
|
2896 | if createopts['backend'] != 'revlogv1': | |
2897 | raise error.Abort(_('unable to determine repository requirements for ' |
|
2897 | raise error.Abort(_('unable to determine repository requirements for ' | |
2898 | 'storage backend: %s') % createopts['backend']) |
|
2898 | 'storage backend: %s') % createopts['backend']) | |
2899 |
|
2899 | |||
2900 | requirements = {'revlogv1'} |
|
2900 | requirements = {'revlogv1'} | |
2901 | if ui.configbool('format', 'usestore'): |
|
2901 | if ui.configbool('format', 'usestore'): | |
2902 | requirements.add('store') |
|
2902 | requirements.add('store') | |
2903 | if ui.configbool('format', 'usefncache'): |
|
2903 | if ui.configbool('format', 'usefncache'): | |
2904 | requirements.add('fncache') |
|
2904 | requirements.add('fncache') | |
2905 | if ui.configbool('format', 'dotencode'): |
|
2905 | if ui.configbool('format', 'dotencode'): | |
2906 | requirements.add('dotencode') |
|
2906 | requirements.add('dotencode') | |
2907 |
|
2907 | |||
2908 | compengine = ui.config('experimental', 'format.compression') |
|
2908 | compengine = ui.config('experimental', 'format.compression') | |
2909 | if compengine not in util.compengines: |
|
2909 | if compengine not in util.compengines: | |
2910 | raise error.Abort(_('compression engine %s defined by ' |
|
2910 | raise error.Abort(_('compression engine %s defined by ' | |
2911 | 'experimental.format.compression not available') % |
|
2911 | 'experimental.format.compression not available') % | |
2912 | compengine, |
|
2912 | compengine, | |
2913 | hint=_('run "hg debuginstall" to list available ' |
|
2913 | hint=_('run "hg debuginstall" to list available ' | |
2914 | 'compression engines')) |
|
2914 | 'compression engines')) | |
2915 |
|
2915 | |||
2916 | # zlib is the historical default and doesn't need an explicit requirement. |
|
2916 | # zlib is the historical default and doesn't need an explicit requirement. | |
2917 | if compengine != 'zlib': |
|
2917 | if compengine != 'zlib': | |
2918 | requirements.add('exp-compression-%s' % compengine) |
|
2918 | requirements.add('exp-compression-%s' % compengine) | |
2919 |
|
2919 | |||
2920 | if scmutil.gdinitconfig(ui): |
|
2920 | if scmutil.gdinitconfig(ui): | |
2921 | requirements.add('generaldelta') |
|
2921 | requirements.add('generaldelta') | |
2922 | # experimental config: format.sparse-revlog |
|
2922 | # experimental config: format.sparse-revlog | |
2923 | if ui.configbool('format', 'sparse-revlog'): |
|
2923 | if ui.configbool('format', 'sparse-revlog'): | |
2924 | requirements.add(SPARSEREVLOG_REQUIREMENT) |
|
2924 | requirements.add(SPARSEREVLOG_REQUIREMENT) | |
2925 | if ui.configbool('experimental', 'treemanifest'): |
|
2925 | if ui.configbool('experimental', 'treemanifest'): | |
2926 | requirements.add('treemanifest') |
|
2926 | requirements.add('treemanifest') | |
2927 |
|
2927 | |||
2928 | revlogv2 = ui.config('experimental', 'revlogv2') |
|
2928 | revlogv2 = ui.config('experimental', 'revlogv2') | |
2929 | if revlogv2 == 'enable-unstable-format-and-corrupt-my-data': |
|
2929 | if revlogv2 == 'enable-unstable-format-and-corrupt-my-data': | |
2930 | requirements.remove('revlogv1') |
|
2930 | requirements.remove('revlogv1') | |
2931 | # generaldelta is implied by revlogv2. |
|
2931 | # generaldelta is implied by revlogv2. | |
2932 | requirements.discard('generaldelta') |
|
2932 | requirements.discard('generaldelta') | |
2933 | requirements.add(REVLOGV2_REQUIREMENT) |
|
2933 | requirements.add(REVLOGV2_REQUIREMENT) | |
2934 | # experimental config: format.internal-phase |
|
2934 | # experimental config: format.internal-phase | |
2935 | if ui.configbool('format', 'internal-phase'): |
|
2935 | if ui.configbool('format', 'internal-phase'): | |
2936 | requirements.add('internal-phase') |
|
2936 | requirements.add('internal-phase') | |
2937 |
|
2937 | |||
2938 | if createopts.get('narrowfiles'): |
|
2938 | if createopts.get('narrowfiles'): | |
2939 | requirements.add(repository.NARROW_REQUIREMENT) |
|
2939 | requirements.add(repository.NARROW_REQUIREMENT) | |
2940 |
|
2940 | |||
2941 | if createopts.get('lfs'): |
|
2941 | if createopts.get('lfs'): | |
2942 | requirements.add('lfs') |
|
2942 | requirements.add('lfs') | |
2943 |
|
2943 | |||
2944 | return requirements |
|
2944 | return requirements | |
2945 |
|
2945 | |||
2946 | def filterknowncreateopts(ui, createopts): |
|
2946 | def filterknowncreateopts(ui, createopts): | |
2947 | """Filters a dict of repo creation options against options that are known. |
|
2947 | """Filters a dict of repo creation options against options that are known. | |
2948 |
|
2948 | |||
2949 | Receives a dict of repo creation options and returns a dict of those |
|
2949 | Receives a dict of repo creation options and returns a dict of those | |
2950 | options that we don't know how to handle. |
|
2950 | options that we don't know how to handle. | |
2951 |
|
2951 | |||
2952 | This function is called as part of repository creation. If the |
|
2952 | This function is called as part of repository creation. If the | |
2953 | returned dict contains any items, repository creation will not |
|
2953 | returned dict contains any items, repository creation will not | |
2954 | be allowed, as it means there was a request to create a repository |
|
2954 | be allowed, as it means there was a request to create a repository | |
2955 | with options not recognized by loaded code. |
|
2955 | with options not recognized by loaded code. | |
2956 |
|
2956 | |||
2957 | Extensions can wrap this function to filter out creation options |
|
2957 | Extensions can wrap this function to filter out creation options | |
2958 | they know how to handle. |
|
2958 | they know how to handle. | |
2959 | """ |
|
2959 | """ | |
2960 | known = { |
|
2960 | known = { | |
2961 | 'backend', |
|
2961 | 'backend', | |
2962 | 'lfs', |
|
2962 | 'lfs', | |
2963 | 'narrowfiles', |
|
2963 | 'narrowfiles', | |
2964 | 'sharedrepo', |
|
2964 | 'sharedrepo', | |
2965 | 'sharedrelative', |
|
2965 | 'sharedrelative', | |
2966 | 'shareditems', |
|
2966 | 'shareditems', | |
2967 | 'shallowfilestore', |
|
2967 | 'shallowfilestore', | |
2968 | } |
|
2968 | } | |
2969 |
|
2969 | |||
2970 | return {k: v for k, v in createopts.items() if k not in known} |
|
2970 | return {k: v for k, v in createopts.items() if k not in known} | |
2971 |
|
2971 | |||
2972 | def createrepository(ui, path, createopts=None): |
|
2972 | def createrepository(ui, path, createopts=None): | |
2973 | """Create a new repository in a vfs. |
|
2973 | """Create a new repository in a vfs. | |
2974 |
|
2974 | |||
2975 | ``path`` path to the new repo's working directory. |
|
2975 | ``path`` path to the new repo's working directory. | |
2976 | ``createopts`` options for the new repository. |
|
2976 | ``createopts`` options for the new repository. | |
2977 |
|
2977 | |||
2978 | The following keys for ``createopts`` are recognized: |
|
2978 | The following keys for ``createopts`` are recognized: | |
2979 |
|
2979 | |||
2980 | backend |
|
2980 | backend | |
2981 | The storage backend to use. |
|
2981 | The storage backend to use. | |
2982 | lfs |
|
2982 | lfs | |
2983 | Repository will be created with ``lfs`` requirement. The lfs extension |
|
2983 | Repository will be created with ``lfs`` requirement. The lfs extension | |
2984 | will automatically be loaded when the repository is accessed. |
|
2984 | will automatically be loaded when the repository is accessed. | |
2985 | narrowfiles |
|
2985 | narrowfiles | |
2986 | Set up repository to support narrow file storage. |
|
2986 | Set up repository to support narrow file storage. | |
2987 | sharedrepo |
|
2987 | sharedrepo | |
2988 | Repository object from which storage should be shared. |
|
2988 | Repository object from which storage should be shared. | |
2989 | sharedrelative |
|
2989 | sharedrelative | |
2990 | Boolean indicating if the path to the shared repo should be |
|
2990 | Boolean indicating if the path to the shared repo should be | |
2991 | stored as relative. By default, the pointer to the "parent" repo |
|
2991 | stored as relative. By default, the pointer to the "parent" repo | |
2992 | is stored as an absolute path. |
|
2992 | is stored as an absolute path. | |
2993 | shareditems |
|
2993 | shareditems | |
2994 | Set of items to share to the new repository (in addition to storage). |
|
2994 | Set of items to share to the new repository (in addition to storage). | |
2995 | shallowfilestore |
|
2995 | shallowfilestore | |
2996 | Indicates that storage for files should be shallow (not all ancestor |
|
2996 | Indicates that storage for files should be shallow (not all ancestor | |
2997 | revisions are known). |
|
2997 | revisions are known). | |
2998 | """ |
|
2998 | """ | |
2999 | createopts = defaultcreateopts(ui, createopts=createopts) |
|
2999 | createopts = defaultcreateopts(ui, createopts=createopts) | |
3000 |
|
3000 | |||
3001 | unknownopts = filterknowncreateopts(ui, createopts) |
|
3001 | unknownopts = filterknowncreateopts(ui, createopts) | |
3002 |
|
3002 | |||
3003 | if not isinstance(unknownopts, dict): |
|
3003 | if not isinstance(unknownopts, dict): | |
3004 | raise error.ProgrammingError('filterknowncreateopts() did not return ' |
|
3004 | raise error.ProgrammingError('filterknowncreateopts() did not return ' | |
3005 | 'a dict') |
|
3005 | 'a dict') | |
3006 |
|
3006 | |||
3007 | if unknownopts: |
|
3007 | if unknownopts: | |
3008 | raise error.Abort(_('unable to create repository because of unknown ' |
|
3008 | raise error.Abort(_('unable to create repository because of unknown ' | |
3009 | 'creation option: %s') % |
|
3009 | 'creation option: %s') % | |
3010 | ', '.join(sorted(unknownopts)), |
|
3010 | ', '.join(sorted(unknownopts)), | |
3011 | hint=_('is a required extension not loaded?')) |
|
3011 | hint=_('is a required extension not loaded?')) | |
3012 |
|
3012 | |||
3013 | requirements = newreporequirements(ui, createopts=createopts) |
|
3013 | requirements = newreporequirements(ui, createopts=createopts) | |
3014 |
|
3014 | |||
3015 | wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True) |
|
3015 | wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True) | |
3016 |
|
3016 | |||
3017 | hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg')) |
|
3017 | hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg')) | |
3018 | if hgvfs.exists(): |
|
3018 | if hgvfs.exists(): | |
3019 | raise error.RepoError(_('repository %s already exists') % path) |
|
3019 | raise error.RepoError(_('repository %s already exists') % path) | |
3020 |
|
3020 | |||
3021 | if 'sharedrepo' in createopts: |
|
3021 | if 'sharedrepo' in createopts: | |
3022 | sharedpath = createopts['sharedrepo'].sharedpath |
|
3022 | sharedpath = createopts['sharedrepo'].sharedpath | |
3023 |
|
3023 | |||
3024 | if createopts.get('sharedrelative'): |
|
3024 | if createopts.get('sharedrelative'): | |
3025 | try: |
|
3025 | try: | |
3026 | sharedpath = os.path.relpath(sharedpath, hgvfs.base) |
|
3026 | sharedpath = os.path.relpath(sharedpath, hgvfs.base) | |
3027 | except (IOError, ValueError) as e: |
|
3027 | except (IOError, ValueError) as e: | |
3028 | # ValueError is raised on Windows if the drive letters differ |
|
3028 | # ValueError is raised on Windows if the drive letters differ | |
3029 | # on each path. |
|
3029 | # on each path. | |
3030 | raise error.Abort(_('cannot calculate relative path'), |
|
3030 | raise error.Abort(_('cannot calculate relative path'), | |
3031 | hint=stringutil.forcebytestr(e)) |
|
3031 | hint=stringutil.forcebytestr(e)) | |
3032 |
|
3032 | |||
3033 | if not wdirvfs.exists(): |
|
3033 | if not wdirvfs.exists(): | |
3034 | wdirvfs.makedirs() |
|
3034 | wdirvfs.makedirs() | |
3035 |
|
3035 | |||
3036 | hgvfs.makedir(notindexed=True) |
|
3036 | hgvfs.makedir(notindexed=True) | |
3037 | if 'sharedrepo' not in createopts: |
|
3037 | if 'sharedrepo' not in createopts: | |
3038 | hgvfs.mkdir(b'cache') |
|
3038 | hgvfs.mkdir(b'cache') | |
3039 | hgvfs.mkdir(b'wcache') |
|
3039 | hgvfs.mkdir(b'wcache') | |
3040 |
|
3040 | |||
3041 | if b'store' in requirements and 'sharedrepo' not in createopts: |
|
3041 | if b'store' in requirements and 'sharedrepo' not in createopts: | |
3042 | hgvfs.mkdir(b'store') |
|
3042 | hgvfs.mkdir(b'store') | |
3043 |
|
3043 | |||
3044 | # We create an invalid changelog outside the store so very old |
|
3044 | # We create an invalid changelog outside the store so very old | |
3045 | # Mercurial versions (which didn't know about the requirements |
|
3045 | # Mercurial versions (which didn't know about the requirements | |
3046 | # file) encounter an error on reading the changelog. This |
|
3046 | # file) encounter an error on reading the changelog. This | |
3047 | # effectively locks out old clients and prevents them from |
|
3047 | # effectively locks out old clients and prevents them from | |
3048 | # mucking with a repo in an unknown format. |
|
3048 | # mucking with a repo in an unknown format. | |
3049 | # |
|
3049 | # | |
3050 | # The revlog header has version 2, which won't be recognized by |
|
3050 | # The revlog header has version 2, which won't be recognized by | |
3051 | # such old clients. |
|
3051 | # such old clients. | |
3052 | hgvfs.append(b'00changelog.i', |
|
3052 | hgvfs.append(b'00changelog.i', | |
3053 | b'\0\0\0\2 dummy changelog to prevent using the old repo ' |
|
3053 | b'\0\0\0\2 dummy changelog to prevent using the old repo ' | |
3054 | b'layout') |
|
3054 | b'layout') | |
3055 |
|
3055 | |||
3056 | scmutil.writerequires(hgvfs, requirements) |
|
3056 | scmutil.writerequires(hgvfs, requirements) | |
3057 |
|
3057 | |||
3058 | # Write out file telling readers where to find the shared store. |
|
3058 | # Write out file telling readers where to find the shared store. | |
3059 | if 'sharedrepo' in createopts: |
|
3059 | if 'sharedrepo' in createopts: | |
3060 | hgvfs.write(b'sharedpath', sharedpath) |
|
3060 | hgvfs.write(b'sharedpath', sharedpath) | |
3061 |
|
3061 | |||
3062 | if createopts.get('shareditems'): |
|
3062 | if createopts.get('shareditems'): | |
3063 | shared = b'\n'.join(sorted(createopts['shareditems'])) + b'\n' |
|
3063 | shared = b'\n'.join(sorted(createopts['shareditems'])) + b'\n' | |
3064 | hgvfs.write(b'shared', shared) |
|
3064 | hgvfs.write(b'shared', shared) | |
3065 |
|
3065 | |||
3066 | def poisonrepository(repo): |
|
3066 | def poisonrepository(repo): | |
3067 | """Poison a repository instance so it can no longer be used.""" |
|
3067 | """Poison a repository instance so it can no longer be used.""" | |
3068 | # Perform any cleanup on the instance. |
|
3068 | # Perform any cleanup on the instance. | |
3069 | repo.close() |
|
3069 | repo.close() | |
3070 |
|
3070 | |||
3071 | # Our strategy is to replace the type of the object with one that |
|
3071 | # Our strategy is to replace the type of the object with one that | |
3072 | # has all attribute lookups result in error. |
|
3072 | # has all attribute lookups result in error. | |
3073 | # |
|
3073 | # | |
3074 | # But we have to allow the close() method because some constructors |
|
3074 | # But we have to allow the close() method because some constructors | |
3075 | # of repos call close() on repo references. |
|
3075 | # of repos call close() on repo references. | |
3076 | class poisonedrepository(object): |
|
3076 | class poisonedrepository(object): | |
3077 | def __getattribute__(self, item): |
|
3077 | def __getattribute__(self, item): | |
3078 | if item == r'close': |
|
3078 | if item == r'close': | |
3079 | return object.__getattribute__(self, item) |
|
3079 | return object.__getattribute__(self, item) | |
3080 |
|
3080 | |||
3081 | raise error.ProgrammingError('repo instances should not be used ' |
|
3081 | raise error.ProgrammingError('repo instances should not be used ' | |
3082 | 'after unshare') |
|
3082 | 'after unshare') | |
3083 |
|
3083 | |||
3084 | def close(self): |
|
3084 | def close(self): | |
3085 | pass |
|
3085 | pass | |
3086 |
|
3086 | |||
3087 | # We may have a repoview, which intercepts __setattr__. So be sure |
|
3087 | # We may have a repoview, which intercepts __setattr__. So be sure | |
3088 | # we operate at the lowest level possible. |
|
3088 | # we operate at the lowest level possible. | |
3089 | object.__setattr__(repo, r'__class__', poisonedrepository) |
|
3089 | object.__setattr__(repo, r'__class__', poisonedrepository) |
@@ -1,311 +1,303 b'' | |||||
1 | # narrowspec.py - methods for working with a narrow view of a repository |
|
1 | # narrowspec.py - methods for working with a narrow view of a repository | |
2 | # |
|
2 | # | |
3 | # Copyright 2017 Google, Inc. |
|
3 | # Copyright 2017 Google, Inc. | |
4 | # |
|
4 | # | |
5 | # This software may be used and distributed according to the terms of the |
|
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. |
|
6 | # GNU General Public License version 2 or any later version. | |
7 |
|
7 | |||
8 | from __future__ import absolute_import |
|
8 | from __future__ import absolute_import | |
9 |
|
9 | |||
10 | import errno |
|
10 | import errno | |
11 |
|
11 | |||
12 | from .i18n import _ |
|
12 | from .i18n import _ | |
13 | from . import ( |
|
13 | from . import ( | |
14 | error, |
|
14 | error, | |
15 | match as matchmod, |
|
15 | match as matchmod, | |
16 | merge, |
|
16 | merge, | |
17 | repository, |
|
17 | repository, | |
18 | sparse, |
|
18 | sparse, | |
19 | util, |
|
19 | util, | |
20 | ) |
|
20 | ) | |
21 |
|
21 | |||
22 | # The file in .hg/store/ that indicates which paths exit in the store |
|
22 | # The file in .hg/store/ that indicates which paths exit in the store | |
23 | FILENAME = 'narrowspec' |
|
23 | FILENAME = 'narrowspec' | |
24 | # The file in .hg/ that indicates which paths exit in the dirstate |
|
24 | # The file in .hg/ that indicates which paths exit in the dirstate | |
25 | DIRSTATE_FILENAME = 'narrowspec.dirstate' |
|
25 | DIRSTATE_FILENAME = 'narrowspec.dirstate' | |
26 |
|
26 | |||
27 | # Pattern prefixes that are allowed in narrow patterns. This list MUST |
|
27 | # Pattern prefixes that are allowed in narrow patterns. This list MUST | |
28 | # only contain patterns that are fast and safe to evaluate. Keep in mind |
|
28 | # only contain patterns that are fast and safe to evaluate. Keep in mind | |
29 | # that patterns are supplied by clients and executed on remote servers |
|
29 | # that patterns are supplied by clients and executed on remote servers | |
30 | # as part of wire protocol commands. That means that changes to this |
|
30 | # as part of wire protocol commands. That means that changes to this | |
31 | # data structure influence the wire protocol and should not be taken |
|
31 | # data structure influence the wire protocol and should not be taken | |
32 | # lightly - especially removals. |
|
32 | # lightly - especially removals. | |
33 | VALID_PREFIXES = ( |
|
33 | VALID_PREFIXES = ( | |
34 | b'path:', |
|
34 | b'path:', | |
35 | b'rootfilesin:', |
|
35 | b'rootfilesin:', | |
36 | ) |
|
36 | ) | |
37 |
|
37 | |||
38 | def normalizesplitpattern(kind, pat): |
|
38 | def normalizesplitpattern(kind, pat): | |
39 | """Returns the normalized version of a pattern and kind. |
|
39 | """Returns the normalized version of a pattern and kind. | |
40 |
|
40 | |||
41 | Returns a tuple with the normalized kind and normalized pattern. |
|
41 | Returns a tuple with the normalized kind and normalized pattern. | |
42 | """ |
|
42 | """ | |
43 | pat = pat.rstrip('/') |
|
43 | pat = pat.rstrip('/') | |
44 | _validatepattern(pat) |
|
44 | _validatepattern(pat) | |
45 | return kind, pat |
|
45 | return kind, pat | |
46 |
|
46 | |||
47 | def _numlines(s): |
|
47 | def _numlines(s): | |
48 | """Returns the number of lines in s, including ending empty lines.""" |
|
48 | """Returns the number of lines in s, including ending empty lines.""" | |
49 | # We use splitlines because it is Unicode-friendly and thus Python 3 |
|
49 | # We use splitlines because it is Unicode-friendly and thus Python 3 | |
50 | # compatible. However, it does not count empty lines at the end, so trick |
|
50 | # compatible. However, it does not count empty lines at the end, so trick | |
51 | # it by adding a character at the end. |
|
51 | # it by adding a character at the end. | |
52 | return len((s + 'x').splitlines()) |
|
52 | return len((s + 'x').splitlines()) | |
53 |
|
53 | |||
54 | def _validatepattern(pat): |
|
54 | def _validatepattern(pat): | |
55 | """Validates the pattern and aborts if it is invalid. |
|
55 | """Validates the pattern and aborts if it is invalid. | |
56 |
|
56 | |||
57 | Patterns are stored in the narrowspec as newline-separated |
|
57 | Patterns are stored in the narrowspec as newline-separated | |
58 | POSIX-style bytestring paths. There's no escaping. |
|
58 | POSIX-style bytestring paths. There's no escaping. | |
59 | """ |
|
59 | """ | |
60 |
|
60 | |||
61 | # We use newlines as separators in the narrowspec file, so don't allow them |
|
61 | # We use newlines as separators in the narrowspec file, so don't allow them | |
62 | # in patterns. |
|
62 | # in patterns. | |
63 | if _numlines(pat) > 1: |
|
63 | if _numlines(pat) > 1: | |
64 | raise error.Abort(_('newlines are not allowed in narrowspec paths')) |
|
64 | raise error.Abort(_('newlines are not allowed in narrowspec paths')) | |
65 |
|
65 | |||
66 | components = pat.split('/') |
|
66 | components = pat.split('/') | |
67 | if '.' in components or '..' in components: |
|
67 | if '.' in components or '..' in components: | |
68 | raise error.Abort(_('"." and ".." are not allowed in narrowspec paths')) |
|
68 | raise error.Abort(_('"." and ".." are not allowed in narrowspec paths')) | |
69 |
|
69 | |||
70 | def normalizepattern(pattern, defaultkind='path'): |
|
70 | def normalizepattern(pattern, defaultkind='path'): | |
71 | """Returns the normalized version of a text-format pattern. |
|
71 | """Returns the normalized version of a text-format pattern. | |
72 |
|
72 | |||
73 | If the pattern has no kind, the default will be added. |
|
73 | If the pattern has no kind, the default will be added. | |
74 | """ |
|
74 | """ | |
75 | kind, pat = matchmod._patsplit(pattern, defaultkind) |
|
75 | kind, pat = matchmod._patsplit(pattern, defaultkind) | |
76 | return '%s:%s' % normalizesplitpattern(kind, pat) |
|
76 | return '%s:%s' % normalizesplitpattern(kind, pat) | |
77 |
|
77 | |||
78 | def parsepatterns(pats): |
|
78 | def parsepatterns(pats): | |
79 | """Parses an iterable of patterns into a typed pattern set. |
|
79 | """Parses an iterable of patterns into a typed pattern set. | |
80 |
|
80 | |||
81 | Patterns are assumed to be ``path:`` if no prefix is present. |
|
81 | Patterns are assumed to be ``path:`` if no prefix is present. | |
82 | For safety and performance reasons, only some prefixes are allowed. |
|
82 | For safety and performance reasons, only some prefixes are allowed. | |
83 | See ``validatepatterns()``. |
|
83 | See ``validatepatterns()``. | |
84 |
|
84 | |||
85 | This function should be used on patterns that come from the user to |
|
85 | This function should be used on patterns that come from the user to | |
86 | normalize and validate them to the internal data structure used for |
|
86 | normalize and validate them to the internal data structure used for | |
87 | representing patterns. |
|
87 | representing patterns. | |
88 | """ |
|
88 | """ | |
89 | res = {normalizepattern(orig) for orig in pats} |
|
89 | res = {normalizepattern(orig) for orig in pats} | |
90 | validatepatterns(res) |
|
90 | validatepatterns(res) | |
91 | return res |
|
91 | return res | |
92 |
|
92 | |||
93 | def validatepatterns(pats): |
|
93 | def validatepatterns(pats): | |
94 | """Validate that patterns are in the expected data structure and format. |
|
94 | """Validate that patterns are in the expected data structure and format. | |
95 |
|
95 | |||
96 | And that is a set of normalized patterns beginning with ``path:`` or |
|
96 | And that is a set of normalized patterns beginning with ``path:`` or | |
97 | ``rootfilesin:``. |
|
97 | ``rootfilesin:``. | |
98 |
|
98 | |||
99 | This function should be used to validate internal data structures |
|
99 | This function should be used to validate internal data structures | |
100 | and patterns that are loaded from sources that use the internal, |
|
100 | and patterns that are loaded from sources that use the internal, | |
101 | prefixed pattern representation (but can't necessarily be fully trusted). |
|
101 | prefixed pattern representation (but can't necessarily be fully trusted). | |
102 | """ |
|
102 | """ | |
103 | if not isinstance(pats, set): |
|
103 | if not isinstance(pats, set): | |
104 | raise error.ProgrammingError('narrow patterns should be a set; ' |
|
104 | raise error.ProgrammingError('narrow patterns should be a set; ' | |
105 | 'got %r' % pats) |
|
105 | 'got %r' % pats) | |
106 |
|
106 | |||
107 | for pat in pats: |
|
107 | for pat in pats: | |
108 | if not pat.startswith(VALID_PREFIXES): |
|
108 | if not pat.startswith(VALID_PREFIXES): | |
109 | # Use a Mercurial exception because this can happen due to user |
|
109 | # Use a Mercurial exception because this can happen due to user | |
110 | # bugs (e.g. manually updating spec file). |
|
110 | # bugs (e.g. manually updating spec file). | |
111 | raise error.Abort(_('invalid prefix on narrow pattern: %s') % pat, |
|
111 | raise error.Abort(_('invalid prefix on narrow pattern: %s') % pat, | |
112 | hint=_('narrow patterns must begin with one of ' |
|
112 | hint=_('narrow patterns must begin with one of ' | |
113 | 'the following: %s') % |
|
113 | 'the following: %s') % | |
114 | ', '.join(VALID_PREFIXES)) |
|
114 | ', '.join(VALID_PREFIXES)) | |
115 |
|
115 | |||
116 | def format(includes, excludes): |
|
116 | def format(includes, excludes): | |
117 | output = '[include]\n' |
|
117 | output = '[include]\n' | |
118 | for i in sorted(includes - excludes): |
|
118 | for i in sorted(includes - excludes): | |
119 | output += i + '\n' |
|
119 | output += i + '\n' | |
120 | output += '[exclude]\n' |
|
120 | output += '[exclude]\n' | |
121 | for e in sorted(excludes): |
|
121 | for e in sorted(excludes): | |
122 | output += e + '\n' |
|
122 | output += e + '\n' | |
123 | return output |
|
123 | return output | |
124 |
|
124 | |||
125 | def match(root, include=None, exclude=None): |
|
125 | def match(root, include=None, exclude=None): | |
126 | if not include: |
|
126 | if not include: | |
127 | # Passing empty include and empty exclude to matchmod.match() |
|
127 | # Passing empty include and empty exclude to matchmod.match() | |
128 | # gives a matcher that matches everything, so explicitly use |
|
128 | # gives a matcher that matches everything, so explicitly use | |
129 | # the nevermatcher. |
|
129 | # the nevermatcher. | |
130 | return matchmod.never(root, '') |
|
130 | return matchmod.never(root, '') | |
131 | return matchmod.match(root, '', [], include=include or [], |
|
131 | return matchmod.match(root, '', [], include=include or [], | |
132 | exclude=exclude or []) |
|
132 | exclude=exclude or []) | |
133 |
|
133 | |||
134 | def parseconfig(ui, spec): |
|
134 | def parseconfig(ui, spec): | |
135 | # maybe we should care about the profiles returned too |
|
135 | # maybe we should care about the profiles returned too | |
136 | includepats, excludepats, profiles = sparse.parseconfig(ui, spec, 'narrow') |
|
136 | includepats, excludepats, profiles = sparse.parseconfig(ui, spec, 'narrow') | |
137 | if profiles: |
|
137 | if profiles: | |
138 | raise error.Abort(_("including other spec files using '%include' is not" |
|
138 | raise error.Abort(_("including other spec files using '%include' is not" | |
139 | " supported in narrowspec")) |
|
139 | " supported in narrowspec")) | |
140 |
|
140 | |||
141 | validatepatterns(includepats) |
|
141 | validatepatterns(includepats) | |
142 | validatepatterns(excludepats) |
|
142 | validatepatterns(excludepats) | |
143 |
|
143 | |||
144 | return includepats, excludepats |
|
144 | return includepats, excludepats | |
145 |
|
145 | |||
146 | def load(repo): |
|
146 | def load(repo): | |
147 | try: |
|
147 | try: | |
148 | spec = repo.svfs.read(FILENAME) |
|
148 | spec = repo.svfs.read(FILENAME) | |
149 | except IOError as e: |
|
149 | except IOError as e: | |
150 | # Treat "narrowspec does not exist" the same as "narrowspec file exists |
|
150 | # Treat "narrowspec does not exist" the same as "narrowspec file exists | |
151 | # and is empty". |
|
151 | # and is empty". | |
152 | if e.errno == errno.ENOENT: |
|
152 | if e.errno == errno.ENOENT: | |
153 | return set(), set() |
|
153 | return set(), set() | |
154 | raise |
|
154 | raise | |
155 |
|
155 | |||
156 | return parseconfig(repo.ui, spec) |
|
156 | return parseconfig(repo.ui, spec) | |
157 |
|
157 | |||
158 | def save(repo, includepats, excludepats): |
|
158 | def save(repo, includepats, excludepats): | |
159 | validatepatterns(includepats) |
|
159 | validatepatterns(includepats) | |
160 | validatepatterns(excludepats) |
|
160 | validatepatterns(excludepats) | |
161 | spec = format(includepats, excludepats) |
|
161 | spec = format(includepats, excludepats) | |
162 | repo.svfs.write(FILENAME, spec) |
|
162 | repo.svfs.write(FILENAME, spec) | |
163 |
|
163 | |||
164 |
def copytoworkingcopy(repo |
|
164 | def copytoworkingcopy(repo): | |
165 | if tr: |
|
165 | spec = repo.svfs.read(FILENAME) | |
166 | def write(file): |
|
166 | repo.vfs.write(DIRSTATE_FILENAME, spec) | |
167 | spec = repo.svfs.read(FILENAME) |
|
|||
168 | file.write(spec) |
|
|||
169 | file.close() |
|
|||
170 | tr.addfilegenerator('narrowspec', (DIRSTATE_FILENAME,), write, |
|
|||
171 | location='plain') |
|
|||
172 | else: |
|
|||
173 | spec = repo.svfs.read(FILENAME) |
|
|||
174 | repo.vfs.write(DIRSTATE_FILENAME, spec) |
|
|||
175 |
|
167 | |||
176 | def savebackup(repo, backupname): |
|
168 | def savebackup(repo, backupname): | |
177 | if repository.NARROW_REQUIREMENT not in repo.requirements: |
|
169 | if repository.NARROW_REQUIREMENT not in repo.requirements: | |
178 | return |
|
170 | return | |
179 | svfs = repo.svfs |
|
171 | svfs = repo.svfs | |
180 | svfs.tryunlink(backupname) |
|
172 | svfs.tryunlink(backupname) | |
181 | util.copyfile(svfs.join(FILENAME), svfs.join(backupname), hardlink=True) |
|
173 | util.copyfile(svfs.join(FILENAME), svfs.join(backupname), hardlink=True) | |
182 |
|
174 | |||
183 | def restorebackup(repo, backupname): |
|
175 | def restorebackup(repo, backupname): | |
184 | if repository.NARROW_REQUIREMENT not in repo.requirements: |
|
176 | if repository.NARROW_REQUIREMENT not in repo.requirements: | |
185 | return |
|
177 | return | |
186 | util.rename(repo.svfs.join(backupname), repo.svfs.join(FILENAME)) |
|
178 | util.rename(repo.svfs.join(backupname), repo.svfs.join(FILENAME)) | |
187 |
|
179 | |||
188 | def savewcbackup(repo, backupname): |
|
180 | def savewcbackup(repo, backupname): | |
189 | if repository.NARROW_REQUIREMENT not in repo.requirements: |
|
181 | if repository.NARROW_REQUIREMENT not in repo.requirements: | |
190 | return |
|
182 | return | |
191 | vfs = repo.vfs |
|
183 | vfs = repo.vfs | |
192 | vfs.tryunlink(backupname) |
|
184 | vfs.tryunlink(backupname) | |
193 | # It may not exist in old repos |
|
185 | # It may not exist in old repos | |
194 | if vfs.exists(DIRSTATE_FILENAME): |
|
186 | if vfs.exists(DIRSTATE_FILENAME): | |
195 | util.copyfile(vfs.join(DIRSTATE_FILENAME), vfs.join(backupname), |
|
187 | util.copyfile(vfs.join(DIRSTATE_FILENAME), vfs.join(backupname), | |
196 | hardlink=True) |
|
188 | hardlink=True) | |
197 |
|
189 | |||
198 | def restorewcbackup(repo, backupname): |
|
190 | def restorewcbackup(repo, backupname): | |
199 | if repository.NARROW_REQUIREMENT not in repo.requirements: |
|
191 | if repository.NARROW_REQUIREMENT not in repo.requirements: | |
200 | return |
|
192 | return | |
201 | util.rename(repo.vfs.join(backupname), repo.vfs.join(DIRSTATE_FILENAME)) |
|
193 | util.rename(repo.vfs.join(backupname), repo.vfs.join(DIRSTATE_FILENAME)) | |
202 |
|
194 | |||
203 | def clearwcbackup(repo, backupname): |
|
195 | def clearwcbackup(repo, backupname): | |
204 | if repository.NARROW_REQUIREMENT not in repo.requirements: |
|
196 | if repository.NARROW_REQUIREMENT not in repo.requirements: | |
205 | return |
|
197 | return | |
206 | repo.vfs.unlink(backupname) |
|
198 | repo.vfs.unlink(backupname) | |
207 |
|
199 | |||
208 | def restrictpatterns(req_includes, req_excludes, repo_includes, repo_excludes): |
|
200 | def restrictpatterns(req_includes, req_excludes, repo_includes, repo_excludes): | |
209 | r""" Restricts the patterns according to repo settings, |
|
201 | r""" Restricts the patterns according to repo settings, | |
210 | results in a logical AND operation |
|
202 | results in a logical AND operation | |
211 |
|
203 | |||
212 | :param req_includes: requested includes |
|
204 | :param req_includes: requested includes | |
213 | :param req_excludes: requested excludes |
|
205 | :param req_excludes: requested excludes | |
214 | :param repo_includes: repo includes |
|
206 | :param repo_includes: repo includes | |
215 | :param repo_excludes: repo excludes |
|
207 | :param repo_excludes: repo excludes | |
216 | :return: include patterns, exclude patterns, and invalid include patterns. |
|
208 | :return: include patterns, exclude patterns, and invalid include patterns. | |
217 |
|
209 | |||
218 | >>> restrictpatterns({'f1','f2'}, {}, ['f1'], []) |
|
210 | >>> restrictpatterns({'f1','f2'}, {}, ['f1'], []) | |
219 | (set(['f1']), {}, []) |
|
211 | (set(['f1']), {}, []) | |
220 | >>> restrictpatterns({'f1'}, {}, ['f1','f2'], []) |
|
212 | >>> restrictpatterns({'f1'}, {}, ['f1','f2'], []) | |
221 | (set(['f1']), {}, []) |
|
213 | (set(['f1']), {}, []) | |
222 | >>> restrictpatterns({'f1/fc1', 'f3/fc3'}, {}, ['f1','f2'], []) |
|
214 | >>> restrictpatterns({'f1/fc1', 'f3/fc3'}, {}, ['f1','f2'], []) | |
223 | (set(['f1/fc1']), {}, []) |
|
215 | (set(['f1/fc1']), {}, []) | |
224 | >>> restrictpatterns({'f1_fc1'}, {}, ['f1','f2'], []) |
|
216 | >>> restrictpatterns({'f1_fc1'}, {}, ['f1','f2'], []) | |
225 | ([], set(['path:.']), []) |
|
217 | ([], set(['path:.']), []) | |
226 | >>> restrictpatterns({'f1/../f2/fc2'}, {}, ['f1','f2'], []) |
|
218 | >>> restrictpatterns({'f1/../f2/fc2'}, {}, ['f1','f2'], []) | |
227 | (set(['f2/fc2']), {}, []) |
|
219 | (set(['f2/fc2']), {}, []) | |
228 | >>> restrictpatterns({'f1/../f3/fc3'}, {}, ['f1','f2'], []) |
|
220 | >>> restrictpatterns({'f1/../f3/fc3'}, {}, ['f1','f2'], []) | |
229 | ([], set(['path:.']), []) |
|
221 | ([], set(['path:.']), []) | |
230 | >>> restrictpatterns({'f1/$non_exitent_var'}, {}, ['f1','f2'], []) |
|
222 | >>> restrictpatterns({'f1/$non_exitent_var'}, {}, ['f1','f2'], []) | |
231 | (set(['f1/$non_exitent_var']), {}, []) |
|
223 | (set(['f1/$non_exitent_var']), {}, []) | |
232 | """ |
|
224 | """ | |
233 | res_excludes = set(req_excludes) |
|
225 | res_excludes = set(req_excludes) | |
234 | res_excludes.update(repo_excludes) |
|
226 | res_excludes.update(repo_excludes) | |
235 | invalid_includes = [] |
|
227 | invalid_includes = [] | |
236 | if not req_includes: |
|
228 | if not req_includes: | |
237 | res_includes = set(repo_includes) |
|
229 | res_includes = set(repo_includes) | |
238 | elif 'path:.' not in repo_includes: |
|
230 | elif 'path:.' not in repo_includes: | |
239 | res_includes = [] |
|
231 | res_includes = [] | |
240 | for req_include in req_includes: |
|
232 | for req_include in req_includes: | |
241 | req_include = util.expandpath(util.normpath(req_include)) |
|
233 | req_include = util.expandpath(util.normpath(req_include)) | |
242 | if req_include in repo_includes: |
|
234 | if req_include in repo_includes: | |
243 | res_includes.append(req_include) |
|
235 | res_includes.append(req_include) | |
244 | continue |
|
236 | continue | |
245 | valid = False |
|
237 | valid = False | |
246 | for repo_include in repo_includes: |
|
238 | for repo_include in repo_includes: | |
247 | if req_include.startswith(repo_include + '/'): |
|
239 | if req_include.startswith(repo_include + '/'): | |
248 | valid = True |
|
240 | valid = True | |
249 | res_includes.append(req_include) |
|
241 | res_includes.append(req_include) | |
250 | break |
|
242 | break | |
251 | if not valid: |
|
243 | if not valid: | |
252 | invalid_includes.append(req_include) |
|
244 | invalid_includes.append(req_include) | |
253 | if len(res_includes) == 0: |
|
245 | if len(res_includes) == 0: | |
254 | res_excludes = {'path:.'} |
|
246 | res_excludes = {'path:.'} | |
255 | else: |
|
247 | else: | |
256 | res_includes = set(res_includes) |
|
248 | res_includes = set(res_includes) | |
257 | else: |
|
249 | else: | |
258 | res_includes = set(req_includes) |
|
250 | res_includes = set(req_includes) | |
259 | return res_includes, res_excludes, invalid_includes |
|
251 | return res_includes, res_excludes, invalid_includes | |
260 |
|
252 | |||
261 | # These two are extracted for extensions (specifically for Google's CitC file |
|
253 | # These two are extracted for extensions (specifically for Google's CitC file | |
262 | # system) |
|
254 | # system) | |
263 | def _deletecleanfiles(repo, files): |
|
255 | def _deletecleanfiles(repo, files): | |
264 | for f in files: |
|
256 | for f in files: | |
265 | repo.wvfs.unlinkpath(f) |
|
257 | repo.wvfs.unlinkpath(f) | |
266 |
|
258 | |||
267 | def _writeaddedfiles(repo, pctx, files): |
|
259 | def _writeaddedfiles(repo, pctx, files): | |
268 | actions = merge.emptyactions() |
|
260 | actions = merge.emptyactions() | |
269 | addgaction = actions[merge.ACTION_GET].append |
|
261 | addgaction = actions[merge.ACTION_GET].append | |
270 | mf = repo['.'].manifest() |
|
262 | mf = repo['.'].manifest() | |
271 | for f in files: |
|
263 | for f in files: | |
272 | if not repo.wvfs.exists(f): |
|
264 | if not repo.wvfs.exists(f): | |
273 | addgaction((f, (mf.flags(f), False), "narrowspec updated")) |
|
265 | addgaction((f, (mf.flags(f), False), "narrowspec updated")) | |
274 | merge.applyupdates(repo, actions, wctx=repo[None], |
|
266 | merge.applyupdates(repo, actions, wctx=repo[None], | |
275 | mctx=repo['.'], overwrite=False) |
|
267 | mctx=repo['.'], overwrite=False) | |
276 |
|
268 | |||
277 | def checkworkingcopynarrowspec(repo): |
|
269 | def checkworkingcopynarrowspec(repo): | |
278 | storespec = repo.svfs.tryread(FILENAME) |
|
270 | storespec = repo.svfs.tryread(FILENAME) | |
279 | wcspec = repo.vfs.tryread(DIRSTATE_FILENAME) |
|
271 | wcspec = repo.vfs.tryread(DIRSTATE_FILENAME) | |
280 | if wcspec != storespec: |
|
272 | if wcspec != storespec: | |
281 | raise error.Abort(_("working copy's narrowspec is stale"), |
|
273 | raise error.Abort(_("working copy's narrowspec is stale"), | |
282 | hint=_("run 'hg tracked --update-working-copy'")) |
|
274 | hint=_("run 'hg tracked --update-working-copy'")) | |
283 |
|
275 | |||
284 | def updateworkingcopy(repo): |
|
276 | def updateworkingcopy(repo): | |
285 | oldspec = repo.vfs.tryread(DIRSTATE_FILENAME) |
|
277 | oldspec = repo.vfs.tryread(DIRSTATE_FILENAME) | |
286 | newspec = repo.svfs.tryread(FILENAME) |
|
278 | newspec = repo.svfs.tryread(FILENAME) | |
287 |
|
279 | |||
288 | oldincludes, oldexcludes = parseconfig(repo.ui, oldspec) |
|
280 | oldincludes, oldexcludes = parseconfig(repo.ui, oldspec) | |
289 | newincludes, newexcludes = parseconfig(repo.ui, newspec) |
|
281 | newincludes, newexcludes = parseconfig(repo.ui, newspec) | |
290 | oldmatch = match(repo.root, include=oldincludes, exclude=oldexcludes) |
|
282 | oldmatch = match(repo.root, include=oldincludes, exclude=oldexcludes) | |
291 | newmatch = match(repo.root, include=newincludes, exclude=newexcludes) |
|
283 | newmatch = match(repo.root, include=newincludes, exclude=newexcludes) | |
292 | addedmatch = matchmod.differencematcher(newmatch, oldmatch) |
|
284 | addedmatch = matchmod.differencematcher(newmatch, oldmatch) | |
293 | removedmatch = matchmod.differencematcher(oldmatch, newmatch) |
|
285 | removedmatch = matchmod.differencematcher(oldmatch, newmatch) | |
294 |
|
286 | |||
295 | ds = repo.dirstate |
|
287 | ds = repo.dirstate | |
296 | lookup, status = ds.status(removedmatch, subrepos=[], ignored=False, |
|
288 | lookup, status = ds.status(removedmatch, subrepos=[], ignored=False, | |
297 | clean=True, unknown=False) |
|
289 | clean=True, unknown=False) | |
298 | _deletecleanfiles(repo, status.clean) |
|
290 | _deletecleanfiles(repo, status.clean) | |
299 | trackeddirty = lookup + status.modified + status.added |
|
291 | trackeddirty = lookup + status.modified + status.added | |
300 | for f in sorted(trackeddirty): |
|
292 | for f in sorted(trackeddirty): | |
301 | repo.ui.status(_('not deleting possibly dirty file %s\n') % f) |
|
293 | repo.ui.status(_('not deleting possibly dirty file %s\n') % f) | |
302 | for f in status.clean + trackeddirty: |
|
294 | for f in status.clean + trackeddirty: | |
303 | ds.drop(f) |
|
295 | ds.drop(f) | |
304 |
|
296 | |||
305 | repo.narrowpats = newincludes, newexcludes |
|
297 | repo.narrowpats = newincludes, newexcludes | |
306 | repo._narrowmatch = newmatch |
|
298 | repo._narrowmatch = newmatch | |
307 | pctx = repo['.'] |
|
299 | pctx = repo['.'] | |
308 | newfiles = [f for f in pctx.manifest().walk(addedmatch) if f not in ds] |
|
300 | newfiles = [f for f in pctx.manifest().walk(addedmatch) if f not in ds] | |
309 | for f in newfiles: |
|
301 | for f in newfiles: | |
310 | ds.normallookup(f) |
|
302 | ds.normallookup(f) | |
311 | _writeaddedfiles(repo, pctx, newfiles) |
|
303 | _writeaddedfiles(repo, pctx, newfiles) |
General Comments 0
You need to be logged in to leave comments.
Login now