OSDN Git Service

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