1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """A temp file that automatically gets pushed and deleted from a device."""
7 # pylint: disable=W0622
12 from pylib
import cmd_helper
13 from pylib
.device
import device_errors
16 class DeviceTempFile(object):
17 def __init__(self
, adb
, suffix
='', prefix
='temp_file', dir='/data/local/tmp'):
18 """Find an unused temporary file path in the devices external directory.
20 When this object is closed, the file will be deleted on the device.
23 adb: An instance of AdbWrapper
24 suffix: The suffix of the name of the temp file.
25 prefix: The prefix of the name of the temp file.
26 dir: The directory on the device where to place the temp file.
29 # make sure that the temp dir is writable
30 self
._adb
.Shell('test -d %s' % cmd_helper
.SingleQuote(dir))
32 self
.name
= '{dir}/{prefix}-{time:d}-{nonce:d}{suffix}'.format(
33 dir=dir, prefix
=prefix
, time
=int(time
.time()),
34 nonce
=random
.randint(0, 1000000), suffix
=suffix
)
35 self
.name_quoted
= cmd_helper
.SingleQuote(self
.name
)
37 self
._adb
.Shell('test -e %s' % self
.name_quoted
)
38 except device_errors
.AdbCommandFailedError
:
39 break # file does not exist
41 # Immediately touch the file, so other temp files can't get the same name.
42 self
._adb
.Shell('touch %s' % self
.name_quoted
)
45 """Deletes the temporary file from the device."""
46 # ignore exception if the file is already gone.
48 self
._adb
.Shell('rm -f %s' % self
.name_quoted
)
49 except device_errors
.AdbCommandFailedError
:
50 # file does not exist on Android version without 'rm -f' support (ICS)
56 def __exit__(self
, type, value
, traceback
):