1# Copyright 2014 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
5import os
6
7
8_next_file_id = 0
9
10
11class FileHandle(object):
12  def __init__(self, temp_file=None, absolute_path=None):
13    """Constructs a FileHandle object.
14
15    This constructor should not be used by the user; rather it is preferred to
16    use the module-level GetAbsPath and FromTempFile functions.
17
18    Args:
19      temp_file: An instance of a temporary file object.
20      absolute_path: A path; should not be passed if tempfile is and vice-versa.
21      extension: A string that specifies the file extension. It must starts with
22        ".".
23    """
24    # Exactly one of absolute_path or temp_file must be specified.
25    assert (absolute_path is None) != (temp_file is None)
26    self._temp_file = temp_file
27    self._absolute_path = absolute_path
28
29    global _next_file_id
30    self._id = _next_file_id
31    _next_file_id += 1
32
33  @property
34  def id(self):
35    return self._id
36
37  @property
38  def extension(self):
39    return os.path.splitext(self.GetAbsPath())[1]
40
41  def GetAbsPath(self):
42    """Returns the path to the pointed-to file relative to the given start path.
43
44    Args:
45      start: A string representing a starting path.
46    Returns:
47      A string giving the relative path from path to this file.
48    """
49    if self._temp_file:
50      self._temp_file.close()
51      return self._temp_file.name
52    else:
53      return self._absolute_path
54
55
56def FromTempFile(temp_file):
57  """Constructs a FileHandle pointing to a temporary file.
58
59  Returns:
60    A FileHandle referring to a named temporary file.
61  """
62  return FileHandle(temp_file)
63
64
65def FromFilePath(path):
66  """Constructs a FileHandle from an absolute file path.
67
68  Args:
69    path: A string giving the absolute path to a file.
70  Returns:
71    A FileHandle referring to the file at the specified path.
72  """
73  return FileHandle(None, os.path.abspath(path))
74