Ejemplo n.º 1
0
Archivo: tui.py Proyecto: bc-python/cdt
def choosedir(description, constraint):
    print()
    print(description)

    while True:
        choice = input("\nPath to the directory:\n--> ")
        choice = cleanpath_escapedchars(choice)

        ppath = PPath(choice)

        # An existing file.
        if ppath.is_file():
            print()
            print("The path points to a file !", end=" ")

# An existing directory.
        elif ppath.is_dir():
            if constraint == DIR_MUST_BE_NEW:
                print()
                print("We need a new directory !", end=" ")

            elif constraint == DIR_MUST_BE_EMPTY and not ppath.is_empty():
                print()
                print("We need an empty directory !", end=" ")

            else:
                break

# A new directory.
        else:
            break

        print("Try again.")

    return ppath
Ejemplo n.º 2
0
def minify(packages):
    locallatexdir = PPath("/usr/local/texlive/2020/texmf-dist")

    stdimports = defaultdict(list)

    print(f"{DECO}* Trying to analyze imports of the offical sty files")

    for stdsty in locallatexdir.walk("file::**.sty"):
        stdname = stdsty.stem

        if stdname in packages \
        and stdname not in PACKAGE_ALREADY_ANALYZED:
            print(f"{DECO*2}- Looking inside the offical << {stdsty.name} >>")

            PACKAGE_ALREADY_ANALYZED.append(stdname)

            with stdsty.open(mode="r", encoding="utf-8") as stdfile:
                for oneline in stdfile.readlines():
                    oneline = oneline.strip()

                    if not oneline:
                        continue

                    info = analyze(info=oneline, nobug=True)

                    if info is None:
                        continue

                    if info[KIND_ID] == PACKAGE_ID:
                        stdimports[stdname] += info[NAMES_ID]

                if stdname not in stdimports:
                    stdimports[stdname] = []


# Local sty.
    localpackages = set(packages) - set(stdimports.keys())

    # Let's minimize.
    somecleaningdone = True

    while (somecleaningdone):
        somecleaningdone = False

        for pack in stdimports:
            for _, itsimports in stdimports.items():
                if pack in itsimports:
                    somecleaningdone = True
                    break

            if somecleaningdone:
                del stdimports[pack]
                break

    shortlist = list(stdimports) + list(localpackages)

    return sorted(shortlist)
Ejemplo n.º 3
0
    def _build_treeview(self):
        """
prototype::
    see = self.buildviews , self._rbuild_treeview

    action = this method returns the attribut ``self.treeview`` (most of the
             job is done recursively by the method ``self._rbuild_treeview``)
        """
        walkview = []
        extradepth = 0
        dirs_found = []

        # Main folder or not ?
        if self.MAIN_PATH in self._display:
            walkview.append({
                self.TAG_TAG: DIR_TAG,
                self.DEPTH_TAG: 0,
                self.PPATH_TAG: self.ppath
            })

            extradepth += 1

            dirs_found.append(PPath("."))

# We have to take care of the parent folders of the matching files and folders.
        for ppath in self.ppath.walk(self.regpath):
            relppath = ppath.relative_to(self.ppath)

            for rel_onepar in relppath.parents:
                if rel_onepar in dirs_found:
                    break

                else:
                    onepar = self.ppath / rel_onepar

                    walkview.append({
                        self.TAG_TAG: DIR_TAG,
                        self.DEPTH_TAG: ppath.depth_in(onepar) + extradepth,
                        self.PPATH_TAG: onepar
                    })

                    dirs_found.append(rel_onepar)

            if ppath._tag in ALL_DIR_TAGS:
                dirs_found.append(ppath.relative_to(self.ppath))

            walkview.append({
                self.TAG_TAG: ppath._tag,
                self.DEPTH_TAG: ppath.depth_in(self.ppath) + extradepth,
                self.PPATH_TAG: ppath
            })

        walkview.sort(key=lambda x: str([x[self.PPATH_TAG]]))

        # Let's work recursively.
        self.treeview = self._rbuild_treeview(walkview)
Ejemplo n.º 4
0
def _localdir_texlive(osname=""):
    """
prototype::
    arg = str: osname = "" in [OS_WIN , OS_LINUX , OS_MAC];
          the name of the ¨os (logical, isn't it ?), that can be found
          automatically if you use the default value ``osname = ""``

    return = PPath ;
             the path of the ¨texlive directory where we have to put special
             ¨latex packages.
    """
    if osname == "":
        osname = system()

    if osname == OS_WIN:
        localdir = runthis("kpsexpand '$TEXMFLOCAL'")
        localdir = PPath(localdir.strip()).normpath

    elif osname in [OS_LINUX, OS_MAC]:
        localdir = runthis('kpsewhich --var-value=TEXMFLOCAL')
        localdir = PPath(localdir.strip()).normpath

    else:
        raise OSError("unsupported OS << {0} >>.".format(osname))

    return localdir
Ejemplo n.º 5
0
#!/usr/bin/env python3

import argparse

from mistool.os_use import (cd, PPath, runthis)

from mistool.string_use import joinand

# --------------- #
# -- CONSTANTS -- #
# --------------- #

THIS_DIR = PPath(__file__).parent

SUFFIX_CFG = {
    "extra": ('-nox', '--noextra'),
    "slow": ('-nos', '--noslow'),
}

EXT_2_CMDS = {"py": 'python', "sh": 'bash'}

PPATH_PATTERNS = [f"file::build-*.{ext}" for ext in EXT_2_CMDS]

# --------- #
# -- CLI -- #
# --------- #

DESC = "This file looks for scripts named ``build-*`` with extensions "
DESC += joinand([f"``.{ext}`` [{cmd}]" for ext, cmd in EXT_2_CMDS.items()])
DESC += ". The scripts founded are executed using natural sorting on their paths."
Ejemplo n.º 6
0
#! /usr/bin/env python3

from collections import defaultdict

from mistool.latex_use import Build, clean as latexclean
from mistool.os_use import cd, PPath, runthis
from mistool.string_use import between, case, joinand, MultiReplace
from mistool.term_use import ALL_FRAMES, withframe
from orpyste.data import ReadBlock

THIS_DIR = PPath( __file__ ).parent

TEMPLATE_PATH = THIS_DIR / "config" / "doc[fr].tex"
DIR_DOC_PATH  = THIS_DIR.parent / "lyalgo"
DOC_PATH      = DIR_DOC_PATH / "lyalgo-doc[fr].tex"
EXA_DIR_DEST  = DIR_DOC_PATH / "examples"

DOUBLE_BRACES = MultiReplace({
    '{': '{{',
    '}': '}}'
})

PYFORMAT = MultiReplace({
    '%((': '{',
    '))%': '}'
})


# ----------------------- #
# -- TOOLS & CONSTANTS -- #
# ----------------------- #
Ejemplo n.º 7
0
# -- USER'S CHOICE -- #
# ------------------- #

a, b = 141, 27

SHOW_ALL = True
SUBDIR = "27-141[all]"

SHOW_ALL = False
SUBDIR = "27-141[Main]"

# --------------- #
# -- CONSTANTS -- #
# --------------- #

THIS_DIR = PPath(__file__).parent
STEPS_DIR = THIS_DIR / "tikz" / SUBDIR

STEPS_DIR.create("dir")

with (THIS_DIR / "config" / "minitikz.tex").open(mode="r",
                                                 encoding="utf-8") as f:
    TIKZ_TEMPLATE = f.read()

for old, new in [
    ("{", "{{"),
    ("}", "}}"),
    ("<<", "{"),
    (">>", "}"),
]:
    TIKZ_TEMPLATE = TIKZ_TEMPLATE.replace(old, new)
Ejemplo n.º 8
0
                tempfile.remove()


# ---------------------------------- #
# -- ABOUT THE LATEX DISTRIBUTION -- #
# ---------------------------------- #

# Sources :
#    * http://tex.stackexchange.com/a/68820/6880
#    * http://tex.stackexchange.com/a/69484/6880
#    * https://groups.google.com/forum/?hl=fr&fromgroups=#!topic/fr.comp.text.tex/ivuCnUlW7i8

# << Warning ! >> The following path is the recommended one for the folder to
# use for homemade packages.

MIKETEX_LOCALDIR = PPath('C:/texmf-local')


def _localdir_texlive(osname=""):
    """
prototype::
    arg = str: osname = "" in [OS_WIN , OS_LINUX , OS_MAC];
          the name of the ¨os (logical, isn't it ?), that can be found
          automatically if you use the default value ``osname = ""``

    return = PPath ;
             the path of the ¨texlive directory where we have to put special
             ¨latex packages.
    """
    if osname == "":
        osname = system()
Ejemplo n.º 9
0
#! /usr/bin/env python3

import re

from collections import defaultdict
from itertools import product

from mistool.os_use import PPath
from mistool.string_use import between, joinand
from orpyste.data import ReadBlock

BASENAME = PPath(__file__).stem.replace("build-", "")
BASENAME = BASENAME.replace("[slow]", "")

THIS_DIR = PPath(__file__).parent
STY_FILE = THIS_DIR / f'{BASENAME}.sty'
TEX_FILE = STY_FILE.parent / (STY_FILE.stem + "[fr].tex")

PATTERN_FOR_PEUF = re.compile("\d+-(.*)")
match = re.search(PATTERN_FOR_PEUF, STY_FILE.stem)
PEUF_FILE = STY_FILE.parent / (match.group(1).strip() + ".peuf")

DECO = " " * 4

# ----------- #
# -- TOOLS -- #
# ----------- #

DELIMS = {'[...]': "C", ']...[': "O"}

Ejemplo n.º 10
0
# ----------------- #
# -- EXTRA TOOLS -- #
# ----------------- #

from mistool.os_use import PPath

from pymodules.available import *
from pymodules.wanted import *
from pymodules.cookify import *

# --------------- #
# -- CONSTANTS -- #
# --------------- #

THIS_DIR = PPath(__file__).parent

COOKIECUTTER_TEMP = THIS_DIR / "cookiecutter-templates"
PEUF_DIR = THIS_DIR / "peuf-init"

# ----------------- #
# -- CLI MANAGER -- #
# ----------------- #

peuf_files = findpeufs(COOKIECUTTER_TEMP, PEUF_DIR)

if not peuf_files:
    print()
    print('Nothing found !\n')
    exit(0)
Ejemplo n.º 11
0
#! /usr/bin/env python3

from mistool.latex_use import clean as latexclean
from mistool.os_use import PPath

# ----------------------- #
# -- TOOLS & CONSTANTS -- #
# ----------------------- #

THIS_DIR = PPath(__file__).parent

PROJECT_NAME = "tnsalgo"
PROJECT_DIR = THIS_DIR.parent / f"{PROJECT_NAME}"

# ----------------------- #
# -- CLEAN BEFORE PUSH -- #
# ----------------------- #

for toremove in PROJECT_DIR.walk("dir::**_minted"):
    if toremove.name.startswith("_minted"):
        toremove.remove()

for toremove in THIS_DIR.walk("file::**.macros-x.txt"):
    toremove.remove()

for toremove in PROJECT_DIR.walk("file::*.macros-x.txt"):
    toremove.remove()

for toremove in THIS_DIR.walk("file::**.pdf"):
    toremove.remove()
Ejemplo n.º 12
0
from pytest import fixture

from mistool.os_use import PPath
from orpyste.data import ReadBlock as READ

# ------------------- #
# -- MODULE TESTED -- #
# ------------------- #

from mistool import term_use

# ----------------------- #
# -- GENERAL CONSTANTS -- #
# ----------------------- #

THIS_DIR = PPath(__file__).parent

DIRVIEW_CLASS = term_use.DirView

# --------------------------------------- #
# -- THE_DATAS_FOR_TESTING FOR TESTING -- #
# --------------------------------------- #

VIRTUAL_DIR = THIS_DIR

while VIRTUAL_DIR.name != "test":
    VIRTUAL_DIR = VIRTUAL_DIR.parent

VIRTUAL_DIR /= "virtual_dir"

THE_DATAS_FOR_TESTING = OrderedDict()
Ejemplo n.º 13
0
# -- SEVERAL IMPORTS -- #
# --------------------- #

from mistool.os_use import (
    cd,
    PPath,
    runthis
)
from mistool.term_use import withframe


# --------------- #
# -- CONSTANTS -- #
# --------------- #

THIS_DIR = PPath(__file__).parent
LOG_FILE = THIS_DIR / "log.txt"


# --------------- #
# -- FUNCTIONS -- #
# --------------- #

def printtile(text):
    print(
        "",
        withframe(text),
        "",
        sep = "\n"
    )
Ejemplo n.º 14
0
#! /usr/bin/env python3

from mistool.latex_use import clean as latexclean
from mistool.os_use import PPath

# ----------------------- #
# -- TOOLS & CONSTANTS -- #
# ----------------------- #

FACTORY_DIR = PPath(__file__).parent
LYBOOK_DIR = FACTORY_DIR.parent / "lybook"

# ----------------------- #
# -- CLEAN BEFORE PUSH -- #
# ----------------------- #

latexclean(LYBOOK_DIR)
Ejemplo n.º 15
0
#!/usr/bin/env python3

# --------------------- #
# -- SEVERAL IMPORTS -- #
# --------------------- #

from mistool.os_use import PPath, runthis

# --------------- #
# -- CONSTANTS -- #
# --------------- #

THIS_FILE = PPath(__file__)
THIS_DIR = THIS_FILE.parent

# -------------------------------------- #
# -- LAUNCHING ALL THE BUILDING TOOLS -- #
# -------------------------------------- #

for onepath in THIS_DIR.walk("file::**build_*.py"):
    print('+ Launching "{0}"'.format(onepath.name))

    runthis(cmd='python "{0}"'.format(onepath), showoutput=True)
Ejemplo n.º 16
0
from mistool.os_use import PPath
from orpyste.data import ReadBlock as READ


# ------------------- #
# -- MODULE TESTED -- #
# ------------------- #

from mistool import term_use


# ----------------------- #
# -- GENERAL CONSTANTS -- #
# ----------------------- #

THIS_DIR = PPath(__file__).parent

DIRVIEW_CLASS = term_use.DirView


# --------------------------------------- #
# -- THE_DATAS_FOR_TESTING FOR TESTING -- #
# --------------------------------------- #

VIRTUAL_DIR = THIS_DIR

while VIRTUAL_DIR.name != "test":
    VIRTUAL_DIR = VIRTUAL_DIR.parent

VIRTUAL_DIR /= "virtual_dir"