示例#1
0
def mqNewRefreshCommand(repo, isnew, stwidget, pnwidget, message, opts, olist):
    if isnew:
        name = hglib.fromunicode(pnwidget.text())
        if not name:
            qtlib.ErrorMsgBox(_('Patch Name Required'),
                              _('You must enter a patch name'))
            pnwidget.setFocus()
            return
        cmdline = ['qnew', '--repository', repo.root, name]
    else:
        cmdline = ['qrefresh', '--repository', repo.root]
    if message:
        cmdline += ['--message=' + hglib.fromunicode(message)]
    cmdline += getUserOptions(opts, *olist)
    files = ['--'] + [repo.wjoin(x) for x in stwidget.getChecked()]
    addrem = [repo.wjoin(x) for x in stwidget.getChecked('!?')]
    if len(files) > 1:
        cmdline += files
    else:
        cmdline += ['--exclude', repo.root]
    if addrem:
        cmdlines = [ ['addremove', '-R', repo.root] + addrem, cmdline]
    else:
        cmdlines = [cmdline]
    return cmdlines
示例#2
0
def _openineditor(repo, path, rev, line=None, pattern=None, parent=None):
    """Open editor to show the specified file [unicode]"""
    path = hglib.fromunicode(path)
    pattern = hglib.fromunicode(pattern)
    base = visdiff.snapshot(repo, [path], repo[rev])[0]
    files = [os.path.join(base, path)]
    qtlib.editfiles(repo, files, line, pattern, parent=self)
示例#3
0
 def editSelected(self, path, rev, line):
     """Open editor to show the specified file"""
     path = hglib.fromunicode(path)
     base = visdiff.snapshot(self.repo, [path], self.repo[rev])[0]
     files = [os.path.join(base, path)]
     pattern = hglib.fromunicode(self._lastSearch[0])
     qtlib.editfiles(self.repo, files, line, pattern, self)
示例#4
0
    def update(self):
        self.saveSettings()
        cmdline = ['rupdate']

        if self.discard_chk.isChecked():
            cmdline.append('--clean')
        if self.push_chk.isChecked():
            cmdline.append('--push')
        if self.newbranch_chk.isChecked():
            cmdline.append('--new-branch')
        if self.force_chk.isChecked():
            cmdline.append('--force')

        dest = hglib.fromunicode(self.path_combo.currentText())
        cmdline.append('-d')
        cmdline.append(dest)

        # Refer to the revision by the short hash.
        rev = hglib.fromunicode(self.rev_combo.currentText())
        revShortHash = node.short(self.repo[rev].node())
        cmdline.append(revShortHash)

        # start updating
        self.repo.incrementBusyCount()
        self.cmd.run(cmdline)
示例#5
0
def launchtool(cmd, opts, replace, block):
    def quote(match):
        key = match.group()[1:]
        return util.shellquote(replace[key])
    if isinstance(cmd, unicode):
        cmd = hglib.fromunicode(cmd)
    lopts = []
    for opt in opts:
        if isinstance(opt, unicode):
            lopts.append(hglib.fromunicode(opt))
        else:
            lopts.append(opt)
    args = ' '.join(lopts)
    args = re.sub(_regex, quote, args)
    cmdline = util.shellquote(cmd) + ' ' + args
    cmdline = util.quotecommand(cmdline)
    try:
        proc = subprocess.Popen(cmdline, shell=True,
                                creationflags=qtlib.openflags,
                                stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stdin=subprocess.PIPE)
        if block:
            proc.communicate()
    except (OSError, EnvironmentError), e:
        QMessageBox.warning(None,
                _('Tool launch failure'),
                _('%s : %s') % (cmd, str(e)))
示例#6
0
 def setpathmap(self, path, localpath):
     """change path mapping at the specified index"""
     self._config.set('paths', hglib.fromunicode(path),
                      hglib.fromunicode(localpath))
     row = self._indexofpath(path)
     self.dataChanged.emit(self.index(row, 0),
                           self.index(row, self.columnCount()))
示例#7
0
 def checkToggled(self, wfile, checked):
     'user has toggled a checkbox, update partial chunk selection status'
     wfile = hglib.fromunicode(wfile)
     if wfile in self.partials:
         del self.partials[wfile]
         if wfile == hglib.fromunicode(self.fileview.filePath()):
             self.onCurrentChange(self.tv.currentIndex())
示例#8
0
 def accept(self):
     try:
         hglib.fromunicode(self.textValue())
         return super(_EncodingSafeInputDialog, self).accept()
     except UnicodeEncodeError:
         WarningMsgBox(_('Text Translation Failure'),
                       _('Unable to translate input to local encoding.'),
                       parent=self)
示例#9
0
    def onAddTag(self):
        tagu = self.tagCombo.currentText()
        tag = hglib.fromunicode(tagu)
        local = self.localCheckBox.isChecked()
        force = self.replaceCheckBox.isChecked()
        english = self.englishCheckBox.isChecked()
        if self.customCheckBox.isChecked():
            message = self.customTextLineEdit.text()
        else:
            message = None

        exists = tag in self.repo.tags()
        if exists and not force:
            self.set_status(_("Tag '%s' already exists") % tagu, False)
            return
        if not local:
            parents = self.repo.parents()
            if len(parents) > 1:
                self.set_status(_('uncommitted merge'), False)
                return
            p1 = parents[0]
            if not force and p1.node() not in self.repo._branchheads:
                self.set_status(_('not at a branch head (use force)'), False)
                return
            if not message:
                ctx = self.repo[self.rev]
                if exists:
                    origctx = self.repo[self.repo.tags()[tag]]
                    msgset = keep._('Moved tag %s to changeset %s' \
                        ' (from changeset %s)')
                    message = (english and msgset['id'] or msgset['str']) \
                       % (tagu, str(ctx), str(origctx))
                else:
                    msgset = keep._('Added tag %s for changeset %s')
                    message = (english and msgset['id'] or msgset['str']) \
                               % (tagu, str(ctx))
            message = hglib.fromunicode(message)

        def finished():
            if exists:
                self.set_status(_("Tag '%s' has been moved") % tagu, True)
            else:
                self.set_status(_("Tag '%s' has been added") % tagu, True)

        user = qtlib.getCurrentUsername(self, self.repo)
        if not user:
            return
        cmd = ['tag', '--repository', self.repo.root, '--rev', str(self.rev),
               '--user', user]
        if local:
            cmd.append('--local')
        else:
            cmd.append('--message=%s' % message)
        if force:
            cmd.append('--force')
        cmd.append(tag)
        self.finishfunc = finished
        self.cmd.run(cmd)
示例#10
0
    def onAddTag(self):
        if self.cmd.core.running():
            self.set_status(_("Repository command still running"), False)
            return

        tagu = self.tagCombo.currentText()
        tag = hglib.fromunicode(tagu)
        local = self.localCheckBox.isChecked()
        force = self.replaceCheckBox.isChecked()
        english = self.englishCheckBox.isChecked()
        if self.customCheckBox.isChecked():
            message = self.customTextLineEdit.text()
        else:
            message = None

        exists = tag in self.repo.tags()
        if exists and not force:
            self.set_status(_("Tag '%s' already exists") % tagu, False)
            return
        if not local:
            parents = self.repo.parents()
            if len(parents) > 1:
                self.set_status(_("uncommitted merge"), False)
                return
            p1 = parents[0]
            if not force and p1.node() not in self.repo._branchheads:
                self.set_status(_("not at a branch head (use force)"), False)
                return
            if not message:
                ctx = self.repo[self.rev]
                if exists:
                    origctx = self.repo[self.repo.tags()[tag]]
                    msgset = keep._("Moved tag %s to changeset %s" " (from changeset %s)")
                    message = (english and msgset["id"] or msgset["str"]) % (tagu, str(ctx), str(origctx))
                else:
                    msgset = keep._("Added tag %s for changeset %s")
                    message = (english and msgset["id"] or msgset["str"]) % (tagu, str(ctx))
            message = hglib.fromunicode(message)

        def finished():
            if exists:
                self.set_status(_("Tag '%s' has been moved") % tagu, True)
            else:
                self.set_status(_("Tag '%s' has been added") % tagu, True)

        user = qtlib.getCurrentUsername(self, self.repo)
        if not user:
            return
        cmd = ["tag", "--repository", self.repo.root, "--rev", str(self.rev), "--user", user]
        if local:
            cmd.append("--local")
        else:
            cmd.append("--message=%s" % message)
        if force:
            cmd.append("--force")
        cmd.append(tag)
        self.finishfunc = finished
        self.cmd.run(cmd)
示例#11
0
 def getCmd(self, cwd):
     cmd = ['pnew', '--cwd', cwd, hglib.fromunicode(self.patchname())]
     optList = [('patchtext','--text'),
                ('patchdate','--date'),
                ('patchuser','--user')]
     for v,o in optList:
         if getattr(self,v+'cb').isChecked():
             cmd.extend([o,hglib.fromunicode(getattr(self,v+'le').text())])
     return cmd
示例#12
0
 def updateIniValue(section, key, newvalue):
     section = hglib.fromunicode(section)
     key = hglib.fromunicode(key)
     try:
         del ini[section][key]
     except KeyError:
         pass
     if newvalue is not None:
         ini.set(section, key, newvalue)
示例#13
0
 def addpathmap(self, path, localpath):
     """add path mapping to serve"""
     assert path not in self.paths
     self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
     try:
         self._config.set('paths', hglib.fromunicode(path),
                          hglib.fromunicode(localpath))
     finally:
         self.endInsertRows()
示例#14
0
 def editfile(self):
     if self.path is None:
         return
     if self.rev is None:
         qtlib.editfiles(self._repo, [hglib.fromunicode(self.path)], parent=self)
     else:
         base, _ = visdiff.snapshot(self._repo, [hglib.fromunicode(self.path)], self._repo[self.rev])
         files = [os.path.join(base, hglib.fromunicode(self.path))]
         qtlib.editfiles(self._repo, files, parent=self)
示例#15
0
 def value(self):
     hooks = {}
     for r in range(self.hooktable.rowCount()):
         hooktype = hglib.fromunicode(self.hooktable.item(r, 0).text())
         hookname = hglib.fromunicode(self.hooktable.item(r, 1).text())
         command = hglib.fromunicode(self.hooktable.item(r, 2).text())
         if hooktype not in hooks:
             hooks[hooktype] = {}
         hooks[hooktype][hookname] = command
     return hooks
示例#16
0
 def goto(self, rev):
     """
     Select revision 'rev' (can be anything understood by repo.changectx())
     """
     if isinstance(rev, (unicode, QString)):
         rev = hglib.fromunicode(rev)
     try:
         rev = self.repo.changectx(rev).rev()
     except error.RepoError:
         self.showMessage.emit(_("Can't find revision '%s'") % rev)
     except LookupError, e:
         self.showMessage.emit(hglib.fromunicode(str(e)))
示例#17
0
 def findHooks(self, hooktype=None, hookname=None, command=None):
     matchingrows = []
     for r in range(self.hooktable.rowCount()):
         currhooktype = hglib.fromunicode(self.hooktable.item(r, 0).text())
         currhookname = hglib.fromunicode(self.hooktable.item(r, 1).text())
         currcommand = hglib.fromunicode(self.hooktable.item(r, 2).text())
         matchinghooktype = hooktype is None or hooktype == currhooktype
         matchinghookname = hookname is None or hookname == currhookname
         matchingcommand = command is None or command == currcommand
         if matchinghooktype and matchinghookname and matchingcommand:
             matchingrows.append(r)
     return matchingrows
示例#18
0
 def setData(self, column, value):
     if column == 0:
         shortname = hglib.fromunicode(value.toString())
         abshgrcpath = os.path.join(hglib.fromunicode(self.rootpath()),
                                    '.hg', 'hgrc')
         if not hgrcutil.setConfigValue(abshgrcpath, 'web.name', shortname):
             qtlib.WarningMsgBox(_('Unable to update repository name'),
                 _('An error occurred while updating the repository hgrc '
                   'file (%s)') % hglib.tounicode(abshgrcpath))
             return False
         self.setShortName(value.toString())
         return True
     return False
示例#19
0
    def appendSubrepos(self, repo=None):
        self._sharedpath = ''
        invalidRepoList = []
        try:
            sri = None
            if repo is None:
                if not os.path.exists(self._root):
                    self._valid = False
                    return [hglib.fromunicode(self._root)]
                elif (not os.path.exists(os.path.join(self._root, '.hgsub'))
                      and not os.path.exists(
                          os.path.join(self._root, '.hg', 'sharedpath'))):
                    return []  # skip repo creation, which is expensive
                repo = hg.repository(ui.ui(), hglib.fromunicode(self._root))
            if repo.sharedpath != repo.path:
                self._sharedpath = hglib.tounicode(repo.sharedpath)
            wctx = repo['.']
            sortkey = lambda x: os.path.basename(util.normpath(repo.wjoin(x)))
            for subpath in sorted(wctx.substate, key=sortkey):
                sri = None
                abssubpath = repo.wjoin(subpath)
                subtype = wctx.substate[subpath][2]
                sriIsValid = os.path.isdir(abssubpath)
                sri = _newSubrepoItem(hglib.tounicode(abssubpath),
                                      repotype=subtype)
                sri._valid = sriIsValid
                self.appendChild(sri)

                if not sriIsValid:
                    self._valid = False
                    sri._valid = False
                    invalidRepoList.append(repo.wjoin(subpath))
                    return invalidRepoList

                if subtype == 'hg':
                    # Only recurse into mercurial subrepos
                    sctx = wctx.sub(subpath)
                    invalidSubrepoList = sri.appendSubrepos(sctx._repo)
                    if invalidSubrepoList:
                        self._valid = False
                        invalidRepoList += invalidSubrepoList

        except (EnvironmentError, error.RepoError, util.Abort), e:
            # Add the repo to the list of repos/subrepos
            # that could not be open
            self._valid = False
            if sri:
                sri._valid = False
                invalidRepoList.append(abssubpath)
            invalidRepoList.append(hglib.fromunicode(self._root))
示例#20
0
 def qqueueRename(self):
     uq = self.ql.item(self.ql.currentRow()).text()
     q = hglib.fromunicode(uq)
     if q == 'patches':
         return
     title = _('TortoiseHg Prompt')
     # this is the only way I found to make that dialog wide enough :(
     label = (_("Rename patch queue '%s' to") % uq) + (u' ' * 30)
     newqname, ok = qtlib.getTextInput(self, title, label)
     if newqname:
         newqname = hglib.fromunicode(newqname)
     if newqname and ok:
         opts = ['--rename', newqname]
         self.qqueueCommand(opts)
示例#21
0
 def setBranch(self, branch=None, allparents=True):
     self.filterbranch = branch  # unicode
     self.invalidateCache()
     if self.revset and self.filterbyrevset:
         grapher = revision_grapher(self.repo, branch=hglib.fromunicode(branch), revset=self.revset)
         self.graph = Graph(self.repo, grapher, include_mq=False)
     else:
         grapher = revision_grapher(self.repo, branch=hglib.fromunicode(branch), allparents=allparents)
         self.graph = Graph(self.repo, grapher, include_mq=True)
     self.rowcount = 0
     self.layoutChanged.emit()
     self.ensureBuilt(row=0)
     self.showMessage.emit("")
     QTimer.singleShot(0, lambda: self.filled.emit())
示例#22
0
    def onRemoveTag(self):
        if self.cmd.core.running():
            self.set_status(_("Repository command still running"), False)
            return

        tagu = self.tagCombo.currentText()
        tag = hglib.fromunicode(tagu)
        local = self.localCheckBox.isChecked()
        force = self.replaceCheckBox.isChecked()
        english = self.englishCheckBox.isChecked()
        if self.customCheckBox.isChecked():
            message = self.customTextLineEdit.text()
        else:
            message = None

        tagtype = self.repo.tagtype(tag)
        if local:
            if tagtype != "local":
                self.set_status(_("tag '%s' is not a local tag") % tagu, False)
                return
        else:
            if tagtype != "global":
                self.set_status(_("tag '%s' is not a global tag") % tagu, False)
                return
            parents = self.repo.parents()
            if len(parents) > 1:
                self.set_status(_("uncommitted merge"), False)
                return
            p1 = parents[0]
            if not force and p1.node() not in self.repo._branchheads:
                self.set_status(_("not at a branch head (use force)"), False)
                return
            if not message:
                msgset = keep._("Removed tag %s")
                message = (english and msgset["id"] or msgset["str"]) % tagu
            message = hglib.fromunicode(message)

        def finished():
            self.set_status(_("Tag '%s' has been removed") % tagu, True)

        cmd = ["tag", "--repository", self.repo.root, "--remove"]
        if local:
            cmd.append("--local")
        else:
            cmd.append("--message=%s" % message)
        cmd.append(tag)
        self.finishfunc = finished
        self.cmd.run(cmd)
示例#23
0
    def dropEvent(self, event):
        data = event.mimeData()
        index, group, row = self.dropLocation(event)

        if index:
            if event.source() is self:
                # Event is an internal move, so pass it to the model
                col = 0
                drop = self.model().dropMimeData(data, event.dropAction(), row,
                                                 col, group)
                if drop:
                    event.accept()
                    self.dropAccepted.emit()
            else:
                # Event is a drop of an external repo
                accept = False
                for u in data.urls():
                    root = paths.find_root(hglib.fromunicode(u.toLocalFile()))
                    if root and not self.model().getRepoItem(root):
                        self.model().addRepo(group, root, row)
                        accept = True
                if accept:
                    event.setDropAction(Qt.LinkAction)
                    event.accept()
                    self.dropAccepted.emit()
        self.setAutoScroll(False)
        self.setState(QAbstractItemView.NoState)
        self.viewport().update()
        self.setAutoScroll(True)
示例#24
0
 def showPatchesForQueue(self):
     currow = self.ql.currentRow()
     if currow == -1:
         return
     while currow > self.ql.count() - 1:
         currow -= 1
     q = hglib.fromunicode(self.ql.item(currow).text())
     self.pl.clear()
     patches = []
     if q == self.repo.thgactivemqname:
         patches = self.repo.mq.fullseries
     else:
         if q == 'patches':
             sf = '/.hg/patches/series'
         else:
             sf = '/.hg/patches-%s/series' % q
         sf = self.repo.root + sf
         if os.path.exists(sf):
             f = open(sf, 'r')
             try:
                 patches = f.read().splitlines()
             finally:
                 f.close()
     for p in patches:
         item = QListWidgetItem(hglib.tounicode(p))
         item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
         self.pl.addItem(item)
     self.ql.setFocus()
示例#25
0
 def interact_handler(self, wrapper):
     prompt, password, choices, default = wrapper.data
     prompt = hglib.tounicode(prompt)
     if choices:
         dlg = QMessageBox(QMessageBox.Question,
                     _('TortoiseHg Prompt'), prompt, parent=self.parent())
         dlg.setWindowFlags(Qt.Sheet)
         dlg.setWindowModality(Qt.WindowModal)
         for index, choice in enumerate(choices):
             button = dlg.addButton(hglib.tounicode(choice),
                                    QMessageBox.ActionRole)
             button.response = index
             if index == default:
                 dlg.setDefaultButton(button)
         dlg.exec_()
         button = dlg.clickedButton()
         if button is 0:
             self.responseq.put(None)
         else:
             self.responseq.put(button.response)
     else:
         mode = password and QLineEdit.Password \
                          or QLineEdit.Normal
         text, ok = qtlib.getTextInput(self.parent(),
                      _('TortoiseHg Prompt'),
                      prompt.title(),
                      mode=mode)
         if ok:
             text = hglib.fromunicode(text)
         else:
             text = None
         self.responseq.put(text)
示例#26
0
    def validatePage(self):

        if self.cmd.core.running():
            return False

        if len(self.repo.parents()) == 1:
            # commit succeeded, repositoryChanged() called wizard().next()
            if self.skiplast.isChecked():
                self.wizard().close()
            return True

        user = qtlib.getCurrentUsername(self, self.repo)
        if not user:
            return False

        self.setTitle(_('Committing...'))
        self.setSubTitle(_('Please wait while committing merged files.'))

        message = hglib.fromunicode(self.msgEntry.text())
        cmdline = ['commit', '--verbose', '--message', message,
                   '--repository', self.repo.root, '--user', user]
        commandlines = [cmdline]
        pushafter = self.repo.ui.config('tortoisehg', 'cipushafter')
        if pushafter:
            cmd = ['push', '--repository', self.repo.root, pushafter]
            commandlines.append(cmd)
        self.repo.incrementBusyCount()
        self.cmd.setShowOutput(True)
        self.cmd.run(*commandlines)
        return False
示例#27
0
    def savefile(self):
        filenames = self.filelist.getSelectedFiles()
        if not filenames:
            return
        rev = self.ctx.rev()
        for curfile in filenames:
            wfile = util.localpath(curfile)
            wfile, ext = os.path.splitext(os.path.basename(wfile))
            if wfile:
                filename = "%s@%d%s" % (wfile, rev, ext)
            else:
                filename = "%s@%d" % (ext, rev)

            result = QFileDialog.getSaveFileName(parent=self, caption=_("Save file to"),
                                                 directory=filename) 
            if not result:
                continue
            cwd = os.getcwd()
            try:
                os.chdir(self.repo.root)
                try:
                    commands.cat(self.repo.ui, self.repo,
                        curfile,
                        rev = rev,
                        output = hglib.fromunicode(result))
                except (util.Abort, IOError), e:
                    QMessageBox.critical(self, _('Unable to save file'), hglib.tounicode(str(e)))
            finally:
                os.chdir(cwd)
示例#28
0
    def match(self):
        self.saveSettings()
        fieldmap = {
            'summary': self.summary_chk,
            'description': self.description_chk,
            'author': self.author_chk,
            'branch': self.branch_chk,
            'date': self.date_chk,
            'files': self.files_chk,
            'diff': self.diff_chk,
            'parents': self.parents_chk,
            'phase': self.phase_chk,
            'substate': self.substate_chk,
        }
        fields = []
        for (field, chk) in fieldmap.items():
            if chk.isChecked():
                fields.append(field)

        rev = hglib.fromunicode(self.rev_combo.currentText())
        if fields:
            self.revsetexpression = ("matching(%s, '%s')"
                                     % (rev, ' '.join(fields)))
        else:
            self.revsetexpression = "matching(%s)" % rev
        self.accept()
示例#29
0
    def postReviewOpts(self, **opts):
        """Generate opts for reviewboard by form values"""
        opts['outgoingchanges'] = self.qui.outgoing_changes_check.isChecked()
        opts['branch'] = self.qui.branch_check.isChecked()
        opts['publish'] = self.qui.publish_immediately_check.isChecked()

        if self.qui.tab_widget.currentIndex() == 1:
            opts["existing"] = self.getReviewId()
            opts['update'] = self.qui.update_fields.isChecked()
            opts['summary'] = self.getSummary()
        else:
            opts['repoid'] = self.getRepoId()
            opts['summary'] = hglib.fromunicode(self.qui.summary_edit.currentText())

        if (len(self.selectedRevs) > 1):
            #Set the parent to the revision below the last one on the list
            #so all checked revisions are included in the request
            opts['parent'] = str(self.selectedRevs[0] - 1)

        # Always use the upstream repo to determine the parent diff base
        # without the diff uploaded to review board dies
        opts['outgoing'] = True

        #Set the password just in  case the user has opted to not save it
        opts['password'] = str(self.password)

        #Finally we want to pass the repo path to the hg extension
        opts['repository'] = self.repo.root

        return opts
示例#30
0
 def get_selected_rev(self):
     rev = self.rev_combo.currentText()
     if rev == WD_PARENT:
         rev = '.'
     else:
         rev = hglib.fromunicode(rev)
     return rev
示例#31
0
 def getcliptext(self):
     text = hglib.fromunicode(QApplication.clipboard().text())
     if not text:
         return
     filename = self.writetempfile(text)
     curtext = self.src_combo.currentText()
     if curtext:
         self.src_combo.setEditText(curtext + os.pathsep + filename)
     else:
         self.src_combo.setEditText(filename)
示例#32
0
 def setFilter(self, match):
     'simple match in filename filter'
     self.layoutAboutToBeChanged.emit()
     oldindexes = [(self.indexFromFile(r['path']), r['path'])
                   for r in self._files]
     self._files = [r for r in self._unfilteredfiles
         if hglib.fromunicode(match) in r['path']]
     for oi, filename in oldindexes:
         self.changePersistentIndex(oi, self.indexFromFile(filename))
     self.layoutChanged.emit()
示例#33
0
 def onGuardSelectionChange(self, isChecked):
     guard = hglib.fromunicode(self.sender().text())
     newguards = self.repo.mq.active()[:]
     if isChecked:
         newguards.append(guard)
     elif guard in newguards:
         newguards.remove(guard)
     cmdline = ['qselect', '-R', self.repo.root]
     cmdline += newguards or ['--none']
     self.repo.incrementBusyCount()
     self.cmd.run(cmdline)
示例#34
0
 def browse_clicked(self):
     """Select the destination directory"""
     dest = hglib.fromunicode(self.dest_edit.text())
     if not os.path.exists(dest):
         dest = os.path.dirname(dest)
     FD = QFileDialog
     caption = _('Select Destination Folder')
     path = FD.getExistingDirectory(parent=self, caption=caption,
             options=FD.ShowDirsOnly | FD.ReadOnly)
     if path:
         self.dest_edit.setText(path)
示例#35
0
 def onBrowseQclone(self):
     FD = QFileDialog
     caption = _("Select patch folder")
     upath = FD.getExistingDirectory(self, caption, \
         self.qclone_txt.text(), QFileDialog.ShowDirsOnly)
     if upath:
         path = hglib.fromunicode(upath).replace('/', os.sep)
         src = hglib.fromunicode(self.src_combo.currentText())
         if not path.startswith(src):
             qtlib.ErrorMsgBox(
                 'TortoiseHg QClone',
                 _('The selected patch folder is not'
                   ' under the source repository.'),
                 '<p>src = %s</p><p>path = %s</p>' % (src, path))
             return
         path = path.replace(src + os.sep, '')
         self.qclone_txt.setText(
             QDir.toNativeSeparators(hglib.tounicode(path)))
         self.qclone_txt.setFocus()
     self.composeCommand()
示例#36
0
 def loadConfigs(self):
     'Load history, etc, from QSettings instance'
     s = QSettings()
     self.splitter.restoreState(s.value('mq/splitter').toByteArray())
     self.vsplitter.restoreState(s.value('mq/vsplitter').toByteArray())
     userhist = s.value('commit/userhist').toStringList()
     self.opts['userhist'] = [hglib.fromunicode(u) for u in userhist if u]
     self.messageEditor.loadSettings(s, 'mq/editor')
     self.fileview.loadSettings(s, 'mq/fileview')
     if not self.parent():
         self.restoreGeometry(s.value('mq/geom').toByteArray())
示例#37
0
    def repoChanged(self, uroot):
        m = self.tview.model()
        changedrootpath = hglib.fromunicode(QDir.fromNativeSeparators(uroot))

        def isAboveOrBelowUroot(testedpath):
            """Return True if rootpath is contained or contains uroot"""
            r1 = hglib.fromunicode(QDir.fromNativeSeparators(testedpath)) + "/"
            r2 = changedrootpath + "/"
            return r1.startswith(r2) or r2.startswith(r1)

        m.loadSubrepos(m.rootItem, isAboveOrBelowUroot)
示例#38
0
 def gverify():
     good = hglib.fromunicode(gle.text().simplified())
     try:
         ctx = repo[good]
         self.goodrev = ctx.rev()
         gb.setEnabled(False)
         gle.setEnabled(False)
         bb.setEnabled(True)
         ble.setEnabled(True)
         ble.setFocus()
     except error.RepoLookupError, e:
         self.cmd.core.stbar.showMessage(hglib.tounicode(str(e)))
示例#39
0
    def openRepoAgent(self, path):
        """Return RepoAgent for the specified path and increment refcount"""
        path = _normreporoot(path)
        if path in self._openagents:
            agent, refcount = self._openagents[path]
            self._openagents[path] = (agent, refcount + 1)
            return agent

        # TODO: move repository creation from thgrepo.repository()
        self._ui.debug('opening repo: %s\n' % hglib.fromunicode(path))
        agent = repository(self._ui, hglib.fromunicode(path))._pyqtobj
        assert agent.parent() is None
        agent.setParent(self)
        for sig, slot in self._mappedSignals(agent):
            sig.connect(slot)
        agent.startMonitoringIfEnabled()

        assert agent.rootPath() == path
        self._openagents[path] = (agent, 1)
        self.repositoryOpened.emit(path)
        return agent
示例#40
0
 def linkActivated(self, link):
     link = hglib.fromunicode(link)
     if link.startswith('subrepo:'):
         from tortoisehg.hgqt.run import qtrun
         from tortoisehg.hgqt import commit
         qtrun(commit.run, self.stwidget.repo.ui, root=link[8:])
     if link.startswith('shelve:'):
         from tortoisehg.hgqt import shelve
         dlg = shelve.ShelveDialog(self.stwidget.repo, self)
         dlg.finished.connect(dlg.deleteLater)
         dlg.exec_()
         self.refresh()
示例#41
0
 def _verifyGood(self):
     good = hglib.fromunicode(self._gle.text().simplified())
     try:
         ctx = self.repo[good]
         self.goodrev = ctx.rev()
         self._gb.setEnabled(False)
         self._gle.setEnabled(False)
         self._bb.setEnabled(True)
         self._ble.setEnabled(True)
         self._ble.setFocus()
     except (error.LookupError, error.RepoLookupError), e:
         self.cmd.core.stbar.showMessage(hglib.tounicode(str(e)))
示例#42
0
 def setData(self, column, value):
     if column == 0:
         shortname = hglib.fromunicode(value.toString())
         abshgrcpath = os.path.join(self.rootpath(), '.hg', 'hgrc')
         if not hgrcutil.setConfigValue(abshgrcpath, 'web.name', shortname):
             qtlib.WarningMsgBox(_('Unable to update repository name'),
                 _('An error occurred while updating the repository hgrc '
                   'file (%s)') % hglib.tounicode(abshgrcpath))
             return False
         self.setShortName(shortname)
         return True
     return False
示例#43
0
 def qqueueActivate(self):
     uq = self.ql.item(self.ql.currentRow()).text()
     q = hglib.fromunicode(uq)
     if q == self.repo.thgactivemqname:
         return
     if qtlib.QuestionMsgBox(
             _('Confirm patch queue switch'),
             _("Do you really want to activate patch queue '%s' ?") % uq,
             parent=self,
             defaultbutton=QMessageBox.No):
         opts = [q]
         self.qqueueCommand(opts)
示例#44
0
def copy(parent, ui, repo, files):
    assert len(files) == 1
    wfile = repo.wjoin(files[0])
    fd = QFileDialog(parent)
    fname = fd.getSaveFileName(parent, _('Copy file to'), wfile)
    if not fname:
        return False
    fname = hglib.fromunicode(fname)
    wfiles = [wfile, fname]
    opts = {'force': True}  # existing file is already checked by QFileDialog
    commands.copy(ui, repo, *wfiles, **opts)
    return True
示例#45
0
 def _toollist2guidef(self, toollist):
     guidef = []
     for uname in toollist:
         if uname == self.SEPARATOR:
             name = '|'
             # avoid putting multiple separators together
             if [name] == toollist[-1:]:
                 continue
         else:
             name = hglib.fromunicode(uname)
         guidef.append(name)
     return guidef
示例#46
0
 def composeCommand(self):
     remotecmd = hglib.fromunicode(self.remote_text.text().trimmed())
     rev = hglib.fromunicode(self.rev_text.text().trimmed())
     startrev = hglib.fromunicode(self.startrev_text.text().trimmed())
     if self.qclone_chk.isChecked():
         cmdline = ['qclone']
         qclonedir = hglib.fromunicode(self.qclone_txt.text().trimmed())
         if qclonedir:
             cmdline += ['--patches', qclonedir]
     else:
         cmdline = ['clone']
     if self.noupdate_chk.isChecked():
         cmdline.append('--noupdate')
     if self.uncomp_chk.isChecked():
         cmdline.append('--uncompressed')
     if self.pproto_chk.isChecked():
         cmdline.append('--pull')
     if self.ui.config('http_proxy', 'host'):
         if not self.proxy_chk.isChecked():
             cmdline += ['--config', 'http_proxy.host=']
     if self.remote_chk.isChecked() and remotecmd:
         cmdline.append('--remotecmd')
         cmdline.append(remotecmd)
     if self.rev_chk.isChecked() and rev:
         cmdline.append('--rev')
         cmdline.append(rev)
     if self.startrev_chk.isChecked() and startrev:
         cmdline.append('--startrev')
         cmdline.append(startrev)
     cmdline.append('--verbose')
     src = self.getSrc()
     dest = self.getDest()
     if self.insecure_chk.isChecked() and src.startswith('https://'):
         cmdline.append('--insecure')
     cmdline.append('--')
     cmdline.append(src)
     if dest:
         cmdline.append(dest)
     self.hgcmd_txt.setText(hglib.tounicode(' '.join(['hg'] + cmdline)))
     return cmdline
示例#47
0
 def _initGraph(self):
     branch = self.filterbranch
     allparents = self.allparents
     showhidden = self.showhidden
     self.invalidateCache()
     if self.revset and self.filterbyrevset:
         grapher = revision_grapher(self.repo,
                                    branch=hglib.fromunicode(branch),
                                    revset=self.revset,
                                    showhidden=showhidden)
         self.graph = Graph(self.repo, grapher, include_mq=False)
     else:
         grapher = revision_grapher(self.repo,
                                    branch=hglib.fromunicode(branch),
                                    allparents=allparents,
                                    showhidden=showhidden)
         self.graph = Graph(self.repo, grapher, include_mq=True)
     self.rowcount = 0
     self.layoutChanged.emit()
     self.ensureBuilt(row=0)
     self.showMessage.emit('')
     QTimer.singleShot(0, self, SIGNAL('filled()'))
示例#48
0
 def goto(self, rev):
     """
     Select revision 'rev' (can be anything understood by repo.changectx())
     """
     if isinstance(rev, (unicode, QString)):
         rev = hglib.fromunicode(rev)
     try:
         rev = self.repo.changectx(rev).rev()
     except error.RepoError:
         self.showMessage.emit(
             _("Can't find revision '%s'") % hglib.tounicode(str(rev)))
     except LookupError, e:
         self.showMessage.emit(hglib.tounicode(str(e)))
示例#49
0
def agettext(message, context=''):
    """Translate message and convert to local encoding
    such as 'ascii' before being returned.

    Only use this if you need to output translated messages
    to command-line interface (ie: Windows Command Prompt).
    """
    try:
        from tortoisehg.util import hglib
        u = _(message, context)
        return hglib.fromunicode(u)
    except (LookupError, UnicodeEncodeError):
        return message
示例#50
0
 def getfile(ctx, dir, fname, source):
     m = ctx.manifest()
     if fname in m:
         path = os.path.join(dir, util.localpath(fname))
         return fname, path
     elif source and source in m:
         path = os.path.join(dir, util.localpath(source))
         return source, path
     else:
         nullfile = os.path.join(qtlib.gettempdir(), 'empty')
         fp = open(nullfile, 'w')
         fp.close()
         return hglib.fromunicode(_nonexistant, 'replace'), nullfile
示例#51
0
 def qqueueDelete(self):
     uq = self.ql.item(self.ql.currentRow()).text()
     q = hglib.fromunicode(uq)
     if q == 'patches':
         return
     if qtlib.QuestionMsgBox(
             _('Confirm patch queue delete'),
             _("Do you really want to delete patch queue '%s' ?") % uq,
             parent=self,
             defaultbutton=QMessageBox.No):
         opts = ['--delete', q]
         self.needsRefresh = True
         self.qqueueCommand(opts)
示例#52
0
    def onSign(self):
        if self.cmd.core.running():
            self.set_status(_('Repository command still running'), False)
            return

        keyu = self.keyLineEdit.text()
        key = hglib.fromunicode(keyu)
        local = self.localCheckBox.isChecked()
        force = self.replaceCheckBox.isChecked()
        nocommit = self.nocommitCheckBox.isChecked()
        if self.customCheckBox.isChecked():
            msgu = self.customTextLineEdit.text()
            msg = hglib.fromunicode(msgu)
        else:
            msg = None

        user = qtlib.getCurrentUsername(self, self.repo)
        if not user:
            return

        cmd = ['sign', '--repository', self.repo.root, '--user', user]

        if key:
            cmd.append('--key=%s' % key)

        if force:
            cmd.append('--force')

        if local:
            cmd.append('--local')

        if nocommit:
            cmd.append('--no-commit')
        else:
            if msg:
                cmd.append('--message=%s' % msg)

        cmd.append(str(self.rev))
        self.cmd.run(cmd)
示例#53
0
    def update_info(self, *args):
        def set_csinfo_mode(mode):
            """Show the csinfo widget or the info text label"""
            # hide first, then show
            if mode:
                self.rev_to_match_info_text.setShown(False)
                self.rev_to_match_info.setShown(True)
            else:
                self.rev_to_match_info.setShown(False)
                self.rev_to_match_info_text.setShown(True)

        def csinfo_update(ctx):
            self.rev_to_match_info.update(ctx)
            set_csinfo_mode(True)

        def csinfo_set_text(text):
            self.rev_to_match_info_text.setText(text)
            set_csinfo_mode(False)

        self.rev_to_match_info_lbl.setText(_('Revision to Match:'))
        new_rev = hglib.fromunicode(self.rev_combo.currentText())
        if new_rev.lower() == 'null':
            self.match_btn.setEnabled(True)
            return
        try:
            csinfo_update(self.repo[new_rev])
            return
        except (error.LookupError, error.RepoLookupError, error.RepoError):
            pass

        # If we get this far, assume we are matching a revision set
        validrevset = False
        try:
            func = revset.match(self.repo.ui, new_rev)
            rset = [c for c in func(self.repo, range(len(self.repo)))]
            if len(rset) > 1:
                self.rev_to_match_info_lbl.setText(_('Revisions to Match:'))
                csinfo_set_text(_('Match any of <b><i>%d</i></b> revisions') \
                    % len(rset))
            else:
                self.rev_to_match_info_lbl.setText(_('Revision to Match:'))
                csinfo_update(rset[0])
            validrevset = True
        except (error.LookupError, error.RepoLookupError):
            csinfo_set_text(_('<b>Unknown revision!</b>'))
        except (error.ParseError):
            csinfo_set_text(_('<b>Parse Error!</b>'))
        if validrevset:
            self.match_btn.setEnabled(True)
        else:
            self.match_btn.setDisabled(True)
示例#54
0
    def _patchbombopts(self, **opts):
        """Generate opts for patchbomb by form values"""
        def headertext(s):
            # QLineEdit may contain newline character
            return re.sub(r'\s', ' ', hglib.fromunicode(s))

        opts['to'] = [headertext(self._qui.to_edit.currentText())]
        opts['cc'] = [headertext(self._qui.cc_edit.currentText())]
        opts['from'] = headertext(self._qui.from_edit.currentText())
        opts['in_reply_to'] = headertext(self._qui.inreplyto_edit.text())
        opts['flag'] = [headertext(self._qui.flag_edit.currentText())]

        if self._qui.bundle_radio.isChecked():
            assert self._outgoing  # only outgoing bundle is supported
            opts['rev'] = map(str, self._outgoingrevs)
            opts['bundle'] = True
        else:
            opts['rev'] = map(str, self._revs)

        def diffformat():
            n = self.getdiffformat()
            if n == 'hg':
                return {}
            else:
                return {n: True}

        opts.update(diffformat())

        opts.update(self.getextraopts())

        def writetempfile(s):
            fd, fname = tempfile.mkstemp(prefix='thg_emaildesc_')
            try:
                os.write(fd, s)
                return fname
            finally:
                os.close(fd)

        opts['intro'] = self._qui.writeintro_check.isChecked()
        if opts['intro']:
            opts['subject'] = headertext(self._qui.subject_edit.text())
            opts['desc'] = writetempfile(
                hglib.fromunicode(self._qui.body_edit.toPlainText()))
            # TODO: change patchbomb not to use temporary file

        # Include the repo in the command so it can be found when thg is not
        # run from within a hg path
        opts['repository'] = self._repo.root

        return opts
示例#55
0
    def dragEnterEvent(self, event):
        if event.source() is self:
            # Use the default event handler for internal dragging
            super(RepoTreeView, self).dragEnterEvent(event)
            return

        d = event.mimeData()
        for u in d.urls():
            root = paths.find_root(hglib.fromunicode(u.toLocalFile()))
            if root:
                event.setDropAction(Qt.LinkAction)
                event.accept()
                self.setState(QAbstractItemView.DraggingState)
                break
示例#56
0
    def launch(self, fname):
        fname = hglib.fromunicode(fname)
        source = self.copies.get(fname, None)
        dir1a, dir1b, dir2 = self.dirs
        rev1a, rev1b, rev2 = self.revs
        ctx1a, ctx1b, ctx2 = self.ctxs

        def getfile(ctx, dir, fname, source):
            m = ctx.manifest()
            if fname in m:
                path = os.path.join(dir, util.localpath(fname))
                return fname, path
            elif source and source in m:
                path = os.path.join(dir, util.localpath(source))
                return source, path
            else:
                nullfile = os.path.join(qtlib.gettempdir(), 'empty')
                fp = open(nullfile, 'w')
                fp.close()
                return hglib.fromunicode(_nonexistant, 'replace'), nullfile

        local, file1a = getfile(ctx1a, dir1a, fname, source)
        if ctx1b:
            other, file1b = getfile(ctx1b, dir1b, fname, source)
        else:
            other, file1b = fname, None
        fname, file2 = getfile(ctx2, dir2, fname, None)

        label1a = local + rev1a
        label1b = other + rev1b
        label2 = fname + rev2
        if ctx1b:
            label1a += '[local]'
            label1b += '[other]'
            label2 += '[merged]'

        # Function to quote file/dir names in the argument string
        replace = dict(parent=file1a,
                       parent1=file1a,
                       plabel1=label1a,
                       parent2=file1b,
                       plabel2=label1b,
                       repo=self.reponame,
                       phash1=str(ctx1a),
                       phash2=str(ctx1b),
                       chash=str(ctx2),
                       clabel=label2,
                       child=file2)
        args = ctx1b and self.mergeopts or self.diffopts
        launchtool(self.diffpath, args, replace, False)
示例#57
0
 def _verifyBad(self):
     bad = hglib.fromunicode(self._ble.text().simplified())
     try:
         ctx = self.repo[bad]
         self.badrev = ctx.rev()
         self._ble.setEnabled(False)
         self._bb.setEnabled(False)
         cmds = []
         cmds.append(self._bisectcmd(reset=True))
         cmds.append(self._bisectcmd(self.goodrev, good=True))
         cmds.append(self._bisectcmd(self.badrev, bad=True))
         self.cmd.run(*cmds)
     except (error.LookupError, error.RepoLookupError), e:
         self.cmd.core.stbar.showMessage(hglib.tounicode(str(e)))
示例#58
0
 def bverify():
     bad = hglib.fromunicode(ble.text().simplified())
     try:
         ctx = repo[bad]
         self.badrev = ctx.rev()
         ble.setEnabled(False)
         bb.setEnabled(False)
         cmds = []
         cmds.append(prefix + ['--reset'])
         cmds.append(prefix + ['--good', str(self.goodrev)])
         cmds.append(prefix + ['--bad', str(self.badrev)])
         self.cmd.run(*cmds)
     except error.RepoLookupError, e:
         self.cmd.core.stbar.showMessage(hglib.tounicode(str(e)))
示例#59
0
    def strip(self):
        # Note that we have discussed that --hidden should only be passed to
        # mercurial commands when hidden revisions are shown.
        # However in the case of strip we can always pass it --hidden safely,
        # since strip will always strip all the descendants of a revision.
        # Thus in this case --hidden will just let us choose a hidden revision
        # as the base revision to strip.
        cmdline = [
            'strip', '--repository', self.repo.root, '--verbose', '--hidden'
        ]
        rev = hglib.fromunicode(self.rev_combo.currentText())
        if not rev:
            return
        cmdline.append(rev)

        if self.discard_chk.isChecked():
            cmdline.append('--force')
        else:
            try:
                node = self.repo[rev]
            except (error.LookupError, error.RepoLookupError, error.RepoError):
                return

            def isclean():
                """return whether WD is changed"""
                wc = self.repo[None]
                return not (wc.modified() or wc.added() or wc.removed())

            if not isclean():
                main = _("Detected uncommitted local changes.")
                text = _("Do you want to discard them and continue?")
                labels = ((QMessageBox.Yes, _('&Yes (--force)')),
                          (QMessageBox.No, _('&No')))
                if qtlib.QuestionMsgBox(_('Confirm Strip'),
                                        main,
                                        text,
                                        labels=labels,
                                        parent=self):
                    cmdline.append('--force')
                else:
                    return

        # backup options
        if self.nobackup_chk.isChecked():
            cmdline.append('--nobackup')

        # start the strip
        self.repo.incrementBusyCount()
        self.cmd.run(cmdline)
示例#60
0
 def accept(self):
     self.newpatchname = hglib.fromunicode(self.le.text())
     if self.newpatchname != self.oldpatchname:
         res = checkPatchname(self.repo.root, self.repo.thgactivemqname,
                              self.newpatchname, self)
         if not res:
             return
         cmdline = [
             'qrename', '--repository', self.repo.root, '--',
             self.oldpatchname, self.newpatchname
         ]
         self.repo.incrementBusyCount()
         self.cmd.run(cmdline)
     else:
         self.close()