xref: /aosp_15_r20/external/fonttools/Lib/fontTools/misc/cliTools.py (revision e1fe3e4ad2793916b15cccdc4a7da52a7e1dd0e9)
1"""Collection of utilities for command-line interfaces and console scripts."""
2
3import os
4import re
5
6
7numberAddedRE = re.compile(r"#\d+$")
8
9
10def makeOutputFileName(
11    input, outputDir=None, extension=None, overWrite=False, suffix=""
12):
13    """Generates a suitable file name for writing output.
14
15    Often tools will want to take a file, do some kind of transformation to it,
16    and write it out again. This function determines an appropriate name for the
17    output file, through one or more of the following steps:
18
19    - changing the output directory
20    - appending suffix before file extension
21    - replacing the file extension
22    - suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid
23      overwriting an existing file.
24
25    Args:
26        input: Name of input file.
27        outputDir: Optionally, a new directory to write the file into.
28        suffix: Optionally, a string suffix is appended to file name before
29            the extension.
30        extension: Optionally, a replacement for the current file extension.
31        overWrite: Overwriting an existing file is permitted if true; if false
32            and the proposed filename exists, a new name will be generated by
33            adding an appropriate number suffix.
34
35    Returns:
36        str: Suitable output filename
37    """
38    dirName, fileName = os.path.split(input)
39    fileName, ext = os.path.splitext(fileName)
40    if outputDir:
41        dirName = outputDir
42    fileName = numberAddedRE.split(fileName)[0]
43    if extension is None:
44        extension = os.path.splitext(input)[1]
45    output = os.path.join(dirName, fileName + suffix + extension)
46    n = 1
47    if not overWrite:
48        while os.path.exists(output):
49            output = os.path.join(
50                dirName, fileName + suffix + "#" + repr(n) + extension
51            )
52            n += 1
53    return output
54