Exemplo n.º 1
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)))
Exemplo n.º 2
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)))
Exemplo n.º 3
0
 def _getlog(self,
             paths,
             start,
             end,
             limit=0,
             discover_changed_paths=True,
             strict_node_history=False):
     # Normalize path names, svn >= 1.5 only wants paths relative to
     # supplied URL
     relpaths = []
     for p in paths:
         if not p.startswith('/'):
             p = self.module + '/' + p
         relpaths.append(p.strip('/'))
     args = [
         self.baseurl, relpaths, start, end, limit, discover_changed_paths,
         strict_node_history
     ]
     arg = encodeargs(args)
     hgexe = util.hgexecutable()
     cmd = '%s debugsvnlog' % util.shellquote(hgexe)
     stdin, stdout = util.popen2(util.quotecommand(cmd))
     stdin.write(arg)
     try:
         stdin.close()
     except IOError:
         raise util.Abort(
             _('Mercurial failed to run itself, check'
               ' hg executable is in PATH'))
     return logstream(stdout)
Exemplo n.º 4
0
 def _execute(self, cmd, *args, **kwargs):
     cmdline = [self.execmd, cmd]
     cmdline += args
     cmdline = [util.shellquote(arg) for arg in cmdline]
     cmdline += ['>', os.devnull, '2>', os.devnull]
     cmdline = util.quotecommand(' '.join(cmdline))
     self.ui.debug(cmdline, '\n')
     return os.system(cmdline)
Exemplo n.º 5
0
 def _execute(self, cmd, *args, **kwargs):
     cmdline = [self.execmd, cmd]
     cmdline += args
     cmdline = [util.shellquote(arg) for arg in cmdline]
     cmdline += ['>', os.devnull, '2>', os.devnull]
     cmdline = util.quotecommand(' '.join(cmdline))
     self.ui.debug(cmdline, '\n')
     return os.system(cmdline)
Exemplo n.º 6
0
def main():
    args = sys.argv[1:]
    if len(args) not in (2, 4):
        print 'Two or four arguments expected:'
        print sys.argv[0], '[local] [other]'
        print sys.argv[0], '[local] [base] [other] [output]'
        sys.exit(1)
    elif len(args) == 2:
        local, other = [os.path.abspath(f) for f in args]
        _base, ext = os.path.splitext(local)
    else:
        local, base, other, output = [os.path.abspath(f) for f in args]
        _base, ext = os.path.splitext(output)

    if not ext or ext.lower()[1:] not in scripts.keys():
        print 'Unsupported file type', ext
        sys.exit(1)

    proc = win32api.GetCurrentProcess()
    try:
        # This will fail on windows < NT
        filename = win32process.GetModuleFileNameEx(proc, 0)
    except:
        filename = win32api.GetModuleFileName(0)
    path = os.path.join(os.path.dirname(filename), 'diff-scripts')
    if not os.path.isdir(path):
        print 'Diff scripts not found at', path
        sys.exit(1)

    use = scripts[ext.lower()[1:]]

    if 'xls' in use[0] and os.path.basename(local) == os.path.basename(other):
        # XLS hack; Excel will not diff two files if they have the same
        # basename.
        othertmp = other + '~x1'
        shutil.copy(other, othertmp)
        other = othertmp

    if len(args) == 2:
        script = os.path.join(path, use[0])
        cmd = ['wscript', script, other, local]
    elif len(use) == 1:
        print 'Unsupported file type for merge', local
        sys.exit(1)
    else:
        script = os.path.join(path, use[1])
        cmd = ['wscript', script, output, other, local, base]

    encoding = locale.getpreferredencoding(do_setlocale=True)
    cmd = [util.shellquote(safe_encode(arg, encoding)) for arg in cmd]
    cmdline = util.quotecommand(' '.join(cmd))
    proc = subprocess.Popen(cmdline,
                            shell=True,
                            creationflags=win32con.CREATE_NO_WINDOW,
                            stderr=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stdin=subprocess.PIPE)
    return proc.communicate()
Exemplo n.º 7
0
def main():
    args = sys.argv[1:]
    if len(args) not in (2, 4):
        print 'Two or four arguments expected:'
        print sys.argv[0], '[local] [other]'
        print sys.argv[0], '[local] [base] [other] [output]'
        sys.exit(1)
    elif len(args) == 2:
        local, other = [os.path.abspath(f) for f in args]
        base, ext = os.path.splitext(local)
    else:
        local, base, other, output = [os.path.abspath(f) for f in args]
        base, ext = os.path.splitext(output)

    if not ext or ext.lower()[1:] not in scripts.keys():
        print 'Unsupported file type', ext
        sys.exit(1)

    proc = win32api.GetCurrentProcess()
    try:
        # This will fail on windows < NT
        filename = win32process.GetModuleFileNameEx(proc, 0)
    except:
        filename = win32api.GetModuleFileName(0)
    path = os.path.join(os.path.dirname(filename), 'diff-scripts')
    if not os.path.isdir(path):
        print 'Diff scripts not found at', path
        sys.exit(1)

    use = scripts[ext.lower()[1:]]

    if 'xls' in use[0] and os.path.basename(local) == os.path.basename(other):
        # XLS hack; Excel will not diff two files if they have the same
        # basename.
        othertmp = other+'~x1'
        shutil.copy(other, othertmp)
        other = othertmp

    if len(args) == 2:
        script = os.path.join(path, use[0])
        cmd = ['wscript', script, other, local]
    elif len(use) == 1:
        print 'Unsupported file type for merge', local
        sys.exit(1)
    else:
        script = os.path.join(path, use[1])
        cmd = ['wscript', script, output, other, local, base]

    encoding = locale.getpreferredencoding(do_setlocale=True)
    cmd = [util.shellquote(safe_encode(arg, encoding)) for arg in cmd]
    cmdline = util.quotecommand(' '.join(cmd))
    proc = subprocess.Popen(cmdline, shell=True,
                            creationflags=win32con.CREATE_NO_WINDOW,
                            stderr=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stdin=subprocess.PIPE)
    return proc.communicate()
Exemplo n.º 8
0
 def run_command(self, host, command, username=None, port=None):
     sshcmd = ui.config("ui", "ssh", "ssh")
     args = util.sshargs(sshcmd, host, username, port)
     cmd = '%s %s %s' % (sshcmd, args,
                         util.shellquote(''.join(command)))
     ui.debug('calling ssh: %s\n' % cmd)
     proc = subprocess.Popen(util.quotecommand(cmd), shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
     return SubprocessWrapper(proc)
Exemplo n.º 9
0
 def run_command(self, host, command, username=None, port=None):
     sshcmd = ui.config("ui", "ssh", "ssh")
     args = util.sshargs(sshcmd, host, username, port)
     cmd = '%s %s %s' % (sshcmd, args, util.shellquote(
         ' '.join(command)))
     ui.debug('calling ssh: %s\n' % cmd)
     proc = subprocess.Popen(util.quotecommand(cmd),
                             shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
     return SubprocessWrapper(proc)
Exemplo n.º 10
0
    def __call__(self, cmd, environ, cwd):
        args = [util.quotecommand(cmd), cwd or '.']
        args.extend('%s=%s' % (k, v) for k, v in environ.iteritems())
        data = '\0'.join(args)
        self.out.write(struct.pack('>cI', self.channel, len(data)))
        self.out.write(data)
        self.out.flush()

        length = self.in_.read(4)
        length, = struct.unpack('>I', length)
        if length != 4:
            raise error.Abort(_('invalid response'))
        rc, = struct.unpack('>i', self.in_.read(4))
        return rc
Exemplo n.º 11
0
    def __call__(self, cmd, environ, cwd):
        args = [util.quotecommand(cmd), os.path.abspath(cwd or '.')]
        args.extend('%s=%s' % (k, v) for k, v in environ.iteritems())
        data = '\0'.join(args)
        self.out.write(struct.pack('>cI', self.channel, len(data)))
        self.out.write(data)
        self.out.flush()

        length = self.in_.read(4)
        length, = struct.unpack('>I', length)
        if length != 4:
            raise error.Abort(_('invalid response'))
        rc, = struct.unpack('>i', self.in_.read(4))
        return rc
Exemplo n.º 12
0
        def connect_ssh(self, host, command, username=None, port=None):
            from dulwich.client import SubprocessWrapper
            from mercurial import util
            import subprocess

            sshcmd = ui.config("ui", "ssh", "ssh")
            args = util.sshargs(sshcmd, host, username, port)
            cmd = '%s %s %s' % (sshcmd, args, 
                                util.shellquote(' '.join(command)))
            ui.debug('calling ssh: %s\n' % cmd)
            print command
            proc = subprocess.Popen(util.quotecommand(cmd), shell=True,
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE)
            return SubprocessWrapper(proc)
 def run_command(self, host, command, username=None, port=None):
     # newer dulwich changes the way they pass command and parameters
     # around, so we detect that here and reformat it back to what
     # hg-git expects (e.g. "command 'arg1 arg2'")
     if len(command) > 1:
         command = ["%s '%s'" % (command[0], ' '.join(command[1:]))]
     sshcmd = ui.config("ui", "ssh", "ssh")
     args = util.sshargs(sshcmd, host, username, port)
     cmd = '%s %s %s' % (sshcmd, args,
                         util.shellquote(' '.join(command)))
     ui.debug('calling ssh: %s\n' % cmd)
     proc = subprocess.Popen(util.quotecommand(cmd), shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
     return SubprocessWrapper(proc)
Exemplo n.º 14
0
        def connect_ssh(self, host, command, username=None, port=None):
            from dulwich.client import SubprocessWrapper
            from mercurial import util
            import subprocess

            sshcmd = ui.config("ui", "ssh", "ssh")
            args = util.sshargs(sshcmd, host, username, port)
            cmd = '%s %s %s' % (sshcmd, args, util.shellquote(
                ' '.join(command)))
            ui.debug('calling ssh: %s\n' % cmd)
            print command
            proc = subprocess.Popen(util.quotecommand(cmd),
                                    shell=True,
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE)
            return SubprocessWrapper(proc)
Exemplo n.º 15
0
 def run_command(self, host, command, username=None, port=None):
     if isinstance(command, basestring):
         # 0.12.x dulwich sends the raw string
         command = [command]
     elif len(command) > 1:
         # 0.11.x dulwich sends an array of [command arg1 arg2 ...], so
         # we detect that here and reformat it back to what hg-git
         # expects (e.g. "command 'arg1 arg2'")
         command = ["%s '%s'" % (command[0], ' '.join(command[1:]))]
     sshcmd = ui.config("ui", "ssh", "ssh")
     args = util.sshargs(sshcmd, host, username, port)
     cmd = '%s %s %s' % (sshcmd, args,
                         util.shellquote(' '.join(command)))
     ui.debug('calling ssh: %s\n' % cmd)
     proc = subprocess.Popen(util.quotecommand(cmd), shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
     return SubprocessWrapper(proc)
Exemplo n.º 16
0
def launchtool(cmd, opts, replace, block):
    def quote(match):
        key = match.group()[1:]
        return util.shellquote(replace[key])
    args = ' '.join(opts)
    args = re.sub(_regex, quote, args)
    cmdline = util.shellquote(cmd) + ' ' + args
    cmdline = util.quotecommand(cmdline)
    try:
        proc = subprocess.Popen(cmdline, shell=True,
                                creationflags=openflags,
                                stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stdin=subprocess.PIPE)
        if block:
            proc.communicate()
    except (OSError, EnvironmentError), e:
        gdialog.Prompt(_('Tool launch failure'),
                       _('%s : %s') % (cmd, str(e)), None).run()
Exemplo n.º 17
0
 def run_command(self, host, command, username=None, port=None):
     if isinstance(command, basestring):
         # 0.12.x dulwich sends the raw string
         command = [command]
     elif len(command) > 1:
         # 0.11.x dulwich sends an array of [command arg1 arg2 ...], so
         # we detect that here and reformat it back to what hg-git
         # expects (e.g. "command 'arg1 arg2'")
         command = ["%s '%s'" % (command[0], ' '.join(command[1:]))]
     sshcmd = ui.config("ui", "ssh", "ssh")
     args = util.sshargs(sshcmd, host, username, port)
     cmd = '%s %s %s' % (sshcmd, args, util.shellquote(
         ' '.join(command)))
     ui.debug('calling ssh: %s\n' % cmd)
     proc = subprocess.Popen(util.quotecommand(cmd),
                             shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
     return SubprocessWrapper(proc)
Exemplo n.º 18
0
 def _getlog(self, paths, start, end, limit=0, discover_changed_paths=True,
             strict_node_history=False):
     # Normalize path names, svn >= 1.5 only wants paths relative to
     # supplied URL
     relpaths = []
     for p in paths:
         if not p.startswith('/'):
             p = self.module + '/' + p
         relpaths.append(p.strip('/'))
     args = [self.baseurl, relpaths, start, end, limit,
             discover_changed_paths, strict_node_history]
     arg = encodeargs(args)
     hgexe = util.hgexecutable()
     cmd = '%s debugsvnlog' % util.shellquote(hgexe)
     stdin, stdout = util.popen2(util.quotecommand(cmd))
     stdin.write(arg)
     try:
         stdin.close()
     except IOError:
         raise util.Abort(_('Mercurial failed to run itself, check'
                            ' hg executable is in PATH'))
     return logstream(stdout)
Exemplo n.º 19
0
    def _connect(self):
        root = self.cvsroot
        conntype = None
        user, host = None, None
        cmd = ['cvs', 'server']

        self.ui.status(_("connecting to %s\n") % root)

        if root.startswith(":pserver:"):
            root = root[9:]
            m = re.match(r'(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?(.*)',
                         root)
            if m:
                conntype = "pserver"
                user, passw, serv, port, root = m.groups()
                if not user:
                    user = "******"
                if not port:
                    port = 2401
                else:
                    port = int(port)
                format0 = ":pserver:%s@%s:%s" % (user, serv, root)
                format1 = ":pserver:%s@%s:%d%s" % (user, serv, port, root)

                if not passw:
                    passw = "A"
                    cvspass = os.path.expanduser("~/.cvspass")
                    try:
                        pf = open(cvspass)
                        for line in pf.read().splitlines():
                            part1, part2 = line.split(' ', 1)
                            # /1 :pserver:[email protected]:2401/cvsroot/foo
                            # Ah<Z
                            if part1 == '/1':
                                part1, part2 = part2.split(' ', 1)
                                format = format1
                            # :pserver:[email protected]:/cvsroot/foo Ah<Z
                            else:
                                format = format0
                            if part1 == format:
                                passw = part2
                                break
                        pf.close()
                    except IOError as inst:
                        if inst.errno != errno.ENOENT:
                            if not getattr(inst, 'filename', None):
                                inst.filename = cvspass
                            raise

                sck = socket.socket()
                sck.connect((serv, port))
                sck.send("\n".join(["BEGIN AUTH REQUEST", root, user, passw,
                                    "END AUTH REQUEST", ""]))
                if sck.recv(128) != "I LOVE YOU\n":
                    raise util.Abort(_("CVS pserver authentication failed"))

                self.writep = self.readp = sck.makefile('r+')

        if not conntype and root.startswith(":local:"):
            conntype = "local"
            root = root[7:]

        if not conntype:
            # :ext:user@host/home/user/path/to/cvsroot
            if root.startswith(":ext:"):
                root = root[5:]
            m = re.match(r'(?:([^@:/]+)@)?([^:/]+):?(.*)', root)
            # Do not take Windows path "c:\foo\bar" for a connection strings
            if os.path.isdir(root) or not m:
                conntype = "local"
            else:
                conntype = "rsh"
                user, host, root = m.group(1), m.group(2), m.group(3)

        if conntype != "pserver":
            if conntype == "rsh":
                rsh = os.environ.get("CVS_RSH") or "ssh"
                if user:
                    cmd = [rsh, '-l', user, host] + cmd
                else:
                    cmd = [rsh, host] + cmd

            # popen2 does not support argument lists under Windows
            cmd = [util.shellquote(arg) for arg in cmd]
            cmd = util.quotecommand(' '.join(cmd))
            self.writep, self.readp = util.popen2(cmd)

        self.realroot = root

        self.writep.write("Root %s\n" % root)
        self.writep.write("Valid-responses ok error Valid-requests Mode"
                          " M Mbinary E Checked-in Created Updated"
                          " Merged Removed\n")
        self.writep.write("valid-requests\n")
        self.writep.flush()
        r = self.readp.readline()
        if not r.startswith("Valid-requests"):
            raise util.Abort(_('unexpected response from CVS server '
                               '(expected "Valid-requests", but got %r)')
                             % r)
        if "UseUnchanged" in r:
            self.writep.write("UseUnchanged\n")
            self.writep.flush()
            r = self.readp.readline()
Exemplo n.º 20
0
                    files = []
                expanded.append(phrase)
            expanded.append(toolpath[pos:])
            cmdline = ' '.join(expanded + files)
        except ValueError, e:
            # '[' or ']' not found
            pass
        except TypeError, e:
            # variable expansion failed
            pass

    shell = not (len(cwd) >= 2 and cwd[0:2] == r'\\')
    try:
        if '$FILES' in cmdline:
            cmdline = cmdline.replace('$FILES', ' '.join(files))
            cmdline = util.quotecommand(cmdline)
            subprocess.Popen(cmdline, shell=shell, creationflags=openflags,
                             stderr=None, stdout=None, stdin=None, cwd=cwd)
        elif '$FILE' in cmdline:
            for file in files:
                cmd = cmdline.replace('$FILE', file)
                cmd = util.quotecommand(cmd)
                subprocess.Popen(cmd, shell=shell, creationflags=openflags,
                                 stderr=None, stdout=None, stdin=None, cwd=cwd)
        else:
            # assume filenames were expanded already
            cmdline = util.quotecommand(cmdline)
            subprocess.Popen(cmdline, shell=shell, creationflags=openflags,
                             stderr=None, stdout=None, stdin=None, cwd=cwd)
    except (OSError, EnvironmentError), e:
        QMessageBox.warning(parent,
Exemplo n.º 21
0
        except TypeError, e:
            # variable expansion failed
            cmdline = ' '.join([editor] + files)
    else:
        editor = os.environ.get('HPLUMAOR') or repo.ui.config('ui', 'editor') \
                 or os.environ.get('EDITOR', 'vi')
        cmdline = ' '.join([editor] + files)
    if os.path.basename(editor) in ('vi', 'vim', 'hplumaor'):
        res = QMessageBox.critical(parent, _('No visual editor configured'),
                                   _('Please configure a visual editor.'))
        from tortoisehg.hgqt.settings import SettingsDialog
        dlg = SettingsDialog(False, focus='tortoisehg.editor')
        dlg.exec_()
        return

    cmdline = util.quotecommand(cmdline)
    shell = not (len(cwd) >= 2 and cwd[0:2] == r'\\')
    try:
        subprocess.Popen(cmdline,
                         shell=shell,
                         creationflags=openflags,
                         stderr=None,
                         stdout=None,
                         stdin=None,
                         cwd=cwd)
    except (OSError, EnvironmentError), e:
        QMessageBox.warning(
            parent, _('Editor launch failure'),
            u'%s : %s' % (hglib.tounicode(cmdline), hglib.tounicode(str(e))))
    return False
Exemplo n.º 22
0
    def _connect(self):
        root = self.cvsroot
        conntype = None
        user, host = None, None
        cmd = ['cvs', 'server']

        self.ui.status(_("connecting to %s\n") % root)

        if root.startswith(":pserver:"):
            root = root[9:]
            m = re.match(r'(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?(.*)',
                         root)
            if m:
                conntype = "pserver"
                user, passw, serv, port, root = m.groups()
                if not user:
                    user = "******"
                if not port:
                    port = 2401
                else:
                    port = int(port)
                format0 = ":pserver:%s@%s:%s" % (user, serv, root)
                format1 = ":pserver:%s@%s:%d%s" % (user, serv, port, root)

                if not passw:
                    passw = "A"
                    cvspass = os.path.expanduser("~/.cvspass")
                    try:
                        pf = open(cvspass)
                        for line in pf.read().splitlines():
                            part1, part2 = line.split(' ', 1)
                            # /1 :pserver:[email protected]:2401/cvsroot/foo
                            # Ah<Z
                            if part1 == '/1':
                                part1, part2 = part2.split(' ', 1)
                                format = format1
                            # :pserver:[email protected]:/cvsroot/foo Ah<Z
                            else:
                                format = format0
                            if part1 == format:
                                passw = part2
                                break
                        pf.close()
                    except IOError as inst:
                        if inst.errno != errno.ENOENT:
                            if not getattr(inst, 'filename', None):
                                inst.filename = cvspass
                            raise

                sck = socket.socket()
                sck.connect((serv, port))
                sck.send("\n".join(["BEGIN AUTH REQUEST", root, user, passw,
                                    "END AUTH REQUEST", ""]))
                if sck.recv(128) != "I LOVE YOU\n":
                    raise util.Abort(_("CVS pserver authentication failed"))

                self.writep = self.readp = sck.makefile('r+')

        if not conntype and root.startswith(":local:"):
            conntype = "local"
            root = root[7:]

        if not conntype:
            # :ext:user@host/home/user/path/to/cvsroot
            if root.startswith(":ext:"):
                root = root[5:]
            m = re.match(r'(?:([^@:/]+)@)?([^:/]+):?(.*)', root)
            # Do not take Windows path "c:\foo\bar" for a connection strings
            if os.path.isdir(root) or not m:
                conntype = "local"
            else:
                conntype = "rsh"
                user, host, root = m.group(1), m.group(2), m.group(3)

        if conntype != "pserver":
            if conntype == "rsh":
                rsh = os.environ.get("CVS_RSH") or "ssh"
                if user:
                    cmd = [rsh, '-l', user, host] + cmd
                else:
                    cmd = [rsh, host] + cmd

            # popen2 does not support argument lists under Windows
            cmd = [util.shellquote(arg) for arg in cmd]
            cmd = util.quotecommand(' '.join(cmd))
            self.writep, self.readp = util.popen2(cmd)

        self.realroot = root

        self.writep.write("Root %s\n" % root)
        self.writep.write("Valid-responses ok error Valid-requests Mode"
                          " M Mbinary E Checked-in Created Updated"
                          " Merged Removed\n")
        self.writep.write("valid-requests\n")
        self.writep.flush()
        r = self.readp.readline()
        if not r.startswith("Valid-requests"):
            raise util.Abort(_('unexpected response from CVS server '
                               '(expected "Valid-requests", but got %r)')
                             % r)
        if "UseUnchanged" in r:
            self.writep.write("UseUnchanged\n")
            self.writep.flush()
            r = self.readp.readline()
Exemplo n.º 23
0
class convert_cvs(converter_source):
    def __init__(self, ui, path, rev=None):
        super(convert_cvs, self).__init__(ui, path, rev=rev)

        cvs = os.path.join(path, "CVS")
        if not os.path.exists(cvs):
            raise NoRepo(_("%s does not look like a CVS checkout") % path)

        checktool('cvs')

        self.changeset = None
        self.files = {}
        self.tags = {}
        self.lastbranch = {}
        self.socket = None
        self.cvsroot = open(os.path.join(cvs, "Root")).read()[:-1]
        self.cvsrepo = open(os.path.join(cvs, "Repository")).read()[:-1]
        self.encoding = encoding.encoding

        self._connect()

    def _parse(self):
        if self.changeset is not None:
            return
        self.changeset = {}

        maxrev = 0
        if self.rev:
            # TODO: handle tags
            try:
                # patchset number?
                maxrev = int(self.rev)
            except ValueError:
                raise util.Abort(_('revision %s is not a patchset number')
                                 % self.rev)

        d = os.getcwd()
        try:
            os.chdir(self.path)
            id = None

            cache = 'update'
            if not self.ui.configbool('convert', 'cvsps.cache', True):
                cache = None
            db = cvsps.createlog(self.ui, cache=cache)
            db = cvsps.createchangeset(self.ui, db,
                fuzz=int(self.ui.config('convert', 'cvsps.fuzz', 60)),
                mergeto=self.ui.config('convert', 'cvsps.mergeto', None),
                mergefrom=self.ui.config('convert', 'cvsps.mergefrom', None))

            for cs in db:
                if maxrev and cs.id > maxrev:
                    break
                id = str(cs.id)
                cs.author = self.recode(cs.author)
                self.lastbranch[cs.branch] = id
                cs.comment = self.recode(cs.comment)
                date = util.datestr(cs.date)
                self.tags.update(dict.fromkeys(cs.tags, id))

                files = {}
                for f in cs.entries:
                    files[f.file] = "%s%s" % ('.'.join([str(x)
                                                        for x in f.revision]),
                                              ['', '(DEAD)'][f.dead])

                # add current commit to set
                c = commit(author=cs.author, date=date,
                           parents=[str(p.id) for p in cs.parents],
                           desc=cs.comment, branch=cs.branch or '')
                self.changeset[id] = c
                self.files[id] = files

            self.heads = self.lastbranch.values()
        finally:
            os.chdir(d)

    def _connect(self):
        root = self.cvsroot
        conntype = None
        user, host = None, None
        cmd = ['cvs', 'server']

        self.ui.status(_("connecting to %s\n") % root)

        if root.startswith(":pserver:"):
            root = root[9:]
            m = re.match(r'(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?(.*)',
                         root)
            if m:
                conntype = "pserver"
                user, passw, serv, port, root = m.groups()
                if not user:
                    user = "******"
                if not port:
                    port = 2401
                else:
                    port = int(port)
                format0 = ":pserver:%s@%s:%s" % (user, serv, root)
                format1 = ":pserver:%s@%s:%d%s" % (user, serv, port, root)

                if not passw:
                    passw = "A"
                    cvspass = os.path.expanduser("~/.cvspass")
                    try:
                        pf = open(cvspass)
                        for line in pf.read().splitlines():
                            part1, part2 = line.split(' ', 1)
                            if part1 == '/1':
                                # /1 :pserver:[email protected]:2401/cvsroot/foo Ah<Z
                                part1, part2 = part2.split(' ', 1)
                                format = format1
                            else:
                                # :pserver:[email protected]:/cvsroot/foo Ah<Z
                                format = format0
                            if part1 == format:
                                passw = part2
                                break
                        pf.close()
                    except IOError, inst:
                        if inst.errno != errno.ENOENT:
                            if not getattr(inst, 'filename', None):
                                inst.filename = cvspass
                            raise

                sck = socket.socket()
                sck.connect((serv, port))
                sck.send("\n".join(["BEGIN AUTH REQUEST", root, user, passw,
                                    "END AUTH REQUEST", ""]))
                if sck.recv(128) != "I LOVE YOU\n":
                    raise util.Abort(_("CVS pserver authentication failed"))

                self.writep = self.readp = sck.makefile('r+')

        if not conntype and root.startswith(":local:"):
            conntype = "local"
            root = root[7:]

        if not conntype:
            # :ext:user@host/home/user/path/to/cvsroot
            if root.startswith(":ext:"):
                root = root[5:]
            m = re.match(r'(?:([^@:/]+)@)?([^:/]+):?(.*)', root)
            # Do not take Windows path "c:\foo\bar" for a connection strings
            if os.path.isdir(root) or not m:
                conntype = "local"
            else:
                conntype = "rsh"
                user, host, root = m.group(1), m.group(2), m.group(3)

        if conntype != "pserver":
            if conntype == "rsh":
                rsh = os.environ.get("CVS_RSH") or "ssh"
                if user:
                    cmd = [rsh, '-l', user, host] + cmd
                else:
                    cmd = [rsh, host] + cmd

            # popen2 does not support argument lists under Windows
            cmd = [util.shellquote(arg) for arg in cmd]
            cmd = util.quotecommand(' '.join(cmd))
            self.writep, self.readp = util.popen2(cmd)

        self.realroot = root

        self.writep.write("Root %s\n" % root)
        self.writep.write("Valid-responses ok error Valid-requests Mode"
                          " M Mbinary E Checked-in Created Updated"
                          " Merged Removed\n")
        self.writep.write("valid-requests\n")
        self.writep.flush()
        r = self.readp.readline()
        if not r.startswith("Valid-requests"):
            raise util.Abort(_('unexpected response from CVS server '
                               '(expected "Valid-requests", but got %r)')
                             % r)
        if "UseUnchanged" in r:
            self.writep.write("UseUnchanged\n")
            self.writep.flush()
            r = self.readp.readline()
Exemplo n.º 24
0
class convert_cvs(converter_source):
    def __init__(self, ui, path, rev=None):
        super(convert_cvs, self).__init__(ui, path, rev=rev)

        cvs = os.path.join(path, "CVS")
        if not os.path.exists(cvs):
            raise NoRepo("%s does not look like a CVS checkout" % path)

        checktool('cvs')
        self.cmd = ui.config('convert', 'cvsps', 'builtin')
        cvspsexe = self.cmd.split(None, 1)[0]
        self.builtin = cvspsexe == 'builtin'
        if not self.builtin:
            ui.warn(
                _('warning: support for external cvsps is deprecated and '
                  'will be removed in Mercurial 1.4\n'))

        if not self.builtin:
            checktool(cvspsexe)

        self.changeset = None
        self.files = {}
        self.tags = {}
        self.lastbranch = {}
        self.parent = {}
        self.socket = None
        self.cvsroot = file(os.path.join(cvs, "Root")).read()[:-1]
        self.cvsrepo = file(os.path.join(cvs, "Repository")).read()[:-1]
        self.encoding = locale.getpreferredencoding()

        self._connect()

    def _parse(self):
        if self.changeset is not None:
            return
        self.changeset = {}

        maxrev = 0
        cmd = self.cmd
        if self.rev:
            # TODO: handle tags
            try:
                # patchset number?
                maxrev = int(self.rev)
            except ValueError:
                try:
                    # date
                    util.parsedate(self.rev, ['%Y/%m/%d %H:%M:%S'])
                    cmd = '%s -d "1970/01/01 00:00:01" -d "%s"' % (cmd,
                                                                   self.rev)
                except util.Abort:
                    raise util.Abort(
                        _('revision %s is not a patchset number or date') %
                        self.rev)

        d = os.getcwd()
        try:
            os.chdir(self.path)
            id = None
            state = 0
            filerevids = {}

            if self.builtin:
                # builtin cvsps code
                self.ui.status(_('using builtin cvsps\n'))

                cache = 'update'
                if not self.ui.configbool('convert', 'cvsps.cache', True):
                    cache = None
                db = cvsps.createlog(self.ui, cache=cache)
                db = cvsps.createchangeset(
                    self.ui,
                    db,
                    fuzz=int(self.ui.config('convert', 'cvsps.fuzz', 60)),
                    mergeto=self.ui.config('convert', 'cvsps.mergeto', None),
                    mergefrom=self.ui.config('convert', 'cvsps.mergefrom',
                                             None))

                for cs in db:
                    if maxrev and cs.id > maxrev:
                        break
                    id = str(cs.id)
                    cs.author = self.recode(cs.author)
                    self.lastbranch[cs.branch] = id
                    cs.comment = self.recode(cs.comment)
                    date = util.datestr(cs.date)
                    self.tags.update(dict.fromkeys(cs.tags, id))

                    files = {}
                    for f in cs.entries:
                        files[f.file] = "%s%s" % ('.'.join(
                            [str(x)
                             for x in f.revision]), ['', '(DEAD)'][f.dead])

                    # add current commit to set
                    c = commit(author=cs.author,
                               date=date,
                               parents=[str(p.id) for p in cs.parents],
                               desc=cs.comment,
                               branch=cs.branch or '')
                    self.changeset[id] = c
                    self.files[id] = files
            else:
                # external cvsps
                for l in util.popen(cmd):
                    if state == 0:  # header
                        if l.startswith("PatchSet"):
                            id = l[9:-2]
                            if maxrev and int(id) > maxrev:
                                # ignore everything
                                state = 3
                        elif l.startswith("Date:"):
                            date = util.parsedate(l[6:-1],
                                                  ["%Y/%m/%d %H:%M:%S"])
                            date = util.datestr(date)
                        elif l.startswith("Branch:"):
                            branch = l[8:-1]
                            self.parent[id] = self.lastbranch.get(
                                branch, 'bad')
                            self.lastbranch[branch] = id
                        elif l.startswith("Ancestor branch:"):
                            ancestor = l[17:-1]
                            # figure out the parent later
                            self.parent[id] = self.lastbranch[ancestor]
                        elif l.startswith("Author:"):
                            author = self.recode(l[8:-1])
                        elif l.startswith("Tag:") or l.startswith("Tags:"):
                            t = l[l.index(':') + 1:]
                            t = [ut.strip() for ut in t.split(',')]
                            if (len(t) > 1) or (t[0] and (t[0] != "(none)")):
                                self.tags.update(dict.fromkeys(t, id))
                        elif l.startswith("Log:"):
                            # switch to gathering log
                            state = 1
                            log = ""
                    elif state == 1:  # log
                        if l == "Members: \n":
                            # switch to gathering members
                            files = {}
                            oldrevs = []
                            log = self.recode(log[:-1])
                            state = 2
                        else:
                            # gather log
                            log += l
                    elif state == 2:  # members
                        if l == "\n":  # start of next entry
                            state = 0
                            p = [self.parent[id]]
                            if id == "1":
                                p = []
                            if branch == "HEAD":
                                branch = ""
                            if branch:
                                latest = 0
                                # the last changeset that contains a base
                                # file is our parent
                                for r in oldrevs:
                                    latest = max(filerevids.get(r, 0), latest)
                                if latest:
                                    p = [latest]

                            # add current commit to set
                            c = commit(author=author,
                                       date=date,
                                       parents=p,
                                       desc=log,
                                       branch=branch)
                            self.changeset[id] = c
                            self.files[id] = files
                        else:
                            colon = l.rfind(':')
                            file = l[1:colon]
                            rev = l[colon + 1:-2]
                            oldrev, rev = rev.split("->")
                            files[file] = rev

                            # save some information for identifying branch points
                            oldrevs.append("%s:%s" % (oldrev, file))
                            filerevids["%s:%s" % (rev, file)] = id
                    elif state == 3:
                        # swallow all input
                        continue

            self.heads = self.lastbranch.values()
        finally:
            os.chdir(d)

    def _connect(self):
        root = self.cvsroot
        conntype = None
        user, host = None, None
        cmd = ['cvs', 'server']

        self.ui.status(_("connecting to %s\n") % root)

        if root.startswith(":pserver:"):
            root = root[9:]
            m = re.match(r'(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?(.*)',
                         root)
            if m:
                conntype = "pserver"
                user, passw, serv, port, root = m.groups()
                if not user:
                    user = "******"
                if not port:
                    port = 2401
                else:
                    port = int(port)
                format0 = ":pserver:%s@%s:%s" % (user, serv, root)
                format1 = ":pserver:%s@%s:%d%s" % (user, serv, port, root)

                if not passw:
                    passw = "A"
                    cvspass = os.path.expanduser("~/.cvspass")
                    try:
                        pf = open(cvspass)
                        for line in pf.read().splitlines():
                            part1, part2 = line.split(' ', 1)
                            if part1 == '/1':
                                # /1 :pserver:[email protected]:2401/cvsroot/foo Ah<Z
                                part1, part2 = part2.split(' ', 1)
                                format = format1
                            else:
                                # :pserver:[email protected]:/cvsroot/foo Ah<Z
                                format = format0
                            if part1 == format:
                                passw = part2
                                break
                        pf.close()
                    except IOError, inst:
                        if inst.errno != errno.ENOENT:
                            if not getattr(inst, 'filename', None):
                                inst.filename = cvspass
                            raise

                sck = socket.socket()
                sck.connect((serv, port))
                sck.send("\n".join([
                    "BEGIN AUTH REQUEST", root, user, passw,
                    "END AUTH REQUEST", ""
                ]))
                if sck.recv(128) != "I LOVE YOU\n":
                    raise util.Abort(_("CVS pserver authentication failed"))

                self.writep = self.readp = sck.makefile('r+')

        if not conntype and root.startswith(":local:"):
            conntype = "local"
            root = root[7:]

        if not conntype:
            # :ext:user@host/home/user/path/to/cvsroot
            if root.startswith(":ext:"):
                root = root[5:]
            m = re.match(r'(?:([^@:/]+)@)?([^:/]+):?(.*)', root)
            # Do not take Windows path "c:\foo\bar" for a connection strings
            if os.path.isdir(root) or not m:
                conntype = "local"
            else:
                conntype = "rsh"
                user, host, root = m.group(1), m.group(2), m.group(3)

        if conntype != "pserver":
            if conntype == "rsh":
                rsh = os.environ.get("CVS_RSH") or "ssh"
                if user:
                    cmd = [rsh, '-l', user, host] + cmd
                else:
                    cmd = [rsh, host] + cmd

            # popen2 does not support argument lists under Windows
            cmd = [util.shellquote(arg) for arg in cmd]
            cmd = util.quotecommand(' '.join(cmd))
            self.writep, self.readp = util.popen2(cmd)

        self.realroot = root

        self.writep.write("Root %s\n" % root)
        self.writep.write("Valid-responses ok error Valid-requests Mode"
                          " M Mbinary E Checked-in Created Updated"
                          " Merged Removed\n")
        self.writep.write("valid-requests\n")
        self.writep.flush()
        r = self.readp.readline()
        if not r.startswith("Valid-requests"):
            raise util.Abort(
                _("unexpected response from CVS server "
                  "(expected \"Valid-requests\", but got %r)") % r)
        if "UseUnchanged" in r:
            self.writep.write("UseUnchanged\n")
            self.writep.flush()
            r = self.readp.readline()