-
Notifications
You must be signed in to change notification settings - Fork 134
/
PySystemState.java
2196 lines (1936 loc) · 77.6 KB
/
PySystemState.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Corporation for National Research Initiatives
package org.python.core;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.python.Version;
import org.python.core.adapter.ClassicPyObjectAdapter;
import org.python.core.adapter.ExtensiblePyObjectAdapter;
import org.python.core.packagecache.PackageManager;
import org.python.core.packagecache.SysPackageManager;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedType;
import org.python.modules.Setup;
import org.python.util.Generic;
import com.carrotsearch.sizeof.RamUsageEstimator;
import jnr.posix.util.Platform;
import static org.python.core.RegistryKey.*;
/**
* The "sys" module.
*/
// xxx Many have lamented, this should really be a module!
// but it will require some refactoring to see this wish come true.
public class PySystemState extends PyObject
implements AutoCloseable, ClassDictInit, Closeable, Traverseproc {
private static final Logger logger = Logger.getLogger("org.python.core");
private static final String CACHEDIR_DEFAULT_NAME = ".jython_cache";
public static final String JYTHON_JAR = "jython.jar";
public static final String JYTHON_DEV_JAR = "jython-dev.jar";
public static final PyString version = new PyString(Version.getVersion());
public static final PyTuple subversion =
new PyTuple(new PyString("Jython"), Py.newString(""), Py.newString(""));
public static final int hexversion = ((Version.PY_MAJOR_VERSION << 24)
| (Version.PY_MINOR_VERSION << 16) | (Version.PY_MICRO_VERSION << 8)
| (Version.PY_RELEASE_LEVEL << 4) | (Version.PY_RELEASE_SERIAL << 0));
public static final PyVersionInfo version_info = getVersionInfo();
public static final int maxunicode = 1114111;
// XXX: we should someday make this Long.MAX_VALUE, but see test_index.py
// for tests that would need to pass but today would not.
public final static int maxsize = Integer.MAX_VALUE;
public final static PyString float_repr_style = Py.newString("short");
/** Nominal Jython file system encoding (as <code>sys.getfilesystemencoding()</code>) */
static final PyString FILE_SYSTEM_ENCODING = Py.newString("utf-8");
public static boolean py3kwarning = false;
public final static Class flags = Options.class;
public final static PyTuple _mercurial = new PyTuple(Py.newString("Jython"),
Py.newString(Version.getHGIdentifier()), Py.newString(Version.getHGVersion()));
/** The copyright notice for this release. */
public static final PyObject copyright =
Py.newString("Copyright (c) 2000-2017 Jython Developers.\n" + "All rights reserved.\n\n"
+ "Copyright (c) 2000 BeOpen.com.\n" + "All Rights Reserved.\n\n"
+ "Copyright (c) 2000 The Apache Software Foundation.\n"
+ "All rights reserved.\n\n"
+ "Copyright (c) 1995-2000 Corporation for National Research Initiatives.\n"
+ "All Rights Reserved.\n\n"
+ "Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\n"
+ "All Rights Reserved.");
private static Map<String, String> builtinNames;
public static PyTuple builtin_module_names = null;
public static PackageManager packageManager;
private static File cachedir;
private static PyList defaultPath; // list of bytes or unicode
private static PyList defaultArgv; // list of bytes or unicode
private static PyObject defaultExecutable; // bytes or unicode or None
public static Properties registry; // = init_registry();
/**
* A string giving the site-specific directory prefix where the platform independent Python
* files are installed; by default, this is based on the property <code>python.home</code> or
* the location of the Jython JAR. The main collection of Python library modules is installed in
* the directory <code>prefix/Lib</code>. This object should contain bytes in the file system
* encoding for consistency with use in the standard library (see <code>sysconfig.py</code>).
*/
public static PyObject prefix;
/**
* A string giving the site-specific directory prefix where the platform-dependent Python files
* are installed; by default, this is the same as {@link #exec_prefix}. This object should
* contain bytes in the file system encoding for consistency with use in the standard library
* (see <code>sysconfig.py</code>).
*/
public static PyObject exec_prefix;
public static final PyString byteorder = new PyString("big");
public static final int maxint = Integer.MAX_VALUE;
public static final int minint = Integer.MIN_VALUE;
private static boolean initialized = false;
/** The arguments passed to this program on the command line. */
public PyList argv = new PyList();
public PyObject modules;
public Map<String, PyModule> modules_reloading;
private ReentrantLock importLock;
private ClassLoader syspathJavaLoader;
public PyList path;
public PyList warnoptions = new PyList();
public PyObject builtins;
private static PyObject defaultPlatform = new PyShadowString("java", getNativePlatform());
public PyObject platform = defaultPlatform;
public PyList meta_path;
public PyList path_hooks;
public PyObject path_importer_cache;
// Only defined if interactive, see https://docs.python.org/2/library/sys.html#sys.ps1
public PyObject ps1 = PyAttributeDeleted.INSTANCE;
public PyObject ps2 = PyAttributeDeleted.INSTANCE;
public PyObject executable;
private String currentWorkingDir;
private ClassLoader classLoader = null;
public PyObject stdout, stderr, stdin;
public PyObject __stdout__, __stderr__, __stdin__;
public PyObject __displayhook__, __excepthook__;
public PyObject last_value = Py.None;
public PyObject last_type = Py.None;
public PyObject last_traceback = Py.None;
public PyObject __name__ = new PyString("sys");
public PyObject __dict__;
private int recursionlimit = 1000;
private int checkinterval = 100;
private codecs.CodecState codecState;
/** Whether bytecode should be written to disk on import. */
public boolean dont_write_bytecode = false;
// Automatically close resources associated with a PySystemState when they get GCed
private final PySystemStateCloser closer;
private static final ReferenceQueue<PySystemState> systemStateQueue =
new ReferenceQueue<PySystemState>();
private static final ConcurrentMap<WeakReference<PySystemState>, PySystemStateCloser> sysClosers =
Generic.concurrentMap();
// float_info
public static final PyObject float_info = FloatInfo.getInfo();
// long_info
public static final PyObject long_info = LongInfo.getInfo();
public PySystemState() {
initialize();
closer = new PySystemStateCloser(this);
modules = new PyStringMap();
modules_reloading = new HashMap<String, PyModule>();
importLock = new ReentrantLock();
syspathJavaLoader = new SyspathJavaLoader(imp.getParentClassLoader());
argv = (PyList) defaultArgv.repeat(1);
path = (PyList) defaultPath.repeat(1);
path.append(Py.newString(JavaImporter.JAVA_IMPORT_PATH_ENTRY));
path.append(Py.newString(ClasspathPyImporter.PYCLASSPATH_PREFIX));
executable = defaultExecutable;
builtins = getDefaultBuiltins();
platform = defaultPlatform;
meta_path = new PyList();
path_hooks = new PyList();
path_hooks.append(new JavaImporter());
path_hooks.append(org.python.modules.zipimport.zipimporter.TYPE);
path_hooks.append(ClasspathPyImporter.TYPE);
path_importer_cache = new PyDictionary();
currentWorkingDir = new File("").getAbsolutePath();
dont_write_bytecode = Options.dont_write_bytecode;
py3kwarning = Options.py3k_warning; // XXX why here if static?
// Set up the initial standard ins and outs
String mode = Options.unbuffered ? "b" : "";
int buffering = Options.unbuffered ? 0 : 1;
stdin = __stdin__ = new PyFile(System.in, "<stdin>", "r" + mode, buffering, false);
stdout = __stdout__ = new PyFile(System.out, "<stdout>", "w" + mode, buffering, false);
stderr = __stderr__ = new PyFile(System.err, "<stderr>", "w" + mode, 0, false);
initEncoding();
__displayhook__ = new PySystemStateFunctions("displayhook", 10, 1, 1);
__excepthook__ = new PySystemStateFunctions("excepthook", 30, 3, 3);
if (builtins == null) {
builtins = getDefaultBuiltins();
}
modules.__setitem__("__builtin__", new PyModule("__builtin__", getDefaultBuiltins()));
__dict__ = new PyStringMap();
__dict__.invoke("update", getType().fastGetDict());
__dict__.__setitem__("displayhook", __displayhook__);
__dict__.__setitem__("excepthook", __excepthook__);
logger.config("sys module instance created");
}
public static void classDictInit(PyObject dict) {
// XXX: Remove bean accessors for settrace/profile that we don't want
dict.__setitem__("trace", null);
dict.__setitem__("profile", null);
dict.__setitem__("windowsversion", null);
if (!System.getProperty("os.name").startsWith("Windows")) {
dict.__setitem__("getwindowsversion", null);
}
}
void reload() throws PyIgnoreMethodTag {
__dict__.invoke("update", getType().fastGetDict());
}
private static void checkReadOnly(String name) {
if (name == "__dict__" || name == "__class__" || name == "registry" || name == "exec_prefix"
|| name == "packageManager") {
throw Py.TypeError("readonly attribute");
}
}
private static void checkMustExist(String name) {
if (name == "__dict__" || name == "__class__" || name == "registry" || name == "exec_prefix"
|| name == "platform" || name == "packageManager" || name == "builtins"
|| name == "warnoptions") {
throw Py.TypeError("readonly attribute");
}
}
/**
* Initialise the encoding of <code>sys.stdin</code>, <code>sys.stdout</code>, and
* <code>sys.stderr</code>, and their error handling policy, from registry variables. Under the
* console app util.jython, values reflect PYTHONIOENCODING if not overridden. Note that the
* encoding must name a Python codec, as in <code>codecs.encode()</code>.
*/
private void initEncoding() {
// Two registry variables, counterparts to PYTHONIOENCODING = [encoding][:errors]
String encoding = registry.getProperty(PYTHON_IO_ENCODING);
String errors = registry.getProperty(PYTHON_IO_ERRORS);
if (encoding == null) {
// We still don't have an explicit selection for this: match the console.
encoding = Py.getConsole().getEncoding();
}
((PyFile) stdin).setEncoding(encoding, errors);
((PyFile) stdout).setEncoding(encoding, errors);
((PyFile) stderr).setEncoding(encoding, "backslashreplace");
}
@Deprecated
public void shadow() {
// Now a no-op
}
private static class DefaultBuiltinsHolder {
static final PyObject builtins = fillin();
static PyObject fillin() {
PyObject temp = new PyStringMap();
__builtin__.fillWithBuiltins(temp);
return temp;
}
}
public static PyObject getDefaultBuiltins() {
return DefaultBuiltinsHolder.builtins;
}
public PyObject getBuiltins() {
return builtins;
}
public void setBuiltins(PyObject value) {
builtins = value;
modules.__setitem__("__builtin__", new PyModule("__builtin__", value));
}
public PyObject getWarnoptions() {
return warnoptions;
}
public void setWarnoptions(PyObject value) {
warnoptions = new PyList(value);
}
public PyObject getPlatform() {
return platform;
}
public void setPlatform(PyObject value) {
platform = value;
}
public WinVersion getwindowsversion() {
return WinVersion.getWinVersion();
}
public synchronized codecs.CodecState getCodecState() {
if (codecState == null) {
codecState = new codecs.CodecState();
try {
imp.load("encodings");
} catch (PyException exc) {
if (exc.type != Py.ImportError) {
throw exc;
}
}
}
return codecState;
}
public ReentrantLock getImportLock() {
return importLock;
}
public ClassLoader getSyspathJavaLoader() {
return syspathJavaLoader;
}
// xxx fix this accessors
@Override
public PyObject __findattr_ex__(String name) {
if (name == "exc_value") {
PyException exc = Py.getThreadState().exception;
if (exc == null) {
return null;
}
return exc.value;
} else if (name == "exc_type") {
PyException exc = Py.getThreadState().exception;
if (exc == null) {
return null;
}
return exc.type;
} else if (name == "exc_traceback") {
PyException exc = Py.getThreadState().exception;
if (exc == null) {
return null;
}
return exc.traceback;
} else {
PyObject ret = super.__findattr_ex__(name);
if (ret != null) {
if (ret instanceof PyMethod) {
if (__dict__.__finditem__(name) instanceof PyReflectedFunction) {
return ret; // xxx depends on nonstandard __dict__
}
} else if (ret == PyAttributeDeleted.INSTANCE) {
return null;
} else {
return ret;
}
}
return __dict__.__finditem__(name);
}
}
@Override
public void __setattr__(String name, PyObject value) {
checkReadOnly(name);
if (name == "builtins") {
setBuiltins(value);
} else {
PyObject ret = getType().lookup(name); // xxx fix fix fix
if (ret != null && ret._doset(this, value)) {
return;
}
__dict__.__setitem__(name, value);
}
}
@Override
public void __delattr__(String name) {
checkMustExist(name);
PyObject ret = getType().lookup(name); // xxx fix fix fix
if (ret != null) {
ret._doset(this, PyAttributeDeleted.INSTANCE);
}
try {
__dict__.__delitem__(name);
} catch (PyException pye) { // KeyError
if (ret == null) {
throw Py.AttributeError(name);
}
}
}
// xxx
@Override
public void __rawdir__(PyDictionary accum) {
accum.update(__dict__);
}
@Override
public String toString() {
return "<module '" + __name__ + "' (built-in)>";
}
public int getrecursionlimit() {
return recursionlimit;
}
@SuppressWarnings("unused")
public long getsizeof(Object obj, long defaultVal) {
return getsizeof(obj);
}
public long getsizeof(Object obj) {
return RamUsageEstimator.shallowSizeOf(obj);
}
public void setrecursionlimit(int recursionlimit) {
if (recursionlimit <= 0) {
throw Py.ValueError("Recursion limit must be positive");
}
this.recursionlimit = recursionlimit;
}
public PyObject gettrace() {
ThreadState ts = Py.getThreadState();
if (ts.tracefunc == null) {
return Py.None;
} else {
return ((PythonTraceFunction) ts.tracefunc).tracefunc;
}
}
public void settrace(PyObject tracefunc) {
ThreadState ts = Py.getThreadState();
if (tracefunc == Py.None) {
ts.tracefunc = null;
} else {
ts.tracefunc = new PythonTraceFunction(tracefunc);
}
}
public PyObject getprofile() {
ThreadState ts = Py.getThreadState();
if (ts.profilefunc == null) {
return Py.None;
} else {
return ((PythonTraceFunction) ts.profilefunc).tracefunc;
}
}
public void setprofile(PyObject profilefunc) {
ThreadState ts = Py.getThreadState();
if (profilefunc == Py.None) {
ts.profilefunc = null;
} else {
ts.profilefunc = new PythonTraceFunction(profilefunc);
}
}
public PyString getdefaultencoding() {
return new PyString(codecs.getDefaultEncoding());
}
public void setdefaultencoding(String encoding) {
codecs.setDefaultEncoding(encoding);
}
public PyObject getfilesystemencoding() {
return FILE_SYSTEM_ENCODING;
}
/* get and setcheckinterval really do nothing, but it helps when some code tries to use these */
public PyInteger getcheckinterval() {
return new PyInteger(checkinterval);
}
public void setcheckinterval(int interval) {
checkinterval = interval;
}
/**
* Change the current working directory to the specified path.
*
* path is assumed to be absolute and canonical (via os.path.realpath).
*
* @param path a path String
*/
public void setCurrentWorkingDir(String path) {
currentWorkingDir = path;
}
/**
* Return a string representing the current working directory.
*
* @return a path String
*/
public String getCurrentWorkingDir() {
return currentWorkingDir;
}
/**
* Resolve a path. Returns the full path taking the current working directory into account.
*
* @param path a path String
* @return a resolved path String
*/
public String getPath(String path) {
return getPath(this, path);
}
/**
* Resolve a path. Returns the full path taking the current working directory into account.
*
* Like getPath but called statically. The current PySystemState is only consulted for the
* current working directory when it's necessary (when the path is relative).
*
* @param path a path String
* @return a resolved path String
*/
public static String getPathLazy(String path) {
// XXX: This method likely an unnecessary optimization
return getPath(null, path);
}
private static String getPath(PySystemState sys, String path) {
if (path != null) {
path = getFile(sys, path).getAbsolutePath();
}
return path;
}
/**
* Resolve a path, returning a {@link File}, taking the current working directory into account.
*
* @param path a path <code>String</code>
* @return a resolved <code>File</code>
*/
public File getFile(String path) {
return getFile(this, path);
}
/**
* Resolve a path, returning a {@link File}, taking the current working directory of the
* specified <code>PySystemState</code> into account. Use of a <code>static</code> here is a
* trick to avoid getting the current state if the path is absolute. (Noted that this may be
* needless optimisation.)
*
* @param sys a <code>PySystemState</code> or null meaning the current one
* @param path a path <code>String</code>
* @return a resolved <code>File</code>
*/
private static File getFile(PySystemState sys, String path) {
File file = new File(path);
if (!file.isAbsolute()) {
// path meaning depends on the current working directory
if (sys == null) {
sys = Py.getSystemState();
}
String cwd = sys.getCurrentWorkingDir();
if (Platform.IS_WINDOWS) {
// Form absolute reference (with mysterious Windows semantics)
file = getWindowsFile(cwd, path);
} else {
// Form absolute reference (with single slash)
file = new File(cwd, path);
}
}
return file;
}
/**
* Resolve a relative path against the supplied current working directory or Windows environment
* working directory for any drive specified in the path. and return a file object. Essentially
* equivalent to os.path.join, but the work is done by {@link File}. The intention is that
* calling {@link File#getAbsolutePath()} should return the corresponding absolute path.
* <p>
* Note: in the context where we use this method, <code>path</code> is already known not to be
* absolute, and <code>cwd</code> is assumed to be absolute.
*
* @param cwd current working directory (of some {@link PySystemState})
* @param path to resolve
* @return specifier of the intended file
*/
private static File getWindowsFile(String cwd, String path) {
// Assumptions: cwd is absolute and path is not absolute
// Start by getting the slashes the right (wrong) way round.
if (path.indexOf('/') >= 0) {
path = path.replace('/', '\\');
}
// Does path start with a drive letter?
char d = driveLetter(path);
if (d != 0) {
if (d == driveLetter(cwd)) {
/*
* path specifies the same drive letter as in the cwd of this PySystemState. Let
* File interpret the rest of the path relative to cwd as parent.
*/
return new File(cwd, path.substring(2));
} else {
// Let File resolve the specified drive against the process environment.
return new File(path);
}
} else if (path.startsWith("\\")) {
// path replaces the file part of the cwd. (Method assumes path is not UNC.)
if (driveLetter(cwd) != 0) {
// cwd has a drive letter
return new File(cwd.substring(0, 2), path);
} else {
// cwd has no drive letter, so should be a UNC path \\host\share\directory\etc
return new File(uncShare(cwd), path);
}
} else {
// path is relative to the cwd of this PySystemState.
return new File(cwd, path);
}
}
/**
* Return the Windows drive letter from the start of the path, upper case, or 0 if the path does
* not start X: where X is a letter.
*
* @param path to examine
* @return drive letter or char 0 if no drive letter
*/
private static char driveLetter(String path) {
if (path.length() >= 2 && path.charAt(1) == ':') {
// Looks like both strings start with a drive letter
char pathDrive = path.charAt(0);
if (Character.isLetter(pathDrive)) {
return Character.toUpperCase(pathDrive);
}
}
return (char) 0;
}
/**
* Return the Windows UNC share name from the start of the path, or <code>null</code> if the
* path is not of Windows UNC type. The path has to be formed with Windows-backslashes: slashes
* '/' are not accepted as a substitute here.
*
* @param path to examine
* @return share name or null
*/
private static String uncShare(String path) {
int n = path.length();
// Has to accommodate at least \\A (3 chars)
if (n >= 5 && path.startsWith("\\\\")) {
// Look for the separator backslash A\B
int p = path.indexOf('\\', 2);
// Has to be at least index 3 (path begins \\A) and 2 more characters left \B
if (p >= 3 && n > p + 2) {
// Look for directory backslash that ends the share name
int dir = path.indexOf('\\', p + 1);
if (dir < 0) {
// path has the form \\A\B (is just the share name)
return path;
} else if (dir > p + 1) {
// path has the form \\A\B\C
return path.substring(0, dir);
}
}
}
return null;
}
public void callExitFunc() throws PyIgnoreMethodTag {
PyObject exitfunc = __findattr__("exitfunc");
if (exitfunc != null) {
try {
exitfunc.__call__();
} catch (PyException exc) {
if (!exc.match(Py.SystemExit)) {
Py.println(stderr, Py.newString("Error in sys.exitfunc:"));
}
Py.printException(exc);
}
}
Py.flushLine();
}
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Work out the root directory of the installation of Jython. Sources for this information are
* quite diverse. {@code python.home} will take precedence if set in either
* {@code postProperties} or {@code preProperties}, {@code install.root} in
* {@code preProperties}, in that order. After this, we search the class path for a JAR, or
* nagigate from the JAR deduced by from the class path, or finally {@code jarFileName}.
* <p>
* We also set by side-effect: {@link #defaultPlatform} from {@code java.version}.
*/
private static String findRoot(Properties preProperties, Properties postProperties,
String jarFileName) {
String root = null;
try {
if (postProperties != null) {
root = postProperties.getProperty("python.home");
}
if (root == null) {
root = preProperties.getProperty("python.home");
}
if (root == null) {
root = preProperties.getProperty("install.root");
}
determinePlatform(preProperties);
} catch (Exception exc) {
return null;
}
// If install.root is undefined find JYTHON_JAR in class.path
if (root == null || root.equals("")) {
String classpath = preProperties.getProperty("java.class.path");
if (classpath != null) {
String lowerCaseClasspath = classpath.toLowerCase();
int jarIndex = lowerCaseClasspath.indexOf(JYTHON_JAR);
if (jarIndex < 0) {
jarIndex = lowerCaseClasspath.indexOf(JYTHON_DEV_JAR);
}
if (jarIndex >= 0) {
int start = classpath.lastIndexOf(File.pathSeparator, jarIndex) + 1;
root = classpath.substring(start, jarIndex);
} else if (jarFileName != null) {
// in case JYTHON_JAR is referenced from a MANIFEST inside another jar on the
// classpath
root = new File(jarFileName).getParent();
}
}
}
if (root == null) {
return null;
}
File rootFile = new File(root);
try {
return rootFile.getCanonicalPath();
} catch (IOException ioe) {
return rootFile.getAbsolutePath();
}
}
/** Set {@link #defaultPlatform} by examination of the {@code java.version} JVM property. */
private static void determinePlatform(Properties props) {
String version = props.getProperty("java.version");
if (version == null) {
version = "???";
}
String lversion = version.toLowerCase();
if (lversion.startsWith("java")) {
version = version.substring(4, version.length());
}
if (lversion.startsWith("jdk") || lversion.startsWith("jre")) {
version = version.substring(3, version.length());
}
if (version.equals("12")) {
version = "1.2";
}
defaultPlatform = new PyShadowString("java" + version, getNativePlatform());
}
/**
* Emulates CPython's way to name sys.platform. Works according to this table:
*
* <table>
* <caption>Platform names</caption>
* <tr>
* <th style="text-align:left">System</th>
* <th style="text-align:left">Value</th>
* </tr>
* <tr>
* <td>Linux (2.x and 3.x)</td>
* <td>linux2</td>
* </tr>
* <tr>
* <td>Windows</td>
* <td>win32</td>
* </tr>
* <tr>
* <td>Windows/Cygwin</td>
* <td>cygwin</td>
* </tr>
* <tr>
* <td>Mac OS X</td>
* <td>darwin</td>
* </tr>
* <tr>
* <td>OS/2</td>
* <td>os2</td>
* </tr>
* <tr>
* <td>OS/2 EMX</td>
* <td>os2emx</td>
* </tr>
* <tr>
* <td>RiscOS</td>
* <td>riscos</td>
* </tr>
* <tr>
* <td>AtheOS</td>
* <td>atheos</td>
* </tr>
* </table>
*
*/
public static String getNativePlatform() {
String osname = System.getProperty("os.name");
if (osname.equals("Linux")) {
return "linux2";
} else if (osname.equals("Mac OS X")) {
return "darwin";
} else if (osname.toLowerCase().contains("cygwin")) {
return "cygwin";
} else if (osname.startsWith("Windows")) {
return "win32";
} else {
return osname.replaceAll("[\\s/]", "").toLowerCase();
}
}
/**
* Install the first argument as the application-wide {@link #registry} (a
* {@code java.util.Properties} object), merge values from system and local (or user) properties
* files, and finally allow values from {@code postProperties} to override. Usually the first
* argument is the {@code System.getProperties()}, if were allowed to access it, and therefore
* represents definitions made on the command-line. The net precedence order is:
* <table>
* <caption>Precedence order of registry sources</caption>
* <tr>
* <th>Source</th>
* <th>Filled by</th>
* </tr>
* <tr>
* <td>postProperties</td>
* <td>Custom {@link JythonInitializer}</td>
* </tr>
* <tr>
* <td>preProperties</td>
* <td>Command-line definitions {@code -Dkey=value})</td>
* </tr>
* <tr>
* <td>... preProperties also contains ...</td>
* <td>Environment variables via {@link org.python.util.jython}</td>
* </tr>
* <tr>
* <td>[user.home]/.jython</td>
* <td>User-specific registry file</td>
* </tr>
* <tr>
* <td>[python.home]/registry</td>
* <td>Installation-wide registry file</td>
* </tr>
* <tr>
* <td>Environmental inference</td>
* <td>e.g. {@code locale} command for console encoding</td>
* </tr>
* </table>
* <p>
* We call {@link Options#setFromRegistry()} to translate certain final values to
* application-wide controls. By side-effect, set {@link #prefix} and {@link #exec_prefix} from
* {@link #findRoot(Properties, Properties, String)}. If it has not been set otherwise, a
* default value for python.console.encoding is derived from the OS environment, via
* {@link #getConsoleEncoding(Properties)}.
*
* @param preProperties initial registry
* @param postProperties overriding values
* @param standalone default {@code python.cachedir.skip} to true (if not otherwise defined)
* @param jarFileName as a clue to the location of the installation
*/
private static void initRegistry(Properties preProperties, Properties postProperties,
boolean standalone, String jarFileName) {
if (registry != null) {
Py.writeError("systemState", "trying to reinitialize registry");
return;
}
registry = preProperties;
// Work out sys.prefix
String prefix = findRoot(preProperties, postProperties, jarFileName);
if (prefix == null || prefix.length() == 0) {
/*
* All strategies in find_root failed (can happen in embedded use), but sys.prefix is
* generally assumed not to be null (or even None). Go for current directory.
*/
prefix = ".";
logger.config("No property 'jython.home' or other clue. sys.prefix defaulting to ''.");
}
// sys.exec_prefix is the same initially
String exec_prefix = prefix;
// Load the default registry
try {
// user registry has precedence over installed registry
File homeFile = new File(registry.getProperty(USER_HOME), ".jython");
addRegistryFile(homeFile);
addRegistryFile(new File(prefix, "registry"));
} catch (Exception exc) {
// Continue: addRegistryFile does its own logging.
}
// Exposed values have to be properly-encoded objects
PySystemState.prefix = Py.fileSystemEncode(prefix);
PySystemState.exec_prefix = Py.fileSystemEncode(exec_prefix);
// Now the post properties (possibly set by custom JythonInitializer).
registry.putAll(postProperties);
if (standalone) {
// set default standalone property (if not yet set)
if (!registry.containsKey(PYTHON_CACHEDIR_SKIP)) {
registry.put(PYTHON_CACHEDIR_SKIP, "true");
}
}
/*
* The console encoding is the one used by line-editing consoles to decode on the OS side
* and encode on the Python side. It must be a Java codec name, so any relationship to
* python.io.encoding is dubious.
*/
if (!registry.containsKey(PYTHON_CONSOLE_ENCODING)) {
registry.put(PYTHON_CONSOLE_ENCODING, getConsoleEncoding(registry));
}
// Set up options from registry
Options.setFromRegistry();
}
/**
* Try to determine the console encoding from the platform, if necessary using a sub-process to
* enquire. If everything fails, assume UTF-8.
*
* @param props in which to look for clues (normally the Jython registry)
* @return the console encoding (and never {@code null})
*/
private static String getConsoleEncoding(Properties props) {
// From Java 8 onwards, the answer may already be to hand in the registry:
String encoding = props.getProperty("sun.stdout.encoding");
String os = props.getProperty("os.name");