Example #1
0
def apt_supports_trusted_option():
    """
    Since apt version 0.8.16~exp3 the option ``[trusted=yes]`` can be used in a
    ``sources.list`` file to disable GPG key checking (see `Debian bug
    #596498`_). This version of apt is included with Ubuntu 12.04 and later,
    but deb-pkg-tools also has to support older versions of apt. The
    :py:func:`apt_supports_trusted_option()` function checks if the installed
    version of apt supports the ``[trusted=yes]`` option, so that deb-pkg-tools
    can use it when possible.

    :returns: ``True`` if the option is supported, ``False`` if it is not.

    .. _Debian bug #596498: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=596498
    """
    global trusted_option_supported
    if trusted_option_supported is None:
        try:
            # Find the installed version of the `apt' package.
            version = execute('dpkg-query','--show', '--showformat=${Version}', 'apt', capture=True)
            # Check if the version is >= 0.8.16 (which includes [trusted=yes] support).
            execute('dpkg','--compare-versions', version, 'ge', '0.8.16~exp3')
            # If ExternalCommandFailed  is not raised,
            # `dpkg --compare-versions' reported succes.
            trusted_option_supported = True
        except ExternalCommandFailed:
            trusted_option_supported = False
    return trusted_option_supported
Example #2
0
def runInteractive():
    """
    Main function for interactive mode
    """
    print "------------- Welcome to the Miner %s ----------------" % miner_version.version
    print "You can run HELP command anytime to get more information."
    print "Press TAB key for context base completion"
    print "    - F1  key to get context base HELP"
    print "    - Ctrl-H to get list of keyboard bindings"
    print "    - Ctrl-D to exit"
    while True:
        s = ""
        try:
            s = raw_input(">>> ")
        except KeyboardInterrupt:
            print
            continue
        except EOFError:
            break
        if not s: continue
        executor.execute(s)
        if statements.Import.checkIfWasModified():
            global theSymbolCompleter
            theSymbolCompleter = CompleterWrap()

    print "\nGoodbye"
Example #3
0
def runInteractive():
    """
    Main function for interactive mode
    """
    print "------------- Welcome to the Miner %s ----------------" % miner_version.version
    print "You can run HELP command anytime to get more information."
    print "Press TAB key for context base completion"
    print "    - F1  key to get miner command help"
    print "    - F2  key to get python documentation"
    print "    - Ctrl-K to get list of keyboard bindings"
    print "    - Ctrl-D to exit"
    miner_globals.setIsInteractive(True)
    while True:
        s = ""
        try:
            s = raw_input(">>> ")
        except KeyboardInterrupt:
            print
            continue
        except EOFError:
            break
        if not s: continue
        executor.execute(s)

    print "\nGoodbye"
Example #4
0
    def wkhtml_to_pdf(cls, data, options=None):
        """
        Call wkhtmltopdf to convert the html to pdf
        """
        with tempfile.NamedTemporaryFile(
                suffix='.html', prefix='trytond_', delete=False
        ) as source_file:
            file_name = source_file.name
            source_file.write(data)
            source_file.close()

            # Evaluate argument to run with subprocess
            args = 'wkhtmltopdf'
            # Add Global Options
            if options:
                for option, value in options.items():
                    args += ' --%s' % option
                    if value:
                        args += ' "%s"' % value

            # Add source file name and output file name
            args += ' %s %s.pdf' % (file_name, file_name)
            # Execute the command using executor
            execute(args)
            return open(file_name + '.pdf').read()
Example #5
0
 def test_subprocess_output(self):
     self.assertEqual(execute('echo', 'this is a test', capture=True), 'this is a test')
     self.assertEqual(execute('echo', '-e', r'line 1\nline 2', capture=True), 'line 1\nline 2\n')
     # I don't know how to test for the effect of silent=True in a practical
     # way without creating the largest test in this test suite :-). The
     # least I can do is make sure the keyword argument is accepted and the
     # code runs without exceptions in supported environments.
     self.assertTrue(execute('echo', 'this is a test', silent=True))
Example #6
0
def copy_package_files(from_directory, to_directory, hard_links=True):
    """
    Copy package files to a temporary directory, using hard links when possible.

    :param from_directory: The pathname of a directory tree suitable for
                           packaging with ``dpkg-deb --build``.
    :param to_directory: The pathname of a temporary build directory.
    :param hard_links: Use hard links to speed up copying when possible.

    This function copies a directory tree suitable for packaging with
    ``dpkg-deb --build`` to a temporary build directory so that individual
    files can be replaced without changing the original directory tree. If the
    build directory is on the same file system as the source directory, hard
    links are used to speed up the copy. This function is used by
    :func:`build_package()`.
    """
    logger.info("Copying files (%s) to temporary directory (%s) ..",
                format_path(from_directory), format_path(to_directory))
    command = ['cp', '-a']
    makedirs(to_directory)
    if hard_links and ALLOW_HARD_LINKS:
        # Check whether we can use hard links to speed up the copy. In the past
        # this used the following simple and obvious check:
        #
        #   os.stat(source_directory).st_dev == os.stat(build_directory).st_dev
        #
        # However this expression holds true inside schroot, yet `cp -al' fails
        # when trying to create the hard links! This is why the following code now
        # tries to create an actual hard link to verify that `cp -al' can be used.
        test_file_from = None
        test_file_to = None
        try:
            # Find a unique filename that we can create and destroy without
            # touching any of the caller's files.
            while True:
                test_name = 'deb-pkg-tools-hard-link-test-%d' % random.randint(1, 1000)
                test_file_from = os.path.join(from_directory, test_name)
                test_file_to = os.path.join(to_directory, test_name)
                if not os.path.isfile(test_file_from):
                    break
            # Create the test file.
            with open(test_file_from, 'w') as handle:
                handle.write('test')
            os.link(test_file_from, test_file_to)
            logger.debug("Speeding up file copy using hard links ..")
            command.append('-l')
        except (IOError, OSError):
            pass
        finally:
            for test_file in [test_file_from, test_file_to]:
                if test_file and os.path.isfile(test_file):
                    os.unlink(test_file)
    # I know this looks really funky, but this is a valid use of shell escaping
    # and globbing (obviously I tested it ;-).
    command.append('%s/*' % pipes.quote(from_directory))
    command.append(pipes.quote(to_directory))
    execute(' '.join(command), logger=logger)
Example #7
0
def execute(stockId=None, date=None):

	now = datetime.datetime.now()
	if date is None or len(date)==0:
        	#convert western calendar to R.O.C calendar
		date = str(now.year-1911) + "{:02d}".format(now.month) + "{:02d}".format(now.day)
	elif len(date)==4:
		date = str(now.year-1911) + date[0:2] + date[2:4]

	executor.execute(stockId, date)
Example #8
0
    def rotate_backups(self, directory):
        """
        Rotate the backups in a directory according to a flexible rotation scheme.
        :param directory: The pathname of a directory that contains backups to
                          rotate (a string).

        .. note:: This function binds the main methods of the
                  :class:`RotateBackups` class together to implement backup
                  rotation with an easy to use Python API. If you're using
                  `rotate-backups` as a Python API and the default behavior is
                  not satisfactory, consider writing your own
                  :func:`rotate_backups()` function based on the underlying
                  :func:`collect_backups()`, :func:`group_backups()`,
                  :func:`apply_rotation_scheme()` and
                  :func:`find_preservation_criteria()` methods.
        """
        # Load configuration overrides by user?

        # Collect the backups in the given directory. if rotate type is on local or on google drive
        sorted_backups = self.collect_backups(directory, self.rotate_type)
        if not sorted_backups:
            logger.info("No backups found in %s.", self.custom_format_path(directory))
            return
        most_recent_backup = sorted_backups[-1]
        # Group the backups by the rotation frequencies.
        backups_by_frequency = self.group_backups(sorted_backups)
        # Apply the user defined rotation scheme.
        self.apply_rotation_scheme(backups_by_frequency, most_recent_backup.datetime)
        # Find which backups to preserve and why.
        backups_to_preserve = self.find_preservation_criteria(backups_by_frequency)
        # Apply the calculated rotation scheme.
        for backup in sorted_backups:
            if backup in backups_to_preserve:
                matching_periods = backups_to_preserve[backup]
                logger.info("Preserving %s (matches %s retention %s) ..",
                            self.custom_format_path(backup.pathname),
                            concatenate(map(repr, matching_periods)),
                            "period" if len(matching_periods) == 1 else "periods")
            else:
                logger.info("Deleting %s %s ..", backup.type, self.custom_format_path(backup.pathname))
                if not self.dry_run:
                    timer = Timer()
                    if self.rotate_type == 'local':  # if rotate type is on local or on google drive
                        command = ['rm', '-Rf', backup.pathname]
                        if self.io_scheduling_class:
                            command = ['ionice', '--class', self.io_scheduling_class] + command

                        execute(*command, logger=logger)
                    else:
                        self.gdrivecm.delete_file(backup.pathname.split('_')[0])
                    logger.debug("Deleted %s in %s.", self.custom_format_path(backup.pathname), timer)
        if len(backups_to_preserve) == len(sorted_backups):
            logger.info("Nothing to do! (all backups preserved)")
Example #9
0
    def generate_key_file(self, filename):
        """
        Generate a temporary host or client key for the OpenSSH server.

        The :func:`start()` method automatically calls :func:`generate_key_file()`
        to generate :data:`host_key_file` and :attr:`client_key_file`. This
        method uses the ``ssh-keygen`` program to generate the keys.
        """
        if not os.path.isfile(filename):
            timer = Timer()
            self.logger.debug("Generating SSH key file (%s) ..", filename)
            execute('ssh-keygen', '-f', filename, '-N', '', '-t', 'rsa', silent=True, logger=self.logger)
            self.logger.debug("Generated key file %s in %s.", filename, timer)
Example #10
0
 def test_status_code_checking(self):
     self.assertTrue(execute('true'))
     self.assertFalse(execute('false', check=False))
     self.assertRaises(ExternalCommandFailed, execute, 'false')
     try:
         execute('bash', '-c', 'exit 42')
         # Make sure the previous line raised an exception.
         self.assertTrue(False)
     except Exception as e:
         # Make sure the expected type of exception was raised.
         self.assertTrue(isinstance(e, ExternalCommandFailed))
         # Make sure the exception has the expected properties.
         self.assertEqual(e.command, "bash -c 'exit 42'")
         self.assertEqual(e.returncode, 42)
Example #11
0
def run(args):
    if (len(args) == 0) or (len(args) % 2 == 1):
        print(messages.HELP_STRING)
        return
    iterator = iter(args)
    jobs = izip(iterator, iterator)
    for job_path, params_json in jobs:
        try:
            job = simplejson.loads(file_get_contents(job_path))
            validictory.validate(job, job_schema)
            params = simplejson.loads(params_json)
            execute(job, params)
        except Exception, error:
            print(error)
Example #12
0
def application(request):
    """
    To use this application, the user must send a POST request with
    base64 or form encoded encoded HTML content and the wkhtmltopdf Options in
    request data, with keys 'base64_html' and 'options'.
    The application will return a response with the PDF file.
    """
    if request.method != 'POST':
        return

    request_is_json = request.content_type.endswith('json')

    with tempfile.NamedTemporaryFile(suffix='.html') as source_file:

        if request_is_json:
            # If a JSON payload is there, all data is in the payload
            payload = json.loads(request.data)
            source_file.write(payload['contents'].decode('base64'))
            options = payload.get('options', {})
        elif request.files:
            # First check if any files were uploaded
            source_file.write(request.files['file'].read())
            # Load any options that may have been provided in options
            options = json.loads(request.form.get('options', '{}'))

        source_file.flush()

        # Evaluate argument to run with subprocess
        args = ['wkhtmltopdf']

        # Add Global Options
        if options:
            for option, value in options.items():
                args.append('--%s' % option)
                if value:
                    args.append('"%s"' % value)

        # Add source file name and output file name
        file_name = source_file.name
        args += [file_name, file_name + ".pdf"]

        # Execute the command using executor
        execute(' '.join(args))

        return Response(
            wrap_file(request.environ, open(file_name + '.pdf')),
            mimetype='application/pdf',
        )
Example #13
0
 def mktx(self, recip, amount):
     if self.iscoinset():
         command = self.coinbinary + " payto -f " + self.fee + " " + recip + " " + str(amount)
         output = execute(command, capture="True")
         return output
     else:
         return False
Example #14
0
    def find_system_dependencies(self, shared_object_files):
        """
        (Ab)use dpkg-shlibdeps_ to find dependencies on system libraries.

        :param shared_object_files: The pathnames of the ``*.so`` file(s) contained
                                    in the package (a list of strings).
        :returns: A list of strings in the format of the entries on the
                  ``Depends:`` line of a binary package control file.

        .. _dpkg-shlibdeps: https://www.debian.org/doc/debian-policy/ch-sharedlibs.html#s-dpkg-shlibdeps
        """
        logger.debug("Abusing `dpkg-shlibdeps' to find dependencies on shared libraries ..")
        # Create a fake source package, because `dpkg-shlibdeps' expects this...
        with TemporaryDirectory(prefix='py2deb-dpkg-shlibdeps-') as fake_source_directory:
            # Create the debian/ directory expected in the source package directory.
            os.mkdir(os.path.join(fake_source_directory, 'debian'))
            # Create an empty debian/control file because `dpkg-shlibdeps' requires
            # this (even though it is apparently fine for the file to be empty ;-).
            open(os.path.join(fake_source_directory, 'debian', 'control'), 'w').close()
            # Run `dpkg-shlibdeps' inside the fake source package directory, but
            # let it analyze the *.so files from the actual build directory.
            command = ['dpkg-shlibdeps', '-O', '--warnings=0'] + shared_object_files
            output = execute(*command, directory=fake_source_directory, capture=True, logger=logger)
            expected_prefix = 'shlibs:Depends='
            if not output.startswith(expected_prefix):
                msg = ("The output of dpkg-shlibdeps doesn't match the"
                       " expected format! (expected prefix: %r, output: %r)")
                logger.warning(msg, expected_prefix, output)
                return []
            output = output[len(expected_prefix):]
            dependencies = sorted(dependency.strip() for dependency in output.split(','))
            logger.debug("Dependencies reported by dpkg-shlibdeps: %s", dependencies)
            return dependencies
Example #15
0
 def daemon(self, control):
     if self.iscoinset() and (control == "start" or control == "stop"):
         command = self.coinbinary + " daemon " + control
         output = execute(command, capture="True")
         return True
     else:
         return False
Example #16
0
 def listaddresses(self):
     if self.iscoinset():
         command = self.coinbinary + " listaddresses"
         output = execute(command, capture="True")
         return output
     else:
         return False
Example #17
0
 def getaddresshistory(self, address):
     if self.iscoinset():
         command = self.coinbinary + " getaddresshistory " + address
         output = execute(command, capture="True")
         return output
     else:
         return False
Example #18
0
def find_channels_of_guest(guest_name):
    """
    Find the pathnames of the channels associated to a guest.

    :param guest_name: The name of the guest (a string).
    :returns: A dictionary with channel names (strings) as keys and pathnames
              of UNIX socket files (strings) as values. If no channels are
              detected an empty dictionary will be returned.

    This function uses ``virsh dumpxml`` and parses the XML output to
    determine the pathnames of the channels associated to the guest.
    """
    logger.debug("Discovering '%s' channels using 'virsh dumpxml' command ..", guest_name)
    domain_xml = execute('virsh', 'dumpxml', guest_name, capture=True)
    parsed_xml = xml.etree.ElementTree.fromstring(domain_xml)
    channels = {}
    for channel in parsed_xml.findall('devices/channel'):
        if channel.attrib.get('type') == 'unix':
            source = channel.find('source')
            target = channel.find('target')
            if source is not None and target is not None and target.attrib.get('type') == 'virtio':
                name = target.attrib.get('name')
                path = source.attrib.get('path')
                if name in SUPPORTED_CHANNEL_NAMES:
                    channels[name] = path
    if channels:
        logger.debug("Discovered '%s' channels: %s", guest_name, channels)
    else:
        logger.debug("No channels found for guest '%s'.", guest_name)
    return channels
Example #19
0
 def broadcast(self, tx):
     if self.iscoinset():
         command = self.coinbinary + " broadcast " + tx
         output = execute(command, capture="True")
         return True
     else:
         return False
Example #20
0
def find_running_guests():
    """
    Find the names of the guests running on the current host.

    This function parses the output of the ``virsh list`` command instead of
    using the libvirt API because of two reasons:

    1. I'm under the impression that the libvirt API is still very much in flux
       and large changes are still being made, so it's not the most stable
       foundation for Negotiator to find running guests.

    2. The Python libvirt API needs to match the version of the libvirt API on
       the host system and there is AFAIK no obvious way to express this in the
       ``setup.py`` script of Negotiator.

    :returns: A generator of strings.
    :raises: :exc:`GuestDiscoveryError` when ``virsh list`` fails.
    """
    try:
        logger.debug("Discovering running guests using 'virsh list' command ..")
        output = execute('virsh', '--quiet', 'list', '--all', capture=True, logger=logger)
    except ExternalCommandFailed:
        raise GuestDiscoveryError("The 'virsh list' command failed! Are you sure libvirtd is running?")
    else:
        for line in output.splitlines():
            logger.debug("Parsing 'virsh list' output: %r", line)
            try:
                vm_id, vm_name, vm_status = line.split(None, 2)
                if vm_status == 'running':
                    yield vm_name
            except Exception:
                logger.warning("Failed to parse 'virsh list' output! (%r)", line)
Example #21
0
def inspect_package_contents(archive, cache=None):
    """
    Get the contents from a ``*.deb`` archive.

    :param archive: The pathname of an existing ``*.deb`` archive.
    :param cache: The :class:`.PackageCache` to use (defaults to :data:`None`).
    :returns: A dictionary with the directories and files contained in the
              package. The dictionary keys are the absolute pathnames and the
              dictionary values are :class:`ArchiveEntry` objects (see the
              example below).

    An example:

    >>> from deb_pkg_tools.package import inspect_package_contents
    >>> print(repr(inspect_package_contents('python3.4-minimal_3.4.0-1+precise1_amd64.deb')))
    {u'/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:54', target=u''),
     u'/usr/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:52', target=u''),
     u'/usr/bin/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:54', target=u''),
     u'/usr/bin/python3.4': ArchiveEntry(permissions=u'-rwxr-xr-x', owner=u'root', group=u'root', size=3536680, modified=u'2014-03-20 23:54', target=u''),
     u'/usr/bin/python3.4m': ArchiveEntry(permissions=u'hrwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:54', target=u'/usr/bin/python3.4'),
     u'/usr/share/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:53', target=u''),
     u'/usr/share/binfmts/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:53', target=u''),
     u'/usr/share/binfmts/python3.4': ArchiveEntry(permissions=u'-rw-r--r--', owner=u'root', group=u'root', size=72, modified=u'2014-03-20 23:53', target=u''),
     u'/usr/share/doc/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:53', target=u''),
     u'/usr/share/doc/python3.4-minimal/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:54', target=u''),
     u'/usr/share/doc/python3.4-minimal/README.Debian': ArchiveEntry(permissions=u'-rw-r--r--', owner=u'root', group=u'root', size=3779, modified=u'2014-03-20 23:52', target=u''),
     u'/usr/share/doc/python3.4-minimal/changelog.Debian.gz': ArchiveEntry(permissions=u'-rw-r--r--', owner=u'root', group=u'root', size=28528, modified=u'2014-03-20 22:32', target=u''),
     u'/usr/share/doc/python3.4-minimal/copyright': ArchiveEntry(permissions=u'-rw-r--r--', owner=u'root', group=u'root', size=51835, modified=u'2014-03-20 20:37', target=u''),
     u'/usr/share/man/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:52', target=u''),
     u'/usr/share/man/man1/': ArchiveEntry(permissions=u'drwxr-xr-x', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:54', target=u''),
     u'/usr/share/man/man1/python3.4.1.gz': ArchiveEntry(permissions=u'-rw-r--r--', owner=u'root', group=u'root', size=5340, modified=u'2014-03-20 23:30', target=u''),
     u'/usr/share/man/man1/python3.4m.1.gz': ArchiveEntry(permissions=u'lrwxrwxrwx', owner=u'root', group=u'root', size=0, modified=u'2014-03-20 23:54', target=u'python3.4.1.gz')}

    """
    if cache:
        entry = cache.get_entry('contents', archive)
        value = entry.get_value()
        if value is not None:
            return value
    contents = {}
    for line in execute('dpkg-deb', '-c', archive, logger=logger, capture=True).splitlines():
        # Example output of dpkg-deb -c archive.deb:
        # drwxr-xr-x root/root 0 2013-07-08 17:49 ./usr/share/doc/
        # lrwxrwxrwx root/root 0 2013-09-26 22:29 ./usr/bin/pdb2.7 -> ../lib/python2.7/pdb.py
        fields = line.split(None, 5)
        permissions = fields[0]
        owner, group = fields[1].split('/')
        size = int(fields[2])
        modified = fields[3] + ' ' + fields[4]
        pathname = re.sub('^./', '/', fields[5])
        pathname, _, target = pathname.partition(' -> ')
        if not target:
            pathname, _, target = pathname.partition(' link to ')
            target = re.sub('^./', '/', target)
        contents[pathname] = ArchiveEntry(permissions, owner, group, size, modified, target)
    if cache:
        entry.set_value(contents)
    return contents
Example #22
0
def dns(adapter, networks):
    """Set dns entries for an adapter"""

    if networks:
        networks = " ".join(networks)

    dns_output = execute('networksetup -setdnsservers {} {}'.format(adapter, networks), capture=True, sudo=True)
    if dns_output:
        click.echo('Added dns servers {} to {}'.format(networks, adapter))
Example #23
0
 def scrape_song(self, title, artist, maximum_age=60):
     scrape_f = lambda p: self.get_muscic_url(p, title, artist, self.cache_location, maximum_age, debrid = self.debrid)
     if len(self.__scrapers) > 0:
         pool_size = 10
         stop_flag = Event()
         populator = lambda: execute(scrape_f, self.__scrapers, stop_flag, pool_size, self.timeout)
         return populator
     else:
         return False
Example #24
0
def launch_program(command, is_running=None):
    """
    Start a program if it's not already running.

    This function makes it easy to turn any program into a single instance
    program. If the default "Is the program already running?" check fails to
    work you can redefine the way this check is done.

    :param command: The shell command used to launch the application (a string).
    :param is_running: The shell command used to check whether the application
                       is already running (a string, optional).
    :returns: One of the values from the :class:`LaunchStatus` enumeration.

    Examples of custom "is running" checks:

    .. code-block:: python

       # Chromium uses a wrapper script, so we need to match the absolute
       # pathname of the executable.
       launch_program('chromium-browser', is_running='pidof /usr/lib/chromium-browser/chromium-browser')

       # Dropbox does the same thing as Chromium, but the absolute pathname of
       # the executable contains a version number that I don't want to hard
       # code in my ~/.dwimrc profile :-)
       launch_program('dropbox start', is_running='pgrep -f "$HOME/.dropbox-dist/*/dropbox"')
    """
    try:
        pathname = resolve_program(extract_program(command))
        if not is_running:
            is_running = 'pidof %s' % quote(pathname)
        logger.verbose("Checking if program is running (%s) ..", pathname)
        if execute(is_running, silent=True, check=False):
            logger.info("Command already running: %s", command)
            return LaunchStatus.already_running
        else:
            logger.info("Starting command: %s", command)
            execute('sh', '-c', '(%s >/dev/null 2>&1) &' % command)
            return LaunchStatus.started
    except MissingProgramError:
        logger.warning("Program not installed! (%s)", command)
        return LaunchStatus.not_installed
    except Exception as e:
        logger.warning("Failed to start program! (%s)", e)
        return LaunchStatus.unspecified_error
Example #25
0
def compare_versions_with_dpkg(version1, operator, version2):
    """
    Compare Debian package versions using the external command ``dpkg --compare-versions ...``.

    :param version1: The version on the left side of the comparison (a string).
    :param operator: The operator to use in the comparison (a string).
    :param version2: The version on the right side of the comparison (a string).
    :returns: :data:`True` if the comparison succeeds, :data:`False` if it fails.
    """
    return execute('dpkg', '--compare-versions', version1, operator, version2, check=False, logger=logger)
Example #26
0
 def scrape_movie(self, maximum_age=60):
     scrape_f = lambda p: self.get_url(p, self.title, '', self.year, '', '', self.imdb, self.tvdb, "movie",
                                       self.cache_location, maximum_age, debrid = self.debrid)
     if len(self.__scrapers) > 0:
         pool_size = 10
         stop_flag = Event()
         populator = lambda: execute(scrape_f, self.__scrapers, stop_flag, pool_size, self.timeout)
         return populator
     else:
         return False
Example #27
0
def clone(years, public, languages, exclude, username):
    """Clones most repositories for a user in the current directory"""
    try:
        """
        Repos for <username> which you have member access
        """
        member_repos = Github(GITHUB.token).get_user().get_repos('member')
        for repo in member_repos:
            if username in repo.full_name and repo.language in languages and exclude not in repo.name:
                click.echo('git clone https://{}:{}@{}'.format(GITHUB.name, GITHUB.token, repo.clone_url[8:]))
                try:
                    c = execute(
                        'git clone https://{}:{}@{}'.format(GITHUB.name, GITHUB.token, repo.clone_url[8:]),
                        capture=True,
                        check=False
                    )
                    click.echo(c)
                except Exception as e:
                    click.echo(e)
        """
        Public repos for <username>
        """
        if public:
            public_repos = Github(GITHUB.token).get_user(username).get_repos()
            for repo in public_repos:
                years_old = datetime.datetime.now() - datetime.timedelta(days=years * 365)
                if repo.updated_at > years_old and repo.language in languages:
                    click.echo('git clone https://{}:{}@{}'.format(GITHUB.name, GITHUB.token, repo.clone_url[8:]))
                    try:
                        c = execute(
                            'git clone https://{}:{}@{}'.format(GITHUB.name, GITHUB.token, repo.clone_url[8:]),
                            capture=True,
                            check=False
                        )
                        click.echo(c)
                    except Exception as e:
                        click.echo(e)

    except TypeError:
        return
    except Exception as e:
        click.echo(e)
        raise e
Example #28
0
    def find_shared_object_files(self, directory):
        """
        Search directory tree of converted package for shared object files.

        Runs ``strip --strip-unneeded`` on all ``*.so`` files found.

        :param directory: The directory to search (a string).
        :returns: A list with pathnames of ``*.so`` files.
        """
        shared_object_files = []
        for root, dirs, files in os.walk(directory):
            for filename in files:
                if filename.endswith('.so'):
                    pathname = os.path.join(root, filename)
                    shared_object_files.append(pathname)
                    execute('strip', '--strip-unneeded', pathname, logger=logger)
        if shared_object_files:
            logger.debug("Found one or more shared object files: %s", shared_object_files)
        return shared_object_files
Example #29
0
 def scrape_episode(self, show_year, season, episode, maximum_age=60):
     scrape_f = lambda p: self.get_url(p, self.title, show_year, self.year, season, episode, self.imdb, self.tvdb,
                                       "episode",
                                       self.cache_location, maximum_age)
     if len(self.__scrapers) > 0:
         pool_size = 10
         stop_flag = Event()
         populator = lambda: execute(scrape_f, self.__scrapers, stop_flag, pool_size, self.timeout)
         return populator
     else:
         return False
Example #30
0
def with_repository(directory, *command, **kw):
    """
    Create/update a trivial package repository, activate the repository, run an
    external command (usually ``apt-get install``) and finally deactivate the
    repository again. Also deactivates the repository when the external command
    fails and :py:exc:`executor.ExternalCommandFailed` is raised.

    :param directory: The pathname of a directory containing ``*.deb`` archives
                      (a string).
    :param command: The command to execute (a tuple of strings, passed verbatim
                    to :py:func:`executor.execute()`).
    :param cache: The :py:class:`.PackageCache` to use (defaults to ``None``).
    """
    update_repository(directory=directory,
                      cache=kw.get('cache'))
    activate_repository(directory)
    try:
        execute(*command, logger=logger)
    finally:
        deactivate_repository(directory)