o 4f@sddlmZddlZddlZddlZddlZddlmZmZm Z m Z m Z m Z m Z mZmZmZmZddlZddlmZmZddlZddlmZmZmZGdddeZGdd d eZGd d d eZGd d d eZ Gddde!Z"Gddde#Z$Gddde#Z%Gddde#Z&Gddde#Z'Gddde'Z(Gddde'Z)Gddde#Z*Gddde#Z+d d!Z,d"d#Z-d$d%Z.e/d&kre.dSdS)')print_functionN) AnyCallableDictIteratorListOptionalSetTupleUnioncastKeysView)PackageVersion)AcquireProgressInstallProgress OpProgressc@eZdZdZdS)FetchCancelledExceptionzAException that is thrown when the user cancels a fetch operation.N__name__ __module__ __qualname____doc__rr+/usr/lib/python3/dist-packages/apt/cache.pyr'rc@r)FetchFailedExceptionz-Exception that is thrown when fetching fails.Nrrrrrr+rrc@r)UntrustedExceptionz>Exception that is thrown when fetching fails for trust reasonsNrrrrrr/rrc@r)LockFailedExceptionz,Exception that is thrown when locking fails.Nrrrrrr3rrc@r)CacheClosedExceptionz>Exception that is thrown when the cache is used after close().Nrrrrrr 7rr c@s(eZdZdZddZddZddZdS) _WrappedLockz`Wraps an apt_pkg.FileLock to raise LockFailedException. Initialized using a directory path.cCs ||_ttj|d|_dS)Nlock)_pathapt_pkgFileLockospathjoin_lock)selfr'rrr__init__@sz_WrappedLock.__init__c Cs:z|jWStjy}z td|j|fd}~ww)NzFailed to lock directory %s: %s)r) __enter__r$Errorrr#)r*errrr,Es z_WrappedLock.__enter__cCs|j|||SN)r)__exit__)r*typvalue tracebackrrrr0Msz_WrappedLock.__exit__N)rrrrr+r,r0rrrrr!;s  r!c@seZdZdZd\ddZddZdd Zd d Zd d Zd]ddZ ddZ ddZ ddZ ddZ ddZd]ddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd^d,d-Zed.d/Zed0d1Zed2d3Zd4d5Z d]d6d7Z   d_d8d9Zd:d;Z < d`d=d>Z! ? dad@dAZ"dBdCZ#   d_dDdEZ$dFdGZ%dHdIZ&dJdKZ'dLdMZ(dNdOZ)dPdQZ*edRdSZ+edTdUZ,edVdWZ-edXdYZ.edZd[Z/dS)bCacheaDictionary-like package cache. The APT cache file contains a hash table mapping names of binary packages to their metadata. A Cache object is the in-core representation of the same. It provides access to APTs idea of the list of available packages. The cache can be used like a mapping from package names to Package objects (although only getting items is supported). Keyword arguments: progress -- a OpProgress object, rootdir -- an alternative root directory. if that is given the system sources.list and system lists/files are not read, only file relative to the given rootdir, memonly -- build the cache in memory only. .. versionchanged:: 1.0 The cache now supports package names with special architecture qualifiers such as :all and :native. It does not export them in :meth:`keys()`, though, to keep :meth:`keys()` a unique set. NFc CsTttjd|_ttjd|_ttjd|_ttjd|_ i|_ i|_ t |_t |_d|_d|_|dd|dd|rGtjdd|rtj|}tj|dr`ttj|dtj|drqttj|dtjd |tjd |d tjd tj|d dd||ttj d}t!||_"|#|dS)Ncache_post_open_inc_changes_countcache_post_changezDir::Cache::pkgcachez/etc/apt/apt.confz/etc/apt/apt.conf.dDirDir::State::status/var/lib/dpkg/statuszDir::bin::dpkgusrbindpkgDir::Cache::Archives)$r r$r4_cacheDepCache _depcachePackageRecords_records SourceList_list _callbacks _callbacks2weakrefWeakValueDictionary_weakrefWeakSet _weakversions_changes_count _sorted_setconnectconfigsetr&r'abspathexistsread_config_fileisdirread_config_dirr(_check_and_create_required_dirs init_systemfind_dirr! _archive_lockopen)r*progressrootdirmemonly archive_dirrrrr+lsH        zCache.__init__cC|jdS)zFix broken packages.N)rC fix_brokenr*rrrrczCache.fix_brokencCs|jd7_dS)zIncrease the number of changesN)rOrdrrrr7zCache._inc_changes_countcCshddg}gd}|D]}tj||st||q |D]}tj||s1t||dqdS)zf check if the required apt directories/files are there and if not create them r<z/etc/apt/sources.list)z /var/lib/dpkgz /etc/apt/z/var/cache/apt/archives/partialz/var/lib/apt/lists/partialwN)r&r'rUmakedirsr]close)r*r_filesdirsdfrrrrYsz%Cache._check_and_create_required_dirscCsp||jvr|j|D]}|dkr|q |q ||jvr4|j|D]\}}}||g|Ri|q#dSdS)z# internal helper to run a callback r7N)rHr7rIr*namecallbackargskwdsrrr_run_callbackss   zCache._run_callbackscCs|dur tjj}|||_|dt||_ t |j |_ t |j |_ t|_|jd|_|ttdk|_||ddS)zY Open the package cache, after that it can be used like a dictionary Ncache_pre_openrfr6)aptr^baserrj op_progressrtr$r4rArBrCrDrErFrGread_main_listrP _Cache__remaplenget_architectures_have_multi_archdone)r*r^rrrr]s     z Cache.openc Cst|jD].}z|j|}Wn tyYqwz|j|jj|jjf|_Wqty5|j|=Yqwt|j D]<}|j jj D].}|j |j j krp|jdks]|j jdks]|j|j jkrp|j|j jkrp|j|j jkrp||_ nqB|j |q;dS)zCalled after cache reopen() to relocate to new cache. Relocate objects like packages and versions from the old underlying cache to the new one. rN)listrLkeysKeyErrorrA_pkgrp architecture LookupErrorrNpackage version_listhash_candsize multi_archver_strremove)r*keypkgvervrrr__remaps0    z Cache.__remapcCs|`ttjd|_dS)z Close the package cache N)rEr r$rDrdrrrrjsz Cache.closecCs|S)z Enter the with statement rrdrrrr, szCache.__enter__cCs |dS)z Exit the with statement N)rj)r*exc_type exc_valuer3rrrr0 zCache.__exit__cCsVz t|}|j|}Wn tytd|w||s$td|||}|S)z" look like a dictionary (get key) z!The cache has no package named %r)strrAr_Cache__is_real_pkg_rawpkg_to_pkg)r*rrawpkgrrrr __getitem__s     zCache.__getitem__cCs"z||WSty|YSw)zaReturn *self*[*key*] or *default* if *key* not in *self*. .. versionadded:: 1.1 )r)r*rdefaultrrrget%s   z Cache.getcCs |jdd}|j|t||S)zgReturns the apt.Package object for an apt_pkg.Package object. .. versionadded:: 1.0.0 Tpretty) get_fullnamerL setdefaultr)r*rfullnamerrrr0s zCache._rawpkg_to_pkgccs4|D]}t||j|}|j||VqdSr/)rrrArLrr*pkgnamerrrr__iter__:s  zCache.__iter__cC|jS)z8Check if the apt_pkg.Package provided is a real package.) has_versions)r*rrrr __is_real_pkgEszCache.__is_real_pkgcC||vSr/rr*rrrrhas_keyJz Cache.has_keycCs,z ||jt|WStyYdSwNF)rrArrrrrr __contains__Ns  zCache.__contains__cCs t|Sr/)r{rrdrrr__len__U z Cache.__len__cs0jdurtfddjjD_tjS)Nc3s&|]}|r|jddVqdS)TrN)rr).0prdrr \s zCache.keys..)rPsortedrApackagesrrdrrdrrYs   z Cache.keyscCs6g}|jj}|jjD]}||s|||q |S)z Get the marked changes )rC marked_keeprArappendr)r*changesrrrrr get_changesas zCache.get_changescCs ||j||dS)zUpgrade all packages. If the parameter *dist_upgrade* is True, new dependencies will be installed as well (and conflicting packages may be removed). The default value is False. N)cache_pre_changerCupgrader8)r* dist_upgraderrrrks  z Cache.upgradecCs>|jdur tdt|j}t}|||j|j|jS)z;Get the size of the packages that are required to download.N&Cache object used after close() called) rEr r$PackageManagerrCAcquire get_archivesrG fetch_needed)r*pmfetcherrrrrequired_downloadws  zCache.required_downloadcC|jjS)z8Get the size of the additional required space on the fs.)rCusr_sizerdrrrrequired_spacezCache.required_spacecCs^t}|jj}ttjtjf}|jjD]}||}|r,|j s,|j |vr,| |j ddq|S)zAReturn the packages not downloadable packages in reqreinst state.Tr) rSrCget_candidate_ver frozensetr$INSTSTATE_REINSTREQINSTSTATE_HOLD_REINSTREQrAr downloadable inst_stateaddr)r* reqreinstrstatesrcandrrrreq_reinstall_pkgss zCache.req_reinstall_pkgscCs|dur tjdd}dd|jD}|r%|s%tdddd|D|}d}d }|jD]}|j|jkr9q0|j r=q0|d |j |j f7}d }q0||j krSt ||rYt||S) NzAPT::Get::AllowUnauthenticatedFcSsg|]}|js|qSr) is_trusted)ritemrrr sz&Cache._run_fetcher..zUntrusted packages: %s css|]}|jVqdSr/)desc_uri)rirrrrsz%Cache._run_fetcher..r9zFailed to fetch %s %s T)r$rRfind_bitemsrr(runstatus STAT_DONE STAT_IDLEr error_textRESULT_CANCELLEDrr)r*rallow_unauthenticated untrustedresfailederr_msgrrrr _run_fetchers4   zCache._run_fetchercCs4|jdur td|||j|jsdS|||S)z fetch the needed archives NrF)rEr rrGr)r*rrrrrr_fetch_archivess  zCache._fetch_archivescCs~|dur |dur td|durtjj}|durt|}|j||t |j |WdS1s8wYdS)aFetch the archives for all packages marked for install/upgrade. You can specify either an :class:`apt.progress.base.AcquireProgress()` object for the parameter *progress*, or specify an already existing :class:`apt_pkg.Acquire` object for the parameter *fetcher*. The return value of the function is undefined. If an error occurred, an exception of type :class:`FetchFailedException` or :class:`FetchCancelledException` is raised. The keyword-only parameter *allow_unauthenticated* specifies whether to allow unauthenticated downloads. If not specified, it defaults to the configuration option `APT::Get::AllowUnauthenticated`. .. versionadded:: 0.8.0 Nz'Takes a progress or a an Acquire object) ValueErrorrvr^textrr$rr\rrrC)r*r^rrrrrfetch_archivess   $zCache.fetch_archivescCs6z|j|}Wn tyYdSwt|jo|j S)z0Return whether the package is a virtual package.F)rArbool has_providesrrrrris_virtual_packages  zCache.is_virtual_packageTc Cst}|jj}z|j|}|jr|st|WSWn ty%t|YSw|jD]\}}} | j} |r9| || krA| | | q)t|S)a)Return a list of all packages providing a package. Return a list of packages which provide the virtual package of the specified name. If 'candidate_only' is False, return all packages with at least one version providing the virtual package. Otherwise, return only those packages where the candidate version provides the virtual package. If 'include_nonvirtual' is True then it will search for all packages providing pkgname, even if pkgname is not itself a virtual pkg. ) rSrCrrArrr provides_list parent_pkgrr) r*rcandidate_onlyinclude_nonvirtual providersrvpprovides providesverversionrrrrget_providing_packagess      zCache.get_providing_packagesrc Csfttjd|r?tjd}tjd}tjd}tjdtj|tjddtjddt }| n|j }zM|durMt j j}z |j|||} Wntyg} zt| d} ~ ww| so|rot| W|rtjd|tjd|tjd|WdS|rtjd|tjd|tjd|ww1swYdS)aRun the equivalent of apt-get update. You probably want to call open() afterwards, in order to utilise the new cache. Otherwise, the old cache will be used which can lead to strange bugs. The first parameter *fetch_progress* may be set to an instance of apt.progress.FetchProgress, the default is apt.progress.FetchProgress() . sources_list -- Update a alternative sources.list than the default. Note that the sources.list.d directory is ignored in this case zDir::State::ListszDir::Etc::sourcelistzDir::Etc::sourcepartszAPT::List-Cleanupxxx0N)r!r$rRr[findrSr&r'rTrFryrGrvr^rwrrAupdate SystemErrorr) r*fetch_progresspulse_intervalraise_on_error sources_listold_sources_listold_sources_list_d old_cleanupslistrr.rrrrsf       z Cache.updatecCsz|Wn ty|Ynwt}|rtz ||}W|r+tn|r3twwz|W|StyI| Y|Sw)aY The first parameter *pm* refers to an object returned by apt_pkg.PackageManager(). The second parameter *install_progress* refers to an InstallProgress() object of the module apt.progress. This releases a system lock in newer versions, if there is any, and reestablishes it afterwards. ) startUpdateAttributeError start_updater$pkgsystem_is_lockedpkgsystem_unlock_innerrpkgsystem_lock_inner finishUpdate finish_update)r*rinstall_progress did_unlockrrrrinstall_archivesKs.       zCache.install_archivesc Cs|dur tjj}|durtjj}|dusJtTt|j}t |}|j 6 | |||}| ||}||j krBn||jkrKtd||jkrQntd||q/Wdn1sfwYWdn1suwY||j kS)a!Apply the marked changes to the cache. The first parameter, *fetch_progress*, refers to a FetchProgress() object as found in apt.progress, the default being apt.progress.FetchProgress(). The second parameter, *install_progress*, is a apt.progress.InstallProgress() object. The keyword-only parameter *allow_unauthenticated* specifies whether to allow unauthenticated downloads. If not specified, it defaults to the configuration option `APT::Get::AllowUnauthenticated`. NTzinstallArchives() failedz|dkr tdtd||jvrg|j|<|j||dS)zConnect to a signal. .. deprecated:: 1.0 Please use connect2() instead, as this function is very likely to cause a memory leak. r7zAconnect() likely causes a reference cycle, use connect2() insteadN)warningswarnRuntimeWarningrHr)r*rprqrrrrQs   z Cache.connectcOs.||jvr g|j|<|j||||fdS)a;Connect to a signal. The callback will be passed the cache as an argument, and any arguments passed to this function. Make sure that, if you pass a method of a class as your callback, your class does not contain a reference to the cache. Cyclic references to the cache can cause issues if the Cache object is replaced by a new one, because the cache keeps a lot of objects and tens of open file descriptors. currently only used for cache_{post,pre}_{changed,open}. .. versionadded:: 1.0 N)rIrrorrrconnect2s  zCache.connect2cCs t|jS)aReturn an `ActionGroup` object for the current cache. Action groups can be used to speedup actions. The action group is active as soon as it is created, and disabled when the object is deleted or when release() is called. You can use the action group as a context manager, this is the recommended way:: with cache.actiongroup(): for package in my_selected_packages: package.mark_install() This way, the action group is automatically released as soon as the with statement block is left. It also has the benefit of making it clear which parts of the code run with a action group and which don't. )r$ ActionGrouprCrdrrr actiongroups zCache.actiongroupcCsDtjtjd}ttj|dD] }t|drdSqdS)zReturn True if the dpkg was interrupted All dpkg operations will fail until this is fixed, the action to fix the system if dpkg got interrupted is to run 'dpkg --configure -a' as root. r;updatesz[0-9]*TF) r&r'dirnamer$rR find_filelistdirr(fnmatch)r*dpkg_status_dirrnrrrdpkg_journal_dirtys  zCache.dpkg_journal_dirtycCr)z7Return the number of packages with broken dependencies.)rC broken_countrdrrrr(rzCache.broken_countcCr)z2Return the number of packages marked for deletion.)rC del_countrdrrr delete_count rzCache.delete_countcCr)z6Return the number of packages marked for installation.)rC inst_countrdrrr install_countrzCache.install_countcCr)z-Return the number of packages marked as keep.)rC keep_countrdrrrr-rzCache.keep_count)NNFr/)F)NNN)TF)NrTN)0rrrrr+rcr7rYrtr]rzrjr,r0rrrrrrrrrrrpropertyrrrrrrrrrrrrr8rrQrr r'r(r*r,r-rrrrr4Rs .           $  "  ! 3# :    r4c@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)ProblemResolverzuResolve problems due to dependencies and conflicts. The first argument 'cache' is an instance of apt.Cache. cCst|j|_||_dSr/)r$r/rC _resolverrAr*cacherrrr+#s zProblemResolver.__init__cC|j|jdS)z'Reset the package to the default state.N)r0rrr*rrrrr(rgzProblemResolver.clearcCr3)z)Protect a package so it won't be removed.N)r0protectrr4rrrr5-rgzProblemResolver.protectcCr3)zMark a package for removal.N)r0rrr4rrrr2rgzProblemResolver.removecC"|j|j|jdS)z:Resolve dependencies, try to remove packages where needed.N)rArr0resolver8rdrrrr77  zProblemResolver.resolvecCr6)z4Resolve dependencies, do not try to remove packages.N)rArr0resolve_by_keepr8rdrrrr9>r8zProblemResolver.resolve_by_keepN) rrrrr+rr5rr7r9rrrrr/s r/c@eZdZdZddZdS)Filterz Filter base class cCsdS)zn Filter function, return True if the package matchs a filter criteria and False otherwise Trr*rrrrapplyLsz Filter.applyNrrrrr=rrrrr;I r;c@r:)MarkedChangesFilterz( Filter that returns all marked changes cCs|js |js |jr dSdS)NTF)marked_install marked_deletemarked_upgrader<rrrr=WszMarkedChangesFilter.applyNr>rrrrr@Tr?r@c@r:)InstalledFilterzMFilter that returns all installed packages. .. versionadded:: 1.0.0 cCrr/) is_installedr<rrrr=eszInstalledFilter.applyNr>rrrrrD_s rDc@s0eZdZdZddZddZddZdd Zd S) _FilteredCacheHelperz:Helper class for FilteredCache to break a reference cycle.cCs,i|_g|_|d|j|d|jdS)Nr8r6) _filtered_filtersrfilter_cache_post_changer1rrrr+msz_FilteredCacheHelper.__init__cCs:i|_|D]}|jD]}||rd|j|j<nq qdS)z internal helper to refilter TN)rGrHr=rp)r*r2rrnrrr_reapply_filtervs   z$_FilteredCacheHelper._reapply_filtercCsg|_|j|dSzSet the current active filter.N)rHrr*filterrrr set_filtersz_FilteredCacheHelper.set_filtercCs||dSz;Called internally if the cache changes, emit a signal then.N)rJr1rrrrIrz-_FilteredCacheHelper.filter_cache_post_changeN)rrrrr+rJrNrIrrrrrFjs   rFc@sbeZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ dS) FilteredCacheza A package cache that is filtered. Can work on a existing cache or create a new one NcCs*|dur t||_n||_t|j|_dSr/)r4r2rF_helper)r*r2r^rrrr+s zFilteredCache.__init__cCs t|jjSr/)r{rQrGrdrrrrrzFilteredCache.__len__cCs |j|Sr/r2rrrrrs zFilteredCache.__getitem__ccs |jjD]}|j|VqdSr/)rQrGr2)r*rrrrrs zFilteredCache.__iter__cCs |jjSr/)rQrGrrdrrrrrzFilteredCache.keyscCrr/rrrrrrrzFilteredCache.has_keycCs,z |j|j|jjvWStyYdSwr)r2rprQrGrrrrrrs  zFilteredCache.__contains__cCs|j||jdSrK)rQrNr2r8rLrrrrNs zFilteredCache.set_filtercCs|j|jdSrO)rQrIr2rdrrrrIrgz&FilteredCache.filter_cache_post_changecCs t|j|S)z)we try to look exactly like a real cache.)getattrr2rrrr __getattr__rzFilteredCache.__getattr__)NN)rrrrr+rrrrrrrNrIrTrrrrrPs  rPcC tddS)Nzcache pre changedprintrRrrrcache_pre_changedrrXcCrU)Nzcache post changedrVrRrrrcache_post_changedrrYcCstdtttjj}|dt |dt td|v|d}t|j tt || D] }||j |ks@Jq5||}tt ||D]}|j sXJqQdD] }tj|sht|q[tjddt|j}ttjj}|||dtd t|}|jdt |jdt |j|ttt || D] }|||j ksJqtt |td ttjjd }|jdt |jdt |j|ttt || D] }|||j ksJqtt |dS) zInternal test code.zCache self testrr8aptitude) /tmp/pytestz/tmp/pytest/partialr@r[Nz.Testing filtered cache (argument is old cache)z$Testing filtered cache (no argument))r^) rWr$rr4rvr^rrrrXrYrpr{rrrr&r'rUmkdirrRrSrrCrrrrPr2rNr@rw)r2rrrr"rrfilteredrrr_testsX                    r^__main__)0 __future__rr%r&rrJtypingrrrrrrr r r r r r$ apt.packagerrapt.progress.textrvapt.progress.baserrrIOErrorrrrr Exceptionr objectr!r4r/r;r@rDrFrPrXrYr^rrrrrsD 4P,   $<9