OSDN Git Service

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