1
// TortoiseGit - a Windows shell extension for easy version control
3 // External Cache Copyright (C) 2005-2006,2008,2010,2014 - TortoiseSVN
4 // Copyright (C) 2008-2019, 2021, 2023 - TortoiseGit
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.
22 #include "GitAdminDir.h"
23 #include "GitStatus.h"
24 #include "GitStatusCache.h"
25 #include "CacheInterface.h"
27 #include "PathUtils.h"
29 //////////////////////////////////////////////////////////////////////////
31 #define BLOCK_PATH_DEFAULT_TIMEOUT 600 // 10 minutes
32 #define BLOCK_PATH_MAX_TIMEOUT 1200 // 20 minutes
34 #define CACHEDISKVERSION 2
37 #define STATUSCACHEFILENAME L"cache64"
39 #define STATUSCACHEFILENAME L"cache"
42 CGitStatusCache
* CGitStatusCache::m_pInstance
;
44 CGitStatusCache
& CGitStatusCache::Instance()
46 ATLASSERT(m_pInstance
);
50 void CGitStatusCache::Create()
52 ATLASSERT(!m_pInstance
);
53 m_pInstance
= new CGitStatusCache
;
55 m_pInstance
->watcher
.SetFolderCrawler(&m_pInstance
->m_folderCrawler
);
57 if (!CRegStdDWORD(L
"Software\\TortoiseGit\\CacheSave", TRUE
))
60 #define LOADVALUEFROMFILE(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto exit;
61 #define LOADVALUEFROMFILE2(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto error;
62 unsigned int value
= (unsigned int)-1;
63 // find the location of the cache
64 CString path
= CPathUtils::GetLocalAppDataDirectory();
68 path
+= STATUSCACHEFILENAME
;
69 // in case the cache file is corrupt, we could crash while
70 // reading it! To prevent crashing every time once that happens,
71 // we make a copy of the cache file and use that copy to read from.
72 // if that copy is corrupt, the original file won't exist anymore
73 // and the second time we start up and try to read the file,
74 // it's not there anymore and we start from scratch without a crash.
78 CopyFile(path
, path2
, FALSE
);
80 CAutoFILE pFile
= _wfsopen(path2
, L
"rb", _SH_DENYWR
);
85 LOADVALUEFROMFILE(value
);
86 if (value
!= CACHEDISKVERSION
)
91 LOADVALUEFROMFILE(mapsize
);
92 for (int i
=0; i
<mapsize
; ++i
)
94 LOADVALUEFROMFILE2(value
);
100 if (fread(sKey
.GetBuffer(value
+1), sizeof(wchar_t), value
, pFile
) != value
)
102 sKey
.ReleaseBuffer(0);
105 sKey
.ReleaseBuffer(value
);
106 auto cacheddir
= std::make_unique
<CCachedDirectory
>();
107 if (!cacheddir
.get() || !cacheddir
->LoadFromDisk(pFile
))
112 CTGitPath KeyPath
= CTGitPath(sKey
);
113 if (m_pInstance
->IsPathAllowed(KeyPath
))
115 // only add the path to the watch list if it is versioned
116 if ((cacheddir
->GetCurrentFullStatus() != git_wc_status_unversioned
)&&(cacheddir
->GetCurrentFullStatus() != git_wc_status_none
))
117 m_pInstance
->watcher
.AddPath(KeyPath
, false);
119 m_pInstance
->m_directoryCache
[KeyPath
] = cacheddir
.release();
121 // do *not* add the paths for crawling!
122 // because crawled paths will trigger a shell
123 // notification, which makes the desktop flash constantly
124 // until the whole first time crawling is over
125 // m_pInstance->AddFolderForCrawling(KeyPath);
130 catch (CAtlException
)
138 m_pInstance
->watcher
.ClearInfoMap();
139 CTraceToOutputDebugString::Instance()(__FUNCTION__
": cache loaded from disk successfully!\n");
143 m_pInstance
->watcher
.ClearInfoMap();
145 m_pInstance
= new CGitStatusCache
;
146 CTraceToOutputDebugString::Instance()(__FUNCTION__
": cache not loaded from disk\n");
149 bool CGitStatusCache::SaveCache()
151 if (!CRegStdDWORD(L
"Software\\TortoiseGit\\CacheSave", TRUE
))
154 #define WRITEVALUETOFILE(x) if (fwrite(&x, sizeof(x), 1, pFile)!=1) goto error;
155 // save the cache to disk
156 // find a location to write the cache to
157 CString path
= CPathUtils::GetLocalAppDataDirectory();
160 path
+= STATUSCACHEFILENAME
;
161 CAutoFILE pFile
= _wfsopen(path
, L
"wb", SH_DENYRW
);
164 unsigned int value
= CACHEDISKVERSION
;
165 WRITEVALUETOFILE(value
);
166 value
= static_cast<int>(m_pInstance
->m_directoryCache
.size());
167 WRITEVALUETOFILE(value
);
168 for (auto I
= m_pInstance
->m_directoryCache
.cbegin(); I
!= m_pInstance
->m_directoryCache
.cend(); ++I
)
173 WRITEVALUETOFILE(value
);
176 const CString
& key
= I
->first
.GetWinPathString();
177 value
= key
.GetLength();
178 WRITEVALUETOFILE(value
);
181 if (fwrite(static_cast<LPCWSTR
>(key
), sizeof(wchar_t), value
, pFile
) != value
)
183 if (!I
->second
->SaveToDisk(pFile
))
189 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": cache saved to disk at %s\n", static_cast<LPCWSTR
>(path
));
197 void CGitStatusCache::Destroy()
204 m_pInstance
= nullptr;
208 void CGitStatusCache::Stop()
211 m_folderCrawler
.Stop();
212 m_shellUpdater
.Stop();
215 void CGitStatusCache::Init()
217 m_folderCrawler
.Initialise();
218 m_shellUpdater
.Initialise();
221 CGitStatusCache::CGitStatusCache()
223 #define forever DWORD(-1)
224 AutoLocker
lock(m_NoWatchPathCritSec
);
225 KNOWNFOLDERID folderids
[] = { FOLDERID_Cookies
, FOLDERID_History
, FOLDERID_InternetCache
, FOLDERID_Windows
, FOLDERID_CDBurning
, FOLDERID_Fonts
, FOLDERID_SearchHistory
}; //FOLDERID_RecycleBinFolder
226 for (KNOWNFOLDERID folderid
: folderids
)
228 CString
path(GetSpecialFolder(folderid
));
230 m_NoWatchPaths
[CTGitPath(path
)] = forever
;
234 CGitStatusCache::~CGitStatusCache()
236 CAutoWriteLock
writeLock(m_guard
);
240 void CGitStatusCache::Refresh()
242 m_shellCache
.RefreshIfNeeded();
243 if (!m_pInstance
->m_directoryCache
.empty())
245 auto I
= m_pInstance
->m_directoryCache
.cbegin();
246 for (/* no init */; I
!= m_pInstance
->m_directoryCache
.cend(); ++I
)
248 if (m_shellCache
.IsPathAllowed(I
->first
.GetWinPath()))
249 I
->second
->RefreshMostImportant();
252 CGitStatusCache::Instance().RemoveCacheForPath(I
->first
);
253 I
= m_pInstance
->m_directoryCache
.cbegin();
254 if (I
== m_pInstance
->m_directoryCache
.cend())
261 bool CGitStatusCache::IsPathGood(const CTGitPath
& path
)
263 AutoLocker
lock(m_NoWatchPathCritSec
);
264 for (auto it
= m_NoWatchPaths
.cbegin(); it
!= m_NoWatchPaths
.cend(); ++it
)
266 // the ticks check is necessary here, because RemoveTimedoutBlocks is only called within the FolderCrawler loop
267 // and we might miss update calls
268 // TODO: maybe we also need to check if index.lock and HEAD.lock still exists after a specific timeout (if we miss update notifications for these files too often)
269 if (GetTickCount64() < it
->second
&& it
->first
.IsAncestorOf(path
))
271 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": path not good: %s\n", it
->first
.GetWinPath());
278 bool CGitStatusCache::BlockPath(const CTGitPath
& path
, ULONGLONG timeout
/* = 0 */)
281 timeout
= BLOCK_PATH_DEFAULT_TIMEOUT
;
283 if (timeout
> BLOCK_PATH_MAX_TIMEOUT
)
284 timeout
= BLOCK_PATH_MAX_TIMEOUT
;
286 timeout
= GetTickCount64() + (timeout
* 1000); // timeout is in seconds, but we need the milliseconds
288 AutoLocker
lock(m_NoWatchPathCritSec
);
289 m_NoWatchPaths
[path
.GetDirectory()] = timeout
;
294 bool CGitStatusCache::UnBlockPath(const CTGitPath
& path
)
297 AutoLocker
lock(m_NoWatchPathCritSec
);
298 std::map
<CTGitPath
, ULONGLONG
>::iterator it
= m_NoWatchPaths
.find(path
.GetDirectory());
299 if (it
!= m_NoWatchPaths
.end())
301 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": path removed from no good: %s\n", it
->first
.GetWinPath());
302 m_NoWatchPaths
.erase(it
);
305 AddFolderForCrawling(path
.GetDirectory());
310 bool CGitStatusCache::RemoveTimedoutBlocks()
313 ULONGLONG currentTicks
= GetTickCount64();
314 AutoLocker
lock(m_NoWatchPathCritSec
);
315 std::vector
<CTGitPath
> toRemove
;
316 for (auto it
= m_NoWatchPaths
.cbegin(); it
!= m_NoWatchPaths
.cend(); ++it
)
318 if (currentTicks
> it
->second
)
319 toRemove
.push_back(it
->first
);
321 if (!toRemove
.empty())
323 for (auto it
= toRemove
.cbegin(); it
!= toRemove
.cend(); ++it
)
324 ret
= ret
|| UnBlockPath(*it
);
330 void CGitStatusCache::UpdateShell(const CTGitPath
& path
)
332 if (path
.IsEquivalentToWithoutCase(m_mostRecentPath
))
333 m_mostRecentExpiresAt
= 0;
334 m_shellUpdater
.AddPathForUpdate(path
);
337 void CGitStatusCache::ClearCache()
339 CAutoWriteLock
writeLock(m_guard
);
340 for (CCachedDirectory::CachedDirMap::iterator I
= m_directoryCache
.begin(); I
!= m_directoryCache
.end(); ++I
)
345 m_directoryCache
.clear();
348 void CGitStatusCache::RemoveCacheForDirectoryChildren(CCachedDirectory
* cdir
, const CTGitPath
& origPath
)
350 m_directoryCache
.erase(origPath
);
352 // we could have entries versioned and/or stored in our cache which are
353 // children of the specified directory, but not in the m_childDirectories
355 auto itMap
= m_directoryCache
.lower_bound(origPath
);
358 if (itMap
!= m_directoryCache
.end())
360 if (origPath
.IsAncestorOf(itMap
->first
))
362 // just in case (see TortoiseSVN issue #255)
363 if (itMap
->second
== cdir
)
364 m_directoryCache
.erase(itMap
);
366 RemoveCacheForDirectory(itMap
->second
, CTGitPath(itMap
->first
));
369 itMap
= m_directoryCache
.lower_bound(origPath
);
370 } while (itMap
!= m_directoryCache
.end() && origPath
.IsAncestorOf(itMap
->first
));
373 bool CGitStatusCache::RemoveCacheForDirectory(CCachedDirectory
* cdir
, const CTGitPath
& origPath
)
378 CAutoWriteLock
writeLock(m_guard
);
379 if (!cdir
->m_childDirectories
.empty())
381 for (auto it
= cdir
->m_childDirectories
.begin(); it
!= cdir
->m_childDirectories
.end();)
383 CCachedDirectory
* childdir
= CGitStatusCache::Instance().GetDirectoryCacheEntryNoCreate(it
->first
);
384 if ((childdir
) && (!cdir
->m_directoryPath
.IsEquivalentTo(childdir
->m_directoryPath
)) && (cdir
->m_directoryPath
.GetFileOrDirectoryName() != L
".."))
385 RemoveCacheForDirectory(childdir
, it
->first
);
386 cdir
->m_childDirectories
.erase(it
->first
);
387 it
= cdir
->m_childDirectories
.begin();
390 cdir
->m_childDirectories
.clear();
392 RemoveCacheForDirectoryChildren(cdir
, origPath
);
393 RemoveCacheForDirectoryChildren(cdir
, cdir
->m_directoryPath
);
395 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": removed from cache %s\n", cdir
->m_directoryPath
.GetWinPath());
400 void CGitStatusCache::RemoveCacheForPath(const CTGitPath
& path
)
402 // Stop the crawler starting on a new folder
403 CCrawlInhibitor
crawlInhibit(&m_folderCrawler
);
404 CCachedDirectory
* dirtoremove
= nullptr;
406 auto itMap
= m_directoryCache
.find(path
);
407 if ((itMap
!= m_directoryCache
.end())&&(itMap
->second
))
408 dirtoremove
= itMap
->second
;
411 ATLASSERT(path
.IsEquivalentToWithoutCase(dirtoremove
->m_directoryPath
));
412 RemoveCacheForDirectory(dirtoremove
, path
);
415 CCachedDirectory
* CGitStatusCache::GetDirectoryCacheEntry(const CTGitPath
& path
)
417 ATLASSERT(path
.IsDirectory() || !PathFileExists(path
.GetWinPath()));
419 CAutoReadLock
readLock(m_guardcacheddirectories
);
420 auto itMap
= m_directoryCache
.find(path
);
421 if ((itMap
!= m_directoryCache
.end())&&(itMap
->second
))
423 // We've found this directory in the cache
424 return itMap
->second
;
428 // if the CCachedDirectory is nullptr but the path is in our cache,
429 // that means that path got invalidated and needs to be treated
430 // as if it never was in our cache. So we remove the last remains
431 // from the cache and start from scratch.
433 CAutoWriteLock
writeLock(m_guardcacheddirectories
);
434 // Since above there's a small chance that before we can upgrade to
435 // writer state some other thread gained writer state and changed
436 // the data, we have to recreate the iterator here again.
437 itMap
= m_directoryCache
.find(path
);
438 if (itMap
!=m_directoryCache
.end())
440 CAutoWriteLock
writeLock2(m_guard
); // needed? Can this happen?
441 delete itMap
->second
;
442 m_directoryCache
.erase(itMap
);
444 // We don't know anything about this directory yet - lets add it to our cache
445 // but only if it exists!
446 if (path
.Exists() && m_shellCache
.IsPathAllowed(path
.GetWinPath()) && !GitAdminDir::IsAdminDirPath(path
.GetWinPath()))
448 // some notifications are for files which got removed/moved around.
449 // In such cases, the CTGitPath::IsDirectory() will return true (it assumes a directory if
450 // the path doesn't exist). Which means we can get here with a path to a file
451 // instead of a directory.
452 // Since we're here most likely called from the crawler thread, the file could exist
453 // again. If that's the case, just do nothing
454 if (path
.IsDirectory()||(!path
.Exists()))
456 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": adding %s to our cache\n", path
.GetWinPath());
457 CCachedDirectory
* newcdir
= new CCachedDirectory(path
);
460 CCachedDirectory
* cdir
= m_directoryCache
.insert(m_directoryCache
.lower_bound(path
), std::make_pair(path
, newcdir
))->second
;
464 m_bClearMemory
= true;
471 CCachedDirectory
* CGitStatusCache::GetDirectoryCacheEntryNoCreate(const CTGitPath
& path
)
473 ATLASSERT(path
.IsDirectory() || !PathFileExists(path
.GetWinPath()));
475 CAutoReadLock
readLock(m_guardcacheddirectories
);
476 auto itMap
= m_directoryCache
.find(path
);
477 if(itMap
!= m_directoryCache
.end())
479 // We've found this directory in the cache
480 return itMap
->second
;
485 CStatusCacheEntry
CGitStatusCache::GetStatusForPath(const CTGitPath
& path
, DWORD flags
)
487 const bool bRecursive
= !!(flags
& TGITCACHE_FLAGS_RECUSIVE_STATUS
);
489 // Check a very short-lived 'mini-cache' of the last thing we were asked for.
490 LONGLONG now
= static_cast<LONGLONG
>(GetTickCount64());
491 if(now
-m_mostRecentExpiresAt
< 0)
493 if (path
.IsEquivalentTo(m_mostRecentPath
))
494 return m_mostRecentStatus
;
497 AutoLocker
lock(m_critSec
);
498 m_mostRecentPath
= path
;
499 m_mostRecentExpiresAt
= now
+ 1000;
502 if (IsPathGood(path
))
504 // Stop the crawler starting on a new folder while we're doing this much more important task...
505 // Please note, that this may be a second "lock" used concurrently to the one in RemoveCacheForPath().
506 CCrawlInhibitor
crawlInhibit(&m_folderCrawler
);
508 CTGitPath dirpath
= path
.GetContainingDirectory();
509 if ((dirpath
.IsEmpty()) || (!m_shellCache
.IsPathAllowed(dirpath
.GetWinPath())))
510 dirpath
= path
.GetDirectory();
511 CCachedDirectory
* cachedDir
= GetDirectoryCacheEntry(dirpath
);
514 //CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": GetStatusForMember %d\n", bFetch);
515 CStatusCacheEntry entry
= cachedDir
->GetStatusForMember(path
, bRecursive
, false);
517 AutoLocker
lock(m_critSec
);
518 m_mostRecentStatus
= entry
;
519 return m_mostRecentStatus
;
525 // path is blocked for some reason: return the cached status if we have one
526 // we do here only a cache search, absolutely no disk access is allowed!
527 auto cachedDir
= GetDirectoryCacheEntryNoCreate(path
.GetDirectory());
530 if (path
.IsDirectory())
532 CStatusCacheEntry entry
= cachedDir
->GetOwnStatus(false);
533 AutoLocker
lock(m_critSec
);
534 m_mostRecentStatus
= entry
;
535 return m_mostRecentStatus
;
539 // We've found this directory in the cache
540 CStatusCacheEntry entry
= cachedDir
->GetCacheStatusForMember(path
);
542 AutoLocker
lock(m_critSec
);
543 m_mostRecentStatus
= entry
;
544 return m_mostRecentStatus
;
549 AutoLocker
lock(m_critSec
);
550 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ignored no good path %s\n", path
.GetWinPath());
551 m_mostRecentStatus
= CStatusCacheEntry();
552 if (m_shellCache
.ShowExcludedAsNormal() && path
.IsDirectory() && m_shellCache
.HasGITAdminDir(path
.GetWinPath(), true))
554 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": force status %s\n", path
.GetWinPath());
555 m_mostRecentStatus
.ForceStatus(git_wc_status_normal
);
557 return m_mostRecentStatus
;
560 void CGitStatusCache::AddFolderForCrawling(const CTGitPath
& path
)
562 m_folderCrawler
.AddDirectoryForUpdate(path
);
565 void CGitStatusCache::CloseWatcherHandles(HANDLE hFile
)
567 CTGitPath path
= watcher
.CloseInfoMap(hFile
);
569 m_folderCrawler
.BlockPath(path
);
570 CGitStatusCache::Instance().m_GitStatus
.ReleasePathsRecursively(path
.GetWinPathString());
573 void CGitStatusCache::CloseWatcherHandles(const CTGitPath
& path
)
575 watcher
.CloseHandlesForPath(path
);
576 m_folderCrawler
.ReleasePathForUpdate(path
);
577 CGitStatusCache::Instance().m_GitStatus
.ReleasePathsRecursively(path
.GetWinPathString());
580 CString
CGitStatusCache::GetSpecialFolder(REFKNOWNFOLDERID rfid
)
582 CComHeapPtr
<WCHAR
> pszPath
;
583 if (SHGetKnownFolderPath(rfid
, KF_FLAG_CREATE
, nullptr, &pszPath
) != S_OK
)
586 return CString(pszPath
);