コード例 #1
0
def getNameWithNamespace(p):
    """
    Return None or the root path of the repository
    """
    # Work out cwd
    if not haveGit:
        raise exceptions.DependencyError(
            "gitpython and a git installation required for getGitRoot()")

    p = pathlib.Path(p).absolute()
    if not p.is_dir():
        p = p.parent  # given a file instead of folder?
    # Open git process
    proc = subprocess.Popen(
        'git config --get remote.origin.url',
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=str(p),
        shell=True,
        universal_newlines=True)  # newlines forces stdout to unicode
    stdout, stderr = proc.communicate()
    # Find a gitlab url in the response
    url = re.match("https:\/\/gitlab\.pavlovia\.org\/\w*\/\w*\.git", stdout)
    if url:
        # Get contents of url from response
        url = url.string[url.pos:url.endpos]
        # Get namespace/name string from url
        path = url
        path = re.sub("\.git[.\n]*", "", path)
        path = re.sub("[.\n]*https:\/\/gitlab\.pavlovia\.org\/", "", path)
        return path
    else:
        return None
コード例 #2
0
def getGitRoot(p):
    """Return None or the root path of the repository"""
    if not haveGit:
        raise exceptions.DependencyError(
            "gitpython and a git installation required for getGitRoot()")

    p = pathlib.Path(p).absolute()
    if not p.is_dir():
        p = p.parent  # given a file instead of folder?

    proc = subprocess.Popen(
        'git branch --show-current',
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=str(p),
        shell=True,
        universal_newlines=True)  # newlines forces stdout to unicode
    stdout, stderr = proc.communicate()
    if 'not a git repository' in (stdout + stderr):
        return None
    else:
        # this should have been possible with git rev-parse --top-level
        # but that sometimes returns a virtual symlink that is not the normal folder name
        # e.g. some other mount point?
        selfAndParents = [p] + list(p.parents)
        for thisPath in selfAndParents:
            if list(thisPath.glob('.git')):
                return str(thisPath)  # convert Path back to str
コード例 #3
0
ファイル: pavlovia.py プロジェクト: yongzhang503/psychopy
def getProject(filename):
    """Will try to find (locally synced) pavlovia Project for the filename
    """
    if not haveGit:
        raise exceptions.DependencyError(
                "gitpython and a git installation required for getProject()")

    gitRoot = getGitRoot(filename)
    if gitRoot in knownProjects:
        return knownProjects[gitRoot]
    elif gitRoot:
        # Existing repo but not in our knownProjects. Investigate
        logging.info("Investigating repo at {}".format(gitRoot))
        localRepo = git.Repo(gitRoot)
        proj = None
        for remote in localRepo.remotes:
            for url in remote.urls:
                if "gitlab.pavlovia.org/" in url:
                    namespaceName = url.split('gitlab.pavlovia.org/')[1]
                    namespaceName = namespaceName.replace('.git', '')
                    pavSession = getCurrentSession()
                    if not pavSession.user:
                        nameSpace = namespaceName.split('/')[0]
                        if nameSpace in knownUsers:  # Log in if user is known
                            login(nameSpace, rememberMe=True)
                        else:  # Check whether project repo is found in any of the known users accounts
                            for user in knownUsers:
                                login(user)
                                foundProject = False
                                for repo in pavSession.findUserProjects():
                                    if namespaceName in repo['id']:
                                        foundProject = True
                                        logging.info("Logging in as {}".format(user))
                                        break
                                if not foundProject:
                                    logging.warning("Could not find {namespace} in your Pavlovia accounts. "
                                                    "Logging in as {user}.".format(namespace=namespaceName,
                                                                                   user=user))
                    if pavSession.user:
                        proj = pavSession.getProject(namespaceName,
                                                     repo=localRepo)
                        if proj.pavlovia == 0:
                            logging.warning(_translate("We found a repository pointing to {} "
                                                       "but no project was found there (deleted?)").format(url))
                    else:
                        logging.warning(_translate("We found a repository pointing to {} "
                                                   "but no user is logged in for us to check it".format(url)))
                    return proj

        if proj == None:
            logging.warning("We found a repository at {} but it "
                            "doesn't point to gitlab.pavlovia.org. "
                            "You could create that as a remote to "
                            "sync from PsychoPy.".format(gitRoot))
コード例 #4
0
def getGitRoot(p):
    """Return None or the root path of the repository"""
    if not haveGit:
        raise exceptions.DependencyError(
            "gitpython and a git installation required for getGitRoot()")

    if not os.path.isdir(p):
        p = [os.path.split(p)[0] if len(os.path.split(p)[0]) > 0 else None
             ].pop()
    if subprocess.call(["git", "branch"],
                       stderr=subprocess.STDOUT,
                       stdout=open(os.devnull, 'w'),
                       cwd=p) != 0:
        return None
    else:
        out = subprocess.check_output(["git", "rev-parse", "--show-toplevel"],
                                      cwd=p)
        return out.strip().decode('utf-8')
コード例 #5
0
ファイル: pavlovia.py プロジェクト: TCRichards/Insights
def getProject(filename):
    """Will try to find (locally synced) pavlovia Project for the filename
    """
    if not haveGit:
        raise exceptions.DependencyError(
            "gitpython and a git installation required for getProject()")

    gitRoot = getGitRoot(filename)
    if gitRoot in knownProjects:
        return knownProjects[gitRoot]
    elif gitRoot:
        # Existing repo but not in our knownProjects. Investigate
        logging.info("Investigating repo at {}".format(gitRoot))
        localRepo = git.Repo(gitRoot)
        proj = None
        for remote in localRepo.remotes:
            for url in remote.urls:
                if "gitlab.pavlovia.org/" in url:
                    namespaceName = url.split('gitlab.pavlovia.org/')[1]
                    namespaceName = namespaceName.replace('.git', '')
                    pavSession = getCurrentSession()
                    if pavSession.user:
                        proj = pavSession.getProject(namespaceName,
                                                     repo=localRepo)
                        if proj.pavlovia == 0:
                            logging.warning(
                                _translate(
                                    "We found a repository pointing to {} "
                                    "but ") +
                                _translate("no project was found there ("
                                           "deleted?)").format(url))

                    else:
                        logging.warning(
                            _translate("We found a repository pointing to {} "
                                       "but ") +
                            _translate("no user is logged in for us to check "
                                       "it").format(url))
                    return proj
        if proj == None:
            logging.warning("We found a repository at {} but it "
                            "doesn't point to gitlab.pavlovia.org. "
                            "You could create that as a remote to "
                            "sync from PsychoPy.".format(gitRoot))
コード例 #6
0
def getProject(filename):
    """Will try to find (locally synced) pavlovia Project for the filename
    """
    # Check that we have Git
    if not haveGit:
        raise exceptions.DependencyError(
            "gitpython and a git installation required for getProject()")
    # Get git root
    gitRoot = getGitRoot(filename)
    # Get name with namespace
    path = getNameWithNamespace(filename)
    # Get session
    session = getCurrentSession()
    # If already found, return
    if (knownProjects is not None) and (path in knownProjects) and (
            'idNumber' in knownProjects[path]):
        try:
            return PavloviaProject(knownProjects[path]['idNumber'])
        except LookupError as err:
            # If project not found, print warning and return None
            logging.warn(str(err))
            return None
    elif gitRoot:
        # Existing repo but not in our knownProjects. Investigate
        logging.info("Investigating repo at {}".format(gitRoot))
        localRepo = git.Repo(gitRoot)
        for remote in localRepo.remotes:
            for url in remote.urls:
                if "gitlab.pavlovia.org" in url:
                    # Get Namespace/Name from standard style url
                    nameSearch = re.search(
                        r"(?<=https:\/\/gitlab\.pavlovia\.org\/).*\/.*(?=\.git)",
                        url)
                elif "[email protected]:" in url:
                    # Get Namespace/Name from @ stye url
                    nameSearch = re.search(
                        r"(?<=git@gitlab\.pavlovia\.org:).*\/.*(?=\.git)", url)
                else:
                    # Attempt to get Namespace/Name from unhandled style
                    nameSearch = re.search(r"[\w\-]*\\[\w\-]*\.git", url)
                if nameSearch is not None:
                    name = nameSearch.group(0)
                    project = session.gitlab.projects.get(name)
                    return PavloviaProject(project.id)
コード例 #7
0
ファイル: pavlovia.py プロジェクト: zlager26/psychopy
def getGitRoot(p):
    """Return None or the root path of the repository"""
    if not haveGit:
        raise exceptions.DependencyError(
            "gitpython and a git installation required for getGitRoot()")

    p = pathlib.Path(p).absolute()
    if not p.is_dir():
        p = p.parent  # given a file instead of folder?

    if 'not a git repository' in subprocess.check_output(
        ["git", "branch", "--show-current"], cwd=str(p)).decode('utf-8'):
        return None
    else:
        # this should have been possible with git rev-parse --top-level
        # but that sometimes returns a virtual symlink that is not the normal folder name
        # e.g. some other mount point?
        selfAndParents = [p] + list(p.parents)
        for thisPath in selfAndParents:
            if list(thisPath.glob('.git')):
                return str(thisPath)  # convert Path back to str
コード例 #8
0
            raise ValueError(msg)
        # if we got this far we were successful in loading the lib
        audioLib = thisLibName
        init = backend.init
        if hasattr(backend, 'getDevices'):
            getDevices = backend.getDevices
        logging.info('sound is using audioLib: %s' % audioLib)
        break
    except exceptions.DependencyError:
        msg = '%s audio lib was requested but not loaded: %s'
        logging.warning(msg % (thisLibName, sys.exc_info()[1]))
        continue  # to try next audio lib

if audioLib is None:
    raise exceptions.DependencyError(
        "No sound libs could be loaded. Tried: {}\n"
        "Check whether the necessary sound libs are installed".format(
            prefs.hardware['audioLib']))


# function to set the device (if current lib allows it)
def setDevice(dev, kind=None):
    """Sets the device to be used for new streams being created.

    :param dev: the device to be used (name, index or sounddevice.device)
    :param kind: one of [None, 'output', 'input']
    """
    if not hasattr(backend, 'defaultOutput'):
        raise IOError("Attempting to SetDevice (audio) but not supported by "
                      "the current audio library ({!r})".format(audioLib))
    if hasattr(dev, 'name'):
        dev = dev['name']
コード例 #9
0
ファイル: backend_pyo.py プロジェクト: wincenciak/psychopy
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import division
from builtins import map
from psychopy import prefs, exceptions
from sys import platform
from psychopy import core, logging
from psychopy.constants import (STARTED, PLAYING, PAUSED, FINISHED, STOPPED,
                                NOT_STARTED, FOREVER)
from ._base import _SoundBase

try:
    import pyo
except ImportError as err:
    # convert this import error to our own, pyo probably not installed
    raise exceptions.DependencyError(repr(err))

import sys
import threading
pyoSndServer = None


def _bestDriver(devNames, devIDs):
    """Find ASIO or Windows sound drivers
    """
    preferredDrivers = prefs.general['audioDriver']
    outputID = None
    audioDriver = None
    osEncoding = sys.getfilesystemencoding()
    for prefDriver in preferredDrivers:
        logging.info('Looking for {}'.format(prefDriver))
コード例 #10
0
from __future__ import division

from psychopy import logging, exceptions
from psychopy.constants import (STARTED, PLAYING, PAUSED, FINISHED, STOPPED,
                                NOT_STARTED, FOREVER)
from psychopy.tools import attributetools
from ._base import _SoundBase

try:
    import pysoundcard as soundcard
    import soundfile as sndfile
except ImportError as err:
    # convert this import error to our own, pysoundcard probably not installed
    raise exceptions.DependencyError(repr(origMsg))

import numpy
from os import path
import weakref


def init():
    pass
    # for compatibility with other backends but not needed

class _PySoundCallbackClass(object):
    """To use callbacks without creating circular references we need a
    callback class.

    Both the Stream and the sound object (SoundPySoundCard) point to this.