TortoiseShell: Added assume valid checkbox to properties dialog
[TortoiseGit.git] / src / TGitCache / GITStatusCache.cpp
blob5ae6acb40db3591ec5cc17a58f5896f7e7da07ff
1 // TortoiseGit - a Windows shell extension for easy version control
3 // External Cache Copyright (C) 2005-2006,2008,2010 - TortoiseSVN
4 // Copyright (C) 2008-2012 - 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 "GitStatus.h"
23 #include "GitStatuscache.h"
24 #include "CacheInterface.h"
25 #include "shlobj.h"
27 //////////////////////////////////////////////////////////////////////////
29 #define BLOCK_PATH_DEFAULT_TIMEOUT 600 // 10 minutes
30 #define BLOCK_PATH_MAX_TIMEOUT 1200 // 20 minutes
32 CGitStatusCache* CGitStatusCache::m_pInstance;
34 CGitStatusCache& CGitStatusCache::Instance()
36 ATLASSERT(m_pInstance != NULL);
37 return *m_pInstance;
40 void CGitStatusCache::Create()
42 ATLASSERT(m_pInstance == NULL);
43 m_pInstance = new CGitStatusCache;
45 m_pInstance->watcher.SetFolderCrawler(&m_pInstance->m_folderCrawler);
46 #define LOADVALUEFROMFILE(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto exit;
47 #define LOADVALUEFROMFILE2(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto error;
48 unsigned int value = (unsigned int)-1;
49 FILE * pFile = NULL;
50 // find the location of the cache
51 TCHAR path[MAX_PATH]; //MAX_PATH ok here.
52 TCHAR path2[MAX_PATH];
53 if (SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path)==S_OK)
55 _tcscat_s(path, MAX_PATH, _T("\\TGitCache"));
56 if (!PathIsDirectory(path))
58 if (CreateDirectory(path, NULL)==0)
59 goto error;
61 _tcscat_s(path, MAX_PATH, _T("\\cache"));
62 // in case the cache file is corrupt, we could crash while
63 // reading it! To prevent crashing every time once that happens,
64 // we make a copy of the cache file and use that copy to read from.
65 // if that copy is corrupt, the original file won't exist anymore
66 // and the second time we start up and try to read the file,
67 // it's not there anymore and we start from scratch without a crash.
68 _tcscpy_s(path2, MAX_PATH, path);
69 _tcscat_s(path2, MAX_PATH, _T("2"));
70 DeleteFile(path2);
71 CopyFile(path, path2, FALSE);
72 DeleteFile(path);
73 pFile = _tfsopen(path2, _T("rb"), _SH_DENYNO);
74 if (pFile)
76 try
78 LOADVALUEFROMFILE(value);
79 if (value != 2)
81 goto error;
83 int mapsize = 0;
84 LOADVALUEFROMFILE(mapsize);
85 for (int i=0; i<mapsize; ++i)
87 LOADVALUEFROMFILE2(value);
88 if (value > MAX_PATH)
89 goto error;
90 if (value)
92 CString sKey;
93 if (fread(sKey.GetBuffer(value+1), sizeof(TCHAR), value, pFile)!=value)
95 sKey.ReleaseBuffer(0);
96 goto error;
98 sKey.ReleaseBuffer(value);
99 CCachedDirectory * cacheddir = new CCachedDirectory();
100 if (cacheddir == NULL)
101 goto error;
102 if (!cacheddir->LoadFromDisk(pFile))
103 goto error;
104 CTGitPath KeyPath = CTGitPath(sKey);
105 if (m_pInstance->IsPathAllowed(KeyPath))
107 m_pInstance->m_directoryCache[KeyPath] = cacheddir;
108 // only add the path to the watch list if it is versioned
109 if ((cacheddir->GetCurrentFullStatus() != git_wc_status_unversioned)&&(cacheddir->GetCurrentFullStatus() != git_wc_status_none))
110 m_pInstance->watcher.AddPath(KeyPath);
111 // do *not* add the paths for crawling!
112 // because crawled paths will trigger a shell
113 // notification, which makes the desktop flash constantly
114 // until the whole first time crawling is over
115 // m_pInstance->AddFolderForCrawling(KeyPath);
120 catch (CAtlException)
122 goto error;
126 exit:
127 if (pFile)
128 fclose(pFile);
129 DeleteFile(path2);
130 m_pInstance->watcher.ClearInfoMap();
131 ATLTRACE("cache loaded from disk successfully!\n");
132 return;
133 error:
134 fclose(pFile);
135 DeleteFile(path2);
136 m_pInstance->watcher.ClearInfoMap();
137 Destroy();
138 m_pInstance = new CGitStatusCache;
139 ATLTRACE("cache not loaded from disk\n");
142 bool CGitStatusCache::SaveCache()
144 #define WRITEVALUETOFILE(x) if (fwrite(&x, sizeof(x), 1, pFile)!=1) goto error;
145 unsigned int value = 0;
146 // save the cache to disk
147 FILE * pFile = NULL;
148 // find a location to write the cache to
149 TCHAR path[MAX_PATH]; //MAX_PATH ok here.
150 if (SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path)==S_OK)
152 _tcscat_s(path, MAX_PATH, _T("\\TGitCache"));
153 if (!PathIsDirectory(path))
154 CreateDirectory(path, NULL);
155 _tcscat_s(path, MAX_PATH, _T("\\cache"));
156 _tfopen_s(&pFile, path, _T("wb"));
157 if (pFile)
159 value = 2; // 'version'
160 WRITEVALUETOFILE(value);
161 value = (int)m_pInstance->m_directoryCache.size();
162 WRITEVALUETOFILE(value);
163 for (CCachedDirectory::CachedDirMap::iterator I = m_pInstance->m_directoryCache.begin(); I != m_pInstance->m_directoryCache.end(); ++I)
165 if (I->second == NULL)
167 value = 0;
168 WRITEVALUETOFILE(value);
169 continue;
171 const CString& key = I->first.GetWinPathString();
172 value = key.GetLength();
173 WRITEVALUETOFILE(value);
174 if (value)
176 if (fwrite((LPCTSTR)key, sizeof(TCHAR), value, pFile)!=value)
177 goto error;
178 if (!I->second->SaveToDisk(pFile))
179 goto error;
182 fclose(pFile);
185 ATLTRACE(_T("cache saved to disk at %s\n"), path);
186 return true;
187 error:
188 fclose(pFile);
189 Destroy();
190 DeleteFile(path);
191 return false;
194 void CGitStatusCache::Destroy()
196 if (m_pInstance)
198 m_pInstance->Stop();
199 Sleep(100);
200 delete m_pInstance;
201 m_pInstance = NULL;
205 void CGitStatusCache::Stop()
207 // m_svnHelp.Cancel(true);
208 watcher.Stop();
209 m_folderCrawler.Stop();
210 m_shellUpdater.Stop();
213 void CGitStatusCache::Init()
215 m_folderCrawler.Initialise();
216 m_shellUpdater.Initialise();
219 CGitStatusCache::CGitStatusCache(void)
221 #define forever DWORD(-1)
222 AutoLocker lock(m_NoWatchPathCritSec);
223 TCHAR path[MAX_PATH];
224 SHGetFolderPath(NULL, CSIDL_COOKIES, NULL, 0, path);
225 m_NoWatchPaths[CTGitPath(CString(path))] = forever;
226 SHGetFolderPath(NULL, CSIDL_HISTORY, NULL, 0, path);
227 m_NoWatchPaths[CTGitPath(CString(path))] = forever;
228 SHGetFolderPath(NULL, CSIDL_INTERNET_CACHE, NULL, 0, path);
229 m_NoWatchPaths[CTGitPath(CString(path))] = forever;
230 SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, path);
231 m_NoWatchPaths[CTGitPath(CString(path))] = forever;
232 SHGetFolderPath(NULL, CSIDL_WINDOWS, NULL, 0, path);
233 m_NoWatchPaths[CTGitPath(CString(path))] = forever;
234 m_bClearMemory = false;
235 m_mostRecentExpiresAt = 0;
238 CGitStatusCache::~CGitStatusCache(void)
240 CAutoWriteLock writeLock(m_guard);
241 ClearCache();
244 void CGitStatusCache::Refresh()
246 m_shellCache.ForceRefresh();
247 // m_pInstance->m_svnHelp.ReloadConfig();
248 if (m_pInstance->m_directoryCache.size())
250 CCachedDirectory::CachedDirMap::iterator I = m_pInstance->m_directoryCache.begin();
251 for (/* no init */; I != m_pInstance->m_directoryCache.end(); ++I)
253 if (m_shellCache.IsPathAllowed(I->first.GetWinPath()))
254 I->second->RefreshMostImportant();
255 else
257 CGitStatusCache::Instance().RemoveCacheForPath(I->first);
258 I = m_pInstance->m_directoryCache.begin();
259 if (I == m_pInstance->m_directoryCache.end())
260 break;
266 bool CGitStatusCache::IsPathGood(const CTGitPath& path)
268 AutoLocker lock(m_NoWatchPathCritSec);
269 for (std::map<CTGitPath, DWORD>::const_iterator it = m_NoWatchPaths.begin(); it != m_NoWatchPaths.end(); ++it)
271 // the ticks check is necessary here, because RemoveTimedoutBlocks is only called within the FolderCrawler loop
272 // and we might miss update calls
273 // 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)
274 if (GetTickCount() < it->second && it->first.IsAncestorOf(path))
276 ATLTRACE(_T("path not good: %s\n"), it->first.GetWinPath());
277 return false;
280 return true;
283 bool CGitStatusCache::BlockPath(const CTGitPath& path, DWORD timeout /* = 0 */)
285 if (timeout == 0)
286 timeout = BLOCK_PATH_DEFAULT_TIMEOUT;
288 if (timeout > BLOCK_PATH_MAX_TIMEOUT)
289 timeout = BLOCK_PATH_MAX_TIMEOUT;
291 timeout = GetTickCount() + (timeout * 1000); // timeout is in seconds, but we need the milliseconds
293 AutoLocker lock(m_NoWatchPathCritSec);
294 m_NoWatchPaths[path.GetDirectory()] = timeout;
296 return true;
299 bool CGitStatusCache::UnBlockPath(const CTGitPath& path)
301 bool ret = false;
302 AutoLocker lock(m_NoWatchPathCritSec);
303 std::map<CTGitPath, DWORD>::iterator it = m_NoWatchPaths.find(path.GetDirectory());
304 if (it != m_NoWatchPaths.end())
306 ATLTRACE(_T("path removed from no good: %s\n"), it->first.GetWinPath());
307 m_NoWatchPaths.erase(it);
308 ret = true;
310 AddFolderForCrawling(path.GetDirectory());
312 return ret;
315 bool CGitStatusCache::RemoveTimedoutBlocks()
317 bool ret = false;
318 DWORD currentTicks = GetTickCount();
319 AutoLocker lock(m_NoWatchPathCritSec);
320 std::vector<CTGitPath> toRemove;
321 for (std::map<CTGitPath, DWORD>::const_iterator it = m_NoWatchPaths.begin(); it != m_NoWatchPaths.end(); ++it)
323 if (currentTicks > it->second)
325 toRemove.push_back(it->first);
328 if (toRemove.size())
330 for (std::vector<CTGitPath>::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it)
332 ret = ret || UnBlockPath(*it);
336 return ret;
339 void CGitStatusCache::UpdateShell(const CTGitPath& path)
341 m_shellUpdater.AddPathForUpdate(path);
344 void CGitStatusCache::ClearCache()
346 for (CCachedDirectory::CachedDirMap::iterator I = m_directoryCache.begin(); I != m_directoryCache.end(); ++I)
348 delete I->second;
349 I->second = NULL;
351 m_directoryCache.clear();
354 bool CGitStatusCache::RemoveCacheForDirectory(CCachedDirectory * cdir)
356 if (cdir == NULL)
357 return false;
359 typedef std::map<CTGitPath, git_wc_status_kind> ChildDirStatus;
360 if (cdir->m_childDirectories.size())
362 ChildDirStatus::iterator it = cdir->m_childDirectories.begin();
363 for (; it != cdir->m_childDirectories.end(); )
365 CCachedDirectory * childdir = CGitStatusCache::Instance().GetDirectoryCacheEntryNoCreate(it->first);
366 if ((childdir) && (!cdir->m_directoryPath.IsEquivalentTo(childdir->m_directoryPath)) && (cdir->m_directoryPath.GetFileOrDirectoryName() != L".."))
367 RemoveCacheForDirectory(childdir);
368 cdir->m_childDirectories.erase(it->first);
369 it = cdir->m_childDirectories.begin();
372 cdir->m_childDirectories.clear();
373 m_directoryCache.erase(cdir->m_directoryPath);
374 ATLTRACE(_T("removed path %s from cache\n"), cdir->m_directoryPath.GetWinPathString());
375 delete cdir;
376 cdir = NULL;
377 return true;
380 void CGitStatusCache::RemoveCacheForPath(const CTGitPath& path)
382 // Stop the crawler starting on a new folder
383 CCrawlInhibitor crawlInhibit(&m_folderCrawler);
384 CCachedDirectory::ItDir itMap;
385 CCachedDirectory * dirtoremove = NULL;
387 itMap = m_directoryCache.find(path);
388 if ((itMap != m_directoryCache.end())&&(itMap->second))
389 dirtoremove = itMap->second;
390 if (dirtoremove == NULL)
391 return;
392 ATLASSERT(path.IsEquivalentToWithoutCase(dirtoremove->m_directoryPath));
393 RemoveCacheForDirectory(dirtoremove);
396 CCachedDirectory * CGitStatusCache::GetDirectoryCacheEntry(const CTGitPath& path, bool isAddToWatch)
398 ATLASSERT(path.IsDirectory() || !PathFileExists(path.GetWinPath()));
401 CCachedDirectory::ItDir itMap;
402 itMap = m_directoryCache.find(path);
403 if ((itMap != m_directoryCache.end())&&(itMap->second))
405 // We've found this directory in the cache
406 return itMap->second;
408 else
410 // if the CCachedDirectory is NULL but the path is in our cache,
411 // that means that path got invalidated and needs to be treated
412 // as if it never was in our cache. So we remove the last remains
413 // from the cache and start from scratch.
415 CAutoWriteLock writeLock(m_guard);
416 // Since above there's a small chance that before we can upgrade to
417 // writer state some other thread gained writer state and changed
418 // the data, we have to recreate the iterator here again.
419 itMap = m_directoryCache.find(path);
420 if (itMap!=m_directoryCache.end())
421 m_directoryCache.erase(itMap);
422 // We don't know anything about this directory yet - lets add it to our cache
423 // but only if it exists!
424 if (path.Exists() && m_shellCache.IsPathAllowed(path.GetWinPath()) && !g_GitAdminDir.IsAdminDirPath(path.GetWinPath()))
426 // some notifications are for files which got removed/moved around.
427 // In such cases, the CTGitPath::IsDirectory() will return true (it assumes a directory if
428 // the path doesn't exist). Which means we can get here with a path to a file
429 // instead of a directory.
430 // Since we're here most likely called from the crawler thread, the file could exist
431 // again. If that's the case, just do nothing
432 if (path.IsDirectory()||(!path.Exists()))
434 ATLTRACE(_T("adding %s to our cache\n"), path.GetWinPath());
435 CCachedDirectory * newcdir = new CCachedDirectory(path);
436 if (newcdir)
438 CCachedDirectory * cdir = m_directoryCache.insert(m_directoryCache.lower_bound(path), std::make_pair(path, newcdir))->second;
439 CString gitdir;
440 if ((!path.IsEmpty())&&(path.HasAdminDir(&gitdir))&&isAddToWatch)
442 bool isVersion = true;
443 CString subpaths;
444 if(subpaths.GetLength() > gitdir.GetLength())
446 if(subpaths[gitdir.GetLength()] == _T('\\'))
447 subpaths=subpaths.Right(subpaths.GetLength() - gitdir.GetLength()-1);
448 else
449 subpaths=subpaths.Right(subpaths.GetLength() - gitdir.GetLength());
451 CGitStatusCache::Instance().m_GitStatus.IsUnderVersionControl(gitdir, subpaths, true, &isVersion);
453 /* Just watch version path */
454 if(isVersion)
456 watcher.AddPath(gitdir);
457 watcher.AddPath(path);
460 return cdir;
462 m_bClearMemory = true;
465 return NULL;
469 CCachedDirectory * CGitStatusCache::GetDirectoryCacheEntryNoCreate(const CTGitPath& path)
471 ATLASSERT(path.IsDirectory() || !PathFileExists(path.GetWinPath()));
473 CCachedDirectory::ItDir itMap;
474 itMap = m_directoryCache.find(path);
475 if(itMap != m_directoryCache.end())
477 // We've found this directory in the cache
478 return itMap->second;
480 return NULL;
483 /* Fetch is true, means fetch status from */
484 /* Fetch is false, means fetch status from cache */
485 CStatusCacheEntry CGitStatusCache::GetStatusForPath(const CTGitPath& path, DWORD flags, bool bFetch /* = true */)
487 bool bRecursive = !!(flags & TGITCACHE_FLAGS_RECUSIVE_STATUS);
489 // Check a very short-lived 'mini-cache' of the last thing we were asked for.
490 long now = (long)GetTickCount();
491 if(now-m_mostRecentExpiresAt < 0)
493 if(path.IsEquivalentToWithoutCase(m_mostRecentPath))
495 return m_mostRecentStatus;
499 AutoLocker lock(m_critSec);
500 m_mostRecentPath = path;
501 m_mostRecentExpiresAt = now + 1000;
504 if (IsPathGood(path))
506 // Stop the crawler starting on a new folder while we're doing this much more important task...
507 // Please note, that this may be a second "lock" used concurrently to the one in RemoveCacheForPath().
508 CCrawlInhibitor crawlInhibit(&m_folderCrawler);
510 CTGitPath dirpath = path.GetContainingDirectory();
511 if ((dirpath.IsEmpty()) || (!m_shellCache.IsPathAllowed(dirpath.GetWinPath())))
512 dirpath = path.GetDirectory();
513 CCachedDirectory * cachedDir = GetDirectoryCacheEntry(dirpath);
514 if (cachedDir != NULL)
516 //ATLTRACE(_T("GetStatusForMember %d\n"), bFetch);
517 CStatusCacheEntry entry = cachedDir->GetStatusForMember(path, bRecursive, bFetch);
519 AutoLocker lock(m_critSec);
520 m_mostRecentStatus = entry;
521 return m_mostRecentStatus;
525 else
527 // path is blocked for some reason: return the cached status if we have one
528 // we do here only a cache search, absolutely no disk access is allowed!
529 CCachedDirectory::ItDir itMap = m_directoryCache.find(path.GetDirectory());
530 if ((itMap != m_directoryCache.end())&&(itMap->second))
532 if (path.IsDirectory())
534 CStatusCacheEntry entry = itMap->second->GetOwnStatus(false);
535 AutoLocker lock(m_critSec);
536 m_mostRecentStatus = entry;
537 return m_mostRecentStatus;
539 else
541 // We've found this directory in the cache
542 CCachedDirectory * cachedDir = itMap->second;
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 ATLTRACE(_T("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 ATLTRACE(_T("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(HDEVNOTIFY hdev)
570 CTGitPath path = watcher.CloseInfoMap(hdev);
571 m_folderCrawler.BlockPath(path);
574 void CGitStatusCache::CloseWatcherHandles(const CTGitPath& path)
576 watcher.CloseHandlesForPath(path);
577 m_folderCrawler.BlockPath(path);