Ejemplo n.º 1
0
 def lol_write(text):
     from lmh.lib.config import get_config
     if get_config("self::colors") and get_config("::eastereggs"):
         a = lolcat.LolCat(mode=lolcat.detect_mode())
         a.cat([text], loloptions)
         loloptions.os += len(text.split("\n"))
         lolcat.reset()
         return
     sys.__stdout__.write(text)
Ejemplo n.º 2
0
Archivo: io.py Proyecto: KWARC/localmh
 def lol_write(text):
     from lmh.lib.config import get_config
     if get_config("self::colors") and get_config("::eastereggs"):
         a = lolcat.LolCat(mode = lolcat.detect_mode())
         a.cat([text], loloptions)
         loloptions.os += len(text.split("\n"))
         lolcat.reset()
         return
     sys.__stdout__.write(text)
Ejemplo n.º 3
0
Archivo: io.py Proyecto: KWARC/localmh
def std_paged(*args, **kwargs):
    """
    Pages output if a pager is available.
    """

    from lmh.lib.config import get_config

    newline = True

    # allow only the newline kwarg
    for k in kwargs:
        if k != "newline":
            raise TypeError("std() got an unexpected keyword argument '"+k+"'")
        else:
            newline = kwargs["newline"]

    if not __supressStd__:
        pager = get_config("env::pager")

        if pager == "":
            return std(*args, **kwargs)
        try:
            p = Popen([pager], stdout=sys.stdout, stderr=sys.stderr, stdin=PIPE)
            p.communicate(" ".join([str(text) for text in args]) + ('\n' if newline else ''))
        except:
            err("Unable to run configured page. ")
            err("Please check your value for env::pager. ")
            err("Falling back to STDOUT. ")
            return std(*args, **kwargs)
Ejemplo n.º 4
0
def find_source(name, quiet = False):
    """
        Finds the source of a repository.
        @param name - Name of repository to find.
        @param quiet - Should we print output.
    """

    # Check if the result is cached.
    # In that case we won't have to query again.
    if name in find_source.cache:
        return find_source.cache[name]


    # Iterate over the root urls
    # and the suffixes.
    root_urls = get_config("install::sources").rsplit(";")
    root_suffix = ["", ".git"]


    for url in root_urls:
        for url_suf in root_suffix:
            # Check if the remote repository exists.
            if exists(url+name+url_suf, False):
                find_source.cache[name] = url+name+url_suf
                return url+name+url_suf

    # We could not find any matching remote.
    # So send an error message unless we are quiet.
    if not quiet:
        err("Can not find remote repository", name)
        err("Please check install::sources and check your network connection. ")

    # and we failed.
    return False
Ejemplo n.º 5
0
def std_paged(*args, **kwargs):
    """
    Pages output if a pager is available.
    """

    from lmh.lib.config import get_config

    newline = True

    # allow only the newline kwarg
    for k in kwargs:
        if k != "newline":
            raise TypeError("std() got an unexpected keyword argument '" + k +
                            "'")
        else:
            newline = kwargs["newline"]

    if not __supressStd__:
        pager = get_config("env::pager")

        if pager == "":
            return std(*args, **kwargs)
        try:
            p = Popen([pager],
                      stdout=sys.stdout,
                      stderr=sys.stderr,
                      stdin=PIPE)
            p.communicate(" ".join([str(text) for text in args]) +
                          ('\n' if newline else ''))
        except:
            err("Unable to run configured page. ")
            err("Please check your value for env::pager. ")
            err("Falling back to STDOUT. ")
            return std(*args, **kwargs)
Ejemplo n.º 6
0
def run(argv=sys.argv[1:]):
    install_excepthook()
    if(get_config("::eastereggs") == True and argv == ["what", "is", "the", "answer", "to", "life", "the", "universe", "and", "everything?"]):
        sys.exit(42)
    if main(argv):
        sys.exit(0)
    else:
        sys.exit(1)
Ejemplo n.º 7
0
def run(argv=sys.argv[1:]):
    install_excepthook()
    if (get_config("::eastereggs") == True and argv == [
            "what", "is", "the", "answer", "to", "life", "the", "universe",
            "and", "everything?"
    ]):
        sys.exit(42)
    if main(argv):
        sys.exit(0)
    else:
        sys.exit(1)
Ejemplo n.º 8
0
    def mark_unmanaged(self):
        # we are already unmanaged.
        if not self.is_managed():
            return True

        # else we need to be added
        managed_packs = get_config("setup::unmanaged").split(",")
        managed_packs.append(self.name)

        # and store it.
        set_config("setup::unmanaged", ",".join(managed_packs))
        return True
Ejemplo n.º 9
0
    def mark_managed(self):
        # we are already managed.
        if self.is_managed():
            return True

        # else we need to be removed
        managed_packs = get_config("setup::unmanaged").split(",")
        while self.name in managed_packs:
            managed_packs.remove(self.name)

        # and store it.
        set_config("setup::unmanaged", ",".join(managed_packs))
        return True
Ejemplo n.º 10
0
def add_parser_args(parser, argparse):
    parser.add_argument('--show-unchanged', '-u', default=False, const=True, action="store_const", help="Also show status on unchanged repositories. ")

    remotes = parser.add_mutually_exclusive_group()
    remotes.add_argument('--remote', '-r', action="store_const", const=True, default=get_config("gl::status_remote_enabled"), dest="remote", help="Enable checking remote for status. Default can be changed by gl::status_remote_enabled. ")
    remotes.add_argument('--no-remote', '-n', action="store_const", const=False, dest="remote", help="Disable checking remote for status. See --remote")

    logtype = parser.add_argument_group("Status Output format ").add_mutually_exclusive_group()
    logtype.add_argument('--long', action="store_const", dest="outputtype", default="--long", const="--long", help="Give the output in the long-format. This is the default.")
    logtype.add_argument('--porcelain', action="store_const", dest="outputtype", const="--porcelain", help="Give the output in an easy-to-parse format for scripts. This is similar to the short output, but will remain stable across Git versions and regardless of user configuration. ")
    logtype.add_argument('--short', action="store_const", dest="outputtype", const="--short", help="Give the output in the short-format.")

    parser.add_argument('repository', nargs='*', help="a list of repositories for which to show the status. ")
    parser.add_argument('--all', "-a", default=False, const=True, action="store_const", help="runs status on all repositories currently in lmh")
    parser.epilog = repo_wildcard_local
Ejemplo n.º 11
0
Archivo: run.py Proyecto: KWARC/localmh
def do(args, unknown):

    url = get_config("mh::issue_url")
    repo = match_repo(args.repo)

    # if we can not match the repository, exit
    if not repo:
        err("Unable to match repository '"+repo+"'")
        return False

    # Try and open the url
    # and if that fails, just print it.      
    url = url.replace("$name", repo)
    if not webbrowser.open(url):
        std(url)

    return True
Ejemplo n.º 12
0
def do(args, unknown):

    url = get_config("mh::issue_url")
    repo = match_repo(args.repo)

    # if we can not match the repository, exit
    if not repo:
        err("Unable to match repository '" + repo + "'")
        return False

    # Try and open the url
    # and if that fails, just print it.
    url = url.replace("$name", repo)
    if not webbrowser.open(url):
        std(url)

    return True
Ejemplo n.º 13
0
def do(args, unknown):
    # If there are no repositories, check everything for dependencies.
    if len(args.spec) == 0:
        std("Nothing to install, re-installing all existing repositories.  ")
        return install(*match_repos(lmh_locate("content")))

    if not get_config("install::noglobs"):
        args.spec = ls_remote(*args.spec)
        if len(args.spec) == 0:
            err("Nothing to install...")
            return True
        if args.no_confirm_install:
            std("Picked", len(args.spec),"repositories. ")
        else:
            std("Picked", len(args.spec),"repositories: ")
            std(*args.spec)
            if read_raw("Continue (y/N)?").lower() != "y":
                err("Installation aborted. ")
                return False


    return install(*args.spec)
Ejemplo n.º 14
0
def term_colors(c):
    """
    Returns terminal encoding for a color given by a string
    """

    colors = {
        "grey": "\033[01;30m",
        "red": "\033[01;31m",
        "green": "\033[01;32m",
        "yellow": "\033[01;33m",
        "blue": "\033[01;34m",
        "magenta": "\033[01;35m",
        "cyan": "\033[01;36m",
        "white": "\033[01;37m",
        "normal": "\033[00m"
    }

    from lmh.lib.config import get_config

    if get_config("self::colors"):
        return colors[c]
    else:
        return ""
Ejemplo n.º 15
0
Archivo: io.py Proyecto: KWARC/localmh
def term_colors(c):
    """
    Returns terminal encoding for a color given by a string
    """

    colors = {
            "grey": "\033[01;30m",
            "red": "\033[01;31m",
            "green": "\033[01;32m",
            "yellow": "\033[01;33m",
            "blue": "\033[01;34m",
            "magenta": "\033[01;35m",
            "cyan": "\033[01;36m",
            "white": "\033[01;37m",
            "normal": "\033[00m"
    }

    from lmh.lib.config import get_config

    if get_config("self::colors"):
        return colors[c]
    else:
        return ""
Ejemplo n.º 16
0
from lmh.lib.packs import classes
from lmh.lib.config import get_config

latexmlkwarc_source = get_config("setup::latexmlkwarc::source")
latexmlkwarc_branch = get_config("setup::latexmlkwarc::branch")

setup = classes.GitPack("LaTeXMLKWARC",
                        latexmlkwarc_source,
                        latexmlkwarc_branch,
                        cpanm=True)
Ejemplo n.º 17
0
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    # Windows: Maybe its a .exe?
    if os.name == "nt" and not program.endswith(".exe"):
        return which(program + ".exe")
    return None


"""Path to the latexmlc executable"""
latexmlc_executable = get_config("env::latexmlc")
latexmlc_builtin = False

# Find it the old way if not available
if latexmlc_executable == "":
    if get_config("setup::cpanm::selfcontained"):
        latexmlc_builtin = True
        latexmlc_executable = lmh_locate("ext", "perl5lib", "bin", "latexmlc")
    else:
        latexmlc_executable = which("latexmlc")
"""Path to the git executable """
git_executable = get_config("env::git")

# Find it yourself if the config is empty
if git_executable == "":
    git_executable = which("git")
Ejemplo n.º 18
0
def do(args, unknown):

    if not webbrowser.open(get_config("gl::issue_url")):
        std(get_config("gl::issue_url"))

    return True
Ejemplo n.º 19
0
from lmh.lib.packs import classes
from lmh.lib.config import get_config

latexmlkwarc_source = get_config("setup::latexmlkwarc::source")
latexmlkwarc_branch = get_config("setup::latexmlkwarc::branch")

setup = classes.GitPack("LaTeXMLKWARC", latexmlkwarc_source, latexmlkwarc_branch, cpanm=True)
Ejemplo n.º 20
0
def create_remote(group, name):
    """Create a remote repository interactively. """

    if gitlab == False:
        err("Missing pyapi-gitlab, unable to create remote repository. ")
        return False

    remote_host = get_config("gl::host")
    std("Attempting to create repository", remote_host+group+"/"+name)

    # Get the private token
    token = get_config("gl::private_token")

    try:
        if token != "":
            gl = gitlab.Gitlab(remote_host, token=token)
            username = gl.currentuser()["username"]
        else:
            gl = gitlab.Gitlab(remote_host)
            raise Exception
    except:
        std("Unable to login with private token. ")
        std("To use it, please run")
        std("   lmh config gl::private_token <token>")
        std("Your private token can be found under Profile -> Account -> Private token")
        std("Switching to username / password authentication. ")

        username = read_raw("Username for "+remote_host+":")
        password = read_raw("Password for "+username+":", True)

        try:
            if not gl.login(username, password):
                raise Exception
        except:
            err("Gitlab Username/Password Authentication failed. ")
            return False

    std("Authentication successfull, creating project. ")

    # Find group Id
    try:
        gid = None
        if group == username:
            gid = ""
        for g in gl.getgroups():
            if g["path"] == group:
                gid = g["id"]
                break

        if gid == None:
            raise Exception

    except:
        err("Unable to determine group id, make sure")
        err("you have access to the group "+group)
        return False

    # Create the project on the given id
    try:
        p = gl.createproject(name, namespace_id=gid, description="lmh auto-created project "+group+"/"+name, public=True)
        if not p:
            raise Exception


        res = find_source(p["path_with_namespace"], quiet=True)
        if not res:
            return res
        else:
            # Fallback to ssh url
            return p["ssh_url_to_repo"]
    except Exception as e:
        err(e)
        err("Project creation failed. ")
        return False

    return False
Ejemplo n.º 21
0
from lmh.lib.packs import classes
from lmh.lib.config import get_config

stex_source = get_config("setup::stex::source")
stex_branch = get_config("setup::stex::branch")

setup = classes.GitPack("sTeX", stex_source, stex_branch, cpanm=False)
Ejemplo n.º 22
0
Archivo: MMT.py Proyecto: KWARC/localmh
mmt_jar_dir = lmh_locate("ext", "MMT", "deploy")
mmt_jar_path = lmh_locate(mmt_jar_dir, "mmt.jar")


class MMTPack(classes.Pack):
    """The special MMT Pack"""
    def __init__(self, mmt_jar_source):
        self.mmt_jar_source = mmt_jar_source
        self.name = "MMT"
    def do_install(self, pack_dir, sstring):
        """Updates the MMT package"""
        return self.do_update(pack_dir,sstring)
    def do_update(self, pack_dir, sstring):
        """Install the MMT package"""

        # Make the directory
        mkdir_p(mmt_jar_dir)
        
        # and wget it, overwriting the existing jar
        proc = subprocess.Popen([wget_executable, self.mmt_jar_source, "-O", mmt_jar_path], stderr=sys.stderr, stdout=sys.stdout)
        proc.wait()

        # chmod +x mmt_jar_path
        st = os.stat(mmt_jar_path)
        os.chmod(mmt_jar_path, st.st_mode | stat.S_IEXEC)

        return proc.returncode == 0

setup = MMTPack(get_config("setup::mmtjar::source"))
Ejemplo n.º 23
0
 def is_managed(self):
     managed_packs = get_config("setup::unmanaged").split(",")
     return not (self.name in managed_packs)
Ejemplo n.º 24
0
        elif index > 0:
            source = source_string[:index]
            branch = source_string[index+1:]
        else:
            source = source_string

        std("Using", name, "Version: "+source+"@"+branch)

    return (source, branch)

#
# CPANM
#

# Is cpanm selfcontained? Check the config setting
if get_config("setup::cpanm::selfcontained"):
    cpanm_installdeps_args = [cpanm_executable, "-v", "-L", perl5root[0], "--notest", "--installdeps", "--prompt", "."]
    cpanm_installself_args = [cpanm_executable, "-v", "-L", perl5root[0], "-v", "--notest", "--prompt", "."]
else:
    cpanm_installdeps_args = [cpanm_executable, "-v", "--notest", "--installdeps", "--prompt", "."]
    cpanm_installself_args = [cpanm_executable, "-v", "--notest", "--prompt", "."]


def cpanm_make(pack_dir):
    """Run CPANM make commands for a package. """

    _env = perl5env(os.environ)
    _env.pop("STEXSTYDIR", None)
    try:
        call(cpanm_installdeps_args, env=_env, cwd=pack_dir, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
        call(cpanm_installself_args, env=_env, cwd=pack_dir, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
Ejemplo n.º 25
0
from lmh.lib.packs import classes
from lmh.lib.config import get_config

latexml_source = get_config("setup::latexml::source")
latexml_branch = get_config("setup::latexml::branch")

setup = classes.GitPack("LaTeXML", latexml_source, latexml_branch, cpanm=True)
Ejemplo n.º 26
0
def create(reponame, type="none", remote = True):
    """Creates a new repository in the given directory"""

    # Resolve the repository to create
    repo = match_repo(reponame, existence=False)
    if repo == None:
        err("Can not resolve repository to create. ")
        return False

    # Remote creation currently disabled
    if remote:
        err("Remote cration currently disabled. ")
        remote = False

    # and the full path
    absrepo = match_repo(reponame, abs=True, existence=False)

    repo_group = repo.split("/")[0]
    repo_name = repo.split("/")[1]

    # Check if it is already installed.
    # TODO: Use the other is_installed
    if is_installed(repo):
        err("Repository", repo, "already installed. ")
        err("Do you maybe want to push this to the remote?")
        return False

    # Make the directory if it does not yet exist.
    try:
        mkdir_p(absrepo)
    except:
        err("Can not create repository directory")
        return False

    if not get_config("init::allow_nonempty"):
        if not (not os.listdir(absrepo)):
            err("Target Directory is non-empty. ")
            err("If you want to enable lmh init on non-empty directories, please run")
            err("    lmh config init::allow_nonempty true")
            return False

    # Template Variables.
    tpl_vars = {
            "repo": repo,
            "repo_group": repo_group,
            "repo_name": repo_name,
            "install_dir": lmh_locate()
    }

    # Copy the base template
    if not copy_template_dir(os.path.join(emptyrepo_dir, "none"), absrepo, tpl_vars):
        err("Unable to create repository base. ")
        return False

    # Copy the specific type.
    if type != "none":
        type_dir = os.path.join(emptyrepo_dir, type)
        if os.path.isdir(type_dir):
            if not copy_template_dir(type_dir, absrepo, tpl_vars):
                err("Unable to use repository template. ")
                return False
        else:
            err("Unknown repository type: ", type)
            return False

    if git_root(absrepo) != absrepo:
        # Now lets make an init
        if not git_do(absrepo, "init"):
            err("Error creating git repository. ")
            err("The directory has been created successfully, however git init failed. ")
            err("Please run it manually. ")
            return False

    # Create the initial commit.
    if not (git_do(absrepo, "add", "-A") and git_commit(absrepo, "-m", "Repository created by lmh")):
        err("Error creating inital commit. ")
        err("The directory has been created successfully, however git commit failed. ")
        err("Please run it manually. ")
        return False

    # Can we find a remote for this?
    source = find_source(repo, quiet=True)

    # Don't do anything remote => we are done.
    if not remote:
        if source:
            if not git_do(absrepo, "remote", "add", "origin", source):
                err("Can not add origin. ")
                err("git is suddenly weird. ")
                return False
        else:
            std("Skipping remote creation because --no-remote is given. ")
        std("Repository created successfully. ")
        return True

    # Source does not exist => we will have to create it.
    if not source:
        source = create_remote(repo_group, repo_name)
        if not source:
            err("local repository created but remote creation failed. ")
            return False

    # Add the origin.
    if not git_do(absrepo, "remote", "add", "origin", source):
        err("Can not add origin. ")
        err("git is suddenly weird. ")
        return False

    if not git_push(absrepo, "-u", "origin", "master"):
        err("Repository created but could not push created repository. ")
        err("Check your network connection and try again using git push. ")
        return False

    std("Created new repository successfully. ")

    return True
Ejemplo n.º 27
0
    """The special MMT Pack"""
    def __init__(self, mmt_jar_source):
        self.mmt_jar_source = mmt_jar_source
        self.name = "MMT"

    def do_install(self, pack_dir, sstring):
        """Updates the MMT package"""
        return self.do_update(pack_dir, sstring)

    def do_update(self, pack_dir, sstring):
        """Install the MMT package"""

        # Make the directory
        mkdir_p(mmt_jar_dir)

        # and wget it, overwriting the existing jar
        proc = subprocess.Popen(
            [wget_executable, self.mmt_jar_source, "-O", mmt_jar_path],
            stderr=sys.stderr,
            stdout=sys.stdout)
        proc.wait()

        # chmod +x mmt_jar_path
        st = os.stat(mmt_jar_path)
        os.chmod(mmt_jar_path, st.st_mode | stat.S_IEXEC)

        return proc.returncode == 0


setup = MMTPack(get_config("setup::mmtjar::source"))
Ejemplo n.º 28
0
from lmh.lib.packs import classes
from lmh.lib.config import get_config

latexmlstex_source = get_config("setup::latexmlstex::source")
latexmlstex_branch = get_config("setup::latexmlstex::branch")

setup = classes.GitPack("LaTeXMLsTeX", latexmlstex_source, latexmlstex_branch, cpanm=True)
Ejemplo n.º 29
0
Archivo: run.py Proyecto: KWARC/localmh
def do(args, unknown):

    if not webbrowser.open(get_config("gl::issue_url")):
        std(get_config("gl::issue_url"))

    return True