source: trunk/abcl/src/org/armedbear/lisp/zip.java

Last change on this file was 15682, checked in by Mark Evenson, 13 months ago

SYSTEM:ZIP works with source in jar files

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 10.8 KB
Line 
1/*
2 * zip.java
3 *
4 * Copyright (C) 2005 Peter Graves
5 * $Id: zip.java 15682 2023-04-01 14:36:12Z mevenson $
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 *
21 * As a special exception, the copyright holders of this library give you
22 * permission to link this library with independent modules to produce an
23 * executable, regardless of the license terms of these independent
24 * modules, and to copy and distribute the resulting executable under
25 * terms of your choice, provided that you also meet, for each linked
26 * independent module, the terms and conditions of the license of that
27 * module.  An independent module is a module which is not derived from
28 * or based on this library.  If you modify this library, you may extend
29 * this exception to your version of the library, but you are not
30 * obligated to do so.  If you do not wish to do so, delete this
31 * exception statement from your version.
32 */
33
34package org.armedbear.lisp;
35
36import static org.armedbear.lisp.Lisp.*;
37
38import java.io.File;
39import java.io.FileNotFoundException;
40import java.io.FileInputStream;
41import java.io.FileOutputStream;
42import java.io.IOException;
43import java.io.InputStream;
44import java.util.HashSet;
45import java.util.Set;
46import java.util.zip.ZipEntry;
47import java.util.zip.ZipOutputStream;
48
49@DocString(name="zip",
50           args="pathname pathnames &optional topdir",
51           doc="Creates a zip archive at PATHNAME whose entries enumerated via the list of PATHNAMES.\n"
52           + "If the optional TOPDIR argument is specified, the archive will "
53           + "preserve the hierarchy of PATHNAMES relative to TOPDIR.  Without "
54           + "TOPDIR, there will be no sub-directories in the archive, i.e. it will "
55           + "be flat.")
56public final class zip extends Primitive
57{
58    private zip()
59    {
60        super("zip", PACKAGE_SYS, true);
61    }
62   
63    @Override
64    public LispObject execute(LispObject first, LispObject second)
65    {
66        Pathname zipfilePathname = coerceToPathname(first);
67        if (second instanceof org.armedbear.lisp.protocol.Hashtable) {
68            return execute(zipfilePathname, (org.armedbear.lisp.protocol.Hashtable)second);
69        }
70        byte[] buffer = new byte[4096];
71        try {
72            String zipfileNamestring = zipfilePathname.getNamestring();
73            if (zipfileNamestring == null)
74                return error(new SimpleError("Pathname has no namestring: " +
75                                              zipfilePathname.princToString()));
76            ZipOutputStream out =
77                new ZipOutputStream(new FileOutputStream(zipfileNamestring));
78            LispObject list = second;
79            while (list != NIL) {
80                Pathname pathname = coerceToPathname(list.car());
81                String namestring = pathname.getNamestring();
82                if (namestring == null) {
83                    // Clean up before signalling error.
84                    out.close();
85                    File zipfile = new File(zipfileNamestring);
86                    zipfile.delete();
87                    return error(new SimpleError("Pathname has no namestring: "
88                                                 + pathname.princToString()));
89                }
90                File file = new File(namestring);
91                makeEntry(out, file);
92                list = list.cdr();
93            }
94            out.close();
95        }
96        catch (IOException e) {
97            return error(new LispError(e.getMessage()));
98        }
99        return zipfilePathname;
100    }
101
102    @Override
103    public LispObject execute(LispObject first, LispObject second, LispObject third)
104    {
105        Pathname zipfilePathname = coerceToPathname(first);
106        try {
107            String zipfileNamestring = zipfilePathname.getNamestring();
108            if (zipfileNamestring == null)
109                return error(new SimpleError("Pathname has no namestring: " +
110                                              zipfilePathname.princToString()));
111            ZipOutputStream out =
112                new ZipOutputStream(new FileOutputStream(zipfileNamestring));
113            Pathname root = (Pathname) Symbol.PROBE_FILE.execute(third);
114            String rootPath = root.getDirectoryNamestring();
115            int rootPathLength = rootPath.length();
116            Set<String> directories = new HashSet<String>();
117            LispObject list = second;
118            while (list != NIL) {
119              Pathname pathname = (Pathname) Symbol.PROBE_FILE.execute(list.car());
120                String namestring = pathname.getNamestring();
121                if (namestring == null) {
122                    // Clean up before signalling error.
123                    out.close();
124                    File zipfile = new File(zipfileNamestring);
125                    zipfile.delete();
126                    return error(new SimpleError("Pathname has no namestring: " +
127                                                  pathname.princToString()));
128                }
129                String directory = "";
130                String dir = pathname.getDirectoryNamestring();
131                if (dir.length() > rootPathLength) {
132                  String d = dir.substring(rootPathLength);
133                  int i = 0;
134                  int j;
135                  while ((j = d.indexOf(Pathname.directoryDelimiter, i)) != -1) {
136                    i = j + 1;
137                    directory = d.substring(0, j) + Pathname.directoryDelimiter;
138                    if (!directories.contains(directory)) {
139                      directories.add(directory);
140                      ZipEntry entry = new ZipEntry(directory);
141                      out.putNextEntry(entry);
142                      out.closeEntry();
143                    }
144                  }
145                }
146                File file = new File(namestring);
147                if (file.isDirectory()) {
148                    list = list.cdr();
149                    continue;
150                }
151                makeEntry(out, file, directory + file.getName());
152                list = list.cdr();
153            }
154            out.close();
155        }
156        catch (IOException e) {
157            return error(new LispError(e.getMessage()));
158        }
159        return zipfilePathname;
160    }
161
162    static class Directories extends HashSet<String> {
163        private Directories() {
164            super();
165        }
166       
167        ZipOutputStream out;
168        public Directories(ZipOutputStream out) {
169            this.out = out;
170        }
171           
172        public void ensure(String path) 
173            throws IOException
174        {
175            int i = 0;
176            int j;
177            while ((j = path.indexOf(Pathname.directoryDelimiter, i)) != -1) {
178                i = j + 1;
179                final String directory = path.substring(0, j) + Pathname.directoryDelimiter;
180                if (!contains(directory)) {
181                    add(directory);
182                    ZipEntry entry = new ZipEntry(directory);
183                    out.putNextEntry(entry);
184                    out.closeEntry();
185                }
186            }
187        }
188    }
189
190    public LispObject execute(final Pathname zipfilePathname,
191                              final org.armedbear.lisp.protocol.Hashtable table)
192  {
193        LispObject entriesObject = (LispObject)table.getEntries();
194        if (!(entriesObject instanceof Cons)) {
195            return NIL;
196        }
197        Cons entries = (Cons)entriesObject;
198
199        String zipfileNamestring = zipfilePathname.getNamestring();
200        if (zipfileNamestring == null)
201            return error(new SimpleError("Pathname has no namestring: " +
202                                         zipfilePathname.princToString()));
203        ZipOutputStream out = null;
204        try {
205            out = new ZipOutputStream(new FileOutputStream(zipfileNamestring));
206        } catch (FileNotFoundException e) {
207            return error(new FileError("Failed to create file for writing zip archive",
208                                       zipfilePathname));
209        }
210        Directories directories = new Directories(out);
211
212        for (LispObject head = entries; head != NIL; head = head.cdr()) {
213            final LispObject key = head.car().car();
214            final LispObject value = head.car().cdr();
215
216            final Pathname source = Lisp.coerceToPathname(key);
217            final Pathname destination = Lisp.coerceToPathname(value);
218            try {
219                String jarEntry = destination.getNamestring();
220                if (jarEntry.startsWith("/")) {
221                    jarEntry = jarEntry.substring(1);
222                }
223                directories.ensure(jarEntry);
224                InputStream input = source.getInputStream();
225                long lastModified = source.getLastModified();
226                makeEntry(out, input, jarEntry, lastModified);
227            } catch (FileNotFoundException e) {
228                return error(new FileError("Failed to read file for incorporation in zip archive.",
229                                           source));
230            } catch (IOException e) {
231                return error(new FileError("Failed to add file to zip archive.",
232                                           source));
233            }
234        } 
235        try {
236            out.close();
237        } catch (IOException ex) {
238            return error(new FileError("Failed to close zip archive.", zipfilePathname));
239        }
240        return zipfilePathname;
241    }
242
243    private static final Primitive zip = new zip();
244
245    private void makeEntry(ZipOutputStream zip, File file) 
246        throws FileNotFoundException, IOException
247    {
248        makeEntry(zip, file, file.getName());
249    }
250
251    private void makeEntry(ZipOutputStream zip, File file, String name) 
252        throws FileNotFoundException, IOException
253    {
254      if (file == null) {
255        throw new IOException("No file to work on.");
256      }
257      long lastModified = file.lastModified();
258      FileInputStream in = new FileInputStream(file);
259      makeEntry(zip, in, name, lastModified);
260    }
261
262  private void makeEntry(ZipOutputStream zip, InputStream source, String entryName, long lastModified) 
263    throws IOException
264  {
265    byte[] buffer = new byte[4096];
266    ZipEntry entry = new ZipEntry(entryName);
267    if (lastModified > 0) {
268      entry.setTime(lastModified);
269    }
270    zip.putNextEntry(entry);
271    int n;
272    while ((n = source.read(buffer)) > 0) {
273      zip.write(buffer, 0, n);
274    }
275    zip.closeEntry();
276    source.close();
277  }
278}
Note: See TracBrowser for help on using the repository browser.