-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathArchiveZip.java
More file actions
1523 lines (1295 loc) · 59.1 KB
/
ArchiveZip.java
File metadata and controls
1523 lines (1295 loc) · 59.1 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
package org.perlonjava.runtime.perlmodule;
import org.perlonjava.runtime.operators.ReferenceOperators;
import org.perlonjava.runtime.runtimetypes.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarCache.*;
/**
* Archive::Zip module implementation for PerlOnJava.
* This class provides zip file handling using Java's java.util.zip package.
*
* Implements core Archive::Zip functionality:
* - Reading zip files
* - Listing members
* - Extracting members
* - Adding new members (files/strings)
* - Writing zip files
*/
public class ArchiveZip extends PerlModuleBase {
// Keys for internal hash storage
private static final String MEMBERS_KEY = "_members";
private static final String FILENAME_KEY = "_filename";
private static final String COMMENT_KEY = "_zipfileComment";
/**
* Resolve a path string against Perl's notion of the current working
* directory (System "user.dir"), since Java's Paths.get does not honor
* Perl chdir() updates to user.dir.
*/
private static Path resolvePath(String name) {
Path p = Paths.get(name);
if (p.isAbsolute()) return p;
return Paths.get(System.getProperty("user.dir")).resolve(p);
}
private static Path resolvePath(String first, String... more) {
Path p = Paths.get(first, more);
if (p.isAbsolute()) return p;
return Paths.get(System.getProperty("user.dir")).resolve(p);
}
// Constants (matching Archive::Zip)
public static final int AZ_OK = 0;
public static final int AZ_STREAM_END = 1;
public static final int AZ_ERROR = 2;
public static final int AZ_FORMAT_ERROR = 3;
public static final int AZ_IO_ERROR = 4;
public static final int COMPRESSION_STORED = 0;
public static final int COMPRESSION_DEFLATED = 8;
public static final int COMPRESSION_LEVEL_NONE = 0;
public static final int COMPRESSION_LEVEL_DEFAULT = -1;
public static final int COMPRESSION_LEVEL_FASTEST = 1;
public static final int COMPRESSION_LEVEL_BEST_COMPRESSION = 9;
public ArchiveZip() {
super("Archive::Zip", false);
}
public static void initialize() {
ArchiveZip az = new ArchiveZip();
try {
// Archive methods
az.registerMethod("new", "newArchive", null);
az.registerMethod("read", null);
az.registerMethod("readFromFileHandle", null);
az.registerMethod("zipfileComment", null);
az.registerMethod("writeToFileNamed", null);
az.registerMethod("writeToFileHandle", null);
az.registerMethod("members", null);
az.registerMethod("memberNames", null);
az.registerMethod("numberOfMembers", null);
az.registerMethod("memberNamed", null);
az.registerMethod("membersMatching", null);
az.registerMethod("addFile", null);
az.registerMethod("addString", null);
az.registerMethod("addDirectory", null);
az.registerMethod("extractMember", null);
az.registerMethod("extractMemberWithoutPaths", null);
az.registerMethod("extractTree", null);
az.registerMethod("removeMember", null);
// Member methods (called on member objects)
az.registerMethod("fileName", null);
az.registerMethod("contents", null);
az.registerMethod("isDirectory", null);
az.registerMethod("uncompressedSize", null);
az.registerMethod("compressedSize", null);
az.registerMethod("compressionMethod", null);
az.registerMethod("lastModTime", null);
az.registerMethod("lastModFileDateTime", null);
az.registerMethod("crc32", null);
az.registerMethod("crc", "crc32", null); // alias for crc32
az.registerMethod("externalFileName", null);
az.registerMethod("versionNeededToExtract", null);
az.registerMethod("bitFlag", null);
az.registerMethod("fileComment", null);
az.registerMethod("extractToFileNamed", null);
// Constants
az.registerMethod("AZ_OK", null);
az.registerMethod("AZ_STREAM_END", null);
az.registerMethod("AZ_ERROR", null);
az.registerMethod("AZ_FORMAT_ERROR", null);
az.registerMethod("AZ_IO_ERROR", null);
az.registerMethod("COMPRESSION_STORED", null);
az.registerMethod("COMPRESSION_DEFLATED", null);
az.registerMethod("COMPRESSION_LEVEL_NONE", null);
az.registerMethod("COMPRESSION_LEVEL_DEFAULT", null);
az.registerMethod("COMPRESSION_LEVEL_FASTEST", null);
az.registerMethod("COMPRESSION_LEVEL_BEST_COMPRESSION", null);
} catch (NoSuchMethodException e) {
System.err.println("Warning: Missing Archive::Zip method: " + e.getMessage());
}
}
// Constants
public static RuntimeList AZ_OK(RuntimeArray args, int ctx) {
return new RuntimeScalar(AZ_OK).getList();
}
public static RuntimeList AZ_STREAM_END(RuntimeArray args, int ctx) {
return new RuntimeScalar(AZ_STREAM_END).getList();
}
public static RuntimeList AZ_ERROR(RuntimeArray args, int ctx) {
return new RuntimeScalar(AZ_ERROR).getList();
}
public static RuntimeList AZ_FORMAT_ERROR(RuntimeArray args, int ctx) {
return new RuntimeScalar(AZ_FORMAT_ERROR).getList();
}
public static RuntimeList AZ_IO_ERROR(RuntimeArray args, int ctx) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
public static RuntimeList COMPRESSION_STORED(RuntimeArray args, int ctx) {
return new RuntimeScalar(COMPRESSION_STORED).getList();
}
public static RuntimeList COMPRESSION_DEFLATED(RuntimeArray args, int ctx) {
return new RuntimeScalar(COMPRESSION_DEFLATED).getList();
}
public static RuntimeList COMPRESSION_LEVEL_NONE(RuntimeArray args, int ctx) {
return new RuntimeScalar(COMPRESSION_LEVEL_NONE).getList();
}
public static RuntimeList COMPRESSION_LEVEL_DEFAULT(RuntimeArray args, int ctx) {
return new RuntimeScalar(COMPRESSION_LEVEL_DEFAULT).getList();
}
public static RuntimeList COMPRESSION_LEVEL_FASTEST(RuntimeArray args, int ctx) {
return new RuntimeScalar(COMPRESSION_LEVEL_FASTEST).getList();
}
public static RuntimeList COMPRESSION_LEVEL_BEST_COMPRESSION(RuntimeArray args, int ctx) {
return new RuntimeScalar(COMPRESSION_LEVEL_BEST_COMPRESSION).getList();
}
/**
* Create a new Archive::Zip object.
* Usage: my $zip = Archive::Zip->new();
* my $zip = Archive::Zip->new('file.zip');
*/
public static RuntimeList newArchive(RuntimeArray args, int ctx) {
RuntimeHash self = new RuntimeHash();
RuntimeArray membersArray = new RuntimeArray();
self.put(MEMBERS_KEY, membersArray.createReference());
RuntimeScalar ref = self.createReference();
ReferenceOperators.bless(ref, new RuntimeScalar("Archive::Zip"));
// If a filename is provided, read it
if (args.size() > 1) {
RuntimeScalar filename = args.get(1);
if (filename.type != RuntimeScalarType.UNDEF) {
self.put(FILENAME_KEY, filename);
RuntimeArray readArgs = new RuntimeArray();
RuntimeArray.push(readArgs, ref);
RuntimeArray.push(readArgs, filename);
RuntimeList result = read(readArgs, RuntimeContextType.SCALAR);
int status = result.scalar().getInt();
if (status != AZ_OK) {
return scalarUndef.getList();
}
}
}
return ref.getList();
}
/**
* Read a zip file.
* Usage: $status = $zip->read('file.zip');
* Returns: AZ_OK on success, error code on failure
*/
public static RuntimeList read(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash self = args.get(0).hashDeref();
String filename = args.get(1).toString();
try {
RuntimeArray members = getMembers(self);
members.undefine(); // Clear existing members
Path path = resolvePath(filename);
if (!Files.exists(path)) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
String resolvedName = path.toString();
// Extract raw DOS timestamps from central directory
// (Java's ZipEntry uses extended timestamps when available)
java.util.Map<String, Long> rawDosTimestamps = extractRawDosTimestamps(resolvedName);
try (ZipFile zipFile = new ZipFile(resolvedName)) {
// Store the zipfile comment
String comment = zipFile.getComment();
if (comment != null) {
self.put(COMMENT_KEY, new RuntimeScalar(comment));
} else {
self.put(COMMENT_KEY, scalarUndef);
}
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
// Create member object with raw DOS timestamp if available
Long rawDosTime = rawDosTimestamps.get(entry.getName());
RuntimeHash member = createMemberFromEntry(zipFile, entry, rawDosTime);
RuntimeScalar memberRef = member.createReference();
ReferenceOperators.bless(memberRef, new RuntimeScalar("Archive::Zip::Member"));
RuntimeArray.push(members, memberRef);
}
}
self.put(FILENAME_KEY, new RuntimeScalar(filename));
return new RuntimeScalar(AZ_OK).getList();
} catch (IOException e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
} catch (Exception e) {
return new RuntimeScalar(AZ_FORMAT_ERROR).getList();
}
}
/**
* Read a zip file from a filehandle.
* Usage: $status = $zip->readFromFileHandle($fh);
* Returns: AZ_OK on success, error code on failure
*/
public static RuntimeList readFromFileHandle(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar fhRef = args.get(1);
try {
RuntimeIO fh = RuntimeIO.getRuntimeIO(fhRef);
if (fh == null) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
RuntimeArray members = getMembers(self);
members.undefine(); // Clear existing members
// Read all data from the filehandle into a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Read in chunks until EOF
int chunkSize = 8192;
while (!fh.ioHandle.eof().getBoolean()) {
RuntimeScalar data = fh.ioHandle.read(chunkSize, StandardCharsets.ISO_8859_1);
if (!data.getDefinedBoolean()) {
break;
}
String dataStr = data.toString();
if (dataStr.isEmpty()) {
break;
}
// Convert string back to bytes using ISO_8859_1 to preserve byte values
baos.write(dataStr.getBytes(StandardCharsets.ISO_8859_1));
}
byte[] zipData = baos.toByteArray();
if (zipData.length == 0) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
// Extract raw DOS timestamps from the ZIP data
java.util.Map<String, Long> rawDosTimestamps = extractRawDosTimestampsFromBytes(zipData);
// Create a ZipInputStream from the byte array
try (ByteArrayInputStream bais = new ByteArrayInputStream(zipData);
ZipInputStream zis = new ZipInputStream(bais)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
// Read entry contents
ByteArrayOutputStream entryBaos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = zis.read(buffer)) != -1) {
entryBaos.write(buffer, 0, bytesRead);
}
// Create member object
RuntimeHash member = new RuntimeHash();
member.put("_name", new RuntimeScalar(entry.getName()));
member.put("_externalFileName", new RuntimeScalar(""));
member.put("_isDirectory", entry.isDirectory() ? scalarTrue : scalarFalse);
member.put("_uncompressedSize", new RuntimeScalar(entry.getSize() >= 0 ? entry.getSize() : entryBaos.size()));
member.put("_compressedSize", new RuntimeScalar(entry.getCompressedSize() >= 0 ? entry.getCompressedSize() : entryBaos.size()));
member.put("_compressionMethod", new RuntimeScalar(entry.getMethod()));
// Store Unix timestamp (seconds since epoch) for lastModTime
long timeMillis = entry.getTime();
member.put("_lastModTime", new RuntimeScalar(timeMillis >= 0 ? timeMillis / 1000 : 0));
// Store raw MS-DOS format for lastModFileDateTime
// Use the raw DOS timestamp extracted from ZIP data if available
Long rawDosTime = rawDosTimestamps.get(entry.getName());
if (rawDosTime != null) {
member.put("_lastModFileDateTime", new RuntimeScalar(rawDosTime));
} else {
member.put("_lastModFileDateTime", new RuntimeScalar(getRawDosTime(entry)));
}
member.put("_crc32", new RuntimeScalar(entry.getCrc() >= 0 ? entry.getCrc() : 0));
// Additional fields for ExifTool compatibility
int versionNeeded = entry.getMethod() == ZipEntry.STORED ? 10 : 20;
member.put("_versionNeededToExtract", new RuntimeScalar(versionNeeded));
member.put("_bitFlag", new RuntimeScalar(0));
String comment = entry.getComment();
member.put("_fileComment", comment != null ? new RuntimeScalar(comment) : new RuntimeScalar(""));
// Store contents
String contents = new String(entryBaos.toByteArray(), StandardCharsets.ISO_8859_1);
member.put("_contents", new RuntimeScalar(contents));
RuntimeScalar memberRef = member.createReference();
ReferenceOperators.bless(memberRef, new RuntimeScalar("Archive::Zip::Member"));
RuntimeArray.push(members, memberRef);
zis.closeEntry();
}
}
// ZipInputStream doesn't provide access to the zipfile comment
// Set it to empty string (not undef) for compatibility
self.put(COMMENT_KEY, new RuntimeScalar(""));
return new RuntimeScalar(AZ_OK).getList();
} catch (java.util.zip.ZipException e) {
return new RuntimeScalar(AZ_FORMAT_ERROR).getList();
} catch (IOException e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
} catch (Exception e) {
return new RuntimeScalar(AZ_ERROR).getList();
}
}
/**
* Get the zip file comment.
* Usage: $comment = $zip->zipfileComment();
* Returns: The comment string or undef if not set.
*/
public static RuntimeList zipfileComment(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return scalarUndef.getList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar comment = self.get(COMMENT_KEY);
if (comment == null) {
return scalarUndef.getList();
}
return comment.getList();
}
/**
* Write zip to a file.
* Usage: $status = $zip->writeToFileNamed('output.zip');
*/
public static RuntimeList writeToFileNamed(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash self = args.get(0).hashDeref();
String filename = args.get(1).toString();
try {
RuntimeArray members = getMembers(self);
try (FileOutputStream fos = new FileOutputStream(resolvePath(filename).toFile());
ZipOutputStream zos = new ZipOutputStream(fos)) {
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
writeMemberToZip(zos, member);
}
}
return new RuntimeScalar(AZ_OK).getList();
} catch (IOException e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
} catch (Exception e) {
return new RuntimeScalar(AZ_ERROR).getList();
}
}
/**
* Write zip to a filehandle.
* Usage: $status = $zip->writeToFileHandle($fh);
*/
public static RuntimeList writeToFileHandle(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar fhRef = args.get(1);
try {
RuntimeIO fh = RuntimeIO.getRuntimeIO(fhRef);
if (fh == null) {
return new RuntimeScalar(AZ_ERROR).getList();
}
// Create a ByteArrayOutputStream to collect the zip data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
RuntimeArray members = getMembers(self);
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
writeMemberToZip(zos, member);
}
}
// Write to filehandle
byte[] data = baos.toByteArray();
String dataStr = new String(data, StandardCharsets.ISO_8859_1);
fh.ioHandle.write(dataStr);
return new RuntimeScalar(AZ_OK).getList();
} catch (Exception e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
}
/**
* Get list of all members.
* Usage: @members = $zip->members();
*/
public static RuntimeList members(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return new RuntimeList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeArray members = getMembers(self);
RuntimeList result = new RuntimeList();
for (int i = 0; i < members.size(); i++) {
result.add(members.get(i));
}
return result;
}
/**
* Get list of all member names.
* Usage: @names = $zip->memberNames();
*/
public static RuntimeList memberNames(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return new RuntimeList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeArray members = getMembers(self);
RuntimeList result = new RuntimeList();
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
result.add(member.get("_name"));
}
return result;
}
/**
* Get number of members.
* Usage: $count = $zip->numberOfMembers();
*/
public static RuntimeList numberOfMembers(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return scalarZero.getList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeArray members = getMembers(self);
return new RuntimeScalar(members.size()).getList();
}
/**
* Get a member by name.
* Usage: $member = $zip->memberNamed('path/to/file.txt');
*/
public static RuntimeList memberNamed(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return scalarUndef.getList();
}
RuntimeHash self = args.get(0).hashDeref();
String name = args.get(1).toString();
RuntimeArray members = getMembers(self);
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
RuntimeScalar memberName = member.get("_name");
if (memberName != null && memberName.toString().equals(name)) {
return members.get(i).getList();
}
}
return scalarUndef.getList();
}
/**
* Get members matching a regex.
* Usage: @members = $zip->membersMatching('\.txt$');
*/
public static RuntimeList membersMatching(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeList();
}
RuntimeHash self = args.get(0).hashDeref();
String regex = args.get(1).toString();
RuntimeArray members = getMembers(self);
RuntimeList result = new RuntimeList();
try {
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
RuntimeScalar memberName = member.get("_name");
if (memberName != null && pattern.matcher(memberName.toString()).find()) {
result.add(members.get(i));
}
}
} catch (Exception e) {
// Invalid regex, return empty list
}
return result;
}
/**
* Add a file to the archive.
* Usage: $member = $zip->addFile('file.txt');
* $member = $zip->addFile('file.txt', 'newname.txt');
*/
public static RuntimeList addFile(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return scalarUndef.getList();
}
RuntimeHash self = args.get(0).hashDeref();
String filename = args.get(1).toString();
String memberName = args.size() > 2 ? args.get(2).toString() : filename;
try {
Path path = resolvePath(filename);
if (!Files.exists(path)) {
return scalarUndef.getList();
}
byte[] content = Files.readAllBytes(path);
long lastModified = Files.getLastModifiedTime(path).toMillis();
RuntimeHash member = new RuntimeHash();
member.put("_name", new RuntimeScalar(memberName));
member.put("_externalFileName", new RuntimeScalar(filename));
member.put("_contents", new RuntimeScalar(new String(content, StandardCharsets.ISO_8859_1)));
member.put("_isDirectory", scalarFalse);
member.put("_uncompressedSize", new RuntimeScalar(content.length));
member.put("_compressedSize", new RuntimeScalar(content.length));
member.put("_compressionMethod", new RuntimeScalar(COMPRESSION_DEFLATED));
member.put("_lastModTime", new RuntimeScalar(lastModified / 1000));
member.put("_crc32", new RuntimeScalar(computeCRC32(content)));
RuntimeScalar memberRef = member.createReference();
ReferenceOperators.bless(memberRef, new RuntimeScalar("Archive::Zip::Member"));
RuntimeArray members = getMembers(self);
RuntimeArray.push(members, memberRef);
return memberRef.getList();
} catch (IOException e) {
return scalarUndef.getList();
}
}
/**
* Add a string as a member.
* Usage: $member = $zip->addString('content', 'name.txt');
*/
public static RuntimeList addString(RuntimeArray args, int ctx) {
if (args.size() < 3) {
return scalarUndef.getList();
}
RuntimeHash self = args.get(0).hashDeref();
String content = args.get(1).toString();
String memberName = args.get(2).toString();
byte[] contentBytes = content.getBytes(StandardCharsets.ISO_8859_1);
RuntimeHash member = new RuntimeHash();
member.put("_name", new RuntimeScalar(memberName));
member.put("_externalFileName", new RuntimeScalar(""));
member.put("_contents", new RuntimeScalar(content));
member.put("_isDirectory", scalarFalse);
member.put("_uncompressedSize", new RuntimeScalar(contentBytes.length));
member.put("_compressedSize", new RuntimeScalar(contentBytes.length));
member.put("_compressionMethod", new RuntimeScalar(COMPRESSION_DEFLATED));
member.put("_lastModTime", new RuntimeScalar(System.currentTimeMillis() / 1000));
member.put("_crc32", new RuntimeScalar(computeCRC32(contentBytes)));
RuntimeScalar memberRef = member.createReference();
ReferenceOperators.bless(memberRef, new RuntimeScalar("Archive::Zip::Member"));
RuntimeArray members = getMembers(self);
RuntimeArray.push(members, memberRef);
return memberRef.getList();
}
/**
* Add a directory entry.
* Usage: $member = $zip->addDirectory('dirname/');
*/
public static RuntimeList addDirectory(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return scalarUndef.getList();
}
RuntimeHash self = args.get(0).hashDeref();
String dirName = args.get(1).toString();
// Ensure directory name ends with /
if (!dirName.endsWith("/")) {
dirName = dirName + "/";
}
RuntimeHash member = new RuntimeHash();
member.put("_name", new RuntimeScalar(dirName));
member.put("_externalFileName", new RuntimeScalar(""));
member.put("_contents", new RuntimeScalar(""));
member.put("_isDirectory", scalarTrue);
member.put("_uncompressedSize", scalarZero);
member.put("_compressedSize", scalarZero);
member.put("_compressionMethod", new RuntimeScalar(COMPRESSION_STORED));
member.put("_lastModTime", new RuntimeScalar(System.currentTimeMillis() / 1000));
member.put("_crc32", scalarZero);
RuntimeScalar memberRef = member.createReference();
ReferenceOperators.bless(memberRef, new RuntimeScalar("Archive::Zip::Member"));
RuntimeArray members = getMembers(self);
RuntimeArray.push(members, memberRef);
return memberRef.getList();
}
/**
* Extract a member to a file.
* Usage: $status = $zip->extractMember('name.txt', 'output.txt');
*/
public static RuntimeList extractMember(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash self = args.get(0).hashDeref();
String memberName = args.get(1).toString();
String destName = args.size() > 2 ? args.get(2).toString() : memberName;
try {
RuntimeArray members = getMembers(self);
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
RuntimeScalar name = member.get("_name");
if (name != null && name.toString().equals(memberName)) {
RuntimeScalar isDir = member.get("_isDirectory");
if (isDir != null && isDir.getBoolean()) {
// Create directory
Path path = resolvePath(destName);
Files.createDirectories(path);
} else {
// Extract file
RuntimeScalar contents = member.get("_contents");
if (contents != null) {
Path path = resolvePath(destName);
// Create parent directories if needed
Path parent = path.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
byte[] data = contents.toString().getBytes(StandardCharsets.ISO_8859_1);
Files.write(path, data);
}
}
return new RuntimeScalar(AZ_OK).getList();
}
}
return new RuntimeScalar(AZ_ERROR).getList();
} catch (IOException e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
}
/**
* Extract a member without paths (just filename).
* Usage: $status = $zip->extractMemberWithoutPaths($member, 'dest/');
*/
public static RuntimeList extractMemberWithoutPaths(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar memberArg = args.get(1);
String destDir = args.size() > 2 ? args.get(2).toString() : ".";
try {
RuntimeHash member;
if (RuntimeScalarType.isReference(memberArg)) {
member = memberArg.hashDeref();
} else {
// It's a member name
RuntimeArray findArgs = new RuntimeArray();
RuntimeArray.push(findArgs, args.get(0));
RuntimeArray.push(findArgs, memberArg);
RuntimeList found = memberNamed(findArgs, ctx);
if (found.isEmpty() || found.scalar().type == RuntimeScalarType.UNDEF) {
return new RuntimeScalar(AZ_ERROR).getList();
}
member = found.scalar().hashDeref();
}
RuntimeScalar name = member.get("_name");
if (name == null) {
return new RuntimeScalar(AZ_ERROR).getList();
}
// Get just the filename without path
String fullName = name.toString();
String baseName = Paths.get(fullName).getFileName().toString();
RuntimeScalar isDir = member.get("_isDirectory");
if (isDir != null && isDir.getBoolean()) {
// Skip directory entries
return new RuntimeScalar(AZ_OK).getList();
}
RuntimeScalar contents = member.get("_contents");
if (contents != null) {
Path destPath = resolvePath(destDir, baseName);
Path parent = destPath.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
byte[] data = contents.toString().getBytes(StandardCharsets.ISO_8859_1);
Files.write(destPath, data);
}
return new RuntimeScalar(AZ_OK).getList();
} catch (IOException e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
}
/**
* Member method: extract this member to a specified file name.
* Usage: $status = $member->extractToFileNamed($filename);
*/
public static RuntimeList extractToFileNamed(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash member = args.get(0).hashDeref();
String destName = args.get(1).toString();
try {
RuntimeScalar isDir = member.get("_isDirectory");
if (isDir != null && isDir.getBoolean()) {
Path path = resolvePath(destName);
Files.createDirectories(path);
return new RuntimeScalar(AZ_OK).getList();
}
RuntimeScalar contents = member.get("_contents");
Path path = resolvePath(destName);
Path parent = path.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
byte[] data = contents != null
? contents.toString().getBytes(StandardCharsets.ISO_8859_1)
: new byte[0];
Files.write(path, data);
return new RuntimeScalar(AZ_OK).getList();
} catch (IOException e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
}
/**
* Extract all members to a directory.
* Usage: $status = $zip->extractTree('', 'dest/');
*/
public static RuntimeList extractTree(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return new RuntimeScalar(AZ_ERROR).getList();
}
RuntimeHash self = args.get(0).hashDeref();
String root = args.size() > 1 ? args.get(1).toString() : "";
String dest = args.size() > 2 ? args.get(2).toString() : ".";
try {
RuntimeArray members = getMembers(self);
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
RuntimeScalar name = member.get("_name");
if (name == null) continue;
String memberName = name.toString();
// Filter by root prefix
if (!root.isEmpty() && !memberName.startsWith(root)) {
continue;
}
// Remove root prefix for destination
String destName = memberName;
if (!root.isEmpty() && memberName.startsWith(root)) {
destName = memberName.substring(root.length());
}
Path destPath = resolvePath(dest, destName);
RuntimeScalar isDir = member.get("_isDirectory");
if (isDir != null && isDir.getBoolean()) {
Files.createDirectories(destPath);
} else {
Path parent = destPath.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
RuntimeScalar contents = member.get("_contents");
if (contents != null) {
byte[] data = contents.toString().getBytes(StandardCharsets.ISO_8859_1);
Files.write(destPath, data);
}
}
}
return new RuntimeScalar(AZ_OK).getList();
} catch (IOException e) {
return new RuntimeScalar(AZ_IO_ERROR).getList();
}
}
/**
* Remove a member from the archive.
* Usage: $removed = $zip->removeMember($member);
*/
public static RuntimeList removeMember(RuntimeArray args, int ctx) {
if (args.size() < 2) {
return scalarUndef.getList();
}
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar memberArg = args.get(1);
RuntimeArray members = getMembers(self);
String targetName;
if (RuntimeScalarType.isReference(memberArg)) {
RuntimeHash member = memberArg.hashDeref();
RuntimeScalar name = member.get("_name");
targetName = name != null ? name.toString() : "";
} else {
targetName = memberArg.toString();
}
for (int i = 0; i < members.size(); i++) {
RuntimeHash member = members.get(i).hashDeref();
RuntimeScalar name = member.get("_name");
if (name != null && name.toString().equals(targetName)) {
RuntimeScalar removed = members.get(i);
// Remove from array
RuntimeArray newMembers = new RuntimeArray();
for (int j = 0; j < members.size(); j++) {
if (j != i) {
RuntimeArray.push(newMembers, members.get(j));
}
}
self.put(MEMBERS_KEY, newMembers.createReference());
return removed.getList();
}
}
return scalarUndef.getList();
}
// Member accessor methods
/**
* Get member filename.
*/
public static RuntimeList fileName(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return scalarUndef.getList();
}
RuntimeHash member = args.get(0).hashDeref();
RuntimeScalar name = member.get("_name");
return name != null ? name.getList() : scalarUndef.getList();
}
/**
* Get member contents.
* Usage: $content = $member->contents();
* ($content, $status) = $zip->contents($member);
*
* When called on a zip object with a member argument, returns (content, status) in list context.
* When called on a member object, returns just the content.
*/
public static RuntimeList contents(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return scalarUndef.getList();
}
RuntimeHash self = args.get(0).hashDeref();
// Check if called as $zip->contents($member)
if (args.size() > 1) {
// Self is the zip archive, second arg is the member
RuntimeScalar memberArg = args.get(1);
RuntimeHash member;
if (RuntimeScalarType.isReference(memberArg)) {
member = memberArg.hashDeref();
} else {
// It's a member name, find it
String memberName = memberArg.toString();
RuntimeArray members = getMembers(self);
member = null;
for (int i = 0; i < members.size(); i++) {
RuntimeHash m = members.get(i).hashDeref();
RuntimeScalar name = m.get("_name");
if (name != null && name.toString().equals(memberName)) {
member = m;
break;
}
}