1#!/usr/bin/python
2# Copyright (c) 2014 The Native Client Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Manages files that'll get deleted when the driver exits unless SAVE_TEMPS.
7"""
8
9import os
10
11import pathtools
12from driver_env import env
13from driver_log import Log, AtDriverExit
14
15class TempFileHandler(object):
16  def __init__(self):
17    AtDriverExit(self.wipe)
18    self.files = []
19
20  def add(self, path):
21    if env.getbool('SAVE_TEMPS'):
22      return
23    path = pathtools.abspath(path)
24    self.files.append(path)
25
26  def wipe(self):
27    for path in self.files:
28      try:
29        sys_path = pathtools.tosys(path)
30        # If exiting early, the file may not have been created yet.
31        if os.path.exists(sys_path):
32          os.remove(sys_path)
33      except OSError as err:
34        Log.Error("TempFileHandler: Unable to wipe file %s w/ error %s",
35                  pathtools.touser(path),
36                  err.strerror)
37    self.files = []
38
39TempFiles = TempFileHandler()
40