예제 #1
0
def doNfgrab():
    """Grab json data from the config file. Iterate through each font and...

	generate a package for each.
	"""
    data = json.loads(open("templates/paths.json", "r").read())
    for data["fontFamilyBase"] in os.listdir(data["file"]["patched"]):
        data["fontFamilyBaseFile"] = data["file"]["patched"] + "/" + data[
            "fontFamilyBase"]
        if os.path.isdir(data["fontFamilyBaseFile"]):
            printf = Logger()
            printf.logPrint(
                data["fontFamilyBase"],
                LogType.SUCCESS if doFontFamily(data) else LogType.ERROR)
예제 #2
0
def main():
    ''' Main entry point for cli '''
    parser = argparse.ArgumentParser(
        description="Compare base16 and base24 windows terminal themes quickly"
    )
    parser.add_argument(
        "themes",
        action="store",
        help="directory containing generated windows terminal themes")
    parser.add_argument("--all",
                        action="store_true",
                        help="compare all schemes")
    args = parser.parse_args()
    # Check for and report level8 errors
    if not os.path.isdir(args.themes):
        Logger().logPrint(args.themes + " is not a valid directory",
                          LogType.ERROR)
        sys.exit(1)

    # Windows has crap colour support to use this
    if platform.system() == "Windows":
        kernel32 = ctypes.windll.kernel32
        kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

    files = {}
    for theme in os.listdir(args.themes):
        key = theme.replace(".json", "").replace("base16-",
                                                 "").replace("base24-", "")
        if key in files:
            files[key].append(theme)
        else:
            files[key] = [theme]

    # Check for b16 and b24 variant of a file
    for key in files:
        if len(files[key]) == 2:  # Both variants
            Logger().logPrint(key, LogType.HEADER)
            Logger().logPrint("  B     W   R Y   G C B M ", LogType.BOLD)
            if "base16-" in files[key][0]:  # First one is base16
                printColours(os.path.join(args.themes, files[key][0]))
                printColours(os.path.join(args.themes, files[key][1]))
            else:
                printColours(os.path.join(args.themes, files[key][1]))
                printColours(os.path.join(args.themes, files[key][0]))
        elif args.all:
            Logger().logPrint(files[key][0].replace(".json", ""),
                              LogType.HEADER)
            Logger().logPrint("  B     W   R Y   G C B M ", LogType.BOLD)
            printColours(os.path.join(args.themes, files[key][0]))
예제 #3
0
def openColourSwatch(file: str) -> ColourSwatch:
    """Open a colour swatch file into a layer image object
	Args:
		file (str): path/ filename
	Returns:
		ColourSwatch: a colour swatch object
	"""
    functionMap = {
        "gpl": openSwatch_GPL,
        "yaml": openSwatch_YAML,
        "colors": openSwatch_COLOR,
        "spl": openSwatch_SPL,
        "skp": openSwatch_SKP,
        "soc": openSwatch_SOC,
        "txt": openSwatch_TXT,
        "acbl": openSwatch_ACBL,
        "xml": openSwatch_XML,
        "pal": openSwatch_CDPAL,
        "hpl": openSwatch_HPL,
        "toml": openSwatch_TOML,
        "json": openSwatch_JSON,
        "png": openSwatch_PNG,
        "jpg": openSwatch_IMAGE,
        "webp": openSwatch_IMAGE,
        "ase": openSwatch_ASE,
        "svg": openSwatch_SVG
    }
    if not exists(file):
        Logger(FHFormatter()).logPrint(file + " does not exist", LogType.ERROR)
        raise FileExistsError
    fileExt = file.split(".")[-1].lower()
    if fileExt not in functionMap:
        extNotRecognised(file)
        raise ValueError
    return functionMap[fileExt](file)
예제 #4
0
def trace(filename: str,
          blackAndWhite: bool = False,
          mode: str = "default") -> str:
    """Do a trace of an image on the filesystem using the pyppeteer library.

	Args:
		filename (str): The location of the file on the filesystem, use an
		absolute filepath for this
		blackAndWhite (bool, optional): Trace a black and white SVG. Defaults to False.
		mode (str, optional): Set the mode. See https://github.com/jankovicsandras/imagetracerjs
		for more information. Defaults to "default".

	Returns:
		str: SVG string
	"""
    if mode.find("black") >= 0 or blackAndWhite:
        mode = "posterized1"
    try:
        return asyncio.get_event_loop().run_until_complete(
            doTrace(filename.replace("\\", "/"), mode))
    except ConnectionResetError:
        Logger(FHFormatter()).logPrint(
            "ConnectionResetError - probably just a hiccup " + "retrying",
            LogType.WARNING)
        return asyncio.get_event_loop().run_until_complete(
            doTrace(filename.replace("\\", "/"), mode))
예제 #5
0
def extNotRecognised(fileName: str):
    """ Output the file extension not recognised error """
    exts = [
        "gpl", "yaml", "colors", "spl", "skp", "soc", "txt", "acbl", "xml",
        "pal", "hpl", "toml", "json", "ase", "png", "jpg", "webp", "svg"
    ]
    Logger(FHFormatter()).logPrint(
        "File extension is not recognised for file: " + fileName +
        "! Must be " + "one of \"" + ", \"".join(exts) + "\"", LogType.ERROR)
예제 #6
0
def main():
    ''' Main entry point for cli '''
    parser = argparse.ArgumentParser(
        description="Convert profiles.json to base24 scheme")
    parser.add_argument("file", action="store", help="profiles.json")
    args = parser.parse_args()
    # Check for and report level8 errors
    if not os.path.isfile(args.file):
        Logger().logPrint(args.file + " is not a valid file", LogType.ERROR)
        sys.exit(1)

    filename = args.file

    base24s = genBase24s(winTerm2hex(filename))

    for base24 in base24s:
        with open(base24["scheme"] + ".yaml", "w") as outfile:
            Logger().logPrint("writing \"" + base24["scheme"] + "\" to file",
                              LogType.SUCCESS)
            yaml.dump(base24, outfile)
예제 #7
0
def main():
	''' Main entry point for cli '''
	parser = argparse.ArgumentParser(
	description="Convert .itermcolors to base24 scheme")
	parser.add_argument("file", action="store",
	help="file.itermschemes")
	args = parser.parse_args()
	# Check for and report level8 errors
	if not os.path.isfile(args.file):
		Logger().logPrint(args.file + " is not a valid file", LogType.ERROR)
		sys.exit(1)

	filename = args.file
	tree = ET.parse(filename)

	base24 = genBase24(filename, iterm2hex(tree.getroot()))

	with open(base24["scheme"]+".yaml", "w") as outfile:
		Logger().logPrint("writing \"" + base24["scheme"] + "\" to file", LogType.SUCCESS)
		yaml.dump(base24, outfile)
예제 #8
0
	CustomFormatter,
)

from io import StringIO
import sys
from pathlib import Path
from ansitoimg.render import ansiToSVG
result = StringIO()
oldStdout = sys.stdout
sys.stdout = result
THISDIR = str(Path(__file__).resolve().parent)

print("#########################")
print("#      Meterpreter      #")
print("#########################")
metLogger = Logger()
metLogger.logPrint("none", LogType.NONE)
metLogger.logPrint("bold indent", LogType.BOLD, True)
metLogger.logPrint("italic indent", LogType.ITALIC, True)
metLogger.logPrint("header", LogType.HEADER)
metLogger.logPrint("debug", LogType.DEBUG)
metLogger.logPrint("info", LogType.INFO)
metLogger.logPrint("success", LogType.SUCCESS)
metLogger.logPrint("warning", LogType.WARNING)
metLogger.logPrint("error", LogType.ERROR)
metLogger.logPrint("critical", LogType.CRITICAL)


print("#########################")
print("#          FH           #")
print("#########################")
예제 #9
0
def extNotLossless(fileName):
    """ Output the file extension not lossless error """
    Logger(FHFormatter()).logPrint(
        "File extension is not lossless: " + fileName + "! Must be " +
        "one of \"" + ", \"".join(exts) + "\"", LogType.ERROR)
예제 #10
0
def extNotSupported(fileName):
    """ Output the file extension not supported error """
    exts = ["jpg", "png", "gif"]
    Logger(FHFormatter()).logPrint(
        "File extension is not supported for file: " + fileName +
        "! Must be " + "one of \"" + ", \"".join(exts) + "\"", LogType.ERROR)
예제 #11
0
- csv
- ansi
"""
from __future__ import annotations

from csv import writer
from io import StringIO
from json import dumps

from licensecheck.types import PackageCompat

logger = None
try:
    from metprint import Logger, LogType

    logger = Logger()
except ModuleNotFoundError:
    pass


def markdown(packages: list[PackageCompat], heading: str | None = None) -> str:
    """Format to Markdown.

	Args:
		packages (list[PackageCompat]): PackageCompats to format
		heading (str, optional): Optional heading to include. Defaults to None.

	Returns:
		str: String to write to a file of stdout
	"""
    if len(packages) == 0:
예제 #12
0
"""Shared utils used by the other builder components
"""
import os
import sys
import asyncio
from contextlib import contextmanager
import yaml
from metprint import LogType, Logger, FHFormatter

printf = Logger(FHFormatter())


class JobOptions:
    """Container for options related to job processing"""
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)


CWD = os.path.realpath(os.getcwd())


@contextmanager
def compat_event_loop():
    """OS agnostic context manager for an event loop."""
    if sys.platform.startswith("win"):
        asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())

    event_loop = asyncio.get_event_loop()

    if event_loop.is_closed():
예제 #13
0
"""Adds functions used by both github_graph and github_rest.
"""
from __future__ import annotations

import datetime
import json
import os
from pathlib import Path

from metprint import FHFormatter, Logger, LogType

printf = Logger(FHFormatter())


def clear():
	"""Clear the terminal."""
	os.system("cls" if os.name == "nt" else "clear")


def getDatetime(datetimeIn: str):
	"""Get the datetime from a date in the format YYYY-MM-DDThh:mm:ssZ e.g. 2000-01-01T00:00:00Z."""
	return datetime.datetime.strptime(datetimeIn, "%Y-%m-%dT%H:%M:%SZ")


def getUsername() -> str:
	"""Get authenticated username."""
	return AUTH[0]


def getPassword() -> str:
	"""Get authenticated password."""