]> Creatis software - CreaPhase.git/blob - octave_packages/m/miscellaneous/unpack.m
update packages
[CreaPhase.git] / octave_packages / m / miscellaneous / unpack.m
1 ## Copyright (C) 2006-2012 Bill Denney
2 ##
3 ## This file is part of Octave.
4 ##
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
9 ##
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ## General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING.  If not, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn  {Function File} {@var{files} =} unpack (@var{file})
21 ## @deftypefnx {Function File} {@var{files} =} unpack (@var{file}, @var{dir})
22 ## @deftypefnx {Function File} {@var{files} =} unpack (@var{file}, @var{dir}, @var{filetype})
23 ## Unpack the archive @var{file} based on its extension to the directory
24 ## @var{dir}.  If @var{file} is a list of strings, then each file is
25 ## unpacked individually.  If @var{dir} is not specified, it defaults to
26 ## the current directory.  If a directory is in the file list, then the
27 ## @var{filetype} must also be specified.
28 ##
29 ## The optional return value is a list of @var{files} unpacked.
30 ## @seealso{bzip2, gzip, zip, tar}
31 ## @end deftypefn
32
33 ## Author: Bill Denney <denney@seas.upenn.edu>
34
35 function filelist = unpack (file, dir = ".", filetype = "")
36
37   if (nargin < 1 || nargin > 3)
38     print_usage ();
39   endif
40
41   if (! ischar (file) && ! iscellstr (file))
42     error ("unpack: invalid input file class, %s", class(file));
43   endif
44
45   ## character arrays of more than one string must be treated as cell strings
46   if (ischar (file) && ! isvector (file))
47     file = cellstr (file);
48   endif
49
50   ## Recursively unpack cellstr arrays one file at a time
51   if (iscellstr (file))
52     files = {};
53     for i = 1:numel (file)
54       tmpfiles = unpack (file{i}, dir);
55       files = {files{:} tmpfiles{:}};
56     endfor
57
58     ## Return output if requested.
59     if (nargout > 0)
60       filelist = files;
61     endif
62
63     return;
64   endif
65
66   if (isdir (file))
67     if (isempty (filetype))
68       error ("unpack: FILETYPE must be given for a directory");
69     elseif (! any (strcmpi (filetype, "gunzip")))
70       error ("unpack: FILETYPE must be gunzip for a directory");
71     endif
72     ext = ".gz";
73   else
74     [pathstr, name, ext] = fileparts (file);
75
76     ## Check to see if it's .tar.gz, .tar.Z, etc.
77     if (any (strcmpi ({".gz" ".Z" ".bz2" ".bz"}, ext)))
78       [tmppathstr, tmpname, tmpext] = fileparts (name);
79       if (strcmpi (tmpext, ".tar"))
80         name = tmpname;
81         ext = cstrcat (tmpext, ext);
82       endif
83     endif
84
85     ## If the file is a URL, download it and then work with that file.
86     if (! isempty (strfind (file, "://")))
87       ## FIXME -- the above is not a perfect test for a URL
88       urlfile = file;
89       ## FIXME -- should we name the file that we download with the
90       ## same file name as the URL requests?
91       tmpfile = cstrcat (tmpnam (), ext);
92       [file, success, msg] = urlwrite (urlfile, tmpfile);
93       if (! success)
94         error ("unpack: could not get \"%s\": %s", urlfile, msg);
95       endif
96     endif
97
98   endif
99
100   ## canonicalize_file_name returns empty if the file isn't found, so
101   ## use that to check for existence.
102   cfile = canonicalize_file_name (file);
103
104   if (isempty (cfile))
105     error ("unpack: file \"%s\" not found", file);
106   else
107     file = cfile;
108   endif
109
110   ## Instructions on what to do for any extension.
111   ##
112   ## The field names are the file extension without periods.
113   ## The first cell is what is executed to unpack an archive verbosely.
114   ## The second cell is what is executed to unpack an archive quietly.
115   ## The third cell is the function to execute on output to get the
116   ##   files list.
117   ## The fourth cell indicates if the files may need to be manually moved
118   ##   (i.e. tar and unzip decompress into the current directory while
119   ##   bzip2 and gzip decompress the file at its location).
120   persistent commandlist;
121   if (isempty (commandlist))
122     commandlist.gz = {"gzip -d -v -r \"%s\"", ...
123                       "gzip -d -r \"%s\"", ...
124                       @__parse_gzip__, true};
125     commandlist.z = commandlist.gz;
126     commandlist.bz2 = {"bzip2 -d -v \"%s\"", ...
127                        "bzip2 -d \"%s\"", ...
128                        @__parse_bzip2__, true};
129     commandlist.bz = commandlist.bz2;
130     commandlist.tar = {"tar xvf \"%s\"", ...
131                        "tar xf \"%s\"", ...
132                        @__parse_tar__, false};
133     commandlist.targz = {"gzip -d -c \"%s\" | tar xvf -", ...
134                          "gzip -d -c \"%s\" | tar xf -", ...
135                          @__parse_tar__, false};
136     commandlist.tgz = commandlist.targz;
137     commandlist.tarbz2 = {"bzip2 -d -c \"%s\" | tar xvf -", ...
138                           "bzip2 -d -c \"%s\" | tar xf -", ...
139                           @__parse_tar__, false};
140     commandlist.tarbz = commandlist.tarbz2;
141     commandlist.tbz2 = commandlist.tarbz2;
142     commandlist.tbz = commandlist.tarbz2;
143     commandlist.zip = {"unzip \"%s\"", ...
144                        "unzip -q \"%s\"", ...
145                        @__parse_zip__, false};
146   endif
147
148   nodotext = ext(! ismember (ext, "."));
149
150   origdir = pwd ();
151
152   if (isfield (commandlist, nodotext))
153     [commandv, commandq, parser, move] = deal (commandlist.(nodotext){:});
154     cstartdir = canonicalize_file_name (origdir);
155     cenddir = canonicalize_file_name (dir);
156     needmove = move && ! strcmp (cstartdir, cenddir);
157     if (nargout > 0 || needmove)
158       command = commandv;
159     else
160       command = commandq;
161     endif
162   else
163     warning ("unpack:filetype", "unrecognized file type, %s", ext);
164     files = file;
165     return;
166   endif
167
168   ## Create the directory if necessary.
169   s = stat (dir);
170   if (isempty (s))
171     [status, msg] = mkdir (dir);
172     if (! status)
173       error ("unpack: mkdir failed to create %s: %s", dir, msg);
174     endif
175   elseif (! S_ISDIR (s.mode))
176     error ("unpack: %s: not a directory", dir);
177   endif
178
179   unwind_protect
180     cd (dir);
181     [status, output] = system (sprintf (cstrcat (command, " 2>&1"), file));
182   unwind_protect_cleanup
183     cd (origdir);
184   end_unwind_protect
185
186   if (status)
187     error ("unpack: unarchiving program exited with status: %d\n%s",
188            status, output);
189   endif
190
191   if (nargout > 0 || needmove)
192     ## Trim the last cr if needed.
193     ## FIXME -- will this need to change to a check for "\r\n" for windows?
194     if (output(length (output)) == "\n")
195       output(length (output)) = [];
196     endif
197     files = parser (strsplit (output, "\n"))';
198
199     ## Move files if necessary
200     if (needmove)
201       [st, msg, msgid] = movefile (files, dir);
202       if (! st)
203         error ("unpack: unable to move files to \"%s\": %s",
204                dir, msg);
205       endif
206
207       ## Fix the names for the files since they were moved.
208       for i = 1:numel (files)
209         files{i} = strrep (files{i}, cstartdir, cenddir);
210       endfor
211     endif
212
213     ## Return output if requested.
214     if (nargout > 0)
215       filelist = files;
216     endif
217   endif
218
219 endfunction
220
221 function files = __parse_zip__ (output)
222   ## Parse the output from zip and unzip.
223
224   ## Skip first line which is Archive header
225   output(1) = [];
226   for i = 1:length (output)
227     files{i} = output{i}(14:length(output{i}));
228   endfor
229 endfunction
230
231 function output = __parse_tar__ (output)
232   ## This is a noop, but it makes things simpler for other cases.
233 endfunction
234
235 function files = __parse_gzip__ (output)
236   ## Parse the output from gzip and gunzip returning the files
237   ## commpressed (or decompressed).
238
239   files = {};
240   ## The middle ": " should indicate a good place to start looking for
241   ## the filename.
242   for i = 1:length (output)
243     colons = strfind (output{i}, ":");
244     if (isempty (colons))
245       warning ("unpack:parsing",
246                "Unable to parse line (gzip missing colon):\n%s", output{i});
247     else
248       midcolon = colons(ceil (length (colons)/2));
249       thisstr = output{i}(midcolon+2:length(output{i}));
250       idx = index (thisstr, "with") + 5;
251       if (isempty (idx))
252         warning ("unpack:parsing",
253                  "Unable to parse line (gzip missing with):\n%s", output{i});
254       else
255         files{i} = thisstr(idx:length (thisstr));
256       endif
257     endif
258   endfor
259 endfunction
260
261 function files = __parse_bzip2__ (output)
262   ## Parse the output from bzip2 and bunzip2 returning the files
263   ## commpressed (or decompressed).
264
265   files = {};
266   for i = 1:length (output)
267     ## the -5 is to remove the ".bz2:"
268     endoffilename = rindex (output{i}, ": ") - 5;
269     if (isempty (endoffilename))
270       warning ("unpack:parsing", "Unable to parse line:\n%s", output{i});
271     else
272       files{i} = output{i}(3:endoffilename);
273     endif
274   endfor
275 endfunction