Debian Codegraph @

CodeFormatter/GenericFormatter.cpp

raw
1 #include "GenericFormatter.hpp"
2
3 #include "Platform.hpp"
4 #include "StringUtils.h"
5 #include "asyncprocess.h"
6 #include "clCodeLiteRemoteProcess.hpp"
7 #include "clDirChanger.hpp"
8 #include "clTempFile.hpp"
9 #include "clWorkspaceManager.h"
10 #include "environmentconfig.h"
11 #include "file_logger.h"
12 #include "fileutils.h"
13 #include "globals.h"
14 #include "imanager.h"
15 #include "macromanager.h"
16 #include "procutils.h"
17 #include "workspace.h"
18
19 #include <sstream>
20 #include <thread>
21 #include <wx/msgdlg.h>
22
23 namespace
24 {
25 wxString join_array(const wxArrayString& arr)
26 {
27 wxString cmd;
28 for(auto c : arr) {
29 cmd << WrapWithQuotes(c) << " ";
30 }
31
32 if(!cmd.IsEmpty()) {
33 cmd.RemoveLast();
34 }
35 return cmd;
36 }
37
38 wxArrayString to_wx_array(const std::vector<wxString>& arr)
39 {
40 wxArrayString wxarr;
41 wxarr.reserve(arr.size());
42
43 for(const auto& s : arr) {
44 wxarr.push_back(s);
45 }
46 return wxarr;
47 }
48
49 wxString replace_macros(const wxString& expression, const wxString& filepath)
50 {
51 wxString expand_stage1 = MacroManager::Instance()->ExpandFileMacros(expression, filepath);
52 wxString resolved = MacroManager::Instance()->Expand(expand_stage1, clGetManager(), wxEmptyString, wxEmptyString);
53 return resolved;
54 }
55
56 wxString get_command_with_desc(const wxArrayString& command_arr, const wxString& desc)
57 {
58 wxString command = StringUtils::BuildCommandStringFromArray(command_arr, StringUtils::WITH_COMMENT_PREFIX);
59 command.Prepend(wxString() << "# " << desc << "\n");
60 return command;
61 }
62
63 bool sync_format(const wxString& cmd, const wxString& wd, bool inplace_formatter, wxString* output)
64 {
65 // save the current directory
66 clDirChanger cd{ wd };
67 EnvSetter es(NULL, NULL, wxEmptyString, wxEmptyString);
68 bool res = ProcUtils::ShellExecSync(cmd, output) == 0;
69 if(inplace_formatter) {
70 output->clear();
71 }
72 return res;
73 }
74 } // namespace
75
76 GenericFormatter::GenericFormatter()
77 {
78 SetWorkingDirectory("$(WorkspacePath)");
79 Bind(wxEVT_SHELL_ASYNC_PROCESS_TERMINATED, &GenericFormatter::OnAsyncShellProcessTerminated, this);
80 }
81
82 GenericFormatter::~GenericFormatter()
83 {
84 Unbind(wxEVT_SHELL_ASYNC_PROCESS_TERMINATED, &GenericFormatter::OnAsyncShellProcessTerminated, this);
85 }
86
87 wxString GenericFormatter::GetCommandAsString() const { return join_array(m_command); }
88
89 /**
90 * @brief format source file using background thread, when the formatting is done, fire an event to the sink object
91 */
92 void GenericFormatter::async_format(const wxString& cmd, const wxString& wd, const wxString& filepath,
93 bool inplace_formatter, wxEvtHandler* sink)
94 {
95 clDirChanger cd{ wd };
96 long pid = wxNOT_FOUND;
97 if(ProcUtils::ShellExecAsync(cmd, &pid, this)) {
98 m_pid_commands.insert({ pid, CommandMetadata{ cmd, filepath, sink } });
99 }
100 }
101
102 bool GenericFormatter::DoFormatFile(const wxString& filepath, wxEvtHandler* sink, wxString* output)
103 {
104 // Create a copy
105 wxString cmd = GetCommandAsString();
106
107 cmd = replace_macros(cmd, filepath);
108 wxString wd = replace_macros(GetWorkingDirectory(), filepath);
109
110 clDEBUG() << "Working dir:" << wd << endl;
111 clDEBUG() << "Calling:" << cmd << endl;
112
113 wxBusyCursor bc;
114 if(sink) {
115 async_format(cmd, wd, filepath, IsInplaceFormatter(), sink);
116 return true;
117 } else {
118 return sync_format(cmd, wd, IsInplaceFormatter(), output);
119 }
120 }
121
122 bool GenericFormatter::FormatFile(const wxFileName& filepath, wxEvtHandler* sink)
123 {
124 return FormatFile(filepath.GetFullPath(), sink);
125 }
126
127 bool GenericFormatter::FormatRemoteFile(const wxString& filepath, wxEvtHandler* sink)
128 {
129 if(!CanHandleRemoteFile()) {
130 return false;
131 }
132
133 // Create a copy
134 wxString cmd = GetRemoteCommand();
135
136 cmd = replace_macros(cmd, filepath);
137 wxString wd = replace_macros(GetWorkingDirectory(), filepath);
138
139 clDEBUG() << "Working dir:" << wd << endl;
140 clDEBUG() << "Calling:" << cmd << endl;
141
142 async_format(cmd, wd, filepath, IsInplaceFormatter(), sink);
143 return true;
144 }
145
146 bool GenericFormatter::FormatFile(const wxString& filepath, wxEvtHandler* sink)
147 {
148 return DoFormatFile(filepath, sink, nullptr);
149 }
150
151 bool GenericFormatter::FormatString(const wxString& content, const wxString& fullpath, wxString* output)
152 {
153 auto file_type = FileExtManager::GetType(fullpath);
154 if(!CanHandle(file_type)) {
155 return false;
156 }
157
158 wxString fullpath_linux_style = fullpath;
159 fullpath_linux_style.Replace("\\", "/");
160
161 wxString dirpart = fullpath_linux_style.BeforeLast('/');
162 clTempFile tmpfile{ dirpart, "txt" };
163
164 if(!tmpfile.Write(content)) {
165 clWARNING() << "failed to write content to temp file:" << tmpfile.GetFullPath() << endl;
166 return false;
167 }
168
169 if(!DoFormatFile(tmpfile.GetFullPath(), nullptr, output)) {
170 return false;
171 }
172
173 if(IsInplaceFormatter()) {
174 // read the content of the temp file and return it
175 return FileUtils::ReadFileContent(tmpfile.GetFullPath(), *output);
176 }
177 return true;
178 }
179
180 void GenericFormatter::FromJSON(const JSONItem& json)
181 {
182 SourceFormatterBase::FromJSON(json);
183 m_command = json["command"].toArrayString();
184 m_workingDirectory = json["working_directory"].toString();
185 }
186
187 JSONItem GenericFormatter::ToJSON() const
188 {
189 auto json = SourceFormatterBase::ToJSON();
190 json.addProperty("command", m_command);
191 json.addProperty("working_directory", m_workingDirectory);
192 return json;
193 }
194
195 void GenericFormatter::SetCommand(const std::vector<wxString>& command) { SetCommand(to_wx_array(command)); }
196
197 void GenericFormatter::SetCommandFromString(const wxString& command)
198 {
199 SetCommand(StringUtils::BuildCommandArrayFromString(command));
200 }
201
202 wxString GenericFormatter::GetCommandWithComments() const { return get_command_with_desc(m_command, m_description); }
203
204 void GenericFormatter::SetRemoteCommand(const wxString& cmd) { m_remote_command = cmd; }
205
206 void GenericFormatter::OnAsyncShellProcessTerminated(clShellProcessEvent& event)
207 {
208 event.Skip();
209 if(m_pid_commands.count(event.GetPid()) == 0) {
210 clWARNING() << "Could not find command for process:" << event.GetPid() << endl;
211 return;
212 }
213
214 // remove the entry from the map
215 auto command_data = m_pid_commands[event.GetPid()];
216 m_pid_commands.erase(event.GetPid());
217
218 if(event.GetExitCode() != 0) {
219 wxString errmsg;
220 errmsg << wxT("\u26A0") << _(" format error. Process exit code: ") << event.GetExitCode();
221 clGetManager()->SetStatusMessage(errmsg, 3);
222 return;
223 }
224
225 // notify the sink that formatting is done
226 if(command_data.m_sink) {
227 clSourceFormatEvent format_completed_event{ IsInplaceFormatter() ? wxEVT_FORMAT_INPLACE_COMPELTED
228 : wxEVT_FORMAT_COMPELTED };
229 format_completed_event.SetFormattedString(IsInplaceFormatter() ? "" : event.GetOutput());
230 format_completed_event.SetFileName(command_data.m_filepath);
231 command_data.m_sink->QueueEvent(format_completed_event.Clone());
232 }
233 }