File: FileCheck.pm

package info (click to toggle)
liboverload-filecheck-perl 0.013-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,088 kB
  • sloc: perl: 2,030; ansic: 97; makefile: 8
file content (1550 lines) | stat: -rw-r--r-- 42,661 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
# Copyright (c) 2018, cPanel, LLC.
# All rights reserved.
# http://cpanel.net
#
# This is free software; you can redistribute it and/or modify it under the
# same terms as Perl itself. See L<perlartistic>.

package Overload::FileCheck;

use strict;
use warnings;

# ABSTRACT: override/mock perl file check -X: -e, -f, -d, ...

use Errno ();

use base 'Exporter';

BEGIN {

    our $VERSION = '0.013'; # VERSION: generated by DZP::OurPkgVersion

    require XSLoader;
    XSLoader::load(__PACKAGE__);
}

use Fcntl (
    '_S_IFMT',     # bit mask for the file type bit field
                   #'S_IFPERMS',   # bit mask for file perms.
    'S_IFSOCK',    # socket
    'S_IFLNK',     # symbolic link
    'S_IFREG',     # regular file
    'S_IFBLK',     # block device
    'S_IFDIR',     # directory
    'S_IFCHR',     # character device
    'S_IFIFO',     # FIFO

    # qw{S_IRUSR S_IWUSR S_IXUSR S_IRWXU}
);

my @STAT_T_IX = qw{
  ST_DEV
  ST_INO
  ST_MODE
  ST_NLINK
  ST_UID
  ST_GID
  ST_RDEV
  ST_SIZE
  ST_ATIME
  ST_MTIME
  ST_CTIME
  ST_BLKSIZE
  ST_BLOCKS
};

my @CHECK_STATUS = qw{CHECK_IS_FALSE CHECK_IS_TRUE FALLBACK_TO_REAL_OP};

my @STAT_HELPERS = qw{ stat_as_directory stat_as_file stat_as_symlink
  stat_as_socket stat_as_chr stat_as_block};

our @EXPORT_OK = (
    qw{
      mock_all_from_stat
      mock_all_file_checks mock_file_check mock_stat
      unmock_file_check unmock_all_file_checks unmock_stat
      },
    @CHECK_STATUS,
    @STAT_T_IX,
    @STAT_HELPERS,
);

our %EXPORT_TAGS = (
    all => [@EXPORT_OK],

    # status code
    check => [@CHECK_STATUS],

    # STAT array indexes
    stat => [ @STAT_T_IX, @STAT_HELPERS ],
);

# hash for every filecheck we can mock
#   and their corresonding OP_TYPE
my %MAP_FC_OP = (
    'R' => OP_FTRREAD,
    'W' => OP_FTRWRITE,
    'X' => OP_FTREXEC,
    'r' => OP_FTEREAD,
    'w' => OP_FTEWRITE,
    'x' => OP_FTEEXEC,

    'e' => OP_FTIS,
    's' => OP_FTSIZE,     # OP_CAN_RETURN_INT
    'M' => OP_FTMTIME,    # OP_CAN_RETURN_INT
    'C' => OP_FTCTIME,    # OP_CAN_RETURN_INT
    'A' => OP_FTATIME,    # OP_CAN_RETURN_INT

    'O' => OP_FTROWNED,
    'o' => OP_FTEOWNED,
    'z' => OP_FTZERO,
    'S' => OP_FTSOCK,
    'c' => OP_FTCHR,
    'b' => OP_FTBLK,
    'f' => OP_FTFILE,
    'd' => OP_FTDIR,
    'p' => OP_FTPIPE,
    'u' => OP_FTSUID,
    'g' => OP_FTSGID,
    'k' => OP_FTSVTX,

    'l' => OP_FTLINK,

    't' => OP_FTTTY,

    'T' => OP_FTTEXT,
    'B' => OP_FTBINARY,

    # special cases for stat & lstat
    'stat'  => OP_STAT,
    'lstat' => OP_LSTAT,

);

my %MAP_STAT_T_IX = (
    st_dev     => ST_DEV,
    st_ino     => ST_INO,
    st_mode    => ST_MODE,
    st_nlink   => ST_NLINK,
    st_uid     => ST_UID,
    st_gid     => ST_GID,
    st_rdev    => ST_RDEV,
    st_size    => ST_SIZE,
    st_atime   => ST_ATIME,
    st_mtime   => ST_MTIME,
    st_ctime   => ST_CTIME,
    st_blksize => ST_BLKSIZE,
    st_blocks  => ST_BLOCKS,
);

# op_type_id => check
my %REVERSE_MAP;

my %OP_CAN_RETURN_INT   = map { $MAP_FC_OP{$_} => 1 } qw{ s M C A };
my %OP_IS_STAT_OR_LSTAT = map { $MAP_FC_OP{$_} => 1 } qw{ stat lstat };
#
# This is listing the default ERRNO codes
#   used by each test when the test fails and
#   the user did not provide one ERRNO error
#
my %DEFAULT_ERRNO = (
    'default' => Errno::ENOENT,    # default value for any other not listed
    'x'       => Errno::ENOEXEC,
    'X'       => Errno::ENOEXEC,

    # ...
);

# this is saving our custom ops
# optype_id => sub
my $_current_mocks = {};

sub import {
    my ( $class, @args ) = @_;

    # mock on import...
    my $_next_check;
    my @for_exporter;
    foreach my $check (@args) {
        if ( !$_next_check && $check !~ qr{^-} ) {

            # this is a valid arg for exporter
            push @for_exporter, $check;
            next;
        }
        if ( !$_next_check ) {

            # we found a key like '-e' in '-e => sub {} '
            $_next_check = $check;
        }
        else {
            # now this is the value
            my $code = $check;

            # use Overload::FileCheck -from_stat => \&my_stat;
            if ( $_next_check eq q{-from_stat} || $_next_check eq q{-from-stat} ) {
                mock_all_from_stat($code);
            }
            else {
                mock_file_check( $_next_check, $code );
            }

            undef $_next_check;
        }
    }

    # callback the exporter logic
    return __PACKAGE__->export_to_level( 1, $class, @for_exporter );
}

sub mock_all_file_checks {
    my ($sub) = @_;

    foreach my $check ( sort keys %MAP_FC_OP ) {
        next if $check =~ qr{^l?stat$};    # we should not mock stat
        mock_file_check(
            $check,
            sub {
                my (@args) = @_;
                return $sub->( $check, @args );
            }
        );
    }

    return 1;
}

sub mock_file_check {
    my ( $check, $sub ) = @_;

    die q[Check is not defined] unless defined $check;
    die q[Second arg must be a CODE ref] unless ref $sub eq 'CODE';

    $check =~ s{^-+}{};    # strip any extra dashes
                           #return -1 unless defined $MAP_FC_OP{$check}; # we should not do that
    die qq[Unknown check '$check'] unless defined $MAP_FC_OP{$check};

    my $optype = $MAP_FC_OP{$check};
    die qq[-$check is already mocked by Overload::FileCheck] if exists $_current_mocks->{$optype};

    $_current_mocks->{$optype} = $sub;

    _xs_mock_op($optype);

    return 1;
}

sub unmock_file_check {
    my (@checks) = @_;

    foreach my $check (@checks) {
        die q[Check is not defined] unless defined $check;
        $check =~ s{^-+}{};    # strip any extra dashes
        die qq[Unknown check '$check'] unless defined $MAP_FC_OP{$check};

        my $optype = $MAP_FC_OP{$check};

        delete $_current_mocks->{$optype};

        _xs_unmock_op($optype);
    }

    return 1;
}

sub mock_all_from_stat {
    my ($sub_for_stat) = @_;

    # then mock all -X checks to our custom
    mock_all_file_checks(
        sub {
            my ( $check, $f_or_fh ) = @_;

            # the main call
            my $return = _check_from_stat( $check, $f_or_fh, $sub_for_stat );

            # auto remock the OP (it could have been temporary unmocked to use -X _)
            _xs_mock_op( $MAP_FC_OP{$check} );

            return $return;
        }
    );

    # start by mocking 'stat' and 'lstat' call
    mock_stat($sub_for_stat);

    return 1;
}

sub _check_from_stat {
    my ( $check, $f_or_fh, $sub_for_stat ) = @_;

    my $optype = $MAP_FC_OP{$check};

    # stat would need to be called twice
    # 1/ we first need to check if we are mocking the file
    #   or if we let it fallback to the Perl OP
    # 2/ doing a second stat call in order to cache _

    my $can_use_stat;
    $can_use_stat = 1 if $check =~ qr{^[sfdMXxzACORWeorw]$};

    my $stat_or_lstat = $can_use_stat ? 'stat' : 'lstat';

    my (@mocked_lstat_result) = $sub_for_stat->( $stat_or_lstat, $f_or_fh );
    if (   scalar @mocked_lstat_result == 1
        && !ref $mocked_lstat_result[0]
        && $mocked_lstat_result[0] == FALLBACK_TO_REAL_OP ) {
        return FALLBACK_TO_REAL_OP;
    }

    # avoid a second callback to the user hook (do not really happen for now)
    local $_current_mocks->{ $MAP_FC_OP{$stat_or_lstat} } = sub {
        return @mocked_lstat_result;
    };

    # now performing a real stat call [ using the mocked stat function ]
    my ( @stat, @lstat );

    if ($can_use_stat) {
        no warnings;    # throw warnings with Perl <= 5.14
        @stat = stat($f_or_fh) if defined $f_or_fh;
    }
    else {
        no warnings;
        @lstat = lstat($f_or_fh) if defined $f_or_fh;
    }

    if ( $check eq 'r' ) {

        # -r  File is readable by effective uid/gid.
        #  return _cando(stat_mode, effective, &PL_statcache)
        #   return _cando( S_IRUSR, 1 )

        # ugly need a better way to do this...
        _xs_unmock_op($optype);
        return _to_bool( scalar -r _ );
    }
    elsif ( $check eq 'w' ) {

        # -w  File is writable by effective uid/gid.
        _xs_unmock_op($optype);
        return _to_bool( scalar -w _ );
    }
    elsif ( $check eq 'x' ) {

        # -x  File is executable by effective uid/gid.
        _xs_unmock_op($optype);
        return _to_bool( scalar -x _ );
    }
    elsif ( $check eq 'o' ) {

        # -o  File is owned by effective uid.
        _xs_unmock_op($optype);
        return _to_bool( scalar -o _ );
    }
    elsif ( $check eq 'R' ) {

        # -R  File is readable by real uid/gid.
        _xs_unmock_op($optype);
        return _to_bool( scalar -R _ );
    }
    elsif ( $check eq 'W' ) {

        # -W  File is writable by real uid/gid.
        _xs_unmock_op($optype);
        return _to_bool( scalar -W _ );
    }
    elsif ( $check eq 'X' ) {

        # -X  File is executable by real uid/gid.

        _xs_unmock_op($optype);
        return _to_bool( scalar -X _ );
    }
    elsif ( $check eq 'O' ) {

        # -O  File is owned by real uid.
        _xs_unmock_op($optype);
        return _to_bool( scalar -O _ );
    }
    elsif ( $check eq 'e' ) {

        # -e  File exists.
        # a file can only exists if MODE is set ?
        return _to_bool( scalar @stat && $stat[ST_MODE] );
    }
    elsif ( $check eq 'z' ) {

        # -z  File has zero size (is empty).

        # TODO: can probably avoid the extra called...
        #   by checking it ourself

        _xs_unmock_op($optype);
        return _to_bool( scalar -z _ );
    }
    elsif ( $check eq 's' ) {

        # -s  File has nonzero size (returns size in bytes).

        # fallback does not work with symlinks
        #   do the check ourself, which also save a few calls

        return $stat[ST_SIZE];
    }
    elsif ( $check eq 'f' ) {

        # -f  File is a plain file.
        return _check_mode_type( $stat[ST_MODE], S_IFREG );
    }
    elsif ( $check eq 'd' ) {

        # -d  File is a directory.

        return _check_mode_type( $stat[ST_MODE], S_IFDIR );
    }
    elsif ( $check eq 'l' ) {

        # -l  File is a symbolic link (false if symlinks aren't
        #    supported by the file system).

        return _check_mode_type( $lstat[ST_MODE], S_IFLNK );
    }
    elsif ( $check eq 'p' ) {

        # -p  File is a named pipe (FIFO), or Filehandle is a pipe.
        return _check_mode_type( $lstat[ST_MODE], S_IFIFO );
    }
    elsif ( $check eq 'S' ) {

        # -S  File is a socket.
        return _check_mode_type( $lstat[ST_MODE], S_IFSOCK );
    }
    elsif ( $check eq 'b' ) {

        # -b  File is a block special file.
        return _check_mode_type( $lstat[ST_MODE], S_IFBLK );
    }
    elsif ( $check eq 'c' ) {

        # -c  File is a character special file.
        return _check_mode_type( $lstat[ST_MODE], S_IFCHR );
    }
    elsif ( $check eq 't' ) {

        # -t  Filehandle is opened to a tty.
        _xs_unmock_op($optype);
        return _to_bool( scalar -t _ );
    }
    elsif ( $check eq 'u' ) {

        # -u  File has setuid bit set.
        _xs_unmock_op($optype);
        return _to_bool( scalar -u _ );
    }
    elsif ( $check eq 'g' ) {

        # -g  File has setgid bit set.
        _xs_unmock_op($optype);
        return _to_bool( scalar -g _ );
    }
    elsif ( $check eq 'k' ) {

        # -k  File has sticky bit set.

        _xs_unmock_op($optype);
        return _to_bool( scalar -k _ );
    }
    elsif ( $check eq 'T' ) {    # heuristic guess.. throw a die?

        # -T  File is an ASCII or UTF-8 text file (heuristic guess).

        #return CHECK_IS_FALSE if -d $f_or_fh;

        _xs_unmock_op($optype);
        return _to_bool( scalar -T *_ );
    }
    elsif ( $check eq 'B' ) {    # heuristic guess.. throw a die?

        # -B  File is a "binary" file (opposite of -T).

        return CHECK_IS_TRUE if -d $f_or_fh;

        # ... we cannot really know...
        # ... this is an heuristic guess...

        _xs_unmock_op($optype);
        return _to_bool( scalar -B *_ );
    }
    elsif ( $check eq 'M' ) {

        # -M  Script start time minus file modification time, in days.

        return CHECK_IS_NULL unless scalar @stat && defined $stat[ST_MTIME];
        return ( ( get_basetime() - $stat[ST_MTIME] ) / 86400.0 );

        #return int( scalar -M _ );
    }
    elsif ( $check eq 'A' ) {

        # -A  Same for access time.
        #
        # ((NV)PL_basetime - PL_statcache.st_atime) / 86400.0
        return CHECK_IS_NULL unless scalar @stat && defined $stat[ST_ATIME];

        return ( ( get_basetime() - $stat[ST_ATIME] ) / 86400.0 );
    }
    elsif ( $check eq 'C' ) {

        # -C  Same for inode change time (Unix, may differ for other
        #_xs_unmock_op($optype);
        #return scalar -C *_;
        return CHECK_IS_NULL unless scalar @stat && defined $stat[ST_CTIME];

        return ( ( get_basetime() - $stat[ST_CTIME] ) / 86400.0 );
    }
    else {
        die "Unknown check $check.\n";
    }

    die "FileCheck -$check is not implemented by Overload::FileCheck...";

    return FALLBACK_TO_REAL_OP;
}

sub _to_bool {
    my ($s) = @_;

    return ( $s ? CHECK_IS_TRUE : CHECK_IS_FALSE );
}

sub _check_mode_type {
    my ( $mode, $type ) = @_;

    return CHECK_IS_FALSE unless defined $mode;
    return _to_bool( ( $mode & _S_IFMT ) == $type );
}

# this is a special case used to mock OP_STAT & OP_LSTAT
sub mock_stat {
    my ($sub) = @_;

    die q[First arg must be a CODE ref] unless ref $sub eq 'CODE';

    foreach my $opname (qw{stat lstat}) {
        my $optype = $MAP_FC_OP{$opname};
        die qq[No optype found for $opname] unless $optype;

        # plug the sub
        $_current_mocks->{$optype} = sub {
            my $file_or_handle = shift;
            return $sub->( $opname, $file_or_handle );
        };

        # setup the mock for the OP
        _xs_mock_op($optype);
    }

    return 1;
}

# just an alias to unmock stat & lstat at the same time
sub unmock_stat {
    return unmock_file_check(qw{stat lstat});
}

sub unmock_all_file_checks {

    if ( !scalar %REVERSE_MAP ) {
        foreach my $k ( keys %MAP_FC_OP ) {
            $REVERSE_MAP{ $MAP_FC_OP{$k} } = $k;
        }
    }

    my @mocks = sort map { $REVERSE_MAP{$_} } keys %$_current_mocks;
    return unless scalar @mocks;

    return unmock_file_check(@mocks);
}

# should not be called directly
# this is called from XS to check if one OP is mocked
# and trigger the callback function when mocked
my $_last_call_for;

sub _check {
    my ( $optype, $file, @others ) = @_;

    die if scalar @others;    # need to move this in a unit test

    # we have no custom mock at this point
    return FALLBACK_TO_REAL_OP unless defined $_current_mocks->{$optype};

    $file = $_last_call_for if !defined $file && defined $_last_call_for && !defined $_current_mocks->{ $MAP_FC_OP{'stat'} };
    my ( $out, @extra ) = $_current_mocks->{$optype}->($file);
    $_last_call_for = $file;

    # FIXME return undef when not defined out

    if ( defined $out && $OP_CAN_RETURN_INT{$optype} ) {
        return $out;          # limitation to int for now in fact some returns NVs
    }

    if ( !$out ) {

        # check if the user provided a custom ERRNO error otherwise
        #   set one for him, so a test could never fail without having
        #   ERRNO set
        if ( !int($!) ) {
            $! = $DEFAULT_ERRNO{ $REVERSE_MAP{$optype} || 'default' } || $DEFAULT_ERRNO{'default'};
        }

        #return undef unless defined $out;
        return CHECK_IS_FALSE;
    }

    return FALLBACK_TO_REAL_OP if !ref $out && $out == FALLBACK_TO_REAL_OP;

    # stat and lstat OP are returning a stat ARRAY in addition to the status code
    if ( $OP_IS_STAT_OR_LSTAT{$optype} ) {

        # .......... Stat_t
        # dev_t     st_dev     Device ID of device containing file.
        # ino_t     st_ino     File serial number.
        # mode_t    st_mode    Mode of file (see below).
        # nlink_t   st_nlink   Number of hard links to the file.
        # uid_t     st_uid     User ID of file.
        # gid_t     st_gid     Group ID of file.
        # dev_t     st_rdev    Device ID (if file is character or block special).
        # off_t     st_size    For regular files, the file size in bytes.
        # time_t    st_atime   Time of last access.
        # time_t    st_mtime   Time of last data modification.
        # time_t    st_ctime   Time of last status change.
        # blksize_t st_blksize A file system-specific preferred I/O block size for
        # blkcnt_t  st_blocks  Number of blocks allocated for this object.
        # ......

        my $stat      = $out // $others[0];    # can be array or hash at this point
        my $stat_is_a = ref $stat;
        die q[Your mocked function for stat should return a stat array or hash] unless $stat_is_a;

        my $stat_as_arrayref;

        # can handle one ARRAY or a HASH
        my $stat_t_max = STAT_T_MAX;
        if ( $stat_is_a eq 'ARRAY' ) {
            $stat_as_arrayref = $stat;
            my $av_size = scalar @$stat;
            if (
                $av_size                       # 0 is valid when the file is missing
                && $av_size != $stat_t_max
            ) {
                die qq[Stat array should contain exactly 0 or $stat_t_max values];
            }
        }
        elsif ( $stat_is_a eq 'HASH' ) {
            $stat_as_arrayref = [ (0) x $stat_t_max ];    # start with an empty array
            foreach my $k ( keys %$stat ) {
                my $ix = $MAP_STAT_T_IX{ lc($k) };
                die qq[Unknown index for stat_t struct key $k] unless defined $ix;
                $stat_as_arrayref->[$ix] = $stat->{$k};
            }
        }
        else {
            die q[Your mocked function for stat should return a stat array or hash];
        }

        return ( CHECK_IS_TRUE, $stat_as_arrayref );
    }

    return CHECK_IS_TRUE;
}

# accessors for testing purpose mainly
sub _get_filecheck_ops_map {
    return {%MAP_FC_OP};    # return a copy
}

######################################################
### stat helpers
######################################################

sub stat_as_directory {
    my (%opts) = @_;

    return _stat_for( S_IFDIR, \%opts );
}

sub stat_as_file {
    my (%opts) = @_;

    return _stat_for( S_IFREG, \%opts );
}

sub stat_as_symlink {
    my (%opts) = @_;

    return _stat_for( S_IFLNK, \%opts );
}

sub stat_as_socket {
    my (%opts) = @_;

    return _stat_for( S_IFSOCK, \%opts );
}

sub stat_as_chr {
    my (%opts) = @_;

    return _stat_for( S_IFCHR, \%opts );
}

sub stat_as_block {
    my (%opts) = @_;

    return _stat_for( S_IFBLK, \%opts );
}

sub _stat_for {
    my ( $type, $opts ) = @_;

    my @stat = ( (0) x 13 );    # STAT_T_MAX

    # set file type
    if ( defined $type ) {

        # _S_IFMT is used as a protection to do not flip outside the mask
        $stat[ST_MODE] |= ( $type & _S_IFMT );
    }

    # set permission using octal
    if ( defined $opts->{perms} ) {

        # _S_IFMT is used as a protection to do not flip outside the mask
        $stat[ST_MODE] |= ( $opts->{perms} & ~_S_IFMT );
    }

    # deal with UID / GID
    if ( defined $opts->{uid} ) {
        if ( $opts->{uid} =~ qr{^[0-9]+$} ) {
            $stat[ST_UID] = $opts->{uid};
        }
        else {

            $stat[ST_UID] = getpwnam( $opts->{uid} );
        }
    }

    if ( defined $opts->{gid} ) {
        if ( $opts->{gid} =~ qr{^[0-9]+$} ) {
            $stat[ST_GID] = $opts->{gid};
        }
        else {
            $stat[ST_GID] = getgrnam( $opts->{gid} );
        }
    }

    # options that we can simply copy to a slot
    my %name2ix = (
        size    => ST_SIZE,
        atime   => ST_ATIME,
        mtime   => ST_MTIME,
        ctime   => ST_CTIME,
        blksize => ST_BLKSIZE,
        blocks  => ST_BLOCKS,
    );

    foreach my $k ( keys %$opts ) {
        $k = lc($k);
        $k =~ s{^st_}{};
        next unless defined $name2ix{$k};

        $stat[ $name2ix{$k} ] = $opts->{$k};
    }

    return \@stat;
}

1;

__END__

=pod

=encoding utf-8

=head1 NAME

Overload::FileCheck - override/mock perl file check -X: -e, -f, -d, ...

=head1 VERSION

version 0.013

=head1 SYNOPSIS

Overload::FileCheck provides a way to mock one or more file checks.
It is also possible to mock stat/lstat functions using L<"mock_all_from_stat"> and let Overload::FileCheck
mock for you for any other -X checks.

By using mock_all_file_checks you can set a hook function to reply any -X check.

 #!perl
 
 use strict;
 use warnings;
 
 use strict;
 use warnings;
 
 use Test::More;
 use Overload::FileCheck q{:all};
 
 my @exist     = qw{cherry banana apple};
 my @not_there = qw{not-there missing-file};
 
 mock_all_file_checks( \&my_custom_check );
 
 sub my_custom_check {
     my ( $check, $f ) = @_;
 
     if ( $check eq 'e' || $check eq 'f' ) {
         return CHECK_IS_TRUE  if grep { $_ eq $f } @exist;
         return CHECK_IS_FALSE if grep { $_ eq $f } @not_there;
     }
 
     return CHECK_IS_FALSE if $check eq 'd' && grep { $_ eq $f } @exist;
 
     # fallback to the original Perl OP
     return FALLBACK_TO_REAL_OP;
 }
 
 foreach my $f (@exist) {
     ok( -e $f,  "-e $f is true" );
     ok( -f $f,  "-f $f is true" );
     ok( !-d $f, "-d $f is false" );
 }
 
 foreach my $f (@not_there) {
     ok( !-e $f, "-e $f is false" );
     ok( !-f $f, "-f $f is false" );
 }
 
 unmock_all_file_checks();
 
 done_testing;

=head1 DESCRIPTION

Overload::FileCheck provides a hook system to mock Perl filechecks OPs

=for markdown [![](https://github.com/CpanelInc/Overload-FileCheck/workflows/linux/badge.svg)](https://github.com/CpanelInc/Overload-FileCheck/actions) [![](https://github.com/CpanelInc/Overload-FileCheck/workflows/macos/badge.svg)](https://github.com/CpanelInc/Overload-FileCheck/actions) [![](https://github.com/CpanelInc/Overload-FileCheck/workflows/windows/badge.svg)](https://github.com/CpanelInc/Overload-FileCheck/actions)

=for HTML <p><img src="https://travis-ci.org/CpanelInc/Overload-FileCheck.svg?branch=master" width="81" height="18" alt="Travis CI" /></p>

With this module you can provide your own pure perl code when performing
file checks using one of the -X ops: -e, -f, -z, ...

L<https://perldoc.perl.org/functions/-X.html>

    -r  File is readable by effective uid/gid.
    -w  File is writable by effective uid/gid.
    -x  File is executable by effective uid/gid.
    -o  File is owned by effective uid.
    -R  File is readable by real uid/gid.
    -W  File is writable by real uid/gid.
    -X  File is executable by real uid/gid.
    -O  File is owned by real uid.
    -e  File exists.
    -z  File has zero size (is empty).
    -s  File has nonzero size (returns size in bytes).
    -f  File is a plain file.
    -d  File is a directory.
    -l  File is a symbolic link (false if symlinks aren't
        supported by the file system).
    -p  File is a named pipe (FIFO), or Filehandle is a pipe.
    -S  File is a socket.
    -b  File is a block special file.
    -c  File is a character special file.
    -t  Filehandle is opened to a tty.
    -u  File has setuid bit set.
    -g  File has setgid bit set.
    -k  File has sticky bit set.
    -T  File is an ASCII or UTF-8 text file (heuristic guess).
    -B  File is a "binary" file (opposite of -T).
    -M  Script start time minus file modification time, in days.
    -A  Same for access time.
    -C  Same for inode change time (Unix, may differ for other
  platforms)

Also view pp_sys.c from the Perl source code, where are defined the original OPs.

In addition it's also possible to mock the Perl OP C<stat> and C<lstat>, read L</"Mocking stat and lstat"> section for more details.

=head1 Usage and Examples

When using this module, you can decide to mock filecheck OPs on import or later
at run time.

=head2 Mocking filecheck at import time

You can mock multiple filecheck at import time.
Note that the ':check' will import constants like:
CHECK_IS_TRUE, CHECK_IS_FALSE, FALLBACK_TO_REAL_OP
which are recommended return values to use in your hook functions.

 #!perl
 
 use strict;
 use warnings;
 
 use Overload::FileCheck '-e' => \&my_dash_e, -f => sub { 1 }, ':check';
 
 # example of your own callback function to mock -e
 # when returning
 #  0: the test is false
 #  1: the test is true
 # -1: you want to use the answer from Perl itself :-)
 
 sub dash_e {
     my ($file_or_handle) = @_;
 
     # return true on -e for this specific file
     return CHECK_IS_TRUE if $file_or_handle eq '/this/file/is/not/there/but/act/like/if/it/was';
 
     # claim that /tmp is not available even if it exists
     return CHECK_IS_FALSE if $file_or_handle eq '/tmp';
 
     # delegate the answer to the Perl CORE -e OP
     #   as we do not want to control these files
     return FALLBACK_TO_REAL_OP;
 }

=head2 Mocking filecheck at run time

You can also get a similar behavior by declaring the overload later at run time.

 #!perl
 
 use strict;
 use warnings;
 
 use Overload::FileCheck q(:all);
 
 mock_file_check( '-e' => \&my_dash_e );
 mock_file_check( '-f' => sub { CHECK_IS_TRUE } );
 
 sub dash_e {
     my ($file_or_fh) = @_;
 
     # return true on -e for this specific file
     return CHECK_IS_TRUE if $file_or_fh eq '/this/file/is/not/there/but/act/like/if/it/was';
 
     # claim that /tmp is not available even if it exists
     return CHECK_IS_FALSE if $file_or_fh eq '/tmp';
 
     # delegate the answer to the Perl CORE -e OP
     #   as we do not want to control these files
     return FALLBACK_TO_REAL_OP;
 }

=head2 Check helpers to use in your callback function

In your callback function you should use the following helpers to return.

=over

=item B<CHECK_IS_FALSE>: use this constant when the test is false

=item B<CHECK_IS_TRUE>: use this when you the test is true

=item B<FALLBACK_TO_REAL_OP>: you want to delegate the answer to Perl itself :-)

=back

It's also possible to return one integer. Checks like C<-s>, C<-M>, C<-C>, C<-A> can return
any integers.

Example:

    use Overload::FileCheck q(:all);

    mock_file_check( '-s' => \&my_dash_s );

    sub my_dash_s {
        my ( $file_or_handle ) = @_;

        if ( $file_or_handle eq '/a/b/c' ) {
            return 42;
        }

        return FALLBACK_TO_REAL_OP;
    }

=head2 Tracing all file checks usage

You can trace all file checks in your codebase without altering it.

 #!perl
 
 use strict;
 use warnings;
 
 use Carp;
 use Overload::FileCheck q{:all};
 
 mock_all_file_checks( \&my_custom_check );
 
 sub my_custom_check {
     my ( $check, $f ) = @_;
 
     local $Carp::CarpLevel = 2;    # do not display Overload::FileCheck stack
     printf( "# %-10s called from %s", "-$check '$f'", Carp::longmess() );
 
     # fallback to the original Perl OP
     return FALLBACK_TO_REAL_OP;
 }
 
 -d '/root';
 -l '/root';
 -e '/';
 -d '/';
 
 unmock_all_file_checks();
 
 __END__
 
 # The output looks similar to
 
 -d '/root' called from  at t/perldoc_mock-all-file-check-trace.t line 26.
 -l '/root' called from  at t/perldoc_mock-all-file-check-trace.t line 27.
 -e '/'     called from  at t/perldoc_mock-all-file-check-trace.t line 28.
 -d '/'     called from  at t/perldoc_mock-all-file-check-trace.t line 29.

=head2 Mock one or more file checks: -e, -f

You can mock a single file check type like '-e', '-f', ...

 #!perl
 
 use strict;
 use warnings;
 
 use Overload::FileCheck qw{mock_file_check unmock_file_check unmock_all_file_checks :check};
 use Errno ();
 
 # all -f checks will be true from now
 mock_file_check( '-f' => sub { 1 } );
 
 # mock all calls to -e and delegate to the function dash_e
 mock_file_check( '-e' => \&dash_e );
 
 # example of your own callback function to mock -e
 # when returning
 #  0: the test is false
 #  1: the test is true
 # -1: you want to use the answer from Perl itself :-)
 
 sub dash_e {
     my ($file_or_fh) = @_;
 
     # return true on -e for this specific file
     return CHECK_IS_TRUE
       if $file_or_fh eq '/this/file/is/not/there/but/act/like/if/it/was';
 
     # claim that /tmp is not available even if it exists
     if ( $file_or_fh eq '/tmp' ) {
 
         # you can set Errno to any custom value
         #   or it would be set to Errno::ENOENT() by default
         $! = Errno::ENOENT();    # set errno to "No such file or directory"
         return CHECK_IS_FALSE;
     }
 
     # delegate the answer to the Perl CORE -e OP
     #   as we do not want to control these files
     return FALLBACK_TO_REAL_OP;
 }
 
 # unmock -e and -f
 unmock_file_check('-e');
 unmock_file_check('-f');
 unmock_file_check(qw{-e -f});
 
 # or unmock all existing filecheck
 unmock_all_file_checks();

=head2 Mock check calls at import time

You can also mock the check functions at import time by providing a check test
and a custom function

 #!perl
 
 use strict;
 use warnings;
 
 use Test::More;
 use Overload::FileCheck '-e' => \&my_dash_e, q{:check};
 
 # Mock one or more check
 #use Overload::FileCheck '-e' => \&my_dash_e, '-f' => sub { 1 }, 'x' => sub { 0 }, ':check';
 
 my @exist     = qw{cherry banana apple};
 my @not_there = qw{chocolate and peanuts};
 
 sub my_dash_e {
     my $f = shift;
 
     note "mocked -e called for", $f;
 
     return CHECK_IS_TRUE  if grep { $_ eq $f } @exist;
     return CHECK_IS_FALSE if grep { $_ eq $f } @not_there;
 
     # we have no idea about these files
     return FALLBACK_TO_REAL_OP;
 }
 
 foreach my $f (@exist) {
     ok( -e $f, "file '$f' exists" );
 }
 
 foreach my $f (@not_there) {
     ok( !-e $f, "file '$f' exists" );
 }
 
 # this is using the fallback logic '-1'
 ok -e $0,  q[$0 is there];
 ok -e $^X, q[$^X is there];
 
 done_testing;

=head1 Mocking stat and lstat

=head2 How to mock stat?

Here is a short sample how you can mock stat and lstat.
This is an extract from the testsuite, Test2::* modules are
just there to illustrate the behavior. You should not necessary use them
in your code.

For more advanced samples, browse to the source code and check the test files
in t or examples directories.

 #!perl
 
 use strict;
 use warnings;
 
 use Test2::Bundle::Extended;
 use Test2::Tools::Explain;
 use Test2::Plugin::NoWarnings;
 
 use Overload::FileCheck q(:all);
 
 # our helper would be called for every stat & lstat calls
 mock_stat( \&my_stat );
 
 sub my_stat {
     my ( $opname, $file_or_handle ) = @_;
 
     # $opname can be 'stat' or 'lstat'
     # in this sample only mock stat, leave lstat alone
     return FALLBACK_TO_REAL_OP() if $opname eq 'lstat';
 
     my $f = $file_or_handle;    # alias for readability
 
     # return an array ref with 13 elements containing the stat output
     return [ 1 .. 13 ] if $f eq $0;
 
     my $fake_stat = [ (0) x 13 ];
 
     # you also have access to some constants
     # to set the stat values in the correct slot
     # this is using some fake values, without any specific meaning...
     $fake_stat->[ST_DEV]     = 1;
     $fake_stat->[ST_INO]     = 2;
     $fake_stat->[ST_MODE]    = 4;
     $fake_stat->[ST_NLINK]   = 8;
     $fake_stat->[ST_UID]     = 16;
     $fake_stat->[ST_GID]     = 32;
     $fake_stat->[ST_RDEV]    = 64;
     $fake_stat->[ST_SIZE]    = 128;
     $fake_stat->[ST_ATIME]   = 256;
     $fake_stat->[ST_MTIME]   = 512;
     $fake_stat->[ST_CTIME]   = 1024;
     $fake_stat->[ST_BLKSIZE] = 2048;
     $fake_stat->[ST_BLOCKS]  = 4096;
 
     return $fake_stat if $f eq 'fake.stat';
 
     # can also return stats as a hash ref
     return { st_dev => 1, st_atime => 987654321 } if $f eq 'hash.stat';
 
     return {
         st_dev     => 1,
         st_ino     => 2,
         st_mode    => 3,
         st_nlink   => 4,
         st_uid     => 5,
         st_gid     => 6,
         st_rdev    => 7,
         st_size    => 8,
         st_atime   => 9,
         st_mtime   => 10,
         st_ctime   => 11,
         st_blksize => 12,
         st_blocks  => 13,
     } if $f eq 'hash.stat.full';
 
     # return an empty array if you want to mark the file as not available
     return [] if $f eq 'file.is.not.there';
 
     # fallback to the regular OP
     return FALLBACK_TO_REAL_OP();
 }
 
 is [ stat($0) ], [ 1 .. 13 ], 'stat is mocked for $0';
 is [ stat(_) ], [ 1 .. 13 ],
   '_ also works: your mocked function is not called';
 
 is [ stat('fake.stat') ],
   [ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096 ], 'fake.stat';
 
 is [ stat('hash.stat.full') ], [ 1 .. 13 ], 'hash.stat.full';
 
 unmock_stat();
 
 done_testing;

=head2 Convenient constants available when mocking stat

When mocking stat or lstat function your callback function should return one of the following

=over

=item either one ARRAY Ref containing 13 entries as described by the stat function (in the same order)

=item or an empty ARRAY Ref, if the file does not exist

=item or one HASH ref using one or more of the following keys: st_dev, st_ino, st_mode, st_nlink,
  st_uid, st_gid, st_rdev, st_size, st_atime, st_mtime, st_ctime, st_blksiz, st_blocks

=item or return FALLBACK_TO_REAL_OP when you want to let Perl take back the control for that file

=back

In order to manipulate the ARRAY ref and insert/update one specific entry, some constant are available
to access to the correct index via a 'name':

=over

=item ST_DEV

=item ST_INO

=item ST_MODE

=item ST_NLINK

=item ST_UID

=item ST_GID

=item ST_RDEV

=item ST_SIZE

=item ST_ATIME

=item ST_MTIME

=item ST_CTIME

=item ST_BLKSIZE

=item ST_BLOCKS

=back

=head2 Mocking all file checks from a single 'stat' function

A recommended option is to only mock the 'stat' and 'lstat' function
and let Overload::FileCheck mock for you all file checks: -e, -f, -s, -z, ...

By doing so, using '_' or '*_' (a.k.a. PL_defgv) in your filecheck would work without any extra effort.

    -d "/my/file" && -s _

Netherway some limitations exist. Indeed the checks '-B' and '-T' are using some heuristics to determine
if the file is a binary or a text. This would require more than just a simple stat output.
In these cases you can mock the -B and -T to your own functions.

    mock_file_check( '-B' => sub { ... } );
    mock_file_check( '-T' => sub { ... } );

=head3 mock_all_from_stat

By using 'mock_all_from_stat' function, you will only provide a 'fake' stat / lstat function and
let Overload::FileCheck provide the hooks for all common checks

 #!perl
 
 use strict;
 use warnings;
 
 # setup at import time
 use Overload::FileCheck '-from-stat' => \&mock_stat_from_sys, qw{:check :stat};
 
 # or set it later at run time
 # mock_all_from_stat( \&my_stat );
 
 sub mock_stat_from_sys {
 
     my ( $stat_or_lstat, $f ) = @_;
 
     # $stat_or_lstat would be set to 'stat' or 'lstat' depending
     #   if it's a 'stat' or 'lstat' call
 
     if ( defined $f && $f eq 'mocked.file' ) {    # "<<$f is mocked>>"
         return [                                  # return a fake stat output (regular file)
             64769,      69887159,   33188, 1, 0, 0, 0, 13,
             1539928982, 1539716940, 1539716940,
             4096,       8
         ];
 
         return stat_as_file();
 
         return [];                                # if the file is missing
     }
 
     # let Perl answer the stat question for us
     return FALLBACK_TO_REAL_OP;
 }
 
 # ...
 
 # later in your code
 if ( -e 'mocked.file' && -f _ && !-d _ ) {
     print "# This file looks real...\n";
 }
 
 # ...
 
 # you can unmock the OPs at anytime
 Overload::FileCheck::unmock_all_file_checks();

=head2 Using stat_as_* helpers

When mocking the stat functions you might consider using one of the 'stat_as_*' helper.
Available functions are:

=over

=item stat_as_directory

=item stat_as_file

=item stat_as_symlink

=item stat_as_socket

=item stat_as_chr

=item stat_as_block

=back

All of these functions take some optional arguments to set: uid, gid, size, atime, mtime, ctime, perms, size.
Example:

    use Overload::FileCheck -from-stat => \&my_stat, q{:check};

    sub my_stat {
        my ( $stat_or_lstat, $f_or_fh ) = @_;

        return stat_as_file() if $f_or_fh eq 'fake.file';

        return stat_as_directory( uid => 0, gid => 'root' ) if $f_or_fh eq 'fake.dir';

        return stat_as_file( mtime => time() ) if $f_or_fh eq 'touch.file';

        return stat_as_file( perms => 0755 ) if $f_or_fh eq 'touch.file.0755';

        return FALLBACK_TO_REAL_OP;
    }

=head1 Available functions

=head2 mock_file_check( $check, CODE )

mock_file_check function is used to mock one of the filecheck op.

The first argument is one of the file check: '-f', '-e', ... where the dash is optional.
It also accepts 'e', 'f', ...

When trying to mock a filecheck already mocked, the function will die with an error like

  -f is already mocked by Overload::FileCheck

This would guarantee that you are not mocking multiple times the same filecheck in your codebase.

Otherwise returns 1 on success.

  # this is probably a very bad idea to do this in your codebase
  # but can be useful for some testing
  # in that sample all '-e' checks will always return true...
  mock_file_check( '-e' => sub { 1 } )

=head2 unmock_file_check( $check, [@extra_checks] )

Disable the effect of one or more specific mock.
The argument to unmock_file_check can be a list or a single scalar value.
The leading dash is optional.

  unmock_file_check( '-e' );
  unmock_file_check( 'e' );            # also work without the dash
  unmock_file_check( qw{-e -f -z} );
  unmock_file_check( qw{e f} );        # also work without the dashes

=head2 unmock_all_file_checks()

By a simple call to unmock_all_file_checks, you would disable the effect of overriding the
filecheck OPs. (not that the XS code is still plugged in, but fallback as soon
as possible to the original OP)

=head2 mock_stat( CODE )

mock_stat provides one interface to setup a hook for all C<stat> and C<lstat> calls.
It's slighly different than the other mock functions. As the first argument passed to
the hook function would be a string 'stat' or 'lstat'.

You can get a more advanced hook sample from L</"Mocking stat">.

    use Overload::FileCheck q(:all);

    # our helper would be called for every stat & lstat calls
    mock_stat( \&my_stat );

    sub my_stat {
        my ( $opname, $file_or_handle ) = @_;

        ...

        return FALLBACK_TO_REAL_OP;
    }

=head2 unmock_stat()

By calling unmock_stat, you would disable any previous hook set using mock_stat

=head2 mock_all_from_stat( CODE )

By providing a single hook for 'stat' and 'lstat' you let OverLoad::FileCheck take care
of mocking all other -X checks.

read L</" Mocking all file checks from a single 'stat' function"> for sample usage.

=head2 stat_as_directory( %OPTS )

Create a stat array ref for a directory.
%OPTS is optional and can set one or more using arguments among: uid, gid, size, atime, mtime, ctime, perms, size.
read the section L</"Using stat_as_* helpers"> for some sample usages.

=head2 stat_as_file( %OPTS )

Create a stat array ref for a regular file
view stat_as_directory and L</"Using stat_as_* helpers"> for some sample usages

=head2 stat_as_symlink( %OPTS )

Create a stat array ref for a symlink
view stat_as_directory and L</"Using stat_as_* helpers"> for some sample usages

=head2 stat_as_socket( %OPTS )

Create a stat array ref for a socket
view stat_as_directory and L</"Using stat_as_* helpers"> for some sample usages

=head2 stat_as_chr( %OPTS )

Create a stat array ref for an empty character device
view stat_as_directory and L</"Using stat_as_* helpers"> for some sample usages

=head2 stat_as_block( %OPTS )

Create a stat array ref for an empty block device
view stat_as_directory and L</"Using stat_as_* helpers"> for some sample usages

=head1 Notice

This is a very early development stage and some behavior might change before the release of a more stable build.

=head1 Known Limitations

=head2 This is design for Unit Test purpose

This code was mainly designed to be used during unit tests. It's far from being optimized at this time.

=head2 Mock as soon as possible

Code loaded/interpreted before mocking a file check, would not take benefit of Overload::FileCheck.
You probably want to load and call the mock function of Overload::FileCheck as early as possible.

=head2 Empty string instead of Undef

Several test operators once mocked will not return the expected 'undef' value but one empty string
instead. This is a future improvement. If you check the output of -X operators in boolean context
it should not impact you.

=head2 -B and -T are using heuristics

File check operators like -B and -T are using heuristics to guess if the file content is binary or text.
By using mock_all_from_stat or ('-from-stat' at import time), we cannot provide an accurate -B or -T checks.
You would need to provide a custom hooks for them

=head1 TODO

=over

=item support for 'undef' using CHECK_IS_UNDEF as valid return (in addition to CHECK_IS_FALSE)

=back

=head1 LICENSE

This software is copyright (c) 2018 by cPanel, Inc.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming
language system itself.

=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE
SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE
OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY
WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

=head1 AUTHOR

Nicolas R <atoomic@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2022 by cPanel, L.L.C.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut