Esempio n. 1
0
 def _renameQueue(self):
     curname = self._activeName()
     newname = self._getNewName(_('Rename Patch Queue'),
                                _("Rename patch queue '%s' to") % curname,
                                _('Rename'))
     if newname and curname != newname:
         self._runQqueue('rename', newname)
Esempio n. 2
0
    def updateModel(self, wctx, wstatus, patchecked):
        self.tv.setSortingEnabled(False)
        if self.tv.model():
            checked = self.tv.model().getChecked()
        else:
            checked = patchecked
            if self.pats and not checked:
                qtlib.WarningMsgBox(_('No appropriate files'),
                                    _('No files found for this operation'),
                                    parent=self)
        ms = hglib.readmergestate(self.repo)
        tm = WctxModel(self._repoagent, wctx, wstatus, ms, self.pctx,
                       self.savechecks, self.opts, checked, self,
                       checkable=self.checkable, defcheck=self.defcheck)
        if self.checkable:
            tm.checkToggled.connect(self.checkToggled)
            tm.checkCountChanged.connect(self.updateCheckCount)
        self.savechecks = True

        oldtm = self.tv.model()
        self.tv.setModel(tm)
        if oldtm:
            oldtm.deleteLater()
        self.tv.setSortingEnabled(True)
        self.tv.setColumnHidden(COL_PATH, bool(wctx.p2()) or not self.checkable)
        self.tv.setColumnHidden(COL_MERGE_STATE, not tm.anyMerge())
        if self.checkable:
            self.updateCheckCount()

        # remove non-existent file from partials table because model changed
        for file in self.partials.keys():
            if file not in tm.checked:
                del self.partials[file]

        for col in (COL_PATH, COL_STATUS, COL_MERGE_STATE):
            w = self.tv.sizeHintForColumn(col)
            self.tv.setColumnWidth(col, w)
        for col in (COL_PATH_DISPLAY, COL_EXTENSION, COL_SIZE):
            self.tv.resizeColumnToContents(col)

        # reset selection, or select first row
        curidx = tm.index(0, 0)
        selmodel = self.tv.selectionModel()
        flags = QItemSelectionModel.Select | QItemSelectionModel.Rows
        if self.reselection:
            selected, current = self.reselection
            for i, row in enumerate(tm.getAllRows()):
                if row[COL_PATH] in selected:
                    selmodel.select(tm.index(i, 0), flags)
                if row[COL_PATH] == current:
                    curidx = tm.index(i, 0)
        else:
            selmodel.select(curidx, flags)
        selmodel.currentChanged.connect(self.onCurrentChange)
        selmodel.selectionChanged.connect(self.onSelectionChange)
        if curidx and curidx.isValid():
            selmodel.setCurrentIndex(curidx, QItemSelectionModel.Current)
        self.onSelectionChange()

        self._togglefileshortcut.setEnabled(True)
Esempio n. 3
0
    def dialog_response(self, dialog, response_id):
        # User-defined buttons
        actmap = self.get_action_map()
        if actmap.has_key(response_id):
            actmap[response_id]()
        # Forced close
        elif response_id == RESPONSE_FORCE_CLOSE:
            if self.cmd.is_alive():
                self.abort()
            self.store_settings()
            self.destroy()
            return # close dialog
        # Cancel button or dialog closing by the user
        elif response_id in (gtk.RESPONSE_CLOSE, gtk.RESPONSE_DELETE_EVENT):
            if self.cmd.is_alive():
                ret = Confirm(_('Confirm Abort'), [], self,
                              _('Do you want to abort?')).run()
                if ret == gtk.RESPONSE_YES:
                    self.abort()
            else:
                close = self.before_close()
                if close:
                    self.store_settings()
                    self.destroy()
                    return # close dialog
        # Abort button
        elif response_id == gtk.RESPONSE_CANCEL:
            self.abort()
        else:
            raise _('unexpected response id: %s') % response_id

        self.run() # don't close dialog
Esempio n. 4
0
    def show_patches_cmenu(self):
        sel = self.list.get_selection()
        patches = []
        for path in sel.get_selected_rows()[1]:
            row = self.model[path]
            if row[MQ_INDEX] in (INDEX_SEPARATOR, INDEX_QPARENT):
                continue
            patches.append(row[MQ_NAME])

        incl_applied, incl_unapplied = False, False
        for patch in patches:
            if self.is_applied(patch):
                incl_applied = True
            else:
                incl_unapplied = True

        m = gtklib.MenuBuilder()
        if incl_unapplied:
            m.append(_('_Delete'), lambda *a: self.qdelete(patches),
                     gtk.STOCK_DELETE)
        if self.has_applied() and incl_unapplied:
            m.append(_('F_old'), lambda *a: self.qfold(patches),
                     gtk.STOCK_DIRECTORY)
        if not incl_applied and incl_unapplied:
            sub = self.create_reorder_menu()
            m.append_submenu(_('Reorder'), sub, gtk.STOCK_INDEX)

        menu = m.build()
        if len(menu.get_children()) > 0:
            menu.show_all()
            menu.popup(None, None, None, 0, 0)
Esempio n. 5
0
    def accept(self):
        # If the editor has been modified, we implicitly accept the changes
        acceptresolution = self.editor.isModified()
        if not acceptresolution:
            action = QMessageBox.warning(self,
                _("Warning"),
                _("You have marked all rejected patch chunks as resolved yet "
                  "you have not modified the file on the edit panel.\n\n"
                  "This probably means that no code from any of the rejected "
                  "patch chunks made it into the file.\n\n"
                  "Are you sure that you want to leave the file as is and "
                  "consider all the rejected patch chunks as resolved?\n\n"
                  "Doing so may delete them from a shelve, for example, which "
                  "would mean that you would lose them forever!\n\n"
                  "Click Yes to accept the file as is or No to continue "
                  "resolving the rejected patch chunks."),
                QMessageBox.Yes, QMessageBox.No)
            if action == QMessageBox.Yes:
                acceptresolution = True

        if acceptresolution:
            if not qscilib.writeFile(self.editor, hglib.tounicode(self.path),
                                     self._textEncoding()):
                return
            self.saveSettings()
            super(RejectsDialog, self).accept()
Esempio n. 6
0
    def runCommand(self):
        # check inputs
        fullsrc, fulldest = self._sourceFile(), self._destinationFile()
        if not os.path.exists(fullsrc):
            qtlib.WarningMsgBox(self.msgTitle, _('Source does not exist.'))
            return cmdcore.nullCmdSession()
        if not fullsrc.startswith(self._repoagent.rootPath()):
            qtlib.ErrorMsgBox(self.errTitle,
                    _('The source must be within the repository tree.'))
            return cmdcore.nullCmdSession()
        if not fulldest.startswith(self._repoagent.rootPath()):
            qtlib.ErrorMsgBox(self.errTitle,
                    _('The destination must be within the repository tree.'))
            return cmdcore.nullCmdSession()
        if os.path.isfile(fulldest) and not self.isCaseFoldingOnWin():
            res = qtlib.QuestionMsgBox(self.msgTitle, '<p>%s</p><p>%s</p>' %
                    (_('Destination file already exists.'),
                    _('Are you sure you want to overwrite it ?')),
                    defaultbutton=QMessageBox.No)
            if not res:
                return cmdcore.nullCmdSession()

        cmdline = self.compose_command()
        self.show_command(cmdline)
        return self._repoagent.runCommand(cmdline, self)
Esempio n. 7
0
def dispatch(args):
    "run the command specified in args"
    try:
        u = _ui.ui()
        if '--traceback' in args:
            u.setconfig('ui', 'traceback', 'on')
        if '--debugger' in args:
            pdb.set_trace()
        return _runcatch(u, args)
    except SystemExit:
        pass
    except KeyboardInterrupt:
        print _('\nCaught keyboard interrupt, aborting.\n')
    except:
        from tortoisehg.hgtk.bugreport import run
        if '--debugger' in args:
            pdb.post_mortem(sys.exc_info()[2])
        error = traceback.format_exc()
        opts = {}
        opts['cmd'] = ' '.join(sys.argv[1:])
        opts['error'] = error
        opts['nofork'] = True
        if gtkmainalive:
            dlg = run(u, **opts)
            dlg.display()
            dlg.show_all()
        else:
            gtkrun(run, u, **opts)
Esempio n. 8
0
 def _addRevertTargetCombo(self, rev):
     if rev is None:
         raise ValueError('Cannot revert to working directory')
     self.revcombo = QComboBox()
     revnames = ['revision %d' % rev]
     repo = self._repoagent.rawRepo()
     ctx = repo[rev]
     parents = ctx.parents()[:2]
     if len(parents) == 1:
         parentdesctemplate = ("revision %d's parent (i.e. revision %d)",)
     else:
         parentdesctemplate = (
             _("revision %d's first parent (i.e. revision %d)"),
             _("revision %d's second parent (i.e. revision %d)"),
         )
     for n, pctx in enumerate(parents):
         if pctx.node() == nullid:
             revdesc = _('null revision (i.e. remove file(s))')
         else:
             revdesc = parentdesctemplate[n] % (rev, pctx.rev())
         revnames.append(revdesc)
     self.revcombo.addItems(revnames)
     reverttargets = [ctx] + parents
     for n, ctx in enumerate(reverttargets):
         self.revcombo.setItemData(n, ctx.hex())
     self.layout().addWidget(self.revcombo)
Esempio n. 9
0
        def createcombo(path, label, title, bundle=False):
            # comboentry
            model = gtk.ListStore(str)
            combo = gtk.ComboBoxEntry(model, 0)
            combo.set_size_request(280, -1)
            combo.size_request()
            entry = combo.get_child()
            entry.set_text(path)
            entry.set_position(-1)
            entry.connect('activate',
                          lambda b: self.response(gtk.RESPONSE_OK))

            # replace the drop-down widget so we can modify it's properties
            combo.clear()
            cell = gtk.CellRendererText()
            cell.set_property('ellipsize', pango.ELLIPSIZE_MIDDLE)
            combo.pack_start(cell)
            combo.add_attribute(cell, 'text', 0)

            # browse button
            browse = gtk.Button(_('Browse...'))
            browse.connect('clicked', self.browse_clicked, title, entry)

            if bundle:
                # bundle button
                bundlebtn = gtk.Button(_('Bundle...'))
                bundlebtn.connect('clicked', self.bundle_clicked, 
                                  _('Select a Mercurial Bundle'), entry)
                table.add_row(label, combo, 0, browse, bundlebtn)
            else:
                table.add_row(label, combo, 0, browse)

            return model, combo
Esempio n. 10
0
class PatchFileData(_AbstractFileData):

    def load(self, changeselect=False, force=False):
        ctx = self._ctx
        wfile = self._wfile
        maxdiff = ctx._repo.maxdiff

        self.error = None
        self.flabel = u'<b>%s</b>' % self.filePath()

        try:
            self.diff = ctx.thgmqpatchdata(wfile)
            flags = ctx.flags(wfile)
        except EnvironmentError, e:
            self.error = hglib.tounicode(str(e))
            return

        if flags == 'x':
            self.elabel = _("exec mode has been "
                            "<font color='red'>set</font>")
        elif flags == '-':
            self.elabel = _("exec mode has been "
                            "<font color='red'>unset</font>")
        elif flags == 'l':
            self.flabel += _(' <i>(is a symlink)</i>')

        # Do not show patches that are too big or may be binary
        if not force:
            self.error = _checkdifferror(self.diff, maxdiff)
            if self.error:
                self.error += u'\n\n' + forcedisplaymsg
Esempio n. 11
0
 def getpass(self, prompt=None, default=None):
     # send request to main thread, await response
     self.dialogq.put( (prompt or _('password: '******'response expected'))
     return r
Esempio n. 12
0
 def command_done(self, returncode, useraborted, *args):
     if returncode == 0:
         self.cmd.set_result(_('Archived successfully'), style='ok')
     elif useraborted:
         self.cmd.set_result(_('Canceled archiving'), style='error')
     else:
         self.cmd.set_result(_('Failed to archive'), style='error')
Esempio n. 13
0
 def menuRequest(self, point):
     'context menu request for unknown list'
     point = self.unknownlist.viewport().mapToGlobal(point)
     selected = [self.lclunknowns[i.row()]
                 for i in sorted(self.unknownlist.selectedIndexes())]
     if len(selected) == 0:
         return
     if not self.contextmenu:
         self.contextmenu = QMenu(self)
         self.contextmenu.setTitle(_('Add ignore filter...'))
     else:
         self.contextmenu.clear()
     filters = []
     if len(selected) == 1:
         local = selected[0]
         filters.append([local])
         dirname = os.path.dirname(local)
         while dirname:
             filters.append([dirname])
             dirname = os.path.dirname(dirname)
         base, ext = os.path.splitext(local)
         if ext:
             filters.append(['*'+ext])
             filters.append(['**'+ext])
     else:
         filters.append(selected)
     for f in filters:
         n = len(f) == 1 and f[0] or _('selected files')
         a = self.contextmenu.addAction(_('Ignore ') + hglib.tounicode(n))
         a._patterns = f
         a.triggered.connect(self.insertFilters)
     self.contextmenu.exec_(point)
Esempio n. 14
0
 def updatestatus(self):
     if not self.curitems:
         text = _('No items to display')
     else:
         num = dict(count=len(self.showitems), total=len(self.curitems))
         text = _('Displaying %(count)d of %(total)d items') % num
     self.statuslabel.setText(text)
Esempio n. 15
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)))
Esempio n. 16
0
    def refreshWctx(self):
        if self.refthread:
            self.refreshWctxLater.start()
            return
        self.refreshWctxLater.stop()
        self.fileview.clearDisplay()

        # store selected paths or current path
        model = self.tv.model()
        if model and model.rowCount(QModelIndex()):
            smodel = self.tv.selectionModel()
            curidx = smodel.currentIndex()
            if curidx.isValid():
                curpath = model.getRow(curidx)[COL_PATH]
            else:
                curpath = None
            spaths = [model.getRow(i)[COL_PATH] for i in smodel.selectedRows()]
            self.reselection = spaths, curpath
        else:
            self.reselection = None

        if self.checkable:
            self.checkAllNoneBtn.setEnabled(False)
        self.refreshBtn.setEnabled(False)
        self.progress.emit(*cmdui.startProgress(_('Refresh'), _('status')))
        self.refthread = StatusThread(self.repo, self.pctx, self.pats, self.opts)
        self.refthread.finished.connect(self.reloadComplete)
        self.refthread.showMessage.connect(self.reloadFailed)
        self.refthread.start()
Esempio n. 17
0
    def validatePage(self):
        if not self._cmdsession.isFinished():
            return False

        if len(self.repo[None].parents()) == 1:
            # commit succeeded, repositoryChanged() called wizard().next()
            if self.field('skiplast').toBool():
                self.wizard().close()
            return True

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

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

        opts = {'verbose': True,
                'message': self.msgEntry.text(),
                'user': user,
                'subrepos': bool(self.opts.get('recurseinsubrepos')),
                'date': hglib.tounicode(self.opts.get('date')),
                }
        commandlines = [hglib.buildcmdargs('commit', **opts)]
        pushafter = self.repo.ui.config('tortoisehg', 'cipushafter')
        if pushafter:
            cmd = ['push', hglib.tounicode(pushafter)]
            commandlines.append(cmd)
        self._cmdlog.show()
        sess = self._repoagent.runCommandSequence(commandlines, self)
        self._cmdsession = sess
        sess.commandFinished.connect(self.onCommandFinished)
        sess.outputReceived.connect(self._cmdlog.appendLog)
        return False
Esempio n. 18
0
 def before_close(self):
     if len(self.cslist.get_items()) != 0 and not self.done:
         ret = gdialog.Confirm(_("Confirm Close"), [], self, _("Do you want to close?")).run()
         if ret != gtk.RESPONSE_YES:
             return False  # don't close
         self.unlink_all_tempfiles()
     return True
Esempio n. 19
0
 def isComplete(self):
     'should Next button be sensitive?'
     if not self.mergecomplete:
         return False
     ucount = 0
     rcount = 0
     for root, path, status in thgrepo.recursiveMergeStatus(self.repo):
         if status == 'u':
             ucount += 1
         if status == 'r':
             rcount += 1
     if ucount:
         if self.field('autoresolve').toBool():
             # if autoresolve is enabled, we know these were real conflicts
             self.reslabel.setText(_('%d files have <b>merge conflicts</b> '
                                     'that must be <a href="resolve">'
                                     '<b>resolved</b></a>') % ucount)
         else:
             # else give a calmer indication of conflicts
             self.reslabel.setText(_('%d files were modified on both '
                                     'branches and must be <a href="resolve">'
                                     '<b>resolved</b></a>') % ucount)
         return False
     elif rcount:
         self.reslabel.setText(_('No merge conflicts, ready to commit or '
                                 '<a href="resolve"><b>review</b></a>'))
     else:
         self.reslabel.setText(_('No merge conflicts, ready to commit'))
     return True
Esempio n. 20
0
    def get_commit_message(self, parameters, logmessage):
        commonurl = ""
        commonroot = ""
        bugid = ""
        bstrarray = _midlSAFEARRAY(comtypes.BSTR)
        pathlist = bstrarray.from_param(())

        bugtr = self._get_bugtraq_object()
        if bugtr is None:
            return ""
        try:
            if self.supports_bugtraq2_interface():
                (bugid, revPropNames, revPropValues,
                 newmessage) = bugtr.GetCommitMessage2(0, parameters,
                                                       commonurl, commonroot,
                                                       pathlist, logmessage,
                                                       bugid)
            else:
                newmessage = bugtr.GetCommitMessage(0, parameters, commonroot,
                                                    pathlist, logmessage)
        except COMError:
            qtlib.ErrorMsgBox(
                _('Issue Tracker Plugin Error'),
                _('Error getting commit message information from Issue Tracker plugin'
                  ))
            return ""

        return newmessage
Esempio n. 21
0
 def update_info(self):
     self.p1_info.update(self.ctxs[0].node())
     merge = len(self.ctxs) == 2
     if merge:
         self.p2_info.update(self.ctxs[1])
     new_rev = hglib.fromunicode(self.rev_combo.currentText())
     if new_rev == 'null':
         self.target_info.setText(_('remove working directory'))
         self.commandChanged.emit()
         return
     try:
         new_ctx = self.repo[new_rev]
         if not merge and new_ctx.rev() == self.ctxs[0].rev() \
                 and not new_ctx.bookmarks():
             self.target_info.setText(_('(same as parent)'))
         else:
             self.target_info.update(self.repo[new_rev])
         # only show the path combo when there are multiple paths
         # and the target revision has subrepos
         showpathcombo = self.path_combo.count() > 1 and \
             '.hgsubstate' in new_ctx
         self.path_combo_label.setVisible(showpathcombo)
         self.path_combo.setVisible(showpathcombo)
     except (error.LookupError, error.RepoError, EnvironmentError):
         self.target_info.setText(_('unknown revision!'))
     self.commandChanged.emit()
Esempio n. 22
0
 def selpretty(self, selected):
     str = ''
     for h in self.header:
         if h.startswith('index '):
             str += _('this modifies a binary file (all or nothing)\n')
             break
         if self.pretty_re.match(h):
             str += hglib.toutf(h)
             if self.binary():
                 str += _('this is a binary file\n')
             break
         if h.startswith('---'):
             hunks = len(self.hunks)
             shunks, lines, slines = 0, 0, 0
             for i, h in enumerate(self.hunks):
                 lines += h.added + h.removed
                 if selected(i):
                     shunks += 1
                     slines += h.added + h.removed
             str += '<span foreground="blue">'
             str += _('total: %d hunks (%d changed lines); '
                     'selected: %d hunks (%d changed lines)') % (hunks,
                             lines, shunks, slines)
             str += '</span>'
             break
         str += hglib.toutf(h)
     return str
Esempio n. 23
0
 def command_done(self, returncode, useraborted, *args):
     if returncode == 0:
         self.cmd.set_result(_('Finished'), style='ok')
     elif useraborted:
         self.cmd.set_result(_('Canceled'), style='error')
     else:
         self.cmd.set_result(_('Failed'), style='error')
Esempio n. 24
0
    def checkResolve(self):
        for root, path, status in thgrepo.recursiveMergeStatus(self.repo):
            if status == 'u':
                txt = _('Graft generated merge <b>conflicts</b> that must '
                        'be <a href="resolve"><b>resolved</b></a>')
                self.graftbtn.setEnabled(False)
                break
        else:
            self.graftbtn.setEnabled(True)
            txt = _('You may continue the graft')
        self._stbar.showMessage(txt)

        currgraftrevs = self.graftstate()
        if currgraftrevs:
            def findrev(rev, revlist):
                rev = self.repo[rev].rev()
                for n, r in enumerate(revlist):
                    r = self.repo[r].rev()
                    if rev == r:
                        return n
                return None
            idx = findrev(currgraftrevs[0], self.sourcelist)
            if idx is not None:
                self._updateSource(idx)
            self.abortbtn.setEnabled(True)
            self.graftbtn.setText('Continue')
            return True
        else:
            self.abortbtn.setEnabled(False)
            return False
Esempio n. 25
0
 def setRenameCopy(self):
     if self.copy_chk.isChecked():
         self.msgTitle = _('Copy')
         self.errTitle = _('Copy Error')
     else:
         self.msgTitle = _('Rename')
         self.errTitle = _('Rename Error')
Esempio n. 26
0
 def _updateSourceTitle(self, idx):
     numrevs = len(self.sourcelist)
     if numrevs <= 1:
         title = _('Graft changeset')
     else:
         title = _('Graft changeset #%d of %d') % (idx + 1, numrevs)
     self.srcb.setTitle(title)
Esempio n. 27
0
    def qfold(self, patch):
        """
        [MQ] Execute 'qfold' command.

        patch: a patch name or an index number, or its list.
        """
        if not patch or not self.has_applied():
            return
        if isinstance(patch, (basestring, int, long)):
            patch = [patch]
        unapplied = [p for p in patch if not self.is_applied(p)]
        if not unapplied:
            return
        data = dict(qtip=self.get_qtip_patchname())
        if len(unapplied) == 1:
            data.update(target=unapplied[0])
            ret = gdialog.Confirm(_('Confirm Fold'), [], None,
                    _("Do you want to fold un-applied patch '%(target)s'"
                      " into current patch '%(qtip)s'?") % data).run()
        else:
            ret = gdialog.Confirm(_('Confirm Fold'), unapplied, None,
                    _("Do you want to fold following un-applied patches"
                      " into the current patch '%(qtip)s'?") % data).run()
        if ret != gtk.RESPONSE_YES:
            return
        cmdline = ['hg', 'qfold', '--'] + unapplied
        self.cmd.execute(cmdline, self.cmd_done)
Esempio n. 28
0
def qreorder(ui, repo, *patches, **opts):
    """move patches to the beginning or after the specified patch"""
    after = opts['after'] or None
    q = repo.mq
    if any(n not in q.series for n in patches):
        raise util.Abort(_('unknown patch to move specified'))
    if after in patches:
        raise util.Abort(_('invalid patch position specified'))
    if any(q.isapplied(n) for n in patches):
        raise util.Abort(_('cannot move applied patches'))

    if after is None:
        at = 0
    else:
        try:
            at = q.series.index(after) + 1
        except ValueError:
            raise util.Abort(_('patch %s not in series') % after)
    if at < q.seriesend(True):
        raise util.Abort(_('cannot move into applied patches'))

    wlock = repo.wlock()
    try:
        _applymovemqpatches(q, after, patches)
        q.savedirty()
    finally:
        wlock.release()
Esempio n. 29
0
    def remove_tag(self):
        # gather input data
        is_local = self.localchk.get_active()
        name = self.tagentry.get_text()
        eng_msg = self.engchk.get_active()
        use_msg = self.customchk.get_active()

        # verify input
        if name == "":
            dialog.error_dialog(self, _("Tag name is empty"), _("Please select tag name to remove"))
            self.tagentry.grab_focus()
            return False

        if use_msg:
            message = self.msgentry.get_text()
        else:
            message = ""

        try:
            self.remove_hg_tag(name, message, is_local, english=eng_msg)
            dialog.info_dialog(self, _("Tagging completed"), _('Tag "%s" has been removed') % name)
            self.update_tagcombo()
        except util.Abort, inst:
            dialog.error_dialog(self, _("Error in tagging"), str(inst))
            return False
Esempio n. 30
0
def debuggethostfingerprint(ui, repo, source='default'):
    """retrieve a fingerprint of the server certificate

    The server certificate is not verified.
    """
    source = ui.expandpath(source)
    u = util.url(source)
    scheme = (u.scheme or '').split('+')[-1]
    host = u.host
    port = util.getport(u.port or scheme or '-1')
    if scheme != 'https' or not host or not (0 <= port <= 65535):
        raise util.Abort(_('unsupported URL: %s') % source)

    sock = socket.socket()
    try:
        sock.connect((host, port))
        sock = sslutil.wrapsocket(sock, None, None, ui, serverhostname=host)
        peercert = sock.getpeercert(True)
        if not peercert:
            raise util.Abort(_('%s certificate error: no certificate received')
                             % host)
    finally:
        sock.close()

    s = util.sha1(peercert).hexdigest()
    ui.write(':'.join([s[x:x + 2] for x in xrange(0, len(s), 2)]), '\n')
Esempio n. 31
0
    def run(self):
        msg = None
        if not self.dialog.server:
            msg = _("Invalid Settings - The ReviewBoard server is not setup")
        elif not self.dialog.user:
            msg = _("Invalid Settings - Please provide your ReviewBoard username")
        else:
            rb = extensions.find("reviewboard")
            try:
                pwd = self.dialog.password
                #if we don't have a password send something here to skip
                #the cli getpass in the extension. We will set the password
                #later
                if not pwd:
                    pwd = "None"

                self.reviewboard = rb.make_rbclient(self.dialog.server,
                                                    self.dialog.user,
                                                    pwd)
                self.loadCombos()

            except rb.ReviewBoardError, e:
                msg = e.msg
            except TypeError:
                msg = _("Invalid reviewboard plugin. Please download the "
                        "Mercurial reviewboard plugin version 3.5 or higher "
                        "from the website below.\n\n %s") % \
                        u'http://bitbucket.org/mdelagra/mercurial-reviewboard/'
Esempio n. 32
0
    def __init__(self, opts, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('MQ options'))

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.forcecb = QCheckBox(
            _('Force push or pop (--force)'))
        layout.addWidget(self.forcecb)

        self.keepcb = QCheckBox(
            _('Tolerate non-conflicting local changes (--keep-changes)'))
        layout.addWidget(self.keepcb)

        self.forcecb.setChecked(opts.get('force', False))
        self.keepcb.setChecked(opts.get('keep_changes', False))

        for cb in [self.forcecb, self.keepcb]:
            cb.clicked.connect(self._resolveopts)

        BB = QDialogButtonBox
        bb = QDialogButtonBox(BB.Ok|BB.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        self.bb = bb
        layout.addWidget(bb)
Esempio n. 33
0
def _createPrompt(parent, files):
    return qtlib.CustomPrompt(
        _('Confirm Add'),
        _('Some of the files that you have selected are of a size '
          'over 10 MB.  You may make more efficient use of disk space '
          'by adding these files as largefiles, which will store only the '
          'most recent revision of each file in your local repository, '
          'with older revisions available on the server.  Do you wish '
          'to add these files as largefiles?'), parent,
        (_('Add as &Largefiles'), _('Add as &Normal Files'), _('Cancel')), 0,
        2, files)
Esempio n. 34
0
def _checkdifferror(data, maxdiff):
    p = _('Diff not displayed: ')
    size = len(data)
    if size > maxdiff:
        return p + _('File is larger than the specified max size.\n'
                     'maxdiff = %s KB') % (maxdiff // 1024)
    elif '\0' in data:
        return p + _('File is binary')
    elif _exceedsMaxLineLength(data):
        # it's incredibly slow to render long line by QScintilla
        return p + _('File may be binary (maximum line length exceeded)')
Esempio n. 35
0
def _dispatch(orig, req):
    ui = req.ui
    try:
        return orig(req)
    except subrepo.SubrepoAbort, e:
        errormsg = str(e)
        label = 'ui.error'
        if e.subrepo:
            label += ' subrepo=%s' % urllib.quote(e.subrepo)
        ui.write_err(_('abort: ') + errormsg + '\n', label=label)
        if e.hint:
            ui.write_err(_('hint: ') + str(e.hint) + '\n', label=label)
Esempio n. 36
0
 def _checkRenamed(self, repo, ctx, pctx, wfile):
     m = match.exact(repo, '', [wfile])
     copy = copies.pathcopies(pctx, ctx, match=m)
     oldname = copy.get(wfile)
     if not oldname:
         self.flabel += _(' <i>(was added)</i>')
         return
     fr = hglib.tounicode(oldname)
     if oldname in ctx:
         self.flabel += _(' <i>(copied from %s)</i>') % fr
     else:
         self.flabel += _(' <i>(renamed from %s)</i>') % fr
     return oldname
Esempio n. 37
0
def rebase(ui, repoagent, *pats, **opts):
    """rebase dialog"""
    from tortoisehg.hgqt import rebase as rebasemod
    repo = repoagent.rawRepo()
    if os.path.exists(repo.vfs.join('rebasestate')):
        # TODO: move info dialog into RebaseDialog if possible
        qtlib.InfoMsgBox(
            hglib.tounicode(_('Rebase already in progress')),
            hglib.tounicode(_('Resuming rebase already in '
                              'progress')))
    elif not opts['source'] or not opts['dest']:
        raise util.Abort(_('You must provide source and dest arguments'))
    return rebasemod.RebaseDialog(repoagent, None, **opts)
Esempio n. 38
0
def _runcommand(ui, options, cmd, cmdfunc):
    def checkargs():
        try:
            return cmdfunc()
        except error.SignatureError:
            raise error.CommandError(cmd, _("invalid arguments"))

    if options['profile']:
        format = ui.config('profiling', 'format', default='text')

        if not format in ['text', 'kcachegrind']:
            ui.warn(
                _("unrecognized profiling format '%s'"
                  " - Ignored\n") % format)
            format = 'text'

        output = ui.config('profiling', 'output')

        if output:
            path = ui.expandpath(output)
            ostream = open(path, 'wb')
        else:
            ostream = sys.stderr

        try:
            from mercurial import lsprof
        except ImportError:
            raise util.Abort(
                _('lsprof not available - install from '
                  'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
        p = lsprof.Profiler()
        p.enable(subcalls=True)
        try:
            return checkargs()
        finally:
            p.disable()

            if format == 'kcachegrind':
                import lsprofcalltree
                calltree = lsprofcalltree.KCacheGrind(p)
                calltree.output(ostream)
            else:
                # format == 'text'
                stats = lsprof.Stats(p.getstats())
                stats.sort()
                stats.pprint(top=10, file=ostream, climit=5)

            if output:
                ostream.close()
    else:
        return checkargs()
Esempio n. 39
0
    def show_options_dialog(self, options):
        if not self.has_options():
            return ""

        bugtr = self._get_bugtraq_object()
        if bugtr is None:
            return ""
        try:
            options = bugtr.ShowOptionsDialog(0, options)
        except COMError:
            qtlib.ErrorMsgBox(_('Issue Tracker Plugin Error'),
                              _('Cannot open Plugin Options dialog'))
            return ""
        return options
Esempio n. 40
0
def package_version():
    try:
        branch, version = liveversion()

        extra = None
        if '+' in version:
            version, extra = version.split('+', 1)

        v = [int(x) for x in version.split('.')]
        while len(v) < 3:
            v.append(0)
        major, minor, periodic = v

        if extra != None:
            tagdistance = int(extra.split('-', 1)[0])
            periodic *= 10000
            if branch == 'default':
                periodic += tagdistance + 5000
            else:
                periodic += tagdistance + 1000

        return '.'.join([str(x) for x in (major, minor, periodic)])
    except:
        pass
    return _('unknown')
Esempio n. 41
0
 def _get_bugtraq_object(self):
     if self.bugtr == None:
         obj = CreateObject(self.guid)
         try:
             self.bugtr = obj.QueryInterface(IBugTraqProvider2)
         except COMError:
             if not self.errorshown:
                 self.errorshown = True
                 qtlib.ErrorMsgBox(
                     _('Issue Tracker Plugin Error'),
                     _('Could not instantiate Issue Tracker plugin COM object'
                       ),
                     _('This error will not be shown again until you restart the workbench'
                       ))
             return None
     return self.bugtr
Esempio n. 42
0
 def addglobalopts(aliases):
     if ui.verbose:
         option_lists.append((_("global options:"), globalopts))
         if name == 'shortlist':
             option_lists.append((_('use "thg help" for the full list '
                                    'of commands'), ()))
     else:
         if name == 'shortlist':
             msg = _('use "thg help" for the full list of commands '
                     'or "thg -v" for details')
         elif aliases:
             msg = _('use "thg -v help%s" to show aliases and '
                     'global options') % (name and " " + name or "")
         else:
             msg = _('use "thg -v help %s" to show global options') % name
         option_lists.append((msg, ()))
Esempio n. 43
0
def postreview(ui, repoagent, *pats, **opts):
    """post changesets to reviewboard"""
    from tortoisehg.hgqt import postreview as postreviewmod
    repo = repoagent.rawRepo()
    if 'reviewboard' not in repo.extensions():
        url = 'https://www.mercurial-scm.org/wiki/ReviewboardExtension'
        raise util.Abort(_('reviewboard extension not enabled'),
                         hint=(_('see <a href="%(url)s">%(url)s</a>') % {
                             'url': url
                         }))
    revs = opts.get('rev') or None
    if not revs and len(pats):
        revs = pats[0]
    if not revs:
        raise util.Abort(_('no revisions specified'))
    return postreviewmod.PostReviewDialog(repo.ui, repoagent, revs)
Esempio n. 44
0
def version(ui, **opts):
    """output version and copyright information"""
    ui.write(
        _('TortoiseHg Dialogs (version %s), '
          'Mercurial (version %s)\n') %
        (thgversion.version(), hglib.hgversion))
    if not ui.quiet:
        ui.write(shortlicense)
Esempio n. 45
0
 def start(self):
     if self._hwnd:
         raise RuntimeError('window already created')
     self._wndcreated.clear()
     self._thread.start()
     self._wndcreated.wait()
     if not self._hwnd:
         raise util.Abort(_('win32ill: cannot create window for messages'))
Esempio n. 46
0
def debugruncommand(ui, repoagent, *cmdline, **opts):
    """run hg command in dialog"""
    if not cmdline:
        raise util.Abort(_('no command specified'))
    dlg = cmdui.CmdSessionDialog()
    dlg.setLogVisible(ui.verbose)
    sess = repoagent.runCommand(map(hglib.tounicode, cmdline), dlg)
    dlg.setSession(sess)
    return dlg
Esempio n. 47
0
 def promptchoice(self, prompt, default=0):
     _msg, choices = self.extractchoices(prompt)
     resps = [r for r, _t in choices]
     prompt = self.label(prompt, 'ui.promptchoice')
     r = self.prompt(prompt, resps[default])
     try:
         return resps.index(r.lower())
     except ValueError:
         raise util.Abort(_('unrecognized response: %s') % r)
Esempio n. 48
0
def graft(ui, repoagent, *revs, **opts):
    """graft dialog"""
    from tortoisehg.hgqt import graft as graftmod
    repo = repoagent.rawRepo()
    revs = list(revs)
    revs.extend(opts['rev'])
    if not os.path.exists(repo.vfs.join('graftstate')) and not revs:
        raise util.Abort(_('You must provide revisions to graft'))
    return graftmod.GraftDialog(repoagent, None, source=revs)
Esempio n. 49
0
def rejects(ui, *pats, **opts):
    """manually resolve rejected patch chunks"""
    from tortoisehg.hgqt import rejects as rejectsmod
    if len(pats) != 1:
        raise util.Abort(_('You must provide the path to a file'))
    path = pats[0]
    if path.endswith('.rej'):
        path = path[:-4]
    return rejectsmod.RejectsDialog(ui, path)
Esempio n. 50
0
def validateextensions(enabledexts):
    """Report extensions which should be disabled

    Returns the dict {name: message} of extensions expected to be disabled.
    message is 'utf-8'-encoded string.
    """
    exts = {}
    if os.name != 'posix':
        exts['inotify'] = _('inotify is not supported on this platform')
    if 'win32text' in enabledexts:
        exts['eol'] = _('eol is incompatible with win32text')
    if 'eol' in enabledexts:
        exts['win32text'] = _('win32text is incompatible with eol')
    if 'perfarce' in enabledexts:
        exts['hgsubversion'] = _('hgsubversion is incompatible with perfarce')
    if 'hgsubversion' in enabledexts:
        exts['perfarce'] = _('perfarce is incompatible with hgsubversion')
    return exts
Esempio n. 51
0
def promptForLfiles(parent, ui, repo, files):
    lfiles = []
    section = 'largefiles'
    try:
        minsize = float(ui.config(section, 'minsize', default=10))
    except ValueError:
        minsize = 10
    patterns = ui.config(section, 'patterns', default=())
    if patterns:
        patterns = patterns.split(' ')
        try:
            matcher = match.match(repo.root, '', list(patterns))
        except error.Abort as e:
            qtlib.WarningMsgBox(_('Invalid Patterns'),
                                _('Failed to process largefiles.patterns.'),
                                hglib.tounicode(str(e)),
                                parent=parent)
            return None
    else:
        matcher = None
    for wfile in files:
        if matcher and matcher(wfile):
            # patterns have always precedence over size
            lfiles.append(wfile)
        else:
            # check for minimal size
            try:
                filesize = os.path.getsize(repo.wjoin(wfile))
                if filesize > minsize * 1024 * 1024:
                    lfiles.append(wfile)
            except OSError:
                pass  # file not exist or inaccessible
    if lfiles:
        ret = _createPrompt(parent, files).run()
        if ret == 0:
            # add as largefiles/bfiles
            for lfile in lfiles:
                files.remove(lfile)
        elif ret == 1:
            # add as normal files
            lfiles = []
        elif ret == 2:
            return None
    return files, lfiles
Esempio n. 52
0
def age(date):
    '''turn a (timestamp, tzoff) tuple into an age string.'''
    # This is i18n-ed version of mercurial.templatefilters.age().

    now = time.time()
    then = date[0]
    if then > now:
        return _('in the future')

    delta = int(now - then)
    if delta == 0:
        return _('now')
    if delta > agescales[0][1] * 2:
        return util.shortdate(date)

    for t, s in agescales:
        n = delta // s
        if n >= 2 or s == 1:
            return t(n) % n
Esempio n. 53
0
    def helplist(header, select=None):
        h = {}
        cmds = {}
        for c, e in table.iteritems():
            f = c.split("|", 1)[0]
            if select and not select(f):
                continue
            if (not select and name != 'shortlist'
                    and e[0].__module__ != __name__):
                continue
            if name == "shortlist" and not f.startswith("^"):
                continue
            f = f.lstrip("^")
            if not ui.debugflag and f.startswith("debug"):
                continue
            doc = e[0].__doc__
            if doc and 'DEPRECATED' in doc and not ui.verbose:
                continue
            #doc = gettext(doc)
            if not doc:
                doc = _("(no help text available)")
            h[f] = doc.splitlines()[0].rstrip()
            cmds[f] = c.lstrip("^")

        if not h:
            ui.status(_('no commands defined\n'))
            return

        ui.status(header)
        fns = sorted(h)
        m = max(map(len, fns))
        for f in fns:
            if ui.verbose:
                commands = cmds[f].replace("|", ", ")
                ui.write(" %s:\n      %s\n" % (commands, h[f]))
            else:
                ui.write('%s\n' % (util.wrap(h[f],
                                             textwidth,
                                             initindent=' %-*s   ' % (m, f),
                                             hangindent=' ' * (m + 4))))

        if not ui.quiet:
            addglobalopts(True)
Esempio n. 54
0
    def on_commit_finished(self, logmessage):
        if not self.supports_bugtraq2_interface():
            return ""

        commonroot = ""
        bstrarray = _midlSAFEARRAY(comtypes.BSTR)
        pathlist = bstrarray.from_param(())

        bugtr = self._get_bugtraq_object()
        if bugtr is None:
            return ""
        try:
            errormessage = bugtr.OnCommitFinished(0, commonroot, pathlist,
                                                  logmessage, 0)
        except COMError:
            qtlib.ErrorMsgBox(_('Issue Tracker Plugin Error'),
                              _('Error executing "commit finished" trigger'))
            return ""
        return errormessage
Esempio n. 55
0
 def retranslateUi(self, WebconfForm):
     _translate = QtCore.QCoreApplication.translate
     WebconfForm.setWindowTitle(_('Webconf'))
     self.path_label.setText(_('Config File:'))
     self.open_button.setText(_('Open'))
     self.save_button.setText(_('Save'))
     self.add_button.setText(_('Add'))
     self.edit_button.setText(_('Edit'))
     self.remove_button.setText(_('Remove'))
Esempio n. 56
0
def version():
    try:
        branch, version = liveversion()
        return version
    except:
        pass
    try:
        import __version__
        return __version__.version
    except ImportError:
        return _('unknown')
Esempio n. 57
0
def merge(ui, repoagent, *pats, **opts):
    """merge wizard"""
    from tortoisehg.hgqt import merge as mergemod
    rev = opts.get('rev') or None
    if not rev and len(pats):
        rev = pats[0]
    if not rev:
        raise util.Abort(_('Merge revision not specified or not found'))
    repo = repoagent.rawRepo()
    rev = scmutil.revsingle(repo, rev).rev()
    return mergemod.MergeDialog(repoagent, rev)
Esempio n. 58
0
def bookmark(ui, repoagent, *names, **opts):
    """add or remove a movable marker"""
    from tortoisehg.hgqt import bookmark as bookmarkmod
    repo = repoagent.rawRepo()
    rev = scmutil.revsingle(repo, opts.get('rev')).rev()
    if len(names) > 1:
        raise util.Abort(_('only one new bookmark name allowed'))
    dlg = bookmarkmod.BookmarkDialog(repoagent, rev)
    if names:
        dlg.setBookmarkName(hglib.tounicode(names[0]))
    return dlg
Esempio n. 59
0
    def helpcmd(name):
        if with_version:
            version(ui)
            ui.write('\n')

        try:
            aliases, i = cmdutil.findcmd(name, table, False)
        except error.AmbiguousCommand, inst:
            select = lambda c: c.lstrip('^').startswith(inst.args[0])
            helplist(_('list of commands:\n\n'), select)
            return
Esempio n. 60
0
def sign(ui, repoagent, *pats, **opts):
    """sign tool"""
    from tortoisehg.hgqt import sign as signmod
    repo = repoagent.rawRepo()
    if 'gpg' not in repo.extensions():
        raise util.Abort(_('Please enable the Gpg extension first.'))
    kargs = {}
    rev = len(pats) > 0 and pats[0] or None
    if rev:
        kargs['rev'] = rev
    return signmod.SignDialog(repoagent, opts=opts, **kargs)