Пример #1
0
def init_proxy(gsettings=None):
    """ init proxy settings

    * first check for http_proxy environment (always wins),
    * then check the apt.conf http proxy,
    * then look into synaptics conffile
    * then into gconf  (if gconfclient was supplied)
    """
    SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
    proxy = None
    # generic apt config wins
    if apt_pkg.config.find("Acquire::http::Proxy") != '':
        proxy = apt_pkg.config.find("Acquire::http::Proxy")
    # then synaptic
    elif os.path.exists(SYNAPTIC_CONF_FILE):
        cnf = apt_pkg.Configuration()
        apt_pkg.read_config_file(cnf, SYNAPTIC_CONF_FILE)
        use_proxy = cnf.find_b("Synaptic::useProxy", False)
        if use_proxy:
            proxy_host = cnf.find("Synaptic::httpProxy")
            proxy_port = str(cnf.find_i("Synaptic::httpProxyPort"))
            if proxy_host and proxy_port:
                proxy = "http://%s:%s/" % (proxy_host, proxy_port)
    # if we have a proxy, set it
    if proxy:
        # basic verification
        if not re.match("http://\w+", proxy):
            print("proxy '%s' looks invalid" % proxy, file=sys.stderr)
            return
        proxy_support = ProxyHandler({"http": proxy})
        opener = build_opener(proxy_support)
        install_opener(opener)
        os.putenv("http_proxy", proxy)
    return proxy
Пример #2
0
 def scan(self, update):
     '''
         This method sets the (global) apt-context to this suite and updates the repository
         metadata in the local cache from the remote apt-repository if update==True.
         Call this method before accessing packages data, e.g. like in queryPackages(...).
         If update==False, the already cached local metadata are used. This method
         returns False if apt-pkg recognized an error during scan (it seems apt-pkg doesn't
         recognize all error situations, i.e. if a repository server is not available).
     '''
     logger.debug("scanning repository/suite {} {} update".format(
         self.suite, 'with' if update else 'without'))
     apt_pkg.read_config_file(apt_pkg.config,
                              self.rootdir + "/etc/apt/apt.conf")
     apt_pkg.config.set("Dir", self.rootdir)
     apt_pkg.config.set("Dir::State::status",
                        self.rootdir + "/var/lib/dpkg/status")
     apt_pkg.init_system()
     self.cache = apt_pkg.Cache()
     ok = True
     if update:
         try:
             self.cache.update(self.__Progress(), self.__sources())
         except SystemError as e:
             logger.warning(
                 "Could not update the cache for suite {}:".format(
                     self.suite))
             for msg in re.sub(r"(\n,)? ([WE]:)", "\n\\2",
                               str(e)).split("\n"):
                 logger.warning(msg)
             ok = False
         self.cache = apt_pkg.Cache()
     self.records = apt_pkg.PackageRecords(self.cache)
     logger.debug("finished scan")
     return ok
    def test_escaped_colon(self):
        apt_pkg.config.clear("Unattended-Upgrade")
        apt_pkg.read_config_file(
            apt_pkg.config, "./data/50unattended-upgrades.colon")
        allowed_origins = unattended_upgrade.get_allowed_origins()

        self.assertIn('o=http://foo.bar,a=stable', allowed_origins)
Пример #4
0
def init_proxy(gsettings=None):
    """ init proxy settings

    * first check for http_proxy environment (always wins),
    * then check the apt.conf http proxy,
    * then look into synaptics conffile
    * then into gconf  (if gconfclient was supplied)
    """
    SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
    proxy = None
    # generic apt config wins
    if apt_pkg.config.find("Acquire::http::Proxy") != '':
        proxy = apt_pkg.config.find("Acquire::http::Proxy")
    # then synaptic
    elif os.path.exists(SYNAPTIC_CONF_FILE):
        cnf = apt_pkg.Configuration()
        apt_pkg.read_config_file(cnf, SYNAPTIC_CONF_FILE)
        use_proxy = cnf.find_b("Synaptic::useProxy", False)
        if use_proxy:
            proxy_host = cnf.find("Synaptic::httpProxy")
            proxy_port = str(cnf.find_i("Synaptic::httpProxyPort"))
            if proxy_host and proxy_port:
                proxy = "http://%s:%s/" % (proxy_host, proxy_port)
    # if we have a proxy, set it
    if proxy:
        # basic verification
        if not re.match("http://\w+", proxy):
            print("proxy '%s' looks invalid" % proxy, file=sys.stderr)
            return
        proxy_support = ProxyHandler({"http": proxy})
        opener = build_opener(proxy_support)
        install_opener(opener)
        os.putenv("http_proxy", proxy)
    return proxy
Пример #5
0
    def test_escaped_colon(self):
        apt_pkg.config.clear("Unattended-Upgrade")
        apt_pkg.read_config_file(apt_pkg.config,
                                 "./data/50unattended-upgrades.colon")
        allowed_origins = unattended_upgrade.get_allowed_origins()

        self.assertIn('o=http://foo.bar,a=stable', allowed_origins)
Пример #6
0
 def __init__(self, progress=None, rootdir=None, memonly=False):
     self._cache = None
     self._depcache = None
     self._records = None
     self._list = None
     self._callbacks = {}
     self._weakref = weakref.WeakValueDictionary()
     self._set = set()
     if memonly:
         # force apt to build its caches in memory
         apt_pkg.config.set("Dir::Cache::pkgcache", "")
     if rootdir:
         if os.path.exists(rootdir+"/etc/apt/apt.conf"):
             apt_pkg.read_config_file(apt_pkg.config,
                                    rootdir + "/etc/apt/apt.conf")
         if os.path.isdir(rootdir+"/etc/apt/apt.conf.d"):
             apt_pkg.read_config_dir(apt_pkg.config,
                                   rootdir + "/etc/apt/apt.conf.d")
         apt_pkg.config.set("Dir", rootdir)
         apt_pkg.config.set("Dir::State::status",
                            rootdir + "/var/lib/dpkg/status")
         # create required dirs/files when run with special rootdir
         # automatically
         self._check_and_create_required_dirs(rootdir)
         # Call InitSystem so the change to Dir::State::Status is actually
         # recognized (LP: #320665)
         apt_pkg.init_system()
     self.open(progress)
Пример #7
0
 def _configure_apt(self):
     """
     Initializes the :mod:`apt_pkg` module global settings.
     """
     apt_pkg.init_config()
     apt_pkg.init_system()
     apt_pkg.read_config_file(apt_pkg.config, self.conf_file_path)
     apt_pkg.config.set('Dir::Etc', self.cache_root_dir)
Пример #8
0
 def test_configuration(self):
     with open(self.file_unicode, 'w') as config:
         config.write("Hello { World 1; };")
     apt_pkg.read_config_file(apt_pkg.config, self.file_bytes)
     apt_pkg.read_config_file(apt_pkg.config, self.file_unicode)
     apt_pkg.read_config_file_isc(apt_pkg.config, self.file_bytes)
     apt_pkg.read_config_file_isc(apt_pkg.config, self.file_unicode)
     apt_pkg.read_config_dir(apt_pkg.config, self.dir_unicode)
     apt_pkg.read_config_dir(apt_pkg.config, b"/etc/apt/apt.conf.d")
Пример #9
0
 def test_configuration(self):
     with open(self.file_unicode, 'w') as config:
         config.write("Hello { World 1; };")
     apt_pkg.read_config_file(apt_pkg.config, self.file_bytes)
     apt_pkg.read_config_file(apt_pkg.config, self.file_unicode)
     apt_pkg.read_config_file_isc(apt_pkg.config, self.file_bytes)
     apt_pkg.read_config_file_isc(apt_pkg.config, self.file_unicode)
     apt_pkg.read_config_dir(apt_pkg.config, self.dir_unicode)
     apt_pkg.read_config_dir(apt_pkg.config, b"/etc/apt/apt.conf.d")
 def test_match_whitelist_from_conffile(self):
     # read some
     apt_pkg.config.clear("Unattended-Upgrade")
     apt_pkg.read_config_file(apt_pkg.config, "./data/50unattended-upgrades.Test")
     allowed_origins = unattended_upgrade.get_allowed_origins()
     #print allowed_origins
     self.assertTrue("o=aOrigin,a=aArchive" in allowed_origins)
     self.assertTrue("s=aSite,l=aLabel" in allowed_origins)
     self.assertTrue("o=Google\, Inc.,suite=stable" in allowed_origins)
Пример #11
0
 def test_match_whitelist_from_conffile(self):
     # read some
     apt_pkg.config.clear("Unattended-Upgrade")
     apt_pkg.read_config_file(apt_pkg.config,
                              "./data/50unattended-upgrades.Test")
     allowed_origins = unattended_upgrade.get_allowed_origins()
     #print allowed_origins
     self.assertTrue("o=aOrigin,a=aArchive" in allowed_origins)
     self.assertTrue("s=aSite,l=aLabel" in allowed_origins)
     self.assertTrue("o=Google\, Inc.,suite=stable" in allowed_origins)
 def test_compatiblity(self):
     apt_pkg.config.clear("Unattended-Upgrade")
     apt_pkg.read_config_file(apt_pkg.config, "./data/50unattended-upgrades.compat")
     allowed_origins = unattended_upgrade.get_allowed_origins()
     #print allowed_origins
     self.assertTrue("o=Google\, Inc.,a=stable" in allowed_origins)
     self.assertTrue("o=MoreCorp\, eink,a=stable" in allowed_origins)
     # test whitelist
     pkg = self._get_mock_package()
     self.assertTrue(is_allowed_origin(pkg.candidate, allowed_origins))
Пример #13
0
 def test_compatiblity(self):
     apt_pkg.config.clear("Unattended-Upgrade")
     apt_pkg.read_config_file(apt_pkg.config,
                              "./data/50unattended-upgrades.compat")
     allowed_origins = unattended_upgrade.get_allowed_origins()
     #print allowed_origins
     self.assertTrue("o=Google\, Inc.,a=stable" in allowed_origins)
     self.assertTrue("o=MoreCorp\, eink,a=stable" in allowed_origins)
     # test whitelist
     pkg = self._get_mock_package()
     self.assertTrue(is_allowed_origin(pkg.candidate, allowed_origins))
Пример #14
0
    def __init__(self, progress=None, rootdir=None, memonly=False):
        # type: (Optional[OpProgress], Optional[str], bool) -> None
        self._cache = cast(apt_pkg.Cache, None)  # type: apt_pkg.Cache
        self._depcache = cast(apt_pkg.DepCache, None)  # type: apt_pkg.DepCache
        self._records = cast(apt_pkg.PackageRecords,
                             None)  # type: apt_pkg.PackageRecords # noqa
        self._list = cast(apt_pkg.SourceList, None)  # type: apt_pkg.SourceList
        self._callbacks = {
        }  # type: Dict[str, List[Union[Callable[..., None],str]]] # noqa
        self._callbacks2 = {
        }  # type: Dict[str, List[Tuple[Callable[..., Any], Tuple[Any, ...], Dict[Any,Any]]]] # noqa
        self._weakref = weakref.WeakValueDictionary(
        )  # type: weakref.WeakValueDictionary[str, apt.Package] # noqa
        self._weakversions = weakref.WeakSet(
        )  # type: weakref.WeakSet[Version] # noqa
        self._changes_count = -1
        self._sorted_set = None  # type: Optional[List[str]]

        self.connect("cache_post_open", "_inc_changes_count")
        self.connect("cache_post_change", "_inc_changes_count")
        if memonly:
            # force apt to build its caches in memory
            apt_pkg.config.set("Dir::Cache::pkgcache", "")
        if rootdir:
            rootdir = os.path.abspath(rootdir)
            if os.path.exists(rootdir + "/etc/apt/apt.conf"):
                apt_pkg.read_config_file(apt_pkg.config,
                                         rootdir + "/etc/apt/apt.conf")
            if os.path.isdir(rootdir + "/etc/apt/apt.conf.d"):
                apt_pkg.read_config_dir(apt_pkg.config,
                                        rootdir + "/etc/apt/apt.conf.d")
            apt_pkg.config.set("Dir", rootdir)
            apt_pkg.config.set("Dir::State::status",
                               rootdir + "/var/lib/dpkg/status")
            # also set dpkg to the rootdir path so that its called for the
            # --print-foreign-architectures call
            apt_pkg.config.set("Dir::bin::dpkg",
                               os.path.join(rootdir, "usr", "bin", "dpkg"))
            # create required dirs/files when run with special rootdir
            # automatically
            self._check_and_create_required_dirs(rootdir)
            # Call InitSystem so the change to Dir::State::Status is actually
            # recognized (LP: #320665)
            apt_pkg.init_system()

        # Prepare a lock object (context manager for archive lock)
        archive_dir = apt_pkg.config.find_dir("Dir::Cache::Archives")
        self._archive_lock = _WrappedLock(archive_dir)

        self.open(progress)
Пример #15
0
def init_proxy(gsettings=None):
    """ init proxy settings 

  * first check for http_proxy environment (always wins),
  * then check the apt.conf http proxy, 
  * then look into synaptics conffile
  * then into gconf  (if gconfclient was supplied)
  """
    SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
    proxy = None
    # generic apt config wins
    if apt_pkg.config.find("Acquire::http::Proxy") != '':
        proxy = apt_pkg.config.find("Acquire::http::Proxy")
    # then synaptic
    elif os.path.exists(SYNAPTIC_CONF_FILE):
        cnf = apt_pkg.Configuration()
        apt_pkg.read_config_file(cnf, SYNAPTIC_CONF_FILE)
        use_proxy = cnf.find_b("Synaptic::useProxy", False)
        if use_proxy:
            proxy_host = cnf.find("Synaptic::httpProxy")
            proxy_port = str(cnf.find_i("Synaptic::httpProxyPort"))
            if proxy_host and proxy_port:
                proxy = "http://%s:%s/" % (proxy_host, proxy_port)
    # gconf is no more
    # elif gconfclient:
    #   try: # see LP: #281248
    #     if gconfclient.get_bool("/system/http_proxy/use_http_proxy"):
    #       host = gconfclient.get_string("/system/http_proxy/host")
    #       port = gconfclient.get_int("/system/http_proxy/port")
    #       use_auth = gconfclient.get_bool("/system/http_proxy/use_authentication")
    #       if host and port:
    #         if use_auth:
    #           auth_user = gconfclient.get_string("/system/http_proxy/authentication_user")
    #           auth_pw = gconfclient.get_string("/system/http_proxy/authentication_password")
    #           proxy = "http://%s:%s@%s:%s/" % (auth_user,auth_pw,host, port)
    #         else:
    #           proxy = "http://%s:%s/" % (host, port)
    #   except Exception, e:
    #     print "error from gconf: %s" % e
    # if we have a proxy, set it
    if proxy:
        # basic verification
        if not re.match("http://\w+", proxy):
            print >> sys.stderr, "proxy '%s' looks invalid" % proxy
            return
        proxy_support = urllib2.ProxyHandler({"http": proxy})
        opener = urllib2.build_opener(proxy_support)
        urllib2.install_opener(opener)
        os.putenv("http_proxy", proxy)
    return proxy
Пример #16
0
def init_proxy(gsettings=None):
  """ init proxy settings 

  * first check for http_proxy environment (always wins),
  * then check the apt.conf http proxy, 
  * then look into synaptics conffile
  * then into gconf  (if gconfclient was supplied)
  """
  SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
  proxy = None
  # generic apt config wins
  if apt_pkg.config.find("Acquire::http::Proxy") != '':
    proxy = apt_pkg.config.find("Acquire::http::Proxy")
  # then synaptic
  elif os.path.exists(SYNAPTIC_CONF_FILE):
    cnf = apt_pkg.Configuration()
    apt_pkg.read_config_file(cnf, SYNAPTIC_CONF_FILE)
    use_proxy = cnf.find_b("Synaptic::useProxy", False)
    if use_proxy:
      proxy_host = cnf.find("Synaptic::httpProxy")
      proxy_port = str(cnf.find_i("Synaptic::httpProxyPort"))
      if proxy_host and proxy_port:
        proxy = "http://%s:%s/" % (proxy_host, proxy_port)
  # gconf is no more
  # elif gconfclient:
  #   try: # see LP: #281248
  #     if gconfclient.get_bool("/system/http_proxy/use_http_proxy"):
  #       host = gconfclient.get_string("/system/http_proxy/host")
  #       port = gconfclient.get_int("/system/http_proxy/port")
  #       use_auth = gconfclient.get_bool("/system/http_proxy/use_authentication")
  #       if host and port:
  #         if use_auth:
  #           auth_user = gconfclient.get_string("/system/http_proxy/authentication_user")
  #           auth_pw = gconfclient.get_string("/system/http_proxy/authentication_password")
  #           proxy = "http://%s:%s@%s:%s/" % (auth_user,auth_pw,host, port)
  #         else:
  #           proxy = "http://%s:%s/" % (host, port)
  #   except Exception, e:
  #     print "error from gconf: %s" % e
  # if we have a proxy, set it
  if proxy:
    # basic verification
    if not re.match("http://\w+", proxy):
      print >> sys.stderr, "proxy '%s' looks invalid" % proxy
      return
    proxy_support = urllib2.ProxyHandler({"http":proxy})
    opener = urllib2.build_opener(proxy_support)
    urllib2.install_opener(opener)
    os.putenv("http_proxy",proxy)
  return proxy
Пример #17
0
    def __init__(self, progress=None, rootdir=None, memonly=False):
        # type: (OpProgress, str, bool) -> None
        self._cache = cast(apt_pkg.Cache, None)  # type: apt_pkg.Cache
        self._depcache = cast(apt_pkg.DepCache, None)  # type: apt_pkg.DepCache
        self._records = cast(apt_pkg.PackageRecords, None)  # type: apt_pkg.PackageRecords # nopep8
        self._list = cast(apt_pkg.SourceList, None)  # type: apt_pkg.SourceList
        self._callbacks = {}  # type: Dict[str, List[Union[Callable[..., None],str]]] # nopep8
        self._callbacks2 = {}  # type: Dict[str, List[Tuple[Callable[..., Any], Tuple[Any, ...], Dict[Any,Any]]]] # nopep8
        self._weakref = weakref.WeakValueDictionary()  # type: weakref.WeakValueDictionary[str, apt.Package] # nopep8
        self._weakversions = weakref.WeakSet()  # type: weakref.WeakSet[Version] # nopep8
        self._changes_count = -1
        self._sorted_set = None  # type: Optional[List[str]]

        self.connect("cache_post_open", "_inc_changes_count")
        self.connect("cache_post_change", "_inc_changes_count")
        if memonly:
            # force apt to build its caches in memory
            apt_pkg.config.set("Dir::Cache::pkgcache", "")
        if rootdir:
            rootdir = os.path.abspath(rootdir)
            if os.path.exists(rootdir + "/etc/apt/apt.conf"):
                apt_pkg.read_config_file(apt_pkg.config,
                                         rootdir + "/etc/apt/apt.conf")
            if os.path.isdir(rootdir + "/etc/apt/apt.conf.d"):
                apt_pkg.read_config_dir(apt_pkg.config,
                                        rootdir + "/etc/apt/apt.conf.d")
            apt_pkg.config.set("Dir", rootdir)
            apt_pkg.config.set("Dir::State::status",
                               rootdir + "/var/lib/dpkg/status")
            # also set dpkg to the rootdir path so that its called for the
            # --print-foreign-architectures call
            apt_pkg.config.set("Dir::bin::dpkg",
                               os.path.join(rootdir, "usr", "bin", "dpkg"))
            # create required dirs/files when run with special rootdir
            # automatically
            self._check_and_create_required_dirs(rootdir)
            # Call InitSystem so the change to Dir::State::Status is actually
            # recognized (LP: #320665)
            apt_pkg.init_system()

        # Prepare a lock object (context manager for archive lock)
        archive_dir = apt_pkg.config.find_dir("Dir::Cache::Archives")
        self._archive_lock = _WrappedLock(archive_dir)

        self.open(progress)
Пример #18
0
    def __init__(self, progress=None, rootdir=None, memonly=False):
        self._cache = None
        self._depcache = None
        self._records = None
        self._list = None
        self._callbacks = {}
        self._weakref = weakref.WeakValueDictionary()
        self._set = set()
        self._fullnameset = set()
        self._changes_count = -1
        self._sorted_set = None

        self.connect("cache_post_open", self._inc_changes_count)
        self.connect("cache_post_change", self._inc_changes_count)
        if memonly:
            # force apt to build its caches in memory
            apt_pkg.config.set("Dir::Cache::pkgcache", "")
        if rootdir:
            rootdir = os.path.abspath(rootdir)
            # clear old config first (Bug#728274)
            apt_pkg.config.clear("APT")
            apt_pkg.config.set("Dir", rootdir)
            apt_pkg.init_config()
            if os.path.exists(rootdir + "/etc/apt/apt.conf"):
                apt_pkg.read_config_file(apt_pkg.config,
                                         rootdir + "/etc/apt/apt.conf")
            if os.path.isdir(rootdir + "/etc/apt/apt.conf.d"):
                apt_pkg.read_config_dir(apt_pkg.config,
                                        rootdir + "/etc/apt/apt.conf.d")
            apt_pkg.config.set("Dir::State::status",
                               rootdir + "/var/lib/dpkg/status")
            # also set dpkg to the rootdir path so that its called for the
            # --print-foreign-architectures call
            apt_pkg.config.set("Dir::bin::dpkg",
                               os.path.join(rootdir, "usr", "bin", "dpkg"))
            # create required dirs/files when run with special rootdir
            # automatically
            self._check_and_create_required_dirs(rootdir)
            # Call InitSystem so the change to Dir::State::Status is actually
            # recognized (LP: #320665)
            apt_pkg.init_system()
        self.open(progress)
Пример #19
0
    def __init__(self, progress=None, rootdir=None, memonly=False):
        self._cache = None
        self._depcache = None
        self._records = None
        self._list = None
        self._callbacks = {}
        self._weakref = weakref.WeakValueDictionary()
        self._set = set()
        self._fullnameset = set()
        self._changes_count = -1
        self._sorted_set = None

        self.connect("cache_post_open", self._inc_changes_count)
        self.connect("cache_post_change", self._inc_changes_count)
        if memonly:
            # force apt to build its caches in memory
            apt_pkg.config.set("Dir::Cache::pkgcache", "")
        if rootdir:
            rootdir = os.path.abspath(rootdir)
            # clear old config first (Bug#728274)
            apt_pkg.config.clear("APT")
            apt_pkg.config.set("Dir", rootdir)
            apt_pkg.init_config()
            if os.path.exists(rootdir + "/etc/apt/apt.conf"):
                apt_pkg.read_config_file(apt_pkg.config,
                                         rootdir + "/etc/apt/apt.conf")
            if os.path.isdir(rootdir + "/etc/apt/apt.conf.d"):
                apt_pkg.read_config_dir(apt_pkg.config,
                                        rootdir + "/etc/apt/apt.conf.d")
            apt_pkg.config.set("Dir::State::status",
                               rootdir + "/var/lib/dpkg/status")
            # also set dpkg to the rootdir path so that its called for the
            # --print-foreign-architectures call
            apt_pkg.config.set("Dir::bin::dpkg",
                               os.path.join(rootdir, "usr", "bin", "dpkg"))
            # create required dirs/files when run with special rootdir
            # automatically
            self._check_and_create_required_dirs(rootdir)
            # Call InitSystem so the change to Dir::State::Status is actually
            # recognized (LP: #320665)
            apt_pkg.init_system()
        self.open(progress)
Пример #20
0
def init_proxy(gsettings=None):
    """ init proxy settings

    * use apt.conf http proxy if present,
    * otherwise look into synaptics config file,
    * otherwise the default behavior will use http_proxy environment
      if present
    """
    SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
    proxies = {}
    # generic apt config wins
    if apt_pkg.config.find("Acquire::http::Proxy") != '':
        proxies["http"] = apt_pkg.config.find("Acquire::http::Proxy")
    # then synaptic
    elif os.path.exists(SYNAPTIC_CONF_FILE):
        cnf = apt_pkg.Configuration()
        apt_pkg.read_config_file(cnf, SYNAPTIC_CONF_FILE)
        use_proxy = cnf.find_b("Synaptic::useProxy", False)
        if use_proxy:
            proxy_host = cnf.find("Synaptic::httpProxy")
            proxy_port = str(cnf.find_i("Synaptic::httpProxyPort"))
            if proxy_host and proxy_port:
                proxies["http"] = "http://%s:%s/" % (proxy_host, proxy_port)
    if apt_pkg.config.find("Acquire::https::Proxy") != '':
        proxies["https"] = apt_pkg.config.find("Acquire::https::Proxy")
    elif "http" in proxies:
        proxies["https"] = proxies["http"]
    # if we have a proxy, set it
    if proxies:
        # basic verification
        for proxy in proxies.values():
            if not re.match("https?://\\w+", proxy):
                print("proxy '%s' looks invalid" % proxy, file=sys.stderr)
                return
        proxy_support = ProxyHandler(proxies)
        opener = build_opener(proxy_support)
        install_opener(opener)
        if "http" in proxies:
            os.putenv("http_proxy", proxies["http"])
        if "https" in proxies:
            os.putenv("https_proxy", proxies["https"])
    return proxies
Пример #21
0
    def __init__(self, progress=None, rootdir=None, memonly=False):
        # type: (OpProgress, str, bool) -> None
        self._cache = None  # type: apt_pkg.Cache
        self._depcache = None  # type: apt_pkg.DepCache
        self._records = None  # type: apt_pkg.PackageRecords
        self._list = None  # type: apt_pkg.SourceList
        self._callbacks = {}  # type: Dict[str, List[Callable[..., None]]]
        self._callbacks2 = {
        }  # type: Dict[str, List[Tuple[Callable[..., None], List[Any], Dict[Any,Any]]]]
        self._weakref = weakref.WeakValueDictionary()  # type: ignore
        self._changes_count = -1
        self._sorted_set = None  # type: List[str]

        self.connect("cache_post_open", "_inc_changes_count")
        self.connect("cache_post_change", "_inc_changes_count")
        if memonly:
            # force apt to build its caches in memory
            apt_pkg.config.set("Dir::Cache::pkgcache", "")
        if rootdir:
            rootdir = os.path.abspath(rootdir)
            if os.path.exists(rootdir + "/etc/apt/apt.conf"):
                apt_pkg.read_config_file(apt_pkg.config,
                                         rootdir + "/etc/apt/apt.conf")
            if os.path.isdir(rootdir + "/etc/apt/apt.conf.d"):
                apt_pkg.read_config_dir(apt_pkg.config,
                                        rootdir + "/etc/apt/apt.conf.d")
            apt_pkg.config.set("Dir", rootdir)
            apt_pkg.config.set("Dir::State::status",
                               rootdir + "/var/lib/dpkg/status")
            # also set dpkg to the rootdir path so that its called for the
            # --print-foreign-architectures call
            apt_pkg.config.set("Dir::bin::dpkg",
                               os.path.join(rootdir, "usr", "bin", "dpkg"))
            # create required dirs/files when run with special rootdir
            # automatically
            self._check_and_create_required_dirs(rootdir)
            # Call InitSystem so the change to Dir::State::Status is actually
            # recognized (LP: #320665)
            apt_pkg.init_system()
        self.open(progress)
Пример #22
0
    def get_updatesApt(self, input_data):
        import apt_pkg
        action = input_data['action']
        upgrade_list = []
        skipped_list = []
        upgrade_count = 0
        skipped_count = 0

        apt_pkg.init()

        if os.path.exists("/etc/apt/apt.conf"):
            apt_pkg.read_config_file(apt_pkg.config,
                                     "/etc/apt/apt.conf")
        if os.path.isdir("/etc/apt/apt.conf.d"):
            apt_pkg.read_config_dir(apt_pkg.config,
                                    "/etc/apt/apt.conf.d")
        apt_pkg.init_system()

        cache = apt_pkg.GetCache(None)

        depcache = apt_pkg.GetDepCache(cache)
        depcache.ReadPinFile()
        depcache.Init(None)

        for i in cache.packages:
            if i.current_state is apt_pkg.CURSTATE_INSTALLED:
                if depcache.is_upgradable(i):
                    if depcache.marked_keep(i):
                        skipped_list.append(i.name)
                        skipped_count += 1
                    else:
                        upgrade_list.append(i.name)
                        upgrade_count += 1
        return(retval(0, "Package Update List", {
            "consequences": [
                'attrs.AvailablePackages := %s' % cache.PackageCount,
                'attrs.UpgradablePackageCount := %s' % upgrade_count,
                'attrs.SkippedPackageCount := %s' % skipped_count,
                'attrs.UpgradablePackages := %s' % json.dumps(upgrade_list),
                'attrs.SkippedPackageList := %s' % json.dumps(skipped_list)]}))
Пример #23
0
import apt_pkg
import sys
import posixpath

# Create a new empty Configuration object - there is also the system global
# configuration object apt_pkg.config which is used interally by apt-pkg
# routines to control unusual situations. I recommend using the sytem global
# whenever possible..
Cnf = apt_pkg.Configuration()

print "Command line is", sys.argv

# Load the default configuration file, init_config() does this better..
Cnf.set("config-file", "/etc/apt/apt.conf")  # or Cnf["config-file"] = ".."
if posixpath.exists(Cnf.find_file("config-file")):
    apt_pkg.read_config_file(Cnf, "/etc/apt/apt.conf")

# Merge the command line arguments into the configuration space
Arguments = [('h', "help", "help"),
             ('v', "version", "version"),
             ('q', "quiet", "quiet", "IntLevel"),
             ('c', "config-file", "", "ConfigFile"),
             ('o', "option", "", "ArbItem")]
print "FileNames", apt_pkg.parse_commandline(Cnf, Arguments, sys.argv)

print "Quiet level selected is", Cnf.find_i("quiet", 0)

# Do some stuff with it
if Cnf.find_b("version", 0) == 1:
    print "Version selected - 1.1"
Пример #24
0
Файл: apt.py Проект: djibi2/pdk
def init():
    "Initialize apt and prepare it for dependency solving."

    global cache

    if cache:
        raise RuntimeError, "apt is already initialized"

    global_conf = picax.config.get_config()
    base_dir = global_conf["temp_dir"] + "/apt-info"
    path = global_conf["base_path"]

    distro_hash = {}
    for (distro, comp) in global_conf["repository_list"]:
        if not distro_hash.has_key(distro):
            distro_hash[distro] = []
        distro_hash[distro].append(comp)
    distro_list = [(x, distro_hash[x]) for x in distro_hash.keys()]

    subdirs = ("state", "state/lists", "state/lists/partial", "cache", "cache/archives", "cache/archives/partial")

    if os.path.exists(base_dir):
        shutil.rmtree(base_dir)
    os.mkdir(base_dir)

    for subdir in subdirs:
        os.mkdir(base_dir + "/" + subdir)

    status = open("%s/state/status" % (base_dir,), "w")
    status.close()

    conf = open("%s/apt.conf" % (base_dir,), "w")
    conf.write(
        """
APT
{
  Architecture "%s";
};
Dir "%s/"
{
  State "state/" {
    status "status";
  };
  Cache "cache/";
  Etc "%s/";
};
"""
        % (global_conf["arch"], base_dir, base_dir)
    )
    conf.close()

    slist = open("%s/sources.list" % (base_dir,), "w")
    for (distro, components) in distro_list:
        for component in components:
            slist.write("deb file://%s %s %s\n" % (path, distro, component))
    if global_conf.has_key("correction_apt_repo"):
        slist.write(global_conf["correction_apt_repo"] + "\n")
    slist.close()

    os.system("apt-get --config-file %s/apt.conf update" % (base_dir,))

    # Add base media to apt's cache.

    for base_media_dir in global_conf["base_media"]:
        os.system("apt-cdrom --config-file %s/apt.conf -d %s -m add" % (base_dir, base_media_dir))

    # Initialize the python-apt bindings.

    apt_pkg.init_config()
    apt_pkg.read_config_file(apt_pkg.config, "%s/apt.conf" % (base_dir,))
    apt_pkg.init_system()

    cache = apt_pkg.Cache()
    global_conf["apt_path"] = base_dir
Пример #25
0
import apt_pkg
import sys
import posixpath

# Create a new empty Configuration object - there is also the system global
# configuration object apt_pkg.config which is used interally by apt-pkg
# routines to control unusual situations. I recommend using the sytem global
# whenever possible..
Cnf = apt_pkg.Configuration()

print("Command line is", sys.argv)

# Load the default configuration file, init_config() does this better..
Cnf.set("config-file", "/etc/apt/apt.conf")  # or Cnf["config-file"] = ".."
if posixpath.exists(Cnf.find_file("config-file")):
    apt_pkg.read_config_file(Cnf, "/etc/apt/apt.conf")

# Merge the command line arguments into the configuration space
Arguments = [('h', "help", "help"),
             ('v', "version", "version"),
             ('q', "quiet", "quiet", "IntLevel"),
             ('c', "config-file", "", "ConfigFile"),
             ('o', "option", "", "ArbItem")]
print("FileNames", apt_pkg.parse_commandline(Cnf, Arguments, sys.argv))

print("Quiet level selected is", Cnf.find_i("quiet", 0))

# Do some stuff with it
if Cnf.find_b("version", 0) == 1:
    print("Version selected - 1.1")
Пример #26
0
    def dpkg_action(self, widget, install):
        if not install:
            self.openCache()
            if not self._deb.pkgname in self._cache:
                return
            self._cache[self._deb.pkgname].mark_delete()
            if self._cache.delete_count > 1:
                details = set()
                for package in self._cache.get_changes():
                    if package.shortname != self._deb.pkgname:
                        if package.marked_delete:
                            details.add(package.shortname)
                self.error_header = _("Dependency problems")
                self.error_body = _("One or more packages are required by %s, "
                                    "it cannot be removed.") % self._deb.pkgname
                self.show_alert(Gtk.MessageType.ERROR, self.error_header,
                                self.error_body, "\n".join(details))
                return
        self.action_completed=False
        # check if we actually have a deb, see #213725
        if install and not self._deb:
            err_header = _("File not found")
            err_body = _("You tried to install a file that does not "
                         "(or no longer) exist. ")
            dia = Gtk.MessageDialog(None, 0, Gtk.MessageType.ERROR,
                                    Gtk.ButtonsType.OK, "")
            dia.set_markup("<b><big>%s</big></b>" % err_header)
            dia.format_secondary_text(err_body)
            dia.run()
            dia.destroy()
            return
        # do it
        if install:
            msgstring = _("Installing package file...")
        else:
            msgstring = _("Removing package...")
        self.statusbar_main.push(self.context, msgstring)
        if install and widget != None and len(self.unauthenticated) > 0:
            primary = _("Install unauthenticated software?")
            secondary = _("Malicious software can damage your data "
                          "and take control of your system.\n\n"
                          "The packages below are not authenticated and "
                          "could therefore be of malicious nature.")
            msg = "<big><b>%s</b></big>\n\n%s" % (primary, secondary)
            dialog = Gtk.MessageDialog(parent=self.dialog_deb_install,
                                       flags=Gtk.DialogFlags.MODAL,
                                       type=Gtk.MessageType.WARNING,
                                       buttons=Gtk.ButtonsType.YES_NO)
            dialog.set_markup(msg)
            dialog.set_border_width(6)
            scrolled = Gtk.ScrolledWindow()
            textview = Gtk.TextView()
            textview.set_cursor_visible(False)
            textview.set_editable(False)
            buf = textview.get_buffer()
            buf.set_text("\n".join(self.unauthenticated))
            scrolled.add(textview)
            scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
            scrolled.show()
            dialog.get_content_area().pack_start(scrolled, True, True, 0)
            textview.show()
            res = dialog.run()
            dialog.destroy()
            if res != Gtk.ResponseType.YES:
                return

        if install:
            msg_hdr = _("You need to grant administrative rights to install software")
            msg_bdy = _("""
It is a possible security risk to install packages files manually.
Install software from trustworthy software distributors only.
""")
        else:
            msg_hdr = _("You need to grant administrative rights to remove software")
            msg_bdy = _("It is a possible risk to remove packages.")
        if os.getuid() != 0:

            # build command and argument lists
            gksu_cmd = "/usr/bin/gksu"
            gksu_args = ["gksu", "--desktop",
                         "/usr/share/applications/gdebi.desktop",
                         "--message",
                         "<big><b>%s</b></big>\n\n%s" % (msg_hdr,msg_bdy)]
            gdebi_args = ["--", "gdebi-gtk", "--non-interactive",
                          self._deb.filename]
            if not install:
                gdebi_args.append("--remove")
            # check if we run on ubuntu and always ask for the password
            # there - we would like to do that on debian too, but this
            # gksu patch is only available on ubuntu currently unfortunately
            if UBUNTU:
                    gksu_args.append("--always-ask-pass")
            os.execv(gksu_cmd, gksu_args+gdebi_args)

        if not self.try_acquire_lock():
            if install:
                msgstring = _("Failed to install package file")
            else:
                msgstring = _("Failed to remove package")
            self.statusbar_main.push(self.context, msgstring)
            self.show_alert(Gtk.MessageType.ERROR, self.error_header, self.error_body)
            return False

        # lock for install
        self.window_main.set_sensitive(False)
        self.button_deb_install_close.set_sensitive(False)
        # clear terminal
        #self.vte_terminal.feed(str(0x1b)+"[2J")

        # Get whether we auto close from synaptic's config file and
        # update the toggle button as neccessary
        config = apt_pkg.Configuration()
        if os.path.isfile("/root/.synaptic/synaptic.conf"):
            apt_pkg.read_config_file(config, "/root/.synaptic/synaptic.conf")
        else:
            config["Synaptic::closeZvt"] = "false"
        if not "Synaptic" in config.list():
            config["Synaptic::closeZvt"] = "false"
        self.synaptic_config = config.subtree("Synaptic")
        self.checkbutton_autoclose.set_active(self.synaptic_config.find_b("closeZvt"))

        self.dialog_deb_install.set_transient_for(self.window_main)
        self.dialog_deb_install.show_all()

        if install and (len(self.install) > 0 or len(self.remove) > 0):
            # FIXME: use the new python-apt acquire interface here,
            # or rather use it in the apt module and raise exception
            # when stuff goes wrong!
            if not self.acquire_lock():
              self.show_alert(Gtk.MessageType.ERROR, self.error_header, self.error_body)
              return False
            fprogress = self.FetchProgressAdapter(self.progressbar_install,
                                                self.label_action,
                                                self.dialog_deb_install)
            iprogress = self.InstallProgressAdapter(self.progressbar_install,
                                                    self.vte_terminal,
                                                    self.label_action,
                                                    self.expander_install)
            try:
                res = self._cache.commit(fprogress,iprogress)
            except IOError as e:
                res = False
                msg = e
                header = _("Could not download all required files")
                body = _("Please check your internet connection or "
                        "installation medium, and make sure your "
                        "APT cache is up-to-date.")
            except SystemError as e:
                res = False
                msg = e
                header = _("Could not install all dependencies"),
                body = _("Usually this is related to an error of the "
                        "software distributor. See the terminal window for "
                        "more details.")
            if not res:
                self.show_alert(Gtk.MessageType.ERROR, header, body, msg,
                                parent=self.dialog_deb_install)

                self.label_install_status.set_markup("<span foreground=\"red\" weight=\"bold\">%s</span>" % header)
                self.button_deb_install_close.set_sensitive(True)
                self.button_deb_install_close.grab_default()
                self.statusbar_main.push(self.context,_("Failed to install package file"))
                return

        # install the package itself
        self.dialog_deb_install.set_title(self.window_main.get_title())
        if install:
            self.label_action.set_markup("<b><big>" + _("Installing %s") %
                                         self._deb.pkgname + "</big></b>")
        else:
            self.label_action.set_markup("<b><big>" + _("Removing %s") %
                                         self._deb.pkgname + "</big></b>")
        if install:
            debfilename = self._deb.filename
        else:
            debfilename = self._deb.pkgname
        dprogress = self.DpkgActionProgress(debfilename,
                                            self.label_install_status,
                                            self.progressbar_install,
                                            self.vte_terminal,
                                            self.expander_install,
                                            install)
        dprogress.commit()
        self.action_completed=True
        #self.label_action.set_markup("<b><big>"+_("Package installed")+"</big></b>")
        # show the button
        self.button_deb_install_close.set_sensitive(True)
        self.button_deb_install_close.grab_default()
        #Close if checkbox is selected
        if self.checkbutton_autoclose.get_active():
            self.on_button_deb_install_close_clicked(None)
        if install:
            self.label_action.set_markup("<b><big>"+_("Installation finished")+"</big></b>")
        else:
            self.label_action.set_markup("<b><big>"+_("Removal finished")+"</big></b>")
        if dprogress.exitstatus == 0:
            if install:
                self.label_install_status.set_markup("<i>"+_("Package '%s' was installed") % os.path.basename(self._deb.filename)+"</i>")
            else:
                self.label_install_status.set_markup("<i>"+_("Package '%s' was removed") % os.path.basename(self._deb.pkgname)+"</i>")
        else:
            if install:
                self.label_install_status.set_markup("<b>"+_("Failed to install package '%s'") %
                                                     os.path.basename(self._deb.filename)+"</b>")
            else:
                self.label_install_status.set_markup("<b>"+_("Failed to remove package '%s'") %
                                                    os.path.basename(self._deb.pkgname)+"</b>")
            self.expander_install.set_expanded(True)
        if install:
            self.statusbar_main.push(self.context,_("Installation complete"))
        else:
            self.statusbar_main.push(self.context,_("Removal complete"))
        # FIXME: Doesn't stop notifying
        #self.window_main.set_property("urgency-hint", 1)

        # reopen the cache, reread the file
        self.openCache()
        if self._cache._depcache.broken_count > 0:
            if install:
                err_header = _("Failed to completely install all dependencies")
            else:
                err_header = _("Failed to completely remove package")
            err_body = _("To fix this run 'sudo apt-get install -f' in a "
                         "terminal window.")
            self.show_alert(Gtk.MessageType.ERROR, err_header, err_body)
        self.open(self._deb.filename)
Пример #27
0
    def dpkg_action(self, widget, install):
        if not install:
            self.openCache()
            if not self._deb.pkgname in self._cache:
                return
            self._cache[self._deb.pkgname].mark_delete()
            if self._cache.delete_count > 1:
                details = set()
                for package in self._cache.get_changes():
                    if package.shortname != self._deb.pkgname:
                        if package.marked_delete:
                            details.add(package.shortname)
                self.error_header = _("Dependency problems")
                self.error_body = _("One or more packages are required by %s, "
                                    "it cannot be removed.") % self._deb.pkgname
                self.show_alert(Gtk.MessageType.ERROR, self.error_header,
                                self.error_body, "\n".join(details))
                return
        self.action_completed=False
        # check if we actually have a deb, see #213725
        if install and not self._deb:
            err_header = _("File not found")
            err_body = _("You tried to install a file that does not "
                         "(or no longer) exist. ")
            dia = Gtk.MessageDialog(None, 0, Gtk.MessageType.ERROR,
                                    Gtk.ButtonsType.OK, "")
            dia.set_markup("<b><big>%s</big></b>" % err_header)
            dia.format_secondary_text(err_body)
            dia.run()
            dia.destroy()
            return
        # do it
        if install:
            msgstring = _("Installing package file...")
        else:
            msgstring = _("Removing package...")
        self.statusbar_main.push(self.context, msgstring)
        if install and widget != None and len(self.unauthenticated) > 0:
            primary = _("Install unauthenticated software?")
            secondary = _("Malicious software can damage your data "
                          "and take control of your system.\n\n"
                          "The packages below are not authenticated and "
                          "could therefore be of malicious nature.")
            msg = "<big><b>%s</b></big>\n\n%s" % (primary, secondary)
            dialog = Gtk.MessageDialog(parent=self.dialog_deb_install,
                                       flags=Gtk.DialogFlags.MODAL,
                                       type=Gtk.MessageType.WARNING,
                                       buttons=Gtk.ButtonsType.YES_NO)
            dialog.set_markup(msg)
            dialog.set_border_width(6)
            scrolled = Gtk.ScrolledWindow()
            textview = Gtk.TextView()
            textview.set_cursor_visible(False)
            textview.set_editable(False)
            buf = textview.get_buffer()
            buf.set_text("\n".join(self.unauthenticated))
            scrolled.add(textview)
            scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
            scrolled.show()
            dialog.get_content_area().pack_start(scrolled, True, True, 0)
            textview.show()
            res = dialog.run()
            dialog.destroy()
            if res != Gtk.ResponseType.YES:
                return

        if install:
            msg_hdr = _("You need to grant administrative rights to install software")
            msg_bdy = _("""
It is a possible security risk to install packages files manually.
Install software from trustworthy software distributors only.
""")
        else:
            msg_hdr = _("You need to grant administrative rights to remove software")
            msg_bdy = _("It is a possible risk to remove packages.")
        if os.getuid() != 0:

            # build command and argument lists
            gksu_cmd = "/usr/bin/gksu"
            gksu_args = ["gksu", "--desktop",
                         "/usr/share/applications/gdebi.desktop",
                         "--message",
                         "<big><b>%s</b></big>\n\n%s" % (msg_hdr,msg_bdy)]
            gdebi_args = ["--", "gdebi-gtk", "--non-interactive",
                          self._deb.filename]
            if not install:
                gdebi_args.append("--remove")
            # check if we run on ubuntu and always ask for the password
            # there - we would like to do that on debian too, but this
            # gksu patch is only available on ubuntu currently unfortunately
            if UBUNTU:
                    gksu_args.append("--always-ask-pass")
            os.execv(gksu_cmd, gksu_args+gdebi_args)

        if not self.try_acquire_lock():
            if install:
                msgstring = _("Failed to install package file")
            else:
                msgstring = _("Failed to remove package")
            self.statusbar_main.push(self.context, msgstring)
            self.show_alert(Gtk.MessageType.ERROR, self.error_header, self.error_body)
            return False

        # lock for install
        self.window_main.set_sensitive(False)
        self.button_deb_install_close.set_sensitive(False)
        # clear terminal
        #self.vte_terminal.feed(str(0x1b)+"[2J")

        # Get whether we auto close from synaptic's config file and
        # update the toggle button as neccessary
        config = apt_pkg.Configuration()
        if os.path.isfile("/root/.synaptic/synaptic.conf"):
            apt_pkg.read_config_file(config, "/root/.synaptic/synaptic.conf")
        else:
            config["Synaptic::closeZvt"] = "false"
        if not "Synaptic" in config.list():
            config["Synaptic::closeZvt"] = "false"
        self.synaptic_config = config.subtree("Synaptic")
        self.checkbutton_autoclose.set_active(self.synaptic_config.find_b("closeZvt"))

        self.dialog_deb_install.set_transient_for(self.window_main)
        self.dialog_deb_install.show_all()

        if install and (len(self.install) > 0 or len(self.remove) > 0):
            # FIXME: use the new python-apt acquire interface here,
            # or rather use it in the apt module and raise exception
            # when stuff goes wrong!
            if not self.acquire_lock():
              self.show_alert(Gtk.MessageType.ERROR, self.error_header, self.error_body)
              return False
            fprogress = self.FetchProgressAdapter(self.progressbar_install,
                                                self.label_action,
                                                self.dialog_deb_install)
            iprogress = self.InstallProgressAdapter(self.progressbar_install,
                                                    self.vte_terminal,
                                                    self.label_action,
                                                    self.expander_install)
            #errMsg = None
            try:
                res = self._cache.commit(fprogress,iprogress)
            except IOError as msg:
                res = False
                #errMsg = "%s" % msg
                header = _("Could not download all required files")
                body = _("Please check your internet connection or "
                        "installation medium, and make sure your "
                        "APT cache is up-to-date.")
            except SystemError as msg:
                res = False
                header = _("Could not install all dependencies"),
                body = _("Usually this is related to an error of the "
                        "software distributor. See the terminal window for "
                        "more details.")
            if not res:
                self.show_alert(Gtk.MessageType.ERROR, header, body, msg,
                                parent=self.dialog_deb_install)

                self.label_install_status.set_markup("<span foreground=\"red\" weight=\"bold\">%s</span>" % header)
                self.button_deb_install_close.set_sensitive(True)
                self.button_deb_install_close.grab_default()
                self.statusbar_main.push(self.context,_("Failed to install package file"))
                return

        # install the package itself
        self.dialog_deb_install.set_title(self.window_main.get_title())
        if install:
            self.label_action.set_markup("<b><big>" + _("Installing %s") %
                                         self._deb.pkgname + "</big></b>")
        else:
            self.label_action.set_markup("<b><big>" + _("Removing %s") %
                                         self._deb.pkgname + "</big></b>")
        if install:
            debfilename = self._deb.filename
        else:
            debfilename = self._deb.pkgname
        dprogress = self.DpkgActionProgress(debfilename,
                                            self.label_install_status,
                                            self.progressbar_install,
                                            self.vte_terminal,
                                            self.expander_install,
                                            install)
        dprogress.commit()
        self.action_completed=True
        #self.label_action.set_markup("<b><big>"+_("Package installed")+"</big></b>")
        # show the button
        self.button_deb_install_close.set_sensitive(True)
        self.button_deb_install_close.grab_default()
        #Close if checkbox is selected
        if self.checkbutton_autoclose.get_active():
            self.on_button_deb_install_close_clicked(None)
        if install:
            self.label_action.set_markup("<b><big>"+_("Installation finished")+"</big></b>")
        else:
            self.label_action.set_markup("<b><big>"+_("Removal finished")+"</big></b>")
        if dprogress.exitstatus == 0:
            if install:
                self.label_install_status.set_markup("<i>"+_("Package '%s' was installed") % os.path.basename(self._deb.filename)+"</i>")
            else:
                self.label_install_status.set_markup("<i>"+_("Package '%s' was removed") % os.path.basename(self._deb.pkgname)+"</i>")
        else:
            if install:
                self.label_install_status.set_markup("<b>"+_("Failed to install package '%s'") %
                                                     os.path.basename(self._deb.filename)+"</b>")
            else:
                self.label_install_status.set_markup("<b>"+_("Failed to remove package '%s'") %
                                                    os.path.basename(self._deb.pkgname)+"</b>")
            self.expander_install.set_expanded(True)
        if install:
            self.statusbar_main.push(self.context,_("Installation complete"))
        else:
            self.statusbar_main.push(self.context,_("Removal complete"))
        # FIXME: Doesn't stop notifying
        #self.window_main.set_property("urgency-hint", 1)

        # reopen the cache, reread the file
        self.openCache()
        if self._cache._depcache.broken_count > 0:
            if install:
                err_header = _("Failed to completely install all dependencies")
            else:
                err_header = _("Failed to completely remove package")
            err_body = _("To fix this run 'sudo apt-get install -f' in a "
                         "terminal window.")
            self.show_alert(Gtk.MessageType.ERROR, err_header, err_body)
        self.open(self._deb.filename)
Пример #28
0
def init():
    "Initialize apt and prepare it for dependency solving."

    global cache

    if cache:
        raise RuntimeError, "apt is already initialized"

    global_conf = picax.config.get_config()
    base_dir = global_conf["temp_dir"] + "/apt-info"
    path = global_conf["base_path"]

    distro_hash = {}
    for (distro, comp) in global_conf["repository_list"]:
        if not distro_hash.has_key(distro):
            distro_hash[distro] = []
        distro_hash[distro].append(comp)
    distro_list = [(x, distro_hash[x]) for x in distro_hash.keys()]

    subdirs = ("state", "state/lists", "state/lists/partial", "cache",
               "cache/archives", "cache/archives/partial")

    if os.path.exists(base_dir):
        shutil.rmtree(base_dir)
    os.mkdir(base_dir)

    for subdir in subdirs:
        os.mkdir(base_dir + "/" + subdir)

    status = open("%s/state/status" % (base_dir, ), "w")
    status.close()

    conf = open("%s/apt.conf" % (base_dir, ), "w")
    conf.write("""
APT
{
  Architecture "%s";
};
Dir "%s/"
{
  State "state/" {
    status "status";
  };
  Cache "cache/";
  Etc "%s/";
};
""" % (global_conf['arch'], base_dir, base_dir))
    conf.close()

    slist = open("%s/sources.list" % (base_dir, ), "w")
    for (distro, components) in distro_list:
        for component in components:
            slist.write("deb file://%s %s %s\n" % (path, distro, component))
    if global_conf.has_key("correction_apt_repo"):
        slist.write(global_conf["correction_apt_repo"] + "\n")
    slist.close()

    os.system("apt-get --config-file %s/apt.conf update" % (base_dir, ))

    # Add base media to apt's cache.

    for base_media_dir in global_conf["base_media"]:
        os.system("apt-cdrom --config-file %s/apt.conf -d %s -m add" %
                  (base_dir, base_media_dir))

    # Initialize the python-apt bindings.

    apt_pkg.init_config()
    apt_pkg.read_config_file(apt_pkg.config, "%s/apt.conf" % (base_dir, ))
    apt_pkg.init_system()

    cache = apt_pkg.Cache()
    global_conf["apt_path"] = base_dir