/
RubyFile.java
2077 lines (1749 loc) · 79.7 KB
/
RubyFile.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
/*
***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse 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/epl-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 EPL, 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 EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.CompatVersion.*;
import static org.jruby.runtime.Visibility.*;
import jnr.constants.platform.OpenFlags;
import org.jcodings.Encoding;
import org.jruby.util.io.ModeFlags;
import org.jruby.util.io.OpenFile;
import org.jruby.util.io.ChannelDescriptor;
import java.io.File;
import java.io.FileDescriptor;
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.Channel;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.Enumeration;
import java.util.jar.JarFile;
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 jnr.posix.FileStat;
import jnr.posix.JavaLibCHelper;
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 org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.encoding.EncodingCapable;
import org.jruby.util.ByteList;
import org.jruby.util.FileResource;
import org.jruby.util.JRubyFile;
import org.jruby.util.TypeConverter;
import org.jruby.util.io.Stream;
import org.jruby.util.io.ChannelStream;
import org.jruby.util.io.IOOptions;
import org.jruby.util.io.BadDescriptorException;
import org.jruby.util.io.InvalidValueException;
import org.jruby.util.io.PipeException;
import org.jruby.exceptions.RaisableException;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.encoding.EncodingService;
import org.jruby.util.encoding.Transcoder;
import org.jruby.util.io.EncodingUtils;
import org.jruby.util.io.IOEncodable;
/**
* Ruby File class equivalent in java.
**/
@JRubyClass(name="File", parent="IO", include="FileTest")
public class RubyFile extends RubyIO implements EncodingCapable {
public static RubyClass createFileClass(Ruby runtime) {
ThreadContext context = runtime.getCurrentContext();
RubyClass fileClass = runtime.defineClass("File", runtime.getIO(), FILE_ALLOCATOR);
runtime.setFile(fileClass);
fileClass.defineAnnotatedMethods(RubyFile.class);
fileClass.index = ClassIndex.FILE;
fileClass.setReifiedClass(RubyFile.class);
fileClass.kindOf = new RubyModule.JavaClassKindOf(RubyFile.class);
// file separator constants
RubyString separator = runtime.newString("/");
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());
}
// path separator
RubyString pathSeparator = runtime.newString(File.pathSeparator);
pathSeparator.freeze(context);
fileClass.defineConstant("PATH_SEPARATOR", pathSeparator);
// For JRUBY-5276, physically define FileTest methods on File's singleton
fileClass.getSingletonClass().defineAnnotatedMethods(RubyFileTest.FileTestFileMethods.class);
// Create Constants class
RubyModule constants = fileClass.defineModuleUnder("Constants");
// 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());
constants.setConstant(cname, cvalue);
}
}
// case handling, escaping, path and dot matching
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));
// flock operations
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));
// NULL device
if (runtime.is1_9() || runtime.is2_0()) {
constants.setConstant("NULL", runtime.newString(getNullDevice()));
}
// File::Constants module is included in IO.
runtime.getIO().includeModule(constants);
return fileClass;
}
private static ObjectAllocator FILE_ALLOCATOR = new ObjectAllocator() {
@Override
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyFile instance = new RubyFile(runtime, klass);
instance.setMetaClass(klass);
return instance;
}
};
private static String getNullDevice() {
// FIXME: MRI defines special null device for Amiga and VMS, but currently
// we lack ability to detect these platforms
String null_device;
if (Platform.IS_WINDOWS) {
null_device = "NUL";
} else {
null_device = "/dev/null";
}
return null_device;
}
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() {
@Override
public int read() throws IOException {
return reader.read();
}
});
}
public RubyFile(Ruby runtime, String path, InputStream in) {
super(runtime, runtime.getFile());
MakeOpenFile();
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();
}
}
@Override
protected IRubyObject ioClose(Ruby runtime) {
// 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.ioClose(runtime);
}
@JRubyMethod(required = 1)
public IRubyObject flock(ThreadContext context, IRubyObject lockingConstant) {
Ruby runtime = context.runtime;
// 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
ChannelDescriptor descriptor;
try {
descriptor = openFile.getMainStreamSafe().getDescriptor();
} catch (BadDescriptorException e) {
throw context.runtime.newErrnoEBADFError();
}
// null channel always succeeds for all locking operations
if (descriptor.isNull()) return RubyFixnum.zero(runtime);
int lockMode = RubyNumeric.num2int(lockingConstant);
Channel channel = descriptor.getChannel();
FileDescriptor fd = ChannelDescriptor.getDescriptorFromChannel(channel);
int real_fd = JavaLibCHelper.getfdFromDescriptor(fd);
if (real_fd != -1) {
// we have a real fd...try native flocking
try {
int result = runtime.getPosix().flock(real_fd, lockMode);
if (result < 0) {
return runtime.getFalse();
}
return RubyFixnum.zero(runtime);
} catch (RaiseException re) {
if (re.getException().getMetaClass() == runtime.getNotImplementedError()) {
// not implemented, probably pure Java; fall through
} else {
throw re;
}
}
}
if (descriptor.getChannel() instanceof FileChannel) {
FileChannel fileChannel = (FileChannel)descriptor.getChannel();
checkSharedExclusive(runtime, openFile, lockMode);
if (!lockStateChanges(currentLock, lockMode)) return RubyFixnum.zero(runtime);
try {
synchronized (fileChannel) {
// check again, to avoid unnecessary overhead
if (!lockStateChanges(currentLock, lockMode)) return RubyFixnum.zero(runtime);
switch (lockMode) {
case LOCK_UN:
case LOCK_UN | LOCK_NB:
return unlock(runtime);
case LOCK_EX:
return lock(runtime, fileChannel, true);
case LOCK_EX | LOCK_NB:
return tryLock(runtime, fileChannel, true);
case LOCK_SH:
return lock(runtime, fileChannel, false);
case LOCK_SH | LOCK_NB:
return tryLock(runtime, fileChannel, false);
}
}
} catch (IOException ioe) {
if (runtime.getDebug().isTrue()) {
ioe.printStackTrace(System.err);
}
} catch (OverlappingFileLockException ioe) {
if (runtime.getDebug().isTrue()) {
ioe.printStackTrace(System.err);
}
}
return lockFailedReturn(runtime, lockMode);
} else {
// We're not actually a real file, so we can't flock
return runtime.getFalse();
}
}
@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.runtime.newRuntimeError("reinitializing File");
}
if (args.length > 0 && args.length <= 3) {
IRubyObject fd = TypeConverter.convertToTypeWithCheck(args[0], context.runtime.getFixnum(), "to_int");
if (!fd.isNil()) {
if (args.length == 1) {
return super.initialize19(context, fd, block);
} else if (args.length == 2) {
return super.initialize19(context, fd, args[1], block);
}
return super.initialize19(context, fd, args[1], args[2], block);
}
}
return openFile19(context, args);
}
@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.runtime.newErrnoENOENTError(path);
}
return context.runtime.newFixnum(context.runtime.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.runtime.newErrnoENOENTError(path);
}
return context.runtime.newFixnum(context.runtime.getPosix().chown(path, owner, group));
}
@JRubyMethod
public IRubyObject atime(ThreadContext context) {
checkClosed(context);
return context.runtime.newFileStat(path, false).atime();
}
@JRubyMethod
public IRubyObject ctime(ThreadContext context) {
checkClosed(context);
return context.runtime.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.runtime.newErrnoENOENTError(path);
}
return context.runtime.newFixnum(context.runtime.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.runtime.newErrnoENOENTError(path);
}
return context.runtime.newFixnum(context.runtime.getPosix().lchown(path, owner, group));
}
@JRubyMethod
public IRubyObject lstat(ThreadContext context) {
checkClosed(context);
return context.runtime.newFileStat(path, true);
}
@JRubyMethod
public IRubyObject mtime(ThreadContext context) {
checkClosed(context);
return context.runtime.newFileStat(path, false).mtime();
}
@JRubyMethod(meta = true, compat = RUBY1_9)
public static IRubyObject path(ThreadContext context, IRubyObject self, IRubyObject str) {
return get_path(context, str);
}
@JRubyMethod(name = {"path", "to_path"})
public IRubyObject path(ThreadContext context) {
IRubyObject newPath = context.runtime.getNil();
if (path != null) {
newPath = context.runtime.newString(path);
newPath.setTaint(true);
}
return newPath;
}
@JRubyMethod
@Override
public IRubyObject stat(ThreadContext context) {
checkClosed(context);
return context.runtime.newFileStat(path, false);
}
@JRubyMethod(required = 1)
public IRubyObject truncate(ThreadContext context, IRubyObject arg) {
RubyInteger newLength = arg.convertToInteger();
if (newLength.getLongValue() < 0) {
throw context.runtime.newErrnoEINVALError(path);
}
try {
openFile.checkWritable(context.runtime);
openFile.getMainStreamSafe().ftruncate(newLength.getLongValue());
} catch (BadDescriptorException e) {
throw context.runtime.newErrnoEBADFError();
} catch (PipeException e) {
throw context.runtime.newErrnoESPIPEError();
} catch (InvalidValueException ex) {
throw context.runtime.newErrnoEINVALError();
} catch (IOException e) {
// Should we do anything?
}
return RubyFixnum.zero(context.runtime);
}
@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.runtime).infectBy(args[0]);
case 3:
return context.runtime.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.runtime.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.runtime;
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());
}
if (0 != runtime.getPosix().chmod(filename.getAbsolutePath(), (int)mode.getLongValue())) {
throw runtime.newErrnoFromLastPOSIXErrno();
} else {
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.runtime;
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());
}
if (0 != runtime.getPosix().chown(filename.getAbsolutePath(), owner, group)) {
throw runtime.newErrnoFromLastPOSIXErrno();
} else {
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.asJavaString();
return context.runtime.newString(dirname(context, jfilename)).infectBy(filename);
}
public static String dirname(ThreadContext context, String jfilename) {
String name = jfilename.replace('\\', '/');
int minPathLength = 1;
boolean trimmedSlashes = false;
boolean startsWithDriveLetterOnWindows = startsWithDriveLetterOnWindows(name);
if (startsWithDriveLetterOnWindows) {
minPathLength = 3;
}
while (name.length() > minPathLength && name.charAt(name.length() - 1) == '/') {
trimmedSlashes = true;
name = name.substring(0, name.length() - 1);
}
String result;
if (startsWithDriveLetterOnWindows && name.length() == 2) {
if (trimmedSlashes) {
// C:\ is returned unchanged
result = jfilename.substring(0, 3);
} else {
result = jfilename.substring(0, 2) + '.';
}
} else {
//TODO deal with UNC names
int index = name.lastIndexOf('/');
if (index == -1) {
if (startsWithDriveLetterOnWindows) {
return jfilename.substring(0, 2) + ".";
} else {
return ".";
}
}
if (index == 0) {
return "/";
}
if (startsWithDriveLetterOnWindows && index == 2) {
// Include additional path separator
// (so that dirname of "C:\file.txt" is "C:\", not "C:")
index++;
}
if (jfilename.startsWith("\\\\")) {
index = jfilename.length();
String[] splitted = jfilename.split(Pattern.quote("\\"));
int last = splitted.length-1;
if (splitted[last].contains(".")) {
index = jfilename.lastIndexOf("\\");
}
}
result = jfilename.substring(0, index);
}
char endChar;
// trim trailing slashes
while (result.length() > minPathLength) {
endChar = result.charAt(result.length() - 1);
if (endChar == '/' || endChar == '\\') {
result = result.substring(0, result.length() - 1);
} else {
break;
}
}
return result;
}
/**
* Returns the extension name of the file. An empty string is returned if
* the filename (not the entire path) starts or ends with a dot.
* @param recv
* @param arg Path to get extension name of
* @return Extension, including the dot, or an empty string
*/
@JRubyMethod(required = 1, meta = true)
public static IRubyObject extname(ThreadContext context, IRubyObject recv, IRubyObject arg) {
IRubyObject baseFilename = basename(context, recv, new IRubyObject[]{arg});
String filename = RubyString.stringValue(baseFilename).getUnicodeValue();
String result = "";
int dotIndex = filename.lastIndexOf(".");
if (dotIndex > 0 && dotIndex != (filename.length() - 1)) {
// Dot is not at beginning and not at end of filename.
result = filename.substring(dotIndex);
}
return context.runtime.newString(result);
}
/**
* Converts a pathname to an absolute pathname. Relative paths are
* referenced from the current working directory of the process unless
* a second argument is given, in which case it will be used as the
* starting point. If the second argument is also relative, it will
* first be converted to an absolute pathname.
* @param recv
* @param args
* @return Resulting absolute path as a String
*/
@JRubyMethod(required = 1, optional = 1, meta = true, compat = CompatVersion.RUBY1_8)
public static IRubyObject expand_path(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return expandPathInternal(context, recv, args, true);
}
@JRubyMethod(name = "expand_path", required = 1, optional = 1, meta = true, compat = CompatVersion.RUBY1_9)
public static IRubyObject expand_path19(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
RubyString path = (RubyString) expandPathInternal(context, recv, args, true);
path.force_encoding(context, context.runtime.getEncodingService().getDefaultExternal());
return path;
}
/**
* ---------------------------------------------------- File::absolute_path
* File.absolute_path(file_name [, dir_string] ) -> abs_file_name
*
* From Ruby 1.9.1
* ------------------------------------------------------------------------
* Converts a pathname to an absolute pathname. Relative paths are
* referenced from the current working directory of the process unless
* _dir_string_ is given, in which case it will be used as the
* starting point. If the given pathname starts with a ``+~+'' it is
* NOT expanded, it is treated as a normal directory name.
*
* File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
*
* @param context
* @param recv
* @param args
* @return
*/
@JRubyMethod(required = 1, optional = 1, meta = true, compat = RUBY1_9)
public static IRubyObject absolute_path(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return expandPathInternal(context, recv, args, false);
}
@JRubyMethod(name = {"realdirpath"}, required = 1, optional = 1, meta = true, compat = RUBY1_9)
public static IRubyObject realdirpath(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return expandPathInternal(context, recv, args, false);
}
@JRubyMethod(name = {"realpath"}, required = 1, optional = 1, meta = true, compat = RUBY1_9)
public static IRubyObject realpath(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject file = expandPathInternal(context, recv, args, false);
if (!RubyFileTest.exist_p(recv, file).isTrue()) {
throw context.runtime.newErrnoENOENTError(file.toString());
}
return file;
}
/**
* Returns true if path matches against pattern The pattern is not a regular expression;
* instead it follows rules similar to shell filename globbing. It may contain the following
* metacharacters:
* *: Glob - match any sequence chars (re: .*). If like begins with '.' then it doesn't.
* ?: Matches a single char (re: .).
* [set]: Matches a single char in a set (re: [...]).
*
*/
@JRubyMethod(name = {"fnmatch", "fnmatch?"}, required = 2, optional = 1, meta = true)
public static IRubyObject fnmatch(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
int flags = args.length == 3 ? RubyNumeric.num2int(args[2]) : 0;
ByteList pattern = args[0].convertToString().getByteList();
ByteList path = get_path(context, args[1]).getByteList();
if (org.jruby.util.Dir.fnmatch(pattern.getUnsafeBytes(), pattern.getBegin(), pattern.getBegin()+pattern.getRealSize(), path.getUnsafeBytes(), path.getBegin(), path.getBegin()+path.getRealSize(), flags) == 0) {
return context.runtime.getTrue();
}
return context.runtime.getFalse();
}
@JRubyMethod(name = "ftype", required = 1, meta = true)
public static IRubyObject ftype(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).getUnicodeValue(), true).ftype();
}
/*
* Fixme: This does not have exact same semantics as RubyArray.join, but they
* probably could be consolidated (perhaps as join(args[], sep, doChomp)).
*/
@JRubyMethod(rest = true, meta = true)
public static RubyString join(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return join(context, recv, RubyArray.newArrayNoCopyLight(context.runtime, args));
}
@JRubyMethod(name = "lstat", required = 1, meta = true)
public static IRubyObject lstat(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = get_path(context, filename).getUnicodeValue();
return context.runtime.newFileStat(f, true);
}
@JRubyMethod(name = "stat", required = 1, meta = true)
public static IRubyObject stat(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = get_path(context, filename).getUnicodeValue();
return context.runtime.newFileStat(f, false);
}
@JRubyMethod(name = "atime", required = 1, meta = true)
public static IRubyObject atime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = get_path(context, filename).getUnicodeValue();
return context.runtime.newFileStat(f, false).atime();
}
@JRubyMethod(name = "ctime", required = 1, meta = true)
public static IRubyObject ctime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = get_path(context, filename).getUnicodeValue();
return context.runtime.newFileStat(f, false).ctime();
}
@JRubyMethod(required = 1, rest = true, meta = true)
public static IRubyObject lchmod(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.runtime;
int count = 0;
RubyInteger mode = args[0].convertToInteger();
for (int i = 1; i < args.length; i++) {
JRubyFile file = file(args[i]);
if (0 != runtime.getPosix().lchmod(file.toString(), (int)mode.getLongValue())) {
throw runtime.newErrnoFromLastPOSIXErrno();
} else {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 2, rest = true, meta = true)
public static IRubyObject lchown(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.runtime;
int owner = !args[0].isNil() ? RubyNumeric.num2int(args[0]) : -1;
int group = !args[1].isNil() ? RubyNumeric.num2int(args[1]) : -1;
int count = 0;
for (int i = 2; i < args.length; i++) {
JRubyFile file = file(args[i]);
if (0 != runtime.getPosix().lchown(file.toString(), owner, group)) {
throw runtime.newErrnoFromLastPOSIXErrno();
} else {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 2, meta = true)
public static IRubyObject link(ThreadContext context, IRubyObject recv, IRubyObject from, IRubyObject to) {
Ruby runtime = context.runtime;
String fromStr = file(from).toString();
String toStr = file(to).toString();
int ret = runtime.getPosix().link(fromStr, toStr);
if (ret != 0) {
if (runtime.getPosix().isNative()) {
throw runtime.newErrnoFromInt(runtime.getPosix().errno(), String.format("(%s, %s)", fromStr, toStr));
} else {
// In most cases, when there is an error during the call,
// the POSIX handler throws an exception, but not in case
// with pure Java POSIX layer (when native support is disabled),
// so we deal with it like this:
throw runtime.newErrnoEEXISTError(fromStr + " or " + toStr);
}
}
return runtime.newFixnum(ret);
}
@JRubyMethod(name = "mtime", required = 1, meta = true)
public static IRubyObject mtime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).getUnicodeValue(), false).mtime();
}
@JRubyMethod(required = 2, meta = true)
public static IRubyObject rename(ThreadContext context, IRubyObject recv, IRubyObject oldName, IRubyObject newName) {
Ruby runtime = context.runtime;
RubyString oldNameString = get_path(context, oldName);
RubyString newNameString = get_path(context, newName);
String newNameJavaString = newNameString.getUnicodeValue();
String oldNameJavaString = oldNameString.getUnicodeValue();
JRubyFile oldFile = JRubyFile.create(runtime.getCurrentDirectory(), oldNameJavaString);
JRubyFile newFile = JRubyFile.create(runtime.getCurrentDirectory(), newNameJavaString);
if (!oldFile.exists() || !newFile.getParentFile().exists()) {
throw runtime.newErrnoENOENTError(oldNameJavaString + " or " + newNameJavaString);
}
JRubyFile dest = JRubyFile.create(runtime.getCurrentDirectory(), newNameJavaString);
if (oldFile.renameTo(dest)) { // rename is successful
return RubyFixnum.zero(runtime);
}
// rename via Java API call wasn't successful, let's try some tricks, similar to MRI
if (newFile.exists()) {
runtime.getPosix().chmod(newNameJavaString, 0666);
newFile.delete();
}
if (oldFile.renameTo(dest)) { // try to rename one more time
return RubyFixnum.zero(runtime);
}
throw runtime.newErrnoEACCESError(oldNameJavaString + " or " + newNameJavaString);
}
@JRubyMethod(required = 1, meta = true)
public static RubyArray split(ThreadContext context, IRubyObject recv, IRubyObject arg) {
RubyString filename = get_path(context, arg);
return context.runtime.newArray(dirname(context, recv, filename),
basename(context, recv, new IRubyObject[]{filename}));
}
@JRubyMethod(required = 2, meta = true)
public static IRubyObject symlink(ThreadContext context, IRubyObject recv, IRubyObject from, IRubyObject to) {
Ruby runtime = context.runtime;
RubyString fromStr = get_path(context, from);
RubyString toStr = get_path(context, to);
String tovalue = toStr.getUnicodeValue();
tovalue = JRubyFile.create(runtime.getCurrentDirectory(), tovalue).getAbsolutePath();
try {
if (runtime.getPosix().symlink(fromStr.getUnicodeValue(), tovalue) == -1) {
if (runtime.getPosix().isNative()) {
throw runtime.newErrnoFromInt(runtime.getPosix().errno(), String.format("(%s, %s)", fromStr, toStr));
} else {
throw runtime.newErrnoEEXISTError(String.format("(%s, %s)", fromStr, toStr));
}
}
} catch (java.lang.UnsatisfiedLinkError ule) {
throw runtime.newNotImplementedError("symlink() function is unimplemented on this machine");
}
return RubyFixnum.zero(runtime);
}
@JRubyMethod(required = 1, meta = true)
public static IRubyObject readlink(ThreadContext context, IRubyObject recv, IRubyObject path) {
Ruby runtime = context.runtime;
JRubyFile link = file(path);
try {
String realPath = runtime.getPosix().readlink(link.toString());
if (!RubyFileTest.exist_p(recv, path).isTrue()) {
throw runtime.newErrnoENOENTError(path.toString());
}
if (!RubyFileTest.symlink_p(recv, path).isTrue()) {
// Can not check earlier, File.exist? might return false yet the symlink be there