Minor cleanup
[TortoiseGit.git] / src / TGitCache / GITStatusCache.cpp
blob35d51a44d71155bb678db2436a17a8f0ba5483ae
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-2017 - 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.
21 #include "stdafx.h"
22 #include "GitAdminDir.h"
23 #include "GitStatus.h"
24 #include "GitStatusCache.h"
25 #include "CacheInterface.h"
26 #include <ShlObj.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
36 #ifdef _WIN64
37 #define STATUSCACHEFILENAME L"cache64"
38 #else
39 #define STATUSCACHEFILENAME L"cache"
40 #endif
42 CGitStatusCache* CGitStatusCache::m_pInstance;
44 CGitStatusCache& CGitStatusCache::Instance()
46 ATLASSERT(m_pInstance);
47 return *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))
58 return;
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();
65 CString path2;
66 if (!path.IsEmpty())
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.
75 path2 = path;
76 path2 += L'2';
77 DeleteFile(path2);
78 CopyFile(path, path2, FALSE);
79 DeleteFile(path);
80 CAutoFILE pFile = _wfsopen(path2, L"rb", _SH_DENYWR);
81 if (pFile)
83 try
85 LOADVALUEFROMFILE(value);
86 if (value != CACHEDISKVERSION)
88 goto error;
90 int mapsize = 0;
91 LOADVALUEFROMFILE(mapsize);
92 for (int i=0; i<mapsize; ++i)
94 LOADVALUEFROMFILE2(value);
95 if (value > MAX_PATH)
96 goto error;
97 if (value)
99 CString sKey;
100 if (fread(sKey.GetBuffer(value+1), sizeof(TCHAR), value, pFile)!=value)
102 sKey.ReleaseBuffer(0);
103 goto error;
105 sKey.ReleaseBuffer(value);
106 auto cacheddir = std::make_unique<CCachedDirectory>();
107 if (!cacheddir.get() || !cacheddir->LoadFromDisk(pFile))
109 cacheddir.reset();
110 goto error;
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)
132 goto error;
136 exit:
137 DeleteFile(path2);
138 m_pInstance->watcher.ClearInfoMap();
139 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": cache loaded from disk successfully!\n");
140 return;
141 error:
142 DeleteFile(path2);
143 m_pInstance->watcher.ClearInfoMap();
144 Destroy();
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))
152 return false;
154 #define WRITEVALUETOFILE(x) if (fwrite(&x, sizeof(x), 1, pFile)!=1) goto error;
155 unsigned int value = 0;
156 // save the cache to disk
157 // find a location to write the cache to
158 CString path = CPathUtils::GetLocalAppDataDirectory();
159 if (!path.IsEmpty())
161 path += STATUSCACHEFILENAME;
162 CAutoFILE pFile = _wfsopen(path, L"wb", SH_DENYRW);
163 if (pFile)
165 value = CACHEDISKVERSION;
166 WRITEVALUETOFILE(value);
167 value = (int)m_pInstance->m_directoryCache.size();
168 WRITEVALUETOFILE(value);
169 for (auto I = m_pInstance->m_directoryCache.cbegin(); I != m_pInstance->m_directoryCache.cend(); ++I)
171 if (!I->second)
173 value = 0;
174 WRITEVALUETOFILE(value);
175 continue;
177 const CString& key = I->first.GetWinPathString();
178 value = key.GetLength();
179 WRITEVALUETOFILE(value);
180 if (value)
182 if (fwrite((LPCTSTR)key, sizeof(TCHAR), value, pFile)!=value)
183 goto error;
184 if (!I->second->SaveToDisk(pFile))
185 goto error;
190 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": cache saved to disk at %s\n", (LPCTSTR)path);
191 return true;
192 error:
193 Destroy();
194 DeleteFile(path);
195 return false;
198 void CGitStatusCache::Destroy()
200 if (m_pInstance)
202 m_pInstance->Stop();
203 Sleep(100);
204 delete m_pInstance;
205 m_pInstance = nullptr;
209 void CGitStatusCache::Stop()
211 watcher.Stop();
212 m_folderCrawler.Stop();
213 m_shellUpdater.Stop();
216 void CGitStatusCache::Init()
218 m_folderCrawler.Initialise();
219 m_shellUpdater.Initialise();
222 CGitStatusCache::CGitStatusCache(void)
224 #define forever DWORD(-1)
225 AutoLocker lock(m_NoWatchPathCritSec);
226 KNOWNFOLDERID folderids[] = { FOLDERID_Cookies, FOLDERID_History, FOLDERID_InternetCache, FOLDERID_Windows, FOLDERID_CDBurning, FOLDERID_Fonts, FOLDERID_RecycleBinFolder }; //FOLDERID_SearchHistory
227 for (KNOWNFOLDERID folderid : folderids)
228 m_NoWatchPaths[CTGitPath(GetSpecialFolder(folderid))] = forever;
229 m_bClearMemory = false;
230 m_mostRecentExpiresAt = 0;
233 CGitStatusCache::~CGitStatusCache(void)
235 CAutoWriteLock writeLock(m_guard);
236 ClearCache();
239 void CGitStatusCache::Refresh()
241 m_shellCache.RefreshIfNeeded();
242 if (!m_pInstance->m_directoryCache.empty())
244 auto I = m_pInstance->m_directoryCache.cbegin();
245 for (/* no init */; I != m_pInstance->m_directoryCache.cend(); ++I)
247 if (m_shellCache.IsPathAllowed(I->first.GetWinPath()))
248 I->second->RefreshMostImportant();
249 else
251 CGitStatusCache::Instance().RemoveCacheForPath(I->first);
252 I = m_pInstance->m_directoryCache.cbegin();
253 if (I == m_pInstance->m_directoryCache.cend())
254 break;
260 bool CGitStatusCache::IsPathGood(const CTGitPath& path)
262 AutoLocker lock(m_NoWatchPathCritSec);
263 for (auto it = m_NoWatchPaths.cbegin(); it != m_NoWatchPaths.cend(); ++it)
265 // the ticks check is necessary here, because RemoveTimedoutBlocks is only called within the FolderCrawler loop
266 // and we might miss update calls
267 // 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)
268 if (GetTickCount64() < it->second && it->first.IsAncestorOf(path))
270 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": path not good: %s\n", it->first.GetWinPath());
271 return false;
274 return true;
277 bool CGitStatusCache::BlockPath(const CTGitPath& path, ULONGLONG timeout /* = 0 */)
279 if (timeout == 0)
280 timeout = BLOCK_PATH_DEFAULT_TIMEOUT;
282 if (timeout > BLOCK_PATH_MAX_TIMEOUT)
283 timeout = BLOCK_PATH_MAX_TIMEOUT;
285 timeout = GetTickCount64() + (timeout * 1000); // timeout is in seconds, but we need the milliseconds
287 AutoLocker lock(m_NoWatchPathCritSec);
288 m_NoWatchPaths[path.GetDirectory()] = timeout;
290 return true;
293 bool CGitStatusCache::UnBlockPath(const CTGitPath& path)
295 bool ret = false;
296 AutoLocker lock(m_NoWatchPathCritSec);
297 std::map<CTGitPath, ULONGLONG>::iterator it = m_NoWatchPaths.find(path.GetDirectory());
298 if (it != m_NoWatchPaths.end())
300 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": path removed from no good: %s\n", it->first.GetWinPath());
301 m_NoWatchPaths.erase(it);
302 ret = true;
304 AddFolderForCrawling(path.GetDirectory());
306 return ret;
309 bool CGitStatusCache::RemoveTimedoutBlocks()
311 bool ret = false;
312 ULONGLONG currentTicks = GetTickCount64();
313 AutoLocker lock(m_NoWatchPathCritSec);
314 std::vector<CTGitPath> toRemove;
315 for (auto it = m_NoWatchPaths.cbegin(); it != m_NoWatchPaths.cend(); ++it)
317 if (currentTicks > it->second)
318 toRemove.push_back(it->first);
320 if (!toRemove.empty())
322 for (auto it = toRemove.cbegin(); it != toRemove.cend(); ++it)
323 ret = ret || UnBlockPath(*it);
326 return ret;
329 void CGitStatusCache::UpdateShell(const CTGitPath& path)
331 if (path.IsEquivalentToWithoutCase(m_mostRecentPath))
332 m_mostRecentExpiresAt = 0;
333 m_shellUpdater.AddPathForUpdate(path);
336 void CGitStatusCache::ClearCache()
338 CAutoWriteLock writeLock(m_guard);
339 for (CCachedDirectory::CachedDirMap::iterator I = m_directoryCache.begin(); I != m_directoryCache.end(); ++I)
341 delete I->second;
342 I->second = nullptr;
344 m_directoryCache.clear();
347 bool CGitStatusCache::RemoveCacheForDirectory(CCachedDirectory * cdir)
349 if (!cdir)
350 return false;
352 CAutoWriteLock writeLock(m_guard);
353 if (!cdir->m_childDirectories.empty())
355 for (auto it = cdir->m_childDirectories.begin(); it != cdir->m_childDirectories.end();)
357 CCachedDirectory * childdir = CGitStatusCache::Instance().GetDirectoryCacheEntryNoCreate(it->first);
358 if ((childdir) && (!cdir->m_directoryPath.IsEquivalentTo(childdir->m_directoryPath)) && (cdir->m_directoryPath.GetFileOrDirectoryName() != L".."))
359 RemoveCacheForDirectory(childdir);
360 cdir->m_childDirectories.erase(it->first);
361 it = cdir->m_childDirectories.begin();
364 cdir->m_childDirectories.clear();
365 m_directoryCache.erase(cdir->m_directoryPath);
367 // we could have entries versioned and/or stored in our cache which are
368 // children of the specified directory, but not in the m_childDirectories
369 // member
370 CCachedDirectory::ItDir itMap = m_directoryCache.lower_bound(cdir->m_directoryPath);
373 if (itMap != m_directoryCache.end())
375 if (cdir->m_directoryPath.IsAncestorOf(itMap->first))
377 // just in case (see TortoiseSVN issue #255)
378 if (itMap->second == cdir)
379 m_directoryCache.erase(itMap);
380 else
381 RemoveCacheForDirectory(itMap->second);
384 itMap = m_directoryCache.lower_bound(cdir->m_directoryPath);
385 } while (itMap != m_directoryCache.end() && cdir->m_directoryPath.IsAncestorOf(itMap->first));
387 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": removed from cache %s\n", cdir->m_directoryPath.GetWinPath());
388 delete cdir;
389 return true;
392 void CGitStatusCache::RemoveCacheForPath(const CTGitPath& path)
394 // Stop the crawler starting on a new folder
395 CCrawlInhibitor crawlInhibit(&m_folderCrawler);
396 CCachedDirectory::ItDir itMap;
397 CCachedDirectory* dirtoremove = nullptr;
399 itMap = m_directoryCache.find(path);
400 if ((itMap != m_directoryCache.end())&&(itMap->second))
401 dirtoremove = itMap->second;
402 if (!dirtoremove)
403 return;
404 ATLASSERT(path.IsEquivalentToWithoutCase(dirtoremove->m_directoryPath));
405 RemoveCacheForDirectory(dirtoremove);
408 CCachedDirectory * CGitStatusCache::GetDirectoryCacheEntry(const CTGitPath& path, bool isAddToWatch)
410 ATLASSERT(path.IsDirectory() || !PathFileExists(path.GetWinPath()));
412 CAutoReadLock readLock(m_guardcacheddirectories);
413 CCachedDirectory::ItDir itMap;
414 itMap = m_directoryCache.find(path);
415 if ((itMap != m_directoryCache.end())&&(itMap->second))
417 // We've found this directory in the cache
418 return itMap->second;
420 else
422 // if the CCachedDirectory is nullptr but the path is in our cache,
423 // that means that path got invalidated and needs to be treated
424 // as if it never was in our cache. So we remove the last remains
425 // from the cache and start from scratch.
427 CAutoWriteLock writeLock(m_guardcacheddirectories);
428 // Since above there's a small chance that before we can upgrade to
429 // writer state some other thread gained writer state and changed
430 // the data, we have to recreate the iterator here again.
431 itMap = m_directoryCache.find(path);
432 if (itMap!=m_directoryCache.end())
434 CAutoWriteLock writeLock2(m_guard); // needed? Can this happen?
435 delete itMap->second;
436 m_directoryCache.erase(itMap);
438 // We don't know anything about this directory yet - lets add it to our cache
439 // but only if it exists!
440 if (path.Exists() && m_shellCache.IsPathAllowed(path.GetWinPath()) && !GitAdminDir::IsAdminDirPath(path.GetWinPath()))
442 // some notifications are for files which got removed/moved around.
443 // In such cases, the CTGitPath::IsDirectory() will return true (it assumes a directory if
444 // the path doesn't exist). Which means we can get here with a path to a file
445 // instead of a directory.
446 // Since we're here most likely called from the crawler thread, the file could exist
447 // again. If that's the case, just do nothing
448 if (path.IsDirectory()||(!path.Exists()))
450 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": adding %s to our cache\n", path.GetWinPath());
451 CCachedDirectory * newcdir = new CCachedDirectory(path);
452 if (newcdir)
454 CCachedDirectory * cdir = m_directoryCache.insert(m_directoryCache.lower_bound(path), std::make_pair(path, newcdir))->second;
455 CString gitdir;
456 if ((!path.IsEmpty())&&(path.HasAdminDir(&gitdir))&&isAddToWatch)
458 /* Just watch version path */
459 watcher.AddPath(gitdir);
460 watcher.AddPath(path);
462 return cdir;
464 m_bClearMemory = true;
467 return nullptr;
471 CCachedDirectory * CGitStatusCache::GetDirectoryCacheEntryNoCreate(const CTGitPath& path)
473 ATLASSERT(path.IsDirectory() || !PathFileExists(path.GetWinPath()));
475 CAutoReadLock readLock(m_guardcacheddirectories);
476 CCachedDirectory::ItDir itMap;
477 itMap = m_directoryCache.find(path);
478 if(itMap != m_directoryCache.end())
480 // We've found this directory in the cache
481 return itMap->second;
483 return nullptr;
486 /* Fetch is true, means fetch status from */
487 /* Fetch is false, means fetch status from cache */
488 CStatusCacheEntry CGitStatusCache::GetStatusForPath(const CTGitPath& path, DWORD flags, bool bFetch /* = true */)
490 bool bRecursive = !!(flags & TGITCACHE_FLAGS_RECUSIVE_STATUS);
492 // Check a very short-lived 'mini-cache' of the last thing we were asked for.
493 LONGLONG now = (LONGLONG)GetTickCount64();
494 if(now-m_mostRecentExpiresAt < 0)
496 if (path.IsEquivalentTo(m_mostRecentPath))
497 return m_mostRecentStatus;
500 AutoLocker lock(m_critSec);
501 m_mostRecentPath = path;
502 m_mostRecentExpiresAt = now + 1000;
505 if (IsPathGood(path))
507 // Stop the crawler starting on a new folder while we're doing this much more important task...
508 // Please note, that this may be a second "lock" used concurrently to the one in RemoveCacheForPath().
509 CCrawlInhibitor crawlInhibit(&m_folderCrawler);
511 CTGitPath dirpath = path.GetContainingDirectory();
512 if ((dirpath.IsEmpty()) || (!m_shellCache.IsPathAllowed(dirpath.GetWinPath())))
513 dirpath = path.GetDirectory();
514 CCachedDirectory * cachedDir = GetDirectoryCacheEntry(dirpath);
515 if (cachedDir)
517 //CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": GetStatusForMember %d\n", bFetch);
518 CStatusCacheEntry entry = cachedDir->GetStatusForMember(path, bRecursive, bFetch);
520 AutoLocker lock(m_critSec);
521 m_mostRecentStatus = entry;
522 return m_mostRecentStatus;
526 else
528 // path is blocked for some reason: return the cached status if we have one
529 // we do here only a cache search, absolutely no disk access is allowed!
530 auto cachedDir = GetDirectoryCacheEntryNoCreate(path.GetDirectory());
531 if (cachedDir)
533 if (path.IsDirectory())
535 CStatusCacheEntry entry = cachedDir->GetOwnStatus(false);
536 AutoLocker lock(m_critSec);
537 m_mostRecentStatus = entry;
538 return m_mostRecentStatus;
540 else
542 // We've found this directory in the cache
543 CStatusCacheEntry entry = cachedDir->GetCacheStatusForMember(path);
545 AutoLocker lock(m_critSec);
546 m_mostRecentStatus = entry;
547 return m_mostRecentStatus;
552 AutoLocker lock(m_critSec);
553 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": ignored no good path %s\n", path.GetWinPath());
554 m_mostRecentStatus = CStatusCacheEntry();
555 if (m_shellCache.ShowExcludedAsNormal() && path.IsDirectory() && m_shellCache.HasGITAdminDir(path.GetWinPath(), true))
557 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": force status %s\n", path.GetWinPath());
558 m_mostRecentStatus.ForceStatus(git_wc_status_normal);
560 return m_mostRecentStatus;
563 void CGitStatusCache::AddFolderForCrawling(const CTGitPath& path)
565 m_folderCrawler.AddDirectoryForUpdate(path);
568 void CGitStatusCache::CloseWatcherHandles(HANDLE hFile)
570 CTGitPath path = watcher.CloseInfoMap(hFile);
571 if (!path.IsEmpty())
572 m_folderCrawler.BlockPath(path);
573 CGitStatusCache::Instance().m_GitStatus.ReleasePathsRecursively(path.GetWinPathString());
576 void CGitStatusCache::CloseWatcherHandles(const CTGitPath& path)
578 watcher.CloseHandlesForPath(path);
579 m_folderCrawler.ReleasePathForUpdate(path);
580 CGitStatusCache::Instance().m_GitStatus.ReleasePathsRecursively(path.GetWinPathString());
583 CString CGitStatusCache::GetSpecialFolder(REFKNOWNFOLDERID rfid)
585 PWSTR pszPath = nullptr;
586 if (SHGetKnownFolderPath(rfid, KF_FLAG_CREATE, nullptr, &pszPath) != S_OK)
587 return CString();
589 CString path = pszPath;
590 CoTaskMemFree(pszPath);
591 return path;