Merge pull request #2756 from fonttools/makeOutputFileName-fragment

[cliTools.makeOutputFileName] Add fragment argument
This commit is contained in:
Behdad Esfahbod 2022-08-22 06:29:19 -06:00 committed by GitHub
commit 3eed84da01
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 53 additions and 27 deletions

View File

@ -6,7 +6,7 @@ import re
numberAddedRE = re.compile(r"#\d+$") numberAddedRE = re.compile(r"#\d+$")
def makeOutputFileName(input, outputDir=None, extension=None, overWrite=False): def makeOutputFileName(input, outputDir=None, extension=None, overWrite=False, suffix=""):
"""Generates a suitable file name for writing output. """Generates a suitable file name for writing output.
Often tools will want to take a file, do some kind of transformation to it, Often tools will want to take a file, do some kind of transformation to it,
@ -14,6 +14,7 @@ def makeOutputFileName(input, outputDir=None, extension=None, overWrite=False):
output file, through one or more of the following steps: output file, through one or more of the following steps:
- changing the output directory - changing the output directory
- appending suffix before file extension
- replacing the file extension - replacing the file extension
- suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid - suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid
overwriting an existing file. overwriting an existing file.
@ -21,6 +22,8 @@ def makeOutputFileName(input, outputDir=None, extension=None, overWrite=False):
Args: Args:
input: Name of input file. input: Name of input file.
outputDir: Optionally, a new directory to write the file into. outputDir: Optionally, a new directory to write the file into.
suffix: Optionally, a string suffix is appended to file name before
the extension.
extension: Optionally, a replacement for the current file extension. extension: Optionally, a replacement for the current file extension.
overWrite: Overwriting an existing file is permitted if true; if false overWrite: Overwriting an existing file is permitted if true; if false
and the proposed filename exists, a new name will be generated by and the proposed filename exists, a new name will be generated by
@ -36,11 +39,11 @@ def makeOutputFileName(input, outputDir=None, extension=None, overWrite=False):
fileName = numberAddedRE.split(fileName)[0] fileName = numberAddedRE.split(fileName)[0]
if extension is None: if extension is None:
extension = os.path.splitext(input)[1] extension = os.path.splitext(input)[1]
output = os.path.join(dirName, fileName + extension) output = os.path.join(dirName, fileName + suffix + extension)
n = 1 n = 1
if not overWrite: if not overWrite:
while os.path.exists(output): while os.path.exists(output):
output = os.path.join( output = os.path.join(
dirName, fileName + "#" + repr(n) + extension) dirName, fileName + suffix + "#" + repr(n) + extension)
n += 1 n += 1
return output return output

View File

@ -10,6 +10,7 @@ from fontTools.ttLib.tables.otBase import USE_HARFBUZZ_REPACKER
from fontTools.otlLib.maxContextCalc import maxCtxFont from fontTools.otlLib.maxContextCalc import maxCtxFont
from fontTools.pens.basePen import NullPen from fontTools.pens.basePen import NullPen
from fontTools.misc.loggingTools import Timer from fontTools.misc.loggingTools import Timer
from fontTools.misc.cliTools import makeOutputFileName
from fontTools.subset.util import _add_method, _uniq_sort from fontTools.subset.util import _add_method, _uniq_sort
from fontTools.subset.cff import * from fontTools.subset.cff import *
from fontTools.subset.svg import * from fontTools.subset.svg import *
@ -3189,12 +3190,7 @@ def main(args=None):
font = load_font(fontfile, options, dontLoadGlyphNames=dontLoadGlyphNames) font = load_font(fontfile, options, dontLoadGlyphNames=dontLoadGlyphNames)
if outfile is None: if outfile is None:
basename, _ = splitext(fontfile) outfile = makeOutputFileName(fontfile, overWrite=True, suffix=".subset")
if options.flavor is not None:
ext = "." + options.flavor.lower()
else:
ext = ".ttf" if font.sfntVersion == "\0\1\0\0" else ".otf"
outfile = basename + ".subset" + ext
with timer("compile glyph list"): with timer("compile glyph list"):
if wildcard_glyphs: if wildcard_glyphs:

View File

@ -300,18 +300,34 @@ def main(args=None):
args = sys.argv[1:] args = sys.argv[1:]
from fontTools.ttLib import TTFont from fontTools.ttLib import TTFont
from fontTools.misc.cliTools import makeOutputFileName
import argparse
if len(args) != 2: parser = argparse.ArgumentParser(
print("usage: fonttools ttLib.scaleUpem font new-upem") "fonttools ttLib.scaleUpem", description="Change the units-per-EM of fonts"
sys.exit() )
parser.add_argument("font", metavar="font", help="Font file.")
parser.add_argument(
"new_upem", metavar="new-upem", help="New units-per-EM integer value."
)
parser.add_argument(
"--output-file", metavar="path", default=None, help="Output file."
)
font = TTFont(args[0]) options = parser.parse_args(args)
new_upem = int(args[1])
font = TTFont(options.font)
new_upem = int(options.new_upem)
output_file = (
options.output_file
if options.output_file is not None
else makeOutputFileName(options.font, overWrite=True, suffix="-scaled")
)
scale_upem(font, new_upem) scale_upem(font, new_upem)
print("Writing out.ttf") print("Writing %s" % output_file)
font.save("out.ttf") font.save(output_file)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -90,6 +90,7 @@ from fontTools.varLib import builder
from fontTools.varLib.mvar import MVAR_ENTRIES from fontTools.varLib.mvar import MVAR_ENTRIES
from fontTools.varLib.merger import MutatorMerger from fontTools.varLib.merger import MutatorMerger
from fontTools.varLib.instancer import names from fontTools.varLib.instancer import names
from fontTools.misc.cliTools import makeOutputFileName
import collections import collections
from copy import deepcopy from copy import deepcopy
from enum import IntEnum from enum import IntEnum
@ -327,7 +328,9 @@ def limitTupleVariationAxisRange(var, axisTag, axisRange):
return [var, newVar] return [var, newVar]
def _instantiateGvarGlyph(glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True): def _instantiateGvarGlyph(
glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True
):
coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics) coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics)
endPts = ctrl.endPts endPts = ctrl.endPts
@ -363,22 +366,26 @@ def _instantiateGvarGlyph(glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits,
for var in tupleVarStore: for var in tupleVarStore:
var.optimize(coordinates, endPts, isComposite) var.optimize(coordinates, endPts, isComposite)
def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True): def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True):
"""Remove? """Remove?
https://github.com/fonttools/fonttools/pull/2266""" https://github.com/fonttools/fonttools/pull/2266"""
gvar = varfont["gvar"] gvar = varfont["gvar"]
glyf = varfont["glyf"] glyf = varfont["glyf"]
hMetrics = varfont['hmtx'].metrics hMetrics = varfont["hmtx"].metrics
vMetrics = getattr(varfont.get('vmtx'), 'metrics', None) vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
_instantiateGvarGlyph(glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize) _instantiateGvarGlyph(
glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
)
def instantiateGvar(varfont, axisLimits, optimize=True): def instantiateGvar(varfont, axisLimits, optimize=True):
log.info("Instantiating glyf/gvar tables") log.info("Instantiating glyf/gvar tables")
gvar = varfont["gvar"] gvar = varfont["gvar"]
glyf = varfont["glyf"] glyf = varfont["glyf"]
hMetrics = varfont['hmtx'].metrics hMetrics = varfont["hmtx"].metrics
vMetrics = getattr(varfont.get('vmtx'), 'metrics', None) vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
# Get list of glyph names sorted by component depth. # Get list of glyph names sorted by component depth.
# If a composite glyph is processed before its base glyph, the bounds may # If a composite glyph is processed before its base glyph, the bounds may
# be calculated incorrectly because deltas haven't been applied to the # be calculated incorrectly because deltas haven't been applied to the
@ -393,7 +400,9 @@ def instantiateGvar(varfont, axisLimits, optimize=True):
), ),
) )
for glyphname in glyphnames: for glyphname in glyphnames:
_instantiateGvarGlyph(glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize) _instantiateGvarGlyph(
glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
)
if not gvar.variations: if not gvar.variations:
del varfont["gvar"] del varfont["gvar"]
@ -924,7 +933,9 @@ def instantiateAvar(varfont, axisLimits):
if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum: if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum:
continue continue
fromCoord = normalizeValue(fromCoord, (axisRange.minimum, 0, axisRange.maximum)) fromCoord = normalizeValue(
fromCoord, (axisRange.minimum, 0, axisRange.maximum)
)
assert mappedMin <= toCoord <= mappedMax assert mappedMin <= toCoord <= mappedMax
toCoord = normalizeValue(toCoord, (mappedMin, 0, mappedMax)) toCoord = normalizeValue(toCoord, (mappedMin, 0, mappedMax))
@ -1399,7 +1410,7 @@ def parseArgs(args):
"--no-recalc-timestamp", "--no-recalc-timestamp",
dest="recalc_timestamp", dest="recalc_timestamp",
action="store_false", action="store_false",
help="Don't set the output font's timestamp to the current time." help="Don't set the output font's timestamp to the current time.",
) )
parser.add_argument( parser.add_argument(
"--no-recalc-bounds", "--no-recalc-bounds",
@ -1468,9 +1479,9 @@ def main(args=None):
updateFontNames=options.update_name_table, updateFontNames=options.update_name_table,
) )
suffix = "-instance" if isFullInstance else "-partial"
outfile = ( outfile = (
os.path.splitext(infile)[0] makeOutputFileName(infile, overWrite=True, suffix=suffix)
+ "-{}.ttf".format("instance" if isFullInstance else "partial")
if not options.output if not options.output
else options.output else options.output
) )