• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4
5"""A temp file that automatically gets pushed and deleted from a device."""
6
7# pylint: disable=W0622
8
9import posixpath
10import random
11import threading
12
13from devil.android import device_errors
14from devil.utils import cmd_helper
15
16
17class DeviceTempFile(object):
18
19  def __init__(self, adb, suffix='', prefix='temp_file', dir='/data/local/tmp'):
20    """Find an unused temporary file path on the device.
21
22    When this object is closed, the file will be deleted on the device.
23
24    Args:
25      adb: An instance of AdbWrapper
26      suffix: The suffix of the name of the temp file.
27      prefix: The prefix of the name of the temp file.
28      dir: The directory on the device where to place the temp file.
29    """
30    self._adb = adb
31    # Python's random module use 52-bit numbers according to its docs.
32    random_hex = hex(random.randint(0, 2 ** 52))[2:]
33    self.name = posixpath.join(dir, '%s-%s%s' % (prefix, random_hex, suffix))
34    self.name_quoted = cmd_helper.SingleQuote(self.name)
35
36  def close(self):
37    """Deletes the temporary file from the device."""
38    # ignore exception if the file is already gone.
39    def delete_temporary_file():
40      try:
41        self._adb.Shell('rm -f %s' % self.name_quoted, expect_status=None)
42      except device_errors.AdbCommandFailedError:
43        # file does not exist on Android version without 'rm -f' support (ICS)
44        pass
45
46    # It shouldn't matter when the temp file gets deleted, so do so
47    # asynchronously.
48    threading.Thread(
49        target=delete_temporary_file,
50        name='delete_temporary_file(%s)' % self._adb.GetDeviceSerial()).start()
51
52  def __enter__(self):
53    return self
54
55  def __exit__(self, type, value, traceback):
56    self.close()
57