1 // TortoiseGitMerge - a Diff/Patch program
3 // Copyright (C) 2009-2013, 2015 - TortoiseGit
4 // Copyright (C) 2012-2013 - Sven Strickroth <email@cs-ware.de>
5 // Copyright (C) 2004-2009,2011-2014 - TortoiseSVN
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License
9 // as published by the Free Software Foundation; either version 2
10 // of the License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software Foundation,
19 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "UnicodeUtils.h"
24 #include "DirFileEnum.h"
25 #include "TortoiseMerge.h"
26 #include "GitAdminDir.h"
32 static char THIS_FILE
[] = __FILE__
;
37 , m_UnicodeType(CFileTextLines::AUTOTYPE
)
46 void CPatch::FreeMemory()
48 for (int i
=0; i
<m_arFileDiffs
.GetCount(); ++i
)
50 Chunks
* chunks
= m_arFileDiffs
.GetAt(i
);
51 for (int j
=0; j
<chunks
->chunks
.GetCount(); ++j
)
53 delete chunks
->chunks
.GetAt(j
);
55 chunks
->chunks
.RemoveAll();
58 m_arFileDiffs
.RemoveAll();
61 BOOL
CPatch::ParsePatchFile(CFileTextLines
&PatchLines
)
64 EOL ending
= EOL_NOENDING
;
68 Chunks
* chunks
= NULL
;
70 int nAddLineCount
= 0;
71 int nRemoveLineCount
= 0;
72 int nContextLineCount
= 0;
73 std::map
<CString
, int> filenamesToPatch
;
74 for ( ; nIndex
< PatchLines
.GetCount(); ++nIndex
)
76 sLine
= PatchLines
.GetAt(nIndex
);
77 ending
= PatchLines
.GetLineEnding(nIndex
);
78 if (ending
!= EOL_NOENDING
)
79 ending
= EOL_AUTOLINE
;
86 if (sLine
.Find(_T("diff ")) == 0)
90 //this is a new file diff, so add the last one to
92 if (chunks
->chunks
.GetCount() > 0)
93 m_arFileDiffs
.Add(chunks
);
97 chunks
= new Chunks();
106 if( sLine
.Find(_T("index"))==0 )
108 int dotstart
=sLine
.Find(_T(".."));
109 if(dotstart
>=0 && chunks
)
111 chunks
->sRevision
= sLine
.Mid(dotstart
-7,7);
112 chunks
->sRevision2
= sLine
.Mid(dotstart
+2,7);
118 if (sLine
.Find(_T("--- ")) == 0)
124 //this is a new file diff, so add the last one to
126 if (chunks
->chunks
.GetCount() > 0)
127 m_arFileDiffs
.Add(chunks
);
131 chunks
= new Chunks();
134 sLine
= sLine
.Mid(3); //remove the "---"
136 //at the end of the filepath there's a revision number...
137 int bracket
= sLine
.ReverseFind('(');
139 // some patch files can have another '(' char, especially ones created in Chinese OS
140 bracket
= sLine
.ReverseFind(0xff08);
144 if (chunks
->sFilePath
.IsEmpty())
145 chunks
->sFilePath
= sLine
.Trim();
148 chunks
->sFilePath
= sLine
.Left(bracket
-1).Trim();
150 if (chunks
->sFilePath
.Find('\t')>=0)
152 chunks
->sFilePath
= chunks
->sFilePath
.Left(chunks
->sFilePath
.Find('\t'));
154 if (chunks
->sFilePath
.Find(_T('"')) == 0 && chunks
->sFilePath
.ReverseFind(_T('"')) == chunks
->sFilePath
.GetLength() - 1)
155 chunks
->sFilePath
=chunks
->sFilePath
.Mid(1, chunks
->sFilePath
.GetLength() - 2);
156 if( chunks
->sFilePath
.Find(_T("a/")) == 0 )
157 chunks
->sFilePath
=chunks
->sFilePath
.Mid(2);
159 if( chunks
->sFilePath
.Find(_T("b/")) == 0 )
160 chunks
->sFilePath
=chunks
->sFilePath
.Mid(2);
163 chunks
->sFilePath
.Replace(_T('/'),_T('\\'));
165 if (chunks
->sFilePath
== _T("\\dev\\null") || chunks
->sFilePath
== _T("/dev/null"))
166 chunks
->sFilePath
= _T("NUL");
172 if (sLine
.Find(_T("@@")) == 0)
189 if (sLine
.Left(3).Compare(_T("+++")) != 0)
191 // no starting "+++" found
192 m_sErrorMessage
.Format(IDS_ERR_PATCH_NOADDFILELINE
, nIndex
);
195 sLine
= sLine
.Mid(3); //remove the "---"
198 //at the end of the filepath there's a revision number...
199 int bracket
= sLine
.ReverseFind('(');
201 // some patch files can have another '(' char, especially ones created in Chinese OS
202 bracket
= sLine
.ReverseFind(0xff08);
205 chunks
->sFilePath2
= sLine
.Trim();
207 chunks
->sFilePath2
= sLine
.Left(bracket
-1).Trim();
208 if (chunks
->sFilePath2
.Find('\t')>=0)
210 chunks
->sFilePath2
= chunks
->sFilePath2
.Left(chunks
->sFilePath2
.Find('\t'));
212 if (chunks
->sFilePath2
.Find(_T('"')) == 0 && chunks
->sFilePath2
.ReverseFind(_T('"')) == chunks
->sFilePath2
.GetLength() - 1)
213 chunks
->sFilePath2
=chunks
->sFilePath2
.Mid(1, chunks
->sFilePath2
.GetLength() - 2);
214 if( chunks
->sFilePath2
.Find(_T("a/")) == 0 )
215 chunks
->sFilePath2
=chunks
->sFilePath2
.Mid(2);
217 if( chunks
->sFilePath2
.Find(_T("b/")) == 0 )
218 chunks
->sFilePath2
=chunks
->sFilePath2
.Mid(2);
220 chunks
->sFilePath2
.Replace(_T('/'),_T('\\'));
222 if (chunks
->sFilePath2
== _T("\\dev\\null") || chunks
->sFilePath2
== _T("/dev/null"))
223 chunks
->sFilePath2
= _T("NUL");
231 //start of a new chunk
232 if (sLine
.Left(2).Compare(_T("@@")) != 0)
234 //chunk doesn't start with "@@"
235 //so there's garbage in between two file diffs
243 for (int i
= 0; i
< chunks
->chunks
.GetCount(); ++i
)
245 delete chunks
->chunks
.GetAt(i
);
247 chunks
->chunks
.RemoveAll();
252 break; //skip the garbage
255 //@@ -xxx,xxx +xxx,xxx @@
256 sLine
= sLine
.Mid(2);
257 sLine
= sLine
.Trim();
259 CString sRemove
= sLine
.Left(sLine
.Find(' '));
260 CString sAdd
= sLine
.Mid(sLine
.Find(' '));
261 chunk
->lRemoveStart
= (-_ttol(sRemove
));
262 if (sRemove
.Find(',')>=0)
264 sRemove
= sRemove
.Mid(sRemove
.Find(',')+1);
265 chunk
->lRemoveLength
= _ttol(sRemove
);
269 chunk
->lRemoveStart
= 0;
270 chunk
->lRemoveLength
= (-_ttol(sRemove
));
272 chunk
->lAddStart
= _ttol(sAdd
);
273 if (sAdd
.Find(',')>=0)
275 sAdd
= sAdd
.Mid(sAdd
.Find(',')+1);
276 chunk
->lAddLength
= _ttol(sAdd
);
280 chunk
->lAddStart
= 1;
281 chunk
->lAddLength
= _ttol(sAdd
);
287 case 5: //[ |+|-] <sourceline>
289 //this line is either a context line (with a ' ' in front)
290 //a line added (with a '+' in front)
291 //or a removed line (with a '-' in front)
296 type
= sLine
.GetAt(0);
299 //it's a context line - we don't use them here right now
300 //but maybe in the future the patch algorithm can be
301 //extended to use those in case the file to patch has
302 //already changed and no base file is around...
303 chunk
->arLines
.Add(RemoveUnicodeBOM(sLine
.Mid(1)));
304 chunk
->arLinesStates
.Add(PATCHSTATE_CONTEXT
);
305 chunk
->arEOLs
.push_back(ending
);
308 else if (type
== '\\')
310 //it's a context line (sort of):
311 //warnings start with a '\' char (e.g. "\ No newline at end of file")
312 //so just ignore this...
314 else if (type
== '-')
317 chunk
->arLines
.Add(RemoveUnicodeBOM(sLine
.Mid(1)));
318 chunk
->arLinesStates
.Add(PATCHSTATE_REMOVED
);
319 chunk
->arEOLs
.push_back(ending
);
322 else if (type
== '+')
325 chunk
->arLines
.Add(RemoveUnicodeBOM(sLine
.Mid(1)));
326 chunk
->arLinesStates
.Add(PATCHSTATE_ADDED
);
327 chunk
->arEOLs
.push_back(ending
);
332 //none of those lines! what the hell happened here?
333 m_sErrorMessage
.Format(IDS_ERR_PATCH_UNKOWNLINETYPE
, nIndex
);
336 if ((chunk
->lAddLength
== (nAddLineCount
+ nContextLineCount
)) &&
337 chunk
->lRemoveLength
== (nRemoveLineCount
+ nContextLineCount
))
341 chunks
->chunks
.Add(chunk
);
346 nContextLineCount
= 0;
347 nRemoveLineCount
= 0;
355 } // for ( ;nIndex<m_PatchLines.GetCount(); nIndex++)
358 m_sErrorMessage
.LoadString(IDS_ERR_PATCH_CHUNKMISMATCH
);
362 m_arFileDiffs
.Add(chunks
);
364 for (int i
= 0; i
< m_arFileDiffs
.GetCount(); ++i
)
366 if (filenamesToPatch
[m_arFileDiffs
.GetAt(i
)->sFilePath
] > 1 && m_arFileDiffs
.GetAt(i
)->sFilePath
!= _T("NUL"))
368 m_sErrorMessage
.Format(IDS_ERR_PATCH_FILENAMENOTUNIQUE
, m_arFileDiffs
.GetAt(i
)->sFilePath
);
372 ++filenamesToPatch
[m_arFileDiffs
.GetAt(i
)->sFilePath
];
373 if (m_arFileDiffs
.GetAt(i
)->sFilePath
!= m_arFileDiffs
.GetAt(i
)->sFilePath2
)
375 if (filenamesToPatch
[m_arFileDiffs
.GetAt(i
)->sFilePath2
] > 1 && m_arFileDiffs
.GetAt(i
)->sFilePath2
!= _T("NUL"))
377 m_sErrorMessage
.Format(IDS_ERR_PATCH_FILENAMENOTUNIQUE
, m_arFileDiffs
.GetAt(i
)->sFilePath
);
381 ++filenamesToPatch
[m_arFileDiffs
.GetAt(i
)->sFilePath2
];
392 for (int i
= 0; i
< chunks
->chunks
.GetCount(); ++i
)
394 delete chunks
->chunks
.GetAt(i
);
396 chunks
->chunks
.RemoveAll();
403 BOOL
CPatch::OpenUnifiedDiffFile(const CString
& filename
)
405 CCrashReport::Instance().AddFile2(filename
, NULL
, _T("unified diff file"), CR_AF_MAKE_FILE_COPY
);
407 CFileTextLines PatchLines
;
408 if (!PatchLines
.Load(filename
))
410 m_sErrorMessage
= PatchLines
.GetErrorString();
415 //now we got all the lines of the patch file
416 //in our array - parsing can start...
417 return ParsePatchFile(PatchLines
);
420 CString
CPatch::GetFilename(int nIndex
)
424 if (nIndex
< m_arFileDiffs
.GetCount())
426 Chunks
* c
= m_arFileDiffs
.GetAt(nIndex
);
427 CString filepath
= Strip(c
->sFilePath
);
433 CString
CPatch::GetRevision(int nIndex
)
437 if (nIndex
< m_arFileDiffs
.GetCount())
439 Chunks
* c
= m_arFileDiffs
.GetAt(nIndex
);
445 CString
CPatch::GetFilename2(int nIndex
)
449 if (nIndex
< m_arFileDiffs
.GetCount())
451 Chunks
* c
= m_arFileDiffs
.GetAt(nIndex
);
452 CString filepath
= Strip(c
->sFilePath2
);
458 CString
CPatch::GetRevision2(int nIndex
)
462 if (nIndex
< m_arFileDiffs
.GetCount())
464 Chunks
* c
= m_arFileDiffs
.GetAt(nIndex
);
465 return c
->sRevision2
;
470 int CPatch::PatchFile(const int strip
, int nIndex
, const CString
& sPatchPath
, const CString
& sSavePath
, const CString
& sBaseFile
, const bool force
)
473 CString sPath
= GetFullPath(sPatchPath
, nIndex
);
474 if (PathIsDirectory(sPath
))
476 m_sErrorMessage
.Format(IDS_ERR_PATCH_INVALIDPATCHFILE
, (LPCTSTR
)sPath
);
481 m_sErrorMessage
.Format(IDS_ERR_PATCH_FILENOTINPATCH
, (LPCTSTR
)sPath
);
485 if (!force
&& sPath
== _T("NUL") && PathFileExists(GetFullPath(sPatchPath
, nIndex
, 1)))
488 if (GetFullPath(sPatchPath
, nIndex
, 1) == _T("NUL") && !PathFileExists(sPath
))
492 CString sPatchFile
= sBaseFile
.IsEmpty() ? sPath
: sBaseFile
;
493 if (PathFileExists(sPatchFile
))
495 CCrashReport::Instance().AddFile2(sPatchFile
, NULL
, _T("File to patch"), CR_AF_MAKE_FILE_COPY
);
497 CFileTextLines PatchLines
;
498 CFileTextLines PatchLinesResult
;
499 PatchLines
.Load(sPatchFile
);
500 PatchLinesResult
= PatchLines
; //.Copy(PatchLines);
501 PatchLines
.CopySettings(&PatchLinesResult
);
503 Chunks
* chunks
= m_arFileDiffs
.GetAt(nIndex
);
505 for (int i
= 0; i
< chunks
->chunks
.GetCount(); ++i
)
507 Chunk
* chunk
= chunks
->chunks
.GetAt(i
);
508 LONG lRemoveLine
= chunk
->lRemoveStart
;
509 LONG lAddLine
= chunk
->lAddStart
;
510 for (int j
= 0; j
< chunk
->arLines
.GetCount(); ++j
)
512 CString sPatchLine
= chunk
->arLines
.GetAt(j
);
513 EOL ending
= chunk
->arEOLs
[j
];
514 if ((m_UnicodeType
!= CFileTextLines::UTF8
)&&(m_UnicodeType
!= CFileTextLines::UTF8BOM
))
516 if ((PatchLines
.GetUnicodeType()==CFileTextLines::UTF8
)||(m_UnicodeType
== CFileTextLines::UTF8BOM
))
518 // convert the UTF-8 contents in CString sPatchLine into a CStringA
519 sPatchLine
= CUnicodeUtils::GetUnicode(CStringA(sPatchLine
));
522 int nPatchState
= (int)chunk
->arLinesStates
.GetAt(j
);
525 case PATCHSTATE_REMOVED
:
527 if ((lAddLine
> PatchLines
.GetCount())||(PatchLines
.GetCount()==0))
529 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, _T(""), (LPCTSTR
)sPatchLine
);
534 if ((sPatchLine
.Compare(PatchLines
.GetAt(lAddLine
-1))!=0)&&(!HasExpandedKeyWords(sPatchLine
)))
536 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, (LPCTSTR
)sPatchLine
, (LPCTSTR
)PatchLines
.GetAt(lAddLine
-1));
539 if (lAddLine
> PatchLines
.GetCount())
541 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, (LPCTSTR
)sPatchLine
, _T(""));
544 PatchLines
.RemoveAt(lAddLine
-1);
547 case PATCHSTATE_ADDED
:
551 // check context after insertions in order to avoid double insertions
552 bool insertOk
= !(lAddLine
< PatchLines
.GetCount());
554 for (; k
< chunk
->arLines
.GetCount(); ++k
)
556 if ((int)chunk
->arLinesStates
.GetAt(k
) == PATCHSTATE_ADDED
)
558 if (PatchLines
.GetCount() >= lAddLine
&& chunk
->arLines
.GetAt(k
).Compare(PatchLines
.GetAt(lAddLine
- 1)) == 0)
566 PatchLines
.InsertAt(lAddLine
-1, sPatchLine
, ending
);
571 if (k
>= chunk
->arLines
.GetCount())
573 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, (LPCTSTR
)PatchLines
.GetAt(lAddLine
- 1), chunk
->arLines
.GetAt(k
));
578 case PATCHSTATE_CONTEXT
:
580 if (lAddLine
> PatchLines
.GetCount())
582 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, _T(""), (LPCTSTR
)sPatchLine
);
587 if (lRemoveLine
== 0)
589 if ((sPatchLine
.Compare(PatchLines
.GetAt(lAddLine
-1))!=0) &&
590 (!HasExpandedKeyWords(sPatchLine
)) &&
591 (lRemoveLine
<= PatchLines
.GetCount()) &&
592 (sPatchLine
.Compare(PatchLines
.GetAt(lRemoveLine
-1))!=0))
594 if ((lAddLine
< PatchLines
.GetCount())&&(sPatchLine
.Compare(PatchLines
.GetAt(lAddLine
))==0))
596 else if (((lAddLine
+ 1) < PatchLines
.GetCount())&&(sPatchLine
.Compare(PatchLines
.GetAt(lAddLine
+1))==0))
598 else if ((lRemoveLine
< PatchLines
.GetCount())&&(sPatchLine
.Compare(PatchLines
.GetAt(lRemoveLine
))==0))
602 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, (LPCTSTR
)sPatchLine
, (LPCTSTR
)PatchLines
.GetAt(lAddLine
-1));
613 } // switch (nPatchState)
614 } // for (j=0; j<chunk->arLines.GetCount(); j++)
615 } // for (int i=0; i<chunks->chunks.GetCount(); i++)
616 if (!sSavePath
.IsEmpty())
618 PatchLines
.Save(sSavePath
, false);
623 BOOL
CPatch::HasExpandedKeyWords(const CString
& line
) const
625 if (line
.Find(_T("$LastChangedDate"))>=0)
627 if (line
.Find(_T("$Date"))>=0)
629 if (line
.Find(_T("$LastChangedRevision"))>=0)
631 if (line
.Find(_T("$Rev"))>=0)
633 if (line
.Find(_T("$LastChangedBy"))>=0)
635 if (line
.Find(_T("$Author"))>=0)
637 if (line
.Find(_T("$HeadURL"))>=0)
639 if (line
.Find(_T("$URL"))>=0)
641 if (line
.Find(_T("$Id"))>=0)
646 CString
CPatch::CheckPatchPath(const CString
& path
)
648 //first check if the path already matches
649 if (CountMatches(path
) > (GetNumberOfFiles()/3))
651 //now go up the tree and try again
652 CString upperpath
= path
;
653 while (upperpath
.ReverseFind('\\')>0)
655 upperpath
= upperpath
.Left(upperpath
.ReverseFind('\\'));
656 if (CountMatches(upperpath
) > (GetNumberOfFiles()/3))
659 //still no match found. So try sub folders
662 CDirFileEnum
filefinder(path
);
663 while (filefinder
.NextFile(subpath
, &isDir
))
667 if (GitAdminDir::IsAdminDirPath(subpath
))
669 if (CountMatches(subpath
) > (GetNumberOfFiles()/3))
673 // if a patch file only contains newly added files
674 // we can't really find the correct path.
675 // But: we can compare paths strings without the filenames
676 // and check if at least those match
678 while (upperpath
.ReverseFind('\\')>0)
680 upperpath
= upperpath
.Left(upperpath
.ReverseFind('\\'));
681 if (CountDirMatches(upperpath
) > (GetNumberOfFiles()/3))
688 int CPatch::CountMatches(const CString
& path
)
691 for (int i
=0; i
<GetNumberOfFiles(); ++i
)
693 CString temp
= GetFilename(i
);
694 temp
.Replace('/', '\\');
695 if (PathIsRelative(temp
))
696 temp
= path
+ _T("\\")+ temp
;
697 if (PathFileExists(temp
))
703 int CPatch::CountDirMatches(const CString
& path
)
706 for (int i
=0; i
<GetNumberOfFiles(); ++i
)
708 CString temp
= GetFilename(i
);
709 temp
.Replace('/', '\\');
710 if (PathIsRelative(temp
))
711 temp
= path
+ _T("\\")+ temp
;
712 // remove the filename
713 temp
= temp
.Left(temp
.ReverseFind('\\'));
714 if (PathFileExists(temp
))
720 BOOL
CPatch::StripPrefixes(const CString
& path
)
723 for (int i
= 0; i
< GetNumberOfFiles(); ++i
)
725 CString filename
= GetFilename(i
);
726 filename
.Replace('/','\\');
727 int nSlashes
= filename
.Replace('\\','/');
728 nSlashesMax
= max(nSlashesMax
,nSlashes
);
731 for (int nStrip
= 1; nStrip
< nSlashesMax
; ++nStrip
)
734 if ( CountMatches(path
) > GetNumberOfFiles()/3 )
736 // Use current m_nStrip
741 // Stripping doesn't help so reset it again
746 CString
CPatch::Strip(const CString
& filename
) const
748 CString s
= filename
;
751 // Remove windows drive letter "c:"
752 if ( s
.GetLength()>2 && s
[1]==':')
757 for (int nStrip
= 1; nStrip
<= m_nStrip
; ++nStrip
)
759 // "/home/ts/my-working-copy/dir/file.txt"
760 // "home/ts/my-working-copy/dir/file.txt"
761 // "ts/my-working-copy/dir/file.txt"
762 // "my-working-copy/dir/file.txt"
764 s
= s
.Mid(s
.FindOneOf(_T("/\\"))+1);
770 CString
CPatch::GetFullPath(const CString
& sPath
, int nIndex
, int fileno
/* = 0*/)
774 temp
= GetFilename(nIndex
);
776 temp
= GetFilename2(nIndex
);
778 temp
.Replace('/', '\\');
779 if(temp
== _T("NUL"))
782 if (PathIsRelative(temp
))
784 if (sPath
.Right(1).Compare(_T("\\")) != 0)
785 temp
= sPath
+ _T("\\") + temp
;
793 CString
CPatch::RemoveUnicodeBOM(const CString
& str
) const
797 if (str
[0] == 0xFEFF)