def test_file_only_renamed(self): """Change by doing a rename without any content editing""" ui = mock_ui() hgcommands.init(ui, self.repo) hgrepo = repository(ui, self.repo) ( open(hgrepo.pathto("file.dtd"), "w").write( """ <!ENTITY key1 "Hello"> <!ENTITY key2 "Cruel"> """ ) ) hgcommands.addremove(ui, hgrepo) hgcommands.commit(ui, hgrepo, user="******", message="initial commit") rev0 = hgrepo[0].hex() hgcommands.rename(ui, hgrepo, hgrepo.pathto("file.dtd"), hgrepo.pathto("newnamefile.dtd")) hgcommands.commit(ui, hgrepo, user="******", message="Second commit") rev1 = hgrepo[1].hex() Repository.objects.create(name=self.repo_name, url="http://localhost:8001/%s/" % self.repo_name) url = reverse("pushes.views.diff") response = self.client.get(url, {"repo": self.repo_name, "from": rev0, "to": rev1}) eq_(response.status_code, 200) html_diff = response.content.split("Changed files:")[1] ok_("renamed from file.dtd" in re.sub("<.*?>", "", html_diff)) ok_(re.findall(">\s*newnamefile\.dtd\s*<", html_diff)) ok_(not re.findall(">\s*Hello\s*<", html_diff))
def hg_move(source, target, dest): face = ui.ui() repo = hg.repository(face, blog_dir) commands.rename(face, repo, source, target) commands.commit(face, repo, source, target, user=g.blog['AUTHOR'], message='moved {} to {}'.format(os.path.basename(source), dest), ) if not os.path.exists(os.path.dirname(source)): os.mkdir(os.path.dirname(source))
def rename_file(self, source, dest): if self.vcs_type == 'git': #http://code.google.com/p/dulwich-mirror/source/browse/docs/tutorial/5-rename-file.txt?name=rc-walker-ack-v5 pass elif self.vcs_type == 'hg': hg.rename( self.ui, self.r, source.encode('utf-8'), dest.encode('utf-8'), force=False) hg.commit( self.ui, self.r, #path.encode('utf-8'), message='rename {0} => {1}'.format(source, dest))
def rename_resp(dlg, response): if response != gtk.RESPONSE_OK: dlg.destroy() return try: root = paths.find_root() repo = hg.repository(ui.ui(), root) except (ImportError, error.RepoError): dlg.destroy() return new_name = hglib.fromutf(dlg.entry.get_text()) opts = {} opts['force'] = False # Checkbox? Nah. opts['after'] = True opts['dry_run'] = False saved = sys.stderr errors = cStringIO.StringIO() toquit = False try: sys.stderr = errors repo.ui.pushbuffer() repo.ui.quiet = True try: new_name = util.canonpath(root, root, new_name) targetdir = os.path.dirname(new_name) or '.' if dlg.orig.lower() == new_name.lower() and os.path.isdir(dlg.orig): os.rename(dlg.orig, new_name) else: if not os.path.isdir(targetdir): os.makedirs(targetdir) shutil.move(dlg.orig, new_name) commands.rename(repo.ui, repo, dlg.orig, new_name, **opts) toquit = True except (OSError, IOError, util.Abort, error.RepoError), inst: dialog.error_dialog(None, _('rename error'), str(inst)) toquit = False finally: sys.stderr = saved textout = errors.getvalue() + repo.ui.popbuffer() errors.close() if len(textout) > 1: dialog.error_dialog(None, _('rename error'), textout) elif toquit: dlg.destroy()
def move(self, key_from, key_to): """ Moves an entity from ``key_from`` to ``key_to`` while keeping the history. This is useful to migrate a repository after the ``rcskey_format`` of a field was changed. TODO: move from mecurial.commands to internal api.# """ u = self.hg_ui repo = hg.repository(u, self.location) absp = lambda p: os.path.join(self.location, p) try: commands.rename(u, repo, absp(key_from), absp(key_to)) commands.commit(u, repo, message="Moved %s to %s" % (key_from, key_to)) return True except: return False
def handle_move(self, dest_path): """Handle a MOVE request natively.""" destType, destHgPath = util.pop_path(dest_path) destHgPath = destHgPath.strip("/") ui = self.provider.ui repo = self.provider.repo _logger.info("handle_copy %s -> %s" % (self.localHgPath, destHgPath)) if self.rev is None and destType == "edit": # MOVE /edit/a/b to /edit/c/d: turn into 'hg rename -f a/b c/d' commands.rename(ui, repo, self.localHgPath, destHgPath, force=True) elif self.rev is None and destType == "released": # MOVE /edit/a/b to /released/c/d # This is interpreted as 'hg commit a/b' (ignoring the dest. path) self._commit("WsgiDAV commit (MOVE %s -> %s)" % (self.path, dest_path)) else: raise DAVError(HTTP_FORBIDDEN) # Return True: request was handled return True
def handleMove(self, destPath): """Handle a MOVE request natively. """ destType, destHgPath = util.popPath(destPath) destHgPath = destHgPath.strip("/") ui = self.provider.ui repo = self.provider.repo util.write("handleCopy %s -> %s" % (self.localHgPath, destHgPath)) if self.rev is None and destType == "edit": # MOVE /edit/a/b to /edit/c/d: turn into 'hg rename -f a/b c/d' commands.rename(ui, repo, self.localHgPath, destHgPath, force=True) elif self.rev is None and destType == "released": # MOVE /edit/a/b to /released/c/d # This is interpreted as 'hg commit a/b' (ignoring the dest. path) self._commit("WsgiDAV commit (MOVE %s -> %s)" % (self.path, destPath)) else: raise DAVError(HTTP_FORBIDDEN) # Return True: request was handled return True
def test_file_renamed_and_edited_original_broken(self): """Change by doing a rename on a previously broken file""" ui = mock_ui() hgcommands.init(ui, self.repo) hgrepo = repository(ui, self.repo) ( codecs.open(hgrepo.pathto("file.dtd"), "w", "latin1").write( u""" <!ENTITY key1 "Hell\xe3"> <!ENTITY key2 "Cruel"> """ ) ) hgcommands.addremove(ui, hgrepo) hgcommands.commit(ui, hgrepo, user="******", message="initial commit") rev0 = hgrepo[0].hex() hgcommands.rename(ui, hgrepo, hgrepo.pathto("file.dtd"), hgrepo.pathto("newnamefile.dtd")) ( open(hgrepo.pathto("newnamefile.dtd"), "w").write( """ <!ENTITY key1 "Hello"> <!ENTITY key2 "World"> """ ) ) hgcommands.commit(ui, hgrepo, user="******", message="Second commit") rev1 = hgrepo[1].hex() Repository.objects.create(name=self.repo_name, url="http://localhost:8001/%s/" % self.repo_name) url = reverse("pushes.views.diff") response = self.client.get(url, {"repo": self.repo_name, "from": rev0, "to": rev1}) eq_(response.status_code, 200) html_diff = response.content.split("Changed files:")[1].split("page_footer")[0] html_diff = unicode(html_diff, "utf-8") ok_(re.findall(">\s*newnamefile\.dtd\s*<", html_diff)) ok_("Cannot parse file" in html_diff) eq_(html_diff.count("Cannot parse file"), 1) ok_("renamed from file.dtd" in re.sub("<.*?>", "", html_diff))
def commitNext(self): if self.rev_no >= len(self.wrevs): return False rev = self.wrevs[self.rev_no] source = self.wd.get_revision_source(rev['rev_id']) # Page title and unix_name changes are only available through another request: details = self.wd.get_revision_version(rev['rev_id']) # Store revision_id for last commit # Without this, empty commits (e.g. file uploads) will be skipped by Mercurial if self.storeRevIds: fname = self.path + '\\.revid' outp = codecs.open(fname, "w", "UTF-8") outp.write( rev['rev_id'] ) # rev_ids are unique amongst all pages, and only one page changes in each commit anyway outp.close() unixname = rev['page_name'] rev_unixname = details[ 'unixname'] # may be different in revision than atm # Unfortunately, there's no exposed way in Wikidot to see page breadcrumbs at any point in history. # The only way to know they were changed is revision comments, though evil people may trick us. if rev['comment'].startswith('Parent page set to: "'): # This is a parenting revision, remember the new parent parent_unixname = rev['comment'][21:-2] self.last_parents[unixname] = parent_unixname else: # Else use last parent_unixname we've recorded parent_unixname = self.last_parents[ unixname] if unixname in self.last_parents else None # There are also problems when parent page gets renamed -- see updateChildren # If the page is tracked and its name just changed, tell HG rename = (unixname in self.last_names) and (self.last_names[unixname] <> rev_unixname) if rename: self.updateChildren( self.last_names[unixname], rev_unixname ) # Update children which reference us -- see comments there commands.rename( self.ui, self.repo, self.path + '\\' + str(self.last_names[unixname]) + '.txt', self.path + '\\' + str(rev_unixname) + '.txt') # Ouput contents fname = self.path + '\\' + rev_unixname + '.txt' outp = codecs.open(fname, "w", "UTF-8") if details['title']: outp.write('title:' + details['title'] + '\n') if parent_unixname: outp.write('parent:' + parent_unixname + '\n') outp.write(source) outp.close() # Add new page if not unixname in self.last_names: # never before seen commands.add(self.ui, self.repo, str(fname)) self.last_names[unixname] = rev_unixname # Commit if rev['comment'] <> '': commit_msg = rev_unixname + ': ' + rev['comment'] else: commit_msg = rev_unixname if rev['date']: commit_date = str(rev['date']) + ' 0' else: commit_date = None print "Commiting: " + str(self.rev_no) + '. ' + commit_msg commands.commit(self.ui, self.repo, message=commit_msg, user=rev['user'], date=commit_date) self.rev_no += 1 self.saveState() # Update operation state return True
def rename(self, source, target): commands.rename( self.ui, self.repo, after=False, # hg 0.9.5 *self.joined([source, target]))
def dohgmove(): #moveopts['force'] = True commands.rename(self.stat.ui, self.stat.repo, *wfiles, **moveopts)
def commitNext(self): if self.rev_no >= len(self.wrevs): return False rev = self.wrevs[self.rev_no] source = self.wd.get_revision_source(rev['rev_id']) # Page title and unix_name changes are only available through another request: details = self.wd.get_revision_version(rev['rev_id']) # Store revision_id for last commit # Without this, empty commits (e.g. file uploads) will be skipped by Mercurial if self.storeRevIds: fname = self.path+'\\.revid' outp = codecs.open(fname, "w", "UTF-8") outp.write(rev['rev_id']) # rev_ids are unique amongst all pages, and only one page changes in each commit anyway outp.close() unixname = rev['page_name'] rev_unixname = details['unixname'] # may be different in revision than atm # Unfortunately, there's no exposed way in Wikidot to see page breadcrumbs at any point in history. # The only way to know they were changed is revision comments, though evil people may trick us. if rev['comment'].startswith('Parent page set to: "'): # This is a parenting revision, remember the new parent parent_unixname = rev['comment'][21:-2] self.last_parents[unixname] = parent_unixname else: # Else use last parent_unixname we've recorded parent_unixname = self.last_parents[unixname] if unixname in self.last_parents else None # There are also problems when parent page gets renamed -- see updateChildren # If the page is tracked and its name just changed, tell HG rename = (unixname in self.last_names) and (self.last_names[unixname] <> rev_unixname) if rename: self.updateChildren(self.last_names[unixname], rev_unixname) # Update children which reference us -- see comments there commands.rename(self.ui, self.repo, self.path+'\\'+str(self.last_names[unixname])+'.txt', self.path+'\\'+str(rev_unixname)+'.txt') # Ouput contents fname = self.path+'\\'+rev_unixname+'.txt' outp = codecs.open(fname, "w", "UTF-8") if details['title']: outp.write('title:'+details['title']+'\n') if parent_unixname: outp.write('parent:'+parent_unixname+'\n') outp.write(source) outp.close() # Add new page if not unixname in self.last_names: # never before seen commands.add(self.ui, self.repo, str(fname)) self.last_names[unixname] = rev_unixname # Commit if rev['comment'] <> '': commit_msg = rev_unixname + ': ' + rev['comment'] else: commit_msg = rev_unixname if rev['date']: commit_date = str(rev['date']) + ' 0' else: commit_date = None print "Commiting: "+str(self.rev_no)+'. '+commit_msg commands.commit(self.ui, self.repo, message=commit_msg, user=rev['user'], date=commit_date) self.rev_no += 1 self.saveState() # Update operation state return True
def subpull(ui, repo, name='', **opts): """Pull subtree(s)""" # change to root directory if repo.getcwd() != '': ui.warn( "Working directory is not repository root. At best, this directory won't exist when subpull is done.\n" ) repo.dirstate._cwd = repo.root os.chdir(repo.root) # if there are uncommitted change, abort --- we will be modifying the working copy quite drammatically modified, added, removed, deleted, _unknown, _ignored, _clean = repo.status( ) if modified or added or removed or deleted: raise error.Abort( "Uncommitted changes in the working copy. Subtree extension needs to modify the working copy, so it cannot proceed." ) # parse .hgsubtree hgsubtree = ui.config('subtree', 'hgsubtree', default=default_hgsubtree) subtrees = _parse_hgsubtree(os.path.join(repo.root, hgsubtree)) # if names not in .hgsubtree, abort # if names is empty, go through all repos in .hgsubtree if name: if name not in subtrees: raise error.Abort("Cannot find %s in %s." % (name, hgsubtree)) names = [name] else: if opts['source']: raise error.Abort( "Cannot use --source without specifying a repository") names = subtrees.keys() null = repo['null'] origin = str(repo[None]) commit_opts = {'edit': opts['edit']} bookmark_prefix = ui.config('subtree', 'bookmark', default=default_bookmark_prefix) nocache = ui.config('subtree', 'nocache', default='') for name in names: subtree = subtrees[name] if 'destination' not in subtree: raise error.Abort('No destination found for %s' % name) collapse = 'collapse' in subtree and subtree['collapse'] # figure out the revision to pull pull_opts = {} if 'rev' in subtree: pull_opts['rev'] = [subtree['rev']] if opts['rev']: pull_opts['rev'] = opts['rev'] # clone or pull into cache source = subtree['source'] if not opts['source'] else opts['source'] if not nocache: source = _clone_or_pull(ui, repo, name, source, pull_opts) # pull tip = repo['tip'] commands.pull(ui, repo, source=source, force=True, **pull_opts) if tip == repo['tip']: ui.status("no changes: nothing for subtree to do\n") continue # collapse or update -C if collapse: # find a matching bookmark bookmark_name = bookmark_prefix + name if bookmark_name in repo._bookmarks: commands.update(ui, repo, bookmark_name, clean=True) else: commands.update(ui, repo, 'null', clean=True) # set up the correct file state and commit as a new changeset pulled_tip = repo['tip'] commands.revert(ui, repo, rev='tip', all=True) hgsubrepo_meta = [ os.path.join(repo.root, '.hgsubstate'), os.path.join(repo.root, '.hgsub') ] for fn in hgsubrepo_meta: if os.path.exists(fn): ui.debug("removing %s\n" % fn) commands.remove(ui, repo, fn, force=True) os.remove(fn) changed = commands.commit(ui, repo, message=ui.config( 'subtree', 'collapse', default_collapse_comment).format( name=name, rev=str(pulled_tip)[:12]), **commit_opts) commands.bookmark(ui, repo, bookmark_name, inactive=True) if not opts['no_strip']: # delete bookmarks on the changesets that will be stripped; not # the most efficient procedure to find them, but will do for now remove_bookmarks = [] for k in repo._bookmarks.keys(): ctx = repo[k] if pulled_tip.ancestor(ctx) != null: remove_bookmarks.append(k) for bookmark in remove_bookmarks: commands.bookmark(ui, repo, bookmark, delete=True) strip.stripcmd(ui, repo, rev=['ancestors(%s)' % str(pulled_tip)], bookmark=[]) if changed == 1: # nothing changed ui.status("no changes: nothing for subtree to do\n") commands.update(ui, repo, origin[:12]) continue else: commands.update(ui, repo, 'tip', clean=True) # move or delete destinations = _destinations(subtree['destination']) # process destinations keep_list = [] for dest in destinations: if dest[0] == 'mkdir': if not os.path.exists(dest[1]): os.makedirs(dest[1]) elif dest[0] == 'mv': commands.rename(ui, repo, *dest[1:], force=False) elif dest[0] == 'cp': commands.copy(ui, repo, *dest[1:], force=False) elif dest[0] == 'rm': commands.remove(ui, repo, *dest[1:], force=False) elif dest[0] == 'keep': keep_list.append(' '.join(dest[1:])) # remove all untouched files, unless instructed to keep them if 'keep' not in subtree or not subtree['keep']: _modified, _added, _removed, _deleted, _unknown, _ignored, clean = repo.status( clean=True) for fn in clean: for keep_pattern in keep_list: if fnmatch(fn, keep_pattern): break else: commands.remove(ui, repo, fn) commands.commit( ui, repo, message=ui.config('subtree', 'move', default_move_comment).format(name=name), **commit_opts) merge_commit = str(repo[None]) # update to original and merge with the new commands.update(ui, repo, origin[:12]) commands.merge(ui, repo, merge_commit[:12]) commands.commit( ui, repo, message=ui.config('subtree', 'merge', default_merge_comment).format(name=name), **commit_opts) origin = str(repo[None])