Debian Codegraph @

src/tools/org/h2/dev/fs/FileShell.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.dev.fs;
7
8 import java.io.BufferedReader;
9 import java.io.File;
10 import java.io.FileNotFoundException;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.InputStreamReader;
14 import java.io.OutputStream;
15 import java.io.PrintStream;
16 import java.nio.channels.FileChannel;
17 import java.sql.SQLException;
18 import java.sql.Timestamp;
19 import java.util.ArrayList;
20 import java.util.zip.ZipEntry;
21 import java.util.zip.ZipInputStream;
22 import java.util.zip.ZipOutputStream;
23
24 import org.h2.command.dml.BackupCommand;
25 import org.h2.engine.Constants;
26 import org.h2.message.DbException;
27 import org.h2.store.fs.FileUtils;
28 import org.h2.util.IOUtils;
29 import org.h2.util.StringUtils;
30 import org.h2.util.Tool;
31
32 /**
33 * A shell tool that allows to list and manipulate files.
34 */
35 public class FileShell extends Tool {
36
37 private boolean verbose;
38 private BufferedReader reader;
39 private PrintStream err = System.err;
40 private InputStream in = System.in;
41 private String currentWorkingDirectory;
42
43 /**
44 * Options are case sensitive.
45 * <table>
46 * <caption>Supported options</caption>
47 * <tr><td>[-help] or [-?]</td>
48 * <td>Print the list of options</td></tr>
49 * <tr><td>[-verbose]</td>
50 * <td>Print stack traces</td></tr>
51 * <tr><td>[-run ...]</td>
52 * <td>Execute the given commands and exit</td></tr>
53 * </table>
54 * Multiple commands may be executed if separated by ;
55 *
56 * @param args the command line arguments
57 * @throws SQLException on failure
58 */
59 public static void main(String... args) throws SQLException {
60 new FileShell().runTool(args);
61 }
62
63 /**
64 * Sets the standard error stream.
65 *
66 * @param err the new standard error stream
67 */
68 public void setErr(PrintStream err) {
69 this.err = err;
70 }
71
72 /**
73 * Redirects the standard input. By default, System.in is used.
74 *
75 * @param in the input stream to use
76 */
77 public void setIn(InputStream in) {
78 this.in = in;
79 }
80
81 /**
82 * Redirects the standard input. By default, System.in is used.
83 *
84 * @param reader the input stream reader to use
85 */
86 public void setInReader(BufferedReader reader) {
87 this.reader = reader;
88 }
89
90 /**
91 * Run the shell tool with the given command line settings.
92 *
93 * @param args the command line settings
94 */
95 @Override
96 public void runTool(String... args) throws SQLException {
97 try {
98 currentWorkingDirectory = new File(".").getCanonicalPath();
99 } catch (IOException e) {
100 throw DbException.convertIOException(e, "cwd");
101 }
102 for (int i = 0; args != null && i < args.length; i++) {
103 String arg = args[i];
104 if (arg.equals("-run")) {
105 try {
106 execute(args[++i]);
107 } catch (Exception e) {
108 throw DbException.convert(e);
109 }
110 } else if (arg.equals("-verbose")) {
111 verbose = true;
112 } else if (arg.equals("-help") || arg.equals("-?")) {
113 showUsage();
114 return;
115 } else {
116 showUsageAndThrowUnsupportedOption(arg);
117 }
118 }
119 promptLoop();
120 }
121
122 private void promptLoop() {
123 println("");
124 println("Welcome to H2 File Shell " + Constants.FULL_VERSION);
125 println("Exit with Ctrl+C");
126 showHelp();
127 if (reader == null) {
128 reader = new BufferedReader(new InputStreamReader(in));
129 }
130 println(FileUtils.toRealPath(currentWorkingDirectory));
131 while (true) {
132 try {
133 print("> ");
134 String line = readLine();
135 if (line == null) {
136 break;
137 }
138 line = line.trim();
139 if (line.length() == 0) {
140 continue;
141 }
142 try {
143 execute(line);
144 } catch (Exception e) {
145 error(e);
146 }
147 } catch (Exception e) {
148 error(e);
149 break;
150 }
151 }
152 }
153
154 private void execute(String line) throws IOException {
155 String[] commands = StringUtils.arraySplit(line, ';', true);
156 for (String command : commands) {
157 String[] list = StringUtils.arraySplit(command, ' ', true);
158 if (!execute(list)) {
159 break;
160 }
161 }
162 }
163
164 private boolean execute(String[] list) throws IOException {
165 // TODO unit tests for everything (multiple commands, errors, ...)
166 // TODO less (support large files)
167 // TODO hex dump
168 int i = 0;
169 String c = list[i++];
170 if ("exit".equals(c) || "quit".equals(c)) {
171 end(list, i);
172 return false;
173 } else if ("help".equals(c) || "?".equals(c)) {
174 showHelp();
175 end(list, i);
176 } else if ("cat".equals(c)) {
177 String file = getFile(list[i++]);
178 end(list, i);
179 cat(file, Long.MAX_VALUE);
180 } else if ("cd".equals(c)) {
181 String dir = getFile(list[i++]);
182 end(list, i);
183 if (FileUtils.isDirectory(dir)) {
184 currentWorkingDirectory = dir;
185 println(dir);
186 } else {
187 println("Not a directory: " + dir);
188 }
189 } else if ("chmod".equals(c)) {
190 String mode = list[i++];
191 String file = getFile(list[i++]);
192 end(list, i);
193 if ("-w".equals(mode)) {
194 boolean success = FileUtils.setReadOnly(file);
195 println(success ? "Success" : "Failed");
196 } else {
197 println("Unsupported mode: " + mode);
198 }
199 } else if ("cp".equals(c)) {
200 String source = getFile(list[i++]);
201 String target = getFile(list[i++]);
202 end(list, i);
203 IOUtils.copyFiles(source, target);
204 } else if ("head".equals(c)) {
205 String file = getFile(list[i++]);
206 end(list, i);
207 cat(file, 1024);
208 } else if ("ls".equals(c)) {
209 String dir = currentWorkingDirectory;
210 if (i < list.length) {
211 dir = getFile(list[i++]);
212 }
213 end(list, i);
214 println(dir);
215 for (String file : FileUtils.newDirectoryStream(dir)) {
216 StringBuilder buff = new StringBuilder();
217 buff.append(FileUtils.isDirectory(file) ? "d" : "-");
218 buff.append(FileUtils.canWrite(file) ? "rw" : "r-");
219 buff.append(' ');
220 buff.append(String.format("%10d", FileUtils.size(file)));
221 buff.append(' ');
222 long lastMod = FileUtils.lastModified(file);
223 buff.append(new Timestamp(lastMod).toString());
224 buff.append(' ');
225 buff.append(FileUtils.getName(file));
226 println(buff.toString());
227 }
228 } else if ("mkdir".equals(c)) {
229 String dir = getFile(list[i++]);
230 end(list, i);
231 FileUtils.createDirectories(dir);
232 } else if ("mv".equals(c)) {
233 String source = getFile(list[i++]);
234 String target = getFile(list[i++]);
235 end(list, i);
236 FileUtils.move(source, target);
237 } else if ("pwd".equals(c)) {
238 end(list, i);
239 println(FileUtils.toRealPath(currentWorkingDirectory));
240 } else if ("rm".equals(c)) {
241 if ("-r".equals(list[i])) {
242 i++;
243 String dir = getFile(list[i++]);
244 end(list, i);
245 FileUtils.deleteRecursive(dir, true);
246 } else if ("-rf".equals(list[i])) {
247 i++;
248 String dir = getFile(list[i++]);
249 end(list, i);
250 FileUtils.deleteRecursive(dir, false);
251 } else {
252 String file = getFile(list[i++]);
253 end(list, i);
254 FileUtils.delete(file);
255 }
256 } else if ("touch".equals(c)) {
257 String file = getFile(list[i++]);
258 end(list, i);
259 truncate(file, FileUtils.size(file));
260 } else if ("truncate".equals(c)) {
261 if ("-s".equals(list[i])) {
262 i++;
263 long length = Long.decode(list[i++]);
264 String file = getFile(list[i++]);
265 end(list, i);
266 truncate(file, length);
267 } else {
268 println("Unsupported option");
269 }
270 } else if ("unzip".equals(c)) {
271 String file = getFile(list[i++]);
272 end(list, i);
273 unzip(file, currentWorkingDirectory);
274 } else if ("zip".equals(c)) {
275 boolean recursive = false;
276 if ("-r".equals(list[i])) {
277 i++;
278 recursive = true;
279 }
280 String target = getFile(list[i++]);
281 ArrayList<String> source = new ArrayList<>();
282 readFileList(list, i, source, recursive);
283 zip(target, currentWorkingDirectory, source);
284 }
285 return true;
286 }
287
288 private static void end(String[] list, int index) throws IOException {
289 if (list.length != index) {
290 throw new IOException("End of command expected, got: " + list[index]);
291 }
292 }
293
294 private void cat(String fileName, long length) {
295 if (!FileUtils.exists(fileName)) {
296 print("No such file: " + fileName);
297 }
298 if (FileUtils.isDirectory(fileName)) {
299 print("Is a directory: " + fileName);
300 }
301 InputStream inFile = null;
302 try {
303 inFile = FileUtils.newInputStream(fileName);
304 IOUtils.copy(inFile, out, length);
305 } catch (IOException e) {
306 error(e);
307 } finally {
308 IOUtils.closeSilently(inFile);
309 }
310 println("");
311 }
312
313 private void truncate(String fileName, long length) {
314 FileChannel f = null;
315 try {
316 f = FileUtils.open(fileName, "rw");
317 f.truncate(length);
318 } catch (IOException e) {
319 error(e);
320 } finally {
321 try {
322 f.close();
323 } catch (IOException e) {
324 error(e);
325 }
326 }
327 }
328
329 private void error(Exception e) {
330 println("Exception: " + e.getMessage());
331 if (verbose) {
332 e.printStackTrace(err);
333 }
334 }
335
336 private static void zip(String zipFileName, String base,
337 ArrayList<String> source) {
338 FileUtils.delete(zipFileName);
339 OutputStream fileOut = null;
340 try {
341 fileOut = FileUtils.newOutputStream(zipFileName, false);
342 ZipOutputStream zipOut = new ZipOutputStream(fileOut);
343 for (String fileName : source) {
344 String f = FileUtils.toRealPath(fileName);
345 if (!f.startsWith(base)) {
346 throw DbException.getInternalError(f + " does not start with " + base);
347 }
348 if (f.endsWith(zipFileName)) {
349 continue;
350 }
351 if (FileUtils.isDirectory(fileName)) {
352 continue;
353 }
354 f = f.substring(base.length());
355 f = BackupCommand.correctFileName(f);
356 ZipEntry entry = new ZipEntry(f);
357 zipOut.putNextEntry(entry);
358 InputStream in = null;
359 try {
360 in = FileUtils.newInputStream(fileName);
361 IOUtils.copyAndCloseInput(in, zipOut);
362 } catch (FileNotFoundException e) {
363 // the file could have been deleted in the meantime
364 // ignore this (in this case an empty file is created)
365 } finally {
366 IOUtils.closeSilently(in);
367 }
368 zipOut.closeEntry();
369 }
370 zipOut.closeEntry();
371 zipOut.close();
372 } catch (IOException e) {
373 throw DbException.convertIOException(e, zipFileName);
374 } finally {
375 IOUtils.closeSilently(fileOut);
376 }
377 }
378
379 private void unzip(String zipFileName, String targetDir) {
380 InputStream inFile = null;
381 try {
382 inFile = FileUtils.newInputStream(zipFileName);
383 ZipInputStream zipIn = new ZipInputStream(inFile);
384 while (true) {
385 ZipEntry entry = zipIn.getNextEntry();
386 if (entry == null) {
387 break;
388 }
389 String fileName = entry.getName();
390 // restoring windows backups on linux and vice versa
391 fileName = IOUtils.nameSeparatorsToNative(fileName);
392 if (fileName.startsWith(File.separator)) {
393 fileName = fileName.substring(1);
394 }
395 OutputStream o = null;
396 try {
397 o = FileUtils.newOutputStream(targetDir + File.separatorChar + fileName, false);
398 IOUtils.copy(zipIn, o);
399 o.close();
400 } finally {
401 IOUtils.closeSilently(o);
402 }
403 zipIn.closeEntry();
404 }
405 zipIn.closeEntry();
406 zipIn.close();
407 } catch (IOException e) {
408 error(e);
409 } finally {
410 IOUtils.closeSilently(inFile);
411 }
412 }
413
414 private int readFileList(String[] list, int i, ArrayList<String> target,
415 boolean recursive) throws IOException {
416 while (i < list.length) {
417 String c = list[i++];
418 if (";".equals(c)) {
419 break;
420 }
421 c = getFile(c);
422 if (!FileUtils.exists(c)) {
423 throw new IOException("File not found: " + c);
424 }
425 if (recursive) {
426 addFilesRecursive(c, target);
427 } else {
428 target.add(c);
429 }
430 }
431 return i;
432 }
433
434 private void addFilesRecursive(String f, ArrayList<String> target) {
435 if (FileUtils.isDirectory(f)) {
436 for (String c : FileUtils.newDirectoryStream(f)) {
437 addFilesRecursive(c, target);
438 }
439 } else {
440 target.add(getFile(f));
441 }
442 }
443
444 private String getFile(String f) {
445 if (FileUtils.isAbsolute(f)) {
446 return f;
447 }
448 String unwrapped = FileUtils.unwrap(f);
449 String prefix = f.substring(0, f.length() - unwrapped.length());
450 f = prefix + currentWorkingDirectory + File.separatorChar + unwrapped;
451 return FileUtils.toRealPath(f);
452 }
453
454 private void showHelp() {
455 println("Commands are case sensitive");
456 println("? or help " +
457 "Display this help");
458 println("cat <file> " +
459 "Print the contents of the file");
460 println("cd <dir> " +
461 "Change the directory");
462 println("chmod -w <file> " +
463 "Make the file read-only");
464 println("cp <source> <target> " +
465 "Copy a file");
466 println("head <file> " +
467 "Print the first few lines of the contents");
468 println("ls [<dir>] " +
469 "Print the directory contents");
470 println("mkdir <dir> " +
471 "Create a directory (including parent directories)");
472 println("mv <source> <target> " +
473 "Rename a file or directory");
474 println("pwd " +
475 "Print the current working directory");
476 println("rm <file> " +
477 "Remove a file");
478 println("rm -r <dir> " +
479 "Remove a directory, recursively");
480 println("rm -rf <dir> " +
481 "Remove a directory, recursively; force");
482 println("touch <file> " +
483 "Update the last modified date (creates the file)");
484 println("truncate -s <size> <file> " +
485 "Set the file length");
486 println("unzip <zip> " +
487 "Extract all files from the zip file");
488 println("zip [-r] <zip> <files..> " +
489 "Create a zip file (-r to recurse directories)");
490 println("exit Exit");
491 println("");
492 }
493
494 private String readLine() throws IOException {
495 String line = reader.readLine();
496 if (line == null) {
497 throw new IOException("Aborted");
498 }
499 return line;
500 }
501
502 private void print(String s) {
503 out.print(s);
504 out.flush();
505 }
506
507 private void println(String s) {
508 out.println(s);
509 out.flush();
510 }
511
512 }