Update cached directory properties
[TortoiseGit.git] / src / Git / TGitPath.cpp
blob9b0f9d6cc3fbb3578906ae46c3d35fb3605c031e
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2017 - TortoiseGit
4 // Copyright (C) 2003-2008 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "TGitPath.h"
22 #include "UnicodeUtils.h"
23 #include "GitAdminDir.h"
24 #include "PathUtils.h"
25 #include <regex>
26 #include "Git.h"
27 #include "../TortoiseShell/Globals.h"
28 #include "StringUtils.h"
29 #include "SmartHandle.h"
30 #include "../Resources/LoglistCommonResource.h"
31 #include <sys/stat.h>
33 extern CGit g_Git;
35 CTGitPath::CTGitPath(void)
36 : m_bDirectoryKnown(false)
37 , m_bIsDirectory(false)
38 , m_bHasAdminDirKnown(false)
39 , m_bHasAdminDir(false)
40 , m_bIsValidOnWindowsKnown(false)
41 , m_bIsValidOnWindows(false)
42 , m_bIsReadOnly(false)
43 , m_bIsAdminDirKnown(false)
44 , m_bIsAdminDir(false)
45 , m_bExists(false)
46 , m_bExistsKnown(false)
47 , m_bLastWriteTimeKnown(0)
48 , m_lastWriteTime(0)
49 , m_bIsWCRootKnown(false)
50 , m_bIsWCRoot(false)
51 , m_fileSize(0)
52 , m_Checked(false)
53 , m_Action(0)
54 , m_ParentNo(0)
55 , m_Stage(0)
59 CTGitPath::~CTGitPath(void)
62 // Create a TGitPath object from an unknown path type (same as using SetFromUnknown)
63 CTGitPath::CTGitPath(const CString& sUnknownPath) : CTGitPath()
65 SetFromUnknown(sUnknownPath);
68 CTGitPath::CTGitPath(const CString& sUnknownPath, bool bIsDirectory) : CTGitPath(sUnknownPath)
70 m_bDirectoryKnown = true;
71 m_bIsDirectory = bIsDirectory;
74 int CTGitPath::ParserAction(BYTE action)
76 //action=action.TrimLeft();
77 //TCHAR c=action.GetAt(0);
78 if(action == 'M')
79 m_Action|= LOGACTIONS_MODIFIED;
80 if(action == 'R')
81 m_Action|= LOGACTIONS_REPLACED;
82 if(action == 'A')
83 m_Action|= LOGACTIONS_ADDED;
84 if(action == 'D')
85 m_Action|= LOGACTIONS_DELETED;
86 if(action == 'U')
87 m_Action|= LOGACTIONS_UNMERGED;
88 if(action == 'K')
89 m_Action|= LOGACTIONS_DELETED;
90 if(action == 'C' )
91 m_Action|= LOGACTIONS_COPY;
92 if(action == 'T')
93 m_Action|= LOGACTIONS_MODIFIED;
95 return m_Action;
98 int CTGitPath::ParserAction(git_delta_t action)
100 if (action == GIT_DELTA_MODIFIED)
101 m_Action |= LOGACTIONS_MODIFIED;
102 if (action == GIT_DELTA_RENAMED)
103 m_Action |= LOGACTIONS_REPLACED;
104 if (action == GIT_DELTA_ADDED)
105 m_Action |= LOGACTIONS_ADDED;
106 if (action == GIT_DELTA_DELETED)
107 m_Action |= LOGACTIONS_DELETED;
108 if (action == GIT_DELTA_UNMODIFIED)
109 m_Action |= LOGACTIONS_UNMERGED;
110 if (action == GIT_DELTA_COPIED)
111 m_Action |= LOGACTIONS_COPY;
112 if (action == GIT_DELTA_TYPECHANGE)
113 m_Action |= LOGACTIONS_MODIFIED;
115 return m_Action;
118 void CTGitPath::SetFromGit(const char* pPath)
120 Reset();
121 if (!pPath)
122 return;
123 int len = MultiByteToWideChar(CP_UTF8, 0, pPath, -1, nullptr, 0);
124 if (len)
126 len = MultiByteToWideChar(CP_UTF8, 0, pPath, -1, m_sFwdslashPath.GetBuffer(len+1), len+1);
127 m_sFwdslashPath.ReleaseBuffer(len-1);
129 SanitizeRootPath(m_sFwdslashPath, true);
132 void CTGitPath::SetFromGit(const char* pPath, bool bIsDirectory)
134 SetFromGit(pPath);
135 m_bDirectoryKnown = true;
136 m_bIsDirectory = bIsDirectory;
139 void CTGitPath::SetFromGit(const TCHAR* pPath, bool bIsDirectory)
141 Reset();
142 if (pPath)
144 m_sFwdslashPath = pPath;
145 SanitizeRootPath(m_sFwdslashPath, true);
147 m_bDirectoryKnown = true;
148 m_bIsDirectory = bIsDirectory;
151 void CTGitPath::SetFromGit(const CString& sPath, CString* oldpath, int* bIsDirectory)
153 Reset();
154 m_sFwdslashPath = sPath;
155 SanitizeRootPath(m_sFwdslashPath, true);
156 if (bIsDirectory)
158 m_bDirectoryKnown = true;
159 m_bIsDirectory = *bIsDirectory != FALSE;
161 if(oldpath)
162 m_sOldFwdslashPath = *oldpath;
165 void CTGitPath::SetFromWin(LPCTSTR pPath)
167 Reset();
168 m_sBackslashPath = pPath;
169 m_sBackslashPath.Replace(L"\\\\?\\", L"");
170 SanitizeRootPath(m_sBackslashPath, false);
171 ATLASSERT(m_sBackslashPath.Find('/')<0);
173 void CTGitPath::SetFromWin(const CString& sPath)
175 Reset();
176 m_sBackslashPath = sPath;
177 m_sBackslashPath.Replace(L"\\\\?\\", L"");
178 SanitizeRootPath(m_sBackslashPath, false);
180 void CTGitPath::SetFromWin(LPCTSTR pPath, bool bIsDirectory)
182 Reset();
183 m_sBackslashPath = pPath;
184 m_bIsDirectory = bIsDirectory;
185 m_bDirectoryKnown = true;
186 SanitizeRootPath(m_sBackslashPath, false);
188 void CTGitPath::SetFromWin(const CString& sPath, bool bIsDirectory)
190 Reset();
191 m_sBackslashPath = sPath;
192 m_bIsDirectory = bIsDirectory;
193 m_bDirectoryKnown = true;
194 SanitizeRootPath(m_sBackslashPath, false);
196 void CTGitPath::SetFromUnknown(const CString& sPath)
198 Reset();
199 // Just set whichever path we think is most likely to be used
200 // GitAdminDir admin;
201 // CString p;
202 // if(admin.HasAdminDir(sPath,&p))
203 // SetFwdslashPath(sPath.Right(sPath.GetLength()-p.GetLength()));
204 // else
205 SetFwdslashPath(sPath);
208 void CTGitPath::UpdateCase()
210 m_sBackslashPath = CPathUtils::GetLongPathname(GetWinPathString());
211 CPathUtils::TrimTrailingPathDelimiter(m_sBackslashPath);
212 SanitizeRootPath(m_sBackslashPath, false);
213 SetFwdslashPath(m_sBackslashPath);
216 LPCTSTR CTGitPath::GetWinPath() const
218 if(IsEmpty())
219 return L"";
220 if(m_sBackslashPath.IsEmpty())
221 SetBackslashPath(m_sFwdslashPath);
222 return m_sBackslashPath;
224 // This is a temporary function, to be used during the migration to
225 // the path class. Ultimately, functions consuming paths should take a CTGitPath&, not a CString
226 const CString& CTGitPath::GetWinPathString() const
228 if(m_sBackslashPath.IsEmpty())
229 SetBackslashPath(m_sFwdslashPath);
230 return m_sBackslashPath;
233 const CString& CTGitPath::GetGitPathString() const
235 if(m_sFwdslashPath.IsEmpty())
236 SetFwdslashPath(m_sBackslashPath);
237 return m_sFwdslashPath;
240 const CString &CTGitPath::GetGitOldPathString() const
242 return m_sOldFwdslashPath;
245 const CString& CTGitPath::GetUIPathString() const
247 if (m_sUIPath.IsEmpty())
248 m_sUIPath = GetWinPathString();
249 return m_sUIPath;
252 void CTGitPath::SetFwdslashPath(const CString& sPath) const
254 CString path = sPath;
255 path.Replace('\\', '/');
257 // We don't leave a trailing /
258 path.TrimRight('/');
259 path.Replace(L"//?/", L"");
261 SanitizeRootPath(path, true);
263 path.Replace(L"file:////", L"file://");
264 m_sFwdslashPath = path;
267 void CTGitPath::SetBackslashPath(const CString& sPath) const
269 CString path = sPath;
270 path.Replace('/', '\\');
271 path.TrimRight('\\');
272 SanitizeRootPath(path, false);
273 m_sBackslashPath = path;
276 void CTGitPath::SanitizeRootPath(CString& sPath, bool bIsForwardPath) const
278 // Make sure to add the trailing slash to root paths such as 'C:'
279 if (sPath.GetLength() == 2 && sPath[1] == ':')
280 sPath += (bIsForwardPath) ? L'/' : L'\\';
283 bool CTGitPath::IsDirectory() const
285 if(!m_bDirectoryKnown)
286 UpdateAttributes();
287 return m_bIsDirectory;
290 bool CTGitPath::Exists() const
292 if (!m_bExistsKnown)
293 UpdateAttributes();
294 return m_bExists;
297 bool CTGitPath::Delete(bool bTrash, bool bShowErrorUI) const
299 EnsureBackslashPathSet();
300 ::SetFileAttributes(m_sBackslashPath, FILE_ATTRIBUTE_NORMAL);
301 bool bRet = false;
302 if (Exists())
304 if ((bTrash)||(IsDirectory()))
306 auto buf = std::make_unique<TCHAR[]>(m_sBackslashPath.GetLength() + 2);
307 wcscpy_s(buf.get(), m_sBackslashPath.GetLength() + 2, m_sBackslashPath);
308 buf[m_sBackslashPath.GetLength()] = L'\0';
309 buf[m_sBackslashPath.GetLength() + 1] = L'\0';
310 bRet = CTGitPathList::DeleteViaShell(buf.get(), bTrash, bShowErrorUI);
312 else
313 bRet = !!::DeleteFile(m_sBackslashPath);
315 m_bExists = false;
316 m_bExistsKnown = true;
317 return bRet;
320 __int64 CTGitPath::GetLastWriteTime() const
322 if(!m_bLastWriteTimeKnown)
323 UpdateAttributes();
324 return m_lastWriteTime;
327 __int64 CTGitPath::GetFileSize() const
329 if(!m_bDirectoryKnown)
330 UpdateAttributes();
331 return m_fileSize;
334 bool CTGitPath::IsReadOnly() const
336 if(!m_bLastWriteTimeKnown)
337 UpdateAttributes();
338 return m_bIsReadOnly;
341 void CTGitPath::UpdateAttributes() const
343 EnsureBackslashPathSet();
344 WIN32_FILE_ATTRIBUTE_DATA attribs;
345 if (m_sBackslashPath.IsEmpty())
346 m_sLongBackslashPath = L".";
347 else if (m_sBackslashPath.GetLength() >= 248)
349 if (!PathIsRelative(m_sBackslashPath))
350 m_sLongBackslashPath = L"\\\\?\\" + m_sBackslashPath;
351 else
352 m_sLongBackslashPath = L"\\\\?\\" + g_Git.CombinePath(m_sBackslashPath);
354 if (GetFileAttributesEx(m_sBackslashPath.IsEmpty() || m_sBackslashPath.GetLength() >= 248 ? m_sLongBackslashPath : m_sBackslashPath, GetFileExInfoStandard, &attribs))
356 m_bIsDirectory = !!(attribs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
357 // don't cast directly to an __int64:
358 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724284%28v=vs.85%29.aspx
359 // "Do not cast a pointer to a FILETIME structure to either a ULARGE_INTEGER* or __int64* value
360 // because it can cause alignment faults on 64-bit Windows."
361 m_lastWriteTime = static_cast<__int64>(attribs.ftLastWriteTime.dwHighDateTime) << 32 | attribs.ftLastWriteTime.dwLowDateTime;
362 if (m_bIsDirectory)
363 m_fileSize = 0;
364 else
365 m_fileSize = ((INT64)( (DWORD)(attribs.nFileSizeLow) ) | ( (INT64)( (DWORD)(attribs.nFileSizeHigh) )<<32 ));
366 m_bIsReadOnly = !!(attribs.dwFileAttributes & FILE_ATTRIBUTE_READONLY);
367 m_bExists = true;
369 else
371 m_bIsDirectory = false;
372 m_lastWriteTime = 0;
373 m_fileSize = 0;
374 DWORD err = GetLastError();
375 if ((err == ERROR_FILE_NOT_FOUND)||(err == ERROR_PATH_NOT_FOUND)||(err == ERROR_INVALID_NAME))
376 m_bExists = false;
377 else
379 m_bExists = true;
380 return;
383 m_bDirectoryKnown = true;
384 m_bLastWriteTimeKnown = true;
385 m_bExistsKnown = true;
388 CTGitPath CTGitPath::GetSubPath(const CTGitPath &root)
390 CTGitPath path;
392 if (CStringUtils::StartsWith(GetWinPathString(), root.GetWinPathString()))
394 CString str=GetWinPathString();
395 path.SetFromWin(str.Right(str.GetLength()-root.GetWinPathString().GetLength()-1));
397 return path;
400 void CTGitPath::EnsureBackslashPathSet() const
402 if(m_sBackslashPath.IsEmpty())
404 SetBackslashPath(m_sFwdslashPath);
405 ATLASSERT(IsEmpty() || !m_sBackslashPath.IsEmpty());
408 void CTGitPath::EnsureFwdslashPathSet() const
410 if(m_sFwdslashPath.IsEmpty())
412 SetFwdslashPath(m_sBackslashPath);
413 ATLASSERT(IsEmpty() || !m_sFwdslashPath.IsEmpty());
418 // Reset all the caches
419 void CTGitPath::Reset()
421 m_bDirectoryKnown = false;
422 m_bLastWriteTimeKnown = false;
423 m_bHasAdminDirKnown = false;
424 m_bIsValidOnWindowsKnown = false;
425 m_bIsAdminDirKnown = false;
426 m_bExistsKnown = false;
428 m_sBackslashPath.Empty();
429 m_sFwdslashPath.Empty();
430 this->m_Action=0;
431 this->m_StatAdd.Empty();
432 this->m_StatDel.Empty();
433 m_ParentNo=0;
434 ATLASSERT(IsEmpty());
437 CTGitPath CTGitPath::GetDirectory() const
439 if ((IsDirectory())||(!Exists()))
440 return *this;
441 return GetContainingDirectory();
444 CTGitPath CTGitPath::GetContainingDirectory() const
446 EnsureBackslashPathSet();
448 CString sDirName = m_sBackslashPath.Left(m_sBackslashPath.ReverseFind('\\'));
449 if(sDirName.GetLength() == 2 && sDirName[1] == ':')
451 // This is a root directory, which needs a trailing slash
452 sDirName += '\\';
453 if(sDirName == m_sBackslashPath)
455 // We were clearly provided with a root path to start with - we should return nothing now
456 sDirName.Empty();
459 if(sDirName.GetLength() == 1 && sDirName[0] == '\\')
461 // We have an UNC path and we already are the root
462 sDirName.Empty();
464 CTGitPath retVal;
465 retVal.SetFromWin(sDirName);
466 return retVal;
469 CString CTGitPath::GetRootPathString() const
471 EnsureBackslashPathSet();
472 CString workingPath = m_sBackslashPath;
473 ATLVERIFY(::PathStripToRoot(CStrBuf(workingPath, MAX_PATH))); // MAX_PATH ok here.
474 return workingPath;
478 CString CTGitPath::GetFilename() const
480 //ATLASSERT(!IsDirectory());
481 return GetFileOrDirectoryName();
484 CString CTGitPath::GetFileOrDirectoryName() const
486 EnsureBackslashPathSet();
487 return m_sBackslashPath.Mid(m_sBackslashPath.ReverseFind('\\')+1);
490 CString CTGitPath::GetUIFileOrDirectoryName() const
492 GetUIPathString();
493 return m_sUIPath.Mid(m_sUIPath.ReverseFind('\\')+1);
496 CString CTGitPath::GetFileExtension() const
498 if(!IsDirectory())
500 EnsureBackslashPathSet();
501 int dotPos = m_sBackslashPath.ReverseFind('.');
502 int slashPos = m_sBackslashPath.ReverseFind('\\');
503 if (dotPos > slashPos)
504 return m_sBackslashPath.Mid(dotPos);
506 return CString();
508 CString CTGitPath::GetBaseFilename() const
510 int dot;
511 CString filename=GetFilename();
512 dot = filename.ReverseFind(L'.');
513 if(dot>0)
514 filename.Truncate(dot);
515 return filename;
518 bool CTGitPath::IsEmpty() const
520 // Check the backward slash path first, since the chance that this
521 // one is set is higher. In case of a 'false' return value it's a little
522 // bit faster.
523 return m_sBackslashPath.IsEmpty() && m_sFwdslashPath.IsEmpty();
526 // Test if both paths refer to the same item
527 // Ignores case and slash direction
528 bool CTGitPath::IsEquivalentTo(const CTGitPath& rhs) const
530 // Try and find a slash direction which avoids having to convert
531 // both filenames
532 if(!m_sBackslashPath.IsEmpty())
534 // *We've* got a \ path - make sure that the RHS also has a \ path
535 rhs.EnsureBackslashPathSet();
536 return CPathUtils::ArePathStringsEqualWithCase(m_sBackslashPath, rhs.m_sBackslashPath);
538 else
540 // Assume we've got a fwdslash path and make sure that the RHS has one
541 rhs.EnsureFwdslashPathSet();
542 return CPathUtils::ArePathStringsEqualWithCase(m_sFwdslashPath, rhs.m_sFwdslashPath);
546 bool CTGitPath::IsEquivalentToWithoutCase(const CTGitPath& rhs) const
548 // Try and find a slash direction which avoids having to convert
549 // both filenames
550 if(!m_sBackslashPath.IsEmpty())
552 // *We've* got a \ path - make sure that the RHS also has a \ path
553 rhs.EnsureBackslashPathSet();
554 return CPathUtils::ArePathStringsEqual(m_sBackslashPath, rhs.m_sBackslashPath);
556 else
558 // Assume we've got a fwdslash path and make sure that the RHS has one
559 rhs.EnsureFwdslashPathSet();
560 return CPathUtils::ArePathStringsEqual(m_sFwdslashPath, rhs.m_sFwdslashPath);
564 bool CTGitPath::IsAncestorOf(const CTGitPath& possibleDescendant) const
566 possibleDescendant.EnsureBackslashPathSet();
567 EnsureBackslashPathSet();
569 bool bPathStringsEqual = CPathUtils::ArePathStringsEqual(m_sBackslashPath, possibleDescendant.m_sBackslashPath.Left(m_sBackslashPath.GetLength()));
570 if (m_sBackslashPath.GetLength() >= possibleDescendant.GetWinPathString().GetLength())
572 return bPathStringsEqual;
575 return (bPathStringsEqual &&
576 ((possibleDescendant.m_sBackslashPath[m_sBackslashPath.GetLength()] == '\\')||
577 (m_sBackslashPath.GetLength()==3 && m_sBackslashPath[1]==':')));
580 // Get a string representing the file path, optionally with a base
581 // section stripped off the front.
582 CString CTGitPath::GetDisplayString(const CTGitPath* pOptionalBasePath /* = nullptr*/) const
584 EnsureFwdslashPathSet();
585 if (pOptionalBasePath)
587 // Find the length of the base-path without having to do an 'ensure' on it
588 int baseLength = max(pOptionalBasePath->m_sBackslashPath.GetLength(), pOptionalBasePath->m_sFwdslashPath.GetLength());
590 // Now, chop that baseLength of the front of the path
591 return m_sFwdslashPath.Mid(baseLength).TrimLeft('/');
593 return m_sFwdslashPath;
596 int CTGitPath::Compare(const CTGitPath& left, const CTGitPath& right)
598 left.EnsureBackslashPathSet();
599 right.EnsureBackslashPathSet();
600 return CStringUtils::FastCompareNoCase(left.m_sBackslashPath, right.m_sBackslashPath);
603 bool operator<(const CTGitPath& left, const CTGitPath& right)
605 return CTGitPath::Compare(left, right) < 0;
608 bool CTGitPath::PredLeftEquivalentToRight(const CTGitPath& left, const CTGitPath& right)
610 return left.IsEquivalentTo(right);
613 bool CTGitPath::PredLeftSameWCPathAsRight(const CTGitPath& left, const CTGitPath& right)
615 if (left.IsAdminDir() && right.IsAdminDir())
617 CTGitPath l = left;
618 CTGitPath r = right;
621 l = l.GetContainingDirectory();
622 } while(l.HasAdminDir());
625 r = r.GetContainingDirectory();
626 } while(r.HasAdminDir());
627 return l.GetContainingDirectory().IsEquivalentTo(r.GetContainingDirectory());
629 return left.GetDirectory().IsEquivalentTo(right.GetDirectory());
632 bool CTGitPath::CheckChild(const CTGitPath &parent, const CTGitPath& child)
634 return parent.IsAncestorOf(child);
637 void CTGitPath::AppendRawString(const CString& sAppend)
639 EnsureFwdslashPathSet();
640 CString strCopy = m_sFwdslashPath += sAppend;
641 SetFromUnknown(strCopy);
644 void CTGitPath::AppendPathString(const CString& sAppend)
646 EnsureBackslashPathSet();
647 CString cleanAppend(sAppend);
648 cleanAppend.Replace(L'/', L'\\');
649 cleanAppend.TrimLeft(L'\\');
650 m_sBackslashPath.TrimRight(L'\\');
651 CString strCopy = m_sBackslashPath;
652 strCopy += L'\\';
653 strCopy += cleanAppend;
654 SetFromWin(strCopy);
657 bool CTGitPath::IsWCRoot() const
659 if (m_bIsWCRootKnown)
660 return m_bIsWCRoot;
662 m_bIsWCRootKnown = true;
663 m_bIsWCRoot = false;
665 CString topDirectory;
666 if (!IsDirectory() || !HasAdminDir(&topDirectory))
667 return m_bIsWCRoot;
669 if (IsEquivalentToWithoutCase(topDirectory))
670 m_bIsWCRoot = true;
672 return m_bIsWCRoot;
675 bool CTGitPath::HasSubmodules() const
677 if (HasAdminDir())
679 CString path = m_sProjectRoot;
680 path += L"\\.gitmodules";
681 if( PathFileExists(path) )
682 return true;
684 return false;
687 int CTGitPath::GetAdminDirMask() const
689 int status = 0;
690 if (!HasAdminDir())
691 return status;
693 // ITEMIS_INGIT will be revoked if necessary in TortoiseShell/ContextMenu.cpp
694 status |= ITEMIS_INGIT|ITEMIS_INVERSIONEDFOLDER;
696 if (IsDirectory())
698 status |= ITEMIS_FOLDERINGIT;
699 if (IsWCRoot())
701 status |= ITEMIS_WCROOT;
703 CString topProjectDir;
704 if (GitAdminDir::HasAdminDir(GetWinPathString(), false, &topProjectDir))
706 if (PathFileExists(topProjectDir + L"\\.gitmodules"))
708 CAutoConfig config(true);
709 git_config_add_file_ondisk(config, CGit::GetGitPathStringA(topProjectDir + L"\\.gitmodules"), GIT_CONFIG_LEVEL_APP, FALSE);
710 CString relativePath = GetWinPathString().Mid(topProjectDir.GetLength());
711 relativePath.Replace(L'\\', L'/');
712 relativePath.Trim(L'/');
713 CStringA submodulePath = CUnicodeUtils::GetUTF8(relativePath);
714 if (git_config_foreach_match(config, "submodule\\..*\\.path",
715 [](const git_config_entry *entry, void *data) { return entry->value == *(CStringA *)data ? GIT_EUSER : 0; }, &submodulePath) == GIT_EUSER)
716 status |= ITEMIS_SUBMODULE;
722 CString dotGitPath;
723 bool isWorktree;
724 GitAdminDir::GetAdminDirPath(m_sProjectRoot, dotGitPath, &isWorktree);
725 if (HasStashDir(dotGitPath))
726 status |= ITEMIS_STASH;
728 if (PathFileExists(dotGitPath + L"svn"))
729 status |= ITEMIS_GITSVN;
731 if (isWorktree)
733 dotGitPath.Empty();
734 GitAdminDir::GetWorktreeAdminDirPath(m_sProjectRoot, dotGitPath);
737 if (PathFileExists(dotGitPath + L"BISECT_START"))
738 status |= ITEMIS_BISECT;
740 if (PathFileExists(dotGitPath + L"MERGE_HEAD"))
741 status |= ITEMIS_MERGEACTIVE;
743 if (PathFileExists(m_sProjectRoot + L"\\.gitmodules"))
744 status |= ITEMIS_SUBMODULECONTAINER;
746 return status;
749 bool CTGitPath::HasStashDir(const CString& dotGitPath) const
751 if (PathFileExists(dotGitPath + L"refs\\stash"))
752 return true;
754 CAutoFile hfile = CreateFile(dotGitPath + L"packed-refs", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
755 if (!hfile)
756 return false;
758 DWORD filesize = ::GetFileSize(hfile, nullptr);
759 if (filesize == 0 || filesize == INVALID_FILE_SIZE)
760 return false;
762 DWORD size = 0;
763 auto buff = std::make_unique<char[]>(filesize + 1);
764 ReadFile(hfile, buff.get(), filesize, &size, nullptr);
765 buff.get()[filesize] = '\0';
767 if (size != filesize)
768 return false;
770 for (DWORD i = 0; i < filesize;)
772 if (buff[i] == '#' || buff[i] == '^')
774 while (buff[i] != '\n')
776 ++i;
777 if (i == filesize)
778 break;
780 ++i;
783 if (i >= filesize)
784 break;
786 while (buff[i] != ' ')
788 ++i;
789 if (i == filesize)
790 break;
793 ++i;
794 if (i >= filesize)
795 break;
797 if (i <= filesize - 10 && (buff[i + 10] == '\n' || buff[i + 10] == '\0') && !strncmp("refs/stash", buff.get() + i, 10))
798 return true;
799 while (buff[i] != '\n')
801 ++i;
802 if (i == filesize)
803 break;
806 while (buff[i] == '\n')
808 ++i;
809 if (i == filesize)
810 break;
813 return false;
816 bool CTGitPath::HasStashDir() const
818 if (!HasAdminDir())
819 return false;
821 CString dotGitPath;
822 GitAdminDir::GetAdminDirPath(m_sProjectRoot, dotGitPath);
824 return HasStashDir(dotGitPath);
827 bool CTGitPath::HasGitSVNDir() const
829 if (!HasAdminDir())
830 return false;
832 CString dotGitPath;
833 GitAdminDir::GetAdminDirPath(m_sProjectRoot, dotGitPath);
835 return !!PathFileExists(dotGitPath + L"svn");
837 bool CTGitPath::IsBisectActive() const
839 if (!HasAdminDir())
840 return false;
842 CString dotGitPath;
843 GitAdminDir::GetWorktreeAdminDirPath(m_sProjectRoot, dotGitPath);
845 return !!PathFileExists(dotGitPath + L"BISECT_START");
847 bool CTGitPath::IsMergeActive() const
849 if (!HasAdminDir())
850 return false;
852 CString dotGitPath;
853 GitAdminDir::GetWorktreeAdminDirPath(m_sProjectRoot, dotGitPath);
855 return !!PathFileExists(dotGitPath + L"MERGE_HEAD");
857 bool CTGitPath::HasRebaseApply() const
859 if (!HasAdminDir())
860 return false;
862 CString dotGitPath;
863 GitAdminDir::GetWorktreeAdminDirPath(m_sProjectRoot, dotGitPath);
865 return !!PathFileExists(dotGitPath + L"rebase-apply");
868 bool CTGitPath::HasAdminDir(CString* ProjectTopDir /* = nullptr */, bool force /* = false */) const
870 if (m_bHasAdminDirKnown && !force)
872 if (ProjectTopDir)
873 *ProjectTopDir = m_sProjectRoot;
874 return m_bHasAdminDir;
877 EnsureBackslashPathSet();
878 bool isAdminDir = false;
879 m_bHasAdminDir = GitAdminDir::HasAdminDir(m_sBackslashPath, IsDirectory(), &m_sProjectRoot);
880 m_bHasAdminDirKnown = true;
881 if ((m_bHasAdminDir || isAdminDir) && !m_bIsAdminDirKnown)
883 m_bIsAdminDir = isAdminDir;
884 m_bIsAdminDirKnown = true;
886 if (ProjectTopDir)
887 *ProjectTopDir = m_sProjectRoot;
888 return m_bHasAdminDir;
891 bool CTGitPath::IsAdminDir() const
893 if (m_bIsAdminDirKnown)
894 return m_bIsAdminDir;
896 EnsureBackslashPathSet();
897 m_bIsAdminDir = GitAdminDir::IsAdminDirPath(m_sBackslashPath);
898 m_bIsAdminDirKnown = true;
899 if (m_bIsAdminDir && !m_bIsAdminDirKnown)
901 m_bHasAdminDir = false;
902 m_bIsAdminDirKnown = true;
904 return m_bIsAdminDir;
907 bool CTGitPath::IsValidOnWindows() const
909 if (m_bIsValidOnWindowsKnown)
910 return m_bIsValidOnWindows;
912 m_bIsValidOnWindows = false;
913 EnsureBackslashPathSet();
914 CString sMatch = m_sBackslashPath + L"\r\n";
915 std::wstring sPattern;
916 // the 'file://' URL is just a normal windows path:
917 if (CStringUtils::StartsWithI(sMatch, L"file:\\\\"))
919 sMatch = sMatch.Mid(7);
920 sMatch.TrimLeft(L'\\');
921 sPattern = L"^(\\\\\\\\\\?\\\\)?(([a-zA-Z]:|\\\\)\\\\)?(((\\.)|(\\.\\.)|([^\\\\/:\\*\\?\"\\|<> ](([^\\\\/:\\*\\?\"\\|<>\\. ])|([^\\\\/:\\*\\?\"\\|<>]*[^\\\\/:\\*\\?\"\\|<>\\. ]))?))\\\\)*[^\\\\/:\\*\\?\"\\|<> ](([^\\\\/:\\*\\?\"\\|<>\\. ])|([^\\\\/:\\*\\?\"\\|<>]*[^\\\\/:\\*\\?\"\\|<>\\. ]))?$";
923 else
924 sPattern = L"^(\\\\\\\\\\?\\\\)?(([a-zA-Z]:|\\\\)\\\\)?(((\\.)|(\\.\\.)|([^\\\\/:\\*\\?\"\\|<> ](([^\\\\/:\\*\\?\"\\|<>\\. ])|([^\\\\/:\\*\\?\"\\|<>]*[^\\\\/:\\*\\?\"\\|<>\\. ]))?))\\\\)*[^\\\\/:\\*\\?\"\\|<> ](([^\\\\/:\\*\\?\"\\|<>\\. ])|([^\\\\/:\\*\\?\"\\|<>]*[^\\\\/:\\*\\?\"\\|<>\\. ]))?$";
928 std::tr1::wregex rx(sPattern, std::tr1::regex_constants::icase | std::tr1::regex_constants::ECMAScript);
929 std::tr1::wsmatch match;
931 std::wstring rmatch = std::wstring((LPCTSTR)sMatch);
932 if (std::tr1::regex_match(rmatch, match, rx))
934 if (std::wstring(match[0]).compare(sMatch)==0)
935 m_bIsValidOnWindows = true;
937 if (m_bIsValidOnWindows)
939 // now check for illegal filenames
940 std::tr1::wregex rx2(L"\\\\(lpt\\d|com\\d|aux|nul|prn|con)(\\\\|$)", std::tr1::regex_constants::icase | std::tr1::regex_constants::ECMAScript);
941 rmatch = m_sBackslashPath;
942 if (std::tr1::regex_search(rmatch, rx2, std::tr1::regex_constants::match_default))
943 m_bIsValidOnWindows = false;
946 catch (std::exception&) {}
948 m_bIsValidOnWindowsKnown = true;
949 return m_bIsValidOnWindows;
952 //////////////////////////////////////////////////////////////////////////
954 CTGitPathList::CTGitPathList()
956 m_Action = 0;
959 // A constructor which allows a path list to be easily built which one initial entry in
960 CTGitPathList::CTGitPathList(const CTGitPath& firstEntry)
962 m_Action = 0;
963 AddPath(firstEntry);
965 int CTGitPathList::ParserFromLsFile(BYTE_VECTOR &out,bool /*staged*/)
967 size_t pos = 0;
968 CString one;
969 CTGitPath path;
970 CString part;
971 this->Clear();
973 while (pos < out.size())
975 one.Empty();
976 path.Reset();
978 CGit::StringAppend(&one, &out[pos], CP_UTF8);
979 int tabstart=0;
980 // m_Action is never used and propably never worked (needs to be set after path.SetFromGit)
981 // also dropped LOGACTIONS_CACHE for 'H'
982 // path.m_Action=path.ParserAction(out[pos]);
983 one.Tokenize(L"\t", tabstart);
985 if (tabstart < 0)
986 return -1;
988 CString pathstring = one.Right(one.GetLength() - tabstart);
990 tabstart=0;
992 part = one.Tokenize(L" ", tabstart); //Tag
993 if (tabstart < 0)
994 return -1;
996 part = one.Tokenize(L" ", tabstart); //Mode
997 if (tabstart < 0)
998 return -1;
999 int mode = wcstol(part, nullptr, 8);
1000 path.SetFromGit(pathstring, (mode & S_IFDIR) == S_IFDIR);
1002 part = one.Tokenize(L" ", tabstart); //Hash
1003 if (tabstart < 0)
1004 return -1;
1006 part = one.Tokenize(L"\t", tabstart); //Stage
1007 if (tabstart < 0)
1008 return -1;
1010 path.m_Stage = _wtol(part);
1012 this->AddPath(path);
1014 pos=out.findNextString(pos);
1016 return 0;
1019 int CTGitPathList::FillUnRev(unsigned int action, const CTGitPathList* list, CString* err)
1021 this->Clear();
1022 CTGitPath path;
1024 int count;
1025 if (!list)
1026 count=1;
1027 else
1028 count=list->GetCount();
1029 for (int i = 0; i < count; ++i)
1031 CString cmd;
1032 CString ignored;
1033 if(action & CTGitPath::LOGACTIONS_IGNORE)
1034 ignored = L" -i";
1036 if (!list)
1038 cmd = L"git.exe ls-files --exclude-standard --full-name --others -z";
1039 cmd+=ignored;
1042 else
1044 cmd.Format(L"git.exe ls-files --exclude-standard --full-name --others -z%s -- \"%s\"",
1045 (LPCTSTR)ignored,
1046 (*list)[i].GetWinPath());
1049 BYTE_VECTOR out, errb;
1050 out.clear();
1051 if (g_Git.Run(cmd, &out, &errb))
1053 if (err != nullptr)
1054 CGit::StringAppend(err, errb.data(), CP_UTF8, (int)errb.size());
1055 return -1;
1058 size_t pos = 0;
1059 CString one;
1060 while (pos < out.size())
1062 one.Empty();
1063 CGit::StringAppend(&one, &out[pos], CP_UTF8);
1064 if(!one.IsEmpty())
1066 //SetFromGit will clear all status
1067 if (CStringUtils::EndsWith(one, L'/'))
1069 one.Truncate(one.GetLength() - 1);
1070 path.SetFromGit(one, true);
1072 else
1073 path.SetFromGit(one);
1074 path.m_Action=action;
1075 AddPath(path);
1077 pos=out.findNextString(pos);
1081 return 0;
1084 int CTGitPathList::FillBasedOnIndexFlags(unsigned short flag, unsigned short flagextended, const CTGitPathList* list /*nullptr*/)
1086 Clear();
1087 CTGitPath path;
1089 CAutoRepository repository(g_Git.GetGitRepository());
1090 if (!repository)
1091 return -1;
1093 CAutoIndex index;
1094 if (git_repository_index(index.GetPointer(), repository))
1095 return -1;
1097 int count;
1098 if (list == nullptr)
1099 count = 1;
1100 else
1101 count = list->GetCount();
1102 for (int j = 0; j < count; ++j)
1104 for (size_t i = 0, ecount = git_index_entrycount(index); i < ecount; ++i)
1106 const git_index_entry *e = git_index_get_byindex(index, i);
1108 if (!e || !((e->flags & flag) || (e->flags_extended & flagextended)) || !e->path)
1109 continue;
1111 CString one = CUnicodeUtils::GetUnicode(e->path);
1113 if (!(!list || (*list)[j].GetWinPathString().IsEmpty() || one == (*list)[j].GetGitPathString() || (PathIsDirectory(g_Git.CombinePath((*list)[j].GetWinPathString())) && CStringUtils::StartsWith(one, (*list)[j].GetGitPathString() + L'/'))))
1114 continue;
1116 //SetFromGit will clear all status
1117 path.SetFromGit(one, (e->mode & S_IFDIR) == S_IFDIR);
1118 if (e->flags_extended & GIT_IDXENTRY_SKIP_WORKTREE)
1119 path.m_Action = CTGitPath::LOGACTIONS_SKIPWORKTREE;
1120 else if (e->flags & GIT_IDXENTRY_VALID)
1121 path.m_Action = CTGitPath::LOGACTIONS_ASSUMEVALID;
1122 AddPath(path);
1125 RemoveDuplicates();
1126 return 0;
1128 int CTGitPathList::ParserFromLog(BYTE_VECTOR &log, bool parseDeletes /*false*/)
1130 this->Clear();
1131 std::map<CString, size_t> duplicateMap;
1132 size_t pos = 0;
1133 CTGitPath path;
1134 m_Action=0;
1135 size_t logend = log.size();
1136 while (pos < logend)
1138 path.Reset();
1139 if(log[pos]=='\n')
1140 ++pos;
1142 if (pos >= logend)
1143 return -1;
1145 if(log[pos]==':')
1147 bool merged=false;
1148 if (pos + 1 >= logend)
1149 return -1;
1150 if (log[pos + 1] == ':')
1152 merged = true;
1153 ++pos;
1156 int modenew = 0;
1157 int modeold = 0;
1158 size_t end = log.find(0, pos);
1159 size_t actionstart = BYTE_VECTOR::npos;
1160 size_t file1 = BYTE_VECTOR::npos, file2 = BYTE_VECTOR::npos;
1161 if (end != BYTE_VECTOR::npos && end > 7)
1163 modeold = strtol((const char*)&log[pos + 1], nullptr, 8);
1164 modenew = strtol((const char*)&log[pos + 7], nullptr, 8);
1165 actionstart=log.find(' ',end-6);
1166 pos=actionstart;
1168 if (actionstart != BYTE_VECTOR::npos && actionstart > 0)
1170 ++actionstart;
1171 if (actionstart >= logend)
1172 return -1;
1174 file1 = log.find(0,actionstart);
1175 if (file1 != BYTE_VECTOR::npos)
1177 ++file1;
1178 pos=file1;
1180 if( log[actionstart] == 'C' || log[actionstart] == 'R' )
1182 file2=file1;
1183 file1 = log.find(0,file1);
1184 if (file1 != BYTE_VECTOR::npos)
1186 ++file1;
1187 pos=file1;
1192 CString pathname1;
1193 CString pathname2;
1195 if (file1 != BYTE_VECTOR::npos)
1196 CGit::StringAppend(&pathname1, &log[file1], CP_UTF8);
1197 if (file2 != BYTE_VECTOR::npos)
1198 CGit::StringAppend(&pathname2, &log[file2], CP_UTF8);
1200 if (actionstart == BYTE_VECTOR::npos)
1201 return -1;
1203 auto existing = duplicateMap.find(pathname1);
1204 if (existing != duplicateMap.end())
1206 CTGitPath& p = m_paths[existing->second];
1207 p.ParserAction(log[actionstart]);
1209 // reset submodule/folder status if a staged entry is not a folder
1210 if (p.IsDirectory() && ((modeold && !(modeold & S_IFDIR)) || (modenew && !(modenew & S_IFDIR))))
1211 p.UnsetDirectoryStatus();
1213 if(merged)
1214 p.m_Action |= CTGitPath::LOGACTIONS_MERGED;
1215 m_Action |= p.m_Action;
1217 else
1219 int ac=path.ParserAction(log[actionstart] );
1220 ac |= merged?CTGitPath::LOGACTIONS_MERGED:0;
1222 int isSubmodule = FALSE;
1223 if (ac & (CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_UNMERGED))
1224 isSubmodule = (modeold & S_IFDIR) == S_IFDIR;
1225 else
1226 isSubmodule = (modenew & S_IFDIR) == S_IFDIR;
1228 path.SetFromGit(pathname1, &pathname2, &isSubmodule);
1229 path.m_Action=ac;
1230 //action must be set after setfromgit. SetFromGit will clear all status.
1231 this->m_Action|=ac;
1233 AddPath(path);
1234 duplicateMap.insert(std::pair<CString, size_t>(path.GetGitPathString(), m_paths.size() - 1));
1237 else
1239 path.Reset();
1240 CString StatAdd;
1241 CString StatDel;
1242 CString file1;
1243 CString file2;
1244 int isSubmodule = FALSE;
1245 size_t tabstart = log.find('\t', pos);
1246 if (tabstart != BYTE_VECTOR::npos)
1248 int modenew = strtol((const char*)&log[pos + 2], nullptr, 8);
1249 isSubmodule = (modenew & S_IFDIR) == S_IFDIR;
1250 log[tabstart]=0;
1251 CGit::StringAppend(&StatAdd, &log[pos], CP_UTF8);
1252 pos=tabstart+1;
1255 tabstart=log.find('\t',pos);
1256 if (tabstart != BYTE_VECTOR::npos)
1258 log[tabstart]=0;
1260 CGit::StringAppend(&StatDel, &log[pos], CP_UTF8);
1261 pos=tabstart+1;
1264 if(log[pos] == 0) //rename
1266 ++pos;
1267 CGit::StringAppend(&file2, &log[pos], CP_UTF8);
1268 size_t sec = log.find(0, pos);
1269 if (sec != BYTE_VECTOR::npos)
1271 ++sec;
1272 CGit::StringAppend(&file1, &log[sec], CP_UTF8);
1274 pos=sec;
1276 else
1278 CGit::StringAppend(&file1, &log[pos], CP_UTF8);
1280 path.SetFromGit(file1, &file2, &isSubmodule);
1282 auto existing = duplicateMap.find(path.GetGitPathString());
1283 if (existing != duplicateMap.end())
1285 CTGitPath& p = m_paths[existing->second];
1286 p.m_StatAdd = StatAdd;
1287 p.m_StatDel = StatDel;
1289 else
1291 //path.SetFromGit(pathname);
1292 if (parseDeletes)
1294 path.m_StatAdd = L"0";
1295 path.m_StatDel = L"0";
1296 path.m_Action |= CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_MISSING;
1298 else
1300 path.m_StatAdd=StatAdd;
1301 path.m_StatDel=StatDel;
1303 AddPath(path);
1304 duplicateMap.insert(std::pair<CString, size_t>(path.GetGitPathString(), m_paths.size() - 1));
1307 pos=log.findNextString(pos);
1309 return 0;
1312 void CTGitPathList::AddPath(const CTGitPath& newPath)
1314 m_paths.push_back(newPath);
1315 m_commonBaseDirectory.Reset();
1317 int CTGitPathList::GetCount() const
1319 return (int)m_paths.size();
1321 bool CTGitPathList::IsEmpty() const
1323 return m_paths.empty();
1325 void CTGitPathList::Clear()
1327 m_Action = 0;
1328 m_paths.clear();
1329 m_commonBaseDirectory.Reset();
1332 const CTGitPath& CTGitPathList::operator[](INT_PTR index) const
1334 ATLASSERT(index >= 0 && index < (INT_PTR)m_paths.size());
1335 return m_paths[index];
1338 bool CTGitPathList::AreAllPathsFiles() const
1340 // Look through the vector for any directories - if we find them, return false
1341 return std::find_if(m_paths.cbegin(), m_paths.cend(), std::mem_fn(&CTGitPath::IsDirectory)) == m_paths.end();
1344 #if defined(_MFC_VER)
1346 bool CTGitPathList::LoadFromFile(const CTGitPath& filename)
1348 Clear();
1351 CString strLine;
1352 CStdioFile file(filename.GetWinPath(), CFile::typeBinary | CFile::modeRead | CFile::shareDenyWrite);
1354 // for every selected file/folder
1355 CTGitPath path;
1356 while (file.ReadString(strLine))
1358 path.SetFromUnknown(strLine);
1359 AddPath(path);
1361 file.Close();
1363 catch (CFileException* pE)
1365 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CFileException loading target file list\n");
1366 TCHAR error[10000] = {0};
1367 pE->GetErrorMessage(error, 10000);
1368 // CMessageBox::Show(nullptr, error, L"TortoiseGit", MB_ICONERROR);
1369 pE->Delete();
1370 return false;
1372 return true;
1375 bool CTGitPathList::WriteToFile(const CString& sFilename, bool bANSI /* = false */) const
1379 if (bANSI)
1381 CStdioFile file(sFilename, CFile::typeText | CFile::modeReadWrite | CFile::modeCreate);
1382 for (const auto& path : m_paths)
1384 CStringA line = CStringA(path.GetGitPathString()) + '\n';
1385 file.Write(line, line.GetLength());
1387 file.Close();
1389 else
1391 CStdioFile file(sFilename, CFile::typeBinary | CFile::modeReadWrite | CFile::modeCreate);
1392 for (const auto& path : m_paths)
1393 file.WriteString(path.GetGitPathString() + L'\n');
1394 file.Close();
1397 catch (CFileException* pE)
1399 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CFileException in writing temp file\n");
1400 pE->Delete();
1401 return false;
1403 return true;
1406 void CTGitPathList::LoadFromAsteriskSeparatedString(const CString& sPathString)
1408 int pos = 0;
1409 CString temp;
1410 for(;;)
1412 temp = sPathString.Tokenize(L"*", pos);
1413 if(temp.IsEmpty())
1414 break;
1415 AddPath(CTGitPath(CPathUtils::GetLongPathname(temp)));
1419 CString CTGitPathList::CreateAsteriskSeparatedString() const
1421 CString sRet;
1422 for (const auto& path : m_paths)
1424 if (!sRet.IsEmpty())
1425 sRet += L'*';
1426 sRet += path.GetWinPathString();
1428 return sRet;
1430 #endif // _MFC_VER
1432 bool
1433 CTGitPathList::AreAllPathsFilesInOneDirectory() const
1435 // Check if all the paths are files and in the same directory
1436 m_commonBaseDirectory.Reset();
1437 for (const auto& path : m_paths)
1439 if (path.IsDirectory())
1440 return false;
1441 const CTGitPath& baseDirectory = path.GetDirectory();
1442 if(m_commonBaseDirectory.IsEmpty())
1443 m_commonBaseDirectory = baseDirectory;
1444 else if(!m_commonBaseDirectory.IsEquivalentTo(baseDirectory))
1446 // Different path
1447 m_commonBaseDirectory.Reset();
1448 return false;
1451 return true;
1454 CTGitPath CTGitPathList::GetCommonDirectory() const
1456 if (m_commonBaseDirectory.IsEmpty())
1458 for (const auto& path : m_paths)
1460 const CTGitPath& baseDirectory = path.GetDirectory();
1461 if(m_commonBaseDirectory.IsEmpty())
1462 m_commonBaseDirectory = baseDirectory;
1463 else if(!m_commonBaseDirectory.IsEquivalentTo(baseDirectory))
1465 // Different path
1466 m_commonBaseDirectory.Reset();
1467 break;
1471 // since we only checked strings, not paths,
1472 // we have to make sure now that we really return a *path* here
1473 for (const auto& path : m_paths)
1475 if (!m_commonBaseDirectory.IsAncestorOf(path))
1477 m_commonBaseDirectory = m_commonBaseDirectory.GetContainingDirectory();
1478 break;
1481 return m_commonBaseDirectory;
1484 CTGitPath CTGitPathList::GetCommonRoot() const
1486 if (IsEmpty())
1487 return CTGitPath();
1489 if (GetCount() == 1)
1490 return m_paths[0];
1492 // first entry is common root for itself
1493 // (add trailing '\\' to detect partial matches of the last path element)
1494 CString root = m_paths[0].GetWinPathString() + L'\\';
1495 int rootLength = root.GetLength();
1497 // determine common path string prefix
1498 for (auto it = m_paths.cbegin() + 1; it != m_paths.cend(); ++it)
1500 CString path = it->GetWinPathString() + L'\\';
1502 int newLength = CStringUtils::GetMatchingLength(root, path);
1503 if (newLength != rootLength)
1505 root.Delete(newLength, rootLength);
1506 rootLength = newLength;
1510 // remove the last (partial) path element
1511 if (rootLength > 0)
1512 root.Delete(root.ReverseFind(L'\\'), rootLength);
1514 // done
1515 return CTGitPath(root);
1518 void CTGitPathList::SortByPathname(bool bReverse /*= false*/)
1520 std::sort(m_paths.begin(), m_paths.end());
1521 if (bReverse)
1522 std::reverse(m_paths.begin(), m_paths.end());
1525 void CTGitPathList::DeleteAllFiles(bool bTrash, bool bFilesOnly, bool bShowErrorUI)
1527 if (m_paths.empty())
1528 return;
1529 PathVector::const_iterator it;
1530 SortByPathname(true); // nested ones first
1532 CString sPaths;
1533 for (it = m_paths.cbegin(); it != m_paths.cend(); ++it)
1535 if ((it->Exists()) && ((it->IsDirectory() != bFilesOnly) || !bFilesOnly))
1537 if (!it->IsDirectory())
1538 ::SetFileAttributes(it->GetWinPath(), FILE_ATTRIBUTE_NORMAL);
1540 sPaths += it->GetWinPath();
1541 sPaths += '\0';
1544 if (sPaths.IsEmpty())
1545 return;
1546 sPaths += '\0';
1547 sPaths += '\0';
1548 DeleteViaShell((LPCTSTR)sPaths, bTrash, bShowErrorUI);
1549 Clear();
1552 bool CTGitPathList::DeleteViaShell(LPCTSTR path, bool bTrash, bool bShowErrorUI)
1554 SHFILEOPSTRUCT shop = {0};
1555 shop.wFunc = FO_DELETE;
1556 shop.pFrom = path;
1557 shop.fFlags = FOF_NOCONFIRMATION|FOF_NO_CONNECTED_ELEMENTS;
1558 if (!bShowErrorUI)
1559 shop.fFlags |= FOF_NOERRORUI | FOF_SILENT;
1560 if (bTrash)
1561 shop.fFlags |= FOF_ALLOWUNDO;
1562 const bool bRet = (SHFileOperation(&shop) == 0);
1563 return bRet;
1566 void CTGitPathList::RemoveDuplicates()
1568 SortByPathname();
1569 // Remove the duplicates
1570 // (Unique moves them to the end of the vector, then erase chops them off)
1571 m_paths.erase(std::unique(m_paths.begin(), m_paths.end(), &CTGitPath::PredLeftEquivalentToRight), m_paths.end());
1574 void CTGitPathList::RemoveAdminPaths()
1576 PathVector::iterator it;
1577 for(it = m_paths.begin(); it != m_paths.end(); )
1579 if (it->IsAdminDir())
1581 m_paths.erase(it);
1582 it = m_paths.begin();
1584 else
1585 ++it;
1589 void CTGitPathList::RemovePath(const CTGitPath& path)
1591 PathVector::iterator it;
1592 for(it = m_paths.begin(); it != m_paths.end(); ++it)
1594 if (it->IsEquivalentTo(path))
1596 m_paths.erase(it);
1597 return;
1602 void CTGitPathList::RemoveItem(CTGitPath & path)
1604 PathVector::iterator it;
1605 for(it = m_paths.begin(); it != m_paths.end(); ++it)
1607 if (CPathUtils::ArePathStringsEqualWithCase(it->GetGitPathString(), path.GetGitPathString()))
1609 m_paths.erase(it);
1610 return;
1614 void CTGitPathList::RemoveChildren()
1616 SortByPathname();
1617 m_paths.erase(std::unique(m_paths.begin(), m_paths.end(), &CTGitPath::CheckChild), m_paths.end());
1620 bool CTGitPathList::IsEqual(const CTGitPathList& list)
1622 if (list.GetCount() != GetCount())
1623 return false;
1624 for (int i=0; i<list.GetCount(); ++i)
1626 if (!list[i].IsEquivalentTo(m_paths[i]))
1627 return false;
1629 return true;
1632 const CTGitPath* CTGitPathList::LookForGitPath(const CString& path)
1634 int i=0;
1635 for (i = 0; i < this->GetCount(); ++i)
1637 if (CPathUtils::ArePathStringsEqualWithCase((*this)[i].GetGitPathString(), path))
1638 return (CTGitPath*)&(*this)[i];
1640 return nullptr;
1643 CString CTGitPath::GetActionName(int action)
1645 if(action & CTGitPath::LOGACTIONS_UNMERGED)
1646 return MAKEINTRESOURCE(IDS_PATHACTIONS_CONFLICT);
1647 if(action & CTGitPath::LOGACTIONS_ADDED)
1648 return MAKEINTRESOURCE(IDS_PATHACTIONS_ADD);
1649 if (action & CTGitPath::LOGACTIONS_MISSING)
1650 return MAKEINTRESOURCE(IDS_PATHACTIONS_MISSING);
1651 if(action & CTGitPath::LOGACTIONS_DELETED)
1652 return MAKEINTRESOURCE(IDS_PATHACTIONS_DELETE);
1653 if(action & CTGitPath::LOGACTIONS_MERGED )
1654 return MAKEINTRESOURCE(IDS_PATHACTIONS_MERGED);
1656 if(action & CTGitPath::LOGACTIONS_MODIFIED)
1657 return MAKEINTRESOURCE(IDS_PATHACTIONS_MODIFIED);
1658 if(action & CTGitPath::LOGACTIONS_REPLACED)
1659 return MAKEINTRESOURCE(IDS_PATHACTIONS_RENAME);
1660 if(action & CTGitPath::LOGACTIONS_COPY)
1661 return MAKEINTRESOURCE(IDS_PATHACTIONS_COPY);
1663 if (action & CTGitPath::LOGACTIONS_ASSUMEVALID)
1664 return MAKEINTRESOURCE(IDS_PATHACTIONS_ASSUMEUNCHANGED);
1665 if (action & CTGitPath::LOGACTIONS_SKIPWORKTREE)
1666 return MAKEINTRESOURCE(IDS_PATHACTIONS_SKIPWORKTREE);
1668 if (action & CTGitPath::LOGACTIONS_IGNORE)
1669 return MAKEINTRESOURCE(IDS_PATHACTIONS_IGNORED);
1671 return MAKEINTRESOURCE(IDS_PATHACTIONS_UNKNOWN);
1674 CString CTGitPath::GetActionName() const
1676 return GetActionName(m_Action);
1679 int CTGitPathList::GetAction()
1681 return m_Action;
1684 CString CTGitPath::GetAbbreviatedRename() const
1686 if (GetGitOldPathString().IsEmpty())
1687 return GetFileOrDirectoryName();
1689 // Find common prefix which ends with a slash
1690 int prefix_length = 0;
1691 for (int i = 0, maxLength = min(m_sOldFwdslashPath.GetLength(), m_sFwdslashPath.GetLength()); i < maxLength; ++i)
1693 if (m_sOldFwdslashPath[i] != m_sFwdslashPath[i])
1694 break;
1695 if (m_sOldFwdslashPath[i] == L'/')
1696 prefix_length = i + 1;
1699 LPCTSTR oldName = (LPCTSTR)m_sOldFwdslashPath + m_sOldFwdslashPath.GetLength();
1700 LPCTSTR newName = (LPCTSTR)m_sFwdslashPath + m_sFwdslashPath.GetLength();
1702 int suffix_length = 0;
1703 int prefix_adjust_for_slash = (prefix_length ? 1 : 0);
1704 while ((LPCTSTR)m_sOldFwdslashPath + prefix_length - prefix_adjust_for_slash <= oldName &&
1705 (LPCTSTR)m_sFwdslashPath + prefix_length - prefix_adjust_for_slash <= newName &&
1706 *oldName == *newName)
1708 if (*oldName == L'/')
1709 suffix_length = m_sOldFwdslashPath.GetLength() - (int)(oldName - (LPCTSTR)m_sOldFwdslashPath);
1710 --oldName;
1711 --newName;
1715 * pfx{old_midlen => new_midlen}sfx
1716 * {pfx-old => pfx-new}sfx
1717 * pfx{sfx-old => sfx-new}
1718 * name-old => name-new
1720 int old_midlen = m_sOldFwdslashPath.GetLength() - prefix_length - suffix_length;
1721 int new_midlen = m_sFwdslashPath.GetLength() - prefix_length - suffix_length;
1722 if (old_midlen < 0)
1723 old_midlen = 0;
1724 if (new_midlen < 0)
1725 new_midlen = 0;
1727 CString ret;
1728 if (prefix_length + suffix_length)
1730 ret = m_sOldFwdslashPath.Left(prefix_length);
1731 ret += L'{';
1733 ret += m_sOldFwdslashPath.Mid(prefix_length, old_midlen);
1734 ret += L" => ";
1735 ret += m_sFwdslashPath.Mid(prefix_length, new_midlen);
1736 if (prefix_length + suffix_length)
1738 ret += L'}';
1739 ret += m_sFwdslashPath.Mid(m_sFwdslashPath.GetLength() - suffix_length, suffix_length);
1741 return ret;