def filter_unknown_bug_ids(self, node, ids): '''filter bug ids from list that already refer to this changeset.''' self.run('''select bug_id from longdescs where bug_id in %s and thetext like "%%%s%%"''' % (buglist(ids), short(node))) unknown = set(ids) for (id,) in self.cursor.fetchall(): self.ui.status(_('bug %d already knows about changeset %s\n') % (id, short(node))) unknown.discard(id) return sorted(unknown)
def sigwalk(repo): """ walk over every sigs, yields a couple ((node, version, sig), (filename, linenumber)) """ def parsefile(fileiter, context): ln = 1 for l in fileiter: if not l: continue yield (l.split(" ", 2), (context, ln)) ln += 1 # read the heads fl = repo.file(".hgsigs") for r in reversed(fl.heads()): fn = ".hgsigs|%s" % hgnode.short(r) for item in parsefile(fl.read(r).splitlines(), fn): yield item try: # read local signatures fn = "localsigs" for item in parsefile(repo.opener(fn), fn): yield item except IOError: pass
def catcommit(ui, repo, n, prefix, ctx=None): nlprefix = '\n' + prefix if ctx is None: ctx = repo[n] ui.write("tree %s\n" % short(ctx.changeset()[0])) # use ctx.node() instead ?? for p in ctx.parents(): ui.write("parent %s\n" % p) date = ctx.date() description = ctx.description().replace("\0", "") lines = description.splitlines() if lines and lines[-1].startswith('committer:'): committer = lines[-1].split(': ')[1].rstrip() else: committer = ctx.user() ui.write("author %s %s %s\n" % (ctx.user(), int(date[0]), date[1])) ui.write("committer %s %s %s\n" % (committer, int(date[0]), date[1])) ui.write("revision %d\n" % ctx.rev()) ui.write("branch %s\n\n" % ctx.branch()) if prefix != "": ui.write("%s%s\n" % (prefix, description.replace('\n', nlprefix).strip())) else: ui.write(description + "\n") if prefix: ui.write('\0')
def archive(web, req, tmpl): type_ = req.form.get('type', [None])[0] allowed = web.configlist("web", "allow_archive") key = req.form['node'][0] if type_ not in web.archives: msg = 'Unsupported archive type: %s' % type_ raise ErrorResponse(HTTP_NOT_FOUND, msg) if not ((type_ in allowed or web.configbool("web", "allow" + type_, False))): msg = 'Archive type not allowed: %s' % type_ raise ErrorResponse(HTTP_FORBIDDEN, msg) reponame = re.sub(r"\W+", "-", os.path.basename(web.reponame)) cnode = web.repo.lookup(key) arch_version = key if cnode == key or key == 'tip': arch_version = short(cnode) name = "%s-%s" % (reponame, arch_version) mimetype, artype, extension, encoding = web.archive_specs[type_] headers = [('Content-Type', mimetype), ('Content-Disposition', 'attachment; filename=%s%s' % (name, extension))] if encoding: headers.append(('Content-Encoding', encoding)) req.header(headers) req.respond(HTTP_OK) archival.archive(web.repo, req, cnode, artype, prefix=name) return []
def fileelems(self): n = self.ctx.node() f = self.cia.repo.status(self.ctx.parents()[0].node(), n) url = self.url or '' elems = [] for path in f[0]: uri = '%s/diff/%s/%s' % (url, short(n), path) elems.append(self.fileelem(path, url and uri, 'modify')) for path in f[1]: # TODO: copy/rename ? uri = '%s/file/%s/%s' % (url, short(n), path) elems.append(self.fileelem(path, url and uri, 'add')) for path in f[2]: elems.append(self.fileelem(path, '', 'remove')) return '\n'.join(elems)
def __difftree(repo, node1, node2, files=[]): assert node2 is not None mmap = repo[node1].manifest() mmap2 = repo[node2].manifest() m = cmdutil.match(repo, files) modified, added, removed = repo.status(node1, node2, m)[:3] empty = short(nullid) for f in modified: # TODO get file permissions ui.write(":100664 100664 %s %s M\t%s\t%s\n" % (short(mmap[f]), short(mmap2[f]), f, f)) for f in added: ui.write(":000000 100664 %s %s N\t%s\t%s\n" % (empty, short(mmap2[f]), f, f)) for f in removed: ui.write(":100664 000000 %s %s D\t%s\t%s\n" % (short(mmap[f]), empty, f, f))
def snapshot(ui, repo, files, node, tmproot): '''snapshot files as of some revision if not using snapshot, -I/-X does not work and recursive diff in tools like kdiff3 and meld displays too many files.''' dirname = os.path.basename(repo.root) if dirname == "": dirname = "root" if node is not None: dirname = '%s.%s' % (dirname, short(node)) base = os.path.join(tmproot, dirname) os.mkdir(base) if node is not None: ui.note( _('making snapshot of %d files from rev %s\n') % (len(files), short(node))) else: ui.note( _('making snapshot of %d files from working directory\n') % (len(files))) wopener = util.opener(base) fns_and_mtime = [] ctx = repo[node] for fn in files: wfn = util.pconvert(fn) if not wfn in ctx: # File doesn't exist; could be a bogus modify continue ui.note(' %s\n' % wfn) dest = os.path.join(base, wfn) fctx = ctx[wfn] data = repo.wwritedata(wfn, fctx.data()) if 'l' in fctx.flags(): wopener.symlink(data, wfn) else: wopener(wfn, 'w').write(data) if 'x' in fctx.flags(): util.set_flags(dest, False, True) if node is None: fns_and_mtime.append( (dest, repo.wjoin(fn), os.path.getmtime(dest))) return dirname, fns_and_mtime
def check(ui, repo, rev): """verify all the signatures there may be for a particular revision""" mygpg = newgpg(ui) rev = repo.lookup(rev) hexrev = hgnode.hex(rev) keys = [] for data, context in sigwalk(repo): node, version, sig = data if node == hexrev: k = getkeys(ui, repo, mygpg, data, context) if k: keys.extend(k) if not keys: ui.write(_("No valid signature for %s\n") % hgnode.short(rev)) return # print summary ui.write("%s is signed by:\n" % hgnode.short(rev)) for key in keys: ui.write(" %s\n" % keystr(ui, key))
def graph(web, req, tmpl): rev = webutil.changectx(web.repo, req).rev() bg_height = 39 revcount = web.maxshortchanges if 'revcount' in req.form: revcount = int(req.form.get('revcount', [revcount])[0]) tmpl.defaults['sessionvars']['revcount'] = revcount lessvars = copy.copy(tmpl.defaults['sessionvars']) lessvars['revcount'] = revcount / 2 morevars = copy.copy(tmpl.defaults['sessionvars']) morevars['revcount'] = revcount * 2 max_rev = len(web.repo) - 1 revcount = min(max_rev, revcount) revnode = web.repo.changelog.node(rev) revnode_hex = hex(revnode) uprev = min(max_rev, rev + revcount) downrev = max(0, rev - revcount) count = len(web.repo) changenav = webutil.revnavgen(rev, revcount, count, web.repo.changectx) dag = graphmod.revisions(web.repo, rev, downrev) tree = list(graphmod.colored(dag)) canvasheight = (len(tree) + 1) * bg_height - 27 data = [] for (id, type, ctx, vtx, edges) in tree: if type != graphmod.CHANGESET: continue node = short(ctx.node()) age = templatefilters.age(ctx.date()) desc = templatefilters.firstline(ctx.description()) desc = cgi.escape(templatefilters.nonempty(desc)) user = cgi.escape(templatefilters.person(ctx.user())) branch = ctx.branch() branch = branch, web.repo.branchtags().get(branch) == ctx.node() data.append((node, vtx, edges, desc, user, age, branch, ctx.tags())) return tmpl('graph', rev=rev, revcount=revcount, uprev=uprev, lessvars=lessvars, morevars=morevars, downrev=downrev, canvasheight=canvasheight, jsdata=data, bg_height=bg_height, node=revnode_hex, changenav=changenav)
def forbidnewline(ui, repo, hooktype, node, newline, **kwargs): halt = False seen = set() # we try to walk changesets in reverse order from newest to # oldest, so that if we see a file multiple times, we take the # newest version as canonical. this prevents us from blocking a # changegroup that contains an unacceptable commit followed later # by a commit that fixes the problem. tip = repo['tip'] for rev in xrange(len(repo) - 1, repo[node].rev() - 1, -1): c = repo[rev] for f in c.files(): if f in seen or f not in tip or f not in c: continue seen.add(f) data = c[f].data() if not util.binary(data) and newline in data: if not halt: ui.warn( _('Attempt to commit or push text file(s) ' 'using %s line endings\n') % newlinestr[newline]) ui.warn(_('in %s: %s\n') % (short(c.node()), f)) halt = True if halt and hooktype == 'pretxnchangegroup': crlf = newlinestr[newline].lower() filter = filterstr[newline] ui.warn( _('\nTo prevent this mistake in your local repository,\n' 'add to Mercurial.ini or .hg/hgrc:\n' '\n' '[hooks]\n' 'pretxncommit.%s = python:hgext.win32text.forbid%s\n' '\n' 'and also consider adding:\n' '\n' '[extensions]\n' 'win32text =\n' '[encode]\n' '** = %sencode:\n' '[decode]\n' '** = %sdecode:\n') % (crlf, crlf, filter, filter)) return halt
def xml(self): n = short(self.ctx.node()) src = self.sourceelem(self.cia.project, module=self.cia.module, branch=self.ctx.branch()) # unix timestamp dt = self.ctx.date() timestamp = dt[0] author = saxutils.escape(self.ctx.user()) rev = '%d:%s' % (self.ctx.rev(), n) log = saxutils.escape(self.logmsg()) url = self.url and '<url>%s/rev/%s</url>' % (saxutils.escape( self.url), n) or '' msg = """ <message> <generator> <name>Mercurial (hgcia)</name> <version>%s</version> <url>%s</url> <user>%s</user> </generator> %s <body> <commit> <author>%s</author> <version>%s</version> <log>%s</log> %s <files>%s</files> </commit> </body> <timestamp>%d</timestamp> </message> """ % \ (HGCIA_VERSION, saxutils.escape(HGCIA_URL), saxutils.escape(self.cia.user), src, author, rev, log, url, self.fileelems(), timestamp) return msg
def sign(ui, repo, *revs, **opts): """add a signature for the current or given revision If no revision is given, the parent of the working directory is used, or tip if no revision is checked out. See :hg:`help dates` for a list of formats valid for -d/--date. """ mygpg = newgpg(ui, **opts) sigver = "0" sigmessage = "" date = opts.get('date') if date: opts['date'] = util.parsedate(date) if revs: nodes = [repo.lookup(n) for n in revs] else: nodes = [ node for node in repo.dirstate.parents() if node != hgnode.nullid ] if len(nodes) > 1: raise util.Abort( _('uncommitted merge - please provide a ' 'specific revision')) if not nodes: nodes = [repo.changelog.tip()] for n in nodes: hexnode = hgnode.hex(n) ui.write( _("Signing %d:%s\n") % (repo.changelog.rev(n), hgnode.short(n))) # build data data = node2txt(repo, n, sigver) sig = mygpg.sign(data) if not sig: raise util.Abort(_("error while signing")) sig = binascii.b2a_base64(sig) sig = sig.replace("\n", "") sigmessage += "%s %s %s\n" % (hexnode, sigver, sig) # write it if opts['local']: repo.opener("localsigs", "ab").write(sigmessage) return msigs = match.exact(repo.root, '', ['.hgsigs']) s = repo.status(match=msigs, unknown=True, ignored=True)[:6] if util.any(s) and not opts["force"]: raise util.Abort( _("working copy of .hgsigs is changed " "(please commit .hgsigs manually " "or use --force)")) repo.wfile(".hgsigs", "ab").write(sigmessage) if '.hgsigs' not in repo.dirstate: repo[None].add([".hgsigs"]) if opts["no_commit"]: return message = opts['message'] if not message: # we don't translate commit messages message = "\n".join([ "Added signature for changeset %s" % hgnode.short(n) for n in nodes ]) try: repo.commit(message, opts['user'], opts['date'], match=msigs) except ValueError, inst: raise util.Abort(str(inst))
def revtree(ui, args, repo, full="tree", maxnr=0, parents=False): def chlogwalk(): count = len(repo) i = count l = [0] * 100 chunk = 100 while True: if chunk > i: chunk = i i = 0 else: i -= chunk for x in xrange(chunk): if i + x >= count: l[chunk - x:] = [0] * (chunk - x) break if full != None: l[x] = repo[i + x] l[x].changeset() # force reading else: l[x] = 1 for x in xrange(chunk - 1, -1, -1): if l[x] != 0: yield (i + x, full != None and l[x] or None) if i == 0: break # calculate and return the reachability bitmask for sha def is_reachable(ar, reachable, sha): if len(ar) == 0: return 1 mask = 0 for i in xrange(len(ar)): if sha in reachable[i]: mask |= 1 << i return mask reachable = [] stop_sha1 = [] want_sha1 = [] count = 0 # figure out which commits they are asking for and which ones they # want us to stop on for i, arg in enumerate(args): if arg.startswith('^'): s = repo.lookup(arg[1:]) stop_sha1.append(s) want_sha1.append(s) elif arg != 'HEAD': want_sha1.append(repo.lookup(arg)) # calculate the graph for the supplied commits for i, n in enumerate(want_sha1): reachable.append(set()) visit = [n] reachable[i].add(n) while visit: n = visit.pop(0) if n in stop_sha1: continue for p in repo.changelog.parents(n): if p not in reachable[i]: reachable[i].add(p) visit.append(p) if p in stop_sha1: continue # walk the repository looking for commits that are in our # reachability graph for i, ctx in chlogwalk(): n = repo.changelog.node(i) mask = is_reachable(want_sha1, reachable, n) if mask: parentstr = "" if parents: pp = repo.changelog.parents(n) if pp[0] != nullid: parentstr += " " + short(pp[0]) if pp[1] != nullid: parentstr += " " + short(pp[1]) if not full: ui.write("%s%s\n" % (short(n), parentstr)) elif full == "commit": ui.write("%s%s\n" % (short(n), parentstr)) catcommit(ui, repo, n, ' ', ctx) else: (p1, p2) = repo.changelog.parents(n) (h, h1, h2) = map(short, (n, p1, p2)) (i1, i2) = map(repo.changelog.rev, (p1, p2)) date = ctx.date()[0] ui.write("%s %s:%s" % (date, h, mask)) mask = is_reachable(want_sha1, reachable, p1) if i1 != nullrev and mask > 0: ui.write("%s:%s " % (h1, mask)), mask = is_reachable(want_sha1, reachable, p2) if i2 != nullrev and mask > 0: ui.write("%s:%s " % (h2, mask)) ui.write("\n") if maxnr and count >= maxnr: break count += 1
def base(ui, repo, node1, node2): """output common ancestor information""" node1 = repo.lookup(node1) node2 = repo.lookup(node2) n = repo.changelog.ancestor(node1, node2) ui.write(short(n) + "\n")
def fetch(ui, repo, source='default', **opts): '''pull changes from a remote repository, merge new changes if needed. This finds all changes from the repository at the specified path or URL and adds them to the local repository. If the pulled changes add a new branch head, the head is automatically merged, and the result of the merge is committed. Otherwise, the working directory is updated to include the new changes. When a merge occurs, the newly pulled changes are assumed to be "authoritative". The head of the new changes is used as the first parent, with local changes as the second. To switch the merge order, use --switch-parent. See :hg:`help dates` for a list of formats valid for -d/--date. Returns 0 on success. ''' date = opts.get('date') if date: opts['date'] = util.parsedate(date) parent, p2 = repo.dirstate.parents() branch = repo.dirstate.branch() branchnode = repo.branchtags().get(branch) if parent != branchnode: raise util.Abort( _('working dir not at branch tip ' '(use "hg update" to check out branch tip)')) if p2 != nullid: raise util.Abort(_('outstanding uncommitted merge')) wlock = lock = None try: wlock = repo.wlock() lock = repo.lock() mod, add, rem, del_ = repo.status()[:4] if mod or add or rem: raise util.Abort(_('outstanding uncommitted changes')) if del_: raise util.Abort(_('working directory is missing some files')) bheads = repo.branchheads(branch) bheads = [head for head in bheads if len(repo[head].children()) == 0] if len(bheads) > 1: raise util.Abort( _('multiple heads in this branch ' '(use "hg heads ." and "hg merge" to merge)')) other = hg.repository(hg.remoteui(repo, opts), ui.expandpath(source)) ui.status( _('pulling from %s\n') % url.hidepassword(ui.expandpath(source))) revs = None if opts['rev']: try: revs = [other.lookup(rev) for rev in opts['rev']] except error.CapabilityError: err = _("Other repository doesn't support revision lookup, " "so a rev cannot be specified.") raise util.Abort(err) # Are there any changes at all? modheads = repo.pull(other, heads=revs) if modheads == 0: return 0 # Is this a simple fast-forward along the current branch? newheads = repo.branchheads(branch) newchildren = repo.changelog.nodesbetween([parent], newheads)[2] if len(newheads) == 1: if newchildren[0] != parent: return hg.clean(repo, newchildren[0]) else: return 0 # Are there more than one additional branch heads? newchildren = [n for n in newchildren if n != parent] newparent = parent if newchildren: newparent = newchildren[0] hg.clean(repo, newparent) newheads = [n for n in newheads if n != newparent] if len(newheads) > 1: ui.status( _('not merging with %d other new branch heads ' '(use "hg heads ." and "hg merge" to merge them)\n') % (len(newheads) - 1)) return 1 # Otherwise, let's merge. err = False if newheads: # By default, we consider the repository we're pulling # *from* as authoritative, so we merge our changes into # theirs. if opts['switch_parent']: firstparent, secondparent = newparent, newheads[0] else: firstparent, secondparent = newheads[0], newparent ui.status( _('updating to %d:%s\n') % (repo.changelog.rev(firstparent), short(firstparent))) hg.clean(repo, firstparent) ui.status( _('merging with %d:%s\n') % (repo.changelog.rev(secondparent), short(secondparent))) err = hg.merge(repo, secondparent, remind=False) if not err: # we don't translate commit messages message = (cmdutil.logmessage(opts) or ('Automated merge with %s' % url.removeauth(other.url()))) editor = cmdutil.commiteditor if opts.get('force_editor') or opts.get('edit'): editor = cmdutil.commitforceeditor n = repo.commit(message, opts['user'], opts['date'], editor=editor) ui.status( _('new changeset %d:%s merges remote changes ' 'with local\n') % (repo.changelog.rev(n), short(n))) return err finally: release(lock, wlock)