Debian Codegraph @

git/git.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : git.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 //////////////////////////////////////////////////////////////////////////////
27
28 #include "git.h"
29
30 #include "DiffSideBySidePanel.h"
31 #include "GitApplyPatchDlg.h"
32 #include "GitConsole.h"
33 #include "GitLocator.h"
34 #include "GitUserEmailDialog.h"
35 #include "bitmap_loader.h"
36 #include "clCommandProcessor.h"
37 #include "clDiffFrame.h"
38 #include "clEditorBar.h"
39 #include "clSFTPManager.hpp"
40 #include "clStatusBar.h"
41 #include "clTempFile.hpp"
42 #include "clWorkspaceManager.h"
43 #include "dirsaver.h"
44 #include "environmentconfig.h"
45 #include "event_notifier.h"
46 #include "file_logger.h"
47 #include "gitBlameDlg.h"
48 #include "gitCloneDlg.h"
49 #include "gitCommitDlg.h"
50 #include "gitCommitListDlg.h"
51 #include "gitDiffDlg.h"
52 #include "gitFileDiffDlg.h"
53 #include "gitSettingsDlg.h"
54 #include "gitentry.h"
55 #include "globals.h"
56 #include "overlaytool.h"
57 #include "project.h"
58 #include "workspace.h"
59
60 #include <stack>
61 #include <unordered_set>
62 #include <wx/artprov.h>
63 #include <wx/ffile.h>
64 #include <wx/file.h>
65 #include <wx/msgdlg.h>
66 #include <wx/sstream.h>
67 #include <wx/tokenzr.h>
68 #include <wx/utils.h>
69 #include <wx/wx.h>
70 #include <wx/xrc/xmlres.h>
71
72 #ifdef __WXGTK__
73 #include <sys/wait.h>
74 #endif
75
76 static GitPlugin* thePlugin = NULL;
77 namespace
78 {
79 wxString GetDirFromPath(const wxString& path)
80 {
81 wxString p = path;
82 p.Replace("\\", "/");
83 return p.BeforeLast('/');
84 }
85 } // namespace
86
87 #define GIT_MESSAGE_IF(cond, ...) \
88 if(cond) { \
89 m_console->AddText(wxString::Format(__VA_ARGS__)); \
90 }
91 #define GIT_MESSAGE(...) GIT_MESSAGE_IF(true, __VA_ARGS__)
92 #define GIT_MESSAGE1(...) GIT_MESSAGE_IF(m_configFlags& GitEntry::Git_Verbose_Log, __VA_ARGS__)
93
94 // Define the plugin entry point
95 CL_PLUGIN_API IPlugin* CreatePlugin(IManager* manager)
96 {
97 if(thePlugin == 0) {
98 thePlugin = new GitPlugin(manager);
99 }
100 return thePlugin;
101 }
102
103 CL_PLUGIN_API PluginInfo* GetPluginInfo()
104 {
105 static PluginInfo info;
106 info.SetAuthor(wxT("René Kraus"));
107 info.SetName(wxT("Git"));
108 info.SetDescription(_("Simple GIT plugin"));
109 info.SetVersion(wxT("v1.1.0"));
110 return &info;
111 }
112
113 CL_PLUGIN_API int GetPluginInterfaceVersion() { return PLUGIN_INTERFACE_VERSION; }
114
115 // Helper that returns the last-used selection for those git commands with several alternative options
116 wxString GetAnyDefaultCommand(const wxString& gitCommand)
117 {
118 clConfig conf("git.conf");
119 GitEntry data;
120 conf.ReadItem(&data);
121 GitCommandsEntries& ce = data.GetGitCommandsEntries(gitCommand);
122 return ce.GetDefaultCommand();
123 }
124
125 BEGIN_EVENT_TABLE(GitPlugin, wxEvtHandler)
126 EVT_TIMER(wxID_ANY, GitPlugin::OnProgressTimer)
127 END_EVENT_TABLE()
128
129 GitPlugin::GitPlugin(IManager* manager)
130 : IPlugin(manager)
131 , m_colourTrackedFile(wxT("DARK GREEN"))
132 , m_colourDiffFile(wxT("MAROON"))
133 , m_pathGITExecutable(wxT("git"))
134 , m_pathGITKExecutable(wxT("gitk"))
135 , m_bActionRequiresTreUpdate(false)
136 , m_process(NULL)
137 , m_eventHandler(NULL)
138 , m_pluginToolbar(NULL)
139 , m_pluginMenu(NULL)
140 , m_commitListDlg(NULL)
141 , m_commandProcessor(NULL)
142 , m_gitBlameDlg(NULL)
143 {
144 m_longName = _("GIT plugin");
145 m_shortName = wxT("Git");
146 m_eventHandler = m_mgr->GetTheApp();
147
148 Bind(wxEVT_ASYNC_PROCESS_OUTPUT, &GitPlugin::OnProcessOutput, this);
149 Bind(wxEVT_ASYNC_PROCESS_TERMINATED, &GitPlugin::OnProcessTerminated, this);
150
151 EventNotifier::Get()->Bind(wxEVT_CC_UPDATE_NAVBAR, &GitPlugin::OnUpdateNavBar, this);
152
153 EventNotifier::Get()->Bind(wxEVT_FILE_CREATED, &GitPlugin::OnFileCreated, this);
154 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_LOADED, &GitPlugin::OnWorkspaceLoaded, this);
155 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_CLOSED, &GitPlugin::OnWorkspaceClosed, this);
156 EventNotifier::Get()->Connect(wxEVT_FILE_SAVED, clCommandEventHandler(GitPlugin::OnFileSaved), NULL, this);
157 EventNotifier::Get()->Connect(wxEVT_PROJ_FILE_ADDED, clCommandEventHandler(GitPlugin::OnFilesAddedToProject), NULL,
158 this);
159 EventNotifier::Get()->Connect(wxEVT_PROJ_FILE_REMOVED, clCommandEventHandler(GitPlugin::OnFilesRemovedFromProject),
160 NULL, this);
161 EventNotifier::Get()->Connect(wxEVT_WORKSPACE_CONFIG_CHANGED,
162 wxCommandEventHandler(GitPlugin::OnWorkspaceConfigurationChanged), NULL, this);
163 EventNotifier::Get()->Connect(wxEVT_CL_FRAME_TITLE, clCommandEventHandler(GitPlugin::OnMainFrameTitle), NULL, this);
164 EventNotifier::Get()->Bind(wxEVT_CONTEXT_MENU_FILE, &GitPlugin::OnFileMenu, this);
165 EventNotifier::Get()->Bind(wxEVT_CONTEXT_MENU_FOLDER, &GitPlugin::OnFolderMenu, this);
166 EventNotifier::Get()->Bind(wxEVT_ACTIVE_PROJECT_CHANGED, &GitPlugin::OnActiveProjectChanged, this);
167 EventNotifier::Get()->Bind(wxEVT_CODELITE_MAINFRAME_GOT_FOCUS, &GitPlugin::OnAppActivated, this);
168 EventNotifier::Get()->Bind(wxEVT_FILES_MODIFIED_REPLACE_IN_FILES, &GitPlugin::OnReplaceInFiles, this);
169 EventNotifier::Get()->Bind(wxEVT_ACTIVE_EDITOR_CHANGED, &GitPlugin::OnEditorChanged, this);
170 EventNotifier::Get()->Bind(wxEVT_EDITOR_CLOSING, &GitPlugin::OnEditorClosed, this);
171 EventNotifier::Get()->Bind(wxEVT_FILE_MODIFIED_EXTERNALLY, &GitPlugin::OnFileModifiedExternally, this);
172
173 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderPullRebase, this, XRCID("git_pull_rebase_folder"));
174 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderCommit, this, XRCID("git_commit_folder"));
175 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderPush, this, XRCID("git_push_folder"));
176 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderStash, this, XRCID("git_stash_folder"));
177 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderStashPop, this, XRCID("git_stash_pop_folder"));
178 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderGitBash, this, XRCID("git_bash_folder"));
179
180 // Connect the file context menu event handlers
181 m_eventHandler->Connect(XRCID("git_add_file"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnFileAddSelected),
182 NULL, this);
183 m_eventHandler->Connect(XRCID("git_reset_file"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnFileResetSelected),
184 NULL, this);
185 m_eventHandler->Connect(XRCID("git_diff_file"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnFileDiffSelected),
186 NULL, this);
187 m_eventHandler->Connect(XRCID("git_commit_list_file"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnFileCommitListSelected),
188 NULL, this);
189 m_eventHandler->Bind(wxEVT_MENU, &GitPlugin::OnFileGitBlame, this, XRCID("git_blame_file"));
190
191 // Respond to our own events
192 EventNotifier::Get()->Bind(wxEVT_SOURCE_CONTROL_PUSHED, &GitPlugin::OnGitActionDone, this);
193 EventNotifier::Get()->Bind(wxEVT_SOURCE_CONTROL_COMMIT_LOCALLY, &GitPlugin::OnGitActionDone, this);
194 EventNotifier::Get()->Bind(wxEVT_SOURCE_CONTROL_PULLED, &GitPlugin::OnGitActionDone, this);
195 EventNotifier::Get()->Bind(wxEVT_SOURCE_CONTROL_RESET_FILES, &GitPlugin::OnGitActionDone, this);
196
197 // Add the console
198 auto images = m_mgr->GetOutputPaneNotebook()->GetBitmaps();
199 m_console = new GitConsole(m_mgr->GetOutputPaneNotebook(), this);
200 m_mgr->GetOutputPaneNotebook()->AddPage(m_console, _("Git"), false, images->Add("git"));
201 m_tabToggler.reset(new clTabTogglerHelper(_("Git"), m_console, "", NULL));
202 m_tabToggler->SetOutputTabBmp(images->Add("git"));
203
204 m_progressTimer.SetOwner(this);
205
206 m_remoteProcess.Bind(wxEVT_CODELITE_REMOTE_FINDPATH, &GitPlugin::OnFindPath, this);
207 m_remoteProcess.Bind(wxEVT_CODELITE_REMOTE_FINDPATH_DONE, &GitPlugin::OnFindPath, this);
208
209 clConfig conf("git.conf");
210 GitEntry data;
211 conf.ReadItem(&data);
212 m_configFlags = data.GetFlags();
213 }
214
215 GitPlugin::~GitPlugin() { wxDELETE(m_gitBlameDlg); }
216
217 void GitPlugin::CreateToolBar(clToolBarGeneric* toolbar) { wxUnusedVar(toolbar); }
218
219 void GitPlugin::CreatePluginMenu(wxMenu* pluginsMenu)
220 {
221 m_pluginMenu = new wxMenu();
222 wxMenuItem* item(NULL);
223
224 BitmapLoader* bmps = m_mgr->GetStdIcons();
225 item = new wxMenuItem(m_pluginMenu, XRCID("git_pull"), _("Pull remote changes"));
226 item->SetBitmap(bmps->LoadBitmap("pull"));
227 m_pluginMenu->Append(item);
228 m_pluginMenu->AppendSeparator();
229
230 item = new wxMenuItem(m_pluginMenu, XRCID("git_commit"), _("Commit changes"));
231 item->SetBitmap(bmps->LoadBitmap("git-commit"));
232 m_pluginMenu->Append(item);
233 item = new wxMenuItem(m_pluginMenu, XRCID("git_push"), _("Push changes"));
234 item->SetBitmap(bmps->LoadBitmap("up"));
235 m_pluginMenu->Append(item);
236 m_pluginMenu->AppendSeparator();
237
238 item = new wxMenuItem(m_pluginMenu, XRCID("git_reset_repository"), _("Reset current repository"));
239 item->SetBitmap(bmps->LoadBitmap("clean"));
240 m_pluginMenu->Append(item);
241 m_pluginMenu->AppendSeparator();
242 item = new wxMenuItem(m_pluginMenu, XRCID("git_create_branch"), _("Create local branch"));
243 item->SetBitmap(bmps->LoadBitmap("plus"));
244 m_pluginMenu->Append(item);
245 item = new wxMenuItem(m_pluginMenu, XRCID("git_switch_branch"), _("Switch local branch"), _("Switch local branch"),
246 wxITEM_NORMAL);
247 item->SetBitmap(bmps->LoadBitmap("split"));
248 m_pluginMenu->Append(item);
249
250 item = new wxMenuItem(m_pluginMenu, XRCID("git_switch_to_remote_branch"), _("Switch remote branch"),
251 _("Switch remote branch"), wxITEM_NORMAL);
252 m_pluginMenu->Append(item);
253
254 m_pluginMenu->AppendSeparator();
255 item = new wxMenuItem(m_pluginMenu, XRCID("git_browse_commit_list"), _("List commits"), _("List commits"),
256 wxITEM_NORMAL);
257 item->SetBitmap(bmps->LoadBitmap("tasks"));
258 m_pluginMenu->Append(item);
259 item =
260 new wxMenuItem(m_pluginMenu, XRCID("git_commit_diff"), _("Show current diffs"), _("Show diffs"), wxITEM_NORMAL);
261 item->SetBitmap(bmps->LoadBitmap("diff"));
262 m_pluginMenu->Append(item);
263 item = new wxMenuItem(m_pluginMenu, XRCID("git_blame"), _("Show git blame"), _("Show blame"), wxITEM_NORMAL);
264 item->SetBitmap(bmps->LoadBitmap("finger"));
265 m_pluginMenu->Append(item);
266 item = new wxMenuItem(m_pluginMenu, XRCID("git_apply_patch"), _("Apply Patch"), _("Apply Patch"), wxITEM_NORMAL);
267 item->SetBitmap(bmps->LoadBitmap("patch"));
268 m_pluginMenu->Append(item);
269
270 m_pluginMenu->AppendSeparator();
271 item = new wxMenuItem(m_pluginMenu, XRCID("git_list_modified"), _("List modified files"), _("List modified files"),
272 wxITEM_NORMAL);
273 item->SetBitmap(bmps->LoadBitmap("marker"));
274 m_pluginMenu->Append(item);
275
276 item = new wxMenuItem(m_pluginMenu, XRCID("git_start_gitk"), _("Start gitk"), _("Start gitk"), wxITEM_NORMAL);
277 item->SetBitmap(bmps->LoadBitmap("debugger_start"));
278 m_pluginMenu->Append(item);
279
280 m_pluginMenu->AppendSeparator();
281 item = new wxMenuItem(m_pluginMenu, XRCID("git_garbage_collection"), _("Clean git database (garbage collection)"));
282 item->SetBitmap(bmps->LoadBitmap("clean"));
283 m_pluginMenu->Append(item);
284
285 item = new wxMenuItem(m_pluginMenu, XRCID("git_refresh"), _("Refresh git file list"), _("Refresh file lists"),
286 wxITEM_NORMAL);
287 item->SetBitmap(bmps->LoadBitmap("debugger_restart"));
288 m_pluginMenu->Append(item);
289 m_pluginMenu->AppendSeparator();
290 item = new wxMenuItem(m_pluginMenu, XRCID("git_settings"), _("GIT plugin settings"), _("GIT plugin settings"),
291 wxITEM_NORMAL);
292 item->SetBitmap(bmps->LoadBitmap("cog"));
293 m_pluginMenu->Append(item);
294 item = new wxMenuItem(m_pluginMenu, XRCID("git_clone"), _("Clone a git repository"), _("Clone a git repository"),
295 wxITEM_NORMAL);
296 item->SetBitmap(bmps->LoadBitmap("copy"));
297 m_pluginMenu->Append(item);
298
299 item = new wxMenuItem(pluginsMenu, wxID_ANY, wxT("Git"));
300 item->SetSubMenu(m_pluginMenu);
301 item->SetBitmap(bmps->LoadBitmap("git"));
302 pluginsMenu->Append(item);
303
304 m_eventHandler->Bind(wxEVT_MENU, &GitPlugin::OnOpenMSYSGit, this, XRCID("git_msysgit"));
305 m_eventHandler->Connect(XRCID("git_settings"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnSettings), NULL,
306 this);
307 m_eventHandler->Connect(XRCID("git_switch_branch"), wxEVT_MENU,
308 wxCommandEventHandler(GitPlugin::OnSwitchLocalBranch), NULL, this);
309 m_eventHandler->Connect(XRCID("git_switch_to_remote_branch"), wxEVT_MENU,
310 wxCommandEventHandler(GitPlugin::OnSwitchRemoteBranch), NULL, this);
311 m_eventHandler->Connect(XRCID("git_create_branch"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnCreateBranch),
312 NULL, this);
313 m_eventHandler->Connect(XRCID("git_pull"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnPull), NULL, this);
314 m_eventHandler->Connect(XRCID("git_clone"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnClone), NULL, this);
315 m_eventHandler->Connect(XRCID("git_commit"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnCommit), NULL, this);
316 m_eventHandler->Connect(XRCID("git_browse_commit_list"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnCommitList),
317 NULL, this);
318 m_eventHandler->Connect(XRCID("git_commit_diff"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnShowDiffs), NULL,
319 this);
320 m_eventHandler->Connect(XRCID("git_blame"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnGitBlame), NULL, this);
321 m_eventHandler->Connect(XRCID("git_apply_patch"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnApplyPatch), NULL,
322 this);
323 m_eventHandler->Connect(XRCID("git_push"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnPush), NULL, this);
324 m_eventHandler->Connect(XRCID("git_rebase"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnRebase), NULL, this);
325 m_eventHandler->Connect(XRCID("git_reset_repository"), wxEVT_MENU,
326 wxCommandEventHandler(GitPlugin::OnResetRepository), NULL, this);
327 m_eventHandler->Connect(XRCID("git_start_gitk"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnStartGitk), NULL,
328 this);
329 m_eventHandler->Connect(XRCID("git_list_modified"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnListModified),
330 NULL, this);
331 m_eventHandler->Connect(XRCID("git_refresh"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnRefresh), NULL, this);
332 m_eventHandler->Connect(XRCID("git_garbage_collection"), wxEVT_MENU,
333 wxCommandEventHandler(GitPlugin::OnGarbageColletion), NULL, this);
334 m_eventHandler->Connect(XRCID("git_switch_branch"), wxEVT_UPDATE_UI,
335 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
336 m_eventHandler->Connect(XRCID("git_switch_to_remote_branch"), wxEVT_UPDATE_UI,
337 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
338 m_eventHandler->Connect(XRCID("git_create_branch"), wxEVT_UPDATE_UI,
339 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
340 m_eventHandler->Connect(XRCID("git_pull"), wxEVT_UPDATE_UI,
341 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
342 m_eventHandler->Connect(XRCID("git_commit"), wxEVT_UPDATE_UI,
343 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
344 m_eventHandler->Connect(XRCID("git_browse_commit_list"), wxEVT_UPDATE_UI,
345 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
346 m_eventHandler->Connect(XRCID("git_commit_diff"), wxEVT_UPDATE_UI,
347 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
348 m_eventHandler->Connect(XRCID("git_apply_patch"), wxEVT_UPDATE_UI,
349 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
350 m_eventHandler->Connect(XRCID("git_push"), wxEVT_UPDATE_UI,
351 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
352 m_eventHandler->Connect(XRCID("git_rebase"), wxEVT_UPDATE_UI,
353 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
354 m_eventHandler->Connect(XRCID("git_reset_repository"), wxEVT_UPDATE_UI,
355 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
356 m_eventHandler->Connect(XRCID("git_start_gitk"), wxEVT_UPDATE_UI, wxUpdateUIEventHandler(GitPlugin::OnStartGitkUI),
357 NULL, this);
358 m_eventHandler->Connect(XRCID("git_list_modified"), wxEVT_UPDATE_UI,
359 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
360 m_eventHandler->Connect(XRCID("git_refresh"), wxEVT_UPDATE_UI,
361 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
362 m_eventHandler->Connect(XRCID("git_garbage_collection"), wxEVT_UPDATE_UI,
363 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
364 m_eventHandler->Connect(XRCID("git_blame"), wxEVT_UPDATE_UI,
365 wxUpdateUIEventHandler(GitPlugin::OnEnableGitRepoExists), NULL, this);
366 }
367
368 void GitPlugin::HookPopupMenu(wxMenu* menu, MenuType type)
369 {
370 wxUnusedVar(menu);
371 wxUnusedVar(type);
372 }
373
374 void GitPlugin::UnPlug()
375 {
376 ClearCodeLiteRemoteInfo();
377 // before this plugin is un-plugged we must remove the tab we added
378 for(size_t i = 0; i < m_mgr->GetOutputPaneNotebook()->GetPageCount(); i++) {
379 if(m_console == m_mgr->GetOutputPaneNotebook()->GetPage(i)) {
380 m_mgr->GetOutputPaneNotebook()->RemovePage(i);
381 m_console->Destroy();
382 break;
383 }
384 }
385
386 EventNotifier::Get()->Unbind(wxEVT_FILE_CREATED, &GitPlugin::OnFileCreated, this);
387 EventNotifier::Get()->Unbind(wxEVT_ACTIVE_EDITOR_CHANGED, &GitPlugin::OnEditorChanged, this);
388 EventNotifier::Get()->Unbind(wxEVT_EDITOR_CLOSING, &GitPlugin::OnEditorClosed, this);
389 EventNotifier::Get()->Unbind(wxEVT_FILE_MODIFIED_EXTERNALLY, &GitPlugin::OnFileModifiedExternally, this);
390 EventNotifier::Get()->Unbind(wxEVT_CC_UPDATE_NAVBAR, &GitPlugin::OnUpdateNavBar, this);
391
392 EventNotifier::Get()->Unbind(wxEVT_SOURCE_CONTROL_PUSHED, &GitPlugin::OnGitActionDone, this);
393 EventNotifier::Get()->Unbind(wxEVT_SOURCE_CONTROL_COMMIT_LOCALLY, &GitPlugin::OnGitActionDone, this);
394 EventNotifier::Get()->Unbind(wxEVT_SOURCE_CONTROL_PULLED, &GitPlugin::OnGitActionDone, this);
395 EventNotifier::Get()->Unbind(wxEVT_SOURCE_CONTROL_RESET_FILES, &GitPlugin::OnGitActionDone, this);
396
397 /*MENU*/
398 m_eventHandler->Unbind(wxEVT_MENU, &GitPlugin::OnOpenMSYSGit, this, XRCID("git_msysgit"));
399 m_eventHandler->Disconnect(XRCID("git_settings"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnSettings), NULL,
400 this);
401 m_eventHandler->Disconnect(XRCID("git_switch_branch"), wxEVT_MENU,
402 wxCommandEventHandler(GitPlugin::OnSwitchLocalBranch), NULL, this);
403 m_eventHandler->Disconnect(XRCID("git_switch_to_remote_branch"), wxEVT_MENU,
404 wxCommandEventHandler(GitPlugin::OnSwitchRemoteBranch), NULL, this);
405 m_eventHandler->Disconnect(XRCID("git_create_branch"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnCreateBranch),
406 NULL, this);
407 m_eventHandler->Disconnect(XRCID("git_pull"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnPull), NULL, this);
408 m_eventHandler->Disconnect(XRCID("git_commit"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnCommit), NULL, this);
409 m_eventHandler->Disconnect(XRCID("git_browse_commit_list"), wxEVT_MENU,
410 wxCommandEventHandler(GitPlugin::OnCommitList), NULL, this);
411 m_eventHandler->Disconnect(XRCID("git_commit_diff"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnShowDiffs),
412 NULL, this);
413 m_eventHandler->Disconnect(XRCID("git_blame"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnGitBlame), NULL,
414 this);
415 m_eventHandler->Disconnect(XRCID("git_apply_patch"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnApplyPatch),
416 NULL, this);
417 m_eventHandler->Disconnect(XRCID("git_push"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnPush), NULL, this);
418 m_eventHandler->Disconnect(XRCID("git_reset_repository"), wxEVT_MENU,
419 wxCommandEventHandler(GitPlugin::OnResetRepository), NULL, this);
420 m_eventHandler->Disconnect(XRCID("git_start_gitk"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnStartGitk), NULL,
421 this);
422 m_eventHandler->Disconnect(XRCID("git_list_modified"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnListModified),
423 NULL, this);
424 m_eventHandler->Disconnect(XRCID("git_refresh"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnRefresh), NULL,
425 this);
426 m_eventHandler->Disconnect(XRCID("git_garbage_collection"), wxEVT_MENU,
427 wxCommandEventHandler(GitPlugin::OnGarbageColletion), NULL, this);
428 m_eventHandler->Unbind(wxEVT_MENU, &GitPlugin::OnFileGitBlame, this, XRCID("git_blame_file"));
429
430 /*SYSTEM*/
431 EventNotifier::Get()->Disconnect(wxEVT_FILE_SAVED, clCommandEventHandler(GitPlugin::OnFileSaved), NULL, this);
432 EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_LOADED, &GitPlugin::OnWorkspaceLoaded, this);
433 EventNotifier::Get()->Unbind(wxEVT_PROJ_FILE_ADDED, &GitPlugin::OnFilesAddedToProject, this);
434 EventNotifier::Get()->Disconnect(wxEVT_WORKSPACE_CONFIG_CHANGED,
435 wxCommandEventHandler(GitPlugin::OnWorkspaceConfigurationChanged), NULL, this);
436 EventNotifier::Get()->Unbind(wxEVT_ACTIVE_PROJECT_CHANGED, &GitPlugin::OnActiveProjectChanged, this);
437 EventNotifier::Get()->Unbind(wxEVT_CODELITE_MAINFRAME_GOT_FOCUS, &GitPlugin::OnAppActivated, this);
438 EventNotifier::Get()->Unbind(wxEVT_FILES_MODIFIED_REPLACE_IN_FILES, &GitPlugin::OnReplaceInFiles, this);
439
440 /*Context Menu*/
441 m_eventHandler->Disconnect(XRCID("git_add_file"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnFileAddSelected),
442 NULL, this);
443 // m_eventHandler->Disconnect( ID_DELETE_FILE, wxEVT_MENU, wxCommandEventHandler(
444 // GitPlugin::OnFileDeleteSelected), NULL, this );
445 m_eventHandler->Disconnect(XRCID("git_reset_file"), wxEVT_MENU,
446 wxCommandEventHandler(GitPlugin::OnFileResetSelected), NULL, this);
447 m_eventHandler->Disconnect(XRCID("git_diff_file"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnFileDiffSelected),
448 NULL, this);
449 m_eventHandler->Disconnect(XRCID("git_commit_list_file"), wxEVT_MENU, wxCommandEventHandler(GitPlugin::OnFileCommitListSelected),
450 NULL, this);
451
452 EventNotifier::Get()->Unbind(wxEVT_CONTEXT_MENU_FILE, &GitPlugin::OnFileMenu, this);
453 EventNotifier::Get()->Unbind(wxEVT_CONTEXT_MENU_FOLDER, &GitPlugin::OnFolderMenu, this);
454 wxTheApp->Unbind(wxEVT_MENU, &GitPlugin::OnFolderPullRebase, this, XRCID("git_pull_rebase_folder"));
455 wxTheApp->Unbind(wxEVT_MENU, &GitPlugin::OnFolderCommit, this, XRCID("git_commit_folder"));
456 wxTheApp->Unbind(wxEVT_MENU, &GitPlugin::OnFolderPush, this, XRCID("git_push_folder"));
457 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderStash, this, XRCID("git_stash_folder"));
458 wxTheApp->Bind(wxEVT_MENU, &GitPlugin::OnFolderStashPop, this, XRCID("git_stash_pop_folder"));
459 Unbind(wxEVT_ASYNC_PROCESS_OUTPUT, &GitPlugin::OnProcessOutput, this);
460 Unbind(wxEVT_ASYNC_PROCESS_TERMINATED, &GitPlugin::OnProcessTerminated, this);
461
462 m_remoteProcess.Unbind(wxEVT_CODELITE_REMOTE_FINDPATH, &GitPlugin::OnFindPath, this);
463 m_remoteProcess.Unbind(wxEVT_CODELITE_REMOTE_FINDPATH_DONE, &GitPlugin::OnFindPath, this);
464
465 m_tabToggler.reset(NULL);
466 }
467
468 void GitPlugin::OnSetGitRepoPath(wxCommandEvent& e)
469 {
470 wxUnusedVar(e);
471 DoSetRepoPath();
472 }
473
474 void GitPlugin::DoSetRepoPath(const wxString& repo_path)
475 {
476 if(repo_path.empty()) {
477 if(!m_userEnteredRepositoryDirectory.empty()) {
478 m_repositoryDirectory = m_userEnteredRepositoryDirectory;
479 } else {
480 m_repositoryDirectory = FindRepositoryRoot(GetDirFromPath(m_workspace_file));
481 }
482 } else {
483 m_repositoryDirectory = repo_path;
484 }
485
486 if(IsGitEnabled()) {
487 wxBitmap bmp = clGetManager()->GetStdIcons()->LoadBitmap("git");
488 clGetManager()->GetStatusBar()->SetSourceControlBitmap(bmp, "Git", _("Using git\nClick to open the git view"));
489 }
490 AddDefaultActions();
491 ProcessGitActionQueue();
492 }
493
494 void GitPlugin::OnSettings(wxCommandEvent& e)
495 {
496 wxString projectNameHash;
497 if(!m_isRemoteWorkspace) {
498 wxString workspaceName = m_mgr->GetWorkspace()->GetWorkspaceFileName().GetName();
499 wxString projectName = m_mgr->GetWorkspace()->GetActiveProjectName();
500 if(!workspaceName.empty() && !projectName.empty()) {
501 projectNameHash << workspaceName << '-' << projectName;
502 }
503 }
504
505 GitSettingsDlg dlg(EventNotifier::Get()->TopFrame(), m_repositoryDirectory, m_userEnteredRepositoryDirectory,
506 projectNameHash);
507 int retValue = dlg.ShowModal();
508
509 if(retValue == wxID_OK || retValue == wxID_REFRESH) {
510 if(retValue == wxID_REFRESH) {
511 // An unusual git repo path was entered (or a previously-entered one removed)
512 m_userEnteredRepositoryDirectory = dlg.GetNewGitRepoPath();
513 m_repositoryDirectory = m_userEnteredRepositoryDirectory;
514 DoSetRepoPath(m_repositoryDirectory);
515 CallAfter(&GitPlugin::DoRefreshView, false);
516 }
517 // update the paths
518 clConfig conf("git.conf");
519 GitEntry data;
520 conf.ReadItem(&data);
521 m_configFlags = data.GetFlags();
522
523 m_pathGITExecutable = data.GetGITExecutablePath();
524 m_pathGITKExecutable = data.GetGITKExecutablePath();
525
526 GIT_MESSAGE("git executable is now set to: %s", m_pathGITExecutable.c_str());
527 GIT_MESSAGE("gitk executable is now set to: %s", m_pathGITKExecutable.c_str());
528
529 // clear any status bar information
530 clGetManager()->GetNavigationBar()->ClearLabel();
531 AddDefaultActions();
532 ProcessGitActionQueue();
533
534 DoLoadBlameInfo(true);
535 }
536 }
537
538 void GitPlugin::OnFileAddSelected(wxCommandEvent& e)
539 {
540 wxUnusedVar(e);
541
542 wxArrayString files;
543 files.swap(m_filesSelected);
544 if(files.IsEmpty())
545 return;
546
547 // Make the git console visible
548 m_mgr->ShowOutputPane("Git");
549
550 wxString workingDir = wxFileName(files.Item(0)).GetPath(wxPATH_UNIX);
551 if(!GetRepositoryPath().empty()) {
552 workingDir = GetRepositoryPath();
553 }
554
555 // Pepare the command:
556 // git add --no-pager
557 wxString cmd = "add";
558 for(size_t i = 0; i < files.size(); ++i) {
559 wxFileName fn(files.Item(i));
560 fn.MakeRelativeTo(workingDir);
561 wxString filename = fn.GetFullPath(wxPATH_UNIX);
562 ::WrapWithQuotes(filename);
563 cmd << " " << filename;
564 }
565
566 wxString commandOutput;
567 DoExecuteCommandSync(cmd, &commandOutput, workingDir);
568 GetConsole()->AddText(commandOutput);
569 RefreshFileListView();
570 }
571
572 void GitPlugin::OnFileDeleteSelected(wxCommandEvent& e) { RefreshFileListView(); }
573
574 void GitPlugin::OnFileDiffSelected(wxCommandEvent& e)
575 {
576 wxUnusedVar(e);
577
578 wxArrayString files;
579 files.swap(m_filesSelected);
580 if(files.IsEmpty())
581 return;
582
583 wxString workingDir = wxFileName(files.Item(0)).GetPath(wxPATH_UNIX);
584 if(!GetRepositoryPath().empty()) {
585 workingDir = GetRepositoryPath();
586 }
587
588 // Make the git console visible
589 m_mgr->ShowOutputPane("Git");
590
591 for(const wxString& filename : files) {
592 // Pepare the command:
593 // git add --no-pager
594 wxString cmd = "show HEAD:";
595
596 wxFileName fn(filename);
597 fn.MakeRelativeTo(workingDir);
598 wxString filenameEscaped = fn.GetFullPath(wxPATH_UNIX);
599
600 ::WrapWithQuotes(filenameEscaped);
601 cmd << filenameEscaped;
602
603 // We need to run this command per file
604 wxString commandOutput;
605 DoExecuteCommandSync(cmd, &commandOutput);
606 if(!commandOutput.IsEmpty()) {
607 DoShowDiffViewer(commandOutput, filename);
608 }
609 }
610 }
611
612 void GitPlugin::OnFileResetSelected(wxCommandEvent& e)
613 {
614 wxUnusedVar(e);
615
616 wxArrayString files;
617 files.swap(m_filesSelected);
618 if(files.IsEmpty())
619 return;
620
621 // Make the git console visible
622 m_mgr->ShowOutputPane("Git");
623
624 wxString workingDir = wxFileName(files.Item(0)).GetPath(wxPATH_UNIX);
625 if(!GetRepositoryPath().empty()) {
626 workingDir = GetRepositoryPath();
627 }
628
629 // Pepare the command:
630 // git add --no-pager
631 wxString cmd = "checkout";
632 for(size_t i = 0; i < files.size(); ++i) {
633 wxFileName fn(files.Item(i));
634 fn.MakeRelativeTo(workingDir);
635 wxString filename = fn.GetFullPath(wxPATH_UNIX);
636 ::WrapWithQuotes(filename);
637 cmd << " " << filename;
638 }
639
640 wxString commandOutput;
641 DoExecuteCommandSync(cmd, &commandOutput, workingDir);
642 GetConsole()->AddText(commandOutput);
643
644 // Reload externally modified files
645 EventNotifier::Get()->PostReloadExternallyModifiedEvent();
646 RefreshFileListView();
647 }
648
649 void GitPlugin::OnSwitchLocalBranch(wxCommandEvent& e)
650 {
651 wxUnusedVar(e);
652 if(!m_modifiedFiles.empty()) {
653 wxMessageBox(_("Modified files found! Commit them first before switching branches..."), wxT("CodeLite"),
654 wxICON_ERROR | wxOK, EventNotifier::Get()->TopFrame());
655 return;
656 }
657
658 if(m_localBranchList.GetCount() == 0) {
659 wxMessageBox(_("No other local branches found."), wxT("CodeLite"), wxICON_INFORMATION | wxOK,
660 EventNotifier::Get()->TopFrame());
661 return;
662 }
663
664 wxString message = _("Select branch (current is ");
665 message << m_currentBranch << wxT(")");
666
667 wxString selection =
668 wxGetSingleChoice(message, _("Switch branch"), m_localBranchList, EventNotifier::Get()->TopFrame());
669
670 if(selection.IsEmpty())
671 return;
672
673 gitAction ganew(gitBranchSwitch, selection);
674 m_gitActionQueue.push_back(ganew);
675 AddDefaultActions();
676 m_mgr->SaveAll();
677 ProcessGitActionQueue();
678 }
679
680 void GitPlugin::OnSwitchRemoteBranch(wxCommandEvent& e)
681 {
682 wxUnusedVar(e);
683 if(!m_modifiedFiles.empty()) {
684 wxMessageBox(_("Modified files found! Commit them first before switching branches..."), wxT("CodeLite"),
685 wxICON_ERROR | wxOK, EventNotifier::Get()->TopFrame());
686 return;
687 }
688 if(m_remoteBranchList.GetCount() == 0) {
689 wxMessageBox(_("No remote branches found."), wxT("CodeLite"), wxICON_INFORMATION | wxOK,
690 EventNotifier::Get()->TopFrame());
691 return;
692 }
693 wxString message = _("Select remote branch (current is ");
694 message << m_currentBranch << wxT(")");
695
696 wxString selection =
697 wxGetSingleChoice(message, _("Switch to remote branch"), m_remoteBranchList, EventNotifier::Get()->TopFrame());
698
699 if(selection.IsEmpty())
700 return;
701
702 wxString localBranch = selection;
703 localBranch.Replace(wxT("origin/"), wxT(""));
704 localBranch = wxGetTextFromUser(_("Specify the name for the local branch"), _("Branch name"), localBranch,
705 EventNotifier::Get()->TopFrame());
706 if(localBranch.IsEmpty())
707 return;
708
709 gitAction ganew(gitBranchSwitchRemote, localBranch + wxT(" ") + selection);
710 m_gitActionQueue.push_back(ganew);
711
712 AddDefaultActions();
713 m_mgr->SaveAll();
714 ProcessGitActionQueue();
715 }
716
717 void GitPlugin::OnCreateBranch(wxCommandEvent& e)
718 {
719 wxUnusedVar(e);
720 wxString newBranch = wxGetTextFromUser(_("Specify the name of the new branch"), _("Branch name"), wxT(""),
721 EventNotifier::Get()->TopFrame());
722 if(newBranch.IsEmpty())
723 return;
724
725 gitAction ga(gitBranchCreate, newBranch);
726 m_gitActionQueue.push_back(ga);
727
728 if(wxMessageBox(_("Switch to new branch once it is created?"), _("Switch to new branch"), wxYES_NO,
729 EventNotifier::Get()->TopFrame()) == wxYES) {
730 ga.action = gitBranchSwitch;
731 ga.arguments = newBranch;
732 m_gitActionQueue.push_back(ga);
733 AddDefaultActions();
734 m_mgr->SaveAll();
735 }
736
737 ProcessGitActionQueue();
738 }
739
740 void GitPlugin::OnCommit(wxCommandEvent& e)
741 {
742 wxUnusedVar(e);
743 gitAction ga(gitDiffRepoCommit, wxT(""));
744 m_gitActionQueue.push_back(ga);
745 m_mgr->ShowOutputPane("Git");
746 ProcessGitActionQueue();
747 }
748
749 void GitPlugin::OnCommitList(wxCommandEvent& e)
750 {
751 wxUnusedVar(e);
752 gitAction ga(gitCommitList, wxT(""));
753 m_gitActionQueue.push_back(ga);
754 ProcessGitActionQueue();
755 }
756
757 void GitPlugin::OnShowDiffs(wxCommandEvent& e)
758 {
759 wxUnusedVar(e);
760 GitDiffDlg dlg(EventNotifier::Get()->TopFrame(), m_repositoryDirectory, this);
761 dlg.ShowModal();
762 }
763
764 void GitPlugin::OnApplyPatch(wxCommandEvent& e)
765 {
766 wxUnusedVar(e);
767 GitApplyPatchDlg dlg(EventNotifier::Get()->TopFrame());
768 if(dlg.ShowModal() == wxID_OK) {
769 ApplyPatch(dlg.GetPatchFile(), dlg.GetExtraFlags());
770 }
771 }
772
773 void GitPlugin::OnPush(wxCommandEvent& e)
774 {
775 wxUnusedVar(e);
776 if(m_remotes.GetCount() == 0) {
777 wxMessageBox(_("No remotes found, can't push!"), wxT("CodeLite"), wxICON_ERROR | wxOK,
778 EventNotifier::Get()->TopFrame());
779 return;
780 }
781
782 wxStandardID res = ::PromptForYesNoDialogWithCheckbox(_("Push all local commits?"), "GitPromptBeforePush");
783 if(res == wxID_YES) {
784 // wxString remote = m_remotes[0];
785 // if(m_remotes.GetCount() > 1) {
786 // remote = wxGetSingleChoice(_("Select remote to push to."), _("Select remote"), m_remotes,
787 // EventNotifier::Get()->TopFrame()); if(remote.IsEmpty()) {
788 // return;
789 // }
790 // }
791 gitAction ga(gitPush, /*remote + wxT(" ") + m_currentBranch*/ wxEmptyString);
792 m_gitActionQueue.push_back(ga);
793 m_mgr->ShowOutputPane("Git");
794 ProcessGitActionQueue();
795 }
796 }
797
798 void GitPlugin::OnPull(wxCommandEvent& e)
799 {
800 wxString argumentString = e.GetString(); // This might be user-specified e.g. pull --rebase
801 if(argumentString.empty()) {
802 argumentString = GetAnyDefaultCommand("git_pull");
803 }
804 argumentString.Replace("pull", "");
805 argumentString.Trim(false);
806
807 wxStandardID res =
808 ::PromptForYesNoDialogWithCheckbox(_("Save all changes and pull remote changes?"), "GitPullRemoteChanges");
809 if(res == wxID_YES) {
810 m_mgr->SaveAll();
811 if(m_console->IsDirty()) {
812 gitAction ga(gitStash, wxT(""));
813 m_gitActionQueue.push_back(ga);
814 }
815 {
816 gitAction ga(gitPull, argumentString);
817 m_gitActionQueue.push_back(ga);
818 }
819 if(m_console->IsDirty()) {
820 gitAction ga(gitStashPop, wxT(""));
821 m_gitActionQueue.push_back(ga);
822 }
823 AddDefaultActions();
824 m_mgr->ShowOutputPane("Git");
825 ProcessGitActionQueue();
826 }
827 }
828
829 void GitPlugin::OnResetRepository(wxCommandEvent& e)
830 {
831 wxUnusedVar(e);
832 if(wxMessageBox(_("Are you sure that you want to discard all local changes?"), _("Reset repository"),
833 wxYES_NO | wxCANCEL | wxCANCEL_DEFAULT | wxICON_WARNING,
834 EventNotifier::Get()->TopFrame()) == wxYES) {
835 gitAction ga(gitResetRepo, wxT(""));
836 m_gitActionQueue.push_back(ga);
837 AddDefaultActions();
838 ProcessGitActionQueue();
839 }
840 }
841
842 void GitPlugin::OnStartGitk(wxCommandEvent& e)
843 {
844 wxUnusedVar(e);
845 DirSaver ds;
846
847 ::wxSetWorkingDirectory(m_repositoryDirectory);
848 ::wxExecute(m_pathGITKExecutable);
849 }
850
851 void GitPlugin::OnListModified(wxCommandEvent& e)
852 {
853 wxUnusedVar(e);
854 wxArrayString choices;
855 std::map<wxString, wxTreeItemId>::const_iterator it;
856
857 // First get a map of the filepaths/treeitemids of modified files
858 std::map<wxString, wxTreeItemId> modifiedIDs;
859 CreateFilesTreeIDsMap(modifiedIDs, true);
860
861 for(it = modifiedIDs.begin(); it != modifiedIDs.end(); ++it) {
862 if(it->second.IsOk())
863 choices.Add(it->first);
864 }
865
866 if(choices.GetCount() == 0)
867 return;
868
869 wxString choice =
870 wxGetSingleChoice(_("Jump to modified file"), _("Modified files"), choices, EventNotifier::Get()->TopFrame());
871 if(!choice.IsEmpty()) {
872 wxTreeItemId id = modifiedIDs[choice];
873 if(id.IsOk()) {
874 m_mgr->GetWorkspaceTree()->EnsureVisible(id);
875 m_mgr->GetWorkspaceTree()->SelectItem(id);
876 }
877 }
878 }
879
880 void GitPlugin::OnGitBlame(wxCommandEvent& e)
881 {
882 wxUnusedVar(e);
883
884 wxString filepath = GetEditorRelativeFilepath();
885 if(!filepath.empty()) {
886 DoGitBlame(filepath);
887 }
888 }
889
890 wxString GitPlugin::GetEditorRelativeFilepath() const // Called by OnGitBlame or the git blame dialog
891 {
892 IEditor* current = m_mgr->GetActiveEditor();
893 if(!current || m_repositoryDirectory.empty()) {
894 return "";
895 }
896
897 // We need to be symlink-aware here on Linux, so use CLRealPath
898 wxString realfilepath = CLRealPath(current->GetFileName().GetFullPath());
899 wxFileName fn(realfilepath);
900 fn.MakeRelativeTo(CLRealPath(m_repositoryDirectory));
901
902 return fn.GetFullPath();
903 }
904
905 void GitPlugin::DoGitBlame(const wxString& args) // Called by OnGitBlame or the git blame dialog
906 {
907 gitAction ga(gitBlame, args);
908 m_gitActionQueue.push_back(ga);
909 ProcessGitActionQueue();
910 }
911
912 void GitPlugin::OnGitBlameRevList(const wxString& arg, const wxString& filepath,
913 const wxString& commit) // Called by the git blame dialog
914 {
915 wxString cmt(commit);
916 if(cmt.empty()) {
917 cmt = "HEAD";
918 }
919 wxString args = arg + ' ' + cmt + " -- " + filepath;
920
921 gitAction ga(gitRevlist, args);
922 m_gitActionQueue.push_back(ga);
923 ProcessGitActionQueue();
924 }
925
926 void GitPlugin::OnRefresh(wxCommandEvent& e)
927 {
928 wxUnusedVar(e);
929 DoRefreshView(true);
930 }
931
932 void GitPlugin::OnGarbageColletion(wxCommandEvent& e)
933 {
934 wxUnusedVar(e);
935 gitAction ga(gitGarbageCollection, wxT(""));
936 m_gitActionQueue.push_back(ga);
937 ProcessGitActionQueue();
938 }
939
940 void GitPlugin::OnFileModifiedExternally(clFileSystemEvent& e)
941 {
942 e.Skip();
943 DoAnyFileModified();
944 }
945
946 void GitPlugin::DoAnyFileModified()
947 {
948 DoLoadBlameInfo(true);
949 gitAction ga(gitListModified, wxT(""));
950 m_gitActionQueue.push_back(ga);
951 ProcessGitActionQueue();
952 RefreshFileListView();
953 }
954 void GitPlugin::OnFileSaved(clCommandEvent& e)
955 {
956 e.Skip();
957 DoAnyFileModified();
958 }
959
960 void GitPlugin::OnFilesAddedToProject(clCommandEvent& e)
961 {
962 e.Skip();
963
964 const wxArrayString& files = e.GetStrings();
965 if(!files.IsEmpty() && !m_repositoryDirectory.IsEmpty()) {
966 GIT_MESSAGE(wxT("Files added to project, updating file list"));
967 DoAddFiles(files);
968 RefreshFileListView();
969 }
970 }
971
972 void GitPlugin::OnFilesRemovedFromProject(clCommandEvent& e)
973 {
974 e.Skip();
975 RefreshFileListView(); // in git world, deleting a file is enough
976 }
977
978 void GitPlugin::ClearCodeLiteRemoteInfo()
979 {
980 m_isRemoteWorkspace = false;
981 m_remoteWorkspaceAccount.clear();
982 m_remoteProcess.Stop();
983 m_codeliteRemoteScriptPath.clear();
984 }
985
986 void GitPlugin::StartCodeLiteRemote()
987 {
988 if(m_isRemoteWorkspace && !m_remoteWorkspaceAccount.empty()) {
989 wxString workspace_dir = GetDirFromPath(m_workspace_file);
990 wxString codelite_remote_script = workspace_dir + "/.codelite/codelite-remote";
991 m_remoteProcess.StartInteractive(m_remoteWorkspaceAccount, codelite_remote_script, "git");
992
993 // find the real git root folder
994 m_remoteProcess.FindPath(workspace_dir + "/.git");
995 }
996 }
997
998 void GitPlugin::OnWorkspaceLoaded(clWorkspaceEvent& e)
999 {
1000 e.Skip();
1001 ClearCodeLiteRemoteInfo();
1002 DoCleanup();
1003
1004 m_workspace_file = e.GetString();
1005 m_isRemoteWorkspace = e.IsRemote();
1006 m_remoteWorkspaceAccount = e.GetRemoteAccount();
1007 StartCodeLiteRemote();
1008 InitDefaults();
1009 RefreshFileListView();
1010
1011 // Try to set the repo, usually to the workspace path
1012 DoSetRepoPath();
1013 CallAfter(&GitPlugin::DoRefreshView, false);
1014 }
1015
1016 void GitPlugin::ProcessGitActionQueue()
1017 {
1018 if(m_gitActionQueue.size() == 0)
1019 return;
1020
1021 // Sanity:
1022 // if there is no repo and the command is not 'clone'
1023 // return
1024 gitAction ga = m_gitActionQueue.front();
1025 if(m_repositoryDirectory.IsEmpty() && ga.action != gitClone) {
1026 m_gitActionQueue.pop_front();
1027 return;
1028 }
1029
1030 if(m_process) {
1031 return;
1032 }
1033
1034 wxString command_args;
1035 size_t createFlags = 0;
1036 bool log_message = false;
1037 switch(ga.action) {
1038 case gitBlameSummary: {
1039 wxString filepath = ga.arguments;
1040 ::WrapWithQuotes(filepath);
1041 command_args << "--no-pager blame --date=short " << filepath;
1042 } break;
1043 case gitStash:
1044 command_args << " stash";
1045 log_message = false;
1046 break;
1047
1048 case gitStashPop:
1049 command_args << " stash pop";
1050 log_message = false;
1051 break;
1052
1053 case gitRevertCommit:
1054 command_args << "revert --no-commit " << ga.arguments;
1055 log_message = true;
1056 break;
1057
1058 case gitApplyPatch:
1059 command_args << "apply --whitespace=nowarn --ignore-whitespace " << ga.arguments;
1060 log_message = true;
1061 break;
1062
1063 case gitRmFiles:
1064 command_args << "--no-pager rm --force " << ga.arguments;
1065 log_message = true;
1066 break;
1067
1068 case gitClone:
1069 command_args << wxT("--no-pager clone ") << ga.arguments;
1070 log_message = true;
1071 break;
1072
1073 case gitStatus:
1074 command_args << "--no-pager status -s";
1075 break;
1076
1077 case gitListAll:
1078 command_args << wxT("--no-pager ls-files");
1079 break;
1080
1081 case gitListModified:
1082 command_args << wxT("--no-pager ls-files -m");
1083 break;
1084
1085 case gitUpdateRemotes:
1086 command_args << wxT("--no-pager remote update");
1087 break;
1088
1089 case gitListRemotes:
1090 command_args << wxT("--no-pager remote");
1091 break;
1092
1093 case gitAddFile:
1094 command_args << wxT("--no-pager add ") << ga.arguments;
1095 log_message = true;
1096 break;
1097
1098 case gitDeleteFile:
1099 command_args << wxT("--no-pager update-index --remove --force-remove ") << ga.arguments;
1100 log_message = true;
1101 break;
1102
1103 case gitDiffFile:
1104 command_args << wxT("--no-pager show HEAD:") << ga.arguments;
1105 break;
1106
1107 case gitDiffRepoCommit:
1108 command_args << wxT("--no-pager diff --no-color HEAD");
1109 ShowProgress(wxT("Obtaining diffs for modified files..."));
1110 break;
1111
1112 case gitDiffRepoShow:
1113 command_args << wxT("--no-pager diff --no-color HEAD");
1114 ShowProgress(wxT("Obtaining diffs for modified files..."));
1115 break;
1116
1117 case gitResetFile:
1118 command_args << wxT("--no-pager checkout ") << ga.arguments;
1119 log_message = true;
1120 break;
1121
1122 case gitUndoAdd:
1123 command_args << wxT("--no-pager reset ") << ga.arguments;
1124 log_message = true;
1125 break;
1126
1127 case gitPull:
1128 ShowProgress(wxT("Obtaining remote changes"), false);
1129 command_args << "--no-pager pull " << ga.arguments;
1130 command_args << " --log";
1131 log_message = true;
1132 createFlags |= IProcessRawOutput;
1133 break;
1134
1135 case gitPush:
1136 command_args << wxT("--no-pager push ") << ga.arguments;
1137 ShowProgress(wxT("Pushing local changes..."), false);
1138 log_message = true;
1139 createFlags |= IProcessRawOutput;
1140 break;
1141
1142 case gitCommit:
1143 command_args << wxT("--no-pager commit ") << ga.arguments;
1144 ShowProgress(wxT("Committing local changes..."));
1145 log_message = true;
1146 createFlags |= IProcessRawOutput;
1147 break;
1148
1149 case gitResetRepo:
1150 command_args << wxT("--no-pager reset --hard");
1151 ShowProgress(wxT("Resetting local repository..."));
1152 log_message = true;
1153 break;
1154
1155 case gitBranchCreate:
1156 command_args << wxT("--no-pager branch ") << ga.arguments;
1157 ShowProgress(wxT("Creating local branch..."));
1158 log_message = true;
1159 break;
1160
1161 case gitBranchCurrent:
1162 command_args << wxT("--no-pager branch --no-color");
1163 break;
1164
1165 case gitBranchList:
1166 command_args << wxT("--no-pager branch --no-color");
1167 break;
1168
1169 case gitBranchListRemote:
1170 command_args << wxT("--no-pager branch -r --no-color");
1171 break;
1172
1173 case gitBranchSwitch:
1174 ShowProgress(wxT("Switching to local branch ") + ga.arguments, false);
1175 command_args << wxT("--no-pager checkout ") << ga.arguments;
1176 log_message = true;
1177 break;
1178
1179 case gitBranchSwitchRemote:
1180 ShowProgress(wxT("Switching to remote branch ") + ga.arguments, false);
1181 command_args << wxT("--no-pager checkout -b ") << ga.arguments;
1182 log_message = true;
1183 createFlags |= IProcessRawOutput;
1184 break;
1185
1186 case gitCommitList:
1187 ShowProgress(wxT("Fetching commit list"));
1188 // hash @ author-name @ date @ subject
1189 command_args << wxT("--no-pager log --pretty=\"%h@%an@%ci@%s\" -n 100 ") << ga.arguments;
1190 break;
1191
1192 case gitBlame:
1193 command_args << "--no-pager blame --line-porcelain " << ga.arguments;
1194 log_message = true;
1195 break;
1196
1197 case gitRevlist:
1198 command_args << "--no-pager rev-list " << ga.arguments;
1199 break;
1200
1201 case gitRebase:
1202 ShowProgress(wxT("Rebase with ") + ga.arguments + wxT(".."));
1203 command_args << wxT("--no-pager rebase ") << ga.arguments;
1204 log_message = true;
1205 createFlags |= IProcessRawOutput;
1206 break;
1207 case gitConfig:
1208 command_args << wxT("--no-pager config ") << ga.arguments;
1209 break;
1210 case gitGarbageCollection:
1211 ShowProgress(wxT("Cleaning git database. This may take some time..."), false);
1212 log_message = true;
1213 command_args << wxT("--no-pager gc");
1214 break;
1215
1216 default:
1217 GIT_MESSAGE(wxT("Unknown git action"));
1218 return;
1219 }
1220
1221 clConfig conf("git.conf");
1222 GitEntry data;
1223 conf.ReadItem(&data);
1224
1225 #ifdef __WXMSW__
1226 if(ga.action == gitClone || ga.action == gitPush || ga.action == gitPull) {
1227 createFlags |=
1228 data.GetFlags() & GitEntry::Git_Show_Terminal ? IProcessCreateConsole : IProcessCreateWithHiddenConsole;
1229
1230 } else {
1231 createFlags |= IProcessCreateWithHiddenConsole;
1232 }
1233 #else
1234 createFlags |= IProcessCreateWithHiddenConsole;
1235
1236 #endif
1237
1238 // Set locale to english
1239 wxStringMap_t om;
1240 om.insert({ "LC_ALL", "C" });
1241 om.insert({ "GIT_MERGE_AUTOEDIT", "no" });
1242
1243 #ifdef __WXMSW__
1244 wxString homeDir;
1245 if(wxGetEnv("USERPROFILE", &homeDir)) {
1246 om.insert(std::make_pair("HOME", homeDir));
1247 }
1248 #endif
1249 EnvSetter es(&om);
1250 wxString workingDirectory = ga.workingDirectory.IsEmpty() ? m_repositoryDirectory : ga.workingDirectory;
1251
1252 m_process = AsyncRunGit(this, command_args, createFlags | IProcessWrapInShell, workingDirectory, log_message);
1253 if(!m_process) {
1254 GIT_MESSAGE(wxT("Failed to execute git command!"));
1255 DoRecoverFromGitCommandError();
1256 }
1257 }
1258
1259 void GitPlugin::FinishGitListAction(const gitAction& ga)
1260 {
1261 clConfig conf("git.conf");
1262 GitEntry data;
1263 conf.ReadItem(&data);
1264
1265 if(!(data.GetFlags() & GitEntry::Git_Colour_Tree_View))
1266 return;
1267
1268 wxArrayString tmpArray = wxStringTokenize(m_commandOutput, wxT("\n"), wxTOKEN_STRTOK);
1269
1270 // Convert path to absolute
1271 for(unsigned i = 0; i < tmpArray.GetCount(); ++i) {
1272 wxFileName fname(tmpArray[i]);
1273 fname.MakeAbsolute(m_repositoryDirectory);
1274 tmpArray[i] = fname.GetFullPath();
1275 }
1276
1277 // convert the array to set for performance
1278 wxStringSet_t gitFileSet;
1279 gitFileSet.insert(tmpArray.begin(), tmpArray.end());
1280
1281 if(ga.action == gitListAll) {
1282 m_mgr->SetStatusMessage(_("Colouring tracked git files..."), 0);
1283 ColourFileTree(m_mgr->GetWorkspaceTree(), gitFileSet, OverlayTool::Bmp_OK);
1284 m_trackedFiles.swap(gitFileSet);
1285
1286 } else if(ga.action == gitListModified) {
1287 m_mgr->SetStatusMessage(_("Colouring modified git files..."), 0);
1288 // Reset modified files
1289 ColourFileTree(m_mgr->GetWorkspaceTree(), m_modifiedFiles, OverlayTool::Bmp_OK);
1290 // First get an up to date map of the filepaths/treeitemids
1291 // (Trying to cache these results in segfaults when the tree has been modified)
1292 std::map<wxString, wxTreeItemId> IDs;
1293 CreateFilesTreeIDsMap(IDs);
1294
1295 // Now filter using the list of modified files, gitFileList, to find which IDs to colour differently
1296 wxStringSet_t toColour;
1297 wxStringSet_t::const_iterator iter = gitFileSet.begin();
1298 for(; iter != gitFileSet.end(); ++iter) {
1299 wxTreeItemId id = IDs[(*iter)];
1300 if(id.IsOk()) {
1301 DoSetTreeItemImage(m_mgr->GetWorkspaceTree(), id, OverlayTool::Bmp_Modified);
1302
1303 } else {
1304 toColour.insert(*iter);
1305 }
1306 }
1307
1308 if(!toColour.empty()) {
1309 ColourFileTree(m_mgr->GetWorkspaceTree(), toColour, OverlayTool::Bmp_Modified);
1310 }
1311
1312 // Finally, cache the modified-files list: it's used in other functions
1313 m_modifiedFiles.swap(gitFileSet);
1314 }
1315 m_mgr->SetStatusMessage("", 0);
1316 }
1317
1318 void GitPlugin::ListBranchAction(const gitAction& ga)
1319 {
1320 wxArrayString gitList = wxStringTokenize(m_commandOutput, wxT("\n"));
1321 if(gitList.GetCount() == 0)
1322 return;
1323
1324 wxArrayString branchList;
1325 for(unsigned i = 0; i < gitList.GetCount(); ++i) {
1326 if(!gitList[i].Contains(wxT("->"))) {
1327 branchList.Add(gitList[i].Mid(2));
1328 }
1329 }
1330
1331 if(branchList.Index(m_currentBranch) != wxNOT_FOUND) {
1332 branchList.Remove(m_currentBranch);
1333 }
1334
1335 if(ga.action == gitBranchList) {
1336 m_localBranchList = branchList;
1337 } else if(ga.action == gitBranchListRemote) {
1338 m_remoteBranchList = branchList;
1339 }
1340 }
1341
1342 void GitPlugin::GetCurrentBranchAction(const gitAction& ga)
1343 {
1344 wxArrayString gitList = wxStringTokenize(m_commandOutput, wxT("\n"));
1345 if(gitList.GetCount() == 0)
1346 return;
1347
1348 m_currentBranch.Empty();
1349 for(unsigned i = 0; i < gitList.GetCount(); ++i) {
1350 if(gitList[i].StartsWith(wxT("*"))) {
1351 m_currentBranch = gitList[i].Mid(2);
1352 break;
1353 }
1354 }
1355
1356 if(!m_currentBranch.IsEmpty()) {
1357 GIT_MESSAGE1(wxT("Current branch ") + m_currentBranch);
1358 m_mgr->GetDockingManager()
1359 ->GetPane(wxT("Workspace View"))
1360 .Caption(_("Workspace View [") + m_currentBranch + wxT("]"));
1361 m_mgr->GetDockingManager()->Update();
1362 }
1363 }
1364
1365 void GitPlugin::UpdateFileTree()
1366 {
1367 if(!m_mgr->GetWorkspace()->IsOpen()) {
1368 return;
1369 }
1370
1371 if(wxMessageBox(_("Do you want to start importing new / updating changed files?"), _("Import files"), wxYES_NO,
1372 EventNotifier::Get()->TopFrame()) == wxNO) {
1373 return;
1374 }
1375
1376 wxString projectName = m_mgr->GetWorkspace()->GetActiveProjectName();
1377 wxString error = _("Error obtaining project");
1378 ProjectPtr proj = m_mgr->GetWorkspace()->FindProjectByName(projectName, error);
1379
1380 proj->BeginTranscation();
1381 wxString path = m_repositoryDirectory;
1382 if(path.EndsWith(wxT("/")) || path.EndsWith(wxT("\\"))) {
1383 path.RemoveLast();
1384 }
1385 wxFileName rootPath(path);
1386
1387 wxArrayString gitfiles = wxStringTokenize(m_commandOutput, wxT("\n"));
1388 wxArrayString files;
1389
1390 // clProgressDlg *prgDlg = new clProgressDlg (EventNotifier::Get()->TopFrame(), _("Importing files ..."), wxT(""),
1391 // (int)gitfiles.GetCount()+2);
1392 wxProgressDialog* prgDlg = new wxProgressDialog(_("Importing files ..."), wxT(""), (int)gitfiles.GetCount() + 2,
1393 EventNotifier::Get()->TopFrame());
1394 wxString filespec = wxT("*.cpp;*.hpp;*.c;*.h;*.ui;*.py;*.txt");
1395 bool extlessFiles(true);
1396 wxStringTokenizer tok(filespec, wxT(";"));
1397 std::set<wxString> specMap;
1398 while(tok.HasMoreTokens()) {
1399 wxString v = tok.GetNextToken().AfterLast(wxT('*'));
1400 v = v.AfterLast(wxT('.')).MakeLower();
1401 specMap.insert(v);
1402 }
1403
1404 // filter non interesting files
1405 for(size_t i = 0; i < gitfiles.GetCount(); i++) {
1406
1407 prgDlg->Update((int)i, _("Checking file ") + gitfiles.Item(i));
1408 wxFileName fn(m_repositoryDirectory + wxT("/") + gitfiles.Item(i));
1409
1410 /* always excluded by default */
1411 wxString filepath = fn.GetPath();
1412 if(filepath.Contains(wxT(".svn")) || filepath.Contains(wxT(".cvs")) || filepath.Contains(wxT(".arch-ids")) ||
1413 filepath.Contains(wxT("arch-inventory")) || filepath.Contains(wxT("autom4te.cache")) ||
1414 filepath.Contains(wxT("BitKeeper")) || filepath.Contains(wxT(".bzr")) ||
1415 filepath.Contains(wxT(".bzrignore")) || filepath.Contains(wxT("CVS")) ||
1416 filepath.Contains(wxT(".cvsignore")) || filepath.Contains(wxT("_darcs")) ||
1417 filepath.Contains(wxT(".deps")) || filepath.Contains(wxT("EIFGEN")) || filepath.Contains(wxT(".git")) ||
1418 filepath.Contains(wxT(".gitignore")) || filepath.Contains(wxT(".hg")) || filepath.Contains(wxT("PENDING")) ||
1419 filepath.Contains(wxT("RCS")) || filepath.Contains(wxT("RESYNC")) || filepath.Contains(wxT("SCCS")) ||
1420 filepath.Contains(wxT("{arch}"))) {
1421 continue;
1422 }
1423
1424 if(specMap.empty()) {
1425 files.Add(gitfiles.Item(i));
1426 } else if(fn.GetExt().IsEmpty() & extlessFiles) {
1427 files.Add(gitfiles.Item(i));
1428 } else if(specMap.find(fn.GetExt().MakeLower()) != specMap.end()) {
1429 files.Add(gitfiles.Item(i));
1430 }
1431 }
1432
1433 prgDlg->Update(gitfiles.GetCount() + 1, _("Adding files..."));
1434 for(size_t i = 0; i < files.GetCount(); i++) {
1435 wxFileName fn(m_repositoryDirectory + wxT("/") + files.Item(i));
1436
1437 // if the file already exist, skip it
1438 if(proj->IsFileExist(fn.GetFullPath())) {
1439 continue;
1440 }
1441
1442 wxString fullpath = fn.GetFullPath();
1443 fn.MakeRelativeTo(path);
1444
1445 wxString relativePath = fn.GetPath();
1446 relativePath.Replace(wxT("/"), wxT(":"));
1447 relativePath.Replace(wxT("\\"), wxT(":"));
1448
1449 if(relativePath.IsEmpty()) {
1450 // the file is probably under the root, add it under
1451 // a virtual directory with the name of the target
1452 // root folder
1453 relativePath = rootPath.GetName();
1454 }
1455 relativePath.Append(wxT(":"));
1456
1457 bool createAndAdd = false;
1458 wxArrayString dummyFiles;
1459 proj->GetFilesByVirtualDir(relativePath, dummyFiles);
1460 if(dummyFiles.GetCount() != 0) {
1461 createAndAdd = true;
1462 } else {
1463 proj->GetFilesByVirtualDir(relativePath.Left(relativePath.Find(wxT(":"))), dummyFiles);
1464 if(dummyFiles.GetCount() != 0) {
1465 createAndAdd = true;
1466 }
1467 }
1468
1469 if(createAndAdd) {
1470 proj->CreateVirtualDir(relativePath, true);
1471 proj->FastAddFile(fullpath, relativePath);
1472 }
1473 }
1474 prgDlg->Update(gitfiles.GetCount() + 2, _("Finished adding files..."));
1475 prgDlg->Destroy();
1476 proj->CommitTranscation();
1477
1478 m_mgr->ReloadWorkspace();
1479 }
1480
1481 void GitPlugin::OnProcessTerminated(clProcessEvent& event)
1482 {
1483 HideProgress();
1484 if(m_gitActionQueue.empty())
1485 return;
1486
1487 gitAction ga = m_gitActionQueue.front();
1488 if(ga.action != gitDiffFile) {
1489 // Dont manipulate the output if its a diff...
1490 m_commandOutput.Replace(wxT("\r"), wxT(""));
1491 }
1492 if (ga.action == gitDiffRepoCommit && m_commandOutput.StartsWith(wxT("fatal"))) {
1493 m_commandOutput.Clear();
1494 DoExecuteCommandSync("diff --no-color --cached", &m_commandOutput);
1495 }
1496 if(m_commandOutput.StartsWith(wxT("fatal")) || m_commandOutput.StartsWith(wxT("error"))) {
1497 // Last action failed, clear queue
1498 LOG_IF_TRACE { clDEBUG1() << "[git]" << m_commandOutput << clEndl; }
1499 static std::unordered_set<int> recoverableActions = { gitBlameSummary };
1500 DoRecoverFromGitCommandError(recoverableActions.count(ga.action) == 0);
1501 GetConsole()->ShowLog();
1502 return;
1503 }
1504
1505 switch(ga.action) {
1506 case gitBlameSummary: {
1507 DoUpdateBlameInfo(m_commandOutput, ga.arguments);
1508 } break;
1509 case gitPush: {
1510 clSourceControlEvent evt(wxEVT_SOURCE_CONTROL_PUSHED);
1511 evt.SetSourceControlName("git");
1512 EventNotifier::Get()->QueueEvent(evt.Clone());
1513 } break;
1514 case gitListAll:
1515 case gitListModified:
1516 case gitResetRepo: {
1517 if(ga.action == gitListAll && m_bActionRequiresTreUpdate) {
1518 if(m_commandOutput.Lower().Contains(_("created"))) {
1519 UpdateFileTree();
1520 }
1521 }
1522 m_bActionRequiresTreUpdate = false;
1523 FinishGitListAction(ga);
1524 if(ga.action == gitResetRepo) {
1525 // Reload files if needed
1526 EventNotifier::Get()->PostReloadExternallyModifiedEvent(true);
1527 // We also want to post reset event here
1528 clSourceControlEvent evt(wxEVT_SOURCE_CONTROL_RESET_FILES);
1529 evt.SetSourceControlName("git");
1530 EventNotifier::Get()->QueueEvent(evt.Clone());
1531 }
1532 } break;
1533 case gitStatus: {
1534 m_console->UpdateTreeView(m_commandOutput);
1535 FinishGitListAction(ga);
1536 } break;
1537 case gitListRemotes: {
1538 wxArrayString gitList = wxStringTokenize(m_commandOutput, wxT("\n"));
1539 m_remotes = gitList;
1540 } break;
1541 case gitDiffFile: {
1542
1543 // Show the diff in the diff-viewer
1544 DoShowDiffViewer(m_commandOutput, ga.arguments);
1545 } break;
1546 case gitDiffRepoCommit: {
1547 wxString commitArgs;
1548 DoShowCommitDialog(m_commandOutput, commitArgs);
1549 if(!commitArgs.IsEmpty()) {
1550 gitAction ga(gitCommit, commitArgs);
1551 m_gitActionQueue.push_back(ga);
1552 AddDefaultActions();
1553 }
1554 } break;
1555 case gitBlame: {
1556 if(!m_gitBlameDlg) {
1557 m_gitBlameDlg = new GitBlameDlg(EventNotifier::Get()->TopFrame(), this);
1558 }
1559 m_gitBlameDlg->SetBlame(m_commandOutput, ga.arguments);
1560 m_gitBlameDlg->Show();
1561 m_gitBlameDlg->SetFocus();
1562 } break;
1563 case gitRevlist: {
1564 if(m_gitBlameDlg) {
1565 m_gitBlameDlg->OnRevListOutput(m_commandOutput, ga.arguments);
1566 }
1567 } break;
1568 case gitDiffRepoShow: {
1569 // This is now dealt with by GitDiffDlg itself
1570 // GitDiffDlg dlg(EventNotifier::Get()->TopFrame(), m_repositoryDirectory, this);
1571 // dlg.SetDiff(m_commandOutput);
1572 // dlg.ShowModal();
1573 } break;
1574 case gitResetFile:
1575 case gitApplyPatch: {
1576 EventNotifier::Get()->PostReloadExternallyModifiedEvent(true);
1577
1578 gitAction newAction;
1579 newAction.action = gitListModified;
1580 m_gitActionQueue.push_back(newAction);
1581
1582 if(ga.action == gitResetFile) {
1583 // We also want to post reset event here
1584 clSourceControlEvent evt(wxEVT_SOURCE_CONTROL_RESET_FILES);
1585 evt.SetSourceControlName("git");
1586 EventNotifier::Get()->QueueEvent(evt.Clone());
1587 }
1588
1589 } break;
1590 case gitBranchCurrent:
1591 GetCurrentBranchAction(ga);
1592 break;
1593 case gitBranchList:
1594 case gitBranchListRemote: {
1595 ListBranchAction(ga);
1596 } break;
1597 case gitBranchSwitch:
1598 case gitBranchSwitchRemote:
1599 case gitPull: {
1600 if(ga.action == gitPull) {
1601 if(m_commandOutput.Contains(wxT("Already"))) {
1602 // do nothing
1603 } else {
1604 wxString log = m_commandOutput.Mid(m_commandOutput.Find(wxT("From")));
1605 if(m_commandOutput.Contains(wxT("Merge made by"))) {
1606 if(wxMessageBox(_("Merged after pull. Rebase?"), _("Rebase"), wxYES_NO,
1607 EventNotifier::Get()->TopFrame()) == wxYES) {
1608 wxString selection;
1609 if(m_remotes.GetCount() > 1) {
1610 selection = wxGetSingleChoice(_("Rebase with what branch?"), _("Rebase"),
1611 m_remoteBranchList, EventNotifier::Get()->TopFrame());
1612 } else {
1613 selection = m_remotes[0] + wxT("/") + m_currentBranch;
1614 if(wxMessageBox(_("Rebase with ") + selection + wxT("?"), _("Rebase"), wxYES_NO,
1615 EventNotifier::Get()->TopFrame()) == wxNO)
1616 selection.Empty();
1617 }
1618
1619 if(selection.IsEmpty())
1620 return;
1621
1622 gitAction ga(gitRebase, selection);
1623 m_gitActionQueue.push_back(ga);
1624 }
1625 } else if(m_commandOutput.Contains(wxT("CONFLICT"))) {
1626 // Do nothing, will be coloured in the console view
1627 GetConsole()->ShowLog();
1628 }
1629 if(m_commandOutput.Contains(wxT("Updating")))
1630 m_bActionRequiresTreUpdate = true;
1631
1632 if(m_bActionRequiresTreUpdate) {
1633 // Post event about file system updated
1634 clFileSystemEvent fsEvent(wxEVT_FILE_SYSTEM_UPDATED);
1635 fsEvent.SetPath(m_repositoryDirectory);
1636 EventNotifier::Get()->AddPendingEvent(fsEvent);
1637 }
1638 }
1639 } else if(ga.action == gitBranchSwitch || ga.action == gitBranchSwitchRemote) {
1640 // update the tree
1641 gitAction ga(gitListAll, wxT(""));
1642 m_gitActionQueue.push_back(ga);
1643 ga.action = gitListModified;
1644 m_gitActionQueue.push_back(ga);
1645 }
1646
1647 clSourceControlEvent evt(wxEVT_SOURCE_CONTROL_PULLED);
1648 evt.SetSourceControlName("git");
1649 EventNotifier::Get()->QueueEvent(evt.Clone());
1650
1651 // Reload files if needed
1652 EventNotifier::Get()->PostReloadExternallyModifiedEvent(true);
1653 } break;
1654 case gitCommitList: {
1655 if(!m_commitListDlg) {
1656 m_commitListDlg = new GitCommitListDlg(EventNotifier::Get()->TopFrame(), m_repositoryDirectory, this);
1657 }
1658 m_commitListDlg->SetCommitList(m_commandOutput);
1659 m_commitListDlg->Show();
1660 } break;
1661 case gitCommit: {
1662 clSourceControlEvent evt(wxEVT_SOURCE_CONTROL_COMMIT_LOCALLY);
1663 evt.SetSourceControlName("git");
1664 EventNotifier::Get()->QueueEvent(evt.Clone());
1665 } break;
1666 case gitRevertCommit: {
1667 // We also want to post reset event here
1668 clSourceControlEvent evt(wxEVT_SOURCE_CONTROL_RESET_FILES);
1669 evt.SetSourceControlName("git");
1670 EventNotifier::Get()->QueueEvent(evt.Clone());
1671 AddDefaultActions();
1672 } break;
1673 default:
1674 break;
1675 }
1676
1677 if(ga.action == gitResetRepo || ga.action == gitResetFile) {
1678 // Reload externally modified files
1679 EventNotifier::Get()->PostReloadExternallyModifiedEvent(true);
1680 }
1681
1682 wxDELETE(m_process);
1683 m_commandOutput.Clear();
1684 m_gitActionQueue.pop_front();
1685
1686 #ifdef __WXGTK__
1687 int statLoc;
1688 ::waitpid(-1, &statLoc, WNOHANG);
1689 #endif
1690 ProcessGitActionQueue();
1691 }
1692
1693 bool GitPlugin::HandleErrorsOnRemoteRepo(const wxString& output) const
1694 {
1695 if(!m_isRemoteWorkspace) {
1696 return false;
1697 }
1698
1699 if(output.Contains("username for") || output.Contains("username for") ||
1700 output.Contains("commit-msg hook failure") || output.Contains("pre-commit hook failure") ||
1701 output.Contains("*** please tell me who you are") || output.EndsWith("password:") ||
1702 output.Contains("password for") || output.Contains("authentication failed") ||
1703 (output.Contains("the authenticity of host") && output.Contains("can't be established")) ||
1704 output.Contains("key fingerprint")) {
1705 ::wxMessageBox(_("Remote git error (needs to be handled manually on the remote server)\n") + output, "CodeLite",
1706 wxICON_WARNING | wxOK | wxCANCEL | wxOK_DEFAULT);
1707 return true;
1708 }
1709 return false;
1710 }
1711
1712 void GitPlugin::OnProcessOutput(clProcessEvent& event)
1713 {
1714 wxString output = event.GetOutput();
1715 auto process = event.GetProcess();
1716 gitAction ga;
1717 if(!m_gitActionQueue.empty()) {
1718 ga = m_gitActionQueue.front();
1719 }
1720
1721 if(ga.action == gitPush || ga.action == gitPull) {
1722 m_console->AddText(output);
1723 }
1724 m_commandOutput.Append(output);
1725
1726 // Handle password required
1727 wxString tmpOutput = output;
1728 tmpOutput.Trim().Trim(false);
1729 tmpOutput.MakeLower();
1730
1731 static std::unordered_set<int> exclude_commands = { gitDiffRepoCommit, gitDiffFile, gitCommitList, gitDiffRepoShow,
1732 gitBlame, gitRevlist, gitBlameSummary };
1733 if(process && exclude_commands.count(ga.action) == 0) {
1734 if(HandleErrorsOnRemoteRepo(tmpOutput)) {
1735 return;
1736 }
1737
1738 if(tmpOutput.Contains("username for")) {
1739 // username is required
1740 wxString username = ::wxGetTextFromUser(output);
1741 if(username.IsEmpty()) {
1742 process->Terminate();
1743 } else {
1744 process->WriteToConsole(username);
1745 }
1746
1747 } else if(tmpOutput.Contains("commit-msg hook failure") || tmpOutput.Contains("pre-commit hook failure")) {
1748 process->Terminate();
1749
1750 } else if(tmpOutput.Contains("*** please tell me who you are")) {
1751 process->Terminate();
1752 GitUserEmailDialog userEmailDialog(EventNotifier::Get()->TopFrame());
1753 if(userEmailDialog.ShowModal() == wxID_OK) {
1754 wxString username = userEmailDialog.GetUsername();
1755 wxString emaiil = userEmailDialog.GetEmail();
1756 {
1757 wxString args;
1758 args << " user.email \"" << emaiil << "\"";
1759 gitAction act(gitConfig, args);
1760 m_gitActionQueue.push_back(act);
1761 }
1762 {
1763 wxString args;
1764 args << " user.name \"" << username << "\"";
1765 gitAction act(gitConfig, args);
1766 m_gitActionQueue.push_back(act);
1767 }
1768 }
1769 } else if(tmpOutput.EndsWith("password:") || tmpOutput.Contains("password for") ||
1770 tmpOutput.Contains("authentication failed")) {
1771
1772 // Password is required
1773 wxString pass = ::wxGetPasswordFromUser(output);
1774 if(pass.IsEmpty()) {
1775
1776 // No point on continuing
1777 process->Terminate();
1778
1779 } else {
1780
1781 // write the password
1782 process->WriteToConsole(pass);
1783 }
1784 } else if((tmpOutput.Contains("the authenticity of host") && tmpOutput.Contains("can't be established")) ||
1785 tmpOutput.Contains("key fingerprint")) {
1786 if(::wxMessageBox(tmpOutput, _("Are you sure you want to continue connecting"),
1787 wxYES_NO | wxCENTER | wxICON_QUESTION) == wxYES) {
1788 process->WriteToConsole("yes");
1789
1790 } else {
1791 process->Terminate();
1792 }
1793 }
1794 }
1795
1796 if(m_console->IsProgressShown()) {
1797 wxString message = output.Left(output.Find(':'));
1798 int percent = output.Find('%', true);
1799 if(percent != wxNOT_FOUND) {
1800
1801 wxString number = output.Mid(percent - 3, 3);
1802 number.Trim(false);
1803 unsigned long current;
1804 if(number.ToULong(&current)) {
1805 message.Prepend(m_progressMessage + " Status: ");
1806 m_console->UpdateProgress(current, message);
1807 }
1808 }
1809 }
1810 }
1811
1812 void GitPlugin::InitDefaults()
1813 {
1814 DoCreateTreeImages();
1815 clConfig conf("git.conf");
1816 GitEntry data;
1817 conf.ReadItem(&data);
1818
1819 if(data.GetTrackedFileColour().IsOk()) {
1820 m_colourTrackedFile = data.GetTrackedFileColour();
1821 }
1822 if(data.GetDiffFileColour().IsOk()) {
1823 m_colourDiffFile = data.GetDiffFileColour();
1824 }
1825 if(!data.GetGITExecutablePath().IsEmpty()) {
1826 m_pathGITExecutable = data.GetGITExecutablePath();
1827 }
1828 if(!data.GetGITKExecutablePath().IsEmpty()) {
1829 m_pathGITKExecutable = data.GetGITKExecutablePath();
1830 }
1831
1832 LoadDefaultGitCommands(data); // Always do this, in case of new entries
1833 conf.WriteItem(&data);
1834 conf.Save();
1835
1836 if(IsWorkspaceOpened()) {
1837 m_repositoryDirectory = GetRepositoryPath();
1838
1839 // Load any unusual git-repo path
1840 wxString projectNameHash, UserEnteredRepoPath;
1841 if(!m_isRemoteWorkspace) {
1842 wxString workspaceName = m_mgr->GetWorkspace()->GetWorkspaceFileName().GetName();
1843 wxString projectName = m_mgr->GetWorkspace()->GetActiveProjectName();
1844 if(!workspaceName.empty() && !projectName.empty()) {
1845 projectNameHash << workspaceName << '-' << projectName;
1846 m_userEnteredRepositoryDirectory = data.GetProjectUserEnteredRepoPath(projectNameHash);
1847 m_repositoryDirectory = m_userEnteredRepositoryDirectory;
1848 }
1849 }
1850 } else {
1851 DoCleanup();
1852 }
1853
1854 if(!m_repositoryDirectory.IsEmpty()) {
1855 m_console->AddLine("Initializing git...");
1856 gitAction ga(gitListAll, wxT(""));
1857 m_gitActionQueue.push_back(ga);
1858 AddDefaultActions();
1859 ProcessGitActionQueue();
1860 }
1861 }
1862
1863 void GitPlugin::AddDefaultActions()
1864 {
1865 gitAction ga(gitBranchCurrent, wxT(""));
1866 m_gitActionQueue.push_back(ga);
1867
1868 // ga.action = gitListAll;
1869 // m_gitActionQueue.push_back(ga);
1870
1871 ga.action = gitListModified;
1872 m_gitActionQueue.push_back(ga);
1873
1874 // ga.action = gitUpdateRemotes;
1875 // m_gitActionQueue.push_back(ga);
1876
1877 ga.action = gitBranchList;
1878 m_gitActionQueue.push_back(ga);
1879
1880 ga.action = gitBranchListRemote;
1881 m_gitActionQueue.push_back(ga);
1882
1883 ga.action = gitListRemotes;
1884 m_gitActionQueue.push_back(ga);
1885
1886 ga.action = gitStatus;
1887 m_gitActionQueue.push_back(ga);
1888 }
1889
1890 void GitPlugin::ColourFileTree(clTreeCtrl* tree, const wxStringSet_t& files, OverlayTool::BmpType bmpType) const
1891 {
1892 clConfig conf("git.conf");
1893 GitEntry data;
1894 conf.ReadItem(&data);
1895
1896 if(!(data.GetFlags() & GitEntry::Git_Colour_Tree_View))
1897 return;
1898
1899 std::stack<wxTreeItemId> items;
1900 if(tree->GetRootItem().IsOk())
1901 items.push(tree->GetRootItem());
1902
1903 while(!items.empty()) {
1904 wxTreeItemId next = items.top();
1905 items.pop();
1906
1907 if(next != tree->GetRootItem()) {
1908 FilewViewTreeItemData* data = static_cast<FilewViewTreeItemData*>(tree->GetItemData(next));
1909 const wxString& path = data->GetData().GetFile();
1910 if(!path.IsEmpty() && files.count(path)) {
1911 DoSetTreeItemImage(tree, next, bmpType);
1912 }
1913 }
1914
1915 wxTreeItemIdValue cookie;
1916 wxTreeItemId nextChild = tree->GetFirstChild(next, cookie);
1917 while(nextChild.IsOk()) {
1918 items.push(nextChild);
1919 nextChild = tree->GetNextSibling(nextChild);
1920 }
1921 }
1922 }
1923
1924 void GitPlugin::CreateFilesTreeIDsMap(std::map<wxString, wxTreeItemId>& IDs, bool ifmodified /*=false*/) const
1925 {
1926 clTreeCtrl* tree = m_mgr->GetWorkspaceTree();
1927 if(!tree) {
1928 return;
1929 }
1930
1931 IDs.clear();
1932
1933 std::stack<wxTreeItemId> items;
1934 if(tree->GetRootItem().IsOk())
1935 items.push(tree->GetRootItem());
1936
1937 while(!items.empty()) {
1938 wxTreeItemId next = items.top();
1939 items.pop();
1940
1941 if(next != tree->GetRootItem()) {
1942 FilewViewTreeItemData* data = static_cast<FilewViewTreeItemData*>(tree->GetItemData(next));
1943 const wxString& path = data->GetData().GetFile();
1944 if(!path.IsEmpty()) {
1945 // If m_modifiedFiles has already been filled, only include files listed there
1946 if(!ifmodified || m_modifiedFiles.count(path)) {
1947 IDs[path] = next;
1948 }
1949 }
1950 }
1951
1952 wxTreeItemIdValue cookie;
1953 wxTreeItemId nextChild = tree->GetFirstChild(next, cookie);
1954 while(nextChild.IsOk()) {
1955 items.push(nextChild);
1956 nextChild = tree->GetNextSibling(nextChild);
1957 }
1958 }
1959 }
1960
1961 void GitPlugin::OnProgressTimer(wxTimerEvent& Event)
1962 {
1963 if(m_console->IsProgressShown())
1964 m_console->PulseProgress();
1965 }
1966
1967 void GitPlugin::ShowProgress(const wxString& message, bool pulse)
1968 {
1969 m_console->ShowProgress(message, pulse);
1970
1971 if(pulse) {
1972 m_progressTimer.Start(50);
1973
1974 } else {
1975 m_progressMessage = message;
1976 }
1977 }
1978
1979 void GitPlugin::HideProgress()
1980 {
1981 m_console->HideProgress();
1982 m_progressTimer.Stop();
1983 }
1984
1985 void GitPlugin::OnEnableGitRepoExists(wxUpdateUIEvent& e) { e.Enable(m_repositoryDirectory.IsEmpty() == false); }
1986
1987 void GitPlugin::OnWorkspaceClosed(clWorkspaceEvent& e)
1988 {
1989 e.Skip();
1990 m_blameMap.clear();
1991 WorkspaceClosed();
1992 m_lastBlameMessage.clear();
1993 ClearCodeLiteRemoteInfo();
1994 clGetManager()->GetStatusBar()->SetSourceControlBitmap(wxNullBitmap, "", "");
1995 }
1996
1997 void GitPlugin::DoCleanup()
1998 {
1999 m_gitActionQueue.clear();
2000 m_repositoryDirectory.Clear();
2001 m_remotes.Clear();
2002 m_localBranchList.Clear();
2003 m_remoteBranchList.Clear();
2004 m_trackedFiles.clear();
2005 m_modifiedFiles.clear();
2006 m_addedFiles = false;
2007 m_progressMessage.Clear();
2008 m_commandOutput.Clear();
2009 m_bActionRequiresTreUpdate = false;
2010 wxDELETE(m_process);
2011 m_mgr->GetDockingManager()->GetPane(wxT("Workspace View")).Caption(wxT("Workspace View"));
2012 m_mgr->GetDockingManager()->Update();
2013 m_filesSelected.Clear();
2014 m_selectedFolder.Clear();
2015 // clear blame info
2016 m_blameMap.clear();
2017 clGetManager()->GetNavigationBar()->ClearLabel();
2018 m_lastBlameMessage.clear();
2019 }
2020
2021 void GitPlugin::DoCreateTreeImages()
2022 {
2023 // We update the tree view with new icons:
2024 // each icon will get an additional of 2 icons:
2025 // modified / OK
2026 // the index will be: m_baseImageCount + img-base + 1 => OK
2027 // m_baseImageCount + img-base + 2 => Modified
2028 #if 0
2029 if(m_treeImageMapping.empty()) {
2030 wxTreeCtrl* tree = m_mgr->GetWorkspaceTree();
2031
2032 // Create 2 sets: modified & normal
2033 wxImageList* il = tree->GetImageList();
2034 m_baseImageCount = il->GetImageCount();
2035
2036 for(int i = 0; i < m_baseImageCount; ++i) {
2037 // we also keep a mapping of the new image to its base image
2038 // The ordeer of adding the images is important since we will use this enumerators (OverlayTool::Bmp_OK etc)
2039 // to choose the correct
2040 // image when colouring the tree
2041 m_treeImageMapping.insert(
2042 std::make_pair(il->Add(OverlayTool::Get().CreateBitmap(il->GetBitmap(i), OverlayTool::Bmp_OK)), i));
2043 m_treeImageMapping.insert(std::make_pair(
2044 il->Add(OverlayTool::Get().CreateBitmap(il->GetBitmap(i), OverlayTool::Bmp_Modified)), i));
2045 m_treeImageMapping.insert(std::make_pair(i, i));
2046 }
2047 }
2048 #endif
2049 }
2050
2051 void GitPlugin::DoSetTreeItemImage(clTreeCtrl* ctrl, const wxTreeItemId& item, OverlayTool::BmpType bmpType) const
2052 {
2053 wxUnusedVar(ctrl);
2054 wxUnusedVar(item);
2055 wxUnusedVar(bmpType);
2056 }
2057
2058 void GitPlugin::OnClone(wxCommandEvent& e)
2059 {
2060 gitCloneDlg dlg(wxTheApp->GetTopWindow());
2061 if(dlg.ShowModal() == wxID_OK) {
2062 gitAction ga;
2063 ga.action = gitClone;
2064 ga.arguments = dlg.GetCloneURL();
2065 ga.workingDirectory = dlg.GetTargetDirectory();
2066 m_gitActionQueue.push_back(ga);
2067 ProcessGitActionQueue();
2068 RefreshFileListView();
2069 }
2070 }
2071
2072 void GitPlugin::DoAddFiles(const wxArrayString& files)
2073 {
2074 if(files.IsEmpty()) {
2075 return;
2076 }
2077 m_addedFiles = true;
2078
2079 wxString filesToAdd;
2080 for(wxString file : files) {
2081 ::WrapWithQuotes(file);
2082 filesToAdd << file << " ";
2083 }
2084
2085 gitAction ga(gitAddFile, filesToAdd);
2086 m_gitActionQueue.push_back(ga);
2087
2088 AddDefaultActions();
2089 ProcessGitActionQueue();
2090 }
2091
2092 void GitPlugin::DoResetFiles(const wxArrayString& files)
2093 {
2094 wxString filesToDelete;
2095 for(wxString file : files) {
2096 ::WrapWithQuotes(file);
2097 filesToDelete << file << " ";
2098 }
2099
2100 gitAction ga(gitResetFile, filesToDelete);
2101 m_gitActionQueue.push_back(ga);
2102 ProcessGitActionQueue();
2103 AddDefaultActions();
2104 RefreshFileListView();
2105 }
2106
2107 void GitPlugin::UndoAddFiles(const wxArrayString& files)
2108 {
2109 wxString filesToDelete;
2110 for(wxString file : files) {
2111 ::WrapWithQuotes(file);
2112 filesToDelete << file << " ";
2113 }
2114
2115 gitAction ga(gitUndoAdd, filesToDelete);
2116 m_gitActionQueue.push_back(ga);
2117 ProcessGitActionQueue();
2118
2119 RefreshFileListView();
2120 }
2121
2122 void GitPlugin::RefreshFileListView()
2123 {
2124 gitAction ga;
2125 ga.action = gitStatus;
2126 m_gitActionQueue.push_back(ga);
2127 ProcessGitActionQueue();
2128 }
2129
2130 void GitPlugin::DoGetFileViewSelectedFiles(wxArrayString& files, bool relativeToRepo)
2131 {
2132 files.Clear();
2133 clTreeCtrl* tree = m_mgr->GetWorkspaceTree();
2134 if(!tree)
2135 return;
2136
2137 wxArrayTreeItemIds items;
2138 tree->GetSelections(items);
2139
2140 for(size_t i = 0; i < items.GetCount(); ++i) {
2141 FilewViewTreeItemData* itemData = dynamic_cast<FilewViewTreeItemData*>(tree->GetItemData(items.Item(i)));
2142 if(itemData && itemData->GetData().GetKind() == ProjectItem::TypeFile) {
2143 // we got a file
2144 wxFileName fn(itemData->GetData().GetFile());
2145 if(relativeToRepo && fn.IsAbsolute()) {
2146 fn.MakeRelativeTo(m_repositoryDirectory);
2147 }
2148
2149 wxString filename = fn.GetFullPath();
2150 if(filename.Contains(" ")) {
2151 filename.Prepend("\"").Append("\"");
2152 }
2153 files.Add(filename);
2154 }
2155 }
2156 }
2157
2158 void GitPlugin::DoShowDiffsForFiles(const wxArrayString& files, bool useFileAsBase)
2159 {
2160 for(const wxString& file : files) {
2161
2162 // and finally, perform the action
2163 // File name should be relative to the repo
2164 gitAction ga(gitDiffFile, file);
2165 m_gitActionQueue.push_back(ga);
2166 }
2167
2168 ProcessGitActionQueue();
2169 }
2170
2171 void GitPlugin::OnStartGitkUI(wxUpdateUIEvent& e)
2172 {
2173 e.Enable(!m_repositoryDirectory.IsEmpty() && !m_pathGITKExecutable.IsEmpty());
2174 }
2175
2176 void GitPlugin::ApplyPatch(const wxString& filename, const wxString& extraFlags)
2177 {
2178 gitAction ga(gitApplyPatch, wxString() << extraFlags << " \"" << filename << "\" ");
2179 m_gitActionQueue.push_back(ga);
2180
2181 // Trigger a refresh
2182 gitAction gaStatus(gitStatus, "");
2183 m_gitActionQueue.push_back(gaStatus);
2184
2185 ProcessGitActionQueue();
2186 }
2187
2188 void GitPlugin::OnWorkspaceConfigurationChanged(wxCommandEvent& e)
2189 {
2190 e.Skip();
2191
2192 // Trigger a refresh
2193 gitAction gaStatus(gitStatus, "");
2194 m_gitActionQueue.push_back(gaStatus);
2195 ProcessGitActionQueue();
2196 }
2197
2198 bool GitPlugin::IsWorkspaceOpened() const { return !m_workspace_file.empty(); }
2199
2200 void GitPlugin::RevertCommit(const wxString& commitId)
2201 {
2202 gitAction ga(gitRevertCommit, commitId);
2203 m_gitActionQueue.push_back(ga);
2204 ProcessGitActionQueue();
2205 }
2206
2207 void GitPlugin::LoadDefaultGitCommands(GitEntry& data, bool overwrite /*= false*/)
2208 {
2209 static const char* commands[] = { // ID_String|MenuLabel,Command;MenuLabel,Command; ...
2210 "git_pull|git pull,pull;git pull --rebase,pull --rebase",
2211 "git_rebase|git rebase,git rebase;git rebase --continue,rebase --continue"
2212 };
2213
2214 const size_t items = sizeof(commands) / sizeof(char*);
2215 for(size_t n = 0; n < items; ++n) {
2216 wxString item = commands[n];
2217
2218 wxString name = item.BeforeFirst('|');
2219 if(name.empty() || name.Len() == item.Len()) {
2220 wxASSERT(name.empty() || name.Len() == item.Len());
2221 continue;
2222 }
2223
2224 if(!overwrite && !data.GetGitCommandsEntries(name).GetCommands().empty()) {
2225 continue;
2226 }
2227
2228 GitCommandsEntries gce(name);
2229 vGitLabelCommands_t commandEntries;
2230 wxArrayString entries = wxStringTokenize(item.AfterFirst('|'), ";");
2231
2232 for(size_t entry = 0; entry < entries.GetCount(); ++entry) {
2233 wxString label = entries.Item(entry).BeforeFirst(',');
2234 wxString command = entries.Item(entry).AfterFirst(',');
2235 wxASSERT(!label.empty() && !command.empty());
2236 if(!label.empty() && !command.empty()) {
2237 commandEntries.push_back(GitLabelCommand(label, command));
2238 }
2239 }
2240
2241 gce.SetCommands(commandEntries);
2242 data.DeleteGitCommandsEntry(name);
2243 data.AddGitCommandsEntry(gce, name);
2244 }
2245 }
2246
2247 void GitPlugin::DoShowDiffViewer(const wxString& headFile, const wxString& fileName)
2248 {
2249 // Write the content of the head file to a temporary file
2250 wxFileName tmpFile(wxFileName::CreateTempFileName("gittmp"));
2251 tmpFile.SetExt(wxFileName(fileName).GetExt());
2252 wxString tmpFilePath = tmpFile.GetFullPath();
2253 wxFFile fp(tmpFilePath, "w+b");
2254 if(fp.IsOpened()) {
2255 fp.Write(headFile);
2256 fp.Close();
2257 }
2258
2259 // Show diff frame
2260 DiffSideBySidePanel::FileInfo l(tmpFilePath, _("HEAD version"), true);
2261 l.deleteOnExit = true;
2262
2263 wxString right_file;
2264 if(IsRemoteWorkspace()) {
2265 #if USE_SFTP
2266 // download the file and store it locally
2267 wxFileName remote_file(GetRepositoryPath() + "/" + fileName);
2268 right_file =
2269 clSFTPManager::Get().Download(remote_file.GetFullPath(wxPATH_UNIX), m_remoteWorkspaceAccount).GetFullPath();
2270 #else
2271 return;
2272 #endif
2273 } else {
2274 wxFileName fnWorkingCopy(fileName);
2275 fnWorkingCopy.MakeAbsolute(m_repositoryDirectory);
2276 right_file = fnWorkingCopy.GetFullPath();
2277 }
2278
2279 DiffSideBySidePanel::FileInfo r(right_file, _("Working copy"), false);
2280 clDiffFrame* diffView = new clDiffFrame(EventNotifier::Get()->TopFrame(), l, r, true);
2281 diffView->Show();
2282 }
2283
2284 void GitPlugin::OnRebase(wxCommandEvent& e)
2285 {
2286 wxString argumentString = e.GetString(); // This might be user-specified e.g. rebase --continue
2287 if(argumentString.empty()) {
2288 argumentString = GetAnyDefaultCommand("git_rebase");
2289 }
2290 argumentString.Replace("rebase", "");
2291 argumentString.Trim(false);
2292
2293 wxStandardID res = ::PromptForYesNoDialogWithCheckbox(_("Save all changes and rebase?"), "GitRebaseChanges");
2294 if(res == wxID_YES) {
2295 m_mgr->SaveAll();
2296 if(m_console->IsDirty()) {
2297 gitAction ga(gitStash, wxT(""));
2298 m_gitActionQueue.push_back(ga);
2299 }
2300 {
2301 gitAction ga(gitRebase, argumentString);
2302 m_gitActionQueue.push_back(ga);
2303 }
2304 if(m_console->IsDirty()) {
2305 gitAction ga(gitStashPop, wxT(""));
2306 m_gitActionQueue.push_back(ga);
2307 }
2308 AddDefaultActions();
2309 ProcessGitActionQueue();
2310 }
2311 }
2312
2313 void GitPlugin::OnMainFrameTitle(clCommandEvent& e)
2314 {
2315 // By default - skip it
2316 e.Skip();
2317 if(!m_currentBranch.IsEmpty() && !m_repositoryDirectory.IsEmpty()) {
2318 wxString newTitle;
2319 newTitle << e.GetString() << wxT(" - [git: ") << m_currentBranch << "]";
2320 e.SetString(newTitle);
2321 e.Skip(false);
2322 }
2323 }
2324
2325 void GitPlugin::DoRecoverFromGitCommandError(bool clear_queue)
2326 {
2327 if(clear_queue) {
2328 // Last action failed, clear queue
2329 while(!m_gitActionQueue.empty()) {
2330 m_gitActionQueue.pop_front();
2331 }
2332 } else {
2333 // do not clear the queue, but we must remove the top command
2334 // (the command that caused the latest failure)
2335 if(!m_gitActionQueue.empty()) {
2336 m_gitActionQueue.pop_front();
2337 }
2338 }
2339 wxDELETE(m_process);
2340 m_commandOutput.Clear();
2341 if(!clear_queue) {
2342 ProcessGitActionQueue();
2343 }
2344 }
2345
2346 void GitPlugin::OnFileMenu(clContextMenuEvent& event)
2347 {
2348 event.Skip();
2349 wxMenu* menu = new wxMenu();
2350 wxMenu* parentMenu = event.GetMenu();
2351 m_filesSelected = event.GetStrings();
2352
2353 BitmapLoader* bmps = m_mgr->GetStdIcons();
2354 wxMenuItem* item = new wxMenuItem(menu, XRCID("git_add_file"), _("Add file"));
2355 item->SetBitmap(bmps->LoadBitmap("plus"));
2356 menu->Append(item);
2357
2358 item = new wxMenuItem(menu, XRCID("git_reset_file"), _("Reset file"));
2359 item->SetBitmap(bmps->LoadBitmap("clean"));
2360 menu->Append(item);
2361
2362 item = new wxMenuItem(menu, XRCID("git_diff_file"), _("Show file diff"));
2363 item->SetBitmap(bmps->LoadBitmap("diff"));
2364 menu->Append(item);
2365
2366 item = new wxMenuItem(menu, XRCID("git_commit_list_file"), _("Show file Log"));
2367 item->SetBitmap(bmps->LoadBitmap("tasks"));
2368 menu->Append(item);
2369
2370 menu->AppendSeparator();
2371 item = new wxMenuItem(menu, XRCID("git_blame_file"), _("Show Git Blame"));
2372 item->SetBitmap(bmps->LoadBitmap("finger"));
2373 menu->Append(item);
2374
2375 item = new wxMenuItem(parentMenu, wxID_ANY, _("Git"), "", wxITEM_NORMAL, menu);
2376 item->SetBitmap(bmps->LoadBitmap("git"));
2377 parentMenu->AppendSeparator();
2378 parentMenu->Append(item);
2379 }
2380
2381 void GitPlugin::OnOpenMSYSGit(wxCommandEvent& e)
2382 {
2383 GitEntry entry;
2384 wxString bashcommand = entry.Load().GetGitShellCommand();
2385 if(!bashcommand.IsEmpty()) {
2386 DirSaver ds;
2387 IEditor* editor = m_mgr->GetActiveEditor();
2388 if(editor) {
2389 ::wxSetWorkingDirectory(editor->GetFileName().GetPath());
2390 }
2391 #ifndef __WXMSW__
2392 ::WrapInShell(bashcommand);
2393 #endif
2394 ::wxExecute(bashcommand);
2395 } else {
2396 ::wxMessageBox(_("Don't know how to start MSYSGit..."), "Git", wxICON_WARNING | wxOK | wxCENTER);
2397 }
2398 }
2399
2400 void GitPlugin::OnFolderMenu(clContextMenuEvent& event)
2401 {
2402 event.Skip();
2403 wxMenu* menu = new wxMenu();
2404 wxMenu* parentMenu = event.GetMenu();
2405 m_selectedFolder = event.GetPath();
2406
2407 BitmapLoader* bmps = m_mgr->GetStdIcons();
2408 wxMenuItem* item = new wxMenuItem(menu, XRCID("git_pull_rebase_folder"), _("Pull remote changes"));
2409 item->SetBitmap(bmps->LoadBitmap("pull"));
2410 menu->Append(item);
2411
2412 item = new wxMenuItem(menu, XRCID("git_commit_folder"), _("Commit"));
2413 item->SetBitmap(bmps->LoadBitmap("git-commit"));
2414 menu->Append(item);
2415
2416 item = new wxMenuItem(menu, XRCID("git_push_folder"), _("Push"));
2417 item->SetBitmap(bmps->LoadBitmap("up"));
2418 menu->Append(item);
2419
2420 menu->AppendSeparator();
2421
2422 item = new wxMenuItem(menu, XRCID("git_stash_folder"), _("Stash"));
2423 item->SetBitmap(bmps->LoadBitmap("down"));
2424 menu->Append(item);
2425
2426 item = new wxMenuItem(menu, XRCID("git_stash_pop_folder"), _("Stash pop"));
2427 item->SetBitmap(bmps->LoadBitmap("up"));
2428 menu->Append(item);
2429
2430 #ifdef __WXMSW__
2431 menu->AppendSeparator();
2432 item = new wxMenuItem(menu, XRCID("git_bash_folder"), _("Open git bash"));
2433 item->SetBitmap(bmps->LoadBitmap("console"));
2434 menu->Append(item);
2435 #endif
2436
2437 item = new wxMenuItem(parentMenu, wxID_ANY, _("Git"), "", wxITEM_NORMAL, menu);
2438 item->SetBitmap(bmps->LoadBitmap("git"));
2439 parentMenu->AppendSeparator();
2440 parentMenu->Append(item);
2441 }
2442
2443 void GitPlugin::OnFolderPullRebase(wxCommandEvent& event)
2444 {
2445 // Just perform a 'pull --rebase'
2446 // if an error occurs, let the user handle it first
2447 GitCmd::Vec_t commands;
2448 commands.push_back(GitCmd("pull --rebase", IProcessCreateConsole));
2449 DoExecuteCommands(commands, m_selectedFolder);
2450 m_selectedFolder.Clear();
2451 }
2452
2453 void GitPlugin::OnCommandEnded(clCommandEvent& event)
2454 {
2455 m_commandProcessor->Unbind(wxEVT_COMMAND_PROCESSOR_OUTPUT, &GitPlugin::OnCommandOutput, this);
2456 m_commandProcessor->Unbind(wxEVT_COMMAND_PROCESSOR_ENDED, &GitPlugin::OnCommandEnded, this);
2457 m_commandProcessor = NULL;
2458
2459 // Perform a tree refresh
2460 DoRefreshView(false);
2461 }
2462
2463 void GitPlugin::OnCommandOutput(clCommandEvent& event)
2464 {
2465 m_console->AddText(event.GetString());
2466 wxString processOutput = event.GetString();
2467 processOutput.MakeLower();
2468 if(processOutput.Contains("username for")) {
2469 wxString user = ::wxGetTextFromUser(event.GetString(), "Git");
2470 if(!user.IsEmpty()) {
2471 event.SetString(user);
2472 }
2473 }
2474 if(processOutput.Contains("password for")) {
2475 wxString pass = ::wxGetPasswordFromUser(event.GetString(), "Git");
2476 if(!pass.IsEmpty()) {
2477 event.SetString(pass);
2478 }
2479 }
2480 }
2481
2482 void GitPlugin::DoExecuteCommands(const GitCmd::Vec_t& commands, const wxString& workingDir)
2483 {
2484 if(commands.empty())
2485 return;
2486
2487 if(m_commandProcessor) {
2488 // another command is already running, don't do anything
2489 return;
2490 }
2491
2492 wxString command = m_pathGITExecutable;
2493 // Wrap the executable with quotes if needed
2494 command.Trim().Trim(false);
2495 ::WrapWithQuotes(command);
2496 command << " --no-pager ";
2497 m_commandProcessor =
2498 new clCommandProcessor(command + commands.at(0).baseCommand, workingDir, commands.at(0).processFlags);
2499 clCommandProcessor* cur = m_commandProcessor;
2500 for(size_t i = 1; i < commands.size(); ++i) {
2501 clCommandProcessor* next =
2502 new clCommandProcessor(command + commands.at(i).baseCommand, workingDir, commands.at(i).processFlags);
2503 cur = cur->Link(next);
2504 }
2505 m_commandProcessor->Bind(wxEVT_COMMAND_PROCESSOR_OUTPUT, &GitPlugin::OnCommandOutput, this);
2506 m_commandProcessor->Bind(wxEVT_COMMAND_PROCESSOR_ENDED, &GitPlugin::OnCommandEnded, this);
2507 m_mgr->ShowOutputPane("Git");
2508 m_commandProcessor->ExecuteCommand();
2509 }
2510
2511 void GitPlugin::DoShowCommitDialog(const wxString& diff, wxString& commitArgs)
2512 {
2513 wxString lastCommitString, commitHistory;
2514 // Find the title/body message of the previous commit, in case the user wants to amend it
2515 DoExecuteCommandSync("log -1 --pretty=format:\"%B\"", &lastCommitString);
2516 // Similarly the # and title of the last 100 commits for the commit history
2517 DoExecuteCommandSync("log -100 --abbrev-commit --pretty=oneline", &commitHistory);
2518
2519 commitArgs.Clear();
2520 GitCommitDlg dlg(EventNotifier::Get()->TopFrame(), this, m_repositoryDirectory);
2521 dlg.AppendDiff(diff);
2522 dlg.SetPreviousCommitMessage(lastCommitString);
2523 dlg.SetHistory(commitHistory);
2524 if(dlg.ShowModal() == wxID_OK) {
2525 if(dlg.GetSelectedFiles().IsEmpty() && !dlg.IsAmending())
2526 return;
2527 wxString message = dlg.GetCommitMessage();
2528 if(!message.IsEmpty() || dlg.IsAmending()) {
2529
2530 // amending?
2531 if(dlg.IsAmending()) {
2532 commitArgs << " --amend ";
2533 }
2534
2535 // Add the message
2536 if(!message.IsEmpty()) {
2537 wxString messagefile = GetCommitMessageFile();
2538 ::WrapWithQuotes(messagefile);
2539 commitArgs << "--file=";
2540 commitArgs << messagefile << " ";
2541
2542 if(IsRemoteWorkspace()) {
2543 #if USE_SFTP
2544 if(!clSFTPManager::Get().AwaitWriteFile(message, messagefile, m_remoteWorkspaceAccount)) {
2545 m_console->AddText(_("ERROR: Failed to write commit message to file: ") + messagefile + "\n" +
2546 clSFTPManager::Get().GetLastError() + "\n");
2547 return;
2548 }
2549 #else
2550 return;
2551 #endif
2552 } else {
2553 if(!FileUtils::WriteFileContent(messagefile, message)) {
2554 m_console->AddText(_("ERROR: Failed to write commit message to file: ") + messagefile + "\n");
2555 return;
2556 }
2557 }
2558 } else {
2559 // we are amending previous commit, use the previous commit message
2560 // by passing the --no-edit switch
2561 commitArgs << " --no-edit ";
2562 }
2563 wxArrayString selectedFiles = dlg.GetSelectedFiles();
2564 for(unsigned i = 0; i < selectedFiles.GetCount(); ++i)
2565 commitArgs << ::WrapWithQuotes(selectedFiles.Item(i)) << wxT(" ");
2566
2567 } else {
2568 m_console->AddText(_("error: no commit message given, aborting"));
2569 }
2570 }
2571 }
2572
2573 void GitPlugin::OnFolderCommit(wxCommandEvent& event)
2574 {
2575 // 1. Get diff output
2576 wxString diff;
2577 bool res = DoExecuteCommandSync("diff --no-color HEAD", &diff, m_selectedFolder);
2578 if (diff.empty()) {
2579 DoExecuteCommandSync("diff --no-color --cached", &diff);
2580 }
2581 if(!diff.IsEmpty()) {
2582 wxString commitArgs;
2583 DoShowCommitDialog(diff, commitArgs);
2584 if(!commitArgs.IsEmpty()) {
2585 GitCmd::Vec_t commands;
2586 commands.push_back(GitCmd("commit " + commitArgs, IProcessCreateDefault));
2587 DoExecuteCommands(commands, m_selectedFolder);
2588 }
2589 } else if(res) {
2590 ::wxMessageBox(_("All files are up-to-date!"), "CodeLite");
2591 }
2592 }
2593
2594 bool GitPlugin::DoExecuteCommandSync(const wxString& command, wxString* commandOutput, const wxString& workingDir)
2595 {
2596 commandOutput->Clear();
2597 if(!IsRemoteWorkspace()) {
2598 wxString git_command = m_pathGITExecutable;
2599 // Wrap the executable with quotes if needed
2600 git_command.Trim().Trim(false);
2601 ::WrapWithQuotes(git_command);
2602 git_command << " --no-pager ";
2603 git_command << command;
2604
2605 GIT_MESSAGE(git_command);
2606 IProcess::Ptr_t gitProc(::CreateSyncProcess(git_command, IProcessCreateSync | IProcessWrapInShell, workingDir));
2607 if(gitProc) {
2608 gitProc->WaitForTerminate(*commandOutput);
2609 } else {
2610 return false;
2611 }
2612
2613 } else {
2614 clEnvList_t env;
2615 wxString git_command = "git --no-pager ";
2616 git_command << command;
2617 GIT_MESSAGE(git_command);
2618 if(!m_remoteProcess.SyncExec(git_command, workingDir.empty() ? m_repositoryDirectory : workingDir, env,
2619 commandOutput)) {
2620 commandOutput->clear();
2621 return false;
2622 }
2623 }
2624
2625 const wxString lcOutput = commandOutput->Lower();
2626 if(lcOutput.Contains("fatal:") || lcOutput.Contains("not a git repository")) {
2627 // prompt the user for the error
2628 commandOutput->clear();
2629 return false;
2630 }
2631 return true;
2632 }
2633
2634 void GitPlugin::OnFolderPush(wxCommandEvent& event)
2635 {
2636 GitCmd::Vec_t commands;
2637 commands.push_back(GitCmd("push", IProcessCreateConsole));
2638 DoExecuteCommands(commands, m_selectedFolder);
2639 }
2640
2641 void GitPlugin::OnFolderStash(wxCommandEvent& event)
2642 {
2643 GitCmd::Vec_t commands;
2644 commands.push_back(GitCmd("stash", IProcessCreateDefault));
2645 DoExecuteCommands(commands, m_selectedFolder);
2646 }
2647
2648 void GitPlugin::OnFolderStashPop(wxCommandEvent& event)
2649 {
2650 GitCmd::Vec_t commands;
2651 commands.push_back(GitCmd("stash pop", IProcessCreateDefault));
2652 DoExecuteCommands(commands, m_selectedFolder);
2653 }
2654
2655 void GitPlugin::OnFolderGitBash(wxCommandEvent& event)
2656 {
2657 GitLocator locator;
2658 wxString bashcommand;
2659 if(locator.MSWGetGitShellCommand(bashcommand)) {
2660 DirSaver ds;
2661 ::wxSetWorkingDirectory(m_selectedFolder);
2662 ::WrapInShell(bashcommand);
2663 ::wxExecute(bashcommand);
2664 } else {
2665 ::wxMessageBox(_("Don't know how to start MSYSGit..."), "Git", wxICON_WARNING | wxOK | wxCENTER);
2666 }
2667 }
2668
2669 void GitPlugin::OnActiveProjectChanged(clProjectSettingsEvent& event)
2670 {
2671 event.Skip();
2672 // Clear any stale repo data, otherwise it looks as if there's a valid git
2673 // repo when it actually belongs to a different project
2674 DoCleanup();
2675 m_console->UpdateTreeView("");
2676
2677 // Load any unusual git-repo path
2678 wxString projectNameHash;
2679 if(!m_isRemoteWorkspace) {
2680 wxString workspaceName = m_mgr->GetWorkspace()->GetWorkspaceFileName().GetName();
2681 wxString projectName = m_mgr->GetWorkspace()->GetActiveProjectName();
2682 if(!workspaceName.empty() && !projectName.empty()) {
2683 projectNameHash << workspaceName << '-' << projectName;
2684 clConfig conf("git.conf");
2685 GitEntry data;
2686 conf.ReadItem(&data);
2687 m_userEnteredRepositoryDirectory = data.GetProjectUserEnteredRepoPath(projectNameHash);
2688 }
2689 }
2690
2691 DoSetRepoPath(m_userEnteredRepositoryDirectory);
2692 }
2693
2694 void GitPlugin::WorkspaceClosed()
2695 {
2696 // Clearn any saved data from the current workspace
2697 // git commands etc
2698 DoCleanup();
2699 m_workspace_file.Clear();
2700 }
2701
2702 void GitPlugin::FetchNextCommits(int skip, const wxString& args)
2703 {
2704 wxString skipCommits;
2705 skipCommits << " --skip=" << skip;
2706 gitAction ga(gitCommitList, args + skipCommits);
2707 m_gitActionQueue.push_back(ga);
2708 ProcessGitActionQueue();
2709 }
2710
2711 void GitPlugin::OnFileGitBlame(wxCommandEvent& event)
2712 {
2713 // Sanity
2714 if(m_filesSelected.IsEmpty() || m_repositoryDirectory.empty())
2715 return;
2716
2717 // We need to be symlink-aware here on Linux, so use CLRealPath
2718 wxString realfilepath = CLRealPath(m_filesSelected.Item(0));
2719 wxFileName fn(realfilepath);
2720 fn.MakeRelativeTo(CLRealPath(m_repositoryDirectory));
2721
2722 DoGitBlame(fn.GetFullPath());
2723 }
2724
2725 void GitPlugin::OnFileCommitListSelected(wxCommandEvent& e)
2726 {
2727 // Sanity
2728 if(m_filesSelected.IsEmpty() || m_repositoryDirectory.empty())
2729 return;
2730
2731 // We need to be symlink-aware here on Linux, so use CLRealPath
2732 wxString realfilepath = CLRealPath(m_filesSelected.Item(0));
2733 wxFileName fn(realfilepath);
2734 fn.MakeRelativeTo(CLRealPath(m_repositoryDirectory));
2735
2736 if(!m_commitListDlg) {
2737 m_commitListDlg = new GitCommitListDlg(EventNotifier::Get()->TopFrame(), m_repositoryDirectory, this);
2738 }
2739 m_commitListDlg->GetComboExtraArgs()->SetValue(wxT(" -- ") + fn.GetFullPath());
2740
2741 gitAction ga(gitCommitList, wxT(" -- ") + fn.GetFullPath());
2742 m_gitActionQueue.push_back(ga);
2743 ProcessGitActionQueue();
2744 }
2745
2746 void GitPlugin::DisplayMessage(const wxString& message) const
2747 {
2748 if(!message.empty()) {
2749 GIT_MESSAGE(message);
2750 }
2751 }
2752
2753 void GitPlugin::DoRefreshView(bool ensureVisible)
2754 {
2755 gitAction ga(gitListAll, wxT(""));
2756 m_gitActionQueue.push_back(ga);
2757 AddDefaultActions();
2758 if(ensureVisible) {
2759 m_mgr->ShowOutputPane("Git");
2760 }
2761 ProcessGitActionQueue();
2762 }
2763
2764 void GitPlugin::OnAppActivated(wxCommandEvent& event)
2765 {
2766 event.Skip();
2767 if(IsGitEnabled()) {
2768 CallAfter(&GitPlugin::DoRefreshView, false);
2769 }
2770 }
2771
2772 bool GitPlugin::IsGitEnabled() const { return !m_repositoryDirectory.IsEmpty(); }
2773
2774 void GitPlugin::OnFileCreated(clFileSystemEvent& event)
2775 {
2776 event.Skip();
2777 if(IsGitEnabled()) {
2778 // A file was created on the file system, add it to git if needed
2779 const wxArrayString& paths = event.GetPaths();
2780 DoAddFiles(paths);
2781 RefreshFileListView();
2782 }
2783 }
2784
2785 void GitPlugin::OnReplaceInFiles(clFileSystemEvent& event)
2786 {
2787 event.Skip();
2788 DoRefreshView(false);
2789 }
2790
2791 void GitPlugin::OnEditorChanged(wxCommandEvent& event)
2792 {
2793 event.Skip();
2794 // Git the basic git blame
2795 DoLoadBlameInfo(false);
2796 }
2797
2798 void GitPlugin::DoLoadBlameInfo(bool clearCache)
2799 {
2800 if(!(m_configFlags & GitEntry::Git_Show_Commit_Info))
2801 return;
2802
2803 if(!IsGitEnabled()) {
2804 return;
2805 }
2806
2807 auto editor = clGetManager()->GetActiveEditor();
2808 CHECK_PTR_RET(editor);
2809
2810 // use the remote path if available
2811 wxString fullpath = editor->GetRemotePathOrLocal();
2812 if(m_blameMap.count(fullpath) && !clearCache) {
2813 return;
2814 }
2815
2816 m_blameMap.erase(fullpath);
2817 gitAction ga(gitBlameSummary, fullpath);
2818 m_gitActionQueue.push_back(ga);
2819 ProcessGitActionQueue();
2820 }
2821
2822 void GitPlugin::DoUpdateBlameInfo(const wxString& info, const wxString& fullpath)
2823 {
2824 // parse the git blame output
2825 if(m_blameMap.count(fullpath)) {
2826 m_blameMap.erase(fullpath);
2827 }
2828 m_blameMap.insert({ fullpath, {} });
2829 auto& V = m_blameMap[fullpath];
2830 wxArrayString lines = ::wxStringTokenize(info, "\n", wxTOKEN_RET_DELIMS);
2831 V.reserve(lines.size());
2832 for(wxString& line : lines) {
2833 line = line.BeforeFirst(')');
2834 wxArrayString parts = ::wxStringTokenize(line, "\t )(", wxTOKEN_STRTOK);
2835 if(!parts.empty()) {
2836 // remove the line number part of the line
2837 parts.pop_back();
2838 }
2839 // build the line
2840 wxString comment;
2841 for(size_t i = 0; i < parts.size(); ++i) {
2842 wxString part = parts[i];
2843 if(i == (parts.size() - 1)) {
2844 part.Append(")").Prepend("(");
2845 } else if(i == 0) {
2846 part << ":";
2847 }
2848 comment << part << " ";
2849 }
2850 V.emplace_back(comment);
2851 }
2852 }
2853
2854 void GitPlugin::OnUpdateNavBar(clCodeCompletionEvent& event)
2855 {
2856 event.Skip();
2857 if(!(m_configFlags & GitEntry::Git_Show_Commit_Info)) {
2858 return;
2859 }
2860
2861 auto editor = clGetManager()->GetActiveEditor();
2862 CHECK_PTR_RET(editor);
2863
2864 wxString fullpath = editor->GetRemotePathOrLocal();
2865 LOG_IF_TRACE { clDEBUG1() << "Checking blame info for file:" << fullpath << clEndl; }
2866 auto where = m_blameMap.find(fullpath);
2867
2868 if(where == m_blameMap.end()) {
2869 LOG_IF_TRACE { clDEBUG1() << "Could not get git blame for file:" << fullpath << clEndl; }
2870 clGetManager()->GetNavigationBar()->ClearLabel();
2871 return;
2872 }
2873
2874 size_t lineNumber = editor->GetCurrentLine();
2875 if(lineNumber < where->second.size()) {
2876 const wxString& newmsg = where->second[lineNumber];
2877 if(m_lastBlameMessage != newmsg) {
2878 m_lastBlameMessage = newmsg;
2879 clGetManager()->GetNavigationBar()->SetLabel(newmsg);
2880 }
2881 }
2882 }
2883
2884 void GitPlugin::OnEditorClosed(wxCommandEvent& event)
2885 {
2886 event.Skip();
2887 IEditor* editor = (IEditor*)event.GetClientData();
2888 CHECK_PTR_RET(editor);
2889 m_blameMap.erase(editor->GetFileName().GetFullPath());
2890 m_lastBlameMessage.clear();
2891 }
2892
2893 void GitPlugin::OnGitActionDone(clSourceControlEvent& event)
2894 {
2895 // whenever a git action is performed, we clear the blame info
2896 // and reload it for the current file
2897 event.Skip();
2898 m_blameMap.clear();
2899 m_lastBlameMessage.clear();
2900 DoLoadBlameInfo(false);
2901 }
2902
2903 IProcess* GitPlugin::AsyncRunGit(wxEvtHandler* handler, const wxString& command_args, size_t create_flags,
2904 const wxString& working_directory, bool logMessage)
2905 {
2906 if(m_isRemoteWorkspace) {
2907 wxString command;
2908 command << "git " << command_args;
2909
2910 clEnvList_t env;
2911 if(logMessage) {
2912 m_console->PrintPrompt();
2913 }
2914
2915 GIT_MESSAGE_IF(logMessage, command);
2916 return m_remoteProcess.CreateAsyncProcess(handler, command, working_directory, env);
2917
2918 } else {
2919 wxString command = m_pathGITExecutable;
2920
2921 // Wrap the executable with quotes if needed
2922 command.Trim().Trim(false);
2923 ::WrapWithQuotes(command);
2924
2925 command << " " << command_args;
2926 if(logMessage) {
2927 m_console->PrintPrompt();
2928 }
2929 GIT_MESSAGE_IF(logMessage, command);
2930
2931 auto process = ::CreateAsyncProcess(handler, command, create_flags | IProcessWrapInShell, working_directory);
2932 return process;
2933 }
2934 }
2935
2936 void GitPlugin::AsyncRunGitWithCallback(const wxString& command_args, std::function<void(const wxString&)> callback,
2937 size_t create_flags, const wxString& working_directory, bool logMessage)
2938 {
2939 if(m_isRemoteWorkspace) {
2940 wxString command;
2941 command << "git " << command_args;
2942
2943 clEnvList_t env;
2944 GIT_MESSAGE_IF(logMessage, command);
2945 m_remoteProcess.CreateAsyncProcessCB(command, std::move(callback), working_directory, env);
2946 } else {
2947 wxString command = m_pathGITExecutable;
2948
2949 // Wrap the executable with quotes if needed
2950 command.Trim().Trim(false);
2951 ::WrapWithQuotes(command);
2952
2953 command << " " << command_args;
2954 GIT_MESSAGE_IF(logMessage, command);
2955 ::CreateAsyncProcessCB(command, callback, create_flags, working_directory, nullptr);
2956 }
2957 }
2958
2959 IEditor* GitPlugin::OpenFile(const wxString& relativePathFile)
2960 {
2961 wxFileName fn(GetRepositoryPath() + "/" + relativePathFile);
2962 if(IsRemoteWorkspace()) {
2963 #if USE_SFTP
2964 return clSFTPManager::Get().OpenFile(fn.GetFullPath(wxPATH_UNIX), m_remoteWorkspaceAccount);
2965 #else
2966 return nullptr;
2967 #endif
2968 } else {
2969 return clGetManager()->OpenFile(fn.GetFullPath());
2970 }
2971 }
2972
2973 wxString GitPlugin::GetCommitMessageFile() const
2974 {
2975 if(IsRemoteWorkspace()) {
2976 return "/tmp/CL_GIT_COMMIT_MSG.TXT";
2977 } else {
2978 wxFileName fn(clStandardPaths::Get().GetTempDir() + "/CL_GIT_COMMIT_MSG.TXT");
2979 return fn.GetFullPath(IsRemoteWorkspace() ? wxPATH_UNIX : wxPATH_NATIVE);
2980 }
2981 }
2982
2983 wxString GitPlugin::FindRepositoryRoot(const wxString& starting_dir) const
2984 {
2985 if(IsRemoteWorkspace()) {
2986 return starting_dir;
2987 }
2988
2989 wxFileName fp(starting_dir, "");
2990 while(fp.GetDirCount()) {
2991 wxFileName gitdir(fp.GetPath(), wxEmptyString);
2992 gitdir.AppendDir(".git");
2993 if(wxFileName::DirExists(gitdir.GetPath())) {
2994 wxString realfilepath = CLRealPath(gitdir.GetPath());
2995 if(realfilepath != gitdir.GetPath() && wxFileName::DirExists(realfilepath)) {
2996 return realfilepath.BeforeLast('.');
2997 }
2998 gitdir.RemoveLastDir(); // remove the .git folder
2999 return gitdir.GetPath();
3000 }
3001 fp.RemoveLastDir();
3002 }
3003 return starting_dir;
3004 }
3005
3006 void GitPlugin::OnFindPath(clCommandEvent& event)
3007 {
3008 wxUnusedVar(event);
3009 if(event.GetEventType() == wxEVT_CODELITE_REMOTE_FINDPATH) {
3010 if(!event.GetString().empty()) {
3011 clDEBUG() << ".git folder found at:" << event.GetString() << endl;
3012 wxString new_path = event.GetString();
3013 new_path = new_path.BeforeLast('.');
3014 clDEBUG() << "Setting repository path at:" << new_path << endl;
3015 DoSetRepoPath(new_path);
3016 RefreshFileListView();
3017 }
3018 }
3019 }
3020
3021 void GitPlugin::OnSftpFileSaved(clCommandEvent& event)
3022 {
3023 event.Skip();
3024 if(IsGitEnabled()) {
3025 // file saved remotely, refresh the view
3026 RefreshFileListView();
3027 }
3028 }