-
-
Notifications
You must be signed in to change notification settings - Fork 938
Expand file tree
/
Copy pathRubyFile.java
More file actions
2431 lines (2047 loc) · 101 KB
/
RubyFile.java
File metadata and controls
2431 lines (2047 loc) · 101 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: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v20.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 jnr.constants.platform.OpenFlags;
import jnr.posix.POSIX;
import jnr.posix.util.Platform;
import org.jcodings.Encoding;
import org.jcodings.specific.ASCIIEncoding;
import org.jcodings.specific.UTF8Encoding;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.api.API;
import org.jruby.api.Error;
import org.jruby.exceptions.NotImplementedError;
import org.jruby.ir.runtime.IRRuntimeHelpers;
import org.jruby.runtime.*;
import org.jruby.runtime.JavaSites.FileSites;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.encoding.EncodingCapable;
import org.jruby.util.*;
import org.jruby.util.io.EncodingUtils;
import org.jruby.util.io.IOEncodable;
import org.jruby.util.io.ModeFlags;
import org.jruby.util.io.OpenFile;
import org.jruby.util.io.PosixShim;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFileAttributeView;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.jruby.RubyInteger.singleCharByteList;
import static org.jruby.api.Access.encodingService;
import static org.jruby.api.Access.fileClass;
import static org.jruby.api.Access.hashClass;
import static org.jruby.api.Access.timeClass;
import static org.jruby.api.Check.checkEmbeddedNulls;
import static org.jruby.api.Convert.*;
import static org.jruby.api.Create.*;
import static org.jruby.api.Define.defineClass;
import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.runtimeError;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.util.StringSupport.*;
import static org.jruby.util.io.EncodingUtils.vmode;
import static org.jruby.util.io.EncodingUtils.vperm;
/**
* The Ruby File class.
*/
@JRubyClass(name="File", parent="IO", include="FileTest")
public class RubyFile extends RubyIO implements EncodingCapable {
static final ByteList SLASH = singleCharByteList((byte) '/');
static final ByteList BACKSLASH = singleCharByteList((byte) '\\');
public static RubyClass createFileClass(ThreadContext context, RubyClass IO) {
// file separator constants
var separator = newString(context, SLASH).freeze(context);
var altSeparator = File.separatorChar == '\\' ? newString(context, BACKSLASH).freeze(context) : context.nil;
var pathSeparator = newString(context, singleCharByteList((byte) File.pathSeparatorChar)).freeze(context);
RubyClass File = defineClass(context, "File", IO, RubyFile::new).
reifiedClass(RubyFile.class).
kindOf(new RubyModule.JavaClassKindOf(RubyFile.class)).
classIndex(ClassIndex.FILE).
defineMethods(context, RubyFile.class).
defineConstant(context, "SEPARATOR", separator).
defineConstant(context, "Separator", separator).
defineConstant(context, "ALT_SEPARATOR", altSeparator).
defineConstant(context, "PATH_SEPARATOR", pathSeparator);
// For JRUBY-5276, physically define FileTest methods on File's singleton
File.singletonClass(context).defineMethods(context, RubyFileTest.FileTestFileMethods.class);
var FileConstants = File.defineModuleUnder(context, "Constants").
defineConstant(context, "RDONLY", asFixnum(context, OpenFlags.O_RDONLY.intValue())).
defineConstant(context, "WRONLY", asFixnum(context, OpenFlags.O_WRONLY.intValue())).
defineConstant(context, "RDWR", asFixnum(context, OpenFlags.O_RDWR.intValue())).
defineConstant(context, "APPEND", asFixnum(context, OpenFlags.O_APPEND.intValue())).
defineConstant(context, "CREAT", asFixnum(context, OpenFlags.O_CREAT.intValue())).
defineConstant(context, "EXCL", asFixnum(context, OpenFlags.O_EXCL.intValue())).
defineConstant(context, "TRUNC", asFixnum(context, OpenFlags.O_TRUNC.intValue())).
// FIXME: NOCTTY is showing up as undefined on Linux, but it should be defined.
defineConstant(context, "NOCTTY", asFixnum(context, OpenFlags.O_NOCTTY.intValue())).
defineConstant(context, "SHARE_DELETE", asFixnum(context, ModeFlags.SHARE_DELETE)).
defineConstant(context, "FNM_NOESCAPE", asFixnum(context, FNM_NOESCAPE)).
defineConstant(context, "FNM_CASEFOLD", asFixnum(context, FNM_CASEFOLD)).
defineConstant(context, "FNM_SYSCASE", asFixnum(context, FNM_SYSCASE)).
defineConstant(context, "FNM_DOTMATCH", asFixnum(context, FNM_DOTMATCH)).
defineConstant(context, "FNM_PATHNAME", asFixnum(context, FNM_PATHNAME)).
defineConstant(context, "FNM_EXTGLOB", asFixnum(context, FNM_EXTGLOB)).
defineConstant(context, "LOCK_SH", asFixnum(context, RubyFile.LOCK_SH)).
defineConstant(context, "LOCK_EX", asFixnum(context, RubyFile.LOCK_EX)).
defineConstant(context, "LOCK_NB", asFixnum(context, RubyFile.LOCK_NB)).
defineConstant(context, "LOCK_UN", asFixnum(context, RubyFile.LOCK_UN)).
defineConstant(context, "NULL", newString(context, getNullDevice()));
// FIXME: Some comment about an O_DELAY not being defined in OpenFlags. This might be missing constants.
// FIXME: Should NONBLOCK exist for Windows fcntl flags?
if (OpenFlags.O_NONBLOCK.defined()) {
FileConstants.defineConstant(context, "NONBLOCK", asFixnum(context, OpenFlags.O_NONBLOCK.intValue()));
} else if (Platform.IS_WINDOWS) {
FileConstants.defineConstant(context, "NONBLOCK", asFixnum(context, 1));
}
if (!OpenFlags.O_BINARY.defined()) {
FileConstants.defineConstant(context, "BINARY", asFixnum(context, 0));
} else {
/* disable line code conversion */
FileConstants.defineConstant(context, "BINARY", asFixnum(context, OpenFlags.O_BINARY.intValue()));
}
if (OpenFlags.O_SYNC.defined()) {
FileConstants.defineConstant(context, "SYNC", asFixnum(context, OpenFlags.O_SYNC.intValue()));
}
// O_DSYNC and O_RSYNC are not in OpenFlags
// #ifdef O_DSYNC
// /* any write operation perform synchronously except some meta data */
// constants.setConstant("DSYNC", asFixnum(context, OpenFlags.O_DSYNC.intValue()));
// #endif
// #ifdef O_RSYNC
// /* any read operation perform synchronously. used with SYNC or DSYNC. */
// constants.setConstant("RSYNC", asFixnum(context, OpenFlags.O_RSYNC.intValue()));
// #endif
if (OpenFlags.O_NOFOLLOW.defined()) {
/* do not follow symlinks */
FileConstants.defineConstant(context, "NOFOLLOW", asFixnum(context, OpenFlags.O_NOFOLLOW.intValue())); /* FreeBSD, Linux */
}
// O_NOATIME and O_DIRECT are not in OpenFlags
// #ifdef O_NOATIME
// /* do not change atime */
// constants.setConstant("NOATIME", asFixnum(context, OpenFlags.O_NOATIME.intValue())); /* Linux */
// #endif
// #ifdef O_DIRECT
// /* Try to minimize cache effects of the I/O to and from this file. */
// constants.setConstant("DIRECT", asFixnum(context, OpenFlags.O_DIRECT.intValue()));
// #endif
if (OpenFlags.O_TMPFILE.defined()) {
/* Create an unnamed temporary file */
FileConstants.defineConstant(context, "TMPFILE", asFixnum(context, OpenFlags.O_TMPFILE.intValue()));
}
// File::Constants module is included in IO.
IO.include(context, FileConstants);
if (Platform.IS_WINDOWS) {
// readlink is not available on Windows. See below and jruby/jruby#3287.
// TODO: MRI does not implement readlink on Windows, but perhaps we could?
File.searchMethod("readlink").setNotImplemented(true);
File.searchMethod("mkfifo").setNotImplemented(true);
}
if (!Platform.IS_BSD) {
// lchmod appears to be mostly a BSD-ism, not supported on Linux.
// See https://github.com/jruby/jruby/issues/5547
File.singletonClass(context).searchMethod("lchmod").setNotImplemented(true);
}
return File;
}
private static String getNullDevice() {
// FIXME: MRI defines null devices for Amiga and VMS, but currently we lack ability to detect these platforms
return Platform.IS_WINDOWS ? "NUL" : "/dev/null";
}
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.
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(), Channels.newChannel(in));
this.setPath(path);
}
private RubyFile(Ruby runtime, String path, SeekableByteChannel in) {
super(runtime, runtime.getFile(), in);
this.setPath(path);
}
/**
* Only used by parser (prism) so that we can get a File
* @param runtime the runtime
* @param path the path of DATA
* @param in the channel to use
* @return a Ruby file
*/
public static RubyFile DATAFile(Ruby runtime, String path, SeekableByteChannel in) {
return new RubyFile(runtime, path, in);
}
public RubyFile(Ruby runtime, String path, FileChannel channel) {
super(runtime, runtime.getFile(), channel);
this.setPath(path);
}
@Override
protected IRubyObject rbIoClose(ThreadContext context) {
// Make sure any existing lock is released before we try and close the file
if (openFile.currentLock != null) {
try {
openFile.currentLock.release();
} catch (IOException e) {
throw context.runtime.newIOError(e.getMessage());
}
}
return super.rbIoClose(context);
}
@JRubyMethod
public IRubyObject flock(ThreadContext context, IRubyObject operation) {
// Solaris uses a ruby-ffi version defined in jruby/kernel/file.rb, so re-dispatch
if (Platform.IS_SOLARIS) return callMethod(context, "flock", operation);
// int[] op = {0,0};
// struct timeval time;
// rb_secure(2);
int op1 = toInt(context, operation);
OpenFile fptr = getOpenFileChecked();
if (fptr.isWritable()) flushRaw(context, false);
// MRI's logic differs here. For a nonblocking flock that produces EAGAIN, EACCES, or EWOULBLOCK, MRI
// just returns false immediately. For the same errnos in blocking mode, MRI waits for 0.1s and then
// attempts the lock again, indefinitely.
while (fptr.threadFlock(context, op1) < 0) {
switch (fptr.errno()) {
case EAGAIN:
case EACCES:
case EWOULDBLOCK:
if ((op1 & LOCK_NB) != 0) return context.fals;
try {
context.getThread().sleep(100);
} catch (InterruptedException ie) {
context.pollThreadEvents();
}
fptr.checkClosed();
continue;
case EINTR:
break;
default:
throw context.runtime.newErrnoFromErrno(fptr.errno(), fptr.getPath());
}
}
return asFixnum(context, 0);
}
// rb_file_initialize
@JRubyMethod(name = "initialize", required = 1, optional = 3, checkArity = false, visibility = PRIVATE, keywords = true)
public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) {
// capture callInfo for delegating to IO#initialize
final int callInfo = context.callInfo;
IRubyObject keywords = IRRuntimeHelpers.receiveKeywords(context, args, false, true, false);
// Mild hack. We want to arity-mismatch if extra arg is not really a kwarg but not if it is one.
int maxArgs = keywords instanceof RubyHash ? 4 : 3;
int argc = Arity.checkArgumentCount(context, args, 1, maxArgs);
if (openFile != null) throw runtimeError(context, "reinitializing File");
if (argc > 0 && argc <= 3) {
IRubyObject fd = TypeConverter.convertToTypeWithCheck(context, args[0], context.runtime.getFixnum(), sites(context).to_int_checked);
if (!fd.isNil()) {
// restore callInfo for delegated call to IO#initialize
context.callInfo = callInfo;
return switch (argc) {
case 1 -> super.initialize(context, fd, block);
case 2 -> super.initialize(context, fd, args[1], block);
default -> super.initialize(context, fd, args[1], args[2], block);
};
}
}
return openFile(context, args);
}
@JRubyMethod
public IRubyObject chmod(ThreadContext context, IRubyObject arg) {
checkClosed(context);
int mode = toInt(context, arg);
final String path = getPath();
if (!new File(path).exists()) throw context.runtime.newErrnoENOENTError(path);
return asFixnum(context, context.runtime.getPosix().chmod(path, mode));
}
@JRubyMethod
public IRubyObject chown(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
checkClosed(context);
int owner = !arg1.isNil() ? toInt(context, arg1) : -1;
int group = !arg2.isNil() ? toInt(context, arg2) : -1;
final String path = getPath();
if (!new File(path).exists()) throw context.runtime.newErrnoENOENTError(path);
return asFixnum(context, context.runtime.getPosix().chown(path, owner, group));
}
@JRubyMethod
public IRubyObject atime(ThreadContext context) {
checkClosed(context);
return context.runtime.newFileStat(getPath(), false).atime(context);
}
@JRubyMethod(name = "ctime")
public IRubyObject ctime(ThreadContext context) {
checkClosed(context);
return context.runtime.newFileStat(getPath(), false).ctime(context);
}
@JRubyMethod(name = "birthtime")
public IRubyObject birthtime(ThreadContext context) {
checkClosed(context);
if (!(Platform.IS_WINDOWS || (Platform.IS_BSD && !Platform.IS_OPENBSD))) {
throw context.runtime.newNotImplementedError("birthtime() function is unimplemented on this machine");
}
FileTime btime = getBirthtimeWithNIO(getPath());
if (btime != null) return context.runtime.newTime(btime.toMillis()); // btime comes in nanos
return ctime(context);
}
public static final FileTime getBirthtimeWithNIO(String pathString) {
// FIXME: birthtime is in stat, so we should use that if platform supports it (#2152)
Path path = Paths.get(pathString);
PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
try {
if (view != null) return view.readAttributes().creationTime();
} catch (IOException ioe) {
// ignore, just fall back on ctime
}
return null;
}
@JRubyMethod
public IRubyObject lstat(ThreadContext context) {
checkClosed(context);
return context.runtime.newFileStat(getPath(), true);
}
@JRubyMethod
public IRubyObject mtime(ThreadContext context) {
checkClosed(context);
return ((RubyFileStat) stat(context)).mtime(context);
}
@JRubyMethod(meta = true)
public static IRubyObject path(ThreadContext context, IRubyObject self, IRubyObject str) {
return get_path(context, str);
}
// Moved to IO in 3.2
public IRubyObject path(ThreadContext context) {
return super.path(context);
}
@JRubyMethod
public IRubyObject truncate(ThreadContext context, IRubyObject len) {
long pos = toInt(context, len);
OpenFile fptr = getOpenFileChecked();
if (!fptr.isWritable()) throw context.runtime.newIOError("not opened for writing");
flushRaw(context, false);
if (pos < 0) throw context.runtime.newErrnoEINVALError(openFile.getPath());
if (fptr.posix.ftruncate(fptr.fd(), pos) < 0) {
throw context.runtime.newErrnoFromErrno(fptr.posix.getErrno(), fptr.getPath());
}
return asFixnum(context, 0);
}
private static final byte[] CLOSED_MESSAGE = new byte[] {' ', '(', 'c', 'l', 'o', 's', 'e', 'd', ')'};
@JRubyMethod
public RubyString inspect(ThreadContext context) {
final String path = openFile.getPath();
ByteList str = new ByteList((path == null ? 4 : path.length()) + 8);
str.append('#').append('<');
str.append(((RubyString) getMetaClass().getRealClass().to_s(context)).getByteList());
str.append(':').append(path == null ? RubyNil.nilBytes : RubyEncoding.encodeUTF8(path));
if (!openFile.isOpen()) str.append(CLOSED_MESSAGE);
str.append('>');
// MRI knows whether path is UTF-8 so it might return ASCII-8BIT (we do not check)
str.setEncoding(UTF8Encoding.INSTANCE);
return RubyString.newStringLight(context.runtime, str);
}
private static final String URI_PREFIX_STRING = "^(uri|jar|file|classpath):([^:/]{2,}:([^:/]{2,}:)?)?";
private static final Pattern ROOT_PATTERN = Pattern.compile(URI_PREFIX_STRING + "/?/?$");
private static final int NULL_CHAR = '\0';
/* File class methods */
@JRubyMethod(meta = true) // required = 1, optional = 1
public static RubyString basename(ThreadContext context, IRubyObject recv, IRubyObject path) {
return basenameImpl(context, (RubyClass) recv, path, null);
}
@JRubyMethod(meta = true) // required = 1, optional = 1
public static RubyString basename(ThreadContext context, IRubyObject recv, IRubyObject path, IRubyObject ext) {
return basenameImpl(context, (RubyClass) recv, path, ext == context.nil ? null : ext);
}
private static RubyString basenameImpl(ThreadContext context, RubyClass klass, IRubyObject path, IRubyObject ext) {
final int separatorChar = getSeparatorChar(context, klass);
final int altSeparatorChar = getAltSeparatorChar(context, klass);
RubyString origString = get_path(context, path);
Encoding origEncoding = origString.getEncoding();
String name = origString.toString();
// uri-like paths without parent directory
if (name.endsWith(".jar!/") || ROOT_PATTERN.matcher(name).matches()) return (RubyString) path;
// 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, origString.getEncoding());
case 3:
return newString(context, RubyString.encodeBytelist(name.substring(2), origEncoding));
default:
switch (name.charAt(2)) {
case '/', '\\':
break;
default:
// strip c: away from relative-pathed name
name = name.substring(2);
}
break;
}
}
}
while (name.length() > 1 && (name.charAt(name.length() - 1) == separatorChar || (name.charAt(name.length() - 1) == altSeparatorChar))) {
name = name.substring(0, name.length() - 1);
}
// Paths which end in File::SEPARATOR or File::ALT_SEPARATOR 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 != separatorChar && c != altSeparatorChar) {
break;
}
slashCount++;
}
if (slashCount > 0 && length > 1) {
name = name.substring(0, name.length() - slashCount);
}
int index = name.lastIndexOf(separatorChar);
if (altSeparatorChar != NULL_CHAR) {
index = Math.max(index, name.lastIndexOf(altSeparatorChar));
}
if (!(contentEquals(name, separatorChar) || (contentEquals(name, altSeparatorChar))) && index != -1) {
name = name.substring(index + 1);
}
if (ext != null) {
final String extStr = RubyString.stringValue(ext).toString();
if (".*".equals(extStr)) {
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(extStr)) {
name = name.substring(0, name.length() - extStr.length());
}
}
return newString(context, RubyString.encodeBytelist(name, origEncoding));
}
private static int getSeparatorChar(ThreadContext context, final RubyClass File) {
final RubyString sep = RubyString.stringValue(File.getConstant(context, "SEPARATOR"));
return sep.getByteList().get(0);
}
private static int getAltSeparatorChar(ThreadContext context, final RubyClass File) {
final IRubyObject sep = File.getConstant(context, "ALT_SEPARATOR");
return sep instanceof RubyString sepStr ? sepStr.getByteList().get(0) : NULL_CHAR;
}
@JRubyMethod(required = 2, rest = true, checkArity = false, meta = true)
public static IRubyObject chmod(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
int argc = Arity.checkArgumentCount(context, args, 2, -1);
int count = 0;
int mode = toInt(context, args[0]);
for (int i = 1; i < argc; i++, count++) {
JRubyFile filename = fileResource(context, args[i]).unwrap(JRubyFile.class);
if (!filename.exists()) throw context.runtime.newErrnoENOENTError(filename.toString());
if (0 != context.runtime.getPosix().chmod(filename.getAbsolutePath(), mode)) {
throw context.runtime.newErrnoFromLastPOSIXErrno();
}
}
return asFixnum(context, count);
}
@JRubyMethod(required = 2, rest = true, checkArity = false, meta = true)
public static IRubyObject chown(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
int argc = Arity.checkArgumentCount(context, args, 2, -1);
int count = 0;
int owner = !args[0].isNil() ? toInt(context, args[0]) : -1;
int group = !args[1].isNil() ? toInt(context, args[1]) : -1;
for (int i = 2; i < argc; i++) {
JRubyFile filename = file(context, args[i]);
if (!filename.exists()) throw context.runtime.newErrnoENOENTError(filename.toString());
if (0 != context.runtime.getPosix().chown(filename.getAbsolutePath(), owner, group)) {
throw context.runtime.newErrnoFromLastPOSIXErrno();
} else {
count++;
}
}
return asFixnum(context, count);
}
@JRubyMethod(meta = true)
public static IRubyObject dirname(ThreadContext context, IRubyObject recv, IRubyObject path) {
return dirnameCommon(context, get_path(context, path), 1);
}
@JRubyMethod(meta = true)
public static IRubyObject dirname(ThreadContext context, IRubyObject recv, IRubyObject path, IRubyObject arg1) {
return dirnameCommon(context, get_path(context, path), toInt(context, arg1));
}
private static RubyString dirnameCommon(ThreadContext context, RubyString filename, int level) {
return newString(context, dirname(context, filename.asJavaString(), level));
}
static final Pattern PROTOCOL_PATTERN = Pattern.compile(URI_PREFIX_STRING + ".*");
public static String dirname(ThreadContext context, final String filename) {
return dirname(context, filename, 1);
}
public static String dirname(ThreadContext context, final String filename, int level) {
if (level < 0) throw argumentError(context, "negative level: " + level);
final RubyClass File = fileClass(context);
IRubyObject sep = File.getConstant(context, "SEPARATOR");
final String separator; final char separatorChar;
if (sep instanceof RubyString && ((RubyString) sep).size() == 1) {
separatorChar = ((RubyString) sep).getByteList().charAt(0);
separator = (separatorChar == '/') ? "/" : String.valueOf(separatorChar);
} else {
separator = sep.toString();
separatorChar = separator.isEmpty() ? '\0' : separator.charAt(0);
}
String altSeparator = null; char altSeparatorChar = '\0';
final IRubyObject rbAltSeparator = File.getConstantNoConstMissing(context, "ALT_SEPARATOR");
if (rbAltSeparator != null && rbAltSeparator != context.nil) {
altSeparator = rbAltSeparator.toString();
if (!altSeparator.isEmpty()) altSeparatorChar = altSeparator.charAt(0);
}
String name = filename;
if (altSeparator != null) name = replace(filename, altSeparator, separator);
boolean startsWithSeparator = false;
if (!name.isEmpty()) startsWithSeparator = name.charAt(0) == separatorChar;
int idx; // jar like paths
if ((idx = name.indexOf(".jar!")) != -1 && name.startsWith(separator, idx + 5)) {
int start = name.indexOf("!" + separator) + 1;
String path = dirname(context, name.substring(start));
if (path.equals(".") || path.equals(separator)) path = "";
return name.substring(0, start) + path;
}
// address all the url like paths first
if (PROTOCOL_PATTERN.matcher(name).matches()) {
int start = name.indexOf(":" + separator) + 2;
String path = dirname(context, name.substring(start));
if (path.equals(".")) path = "";
return name.substring(0, start) + path;
}
int minPathLength = 1;
boolean trimmedSlashes = false;
boolean startsWithUNCOnWindows = Platform.IS_WINDOWS && startsWith(name, separatorChar, separatorChar);
if (startsWithUNCOnWindows) minPathLength = 2;
boolean startsWithDriveLetterOnWindows = startsWithDriveLetterOnWindows(name);
if (startsWithDriveLetterOnWindows) minPathLength = 3;
while (name.length() > minPathLength && name.charAt(name.length() - 1) == separatorChar) {
trimmedSlashes = true;
name = name.substring(0, name.length() - 1);
}
String result;
if (startsWithDriveLetterOnWindows && name.length() == 2) {
if (trimmedSlashes) {
// C:\ is returned unchanged
result = filename.substring(0, 3);
} else {
result = filename.substring(0, 2) + '.';
}
} else {
//TODO deal with UNC names
int index = name.lastIndexOf(separator);
if (index == -1) {
if (startsWithDriveLetterOnWindows) {
return filename.substring(0, 2) + '.';
}
return level == 0 ? name : ".";
}
if (index == 0) {
return filename.substring(0, 1);
}
if (startsWithDriveLetterOnWindows && index == 2) {
// Include additional path separator
// (so that dirname of "C:\file.txt" is "C:\", not "C:")
index++;
}
if (startsWithUNCOnWindows) {
index = filename.length();
List<String> split = StringSupport.split(name, separatorChar);
int pathSectionCount = 0;
for (int i = 0; i < split.size(); i++) {
if (!split.get(i).isEmpty()) pathSectionCount += 1;
}
if (pathSectionCount > 2) index = name.lastIndexOf(separator);
}
result = filename.substring(0, index);
for (int i = level - 1; i > 0; i--) {
int _index = result.lastIndexOf(separator);
if (_index == 0) {
result = separator;
break;
} else if (_index != -1) {
result = result.substring(0, _index);
}
}
}
// trim leading slashes
if (startsWithSeparator && result.length() > minPathLength) {
while ( result.length() > minPathLength &&
(result.charAt(minPathLength) == separatorChar ||
(altSeparator != null && result.charAt(minPathLength) == altSeparatorChar)) ) {
result = result.substring(1, result.length());
}
}
char endChar;
// trim trailing slashes
while (result.length() > minPathLength) {
endChar = result.charAt(result.length() - 1);
if (endChar == separatorChar || (altSeparator != null && endChar == altSeparatorChar)) {
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(meta = true)
public static IRubyObject extname(ThreadContext context, IRubyObject recv, IRubyObject arg) {
String filename = basename(context, recv, arg).toString();
int dotIndex = filename.indexOf('.');
if (dotIndex < 0) return newEmptyString(context);
int length = filename.length();
if (dotIndex == length - 1 && length != 1) return newString(context, filename.substring(dotIndex));
int e = dotIndex;
// skip through whole sequence of '........'
for (e = e + 1; e < length; e++) {
if (filename.charAt(e) != '.') {
e = e - 1;
break;
}
}
if (e == length) return newEmptyString(context); // all dots
for (int i = e; i < length; i++) {
char c = filename.charAt(i);
if (c == '.' || c == ' ') e = i;
}
return e == 0 ? newEmptyString(context) : newString(context, filename.substring(e));
}
/**
* Converts a pathname to an absolute pathname. Relative paths are
* referenced from the current working directory of the process.
* @param recv
* @param path
* @return Resulting absolute path as a String
*/
@JRubyMethod(name = "expand_path", meta = true)
public static IRubyObject expand_path(ThreadContext context, IRubyObject recv, IRubyObject path) {
return expandPathInternal(context, path, true, false);
}
/**
* Converts a pathname to an absolute pathname. Relative paths are
* referenced from the given working directory. If the second argument is also relative, it will
* first be converted to an absolute pathname.
* @param recv
* @param path
* @param wd
* @return Resulting absolute path as a String
*/
@JRubyMethod(name = "expand_path", meta = true)
public static IRubyObject expand_path(ThreadContext context, IRubyObject recv, IRubyObject path, IRubyObject wd) {
return expandPathInternal(context, path, wd, true, false);
}
/**
* Converts a pathname to an absolute pathname. Relative paths are
* referenced from the current working directory of the process.
* If the given pathname starts with a ``+~+'' it is
* NOT expanded, it is treated as a normal directory name.
*
* @param context
* @param recv
* @param path
* @return
*/
@JRubyMethod(meta = true)
public static IRubyObject absolute_path(ThreadContext context, IRubyObject recv, IRubyObject path) {
return expandPathInternal(context, path, false, false);
}
/**
* Converts a pathname to an absolute pathname. Relative paths are
* referenced from _dir_. If the given pathname starts with a ``+~+'' it is
* NOT expanded, it is treated as a normal directory name.
*
* @param context
* @param recv
* @param path
* @param dir
* @return
*/
@JRubyMethod(meta = true)
public static IRubyObject absolute_path(ThreadContext context, IRubyObject recv, IRubyObject path, IRubyObject dir) {
return expandPathInternal(context, path, dir, false, false);
}
@JRubyMethod(name = "absolute_path?", meta = true)
public static IRubyObject absolute_path_p(ThreadContext context, IRubyObject recv, IRubyObject arg) {
RubyString file = get_path(context, arg);
// asJavaString should be ok here since windows drive shares will be charset representable and otherwise we look for "/" at front.
return asBoolean(context, isJRubyAbsolutePath(file.asJavaString()));
}
@JRubyMethod(meta = true)
public static IRubyObject realdirpath(ThreadContext context, IRubyObject recv, IRubyObject path) {
return expandPathInternal(context, path, false, true);
}
@JRubyMethod(meta = true)
public static IRubyObject realdirpath(ThreadContext context, IRubyObject recv, IRubyObject path, IRubyObject dir) {
return expandPathInternal(context, path, dir, false, true);
}
@JRubyMethod(meta = true)
public static IRubyObject realpath(ThreadContext context, IRubyObject recv, IRubyObject path) {
return realPathCommon(context, get_path(context, path), null);
}
@JRubyMethod(meta = true)
public static IRubyObject realpath(ThreadContext context, IRubyObject recv, IRubyObject path, IRubyObject cwd) {
return realPathCommon(context, get_path(context, path), get_path(context, cwd));
}
private static RubyString realPathCommon(ThreadContext context, RubyString file, RubyString cwd) {
file = expandPathInternal(context, file, cwd, false, true);
if (!RubyFileTest.exist(context, file)) 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?"}, meta = true)
public static IRubyObject fnmatch(ThreadContext context, IRubyObject recv, IRubyObject _pattern, IRubyObject _path) {
return fnmatchCommon(context, _pattern, _path, 0);
}
@JRubyMethod(name = {"fnmatch", "fnmatch?"}, meta = true)
public static IRubyObject fnmatch(ThreadContext context, IRubyObject recv, IRubyObject _pattern, IRubyObject _path, IRubyObject _flags) {
return fnmatchCommon(context, _pattern, _path, toInt(context, _flags));
}
private static RubyBoolean fnmatchCommon(ThreadContext context, IRubyObject _path, IRubyObject _pattern, int flags) {
boolean braces_match = false;
boolean extglob = (flags & FNM_EXTGLOB) != 0;
ByteList pattern = checkEmbeddedNulls(context, _path.convertToString()).getByteList();
ByteList path = checkEmbeddedNulls(context, get_path(context, _pattern)).getByteList();
if (extglob) {
String spattern = _path.asJavaString();
ArrayList<String> patterns = Dir.braces(spattern, flags, new ArrayList<>());
boolean matches = false;
for(int i = 0; i < patterns.size(); i++) {
matches |= dir_fnmatch(new ByteList(patterns.get(i).getBytes()), path, flags);
}
braces_match = matches;
}
return braces_match || dir_fnmatch(pattern, path, flags) ? context.tru : context.fals;
}
private static boolean dir_fnmatch(ByteList pattern, ByteList path, int flags) {
return Dir.fnmatch(pattern.getUnsafeBytes(),
pattern.getBegin(),
pattern.getBegin() + pattern.getRealSize(),
path.getUnsafeBytes(),
path.getBegin(),
path.getBegin() + path.getRealSize(),
flags,
path.getEncoding()) == 0;
}
@JRubyMethod(name = "ftype", meta = true)
public static IRubyObject ftype(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).toString(), true).ftype(context);
}
@JRubyMethod(rest = true, meta = true)
public static RubyString join(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return doJoin(context, recv, args);
}
@JRubyMethod(name = "lstat", meta = true)
public static IRubyObject lstat(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).toString(), true);
}
@JRubyMethod(name = "stat", meta = true)
public static IRubyObject stat(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).toString(), false);
}
@JRubyMethod(name = "atime", meta = true)
public static IRubyObject atime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).toString(), false).atime(context);
}
@JRubyMethod(name = "ctime", meta = true)
public static IRubyObject ctime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).toString(), false).ctime(context);
}
@JRubyMethod(name = "birthtime", meta = true)
public static IRubyObject birthtime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.runtime.newFileStat(get_path(context, filename).toString(), false).birthtime(context);
}
@JRubyMethod(required = 1, rest = true, checkArity = false, meta = true)
public static IRubyObject lchmod(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
int argc = Arity.checkArgumentCount(context, args, 1, -1);
int count = 0;
int mode = toInt(context, args[0]);
for (int i = 1; i < argc; i++, count++) {
JRubyFile file = file(context, args[i]);
if (context.runtime.getPosix().lchmod(file.toString(), mode) != 0) {
throw context.runtime.newErrnoFromLastPOSIXErrno();
}
}
return asFixnum(context, count);
}
@JRubyMethod(required = 2, rest = true, checkArity = false, meta = true)
public static IRubyObject lchown(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
int argc = Arity.checkArgumentCount(context, args, 2, -1);
int owner = !args[0].isNil() ? toInt(context, args[0]) : -1;
int group = !args[1].isNil() ? toInt(context, args[1]) : -1;
int count = 0;
for (int i = 2; i < argc; i++) {
JRubyFile file = file(context, args[i]);
if (0 != context.runtime.getPosix().lchown(file.toString(), owner, group)) {
throw context.runtime.newErrnoFromLastPOSIXErrno();
} else {
count++;
}
}
return asFixnum(context, count);
}
@JRubyMethod(meta = true)
public static IRubyObject link(ThreadContext context, IRubyObject recv, IRubyObject from, IRubyObject to) {
Ruby runtime = context.runtime;