OXYGENHUB
◆ main openmsx / build / outpututils.py
1.0 KiB · Python · last changed chore(): initial commit 1 month ago source blame history raw
1
# Various utility functions for generating output files and directories.
2
3
from io import open
4
from os import makedirs
5
from os.path import dirname, isdir, isfile
6
7
def createDirFor(filePath):
8
	'''Creates an output directory for containing the given file path.
9
	Nothing happens if the directory already exsits.
10
	'''
11
	dirPath = dirname(filePath)
12
	if dirPath and not isdir(dirPath):
13
		makedirs(dirPath)
14
15
def rewriteIfChanged(path, lines):
16
	'''Writes the file with the given path if it does not exist yet or if its
17
	contents should change. The contents are given by the "lines" sequence.
18
	Returns True if the file was (re)written, False otherwise.
19
	'''
20
	newLines = [line + '\n' for line in lines]
21
22
	if isfile(path):
23
		with open(path, 'r', encoding='utf-8') as inp:
24
			oldLines = inp.readlines()
25
		if newLines == oldLines:
26
			print('Up to date: %s' % path)
27
			return False
28
		else:
29
			print('Updating %s...' % path)
30
	else:
31
		print('Creating %s...' % path)
32
		createDirFor(path)
33
34
	with open(path, 'w', encoding='utf-8') as out:
35
		out.writelines(newLines)
36
	return True