コード例 #1
0
ファイル: action_sync.py プロジェクト: remyoudompheng/pyalpm
def main(rawargs):
    global handle
    args = parse_options(rawargs)
    handle = config.init_with_config_and_options(args)

    if args.verbose:
        print("sync " + " ".join(rawargs), file=sys.stderr)

        # Refresh databases if necessary
    if args.refresh > 0:
        ret = do_refresh(args)
        if ret != 0:
            return ret

            # If a query action is set
    if args.search:
        return show_search(args.args, args)
    elif args.groups:
        return show_groups(args)
    elif args.info:
        return show_packages(args)
    elif args.list:
        return show_repo(args)
        # If a cleanup is required
    elif args.clean > 0:
        return do_clean(args)
        # If a sysupgrade is required
    elif args.sysupgrade > 0:
        return do_sysupgrade(args)
        # If only a refresh was requested
    elif len(args.args) == 0 and args.refresh > 0:
        return 0
        # Otherwise it's a normal install
    else:
        return do_install(args.args, args)
コード例 #2
0
def main(rawargs):
	global handle
	parser = config.make_parser()
	group = parser.add_argument_group("upgrade options")
	group.add_argument('-d', '--nodeps',
			action = 'store_true', default = False,
			help = 'skip dependency checks')
	group.add_argument('-f', '--force',
			action = 'store_true', default = False,
			help = 'force install, overwrite conflicting files')
	group.add_argument('-k', '--dbonly',
			action = 'store_true', default = False,
			help = 'only modify database entries, not package files')
	group.add_argument('--asdeps', dest = 'mode',
			action = "store_const",
			const = pyalpm.PKG_REASON_DEPEND)
	group.add_argument('--asexplicit', dest = 'mode',
			action = "store_const",
			const = pyalpm.PKG_REASON_EXPLICIT)
	group.add_argument('pkgs', metavar = 'pkg', nargs='*',
			help = "a list of package URLs, e.g. package-1.0-1-i686.tar.xz")

	args = parser.parse_args(rawargs)
	handle = config.init_with_config_and_options(args)

	if args.verbose:
		print("upgrade " + " ".join(rawargs), file = sys.stderr)

	return upgrade(args.pkgs, args)
コード例 #3
0
ファイル: action_upgrade.py プロジェクト: sri-ka1ki/pyalpm
def main(rawargs):
	global handle
	parser = config.make_parser()
	group = parser.add_argument_group("upgrade options")
	group.add_argument('-d', '--nodeps',
			action='store_true', default=False,
			help='skip dependency checks')
	group.add_argument('-f', '--force',
			action='store_true', default=False,
			help='force install, overwrite conflicting files')
	group.add_argument('-k', '--dbonly',
			action='store_true', default=False,
			help='only modify database entries, not package files')
	group.add_argument('--asdeps', dest='mode',
			action="store_const",
			const=pyalpm.PKG_REASON_DEPEND)
	group.add_argument('--asexplicit', dest='mode',
			action="store_const",
			const=pyalpm.PKG_REASON_EXPLICIT)
	group.add_argument('pkgs', metavar='pkg', nargs='*',
			help="a list of package URLs, e.g. package-1.0-1-x86_64.tar.xz")

	args = parser.parse_args(rawargs)
	handle = config.init_with_config_and_options(args)

	if args.verbose:
		print("upgrade " + " ".join(rawargs), file=sys.stderr)

	return upgrade(args.pkgs, args)
コード例 #4
0
ファイル: action_sync.py プロジェクト: sri-ka1ki/pyalpm
def main(rawargs):
    global handle
    args = parse_options(rawargs)
    handle = config.init_with_config_and_options(args)

    if args.verbose:
        print("sync " + " ".join(rawargs), file=sys.stderr)

    # Refresh databases if necessary
    if args.refresh > 0:
        ret = do_refresh(args)
        if ret != 0:
            return ret

    # If a query action is set
    if args.search:
        return show_search(args.args, args)
    elif args.groups:
        return show_groups(args)
    elif args.info:
        return show_packages(args)
    elif args.list:
        return show_repo(args)
    # If a cleanup is required
    elif args.clean > 0:
        return do_clean(args)
    # If a sysupgrade is required
    elif args.sysupgrade > 0:
        return do_sysupgrade(args)
    # If only a refresh was requested
    elif len(args.args) == 0 and args.refresh > 0:
        return 0
    # Otherwise it's a normal install
    else:
        return do_install(args.args, args)
コード例 #5
0
def main(rawargs):
    global handle
    parser = config.make_parser()
    group = parser.add_argument_group("Remove options")
    group.add_argument(
        '-c',
        '--cascade',
        action='store_true',
        default=False,
        help='remove packages and all packages that depend on them')
    group.add_argument('-d',
                       '--nodeps',
                       action='store_true',
                       default=False,
                       help='skip dependency checks')
    group.add_argument('-k',
                       '--dbonly',
                       action='store_true',
                       default=False,
                       help='only modify database entries, not package files')
    group.add_argument('-n',
                       '--nosave',
                       action='store_true',
                       default=False,
                       help='remove configuration files as well')
    group.add_argument(
        '-s',
        '--recursive',
        action='store_true',
        default=False,
        help="remove dependencies also (that won't break packages)")
    group.add_argument(
        '-u',
        '--unneeded',
        action='store_true',
        default=False,
        help="remove unneeded packages (that won't break packages)")
    group.add_argument('pkgs',
                       metavar='pkg',
                       nargs='*',
                       help="a list of packages, e.g. libreoffice, openjdk6")

    args = parser.parse_args(rawargs)
    handle = config.init_with_config_and_options(args)

    if args.verbose:
        print("remove " + " ".join(rawargs), file=sys.stderr)

    if len(args.pkgs) == 0:
        print('error: no targets specified')
        return 1

    return remove(args.pkgs, args)
コード例 #6
0
def main(rawargs):
	global handle
	parser = config.make_parser()
	parser.add_argument('deps', metavar = 'dep', nargs='*',
			help = "a dependency string, e.g. 'pacman>=3.4.0'")
	args = parser.parse_args(rawargs)
	handle = config.init_with_config_and_options(args)

	if args.verbose:
		print("deptest " + " ".join(rawargs), file = sys.stderr)
	missing = deptest(args.deps)

	if len(missing) == 0:
		return 0
	else:
		[print(dep) for dep in missing]
		return 127
コード例 #7
0
def main(rawargs):
    global handle
    parser = config.make_parser()
    parser.add_argument('deps',
                        metavar='dep',
                        nargs='*',
                        help="a dependency string, e.g. 'pacman>=3.4.0'")
    args = parser.parse_args(rawargs)
    handle = config.init_with_config_and_options(args)

    if args.verbose:
        print("deptest " + " ".join(rawargs), file=sys.stderr)
    missing = deptest(args.deps)

    if len(missing) == 0:
        return 0
    else:
        [print(dep) for dep in missing]
        return 127
コード例 #8
0
def main(rawargs):
	global handle
	parser = config.make_parser()
	mode = parser.add_mutually_exclusive_group(required = True)
	mode.add_argument('--asdeps', dest = 'mode',
			action = "store_const",
			const = pyalpm.PKG_REASON_DEPEND)
	mode.add_argument('--asexplicit', dest = 'mode',
			action = "store_const",
			const = pyalpm.PKG_REASON_EXPLICIT)
	parser.add_argument('pkgs', metavar = 'pkg', nargs='*',
			help = "a dependency string, e.g. 'pacman>=3.4.0'")
	args = parser.parse_args(rawargs)
	handle = config.init_with_config_and_options(args)

	if args.verbose:
		print("database " + " ".join(rawargs), file = sys.stderr)

	commit(args.pkgs, args.mode)
	return 0
コード例 #9
0
def checkupdates():
    count = 0
    options = PacmanConf()
    tempdir = mkdtemp(dir='/tmp')
    options.dbpath = tempdir
    symlink('/var/lib/pacman/local', f'{tempdir}/local')

    # Workaround for passing a different DBPath but with the system pacman.conf
    handle = init_with_config_and_options(options)
    for db in handle.get_syncdbs():
        db.update(False)

    db = handle.get_localdb()
    for pkg in db.pkgcache:
        if sync_newversion(pkg, handle.get_syncdbs()) is None:
            continue
        count += 1

    rmtree(tempdir)

    return count
コード例 #10
0
ファイル: action_remove.py プロジェクト: arthurdandrea/pyalpm
def main(rawargs):
	global handle
	parser = config.make_parser()
	group = parser.add_argument_group("Remove options")
	group.add_argument('-c', '--cascade',
			action = 'store_true', default = False,
			help = 'remove packages and all packages that depend on them')
	group.add_argument('-d', '--nodeps',
			action = 'store_true', default = False,
			help = 'skip dependency checks')
	group.add_argument('-k', '--dbonly',
			action = 'store_true', default = False,
			help = 'only modify database entries, not package files')
	group.add_argument('-n', '--nosave',
			action = 'store_true', default = False,
			help = 'remove configuration files as well')
	group.add_argument('-s', '--recursive',
			action = 'store_true', default = False,
			help = "remove dependencies also (that won't break packages)")
	group.add_argument('-u', '--unneeded',
			action = 'store_true', default = False,
			help = "remove unneeded packages (that won't break packages)")
	group.add_argument('pkgs', metavar = 'pkg', nargs='*',
			help = "a list of packages, e.g. libreoffice, openjdk6")

	args = parser.parse_args(rawargs)
	handle = config.init_with_config_and_options(args)

	if args.verbose:
		print("remove " + " ".join(rawargs), file = sys.stderr)

	if len(args.pkgs) == 0:
		print('error: no targets specified')
		return 1

	return remove(args.pkgs, args)
コード例 #11
0
def main(rawargs):
    global handle
    parser = config.make_parser(prog='pycman-query')
    group = parser.add_argument_group("Query options")
    group.add_argument('-d',
                       '--deps',
                       action='store_true',
                       default=False,
                       help='list packages installed as dependencies [filter]')
    group.add_argument('-e',
                       '--explicit',
                       action='store_true',
                       default=False,
                       help='list packages explicitly installed [filter]')
    group.add_argument('-i',
                       '--info',
                       action='count',
                       dest='info',
                       default=0,
                       help='view package information')
    group.add_argument('-l',
                       '--list',
                       action='store_true',
                       dest='listfiles',
                       default=False,
                       help='list the contents of the queried package')
    group.add_argument(
        '-m',
        '--foreign',
        action='store_true',
        default=False,
        help='list installed packages not found in sync db(s) [filter]')
    group.add_argument('-o',
                       '--owns',
                       action='store_true',
                       default=False,
                       help='query the package that owns <file>')
    group.add_argument('-p',
                       '--package',
                       action='store_true',
                       default=False,
                       help='query a package file instead of the database')
    group.add_argument('-q',
                       '--quiet',
                       action='store_true',
                       dest='quiet',
                       default=False,
                       help='show less information for query and search')
    group.add_argument(
        '-s',
        '--search',
        action='store_true',
        default=False,
        help='search locally-installed packages for matching strings')
    group.add_argument(
        '-t',
        '--unrequired',
        action='store_true',
        default=False,
        help="list packages not required by any package [filter]")
    group.add_argument('-u',
                       '--upgrades',
                       action='store_true',
                       default=False,
                       help="list outdated packages [filter]")
    group.add_argument(
        'pkgnames',
        metavar='pkg',
        nargs='*',
        help='packages to show (show all packages if no arguments) '
        '(when used with -o: a filename, '
        'when used with -p: the path to a package file)')

    args = parser.parse_args(rawargs)
    handle = config.init_with_config_and_options(args)

    if args.verbose:
        print("query " + " ".join(rawargs), file=sys.stderr)

    db = handle.get_localdb()
    retcode = 0

    # actions other than listing packages
    if args.owns:
        return find_file(args.pkgnames, args)
    if args.search:
        return find_search(args.pkgnames, args)

    pkglist = []
    if len(args.pkgnames) > 0:
        # a list of package names was specified
        for pkgname in args.pkgnames:
            if args.package:
                pkg = handle.load_pkg(pkgname)
            else:
                pkg = db.get_pkg(pkgname)
            if pkg is None:
                print('error: package "%s" not found' % pkgname)
                retcode = 1
            else:
                pkglist.append(pkg)
    else:
        # no package was specified, display all
        pkglist = db.pkgcache
    # determine the list of package to actually display
    pkglist = filter_pkglist(pkglist, args)
    for pkg in pkglist:
        display_pkg(pkg, args)

    return retcode
コード例 #12
0
def main(argv):
    global HTML_MIN
    retcode = 0
    parser = config.make_parser(
        prog=__program__,
        description=
        "Generate a static site for browsing an Arch repo, styled like the main website.",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}",
    )
    group = parser.add_argument_group("Generator options")
    group.add_argument(
        "-d",
        "--pkg-dir",
        metavar="<dir>",
        action="store",
        dest="pkg_dir",
        type=str,
        default=".",
        help="Path to the directory of packages",
    )
    group.add_argument(
        "-o",
        "--output",
        metavar="<dir>",
        action="store",
        dest="output",
        type=str,
        default="build",
        help="Directory to put resulting HTML files",
    )
    group.add_argument(
        "-n",
        "--name",
        metavar="<name>",
        action="store",
        dest="repo_name",
        type=str,
        default="unofficial",
        help="Repository name. Defaults to unofficial",
    )
    group.add_argument(
        "--url",
        metavar="<url>",
        action="store",
        dest="repo_url",
        type=str,
        help="The URL to use in the pacman configuration",
    )
    group.add_argument(
        "--key-id",
        metavar="<ID>",
        action="store",
        dest="key_id",
        type=str,
        help="GPG key ID that has been used to sign this repository",
    )
    group.add_argument(
        "--description",
        metavar="<text>",
        action="store",
        dest="description",
        type=str,
        help="The repository description",
    )
    group.add_argument(
        "--resources",
        metavar="<dir>",
        action="store",
        dest="res_dir",
        type=str,
        default=f"/usr/share/{__program__}",
        help="Where additional resources (templates, CSS) are in the system",
    )
    group.add_argument(
        "--html-min",
        action="store_true",
        help="Minify the generated HTML",
    )
    global args
    args = parser.parse_args(argv)

    # Set up logging
    if args.debug:
        log_level = logging.DEBUG
    elif args.verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING
    if DAIQUIRI_LOGS:
        daiquiri.setup(level=log_level)
    else:
        logging.basicConfig(level=log_level)

    if args.html_min and not HTML_MIN:
        logger.error(
            "Can not minify HTML without the htmlmin library installed!")
        return 1
    HTML_MIN = args.html_min

    handle = config.init_with_config_and_options(args)
    os.makedirs(args.output, mode=0o755, exist_ok=True)

    for db in handle.get_syncdbs():
        if db.name.lower() in official_repos:
            for package in db.pkgcache:
                cached_packages[package.name] = package

    packages = []
    pkg_dir_list = os.listdir(args.pkg_dir)
    pkg_dir_list.sort()
    for filename in pkg_dir_list:
        if ".pkg.tar." in filename and not filename.endswith(".sig"):
            file = os.path.join(args.pkg_dir, filename)
            logger.debug(f"Loading package {file=}")
            sibling_packages.append(handle.load_pkg(file))

    for package in sibling_packages:
        data = pkg_to_dict(package, package.filename)
        packages.append(data)
        output_file = os.path.join(args.output, package_html_path(package))
        package_template(
            data,
            outfile=output_file,
            repo=args.repo_name,
            template_file=os.path.join(args.res_dir, "package.html.j2"),
        )

    te = Template(open(os.path.join(args.res_dir, "index.html.j2")).read())
    index_page = os.path.join(args.output, "index.html")
    logger.info(f"Writing index template to {index_page}")
    with open(index_page, "w") as f:
        html_text = te.render(
            packages=packages,
            repo_name=args.repo_name,
            url=args.repo_url,
            repo_desc=args.description,
            key_id=args.key_id,
        )
        f.write(minify_html(html_text))

    shutil.copyfile(
        os.path.join(args.res_dir, "archrepo.css"),
        os.path.join(args.output, "archrepo.css"),
    )
    return retcode
コード例 #13
0
ファイル: action_query.py プロジェクト: arthurdandrea/pyalpm
def main(rawargs):
	global handle
	parser = config.make_parser(prog = 'pycman-query')
	group = parser.add_argument_group("Query options")
	group.add_argument('-d', '--deps',
			action = 'store_true', default = False,
			help = 'list packages installed as dependencies [filter]')
	group.add_argument('-e', '--explicit',
			action = 'store_true', default = False,
			help = 'list packages explicitly installed [filter]')
	group.add_argument('-i', '--info',
			action = 'count', dest = 'info', default = 0,
			help = 'view package information')
	group.add_argument('-l', '--list',
			action = 'store_true', dest = 'listfiles', default = False,
			help = 'list the contents of the queried package')
	group.add_argument('-m', '--foreign',
			action = 'store_true', default = False,
			help = 'list installed packages not found in sync db(s) [filter]')
	group.add_argument('-o', '--owns',
			action = 'store_true', default = False,
			help = 'query the package that owns <file>')
	group.add_argument('-p', '--package',
			action = 'store_true', default = False,
			help = 'query a package file instead of the database')
	group.add_argument('-q', '--quiet',
			action = 'store_true', dest = 'quiet', default = False,
			help = 'show less information for query and search')
	group.add_argument('-s', '--search', action = 'store_true', default = False,
			help = 'search locally-installed packages for matching strings')
	group.add_argument('-t', '--unrequired',
			action = 'store_true', default = False,
			help = "list packages not required by any package [filter]")
	group.add_argument('-u', '--upgrades',
			action = 'store_true', default = False,
			help = "list outdated packages [filter]")
	group.add_argument('pkgnames', metavar = 'pkg', nargs = '*',
			help = 'packages to show (show all packages if no arguments) '
			'(when used with -o: a filename, '
			'when used with -p: the path to a package file)')

	args = parser.parse_args(rawargs)
	handle = config.init_with_config_and_options(args)

	if args.verbose:
		print("query " + " ".join(rawargs), file = sys.stderr)

	db = handle.get_localdb()
	retcode = 0

	# actions other than listing packages
	if args.owns:
		return find_file(args.pkgnames, args)
	if args.search:
		return find_search(args.pkgnames, args)

	pkglist = []
	if len(args.pkgnames) > 0:
		# a list of package names was specified
		for pkgname in args.pkgnames:
			if args.package:
				pkg = handle.load_pkg(pkgname)
			else:
				pkg = db.get_pkg(pkgname)
			if pkg is None:
				print('error: package "%s" not found' % pkgname)
				retcode = 1
			else:
				pkglist.append(pkg)
	else:
		# no package was specified, display all
		pkglist = db.pkgcache
	# determine the list of package to actually display
	pkglist = filter_pkglist(pkglist, args)
	for pkg in pkglist:
		display_pkg(pkg, args)

	return retcode
コード例 #14
0
ファイル: paconky.py プロジェクト: MaxKh/dotfiles_obsolete
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)
コード例 #15
0
ファイル: pacman.py プロジェクト: 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)
コード例 #16
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)
コード例 #17
0
ファイル: test_pycman.py プロジェクト: lilydjwg/pyalpm
def test_init_with_options():
    options = MockConfig()
    handle = init_with_config_and_options(options)

    assert handle.dbpath == options.dbpath + '/'
    assert handle.root == options.root
コード例 #18
0
ファイル: pacbackup.py プロジェクト: xguse/pacbackup
 def __init__(self, options):
   self.handle = config.init_with_config_and_options(options)
   self.backup_file_path = sanitize_path(options.backup_config)
   self.container = os.path.abspath(os.path.join(self.backup_file_path, os.pardir))
   self.verbosity = options.verbose
コード例 #19
0
ファイル: pacbackup.py プロジェクト: ajaybhatia/pacbackup
 def __init__(self, options):
     self.handle = config.init_with_config_and_options(options)
     self.backup_file_path = sanitize_path(options.backup_config)
     self.container = os.path.abspath(
         os.path.join(self.backup_file_path, os.pardir))
     self.verbosity = options.verbose