forked from jruby/jruby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRubyFile.java
More file actions
1914 lines (1629 loc) · 74.8 KB
/
Copy pathRubyFile.java
File metadata and controls
1914 lines (1629 loc) · 74.8 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
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
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.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.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2003 Joey Gibson <joey@joeygibson.com>
* Copyright (C) 2004-2007 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2007 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import jnr.constants.platform.OpenFlags;
import org.jcodings.Encoding;
import org.jruby.util.io.OpenFile;
import org.jruby.util.io.ChannelDescriptor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.jcodings.specific.ASCIIEncoding;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import jnr.posix.FileStat;
import jnr.posix.util.Platform;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import static org.jruby.runtime.Visibility.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.encoding.EncodingCapable;
import org.jruby.util.ByteList;
import org.jruby.util.io.DirectoryAsFileException;
import org.jruby.util.io.PermissionDeniedException;
import org.jruby.util.io.Stream;
import org.jruby.util.io.ChannelStream;
import org.jruby.util.io.ModeFlags;
import org.jruby.util.JRubyFile;
import org.jruby.util.TypeConverter;
import org.jruby.util.io.BadDescriptorException;
import org.jruby.util.io.FileExistsException;
import org.jruby.util.io.InvalidValueException;
import org.jruby.util.io.PipeException;
import static org.jruby.CompatVersion.*;
/**
* Ruby File class equivalent in java.
**/
@JRubyClass(name="File", parent="IO", include="FileTest")
public class RubyFile extends RubyIO implements EncodingCapable {
private static final long serialVersionUID = 1L;
public static final int LOCK_SH = 1;
public static final int LOCK_EX = 2;
public static final int LOCK_NB = 4;
public static final int LOCK_UN = 8;
private static final int FNM_NOESCAPE = 1;
private static final int FNM_PATHNAME = 2;
private static final int FNM_DOTMATCH = 4;
private static final int FNM_CASEFOLD = 8;
private static final int FNM_SYSCASE;
private static int _cachedUmask = 0;
private static final Object _umaskLock = new Object();
static {
if (Platform.IS_WINDOWS) {
FNM_SYSCASE = FNM_CASEFOLD;
} else {
FNM_SYSCASE = 0;
}
}
public Encoding getEncoding() {
return null;
}
public void setEncoding(Encoding encoding) {
// :)
}
private static boolean startsWithDriveLetterOnWindows(String path) {
return (path != null)
&& Platform.IS_WINDOWS &&
((path.length()>1 && path.charAt(0) == '/') ?
(path.length() > 2
&& isWindowsDriveLetter(path.charAt(1))
&& path.charAt(2) == ':') :
(path.length() > 1
&& isWindowsDriveLetter(path.charAt(0))
&& path.charAt(1) == ':'));
}
// adjusts paths started with '/' or '\\', on windows.
static String adjustRootPathOnWindows(Ruby runtime, String path, String dir) {
if (path == null || !Platform.IS_WINDOWS) return path;
// MRI behavior on Windows: it treats '/' as a root of
// a current drive (but only if SINGLE slash is present!):
// E.g., if current work directory is
// 'D:/home/directory', then '/' means 'D:/'.
//
// Basically, '/path' is treated as a *RELATIVE* path,
// relative to the current drive. '//path' is treated
// as absolute one.
if ((path.startsWith("/") && !(path.length() > 2 && path.charAt(2) == ':')) || path.startsWith("\\")) {
if (path.length() > 1 && (path.charAt(1) == '/' || path.charAt(1) == '\\')) {
return path;
}
// First try to use drive letter from supplied dir value,
// then try current work dir.
if (!startsWithDriveLetterOnWindows(dir)) {
dir = runtime.getCurrentDirectory();
}
if (dir.length() >= 2) {
path = dir.substring(0, 2) + path;
}
} else if (startsWithDriveLetterOnWindows(path) && path.length() == 2) {
// compensate for missing slash after drive letter on windows
path += "/";
}
return path;
}
protected String path;
private FileLock currentLock;
public RubyFile(Ruby runtime, RubyClass type) {
super(runtime, type);
}
// XXX This constructor is a hack to implement the __END__ syntax.
// Converting a reader back into an InputStream doesn't generally work.
public RubyFile(Ruby runtime, String path, final Reader reader) {
this(runtime, path, new InputStream() {
public int read() throws IOException {
return reader.read();
}
});
}
public RubyFile(Ruby runtime, String path, InputStream in) {
super(runtime, runtime.getFile());
this.path = path;
try {
this.openFile.setMainStream(ChannelStream.open(runtime, new ChannelDescriptor(Channels.newChannel(in))));
this.openFile.setMode(openFile.getMainStreamSafe().getModes().getOpenFileFlags());
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
}
}
private static ObjectAllocator FILE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyFile instance = new RubyFile(runtime, klass);
instance.setMetaClass(klass);
return instance;
}
};
public String getPath() {
return path;
}
@JRubyModule(name="File::Constants")
public static class Constants {}
public static RubyClass createFileClass(Ruby runtime) {
RubyClass fileClass = runtime.defineClass("File", runtime.getIO(), FILE_ALLOCATOR);
// Create Constants class
RubyModule constants = fileClass.defineModuleUnder("Constants");
runtime.setFile(fileClass);
fileClass.index = ClassIndex.FILE;
fileClass.setReifiedClass(RubyFile.class);
RubyString separator = runtime.newString("/");
ThreadContext context = runtime.getCurrentContext();
fileClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyFile;
}
};
separator.freeze(context);
fileClass.defineConstant("SEPARATOR", separator);
fileClass.defineConstant("Separator", separator);
if (File.separatorChar == '\\') {
RubyString altSeparator = runtime.newString("\\");
altSeparator.freeze(context);
fileClass.defineConstant("ALT_SEPARATOR", altSeparator);
} else {
fileClass.defineConstant("ALT_SEPARATOR", runtime.getNil());
}
RubyString pathSeparator = runtime.newString(File.pathSeparator);
pathSeparator.freeze(context);
fileClass.defineConstant("PATH_SEPARATOR", pathSeparator);
// TODO: why are we duplicating the constants here, and then in
// File::Constants below? File::Constants is included in IO.
// TODO: These were missing, so we're not handling them elsewhere?
fileClass.setConstant("FNM_NOESCAPE", runtime.newFixnum(FNM_NOESCAPE));
fileClass.setConstant("FNM_CASEFOLD", runtime.newFixnum(FNM_CASEFOLD));
fileClass.setConstant("FNM_SYSCASE", runtime.newFixnum(FNM_SYSCASE));
fileClass.setConstant("FNM_DOTMATCH", runtime.newFixnum(FNM_DOTMATCH));
fileClass.setConstant("FNM_PATHNAME", runtime.newFixnum(FNM_PATHNAME));
// Create constants for open flags
for (OpenFlags f : OpenFlags.values()) {
// Strip off the O_ prefix, so they become File::RDONLY, and so on
final String name = f.name();
if (name.startsWith("O_")) {
final String cname = name.substring(2);
// Special case for handling ACCMODE, since constantine will generate
// an invalid value if it is not defined by the platform.
final RubyFixnum cvalue = f == OpenFlags.O_ACCMODE
? runtime.newFixnum(ModeFlags.ACCMODE)
: runtime.newFixnum(f.intValue());
fileClass.setConstant(cname, cvalue);
constants.setConstant(cname, cvalue);
}
}
// Create constants for flock
fileClass.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH));
fileClass.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX));
fileClass.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB));
fileClass.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN));
constants.setConstant("FNM_NOESCAPE", runtime.newFixnum(FNM_NOESCAPE));
constants.setConstant("FNM_CASEFOLD", runtime.newFixnum(FNM_CASEFOLD));
constants.setConstant("FNM_SYSCASE", runtime.newFixnum(FNM_SYSCASE));
constants.setConstant("FNM_DOTMATCH", runtime.newFixnum(FNM_DOTMATCH));
constants.setConstant("FNM_PATHNAME", runtime.newFixnum(FNM_PATHNAME));
// Create constants for flock
constants.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH));
constants.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX));
constants.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB));
constants.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN));
// File::Constants module is included in IO.
runtime.getIO().includeModule(constants);
runtime.getFileTest().extend_object(fileClass);
fileClass.defineAnnotatedMethods(RubyFile.class);
// For JRUBY-5276, physically define FileTest methods on File's singleton
fileClass.getSingletonClass().defineAnnotatedMethods(RubyFileTest.FileTestFileMethods.class);
return fileClass;
}
@JRubyMethod
@Override
public IRubyObject close() {
// Make sure any existing lock is released before we try and close the file
if (currentLock != null) {
try {
currentLock.release();
} catch (IOException e) {
throw getRuntime().newIOError(e.getMessage());
}
}
return super.close();
}
@JRubyMethod(required = 1)
public IRubyObject flock(ThreadContext context, IRubyObject lockingConstant) {
// TODO: port exact behavior from MRI, and move most locking logic into ChannelDescriptor
// TODO: for all LOCK_NB cases, return false if they would block
try {
ChannelDescriptor descriptor = openFile.getMainStreamSafe().getDescriptor();
// null channel always succeeds for all locking operations
if (descriptor.isNull()) return RubyFixnum.zero(context.getRuntime());
if (descriptor.getChannel() instanceof FileChannel) {
FileChannel fileChannel = (FileChannel)descriptor.getChannel();
int lockMode = RubyNumeric.num2int(lockingConstant);
// This logic used to attempt a shared lock instead of an exclusive
// lock, because LOCK_EX on some systems (as reported in JRUBY-1214)
// allow exclusively locking a read-only file. However, the JDK
// APIs do not allow acquiring an exclusive lock on files that are
// not open for read, and there are other platforms (such as Solaris,
// see JRUBY-5627) that refuse at an *OS* level to exclusively lock
// files opened only for read. As a result, this behavior is platform-
// dependent, and so we will obey the JDK's policy of disallowing
// exclusive locks on files opened only for read.
if (!openFile.isWritable() && (lockMode & LOCK_EX) > 0) {
throw context.runtime.newErrnoEBADFError("cannot acquire exclusive lock on File not opened for write");
}
// Likewise, JDK does not allow acquiring a shared lock on files
// that have not been opened for read. We comply here.
if (!openFile.isReadable() && (lockMode & LOCK_SH) > 0) {
throw context.runtime.newErrnoEBADFError("cannot acquire shared lock on File not opened for read");
}
try {
switch (lockMode) {
case LOCK_UN:
case LOCK_UN | LOCK_NB:
if (currentLock != null) {
currentLock.release();
currentLock = null;
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_EX:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.lock();
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_EX | LOCK_NB:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.tryLock();
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_SH:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.lock(0L, Long.MAX_VALUE, true);
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_SH | LOCK_NB:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.tryLock(0L, Long.MAX_VALUE, true);
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
default:
}
} catch (IOException ioe) {
if (context.getRuntime().getDebug().isTrue()) {
ioe.printStackTrace(System.err);
}
} catch (java.nio.channels.OverlappingFileLockException ioe) {
if (context.getRuntime().getDebug().isTrue()) {
ioe.printStackTrace(System.err);
}
}
return (lockMode & LOCK_EX) == 0 ? RubyFixnum.zero(context.getRuntime()) : context.getRuntime().getFalse();
} else {
// We're not actually a real file, so we can't flock
return context.getRuntime().getFalse();
}
} catch (BadDescriptorException e) {
throw context.runtime.newErrnoEBADFError();
}
}
@JRubyMethod(required = 1, optional = 2, visibility = PRIVATE, compat = RUBY1_8)
@Override
public IRubyObject initialize(IRubyObject[] args, Block block) {
if (openFile == null) {
throw getRuntime().newRuntimeError("reinitializing File");
}
if (args.length > 0 && args.length < 3) {
if (args[0] instanceof RubyInteger) {
return super.initialize(args, block);
}
}
return openFile(args);
}
@JRubyMethod(name = "initialize", required = 1, optional = 2, visibility = PRIVATE, compat = RUBY1_9)
public IRubyObject initialize19(ThreadContext context, IRubyObject[] args, Block block) {
if (openFile == null) {
throw context.getRuntime().newRuntimeError("reinitializing File");
}
if (args.length > 0 && args.length <= 3) {
IRubyObject fd = TypeConverter.convertToTypeWithCheck(args[0], context.getRuntime().getFixnum(), "to_int");
if (!fd.isNil()) {
args[0] = fd;
if (args.length == 1) {
return super.initialize19(context, args[0], block);
} else if (args.length == 2) {
return super.initialize19(context, args[0], args[1], block);
}
return super.initialize19(context, args[0], args[1], args[2], block);
}
}
return openFile19(context, args);
}
private IRubyObject openFile19(ThreadContext context, IRubyObject args[]) {
Ruby runtime = context.getRuntime();
RubyString filename = get_path(context, args[0]);
runtime.checkSafeString(filename);
path = adjustRootPathOnWindows(runtime, filename.getUnicodeValue(), runtime.getCurrentDirectory());
String modeString = "r";
ModeFlags modes = new ModeFlags();
int perm = 0;
try {
if (args.length > 1) {
if (args[1] instanceof RubyHash) {
modes = parseOptions(context, args[1], modes);
} else {
modes = parseModes19(context, args[1]);
if (args[1] instanceof RubyFixnum) {
perm = getFilePermissions(args);
} else {
modeString = args[1].convertToString().toString();
}
}
} else {
modes = parseModes19(context, RubyString.newString(runtime, modeString));
}
if (args.length > 2 && !args[2].isNil()) {
if (args[2] instanceof RubyHash) {
modes = parseOptions(context, args[2], modes);
} else {
perm = getFilePermissions(args);
}
}
if (perm > 0) {
sysopenInternal(path, modes, perm);
} else {
openInternal(path, modeString, modes);
}
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
}
return this;
}
private IRubyObject openFile(IRubyObject args[]) {
Ruby runtime = getRuntime();
RubyString filename = get_path(runtime.getCurrentContext(), args[0]);
runtime.checkSafeString(filename);
path = adjustRootPathOnWindows(runtime, filename.getUnicodeValue(), runtime.getCurrentDirectory());
String modeString;
ModeFlags modes;
int perm;
try {
if ((args.length > 1 && args[1] instanceof RubyFixnum) || (args.length > 2 && !args[2].isNil())) {
modes = parseModes(args[1]);
perm = getFilePermissions(args);
sysopenInternal(path, modes, perm);
} else {
modeString = "r";
if (args.length > 1 && !args[1].isNil()) {
modeString = args[1].convertToString().toString();
}
openInternal(path, modeString);
}
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} finally {}
return this;
}
private int getFilePermissions(IRubyObject[] args) {
return (args.length > 2 && !args[2].isNil()) ? RubyNumeric.num2int(args[2]) : 438;
}
protected void sysopenInternal(String path, ModeFlags modes, int perm) throws InvalidValueException {
openFile = new OpenFile();
openFile.setPath(path);
openFile.setMode(modes.getOpenFileFlags());
if (modes.isBinary()) externalEncoding = ASCIIEncoding.INSTANCE;
int umask = getUmaskSafe( getRuntime() );
perm = perm - (perm & umask);
ChannelDescriptor descriptor = sysopen(path, modes, perm);
openFile.setMainStream(fdopen(descriptor, modes));
}
protected void openInternal(String path, String modeString, ModeFlags modes) throws InvalidValueException {
openFile = new OpenFile();
openFile.setMode(modes.getOpenFileFlags());
if (modes.isBinary()) externalEncoding = ASCIIEncoding.INSTANCE;
openFile.setPath(path);
openFile.setMainStream(fopen(path, modeString));
}
protected void openInternal(String path, String modeString) throws InvalidValueException {
openFile = new OpenFile();
ModeFlags modes = getIOModes(getRuntime(), modeString);
openFile.setMode(modes.getOpenFileFlags());
if (modes.isBinary()) externalEncoding = ASCIIEncoding.INSTANCE;
openFile.setPath(path);
openFile.setMainStream(fopen(path, modeString));
}
private ChannelDescriptor sysopen(String path, ModeFlags modes, int perm) throws InvalidValueException {
try {
ChannelDescriptor descriptor = ChannelDescriptor.open(
getRuntime().getCurrentDirectory(),
path,
modes,
perm,
getRuntime().getPosix(),
getRuntime().getJRubyClassLoader());
// TODO: check if too many open files, GC and try again
return descriptor;
} catch (PermissionDeniedException pde) {
// PDException can be thrown only when creating the file and
// permission is denied. See JavaDoc of PermissionDeniedException.
throw getRuntime().newErrnoEACCESError(path);
} catch (FileNotFoundException fnfe) {
// FNFException can be thrown in both cases, when the file
// is not found, or when permission is denied.
if (Ruby.isSecurityRestricted() || new File(path).exists()) {
throw getRuntime().newErrnoEACCESError(path);
}
throw getRuntime().newErrnoENOENTError(path);
} catch (DirectoryAsFileException dafe) {
throw getRuntime().newErrnoEISDirError();
} catch (FileExistsException fee) {
throw getRuntime().newErrnoEEXISTError(path);
} catch (IOException ioe) {
throw getRuntime().newIOErrorFromException(ioe);
}
}
private Stream fopen(String path, String modeString) {
try {
Stream stream = ChannelStream.fopen(
getRuntime(),
path,
getIOModes(getRuntime(), modeString));
if (stream == null) {
// TODO
// if (errno == EMFILE || errno == ENFILE) {
// rb_gc();
// file = fopen(fname, mode);
// }
// if (!file) {
// rb_sys_fail(fname);
// }
}
// Do we need to be in SETVBUF mode for buffering to make sense? This comes up elsewhere.
// #ifdef USE_SETVBUF
// if (setvbuf(file, NULL, _IOFBF, 0) != 0)
// rb_warn("setvbuf() can't be honoured for %s", fname);
// #endif
// #ifdef __human68k__
// fmode(file, _IOTEXT);
// #endif
return stream;
} catch (BadDescriptorException e) {
throw getRuntime().newErrnoEBADFError();
} catch (PermissionDeniedException pde) {
// PDException can be thrown only when creating the file and
// permission is denied. See JavaDoc of PermissionDeniedException.
throw getRuntime().newErrnoEACCESError(path);
} catch (FileNotFoundException ex) {
// FNFException can be thrown in both cases, when the file
// is not found, or when permission is denied.
if (Ruby.isSecurityRestricted() || new File(path).exists()) {
throw getRuntime().newErrnoEACCESError(path);
}
throw getRuntime().newErrnoENOENTError(path);
} catch (DirectoryAsFileException ex) {
throw getRuntime().newErrnoEISDirError();
} catch (FileExistsException ex) {
throw getRuntime().newErrnoEEXISTError(path);
} catch (IOException ex) {
throw getRuntime().newIOErrorFromException(ex);
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} catch (PipeException ex) {
throw getRuntime().newErrnoEPIPEError();
} catch (SecurityException ex) {
throw getRuntime().newErrnoEACCESError(path);
}
}
@JRubyMethod(required = 1)
public IRubyObject chmod(ThreadContext context, IRubyObject arg) {
checkClosed(context);
int mode = (int) arg.convertToInteger().getLongValue();
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError(path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().chmod(path, mode));
}
@JRubyMethod(required = 2)
public IRubyObject chown(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
checkClosed(context);
int owner = -1;
if (!arg1.isNil()) {
owner = RubyNumeric.num2int(arg1);
}
int group = -1;
if (!arg2.isNil()) {
group = RubyNumeric.num2int(arg2);
}
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError(path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().chown(path, owner, group));
}
@JRubyMethod
public IRubyObject atime(ThreadContext context) {
checkClosed(context);
return context.getRuntime().newFileStat(path, false).atime();
}
@JRubyMethod
public IRubyObject ctime(ThreadContext context) {
checkClosed(context);
return context.getRuntime().newFileStat(path, false).ctime();
}
@JRubyMethod(required = 1)
public IRubyObject lchmod(ThreadContext context, IRubyObject arg) {
int mode = (int) arg.convertToInteger().getLongValue();
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError(path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().lchmod(path, mode));
}
// TODO: this method is not present in MRI!
@JRubyMethod(required = 2)
public IRubyObject lchown(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
int owner = -1;
if (!arg1.isNil()) {
owner = RubyNumeric.num2int(arg1);
}
int group = -1;
if (!arg2.isNil()) {
group = RubyNumeric.num2int(arg2);
}
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError(path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().lchown(path, owner, group));
}
@JRubyMethod
public IRubyObject lstat(ThreadContext context) {
checkClosed(context);
return context.getRuntime().newFileStat(path, true);
}
@JRubyMethod
public IRubyObject mtime(ThreadContext context) {
checkClosed(context);
return getLastModified(context.getRuntime(), path);
}
@JRubyMethod(meta = true, compat = RUBY1_9)
public static IRubyObject path(ThreadContext context, IRubyObject self, IRubyObject str) {
return get_path(context, str);
}
/**
* similar in spirit to rb_get_path from 1.9 source
* @param context
* @param obj
* @return
*/
public static RubyString get_path(ThreadContext context, IRubyObject obj) {
if (context.getRuntime().is1_9()) {
if (obj instanceof RubyString) {
return (RubyString)obj;
}
if (obj.respondsTo("to_path")) {
obj = obj.callMethod(context, "to_path");
}
}
return obj.convertToString();
}
/**
* Get the fully-qualified JRubyFile object for the path, taking into
* account the runtime's current directory.
*/
public static JRubyFile file(IRubyObject pathOrFile) {
Ruby runtime = pathOrFile.getRuntime();
if (pathOrFile instanceof RubyFile) {
return JRubyFile.create(runtime.getCurrentDirectory(), ((RubyFile) pathOrFile).getPath());
} else {
RubyString pathStr = get_path(runtime.getCurrentContext(), pathOrFile);
String path = pathStr.getUnicodeValue();
String[] pathParts = splitURI(path);
if (pathParts != null && pathParts[0].equals("file:")) {
path = pathParts[1];
}
return JRubyFile.create(runtime.getCurrentDirectory(), path);
}
}
@JRubyMethod(name = {"path", "to_path"})
public IRubyObject path(ThreadContext context) {
IRubyObject newPath = context.getRuntime().getNil();
if (path != null) {
newPath = context.getRuntime().newString(path);
newPath.setTaint(true);
}
return newPath;
}
@JRubyMethod
@Override
public IRubyObject stat(ThreadContext context) {
checkClosed(context);
return context.getRuntime().newFileStat(path, false);
}
@JRubyMethod(required = 1)
public IRubyObject truncate(ThreadContext context, IRubyObject arg) {
RubyInteger newLength = arg.convertToInteger();
if (newLength.getLongValue() < 0) {
throw context.getRuntime().newErrnoEINVALError(path);
}
try {
openFile.checkWritable(context.getRuntime());
openFile.getMainStreamSafe().ftruncate(newLength.getLongValue());
} catch (BadDescriptorException e) {
throw context.getRuntime().newErrnoEBADFError();
} catch (PipeException e) {
throw context.getRuntime().newErrnoESPIPEError();
} catch (InvalidValueException ex) {
throw context.getRuntime().newErrnoEINVALError();
} catch (IOException e) {
// Should we do anything?
}
return RubyFixnum.zero(context.getRuntime());
}
@Override
public String toString() {
try {
return "RubyFile(" + path + ", " + openFile.getMode() + ", " + getRuntime().getFileno(openFile.getMainStreamSafe().getDescriptor()) + ")";
} catch (BadDescriptorException e) {
throw getRuntime().newErrnoEBADFError();
}
}
// TODO: This is also defined in the MetaClass too...Consolidate somewhere.
private static ModeFlags getModes(Ruby runtime, IRubyObject object) throws InvalidValueException {
if (object instanceof RubyString) {
return getIOModes(runtime, ((RubyString) object).toString());
} else if (object instanceof RubyFixnum) {
return new ModeFlags(((RubyFixnum) object).getLongValue());
}
throw runtime.newTypeError("Invalid type for modes");
}
@JRubyMethod
@Override
public IRubyObject inspect() {
StringBuilder val = new StringBuilder();
val.append("#<File:").append(path);
if(!openFile.isOpen()) {
val.append(" (closed)");
}
val.append(">");
return getRuntime().newString(val.toString());
}
/* File class methods */
@JRubyMethod(required = 1, optional = 1, meta = true)
public static IRubyObject basename(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
String name = get_path(context,args[0]).getUnicodeValue();
// MRI-compatible basename handling for windows drive letter paths
if (Platform.IS_WINDOWS) {
if (name.length() > 1 && name.charAt(1) == ':' && Character.isLetter(name.charAt(0))) {
switch (name.length()) {
case 2:
return RubyString.newEmptyString(context.getRuntime()).infectBy(args[0]);
case 3:
return context.getRuntime().newString(name.substring(2)).infectBy(args[0]);
default:
switch (name.charAt(2)) {
case '/':
case '\\':
break;
default:
// strip c: away from relative-pathed name
name = name.substring(2);
break;
}
break;
}
}
}
while (name.length() > 1 && name.charAt(name.length() - 1) == '/') {
name = name.substring(0, name.length() - 1);
}
// Paths which end in "/" or "\\" must be stripped off.
int slashCount = 0;
int length = name.length();
for (int i = length - 1; i >= 0; i--) {
char c = name.charAt(i);
if (c != '/' && c != '\\') {
break;
}
slashCount++;
}
if (slashCount > 0 && length > 1) {
name = name.substring(0, name.length() - slashCount);
}
int index = name.lastIndexOf('/');
if (index == -1) {
// XXX actually only on windows...
index = name.lastIndexOf('\\');
}
if (!name.equals("/") && index != -1) {
name = name.substring(index + 1);
}
if (args.length == 2) {
String ext = RubyString.stringValue(args[1]).toString();
if (".*".equals(ext)) {
index = name.lastIndexOf('.');
if (index > 0) { // -1 no match; 0 it is dot file not extension
name = name.substring(0, index);
}
} else if (name.endsWith(ext)) {
name = name.substring(0, name.length() - ext.length());
}
}
return context.getRuntime().newString(name).infectBy(args[0]);
}
@JRubyMethod(required = 2, rest = true, meta = true)
public static IRubyObject chmod(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int count = 0;
RubyInteger mode = args[0].convertToInteger();
for (int i = 1; i < args.length; i++) {
JRubyFile filename = file(args[i]);
if (!filename.exists()) {
throw runtime.newErrnoENOENTError(filename.toString());
}
boolean result = 0 == runtime.getPosix().chmod(filename.getAbsolutePath(), (int)mode.getLongValue());
if (result) {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 3, rest = true, meta = true)
public static IRubyObject chown(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int count = 0;
int owner = -1;
if (!args[0].isNil()) {
owner = RubyNumeric.num2int(args[0]);
}
int group = -1;
if (!args[1].isNil()) {
group = RubyNumeric.num2int(args[1]);
}
for (int i = 2; i < args.length; i++) {
JRubyFile filename = file(args[i]);
if (!filename.exists()) {
throw runtime.newErrnoENOENTError(filename.toString());
}
boolean result = 0 == runtime.getPosix().chown(filename.getAbsolutePath(), owner, group);
if (result) {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 1, meta = true)
public static IRubyObject dirname(ThreadContext context, IRubyObject recv, IRubyObject arg) {
RubyString filename = get_path(context, arg);
String jfilename = filename.getUnicodeValue();