rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
self._persistdir = root + '/' + persistdir | if not os.path.normpath(persistdir).startswith(self.root): self._persistdir = root + '/' + persistdir else: self._persistdir = persistdir | def __init__(self, root='/', releasever=None, cachedir=None, persistdir='/var/lib/yum'): self.root = root self._idx2pkg = {} self._name2pkg = {} self._pkgnames_loaded = set() self._tup2pkg = {} self._completely_loaded = False self._pkgmatch_fails = set() self._provmatch_fails = set() self._simple_pkgtup_list = [] self._get_pro_cache = {} self._get_req_cache = {} self._loaded_gpg_keys = False if cachedir is None: cachedir = misc.getCacheDir() self.setCacheDir(cachedir) self._persistdir = root + '/' + persistdir self._have_cached_rpmdbv_data = None self._cached_conflicts_data = None # Store the result of what happens, if a transaction completes. self._trans_cache_store = {} self.ts = None self.releasever = releasever self.auto_close = False # this forces a self.ts.close() after # most operations so it doesn't leave # any lingering locks. |
self._cachedir = self.root + '/' + cachedir + "/installed/" | if not os.path.normpath(cachedir).startswith(self.root): self._cachedir = self.root + '/' + cachedir + "/installed/" else: self._cachedir = '/' + cachedir + "/installed/" | def setCacheDir(self, cachedir): """ Sets the internal cachedir value for the rpmdb, to be the "installed" directory from this parent. """ self._cachedir = self.root + '/' + cachedir + "/installed/" |
def import_key_to_pubring(rawkey, keyid, cachedir=None, gpgdir=None): | def import_key_to_pubring(rawkey, keyid, cachedir=None, gpgdir=None, make_ro_copy=True): | def import_key_to_pubring(rawkey, keyid, cachedir=None, gpgdir=None): # FIXME - cachedir can be removed from this method when we break api if gpgme is None: return False if not gpgdir: gpgdir = '%s/gpgdir' % cachedir if not os.path.exists(gpgdir): os.makedirs(gpgdir) key_fo = StringIO(rawkey) os.environ['GNUPGHOME'] = gpgdir # import the key ctx = gpgme.Context() fp = open(os.path.join(gpgdir, 'gpg.conf'), 'wb') fp.write('') fp.close() ctx.import_(key_fo) key_fo.close() # ultimately trust the key or pygpgme is definitionally stupid k = ctx.get_key(keyid) gpgme.editutil.edit_trust(ctx, k, gpgme.VALIDITY_ULTIMATE) return True |
if gpghome and os.path.exists(gpghome): | if gpghome: if not os.path.exists(gpghome): return False | def valid_detached_sig(sig_file, signed_file, gpghome=None): """takes signature , file that was signed and an optional gpghomedir""" if gpgme is None: return False if gpghome and os.path.exists(gpghome): os.environ['GNUPGHOME'] = gpghome if hasattr(sig_file, 'read'): sig = sig_file else: sig = open(sig_file, 'r') if hasattr(signed_file, 'read'): signed_text = signed_file else: signed_text = open(signed_file, 'r') plaintext = None ctx = gpgme.Context() try: sigs = ctx.verify(sig, signed_text, plaintext) except gpgme.GpgmeError, e: return False else: if not sigs: return False # is there ever a case where we care about a sig beyond the first one? thissig = sigs[0] if not thissig: return False if thissig.validity in (gpgme.VALIDITY_FULL, gpgme.VALIDITY_MARGINAL, gpgme.VALIDITY_ULTIMATE): return True return False |
def getCacheDir(tmpdir='/var/tmp', reuse=True): | def getCacheDir(tmpdir='/var/tmp', reuse=True, prefix='yum-'): | def getCacheDir(tmpdir='/var/tmp', reuse=True): """return a path to a valid and safe cachedir - only used when not running as root or when --tempcache is set""" uid = os.geteuid() try: usertup = pwd.getpwuid(uid) username = usertup[0] except KeyError: return None # if it returns None then, well, it's bollocksed prefix = 'yum-' if reuse: # check for /var/tmp/yum-username-* - prefix = 'yum-%s-' % username dirpath = '%s/%s*' % (tmpdir, prefix) cachedirs = sorted(glob.glob(dirpath)) for thisdir in cachedirs: stats = os.lstat(thisdir) if S_ISDIR(stats[0]) and S_IMODE(stats[0]) == 448 and stats[4] == uid: return thisdir # make the dir (tempfile.mkdtemp()) cachedir = tempfile.mkdtemp(prefix=prefix, dir=tmpdir) return cachedir |
prefix = 'yum-' | prefix = prefix | def getCacheDir(tmpdir='/var/tmp', reuse=True): """return a path to a valid and safe cachedir - only used when not running as root or when --tempcache is set""" uid = os.geteuid() try: usertup = pwd.getpwuid(uid) username = usertup[0] except KeyError: return None # if it returns None then, well, it's bollocksed prefix = 'yum-' if reuse: # check for /var/tmp/yum-username-* - prefix = 'yum-%s-' % username dirpath = '%s/%s*' % (tmpdir, prefix) cachedirs = sorted(glob.glob(dirpath)) for thisdir in cachedirs: stats = os.lstat(thisdir) if S_ISDIR(stats[0]) and S_IMODE(stats[0]) == 448 and stats[4] == uid: return thisdir # make the dir (tempfile.mkdtemp()) cachedir = tempfile.mkdtemp(prefix=prefix, dir=tmpdir) return cachedir |
prefix = 'yum-%s-' % username | prefix = '%s%s-' % (prefix, username) | def getCacheDir(tmpdir='/var/tmp', reuse=True): """return a path to a valid and safe cachedir - only used when not running as root or when --tempcache is set""" uid = os.geteuid() try: usertup = pwd.getpwuid(uid) username = usertup[0] except KeyError: return None # if it returns None then, well, it's bollocksed prefix = 'yum-' if reuse: # check for /var/tmp/yum-username-* - prefix = 'yum-%s-' % username dirpath = '%s/%s*' % (tmpdir, prefix) cachedirs = sorted(glob.glob(dirpath)) for thisdir in cachedirs: stats = os.lstat(thisdir) if S_ISDIR(stats[0]) and S_IMODE(stats[0]) == 448 and stats[4] == uid: return thisdir # make the dir (tempfile.mkdtemp()) cachedir = tempfile.mkdtemp(prefix=prefix, dir=tmpdir) return cachedir |
return cmp(self.pkg, other.pkg) or cmp(self.problem, problem) | return cmp(self.pkg, other.pkg) or cmp(self.problem, other.problem) | def __cmp__(self, other): if other is None: return 1 return cmp(self.pkg, other.pkg) or cmp(self.problem, problem) |
if hasattr(txmbr, 'reinstall'): | if txmbr.reinstall: | def txmbr2state(txmbr): state = None if txmbr.output_state in (TS_INSTALL, TS_TRUEINSTALL): if hasattr(txmbr, 'reinstall'): state = 'Reinstall' elif txmbr.downgrades: state = 'Downgrade' if txmbr.output_state == TS_ERASE: if txmbr.downgraded_by: state = 'Downgraded' if state is None: state = _stcode2sttxt.get(txmbr.output_state) if state == 'Install' and txmbr.isDep: state = 'Dep-Install' return state |
prefix = prefix | def getCacheDir(tmpdir='/var/tmp', reuse=True, prefix='yum-'): """return a path to a valid and safe cachedir - only used when not running as root or when --tempcache is set""" uid = os.geteuid() try: usertup = pwd.getpwuid(uid) username = usertup[0] except KeyError: return None # if it returns None then, well, it's bollocksed prefix = prefix if reuse: # check for /var/tmp/yum-username-* - prefix = '%s%s-' % (prefix, username) dirpath = '%s/%s*' % (tmpdir, prefix) cachedirs = sorted(glob.glob(dirpath)) for thisdir in cachedirs: stats = os.lstat(thisdir) if S_ISDIR(stats[0]) and S_IMODE(stats[0]) == 448 and stats[4] == uid: return thisdir # make the dir (tempfile.mkdtemp()) cachedir = tempfile.mkdtemp(prefix=prefix, dir=tmpdir) return cachedir |
|
ini[repo.id][name] = option.tostring(value) | ini[section_id][name] = option.tostring(value) | def writeRawRepoFile(repo,only=None): """ Writes changes in a repo object back to a .repo file. @param repo: Repo Object @param only: List of attributes to work on (None = All) It work by reading the repo file, changes the values there shall be changed and write it back to disk. """ if not _use_iniparse: return ini = INIConfig(open(repo.repofile)) # Updated the ConfigParser with the changed values cfgOptions = repo.cfg.options(repo.id) for name,value in repo.iteritems(): option = repo.optionobj(name) if option.default != value or name in cfgOptions : if only == None or name in only: ini[repo.id][name] = option.tostring(value) fp =file(repo.repofile,"w") fp.write(str(ini)) fp.close() |
n = to_unicode(n) | n_b = n n_u = to_unicode(n) n = n_u | def searchPrco(self, name, prcotype): """return list of packages matching name and prcotype """ # we take name to be a string of some kind # we parse the string to see if it is a foo > 1.1 or if it is just 'foo' # or what - so we can answer correctly if self._skip_all(): return [] try: (n,f,(e,v,r)) = misc.string_to_prco_tuple(name) except Errors.MiscError, e: raise Errors.PackageSackError, to_unicode(e) n = to_unicode(n) |
if po.checkPrco(prcotype, (n, f, (e,v,r))): | if po.checkPrco(prcotype, (n_b, f, (e,v,r))): | def searchPrco(self, name, prcotype): """return list of packages matching name and prcotype """ # we take name to be a string of some kind # we parse the string to see if it is a foo > 1.1 or if it is just 'foo' # or what - so we can answer correctly if self._skip_all(): return [] try: (n,f,(e,v,r)) = misc.string_to_prco_tuple(name) except Errors.MiscError, e: raise Errors.PackageSackError, to_unicode(e) n = to_unicode(n) |
raise Errors.DowngradeError, 'Nothing specified to remove' | raise Errors.DowngradeError, 'Nothing specified to downgrade' | def downgrade(self, po=None, **kwargs): """ Try to downgrade a package. Works like: % yum shell <<EOL remove abcd install abcd-<old-version> run EOL """ |
return syslog.LOG_USER | return syslog_module.LOG_USER | def syslogFacilityMap(facility): if type(facility) == int: return facility elif facility.upper() in _syslog_facility_map: return _syslog_facility_map[facility.upper()] elif (facility.upper().startswith("LOG_") and facility[4:].upper() in _syslog_facility_map): return _syslog_facility_map[facility[4:].upper()] return syslog.LOG_USER |
cols.append((str(repo), repo.name, | cols.append((rid, repo.name, | def _num2ui_num(num): return to_unicode(locale.format("%d", num, True)) |
if ipkg.verGT(po): | for ipkg in self.rpmdb.searchNevra(name=po.name): if ipkg.verGT(po) and not canCoinstall(ipkg.arch, po.arch): | def install(self, po=None, **kwargs): """try to mark for install the item specified. Uses provided package object, if available. If not it uses the kwargs and gets the best packages from the keyword options provided returns the list of txmbr of the items it installs """ pkgs = [] was_pattern = False if po: if isinstance(po, YumAvailablePackage) or isinstance(po, YumLocalPackage): pkgs.append(po) else: raise Errors.InstallError, _('Package Object was not a package object instance') else: if not kwargs: raise Errors.InstallError, _('Nothing specified to install') |
def getPackageObject(self, pkgtup): | def getPackageObject(self, pkgtup, allow_missing=False): | def getPackageObject(self, pkgtup): """retrieves a packageObject from a pkgtuple - if we need to pick and choose which one is best we better call out to some method from here to pick the best pkgobj if there are more than one response - right now it's more rudimentary.""" # look it up in the self.localPackages first: for po in self.localPackages: if po.pkgtup == pkgtup: return po pkgs = self.pkgSack.searchPkgTuple(pkgtup) |
obsoleting = obsoleting[0] obsoleting_pkg = self.getPackageObject(obsoleting) return obsoleting_pkg | for pkgtup in obsoleting: pkg = self.getPackageObject(pkgtup, allow_missing=True) if pkg is not None: return pkg return None | def _sort_arch(x, y): n1,a1,e1,v1,r1 = x n2,a2,e2,v2,r2 = y ret = _sort_arch_i(po.arch, a1, a2) if ret: return ret ret = _sort_arch_i(self.arch.bestarch, a1, a2) return ret |
obsoleting_pkg = self.getPackageObject(obsoleting) | obsoleting_pkg = self.getPackageObject(obsoleting, allow_missing=True) if obsoleting_pkg is None: continue | def update(self, po=None, requiringPo=None, **kwargs): """try to mark for update the item(s) specified. po is a package object - if that is there, mark it for update, if possible else use **kwargs to match the package needing update if nothing is specified at all then attempt to update everything returns the list of txmbr of the items it marked for update""" # check for args - if no po nor kwargs, do them all # if po, do it, ignore all else # if no po do kwargs # uninstalled pkgs called for update get returned with errors in a list, maybe? |
tx_return.extend(self.update(po=self.getPackageObject(new))) | new = self.getPackageObject(new, allow_missing=True) if new is None: continue tx_return.extend(self.update(po=new)) | def update(self, po=None, requiringPo=None, **kwargs): """try to mark for update the item(s) specified. po is a package object - if that is there, mark it for update, if possible else use **kwargs to match the package needing update if nothing is specified at all then attempt to update everything returns the list of txmbr of the items it marked for update""" # check for args - if no po nor kwargs, do them all # if po, do it, ignore all else # if no po do kwargs # uninstalled pkgs called for update get returned with errors in a list, maybe? |
opkgs = self.pkgSack.searchPkgTuple(pkgtup) if not opkgs: continue obs_pkgs.append(opkgs[0]) | obsoleting_pkg = self.getPackageObject(pkgtup, allow_missing=True) if obsoleting_pkg is None: continue obs_pkgs.append(obsoleting_pkg) | def update(self, po=None, requiringPo=None, **kwargs): """try to mark for update the item(s) specified. po is a package object - if that is there, mark it for update, if possible else use **kwargs to match the package needing update if nothing is specified at all then attempt to update everything returns the list of txmbr of the items it marked for update""" # check for args - if no po nor kwargs, do them all # if po, do it, ignore all else # if no po do kwargs # uninstalled pkgs called for update get returned with errors in a list, maybe? |
po = self.getPackageObject(updating) | po = self.getPackageObject(updating, allow_missing=True) if po is None: continue | def update(self, po=None, requiringPo=None, **kwargs): """try to mark for update the item(s) specified. po is a package object - if that is there, mark it for update, if possible else use **kwargs to match the package needing update if nothing is specified at all then attempt to update everything returns the list of txmbr of the items it marked for update""" # check for args - if no po nor kwargs, do them all # if po, do it, ignore all else # if no po do kwargs # uninstalled pkgs called for update get returned with errors in a list, maybe? |
if not pid: return | def show_lock_owner(pid, logger): if not pid: return ps = get_process_info(pid) # This yumBackend isn't very friendly, so... if ps is not None and ps['name'] == 'yumBackend.py': nmsg = _(" The other application is: PackageKit") else: nmsg = _(" The other application is: %s") % ps['name'] logger.critical("%s", nmsg) logger.critical(_(" Memory : %5s RSS (%5sB VSZ)") % (format_number(int(ps['vmrss']) * 1024), format_number(int(ps['vmsize']) * 1024))) ago = seconds_to_ui_time(int(time.time()) - ps['start_time']) logger.critical(_(" Started: %s - %s ago") % (time.ctime(ps['start_time']), ago)) logger.critical(_(" State : %s, pid: %d") % (ps['state'], pid)) |
|
if ps is not None and ps['name'] == 'yumBackend.py': | if ps['name'] == 'yumBackend.py': | def show_lock_owner(pid, logger): if not pid: return ps = get_process_info(pid) # This yumBackend isn't very friendly, so... if ps is not None and ps['name'] == 'yumBackend.py': nmsg = _(" The other application is: PackageKit") else: nmsg = _(" The other application is: %s") % ps['name'] logger.critical("%s", nmsg) logger.critical(_(" Memory : %5s RSS (%5sB VSZ)") % (format_number(int(ps['vmrss']) * 1024), format_number(int(ps['vmsize']) * 1024))) ago = seconds_to_ui_time(int(time.time()) - ps['start_time']) logger.critical(_(" Started: %s - %s ago") % (time.ctime(ps['start_time']), ago)) logger.critical(_(" State : %s, pid: %d") % (ps['state'], pid)) |
raise URLGrabError(-1, _('Package does not match intended download')) | msg = _(_('Package does not match intended download. Suggestion: run yum clean metadata')) raise URLGrabError(-1, msg) | def verifyPkg(self, fo, po, raiseError): """verifies the package is what we expect it to be raiseError = defaults to 0 - if 1 then will raise a URLGrabError if the file does not check out. otherwise it returns false for a failure, true for success""" failed = False |
tid = extcmds[1] | tid = None if len(extcmds) > 1: tid = extcmds[1] | def historyAddonInfoCmd(self, extcmds): tid = extcmds[1] try: int(tid) except ValueError: self.logger.critical(_('No transaction ID given')) return 1, ['Failed history addon-info'] |
old = self.history.old(tids=[tid]) if old is None: | except TypeError: pass if tid is not None: old = self.history.old(tids=[tid]) else: old = [self.history.last(complete_transactions_only=False)] if old[0] is None: self.logger.critical(_('No transaction ID, or package, given')) return 1, ['Failed history addon-info'] if not old: | def historyAddonInfoCmd(self, extcmds): tid = extcmds[1] try: int(tid) except ValueError: self.logger.critical(_('No transaction ID given')) return 1, ['Failed history addon-info'] |
print 'Available additional history information:' | print _("Transaction ID:"), hist_data.tid print _('Available additional history information:') | def historyAddonInfoCmd(self, extcmds): tid = extcmds[1] try: int(tid) except ValueError: self.logger.critical(_('No transaction ID given')) return 1, ['Failed history addon-info'] |
print '%s: No additional data found by this name' % item | print _('%s: No additional data found by this name') % item | def historyAddonInfoCmd(self, extcmds): tid = extcmds[1] try: int(tid) except ValueError: self.logger.critical(_('No transaction ID given')) return 1, ['Failed history addon-info'] |
try: base.repos.populateSack() except yum.Errors.RepoError: if verbose: raise | if arg != 'disabled' or extcmds: try: base.repos.populateSack() base.pkgSack except yum.Errors.RepoError: if verbose: raise | def _num2ui_num(num): return to_unicode(locale.format("%d", num, True)) |
if arg != 'disabled' or verbose: base.pkgSack | def _num2ui_num(num): return to_unicode(locale.format("%d", num, True)) |
|
if not os.path.exists(logfile): f = open(logfile, 'w') os.chmod(logfile, 0600) f.close() | def setFileLog(uid, logfile): # TODO: When python's logging config parser doesn't blow up # when the user is non-root, put this in the config file. # syslog-style log if uid == 0: try: # For installroot etc. logdir = os.path.dirname(logfile) if not os.path.exists(logdir): os.makedirs(logdir, mode=0755) filelogger = logging.getLogger("yum.filelogging") filehandler = logging.FileHandler(logfile) formatter = logging.Formatter("%(asctime)s %(message)s", "%b %d %H:%M:%S") filehandler.setFormatter(formatter) filelogger.addHandler(filehandler) except IOError: logging.getLogger("yum").critical('Cannot open logfile %s', logfile) |
|
return -ret | return ret | def __cmp__(self, other): if other is None: return 1 ret = cmp(self.problem, other.problem) if ret: return -ret ret = cmp(self.rpid, other.rpid) return -ret |
my_st.st_mtime != mtime): | int(my_st.st_mtime) != int(mtime)): | def _ftype(mode): """ Given a "mode" return the name of the type of file. """ if stat.S_ISREG(mode): return "file" if stat.S_ISDIR(mode): return "directory" if stat.S_ISLNK(mode): return "symlink" if stat.S_ISFIFO(mode): return "fifo" if stat.S_ISCHR(mode): return "character device" if stat.S_ISBLK(mode): return "block device" return "<unknown>" |
prob.disk_value = my_st.st_mtime | prob.disk_value = int(my_st.st_mtime) | def _ftype(mode): """ Given a "mode" return the name of the type of file. """ if stat.S_ISREG(mode): return "file" if stat.S_ISDIR(mode): return "directory" if stat.S_ISLNK(mode): return "symlink" if stat.S_ISFIFO(mode): return "fifo" if stat.S_ISCHR(mode): return "character device" if stat.S_ISBLK(mode): return "block device" return "<unknown>" |
summary += _(' At least %dMB needed on the %s filesystem.\n') % (disk[k], k) | summary += _(' At least %dMB more space needed on the %s filesystem.\n') % (disk[k], k) | def errorSummary(self, errstring): """ parse the error string for 'interesting' errors which can be grouped, such as disk space issues """ summary = '' # do disk space report first p = re.compile('needs (\d+)MB on the (\S+) filesystem') disk = {} for m in p.finditer(errstring): if not disk.has_key(m.group(2)): disk[m.group(2)] = int(m.group(1)) if disk[m.group(2)] < int(m.group(1)): disk[m.group(2)] = int(m.group(1)) if disk: summary += _('Disk Requirements:\n') for k in disk: summary += _(' At least %dMB needed on the %s filesystem.\n') % (disk[k], k) |
errtring = str(depstring) | errstring = str(depstring) | def returnPackageByDep(self, depstring): """Pass in a generic [build]require string and this function will pass back the best(or first) package it finds providing that dep.""" # we get all sorts of randomness here errstring = depstring if type(depstring) not in types.StringTypes: errtring = str(depstring) try: pkglist = self.returnPackagesByDep(depstring) except Errors.YumBaseError: raise Errors.YumBaseError, _('No Package found for %s') % errstring ps = ListPackageSack(pkglist) result = self._bestPackageFromList(ps.returnNewestByNameArch()) if result is None: raise Errors.YumBaseError, _('No Package found for %s') % errstring return result |
obsoleting = thispkgobsdict[po.pkgtup][0] | obsoleting = thispkgobsdict[po.pkgtup] oobsoleting = [] for opkgtup in obsoleting: if not canCoinstall(po.arch, opkgtup[1]): oobsoleting.append(opkgtup) if oobsoleting: obsoleting = oobsoleting obsoleting = obsoleting[0] | def _pkg2obspkg(self, po): """ Given a package return the package it's obsoleted by and so we should install instead. Or None if there isn't one. """ thispkgobsdict = self.up.checkForObsolete([po.pkgtup]) if po.pkgtup in thispkgobsdict: obsoleting = thispkgobsdict[po.pkgtup][0] obsoleting_pkg = self.getPackageObject(obsoleting) return obsoleting_pkg return None |
self.base.ts.scriptFd = self._writepipe.fileno() | self.base.ts.ts.scriptFd = self._writepipe.fileno() | def _setupOutputLogging(self, rpmverbosity="info"): # UGLY... set up the transaction to record output from scriptlets io_r = tempfile.NamedTemporaryFile() self._readpipe = io_r self._writepipe = open(io_r.name, 'w+b') self.base.ts.scriptFd = self._writepipe.fileno() rpmverbosity = {'critical' : 'crit', 'emergency' : 'emerg', 'error' : 'err', 'information' : 'info', 'warn' : 'warning'}.get(rpmverbosity, rpmverbosity) rpmverbosity = 'RPMLOG_' + rpmverbosity.upper() if not hasattr(rpm, rpmverbosity): rpmverbosity = 'RPMLOG_INFO' rpm.setVerbosity(getattr(rpm, rpmverbosity)) rpm.setLogFile(self._writepipe) |
to_unicode(str(problem)))) | uproblem)) | def _trans_rpmdb_problem(self, problem): if not hasattr(self, '_tid'): return # Not configured to run cur = self._get_cursor() if cur is None or not self._update_db_file_2(): return None res = executeSQL(cur, """INSERT INTO trans_rpmdb_problems (tid, problem, msg) VALUES (?, ?, ?)""", (self._tid, problem.problem, to_unicode(str(problem)))) rpid = cur.lastrowid |
except plugins.PluginYumExit, e: self.logger.critical(_('PluginExit Error: %s'), e) sys.exit(1) | def doUtilConfigSetup(self,args = sys.argv[1:],pluginsTypes=(plugins.TYPE_CORE,)): # Parse only command line options that affect basic yum setup opts = self._parser.firstParse(args) # Just print out the version if that's what the user wanted if opts.version: self._printUtilVersion() sys.exit(0) # get the install root to use root = self._parser.getRoot(opts) if opts.quiet: opts.debuglevel = 0 if opts.verbose: opts.debuglevel = opts.errorlevel = 6 # Read up configuration options and initialise plugins try: pc = self.preconf pc.fn = opts.conffile pc.root = root pc.init_plugins = not opts.noplugins pc.plugin_types = pluginsTypes pc.optparser = self._parser pc.debuglevel = opts.debuglevel pc.errorlevel = opts.errorlevel if hasattr(opts, "disableplugins"): pc.disabled_plugins =self._parser._splitArg(opts.disableplugins) if hasattr(opts, "enableplugins"): pc.enabled_plugins = self._parser._splitArg(opts.enableplugins) self.conf |
|
repo.populate(parser, section, self.conf) | try: repo.populate(parser, section, self.conf) except ValueError, e: msg = _('Repository %r: Error parsing config: %s' % (section,e)) raise Errors.ConfigError, msg | def readRepoConfig(self, parser, section): '''Parse an INI file section for a repository. |
if not key_installed: raise Errors.YumBaseError, \ _('The GPG keys listed for the "%s" repository are ' \ 'already installed but they are not correct for this ' \ 'package.\n' \ 'Check that the correct key URLs are configured for ' \ 'this repository.') % (repo.name) | if not key_installed: raise Errors.YumBaseError, \ _('The GPG keys listed for the "%s" repository are ' \ 'already installed but they are not correct.\n' \ 'Check that the correct key URLs are configured for ' \ 'this repository.') % (repo.name) | def getKeyForRepo(self, repo, callback=None): """ Retrieve a key for a repository If needed, prompt for if the key should be imported using callback @param repo: Repository object to retrieve the key of. @param callback: Callback function to use for asking for verification of a key. Takes a dictionary of key info. """ keyurls = repo.gpgkey key_installed = False for keyurl in keyurls: keys = self._retrievePublicKey(keyurl, repo) for info in keys: # Check if key is already installed if info['keyid'] in misc.return_keyids_from_pubring(repo.gpgdir): self.logger.info(_('GPG key at %s (0x%s) is already imported') % ( keyurl, info['hexkeyid'])) continue |
print fmt % (utf8_width_fill(name, 22, 22), | print fmt % (utf8_width_fill(name, 26, 26), | def historySummaryCmd(self, extcmds): tids, printall = self._history_list_transactions(extcmds) if tids is None: return 1, ['Failed history info'] |
if self.ftype == 'symlnk' and vflags & _RPMVERIFY_LINKTO: | if self.ftype == 'symlink' and vflags & _RPMVERIFY_LINKTO: | def __init__(self, fi, filetuple, csum_type, override_vflags=False): YUMVerifyPackageFile.__init__(self, filetuple[0]) |
self.basecmd = self.cmds[0] | if self.cmds: self.basecmd = self.cmds[0] else: self.basecmd = None | def doUtilConfigSetup(self,args = sys.argv[1:],pluginsTypes=(plugins.TYPE_CORE,)): # Parse only command line options that affect basic yum setup opts = self._parser.firstParse(args) # Just print out the version if that's what the user wanted if opts.version: self._printUtilVersion() sys.exit(0) # get the install root to use root = self._parser.getRoot(opts) if opts.quiet: opts.debuglevel = 0 if opts.verbose: opts.debuglevel = opts.errorlevel = 6 # Read up configuration options and initialise plugins try: pc = self.preconf pc.fn = opts.conffile pc.root = root pc.init_plugins = not opts.noplugins pc.plugin_types = pluginsTypes pc.optparser = self._parser pc.debuglevel = opts.debuglevel pc.errorlevel = opts.errorlevel if hasattr(opts, "disableplugins"): pc.disabled_plugins =self._parser._splitArg(opts.disableplugins) if hasattr(opts, "enableplugins"): pc.enabled_plugins = self._parser._splitArg(opts.enableplugins) self.conf |
self.verbose_logger.log(yum.logginglevels.INFO_2, msg) | self.verbose_logger.log(yum.logginglevels.INFO_2, to_unicode(msg)) | def _maybeYouMeant(self, arg): """ If install argument doesn't match with case, tell the user. """ matches = self.doPackageLists(patterns=[arg], ignore_case=True) matches = matches.installed + matches.available matches = set(map(lambda x: x.name, matches)) if matches: msg = self.fmtKeyValFill(_(' * Maybe you meant: '), ", ".join(matches)) self.verbose_logger.log(yum.logginglevels.INFO_2, msg) |
if needmode in ['ud', 'od']: | if needmode in ['ud']: self.verbose_logger.log(logginglevels.DEBUG_2, _('Trying to update %s to resolve dep'), requiringPo) origobs = self.conf.obsoletes self.conf.obsoletes = 0 txmbrs = self.update(po=requiringPo, requiringPo=requiringPo) self.conf.obsoletes = origobs if not txmbrs: txmbrs = self.update(po=requiringPo, requiringPo=requiringPo) if not txmbrs: msg = self._err_missing_requires(requiringPo, requirement) self.verbose_logger.log(logginglevels.DEBUG_2, _('No update paths found for %s. Failure!'), requiringPo) return self._requiringFromTransaction(requiringPo, requirement, errorlist) checkdeps = 1 if needmode in ['od']: | def _requiringFromInstalled(self, requiringPo, requirement, errorlist): """processes the dependency resolution for a dep where the requiring package is installed""" |
txmbrs = self.matchNaevr(na[0], na[1]) | if len(na) == 2: txmbrs = self.matchNaevr(na[0], na[1]) | def deselect(self, pattern): """ Remove these packages from the transaction. This is more user orientated than .remove(). Used from kickstart/install -blah. """ |
if self.pkgSack is not None: | if self.pkgSack is None: | def deselect(self, pattern): """ Remove these packages from the transaction. This is more user orientated than .remove(). Used from kickstart/install -blah. """ |
pkgs = self.pkgSack.returnPackages(pattern) | pkgs = self.pkgSack.returnPackages(patterns=[pattern]) | def deselect(self, pattern): """ Remove these packages from the transaction. This is more user orientated than .remove(). Used from kickstart/install -blah. """ |
pkgs = self.rpmdb.returnPackages(pattern) | pkgs = self.rpmdb.returnPackages(patterns=[pattern]) | def deselect(self, pattern): """ Remove these packages from the transaction. This is more user orientated than .remove(). Used from kickstart/install -blah. """ |
msg = _('Package does not match intended download. Suggestion: run yum clean metadata') | msg = _('Package does not match intended download. Suggestion: run yum --enablerepo=%s clean metadata') % po.repo.id | def verifyPkg(self, fo, po, raiseError): """verifies the package is what we expect it to be raiseError = defaults to 0 - if 1 then will raise a URLGrabError if the file does not check out. otherwise it returns false for a failure, true for success""" failed = False |
thesecerts = decode_msg(block) | thesecerts = decode_msg(block, multi=True) | def decode_multiple_keys(msg): #ditto of above - but handling multiple certs/keys per file certs = [] pgpkey_lines = map(lambda x : x.rstrip(), msg.split('\n')) in_block = 0 block = '' for l in pgpkey_lines : if not in_block : if l == '-----BEGIN PGP PUBLIC KEY BLOCK-----' : in_block = 1 block += '%s\n' % l continue block += '%s\n' % l if l == '-----END PGP PUBLIC KEY BLOCK-----': in_block = 0 thesecerts = decode_msg(block) if thesecerts: certs.extend(thesecerts) block = '' continue return certs |
if 'checksum_type' in yumdb and 'checksum_type' in yumdb: | if 'checksum_type' in yumdb and 'checksum_data' in yumdb: | def _ipkg2pid(self, po): csum = None yumdb = po.yumdb_info if 'checksum_type' in yumdb and 'checksum_type' in yumdb: csum = "%s:%s" % (yumdb.checksum_type, yumdb.checksum_data) return self._pkgtup2pid(po.pkgtup, csum) |
self.rpmdb.dropCachedData() | def buildTransaction(self, unfinished_transactions_check=True): """go through the packages in the transaction set, find them in the packageSack or rpmdb, and pack up the ts accordingly""" if (unfinished_transactions_check and misc.find_unfinished_transactions(yumlibpath=self.conf.persistdir)): msg = _('There are unfinished transactions remaining. You might ' \ 'consider running yum-complete-transaction first to finish them.' ) self.logger.critical(msg) self.yumUtilsMsg(self.logger.critical, "yum-complete-transaction") time.sleep(3) # XXX - we could add a conditional here to avoid running the plugins and # limit_installonly_pkgs, etc - if we're being run from yum-complete-transaction # and don't want it to happen. - skv self.plugins.run('preresolve') ds_st = time.time() |
|
if self.conf.history_record and not self.ts.isTsFlagSet(rpm.RPMTRANS_FLAG_TEST): | if (not self.conf.history_record or self.ts.isTsFlagSet(rpm.RPMTRANS_FLAG_TEST)): frpmdbv = self.tsInfo.futureRpmDBVersion() else: | def runTransaction(self, cb): """takes an rpm callback object, performs the transaction""" |
self.rpmdb.transactionResultVersion(self.tsInfo.futureRpmDBVersion()) | self.rpmdb.transactionResultVersion(frpmdbv) | def runTransaction(self, cb): """takes an rpm callback object, performs the transaction""" |
self.rpmdb.dropCachedData() | self.rpmdb.dropCachedDataPostTransaction(list(self.tsInfo)) | def runTransaction(self, cb): """takes an rpm callback object, performs the transaction""" |
self.rpmdb.dropCachedData() | def verifyTransaction(self, resultobject=None): """checks that the transaction did what we expected it to do. Also propagates our external yumdb info""" # check to see that the rpmdb and the tsInfo roughly matches # push package object metadata outside of rpmdb into yumdb # delete old yumdb metadata entries # for each pkg in the tsInfo # if it is an install - see that the pkg is installed # if it is a remove - see that the pkg is no longer installed, provided # that there is not also an install of this pkg in the tsInfo (reinstall) # for any kind of install add from_repo to the yumdb, and the cmdline # and the install reason vt_st = time.time() self.rpmdb.dropCachedData() self.plugins.run('preverifytrans') for txmbr in self.tsInfo: if txmbr.output_state in TS_INSTALL_STATES: if not self.rpmdb.contains(po=txmbr.po): # maybe a file log here, too # but raising an exception is not going to do any good self.logger.critical(_('%s was supposed to be installed' \ ' but is not!' % txmbr.po)) continue po = self.getInstalledPackageObject(txmbr.pkgtup) rpo = txmbr.po po.yumdb_info.from_repo = rpo.repoid po.yumdb_info.reason = txmbr.reason po.yumdb_info.releasever = self.conf.yumvar['releasever'] if hasattr(self, 'args') and self.args: po.yumdb_info.command_line = ' '.join(self.args) elif hasattr(self, 'cmds') and self.cmds: po.yumdb_info.command_line = ' '.join(self.cmds) csum = rpo.returnIdSum() if csum is not None: po.yumdb_info.checksum_type = str(csum[0]) po.yumdb_info.checksum_data = str(csum[1]) |
|
self.history.end(self.rpmdb.simpleVersion(main_only=True)[0], ret) | self.history.end(rpmdbv, ret) | def verifyTransaction(self, resultobject=None): """checks that the transaction did what we expected it to do. Also propagates our external yumdb info""" # check to see that the rpmdb and the tsInfo roughly matches # push package object metadata outside of rpmdb into yumdb # delete old yumdb metadata entries # for each pkg in the tsInfo # if it is an install - see that the pkg is installed # if it is a remove - see that the pkg is no longer installed, provided # that there is not also an install of this pkg in the tsInfo (reinstall) # for any kind of install add from_repo to the yumdb, and the cmdline # and the install reason vt_st = time.time() self.rpmdb.dropCachedData() self.plugins.run('preverifytrans') for txmbr in self.tsInfo: if txmbr.output_state in TS_INSTALL_STATES: if not self.rpmdb.contains(po=txmbr.po): # maybe a file log here, too # but raising an exception is not going to do any good self.logger.critical(_('%s was supposed to be installed' \ ' but is not!' % txmbr.po)) continue po = self.getInstalledPackageObject(txmbr.pkgtup) rpo = txmbr.po po.yumdb_info.from_repo = rpo.repoid po.yumdb_info.reason = txmbr.reason po.yumdb_info.releasever = self.conf.yumvar['releasever'] if hasattr(self, 'args') and self.args: po.yumdb_info.command_line = ' '.join(self.args) elif hasattr(self, 'cmds') and self.cmds: po.yumdb_info.command_line = ' '.join(self.cmds) csum = rpo.returnIdSum() if csum is not None: po.yumdb_info.checksum_type = str(csum[0]) po.yumdb_info.checksum_data = str(csum[1]) |
VALUES (?, ?)""", (self._tid, cmdline)) | VALUES (?, ?)""", (self._tid, to_unicode(cmdline))) | def _trans_cmdline(self, cmdline): if not hasattr(self, '_tid'): return # Not configured to run cur = self._get_cursor() if cur is None or not self._update_db_file_2(): return None res = executeSQL(cur, """INSERT INTO trans_cmdline (tid, cmdline) VALUES (?, ?)""", (self._tid, cmdline)) return cur.lastrowid |
shell=True, bufsize=-1, stdin=PIPE, | bufsize=-1, stdin=PIPE, | def _ftype(mode): """ Given a "mode" return the name of the type of file. """ if stat.S_ISREG(mode): return "file" if stat.S_ISDIR(mode): return "directory" if stat.S_ISLNK(mode): return "symlink" if stat.S_ISFIFO(mode): return "fifo" if stat.S_ISCHR(mode): return "character device" if stat.S_ISBLK(mode): return "block device" return "<unknown>" |
my_csum = misc.checksum(csum_type, fp) | my_csum = tcsum | def _ftype(mode): """ Given a "mode" return the name of the type of file. """ if stat.S_ISREG(mode): return "file" if stat.S_ISDIR(mode): return "directory" if stat.S_ISLNK(mode): return "symlink" if stat.S_ISFIFO(mode): return "fifo" if stat.S_ISCHR(mode): return "character device" if stat.S_ISBLK(mode): return "block device" return "<unknown>" |
for res in prob.res: | for res in prob.conflicts: | def _rpmdb_warn_checks(self, out=None, warn=True, chkcmd=None, header=None, ignore_pkgs=[]): if out is None: out = self.logger.warning if chkcmd is None: chkcmd = ['dependencies', 'duplicates'] if header is None: # FIXME: _N() msg = _("** Found %d pre-existing rpmdb problem(s)," " 'yum check' output follows:") header = lambda problems: not problems or out(msg % problems) if warn: out(_('Warning: RPMDB altered outside of yum.')) |
CREATE VIEW vtrans_prob_pkgs AS | CREATE VIEW vtrans_prob_pkgs2 AS | def search(self, patterns, ignore_case=True): """ Search for history transactions which contain specified packages al. la. "yum list". Returns transaction ids. """ # Search packages ... kind of sucks that it's search not list, pkglist? |
main, | main,problem,msg, | def search(self, patterns, ignore_case=True): """ Search for history transactions which contain specified packages al. la. "yum list". Returns transaction ids. """ # Search packages ... kind of sucks that it's search not list, pkglist? |
FROM (trans_prob_pkgs JOIN trans_rpmdb_problems USING(rpid)) JOIN pkgtups USING(pkgtupid) | FROM (SELECT * FROM trans_prob_pkgs,trans_rpmdb_problems WHERE trans_prob_pkgs.rpid=trans_rpmdb_problems.rpid) JOIN pkgtups USING(pkgtupid) | def search(self, patterns, ignore_case=True): """ Search for history transactions which contain specified packages al. la. "yum list". Returns transaction ids. """ # Search packages ... kind of sucks that it's search not list, pkglist? |
results = self.update(requiringPo=requiringPo, name=pkg.name, epoch=pkg.epoch, version=pkg.version, rel=pkg.rel) | tresults = self.update(requiringPo=requiringPo, name=pkg.name, epoch=pkg.epoch, version=pkg.version, rel=pkg.rel) | def _requiringFromTransaction(self, requiringPo, requirement, errorlist): """processes the dependency resolution for a dep where requiring package is in the transaction set""" (name, arch, epoch, version, release) = requiringPo.pkgtup (needname, needflags, needversion) = requirement checkdeps = 0 missingdep = 0 upgraded = {} |
self.yumdb = RPMDBAdditionalData(db_path=addldb_path) | version_path = os.path.normpath(cachedir + '/version') self.yumdb = RPMDBAdditionalData(db_path=addldb_path, version_path=version_path) | def __init__(self, root='/', releasever=None, cachedir=None, persistdir='/var/lib/yum'): self.root = root self._idx2pkg = {} self._name2pkg = {} self._pkgnames_loaded = set() self._tup2pkg = {} self._completely_loaded = False self._pkgname_fails = set() self._pkgmatch_fails = set() self._provmatch_fails = set() self._simple_pkgtup_list = [] self._get_pro_cache = {} self._get_req_cache = {} self._loaded_gpg_keys = False if cachedir is None: cachedir = persistdir + "/rpmdb-indexes" self.setCacheDir(cachedir) if not os.path.normpath(persistdir).startswith(self.root): self._persistdir = root + '/' + persistdir else: self._persistdir = persistdir self._have_cached_rpmdbv_data = None self._cached_conflicts_data = None # Store the result of what happens, if a transaction completes. self._trans_cache_store = {} self.ts = None self.releasever = releasever self.auto_close = False # this forces a self.ts.close() after # most operations so it doesn't leave # any lingering locks. self._cached_rpmdb_mtime = None |
def __init__(self, db_path='/var/lib/yum/yumdb'): | def __init__(self, db_path='/var/lib/yum/yumdb', version_path=None): | def __init__(self, db_path='/var/lib/yum/yumdb'): self.conf = misc.GenericHolder() self.conf.db_path = db_path self.conf.writable = False self._packages = {} # pkgid = dir if not os.path.exists(self.conf.db_path): try: os.makedirs(self.conf.db_path) except (IOError, OSError), e: # some sort of useful thing here? A warning? return self.conf.writable = True else: if os.access(self.conf.db_path, os.W_OK): self.conf.writable = True # Don't call _load_all_package_paths to preload, as it's expensive # if the dirs. aren't in cache. self.yumdb_cache = {'attr' : {}} |
ts = self.rpmdb.readOnlyTS() | def getKeyForPackage(self, po, askcb = None, fullaskcb = None): """ Retrieve a key for a package. If needed, prompt for if the key should be imported using askcb. @param po: Package object to retrieve the key of. @param askcb: Callback function to use for asking for verification. Takes arguments of the po, the userid for the key, and the keyid. @param fullaskcb: Callback function to use for asking for verification of a key. Differs from askcb in that it gets passed a dictionary so that we can expand the values passed. """ repo = self.repos.getRepo(po.repoid) keyurls = repo.gpgkey key_installed = False |
|
if arg == 'all': ehibeg = base.term.FG_COLOR['green'] + base.term.MODE['bold'] dhibeg = base.term.FG_COLOR['red'] hiend = base.term.MODE['normal'] else: ehibeg = '' dhibeg = '' hiend = '' | on_ehibeg = base.term.FG_COLOR['green'] + base.term.MODE['bold'] on_dhibeg = base.term.FG_COLOR['red'] on_hiend = base.term.MODE['normal'] | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
if arg != 'all': ui_enabled = '' ui_endis_wid = 0 | (ehibeg, dhibeg, hiend) = '', '', '' ui_enabled = '' ui_endis_wid = 0 ui_num = "" ui_excludes_num = '' force_show = False if arg == 'all' or repo.id in extcmds or repo.name in extcmds: force_show = True (ehibeg, dhibeg, hiend) = (on_ehibeg, on_dhibeg, on_hiend) | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
if arg == 'all': ui_enabled = ehibeg + _('enabled') + hiend + ": " ui_endis_wid = utf8_width(_('enabled')) + 2 num = len(repo.sack) tot_num += num ui_num = to_unicode(locale.format("%d", num, True)) | if arg == 'enabled': force_show = False elif arg == 'disabled' and not force_show: continue if force_show or verbose: ui_enabled = ehibeg + _('enabled') + hiend ui_endis_wid = utf8_width(_('enabled')) if not verbose: ui_enabled += ": " ui_endis_wid += 2 | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
ui_num = "" if (arg == 'all' or (arg == 'enabled' and enabled) or (arg == 'disabled' and not enabled)): | if True: | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
base.fmtKeyValFill(_("Repo-name : "), repo.name), base.fmtKeyValFill(_("Repo-status : "), ui_enabled)] | base.fmtKeyValFill(_("Repo-name : "), repo.name)] if force_show or extcmds: out += [base.fmtKeyValFill(_("Repo-status : "), ui_enabled)] | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
num = locale.format("%d", repo.metadata_expire, True) num = _("%s second(s) (last: %s)") % (misc.to_unicode(num), last) | num = _num2ui_num(repo.metadata_expire) num = _("%s second(s) (last: %s)") % (num, last) | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
ct_len = 0 | st_len = 0 | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
if ct_len < ui_endis_wid: ct_len = ui_endis_wid | if st_len < (ui_endis_wid + len(ui_num)): st_len = (ui_endis_wid + len(ui_num)) | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
elif utf8_width(_('status')) > ct_len + ui_len: | elif utf8_width(_('status')) > st_len: | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
left = base.term.columns - (id_len + ct_len + ui_len + 2) | left = base.term.columns - (id_len + st_len + 2) | def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False |
return mysqldump_command ("-u%s %s%s --add-drop-table --default-character-set=utf8 %s" % (user, "-p" if password else "", password, db)) | host = config["db_host"] return mysqldump_command ("-u%s %s%s %s --add-drop-table --default-character-set=utf8 %s" % (user, "-p" if password else "", password, "-h"+host if host <> 'localhost' else "", db)) | def restore_point(): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] return mysqldump_command ("-u%s %s%s --add-drop-table --default-character-set=utf8 %s" % (user, "-p" if password else "", password, db)) |
return mysqldump_command ("--no-data --compact -u%s %s%s --default-character-set=utf8 %s" % (user, "-p" if password else "", password, db)) | host = config["db_host"] return mysqldump_command ("--no-data --add-lock=false --compact -u%s %s%s %s --default-character-set=utf8 %s" % (user, "-p" if password else "", password, "-h"+host if host <> 'localhost' else "", db)) | def dump(): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] return mysqldump_command ("--no-data --compact -u%s %s%s --default-character-set=utf8 %s" % (user, "-p" if password else "", password, db)) |
(output, errors) = mysql_command ("-u%s %s%s --default-character-set=utf8 %s < %s" % (user, "-p" if password else "", password, db, tempfile)) | (output, errors) = mysql_command ("-u%s %s%s %s --default-character-set=utf8 %s < %s" % (user, "-p" if password else "", password, "-h"+host if host <> 'localhost' else "", db, tempfile)) | def load (sql): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] tempfile = ".temp-mygrate-%s" % str(datetime.time()).replace (':', '_') f = open (tempfile, 'w') f.write (sql) f.close() (output, errors) = mysql_command ("-u%s %s%s --default-character-set=utf8 %s < %s" % (user, "-p" if password else "", password, db, tempfile)) os.unlink(tempfile) if errors: raise SQLLoadError (sql = sql, errors = errors) return True |
self.old_restrictions = ["", "", "", "", "", "", "%d" % DEFAULT_MAP_WIDTH, default_font] | self.old_restrictions = ["", "", "", "", "", "", "", "%d" % DEFAULT_MAP_WIDTH, default_font] | def __init__(self, driver, title): default_restriction = 4 default_font = "Anonymous Pro,DejaVu Sans Mono,Consolas,Lucida Console,monospace 8" |
'\x0c\x0c\x0c\x0c\x0c' | '\x0c\x0c\x0c\x0c\x0c\x0c' | def test_export_ps(self): r''' >>> import sys >>> context = Context() >>> document = context.new_document(FileUri(images + 'test0.djvu')) >>> message = document.get_message() >>> type(message) == DocInfoMessage True >>> document.decoding_done True >>> document.decoding_error False >>> document.decoding_status == JobOK True >>> document.type == DOCUMENT_TYPE_BUNDLED True >>> len(document.pages) 6 >>> len(document.files) 7 |
' 3' | ' 3\x0c' | def test_export_ps(self): r''' >>> import sys >>> context = Context() >>> document = context.new_document(FileUri(images + 'test0.djvu')) >>> message = document.get_message() >>> type(message) == DocInfoMessage True >>> document.decoding_done True >>> document.decoding_error False >>> document.decoding_status == JobOK True >>> document.type == DOCUMENT_TYPE_BUNDLED True >>> len(document.pages) 6 >>> len(document.files) 7 |
self.make_file(depends, target, distutils.spawn.spawn, [['cython', source]]) | def build_c(source, target): distutils.spawn.spawn(['cython', source]) distutils.spawn.spawn(['sed', '-i~', '-e', r's/\(static int __Pyx_GetVtable(PyObject [*]dict, void [*]vtabptr) {\)/\1 return 0;/', target ]) self.make_file(depends, target, build_c, [source, target]) | def cython_sources(self, ext): targets = {} deps = [] for source in ext.sources: assert source.endswith('.pyx') target = '%s.c' % source[:-4] yield target depends = [source, self.config_filename] + ext.depends if not (self.force or distutils.dep_util.newer_group(depends, target)): distutils.log.debug('not cythoning %r (up-to-date)', ext.name) continue distutils.log.info('cythoning %r extension', ext.name) self.make_file(depends, target, distutils.spawn.spawn, [['cython', source]]) |
for wildcard in 'djvu/*.c', 'djvu/config.pxi': | for wildcard in 'djvu/*.c', 'djvu/*.c~', 'djvu/config.pxi': | def run(self): if self.all: for wildcard in 'djvu/*.c', 'djvu/config.pxi': filenames = glob.glob(wildcard) if filenames: distutils.log.info('removing %r', wildcard) if self.dry_run: continue for filename in glob.glob(wildcard): os.remove(filename) return distutils.command.clean.clean.run(self) |
def set_cache_size(n): context.cache_size = n | def test_context_cache(): def set_cache_size(n): context.cache_size = n context = Context() assert_equal(context.cache_size, 10 << 20) for n in -100, 0, 1 << 31: with raises(ValueError, '0 < cache_size < (2 ** 31) must be satisfied'): set_cache_size(n) with raises(ValueError, '0 < cache_size < (2 ** 31) must be satisfied'): set_cache_size(0) n = 1 while n < (1 << 31): set_cache_size(n) assert_equal(context.cache_size, n) n = (n + 1) * 2 - 1 context.clear_cache() |
|
set_cache_size(n) | context.cache_size = n | def set_cache_size(n): context.cache_size = n |
set_cache_size(0) | context.cache_size = 0 | def set_cache_size(n): context.cache_size = n |
def test_new(self): | def test_bad_new(self): | def test_new(self): with raises(TypeError, "cannot create 'djvu.decode.Document' instances"): Document() |
class test_pixel_formats: def test_new(self): | class test_pixel_formats(): def test_bad_new(self): | def test_export_ps(self): context = Context() document = context.new_document(FileUri(images + 'test0.djvu')) message = document.get_message() assert_equal(type(message), DocInfoMessage) assert_true(document.decoding_done) assert_false(document.decoding_error) assert_equal(document.decoding_status, JobOK) assert_equal(document.type, DOCUMENT_TYPE_BUNDLED) assert_equal(len(document.pages), 6) assert_equal(len(document.files), 7) |
class test_page_jobs: def test_new(self): | class test_page_jobs(): def test_bad_new(self): | def test_packed_bits(self): pf = PixelFormatPackedBits('<') assert_equal(repr(pf), "djvu.decode.PixelFormatPackedBits('<')") assert_equal(pf.bpp, 1) pf = PixelFormatPackedBits('>') assert_equal(repr(pf), "djvu.decode.PixelFormatPackedBits('>')") assert_equal(pf.bpp, 1) |
def test_new(self): | def test_bad_new(self): | def test_new(self): with raises(TypeError, "cannot create 'djvu.decode.Message' instances"): Message() |
def test_bad_construction(self): | def test_bad_new(self): | def test_bad_construction(self): with raises(TypeError, "Argument 'document' has incorrect type (expected djvu.decode.Document, got NoneType)"): Stream(None, 42) |
changelog = open(os.path.join('doc', 'changelog')) | if sys.version_info >= (3, 0): extra = dict(encoding='UTF-8') else: extra = {} changelog = open(os.path.join('doc', 'changelog'), **extra) | def get_version(): changelog = open(os.path.join('doc', 'changelog')) try: return changelog.readline().split()[1].strip('()') finally: changelog.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.