forked from consulo/consulo-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildoutFacet.java
More file actions
340 lines (315 loc) · 11.4 KB
/
Copy pathBuildoutFacet.java
File metadata and controls
340 lines (315 loc) · 11.4 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.impl.buildout;
import org.jspecify.annotations.Nullable;
/**
* Facet for buildout support.
* Knows which script in bin/ contains paths we want to add.
* @author dcheryasov
* @since 2010-07-25
*/
public class BuildoutFacet /*extends Facet<BuildoutFacetConfiguration> implements PythonPathContributingFacet, LibraryContributingFacet */{
/* private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.buildout.BuildoutFacet");
@NonNls public static final String BUILDOUT_CFG = "buildout.cfg";
@NonNls public static final String SCRIPT_SUFFIX = "-script";
private static final String BUILDOUT_LIB_NAME = "Buildout Eggs";
public BuildoutFacet(@NotNull final FacetType facetType,
@NotNull final Module module,
@NotNull final String name,
@NotNull final BuildoutFacetConfiguration configuration, Facet underlyingFacet) {
super(facetType, module, name, configuration, underlyingFacet);
VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
@Override
public void contentsChanged(VirtualFileEvent event) {
if (Comparing.equal(event.getFile(), getScript())) {
updatePaths();
attachLibrary(module);
}
}
}, this);
}
@Nullable
public static VirtualFile getRunner(VirtualFile baseDir) {
if (baseDir == null) return null;
final VirtualFile cfg = baseDir.findChild(BUILDOUT_CFG);
if (cfg != null && !cfg.isDirectory()) {
VirtualFile eggs = baseDir.findChild("eggs");
if (eggs != null && eggs.isDirectory()) {
VirtualFile bin = baseDir.findChild("bin");
if (bin != null && bin.isDirectory()) {
if (ApplicationManager.getApplication().isDispatchThread() || !ApplicationManager.getApplication().isReadAccessAllowed()) {
bin.refresh(false, false);
}
final String exe;
if (SystemInfo.isWindows || SystemInfo.isOS2) {
exe = "buildout.exe";
}
else {
exe = "buildout";
}
VirtualFile runner = bin.findChild(exe);
if (runner != null && !runner.isDirectory()) {
return runner;
}
}
}
}
return null;
}
/**
* Generates a <code>sys.path[0:0] = [...]</code> with paths that buildout script wants.
*
* @param additionalPythonPath
* @param module to get a buildout facet from
* @return the statement, or null if there's no buildout facet.
*/
/* @Nullable
public String getPathPrependStatement(List<String> additionalPythonPath) {
StringBuilder sb = new StringBuilder("sys.path[0:0]=[");
for (String s : additionalPythonPath) {
sb.append("'").append(s).append("',");
// NOTE: we assume that quotes and spaces are escaped in paths back in the buildout script we extracted them from.
}
sb.append("]");
return sb.toString();
}
@Override
public void initFacet() {
updateLibrary();
}
@Override
public void updateLibrary() {
updatePaths();
attachLibrary(getModule());
}
@Override
public void removeLibrary() {
detachLibrary(getModule());
}
public void updatePaths() {
BuildoutFacetConfiguration config = getConfiguration();
final VirtualFile script = getScript();
if (script != null) {
config.setPaths(extractBuildoutPaths(script));
}
}
@Nullable
public VirtualFile getScript() {
return LocalFileSystem.getInstance().findFileByPath(getConfiguration().getScriptName());
}
@Nullable
public static List<String> extractBuildoutPaths(@NotNull VirtualFile script) {
try {
List<String> paths = extractFromScript(script);
if (paths == null) {
VirtualFile root = script.getParent().getParent();
String partName = FileUtil.getNameWithoutExtension(script.getName());
if (SystemInfo.isWindows && partName.endsWith(SCRIPT_SUFFIX)) {
partName = partName.substring(0, partName.length() - SCRIPT_SUFFIX.length());
}
VirtualFile sitePy = root.findFileByRelativePath("parts/" + partName + "/site.py");
if (sitePy != null) {
paths = extractFromSitePy(sitePy);
}
}
return paths;
}
catch (IOException e) {
LOG.info(e);
return null;
}
}
/**
* Extracts paths from given script, assuming sys.path[0:0] assignment.
*
* @param script
* @return extracted paths, or null if extraction fails.
*/
/* @Nullable
public static List<String> extractFromScript(@NotNull VirtualFile script) throws IOException {
String text = VirtualFileUtil.loadText(script);
Pattern pat = Pattern.compile("(?:^\\s*(['\"])(.*)(\\1),\\s*$)|(\\])", Pattern.MULTILINE);
final String bait_string = "sys.path[0:0]";
int pos = text.indexOf(bait_string);
List<String> ret = null;
if (pos >= 0) {
pos += bait_string.length();
Matcher scanner = pat.matcher(text);
while (scanner.find(pos)) {
String value = scanner.group(2);
if (value != null) {
if (ret == null) {
ret = new ArrayList<String>();
}
ret.add(value);
pos = scanner.end();
}
else {
break;
} // we've matched the ']', it's group(4)
}
}
return ret;
}
*/
/**
* Extracts paths from site.py generated by buildout 1.5+
*
* @param vFile path to site.py
* @return extracted paths
*/
/*public static List<String> extractFromSitePy(VirtualFile vFile) throws IOException {
List<String> result = new ArrayList<String>();
String text = VirtualFileUtil.loadText(vFile);
String[] lines = LineTokenizer.tokenize(text, false);
int index = 0;
while (index < lines.length && !lines[index].startsWith("def addsitepackages(")) {
index++;
}
while (index < lines.length && !lines[index].trim().startsWith("buildout_paths = [")) {
index++;
}
index++;
while (index < lines.length && !lines[index].trim().equals("]")) {
String line = lines[index].trim();
if (line.endsWith(",")) {
line = line.substring(0, line.length() - 1);
}
if (StringEscapeUtil.isQuoted(line, '\'')) {
result.add(StringEscapeUtil.unescape(line, 1, line.length() - 1));
}
index++;
}
return result;
}
@Override
public List<String> getAdditionalPythonPath() {
BuildoutFacetConfiguration cfg = getConfiguration();
return cfg.getPaths();
}
@Override
public boolean acceptRootAsTopLevelPackage() {
return false;
}
@Nullable
public static BuildoutFacet getInstance(Module module) {
return FacetManager.getInstance(module).getFacetByType(BuildoutFacetType.ID);
} */
/*
public void patchCommandLineForBuildout(GeneralCommandLine commandLine) {
Map<String, String> env = commandLine.getEnvironment();
ParametersList params = commandLine.getParametersList();
// alter execution script
ParamsGroup script_params = params.getParamsGroup(PythonCommandLineState.GROUP_SCRIPT);
assert script_params != null;
if (script_params.getParameters().size() > 0) {
String normal_script = script_params.getParameters().get(0); // expect DjangoUtil.MANAGE_FILE
String engulfer_path = PythonHelpersLocator.getHelperPath("pycharm/buildout_engulfer.py");
env.put("PYCHARM_ENGULF_SCRIPT", getConfiguration().getScriptName());
script_params.getParametersList().replaceOrPrepend(normal_script, engulfer_path);
}
// add pycharm helpers to pythonpath so that fixGetpass is importable
PythonEnvUtil.addToPythonPath(env, PythonHelpersLocator.getHelpersRoot().getAbsolutePath());
/*
// set prependable paths
List<String> paths = facet.getAdditionalPythonPath();
if (paths != null) {
path_value = PyUtil.joinWith(File.pathSeparator, paths);
env.put("PYCHARM_PREPEND_SYSPATH", path_value);
}
*/
/* }
@Nullable
public File getConfigFile() {
final String scriptName = getConfiguration().getScriptName();
if (!StringUtil.isEmpty(scriptName)) {
return new File(new File(scriptName).getParentFile().getParentFile(), BUILDOUT_CFG);
}
return null;
}
@Nullable
public BuildoutCfgFile getConfigPsiFile() {
File cfg = getConfigFile();
if (cfg != null && cfg.exists()) {
try {
// this method is called before the project initialization is complete, so it has to use createFileFromText() instead
// of PsiManager.findFile()
String text = FileUtil.loadFile(cfg);
final PsiFile configFile = PsiFileFactory
.getInstance(getModule().getProject()).createFileFromText("buildout.cfg",
BuildoutCfgLanguage.INSTANCE, text);
if (configFile != null && configFile instanceof BuildoutCfgFile) {
return (BuildoutCfgFile)configFile;
}
}
catch (Exception ignored) {
}
}
return null;
}
public static List<File> getScripts(@Nullable BuildoutFacet buildoutFacet, final VirtualFile baseDir) {
File rootPath = null;
if (buildoutFacet != null) {
final File configIOFile = buildoutFacet.getConfigFile();
if (configIOFile != null) {
rootPath = configIOFile.getParentFile();
}
}
if (rootPath == null || !rootPath.exists()) {
if (baseDir != null) {
rootPath = new File(baseDir.getPath());
}
}
if (rootPath != null) {
final File[] scripts = new File(rootPath, "bin").listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (SystemInfo.isWindows) {
return name.endsWith("-script.py");
}
String ext = FileUtilRt.getExtension(name);
return ext.length() == 0 || FileUtil.namesEqual(ext, "py");
}
});
if (scripts != null) {
return Arrays.asList(scripts);
}
}
return Collections.emptyList();
}
@Nullable
public static File findScript(@Nullable BuildoutFacet buildoutFacet, String name, final VirtualFile baseDir) {
String scriptName = SystemInfo.isWindows ? name + SCRIPT_SUFFIX : name;
final List<File> scripts = getScripts(buildoutFacet, baseDir);
for (File script : scripts) {
if (FileUtil.getNameWithoutExtension(script.getName()).equals(scriptName)) {
return script;
}
}
return null;
}
public static void attachLibrary(final Module module) {
final BuildoutFacet facet = getInstance(module);
if (facet == null) {
return;
}
final List<String> paths = facet.getConfiguration().getPaths();
FacetLibraryConfigurator.attachLibrary(module, null, BUILDOUT_LIB_NAME, paths);
}
public static void detachLibrary(final Module module) {
FacetLibraryConfigurator.detachLibrary(module, BUILDOUT_LIB_NAME);
} */
}