some late comments :)
[gostyle.git] / result_file.py
blobcfa47c7f42853ad95560815d28642a23b6b6a22d
1 from os.path import abspath, exists
2 import os
4 from config import OUTPUT_DIR
6 from utils.colors import *
7 from utils import misc
9 """Utility class to generate a randomly named (without collisions)
10 file to output i.e. pattern files from pachi. """
12 class ResultFile:
13 def __init__(self, filename, create_empty=False):
14 self.filename = filename
15 if create_empty:
16 assert not self.exists()
17 open(self.filename,'w').close()
19 def exists(self, warn=False):
20 status = exists(self.filename)
21 if not status and warn:
22 logging.warn("File '%s' does not exist."%(self.filename,))
23 return status
25 def __repr__(self):
26 return "ResultFile('%s')"%(self.filename,)
28 def get_random_output_base(sub_len=3, levels=2):
29 h = misc.unique_hash()
30 assert len(h) > levels * sub_len
31 assert levels >= 1
32 l = [OUTPUT_DIR]
33 for x in xrange(levels):
34 l.append( h[ x * sub_len : (x+1) * sub_len ] )
36 d = os.path.join(*l)
37 if not os.path.isdir(d):
38 os.makedirs(d)
39 return os.path.join(d, h)
41 def get_output_resultfile(suffix=''):
42 ret = ResultFile( get_random_output_base() + suffix)
43 if ret.exists():
44 raise RuntimeError("New output result file '%s' already exists, unique hash not really unique..."%(ret))
45 return ret
47 def get_output_resultpair(suffix=''):
48 basename = get_random_output_base()
49 ret1 = ResultFile(basename + '_B' + suffix)
50 ret2 = ResultFile(basename + '_W' + suffix)
51 rettup = BlackWhite(ret1, ret2)
52 for ret in rettup:
53 if ret.exists():
54 raise RuntimeError("New output result file '%s' already exists, unique hash not really unique..."%(ret))
55 return rettup