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.
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(TCHAR
), 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 unsigned int value
= 0;
156 // save the cache to disk
157 // find a location to write the cache to
158 CString path
= CPathUtils::GetLocalAppDataDirectory();
161 path
+= STATUSCACHEFILENAME
;
162 CAutoFILE pFile
= _wfsopen(path
, L
"wb", SH_DENYRW
);
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
)
174 WRITEVALUETOFILE(value
);
177 const CString
& key
= I
->first
.GetWinPathString();
178 value
= key
.GetLength();
179 WRITEVALUETOFILE(value
);
182 if (fwrite((LPCTSTR
)key
, sizeof(TCHAR
), value
, pFile
)!=value
)
184 if (!I
->second
->SaveToDisk(pFile
))
190 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": cache saved to disk at %s\n", (LPCTSTR
)path
);
198 void CGitStatusCache::Destroy()
205 m_pInstance
= nullptr;
209 void CGitStatusCache::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_SearchHistory
}; //FOLDERID_RecycleBinFolder
227 for (KNOWNFOLDERID folderid
: folderids
)
229 CString
path(GetSpecialFolder(folderid
));
231 m_NoWatchPaths
[CTGitPath(path
)] = forever
;
233 m_bClearMemory
= false;
234 m_mostRecentExpiresAt
= 0;
237 CGitStatusCache::~CGitStatusCache(void)
239 CAutoWriteLock
writeLock(m_guard
);
243 void CGitStatusCache::Refresh()
245 m_shellCache
.RefreshIfNeeded();
246 if (!m_pInstance
->m_directoryCache
.empty())
248 auto I
= m_pInstance
->m_directoryCache
.cbegin();
249 for (/* no init */; I
!= m_pInstance
->m_directoryCache
.cend(); ++I
)
251 if (m_shellCache
.IsPathAllowed(I
->first
.GetWinPath()))
252 I
->second
->RefreshMostImportant();
255 CGitStatusCache::Instance().RemoveCacheForPath(I
->first
);
256 I
= m_pInstance
->m_directoryCache
.cbegin();
257 if (I
== m_pInstance
->m_directoryCache
.cend())
264 bool CGitStatusCache::IsPathGood(const CTGitPath
& path
)
266 AutoLocker
lock(m_NoWatchPathCritSec
);
267 for (auto it
= m_NoWatchPaths
.cbegin(); it
!= m_NoWatchPaths
.cend(); ++it
)
269 // the ticks check is necessary here, because RemoveTimedoutBlocks is only called within the FolderCrawler loop
270 // and we might miss update calls
271 // 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)
272 if (GetTickCount64() < it
->second
&& it
->first
.IsAncestorOf(path
))
274 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": path not good: %s\n", it
->first
.GetWinPath());
281 bool CGitStatusCache::BlockPath(const CTGitPath
& path
, ULONGLONG timeout
/* = 0 */)
284 timeout
= BLOCK_PATH_DEFAULT_TIMEOUT
;
286 if (timeout
> BLOCK_PATH_MAX_TIMEOUT
)
287 timeout
= BLOCK_PATH_MAX_TIMEOUT
;
289 timeout
= GetTickCount64() + (timeout
* 1000); // timeout is in seconds, but we need the milliseconds
291 AutoLocker
lock(m_NoWatchPathCritSec
);
292 m_NoWatchPaths
[path
.GetDirectory()] = timeout
;
297 bool CGitStatusCache::UnBlockPath(const CTGitPath
& path
)
300 AutoLocker
lock(m_NoWatchPathCritSec
);
301 std::map
<CTGitPath
, ULONGLONG
>::iterator it
= m_NoWatchPaths
.find(path
.GetDirectory());
302 if (it
!= m_NoWatchPaths
.end())
304 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": path removed from no good: %s\n", it
->first
.GetWinPath());
305 m_NoWatchPaths
.erase(it
);
308 AddFolderForCrawling(path
.GetDirectory());
313 bool CGitStatusCache::RemoveTimedoutBlocks()
316 ULONGLONG currentTicks
= GetTickCount64();
317 AutoLocker
lock(m_NoWatchPathCritSec
);
318 std::vector
<CTGitPath
> toRemove
;
319 for (auto it
= m_NoWatchPaths
.cbegin(); it
!= m_NoWatchPaths
.cend(); ++it
)
321 if (currentTicks
> it
->second
)
322 toRemove
.push_back(it
->first
);
324 if (!toRemove
.empty())
326 for (auto it
= toRemove
.cbegin(); it
!= toRemove
.cend(); ++it
)
327 ret
= ret
|| UnBlockPath(*it
);
333 void CGitStatusCache::UpdateShell(const CTGitPath
& path
)
335 if (path
.IsEquivalentToWithoutCase(m_mostRecentPath
))
336 m_mostRecentExpiresAt
= 0;
337 m_shellUpdater
.AddPathForUpdate(path
);
340 void CGitStatusCache::ClearCache()
342 CAutoWriteLock
writeLock(m_guard
);
343 for (CCachedDirectory::CachedDirMap::iterator I
= m_directoryCache
.begin(); I
!= m_directoryCache
.end(); ++I
)
348 m_directoryCache
.clear();
351 bool CGitStatusCache::RemoveCacheForDirectory(CCachedDirectory
* cdir
)
356 CAutoWriteLock
writeLock(m_guard
);
357 if (!cdir
->m_childDirectories
.empty())
359 for (auto it
= cdir
->m_childDirectories
.begin(); it
!= cdir
->m_childDirectories
.end();)
361 CCachedDirectory
* childdir
= CGitStatusCache::Instance().GetDirectoryCacheEntryNoCreate(it
->first
);
362 if ((childdir
) && (!cdir
->m_directoryPath
.IsEquivalentTo(childdir
->m_directoryPath
)) && (cdir
->m_directoryPath
.GetFileOrDirectoryName() != L
".."))
363 RemoveCacheForDirectory(childdir
);
364 cdir
->m_childDirectories
.erase(it
->first
);
365 it
= cdir
->m_childDirectories
.begin();
368 cdir
->m_childDirectories
.clear();
369 m_directoryCache
.erase(cdir
->m_directoryPath
);
371 // we could have entries versioned and/or stored in our cache which are
372 // children of the specified directory, but not in the m_childDirectories
374 CCachedDirectory::ItDir itMap
= m_directoryCache
.lower_bound(cdir
->m_directoryPath
);
377 if (itMap
!= m_directoryCache
.end())
379 if (cdir
->m_directoryPath
.IsAncestorOf(itMap
->first
))
381 // just in case (see TortoiseSVN issue #255)
382 if (itMap
->second
== cdir
)
383 m_directoryCache
.erase(itMap
);
385 RemoveCacheForDirectory(itMap
->second
);
388 itMap
= m_directoryCache
.lower_bound(cdir
->m_directoryPath
);
389 } while (itMap
!= m_directoryCache
.end() && cdir
->m_directoryPath
.IsAncestorOf(itMap
->first
));
391 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": removed from cache %s\n", cdir
->m_directoryPath
.GetWinPath());
396 void CGitStatusCache::RemoveCacheForPath(const CTGitPath
& path
)
398 // Stop the crawler starting on a new folder
399 CCrawlInhibitor
crawlInhibit(&m_folderCrawler
);
400 CCachedDirectory::ItDir itMap
;
401 CCachedDirectory
* dirtoremove
= nullptr;
403 itMap
= m_directoryCache
.find(path
);
404 if ((itMap
!= m_directoryCache
.end())&&(itMap
->second
))
405 dirtoremove
= itMap
->second
;
408 ATLASSERT(path
.IsEquivalentToWithoutCase(dirtoremove
->m_directoryPath
));
409 RemoveCacheForDirectory(dirtoremove
);
412 CCachedDirectory
* CGitStatusCache::GetDirectoryCacheEntry(const CTGitPath
& path
)
414 ATLASSERT(path
.IsDirectory() || !PathFileExists(path
.GetWinPath()));
416 CAutoReadLock
readLock(m_guardcacheddirectories
);
417 CCachedDirectory::ItDir itMap
;
418 itMap
= m_directoryCache
.find(path
);
419 if ((itMap
!= m_directoryCache
.end())&&(itMap
->second
))
421 // We've found this directory in the cache
422 return itMap
->second
;
426 // if the CCachedDirectory is nullptr but the path is in our cache,
427 // that means that path got invalidated and needs to be treated
428 // as if it never was in our cache. So we remove the last remains
429 // from the cache and start from scratch.
431 CAutoWriteLock
writeLock(m_guardcacheddirectories
);
432 // Since above there's a small chance that before we can upgrade to
433 // writer state some other thread gained writer state and changed
434 // the data, we have to recreate the iterator here again.
435 itMap
= m_directoryCache
.find(path
);
436 if (itMap
!=m_directoryCache
.end())
438 CAutoWriteLock
writeLock2(m_guard
); // needed? Can this happen?
439 delete itMap
->second
;
440 m_directoryCache
.erase(itMap
);
442 // We don't know anything about this directory yet - lets add it to our cache
443 // but only if it exists!
444 if (path
.Exists() && m_shellCache
.IsPathAllowed(path
.GetWinPath()) && !GitAdminDir::IsAdminDirPath(path
.GetWinPath()))
446 // some notifications are for files which got removed/moved around.
447 // In such cases, the CTGitPath::IsDirectory() will return true (it assumes a directory if
448 // the path doesn't exist). Which means we can get here with a path to a file
449 // instead of a directory.
450 // Since we're here most likely called from the crawler thread, the file could exist
451 // again. If that's the case, just do nothing
452 if (path
.IsDirectory()||(!path
.Exists()))
454 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": adding %s to our cache\n", path
.GetWinPath());
455 CCachedDirectory
* newcdir
= new CCachedDirectory(path
);
458 CCachedDirectory
* cdir
= m_directoryCache
.insert(m_directoryCache
.lower_bound(path
), std::make_pair(path
, newcdir
))->second
;
462 m_bClearMemory
= true;
469 CCachedDirectory
* CGitStatusCache::GetDirectoryCacheEntryNoCreate(const CTGitPath
& path
)
471 ATLASSERT(path
.IsDirectory() || !PathFileExists(path
.GetWinPath()));
473 CAutoReadLock
readLock(m_guardcacheddirectories
);
474 CCachedDirectory::ItDir itMap
;
475 itMap
= m_directoryCache
.find(path
);
476 if(itMap
!= m_directoryCache
.end())
478 // We've found this directory in the cache
479 return itMap
->second
;
484 CStatusCacheEntry
CGitStatusCache::GetStatusForPath(const CTGitPath
& path
, DWORD flags
)
486 bool bRecursive
= !!(flags
& TGITCACHE_FLAGS_RECUSIVE_STATUS
);
488 // Check a very short-lived 'mini-cache' of the last thing we were asked for.
489 LONGLONG now
= (LONGLONG
)GetTickCount64();
490 if(now
-m_mostRecentExpiresAt
< 0)
492 if (path
.IsEquivalentTo(m_mostRecentPath
))
493 return m_mostRecentStatus
;
496 AutoLocker
lock(m_critSec
);
497 m_mostRecentPath
= path
;
498 m_mostRecentExpiresAt
= now
+ 1000;
501 if (IsPathGood(path
))
503 // Stop the crawler starting on a new folder while we're doing this much more important task...
504 // Please note, that this may be a second "lock" used concurrently to the one in RemoveCacheForPath().
505 CCrawlInhibitor
crawlInhibit(&m_folderCrawler
);
507 CTGitPath dirpath
= path
.GetContainingDirectory();
508 if ((dirpath
.IsEmpty()) || (!m_shellCache
.IsPathAllowed(dirpath
.GetWinPath())))
509 dirpath
= path
.GetDirectory();
510 CCachedDirectory
* cachedDir
= GetDirectoryCacheEntry(dirpath
);
513 //CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": GetStatusForMember %d\n", bFetch);
514 CStatusCacheEntry entry
= cachedDir
->GetStatusForMember(path
, bRecursive
, false);
516 AutoLocker
lock(m_critSec
);
517 m_mostRecentStatus
= entry
;
518 return m_mostRecentStatus
;
524 // path is blocked for some reason: return the cached status if we have one
525 // we do here only a cache search, absolutely no disk access is allowed!
526 auto cachedDir
= GetDirectoryCacheEntryNoCreate(path
.GetDirectory());
529 if (path
.IsDirectory())
531 CStatusCacheEntry entry
= cachedDir
->GetOwnStatus(false);
532 AutoLocker
lock(m_critSec
);
533 m_mostRecentStatus
= entry
;
534 return m_mostRecentStatus
;
538 // We've found this directory in the cache
539 CStatusCacheEntry entry
= cachedDir
->GetCacheStatusForMember(path
);
541 AutoLocker
lock(m_critSec
);
542 m_mostRecentStatus
= entry
;
543 return m_mostRecentStatus
;
548 AutoLocker
lock(m_critSec
);
549 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ignored no good path %s\n", path
.GetWinPath());
550 m_mostRecentStatus
= CStatusCacheEntry();
551 if (m_shellCache
.ShowExcludedAsNormal() && path
.IsDirectory() && m_shellCache
.HasGITAdminDir(path
.GetWinPath(), true))
553 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": force status %s\n", path
.GetWinPath());
554 m_mostRecentStatus
.ForceStatus(git_wc_status_normal
);
556 return m_mostRecentStatus
;
559 void CGitStatusCache::AddFolderForCrawling(const CTGitPath
& path
)
561 m_folderCrawler
.AddDirectoryForUpdate(path
);
564 void CGitStatusCache::CloseWatcherHandles(HANDLE hFile
)
566 CTGitPath path
= watcher
.CloseInfoMap(hFile
);
568 m_folderCrawler
.BlockPath(path
);
569 CGitStatusCache::Instance().m_GitStatus
.ReleasePathsRecursively(path
.GetWinPathString());
572 void CGitStatusCache::CloseWatcherHandles(const CTGitPath
& path
)
574 watcher
.CloseHandlesForPath(path
);
575 m_folderCrawler
.ReleasePathForUpdate(path
);
576 CGitStatusCache::Instance().m_GitStatus
.ReleasePathsRecursively(path
.GetWinPathString());
579 CString
CGitStatusCache::GetSpecialFolder(REFKNOWNFOLDERID rfid
)
581 PWSTR pszPath
= nullptr;
582 if (SHGetKnownFolderPath(rfid
, KF_FLAG_CREATE
, nullptr, &pszPath
) != S_OK
)
585 CString path
= pszPath
;
586 CoTaskMemFree(pszPath
);