OSDN Git Service

Add union code encode at commit support i18n.commitencoding
[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(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)\r
480                 param += _T(" -c ");\r
481 \r
482         if(from != NULL && to != NULL)\r
483         {\r
484                 CString range;\r
485                 range.Format(_T(" %s..%s "),*from,*to);\r
486                 param += range;\r
487         }\r
488         param+=hash;\r
489 \r
490         cmd.Format(_T("git.exe log %s -z --topo-order %s --parents --pretty=format:\""),\r
491                                 num,param);\r
492 \r
493         BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));\r
494 \r
495         cmd += log;\r
496         cmd += CString(_T("\"  "))+hash+file;\r
497 \r
498         pgitCall->SetCmd(cmd);\r
499 \r
500         return Run(pgitCall);\r
501 //      return Run(cmd,&logOut);\r
502 }\r
503 \r
504 #if 0\r
505 int CGit::GetShortLog(CString &logOut,CTGitPath * path, int count)\r
506 {\r
507         CString cmd;\r
508         CString log;\r
509         int n;\r
510         if(count<0)\r
511                 n=100;\r
512         else\r
513                 n=count;\r
514         cmd.Format(_T("git.exe log --left-right --boundary --topo-order -n%d --pretty=format:\""),n);\r
515         BuildOutputFormat(log,false);\r
516         cmd += log+_T("\"");\r
517         if (path)\r
518                 cmd+= _T("  -- \"")+path->GetGitPathString()+_T("\"");\r
519         //cmd += CString(_T("\" HEAD~40..HEAD"));\r
520         return Run(cmd,&logOut);\r
521 }\r
522 #endif\r
523 \r
524 #define BUFSIZE 512\r
525 void GetTempPath(CString &path)\r
526 {\r
527         TCHAR lpPathBuffer[BUFSIZE];\r
528         DWORD dwRetVal;\r
529         DWORD dwBufSize=BUFSIZE;\r
530         dwRetVal = GetTempPath(dwBufSize,     // length of the buffer\r
531                            lpPathBuffer); // buffer for path \r
532     if (dwRetVal > dwBufSize || (dwRetVal == 0))\r
533     {\r
534         path=_T("");\r
535     }\r
536         path.Format(_T("%s"),lpPathBuffer);\r
537 }\r
538 CString GetTempFile()\r
539 {\r
540         TCHAR lpPathBuffer[BUFSIZE];\r
541         DWORD dwRetVal;\r
542     DWORD dwBufSize=BUFSIZE;\r
543         TCHAR szTempName[BUFSIZE];  \r
544         UINT uRetVal;\r
545 \r
546         dwRetVal = GetTempPath(dwBufSize,     // length of the buffer\r
547                            lpPathBuffer); // buffer for path \r
548     if (dwRetVal > dwBufSize || (dwRetVal == 0))\r
549     {\r
550         return _T("");\r
551     }\r
552          // Create a temporary file. \r
553     uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files\r
554                               TEXT("Patch"),  // temp file name prefix \r
555                               0,            // create unique name \r
556                               szTempName);  // buffer for name \r
557 \r
558 \r
559     if (uRetVal == 0)\r
560     {\r
561         return _T("");\r
562     }\r
563 \r
564         return CString(szTempName);\r
565 \r
566 }\r
567 \r
568 int CGit::RunLogFile(CString cmd,CString &filename)\r
569 {\r
570         STARTUPINFO si;\r
571         PROCESS_INFORMATION pi;\r
572         si.cb=sizeof(STARTUPINFO);\r
573         GetStartupInfo(&si);\r
574 \r
575         SECURITY_ATTRIBUTES   psa={sizeof(psa),NULL,TRUE};;   \r
576         psa.bInheritHandle=TRUE;   \r
577     \r
578         HANDLE   houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ   |   FILE_SHARE_WRITE,   \r
579                         &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);   \r
580 \r
581 \r
582         si.wShowWindow=SW_HIDE;\r
583         si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;\r
584         si.hStdOutput   =   houtfile; \r
585         \r
586         if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,NULL,NULL,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))\r
587         {\r
588                 LPVOID lpMsgBuf;\r
589                 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,\r
590                         NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\r
591                         (LPTSTR)&lpMsgBuf,\r
592                         0,NULL);\r
593                 return GIT_ERROR_CREATE_PROCESS;\r
594         }\r
595         \r
596         WaitForSingleObject(pi.hProcess,INFINITE);   \r
597         \r
598         CloseHandle(pi.hThread);\r
599         CloseHandle(pi.hProcess);\r
600         CloseHandle(houtfile);\r
601         return GIT_SUCCESS;\r
602 //      return 0;\r
603 }\r
604 \r
605 git_revnum_t CGit::GetHash(CString &friendname)\r
606 {\r
607         CString cmd;\r
608         CString out;\r
609         cmd.Format(_T("git.exe rev-parse %s" ),friendname);\r
610         Run(cmd,&out,CP_UTF8);\r
611 //      int pos=out.ReverseFind(_T('\n'));\r
612         int pos=out.FindOneOf(_T("\r\n"));\r
613         if(pos>0)\r
614                 return out.Left(pos);\r
615         return out;\r
616 }\r
617 \r
618 int CGit::GetTagList(STRING_VECTOR &list)\r
619 {\r
620         int ret;\r
621         CString cmd,output;\r
622         cmd=_T("git.exe tag -l");\r
623         int i=0;\r
624         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
625         if(!ret)\r
626         {               \r
627                 int pos=0;\r
628                 CString one;\r
629                 while( pos>=0 )\r
630                 {\r
631                         i++;\r
632                         one=output.Tokenize(_T("\n"),pos);\r
633                         list.push_back(one);\r
634                 }\r
635         }\r
636         return ret;\r
637 }\r
638 \r
639 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)\r
640 {\r
641         int ret;\r
642         CString cmd,output;\r
643         cmd=_T("git.exe branch");\r
644 \r
645         if(type==(BRANCH_LOCAL|BRANCH_REMOTE))\r
646                 cmd+=_T(" -a");\r
647         else if(type==BRANCH_REMOTE)\r
648                 cmd+=_T(" -r");\r
649 \r
650         int i=0;\r
651         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
652         if(!ret)\r
653         {               \r
654                 int pos=0;\r
655                 CString one;\r
656                 while( pos>=0 )\r
657                 {\r
658                         one=output.Tokenize(_T("\n"),pos);\r
659                         list.push_back(one.Right(one.GetLength()-2));\r
660                         if(one[0] == _T('*'))\r
661                                 if(current)\r
662                                         *current=i;\r
663                         i++;\r
664                 }\r
665         }\r
666         return ret;\r
667 }\r
668 \r
669 int CGit::GetRemoteList(STRING_VECTOR &list)\r
670 {\r
671         int ret;\r
672         CString cmd,output;\r
673         cmd=_T("git.exe config  --get-regexp remote.*.url");\r
674         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
675         if(!ret)\r
676         {\r
677                 int pos=0;\r
678                 CString one;\r
679                 while( pos>=0 )\r
680                 {\r
681                         one=output.Tokenize(_T("\n"),pos);\r
682                         int start=one.Find(_T("."),0);\r
683                         if(start>0)\r
684                         {\r
685                                 CString url;\r
686                                 url=one.Right(one.GetLength()-start-1);\r
687                                 one=url;\r
688                                 one=one.Left(one.Find(_T("."),0));\r
689                                 list.push_back(one);\r
690                         }\r
691                 }\r
692         }\r
693         return ret;\r
694 }\r
695 \r
696 int CGit::GetRefList(STRING_VECTOR &list)\r
697 {\r
698         int ret;\r
699         CString cmd,output;\r
700         cmd=_T("git show-ref -d");\r
701         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
702         if(!ret)\r
703         {\r
704                 int pos=0;\r
705                 CString one;\r
706                 while( pos>=0 )\r
707                 {\r
708                         one=output.Tokenize(_T("\n"),pos);\r
709                         int start=one.Find(_T(" "),0);\r
710                         if(start>0)\r
711                         {\r
712                                 CString name;\r
713                                 name=one.Right(one.GetLength()-start-1);\r
714                                 list.push_back(name);\r
715                         }\r
716                 }\r
717         }\r
718         return ret;\r
719 }\r
720 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)\r
721 {\r
722         int ret;\r
723         CString cmd,output;\r
724         cmd=_T("git show-ref -d");\r
725         ret=g_Git.Run(cmd,&output,CP_UTF8);\r
726         if(!ret)\r
727         {\r
728                 int pos=0;\r
729                 CString one;\r
730                 while( pos>=0 )\r
731                 {\r
732                         one=output.Tokenize(_T("\n"),pos);\r
733                         int start=one.Find(_T(" "),0);\r
734                         if(start>0)\r
735                         {\r
736                                 CString name;\r
737                                 name=one.Right(one.GetLength()-start-1);\r
738 \r
739                                 CString hash;\r
740                                 hash=one.Left(start);\r
741 \r
742                                 map[hash].push_back(name);\r
743                         }\r
744                 }\r
745         }\r
746         return ret;\r
747 }\r
748 \r
749 BOOL CGit::CheckMsysGitDir()\r
750 {\r
751         static BOOL bInitialized = FALSE;\r
752 \r
753         if (bInitialized)\r
754         {\r
755                 return TRUE;\r
756         }\r
757 \r
758         TCHAR *oldpath,*home;\r
759         size_t size;\r
760 \r
761         // set HOME if not set already\r
762         _tgetenv_s(&size, NULL, 0, _T("HOME"));\r
763         if (!size)\r
764         {\r
765                 _tdupenv_s(&home,&size,_T("USERPROFILE")); \r
766                 _tputenv_s(_T("HOME"),home);\r
767                 free(home);\r
768         }\r
769 \r
770         //setup ssh client\r
771         CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));\r
772 \r
773         if(!sshclient.IsEmpty())\r
774         {\r
775                 _tputenv_s(_T("GIT_SSH"),sshclient);\r
776         }else\r
777         {\r
778                 TCHAR sPlink[MAX_PATH];\r
779                 GetModuleFileName(NULL, sPlink, _countof(sPlink));\r
780                 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));\r
781                 if (ptr) {\r
782                         _tcscpy(ptr + 1, _T("TortoisePlink.exe"));\r
783                         _tputenv_s(_T("GIT_SSH"), sPlink);\r
784                 }\r
785         }\r
786 \r
787         {\r
788                 TCHAR sAskPass[MAX_PATH];\r
789                 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));\r
790                 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));\r
791                 if (ptr) \r
792                 {\r
793                         _tcscpy(ptr + 1, _T("SshAskPass.exe"));\r
794                         _tputenv_s(_T("DISPLAY"),_T(":9999"));\r
795                         _tputenv_s(_T("SSH_ASKPASS"),sAskPass);\r
796                 }\r
797         }\r
798         // search PATH if git/bin directory is alredy present\r
799         if ( FindGitPath() )\r
800         {\r
801                 bInitialized = TRUE;\r
802                 return TRUE;\r
803         }\r
804 \r
805         // add git/bin path to PATH\r
806 \r
807         CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);\r
808         CString str=msysdir;\r
809         if(str.IsEmpty())\r
810         {\r
811                 CRegString msysinstalldir=CRegString(REG_MSYSGIT_INSTALL,_T(""),FALSE,HKEY_LOCAL_MACHINE);\r
812                 str=msysinstalldir;\r
813                 if ( !str.IsEmpty() )\r
814                 {\r
815                         str += (str[str.GetLength()-1] != '\\') ? "\\bin" : "bin";\r
816                         msysdir=str;\r
817                         msysdir.write();\r
818                 }\r
819                 else\r
820                 {\r
821                         return false;\r
822                 }\r
823         }\r
824         //CGit::m_MsysGitPath=str;\r
825 \r
826         //set path\r
827 \r
828         _tdupenv_s(&oldpath,&size,_T("PATH")); \r
829 \r
830         CString path;\r
831         path.Format(_T("%s;%s"),oldpath,str);\r
832 \r
833         _tputenv_s(_T("PATH"),path);\r
834 \r
835         CString sOldPath = oldpath;\r
836         free(oldpath);\r
837 \r
838 \r
839     if( !FindGitPath() )\r
840         {\r
841                 return false;\r
842         }\r
843         else\r
844         {\r
845 #ifdef _TORTOISESHELL\r
846                 l_processEnv = GetEnvironmentStrings();\r
847                 // updated environment is now duplicated for use in CreateProcess, restore original PATH for current process\r
848                 _tputenv_s(_T("PATH"),sOldPath);\r
849 #endif\r
850 \r
851                 bInitialized = TRUE;\r
852                 return true;\r
853         }\r
854 }\r
855 \r
856 \r
857 class CGitCall_EnumFiles : public CGitCall\r
858 {\r
859 public:\r
860         CGitCall_EnumFiles(const TCHAR *pszProjectPath, const TCHAR *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)\r
861         :       m_pszProjectPath(pszProjectPath),\r
862                 m_pszSubPath(pszSubPath),\r
863                 m_nFlags(nFlags),\r
864                 m_pEnumCb(pEnumCb),\r
865                 m_pUserData(pUserData)\r
866         {\r
867         }\r
868 \r
869         typedef std::map<CStringA,char> TStrCharMap;\r
870 \r
871         const TCHAR *   m_pszProjectPath;\r
872         const TCHAR *   m_pszSubPath;\r
873         unsigned int    m_nFlags;\r
874         WGENUMFILECB *  m_pEnumCb;\r
875         void *                  m_pUserData;\r
876 \r
877         BYTE_VECTOR             m_DataCollector;\r
878 \r
879         virtual bool    OnOutputData(const BYTE* data, size_t size)\r
880         {\r
881                 m_DataCollector.append(data,size);\r
882                 while(true)\r
883                 {\r
884                         // lines from igit.exe are 0 terminated\r
885                         int found=m_DataCollector.findData((const BYTE*)"",1);\r
886                         if(found<0)\r
887                                 return false;\r
888                         OnSingleLine( (LPCSTR)&*m_DataCollector.begin() );\r
889                         m_DataCollector.erase(m_DataCollector.begin(), m_DataCollector.begin()+found+1);\r
890                 }\r
891                 return false;//Should never reach this\r
892         }\r
893         virtual void    OnEnd()\r
894         {\r
895         }\r
896 \r
897         BYTE HexChar(char ch)\r
898         {\r
899                 if (ch >= '0' && ch <= '9')\r
900                         return (UINT)(ch - '0');\r
901                 else if (ch >= 'A' && ch <= 'F')\r
902                         return (UINT)(ch - 'A') + 10;\r
903                 else if (ch >= 'a' && ch <= 'f')\r
904                         return (UINT)(ch - 'a') + 10;\r
905                 else\r
906                         return 0;\r
907         }\r
908 \r
909         bool OnSingleLine(LPCSTR line)\r
910         {\r
911                 //Parse single line\r
912 \r
913                 wgFile_s fileStatus;\r
914 \r
915                 // file/dir type\r
916 \r
917                 fileStatus.nFlags = 0;\r
918                 if (*line == 'D')\r
919                         fileStatus.nFlags |= WGFF_Directory;\r
920                 else if (*line != 'F')\r
921                         // parse error\r
922                         return false;\r
923                 line += 2;\r
924 \r
925                 // status\r
926 \r
927                 fileStatus.nStatus = WGFS_Unknown;\r
928                 switch (*line)\r
929                 {\r
930                 case 'N': fileStatus.nStatus = WGFS_Normal; break;\r
931                 case 'M': fileStatus.nStatus = WGFS_Modified; break;\r
932                 case 'S': fileStatus.nStatus = WGFS_Staged; break;\r
933                 case 'A': fileStatus.nStatus = WGFS_Added; break;\r
934                 case 'C': fileStatus.nStatus = WGFS_Conflicted; break;\r
935                 case 'D': fileStatus.nStatus = WGFS_Deleted; break;\r
936                 case 'I': fileStatus.nStatus = WGFS_Ignored; break;\r
937                 case 'U': fileStatus.nStatus = WGFS_Unversioned; break;\r
938                 case 'E': fileStatus.nStatus = WGFS_Empty; break;\r
939                 case '?': fileStatus.nStatus = WGFS_Unknown; break;\r
940                 default:\r
941                         // parse error\r
942                         return false;\r
943                 }\r
944                 line += 2;\r
945 \r
946                 // file sha1\r
947 \r
948                 BYTE sha1[20];\r
949                 fileStatus.sha1 = NULL;\r
950                 if ( !(fileStatus.nFlags & WGFF_Directory) )\r
951                 {\r
952                         for (int i=0; i<20; i++)\r
953                         {\r
954                                 sha1[i]  = (HexChar(line[0])<<4)&0xF0;\r
955                                 sha1[i] |= HexChar(line[1])&0xF;\r
956 \r
957                                 line += 2;\r
958                         }\r
959 \r
960                         line++;\r
961                 }\r
962 \r
963                 // filename\r
964                 int len = strlen(line);\r
965                 if (len && len < 2048)\r
966                 {\r
967                         WCHAR *buf = (WCHAR*)alloca((len*4+2)*sizeof(WCHAR));\r
968                         *buf = 0;\r
969                         MultiByteToWideChar(CP_ACP, 0, line, len+1, buf, len*4+1);\r
970                         fileStatus.sFileName = buf;\r
971 \r
972                         if (*buf && (*m_pEnumCb)(&fileStatus,m_pUserData))\r
973                                 return false;\r
974                 }\r
975 \r
976                 return true;\r
977         }\r
978 };\r
979 \r
980 BOOL CGit::EnumFiles(const TCHAR *pszProjectPath, const TCHAR *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)\r
981 {\r
982         if(!pszProjectPath || *pszProjectPath=='\0')\r
983                 return FALSE;\r
984 \r
985         CGitCall_EnumFiles W_GitCall(pszProjectPath,pszSubPath,nFlags,pEnumCb,pUserData);\r
986         CString cmd;\r
987 \r
988 /*      char W_szToDir[MAX_PATH];\r
989         strncpy(W_szToDir,pszProjectPath,sizeof(W_szToDir)-1);\r
990         if(W_szToDir[strlen(W_szToDir)-1]!='\\')\r
991                 strncat(W_szToDir,"\\",sizeof(W_szToDir)-1);\r
992 \r
993         SetCurrentDirectoryA(W_szToDir);\r
994         GetCurrentDirectoryA(sizeof(W_szToDir)-1,W_szToDir);\r
995 */\r
996         SetCurrentDir(pszProjectPath);\r
997 \r
998         CString sMode;\r
999         if (nFlags)\r
1000         {\r
1001                 if (nFlags & WGEFF_NoRecurse) sMode += _T("r");\r
1002                 if (nFlags & WGEFF_FullPath) sMode += _T("f");\r
1003                 if (nFlags & WGEFF_DirStatusDelta) sMode += _T("d");\r
1004                 if (nFlags & WGEFF_DirStatusAll) sMode += _T("D");\r
1005                 if (nFlags & WGEFF_EmptyAsNormal) sMode += _T("e");\r
1006                 if (nFlags & WGEFF_SingleFile) sMode += _T("s");\r
1007         }\r
1008         else\r
1009         {\r
1010                 sMode = _T("-");\r
1011         }\r
1012 \r
1013         if (pszSubPath)\r
1014                 cmd.Format(_T("igit.exe \"%s\" status %s \"%s\""), pszProjectPath, sMode, pszSubPath);\r
1015         else\r
1016                 cmd.Format(_T("igit.exe \"%s\" status %s"), pszProjectPath, sMode);\r
1017 \r
1018         W_GitCall.SetCmd(cmd);\r
1019         // NOTE: should igit get added as a part of msysgit then use below line instead of the above one\r
1020         //W_GitCall.SetCmd(CGit::ms_LastMsysGitDir + cmd);\r
1021 \r
1022         if ( Run(&W_GitCall) )\r
1023                 return FALSE;\r
1024 \r
1025         return TRUE;\r
1026 }\r
1027 \r
1028 BOOL CGit::CheckCleanWorkTree()\r
1029 {\r
1030         CString out;\r
1031         CString cmd;\r
1032         cmd=_T("git.exe rev-parse --verify HEAD");\r
1033 \r
1034         if(g_Git.Run(cmd,&out,CP_UTF8))\r
1035                 return FALSE;\r
1036 \r
1037         cmd=_T("git.exe update-index --ignore-submodules --refresh");\r
1038         if(g_Git.Run(cmd,&out,CP_UTF8))\r
1039                 return FALSE;\r
1040 \r
1041         cmd=_T("git.exe diff-files --quiet --ignore-submodules");\r
1042         if(g_Git.Run(cmd,&out,CP_UTF8))\r
1043                 return FALSE;\r
1044 \r
1045         cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");\r
1046         if(g_Git.Run(cmd,&out,CP_UTF8))\r
1047                 return FALSE;\r
1048 \r
1049         return TRUE;\r
1050 }\r
1051 int CGit::Revert(CTGitPathList &list,bool keep)\r
1052 {\r
1053         int ret;\r
1054         for(int i=0;i<list.GetCount();i++)\r
1055         {       \r
1056                 ret = Revert((CTGitPath&)list[i],keep);\r
1057                 if(ret)\r
1058                         return ret;\r
1059         }\r
1060         return 0;\r
1061 }\r
1062 int CGit::Revert(CTGitPath &path,bool keep)\r
1063 {\r
1064         CString cmd, out;\r
1065         if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)\r
1066         {       //To init git repository, there are not HEAD, so we can use git reset command\r
1067                 cmd.Format(_T("git.exe rm --cache -- \"%s\""),path.GetGitPathString());\r
1068                 if(g_Git.Run(cmd,&out,CP_ACP))\r
1069                         return -1;\r
1070         }\r
1071         else if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED )\r
1072         {\r
1073                 cmd.Format(_T("git.exe mv \"%s\" \"%s\""),path.GetGitPathString(),path.GetGitOldPathString());\r
1074                 if(g_Git.Run(cmd,&out,CP_ACP))\r
1075                         return -1;\r
1076                 \r
1077                 cmd.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path.GetGitOldPathString());\r
1078                 if(g_Git.Run(cmd,&out,CP_ACP))\r
1079                         return -1;\r
1080         }\r
1081         else\r
1082         {\r
1083                 cmd.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path.GetGitPathString());\r
1084                 if(g_Git.Run(cmd,&out,CP_ACP))\r
1085                         return -1;\r
1086         }\r
1087         return 0;\r
1088 }\r
1089 \r
1090 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)\r
1091 {\r
1092         BYTE_VECTOR vector;\r
1093 \r
1094         CString cmd;\r
1095         if(path)\r
1096                 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());\r
1097         else\r
1098                 cmd=_T("git.exe ls-files -u -t -z");\r
1099 \r
1100         if(g_Git.Run(cmd,&vector))\r
1101         {\r
1102                 return -1;\r
1103         }\r
1104 \r
1105         list.ParserFromLsFile(vector);\r
1106 \r
1107         return 0;\r
1108 }