1 // TortoiseGitMerge - a Diff/Patch program
3 // Copyright (C) 2009-2013 - TortoiseGit
4 // Copyright (C) 2012-2013 - Sven Strickroth <email@cs-ware.de>
5 // Copyright (C) 2004-2009,2011-2012 - 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(".."));
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 (chunk
->arLines
.GetAt(k
).Compare(PatchLines
.GetAt(lAddLine
- 1)) == 0)
566 PatchLines
.InsertAt(lAddLine
-1, sPatchLine
, ending
);
571 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, (LPCTSTR
)PatchLines
.GetAt(lAddLine
- 1), chunk
->arLines
.GetAt(k
));
576 case PATCHSTATE_CONTEXT
:
578 if (lAddLine
> PatchLines
.GetCount())
580 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, _T(""), (LPCTSTR
)sPatchLine
);
585 if (lRemoveLine
== 0)
587 if ((sPatchLine
.Compare(PatchLines
.GetAt(lAddLine
-1))!=0) &&
588 (!HasExpandedKeyWords(sPatchLine
)) &&
589 (lRemoveLine
<= PatchLines
.GetCount()) &&
590 (sPatchLine
.Compare(PatchLines
.GetAt(lRemoveLine
-1))!=0))
592 if ((lAddLine
< PatchLines
.GetCount())&&(sPatchLine
.Compare(PatchLines
.GetAt(lAddLine
))==0))
594 else if (((lAddLine
+ 1) < PatchLines
.GetCount())&&(sPatchLine
.Compare(PatchLines
.GetAt(lAddLine
+1))==0))
596 else if ((lRemoveLine
< PatchLines
.GetCount())&&(sPatchLine
.Compare(PatchLines
.GetAt(lRemoveLine
))==0))
600 m_sErrorMessage
.Format(IDS_ERR_PATCH_DOESNOTMATCH
, (LPCTSTR
)sPatchLine
, (LPCTSTR
)PatchLines
.GetAt(lAddLine
-1));
611 } // switch (nPatchState)
612 } // for (j=0; j<chunk->arLines.GetCount(); j++)
613 } // for (int i=0; i<chunks->chunks.GetCount(); i++)
614 if (!sSavePath
.IsEmpty())
616 PatchLines
.Save(sSavePath
, false);
621 BOOL
CPatch::HasExpandedKeyWords(const CString
& line
)
623 if (line
.Find(_T("$LastChangedDate"))>=0)
625 if (line
.Find(_T("$Date"))>=0)
627 if (line
.Find(_T("$LastChangedRevision"))>=0)
629 if (line
.Find(_T("$Rev"))>=0)
631 if (line
.Find(_T("$LastChangedBy"))>=0)
633 if (line
.Find(_T("$Author"))>=0)
635 if (line
.Find(_T("$HeadURL"))>=0)
637 if (line
.Find(_T("$URL"))>=0)
639 if (line
.Find(_T("$Id"))>=0)
644 CString
CPatch::CheckPatchPath(const CString
& path
)
646 //first check if the path already matches
647 if (CountMatches(path
) > (GetNumberOfFiles()/3))
649 //now go up the tree and try again
650 CString upperpath
= path
;
651 while (upperpath
.ReverseFind('\\')>0)
653 upperpath
= upperpath
.Left(upperpath
.ReverseFind('\\'));
654 if (CountMatches(upperpath
) > (GetNumberOfFiles()/3))
657 //still no match found. So try sub folders
660 CDirFileEnum
filefinder(path
);
661 while (filefinder
.NextFile(subpath
, &isDir
))
665 if (g_GitAdminDir
.IsAdminDirPath(subpath
))
667 if (CountMatches(subpath
) > (GetNumberOfFiles()/3))
671 // if a patch file only contains newly added files
672 // we can't really find the correct path.
673 // But: we can compare paths strings without the filenames
674 // and check if at least those match
676 while (upperpath
.ReverseFind('\\')>0)
678 upperpath
= upperpath
.Left(upperpath
.ReverseFind('\\'));
679 if (CountDirMatches(upperpath
) > (GetNumberOfFiles()/3))
686 int CPatch::CountMatches(const CString
& path
)
689 for (int i
=0; i
<GetNumberOfFiles(); ++i
)
691 CString temp
= GetFilename(i
);
692 temp
.Replace('/', '\\');
693 if (PathIsRelative(temp
))
694 temp
= path
+ _T("\\")+ temp
;
695 if (PathFileExists(temp
))
701 int CPatch::CountDirMatches(const CString
& path
)
704 for (int i
=0; i
<GetNumberOfFiles(); ++i
)
706 CString temp
= GetFilename(i
);
707 temp
.Replace('/', '\\');
708 if (PathIsRelative(temp
))
709 temp
= path
+ _T("\\")+ temp
;
710 // remove the filename
711 temp
= temp
.Left(temp
.ReverseFind('\\'));
712 if (PathFileExists(temp
))
718 BOOL
CPatch::StripPrefixes(const CString
& path
)
721 for (int i
= 0; i
< GetNumberOfFiles(); ++i
)
723 CString filename
= GetFilename(i
);
724 filename
.Replace('/','\\');
725 int nSlashes
= filename
.Replace('\\','/');
726 nSlashesMax
= max(nSlashesMax
,nSlashes
);
729 for (int nStrip
= 1; nStrip
< nSlashesMax
; ++nStrip
)
732 if ( CountMatches(path
) > GetNumberOfFiles()/3 )
734 // Use current m_nStrip
739 // Stripping doesn't help so reset it again
744 CString
CPatch::Strip(const CString
& filename
)
746 CString s
= filename
;
749 // Remove windows drive letter "c:"
750 if ( s
.GetLength()>2 && s
[1]==':')
755 for (int nStrip
= 1; nStrip
<= m_nStrip
; ++nStrip
)
757 // "/home/ts/my-working-copy/dir/file.txt"
758 // "home/ts/my-working-copy/dir/file.txt"
759 // "ts/my-working-copy/dir/file.txt"
760 // "my-working-copy/dir/file.txt"
762 s
= s
.Mid(s
.FindOneOf(_T("/\\"))+1);
768 CString
CPatch::GetFullPath(const CString
& sPath
, int nIndex
, int fileno
/* = 0*/)
772 temp
= GetFilename(nIndex
);
774 temp
= GetFilename2(nIndex
);
776 temp
.Replace('/', '\\');
777 if(temp
== _T("NUL"))
780 if (PathIsRelative(temp
))
782 if (sPath
.Right(1).Compare(_T("\\")) != 0)
783 temp
= sPath
+ _T("\\") + temp
;
791 CString
CPatch::RemoveUnicodeBOM(const CString
& str
)
793 if (str
.GetLength()==0)
795 if (str
[0] == 0xFEFF)