This repository has been archived by the owner on Mar 25, 2019. It is now read-only.
/
ConvertProject.java
188 lines (164 loc) · 8.57 KB
/
ConvertProject.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package xyz.elmot.clion.cubemx;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.cidr.cpp.cmake.CMakeSettings;
import com.jetbrains.cidr.cpp.cmake.workspace.CMakeWorkspace;
import org.apache.commons.lang.text.StrSubstitutor;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* (c) elmot on 27.9.2017.
*/
public class ConvertProject extends AnAction {
//TODO CubeMX run
//Todo generate run configuration automatically
//todo FPU support flag
private static final String DEFINES_KEY = "gnu.c.compiler.option.preprocessor.def.symbols";
private static final String CONFIG_DEBUG_XPATH = ".//configuration[@artifactExtension='elf' and @name='Debug']";
private static final String DEFINES_XPATH = CONFIG_DEBUG_XPATH + "//*[@superClass='" + DEFINES_KEY + "']/listOptionValue/@value";
private static final String INCLUDES_KEY = "gnu.c.compiler.option.include.paths";
private static final String INCLUDES_XPATH = CONFIG_DEBUG_XPATH + "//*[@superClass='" + INCLUDES_KEY + "']/listOptionValue/@value";
private static final String SOURCE_XPATH = CONFIG_DEBUG_XPATH + "//sourceEntries/entry/@name";
private static final String DCMAKE_TOOLCHAIN_FILE = "-DCMAKE_TOOLCHAIN_FILE=";
public ConvertProject() {
super("Update CLion from STM32CubeMX project");
}
@Override
public void actionPerformed(AnActionEvent event) {
Project project = getEventProject(event);
if (project == null) return;
Context context = new Context(detectAndLoadFile(project, ".cproject"));
Document dotProject = detectAndLoadFile(project, ".project");
ProjectData projectData = new ProjectData();
//noinspection ConstantConditions
projectData.setProjectName(dotProject.getRootElement().getChild("name").getText());
try {
String linkerScript = fetchValueBySuperClass(context, "fr.ac6.managedbuild.tool.gnu.cross.c.linker.script");
projectData.setLinkerScript(linkerScript.replace("../", ""));
projectData.setMcuFamily(fetchValueBySuperClass(context, "fr.ac6.managedbuild.option.gnu.cross.mcu"));
projectData.setLinkerFlags(fetchValueBySuperClass(context, "gnu.c.link.option.ldflags"));
projectData.setDefines(loadDefines(context));
projectData.setIncludes(loadIncludes(context));
projectData.setSources(loadSources(context));
} catch (JDOMException e) {
Messages.showErrorDialog(project, "Xml data error", String.format("XML data retrieval error\n Key: %s ", context.currentKey));
}
modifyCMakeConfigs(project, projectData);
writeProjectFile(project, "tmpl_toolset.txt", projectData.getCmakeFileName(), projectData);
writeProjectFile(project, "tmpl_CMakeLists.txt", "CMakeLists.txt", projectData);
writeProjectFile(project, "tmpl_gitignore.txt", ".gitignore", projectData);
CMakeWorkspace.getInstance(project).scheduleClearGeneratedFilesAndReload();
Messages.showInfoMessage(project, projectData.toString(), "Project Info");
}
@Override
public boolean startInTransaction() {
return super.startInTransaction();
}
private void writeProjectFile(Project project, String templateName, String fileName, ProjectData projectData) {
Application application = ApplicationManager.getApplication();
application.runWriteAction(() -> {
try {
VirtualFile childData = project.getBaseDir().findOrCreateChildData(this, fileName);
try (OutputStream outputStream = childData.getOutputStream(this);
OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.US_ASCII)) {
String template = FileUtil.loadTextAndClose(ConvertProject.class.getResourceAsStream(templateName));
String text = new StrSubstitutor(projectData.getAsMap()).replace(template);
writer.write(text);
}
} catch (IOException e) {
application.invokeLater(() ->
Messages.showErrorDialog(project, String.format("%s:\n %s ", fileName, e.getLocalizedMessage()), "File Write Error"));
}
}
);
}
private void modifyCMakeConfigs(Project project, ProjectData projectData) {
CMakeSettings component = project.getComponent(CMakeSettings.class);
List<CMakeSettings.Configuration> configurations = component.getConfigurations();
ArrayList<CMakeSettings.Configuration> newConfigs = new ArrayList<>(configurations.size());
for (CMakeSettings.Configuration configuration : configurations) {
String options = Objects.toString(configuration.getGenerationOptions(), "");
options = options.replaceAll(DCMAKE_TOOLCHAIN_FILE + "[^\\s]*", "").trim();
String newOptions = DCMAKE_TOOLCHAIN_FILE + projectData.getCmakeFileName();
if (!options.isEmpty()) newOptions += " " + options;
newConfigs.add(configuration.withGenerationOptions(newOptions));
}
component.setConfigurations(newConfigs);
}
private String loadIncludes(Context context) throws JDOMException {
context.currentKey = INCLUDES_KEY;
@SuppressWarnings("unchecked")
List<Attribute> list = XPath.selectNodes(context.cProject, INCLUDES_XPATH);
return list.stream()
.map(Attribute::getValue)
.map(s -> s.replace("../", ""))
.collect(Collectors.joining(" "));
}
private String loadSources(Context context) throws JDOMException {
context.currentKey = SOURCE_XPATH;
@SuppressWarnings("unchecked")
List<Attribute> list = XPath.selectNodes(context.cProject, SOURCE_XPATH);
return list.stream()
.map(Attribute::getValue)
.map(s -> "\"" + s + "/*.*\"")
.collect(Collectors.joining(" "));
}
private String loadDefines(Context context) throws JDOMException {
context.currentKey = DEFINES_KEY;
@SuppressWarnings("unchecked")
List<Attribute> list = XPath.selectNodes(context.cProject, DEFINES_XPATH);
return list.stream()
.map(Attribute::getValue)
.map(s -> "-D" + s
.replace("\"", "")
.replace("(", "\\(")
.replace(")", "\\)")
.replace("//", "////"))
.collect(Collectors.joining(" "));
}
private String fetchValueBySuperClass(Context context, String key) throws JDOMException {
context.currentKey = key;
return ((Attribute) XPath.selectSingleNode(context.cProject, ".//*[@superClass='" + key + "']/@value")).getValue();
}
private Document detectAndLoadFile(Project project, String fileName) {
VirtualFile child = project.getBaseDir().findChild(fileName);
if (child == null || !child.exists() || child.isDirectory()) {
Messages.showErrorDialog("File not found",
String.format("File %s is not found in the project directory %s", fileName, project.getBasePath()));
return null;
}
try (InputStream inputStream = child.getInputStream()) {
SAXBuilder saxBuilder = new SAXBuilder();
return saxBuilder.build(inputStream);
} catch (IOException | JDOMException e) {
Messages.showErrorDialog("File Read error",
String.format("Failed to read %s in project directory %s\n(%s)", fileName, project.getBasePath(), e.getLocalizedMessage()));
return null;
}
}
private static class Context {
final Document cProject;
String currentKey;
Context(Document cProject) {
this.cProject = cProject;
}
}
}