summaryrefslogtreecommitdiff
path: root/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnChangeList.java
blob: 01f9a213907c063ca477c5c2bbf4cbd9c5adc35d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Created by IntelliJ IDEA.
 * User: yole
 * Date: 28.11.2006
 * Time: 17:20:32
 */
package org.jetbrains.idea.svn.history;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FilePathImpl;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ConstantFunction;
import com.intellij.util.NotNullFunction;
import com.intellij.util.UriUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.*;
import org.jetbrains.idea.svn.api.Depth;
import org.jetbrains.idea.svn.browse.DirectoryEntry;
import org.jetbrains.idea.svn.browse.DirectoryEntryConsumer;
import org.jetbrains.idea.svn.commandLine.SvnBindException;
import org.jetbrains.idea.svn.info.Info;
import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc2.SvnTarget;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class SvnChangeList implements CommittedChangeList {
  private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.svn.history");

  private final SvnVcs myVcs;
  private final SvnRepositoryLocation myLocation;
  private String myRepositoryRoot;
  private long myRevision;
  private String myAuthor;
  private Date myDate;
  private String myMessage;
  private final Set<String> myChangedPaths = new HashSet<String>();
  private final Set<String> myAddedPaths = new HashSet<String>();
  private final Set<String> myDeletedPaths = new HashSet<String>();
  private final Set<String> myReplacedPaths = new HashSet<String>();

  private ChangesListCreationHelper myListsHolder;

  private SVNURL myBranchUrl;

  private boolean myCachedInfoLoaded;

  // key: added path, value: copied-from
  private final TreeMap<String, String> myCopiedAddedPaths = new TreeMap<String, String>();
  private RootUrlInfo myWcRoot;
  private final CommonPathSearcher myCommonPathSearcher;
  private final Set<String> myKnownAsDirectories;

  public SvnChangeList(@NotNull final List<CommittedChangeList> lists, @NotNull final SvnRepositoryLocation location) {

    final SvnChangeList sample = (SvnChangeList) lists.get(0);
    myVcs = sample.myVcs;
    myLocation = location;
    myRevision = sample.myRevision;
    myAuthor = sample.myAuthor;
    myDate = sample.myDate;
    myMessage = sample.myMessage;
    myRepositoryRoot = sample.myRepositoryRoot;
    myCommonPathSearcher = new CommonPathSearcher();

    for (CommittedChangeList list : lists) {
      final SvnChangeList svnList = (SvnChangeList) list;
      myChangedPaths.addAll(svnList.myChangedPaths);
      myAddedPaths.addAll(svnList.myAddedPaths);
      myDeletedPaths.addAll(svnList.myDeletedPaths);
      myReplacedPaths.addAll(svnList.myReplacedPaths);
    }
    myKnownAsDirectories = new HashSet<String>(0);
  }

  public SvnChangeList(SvnVcs vcs, @NotNull final SvnRepositoryLocation location, final LogEntry logEntry, String repositoryRoot) {
    myVcs = vcs;
    myLocation = location;
    myRevision = logEntry.getRevision();
    myAuthor = StringUtil.notNullize(logEntry.getAuthor());
    myDate = logEntry.getDate();
    myMessage = StringUtil.notNullize(logEntry.getMessage());
    myRepositoryRoot = UriUtil.trimTrailingSlashes(repositoryRoot);

    myCommonPathSearcher = new CommonPathSearcher();

    myKnownAsDirectories = new HashSet<String>(0);
    for(LogEntryPath entry : logEntry.getChangedPaths().values()) {
      final String path = entry.getPath();

      if (entry.isDirectory()) {
        myKnownAsDirectories.add(path);
      }

      myCommonPathSearcher.next(path);
      
      if (entry.getType() == 'A') {
        if (entry.getCopyPath() != null) {
          myCopiedAddedPaths.put(path, entry.getCopyPath());
        }
        myAddedPaths.add(path);
      }
      else if (entry.getType() == 'D') {
        myDeletedPaths.add(path);
      }
      else {
        if (entry.getType() == 'R') {
          myReplacedPaths.add(path);
        }
        myChangedPaths.add(path);
      }
    }
  }

  public SvnChangeList(SvnVcs vcs, @NotNull SvnRepositoryLocation location, DataInput stream, final boolean supportsCopyFromInfo,
                       final boolean supportsReplaced) throws IOException {
    myVcs = vcs;
    myLocation = location;
    myKnownAsDirectories = new HashSet<String>();
    readFromStream(stream, supportsCopyFromInfo, supportsReplaced);
    myCommonPathSearcher = new CommonPathSearcher();
    myCommonPathSearcher.next(myAddedPaths);
    myCommonPathSearcher.next(myDeletedPaths);
    myCommonPathSearcher.next(myChangedPaths);
  }

  public Change getByPath(final String path) {
    if (myListsHolder == null) {
      createLists();
    }
    return myListsHolder.getByPath(path);
  }

  public String getCommitterName() {
    return myAuthor;
  }

  public Date getCommitDate() {
    return myDate;
  }


  public Collection<Change> getChanges() {
    if (myListsHolder == null) {
      createLists();
    }
    return myListsHolder.getList();
  }

  private void createLists() {
    myListsHolder = new ChangesListCreationHelper();
    
    // key: copied-from
    final Map<String, ExternallyRenamedChange> copiedAddedChanges = new HashMap<String, ExternallyRenamedChange>();

    correctBeforePaths();
    final List<String> copyDeleted = new ArrayList<String>(myDeletedPaths);

    for(String path: myAddedPaths) {
      final Change addedChange;
      if (myCopiedAddedPaths.containsKey(path)) {
        final String copyTarget = myCopiedAddedPaths.get(path);
        if (copyDeleted.contains(copyTarget)) {
          addedChange = new ExternallyRenamedChange(myListsHolder.createRevisionLazily(copyTarget, true),
                                                    myListsHolder.createRevisionLazily(path, false), copyTarget);
          addedChange.getMoveRelativePath(myVcs.getProject());
          ((ExternallyRenamedChange) addedChange).setCopied(false);
          copyDeleted.remove(copyTarget);
        } else {
          addedChange = new ExternallyRenamedChange(null, myListsHolder.createRevisionLazily(path, false), copyTarget);
        }
        copiedAddedChanges.put(copyTarget, (ExternallyRenamedChange) addedChange);
      } else {
        addedChange = new Change(null, myListsHolder.createRevisionLazily(path, false));
      }
      myListsHolder.add(path, addedChange);
    }
    for(String path: copyDeleted) {
      final Change deletedChange;
      if (copiedAddedChanges.containsKey(path)) {
        // seems never occurs any more
        final ExternallyRenamedChange addedChange = copiedAddedChanges.get(path);
        final FilePath source = addedChange.getAfterRevision().getFile();
        deletedChange = new ExternallyRenamedChange(myListsHolder.createDeletedItemRevision(path, true), null, path);
        ((ExternallyRenamedChange) deletedChange).setCopied(false);
        //noinspection ConstantConditions
        //addedChange.setRenamedOrMovedTarget(deletedChange.getBeforeRevision().getFile());
        //noinspection ConstantConditions
        ((ExternallyRenamedChange) deletedChange).setRenamedOrMovedTarget(source);
      } else {
        deletedChange = new Change(myListsHolder.createDeletedItemRevision(path, true), null);
      }
      myListsHolder.add(path, deletedChange);
    }
    for(String path: myChangedPaths) {
      boolean moveAndChange = false;
      final boolean replaced = myReplacedPaths.contains(path);

      // this piece: for copied-from (or moved) and further modified
      for (String addedPath : myAddedPaths) {
        String copyFromPath = myCopiedAddedPaths.get(addedPath);
        if ((copyFromPath != null) && (SVNPathUtil.isAncestor(addedPath, path))) {
          if (addedPath.length() < path.length()) {
            final String relative = SVNPathUtil.getRelativePath(addedPath, path);
            copyFromPath = SVNPathUtil.append(copyFromPath, relative);
          }
          final ExternallyRenamedChange renamedChange = new ExternallyRenamedChange(myListsHolder.createRevisionLazily(copyFromPath, true),
                                                     myListsHolder.createRevisionLazily(path, false), copyFromPath);
          moveAndChange = true;
          renamedChange.getMoveRelativePath(myVcs.getProject());
          renamedChange.setIsReplaced(replaced);

          final ExternallyRenamedChange addedChange = copiedAddedChanges.get(myCopiedAddedPaths.get(addedPath));
          renamedChange.setCopied(addedChange != null && addedChange.isCopied());

          myListsHolder.add(path, renamedChange);
          break;
        }
      }
      if (! moveAndChange) {
        final ExternallyRenamedChange renamedChange =
          new ExternallyRenamedChange(myListsHolder.createRevisionLazily(path, true), myListsHolder.createRevisionLazily(path, false),
                                      null);
        renamedChange.setIsReplaced(replaced);
        renamedChange.setCopied(false);
        myListsHolder.add(path, renamedChange);
      }
    }
  }

  private void correctBeforePaths() {
    processDeletedForBeforePaths(myDeletedPaths);
    processModifiedForBeforePaths(myChangedPaths);
    processModifiedForBeforePaths(myReplacedPaths);
  }

  private void processModifiedForBeforePaths(Set<String> paths) {
    final RenameHelper helper = new RenameHelper();
    for (String s : paths) {
      final String converted = helper.convertBeforePath(s, myCopiedAddedPaths);
      if (! s.equals(converted)) {
        myCopiedAddedPaths.put(s, converted);
      }
    }
  }

  private void processDeletedForBeforePaths(Set<String> paths) {
    final RenameHelper helper = new RenameHelper();
    final HashSet<String> copy = new HashSet<String>(paths);
    paths.clear();
    for (String s : copy) {
      paths.add(helper.convertBeforePath(s, myCopiedAddedPaths));
    }
  }

  @Nullable
  private FilePath getLocalPath(final String path, final NotNullFunction<File, Boolean> detector) {
    return SvnRepositoryLocation.getLocalPath(myRepositoryRoot + path, detector, myVcs);
  }

  private long getRevision(final boolean isBeforeRevision) {
    return isBeforeRevision ? (myRevision - 1) : myRevision;
  }

  public SvnRepositoryLocation getLocation() {
    return myLocation;
  }

  /**
   * needed to track in which changes non-local files live
   */
  private class ChangesListCreationHelper {
    private final List<Change> myList;
    private final Map<String, Change> myPathToChangeMapping;
    private List<Change> myDetailedList;
    private final List<Pair<Integer, Boolean>> myWithoutDirStatus;

    private ChangesListCreationHelper() {
      myList = new ArrayList<Change>();
      myWithoutDirStatus = new ArrayList<Pair<Integer, Boolean>>();
      myPathToChangeMapping = new HashMap<String, Change>();
    }

    public void add(final String path, final Change change) {
      patchChange(change, path);
      myList.add(change);
      myPathToChangeMapping.put(path, change);
    }

    public Change getByPath(final String path) {
      return myPathToChangeMapping.get(path);
    }

    private FilePath localDeletedPath(final String fullPath, final boolean isDir) {
      final SvnFileUrlMapping urlMapping = myVcs.getSvnFileUrlMapping();
      final String path = urlMapping.getLocalPath(fullPath);
      if (path != null) {
        File file = new File(path);
        return VcsUtil.getFilePathForDeletedFile(path, isDir || file.isDirectory());
      }

      return null;
    }

    public SvnRepositoryContentRevision createDeletedItemRevision(final String path, final boolean isBeforeRevision) {
      final boolean knownAsDirectory = myKnownAsDirectories.contains(path);
      final String fullPath = myRepositoryRoot + path;
      if (! knownAsDirectory) {
        myWithoutDirStatus.add(Pair.create(myList.size(), isBeforeRevision));
      }
      return SvnRepositoryContentRevision.create(myVcs, myRepositoryRoot, path, localDeletedPath(fullPath, knownAsDirectory),
                                                 getRevision(isBeforeRevision));
    }

    public SvnRepositoryContentRevision createRevisionLazily(final String path, final boolean isBeforeRevision) {
      final boolean knownAsDirectory = myKnownAsDirectories.contains(path);
      final FilePath localPath = getLocalPath(path, new NotNullFunction<File, Boolean>() {
        @NotNull
        public Boolean fun(final File file) {
          if (knownAsDirectory) return Boolean.TRUE;
          // list will be next
          myWithoutDirStatus.add(new Pair<Integer, Boolean>(myList.size(), isBeforeRevision));
          return Boolean.FALSE;
        }
      });
      final SvnRepositoryContentRevision contentRevision =
        SvnRepositoryContentRevision.create(myVcs, myRepositoryRoot, path, localPath, getRevision(isBeforeRevision));
      if (knownAsDirectory) {
        ((FilePathImpl) contentRevision.getFile()).setIsDirectory(true);
      }
      return contentRevision;
    }

    public List<Change> getList() {
      return myList;
    }

    public List<Change> getDetailedList() {
      if (myDetailedList == null) {
        myDetailedList = new ArrayList<Change>(myList);

        try {
          doRemoteDetails();
          uploadDeletedRenamedChildren();
          ContainerUtil.removeDuplicates(myDetailedList);
        }
        catch (SVNException e) {
          LOG.info(e);
        }
        catch (VcsException e) {
          LOG.info(e);
        }
      }
      return myDetailedList;
    }

    private void doRemoteDetails() throws SVNException, SvnBindException {
      for (Pair<Integer, Boolean> idxData : myWithoutDirStatus) {
        final Change sourceChange = myDetailedList.get(idxData.first.intValue());
        final SvnRepositoryContentRevision revision = (SvnRepositoryContentRevision)
            (idxData.second.booleanValue() ? sourceChange.getBeforeRevision() : sourceChange.getAfterRevision());
        if (revision == null) {
          continue;
        }
        // TODO: Logic with detecting "isDirectory" status is not clear enough. Why we can't just collect this info from logEntry and
        // TODO: if loading from disk - use cached values? Not to invoke separate call here.
        SVNRevision beforeRevision = SVNRevision.create(getRevision(idxData.second.booleanValue()));
        Info info = myVcs.getInfo(SvnUtil.createUrl(revision.getFullPath()), beforeRevision, beforeRevision);
        boolean isDirectory = info != null && info.isDirectory();
        Change replacingChange = new Change(createRevision((SvnRepositoryContentRevision)sourceChange.getBeforeRevision(), isDirectory),
                                            createRevision((SvnRepositoryContentRevision)sourceChange.getAfterRevision(), isDirectory));
        replacingChange.setIsReplaced(sourceChange.isIsReplaced());
        myDetailedList.set(idxData.first.intValue(), replacingChange);
      }

      myWithoutDirStatus.clear();
    }

    @Nullable
    private SvnRepositoryContentRevision createRevision(final SvnRepositoryContentRevision previousRevision, final boolean isDir) {
      return previousRevision == null ? null :
             SvnRepositoryContentRevision.create(myVcs, previousRevision.getFullPath(),
                                                 new FilePathImpl(previousRevision.getFile().getIOFile(), isDir),
                                                 ((SvnRevisionNumber)previousRevision.getRevisionNumber()).getRevision().getNumber());
    }

    private void uploadDeletedRenamedChildren() throws VcsException {
      Set<Pair<Boolean, String>> duplicates = collectDuplicates();
      List<Change> preprocessed = ChangesPreprocess.preprocessChangesRemoveDeletedForDuplicateMoved(myDetailedList);

      myDetailedList.addAll(collectDetails(preprocessed, duplicates));
    }

    private List<Change> collectDetails(@NotNull List<Change> changes, @NotNull Set<Pair<Boolean, String>> duplicates)
      throws VcsException {
      List<Change> result = ContainerUtil.newArrayList();

      for (Change change : changes) {
        // directory statuses are already uploaded
        if ((change.getAfterRevision() == null) && (change.getBeforeRevision().getFile().isDirectory())) {
          result.addAll(getChildrenAsChanges(change.getBeforeRevision(), true, duplicates));
        } else if ((change.getBeforeRevision() == null) && (change.getAfterRevision().getFile().isDirectory())) {
          // look for renamed folders contents
          if (myCopiedAddedPaths.containsKey(getRelativePath(change.getAfterRevision()))) {
            result.addAll(getChildrenAsChanges(change.getAfterRevision(), false, duplicates));
          }
        } else if ((change.isIsReplaced() || change.isMoved() || change.isRenamed()) && change.getAfterRevision().getFile().isDirectory()) {
          result.addAll(getChildrenAsChanges(change.getBeforeRevision(), true, duplicates));
          result.addAll(getChildrenAsChanges(change.getAfterRevision(), false, duplicates));
        }
      }

      return result;
    }

    private Set<Pair<Boolean, String>> collectDuplicates() {
      Set<Pair<Boolean, String>> result = ContainerUtil.newHashSet();

      for (Change change : myDetailedList) {
        addDuplicate(result, true, change.getBeforeRevision());
        addDuplicate(result, false, change.getAfterRevision());
      }

      return result;
    }

    private void addDuplicate(@NotNull Set<Pair<Boolean, String>> duplicates,
                              boolean isBefore,
                              @Nullable ContentRevision revision) {
      if (revision != null) {
        duplicates.add(Pair.create(isBefore, getRelativePath(revision)));
      }
    }

    @NotNull
    private String getRelativePath(@NotNull ContentRevision revision) {
      return ((SvnRepositoryContentRevision)revision).getRelativePath(myRepositoryRoot);
    }

    @NotNull
    private Collection<Change> getChildrenAsChanges(@NotNull ContentRevision contentRevision,
                                                    final boolean isBefore,
                                                    @NotNull final Set<Pair<Boolean, String>> duplicates)
      throws VcsException {
      final List<Change> result = new ArrayList<Change>();

      final String path = getRelativePath(contentRevision);
      SVNURL fullPath = SvnUtil.createUrl(((SvnRepositoryContentRevision)contentRevision).getFullPath());
      SVNRevision revisionNumber = SVNRevision.create(getRevision(isBefore));
      SvnTarget target = SvnTarget.fromURL(fullPath, revisionNumber);

      myVcs.getFactory(target).createBrowseClient().list(target, revisionNumber, Depth.INFINITY, new DirectoryEntryConsumer() {

        @Override
        public void consume(final DirectoryEntry entry) throws SVNException {
          final String childPath = path + '/' + entry.getRelativePath();

          if (!duplicates.contains(Pair.create(isBefore, childPath))) {
            final ContentRevision contentRevision = createRevision(childPath, isBefore, entry.isDirectory());
            result.add(new Change(isBefore ? contentRevision : null, isBefore ? null : contentRevision));
          }
        }
      });

      return result;
    }

    private SvnRepositoryContentRevision createRevision(final String path, final boolean isBeforeRevision, final boolean isDir) {
      return SvnRepositoryContentRevision.create(myVcs, myRepositoryRoot, path,
                                                 getLocalPath(path, new ConstantFunction<File, Boolean>(isDir)), getRevision(isBeforeRevision));
    }
  }

  private static class RenameHelper {

    public String convertBeforePath(final String path, final TreeMap<String, String> after2before) {
      String current = path;
      // backwards
      for (String key : after2before.descendingKeySet()) {
        if (SVNPathUtil.isAncestor(key, current)) {
          final String relativePath = SVNPathUtil.getRelativePath(key, current);
          current = SVNPathUtil.append(after2before.get(key), relativePath);
        }
      }
      return current;
    }
  }

  private void patchChange(Change change, final String path) {
    final SVNURL becameUrl;
    SVNURL wasUrl;
    try {
      becameUrl = SVNURL.parseURIEncoded(SVNPathUtil.append(myRepositoryRoot, path));
      wasUrl = becameUrl;

      if (change instanceof ExternallyRenamedChange && change.getBeforeRevision() != null) {
        String originUrl = ((ExternallyRenamedChange)change).getOriginUrl();

        if (originUrl != null) {
          // use another url for origin
          wasUrl = SVNURL.parseURIEncoded(SVNPathUtil.append(myRepositoryRoot, originUrl));
        }
      }
    }
    catch (SVNException e) {
      // nothing to do
      LOG.info(e);
      return;
    }

    final FilePath filePath = ChangesUtil.getFilePath(change);
    final Change additional = new Change(createPropertyRevision(filePath, change.getBeforeRevision(), wasUrl),
                                         createPropertyRevision(filePath, change.getAfterRevision(), becameUrl));
    change.addAdditionalLayerElement(SvnChangeProvider.PROPERTY_LAYER, additional);
  }

  @Nullable
  private SvnLazyPropertyContentRevision createPropertyRevision(@NotNull FilePath filePath,
                                                                @Nullable ContentRevision revision,
                                                                @NotNull SVNURL url) {
    return revision == null ? null : new SvnLazyPropertyContentRevision(filePath, revision.getRevisionNumber(), myVcs.getProject(), url);
  }

  @NotNull
  public String getName() {
    return myMessage;
  }

  public String getComment() {
    return myMessage;
  }

  public long getNumber() {
    return myRevision;
  }

  @Override
  public String getBranch() {
    return null;
  }

  public AbstractVcs getVcs() {
    return myVcs;
  }

  public Collection<Change> getChangesWithMovedTrees() {
    if (myListsHolder == null) {
      createLists();
    }

    return myListsHolder.getDetailedList();
  }

  @Override
  public boolean isModifiable() {
    return true;
  }

  @Override
  public void setDescription(String newMessage) {
    myMessage = newMessage;
  }

  public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    final SvnChangeList that = (SvnChangeList)o;

    if (myRevision != that.myRevision) return false;
    if (myAuthor != null ? !myAuthor.equals(that.myAuthor) : that.myAuthor != null) return false;
    if (myDate != null ? !myDate.equals(that.myDate) : that.myDate != null) return false;
    if (myMessage != null ? !myMessage.equals(that.myMessage) : that.myMessage != null) return false;

    return true;
  }

  public int hashCode() {
    int result;
    result = (int)(myRevision ^ (myRevision >>> 32));
    result = 31 * result + (myAuthor != null ? myAuthor.hashCode() : 0);
    result = 31 * result + (myDate != null ? myDate.hashCode() : 0);
    result = 31 * result + (myMessage != null ? myMessage.hashCode() : 0);
    return result;
  }

  public String toString() {
    return myMessage;
  }

  public void writeToStream(final DataOutput stream) throws IOException {
    stream.writeUTF(myRepositoryRoot);
    stream.writeLong(myRevision);
    stream.writeUTF(myAuthor);
    stream.writeLong(myDate.getTime());
    writeUTFTruncated(stream, myMessage);
    writeFiles(stream, myChangedPaths);
    writeFiles(stream, myAddedPaths);
    writeFiles(stream, myDeletedPaths);
    writeMap(stream, myCopiedAddedPaths);
    writeFiles(stream, myReplacedPaths);

    stream.writeInt(myKnownAsDirectories.size());
    for (String directory : myKnownAsDirectories) {
      stream.writeUTF(directory);
    }
  }

  // to be able to update plugin only
  public static void writeUTFTruncated(final DataOutput stream, final String text) throws IOException {
    // we should not compare number of symbols to 65635 -> it is number of bytes what should be compared
    // ? 4 bytes per symbol - rough estimation
    if (text.length() > 16383) {
      stream.writeUTF(text.substring(0, 16383));
    }
    else {
      stream.writeUTF(text);
    }
  }

  private static void writeFiles(final DataOutput stream, final Set<String> paths) throws IOException {
    stream.writeInt(paths.size());
    for(String s: paths) {
      stream.writeUTF(s);
    }
  }

  private void readFromStream(final DataInput stream, final boolean supportsCopyFromInfo, final boolean supportsReplaced) throws IOException {
    myRepositoryRoot = stream.readUTF();
    myRevision = stream.readLong();
    myAuthor = stream.readUTF();
    myDate = new Date(stream.readLong());
    myMessage = stream.readUTF();
    readFiles(stream, myChangedPaths);
    readFiles(stream, myAddedPaths);
    readFiles(stream, myDeletedPaths);

    if (supportsCopyFromInfo) {
      readMap(stream, myCopiedAddedPaths);
    }

    if (supportsReplaced) {
      readFiles(stream, myReplacedPaths);
    }

    final int size = stream.readInt();
    for (int i = 0; i < size; i++) {
      myKnownAsDirectories.add(stream.readUTF());
    }
  }

  private static void writeMap(final DataOutput stream, final Map<String, String> map) throws IOException {
    stream.writeInt(map.size());
    for (Map.Entry<String, String> entry : map.entrySet()) {
      stream.writeUTF(entry.getKey());
      stream.writeUTF(entry.getValue());
    }
  }

  private static void readMap(final DataInput stream, final Map<String, String> map) throws IOException {
    int count = stream.readInt();
    for (int i = 0; i < count; i++) {
      map.put(stream.readUTF(), stream.readUTF());
    }
  }

  private static void readFiles(final DataInput stream, final Set<String> paths) throws IOException {
    int count = stream.readInt();
    for(int i=0; i<count; i++) {
      paths.add(stream.readUTF());
    }
  }

  public SVNURL getBranchUrl() {
    ensureCacheUpdated();

    return myBranchUrl;
  }

  @Nullable
  public VirtualFile getVcsRoot() {
    ensureCacheUpdated();

    return myWcRoot == null ? null : myWcRoot.getRoot();
  }

  @Nullable
  public VirtualFile getRoot() {
    ensureCacheUpdated();

    return myWcRoot == null ? null : myWcRoot.getVirtualFile();
  }

  public RootUrlInfo getWcRootInfo() {
    ensureCacheUpdated();

    return myWcRoot;
  }

  private void ensureCacheUpdated() {
    if (!myCachedInfoLoaded) {
      updateCachedInfo();
    }
  }

  private static class CommonPathSearcher {
    private String myCommon;

    public void next(Iterable<String> values) {
      for (String value : values) {
        next(value);
      }
    }

    public void next(final String value) {
      if (value == null) {
        return;
      }
      if (myCommon == null) {
        myCommon = value;
        return;
      }

      if (value.startsWith(myCommon)) {
        return;
      }

      myCommon = SVNPathUtil.getCommonPathAncestor(myCommon, value);
    }

    public String getCommon() {
      return myCommon;
    }
  }

  private void updateCachedInfo() {
    myCachedInfoLoaded = true;

    final String commonPath = myCommonPathSearcher.getCommon();
    if (commonPath != null) {
      final SvnFileUrlMapping urlMapping = myVcs.getSvnFileUrlMapping();
      if (urlMapping.isEmpty()) {
        myCachedInfoLoaded = false;
        return;
      }
      final String absoluteUrl = SVNPathUtil.append(myRepositoryRoot, commonPath);
      myWcRoot = urlMapping.getWcRootForUrl(absoluteUrl);
      if (myWcRoot != null) {
        myBranchUrl = SvnUtil.getBranchForUrl(myVcs, myWcRoot.getVirtualFile(), absoluteUrl);
      }
    }
  }

  public void forceReloadCachedInfo(final boolean reloadRoot) {
    myCachedInfoLoaded = false;
    myBranchUrl = null;

    if (reloadRoot) {
      myWcRoot = null;
    }
  }

  public Set<String> getChangedPaths() {
    return myChangedPaths;
  }

  public Set<String> getAddedPaths() {
    return myAddedPaths;
  }

  public Set<String> getDeletedPaths() {
    return myDeletedPaths;
  }

  @Nullable
  public String getWcPath() {
    final RootUrlInfo rootInfo = getWcRootInfo();

    return rootInfo == null ? null : rootInfo.getIoFile().getAbsolutePath();
  }

  public boolean allPathsUnder(final String path) {
    final String commonRelative = myCommonPathSearcher.getCommon();

    return commonRelative != null && SVNPathUtil.isAncestor(path, SVNPathUtil.append(myRepositoryRoot, commonRelative));
  }
}