##// END OF EJS Templates
py3: fix some membership tests on linkrev adjustment
Yuya Nishihara -
r36657:334da951 default
parent child Browse files
Show More
@@ -1,348 +1,349 b''
1 test-abort-checkin.t
1 test-abort-checkin.t
2 test-add.t
2 test-add.t
3 test-addremove-similar.t
3 test-addremove-similar.t
4 test-addremove.t
4 test-addremove.t
5 test-amend-subrepo.t
5 test-amend-subrepo.t
6 test-ancestor.py
6 test-ancestor.py
7 test-annotate.py
7 test-annotate.py
8 test-annotate.t
8 test-automv.t
9 test-automv.t
9 test-backout.t
10 test-backout.t
10 test-backwards-remove.t
11 test-backwards-remove.t
11 test-basic.t
12 test-basic.t
12 test-bheads.t
13 test-bheads.t
13 test-bisect2.t
14 test-bisect2.t
14 test-bookmarks-current.t
15 test-bookmarks-current.t
15 test-bookmarks-merge.t
16 test-bookmarks-merge.t
16 test-bookmarks-rebase.t
17 test-bookmarks-rebase.t
17 test-bookmarks-strip.t
18 test-bookmarks-strip.t
18 test-bookmarks.t
19 test-bookmarks.t
19 test-branch-option.t
20 test-branch-option.t
20 test-branch-tag-confict.t
21 test-branch-tag-confict.t
21 test-branches.t
22 test-branches.t
22 test-bundle-phases.t
23 test-bundle-phases.t
23 test-bundle-vs-outgoing.t
24 test-bundle-vs-outgoing.t
24 test-bundle2-multiple-changegroups.t
25 test-bundle2-multiple-changegroups.t
25 test-cappedreader.py
26 test-cappedreader.py
26 test-casecollision.t
27 test-casecollision.t
27 test-cat.t
28 test-cat.t
28 test-censor.t
29 test-censor.t
29 test-changelog-exec.t
30 test-changelog-exec.t
30 test-check-commit.t
31 test-check-commit.t
31 test-check-execute.t
32 test-check-execute.t
32 test-check-module-imports.t
33 test-check-module-imports.t
33 test-check-pyflakes.t
34 test-check-pyflakes.t
34 test-check-pylint.t
35 test-check-pylint.t
35 test-check-shbang.t
36 test-check-shbang.t
36 test-children.t
37 test-children.t
37 test-clone-pull-corruption.t
38 test-clone-pull-corruption.t
38 test-clone-r.t
39 test-clone-r.t
39 test-clone-update-order.t
40 test-clone-update-order.t
40 test-command-template.t
41 test-command-template.t
41 test-commit-amend.t
42 test-commit-amend.t
42 test-commit-unresolved.t
43 test-commit-unresolved.t
43 test-commit.t
44 test-commit.t
44 test-completion.t
45 test-completion.t
45 test-conflict.t
46 test-conflict.t
46 test-confused-revert.t
47 test-confused-revert.t
47 test-contrib-check-code.t
48 test-contrib-check-code.t
48 test-contrib-check-commit.t
49 test-contrib-check-commit.t
49 test-convert-authormap.t
50 test-convert-authormap.t
50 test-convert-clonebranches.t
51 test-convert-clonebranches.t
51 test-convert-datesort.t
52 test-convert-datesort.t
52 test-convert-filemap.t
53 test-convert-filemap.t
53 test-convert-hg-sink.t
54 test-convert-hg-sink.t
54 test-convert-hg-source.t
55 test-convert-hg-source.t
55 test-convert-hg-startrev.t
56 test-convert-hg-startrev.t
56 test-copy-move-merge.t
57 test-copy-move-merge.t
57 test-copytrace-heuristics.t
58 test-copytrace-heuristics.t
58 test-debugbuilddag.t
59 test-debugbuilddag.t
59 test-debugbundle.t
60 test-debugbundle.t
60 test-debugextensions.t
61 test-debugextensions.t
61 test-debugindexdot.t
62 test-debugindexdot.t
62 test-debugrename.t
63 test-debugrename.t
63 test-diff-binary-file.t
64 test-diff-binary-file.t
64 test-diff-change.t
65 test-diff-change.t
65 test-diff-copy-depth.t
66 test-diff-copy-depth.t
66 test-diff-hashes.t
67 test-diff-hashes.t
67 test-diff-issue2761.t
68 test-diff-issue2761.t
68 test-diff-newlines.t
69 test-diff-newlines.t
69 test-diff-reverse.t
70 test-diff-reverse.t
70 test-diff-subdir.t
71 test-diff-subdir.t
71 test-diffdir.t
72 test-diffdir.t
72 test-directaccess.t
73 test-directaccess.t
73 test-dirstate-backup.t
74 test-dirstate-backup.t
74 test-dirstate-nonnormalset.t
75 test-dirstate-nonnormalset.t
75 test-doctest.py
76 test-doctest.py
76 test-double-merge.t
77 test-double-merge.t
77 test-drawdag.t
78 test-drawdag.t
78 test-duplicateoptions.py
79 test-duplicateoptions.py
79 test-empty-dir.t
80 test-empty-dir.t
80 test-empty-file.t
81 test-empty-file.t
81 test-empty-group.t
82 test-empty-group.t
82 test-empty.t
83 test-empty.t
83 test-encoding-func.py
84 test-encoding-func.py
84 test-encoding.t
85 test-encoding.t
85 test-eol-add.t
86 test-eol-add.t
86 test-eol-clone.t
87 test-eol-clone.t
87 test-eol-tag.t
88 test-eol-tag.t
88 test-eol-update.t
89 test-eol-update.t
89 test-excessive-merge.t
90 test-excessive-merge.t
90 test-exchange-obsmarkers-case-A1.t
91 test-exchange-obsmarkers-case-A1.t
91 test-exchange-obsmarkers-case-A2.t
92 test-exchange-obsmarkers-case-A2.t
92 test-exchange-obsmarkers-case-A3.t
93 test-exchange-obsmarkers-case-A3.t
93 test-exchange-obsmarkers-case-A4.t
94 test-exchange-obsmarkers-case-A4.t
94 test-exchange-obsmarkers-case-A5.t
95 test-exchange-obsmarkers-case-A5.t
95 test-exchange-obsmarkers-case-A6.t
96 test-exchange-obsmarkers-case-A6.t
96 test-exchange-obsmarkers-case-A7.t
97 test-exchange-obsmarkers-case-A7.t
97 test-exchange-obsmarkers-case-B1.t
98 test-exchange-obsmarkers-case-B1.t
98 test-exchange-obsmarkers-case-B2.t
99 test-exchange-obsmarkers-case-B2.t
99 test-exchange-obsmarkers-case-B3.t
100 test-exchange-obsmarkers-case-B3.t
100 test-exchange-obsmarkers-case-B4.t
101 test-exchange-obsmarkers-case-B4.t
101 test-exchange-obsmarkers-case-B5.t
102 test-exchange-obsmarkers-case-B5.t
102 test-exchange-obsmarkers-case-B6.t
103 test-exchange-obsmarkers-case-B6.t
103 test-exchange-obsmarkers-case-B7.t
104 test-exchange-obsmarkers-case-B7.t
104 test-exchange-obsmarkers-case-C1.t
105 test-exchange-obsmarkers-case-C1.t
105 test-exchange-obsmarkers-case-C2.t
106 test-exchange-obsmarkers-case-C2.t
106 test-exchange-obsmarkers-case-C3.t
107 test-exchange-obsmarkers-case-C3.t
107 test-exchange-obsmarkers-case-C4.t
108 test-exchange-obsmarkers-case-C4.t
108 test-exchange-obsmarkers-case-D1.t
109 test-exchange-obsmarkers-case-D1.t
109 test-exchange-obsmarkers-case-D2.t
110 test-exchange-obsmarkers-case-D2.t
110 test-exchange-obsmarkers-case-D3.t
111 test-exchange-obsmarkers-case-D3.t
111 test-exchange-obsmarkers-case-D4.t
112 test-exchange-obsmarkers-case-D4.t
112 test-execute-bit.t
113 test-execute-bit.t
113 test-extdiff.t
114 test-extdiff.t
114 test-extra-filelog-entry.t
115 test-extra-filelog-entry.t
115 test-filebranch.t
116 test-filebranch.t
116 test-fileset-generated.t
117 test-fileset-generated.t
117 test-flags.t
118 test-flags.t
118 test-generaldelta.t
119 test-generaldelta.t
119 test-getbundle.t
120 test-getbundle.t
120 test-git-export.t
121 test-git-export.t
121 test-glog-topological.t
122 test-glog-topological.t
122 test-gpg.t
123 test-gpg.t
123 test-graft.t
124 test-graft.t
124 test-hghave.t
125 test-hghave.t
125 test-hgignore.t
126 test-hgignore.t
126 test-hgk.t
127 test-hgk.t
127 test-hgweb-removed.t
128 test-hgweb-removed.t
128 test-histedit-arguments.t
129 test-histedit-arguments.t
129 test-histedit-base.t
130 test-histedit-base.t
130 test-histedit-bookmark-motion.t
131 test-histedit-bookmark-motion.t
131 test-histedit-commute.t
132 test-histedit-commute.t
132 test-histedit-drop.t
133 test-histedit-drop.t
133 test-histedit-edit.t
134 test-histedit-edit.t
134 test-histedit-fold-non-commute.t
135 test-histedit-fold-non-commute.t
135 test-histedit-fold.t
136 test-histedit-fold.t
136 test-histedit-no-change.t
137 test-histedit-no-change.t
137 test-histedit-non-commute-abort.t
138 test-histedit-non-commute-abort.t
138 test-histedit-non-commute.t
139 test-histedit-non-commute.t
139 test-histedit-obsolete.t
140 test-histedit-obsolete.t
140 test-histedit-outgoing.t
141 test-histedit-outgoing.t
141 test-histedit-templates.t
142 test-histedit-templates.t
142 test-http-branchmap.t
143 test-http-branchmap.t
143 test-http-clone-r.t
144 test-http-clone-r.t
144 test-identify.t
145 test-identify.t
145 test-imports-checker.t
146 test-imports-checker.t
146 test-inherit-mode.t
147 test-inherit-mode.t
147 test-issue1089.t
148 test-issue1089.t
148 test-issue1102.t
149 test-issue1102.t
149 test-issue1175.t
150 test-issue1175.t
150 test-issue1306.t
151 test-issue1306.t
151 test-issue1438.t
152 test-issue1438.t
152 test-issue1502.t
153 test-issue1502.t
153 test-issue1802.t
154 test-issue1802.t
154 test-issue1877.t
155 test-issue1877.t
155 test-issue1993.t
156 test-issue1993.t
156 test-issue2137.t
157 test-issue2137.t
157 test-issue3084.t
158 test-issue3084.t
158 test-issue4074.t
159 test-issue4074.t
159 test-issue522.t
160 test-issue522.t
160 test-issue586.t
161 test-issue586.t
161 test-issue612.t
162 test-issue612.t
162 test-issue619.t
163 test-issue619.t
163 test-issue672.t
164 test-issue672.t
164 test-issue842.t
165 test-issue842.t
165 test-journal-exists.t
166 test-journal-exists.t
166 test-largefiles-small-disk.t
167 test-largefiles-small-disk.t
167 test-locate.t
168 test-locate.t
168 test-logexchange.t
169 test-logexchange.t
169 test-lrucachedict.py
170 test-lrucachedict.py
170 test-mactext.t
171 test-mactext.t
171 test-manifest-merging.t
172 test-manifest-merging.t
172 test-manifest.py
173 test-manifest.py
173 test-manifest.t
174 test-manifest.t
174 test-match.py
175 test-match.py
175 test-mdiff.py
176 test-mdiff.py
176 test-merge-closedheads.t
177 test-merge-closedheads.t
177 test-merge-commit.t
178 test-merge-commit.t
178 test-merge-criss-cross.t
179 test-merge-criss-cross.t
179 test-merge-default.t
180 test-merge-default.t
180 test-merge-internal-tools-pattern.t
181 test-merge-internal-tools-pattern.t
181 test-merge-local.t
182 test-merge-local.t
182 test-merge-remove.t
183 test-merge-remove.t
183 test-merge-revert.t
184 test-merge-revert.t
184 test-merge-revert2.t
185 test-merge-revert2.t
185 test-merge-subrepos.t
186 test-merge-subrepos.t
186 test-merge-symlinks.t
187 test-merge-symlinks.t
187 test-merge-types.t
188 test-merge-types.t
188 test-merge1.t
189 test-merge1.t
189 test-merge10.t
190 test-merge10.t
190 test-merge2.t
191 test-merge2.t
191 test-merge4.t
192 test-merge4.t
192 test-merge5.t
193 test-merge5.t
193 test-merge6.t
194 test-merge6.t
194 test-merge7.t
195 test-merge7.t
195 test-merge8.t
196 test-merge8.t
196 test-merge9.t
197 test-merge9.t
197 test-mq-git.t
198 test-mq-git.t
198 test-mq-pull-from-bundle.t
199 test-mq-pull-from-bundle.t
199 test-mq-qdiff.t
200 test-mq-qdiff.t
200 test-mq-qimport-fail-cleanup.t
201 test-mq-qimport-fail-cleanup.t
201 test-mq-qqueue.t
202 test-mq-qqueue.t
202 test-mq-qrefresh.t
203 test-mq-qrefresh.t
203 test-mq-qsave.t
204 test-mq-qsave.t
204 test-narrow-clone-no-ellipsis.t
205 test-narrow-clone-no-ellipsis.t
205 test-narrow-clone-nonlinear.t
206 test-narrow-clone-nonlinear.t
206 test-narrow-clone.t
207 test-narrow-clone.t
207 test-narrow-commit.t
208 test-narrow-commit.t
208 test-narrow-copies.t
209 test-narrow-copies.t
209 test-narrow-debugrebuilddirstate.t
210 test-narrow-debugrebuilddirstate.t
210 test-narrow-exchange-merges.t
211 test-narrow-exchange-merges.t
211 test-narrow-exchange.t
212 test-narrow-exchange.t
212 test-narrow-merge.t
213 test-narrow-merge.t
213 test-narrow-patch.t
214 test-narrow-patch.t
214 test-narrow-patterns.t
215 test-narrow-patterns.t
215 test-narrow-pull.t
216 test-narrow-pull.t
216 test-narrow-rebase.t
217 test-narrow-rebase.t
217 test-narrow-shallow-merges.t
218 test-narrow-shallow-merges.t
218 test-narrow-shallow.t
219 test-narrow-shallow.t
219 test-narrow-update.t
220 test-narrow-update.t
220 test-newbranch.t
221 test-newbranch.t
221 test-obshistory.t
222 test-obshistory.t
222 test-obsmarker-template.t
223 test-obsmarker-template.t
223 test-obsmarkers-effectflag.t
224 test-obsmarkers-effectflag.t
224 test-obsolete-bundle-strip.t
225 test-obsolete-bundle-strip.t
225 test-obsolete-changeset-exchange.t
226 test-obsolete-changeset-exchange.t
226 test-obsolete-checkheads.t
227 test-obsolete-checkheads.t
227 test-obsolete-distributed.t
228 test-obsolete-distributed.t
228 test-obsolete-tag-cache.t
229 test-obsolete-tag-cache.t
229 test-parents.t
230 test-parents.t
230 test-pathconflicts-merge.t
231 test-pathconflicts-merge.t
231 test-pathconflicts-update.t
232 test-pathconflicts-update.t
232 test-pending.t
233 test-pending.t
233 test-permissions.t
234 test-permissions.t
234 test-phases.t
235 test-phases.t
235 test-pull-branch.t
236 test-pull-branch.t
236 test-pull-http.t
237 test-pull-http.t
237 test-pull-permission.t
238 test-pull-permission.t
238 test-pull-pull-corruption.t
239 test-pull-pull-corruption.t
239 test-pull-r.t
240 test-pull-r.t
240 test-pull-update.t
241 test-pull-update.t
241 test-purge.t
242 test-purge.t
242 test-push-checkheads-partial-C1.t
243 test-push-checkheads-partial-C1.t
243 test-push-checkheads-partial-C2.t
244 test-push-checkheads-partial-C2.t
244 test-push-checkheads-partial-C3.t
245 test-push-checkheads-partial-C3.t
245 test-push-checkheads-partial-C4.t
246 test-push-checkheads-partial-C4.t
246 test-push-checkheads-pruned-B1.t
247 test-push-checkheads-pruned-B1.t
247 test-push-checkheads-pruned-B2.t
248 test-push-checkheads-pruned-B2.t
248 test-push-checkheads-pruned-B3.t
249 test-push-checkheads-pruned-B3.t
249 test-push-checkheads-pruned-B4.t
250 test-push-checkheads-pruned-B4.t
250 test-push-checkheads-pruned-B5.t
251 test-push-checkheads-pruned-B5.t
251 test-push-checkheads-pruned-B6.t
252 test-push-checkheads-pruned-B6.t
252 test-push-checkheads-pruned-B7.t
253 test-push-checkheads-pruned-B7.t
253 test-push-checkheads-pruned-B8.t
254 test-push-checkheads-pruned-B8.t
254 test-push-checkheads-superceed-A1.t
255 test-push-checkheads-superceed-A1.t
255 test-push-checkheads-superceed-A2.t
256 test-push-checkheads-superceed-A2.t
256 test-push-checkheads-superceed-A3.t
257 test-push-checkheads-superceed-A3.t
257 test-push-checkheads-superceed-A4.t
258 test-push-checkheads-superceed-A4.t
258 test-push-checkheads-superceed-A5.t
259 test-push-checkheads-superceed-A5.t
259 test-push-checkheads-superceed-A6.t
260 test-push-checkheads-superceed-A6.t
260 test-push-checkheads-superceed-A7.t
261 test-push-checkheads-superceed-A7.t
261 test-push-checkheads-superceed-A8.t
262 test-push-checkheads-superceed-A8.t
262 test-push-checkheads-unpushed-D1.t
263 test-push-checkheads-unpushed-D1.t
263 test-push-checkheads-unpushed-D2.t
264 test-push-checkheads-unpushed-D2.t
264 test-push-checkheads-unpushed-D3.t
265 test-push-checkheads-unpushed-D3.t
265 test-push-checkheads-unpushed-D4.t
266 test-push-checkheads-unpushed-D4.t
266 test-push-checkheads-unpushed-D5.t
267 test-push-checkheads-unpushed-D5.t
267 test-push-checkheads-unpushed-D6.t
268 test-push-checkheads-unpushed-D6.t
268 test-push-checkheads-unpushed-D7.t
269 test-push-checkheads-unpushed-D7.t
269 test-push-http.t
270 test-push-http.t
270 test-push-warn.t
271 test-push-warn.t
271 test-pushvars.t
272 test-pushvars.t
272 test-rebase-abort.t
273 test-rebase-abort.t
273 test-rebase-base-flag.t
274 test-rebase-base-flag.t
274 test-rebase-bookmarks.t
275 test-rebase-bookmarks.t
275 test-rebase-brute-force.t
276 test-rebase-brute-force.t
276 test-rebase-cache.t
277 test-rebase-cache.t
277 test-rebase-check-restore.t
278 test-rebase-check-restore.t
278 test-rebase-collapse.t
279 test-rebase-collapse.t
279 test-rebase-dest.t
280 test-rebase-dest.t
280 test-rebase-detach.t
281 test-rebase-detach.t
281 test-rebase-emptycommit.t
282 test-rebase-emptycommit.t
282 test-rebase-inmemory.t
283 test-rebase-inmemory.t
283 test-rebase-interruptions.t
284 test-rebase-interruptions.t
284 test-rebase-issue-noparam-single-rev.t
285 test-rebase-issue-noparam-single-rev.t
285 test-rebase-legacy.t
286 test-rebase-legacy.t
286 test-rebase-named-branches.t
287 test-rebase-named-branches.t
287 test-rebase-newancestor.t
288 test-rebase-newancestor.t
288 test-rebase-obsolete.t
289 test-rebase-obsolete.t
289 test-rebase-parameters.t
290 test-rebase-parameters.t
290 test-rebase-partial.t
291 test-rebase-partial.t
291 test-rebase-pull.t
292 test-rebase-pull.t
292 test-rebase-rename.t
293 test-rebase-rename.t
293 test-rebase-scenario-global.t
294 test-rebase-scenario-global.t
294 test-rebase-templates.t
295 test-rebase-templates.t
295 test-rebase-transaction.t
296 test-rebase-transaction.t
296 test-record.t
297 test-record.t
297 test-relink.t
298 test-relink.t
298 test-remove.t
299 test-remove.t
299 test-rename-after-merge.t
300 test-rename-after-merge.t
300 test-rename-dir-merge.t
301 test-rename-dir-merge.t
301 test-rename-merge1.t
302 test-rename-merge1.t
302 test-rename.t
303 test-rename.t
303 test-repair-strip.t
304 test-repair-strip.t
304 test-repo-compengines.t
305 test-repo-compengines.t
305 test-resolve.t
306 test-resolve.t
306 test-revert-flags.t
307 test-revert-flags.t
307 test-revert-unknown.t
308 test-revert-unknown.t
308 test-revlog-ancestry.py
309 test-revlog-ancestry.py
309 test-revlog-group-emptyiter.t
310 test-revlog-group-emptyiter.t
310 test-revlog-mmapindex.t
311 test-revlog-mmapindex.t
311 test-revlog-packentry.t
312 test-revlog-packentry.t
312 test-revset-dirstate-parents.t
313 test-revset-dirstate-parents.t
313 test-revset-outgoing.t
314 test-revset-outgoing.t
314 test-run-tests.py
315 test-run-tests.py
315 test-serve.t
316 test-serve.t
316 test-share.t
317 test-share.t
317 test-show-stack.t
318 test-show-stack.t
318 test-show-work.t
319 test-show-work.t
319 test-show.t
320 test-show.t
320 test-simple-update.t
321 test-simple-update.t
321 test-single-head.t
322 test-single-head.t
322 test-sparse-clear.t
323 test-sparse-clear.t
323 test-sparse-merges.t
324 test-sparse-merges.t
324 test-sparse-requirement.t
325 test-sparse-requirement.t
325 test-sparse-verbose-json.t
326 test-sparse-verbose-json.t
326 test-ssh-clone-r.t
327 test-ssh-clone-r.t
327 test-ssh-proto.t
328 test-ssh-proto.t
328 test-sshserver.py
329 test-sshserver.py
329 test-status-rev.t
330 test-status-rev.t
330 test-status-terse.t
331 test-status-terse.t
331 test-strip-cross.t
332 test-strip-cross.t
332 test-strip.t
333 test-strip.t
333 test-unamend.t
334 test-unamend.t
334 test-uncommit.t
335 test-uncommit.t
335 test-unified-test.t
336 test-unified-test.t
336 test-unrelated-pull.t
337 test-unrelated-pull.t
337 test-up-local-change.t
338 test-up-local-change.t
338 test-update-branches.t
339 test-update-branches.t
339 test-update-dest.t
340 test-update-dest.t
340 test-update-issue1456.t
341 test-update-issue1456.t
341 test-update-names.t
342 test-update-names.t
342 test-update-reverse.t
343 test-update-reverse.t
343 test-url-rev.t
344 test-url-rev.t
344 test-username-newline.t
345 test-username-newline.t
345 test-verify.t
346 test-verify.t
346 test-websub.t
347 test-websub.t
347 test-win32text.t
348 test-win32text.t
348 test-xdg.t
349 test-xdg.t
@@ -1,2748 +1,2748 b''
1 # context.py - changeset and file context objects for mercurial
1 # context.py - changeset and file context objects for mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 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 filecmp
11 import filecmp
12 import os
12 import os
13 import re
13 import re
14 import stat
14 import stat
15
15
16 from .i18n import _
16 from .i18n import _
17 from .node import (
17 from .node import (
18 addednodeid,
18 addednodeid,
19 bin,
19 bin,
20 hex,
20 hex,
21 modifiednodeid,
21 modifiednodeid,
22 nullid,
22 nullid,
23 nullrev,
23 nullrev,
24 short,
24 short,
25 wdirid,
25 wdirid,
26 wdirnodes,
26 wdirnodes,
27 wdirrev,
27 wdirrev,
28 )
28 )
29 from .thirdparty import (
29 from .thirdparty import (
30 attr,
30 attr,
31 )
31 )
32 from . import (
32 from . import (
33 encoding,
33 encoding,
34 error,
34 error,
35 fileset,
35 fileset,
36 match as matchmod,
36 match as matchmod,
37 mdiff,
37 mdiff,
38 obsolete as obsmod,
38 obsolete as obsmod,
39 obsutil,
39 obsutil,
40 patch,
40 patch,
41 pathutil,
41 pathutil,
42 phases,
42 phases,
43 pycompat,
43 pycompat,
44 repoview,
44 repoview,
45 revlog,
45 revlog,
46 scmutil,
46 scmutil,
47 sparse,
47 sparse,
48 subrepo,
48 subrepo,
49 subrepoutil,
49 subrepoutil,
50 util,
50 util,
51 )
51 )
52 from .utils import dateutil
52 from .utils import dateutil
53
53
54 propertycache = util.propertycache
54 propertycache = util.propertycache
55
55
56 nonascii = re.compile(r'[^\x21-\x7f]').search
56 nonascii = re.compile(r'[^\x21-\x7f]').search
57
57
58 class basectx(object):
58 class basectx(object):
59 """A basectx object represents the common logic for its children:
59 """A basectx object represents the common logic for its children:
60 changectx: read-only context that is already present in the repo,
60 changectx: read-only context that is already present in the repo,
61 workingctx: a context that represents the working directory and can
61 workingctx: a context that represents the working directory and can
62 be committed,
62 be committed,
63 memctx: a context that represents changes in-memory and can also
63 memctx: a context that represents changes in-memory and can also
64 be committed."""
64 be committed."""
65 def __new__(cls, repo, changeid='', *args, **kwargs):
65 def __new__(cls, repo, changeid='', *args, **kwargs):
66 if isinstance(changeid, basectx):
66 if isinstance(changeid, basectx):
67 return changeid
67 return changeid
68
68
69 o = super(basectx, cls).__new__(cls)
69 o = super(basectx, cls).__new__(cls)
70
70
71 o._repo = repo
71 o._repo = repo
72 o._rev = nullrev
72 o._rev = nullrev
73 o._node = nullid
73 o._node = nullid
74
74
75 return o
75 return o
76
76
77 def __bytes__(self):
77 def __bytes__(self):
78 return short(self.node())
78 return short(self.node())
79
79
80 __str__ = encoding.strmethod(__bytes__)
80 __str__ = encoding.strmethod(__bytes__)
81
81
82 def __repr__(self):
82 def __repr__(self):
83 return r"<%s %s>" % (type(self).__name__, str(self))
83 return r"<%s %s>" % (type(self).__name__, str(self))
84
84
85 def __eq__(self, other):
85 def __eq__(self, other):
86 try:
86 try:
87 return type(self) == type(other) and self._rev == other._rev
87 return type(self) == type(other) and self._rev == other._rev
88 except AttributeError:
88 except AttributeError:
89 return False
89 return False
90
90
91 def __ne__(self, other):
91 def __ne__(self, other):
92 return not (self == other)
92 return not (self == other)
93
93
94 def __contains__(self, key):
94 def __contains__(self, key):
95 return key in self._manifest
95 return key in self._manifest
96
96
97 def __getitem__(self, key):
97 def __getitem__(self, key):
98 return self.filectx(key)
98 return self.filectx(key)
99
99
100 def __iter__(self):
100 def __iter__(self):
101 return iter(self._manifest)
101 return iter(self._manifest)
102
102
103 def _buildstatusmanifest(self, status):
103 def _buildstatusmanifest(self, status):
104 """Builds a manifest that includes the given status results, if this is
104 """Builds a manifest that includes the given status results, if this is
105 a working copy context. For non-working copy contexts, it just returns
105 a working copy context. For non-working copy contexts, it just returns
106 the normal manifest."""
106 the normal manifest."""
107 return self.manifest()
107 return self.manifest()
108
108
109 def _matchstatus(self, other, match):
109 def _matchstatus(self, other, match):
110 """This internal method provides a way for child objects to override the
110 """This internal method provides a way for child objects to override the
111 match operator.
111 match operator.
112 """
112 """
113 return match
113 return match
114
114
115 def _buildstatus(self, other, s, match, listignored, listclean,
115 def _buildstatus(self, other, s, match, listignored, listclean,
116 listunknown):
116 listunknown):
117 """build a status with respect to another context"""
117 """build a status with respect to another context"""
118 # Load earliest manifest first for caching reasons. More specifically,
118 # Load earliest manifest first for caching reasons. More specifically,
119 # if you have revisions 1000 and 1001, 1001 is probably stored as a
119 # if you have revisions 1000 and 1001, 1001 is probably stored as a
120 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
120 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
121 # 1000 and cache it so that when you read 1001, we just need to apply a
121 # 1000 and cache it so that when you read 1001, we just need to apply a
122 # delta to what's in the cache. So that's one full reconstruction + one
122 # delta to what's in the cache. So that's one full reconstruction + one
123 # delta application.
123 # delta application.
124 mf2 = None
124 mf2 = None
125 if self.rev() is not None and self.rev() < other.rev():
125 if self.rev() is not None and self.rev() < other.rev():
126 mf2 = self._buildstatusmanifest(s)
126 mf2 = self._buildstatusmanifest(s)
127 mf1 = other._buildstatusmanifest(s)
127 mf1 = other._buildstatusmanifest(s)
128 if mf2 is None:
128 if mf2 is None:
129 mf2 = self._buildstatusmanifest(s)
129 mf2 = self._buildstatusmanifest(s)
130
130
131 modified, added = [], []
131 modified, added = [], []
132 removed = []
132 removed = []
133 clean = []
133 clean = []
134 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
134 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
135 deletedset = set(deleted)
135 deletedset = set(deleted)
136 d = mf1.diff(mf2, match=match, clean=listclean)
136 d = mf1.diff(mf2, match=match, clean=listclean)
137 for fn, value in d.iteritems():
137 for fn, value in d.iteritems():
138 if fn in deletedset:
138 if fn in deletedset:
139 continue
139 continue
140 if value is None:
140 if value is None:
141 clean.append(fn)
141 clean.append(fn)
142 continue
142 continue
143 (node1, flag1), (node2, flag2) = value
143 (node1, flag1), (node2, flag2) = value
144 if node1 is None:
144 if node1 is None:
145 added.append(fn)
145 added.append(fn)
146 elif node2 is None:
146 elif node2 is None:
147 removed.append(fn)
147 removed.append(fn)
148 elif flag1 != flag2:
148 elif flag1 != flag2:
149 modified.append(fn)
149 modified.append(fn)
150 elif node2 not in wdirnodes:
150 elif node2 not in wdirnodes:
151 # When comparing files between two commits, we save time by
151 # When comparing files between two commits, we save time by
152 # not comparing the file contents when the nodeids differ.
152 # not comparing the file contents when the nodeids differ.
153 # Note that this means we incorrectly report a reverted change
153 # Note that this means we incorrectly report a reverted change
154 # to a file as a modification.
154 # to a file as a modification.
155 modified.append(fn)
155 modified.append(fn)
156 elif self[fn].cmp(other[fn]):
156 elif self[fn].cmp(other[fn]):
157 modified.append(fn)
157 modified.append(fn)
158 else:
158 else:
159 clean.append(fn)
159 clean.append(fn)
160
160
161 if removed:
161 if removed:
162 # need to filter files if they are already reported as removed
162 # need to filter files if they are already reported as removed
163 unknown = [fn for fn in unknown if fn not in mf1 and
163 unknown = [fn for fn in unknown if fn not in mf1 and
164 (not match or match(fn))]
164 (not match or match(fn))]
165 ignored = [fn for fn in ignored if fn not in mf1 and
165 ignored = [fn for fn in ignored if fn not in mf1 and
166 (not match or match(fn))]
166 (not match or match(fn))]
167 # if they're deleted, don't report them as removed
167 # if they're deleted, don't report them as removed
168 removed = [fn for fn in removed if fn not in deletedset]
168 removed = [fn for fn in removed if fn not in deletedset]
169
169
170 return scmutil.status(modified, added, removed, deleted, unknown,
170 return scmutil.status(modified, added, removed, deleted, unknown,
171 ignored, clean)
171 ignored, clean)
172
172
173 @propertycache
173 @propertycache
174 def substate(self):
174 def substate(self):
175 return subrepoutil.state(self, self._repo.ui)
175 return subrepoutil.state(self, self._repo.ui)
176
176
177 def subrev(self, subpath):
177 def subrev(self, subpath):
178 return self.substate[subpath][1]
178 return self.substate[subpath][1]
179
179
180 def rev(self):
180 def rev(self):
181 return self._rev
181 return self._rev
182 def node(self):
182 def node(self):
183 return self._node
183 return self._node
184 def hex(self):
184 def hex(self):
185 return hex(self.node())
185 return hex(self.node())
186 def manifest(self):
186 def manifest(self):
187 return self._manifest
187 return self._manifest
188 def manifestctx(self):
188 def manifestctx(self):
189 return self._manifestctx
189 return self._manifestctx
190 def repo(self):
190 def repo(self):
191 return self._repo
191 return self._repo
192 def phasestr(self):
192 def phasestr(self):
193 return phases.phasenames[self.phase()]
193 return phases.phasenames[self.phase()]
194 def mutable(self):
194 def mutable(self):
195 return self.phase() > phases.public
195 return self.phase() > phases.public
196
196
197 def getfileset(self, expr):
197 def getfileset(self, expr):
198 return fileset.getfileset(self, expr)
198 return fileset.getfileset(self, expr)
199
199
200 def obsolete(self):
200 def obsolete(self):
201 """True if the changeset is obsolete"""
201 """True if the changeset is obsolete"""
202 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
202 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
203
203
204 def extinct(self):
204 def extinct(self):
205 """True if the changeset is extinct"""
205 """True if the changeset is extinct"""
206 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
206 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
207
207
208 def orphan(self):
208 def orphan(self):
209 """True if the changeset is not obsolete but it's ancestor are"""
209 """True if the changeset is not obsolete but it's ancestor are"""
210 return self.rev() in obsmod.getrevs(self._repo, 'orphan')
210 return self.rev() in obsmod.getrevs(self._repo, 'orphan')
211
211
212 def phasedivergent(self):
212 def phasedivergent(self):
213 """True if the changeset try to be a successor of a public changeset
213 """True if the changeset try to be a successor of a public changeset
214
214
215 Only non-public and non-obsolete changesets may be bumped.
215 Only non-public and non-obsolete changesets may be bumped.
216 """
216 """
217 return self.rev() in obsmod.getrevs(self._repo, 'phasedivergent')
217 return self.rev() in obsmod.getrevs(self._repo, 'phasedivergent')
218
218
219 def contentdivergent(self):
219 def contentdivergent(self):
220 """Is a successors of a changeset with multiple possible successors set
220 """Is a successors of a changeset with multiple possible successors set
221
221
222 Only non-public and non-obsolete changesets may be divergent.
222 Only non-public and non-obsolete changesets may be divergent.
223 """
223 """
224 return self.rev() in obsmod.getrevs(self._repo, 'contentdivergent')
224 return self.rev() in obsmod.getrevs(self._repo, 'contentdivergent')
225
225
226 def isunstable(self):
226 def isunstable(self):
227 """True if the changeset is either unstable, bumped or divergent"""
227 """True if the changeset is either unstable, bumped or divergent"""
228 return self.orphan() or self.phasedivergent() or self.contentdivergent()
228 return self.orphan() or self.phasedivergent() or self.contentdivergent()
229
229
230 def instabilities(self):
230 def instabilities(self):
231 """return the list of instabilities affecting this changeset.
231 """return the list of instabilities affecting this changeset.
232
232
233 Instabilities are returned as strings. possible values are:
233 Instabilities are returned as strings. possible values are:
234 - orphan,
234 - orphan,
235 - phase-divergent,
235 - phase-divergent,
236 - content-divergent.
236 - content-divergent.
237 """
237 """
238 instabilities = []
238 instabilities = []
239 if self.orphan():
239 if self.orphan():
240 instabilities.append('orphan')
240 instabilities.append('orphan')
241 if self.phasedivergent():
241 if self.phasedivergent():
242 instabilities.append('phase-divergent')
242 instabilities.append('phase-divergent')
243 if self.contentdivergent():
243 if self.contentdivergent():
244 instabilities.append('content-divergent')
244 instabilities.append('content-divergent')
245 return instabilities
245 return instabilities
246
246
247 def parents(self):
247 def parents(self):
248 """return contexts for each parent changeset"""
248 """return contexts for each parent changeset"""
249 return self._parents
249 return self._parents
250
250
251 def p1(self):
251 def p1(self):
252 return self._parents[0]
252 return self._parents[0]
253
253
254 def p2(self):
254 def p2(self):
255 parents = self._parents
255 parents = self._parents
256 if len(parents) == 2:
256 if len(parents) == 2:
257 return parents[1]
257 return parents[1]
258 return changectx(self._repo, nullrev)
258 return changectx(self._repo, nullrev)
259
259
260 def _fileinfo(self, path):
260 def _fileinfo(self, path):
261 if r'_manifest' in self.__dict__:
261 if r'_manifest' in self.__dict__:
262 try:
262 try:
263 return self._manifest[path], self._manifest.flags(path)
263 return self._manifest[path], self._manifest.flags(path)
264 except KeyError:
264 except KeyError:
265 raise error.ManifestLookupError(self._node, path,
265 raise error.ManifestLookupError(self._node, path,
266 _('not found in manifest'))
266 _('not found in manifest'))
267 if r'_manifestdelta' in self.__dict__ or path in self.files():
267 if r'_manifestdelta' in self.__dict__ or path in self.files():
268 if path in self._manifestdelta:
268 if path in self._manifestdelta:
269 return (self._manifestdelta[path],
269 return (self._manifestdelta[path],
270 self._manifestdelta.flags(path))
270 self._manifestdelta.flags(path))
271 mfl = self._repo.manifestlog
271 mfl = self._repo.manifestlog
272 try:
272 try:
273 node, flag = mfl[self._changeset.manifest].find(path)
273 node, flag = mfl[self._changeset.manifest].find(path)
274 except KeyError:
274 except KeyError:
275 raise error.ManifestLookupError(self._node, path,
275 raise error.ManifestLookupError(self._node, path,
276 _('not found in manifest'))
276 _('not found in manifest'))
277
277
278 return node, flag
278 return node, flag
279
279
280 def filenode(self, path):
280 def filenode(self, path):
281 return self._fileinfo(path)[0]
281 return self._fileinfo(path)[0]
282
282
283 def flags(self, path):
283 def flags(self, path):
284 try:
284 try:
285 return self._fileinfo(path)[1]
285 return self._fileinfo(path)[1]
286 except error.LookupError:
286 except error.LookupError:
287 return ''
287 return ''
288
288
289 def sub(self, path, allowcreate=True):
289 def sub(self, path, allowcreate=True):
290 '''return a subrepo for the stored revision of path, never wdir()'''
290 '''return a subrepo for the stored revision of path, never wdir()'''
291 return subrepo.subrepo(self, path, allowcreate=allowcreate)
291 return subrepo.subrepo(self, path, allowcreate=allowcreate)
292
292
293 def nullsub(self, path, pctx):
293 def nullsub(self, path, pctx):
294 return subrepo.nullsubrepo(self, path, pctx)
294 return subrepo.nullsubrepo(self, path, pctx)
295
295
296 def workingsub(self, path):
296 def workingsub(self, path):
297 '''return a subrepo for the stored revision, or wdir if this is a wdir
297 '''return a subrepo for the stored revision, or wdir if this is a wdir
298 context.
298 context.
299 '''
299 '''
300 return subrepo.subrepo(self, path, allowwdir=True)
300 return subrepo.subrepo(self, path, allowwdir=True)
301
301
302 def match(self, pats=None, include=None, exclude=None, default='glob',
302 def match(self, pats=None, include=None, exclude=None, default='glob',
303 listsubrepos=False, badfn=None):
303 listsubrepos=False, badfn=None):
304 r = self._repo
304 r = self._repo
305 return matchmod.match(r.root, r.getcwd(), pats,
305 return matchmod.match(r.root, r.getcwd(), pats,
306 include, exclude, default,
306 include, exclude, default,
307 auditor=r.nofsauditor, ctx=self,
307 auditor=r.nofsauditor, ctx=self,
308 listsubrepos=listsubrepos, badfn=badfn)
308 listsubrepos=listsubrepos, badfn=badfn)
309
309
310 def diff(self, ctx2=None, match=None, **opts):
310 def diff(self, ctx2=None, match=None, **opts):
311 """Returns a diff generator for the given contexts and matcher"""
311 """Returns a diff generator for the given contexts and matcher"""
312 if ctx2 is None:
312 if ctx2 is None:
313 ctx2 = self.p1()
313 ctx2 = self.p1()
314 if ctx2 is not None:
314 if ctx2 is not None:
315 ctx2 = self._repo[ctx2]
315 ctx2 = self._repo[ctx2]
316 diffopts = patch.diffopts(self._repo.ui, pycompat.byteskwargs(opts))
316 diffopts = patch.diffopts(self._repo.ui, pycompat.byteskwargs(opts))
317 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
317 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
318
318
319 def dirs(self):
319 def dirs(self):
320 return self._manifest.dirs()
320 return self._manifest.dirs()
321
321
322 def hasdir(self, dir):
322 def hasdir(self, dir):
323 return self._manifest.hasdir(dir)
323 return self._manifest.hasdir(dir)
324
324
325 def status(self, other=None, match=None, listignored=False,
325 def status(self, other=None, match=None, listignored=False,
326 listclean=False, listunknown=False, listsubrepos=False):
326 listclean=False, listunknown=False, listsubrepos=False):
327 """return status of files between two nodes or node and working
327 """return status of files between two nodes or node and working
328 directory.
328 directory.
329
329
330 If other is None, compare this node with working directory.
330 If other is None, compare this node with working directory.
331
331
332 returns (modified, added, removed, deleted, unknown, ignored, clean)
332 returns (modified, added, removed, deleted, unknown, ignored, clean)
333 """
333 """
334
334
335 ctx1 = self
335 ctx1 = self
336 ctx2 = self._repo[other]
336 ctx2 = self._repo[other]
337
337
338 # This next code block is, admittedly, fragile logic that tests for
338 # This next code block is, admittedly, fragile logic that tests for
339 # reversing the contexts and wouldn't need to exist if it weren't for
339 # reversing the contexts and wouldn't need to exist if it weren't for
340 # the fast (and common) code path of comparing the working directory
340 # the fast (and common) code path of comparing the working directory
341 # with its first parent.
341 # with its first parent.
342 #
342 #
343 # What we're aiming for here is the ability to call:
343 # What we're aiming for here is the ability to call:
344 #
344 #
345 # workingctx.status(parentctx)
345 # workingctx.status(parentctx)
346 #
346 #
347 # If we always built the manifest for each context and compared those,
347 # If we always built the manifest for each context and compared those,
348 # then we'd be done. But the special case of the above call means we
348 # then we'd be done. But the special case of the above call means we
349 # just copy the manifest of the parent.
349 # just copy the manifest of the parent.
350 reversed = False
350 reversed = False
351 if (not isinstance(ctx1, changectx)
351 if (not isinstance(ctx1, changectx)
352 and isinstance(ctx2, changectx)):
352 and isinstance(ctx2, changectx)):
353 reversed = True
353 reversed = True
354 ctx1, ctx2 = ctx2, ctx1
354 ctx1, ctx2 = ctx2, ctx1
355
355
356 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
356 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
357 match = ctx2._matchstatus(ctx1, match)
357 match = ctx2._matchstatus(ctx1, match)
358 r = scmutil.status([], [], [], [], [], [], [])
358 r = scmutil.status([], [], [], [], [], [], [])
359 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
359 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
360 listunknown)
360 listunknown)
361
361
362 if reversed:
362 if reversed:
363 # Reverse added and removed. Clear deleted, unknown and ignored as
363 # Reverse added and removed. Clear deleted, unknown and ignored as
364 # these make no sense to reverse.
364 # these make no sense to reverse.
365 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
365 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
366 r.clean)
366 r.clean)
367
367
368 if listsubrepos:
368 if listsubrepos:
369 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
369 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
370 try:
370 try:
371 rev2 = ctx2.subrev(subpath)
371 rev2 = ctx2.subrev(subpath)
372 except KeyError:
372 except KeyError:
373 # A subrepo that existed in node1 was deleted between
373 # A subrepo that existed in node1 was deleted between
374 # node1 and node2 (inclusive). Thus, ctx2's substate
374 # node1 and node2 (inclusive). Thus, ctx2's substate
375 # won't contain that subpath. The best we can do ignore it.
375 # won't contain that subpath. The best we can do ignore it.
376 rev2 = None
376 rev2 = None
377 submatch = matchmod.subdirmatcher(subpath, match)
377 submatch = matchmod.subdirmatcher(subpath, match)
378 s = sub.status(rev2, match=submatch, ignored=listignored,
378 s = sub.status(rev2, match=submatch, ignored=listignored,
379 clean=listclean, unknown=listunknown,
379 clean=listclean, unknown=listunknown,
380 listsubrepos=True)
380 listsubrepos=True)
381 for rfiles, sfiles in zip(r, s):
381 for rfiles, sfiles in zip(r, s):
382 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
382 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
383
383
384 for l in r:
384 for l in r:
385 l.sort()
385 l.sort()
386
386
387 return r
387 return r
388
388
389 def _filterederror(repo, changeid):
389 def _filterederror(repo, changeid):
390 """build an exception to be raised about a filtered changeid
390 """build an exception to be raised about a filtered changeid
391
391
392 This is extracted in a function to help extensions (eg: evolve) to
392 This is extracted in a function to help extensions (eg: evolve) to
393 experiment with various message variants."""
393 experiment with various message variants."""
394 if repo.filtername.startswith('visible'):
394 if repo.filtername.startswith('visible'):
395
395
396 # Check if the changeset is obsolete
396 # Check if the changeset is obsolete
397 unfilteredrepo = repo.unfiltered()
397 unfilteredrepo = repo.unfiltered()
398 ctx = unfilteredrepo[changeid]
398 ctx = unfilteredrepo[changeid]
399
399
400 # If the changeset is obsolete, enrich the message with the reason
400 # If the changeset is obsolete, enrich the message with the reason
401 # that made this changeset not visible
401 # that made this changeset not visible
402 if ctx.obsolete():
402 if ctx.obsolete():
403 msg = obsutil._getfilteredreason(repo, changeid, ctx)
403 msg = obsutil._getfilteredreason(repo, changeid, ctx)
404 else:
404 else:
405 msg = _("hidden revision '%s'") % changeid
405 msg = _("hidden revision '%s'") % changeid
406
406
407 hint = _('use --hidden to access hidden revisions')
407 hint = _('use --hidden to access hidden revisions')
408
408
409 return error.FilteredRepoLookupError(msg, hint=hint)
409 return error.FilteredRepoLookupError(msg, hint=hint)
410 msg = _("filtered revision '%s' (not in '%s' subset)")
410 msg = _("filtered revision '%s' (not in '%s' subset)")
411 msg %= (changeid, repo.filtername)
411 msg %= (changeid, repo.filtername)
412 return error.FilteredRepoLookupError(msg)
412 return error.FilteredRepoLookupError(msg)
413
413
414 class changectx(basectx):
414 class changectx(basectx):
415 """A changecontext object makes access to data related to a particular
415 """A changecontext object makes access to data related to a particular
416 changeset convenient. It represents a read-only context already present in
416 changeset convenient. It represents a read-only context already present in
417 the repo."""
417 the repo."""
418 def __init__(self, repo, changeid=''):
418 def __init__(self, repo, changeid=''):
419 """changeid is a revision number, node, or tag"""
419 """changeid is a revision number, node, or tag"""
420
420
421 # since basectx.__new__ already took care of copying the object, we
421 # since basectx.__new__ already took care of copying the object, we
422 # don't need to do anything in __init__, so we just exit here
422 # don't need to do anything in __init__, so we just exit here
423 if isinstance(changeid, basectx):
423 if isinstance(changeid, basectx):
424 return
424 return
425
425
426 if changeid == '':
426 if changeid == '':
427 changeid = '.'
427 changeid = '.'
428 self._repo = repo
428 self._repo = repo
429
429
430 try:
430 try:
431 if isinstance(changeid, int):
431 if isinstance(changeid, int):
432 self._node = repo.changelog.node(changeid)
432 self._node = repo.changelog.node(changeid)
433 self._rev = changeid
433 self._rev = changeid
434 return
434 return
435 if not pycompat.ispy3 and isinstance(changeid, long):
435 if not pycompat.ispy3 and isinstance(changeid, long):
436 changeid = str(changeid)
436 changeid = str(changeid)
437 if changeid == 'null':
437 if changeid == 'null':
438 self._node = nullid
438 self._node = nullid
439 self._rev = nullrev
439 self._rev = nullrev
440 return
440 return
441 if changeid == 'tip':
441 if changeid == 'tip':
442 self._node = repo.changelog.tip()
442 self._node = repo.changelog.tip()
443 self._rev = repo.changelog.rev(self._node)
443 self._rev = repo.changelog.rev(self._node)
444 return
444 return
445 if (changeid == '.'
445 if (changeid == '.'
446 or repo.local() and changeid == repo.dirstate.p1()):
446 or repo.local() and changeid == repo.dirstate.p1()):
447 # this is a hack to delay/avoid loading obsmarkers
447 # this is a hack to delay/avoid loading obsmarkers
448 # when we know that '.' won't be hidden
448 # when we know that '.' won't be hidden
449 self._node = repo.dirstate.p1()
449 self._node = repo.dirstate.p1()
450 self._rev = repo.unfiltered().changelog.rev(self._node)
450 self._rev = repo.unfiltered().changelog.rev(self._node)
451 return
451 return
452 if len(changeid) == 20:
452 if len(changeid) == 20:
453 try:
453 try:
454 self._node = changeid
454 self._node = changeid
455 self._rev = repo.changelog.rev(changeid)
455 self._rev = repo.changelog.rev(changeid)
456 return
456 return
457 except error.FilteredRepoLookupError:
457 except error.FilteredRepoLookupError:
458 raise
458 raise
459 except LookupError:
459 except LookupError:
460 pass
460 pass
461
461
462 try:
462 try:
463 r = int(changeid)
463 r = int(changeid)
464 if '%d' % r != changeid:
464 if '%d' % r != changeid:
465 raise ValueError
465 raise ValueError
466 l = len(repo.changelog)
466 l = len(repo.changelog)
467 if r < 0:
467 if r < 0:
468 r += l
468 r += l
469 if r < 0 or r >= l and r != wdirrev:
469 if r < 0 or r >= l and r != wdirrev:
470 raise ValueError
470 raise ValueError
471 self._rev = r
471 self._rev = r
472 self._node = repo.changelog.node(r)
472 self._node = repo.changelog.node(r)
473 return
473 return
474 except error.FilteredIndexError:
474 except error.FilteredIndexError:
475 raise
475 raise
476 except (ValueError, OverflowError, IndexError):
476 except (ValueError, OverflowError, IndexError):
477 pass
477 pass
478
478
479 if len(changeid) == 40:
479 if len(changeid) == 40:
480 try:
480 try:
481 self._node = bin(changeid)
481 self._node = bin(changeid)
482 self._rev = repo.changelog.rev(self._node)
482 self._rev = repo.changelog.rev(self._node)
483 return
483 return
484 except error.FilteredLookupError:
484 except error.FilteredLookupError:
485 raise
485 raise
486 except (TypeError, LookupError):
486 except (TypeError, LookupError):
487 pass
487 pass
488
488
489 # lookup bookmarks through the name interface
489 # lookup bookmarks through the name interface
490 try:
490 try:
491 self._node = repo.names.singlenode(repo, changeid)
491 self._node = repo.names.singlenode(repo, changeid)
492 self._rev = repo.changelog.rev(self._node)
492 self._rev = repo.changelog.rev(self._node)
493 return
493 return
494 except KeyError:
494 except KeyError:
495 pass
495 pass
496 except error.FilteredRepoLookupError:
496 except error.FilteredRepoLookupError:
497 raise
497 raise
498 except error.RepoLookupError:
498 except error.RepoLookupError:
499 pass
499 pass
500
500
501 self._node = repo.unfiltered().changelog._partialmatch(changeid)
501 self._node = repo.unfiltered().changelog._partialmatch(changeid)
502 if self._node is not None:
502 if self._node is not None:
503 self._rev = repo.changelog.rev(self._node)
503 self._rev = repo.changelog.rev(self._node)
504 return
504 return
505
505
506 # lookup failed
506 # lookup failed
507 # check if it might have come from damaged dirstate
507 # check if it might have come from damaged dirstate
508 #
508 #
509 # XXX we could avoid the unfiltered if we had a recognizable
509 # XXX we could avoid the unfiltered if we had a recognizable
510 # exception for filtered changeset access
510 # exception for filtered changeset access
511 if (repo.local()
511 if (repo.local()
512 and changeid in repo.unfiltered().dirstate.parents()):
512 and changeid in repo.unfiltered().dirstate.parents()):
513 msg = _("working directory has unknown parent '%s'!")
513 msg = _("working directory has unknown parent '%s'!")
514 raise error.Abort(msg % short(changeid))
514 raise error.Abort(msg % short(changeid))
515 try:
515 try:
516 if len(changeid) == 20 and nonascii(changeid):
516 if len(changeid) == 20 and nonascii(changeid):
517 changeid = hex(changeid)
517 changeid = hex(changeid)
518 except TypeError:
518 except TypeError:
519 pass
519 pass
520 except (error.FilteredIndexError, error.FilteredLookupError,
520 except (error.FilteredIndexError, error.FilteredLookupError,
521 error.FilteredRepoLookupError):
521 error.FilteredRepoLookupError):
522 raise _filterederror(repo, changeid)
522 raise _filterederror(repo, changeid)
523 except IndexError:
523 except IndexError:
524 pass
524 pass
525 raise error.RepoLookupError(
525 raise error.RepoLookupError(
526 _("unknown revision '%s'") % changeid)
526 _("unknown revision '%s'") % changeid)
527
527
528 def __hash__(self):
528 def __hash__(self):
529 try:
529 try:
530 return hash(self._rev)
530 return hash(self._rev)
531 except AttributeError:
531 except AttributeError:
532 return id(self)
532 return id(self)
533
533
534 def __nonzero__(self):
534 def __nonzero__(self):
535 return self._rev != nullrev
535 return self._rev != nullrev
536
536
537 __bool__ = __nonzero__
537 __bool__ = __nonzero__
538
538
539 @propertycache
539 @propertycache
540 def _changeset(self):
540 def _changeset(self):
541 return self._repo.changelog.changelogrevision(self.rev())
541 return self._repo.changelog.changelogrevision(self.rev())
542
542
543 @propertycache
543 @propertycache
544 def _manifest(self):
544 def _manifest(self):
545 return self._manifestctx.read()
545 return self._manifestctx.read()
546
546
547 @property
547 @property
548 def _manifestctx(self):
548 def _manifestctx(self):
549 return self._repo.manifestlog[self._changeset.manifest]
549 return self._repo.manifestlog[self._changeset.manifest]
550
550
551 @propertycache
551 @propertycache
552 def _manifestdelta(self):
552 def _manifestdelta(self):
553 return self._manifestctx.readdelta()
553 return self._manifestctx.readdelta()
554
554
555 @propertycache
555 @propertycache
556 def _parents(self):
556 def _parents(self):
557 repo = self._repo
557 repo = self._repo
558 p1, p2 = repo.changelog.parentrevs(self._rev)
558 p1, p2 = repo.changelog.parentrevs(self._rev)
559 if p2 == nullrev:
559 if p2 == nullrev:
560 return [changectx(repo, p1)]
560 return [changectx(repo, p1)]
561 return [changectx(repo, p1), changectx(repo, p2)]
561 return [changectx(repo, p1), changectx(repo, p2)]
562
562
563 def changeset(self):
563 def changeset(self):
564 c = self._changeset
564 c = self._changeset
565 return (
565 return (
566 c.manifest,
566 c.manifest,
567 c.user,
567 c.user,
568 c.date,
568 c.date,
569 c.files,
569 c.files,
570 c.description,
570 c.description,
571 c.extra,
571 c.extra,
572 )
572 )
573 def manifestnode(self):
573 def manifestnode(self):
574 return self._changeset.manifest
574 return self._changeset.manifest
575
575
576 def user(self):
576 def user(self):
577 return self._changeset.user
577 return self._changeset.user
578 def date(self):
578 def date(self):
579 return self._changeset.date
579 return self._changeset.date
580 def files(self):
580 def files(self):
581 return self._changeset.files
581 return self._changeset.files
582 def description(self):
582 def description(self):
583 return self._changeset.description
583 return self._changeset.description
584 def branch(self):
584 def branch(self):
585 return encoding.tolocal(self._changeset.extra.get("branch"))
585 return encoding.tolocal(self._changeset.extra.get("branch"))
586 def closesbranch(self):
586 def closesbranch(self):
587 return 'close' in self._changeset.extra
587 return 'close' in self._changeset.extra
588 def extra(self):
588 def extra(self):
589 """Return a dict of extra information."""
589 """Return a dict of extra information."""
590 return self._changeset.extra
590 return self._changeset.extra
591 def tags(self):
591 def tags(self):
592 """Return a list of byte tag names"""
592 """Return a list of byte tag names"""
593 return self._repo.nodetags(self._node)
593 return self._repo.nodetags(self._node)
594 def bookmarks(self):
594 def bookmarks(self):
595 """Return a list of byte bookmark names."""
595 """Return a list of byte bookmark names."""
596 return self._repo.nodebookmarks(self._node)
596 return self._repo.nodebookmarks(self._node)
597 def phase(self):
597 def phase(self):
598 return self._repo._phasecache.phase(self._repo, self._rev)
598 return self._repo._phasecache.phase(self._repo, self._rev)
599 def hidden(self):
599 def hidden(self):
600 return self._rev in repoview.filterrevs(self._repo, 'visible')
600 return self._rev in repoview.filterrevs(self._repo, 'visible')
601
601
602 def isinmemory(self):
602 def isinmemory(self):
603 return False
603 return False
604
604
605 def children(self):
605 def children(self):
606 """return list of changectx contexts for each child changeset.
606 """return list of changectx contexts for each child changeset.
607
607
608 This returns only the immediate child changesets. Use descendants() to
608 This returns only the immediate child changesets. Use descendants() to
609 recursively walk children.
609 recursively walk children.
610 """
610 """
611 c = self._repo.changelog.children(self._node)
611 c = self._repo.changelog.children(self._node)
612 return [changectx(self._repo, x) for x in c]
612 return [changectx(self._repo, x) for x in c]
613
613
614 def ancestors(self):
614 def ancestors(self):
615 for a in self._repo.changelog.ancestors([self._rev]):
615 for a in self._repo.changelog.ancestors([self._rev]):
616 yield changectx(self._repo, a)
616 yield changectx(self._repo, a)
617
617
618 def descendants(self):
618 def descendants(self):
619 """Recursively yield all children of the changeset.
619 """Recursively yield all children of the changeset.
620
620
621 For just the immediate children, use children()
621 For just the immediate children, use children()
622 """
622 """
623 for d in self._repo.changelog.descendants([self._rev]):
623 for d in self._repo.changelog.descendants([self._rev]):
624 yield changectx(self._repo, d)
624 yield changectx(self._repo, d)
625
625
626 def filectx(self, path, fileid=None, filelog=None):
626 def filectx(self, path, fileid=None, filelog=None):
627 """get a file context from this changeset"""
627 """get a file context from this changeset"""
628 if fileid is None:
628 if fileid is None:
629 fileid = self.filenode(path)
629 fileid = self.filenode(path)
630 return filectx(self._repo, path, fileid=fileid,
630 return filectx(self._repo, path, fileid=fileid,
631 changectx=self, filelog=filelog)
631 changectx=self, filelog=filelog)
632
632
633 def ancestor(self, c2, warn=False):
633 def ancestor(self, c2, warn=False):
634 """return the "best" ancestor context of self and c2
634 """return the "best" ancestor context of self and c2
635
635
636 If there are multiple candidates, it will show a message and check
636 If there are multiple candidates, it will show a message and check
637 merge.preferancestor configuration before falling back to the
637 merge.preferancestor configuration before falling back to the
638 revlog ancestor."""
638 revlog ancestor."""
639 # deal with workingctxs
639 # deal with workingctxs
640 n2 = c2._node
640 n2 = c2._node
641 if n2 is None:
641 if n2 is None:
642 n2 = c2._parents[0]._node
642 n2 = c2._parents[0]._node
643 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
643 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
644 if not cahs:
644 if not cahs:
645 anc = nullid
645 anc = nullid
646 elif len(cahs) == 1:
646 elif len(cahs) == 1:
647 anc = cahs[0]
647 anc = cahs[0]
648 else:
648 else:
649 # experimental config: merge.preferancestor
649 # experimental config: merge.preferancestor
650 for r in self._repo.ui.configlist('merge', 'preferancestor'):
650 for r in self._repo.ui.configlist('merge', 'preferancestor'):
651 try:
651 try:
652 ctx = changectx(self._repo, r)
652 ctx = changectx(self._repo, r)
653 except error.RepoLookupError:
653 except error.RepoLookupError:
654 continue
654 continue
655 anc = ctx.node()
655 anc = ctx.node()
656 if anc in cahs:
656 if anc in cahs:
657 break
657 break
658 else:
658 else:
659 anc = self._repo.changelog.ancestor(self._node, n2)
659 anc = self._repo.changelog.ancestor(self._node, n2)
660 if warn:
660 if warn:
661 self._repo.ui.status(
661 self._repo.ui.status(
662 (_("note: using %s as ancestor of %s and %s\n") %
662 (_("note: using %s as ancestor of %s and %s\n") %
663 (short(anc), short(self._node), short(n2))) +
663 (short(anc), short(self._node), short(n2))) +
664 ''.join(_(" alternatively, use --config "
664 ''.join(_(" alternatively, use --config "
665 "merge.preferancestor=%s\n") %
665 "merge.preferancestor=%s\n") %
666 short(n) for n in sorted(cahs) if n != anc))
666 short(n) for n in sorted(cahs) if n != anc))
667 return changectx(self._repo, anc)
667 return changectx(self._repo, anc)
668
668
669 def descendant(self, other):
669 def descendant(self, other):
670 """True if other is descendant of this changeset"""
670 """True if other is descendant of this changeset"""
671 return self._repo.changelog.descendant(self._rev, other._rev)
671 return self._repo.changelog.descendant(self._rev, other._rev)
672
672
673 def walk(self, match):
673 def walk(self, match):
674 '''Generates matching file names.'''
674 '''Generates matching file names.'''
675
675
676 # Wrap match.bad method to have message with nodeid
676 # Wrap match.bad method to have message with nodeid
677 def bad(fn, msg):
677 def bad(fn, msg):
678 # The manifest doesn't know about subrepos, so don't complain about
678 # The manifest doesn't know about subrepos, so don't complain about
679 # paths into valid subrepos.
679 # paths into valid subrepos.
680 if any(fn == s or fn.startswith(s + '/')
680 if any(fn == s or fn.startswith(s + '/')
681 for s in self.substate):
681 for s in self.substate):
682 return
682 return
683 match.bad(fn, _('no such file in rev %s') % self)
683 match.bad(fn, _('no such file in rev %s') % self)
684
684
685 m = matchmod.badmatch(match, bad)
685 m = matchmod.badmatch(match, bad)
686 return self._manifest.walk(m)
686 return self._manifest.walk(m)
687
687
688 def matches(self, match):
688 def matches(self, match):
689 return self.walk(match)
689 return self.walk(match)
690
690
691 class basefilectx(object):
691 class basefilectx(object):
692 """A filecontext object represents the common logic for its children:
692 """A filecontext object represents the common logic for its children:
693 filectx: read-only access to a filerevision that is already present
693 filectx: read-only access to a filerevision that is already present
694 in the repo,
694 in the repo,
695 workingfilectx: a filecontext that represents files from the working
695 workingfilectx: a filecontext that represents files from the working
696 directory,
696 directory,
697 memfilectx: a filecontext that represents files in-memory,
697 memfilectx: a filecontext that represents files in-memory,
698 overlayfilectx: duplicate another filecontext with some fields overridden.
698 overlayfilectx: duplicate another filecontext with some fields overridden.
699 """
699 """
700 @propertycache
700 @propertycache
701 def _filelog(self):
701 def _filelog(self):
702 return self._repo.file(self._path)
702 return self._repo.file(self._path)
703
703
704 @propertycache
704 @propertycache
705 def _changeid(self):
705 def _changeid(self):
706 if r'_changeid' in self.__dict__:
706 if r'_changeid' in self.__dict__:
707 return self._changeid
707 return self._changeid
708 elif r'_changectx' in self.__dict__:
708 elif r'_changectx' in self.__dict__:
709 return self._changectx.rev()
709 return self._changectx.rev()
710 elif r'_descendantrev' in self.__dict__:
710 elif r'_descendantrev' in self.__dict__:
711 # this file context was created from a revision with a known
711 # this file context was created from a revision with a known
712 # descendant, we can (lazily) correct for linkrev aliases
712 # descendant, we can (lazily) correct for linkrev aliases
713 return self._adjustlinkrev(self._descendantrev)
713 return self._adjustlinkrev(self._descendantrev)
714 else:
714 else:
715 return self._filelog.linkrev(self._filerev)
715 return self._filelog.linkrev(self._filerev)
716
716
717 @propertycache
717 @propertycache
718 def _filenode(self):
718 def _filenode(self):
719 if r'_fileid' in self.__dict__:
719 if r'_fileid' in self.__dict__:
720 return self._filelog.lookup(self._fileid)
720 return self._filelog.lookup(self._fileid)
721 else:
721 else:
722 return self._changectx.filenode(self._path)
722 return self._changectx.filenode(self._path)
723
723
724 @propertycache
724 @propertycache
725 def _filerev(self):
725 def _filerev(self):
726 return self._filelog.rev(self._filenode)
726 return self._filelog.rev(self._filenode)
727
727
728 @propertycache
728 @propertycache
729 def _repopath(self):
729 def _repopath(self):
730 return self._path
730 return self._path
731
731
732 def __nonzero__(self):
732 def __nonzero__(self):
733 try:
733 try:
734 self._filenode
734 self._filenode
735 return True
735 return True
736 except error.LookupError:
736 except error.LookupError:
737 # file is missing
737 # file is missing
738 return False
738 return False
739
739
740 __bool__ = __nonzero__
740 __bool__ = __nonzero__
741
741
742 def __bytes__(self):
742 def __bytes__(self):
743 try:
743 try:
744 return "%s@%s" % (self.path(), self._changectx)
744 return "%s@%s" % (self.path(), self._changectx)
745 except error.LookupError:
745 except error.LookupError:
746 return "%s@???" % self.path()
746 return "%s@???" % self.path()
747
747
748 __str__ = encoding.strmethod(__bytes__)
748 __str__ = encoding.strmethod(__bytes__)
749
749
750 def __repr__(self):
750 def __repr__(self):
751 return "<%s %s>" % (type(self).__name__, str(self))
751 return "<%s %s>" % (type(self).__name__, str(self))
752
752
753 def __hash__(self):
753 def __hash__(self):
754 try:
754 try:
755 return hash((self._path, self._filenode))
755 return hash((self._path, self._filenode))
756 except AttributeError:
756 except AttributeError:
757 return id(self)
757 return id(self)
758
758
759 def __eq__(self, other):
759 def __eq__(self, other):
760 try:
760 try:
761 return (type(self) == type(other) and self._path == other._path
761 return (type(self) == type(other) and self._path == other._path
762 and self._filenode == other._filenode)
762 and self._filenode == other._filenode)
763 except AttributeError:
763 except AttributeError:
764 return False
764 return False
765
765
766 def __ne__(self, other):
766 def __ne__(self, other):
767 return not (self == other)
767 return not (self == other)
768
768
769 def filerev(self):
769 def filerev(self):
770 return self._filerev
770 return self._filerev
771 def filenode(self):
771 def filenode(self):
772 return self._filenode
772 return self._filenode
773 @propertycache
773 @propertycache
774 def _flags(self):
774 def _flags(self):
775 return self._changectx.flags(self._path)
775 return self._changectx.flags(self._path)
776 def flags(self):
776 def flags(self):
777 return self._flags
777 return self._flags
778 def filelog(self):
778 def filelog(self):
779 return self._filelog
779 return self._filelog
780 def rev(self):
780 def rev(self):
781 return self._changeid
781 return self._changeid
782 def linkrev(self):
782 def linkrev(self):
783 return self._filelog.linkrev(self._filerev)
783 return self._filelog.linkrev(self._filerev)
784 def node(self):
784 def node(self):
785 return self._changectx.node()
785 return self._changectx.node()
786 def hex(self):
786 def hex(self):
787 return self._changectx.hex()
787 return self._changectx.hex()
788 def user(self):
788 def user(self):
789 return self._changectx.user()
789 return self._changectx.user()
790 def date(self):
790 def date(self):
791 return self._changectx.date()
791 return self._changectx.date()
792 def files(self):
792 def files(self):
793 return self._changectx.files()
793 return self._changectx.files()
794 def description(self):
794 def description(self):
795 return self._changectx.description()
795 return self._changectx.description()
796 def branch(self):
796 def branch(self):
797 return self._changectx.branch()
797 return self._changectx.branch()
798 def extra(self):
798 def extra(self):
799 return self._changectx.extra()
799 return self._changectx.extra()
800 def phase(self):
800 def phase(self):
801 return self._changectx.phase()
801 return self._changectx.phase()
802 def phasestr(self):
802 def phasestr(self):
803 return self._changectx.phasestr()
803 return self._changectx.phasestr()
804 def obsolete(self):
804 def obsolete(self):
805 return self._changectx.obsolete()
805 return self._changectx.obsolete()
806 def instabilities(self):
806 def instabilities(self):
807 return self._changectx.instabilities()
807 return self._changectx.instabilities()
808 def manifest(self):
808 def manifest(self):
809 return self._changectx.manifest()
809 return self._changectx.manifest()
810 def changectx(self):
810 def changectx(self):
811 return self._changectx
811 return self._changectx
812 def renamed(self):
812 def renamed(self):
813 return self._copied
813 return self._copied
814 def repo(self):
814 def repo(self):
815 return self._repo
815 return self._repo
816 def size(self):
816 def size(self):
817 return len(self.data())
817 return len(self.data())
818
818
819 def path(self):
819 def path(self):
820 return self._path
820 return self._path
821
821
822 def isbinary(self):
822 def isbinary(self):
823 try:
823 try:
824 return util.binary(self.data())
824 return util.binary(self.data())
825 except IOError:
825 except IOError:
826 return False
826 return False
827 def isexec(self):
827 def isexec(self):
828 return 'x' in self.flags()
828 return 'x' in self.flags()
829 def islink(self):
829 def islink(self):
830 return 'l' in self.flags()
830 return 'l' in self.flags()
831
831
832 def isabsent(self):
832 def isabsent(self):
833 """whether this filectx represents a file not in self._changectx
833 """whether this filectx represents a file not in self._changectx
834
834
835 This is mainly for merge code to detect change/delete conflicts. This is
835 This is mainly for merge code to detect change/delete conflicts. This is
836 expected to be True for all subclasses of basectx."""
836 expected to be True for all subclasses of basectx."""
837 return False
837 return False
838
838
839 _customcmp = False
839 _customcmp = False
840 def cmp(self, fctx):
840 def cmp(self, fctx):
841 """compare with other file context
841 """compare with other file context
842
842
843 returns True if different than fctx.
843 returns True if different than fctx.
844 """
844 """
845 if fctx._customcmp:
845 if fctx._customcmp:
846 return fctx.cmp(self)
846 return fctx.cmp(self)
847
847
848 if (fctx._filenode is None
848 if (fctx._filenode is None
849 and (self._repo._encodefilterpats
849 and (self._repo._encodefilterpats
850 # if file data starts with '\1\n', empty metadata block is
850 # if file data starts with '\1\n', empty metadata block is
851 # prepended, which adds 4 bytes to filelog.size().
851 # prepended, which adds 4 bytes to filelog.size().
852 or self.size() - 4 == fctx.size())
852 or self.size() - 4 == fctx.size())
853 or self.size() == fctx.size()):
853 or self.size() == fctx.size()):
854 return self._filelog.cmp(self._filenode, fctx.data())
854 return self._filelog.cmp(self._filenode, fctx.data())
855
855
856 return True
856 return True
857
857
858 def _adjustlinkrev(self, srcrev, inclusive=False):
858 def _adjustlinkrev(self, srcrev, inclusive=False):
859 """return the first ancestor of <srcrev> introducing <fnode>
859 """return the first ancestor of <srcrev> introducing <fnode>
860
860
861 If the linkrev of the file revision does not point to an ancestor of
861 If the linkrev of the file revision does not point to an ancestor of
862 srcrev, we'll walk down the ancestors until we find one introducing
862 srcrev, we'll walk down the ancestors until we find one introducing
863 this file revision.
863 this file revision.
864
864
865 :srcrev: the changeset revision we search ancestors from
865 :srcrev: the changeset revision we search ancestors from
866 :inclusive: if true, the src revision will also be checked
866 :inclusive: if true, the src revision will also be checked
867 """
867 """
868 repo = self._repo
868 repo = self._repo
869 cl = repo.unfiltered().changelog
869 cl = repo.unfiltered().changelog
870 mfl = repo.manifestlog
870 mfl = repo.manifestlog
871 # fetch the linkrev
871 # fetch the linkrev
872 lkr = self.linkrev()
872 lkr = self.linkrev()
873 # hack to reuse ancestor computation when searching for renames
873 # hack to reuse ancestor computation when searching for renames
874 memberanc = getattr(self, '_ancestrycontext', None)
874 memberanc = getattr(self, '_ancestrycontext', None)
875 iteranc = None
875 iteranc = None
876 if srcrev is None:
876 if srcrev is None:
877 # wctx case, used by workingfilectx during mergecopy
877 # wctx case, used by workingfilectx during mergecopy
878 revs = [p.rev() for p in self._repo[None].parents()]
878 revs = [p.rev() for p in self._repo[None].parents()]
879 inclusive = True # we skipped the real (revless) source
879 inclusive = True # we skipped the real (revless) source
880 else:
880 else:
881 revs = [srcrev]
881 revs = [srcrev]
882 if memberanc is None:
882 if memberanc is None:
883 memberanc = iteranc = cl.ancestors(revs, lkr,
883 memberanc = iteranc = cl.ancestors(revs, lkr,
884 inclusive=inclusive)
884 inclusive=inclusive)
885 # check if this linkrev is an ancestor of srcrev
885 # check if this linkrev is an ancestor of srcrev
886 if lkr not in memberanc:
886 if lkr not in memberanc:
887 if iteranc is None:
887 if iteranc is None:
888 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
888 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
889 fnode = self._filenode
889 fnode = self._filenode
890 path = self._path
890 path = self._path
891 for a in iteranc:
891 for a in iteranc:
892 ac = cl.read(a) # get changeset data (we avoid object creation)
892 ac = cl.read(a) # get changeset data (we avoid object creation)
893 if path in ac[3]: # checking the 'files' field.
893 if path in ac[3]: # checking the 'files' field.
894 # The file has been touched, check if the content is
894 # The file has been touched, check if the content is
895 # similar to the one we search for.
895 # similar to the one we search for.
896 if fnode == mfl[ac[0]].readfast().get(path):
896 if fnode == mfl[ac[0]].readfast().get(path):
897 return a
897 return a
898 # In theory, we should never get out of that loop without a result.
898 # In theory, we should never get out of that loop without a result.
899 # But if manifest uses a buggy file revision (not children of the
899 # But if manifest uses a buggy file revision (not children of the
900 # one it replaces) we could. Such a buggy situation will likely
900 # one it replaces) we could. Such a buggy situation will likely
901 # result is crash somewhere else at to some point.
901 # result is crash somewhere else at to some point.
902 return lkr
902 return lkr
903
903
904 def introrev(self):
904 def introrev(self):
905 """return the rev of the changeset which introduced this file revision
905 """return the rev of the changeset which introduced this file revision
906
906
907 This method is different from linkrev because it take into account the
907 This method is different from linkrev because it take into account the
908 changeset the filectx was created from. It ensures the returned
908 changeset the filectx was created from. It ensures the returned
909 revision is one of its ancestors. This prevents bugs from
909 revision is one of its ancestors. This prevents bugs from
910 'linkrev-shadowing' when a file revision is used by multiple
910 'linkrev-shadowing' when a file revision is used by multiple
911 changesets.
911 changesets.
912 """
912 """
913 lkr = self.linkrev()
913 lkr = self.linkrev()
914 attrs = vars(self)
914 attrs = vars(self)
915 noctx = not ('_changeid' in attrs or '_changectx' in attrs)
915 noctx = not (r'_changeid' in attrs or r'_changectx' in attrs)
916 if noctx or self.rev() == lkr:
916 if noctx or self.rev() == lkr:
917 return self.linkrev()
917 return self.linkrev()
918 return self._adjustlinkrev(self.rev(), inclusive=True)
918 return self._adjustlinkrev(self.rev(), inclusive=True)
919
919
920 def introfilectx(self):
920 def introfilectx(self):
921 """Return filectx having identical contents, but pointing to the
921 """Return filectx having identical contents, but pointing to the
922 changeset revision where this filectx was introduced"""
922 changeset revision where this filectx was introduced"""
923 introrev = self.introrev()
923 introrev = self.introrev()
924 if self.rev() == introrev:
924 if self.rev() == introrev:
925 return self
925 return self
926 return self.filectx(self.filenode(), changeid=introrev)
926 return self.filectx(self.filenode(), changeid=introrev)
927
927
928 def _parentfilectx(self, path, fileid, filelog):
928 def _parentfilectx(self, path, fileid, filelog):
929 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
929 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
930 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
930 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
931 if '_changeid' in vars(self) or '_changectx' in vars(self):
931 if r'_changeid' in vars(self) or r'_changectx' in vars(self):
932 # If self is associated with a changeset (probably explicitly
932 # If self is associated with a changeset (probably explicitly
933 # fed), ensure the created filectx is associated with a
933 # fed), ensure the created filectx is associated with a
934 # changeset that is an ancestor of self.changectx.
934 # changeset that is an ancestor of self.changectx.
935 # This lets us later use _adjustlinkrev to get a correct link.
935 # This lets us later use _adjustlinkrev to get a correct link.
936 fctx._descendantrev = self.rev()
936 fctx._descendantrev = self.rev()
937 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
937 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
938 elif '_descendantrev' in vars(self):
938 elif r'_descendantrev' in vars(self):
939 # Otherwise propagate _descendantrev if we have one associated.
939 # Otherwise propagate _descendantrev if we have one associated.
940 fctx._descendantrev = self._descendantrev
940 fctx._descendantrev = self._descendantrev
941 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
941 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
942 return fctx
942 return fctx
943
943
944 def parents(self):
944 def parents(self):
945 _path = self._path
945 _path = self._path
946 fl = self._filelog
946 fl = self._filelog
947 parents = self._filelog.parents(self._filenode)
947 parents = self._filelog.parents(self._filenode)
948 pl = [(_path, node, fl) for node in parents if node != nullid]
948 pl = [(_path, node, fl) for node in parents if node != nullid]
949
949
950 r = fl.renamed(self._filenode)
950 r = fl.renamed(self._filenode)
951 if r:
951 if r:
952 # - In the simple rename case, both parent are nullid, pl is empty.
952 # - In the simple rename case, both parent are nullid, pl is empty.
953 # - In case of merge, only one of the parent is null id and should
953 # - In case of merge, only one of the parent is null id and should
954 # be replaced with the rename information. This parent is -always-
954 # be replaced with the rename information. This parent is -always-
955 # the first one.
955 # the first one.
956 #
956 #
957 # As null id have always been filtered out in the previous list
957 # As null id have always been filtered out in the previous list
958 # comprehension, inserting to 0 will always result in "replacing
958 # comprehension, inserting to 0 will always result in "replacing
959 # first nullid parent with rename information.
959 # first nullid parent with rename information.
960 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
960 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
961
961
962 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
962 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
963
963
964 def p1(self):
964 def p1(self):
965 return self.parents()[0]
965 return self.parents()[0]
966
966
967 def p2(self):
967 def p2(self):
968 p = self.parents()
968 p = self.parents()
969 if len(p) == 2:
969 if len(p) == 2:
970 return p[1]
970 return p[1]
971 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
971 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
972
972
973 def annotate(self, follow=False, linenumber=False, skiprevs=None,
973 def annotate(self, follow=False, linenumber=False, skiprevs=None,
974 diffopts=None):
974 diffopts=None):
975 '''returns a list of tuples of ((ctx, number), line) for each line
975 '''returns a list of tuples of ((ctx, number), line) for each line
976 in the file, where ctx is the filectx of the node where
976 in the file, where ctx is the filectx of the node where
977 that line was last changed; if linenumber parameter is true, number is
977 that line was last changed; if linenumber parameter is true, number is
978 the line number at the first appearance in the managed file, otherwise,
978 the line number at the first appearance in the managed file, otherwise,
979 number has a fixed value of False.
979 number has a fixed value of False.
980 '''
980 '''
981
981
982 def lines(text):
982 def lines(text):
983 if text.endswith("\n"):
983 if text.endswith("\n"):
984 return text.count("\n")
984 return text.count("\n")
985 return text.count("\n") + int(bool(text))
985 return text.count("\n") + int(bool(text))
986
986
987 if linenumber:
987 if linenumber:
988 def decorate(text, rev):
988 def decorate(text, rev):
989 return ([annotateline(fctx=rev, lineno=i)
989 return ([annotateline(fctx=rev, lineno=i)
990 for i in xrange(1, lines(text) + 1)], text)
990 for i in xrange(1, lines(text) + 1)], text)
991 else:
991 else:
992 def decorate(text, rev):
992 def decorate(text, rev):
993 return ([annotateline(fctx=rev)] * lines(text), text)
993 return ([annotateline(fctx=rev)] * lines(text), text)
994
994
995 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
995 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
996
996
997 def parents(f):
997 def parents(f):
998 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
998 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
999 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
999 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
1000 # from the topmost introrev (= srcrev) down to p.linkrev() if it
1000 # from the topmost introrev (= srcrev) down to p.linkrev() if it
1001 # isn't an ancestor of the srcrev.
1001 # isn't an ancestor of the srcrev.
1002 f._changeid
1002 f._changeid
1003 pl = f.parents()
1003 pl = f.parents()
1004
1004
1005 # Don't return renamed parents if we aren't following.
1005 # Don't return renamed parents if we aren't following.
1006 if not follow:
1006 if not follow:
1007 pl = [p for p in pl if p.path() == f.path()]
1007 pl = [p for p in pl if p.path() == f.path()]
1008
1008
1009 # renamed filectx won't have a filelog yet, so set it
1009 # renamed filectx won't have a filelog yet, so set it
1010 # from the cache to save time
1010 # from the cache to save time
1011 for p in pl:
1011 for p in pl:
1012 if not r'_filelog' in p.__dict__:
1012 if not r'_filelog' in p.__dict__:
1013 p._filelog = getlog(p.path())
1013 p._filelog = getlog(p.path())
1014
1014
1015 return pl
1015 return pl
1016
1016
1017 # use linkrev to find the first changeset where self appeared
1017 # use linkrev to find the first changeset where self appeared
1018 base = self.introfilectx()
1018 base = self.introfilectx()
1019 if getattr(base, '_ancestrycontext', None) is None:
1019 if getattr(base, '_ancestrycontext', None) is None:
1020 cl = self._repo.changelog
1020 cl = self._repo.changelog
1021 if base.rev() is None:
1021 if base.rev() is None:
1022 # wctx is not inclusive, but works because _ancestrycontext
1022 # wctx is not inclusive, but works because _ancestrycontext
1023 # is used to test filelog revisions
1023 # is used to test filelog revisions
1024 ac = cl.ancestors([p.rev() for p in base.parents()],
1024 ac = cl.ancestors([p.rev() for p in base.parents()],
1025 inclusive=True)
1025 inclusive=True)
1026 else:
1026 else:
1027 ac = cl.ancestors([base.rev()], inclusive=True)
1027 ac = cl.ancestors([base.rev()], inclusive=True)
1028 base._ancestrycontext = ac
1028 base._ancestrycontext = ac
1029
1029
1030 # This algorithm would prefer to be recursive, but Python is a
1030 # This algorithm would prefer to be recursive, but Python is a
1031 # bit recursion-hostile. Instead we do an iterative
1031 # bit recursion-hostile. Instead we do an iterative
1032 # depth-first search.
1032 # depth-first search.
1033
1033
1034 # 1st DFS pre-calculates pcache and needed
1034 # 1st DFS pre-calculates pcache and needed
1035 visit = [base]
1035 visit = [base]
1036 pcache = {}
1036 pcache = {}
1037 needed = {base: 1}
1037 needed = {base: 1}
1038 while visit:
1038 while visit:
1039 f = visit.pop()
1039 f = visit.pop()
1040 if f in pcache:
1040 if f in pcache:
1041 continue
1041 continue
1042 pl = parents(f)
1042 pl = parents(f)
1043 pcache[f] = pl
1043 pcache[f] = pl
1044 for p in pl:
1044 for p in pl:
1045 needed[p] = needed.get(p, 0) + 1
1045 needed[p] = needed.get(p, 0) + 1
1046 if p not in pcache:
1046 if p not in pcache:
1047 visit.append(p)
1047 visit.append(p)
1048
1048
1049 # 2nd DFS does the actual annotate
1049 # 2nd DFS does the actual annotate
1050 visit[:] = [base]
1050 visit[:] = [base]
1051 hist = {}
1051 hist = {}
1052 while visit:
1052 while visit:
1053 f = visit[-1]
1053 f = visit[-1]
1054 if f in hist:
1054 if f in hist:
1055 visit.pop()
1055 visit.pop()
1056 continue
1056 continue
1057
1057
1058 ready = True
1058 ready = True
1059 pl = pcache[f]
1059 pl = pcache[f]
1060 for p in pl:
1060 for p in pl:
1061 if p not in hist:
1061 if p not in hist:
1062 ready = False
1062 ready = False
1063 visit.append(p)
1063 visit.append(p)
1064 if ready:
1064 if ready:
1065 visit.pop()
1065 visit.pop()
1066 curr = decorate(f.data(), f)
1066 curr = decorate(f.data(), f)
1067 skipchild = False
1067 skipchild = False
1068 if skiprevs is not None:
1068 if skiprevs is not None:
1069 skipchild = f._changeid in skiprevs
1069 skipchild = f._changeid in skiprevs
1070 curr = _annotatepair([hist[p] for p in pl], f, curr, skipchild,
1070 curr = _annotatepair([hist[p] for p in pl], f, curr, skipchild,
1071 diffopts)
1071 diffopts)
1072 for p in pl:
1072 for p in pl:
1073 if needed[p] == 1:
1073 if needed[p] == 1:
1074 del hist[p]
1074 del hist[p]
1075 del needed[p]
1075 del needed[p]
1076 else:
1076 else:
1077 needed[p] -= 1
1077 needed[p] -= 1
1078
1078
1079 hist[f] = curr
1079 hist[f] = curr
1080 del pcache[f]
1080 del pcache[f]
1081
1081
1082 return pycompat.ziplist(hist[base][0], hist[base][1].splitlines(True))
1082 return pycompat.ziplist(hist[base][0], hist[base][1].splitlines(True))
1083
1083
1084 def ancestors(self, followfirst=False):
1084 def ancestors(self, followfirst=False):
1085 visit = {}
1085 visit = {}
1086 c = self
1086 c = self
1087 if followfirst:
1087 if followfirst:
1088 cut = 1
1088 cut = 1
1089 else:
1089 else:
1090 cut = None
1090 cut = None
1091
1091
1092 while True:
1092 while True:
1093 for parent in c.parents()[:cut]:
1093 for parent in c.parents()[:cut]:
1094 visit[(parent.linkrev(), parent.filenode())] = parent
1094 visit[(parent.linkrev(), parent.filenode())] = parent
1095 if not visit:
1095 if not visit:
1096 break
1096 break
1097 c = visit.pop(max(visit))
1097 c = visit.pop(max(visit))
1098 yield c
1098 yield c
1099
1099
1100 def decodeddata(self):
1100 def decodeddata(self):
1101 """Returns `data()` after running repository decoding filters.
1101 """Returns `data()` after running repository decoding filters.
1102
1102
1103 This is often equivalent to how the data would be expressed on disk.
1103 This is often equivalent to how the data would be expressed on disk.
1104 """
1104 """
1105 return self._repo.wwritedata(self.path(), self.data())
1105 return self._repo.wwritedata(self.path(), self.data())
1106
1106
1107 @attr.s(slots=True, frozen=True)
1107 @attr.s(slots=True, frozen=True)
1108 class annotateline(object):
1108 class annotateline(object):
1109 fctx = attr.ib()
1109 fctx = attr.ib()
1110 lineno = attr.ib(default=False)
1110 lineno = attr.ib(default=False)
1111 # Whether this annotation was the result of a skip-annotate.
1111 # Whether this annotation was the result of a skip-annotate.
1112 skip = attr.ib(default=False)
1112 skip = attr.ib(default=False)
1113
1113
1114 def _annotatepair(parents, childfctx, child, skipchild, diffopts):
1114 def _annotatepair(parents, childfctx, child, skipchild, diffopts):
1115 r'''
1115 r'''
1116 Given parent and child fctxes and annotate data for parents, for all lines
1116 Given parent and child fctxes and annotate data for parents, for all lines
1117 in either parent that match the child, annotate the child with the parent's
1117 in either parent that match the child, annotate the child with the parent's
1118 data.
1118 data.
1119
1119
1120 Additionally, if `skipchild` is True, replace all other lines with parent
1120 Additionally, if `skipchild` is True, replace all other lines with parent
1121 annotate data as well such that child is never blamed for any lines.
1121 annotate data as well such that child is never blamed for any lines.
1122
1122
1123 See test-annotate.py for unit tests.
1123 See test-annotate.py for unit tests.
1124 '''
1124 '''
1125 pblocks = [(parent, mdiff.allblocks(parent[1], child[1], opts=diffopts))
1125 pblocks = [(parent, mdiff.allblocks(parent[1], child[1], opts=diffopts))
1126 for parent in parents]
1126 for parent in parents]
1127
1127
1128 if skipchild:
1128 if skipchild:
1129 # Need to iterate over the blocks twice -- make it a list
1129 # Need to iterate over the blocks twice -- make it a list
1130 pblocks = [(p, list(blocks)) for (p, blocks) in pblocks]
1130 pblocks = [(p, list(blocks)) for (p, blocks) in pblocks]
1131 # Mercurial currently prefers p2 over p1 for annotate.
1131 # Mercurial currently prefers p2 over p1 for annotate.
1132 # TODO: change this?
1132 # TODO: change this?
1133 for parent, blocks in pblocks:
1133 for parent, blocks in pblocks:
1134 for (a1, a2, b1, b2), t in blocks:
1134 for (a1, a2, b1, b2), t in blocks:
1135 # Changed blocks ('!') or blocks made only of blank lines ('~')
1135 # Changed blocks ('!') or blocks made only of blank lines ('~')
1136 # belong to the child.
1136 # belong to the child.
1137 if t == '=':
1137 if t == '=':
1138 child[0][b1:b2] = parent[0][a1:a2]
1138 child[0][b1:b2] = parent[0][a1:a2]
1139
1139
1140 if skipchild:
1140 if skipchild:
1141 # Now try and match up anything that couldn't be matched,
1141 # Now try and match up anything that couldn't be matched,
1142 # Reversing pblocks maintains bias towards p2, matching above
1142 # Reversing pblocks maintains bias towards p2, matching above
1143 # behavior.
1143 # behavior.
1144 pblocks.reverse()
1144 pblocks.reverse()
1145
1145
1146 # The heuristics are:
1146 # The heuristics are:
1147 # * Work on blocks of changed lines (effectively diff hunks with -U0).
1147 # * Work on blocks of changed lines (effectively diff hunks with -U0).
1148 # This could potentially be smarter but works well enough.
1148 # This could potentially be smarter but works well enough.
1149 # * For a non-matching section, do a best-effort fit. Match lines in
1149 # * For a non-matching section, do a best-effort fit. Match lines in
1150 # diff hunks 1:1, dropping lines as necessary.
1150 # diff hunks 1:1, dropping lines as necessary.
1151 # * Repeat the last line as a last resort.
1151 # * Repeat the last line as a last resort.
1152
1152
1153 # First, replace as much as possible without repeating the last line.
1153 # First, replace as much as possible without repeating the last line.
1154 remaining = [(parent, []) for parent, _blocks in pblocks]
1154 remaining = [(parent, []) for parent, _blocks in pblocks]
1155 for idx, (parent, blocks) in enumerate(pblocks):
1155 for idx, (parent, blocks) in enumerate(pblocks):
1156 for (a1, a2, b1, b2), _t in blocks:
1156 for (a1, a2, b1, b2), _t in blocks:
1157 if a2 - a1 >= b2 - b1:
1157 if a2 - a1 >= b2 - b1:
1158 for bk in xrange(b1, b2):
1158 for bk in xrange(b1, b2):
1159 if child[0][bk].fctx == childfctx:
1159 if child[0][bk].fctx == childfctx:
1160 ak = min(a1 + (bk - b1), a2 - 1)
1160 ak = min(a1 + (bk - b1), a2 - 1)
1161 child[0][bk] = attr.evolve(parent[0][ak], skip=True)
1161 child[0][bk] = attr.evolve(parent[0][ak], skip=True)
1162 else:
1162 else:
1163 remaining[idx][1].append((a1, a2, b1, b2))
1163 remaining[idx][1].append((a1, a2, b1, b2))
1164
1164
1165 # Then, look at anything left, which might involve repeating the last
1165 # Then, look at anything left, which might involve repeating the last
1166 # line.
1166 # line.
1167 for parent, blocks in remaining:
1167 for parent, blocks in remaining:
1168 for a1, a2, b1, b2 in blocks:
1168 for a1, a2, b1, b2 in blocks:
1169 for bk in xrange(b1, b2):
1169 for bk in xrange(b1, b2):
1170 if child[0][bk].fctx == childfctx:
1170 if child[0][bk].fctx == childfctx:
1171 ak = min(a1 + (bk - b1), a2 - 1)
1171 ak = min(a1 + (bk - b1), a2 - 1)
1172 child[0][bk] = attr.evolve(parent[0][ak], skip=True)
1172 child[0][bk] = attr.evolve(parent[0][ak], skip=True)
1173 return child
1173 return child
1174
1174
1175 class filectx(basefilectx):
1175 class filectx(basefilectx):
1176 """A filecontext object makes access to data related to a particular
1176 """A filecontext object makes access to data related to a particular
1177 filerevision convenient."""
1177 filerevision convenient."""
1178 def __init__(self, repo, path, changeid=None, fileid=None,
1178 def __init__(self, repo, path, changeid=None, fileid=None,
1179 filelog=None, changectx=None):
1179 filelog=None, changectx=None):
1180 """changeid can be a changeset revision, node, or tag.
1180 """changeid can be a changeset revision, node, or tag.
1181 fileid can be a file revision or node."""
1181 fileid can be a file revision or node."""
1182 self._repo = repo
1182 self._repo = repo
1183 self._path = path
1183 self._path = path
1184
1184
1185 assert (changeid is not None
1185 assert (changeid is not None
1186 or fileid is not None
1186 or fileid is not None
1187 or changectx is not None), \
1187 or changectx is not None), \
1188 ("bad args: changeid=%r, fileid=%r, changectx=%r"
1188 ("bad args: changeid=%r, fileid=%r, changectx=%r"
1189 % (changeid, fileid, changectx))
1189 % (changeid, fileid, changectx))
1190
1190
1191 if filelog is not None:
1191 if filelog is not None:
1192 self._filelog = filelog
1192 self._filelog = filelog
1193
1193
1194 if changeid is not None:
1194 if changeid is not None:
1195 self._changeid = changeid
1195 self._changeid = changeid
1196 if changectx is not None:
1196 if changectx is not None:
1197 self._changectx = changectx
1197 self._changectx = changectx
1198 if fileid is not None:
1198 if fileid is not None:
1199 self._fileid = fileid
1199 self._fileid = fileid
1200
1200
1201 @propertycache
1201 @propertycache
1202 def _changectx(self):
1202 def _changectx(self):
1203 try:
1203 try:
1204 return changectx(self._repo, self._changeid)
1204 return changectx(self._repo, self._changeid)
1205 except error.FilteredRepoLookupError:
1205 except error.FilteredRepoLookupError:
1206 # Linkrev may point to any revision in the repository. When the
1206 # Linkrev may point to any revision in the repository. When the
1207 # repository is filtered this may lead to `filectx` trying to build
1207 # repository is filtered this may lead to `filectx` trying to build
1208 # `changectx` for filtered revision. In such case we fallback to
1208 # `changectx` for filtered revision. In such case we fallback to
1209 # creating `changectx` on the unfiltered version of the reposition.
1209 # creating `changectx` on the unfiltered version of the reposition.
1210 # This fallback should not be an issue because `changectx` from
1210 # This fallback should not be an issue because `changectx` from
1211 # `filectx` are not used in complex operations that care about
1211 # `filectx` are not used in complex operations that care about
1212 # filtering.
1212 # filtering.
1213 #
1213 #
1214 # This fallback is a cheap and dirty fix that prevent several
1214 # This fallback is a cheap and dirty fix that prevent several
1215 # crashes. It does not ensure the behavior is correct. However the
1215 # crashes. It does not ensure the behavior is correct. However the
1216 # behavior was not correct before filtering either and "incorrect
1216 # behavior was not correct before filtering either and "incorrect
1217 # behavior" is seen as better as "crash"
1217 # behavior" is seen as better as "crash"
1218 #
1218 #
1219 # Linkrevs have several serious troubles with filtering that are
1219 # Linkrevs have several serious troubles with filtering that are
1220 # complicated to solve. Proper handling of the issue here should be
1220 # complicated to solve. Proper handling of the issue here should be
1221 # considered when solving linkrev issue are on the table.
1221 # considered when solving linkrev issue are on the table.
1222 return changectx(self._repo.unfiltered(), self._changeid)
1222 return changectx(self._repo.unfiltered(), self._changeid)
1223
1223
1224 def filectx(self, fileid, changeid=None):
1224 def filectx(self, fileid, changeid=None):
1225 '''opens an arbitrary revision of the file without
1225 '''opens an arbitrary revision of the file without
1226 opening a new filelog'''
1226 opening a new filelog'''
1227 return filectx(self._repo, self._path, fileid=fileid,
1227 return filectx(self._repo, self._path, fileid=fileid,
1228 filelog=self._filelog, changeid=changeid)
1228 filelog=self._filelog, changeid=changeid)
1229
1229
1230 def rawdata(self):
1230 def rawdata(self):
1231 return self._filelog.revision(self._filenode, raw=True)
1231 return self._filelog.revision(self._filenode, raw=True)
1232
1232
1233 def rawflags(self):
1233 def rawflags(self):
1234 """low-level revlog flags"""
1234 """low-level revlog flags"""
1235 return self._filelog.flags(self._filerev)
1235 return self._filelog.flags(self._filerev)
1236
1236
1237 def data(self):
1237 def data(self):
1238 try:
1238 try:
1239 return self._filelog.read(self._filenode)
1239 return self._filelog.read(self._filenode)
1240 except error.CensoredNodeError:
1240 except error.CensoredNodeError:
1241 if self._repo.ui.config("censor", "policy") == "ignore":
1241 if self._repo.ui.config("censor", "policy") == "ignore":
1242 return ""
1242 return ""
1243 raise error.Abort(_("censored node: %s") % short(self._filenode),
1243 raise error.Abort(_("censored node: %s") % short(self._filenode),
1244 hint=_("set censor.policy to ignore errors"))
1244 hint=_("set censor.policy to ignore errors"))
1245
1245
1246 def size(self):
1246 def size(self):
1247 return self._filelog.size(self._filerev)
1247 return self._filelog.size(self._filerev)
1248
1248
1249 @propertycache
1249 @propertycache
1250 def _copied(self):
1250 def _copied(self):
1251 """check if file was actually renamed in this changeset revision
1251 """check if file was actually renamed in this changeset revision
1252
1252
1253 If rename logged in file revision, we report copy for changeset only
1253 If rename logged in file revision, we report copy for changeset only
1254 if file revisions linkrev points back to the changeset in question
1254 if file revisions linkrev points back to the changeset in question
1255 or both changeset parents contain different file revisions.
1255 or both changeset parents contain different file revisions.
1256 """
1256 """
1257
1257
1258 renamed = self._filelog.renamed(self._filenode)
1258 renamed = self._filelog.renamed(self._filenode)
1259 if not renamed:
1259 if not renamed:
1260 return renamed
1260 return renamed
1261
1261
1262 if self.rev() == self.linkrev():
1262 if self.rev() == self.linkrev():
1263 return renamed
1263 return renamed
1264
1264
1265 name = self.path()
1265 name = self.path()
1266 fnode = self._filenode
1266 fnode = self._filenode
1267 for p in self._changectx.parents():
1267 for p in self._changectx.parents():
1268 try:
1268 try:
1269 if fnode == p.filenode(name):
1269 if fnode == p.filenode(name):
1270 return None
1270 return None
1271 except error.LookupError:
1271 except error.LookupError:
1272 pass
1272 pass
1273 return renamed
1273 return renamed
1274
1274
1275 def children(self):
1275 def children(self):
1276 # hard for renames
1276 # hard for renames
1277 c = self._filelog.children(self._filenode)
1277 c = self._filelog.children(self._filenode)
1278 return [filectx(self._repo, self._path, fileid=x,
1278 return [filectx(self._repo, self._path, fileid=x,
1279 filelog=self._filelog) for x in c]
1279 filelog=self._filelog) for x in c]
1280
1280
1281 class committablectx(basectx):
1281 class committablectx(basectx):
1282 """A committablectx object provides common functionality for a context that
1282 """A committablectx object provides common functionality for a context that
1283 wants the ability to commit, e.g. workingctx or memctx."""
1283 wants the ability to commit, e.g. workingctx or memctx."""
1284 def __init__(self, repo, text="", user=None, date=None, extra=None,
1284 def __init__(self, repo, text="", user=None, date=None, extra=None,
1285 changes=None):
1285 changes=None):
1286 self._repo = repo
1286 self._repo = repo
1287 self._rev = None
1287 self._rev = None
1288 self._node = None
1288 self._node = None
1289 self._text = text
1289 self._text = text
1290 if date:
1290 if date:
1291 self._date = dateutil.parsedate(date)
1291 self._date = dateutil.parsedate(date)
1292 if user:
1292 if user:
1293 self._user = user
1293 self._user = user
1294 if changes:
1294 if changes:
1295 self._status = changes
1295 self._status = changes
1296
1296
1297 self._extra = {}
1297 self._extra = {}
1298 if extra:
1298 if extra:
1299 self._extra = extra.copy()
1299 self._extra = extra.copy()
1300 if 'branch' not in self._extra:
1300 if 'branch' not in self._extra:
1301 try:
1301 try:
1302 branch = encoding.fromlocal(self._repo.dirstate.branch())
1302 branch = encoding.fromlocal(self._repo.dirstate.branch())
1303 except UnicodeDecodeError:
1303 except UnicodeDecodeError:
1304 raise error.Abort(_('branch name not in UTF-8!'))
1304 raise error.Abort(_('branch name not in UTF-8!'))
1305 self._extra['branch'] = branch
1305 self._extra['branch'] = branch
1306 if self._extra['branch'] == '':
1306 if self._extra['branch'] == '':
1307 self._extra['branch'] = 'default'
1307 self._extra['branch'] = 'default'
1308
1308
1309 def __bytes__(self):
1309 def __bytes__(self):
1310 return bytes(self._parents[0]) + "+"
1310 return bytes(self._parents[0]) + "+"
1311
1311
1312 __str__ = encoding.strmethod(__bytes__)
1312 __str__ = encoding.strmethod(__bytes__)
1313
1313
1314 def __nonzero__(self):
1314 def __nonzero__(self):
1315 return True
1315 return True
1316
1316
1317 __bool__ = __nonzero__
1317 __bool__ = __nonzero__
1318
1318
1319 def _buildflagfunc(self):
1319 def _buildflagfunc(self):
1320 # Create a fallback function for getting file flags when the
1320 # Create a fallback function for getting file flags when the
1321 # filesystem doesn't support them
1321 # filesystem doesn't support them
1322
1322
1323 copiesget = self._repo.dirstate.copies().get
1323 copiesget = self._repo.dirstate.copies().get
1324 parents = self.parents()
1324 parents = self.parents()
1325 if len(parents) < 2:
1325 if len(parents) < 2:
1326 # when we have one parent, it's easy: copy from parent
1326 # when we have one parent, it's easy: copy from parent
1327 man = parents[0].manifest()
1327 man = parents[0].manifest()
1328 def func(f):
1328 def func(f):
1329 f = copiesget(f, f)
1329 f = copiesget(f, f)
1330 return man.flags(f)
1330 return man.flags(f)
1331 else:
1331 else:
1332 # merges are tricky: we try to reconstruct the unstored
1332 # merges are tricky: we try to reconstruct the unstored
1333 # result from the merge (issue1802)
1333 # result from the merge (issue1802)
1334 p1, p2 = parents
1334 p1, p2 = parents
1335 pa = p1.ancestor(p2)
1335 pa = p1.ancestor(p2)
1336 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1336 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1337
1337
1338 def func(f):
1338 def func(f):
1339 f = copiesget(f, f) # may be wrong for merges with copies
1339 f = copiesget(f, f) # may be wrong for merges with copies
1340 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1340 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1341 if fl1 == fl2:
1341 if fl1 == fl2:
1342 return fl1
1342 return fl1
1343 if fl1 == fla:
1343 if fl1 == fla:
1344 return fl2
1344 return fl2
1345 if fl2 == fla:
1345 if fl2 == fla:
1346 return fl1
1346 return fl1
1347 return '' # punt for conflicts
1347 return '' # punt for conflicts
1348
1348
1349 return func
1349 return func
1350
1350
1351 @propertycache
1351 @propertycache
1352 def _flagfunc(self):
1352 def _flagfunc(self):
1353 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1353 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1354
1354
1355 @propertycache
1355 @propertycache
1356 def _status(self):
1356 def _status(self):
1357 return self._repo.status()
1357 return self._repo.status()
1358
1358
1359 @propertycache
1359 @propertycache
1360 def _user(self):
1360 def _user(self):
1361 return self._repo.ui.username()
1361 return self._repo.ui.username()
1362
1362
1363 @propertycache
1363 @propertycache
1364 def _date(self):
1364 def _date(self):
1365 ui = self._repo.ui
1365 ui = self._repo.ui
1366 date = ui.configdate('devel', 'default-date')
1366 date = ui.configdate('devel', 'default-date')
1367 if date is None:
1367 if date is None:
1368 date = dateutil.makedate()
1368 date = dateutil.makedate()
1369 return date
1369 return date
1370
1370
1371 def subrev(self, subpath):
1371 def subrev(self, subpath):
1372 return None
1372 return None
1373
1373
1374 def manifestnode(self):
1374 def manifestnode(self):
1375 return None
1375 return None
1376 def user(self):
1376 def user(self):
1377 return self._user or self._repo.ui.username()
1377 return self._user or self._repo.ui.username()
1378 def date(self):
1378 def date(self):
1379 return self._date
1379 return self._date
1380 def description(self):
1380 def description(self):
1381 return self._text
1381 return self._text
1382 def files(self):
1382 def files(self):
1383 return sorted(self._status.modified + self._status.added +
1383 return sorted(self._status.modified + self._status.added +
1384 self._status.removed)
1384 self._status.removed)
1385
1385
1386 def modified(self):
1386 def modified(self):
1387 return self._status.modified
1387 return self._status.modified
1388 def added(self):
1388 def added(self):
1389 return self._status.added
1389 return self._status.added
1390 def removed(self):
1390 def removed(self):
1391 return self._status.removed
1391 return self._status.removed
1392 def deleted(self):
1392 def deleted(self):
1393 return self._status.deleted
1393 return self._status.deleted
1394 def branch(self):
1394 def branch(self):
1395 return encoding.tolocal(self._extra['branch'])
1395 return encoding.tolocal(self._extra['branch'])
1396 def closesbranch(self):
1396 def closesbranch(self):
1397 return 'close' in self._extra
1397 return 'close' in self._extra
1398 def extra(self):
1398 def extra(self):
1399 return self._extra
1399 return self._extra
1400
1400
1401 def isinmemory(self):
1401 def isinmemory(self):
1402 return False
1402 return False
1403
1403
1404 def tags(self):
1404 def tags(self):
1405 return []
1405 return []
1406
1406
1407 def bookmarks(self):
1407 def bookmarks(self):
1408 b = []
1408 b = []
1409 for p in self.parents():
1409 for p in self.parents():
1410 b.extend(p.bookmarks())
1410 b.extend(p.bookmarks())
1411 return b
1411 return b
1412
1412
1413 def phase(self):
1413 def phase(self):
1414 phase = phases.draft # default phase to draft
1414 phase = phases.draft # default phase to draft
1415 for p in self.parents():
1415 for p in self.parents():
1416 phase = max(phase, p.phase())
1416 phase = max(phase, p.phase())
1417 return phase
1417 return phase
1418
1418
1419 def hidden(self):
1419 def hidden(self):
1420 return False
1420 return False
1421
1421
1422 def children(self):
1422 def children(self):
1423 return []
1423 return []
1424
1424
1425 def flags(self, path):
1425 def flags(self, path):
1426 if r'_manifest' in self.__dict__:
1426 if r'_manifest' in self.__dict__:
1427 try:
1427 try:
1428 return self._manifest.flags(path)
1428 return self._manifest.flags(path)
1429 except KeyError:
1429 except KeyError:
1430 return ''
1430 return ''
1431
1431
1432 try:
1432 try:
1433 return self._flagfunc(path)
1433 return self._flagfunc(path)
1434 except OSError:
1434 except OSError:
1435 return ''
1435 return ''
1436
1436
1437 def ancestor(self, c2):
1437 def ancestor(self, c2):
1438 """return the "best" ancestor context of self and c2"""
1438 """return the "best" ancestor context of self and c2"""
1439 return self._parents[0].ancestor(c2) # punt on two parents for now
1439 return self._parents[0].ancestor(c2) # punt on two parents for now
1440
1440
1441 def walk(self, match):
1441 def walk(self, match):
1442 '''Generates matching file names.'''
1442 '''Generates matching file names.'''
1443 return sorted(self._repo.dirstate.walk(match,
1443 return sorted(self._repo.dirstate.walk(match,
1444 subrepos=sorted(self.substate),
1444 subrepos=sorted(self.substate),
1445 unknown=True, ignored=False))
1445 unknown=True, ignored=False))
1446
1446
1447 def matches(self, match):
1447 def matches(self, match):
1448 return sorted(self._repo.dirstate.matches(match))
1448 return sorted(self._repo.dirstate.matches(match))
1449
1449
1450 def ancestors(self):
1450 def ancestors(self):
1451 for p in self._parents:
1451 for p in self._parents:
1452 yield p
1452 yield p
1453 for a in self._repo.changelog.ancestors(
1453 for a in self._repo.changelog.ancestors(
1454 [p.rev() for p in self._parents]):
1454 [p.rev() for p in self._parents]):
1455 yield changectx(self._repo, a)
1455 yield changectx(self._repo, a)
1456
1456
1457 def markcommitted(self, node):
1457 def markcommitted(self, node):
1458 """Perform post-commit cleanup necessary after committing this ctx
1458 """Perform post-commit cleanup necessary after committing this ctx
1459
1459
1460 Specifically, this updates backing stores this working context
1460 Specifically, this updates backing stores this working context
1461 wraps to reflect the fact that the changes reflected by this
1461 wraps to reflect the fact that the changes reflected by this
1462 workingctx have been committed. For example, it marks
1462 workingctx have been committed. For example, it marks
1463 modified and added files as normal in the dirstate.
1463 modified and added files as normal in the dirstate.
1464
1464
1465 """
1465 """
1466
1466
1467 with self._repo.dirstate.parentchange():
1467 with self._repo.dirstate.parentchange():
1468 for f in self.modified() + self.added():
1468 for f in self.modified() + self.added():
1469 self._repo.dirstate.normal(f)
1469 self._repo.dirstate.normal(f)
1470 for f in self.removed():
1470 for f in self.removed():
1471 self._repo.dirstate.drop(f)
1471 self._repo.dirstate.drop(f)
1472 self._repo.dirstate.setparents(node)
1472 self._repo.dirstate.setparents(node)
1473
1473
1474 # write changes out explicitly, because nesting wlock at
1474 # write changes out explicitly, because nesting wlock at
1475 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1475 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1476 # from immediately doing so for subsequent changing files
1476 # from immediately doing so for subsequent changing files
1477 self._repo.dirstate.write(self._repo.currenttransaction())
1477 self._repo.dirstate.write(self._repo.currenttransaction())
1478
1478
1479 def dirty(self, missing=False, merge=True, branch=True):
1479 def dirty(self, missing=False, merge=True, branch=True):
1480 return False
1480 return False
1481
1481
1482 class workingctx(committablectx):
1482 class workingctx(committablectx):
1483 """A workingctx object makes access to data related to
1483 """A workingctx object makes access to data related to
1484 the current working directory convenient.
1484 the current working directory convenient.
1485 date - any valid date string or (unixtime, offset), or None.
1485 date - any valid date string or (unixtime, offset), or None.
1486 user - username string, or None.
1486 user - username string, or None.
1487 extra - a dictionary of extra values, or None.
1487 extra - a dictionary of extra values, or None.
1488 changes - a list of file lists as returned by localrepo.status()
1488 changes - a list of file lists as returned by localrepo.status()
1489 or None to use the repository status.
1489 or None to use the repository status.
1490 """
1490 """
1491 def __init__(self, repo, text="", user=None, date=None, extra=None,
1491 def __init__(self, repo, text="", user=None, date=None, extra=None,
1492 changes=None):
1492 changes=None):
1493 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1493 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1494
1494
1495 def __iter__(self):
1495 def __iter__(self):
1496 d = self._repo.dirstate
1496 d = self._repo.dirstate
1497 for f in d:
1497 for f in d:
1498 if d[f] != 'r':
1498 if d[f] != 'r':
1499 yield f
1499 yield f
1500
1500
1501 def __contains__(self, key):
1501 def __contains__(self, key):
1502 return self._repo.dirstate[key] not in "?r"
1502 return self._repo.dirstate[key] not in "?r"
1503
1503
1504 def hex(self):
1504 def hex(self):
1505 return hex(wdirid)
1505 return hex(wdirid)
1506
1506
1507 @propertycache
1507 @propertycache
1508 def _parents(self):
1508 def _parents(self):
1509 p = self._repo.dirstate.parents()
1509 p = self._repo.dirstate.parents()
1510 if p[1] == nullid:
1510 if p[1] == nullid:
1511 p = p[:-1]
1511 p = p[:-1]
1512 return [changectx(self._repo, x) for x in p]
1512 return [changectx(self._repo, x) for x in p]
1513
1513
1514 def filectx(self, path, filelog=None):
1514 def filectx(self, path, filelog=None):
1515 """get a file context from the working directory"""
1515 """get a file context from the working directory"""
1516 return workingfilectx(self._repo, path, workingctx=self,
1516 return workingfilectx(self._repo, path, workingctx=self,
1517 filelog=filelog)
1517 filelog=filelog)
1518
1518
1519 def dirty(self, missing=False, merge=True, branch=True):
1519 def dirty(self, missing=False, merge=True, branch=True):
1520 "check whether a working directory is modified"
1520 "check whether a working directory is modified"
1521 # check subrepos first
1521 # check subrepos first
1522 for s in sorted(self.substate):
1522 for s in sorted(self.substate):
1523 if self.sub(s).dirty(missing=missing):
1523 if self.sub(s).dirty(missing=missing):
1524 return True
1524 return True
1525 # check current working dir
1525 # check current working dir
1526 return ((merge and self.p2()) or
1526 return ((merge and self.p2()) or
1527 (branch and self.branch() != self.p1().branch()) or
1527 (branch and self.branch() != self.p1().branch()) or
1528 self.modified() or self.added() or self.removed() or
1528 self.modified() or self.added() or self.removed() or
1529 (missing and self.deleted()))
1529 (missing and self.deleted()))
1530
1530
1531 def add(self, list, prefix=""):
1531 def add(self, list, prefix=""):
1532 with self._repo.wlock():
1532 with self._repo.wlock():
1533 ui, ds = self._repo.ui, self._repo.dirstate
1533 ui, ds = self._repo.ui, self._repo.dirstate
1534 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1534 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1535 rejected = []
1535 rejected = []
1536 lstat = self._repo.wvfs.lstat
1536 lstat = self._repo.wvfs.lstat
1537 for f in list:
1537 for f in list:
1538 # ds.pathto() returns an absolute file when this is invoked from
1538 # ds.pathto() returns an absolute file when this is invoked from
1539 # the keyword extension. That gets flagged as non-portable on
1539 # the keyword extension. That gets flagged as non-portable on
1540 # Windows, since it contains the drive letter and colon.
1540 # Windows, since it contains the drive letter and colon.
1541 scmutil.checkportable(ui, os.path.join(prefix, f))
1541 scmutil.checkportable(ui, os.path.join(prefix, f))
1542 try:
1542 try:
1543 st = lstat(f)
1543 st = lstat(f)
1544 except OSError:
1544 except OSError:
1545 ui.warn(_("%s does not exist!\n") % uipath(f))
1545 ui.warn(_("%s does not exist!\n") % uipath(f))
1546 rejected.append(f)
1546 rejected.append(f)
1547 continue
1547 continue
1548 if st.st_size > 10000000:
1548 if st.st_size > 10000000:
1549 ui.warn(_("%s: up to %d MB of RAM may be required "
1549 ui.warn(_("%s: up to %d MB of RAM may be required "
1550 "to manage this file\n"
1550 "to manage this file\n"
1551 "(use 'hg revert %s' to cancel the "
1551 "(use 'hg revert %s' to cancel the "
1552 "pending addition)\n")
1552 "pending addition)\n")
1553 % (f, 3 * st.st_size // 1000000, uipath(f)))
1553 % (f, 3 * st.st_size // 1000000, uipath(f)))
1554 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1554 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1555 ui.warn(_("%s not added: only files and symlinks "
1555 ui.warn(_("%s not added: only files and symlinks "
1556 "supported currently\n") % uipath(f))
1556 "supported currently\n") % uipath(f))
1557 rejected.append(f)
1557 rejected.append(f)
1558 elif ds[f] in 'amn':
1558 elif ds[f] in 'amn':
1559 ui.warn(_("%s already tracked!\n") % uipath(f))
1559 ui.warn(_("%s already tracked!\n") % uipath(f))
1560 elif ds[f] == 'r':
1560 elif ds[f] == 'r':
1561 ds.normallookup(f)
1561 ds.normallookup(f)
1562 else:
1562 else:
1563 ds.add(f)
1563 ds.add(f)
1564 return rejected
1564 return rejected
1565
1565
1566 def forget(self, files, prefix=""):
1566 def forget(self, files, prefix=""):
1567 with self._repo.wlock():
1567 with self._repo.wlock():
1568 ds = self._repo.dirstate
1568 ds = self._repo.dirstate
1569 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1569 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1570 rejected = []
1570 rejected = []
1571 for f in files:
1571 for f in files:
1572 if f not in self._repo.dirstate:
1572 if f not in self._repo.dirstate:
1573 self._repo.ui.warn(_("%s not tracked!\n") % uipath(f))
1573 self._repo.ui.warn(_("%s not tracked!\n") % uipath(f))
1574 rejected.append(f)
1574 rejected.append(f)
1575 elif self._repo.dirstate[f] != 'a':
1575 elif self._repo.dirstate[f] != 'a':
1576 self._repo.dirstate.remove(f)
1576 self._repo.dirstate.remove(f)
1577 else:
1577 else:
1578 self._repo.dirstate.drop(f)
1578 self._repo.dirstate.drop(f)
1579 return rejected
1579 return rejected
1580
1580
1581 def undelete(self, list):
1581 def undelete(self, list):
1582 pctxs = self.parents()
1582 pctxs = self.parents()
1583 with self._repo.wlock():
1583 with self._repo.wlock():
1584 ds = self._repo.dirstate
1584 ds = self._repo.dirstate
1585 for f in list:
1585 for f in list:
1586 if self._repo.dirstate[f] != 'r':
1586 if self._repo.dirstate[f] != 'r':
1587 self._repo.ui.warn(_("%s not removed!\n") % ds.pathto(f))
1587 self._repo.ui.warn(_("%s not removed!\n") % ds.pathto(f))
1588 else:
1588 else:
1589 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1589 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1590 t = fctx.data()
1590 t = fctx.data()
1591 self._repo.wwrite(f, t, fctx.flags())
1591 self._repo.wwrite(f, t, fctx.flags())
1592 self._repo.dirstate.normal(f)
1592 self._repo.dirstate.normal(f)
1593
1593
1594 def copy(self, source, dest):
1594 def copy(self, source, dest):
1595 try:
1595 try:
1596 st = self._repo.wvfs.lstat(dest)
1596 st = self._repo.wvfs.lstat(dest)
1597 except OSError as err:
1597 except OSError as err:
1598 if err.errno != errno.ENOENT:
1598 if err.errno != errno.ENOENT:
1599 raise
1599 raise
1600 self._repo.ui.warn(_("%s does not exist!\n")
1600 self._repo.ui.warn(_("%s does not exist!\n")
1601 % self._repo.dirstate.pathto(dest))
1601 % self._repo.dirstate.pathto(dest))
1602 return
1602 return
1603 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1603 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1604 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1604 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1605 "symbolic link\n")
1605 "symbolic link\n")
1606 % self._repo.dirstate.pathto(dest))
1606 % self._repo.dirstate.pathto(dest))
1607 else:
1607 else:
1608 with self._repo.wlock():
1608 with self._repo.wlock():
1609 if self._repo.dirstate[dest] in '?':
1609 if self._repo.dirstate[dest] in '?':
1610 self._repo.dirstate.add(dest)
1610 self._repo.dirstate.add(dest)
1611 elif self._repo.dirstate[dest] in 'r':
1611 elif self._repo.dirstate[dest] in 'r':
1612 self._repo.dirstate.normallookup(dest)
1612 self._repo.dirstate.normallookup(dest)
1613 self._repo.dirstate.copy(source, dest)
1613 self._repo.dirstate.copy(source, dest)
1614
1614
1615 def match(self, pats=None, include=None, exclude=None, default='glob',
1615 def match(self, pats=None, include=None, exclude=None, default='glob',
1616 listsubrepos=False, badfn=None):
1616 listsubrepos=False, badfn=None):
1617 r = self._repo
1617 r = self._repo
1618
1618
1619 # Only a case insensitive filesystem needs magic to translate user input
1619 # Only a case insensitive filesystem needs magic to translate user input
1620 # to actual case in the filesystem.
1620 # to actual case in the filesystem.
1621 icasefs = not util.fscasesensitive(r.root)
1621 icasefs = not util.fscasesensitive(r.root)
1622 return matchmod.match(r.root, r.getcwd(), pats, include, exclude,
1622 return matchmod.match(r.root, r.getcwd(), pats, include, exclude,
1623 default, auditor=r.auditor, ctx=self,
1623 default, auditor=r.auditor, ctx=self,
1624 listsubrepos=listsubrepos, badfn=badfn,
1624 listsubrepos=listsubrepos, badfn=badfn,
1625 icasefs=icasefs)
1625 icasefs=icasefs)
1626
1626
1627 def _filtersuspectsymlink(self, files):
1627 def _filtersuspectsymlink(self, files):
1628 if not files or self._repo.dirstate._checklink:
1628 if not files or self._repo.dirstate._checklink:
1629 return files
1629 return files
1630
1630
1631 # Symlink placeholders may get non-symlink-like contents
1631 # Symlink placeholders may get non-symlink-like contents
1632 # via user error or dereferencing by NFS or Samba servers,
1632 # via user error or dereferencing by NFS or Samba servers,
1633 # so we filter out any placeholders that don't look like a
1633 # so we filter out any placeholders that don't look like a
1634 # symlink
1634 # symlink
1635 sane = []
1635 sane = []
1636 for f in files:
1636 for f in files:
1637 if self.flags(f) == 'l':
1637 if self.flags(f) == 'l':
1638 d = self[f].data()
1638 d = self[f].data()
1639 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1639 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1640 self._repo.ui.debug('ignoring suspect symlink placeholder'
1640 self._repo.ui.debug('ignoring suspect symlink placeholder'
1641 ' "%s"\n' % f)
1641 ' "%s"\n' % f)
1642 continue
1642 continue
1643 sane.append(f)
1643 sane.append(f)
1644 return sane
1644 return sane
1645
1645
1646 def _checklookup(self, files):
1646 def _checklookup(self, files):
1647 # check for any possibly clean files
1647 # check for any possibly clean files
1648 if not files:
1648 if not files:
1649 return [], [], []
1649 return [], [], []
1650
1650
1651 modified = []
1651 modified = []
1652 deleted = []
1652 deleted = []
1653 fixup = []
1653 fixup = []
1654 pctx = self._parents[0]
1654 pctx = self._parents[0]
1655 # do a full compare of any files that might have changed
1655 # do a full compare of any files that might have changed
1656 for f in sorted(files):
1656 for f in sorted(files):
1657 try:
1657 try:
1658 # This will return True for a file that got replaced by a
1658 # This will return True for a file that got replaced by a
1659 # directory in the interim, but fixing that is pretty hard.
1659 # directory in the interim, but fixing that is pretty hard.
1660 if (f not in pctx or self.flags(f) != pctx.flags(f)
1660 if (f not in pctx or self.flags(f) != pctx.flags(f)
1661 or pctx[f].cmp(self[f])):
1661 or pctx[f].cmp(self[f])):
1662 modified.append(f)
1662 modified.append(f)
1663 else:
1663 else:
1664 fixup.append(f)
1664 fixup.append(f)
1665 except (IOError, OSError):
1665 except (IOError, OSError):
1666 # A file become inaccessible in between? Mark it as deleted,
1666 # A file become inaccessible in between? Mark it as deleted,
1667 # matching dirstate behavior (issue5584).
1667 # matching dirstate behavior (issue5584).
1668 # The dirstate has more complex behavior around whether a
1668 # The dirstate has more complex behavior around whether a
1669 # missing file matches a directory, etc, but we don't need to
1669 # missing file matches a directory, etc, but we don't need to
1670 # bother with that: if f has made it to this point, we're sure
1670 # bother with that: if f has made it to this point, we're sure
1671 # it's in the dirstate.
1671 # it's in the dirstate.
1672 deleted.append(f)
1672 deleted.append(f)
1673
1673
1674 return modified, deleted, fixup
1674 return modified, deleted, fixup
1675
1675
1676 def _poststatusfixup(self, status, fixup):
1676 def _poststatusfixup(self, status, fixup):
1677 """update dirstate for files that are actually clean"""
1677 """update dirstate for files that are actually clean"""
1678 poststatus = self._repo.postdsstatus()
1678 poststatus = self._repo.postdsstatus()
1679 if fixup or poststatus:
1679 if fixup or poststatus:
1680 try:
1680 try:
1681 oldid = self._repo.dirstate.identity()
1681 oldid = self._repo.dirstate.identity()
1682
1682
1683 # updating the dirstate is optional
1683 # updating the dirstate is optional
1684 # so we don't wait on the lock
1684 # so we don't wait on the lock
1685 # wlock can invalidate the dirstate, so cache normal _after_
1685 # wlock can invalidate the dirstate, so cache normal _after_
1686 # taking the lock
1686 # taking the lock
1687 with self._repo.wlock(False):
1687 with self._repo.wlock(False):
1688 if self._repo.dirstate.identity() == oldid:
1688 if self._repo.dirstate.identity() == oldid:
1689 if fixup:
1689 if fixup:
1690 normal = self._repo.dirstate.normal
1690 normal = self._repo.dirstate.normal
1691 for f in fixup:
1691 for f in fixup:
1692 normal(f)
1692 normal(f)
1693 # write changes out explicitly, because nesting
1693 # write changes out explicitly, because nesting
1694 # wlock at runtime may prevent 'wlock.release()'
1694 # wlock at runtime may prevent 'wlock.release()'
1695 # after this block from doing so for subsequent
1695 # after this block from doing so for subsequent
1696 # changing files
1696 # changing files
1697 tr = self._repo.currenttransaction()
1697 tr = self._repo.currenttransaction()
1698 self._repo.dirstate.write(tr)
1698 self._repo.dirstate.write(tr)
1699
1699
1700 if poststatus:
1700 if poststatus:
1701 for ps in poststatus:
1701 for ps in poststatus:
1702 ps(self, status)
1702 ps(self, status)
1703 else:
1703 else:
1704 # in this case, writing changes out breaks
1704 # in this case, writing changes out breaks
1705 # consistency, because .hg/dirstate was
1705 # consistency, because .hg/dirstate was
1706 # already changed simultaneously after last
1706 # already changed simultaneously after last
1707 # caching (see also issue5584 for detail)
1707 # caching (see also issue5584 for detail)
1708 self._repo.ui.debug('skip updating dirstate: '
1708 self._repo.ui.debug('skip updating dirstate: '
1709 'identity mismatch\n')
1709 'identity mismatch\n')
1710 except error.LockError:
1710 except error.LockError:
1711 pass
1711 pass
1712 finally:
1712 finally:
1713 # Even if the wlock couldn't be grabbed, clear out the list.
1713 # Even if the wlock couldn't be grabbed, clear out the list.
1714 self._repo.clearpostdsstatus()
1714 self._repo.clearpostdsstatus()
1715
1715
1716 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1716 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1717 '''Gets the status from the dirstate -- internal use only.'''
1717 '''Gets the status from the dirstate -- internal use only.'''
1718 subrepos = []
1718 subrepos = []
1719 if '.hgsub' in self:
1719 if '.hgsub' in self:
1720 subrepos = sorted(self.substate)
1720 subrepos = sorted(self.substate)
1721 cmp, s = self._repo.dirstate.status(match, subrepos, ignored=ignored,
1721 cmp, s = self._repo.dirstate.status(match, subrepos, ignored=ignored,
1722 clean=clean, unknown=unknown)
1722 clean=clean, unknown=unknown)
1723
1723
1724 # check for any possibly clean files
1724 # check for any possibly clean files
1725 fixup = []
1725 fixup = []
1726 if cmp:
1726 if cmp:
1727 modified2, deleted2, fixup = self._checklookup(cmp)
1727 modified2, deleted2, fixup = self._checklookup(cmp)
1728 s.modified.extend(modified2)
1728 s.modified.extend(modified2)
1729 s.deleted.extend(deleted2)
1729 s.deleted.extend(deleted2)
1730
1730
1731 if fixup and clean:
1731 if fixup and clean:
1732 s.clean.extend(fixup)
1732 s.clean.extend(fixup)
1733
1733
1734 self._poststatusfixup(s, fixup)
1734 self._poststatusfixup(s, fixup)
1735
1735
1736 if match.always():
1736 if match.always():
1737 # cache for performance
1737 # cache for performance
1738 if s.unknown or s.ignored or s.clean:
1738 if s.unknown or s.ignored or s.clean:
1739 # "_status" is cached with list*=False in the normal route
1739 # "_status" is cached with list*=False in the normal route
1740 self._status = scmutil.status(s.modified, s.added, s.removed,
1740 self._status = scmutil.status(s.modified, s.added, s.removed,
1741 s.deleted, [], [], [])
1741 s.deleted, [], [], [])
1742 else:
1742 else:
1743 self._status = s
1743 self._status = s
1744
1744
1745 return s
1745 return s
1746
1746
1747 @propertycache
1747 @propertycache
1748 def _manifest(self):
1748 def _manifest(self):
1749 """generate a manifest corresponding to the values in self._status
1749 """generate a manifest corresponding to the values in self._status
1750
1750
1751 This reuse the file nodeid from parent, but we use special node
1751 This reuse the file nodeid from parent, but we use special node
1752 identifiers for added and modified files. This is used by manifests
1752 identifiers for added and modified files. This is used by manifests
1753 merge to see that files are different and by update logic to avoid
1753 merge to see that files are different and by update logic to avoid
1754 deleting newly added files.
1754 deleting newly added files.
1755 """
1755 """
1756 return self._buildstatusmanifest(self._status)
1756 return self._buildstatusmanifest(self._status)
1757
1757
1758 def _buildstatusmanifest(self, status):
1758 def _buildstatusmanifest(self, status):
1759 """Builds a manifest that includes the given status results."""
1759 """Builds a manifest that includes the given status results."""
1760 parents = self.parents()
1760 parents = self.parents()
1761
1761
1762 man = parents[0].manifest().copy()
1762 man = parents[0].manifest().copy()
1763
1763
1764 ff = self._flagfunc
1764 ff = self._flagfunc
1765 for i, l in ((addednodeid, status.added),
1765 for i, l in ((addednodeid, status.added),
1766 (modifiednodeid, status.modified)):
1766 (modifiednodeid, status.modified)):
1767 for f in l:
1767 for f in l:
1768 man[f] = i
1768 man[f] = i
1769 try:
1769 try:
1770 man.setflag(f, ff(f))
1770 man.setflag(f, ff(f))
1771 except OSError:
1771 except OSError:
1772 pass
1772 pass
1773
1773
1774 for f in status.deleted + status.removed:
1774 for f in status.deleted + status.removed:
1775 if f in man:
1775 if f in man:
1776 del man[f]
1776 del man[f]
1777
1777
1778 return man
1778 return man
1779
1779
1780 def _buildstatus(self, other, s, match, listignored, listclean,
1780 def _buildstatus(self, other, s, match, listignored, listclean,
1781 listunknown):
1781 listunknown):
1782 """build a status with respect to another context
1782 """build a status with respect to another context
1783
1783
1784 This includes logic for maintaining the fast path of status when
1784 This includes logic for maintaining the fast path of status when
1785 comparing the working directory against its parent, which is to skip
1785 comparing the working directory against its parent, which is to skip
1786 building a new manifest if self (working directory) is not comparing
1786 building a new manifest if self (working directory) is not comparing
1787 against its parent (repo['.']).
1787 against its parent (repo['.']).
1788 """
1788 """
1789 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1789 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1790 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1790 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1791 # might have accidentally ended up with the entire contents of the file
1791 # might have accidentally ended up with the entire contents of the file
1792 # they are supposed to be linking to.
1792 # they are supposed to be linking to.
1793 s.modified[:] = self._filtersuspectsymlink(s.modified)
1793 s.modified[:] = self._filtersuspectsymlink(s.modified)
1794 if other != self._repo['.']:
1794 if other != self._repo['.']:
1795 s = super(workingctx, self)._buildstatus(other, s, match,
1795 s = super(workingctx, self)._buildstatus(other, s, match,
1796 listignored, listclean,
1796 listignored, listclean,
1797 listunknown)
1797 listunknown)
1798 return s
1798 return s
1799
1799
1800 def _matchstatus(self, other, match):
1800 def _matchstatus(self, other, match):
1801 """override the match method with a filter for directory patterns
1801 """override the match method with a filter for directory patterns
1802
1802
1803 We use inheritance to customize the match.bad method only in cases of
1803 We use inheritance to customize the match.bad method only in cases of
1804 workingctx since it belongs only to the working directory when
1804 workingctx since it belongs only to the working directory when
1805 comparing against the parent changeset.
1805 comparing against the parent changeset.
1806
1806
1807 If we aren't comparing against the working directory's parent, then we
1807 If we aren't comparing against the working directory's parent, then we
1808 just use the default match object sent to us.
1808 just use the default match object sent to us.
1809 """
1809 """
1810 if other != self._repo['.']:
1810 if other != self._repo['.']:
1811 def bad(f, msg):
1811 def bad(f, msg):
1812 # 'f' may be a directory pattern from 'match.files()',
1812 # 'f' may be a directory pattern from 'match.files()',
1813 # so 'f not in ctx1' is not enough
1813 # so 'f not in ctx1' is not enough
1814 if f not in other and not other.hasdir(f):
1814 if f not in other and not other.hasdir(f):
1815 self._repo.ui.warn('%s: %s\n' %
1815 self._repo.ui.warn('%s: %s\n' %
1816 (self._repo.dirstate.pathto(f), msg))
1816 (self._repo.dirstate.pathto(f), msg))
1817 match.bad = bad
1817 match.bad = bad
1818 return match
1818 return match
1819
1819
1820 def markcommitted(self, node):
1820 def markcommitted(self, node):
1821 super(workingctx, self).markcommitted(node)
1821 super(workingctx, self).markcommitted(node)
1822
1822
1823 sparse.aftercommit(self._repo, node)
1823 sparse.aftercommit(self._repo, node)
1824
1824
1825 class committablefilectx(basefilectx):
1825 class committablefilectx(basefilectx):
1826 """A committablefilectx provides common functionality for a file context
1826 """A committablefilectx provides common functionality for a file context
1827 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1827 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1828 def __init__(self, repo, path, filelog=None, ctx=None):
1828 def __init__(self, repo, path, filelog=None, ctx=None):
1829 self._repo = repo
1829 self._repo = repo
1830 self._path = path
1830 self._path = path
1831 self._changeid = None
1831 self._changeid = None
1832 self._filerev = self._filenode = None
1832 self._filerev = self._filenode = None
1833
1833
1834 if filelog is not None:
1834 if filelog is not None:
1835 self._filelog = filelog
1835 self._filelog = filelog
1836 if ctx:
1836 if ctx:
1837 self._changectx = ctx
1837 self._changectx = ctx
1838
1838
1839 def __nonzero__(self):
1839 def __nonzero__(self):
1840 return True
1840 return True
1841
1841
1842 __bool__ = __nonzero__
1842 __bool__ = __nonzero__
1843
1843
1844 def linkrev(self):
1844 def linkrev(self):
1845 # linked to self._changectx no matter if file is modified or not
1845 # linked to self._changectx no matter if file is modified or not
1846 return self.rev()
1846 return self.rev()
1847
1847
1848 def parents(self):
1848 def parents(self):
1849 '''return parent filectxs, following copies if necessary'''
1849 '''return parent filectxs, following copies if necessary'''
1850 def filenode(ctx, path):
1850 def filenode(ctx, path):
1851 return ctx._manifest.get(path, nullid)
1851 return ctx._manifest.get(path, nullid)
1852
1852
1853 path = self._path
1853 path = self._path
1854 fl = self._filelog
1854 fl = self._filelog
1855 pcl = self._changectx._parents
1855 pcl = self._changectx._parents
1856 renamed = self.renamed()
1856 renamed = self.renamed()
1857
1857
1858 if renamed:
1858 if renamed:
1859 pl = [renamed + (None,)]
1859 pl = [renamed + (None,)]
1860 else:
1860 else:
1861 pl = [(path, filenode(pcl[0], path), fl)]
1861 pl = [(path, filenode(pcl[0], path), fl)]
1862
1862
1863 for pc in pcl[1:]:
1863 for pc in pcl[1:]:
1864 pl.append((path, filenode(pc, path), fl))
1864 pl.append((path, filenode(pc, path), fl))
1865
1865
1866 return [self._parentfilectx(p, fileid=n, filelog=l)
1866 return [self._parentfilectx(p, fileid=n, filelog=l)
1867 for p, n, l in pl if n != nullid]
1867 for p, n, l in pl if n != nullid]
1868
1868
1869 def children(self):
1869 def children(self):
1870 return []
1870 return []
1871
1871
1872 class workingfilectx(committablefilectx):
1872 class workingfilectx(committablefilectx):
1873 """A workingfilectx object makes access to data related to a particular
1873 """A workingfilectx object makes access to data related to a particular
1874 file in the working directory convenient."""
1874 file in the working directory convenient."""
1875 def __init__(self, repo, path, filelog=None, workingctx=None):
1875 def __init__(self, repo, path, filelog=None, workingctx=None):
1876 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1876 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1877
1877
1878 @propertycache
1878 @propertycache
1879 def _changectx(self):
1879 def _changectx(self):
1880 return workingctx(self._repo)
1880 return workingctx(self._repo)
1881
1881
1882 def data(self):
1882 def data(self):
1883 return self._repo.wread(self._path)
1883 return self._repo.wread(self._path)
1884 def renamed(self):
1884 def renamed(self):
1885 rp = self._repo.dirstate.copied(self._path)
1885 rp = self._repo.dirstate.copied(self._path)
1886 if not rp:
1886 if not rp:
1887 return None
1887 return None
1888 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1888 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1889
1889
1890 def size(self):
1890 def size(self):
1891 return self._repo.wvfs.lstat(self._path).st_size
1891 return self._repo.wvfs.lstat(self._path).st_size
1892 def date(self):
1892 def date(self):
1893 t, tz = self._changectx.date()
1893 t, tz = self._changectx.date()
1894 try:
1894 try:
1895 return (self._repo.wvfs.lstat(self._path).st_mtime, tz)
1895 return (self._repo.wvfs.lstat(self._path).st_mtime, tz)
1896 except OSError as err:
1896 except OSError as err:
1897 if err.errno != errno.ENOENT:
1897 if err.errno != errno.ENOENT:
1898 raise
1898 raise
1899 return (t, tz)
1899 return (t, tz)
1900
1900
1901 def exists(self):
1901 def exists(self):
1902 return self._repo.wvfs.exists(self._path)
1902 return self._repo.wvfs.exists(self._path)
1903
1903
1904 def lexists(self):
1904 def lexists(self):
1905 return self._repo.wvfs.lexists(self._path)
1905 return self._repo.wvfs.lexists(self._path)
1906
1906
1907 def audit(self):
1907 def audit(self):
1908 return self._repo.wvfs.audit(self._path)
1908 return self._repo.wvfs.audit(self._path)
1909
1909
1910 def cmp(self, fctx):
1910 def cmp(self, fctx):
1911 """compare with other file context
1911 """compare with other file context
1912
1912
1913 returns True if different than fctx.
1913 returns True if different than fctx.
1914 """
1914 """
1915 # fctx should be a filectx (not a workingfilectx)
1915 # fctx should be a filectx (not a workingfilectx)
1916 # invert comparison to reuse the same code path
1916 # invert comparison to reuse the same code path
1917 return fctx.cmp(self)
1917 return fctx.cmp(self)
1918
1918
1919 def remove(self, ignoremissing=False):
1919 def remove(self, ignoremissing=False):
1920 """wraps unlink for a repo's working directory"""
1920 """wraps unlink for a repo's working directory"""
1921 self._repo.wvfs.unlinkpath(self._path, ignoremissing=ignoremissing)
1921 self._repo.wvfs.unlinkpath(self._path, ignoremissing=ignoremissing)
1922
1922
1923 def write(self, data, flags, backgroundclose=False, **kwargs):
1923 def write(self, data, flags, backgroundclose=False, **kwargs):
1924 """wraps repo.wwrite"""
1924 """wraps repo.wwrite"""
1925 self._repo.wwrite(self._path, data, flags,
1925 self._repo.wwrite(self._path, data, flags,
1926 backgroundclose=backgroundclose,
1926 backgroundclose=backgroundclose,
1927 **kwargs)
1927 **kwargs)
1928
1928
1929 def markcopied(self, src):
1929 def markcopied(self, src):
1930 """marks this file a copy of `src`"""
1930 """marks this file a copy of `src`"""
1931 if self._repo.dirstate[self._path] in "nma":
1931 if self._repo.dirstate[self._path] in "nma":
1932 self._repo.dirstate.copy(src, self._path)
1932 self._repo.dirstate.copy(src, self._path)
1933
1933
1934 def clearunknown(self):
1934 def clearunknown(self):
1935 """Removes conflicting items in the working directory so that
1935 """Removes conflicting items in the working directory so that
1936 ``write()`` can be called successfully.
1936 ``write()`` can be called successfully.
1937 """
1937 """
1938 wvfs = self._repo.wvfs
1938 wvfs = self._repo.wvfs
1939 f = self._path
1939 f = self._path
1940 wvfs.audit(f)
1940 wvfs.audit(f)
1941 if wvfs.isdir(f) and not wvfs.islink(f):
1941 if wvfs.isdir(f) and not wvfs.islink(f):
1942 wvfs.rmtree(f, forcibly=True)
1942 wvfs.rmtree(f, forcibly=True)
1943 for p in reversed(list(util.finddirs(f))):
1943 for p in reversed(list(util.finddirs(f))):
1944 if wvfs.isfileorlink(p):
1944 if wvfs.isfileorlink(p):
1945 wvfs.unlink(p)
1945 wvfs.unlink(p)
1946 break
1946 break
1947
1947
1948 def setflags(self, l, x):
1948 def setflags(self, l, x):
1949 self._repo.wvfs.setflags(self._path, l, x)
1949 self._repo.wvfs.setflags(self._path, l, x)
1950
1950
1951 class overlayworkingctx(committablectx):
1951 class overlayworkingctx(committablectx):
1952 """Wraps another mutable context with a write-back cache that can be
1952 """Wraps another mutable context with a write-back cache that can be
1953 converted into a commit context.
1953 converted into a commit context.
1954
1954
1955 self._cache[path] maps to a dict with keys: {
1955 self._cache[path] maps to a dict with keys: {
1956 'exists': bool?
1956 'exists': bool?
1957 'date': date?
1957 'date': date?
1958 'data': str?
1958 'data': str?
1959 'flags': str?
1959 'flags': str?
1960 'copied': str? (path or None)
1960 'copied': str? (path or None)
1961 }
1961 }
1962 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
1962 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
1963 is `False`, the file was deleted.
1963 is `False`, the file was deleted.
1964 """
1964 """
1965
1965
1966 def __init__(self, repo):
1966 def __init__(self, repo):
1967 super(overlayworkingctx, self).__init__(repo)
1967 super(overlayworkingctx, self).__init__(repo)
1968 self._repo = repo
1968 self._repo = repo
1969 self.clean()
1969 self.clean()
1970
1970
1971 def setbase(self, wrappedctx):
1971 def setbase(self, wrappedctx):
1972 self._wrappedctx = wrappedctx
1972 self._wrappedctx = wrappedctx
1973 self._parents = [wrappedctx]
1973 self._parents = [wrappedctx]
1974 # Drop old manifest cache as it is now out of date.
1974 # Drop old manifest cache as it is now out of date.
1975 # This is necessary when, e.g., rebasing several nodes with one
1975 # This is necessary when, e.g., rebasing several nodes with one
1976 # ``overlayworkingctx`` (e.g. with --collapse).
1976 # ``overlayworkingctx`` (e.g. with --collapse).
1977 util.clearcachedproperty(self, '_manifest')
1977 util.clearcachedproperty(self, '_manifest')
1978
1978
1979 def data(self, path):
1979 def data(self, path):
1980 if self.isdirty(path):
1980 if self.isdirty(path):
1981 if self._cache[path]['exists']:
1981 if self._cache[path]['exists']:
1982 if self._cache[path]['data']:
1982 if self._cache[path]['data']:
1983 return self._cache[path]['data']
1983 return self._cache[path]['data']
1984 else:
1984 else:
1985 # Must fallback here, too, because we only set flags.
1985 # Must fallback here, too, because we only set flags.
1986 return self._wrappedctx[path].data()
1986 return self._wrappedctx[path].data()
1987 else:
1987 else:
1988 raise error.ProgrammingError("No such file or directory: %s" %
1988 raise error.ProgrammingError("No such file or directory: %s" %
1989 path)
1989 path)
1990 else:
1990 else:
1991 return self._wrappedctx[path].data()
1991 return self._wrappedctx[path].data()
1992
1992
1993 @propertycache
1993 @propertycache
1994 def _manifest(self):
1994 def _manifest(self):
1995 parents = self.parents()
1995 parents = self.parents()
1996 man = parents[0].manifest().copy()
1996 man = parents[0].manifest().copy()
1997
1997
1998 flag = self._flagfunc
1998 flag = self._flagfunc
1999 for path in self.added():
1999 for path in self.added():
2000 man[path] = addednodeid
2000 man[path] = addednodeid
2001 man.setflag(path, flag(path))
2001 man.setflag(path, flag(path))
2002 for path in self.modified():
2002 for path in self.modified():
2003 man[path] = modifiednodeid
2003 man[path] = modifiednodeid
2004 man.setflag(path, flag(path))
2004 man.setflag(path, flag(path))
2005 for path in self.removed():
2005 for path in self.removed():
2006 del man[path]
2006 del man[path]
2007 return man
2007 return man
2008
2008
2009 @propertycache
2009 @propertycache
2010 def _flagfunc(self):
2010 def _flagfunc(self):
2011 def f(path):
2011 def f(path):
2012 return self._cache[path]['flags']
2012 return self._cache[path]['flags']
2013 return f
2013 return f
2014
2014
2015 def files(self):
2015 def files(self):
2016 return sorted(self.added() + self.modified() + self.removed())
2016 return sorted(self.added() + self.modified() + self.removed())
2017
2017
2018 def modified(self):
2018 def modified(self):
2019 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
2019 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
2020 self._existsinparent(f)]
2020 self._existsinparent(f)]
2021
2021
2022 def added(self):
2022 def added(self):
2023 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
2023 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
2024 not self._existsinparent(f)]
2024 not self._existsinparent(f)]
2025
2025
2026 def removed(self):
2026 def removed(self):
2027 return [f for f in self._cache.keys() if
2027 return [f for f in self._cache.keys() if
2028 not self._cache[f]['exists'] and self._existsinparent(f)]
2028 not self._cache[f]['exists'] and self._existsinparent(f)]
2029
2029
2030 def isinmemory(self):
2030 def isinmemory(self):
2031 return True
2031 return True
2032
2032
2033 def filedate(self, path):
2033 def filedate(self, path):
2034 if self.isdirty(path):
2034 if self.isdirty(path):
2035 return self._cache[path]['date']
2035 return self._cache[path]['date']
2036 else:
2036 else:
2037 return self._wrappedctx[path].date()
2037 return self._wrappedctx[path].date()
2038
2038
2039 def markcopied(self, path, origin):
2039 def markcopied(self, path, origin):
2040 if self.isdirty(path):
2040 if self.isdirty(path):
2041 self._cache[path]['copied'] = origin
2041 self._cache[path]['copied'] = origin
2042 else:
2042 else:
2043 raise error.ProgrammingError('markcopied() called on clean context')
2043 raise error.ProgrammingError('markcopied() called on clean context')
2044
2044
2045 def copydata(self, path):
2045 def copydata(self, path):
2046 if self.isdirty(path):
2046 if self.isdirty(path):
2047 return self._cache[path]['copied']
2047 return self._cache[path]['copied']
2048 else:
2048 else:
2049 raise error.ProgrammingError('copydata() called on clean context')
2049 raise error.ProgrammingError('copydata() called on clean context')
2050
2050
2051 def flags(self, path):
2051 def flags(self, path):
2052 if self.isdirty(path):
2052 if self.isdirty(path):
2053 if self._cache[path]['exists']:
2053 if self._cache[path]['exists']:
2054 return self._cache[path]['flags']
2054 return self._cache[path]['flags']
2055 else:
2055 else:
2056 raise error.ProgrammingError("No such file or directory: %s" %
2056 raise error.ProgrammingError("No such file or directory: %s" %
2057 self._path)
2057 self._path)
2058 else:
2058 else:
2059 return self._wrappedctx[path].flags()
2059 return self._wrappedctx[path].flags()
2060
2060
2061 def _existsinparent(self, path):
2061 def _existsinparent(self, path):
2062 try:
2062 try:
2063 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2063 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2064 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2064 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2065 # with an ``exists()`` function.
2065 # with an ``exists()`` function.
2066 self._wrappedctx[path]
2066 self._wrappedctx[path]
2067 return True
2067 return True
2068 except error.ManifestLookupError:
2068 except error.ManifestLookupError:
2069 return False
2069 return False
2070
2070
2071 def _auditconflicts(self, path):
2071 def _auditconflicts(self, path):
2072 """Replicates conflict checks done by wvfs.write().
2072 """Replicates conflict checks done by wvfs.write().
2073
2073
2074 Since we never write to the filesystem and never call `applyupdates` in
2074 Since we never write to the filesystem and never call `applyupdates` in
2075 IMM, we'll never check that a path is actually writable -- e.g., because
2075 IMM, we'll never check that a path is actually writable -- e.g., because
2076 it adds `a/foo`, but `a` is actually a file in the other commit.
2076 it adds `a/foo`, but `a` is actually a file in the other commit.
2077 """
2077 """
2078 def fail(path, component):
2078 def fail(path, component):
2079 # p1() is the base and we're receiving "writes" for p2()'s
2079 # p1() is the base and we're receiving "writes" for p2()'s
2080 # files.
2080 # files.
2081 if 'l' in self.p1()[component].flags():
2081 if 'l' in self.p1()[component].flags():
2082 raise error.Abort("error: %s conflicts with symlink %s "
2082 raise error.Abort("error: %s conflicts with symlink %s "
2083 "in %s." % (path, component,
2083 "in %s." % (path, component,
2084 self.p1().rev()))
2084 self.p1().rev()))
2085 else:
2085 else:
2086 raise error.Abort("error: '%s' conflicts with file '%s' in "
2086 raise error.Abort("error: '%s' conflicts with file '%s' in "
2087 "%s." % (path, component,
2087 "%s." % (path, component,
2088 self.p1().rev()))
2088 self.p1().rev()))
2089
2089
2090 # Test that each new directory to be created to write this path from p2
2090 # Test that each new directory to be created to write this path from p2
2091 # is not a file in p1.
2091 # is not a file in p1.
2092 components = path.split('/')
2092 components = path.split('/')
2093 for i in xrange(len(components)):
2093 for i in xrange(len(components)):
2094 component = "/".join(components[0:i])
2094 component = "/".join(components[0:i])
2095 if component in self.p1():
2095 if component in self.p1():
2096 fail(path, component)
2096 fail(path, component)
2097
2097
2098 # Test the other direction -- that this path from p2 isn't a directory
2098 # Test the other direction -- that this path from p2 isn't a directory
2099 # in p1 (test that p1 doesn't any paths matching `path/*`).
2099 # in p1 (test that p1 doesn't any paths matching `path/*`).
2100 match = matchmod.match('/', '', [path + '/'], default=b'relpath')
2100 match = matchmod.match('/', '', [path + '/'], default=b'relpath')
2101 matches = self.p1().manifest().matches(match)
2101 matches = self.p1().manifest().matches(match)
2102 if len(matches) > 0:
2102 if len(matches) > 0:
2103 if len(matches) == 1 and matches.keys()[0] == path:
2103 if len(matches) == 1 and matches.keys()[0] == path:
2104 return
2104 return
2105 raise error.Abort("error: file '%s' cannot be written because "
2105 raise error.Abort("error: file '%s' cannot be written because "
2106 " '%s/' is a folder in %s (containing %d "
2106 " '%s/' is a folder in %s (containing %d "
2107 "entries: %s)"
2107 "entries: %s)"
2108 % (path, path, self.p1(), len(matches),
2108 % (path, path, self.p1(), len(matches),
2109 ', '.join(matches.keys())))
2109 ', '.join(matches.keys())))
2110
2110
2111 def write(self, path, data, flags='', **kwargs):
2111 def write(self, path, data, flags='', **kwargs):
2112 if data is None:
2112 if data is None:
2113 raise error.ProgrammingError("data must be non-None")
2113 raise error.ProgrammingError("data must be non-None")
2114 self._auditconflicts(path)
2114 self._auditconflicts(path)
2115 self._markdirty(path, exists=True, data=data, date=dateutil.makedate(),
2115 self._markdirty(path, exists=True, data=data, date=dateutil.makedate(),
2116 flags=flags)
2116 flags=flags)
2117
2117
2118 def setflags(self, path, l, x):
2118 def setflags(self, path, l, x):
2119 self._markdirty(path, exists=True, date=dateutil.makedate(),
2119 self._markdirty(path, exists=True, date=dateutil.makedate(),
2120 flags=(l and 'l' or '') + (x and 'x' or ''))
2120 flags=(l and 'l' or '') + (x and 'x' or ''))
2121
2121
2122 def remove(self, path):
2122 def remove(self, path):
2123 self._markdirty(path, exists=False)
2123 self._markdirty(path, exists=False)
2124
2124
2125 def exists(self, path):
2125 def exists(self, path):
2126 """exists behaves like `lexists`, but needs to follow symlinks and
2126 """exists behaves like `lexists`, but needs to follow symlinks and
2127 return False if they are broken.
2127 return False if they are broken.
2128 """
2128 """
2129 if self.isdirty(path):
2129 if self.isdirty(path):
2130 # If this path exists and is a symlink, "follow" it by calling
2130 # If this path exists and is a symlink, "follow" it by calling
2131 # exists on the destination path.
2131 # exists on the destination path.
2132 if (self._cache[path]['exists'] and
2132 if (self._cache[path]['exists'] and
2133 'l' in self._cache[path]['flags']):
2133 'l' in self._cache[path]['flags']):
2134 return self.exists(self._cache[path]['data'].strip())
2134 return self.exists(self._cache[path]['data'].strip())
2135 else:
2135 else:
2136 return self._cache[path]['exists']
2136 return self._cache[path]['exists']
2137
2137
2138 return self._existsinparent(path)
2138 return self._existsinparent(path)
2139
2139
2140 def lexists(self, path):
2140 def lexists(self, path):
2141 """lexists returns True if the path exists"""
2141 """lexists returns True if the path exists"""
2142 if self.isdirty(path):
2142 if self.isdirty(path):
2143 return self._cache[path]['exists']
2143 return self._cache[path]['exists']
2144
2144
2145 return self._existsinparent(path)
2145 return self._existsinparent(path)
2146
2146
2147 def size(self, path):
2147 def size(self, path):
2148 if self.isdirty(path):
2148 if self.isdirty(path):
2149 if self._cache[path]['exists']:
2149 if self._cache[path]['exists']:
2150 return len(self._cache[path]['data'])
2150 return len(self._cache[path]['data'])
2151 else:
2151 else:
2152 raise error.ProgrammingError("No such file or directory: %s" %
2152 raise error.ProgrammingError("No such file or directory: %s" %
2153 self._path)
2153 self._path)
2154 return self._wrappedctx[path].size()
2154 return self._wrappedctx[path].size()
2155
2155
2156 def tomemctx(self, text, branch=None, extra=None, date=None, parents=None,
2156 def tomemctx(self, text, branch=None, extra=None, date=None, parents=None,
2157 user=None, editor=None):
2157 user=None, editor=None):
2158 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2158 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2159 committed.
2159 committed.
2160
2160
2161 ``text`` is the commit message.
2161 ``text`` is the commit message.
2162 ``parents`` (optional) are rev numbers.
2162 ``parents`` (optional) are rev numbers.
2163 """
2163 """
2164 # Default parents to the wrapped contexts' if not passed.
2164 # Default parents to the wrapped contexts' if not passed.
2165 if parents is None:
2165 if parents is None:
2166 parents = self._wrappedctx.parents()
2166 parents = self._wrappedctx.parents()
2167 if len(parents) == 1:
2167 if len(parents) == 1:
2168 parents = (parents[0], None)
2168 parents = (parents[0], None)
2169
2169
2170 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2170 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2171 if parents[1] is None:
2171 if parents[1] is None:
2172 parents = (self._repo[parents[0]], None)
2172 parents = (self._repo[parents[0]], None)
2173 else:
2173 else:
2174 parents = (self._repo[parents[0]], self._repo[parents[1]])
2174 parents = (self._repo[parents[0]], self._repo[parents[1]])
2175
2175
2176 files = self._cache.keys()
2176 files = self._cache.keys()
2177 def getfile(repo, memctx, path):
2177 def getfile(repo, memctx, path):
2178 if self._cache[path]['exists']:
2178 if self._cache[path]['exists']:
2179 return memfilectx(repo, memctx, path,
2179 return memfilectx(repo, memctx, path,
2180 self._cache[path]['data'],
2180 self._cache[path]['data'],
2181 'l' in self._cache[path]['flags'],
2181 'l' in self._cache[path]['flags'],
2182 'x' in self._cache[path]['flags'],
2182 'x' in self._cache[path]['flags'],
2183 self._cache[path]['copied'])
2183 self._cache[path]['copied'])
2184 else:
2184 else:
2185 # Returning None, but including the path in `files`, is
2185 # Returning None, but including the path in `files`, is
2186 # necessary for memctx to register a deletion.
2186 # necessary for memctx to register a deletion.
2187 return None
2187 return None
2188 return memctx(self._repo, parents, text, files, getfile, date=date,
2188 return memctx(self._repo, parents, text, files, getfile, date=date,
2189 extra=extra, user=user, branch=branch, editor=editor)
2189 extra=extra, user=user, branch=branch, editor=editor)
2190
2190
2191 def isdirty(self, path):
2191 def isdirty(self, path):
2192 return path in self._cache
2192 return path in self._cache
2193
2193
2194 def isempty(self):
2194 def isempty(self):
2195 # We need to discard any keys that are actually clean before the empty
2195 # We need to discard any keys that are actually clean before the empty
2196 # commit check.
2196 # commit check.
2197 self._compact()
2197 self._compact()
2198 return len(self._cache) == 0
2198 return len(self._cache) == 0
2199
2199
2200 def clean(self):
2200 def clean(self):
2201 self._cache = {}
2201 self._cache = {}
2202
2202
2203 def _compact(self):
2203 def _compact(self):
2204 """Removes keys from the cache that are actually clean, by comparing
2204 """Removes keys from the cache that are actually clean, by comparing
2205 them with the underlying context.
2205 them with the underlying context.
2206
2206
2207 This can occur during the merge process, e.g. by passing --tool :local
2207 This can occur during the merge process, e.g. by passing --tool :local
2208 to resolve a conflict.
2208 to resolve a conflict.
2209 """
2209 """
2210 keys = []
2210 keys = []
2211 for path in self._cache.keys():
2211 for path in self._cache.keys():
2212 cache = self._cache[path]
2212 cache = self._cache[path]
2213 try:
2213 try:
2214 underlying = self._wrappedctx[path]
2214 underlying = self._wrappedctx[path]
2215 if (underlying.data() == cache['data'] and
2215 if (underlying.data() == cache['data'] and
2216 underlying.flags() == cache['flags']):
2216 underlying.flags() == cache['flags']):
2217 keys.append(path)
2217 keys.append(path)
2218 except error.ManifestLookupError:
2218 except error.ManifestLookupError:
2219 # Path not in the underlying manifest (created).
2219 # Path not in the underlying manifest (created).
2220 continue
2220 continue
2221
2221
2222 for path in keys:
2222 for path in keys:
2223 del self._cache[path]
2223 del self._cache[path]
2224 return keys
2224 return keys
2225
2225
2226 def _markdirty(self, path, exists, data=None, date=None, flags=''):
2226 def _markdirty(self, path, exists, data=None, date=None, flags=''):
2227 self._cache[path] = {
2227 self._cache[path] = {
2228 'exists': exists,
2228 'exists': exists,
2229 'data': data,
2229 'data': data,
2230 'date': date,
2230 'date': date,
2231 'flags': flags,
2231 'flags': flags,
2232 'copied': None,
2232 'copied': None,
2233 }
2233 }
2234
2234
2235 def filectx(self, path, filelog=None):
2235 def filectx(self, path, filelog=None):
2236 return overlayworkingfilectx(self._repo, path, parent=self,
2236 return overlayworkingfilectx(self._repo, path, parent=self,
2237 filelog=filelog)
2237 filelog=filelog)
2238
2238
2239 class overlayworkingfilectx(committablefilectx):
2239 class overlayworkingfilectx(committablefilectx):
2240 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2240 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2241 cache, which can be flushed through later by calling ``flush()``."""
2241 cache, which can be flushed through later by calling ``flush()``."""
2242
2242
2243 def __init__(self, repo, path, filelog=None, parent=None):
2243 def __init__(self, repo, path, filelog=None, parent=None):
2244 super(overlayworkingfilectx, self).__init__(repo, path, filelog,
2244 super(overlayworkingfilectx, self).__init__(repo, path, filelog,
2245 parent)
2245 parent)
2246 self._repo = repo
2246 self._repo = repo
2247 self._parent = parent
2247 self._parent = parent
2248 self._path = path
2248 self._path = path
2249
2249
2250 def cmp(self, fctx):
2250 def cmp(self, fctx):
2251 return self.data() != fctx.data()
2251 return self.data() != fctx.data()
2252
2252
2253 def changectx(self):
2253 def changectx(self):
2254 return self._parent
2254 return self._parent
2255
2255
2256 def data(self):
2256 def data(self):
2257 return self._parent.data(self._path)
2257 return self._parent.data(self._path)
2258
2258
2259 def date(self):
2259 def date(self):
2260 return self._parent.filedate(self._path)
2260 return self._parent.filedate(self._path)
2261
2261
2262 def exists(self):
2262 def exists(self):
2263 return self.lexists()
2263 return self.lexists()
2264
2264
2265 def lexists(self):
2265 def lexists(self):
2266 return self._parent.exists(self._path)
2266 return self._parent.exists(self._path)
2267
2267
2268 def renamed(self):
2268 def renamed(self):
2269 path = self._parent.copydata(self._path)
2269 path = self._parent.copydata(self._path)
2270 if not path:
2270 if not path:
2271 return None
2271 return None
2272 return path, self._changectx._parents[0]._manifest.get(path, nullid)
2272 return path, self._changectx._parents[0]._manifest.get(path, nullid)
2273
2273
2274 def size(self):
2274 def size(self):
2275 return self._parent.size(self._path)
2275 return self._parent.size(self._path)
2276
2276
2277 def markcopied(self, origin):
2277 def markcopied(self, origin):
2278 self._parent.markcopied(self._path, origin)
2278 self._parent.markcopied(self._path, origin)
2279
2279
2280 def audit(self):
2280 def audit(self):
2281 pass
2281 pass
2282
2282
2283 def flags(self):
2283 def flags(self):
2284 return self._parent.flags(self._path)
2284 return self._parent.flags(self._path)
2285
2285
2286 def setflags(self, islink, isexec):
2286 def setflags(self, islink, isexec):
2287 return self._parent.setflags(self._path, islink, isexec)
2287 return self._parent.setflags(self._path, islink, isexec)
2288
2288
2289 def write(self, data, flags, backgroundclose=False, **kwargs):
2289 def write(self, data, flags, backgroundclose=False, **kwargs):
2290 return self._parent.write(self._path, data, flags, **kwargs)
2290 return self._parent.write(self._path, data, flags, **kwargs)
2291
2291
2292 def remove(self, ignoremissing=False):
2292 def remove(self, ignoremissing=False):
2293 return self._parent.remove(self._path)
2293 return self._parent.remove(self._path)
2294
2294
2295 def clearunknown(self):
2295 def clearunknown(self):
2296 pass
2296 pass
2297
2297
2298 class workingcommitctx(workingctx):
2298 class workingcommitctx(workingctx):
2299 """A workingcommitctx object makes access to data related to
2299 """A workingcommitctx object makes access to data related to
2300 the revision being committed convenient.
2300 the revision being committed convenient.
2301
2301
2302 This hides changes in the working directory, if they aren't
2302 This hides changes in the working directory, if they aren't
2303 committed in this context.
2303 committed in this context.
2304 """
2304 """
2305 def __init__(self, repo, changes,
2305 def __init__(self, repo, changes,
2306 text="", user=None, date=None, extra=None):
2306 text="", user=None, date=None, extra=None):
2307 super(workingctx, self).__init__(repo, text, user, date, extra,
2307 super(workingctx, self).__init__(repo, text, user, date, extra,
2308 changes)
2308 changes)
2309
2309
2310 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2310 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2311 """Return matched files only in ``self._status``
2311 """Return matched files only in ``self._status``
2312
2312
2313 Uncommitted files appear "clean" via this context, even if
2313 Uncommitted files appear "clean" via this context, even if
2314 they aren't actually so in the working directory.
2314 they aren't actually so in the working directory.
2315 """
2315 """
2316 if clean:
2316 if clean:
2317 clean = [f for f in self._manifest if f not in self._changedset]
2317 clean = [f for f in self._manifest if f not in self._changedset]
2318 else:
2318 else:
2319 clean = []
2319 clean = []
2320 return scmutil.status([f for f in self._status.modified if match(f)],
2320 return scmutil.status([f for f in self._status.modified if match(f)],
2321 [f for f in self._status.added if match(f)],
2321 [f for f in self._status.added if match(f)],
2322 [f for f in self._status.removed if match(f)],
2322 [f for f in self._status.removed if match(f)],
2323 [], [], [], clean)
2323 [], [], [], clean)
2324
2324
2325 @propertycache
2325 @propertycache
2326 def _changedset(self):
2326 def _changedset(self):
2327 """Return the set of files changed in this context
2327 """Return the set of files changed in this context
2328 """
2328 """
2329 changed = set(self._status.modified)
2329 changed = set(self._status.modified)
2330 changed.update(self._status.added)
2330 changed.update(self._status.added)
2331 changed.update(self._status.removed)
2331 changed.update(self._status.removed)
2332 return changed
2332 return changed
2333
2333
2334 def makecachingfilectxfn(func):
2334 def makecachingfilectxfn(func):
2335 """Create a filectxfn that caches based on the path.
2335 """Create a filectxfn that caches based on the path.
2336
2336
2337 We can't use util.cachefunc because it uses all arguments as the cache
2337 We can't use util.cachefunc because it uses all arguments as the cache
2338 key and this creates a cycle since the arguments include the repo and
2338 key and this creates a cycle since the arguments include the repo and
2339 memctx.
2339 memctx.
2340 """
2340 """
2341 cache = {}
2341 cache = {}
2342
2342
2343 def getfilectx(repo, memctx, path):
2343 def getfilectx(repo, memctx, path):
2344 if path not in cache:
2344 if path not in cache:
2345 cache[path] = func(repo, memctx, path)
2345 cache[path] = func(repo, memctx, path)
2346 return cache[path]
2346 return cache[path]
2347
2347
2348 return getfilectx
2348 return getfilectx
2349
2349
2350 def memfilefromctx(ctx):
2350 def memfilefromctx(ctx):
2351 """Given a context return a memfilectx for ctx[path]
2351 """Given a context return a memfilectx for ctx[path]
2352
2352
2353 This is a convenience method for building a memctx based on another
2353 This is a convenience method for building a memctx based on another
2354 context.
2354 context.
2355 """
2355 """
2356 def getfilectx(repo, memctx, path):
2356 def getfilectx(repo, memctx, path):
2357 fctx = ctx[path]
2357 fctx = ctx[path]
2358 # this is weird but apparently we only keep track of one parent
2358 # this is weird but apparently we only keep track of one parent
2359 # (why not only store that instead of a tuple?)
2359 # (why not only store that instead of a tuple?)
2360 copied = fctx.renamed()
2360 copied = fctx.renamed()
2361 if copied:
2361 if copied:
2362 copied = copied[0]
2362 copied = copied[0]
2363 return memfilectx(repo, memctx, path, fctx.data(),
2363 return memfilectx(repo, memctx, path, fctx.data(),
2364 islink=fctx.islink(), isexec=fctx.isexec(),
2364 islink=fctx.islink(), isexec=fctx.isexec(),
2365 copied=copied)
2365 copied=copied)
2366
2366
2367 return getfilectx
2367 return getfilectx
2368
2368
2369 def memfilefrompatch(patchstore):
2369 def memfilefrompatch(patchstore):
2370 """Given a patch (e.g. patchstore object) return a memfilectx
2370 """Given a patch (e.g. patchstore object) return a memfilectx
2371
2371
2372 This is a convenience method for building a memctx based on a patchstore.
2372 This is a convenience method for building a memctx based on a patchstore.
2373 """
2373 """
2374 def getfilectx(repo, memctx, path):
2374 def getfilectx(repo, memctx, path):
2375 data, mode, copied = patchstore.getfile(path)
2375 data, mode, copied = patchstore.getfile(path)
2376 if data is None:
2376 if data is None:
2377 return None
2377 return None
2378 islink, isexec = mode
2378 islink, isexec = mode
2379 return memfilectx(repo, memctx, path, data, islink=islink,
2379 return memfilectx(repo, memctx, path, data, islink=islink,
2380 isexec=isexec, copied=copied)
2380 isexec=isexec, copied=copied)
2381
2381
2382 return getfilectx
2382 return getfilectx
2383
2383
2384 class memctx(committablectx):
2384 class memctx(committablectx):
2385 """Use memctx to perform in-memory commits via localrepo.commitctx().
2385 """Use memctx to perform in-memory commits via localrepo.commitctx().
2386
2386
2387 Revision information is supplied at initialization time while
2387 Revision information is supplied at initialization time while
2388 related files data and is made available through a callback
2388 related files data and is made available through a callback
2389 mechanism. 'repo' is the current localrepo, 'parents' is a
2389 mechanism. 'repo' is the current localrepo, 'parents' is a
2390 sequence of two parent revisions identifiers (pass None for every
2390 sequence of two parent revisions identifiers (pass None for every
2391 missing parent), 'text' is the commit message and 'files' lists
2391 missing parent), 'text' is the commit message and 'files' lists
2392 names of files touched by the revision (normalized and relative to
2392 names of files touched by the revision (normalized and relative to
2393 repository root).
2393 repository root).
2394
2394
2395 filectxfn(repo, memctx, path) is a callable receiving the
2395 filectxfn(repo, memctx, path) is a callable receiving the
2396 repository, the current memctx object and the normalized path of
2396 repository, the current memctx object and the normalized path of
2397 requested file, relative to repository root. It is fired by the
2397 requested file, relative to repository root. It is fired by the
2398 commit function for every file in 'files', but calls order is
2398 commit function for every file in 'files', but calls order is
2399 undefined. If the file is available in the revision being
2399 undefined. If the file is available in the revision being
2400 committed (updated or added), filectxfn returns a memfilectx
2400 committed (updated or added), filectxfn returns a memfilectx
2401 object. If the file was removed, filectxfn return None for recent
2401 object. If the file was removed, filectxfn return None for recent
2402 Mercurial. Moved files are represented by marking the source file
2402 Mercurial. Moved files are represented by marking the source file
2403 removed and the new file added with copy information (see
2403 removed and the new file added with copy information (see
2404 memfilectx).
2404 memfilectx).
2405
2405
2406 user receives the committer name and defaults to current
2406 user receives the committer name and defaults to current
2407 repository username, date is the commit date in any format
2407 repository username, date is the commit date in any format
2408 supported by dateutil.parsedate() and defaults to current date, extra
2408 supported by dateutil.parsedate() and defaults to current date, extra
2409 is a dictionary of metadata or is left empty.
2409 is a dictionary of metadata or is left empty.
2410 """
2410 """
2411
2411
2412 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2412 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2413 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2413 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2414 # this field to determine what to do in filectxfn.
2414 # this field to determine what to do in filectxfn.
2415 _returnnoneformissingfiles = True
2415 _returnnoneformissingfiles = True
2416
2416
2417 def __init__(self, repo, parents, text, files, filectxfn, user=None,
2417 def __init__(self, repo, parents, text, files, filectxfn, user=None,
2418 date=None, extra=None, branch=None, editor=False):
2418 date=None, extra=None, branch=None, editor=False):
2419 super(memctx, self).__init__(repo, text, user, date, extra)
2419 super(memctx, self).__init__(repo, text, user, date, extra)
2420 self._rev = None
2420 self._rev = None
2421 self._node = None
2421 self._node = None
2422 parents = [(p or nullid) for p in parents]
2422 parents = [(p or nullid) for p in parents]
2423 p1, p2 = parents
2423 p1, p2 = parents
2424 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
2424 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
2425 files = sorted(set(files))
2425 files = sorted(set(files))
2426 self._files = files
2426 self._files = files
2427 if branch is not None:
2427 if branch is not None:
2428 self._extra['branch'] = encoding.fromlocal(branch)
2428 self._extra['branch'] = encoding.fromlocal(branch)
2429 self.substate = {}
2429 self.substate = {}
2430
2430
2431 if isinstance(filectxfn, patch.filestore):
2431 if isinstance(filectxfn, patch.filestore):
2432 filectxfn = memfilefrompatch(filectxfn)
2432 filectxfn = memfilefrompatch(filectxfn)
2433 elif not callable(filectxfn):
2433 elif not callable(filectxfn):
2434 # if store is not callable, wrap it in a function
2434 # if store is not callable, wrap it in a function
2435 filectxfn = memfilefromctx(filectxfn)
2435 filectxfn = memfilefromctx(filectxfn)
2436
2436
2437 # memoizing increases performance for e.g. vcs convert scenarios.
2437 # memoizing increases performance for e.g. vcs convert scenarios.
2438 self._filectxfn = makecachingfilectxfn(filectxfn)
2438 self._filectxfn = makecachingfilectxfn(filectxfn)
2439
2439
2440 if editor:
2440 if editor:
2441 self._text = editor(self._repo, self, [])
2441 self._text = editor(self._repo, self, [])
2442 self._repo.savecommitmessage(self._text)
2442 self._repo.savecommitmessage(self._text)
2443
2443
2444 def filectx(self, path, filelog=None):
2444 def filectx(self, path, filelog=None):
2445 """get a file context from the working directory
2445 """get a file context from the working directory
2446
2446
2447 Returns None if file doesn't exist and should be removed."""
2447 Returns None if file doesn't exist and should be removed."""
2448 return self._filectxfn(self._repo, self, path)
2448 return self._filectxfn(self._repo, self, path)
2449
2449
2450 def commit(self):
2450 def commit(self):
2451 """commit context to the repo"""
2451 """commit context to the repo"""
2452 return self._repo.commitctx(self)
2452 return self._repo.commitctx(self)
2453
2453
2454 @propertycache
2454 @propertycache
2455 def _manifest(self):
2455 def _manifest(self):
2456 """generate a manifest based on the return values of filectxfn"""
2456 """generate a manifest based on the return values of filectxfn"""
2457
2457
2458 # keep this simple for now; just worry about p1
2458 # keep this simple for now; just worry about p1
2459 pctx = self._parents[0]
2459 pctx = self._parents[0]
2460 man = pctx.manifest().copy()
2460 man = pctx.manifest().copy()
2461
2461
2462 for f in self._status.modified:
2462 for f in self._status.modified:
2463 p1node = nullid
2463 p1node = nullid
2464 p2node = nullid
2464 p2node = nullid
2465 p = pctx[f].parents() # if file isn't in pctx, check p2?
2465 p = pctx[f].parents() # if file isn't in pctx, check p2?
2466 if len(p) > 0:
2466 if len(p) > 0:
2467 p1node = p[0].filenode()
2467 p1node = p[0].filenode()
2468 if len(p) > 1:
2468 if len(p) > 1:
2469 p2node = p[1].filenode()
2469 p2node = p[1].filenode()
2470 man[f] = revlog.hash(self[f].data(), p1node, p2node)
2470 man[f] = revlog.hash(self[f].data(), p1node, p2node)
2471
2471
2472 for f in self._status.added:
2472 for f in self._status.added:
2473 man[f] = revlog.hash(self[f].data(), nullid, nullid)
2473 man[f] = revlog.hash(self[f].data(), nullid, nullid)
2474
2474
2475 for f in self._status.removed:
2475 for f in self._status.removed:
2476 if f in man:
2476 if f in man:
2477 del man[f]
2477 del man[f]
2478
2478
2479 return man
2479 return man
2480
2480
2481 @propertycache
2481 @propertycache
2482 def _status(self):
2482 def _status(self):
2483 """Calculate exact status from ``files`` specified at construction
2483 """Calculate exact status from ``files`` specified at construction
2484 """
2484 """
2485 man1 = self.p1().manifest()
2485 man1 = self.p1().manifest()
2486 p2 = self._parents[1]
2486 p2 = self._parents[1]
2487 # "1 < len(self._parents)" can't be used for checking
2487 # "1 < len(self._parents)" can't be used for checking
2488 # existence of the 2nd parent, because "memctx._parents" is
2488 # existence of the 2nd parent, because "memctx._parents" is
2489 # explicitly initialized by the list, of which length is 2.
2489 # explicitly initialized by the list, of which length is 2.
2490 if p2.node() != nullid:
2490 if p2.node() != nullid:
2491 man2 = p2.manifest()
2491 man2 = p2.manifest()
2492 managing = lambda f: f in man1 or f in man2
2492 managing = lambda f: f in man1 or f in man2
2493 else:
2493 else:
2494 managing = lambda f: f in man1
2494 managing = lambda f: f in man1
2495
2495
2496 modified, added, removed = [], [], []
2496 modified, added, removed = [], [], []
2497 for f in self._files:
2497 for f in self._files:
2498 if not managing(f):
2498 if not managing(f):
2499 added.append(f)
2499 added.append(f)
2500 elif self[f]:
2500 elif self[f]:
2501 modified.append(f)
2501 modified.append(f)
2502 else:
2502 else:
2503 removed.append(f)
2503 removed.append(f)
2504
2504
2505 return scmutil.status(modified, added, removed, [], [], [], [])
2505 return scmutil.status(modified, added, removed, [], [], [], [])
2506
2506
2507 class memfilectx(committablefilectx):
2507 class memfilectx(committablefilectx):
2508 """memfilectx represents an in-memory file to commit.
2508 """memfilectx represents an in-memory file to commit.
2509
2509
2510 See memctx and committablefilectx for more details.
2510 See memctx and committablefilectx for more details.
2511 """
2511 """
2512 def __init__(self, repo, changectx, path, data, islink=False,
2512 def __init__(self, repo, changectx, path, data, islink=False,
2513 isexec=False, copied=None):
2513 isexec=False, copied=None):
2514 """
2514 """
2515 path is the normalized file path relative to repository root.
2515 path is the normalized file path relative to repository root.
2516 data is the file content as a string.
2516 data is the file content as a string.
2517 islink is True if the file is a symbolic link.
2517 islink is True if the file is a symbolic link.
2518 isexec is True if the file is executable.
2518 isexec is True if the file is executable.
2519 copied is the source file path if current file was copied in the
2519 copied is the source file path if current file was copied in the
2520 revision being committed, or None."""
2520 revision being committed, or None."""
2521 super(memfilectx, self).__init__(repo, path, None, changectx)
2521 super(memfilectx, self).__init__(repo, path, None, changectx)
2522 self._data = data
2522 self._data = data
2523 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
2523 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
2524 self._copied = None
2524 self._copied = None
2525 if copied:
2525 if copied:
2526 self._copied = (copied, nullid)
2526 self._copied = (copied, nullid)
2527
2527
2528 def data(self):
2528 def data(self):
2529 return self._data
2529 return self._data
2530
2530
2531 def remove(self, ignoremissing=False):
2531 def remove(self, ignoremissing=False):
2532 """wraps unlink for a repo's working directory"""
2532 """wraps unlink for a repo's working directory"""
2533 # need to figure out what to do here
2533 # need to figure out what to do here
2534 del self._changectx[self._path]
2534 del self._changectx[self._path]
2535
2535
2536 def write(self, data, flags, **kwargs):
2536 def write(self, data, flags, **kwargs):
2537 """wraps repo.wwrite"""
2537 """wraps repo.wwrite"""
2538 self._data = data
2538 self._data = data
2539
2539
2540 class overlayfilectx(committablefilectx):
2540 class overlayfilectx(committablefilectx):
2541 """Like memfilectx but take an original filectx and optional parameters to
2541 """Like memfilectx but take an original filectx and optional parameters to
2542 override parts of it. This is useful when fctx.data() is expensive (i.e.
2542 override parts of it. This is useful when fctx.data() is expensive (i.e.
2543 flag processor is expensive) and raw data, flags, and filenode could be
2543 flag processor is expensive) and raw data, flags, and filenode could be
2544 reused (ex. rebase or mode-only amend a REVIDX_EXTSTORED file).
2544 reused (ex. rebase or mode-only amend a REVIDX_EXTSTORED file).
2545 """
2545 """
2546
2546
2547 def __init__(self, originalfctx, datafunc=None, path=None, flags=None,
2547 def __init__(self, originalfctx, datafunc=None, path=None, flags=None,
2548 copied=None, ctx=None):
2548 copied=None, ctx=None):
2549 """originalfctx: filecontext to duplicate
2549 """originalfctx: filecontext to duplicate
2550
2550
2551 datafunc: None or a function to override data (file content). It is a
2551 datafunc: None or a function to override data (file content). It is a
2552 function to be lazy. path, flags, copied, ctx: None or overridden value
2552 function to be lazy. path, flags, copied, ctx: None or overridden value
2553
2553
2554 copied could be (path, rev), or False. copied could also be just path,
2554 copied could be (path, rev), or False. copied could also be just path,
2555 and will be converted to (path, nullid). This simplifies some callers.
2555 and will be converted to (path, nullid). This simplifies some callers.
2556 """
2556 """
2557
2557
2558 if path is None:
2558 if path is None:
2559 path = originalfctx.path()
2559 path = originalfctx.path()
2560 if ctx is None:
2560 if ctx is None:
2561 ctx = originalfctx.changectx()
2561 ctx = originalfctx.changectx()
2562 ctxmatch = lambda: True
2562 ctxmatch = lambda: True
2563 else:
2563 else:
2564 ctxmatch = lambda: ctx == originalfctx.changectx()
2564 ctxmatch = lambda: ctx == originalfctx.changectx()
2565
2565
2566 repo = originalfctx.repo()
2566 repo = originalfctx.repo()
2567 flog = originalfctx.filelog()
2567 flog = originalfctx.filelog()
2568 super(overlayfilectx, self).__init__(repo, path, flog, ctx)
2568 super(overlayfilectx, self).__init__(repo, path, flog, ctx)
2569
2569
2570 if copied is None:
2570 if copied is None:
2571 copied = originalfctx.renamed()
2571 copied = originalfctx.renamed()
2572 copiedmatch = lambda: True
2572 copiedmatch = lambda: True
2573 else:
2573 else:
2574 if copied and not isinstance(copied, tuple):
2574 if copied and not isinstance(copied, tuple):
2575 # repo._filecommit will recalculate copyrev so nullid is okay
2575 # repo._filecommit will recalculate copyrev so nullid is okay
2576 copied = (copied, nullid)
2576 copied = (copied, nullid)
2577 copiedmatch = lambda: copied == originalfctx.renamed()
2577 copiedmatch = lambda: copied == originalfctx.renamed()
2578
2578
2579 # When data, copied (could affect data), ctx (could affect filelog
2579 # When data, copied (could affect data), ctx (could affect filelog
2580 # parents) are not overridden, rawdata, rawflags, and filenode may be
2580 # parents) are not overridden, rawdata, rawflags, and filenode may be
2581 # reused (repo._filecommit should double check filelog parents).
2581 # reused (repo._filecommit should double check filelog parents).
2582 #
2582 #
2583 # path, flags are not hashed in filelog (but in manifestlog) so they do
2583 # path, flags are not hashed in filelog (but in manifestlog) so they do
2584 # not affect reusable here.
2584 # not affect reusable here.
2585 #
2585 #
2586 # If ctx or copied is overridden to a same value with originalfctx,
2586 # If ctx or copied is overridden to a same value with originalfctx,
2587 # still consider it's reusable. originalfctx.renamed() may be a bit
2587 # still consider it's reusable. originalfctx.renamed() may be a bit
2588 # expensive so it's not called unless necessary. Assuming datafunc is
2588 # expensive so it's not called unless necessary. Assuming datafunc is
2589 # always expensive, do not call it for this "reusable" test.
2589 # always expensive, do not call it for this "reusable" test.
2590 reusable = datafunc is None and ctxmatch() and copiedmatch()
2590 reusable = datafunc is None and ctxmatch() and copiedmatch()
2591
2591
2592 if datafunc is None:
2592 if datafunc is None:
2593 datafunc = originalfctx.data
2593 datafunc = originalfctx.data
2594 if flags is None:
2594 if flags is None:
2595 flags = originalfctx.flags()
2595 flags = originalfctx.flags()
2596
2596
2597 self._datafunc = datafunc
2597 self._datafunc = datafunc
2598 self._flags = flags
2598 self._flags = flags
2599 self._copied = copied
2599 self._copied = copied
2600
2600
2601 if reusable:
2601 if reusable:
2602 # copy extra fields from originalfctx
2602 # copy extra fields from originalfctx
2603 attrs = ['rawdata', 'rawflags', '_filenode', '_filerev']
2603 attrs = ['rawdata', 'rawflags', '_filenode', '_filerev']
2604 for attr_ in attrs:
2604 for attr_ in attrs:
2605 if util.safehasattr(originalfctx, attr_):
2605 if util.safehasattr(originalfctx, attr_):
2606 setattr(self, attr_, getattr(originalfctx, attr_))
2606 setattr(self, attr_, getattr(originalfctx, attr_))
2607
2607
2608 def data(self):
2608 def data(self):
2609 return self._datafunc()
2609 return self._datafunc()
2610
2610
2611 class metadataonlyctx(committablectx):
2611 class metadataonlyctx(committablectx):
2612 """Like memctx but it's reusing the manifest of different commit.
2612 """Like memctx but it's reusing the manifest of different commit.
2613 Intended to be used by lightweight operations that are creating
2613 Intended to be used by lightweight operations that are creating
2614 metadata-only changes.
2614 metadata-only changes.
2615
2615
2616 Revision information is supplied at initialization time. 'repo' is the
2616 Revision information is supplied at initialization time. 'repo' is the
2617 current localrepo, 'ctx' is original revision which manifest we're reuisng
2617 current localrepo, 'ctx' is original revision which manifest we're reuisng
2618 'parents' is a sequence of two parent revisions identifiers (pass None for
2618 'parents' is a sequence of two parent revisions identifiers (pass None for
2619 every missing parent), 'text' is the commit.
2619 every missing parent), 'text' is the commit.
2620
2620
2621 user receives the committer name and defaults to current repository
2621 user receives the committer name and defaults to current repository
2622 username, date is the commit date in any format supported by
2622 username, date is the commit date in any format supported by
2623 dateutil.parsedate() and defaults to current date, extra is a dictionary of
2623 dateutil.parsedate() and defaults to current date, extra is a dictionary of
2624 metadata or is left empty.
2624 metadata or is left empty.
2625 """
2625 """
2626 def __new__(cls, repo, originalctx, *args, **kwargs):
2626 def __new__(cls, repo, originalctx, *args, **kwargs):
2627 return super(metadataonlyctx, cls).__new__(cls, repo)
2627 return super(metadataonlyctx, cls).__new__(cls, repo)
2628
2628
2629 def __init__(self, repo, originalctx, parents=None, text=None, user=None,
2629 def __init__(self, repo, originalctx, parents=None, text=None, user=None,
2630 date=None, extra=None, editor=False):
2630 date=None, extra=None, editor=False):
2631 if text is None:
2631 if text is None:
2632 text = originalctx.description()
2632 text = originalctx.description()
2633 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2633 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2634 self._rev = None
2634 self._rev = None
2635 self._node = None
2635 self._node = None
2636 self._originalctx = originalctx
2636 self._originalctx = originalctx
2637 self._manifestnode = originalctx.manifestnode()
2637 self._manifestnode = originalctx.manifestnode()
2638 if parents is None:
2638 if parents is None:
2639 parents = originalctx.parents()
2639 parents = originalctx.parents()
2640 else:
2640 else:
2641 parents = [repo[p] for p in parents if p is not None]
2641 parents = [repo[p] for p in parents if p is not None]
2642 parents = parents[:]
2642 parents = parents[:]
2643 while len(parents) < 2:
2643 while len(parents) < 2:
2644 parents.append(repo[nullid])
2644 parents.append(repo[nullid])
2645 p1, p2 = self._parents = parents
2645 p1, p2 = self._parents = parents
2646
2646
2647 # sanity check to ensure that the reused manifest parents are
2647 # sanity check to ensure that the reused manifest parents are
2648 # manifests of our commit parents
2648 # manifests of our commit parents
2649 mp1, mp2 = self.manifestctx().parents
2649 mp1, mp2 = self.manifestctx().parents
2650 if p1 != nullid and p1.manifestnode() != mp1:
2650 if p1 != nullid and p1.manifestnode() != mp1:
2651 raise RuntimeError('can\'t reuse the manifest: '
2651 raise RuntimeError('can\'t reuse the manifest: '
2652 'its p1 doesn\'t match the new ctx p1')
2652 'its p1 doesn\'t match the new ctx p1')
2653 if p2 != nullid and p2.manifestnode() != mp2:
2653 if p2 != nullid and p2.manifestnode() != mp2:
2654 raise RuntimeError('can\'t reuse the manifest: '
2654 raise RuntimeError('can\'t reuse the manifest: '
2655 'its p2 doesn\'t match the new ctx p2')
2655 'its p2 doesn\'t match the new ctx p2')
2656
2656
2657 self._files = originalctx.files()
2657 self._files = originalctx.files()
2658 self.substate = {}
2658 self.substate = {}
2659
2659
2660 if editor:
2660 if editor:
2661 self._text = editor(self._repo, self, [])
2661 self._text = editor(self._repo, self, [])
2662 self._repo.savecommitmessage(self._text)
2662 self._repo.savecommitmessage(self._text)
2663
2663
2664 def manifestnode(self):
2664 def manifestnode(self):
2665 return self._manifestnode
2665 return self._manifestnode
2666
2666
2667 @property
2667 @property
2668 def _manifestctx(self):
2668 def _manifestctx(self):
2669 return self._repo.manifestlog[self._manifestnode]
2669 return self._repo.manifestlog[self._manifestnode]
2670
2670
2671 def filectx(self, path, filelog=None):
2671 def filectx(self, path, filelog=None):
2672 return self._originalctx.filectx(path, filelog=filelog)
2672 return self._originalctx.filectx(path, filelog=filelog)
2673
2673
2674 def commit(self):
2674 def commit(self):
2675 """commit context to the repo"""
2675 """commit context to the repo"""
2676 return self._repo.commitctx(self)
2676 return self._repo.commitctx(self)
2677
2677
2678 @property
2678 @property
2679 def _manifest(self):
2679 def _manifest(self):
2680 return self._originalctx.manifest()
2680 return self._originalctx.manifest()
2681
2681
2682 @propertycache
2682 @propertycache
2683 def _status(self):
2683 def _status(self):
2684 """Calculate exact status from ``files`` specified in the ``origctx``
2684 """Calculate exact status from ``files`` specified in the ``origctx``
2685 and parents manifests.
2685 and parents manifests.
2686 """
2686 """
2687 man1 = self.p1().manifest()
2687 man1 = self.p1().manifest()
2688 p2 = self._parents[1]
2688 p2 = self._parents[1]
2689 # "1 < len(self._parents)" can't be used for checking
2689 # "1 < len(self._parents)" can't be used for checking
2690 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2690 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2691 # explicitly initialized by the list, of which length is 2.
2691 # explicitly initialized by the list, of which length is 2.
2692 if p2.node() != nullid:
2692 if p2.node() != nullid:
2693 man2 = p2.manifest()
2693 man2 = p2.manifest()
2694 managing = lambda f: f in man1 or f in man2
2694 managing = lambda f: f in man1 or f in man2
2695 else:
2695 else:
2696 managing = lambda f: f in man1
2696 managing = lambda f: f in man1
2697
2697
2698 modified, added, removed = [], [], []
2698 modified, added, removed = [], [], []
2699 for f in self._files:
2699 for f in self._files:
2700 if not managing(f):
2700 if not managing(f):
2701 added.append(f)
2701 added.append(f)
2702 elif f in self:
2702 elif f in self:
2703 modified.append(f)
2703 modified.append(f)
2704 else:
2704 else:
2705 removed.append(f)
2705 removed.append(f)
2706
2706
2707 return scmutil.status(modified, added, removed, [], [], [], [])
2707 return scmutil.status(modified, added, removed, [], [], [], [])
2708
2708
2709 class arbitraryfilectx(object):
2709 class arbitraryfilectx(object):
2710 """Allows you to use filectx-like functions on a file in an arbitrary
2710 """Allows you to use filectx-like functions on a file in an arbitrary
2711 location on disk, possibly not in the working directory.
2711 location on disk, possibly not in the working directory.
2712 """
2712 """
2713 def __init__(self, path, repo=None):
2713 def __init__(self, path, repo=None):
2714 # Repo is optional because contrib/simplemerge uses this class.
2714 # Repo is optional because contrib/simplemerge uses this class.
2715 self._repo = repo
2715 self._repo = repo
2716 self._path = path
2716 self._path = path
2717
2717
2718 def cmp(self, fctx):
2718 def cmp(self, fctx):
2719 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
2719 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
2720 # path if either side is a symlink.
2720 # path if either side is a symlink.
2721 symlinks = ('l' in self.flags() or 'l' in fctx.flags())
2721 symlinks = ('l' in self.flags() or 'l' in fctx.flags())
2722 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
2722 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
2723 # Add a fast-path for merge if both sides are disk-backed.
2723 # Add a fast-path for merge if both sides are disk-backed.
2724 # Note that filecmp uses the opposite return values (True if same)
2724 # Note that filecmp uses the opposite return values (True if same)
2725 # from our cmp functions (True if different).
2725 # from our cmp functions (True if different).
2726 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
2726 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
2727 return self.data() != fctx.data()
2727 return self.data() != fctx.data()
2728
2728
2729 def path(self):
2729 def path(self):
2730 return self._path
2730 return self._path
2731
2731
2732 def flags(self):
2732 def flags(self):
2733 return ''
2733 return ''
2734
2734
2735 def data(self):
2735 def data(self):
2736 return util.readfile(self._path)
2736 return util.readfile(self._path)
2737
2737
2738 def decodeddata(self):
2738 def decodeddata(self):
2739 with open(self._path, "rb") as f:
2739 with open(self._path, "rb") as f:
2740 return f.read()
2740 return f.read()
2741
2741
2742 def remove(self):
2742 def remove(self):
2743 util.unlink(self._path)
2743 util.unlink(self._path)
2744
2744
2745 def write(self, data, flags, **kwargs):
2745 def write(self, data, flags, **kwargs):
2746 assert not flags
2746 assert not flags
2747 with open(self._path, "w") as f:
2747 with open(self._path, "w") as f:
2748 f.write(data)
2748 f.write(data)
General Comments 0
You need to be logged in to leave comments. Login now