OSDN Git Service

Add Show Whole Project Checkbox at commitdlg.
[tortoisegit/TortoiseGitJp.git] / src / Git / Git.cpp
1 #include "StdAfx.h"\r
2 #include "Git.h"\r
3 #include "atlconv.h"\r
4 #include "GitRev.h"\r
5 #include "registry.h"\r
6 #include "GitConfig.h"\r
7 #include <map>\r
8 #include "UnicodeUtils.h"\r
9 \r
10 \r
11 static LPTSTR nextpath(LPCTSTR src, LPTSTR dst, UINT maxlen)\r
12 {\r
13         LPCTSTR orgsrc;\r
14 \r
15         while (*src == _T(';'))\r
16                 src++;\r
17 \r
18         orgsrc = src;\r
19 \r
20         if (!--maxlen)\r
21                 goto nullterm;\r
22 \r
23         while (*src && *src != _T(';'))\r
24         {\r
25                 if (*src != _T('"'))\r
26                 {\r
27                         *dst++ = *src++;\r
28                         if (!--maxlen)\r
29                         {\r
30                                 orgsrc = src;\r
31                                 goto nullterm;\r
32                         }\r
33                 }\r
34                 else\r
35                 {\r
36                         src++;\r
37                         while (*src && *src != _T('"'))\r
38                         {\r
39                                 *dst++ = *src++;\r
40                                 if (!--maxlen)\r
41                                 {\r
42                                         orgsrc = src;\r
43                                         goto nullterm;\r
44                                 }\r
45                         }\r
46 \r
47                         if (*src)\r
48                                 src++;\r
49                 }\r
50         }\r
51 \r
52         while (*src == _T(';'))\r
53                 src++;\r
54 \r
55 nullterm:\r
56 \r
57         *dst = 0;\r
58 \r
59         return (orgsrc != src) ? (LPTSTR)src : NULL;\r
60 }\r
61 \r
62 static inline BOOL FileExists(LPCTSTR lpszFileName)\r
63 {\r
64         struct _stat st;\r
65         return _tstat(lpszFileName, &st) == 0;\r
66 }\r
67 \r
68 static BOOL FindGitPath()\r
69 {\r
70         size_t size;\r
71         _tgetenv_s(&size, NULL, 0, _T("PATH"));\r
72 \r
73         if (!size)\r
74         {\r
75                 return FALSE;\r
76         }\r
77 \r
78         TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));\r
79         _tgetenv_s(&size, env, size, _T("PATH"));\r
80 \r
81         TCHAR buf[_MAX_PATH];\r
82 \r
83         // search in all paths defined in PATH\r
84         while ((env = nextpath(env, buf, _MAX_PATH-1)) && *buf)\r
85         {\r
86                 TCHAR *pfin = buf + _tcslen(buf)-1;\r
87 \r
88                 // ensure trailing slash\r
89                 if (*pfin != _T('/') && *pfin != _T('\\'))\r
90                         _tcscpy(++pfin, _T("\\"));\r
91 \r
92                 const int len = _tcslen(buf);\r
93 \r
94                 if ((len + 7) < _MAX_PATH)\r
95                         _tcscpy(pfin+1, _T("git.exe"));\r
96                 else\r
97                         break;\r
98 \r
99                 if ( FileExists(buf) )\r
100                 {\r
101                         // dir found\r
102                         pfin[1] = 0;\r
103                         CGit::ms_LastMsysGitDir = buf;\r
104                         return TRUE;\r
105                 }\r
106         }\r
107 \r
108         return FALSE;\r
109 }\r
110 \r
111 \r
112 #define MAX_DIRBUFFER 1000\r
113 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024\r
114 \r
115 CString CGit::ms_LastMsysGitDir;\r
116 CGit g_Git;\r
117 \r
118 // contains system environment that should be used by child processes (RunAsync)\r
119 // initialized by CheckMsysGitDir\r
120 static LPTSTR l_processEnv = NULL;\r
121 \r
122 \r
123 BOOL CGit::IsVista()\r
124 {\r
125 \r
126         if( CRegStdWORD(_T("Software\\TortoiseGit\\CacheType") ) == 0)\r
127         {\r
128                 return TRUE;\r
129         }\r
130 \r
131         OSVERSIONINFO osvi;\r
132     BOOL bIsWindowsXPorLater;\r
133 \r
134     ZeroMemory(&osvi, sizeof(OSVERSIONINFO));\r
135     osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r
136 \r
137     GetVersionEx(&osvi);\r
138         \r
139         if(osvi.dwMajorVersion >= 6)\r
140                 return TRUE;\r
141         else\r
142                 return FALSE;\r
143 }\r
144 \r
145 CGit::CGit(void)\r
146 {\r
147         GetCurrentDirectory(MAX_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));\r
148         m_CurrentDir.ReleaseBuffer();\r
149 \r
150         CheckMsysGitDir();\r
151 }\r
152 \r
153 CGit::~CGit(void)\r
154 {\r
155 }\r
156 \r
157 static char g_Buffer[4096];\r
158 \r
159 int CGit::RunAsync(CString cmd,PROCESS_INFORMATION *piOut,HANDLE *hReadOut,CString *StdioFile)\r
160 {\r
161         SECURITY_ATTRIBUTES sa;\r
162         HANDLE hRead, hWrite;\r
163         HANDLE hStdioFile = NULL;\r
164 \r
165         sa.nLength = sizeof(SECURITY_ATTRIBUTES);\r
166         sa.lpSecurityDescriptor=NULL;\r
167         sa.bInheritHandle=TRUE;\r
168         if(!CreatePipe(&hRead,&hWrite,&sa,0))\r
169         {\r
170                 return GIT_ERROR_OPEN_PIP;\r
171         }\r
172         \r
173         if(StdioFile)\r
174         {\r
175                 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ   |   FILE_SHARE_WRITE,   \r
176                         &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);  \r
177         }\r
178 \r
179         STARTUPINFO si;\r
180         PROCESS_INFORMATION pi;\r
181         si.cb=sizeof(STARTUPINFO);\r
182         GetStartupInfo(&si);\r
183 \r
184         si.hStdError=hWrite;\r
185         if(StdioFile)\r
186                 si.hStdOutput=hStdioFile;\r
187         else\r
188                 si.hStdOutput=hWrite;\r
189 \r
190         si.wShowWindow=SW_HIDE;\r
191         si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;\r
192 \r
193         LPTSTR pEnv = l_processEnv;\r
194         DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;\r
195 \r
196         if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))\r
197         {\r
198                 LPVOID lpMsgBuf;\r
199                 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,\r
200                         NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\r
201                         (LPTSTR)&lpMsgBuf,\r
202                         0,NULL);\r
203                 return GIT_ERROR_CREATE_PROCESS;\r
204         }\r
205         \r
206         CloseHandle(hWrite);\r
207         if(piOut)\r
208                 *piOut=pi;\r
209         if(hReadOut)\r
210                 *hReadOut=hRead;\r
211         \r
212         return 0;\r
213 \r
214 }\r
215 //Must use sperate function to convert ANSI str to union code string\r
216 //Becuase A2W use stack as internal convert buffer. \r
217 void CGit::StringAppend(CString *str,BYTE *p,int code,int length)\r
218 {\r
219      //USES_CONVERSION;\r
220          //str->Append(A2W_CP((LPCSTR)p,code));\r
221         if(str == NULL)\r
222                 return ;\r
223 \r
224         WCHAR * buf;\r
225 \r
226         int len ;\r
227         if(length<0)\r
228                 len= strlen((const char*)p);\r
229         else\r
230                 len=length;\r
231         //if (len==0)\r
232         //      return ;\r
233         //buf = new WCHAR[len*4 + 1];\r
234         buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();\r
235         SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));\r
236         MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);\r
237         str->ReleaseBuffer();\r
238         //str->Append(buf);\r
239         //delete buf;\r
240 }       \r
241 BOOL CGit::IsInitRepos()\r
242 {\r
243         CString cmdout;\r
244         cmdout.Empty();\r
245         if(g_Git.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout,CP_UTF8))\r
246         {\r
247         //      CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);\r
248                 return TRUE;\r
249         }\r
250         if(cmdout.IsEmpty())\r
251                 return TRUE;\r
252 \r
253         return FALSE;\r
254 }\r
255 int CGit::Run(CGitCall* pcall)\r
256 {\r
257         PROCESS_INFORMATION pi;\r
258         HANDLE hRead;\r
259         if(RunAsync(pcall->GetCmd(),&pi,&hRead))\r
260                 return GIT_ERROR_CREATE_PROCESS;\r
261 \r
262         DWORD readnumber;\r
263         BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];\r
264         bool bAborted=false;\r
265         while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))\r
266         {\r
267                 //Todo: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?\r
268                 if(!bAborted)//For now, flush output when command aborted.\r
269                         if(pcall->OnOutputData(data,readnumber))\r
270                                 bAborted=true;\r
271         }\r
272         if(!bAborted)\r
273                 pcall->OnEnd();\r
274 \r
275         \r
276         CloseHandle(pi.hThread);\r
277 \r
278         WaitForSingleObject(pi.hProcess, INFINITE);\r
279         DWORD exitcode =0;\r
280 \r
281         if(!GetExitCodeProcess(pi.hProcess,&exitcode))\r
282         {\r
283                 return GIT_ERROR_GET_EXIT_CODE;\r
284         }\r
285 \r
286         CloseHandle(pi.hProcess);\r
287 \r
288         CloseHandle(hRead);\r
289         return exitcode;\r
290 }\r
291 class CGitCall_ByteVector : public CGitCall\r
292 {\r
293 public:\r
294         CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector):CGitCall(cmd),m_pvector(pvector){}\r
295         virtual bool OnOutputData(const BYTE* data, size_t size)\r
296         {\r
297                 size_t oldsize=m_pvector->size();\r
298                 m_pvector->resize(m_pvector->size()+size);\r
299                 memcpy(&*(m_pvector->begin()+oldsize),data,size);\r
300                 return false;\r
301         }\r
302         BYTE_VECTOR* m_pvector;\r
303 \r
304 };\r
305 int CGit::Run(CString cmd,BYTE_VECTOR *vector)\r
306 {\r
307         CGitCall_ByteVector call(cmd,vector);\r
308         return Run(&call);\r
309 }\r
310 int CGit::Run(CString cmd, CString* output,int code)\r
311 {\r
312         BYTE_VECTOR vector;\r
313         int ret;\r
314         ret=Run(cmd,&vector);\r
315 \r
316         vector.push_back(0);\r
317         \r
318         StringAppend(output,&(vector[0]),code);\r
319         return ret;\r
320 }\r
321 \r
322 CString CGit::GetUserName(void)\r
323 {\r
324         CString UserName;\r
325         Run(_T("git.exe config user.name"),&UserName,CP_UTF8);\r
326         return UserName;\r
327 }\r
328 CString CGit::GetUserEmail(void)\r
329 {\r
330         CString UserName;\r
331         Run(_T("git.exe config user.email"),&UserName,CP_UTF8);\r
332         return UserName;\r
333 }\r
334 \r
335 CString CGit::GetCurrentBranch(void)\r
336 {\r
337         CString output;\r
338         //Run(_T("git.exe branch"),&branch);\r
339 \r
340         int ret=g_Git.Run(_T("git.exe branch"),&output,CP_UTF8);\r
341         if(!ret)\r
342         {               \r
343                 int pos=0;\r
344                 CString one;\r
345                 while( pos>=0 )\r
346                 {\r
347                         //i++;\r
348                         one=output.Tokenize(_T("\n"),pos);\r
349                         //list.push_back(one.Right(one.GetLength()-2));\r
350                         if(one[0] == _T('*'))\r
351                                 return one.Right(one.GetLength()-2);\r
352                 }\r
353         }\r
354         return CString("");\r
355 }\r
356 \r
357 int CGit::BuildOutputFormat(CString &format,bool IsFull)\r
358 {\r
359         CString log;\r
360         log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);\r
361         format += log;\r
362         if(IsFull)\r
363         {\r
364                 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);\r
365                 format += log;\r
366                 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);\r
367                 format += log;\r
368                 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);\r
369                 format += log;\r
370                 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);\r
371                 format += log;\r
372                 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);\r
373                 format += log;\r
374                 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);\r
375                 format += log;\r
376                 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);\r
377                 format += log;\r
378                 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);\r
379                 format += log;\r
380         }\r
381         log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);\r
382         format += log;\r
383         log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);\r
384         format += log;\r
385 \r
386         if(IsFull)\r
387         {\r
388                 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);\r
389                 format += log;\r
390         }\r
391         return 0;\r
392 }\r
393 \r
394 int CGit::GetLog(BYTE_VECTOR& logOut, CString &hash,  CTGitPath *path ,int count,int mask,CString *from,CString *to)\r
395 {\r
396         CGitCall_ByteVector gitCall(CString(),&logOut);\r
397         return GetLog(&gitCall,hash,path,count,mask,from,to);\r
398 }\r
399 \r
400 //int CGit::GetLog(CGitCall* pgitCall, CString &hash,  CTGitPath *path ,int count,int mask)\r
401 int CGit::GetLog(CGitCall* pgitCall, CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)\r
402 {\r
403 \r
404         CString cmd;\r
405         CString log;\r
406         CString num;\r
407         CString since;\r
408 \r
409         CString file;\r
410 \r
411         if(path)\r
412                 file.Format(_T(" -- \"%s\""),path->GetGitPathString());\r
413         \r
414         if(count>0)\r
415                 num.Format(_T("-n%d"),count);\r
416 \r
417         CString param;\r
418 \r
419         if(mask& LOG_INFO_STAT )\r
420                 param += _T(" --numstat ");\r
421         if(mask& LOG_INFO_FILESTATE)\r
422                 param += _T(" --raw ");\r
423 \r
424         if(mask& LOG_INFO_FULLHISTORY)\r
425                 param += _T(" --full-history ");\r
426 \r
427         if(mask& LOG_INFO_BOUNDARY)\r
428                 param += _T(" --left-right --boundary ");\r
429 \r
430         if(mask& CGit::LOG_INFO_ALL_BRANCH)\r
431                 param += _T(" --all ");\r
432 \r
433         if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)\r
434                 param += _T(" -C ");\r
435         \r
436         if(mask& CGit::LOG_INFO_DETECT_RENAME )\r
437                 param += _T(" -M ");\r
438 \r
439         if(mask& CGit::LOG_INFO_FIRST_PARENT )\r
440                 param += _T(" --first-parent ");\r
441         \r
442         if(mask& CGit::LOG_INFO_NO_MERGE )\r
443                 param += _T(" --no-merges ");\r
444 \r
445         if(mask& CGit::LOG_INFO_FOLLOW)\r
446                 param += _T(" --follow ");\r
447 \r
448         if(from != NULL && to != NULL)\r
449         {\r
450                 CString range;\r
451                 range.Format(_T(" %s..%s "),*from,*to);\r
452                 param += range;\r
453         }\r
454         param+=hash;\r
455 \r
456         cmd.Format(_T("git.exe log %s -z --topo-order %s --parents --pretty=format:\""),\r
457                                 num,param);\r
458 \r
459         BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));\r
460 \r
461         cmd += log;\r
462         cmd += CString(_T("\"  "))+hash+file;\r
463 \r
464         pgitCall->SetCmd(cmd);\r
465 \r
466         return Run(pgitCall);\r
467 //      return Run(cmd,&logOut);\r
468 }\r
469 \r
470 #if 0\r
471 int CGit::GetShortLog(CString &logOut,CTGitPath * path, int count)\r
472 {\r
473         CString cmd;\r
474         CString log;\r
475         int n;\r
476         if(count<0)\r
477                 n=100;\r
478         else\r
479                 n=count;\r
480         cmd.Format(_T("git.exe log --left-right --boundary --topo-order -n%d --pretty=format:\""),n);\r
481         BuildOutputFormat(log,false);\r
482         cmd += log+_T("\"");\r
483         if (path)\r
484                 cmd+= _T("  -- \"")+path->GetGitPathString()+_T("\"");\r
485         //cmd += CString(_T("\" HEAD~40..HEAD"));\r
486         return Run(cmd,&logOut);\r
487 }\r
488 #endif\r
489 \r
490 #define BUFSIZE 512\r
491 void GetTempPath(CString &path)\r
492 {\r
493         TCHAR lpPathBuffer[BUFSIZE];\r
494         DWORD dwRetVal;\r
495         DWORD dwBufSize=BUFSIZE;\r
496         dwRetVal = GetTempPath(dwBufSize,     // length of the buffer\r
497                            lpPathBuffer); // buffer for path \r
498     if (dwRetVal > dwBufSize || (dwRetVal == 0))\r
499     {\r
500         path=_T("");\r
501     }\r
502         path.Format(_T("%s"),lpPathBuffer);\r
503 }\r
504 CString GetTempFile()\r
505 {\r
506         TCHAR lpPathBuffer[BUFSIZE];\r
507         DWORD dwRetVal;\r
508     DWORD dwBufSize=BUFSIZE;\r
509         TCHAR szTempName[BUFSIZE];  \r
510         UINT uRetVal;\r
511 \r
512         dwRetVal = GetTempPath(dwBufSize,     // length of the buffer\r
513                            lpPathBuffer); // buffer for path \r
514     if (dwRetVal > dwBufSize || (dwRetVal == 0))\r
515     {\r
516         return _T("");\r
517     }\r
518          // Create a temporary file. \r
519     uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files\r
520                               TEXT("Patch"),  // temp file name prefix \r
521                               0,            // create unique name \r
522                               szTempName);  // buffer for name \r
523 \r
524 \r
525     if (uRetVal == 0)\r
526     {\r
527         return _T("");\r
528     }\r
529 \r
530         return CString(szTempName);\r
531 \r
532 }\r
533 \r
534 int CGit::RunLogFile(CString cmd,CString &filename)\r
535 {\r
536         STARTUPINFO si;\r
537         PROCESS_INFORMATION pi;\r
538         si.cb=sizeof(STARTUPINFO);\r
539         GetStartupInfo(&si);\r
540 \r
541         SECURITY_ATTRIBUTES   psa={sizeof(psa),NULL,TRUE};;   \r
542         psa.bInheritHandle=TRUE;   \r
543     \r
544         HANDLE   houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ   |   FILE_SHARE_WRITE,   \r
545                         &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);   \r
546 \r
547 \r
548         si.wShowWindow=SW_HIDE;\r
549         si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;\r
550         si.hStdOutput   =   houtfile; \r
551         \r
552         if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,NULL,NULL,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))\r
553         {\r
554                 LPVOID lpMsgBuf;\r
555                 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,\r
556                         NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\r
557                         (LPTSTR)&lpMsgBuf,\r
558                         0,NULL);\r
559                 return GIT_ERROR_CREATE_PROCESS;\r
560         }\r
561         \r
562         WaitForSingleObject(pi.hProcess,INFINITE);   \r
563         \r
564         CloseHandle(pi.hThread);\r
565         CloseHandle(pi.hProcess);\r
566         CloseHandle(houtfile);\r
567         return GIT_SUCCESS;\r
568 //      return 0;\r
569 }\r
570 \r
571 git_revnum_t CGit::GetHash(CString &friendname)\r
572 {\r
573         CString cmd;\r
574         CString out;\r
575         cmd.Format(_T("git.exe rev-parse %s" ),friendname);\r
576         Run(cmd,&out,CP_UTF8);\r
577         int pos=out.ReverseFind(_T('\n'));\r
578         if(pos>0)\r
579                 return out.Left(pos);\r
580         return out;\r
581 }\r
582 \r
583 int CGit::GetTagList(STRING_VECTOR &list)\r
584 {\r
585         int ret;\r
586         CString cmd,output;\r
587         cmd=_T("git.exe tag -l");\r
588         int i=0;\r
589         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
590         if(!ret)\r
591         {               \r
592                 int pos=0;\r
593                 CString one;\r
594                 while( pos>=0 )\r
595                 {\r
596                         i++;\r
597                         one=output.Tokenize(_T("\n"),pos);\r
598                         list.push_back(one);\r
599                 }\r
600         }\r
601         return ret;\r
602 }\r
603 \r
604 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)\r
605 {\r
606         int ret;\r
607         CString cmd,output;\r
608         cmd=_T("git.exe branch");\r
609 \r
610         if(type==(BRANCH_LOCAL|BRANCH_REMOTE))\r
611                 cmd+=_T(" -a");\r
612         else if(type==BRANCH_REMOTE)\r
613                 cmd+=_T(" -r");\r
614 \r
615         int i=0;\r
616         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
617         if(!ret)\r
618         {               \r
619                 int pos=0;\r
620                 CString one;\r
621                 while( pos>=0 )\r
622                 {\r
623                         one=output.Tokenize(_T("\n"),pos);\r
624                         list.push_back(one.Right(one.GetLength()-2));\r
625                         if(one[0] == _T('*'))\r
626                                 if(current)\r
627                                         *current=i;\r
628                         i++;\r
629                 }\r
630         }\r
631         return ret;\r
632 }\r
633 \r
634 int CGit::GetRemoteList(STRING_VECTOR &list)\r
635 {\r
636         int ret;\r
637         CString cmd,output;\r
638         cmd=_T("git.exe config  --get-regexp remote.*.url");\r
639         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
640         if(!ret)\r
641         {\r
642                 int pos=0;\r
643                 CString one;\r
644                 while( pos>=0 )\r
645                 {\r
646                         one=output.Tokenize(_T("\n"),pos);\r
647                         int start=one.Find(_T("."),0);\r
648                         if(start>0)\r
649                         {\r
650                                 CString url;\r
651                                 url=one.Right(one.GetLength()-start-1);\r
652                                 one=url;\r
653                                 one=one.Left(one.Find(_T("."),0));\r
654                                 list.push_back(one);\r
655                         }\r
656                 }\r
657         }\r
658         return ret;\r
659 }\r
660 \r
661 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)\r
662 {\r
663         int ret;\r
664         CString cmd,output;\r
665         cmd=_T("git show-ref -d");\r
666         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
667         if(!ret)\r
668         {\r
669                 int pos=0;\r
670                 CString one;\r
671                 while( pos>=0 )\r
672                 {\r
673                         one=output.Tokenize(_T("\n"),pos);\r
674                         int start=one.Find(_T(" "),0);\r
675                         if(start>0)\r
676                         {\r
677                                 CString name;\r
678                                 name=one.Right(one.GetLength()-start-1);\r
679 \r
680                                 CString hash;\r
681                                 hash=one.Left(start);\r
682 \r
683                                 map[hash].push_back(name);\r
684                         }\r
685                 }\r
686         }\r
687         return ret;\r
688 }\r
689 \r
690 BOOL CGit::CheckMsysGitDir()\r
691 {\r
692         static BOOL bInitialized = FALSE;\r
693 \r
694         if (bInitialized)\r
695         {\r
696                 return TRUE;\r
697         }\r
698 \r
699         TCHAR *oldpath,*home;\r
700         size_t size;\r
701 \r
702         // set HOME if not set already\r
703         _tgetenv_s(&size, NULL, 0, _T("HOME"));\r
704         if (!size)\r
705         {\r
706                 _tdupenv_s(&home,&size,_T("USERPROFILE")); \r
707                 _tputenv_s(_T("HOME"),home);\r
708                 free(home);\r
709         }\r
710 \r
711         //setup ssh client\r
712         CRegString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));\r
713         CString ssh=sshclient;\r
714 \r
715         if(!ssh.IsEmpty())\r
716         {\r
717                 _tputenv_s(_T("GIT_SSH"),ssh);\r
718         }else\r
719         {\r
720                 _tputenv_s(_T("GIT_SSH"),_T(""));\r
721         }\r
722 \r
723         // search PATH if git/bin directory is alredy present\r
724         if ( FindGitPath() )\r
725         {\r
726                 bInitialized = TRUE;\r
727                 return TRUE;\r
728         }\r
729 \r
730         // add git/bin path to PATH\r
731 \r
732         CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE,HKEY_LOCAL_MACHINE);\r
733         CString str=msysdir;\r
734         if(str.IsEmpty())\r
735         {\r
736                 CRegString msysinstalldir=CRegString(REG_MSYSGIT_INSTALL,_T(""),FALSE,HKEY_LOCAL_MACHINE);\r
737                 str=msysinstalldir;\r
738                 if ( !str.IsEmpty() )\r
739                 {\r
740                         str += (str[str.GetLength()-1] != '\\') ? "\\bin" : "bin";\r
741                         msysdir=str;\r
742                         msysdir.write();\r
743                 }\r
744                 else\r
745                 {\r
746                         return false;\r
747                 }\r
748         }\r
749         //CGit::m_MsysGitPath=str;\r
750 \r
751         //set path\r
752 \r
753         _tdupenv_s(&oldpath,&size,_T("PATH")); \r
754 \r
755         CString path;\r
756         path.Format(_T("%s;%s"),oldpath,str);\r
757 \r
758         _tputenv_s(_T("PATH"),path);\r
759 \r
760         CString sOldPath = oldpath;\r
761         free(oldpath);\r
762 \r
763 \r
764     if( !FindGitPath() )\r
765         {\r
766                 return false;\r
767         }\r
768         else\r
769         {\r
770 #ifdef _TORTOISESHELL\r
771                 l_processEnv = GetEnvironmentStrings();\r
772                 // updated environment is now duplicated for use in CreateProcess, restore original PATH for current process\r
773                 _tputenv_s(_T("PATH"),sOldPath);\r
774 #endif\r
775 \r
776                 bInitialized = TRUE;\r
777                 return true;\r
778         }\r
779 }\r
780 \r
781 \r
782 class CGitCall_EnumFiles : public CGitCall\r
783 {\r
784 public:\r
785         CGitCall_EnumFiles(const char *pszProjectPath, const char *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)\r
786         :       m_pszProjectPath(pszProjectPath),\r
787                 m_pszSubPath(pszSubPath),\r
788                 m_nFlags(nFlags),\r
789                 m_pEnumCb(pEnumCb),\r
790                 m_pUserData(pUserData)\r
791         {\r
792         }\r
793 \r
794         typedef std::map<CStringA,char> TStrCharMap;\r
795 \r
796         const char *    m_pszProjectPath;\r
797         const char *    m_pszSubPath;\r
798         unsigned int    m_nFlags;\r
799         WGENUMFILECB *  m_pEnumCb;\r
800         void *                  m_pUserData;\r
801 \r
802         BYTE_VECTOR             m_DataCollector;\r
803 \r
804         virtual bool    OnOutputData(const BYTE* data, size_t size)\r
805         {\r
806                 m_DataCollector.append(data,size);\r
807                 while(true)\r
808                 {\r
809                         // lines from igit.exe are 0 terminated\r
810                         int found=m_DataCollector.findData((const BYTE*)"",1);\r
811                         if(found<0)\r
812                                 return false;\r
813                         OnSingleLine( (LPCSTR)&*m_DataCollector.begin() );\r
814                         m_DataCollector.erase(m_DataCollector.begin(), m_DataCollector.begin()+found+1);\r
815                 }\r
816                 return false;//Should never reach this\r
817         }\r
818         virtual void    OnEnd()\r
819         {\r
820         }\r
821 \r
822         UINT HexChar(char ch)\r
823         {\r
824                 if (ch >= '0' && ch <= '9')\r
825                         return (UINT)(ch - '0');\r
826                 else if (ch >= 'A' && ch <= 'F')\r
827                         return (UINT)(ch - 'A') + 10;\r
828                 else if (ch >= 'a' && ch <= 'f')\r
829                         return (UINT)(ch - 'a') + 10;\r
830                 else\r
831                         return 0;\r
832         }\r
833 \r
834         bool OnSingleLine(LPCSTR line)\r
835         {\r
836                 //Parse single line\r
837 \r
838                 wgFile_s fileStatus;\r
839 \r
840                 // file/dir type\r
841 \r
842                 fileStatus.nFlags = 0;\r
843                 if (*line == 'D')\r
844                         fileStatus.nFlags |= WGFF_Directory;\r
845                 line += 2;\r
846 \r
847                 // status\r
848 \r
849                 fileStatus.nStatus = WGFS_Unknown;\r
850                 switch (*line)\r
851                 {\r
852                 case 'N': fileStatus.nStatus = WGFS_Normal; break;\r
853                 case 'M': fileStatus.nStatus = WGFS_Modified; break;\r
854                 case 'S': fileStatus.nStatus = WGFS_Staged; break;\r
855                 case 'A': fileStatus.nStatus = WGFS_Added; break;\r
856                 case 'C': fileStatus.nStatus = WGFS_Conflicted; break;\r
857                 case 'D': fileStatus.nStatus = WGFS_Deleted; break;\r
858                 case 'I': fileStatus.nStatus = WGFS_Ignored; break;\r
859                 case 'U': fileStatus.nStatus = WGFS_Unversioned; break;\r
860                 case 'E': fileStatus.nStatus = WGFS_Empty; break;\r
861                 }\r
862                 line += 2;\r
863 \r
864                 // file sha1\r
865 \r
866                 BYTE sha1[20];\r
867                 fileStatus.sha1 = NULL;\r
868                 if ( !(fileStatus.nFlags & WGFF_Directory) )\r
869                 {\r
870                         for (int i=0; i<20; i++)\r
871                         {\r
872                                 sha1[i] = (HexChar(line[0]) << 8) | HexChar(line[1]);\r
873                                 line += 2;\r
874                         }\r
875 \r
876                         line++;\r
877                 }\r
878 \r
879                 // filename\r
880                 fileStatus.sFileName = line;\r
881 \r
882                 if ( (*m_pEnumCb)(&fileStatus,m_pUserData) )\r
883                         return false;\r
884 \r
885                 return true;\r
886         }\r
887 };\r
888 \r
889 BOOL CGit::EnumFiles(const char *pszProjectPath, const char *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)\r
890 {\r
891         if(!pszProjectPath || *pszProjectPath=='\0')\r
892                 return FALSE;\r
893 \r
894         CGitCall_EnumFiles W_GitCall(pszProjectPath,pszSubPath,nFlags,pEnumCb,pUserData);\r
895         CString cmd;\r
896 \r
897 /*      char W_szToDir[MAX_PATH];\r
898         strncpy(W_szToDir,pszProjectPath,sizeof(W_szToDir)-1);\r
899         if(W_szToDir[strlen(W_szToDir)-1]!='\\')\r
900                 strncat(W_szToDir,"\\",sizeof(W_szToDir)-1);\r
901 \r
902         SetCurrentDirectoryA(W_szToDir);\r
903         GetCurrentDirectoryA(sizeof(W_szToDir)-1,W_szToDir);\r
904 */\r
905         SetCurrentDir(CUnicodeUtils::GetUnicode(pszProjectPath));\r
906 \r
907         CString sMode;\r
908         if (nFlags)\r
909         {\r
910                 if (nFlags & WGEFF_NoRecurse) sMode += _T("r");\r
911                 if (nFlags & WGEFF_FullPath) sMode += _T("f");\r
912                 if (nFlags & WGEFF_DirStatusDelta) sMode += _T("d");\r
913                 if (nFlags & WGEFF_DirStatusAll) sMode += _T("D");\r
914                 if (nFlags & WGEFF_EmptyAsNormal) sMode += _T("e");\r
915                 if (nFlags & WGEFF_SingleFile) sMode += _T("s");\r
916         }\r
917         else\r
918         {\r
919                 sMode = _T("-");\r
920         }\r
921 \r
922         if (pszSubPath)\r
923                 cmd.Format(_T("igit.exe \"%s\" status %s \"%s\""), CUnicodeUtils::GetUnicode(pszProjectPath), sMode, CUnicodeUtils::GetUnicode(pszSubPath));\r
924         else\r
925                 cmd.Format(_T("igit.exe \"%s\" status %s"), CUnicodeUtils::GetUnicode(pszProjectPath), sMode);\r
926 \r
927         W_GitCall.SetCmd(cmd);\r
928         // NOTE: should igit get added as a part of msysgit then use below line instead of the above one\r
929         //W_GitCall.SetCmd(CGit::ms_LastMsysGitDir + cmd);\r
930 \r
931         if ( Run(&W_GitCall) )\r
932                 return FALSE;\r
933 \r
934         return TRUE;\r
935 }\r
936 \r
937 BOOL CGit::CheckCleanWorkTree()\r
938 {\r
939         CString out;\r
940         CString cmd;\r
941         cmd=_T("git.exe rev-parse --verify HEAD");\r
942 \r
943         if(g_Git.Run(cmd,&out,CP_UTF8))\r
944                 return FALSE;\r
945 \r
946         cmd=_T("git.exe update-index --ignore-submodules --refresh");\r
947         if(g_Git.Run(cmd,&out,CP_UTF8))\r
948                 return FALSE;\r
949 \r
950         cmd=_T("git.exe diff-files --quiet --ignore-submodules");\r
951         if(g_Git.Run(cmd,&out,CP_UTF8))\r
952                 return FALSE;\r
953 \r
954         cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");\r
955         if(g_Git.Run(cmd,&out,CP_UTF8))\r
956                 return FALSE;\r
957 \r
958         return TRUE;\r
959 }\r
960 \r
961 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)\r
962 {\r
963         BYTE_VECTOR vector;\r
964 \r
965         CString cmd;\r
966         if(path)\r
967                 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());\r
968         else\r
969                 cmd=_T("git.exe ls-files -u -t -z");\r
970 \r
971         if(g_Git.Run(cmd,&vector))\r
972         {\r
973                 return -1;\r
974         }\r
975 \r
976         list.ParserFromLsFile(vector);\r
977 \r
978         return 0;\r
979 }