Adding Peter Thatcher to the owners file.
[chromium-blink-merge.git] / build / android / pylib / utils / device_temp_file.py
blob7d3b95b10464263c1abb9f79f4f5e90322b741b6
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
9 import random
10 import time
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.
22 Args:
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.
27 """
28 self._adb = adb
29 # make sure that the temp dir is writable
30 self._adb.Shell('test -d %s' % cmd_helper.SingleQuote(dir))
31 while True:
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)
36 try:
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)
44 def close(self):
45 """Deletes the temporary file from the device."""
46 # ignore exception if the file is already gone.
47 try:
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)
51 pass
53 def __enter__(self):
54 return self
56 def __exit__(self, type, value, traceback):
57 self.close()