OLD | NEW |
1 # Copyright 2013 The Chromium Authors. All rights reserved. | 1 # Copyright 2015 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 """A temp file that automatically gets pushed and deleted from a device.""" | 5 # pylint: disable=unused-wildcard-import |
| 6 # pylint: disable=wildcard-import |
6 | 7 |
7 # pylint: disable=W0622 | 8 from devil.android.device_temp_file import * |
8 | |
9 import threading | |
10 | |
11 from pylib import cmd_helper | |
12 from pylib.device import device_errors | |
13 | |
14 _COMMAND_TEMPLATE = ( | |
15 # Make sure that the temp dir is writable | |
16 'test -d {dir} && ' | |
17 # If 5 random attempts fail, something is up. | |
18 'for i in 1 2 3 4 5; do ' | |
19 'fn={dir}/{prefix}-$(date +%s)-"$RANDOM"{suffix};' | |
20 'test -e "$fn" || break;' | |
21 'done && ' | |
22 # Touch the file, so other temp files can't get the same name. | |
23 'touch "$fn" && echo -n "$fn"') | |
24 | |
25 class DeviceTempFile(object): | |
26 def __init__(self, adb, suffix='', prefix='temp_file', dir='/data/local/tmp'): | |
27 """Find an unused temporary file path in the devices external directory. | |
28 | |
29 When this object is closed, the file will be deleted on the device. | |
30 | |
31 Args: | |
32 adb: An instance of AdbWrapper | |
33 suffix: The suffix of the name of the temp file. | |
34 prefix: The prefix of the name of the temp file. | |
35 dir: The directory on the device where to place the temp file. | |
36 """ | |
37 self._adb = adb | |
38 command = _COMMAND_TEMPLATE.format( | |
39 dir=cmd_helper.SingleQuote(dir), | |
40 suffix=cmd_helper.SingleQuote(suffix), | |
41 prefix=cmd_helper.SingleQuote(prefix)) | |
42 self.name = self._adb.Shell(command) | |
43 self.name_quoted = cmd_helper.SingleQuote(self.name) | |
44 | |
45 def close(self): | |
46 """Deletes the temporary file from the device.""" | |
47 # ignore exception if the file is already gone. | |
48 def helper(): | |
49 try: | |
50 self._adb.Shell('rm -f %s' % self.name_quoted, expect_status=None) | |
51 except device_errors.AdbCommandFailedError: | |
52 # file does not exist on Android version without 'rm -f' support (ICS) | |
53 pass | |
54 | |
55 # It shouldn't matter when the temp file gets deleted, so do so | |
56 # asynchronously. | |
57 threading.Thread(target=helper).start() | |
58 | |
59 def __enter__(self): | |
60 return self | |
61 | |
62 def __exit__(self, type, value, traceback): | |
63 self.close() | |
OLD | NEW |