OSDN Git Service

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