OSDN Git Service

Merge Myagi exe shell version to show overlay
[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         WCHAR * buf;\r
222 \r
223         int len ;\r
224         if(length<0)\r
225                 len= strlen((const char*)p);\r
226         else\r
227                 len=length;\r
228         //if (len==0)\r
229         //      return ;\r
230         //buf = new WCHAR[len*4 + 1];\r
231         buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();\r
232         SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));\r
233         MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);\r
234         str->ReleaseBuffer();\r
235         //str->Append(buf);\r
236         //delete buf;\r
237 }       \r
238 BOOL CGit::IsInitRepos()\r
239 {\r
240         CString cmdout;\r
241         cmdout.Empty();\r
242         if(g_Git.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout,CP_UTF8))\r
243         {\r
244         //      CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);\r
245                 return TRUE;\r
246         }\r
247         if(cmdout.IsEmpty())\r
248                 return TRUE;\r
249 \r
250         return FALSE;\r
251 }\r
252 int CGit::Run(CGitCall* pcall)\r
253 {\r
254         PROCESS_INFORMATION pi;\r
255         HANDLE hRead;\r
256         if(RunAsync(pcall->GetCmd(),&pi,&hRead))\r
257                 return GIT_ERROR_CREATE_PROCESS;\r
258 \r
259         DWORD readnumber;\r
260         BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];\r
261         bool bAborted=false;\r
262         while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))\r
263         {\r
264                 //Todo: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?\r
265                 if(!bAborted)//For now, flush output when command aborted.\r
266                         if(pcall->OnOutputData(data,readnumber))\r
267                                 bAborted=true;\r
268         }\r
269         if(!bAborted)\r
270                 pcall->OnEnd();\r
271 \r
272         \r
273         CloseHandle(pi.hThread);\r
274 \r
275         WaitForSingleObject(pi.hProcess, INFINITE);\r
276         DWORD exitcode =0;\r
277 \r
278         if(!GetExitCodeProcess(pi.hProcess,&exitcode))\r
279         {\r
280                 return GIT_ERROR_GET_EXIT_CODE;\r
281         }\r
282 \r
283         CloseHandle(pi.hProcess);\r
284 \r
285         CloseHandle(hRead);\r
286         return exitcode;\r
287 }\r
288 class CGitCall_ByteVector : public CGitCall\r
289 {\r
290 public:\r
291         CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector):CGitCall(cmd),m_pvector(pvector){}\r
292         virtual bool OnOutputData(const BYTE* data, size_t size)\r
293         {\r
294                 size_t oldsize=m_pvector->size();\r
295                 m_pvector->resize(m_pvector->size()+size);\r
296                 memcpy(&*(m_pvector->begin()+oldsize),data,size);\r
297                 return false;\r
298         }\r
299         BYTE_VECTOR* m_pvector;\r
300 \r
301 };\r
302 int CGit::Run(CString cmd,BYTE_VECTOR *vector)\r
303 {\r
304         CGitCall_ByteVector call(cmd,vector);\r
305         return Run(&call);\r
306 }\r
307 int CGit::Run(CString cmd, CString* output,int code)\r
308 {\r
309         BYTE_VECTOR vector;\r
310         int ret;\r
311         ret=Run(cmd,&vector);\r
312 \r
313         vector.push_back(0);\r
314         \r
315         StringAppend(output,&(vector[0]),code);\r
316         return ret;\r
317 }\r
318 \r
319 CString CGit::GetUserName(void)\r
320 {\r
321         CString UserName;\r
322         Run(_T("git.exe config user.name"),&UserName,CP_UTF8);\r
323         return UserName;\r
324 }\r
325 CString CGit::GetUserEmail(void)\r
326 {\r
327         CString UserName;\r
328         Run(_T("git.exe config user.email"),&UserName,CP_UTF8);\r
329         return UserName;\r
330 }\r
331 \r
332 CString CGit::GetCurrentBranch(void)\r
333 {\r
334         CString output;\r
335         //Run(_T("git.exe branch"),&branch);\r
336 \r
337         int ret=g_Git.Run(_T("git.exe branch"),&output,CP_UTF8);\r
338         if(!ret)\r
339         {               \r
340                 int pos=0;\r
341                 CString one;\r
342                 while( pos>=0 )\r
343                 {\r
344                         //i++;\r
345                         one=output.Tokenize(_T("\n"),pos);\r
346                         //list.push_back(one.Right(one.GetLength()-2));\r
347                         if(one[0] == _T('*'))\r
348                                 return one.Right(one.GetLength()-2);\r
349                 }\r
350         }\r
351         return CString("");\r
352 }\r
353 \r
354 int CGit::BuildOutputFormat(CString &format,bool IsFull)\r
355 {\r
356         CString log;\r
357         log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);\r
358         format += log;\r
359         if(IsFull)\r
360         {\r
361                 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);\r
362                 format += log;\r
363                 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);\r
364                 format += log;\r
365                 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);\r
366                 format += log;\r
367                 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);\r
368                 format += log;\r
369                 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);\r
370                 format += log;\r
371                 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);\r
372                 format += log;\r
373                 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);\r
374                 format += log;\r
375                 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);\r
376                 format += log;\r
377         }\r
378         log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);\r
379         format += log;\r
380         log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);\r
381         format += log;\r
382 \r
383         if(IsFull)\r
384         {\r
385                 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);\r
386                 format += log;\r
387         }\r
388         return 0;\r
389 }\r
390 \r
391 int CGit::GetLog(BYTE_VECTOR& logOut, CString &hash,  CTGitPath *path ,int count,int mask)\r
392 {\r
393         CGitCall_ByteVector gitCall(CString(),&logOut);\r
394         return GetLog(&gitCall,hash,path,count,mask);\r
395 }\r
396 \r
397 //int CGit::GetLog(CGitCall* pgitCall, CString &hash,  CTGitPath *path ,int count,int mask)\r
398 int CGit::GetLog(CGitCall* pgitCall, CString &hash, CTGitPath *path, int count, int mask)\r
399 {\r
400 \r
401         CString cmd;\r
402         CString log;\r
403         CString num;\r
404         CString since;\r
405 \r
406         CString file;\r
407 \r
408         if(path)\r
409                 file.Format(_T(" -- \"%s\""),path->GetGitPathString());\r
410         \r
411         if(count>0)\r
412                 num.Format(_T("-n%d"),count);\r
413 \r
414         CString param;\r
415 \r
416         if(mask& LOG_INFO_STAT )\r
417                 param += _T(" --numstat ");\r
418         if(mask& LOG_INFO_FILESTATE)\r
419                 param += _T(" --raw ");\r
420 \r
421         if(mask& LOG_INFO_FULLHISTORY)\r
422                 param += _T(" --full-history ");\r
423 \r
424         if(mask& LOG_INFO_BOUNDARY)\r
425                 param += _T(" --left-right --boundary ");\r
426 \r
427         if(mask& CGit::LOG_INFO_ALL_BRANCH)\r
428                 param += _T(" --all ");\r
429 \r
430         if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)\r
431                 param += _T(" -C ");\r
432         \r
433         if(mask& CGit::LOG_INFO_DETECT_RENAME )\r
434                 param += _T(" -M ");\r
435 \r
436         if(mask& CGit::LOG_INFO_FIRST_PARENT )\r
437                 param += _T(" --first-parent ");\r
438         \r
439         if(mask& CGit::LOG_INFO_NO_MERGE )\r
440                 param += _T(" --no-merges ");\r
441 \r
442         if(mask& CGit::LOG_INFO_FOLLOW)\r
443                 param += _T(" --follow ");\r
444 \r
445         param+=hash;\r
446 \r
447         cmd.Format(_T("git.exe log %s -z --topo-order %s --parents --pretty=format:\""),\r
448                                 num,param);\r
449 \r
450         BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));\r
451 \r
452         cmd += log;\r
453         cmd += CString(_T("\"  "))+hash+file;\r
454 \r
455         pgitCall->SetCmd(cmd);\r
456 \r
457         return Run(pgitCall);\r
458 //      return Run(cmd,&logOut);\r
459 }\r
460 \r
461 #if 0\r
462 int CGit::GetShortLog(CString &logOut,CTGitPath * path, int count)\r
463 {\r
464         CString cmd;\r
465         CString log;\r
466         int n;\r
467         if(count<0)\r
468                 n=100;\r
469         else\r
470                 n=count;\r
471         cmd.Format(_T("git.exe log --left-right --boundary --topo-order -n%d --pretty=format:\""),n);\r
472         BuildOutputFormat(log,false);\r
473         cmd += log+_T("\"");\r
474         if (path)\r
475                 cmd+= _T("  -- \"")+path->GetGitPathString()+_T("\"");\r
476         //cmd += CString(_T("\" HEAD~40..HEAD"));\r
477         return Run(cmd,&logOut);\r
478 }\r
479 #endif\r
480 \r
481 #define BUFSIZE 512\r
482 void GetTempPath(CString &path)\r
483 {\r
484         TCHAR lpPathBuffer[BUFSIZE];\r
485         DWORD dwRetVal;\r
486         DWORD dwBufSize=BUFSIZE;\r
487         dwRetVal = GetTempPath(dwBufSize,     // length of the buffer\r
488                            lpPathBuffer); // buffer for path \r
489     if (dwRetVal > dwBufSize || (dwRetVal == 0))\r
490     {\r
491         path=_T("");\r
492     }\r
493         path.Format(_T("%s"),lpPathBuffer);\r
494 }\r
495 CString GetTempFile()\r
496 {\r
497         TCHAR lpPathBuffer[BUFSIZE];\r
498         DWORD dwRetVal;\r
499     DWORD dwBufSize=BUFSIZE;\r
500         TCHAR szTempName[BUFSIZE];  \r
501         UINT uRetVal;\r
502 \r
503         dwRetVal = GetTempPath(dwBufSize,     // length of the buffer\r
504                            lpPathBuffer); // buffer for path \r
505     if (dwRetVal > dwBufSize || (dwRetVal == 0))\r
506     {\r
507         return _T("");\r
508     }\r
509          // Create a temporary file. \r
510     uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files\r
511                               TEXT("Patch"),  // temp file name prefix \r
512                               0,            // create unique name \r
513                               szTempName);  // buffer for name \r
514 \r
515 \r
516     if (uRetVal == 0)\r
517     {\r
518         return _T("");\r
519     }\r
520 \r
521         return CString(szTempName);\r
522 \r
523 }\r
524 \r
525 int CGit::RunLogFile(CString cmd,CString &filename)\r
526 {\r
527         STARTUPINFO si;\r
528         PROCESS_INFORMATION pi;\r
529         si.cb=sizeof(STARTUPINFO);\r
530         GetStartupInfo(&si);\r
531 \r
532         SECURITY_ATTRIBUTES   psa={sizeof(psa),NULL,TRUE};;   \r
533         psa.bInheritHandle=TRUE;   \r
534     \r
535         HANDLE   houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ   |   FILE_SHARE_WRITE,   \r
536                         &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);   \r
537 \r
538 \r
539         si.wShowWindow=SW_HIDE;\r
540         si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;\r
541         si.hStdOutput   =   houtfile; \r
542         \r
543         if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,NULL,NULL,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))\r
544         {\r
545                 LPVOID lpMsgBuf;\r
546                 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,\r
547                         NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\r
548                         (LPTSTR)&lpMsgBuf,\r
549                         0,NULL);\r
550                 return GIT_ERROR_CREATE_PROCESS;\r
551         }\r
552         \r
553         WaitForSingleObject(pi.hProcess,INFINITE);   \r
554         \r
555         CloseHandle(pi.hThread);\r
556         CloseHandle(pi.hProcess);\r
557         CloseHandle(houtfile);\r
558         return GIT_SUCCESS;\r
559 //      return 0;\r
560 }\r
561 \r
562 git_revnum_t CGit::GetHash(CString &friendname)\r
563 {\r
564         CString cmd;\r
565         CString out;\r
566         cmd.Format(_T("git.exe rev-parse %s" ),friendname);\r
567         Run(cmd,&out,CP_UTF8);\r
568         int pos=out.ReverseFind(_T('\n'));\r
569         if(pos>0)\r
570                 return out.Left(pos);\r
571         return out;\r
572 }\r
573 \r
574 int CGit::GetTagList(STRING_VECTOR &list)\r
575 {\r
576         int ret;\r
577         CString cmd,output;\r
578         cmd=_T("git.exe tag -l");\r
579         int i=0;\r
580         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
581         if(!ret)\r
582         {               \r
583                 int pos=0;\r
584                 CString one;\r
585                 while( pos>=0 )\r
586                 {\r
587                         i++;\r
588                         one=output.Tokenize(_T("\n"),pos);\r
589                         list.push_back(one);\r
590                 }\r
591         }\r
592         return ret;\r
593 }\r
594 \r
595 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)\r
596 {\r
597         int ret;\r
598         CString cmd,output;\r
599         cmd=_T("git.exe branch");\r
600 \r
601         if(type==(BRANCH_LOCAL|BRANCH_REMOTE))\r
602                 cmd+=_T(" -a");\r
603         else if(type==BRANCH_REMOTE)\r
604                 cmd+=_T(" -r");\r
605 \r
606         int i=0;\r
607         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
608         if(!ret)\r
609         {               \r
610                 int pos=0;\r
611                 CString one;\r
612                 while( pos>=0 )\r
613                 {\r
614                         one=output.Tokenize(_T("\n"),pos);\r
615                         list.push_back(one.Right(one.GetLength()-2));\r
616                         if(one[0] == _T('*'))\r
617                                 if(current)\r
618                                         *current=i;\r
619                         i++;\r
620                 }\r
621         }\r
622         return ret;\r
623 }\r
624 \r
625 int CGit::GetRemoteList(STRING_VECTOR &list)\r
626 {\r
627         int ret;\r
628         CString cmd,output;\r
629         cmd=_T("git.exe config  --get-regexp remote.*.url");\r
630         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
631         if(!ret)\r
632         {\r
633                 int pos=0;\r
634                 CString one;\r
635                 while( pos>=0 )\r
636                 {\r
637                         one=output.Tokenize(_T("\n"),pos);\r
638                         int start=one.Find(_T("."),0);\r
639                         if(start>0)\r
640                         {\r
641                                 CString url;\r
642                                 url=one.Right(one.GetLength()-start-1);\r
643                                 one=url;\r
644                                 one=one.Left(one.Find(_T("."),0));\r
645                                 list.push_back(one);\r
646                         }\r
647                 }\r
648         }\r
649         return ret;\r
650 }\r
651 \r
652 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)\r
653 {\r
654         int ret;\r
655         CString cmd,output;\r
656         cmd=_T("git show-ref -d");\r
657         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
658         if(!ret)\r
659         {\r
660                 int pos=0;\r
661                 CString one;\r
662                 while( pos>=0 )\r
663                 {\r
664                         one=output.Tokenize(_T("\n"),pos);\r
665                         int start=one.Find(_T(" "),0);\r
666                         if(start>0)\r
667                         {\r
668                                 CString name;\r
669                                 name=one.Right(one.GetLength()-start-1);\r
670 \r
671                                 CString hash;\r
672                                 hash=one.Left(start);\r
673 \r
674                                 map[hash].push_back(name);\r
675                         }\r
676                 }\r
677         }\r
678         return ret;\r
679 }\r
680 \r
681 BOOL CGit::CheckMsysGitDir()\r
682 {\r
683         static BOOL bInitialized = FALSE;\r
684 \r
685         if (bInitialized)\r
686         {\r
687                 return TRUE;\r
688         }\r
689 \r
690         TCHAR *oldpath,*home;\r
691         size_t size;\r
692 \r
693         // set HOME if not set already\r
694         _tgetenv_s(&size, NULL, 0, _T("HOME"));\r
695         if (!size)\r
696         {\r
697                 _tdupenv_s(&home,&size,_T("USERPROFILE")); \r
698                 _tputenv_s(_T("HOME"),home);\r
699                 free(home);\r
700         }\r
701 \r
702         //setup ssh client\r
703         CRegString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));\r
704         CString ssh=sshclient;\r
705 \r
706         if(!ssh.IsEmpty())\r
707         {\r
708                 _tputenv_s(_T("GIT_SSH"),ssh);\r
709         }else\r
710         {\r
711                 _tputenv_s(_T("GIT_SSH"),_T(""));\r
712         }\r
713 \r
714         // search PATH if git/bin directory is alredy present\r
715         if ( FindGitPath() )\r
716         {\r
717                 bInitialized = TRUE;\r
718                 return TRUE;\r
719         }\r
720 \r
721         // add git/bin path to PATH\r
722 \r
723         CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE,HKEY_LOCAL_MACHINE);\r
724         CString str=msysdir;\r
725         if(str.IsEmpty())\r
726         {\r
727                 CRegString msysinstalldir=CRegString(REG_MSYSGIT_INSTALL,_T(""),FALSE,HKEY_LOCAL_MACHINE);\r
728                 str=msysinstalldir;\r
729                 if ( !str.IsEmpty() )\r
730                 {\r
731                         str += (str[str.GetLength()-1] != '\\') ? "\\bin" : "bin";\r
732                         msysdir=str;\r
733                         msysdir.write();\r
734                 }\r
735                 else\r
736                 {\r
737                         return false;\r
738                 }\r
739         }\r
740         //CGit::m_MsysGitPath=str;\r
741 \r
742         //set path\r
743 \r
744         _tdupenv_s(&oldpath,&size,_T("PATH")); \r
745 \r
746         CString path;\r
747         path.Format(_T("%s;%s"),oldpath,str);\r
748 \r
749         _tputenv_s(_T("PATH"),path);\r
750 \r
751         CString sOldPath = oldpath;\r
752         free(oldpath);\r
753 \r
754 \r
755     if( !FindGitPath() )\r
756         {\r
757                 return false;\r
758         }\r
759         else\r
760         {\r
761 #ifdef _TORTOISESHELL\r
762                 l_processEnv = GetEnvironmentStrings();\r
763                 // updated environment is now duplicated for use in CreateProcess, restore original PATH for current process\r
764                 _tputenv_s(_T("PATH"),sOldPath);\r
765 #endif\r
766 \r
767                 bInitialized = TRUE;\r
768                 return true;\r
769         }\r
770 }\r
771 \r
772 \r
773 class CGitCall_EnumFiles : public CGitCall\r
774 {\r
775 public:\r
776         CGitCall_EnumFiles(const char *pszProjectPath, const char *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)\r
777         :       m_pszProjectPath(pszProjectPath),\r
778                 m_pszSubPath(pszSubPath),\r
779                 m_nFlags(nFlags),\r
780                 m_pEnumCb(pEnumCb),\r
781                 m_pUserData(pUserData)\r
782         {\r
783         }\r
784 \r
785         typedef std::map<CStringA,char> TStrCharMap;\r
786 \r
787         const char *    m_pszProjectPath;\r
788         const char *    m_pszSubPath;\r
789         unsigned int    m_nFlags;\r
790         WGENUMFILECB *  m_pEnumCb;\r
791         void *                  m_pUserData;\r
792 \r
793         BYTE_VECTOR             m_DataCollector;\r
794 \r
795         virtual bool    OnOutputData(const BYTE* data, size_t size)\r
796         {\r
797                 m_DataCollector.append(data,size);\r
798                 while(true)\r
799                 {\r
800                         // lines from igit.exe are 0 terminated\r
801                         int found=m_DataCollector.findData((const BYTE*)"",1);\r
802                         if(found<0)\r
803                                 return false;\r
804                         OnSingleLine( (LPCSTR)&*m_DataCollector.begin() );\r
805                         m_DataCollector.erase(m_DataCollector.begin(), m_DataCollector.begin()+found+1);\r
806                 }\r
807                 return false;//Should never reach this\r
808         }\r
809         virtual void    OnEnd()\r
810         {\r
811         }\r
812 \r
813         UINT HexChar(char ch)\r
814         {\r
815                 if (ch >= '0' && ch <= '9')\r
816                         return (UINT)(ch - '0');\r
817                 else if (ch >= 'A' && ch <= 'F')\r
818                         return (UINT)(ch - 'A') + 10;\r
819                 else if (ch >= 'a' && ch <= 'f')\r
820                         return (UINT)(ch - 'a') + 10;\r
821                 else\r
822                         return 0;\r
823         }\r
824 \r
825         bool OnSingleLine(LPCSTR line)\r
826         {\r
827                 //Parse single line\r
828 \r
829                 wgFile_s fileStatus;\r
830 \r
831                 // file/dir type\r
832 \r
833                 fileStatus.nFlags = 0;\r
834                 if (*line == 'D')\r
835                         fileStatus.nFlags |= WGFF_Directory;\r
836                 line += 2;\r
837 \r
838                 // status\r
839 \r
840                 fileStatus.nStatus = WGFS_Unknown;\r
841                 switch (*line)\r
842                 {\r
843                 case 'N': fileStatus.nStatus = WGFS_Normal; break;\r
844                 case 'M': fileStatus.nStatus = WGFS_Modified; break;\r
845                 case 'S': fileStatus.nStatus = WGFS_Staged; break;\r
846                 case 'A': fileStatus.nStatus = WGFS_Added; break;\r
847                 case 'C': fileStatus.nStatus = WGFS_Conflicted; break;\r
848                 case 'D': fileStatus.nStatus = WGFS_Deleted; break;\r
849                 case 'I': fileStatus.nStatus = WGFS_Ignored; break;\r
850                 case 'U': fileStatus.nStatus = WGFS_Unversioned; break;\r
851                 case 'E': fileStatus.nStatus = WGFS_Empty; break;\r
852                 }\r
853                 line += 2;\r
854 \r
855                 // file sha1\r
856 \r
857                 BYTE sha1[20];\r
858                 fileStatus.sha1 = NULL;\r
859                 if ( !(fileStatus.nFlags & WGFF_Directory) )\r
860                 {\r
861                         for (int i=0; i<20; i++)\r
862                         {\r
863                                 sha1[i] = (HexChar(line[0]) << 8) | HexChar(line[1]);\r
864                                 line += 2;\r
865                         }\r
866 \r
867                         line++;\r
868                 }\r
869 \r
870                 // filename\r
871                 fileStatus.sFileName = line;\r
872 \r
873                 if ( (*m_pEnumCb)(&fileStatus,m_pUserData) )\r
874                         return false;\r
875 \r
876                 return true;\r
877         }\r
878 };\r
879 \r
880 BOOL CGit::EnumFiles(const char *pszProjectPath, const char *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)\r
881 {\r
882         if(!pszProjectPath || *pszProjectPath=='\0')\r
883                 return FALSE;\r
884 \r
885         CGitCall_EnumFiles W_GitCall(pszProjectPath,pszSubPath,nFlags,pEnumCb,pUserData);\r
886         CString cmd;\r
887 \r
888 /*      char W_szToDir[MAX_PATH];\r
889         strncpy(W_szToDir,pszProjectPath,sizeof(W_szToDir)-1);\r
890         if(W_szToDir[strlen(W_szToDir)-1]!='\\')\r
891                 strncat(W_szToDir,"\\",sizeof(W_szToDir)-1);\r
892 \r
893         SetCurrentDirectoryA(W_szToDir);\r
894         GetCurrentDirectoryA(sizeof(W_szToDir)-1,W_szToDir);\r
895 */\r
896         SetCurrentDir(CUnicodeUtils::GetUnicode(pszProjectPath));\r
897 \r
898         CString sMode;\r
899         if (nFlags)\r
900         {\r
901                 if (nFlags & WGEFF_NoRecurse) sMode += _T("r");\r
902                 if (nFlags & WGEFF_FullPath) sMode += _T("f");\r
903                 if (nFlags & WGEFF_DirStatusDelta) sMode += _T("d");\r
904                 if (nFlags & WGEFF_DirStatusAll) sMode += _T("D");\r
905                 if (nFlags & WGEFF_EmptyAsNormal) sMode += _T("e");\r
906                 if (nFlags & WGEFF_SingleFile) sMode += _T("s");\r
907         }\r
908         else\r
909         {\r
910                 sMode = _T("-");\r
911         }\r
912 \r
913         if (pszSubPath)\r
914                 cmd.Format(_T("igit.exe %s status %s %s"), CUnicodeUtils::GetUnicode(pszProjectPath), sMode, CUnicodeUtils::GetUnicode(pszSubPath));\r
915         else\r
916                 cmd.Format(_T("igit.exe %s status %s"), CUnicodeUtils::GetUnicode(pszProjectPath), sMode);\r
917 \r
918         W_GitCall.SetCmd(cmd);\r
919         // NOTE: should igit get added as a part of msysgit then use below line instead of the above one\r
920         //W_GitCall.SetCmd(CGit::ms_LastMsysGitDir + cmd);\r
921 \r
922         if ( Run(&W_GitCall) )\r
923                 return FALSE;\r
924 \r
925         return TRUE;\r
926 }\r