Example #1
0
def test_init_with_config_invalid(tmpdir):
    configfile = tmpdir.join("bad.cfg")
    configfile.write(BAD_CONFIG)

    with pytest.raises(InvalidSyntax) as exc_info:
        init_with_config(str(configfile))
    assert "statement outside of a section: 'Invalid'" in str(exc_info.value)
def vulernablepackges():
    count = 0
    handle = init_with_config('/etc/pacman.conf')
    db = handle.get_localdb()

    # XXX: error handling
    user_agent = {'User-Agent': USER_AGENT}
    r = requests.get('https://security.archlinux.org/issues.json', headers=user_agent)
    advisories = r.json()
    for adv in advisories:
        version = adv['fixed']
        packages = adv['packages']

        if not version:
            continue

        if not any(db.get_pkg(pkg) for pkg in packages):
            continue

        for pkg in packages:
            alpm_pkg = db.get_pkg(pkg)

            if not alpm_pkg:
                continue

            if vercmp(version, alpm_pkg.version) > 0:
                count += 1

        return count
Example #3
0
def cli(ctx, config_file, list_installed, show_detail, pkgnames):
    handle = config.init_with_config(config_file)

    if list_installed:
        return list_installed_packages(handle, pkgnames, show_detail)

    return list_remote_packages(handle, pkgnames, show_detail)
Example #4
0
def cli(ctx, config_file, quiet, pkgnames):
    handle = config.init_with_config(config_file)
    syncdbs = handle.get_syncdbs()

    eyapm.util.sync_dbs(handle, syncdbs)

    reinstall_pkgs(handle, quiet, pkgnames)
Example #5
0
def cli(ctx, config_file, search_files, pkgname_or_filename):
    handle = config.init_with_config(config_file)

    if not search_files:
        search_pkgname(handle, pkgname_or_filename[0])
        return

    search_filenames(handle, pkgname_or_filename)
Example #6
0
def get_handle(arch, force_fresh_handle=False):
    if not force_fresh_handle and arch in handles:
        handle, creation_time = handles[arch]
        if creation_time > time() - PACMAN_HANDLE_CACHE_TIME:
            return handle
    handle = init_with_config(get_configpath(arch))
    handles[arch] = (handle, time())
    return handle
Example #7
0
	def __init__(self):
		self.handle  = config.init_with_config("/etc/pacman.conf")

		for db in self.handle.get_syncdbs(): # do a -Sy on start
			t = transaction.init_from_options(self.handle, None)
			db.update(False) # dont force update
			t.release()

		self.update_members()
Example #8
0
def test_init_with_config(tmpdir):
    rootdir = "/"
    dbpath = str(tmpdir)

    configfile = tmpdir.join("good.cfg")
    configfile.write(CONFIG.format(rootdir=rootdir, dbpath=dbpath))
    handle = init_with_config(str(configfile))

    assert handle.dbpath == dbpath + '/'
    assert handle.root == rootdir
Example #9
0
	def __init__(self):
		''' Initialize pyalpm '''
		
		handle = init_with_config("/etc/pacman.conf")
		self.repos = handle.get_syncdbs()
		self.localdb = handle.get_localdb()

		# delete old SQL file if exist	
		if os.path.isfile("update.sql"):
			os.remove("update.sql")
Example #10
0
def cli(ctx, config_file, quiet):
    handle = config.init_with_config(config_file)
    syncdbs = handle.get_syncdbs()

    eyapm.util.sync_dbs(handle, syncdbs)
    print('')

    t = transaction.create_transaction(handle, {})
    with eyapm.util.work_with_transaction(t):
        t.sysupgrade(True)
        t.prepare()
        #print(dir(t))
        #print(len(t.to_remove))
        if len(t.to_add) == 0:
            print(' Nothing to do.')
            return

        total_install_size = 0
        total_download_size = 0
        total_size = 0
        for x in t.to_add:
            #print(dir(x))
            total_install_size += x.isize
            total_download_size += x.download_size
            total_size += x.size

        print('')
        package_name_list = [x.name for x in t.to_add]
        print('Packages (%d) %s\n' %
              (len(t.to_add), ' '.join(package_name_list)))
        size_str = '{:.2f}'.format(total_download_size / 1024 / 1024)
        s = 'Total Download Size:     {:>8} MiB'.format(size_str)
        print(s)
        size_str = '{:.2f}'.format(total_install_size / 1024 / 1024)
        s = 'Total Installed Size:    {:>8} MiB'.format(size_str)
        print(s)
        #print(total_size/1024/1024)
        print('')

        answer = 'y'
        if not quiet:
            answer = input(':: Proceed with installation? [Y/n] ')
            if not answer:
                answer = 'y'
            else:
                answer = answer.lower()

        if answer in ('y', 'yes'):
            t.commit()
            return
 def __init__(self):
     """set dbus and load alpm"""
     dbus.service.Object.__init__(
         self, dbus.service.BusName("net.kpacman2", dbus.SessionBus()),
         objpath)
     self.alpm = config.init_with_config("/etc/pacman.conf")
     self.local = self.alpm.get_localdb()
     self.pamac = Path('/usr/bin/pamac-manager').is_file()
     self.desc = True  # search in descriptions
     inirc = configparser.ConfigParser()
     inirc.read(f"{Path.home()}/.config/krunnerrc")
     try:
         self.desc = False if inirc['kpacman']['desc'].lower(
         ) == "false" else True
     except KeyError:
         pass
Example #12
0
    def __init__(self):
        #  /usr/share/gir-1.0/AppStreamGlib-1.0.gir
        try:
            if not USE_APPSTREAM:
                raise ValueError
            import gi
            gi.require_version('AppStreamGlib', '1.0')
            from gi.repository import AppStreamGlib
            app_store = AppStreamGlib.Store()
            app_store.load(flags=AppStreamGlib.StoreLoadFlags.APP_INFO_SYSTEM);
            app_store.set_search_match(AppStreamGlib.AppSearchMatch.PKGNAME | AppStreamGlib.AppSearchMatch.NAME |  AppStreamGlib.AppSearchMatch.KEYWORD);
        except ValueError:
            app_store = None

        def _app_store_ico(tofind):
            """ find app in store
            It's very slow ...
            """
            default = "package"
            for app in app_store.get_apps():
                if app.get_kind() != AppStreamGlib.AppKind.DESKTOP:
                    continue
                if app.get_pkgname_default() == tofind:
                    #print(f"-- AppStream trouvé -- {tofind}")
                    # FIX entries errors
                    iname = app.get_icon_default().get_name()
                    if not ".png" in iname:
                        iname = f"{app.get_pkgname_default()}_{iname}.png"
                    icon = f"{app.get_icon_path()}/64x64/{iname}"
                    if not Path(icon).exists():
                        print(f"  bad ico ? {icon} {app.get_icon_default().get_name()}")
                        icon = default
                    return icon
            return default

        #self.handle = Handle('/', '/var/lib/pacman')
        self.handle = config.init_with_config("/etc/pacman.conf")
        self.pkgs = []
        for i, pkg in enumerate(self.handle.get_localdb().pkgcache):
            pkg_repo = self._find(pkg.name)
            afile = AlpmFile(pkg, i, pkg_repo)
            if app_store:
                afile.ico = _app_store_ico(pkg.name)
            self.pkgs.append(afile)
        print(f"end scan {len(self.pkgs)} packages")
Example #13
0
def cli(ctx, config_file, pkgnames):

    handle = config.init_with_config(config_file)
    syncdbs = handle.get_syncdbs()
    db = handle.get_localdb()

    for name in pkgnames:
        pkg = eyapm.util.find_remote_package(syncdbs, name)
        if pkg is None:
            print('Error: target not found: %s' % name)
            continue

        local_pkg = db.get_pkg(name)
        if local_pkg:
            pkginfo.display_pkginfo(pkg, 2, 'local')
        else:
            pkginfo.display_pkginfo(pkg, 2, 'sync')

        print('')
Example #14
0
	def __init__(self):
		self.handle  = config.init_with_config("/etc/pacman.conf")
		self.handle.dlcb = self._cb_dl
		self.handle.eventcb = self._cb_event
		self.handle.questioncb = self._cb_conv
		self.handle.progresscb = self._cb_progress

		# for callbacks
		self._last_percent = 100
		self._last_i = -1

		self.update_members()

		self._to_install = set()
		self._to_upgrade = set()
		self._to_remove  = set()
		self._to_install_dep = set()
		self._to_upgrade_dep = set()
		self._to_remove_dep  = set()
Example #15
0
 def get_upgradable(self):
     """Search for upgradable packages."""
   
     h = config.init_with_config("/etc/pacman.conf")
     installed = set(h.get_localdb().pkgcache)
   
     for db in h.get_syncdbs():
         for pkg in list(installed):
             pkgname = pkg.name
             syncpkg = db.get_pkg(pkgname)
             if syncpkg:
                 installed.remove(pkg)
       
     foreign = dict([(p.name,p) for p in installed])
   
     ag1 = Aurget((p.name for p in installed))
   
     for aur_pkg in ag1.get_aur_pkgs():
         installed_pkg = foreign[aur_pkg['Name']]
         if pyalpm.vercmp(aur_pkg['Version'], installed_pkg.version) != 0:
             key = aur_pkg['Name']
             self.aurs.append(key)
             self.dict1[key]= installed_pkg.version
Example #16
0
 def __init__(self):
     self.rstats = {}
     self.handle = config.init_with_config("/etc/pacman.conf")
     for db in self.handle.get_syncdbs():
         self.rstats[db.name] = RepoStats(db)
Example #17
0
File: pacman.py Project: n1x4/conky
def main(tmp_db_path):
  # Use a temporary database path to avoid issues caused by synchronizing the
  # sync database without a full system upgrade.

  # See the discussion here:
  #   https://bbs.archlinux.org/viewtopic.php?pid=951285#p951285

  # Basically, if you sync the database and then install packages without first
  # upgrading the system (-y), you can do some damage.


  tmp_db_path = os.path.abspath(tmp_db_path)
#   conf = config.PacmanConfig(conf = '/etc/pacman.conf')
  h = config.init_with_config("/etc/pacman.conf")
  db_path = h.dbpath
  if tmp_db_path == db_path:
    print("temporary path cannot be %s" % db_path)
    sys.exit(1)
  local_db_path = os.path.join(db_path, 'local')
  tmp_local_db_path = os.path.join(tmp_db_path, 'local')

  # Set up the temporary database path
  if not os.path.exists(tmp_db_path):
    os.makedirs(tmp_db_path)
    os.symlink(local_db_path, tmp_local_db_path)
  elif not os.path.islink(tmp_local_db_path):
    # Move instead of unlinking just in case.
    if os.path.exists(tmp_local_db_path):
      os.rename(tmp_local_db_path, tmp_local_db_path + '.old')
    os.symlink(local_db_path, tmp_local_db_path)


  # Sync the temporary database.
  args = action_sync.parse_options(('-b', tmp_db_path, '-y'))
  h = config.init_with_config_and_options(args)
  sys.stdout = sys.__stderr__
  for db in h.get_syncdbs():
    t = transaction.init_from_options(h, args)
    try:
      db.update(False)
    except pyalpm.error as e:
      sys.stderr.write('%s: %s\n' % (db.name, e))
    t.release()
  sys.stdout = sys.__stdout__


  installed = set(p for p in h.get_localdb().pkgcache)
  upgradable = OrderedDict()

  syncdbs = h.get_syncdbs()
  for db in syncdbs:
    # Without "list" the set cannot be altered with "remove" below.
    for pkg in list(installed):
      pkgname = pkg.name
      syncpkg = db.get_pkg(pkgname)
      if syncpkg:
        if pyalpm.vercmp(syncpkg.version, pkg.version) > 0:
          try:
            upgradable[db.name].add((pkg, syncpkg))
          except KeyError:
            upgradable[db.name] = set(((pkg, syncpkg),))
        installed.remove(pkg)

  foreign = dict([(p.name,p) for p in installed])

  try:
    aur = AUR.AUR()
    aur_pkgs = aur.info(foreign.keys())
  except AUR.AURError as e:
    sys.stderr.write(str(e))
    sys.exit(1)

  upgradable_aur = list()
  for aur_pkg in aur_pkgs:
    installed_pkg = foreign[aur_pkg['Name']]
    if pyalpm.vercmp(aur_pkg['Version'], installed_pkg.version) > 0:
      upgradable_aur.append((installed_pkg, aur_pkg))
    installed.remove(installed_pkg)

  display(upgradable, upgradable_aur)
Example #18
0
def main(tmp_db_path, sync_cmd=None):
  # Use a temporary database path to avoid issues caused by synchronizing the
  # sync database without a full system upgrade.

  # See the discussion here:
  #   https://bbs.archlinux.org/viewtopic.php?pid=951285#p951285

  # Basically, if you sync the database and then install packages without first
  # upgrading the system (-y), you can do some damage.


  tmp_db_path = os.path.abspath(tmp_db_path)
#   conf = config.PacmanConfig(conf = '/etc/pacman.conf')
  h = config.init_with_config("/etc/pacman.conf")
  db_path = h.dbpath
  if tmp_db_path == db_path:
    print("temporary path cannot be %s" % db_path)
    sys.exit(1)
  local_db_path = os.path.join(db_path, 'local')
  tmp_local_db_path = os.path.join(tmp_db_path, 'local')

  # Set up the temporary database path
  if not os.path.exists(tmp_db_path):
    os.makedirs(tmp_db_path)
    os.symlink(local_db_path, tmp_local_db_path)
  elif not os.path.islink(tmp_local_db_path):
    # Move instead of unlinking just in case.
    if os.path.exists(tmp_local_db_path):
      sys.stderr.write(
        "warning: expected file or directory at %s\n" % tmp_local_db_path
      )
      i = 1
      backup_path = tmp_local_db_path + ('.%d' % i)
      while os.path.exists(backup_path):
        i += 1
        backup_path = tmp_local_db_path + ('.%d' % i)
      sys.stderr.write("attempting to move to %s\n" % backup_path)
      os.rename(tmp_local_db_path, backup_path)
    os.symlink(local_db_path, tmp_local_db_path)

  # Copy in the existing database files. If a repo is offline when paconky is
  # run then no database will be downloaded. If the databases are not copied
  # first then the output will be inconsistent due to missing information. For
  # example, if the Haskell repo is offline then Haskell packages will appear
  # in the [community] and [AUR] sections of the output.
  tmp_sync_db_path = os.path.join(tmp_db_path, 'sync')
  os.makedirs(tmp_sync_db_path, exist_ok=True)
  sync_db_path = os.path.join(db_path, 'sync')

  for db in glob.iglob(os.path.join(sync_db_path,'*.db')):
    tmp_db = os.path.join(tmp_sync_db_path, os.path.basename(db))
    try:
      mtime = os.path.getmtime(tmp_db)
    except OSError as e:
      if e.errno != errno.ENOENT:
        raise e
      else:
        mtime = 0
    if mtime < os.path.getmtime(db):
      shutil.copy2(db, tmp_db)



  # Sync the temporary database.
  # Support external synchronizers such as parisync.
  if sync_cmd:
    for index, item in enumerate(sync_cmd):
      if item == '%d':
        sync_cmd[index] = tmp_sync_db_path
      elif item == '%r':
        sync_cmd[index] = os.path.dirname(tmp_sync_db_path)
    p = subprocess.Popen(sync_cmd, stdout=subprocess.PIPE)
    e = p.wait()
    if e != 0:
      sys.stderr.write("sync command exited with %d\n" % e)
    # Re-initialize with new databases.
    args = action_sync.parse_options(('-b', tmp_db_path))
    h = config.init_with_config_and_options(args)
  else:
    args = action_sync.parse_options(('-b', tmp_db_path, '-y'))
    h = config.init_with_config_and_options(args)
    sys.stdout = sys.__stderr__
    try:
      t = transaction.init_from_options(h, args)
    except pyalpm.error as e:
      sys.stderr.write('%s\n' % (e,))
      eno = e.args[1]
      if eno == 10:
        lckpath = os.path.join(tmp_db_path, 'db.lck')
        sys.stderr.write('  %s\n' % lckpath)
      sys.exit(1)
    for db in h.get_syncdbs():
      try:
        db.update(False)
      except pyalpm.error as e:
        sys.stderr.write('%s: %s\n' % (db.name, e))
    t.release()
    sys.stdout = sys.__stdout__


  installed = set(p for p in h.get_localdb().pkgcache)
  upgradable = OrderedDict()

  syncdbs = h.get_syncdbs()
  for db in syncdbs:
    # Without "list" the set cannot be altered with "remove" below.
    for pkg in list(installed):
      pkgname = pkg.name
      syncpkg = db.get_pkg(pkgname)
      if syncpkg:
        if pyalpm.vercmp(syncpkg.version, pkg.version) > 0:
          try:
            upgradable[db.name].add((pkg, syncpkg))
          except KeyError:
            upgradable[db.name] = set(((pkg, syncpkg),))
        installed.remove(pkg)

  foreign = dict([(p.name,p) for p in installed])

  try:
    aur = AUR.AurRpc()
    aur_pkgs = aur.info(foreign.keys())
    upgradable_aur = list()
    for aur_pkg in aur_pkgs:
      try:
        installed_pkg = foreign[aur_pkg['Name']]
      except KeyError:
        upgradable_aur.append(aur_pkg)
        continue
      if pyalpm.vercmp(aur_pkg['Version'], installed_pkg.version) > 0:
        upgradable_aur.append(aur_pkg)
      installed.remove(installed_pkg)
  except AUR.AurError as e:
    sys.stderr.write(str(e))
    sys.exit(1)
  except urllib.error.URLError as e:
    sys.stderr.write(
      'error: failed to retrieve information from the AUR (%s)\n' % e.reason
    )
    upgradable_aur = None
  except TypeError:
    upgradable_aur = None


  display(upgradable, upgradable_aur)
Example #19
0
#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
#import AUR.RPC as AUR
from AUR.RPC import AUR
from time import localtime, strftime 
from pycman import config
import pyalpm

if __name__ == '__main__':
    h = config.init_with_config("/etc/pacman.conf")
    #print(h.get_localdb().pkgcache)
    installed = set(h.get_localdb().pkgcache)
    #print(h.get_localdb().get_pkg('mysql'))
    #print(h.get_localdb().grpcache)
    #print(installed)
    aur = AUR()
    #print(aur.info('mysql'))
    #[{'ID': 69409, 'NumVotes': 4, 'OutOfDate': 0, 'CategoryID': 2, 'FirstSubmitted': 1366917203, 'Version': '5.6.13-1', 'URL': 'https://www.mysql.com/products/community/', 'LastModified': 1375714132, 'Name': 'mysql', 'Maintainer': 'rustam', 'Description': 'A fast SQL database server', 'License': 'GPL', 'URLPath': '/packages/my/mysql/mysql.tar.gz'}]
    #print(aur.info(('mysql','heidisql')))
    #[{'NumVotes': 4, 'Version': '5.6.13-1', 'URL': 'https://www.mysql.com/products/community/', 'Name': 'mysql', 'License': 'GPL', 'FirstSubmitted': 1366917203, 'Maintainer': 'rustam', 'URLPath': '/packages/my/mysql/mysql.tar.gz', 'ID': 69409, 'OutOfDate': 0, 'LastModified': 1375714132, 'Description': 'A fast SQL database server', 'CategoryID': 2}, {'NumVotes': 9, 'ID': 65392, 'URL': 'http://www.heidisql.com/', 'Name': 'heidisql', 'License': 'GPL', 'FirstSubmitted': 1355313819, 'Maintainer': 'crush', 'URLPath': '/packages/he/heidisql/heidisql.tar.gz', 'Version': '7.0-2', 'OutOfDate': 1372029392, 'LastModified': 1355314287, 'Description': 'A lightweight, Windows based interface for managing MySQL and Microsoft SQL databases. (uses Wine).', 'CategoryID': 3}]
    #display_fields = ('LocalVersion','Version', 'LastModified')
    #aurpkg['LastModified'] = strftime('%Y-%m-%d %H:%M:%S', localtime(aurpkg['LastModified']))
    offical_repo = ['core', 'extra', 'community', 'multilib']
    for db in h.get_syncdbs():
        if db.name in offical_repo:
            for item in list(installed):
                if db.get_pkg(item.name):
                    installed.remove(item)
            #print(pkg)
Example #20
0
def main(tmp_db_path, sync_cmd=None):
  # Use a temporary database path to avoid issues caused by synchronizing the
  # sync database without a full system upgrade.

  # See the discussion here:
  #   https://bbs.archlinux.org/viewtopic.php?pid=951285#p951285

  # Basically, if you sync the database and then install packages without first
  # upgrading the system (-y), you can do some damage.


  tmp_db_path = os.path.abspath(tmp_db_path)
#   conf = config.PacmanConfig(conf = '/etc/pacman.conf')
  h = config.init_with_config("/etc/pacman.conf")
  db_path = h.dbpath
  if tmp_db_path == db_path:
    print("temporary path cannot be %s" % db_path)
    sys.exit(1)
  local_db_path = os.path.join(db_path, 'local')
  tmp_local_db_path = os.path.join(tmp_db_path, 'local')

  # Set up the temporary database path
  if not os.path.exists(tmp_db_path):
    os.makedirs(tmp_db_path)
    os.symlink(local_db_path, tmp_local_db_path)
  elif not os.path.islink(tmp_local_db_path):
    # Move instead of unlinking just in case.
    if os.path.exists(tmp_local_db_path):
      sys.stderr.write(
        "warning: expected file or directory at %s\n" % tmp_local_db_path
      )
      i = 1
      backup_path = tmp_local_db_path + ('.%d' % i)
      while os.path.exists(backup_path):
        i += 1
        backup_path = tmp_local_db_path + ('.%d' % i)
      sys.stderr.write("attempting to move to %s\n" % backup_path)
      os.rename(tmp_local_db_path, backup_path)
    os.symlink(local_db_path, tmp_local_db_path)

  # Copy in the existing database files. If a repo is offline when paconky is
  # run then no database will be downloaded. If the databases are not copied
  # first then the output will be inconsistent due to missing information. For
  # example, if the Haskell repo is offline then Haskell packages will appear
  # in the [community] and [AUR] sections of the output.
  tmp_sync_db_path = os.path.join(tmp_db_path, 'sync')
  os.makedirs(tmp_sync_db_path, exist_ok=True)
  sync_db_path = os.path.join(db_path, 'sync')

  for db in glob.iglob(os.path.join(sync_db_path,'*.db')):
    tmp_db = os.path.join(tmp_sync_db_path, os.path.basename(db))
    try:
      mtime = os.path.getmtime(tmp_db)
    except OSError as e:
      if e.errno != errno.ENOENT:
        raise e
      else:
        mtime = 0
    if mtime < os.path.getmtime(db):
      shutil.copy2(db, tmp_db)



  # Sync the temporary database.
  # Support external synchronizers such as parisync.
  if sync_cmd:
    for index, item in enumerate(sync_cmd):
      if item == '%d':
        sync_cmd[index] = tmp_sync_db_path
      elif item == '%r':
        sync_cmd[index] = os.path.dirname(tmp_sync_db_path)
    p = subprocess.Popen(sync_cmd, stdout=subprocess.PIPE)
    e = p.wait()
    if e != 0:
      sys.stderr.write("sync command exited with %d\n" % e)
    # Re-initialize with new databases.
    args = action_sync.parse_options(('-b', tmp_db_path))
    h = config.init_with_config_and_options(args)
  else:
    args = action_sync.parse_options(('-b', tmp_db_path, '-y'))
    h = config.init_with_config_and_options(args)
    sys.stdout = sys.__stderr__
    try:
      t = transaction.init_from_options(h, args)
    except pyalpm.error as e:
      sys.stderr.write('%s\n' % (e,))
      eno = e.args[1]
      if eno == 10:
        lckpath = os.path.join(tmp_db_path, 'db.lck')
        sys.stderr.write('  %s\n' % lckpath)
      sys.exit(1)
    for db in h.get_syncdbs():
      try:
        db.update(False)
      except pyalpm.error as e:
        sys.stderr.write('%s: %s\n' % (db.name, e))
    t.release()
    sys.stdout = sys.__stdout__


  installed = set(p for p in h.get_localdb().pkgcache)
  upgradable = OrderedDict()

  syncdbs = h.get_syncdbs()
  for db in syncdbs:
    # Without "list" the set cannot be altered with "remove" below.
    for pkg in list(installed):
      pkgname = pkg.name
      syncpkg = db.get_pkg(pkgname)
      if syncpkg:
        if pyalpm.vercmp(syncpkg.version, pkg.version) > 0:
          try:
            upgradable[db.name].add((pkg, syncpkg))
          except KeyError:
            upgradable[db.name] = set(((pkg, syncpkg),))
        installed.remove(pkg)

  foreign = dict([(p.name,p) for p in installed])

  try:
    aur = AUR.AUR()
    aur_pkgs = aur.info(foreign.keys())
    upgradable_aur = list()
    for aur_pkg in aur_pkgs:
      try:
        installed_pkg = foreign[aur_pkg['Name']]
      except KeyError:
        upgradable_aur.append(aur_pkg)
        continue
      if pyalpm.vercmp(aur_pkg['Version'], installed_pkg.version) > 0:
        upgradable_aur.append(aur_pkg)
      installed.remove(installed_pkg)
  except AUR.AURError as e:
    sys.stderr.write(str(e))
    sys.exit(1)
  except urllib.error.URLError as e:
    sys.stderr.write(
      'error: failed to retrieve information from the AUR (%s)\n' % e.reason
    )
    upgradable_aur = None
  except TypeError:
    upgradable_aur = None


  display(upgradable, upgradable_aur)
Example #21
0
def display(upgradable_sync, upgradable_aur):
  """Display the output.

  upgradable_sync: An OrderedDict of sync database names and sets of tuples.
  Each tuple consists of the local package and sync package returned by pyalpm.

  upgradable_aur: A list of tuples. Each tuple consists of the local package
  returned by pyalpm and a dictionary object returned from the AUR.
  """

  # To change the output, edit these formatting strings.
  # You can change anything except the number of "%s" in each.
  # If you need to insert a percent sign, use "%%".
  # The header at the top of each repo list.
  header = '${color1}${hr}\n${color1}[${color2}%s${color1}] ${alignr}${color3}%s'
  error = 'update check failed'
  zero = 'updated'
  one = '1 new package'
  many = '%d new packages'
  # Text shown instead of repo when everything is up-to-date.
  zero_text = 'local packages'

  # The line showing a package and the available version.
  line = '\n${color1}%s ${alignr}%s'

  # The footer at the end of the list.
  footer = '\n${color1}${hr}\n \n '

  h = config.init_with_config("/etc/pacman.conf")

  # An error occured.
  if upgradable_sync is None or upgradable_aur is None:
    print(header % (zero_text, error) + footer);

  # Nothing to upgrade.
  elif not (upgradable_sync or upgradable_aur):
    print(header % (zero_text, zero) + footer);

  else:
    for repo, pkgs in upgradable_sync.items():
      n = len(pkgs)
      if n > 1:
        msg = many % n
      else:
        msg = one

      print(header % (repo,msg), end='');

      pkgs = sorted(pkgs, key=lambda x: x[0].name)
      for local, sync in pkgs:

        name, version = "", ""

        try:
          locked_group = set(local.groups) & set(h.ignoregrps)
          if local.name in h.ignorepkgs or len(locked_group):
            name, version = local.name, str(sync.version)+"${color2}/locked${color}"
          else:
            name, version = local.name, sync.version
        except:
          name, version = "alpm issue", "detected"

        if len(name) > 20:
          name = name[0:18] + "..."

        print(line % (name, version), end='')

      print(footer)


    if upgradable_aur:
      n = len(upgradable_aur)
      if n > 1:
        msg = many % n
      else:
        msg = one

      print(header % ('AUR',msg), end='');

      upgradable_aur.sort(key=lambda x: x['Name'])
      for pkg in upgradable_aur:
        print(line % (pkg['Name'], pkg['Version']), end='')

      print(footer)
Example #22
0
def cli(ctx, config_file, quiet, pkgnames):
    handle = config.init_with_config(config_file)

    remove_pkgs(handle, quiet, pkgnames)
import textwrap

try:
    import pyalpm
except:
    print('Please install the pyalpm package')
    sys.exit(1)

from pycman import config
from pycman import pkginfo

list_source = 'README.md'
script_version = 'Thu, 24 Apr 2014 13:07:55 -0400'
topdir = os.path.dirname(os.path.realpath(__file__))

handle = config.init_with_config('/etc/pacman.conf')
db = handle.get_localdb()
packages = list()

show_valid = ['pkgver', 'instver']
show = []
show_list = False
show_pkgbase = False
show_pkgdir = False


class subpackage:
    def __init__(self, pkgname, pkgver):
        self.pkgname = pkgname
        self.pkgver = pkgver
        self.instver = None
Example #24
0
        help = SUPPRESS
    )

    parser.add_argument(
        "-c", "--conf",
        default = Path("/etc/pacman.conf"),
        type    = Path,
        help    = "Path of pacman configuration file"
    )

    parser.add_argument(
        "-s", "--script",
        action = "store_true",
        help   = "Enable script mode"
    )

    args = parser.parse_args()

    if pyalpm_error:
        msg("pyalpm is not installed.", "error")
        sys.exit(4)

    handle = init_with_config(str(args.conf))

    exit_code, info = compare(args.package)

    if args.script and info:
        print(" ".join(info))

    sys.exit(exit_code)
import textwrap

try:
    import pyalpm
except:
    sys.stderr.write('Please install the pyalpm package!')
    sys.exit(1)

from pycman import config
from pycman import pkginfo

list_source = 'README.md'
script_version = 'Thu, 24 Apr 2014 13:07:55 -0400'
topdir = os.path.dirname(os.path.realpath(__file__))

handle = config.init_with_config('/etc/pacman.conf')
db = handle.get_localdb()
packages = list()

show_valid = ['pkgver', 'instver']
show = []
show_list = False
show_pkgbase = False
show_pkgdir = False


class subpackage:
    def __init__(self, pkgname, pkgver):
        self.pkgname = pkgname
        self.pkgver = pkgver
        self.instver = None