예제 #1
0
파일: www.py 프로젝트: stnbu/dunaway
 def physical_host_reset(info):
     ip_address = info['oob_ip_address']
     cmd = 'ipmitool -H %s -I lanplus -U %s -P %s chassis power cycle'
     cmd %= (ip_address, config.oob_username, config.oob_password)
     cmd = cmd.split()
     logger.info('Resetting host at OOB IP %s' % ip_address)
     util.system(cmd)
예제 #2
0
 def setup_files(self):
   system("cp -r %s %s" % (MODEL, self.home))
   system("rm -rf %s/nxserver/lib" % self.home)
   system("rm -rf %s/nxserver/bundles" % self.home)
   system("ln -sf %s/nxserver/lib %s/nxserver/lib" % (MODEL, self.home))
   system("ln -sf %s/nxserver/bundles %s/nxserver/bundles"
       % (MODEL, self.home))
예제 #3
0
파일: ui.py 프로젝트: zeroincombenze/VME
    def edit(self, text, user, extra={}, editform=None):
        (fd, name) = tempfile.mkstemp(prefix="hg-editor-",
                                      suffix=".txt",
                                      text=True)
        try:
            f = os.fdopen(fd, "w")
            f.write(text)
            f.close()

            environ = {'HGUSER': user}
            if 'transplant_source' in extra:
                environ.update({'HGREVISION': hex(extra['transplant_source'])})
            for label in ('source', 'rebase_source'):
                if label in extra:
                    environ.update({'HGREVISION': extra[label]})
                    break
            if editform:
                environ.update({'HGEDITFORM': editform})

            editor = self.geteditor()

            util.system("%s \"%s\"" % (editor, name),
                        environ=environ,
                        onerr=util.Abort,
                        errprefix=_("edit failed"),
                        out=self.fout)

            f = open(name)
            t = f.read()
            f.close()
        finally:
            os.unlink(name)

        return t
예제 #4
0
def make_corrects_Python3 ():
    for f in glob.glob("*.cor"):
        util.del_file(f)
    inps = sorted(glob.glob("*.inp"))
    for inp in inps:
        tst = os.path.splitext(inp)[0]
        util.system("python3 solution.py <%s.inp >%s.cor" % (tst, tst))
예제 #5
0
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))

    starttime = time.time()
    env = {}
    for k, v in args.iteritems():
        if callable(v):
            v = v()
        if isinstance(v, dict):
            # make the dictionary element order stable across Python
            # implementations
            v = ('{' +
                 ', '.join('%r: %r' % i for i in sorted(v.iteritems())) +
                 '}')
        env['HG_' + k.upper()] = v

    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
        r = util.system(cmd, environ=env, cwd=cwd, out=ui)
    else:
        r = util.system(cmd, environ=env, cwd=cwd, out=ui.fout)

    duration = time.time() - starttime
    ui.log('exthook', 'exthook-%s: %s finished in %0.2f seconds\n',
           name, cmd, duration)
    if r:
        desc, r = util.explainexit(r)
        if throw:
            raise error.HookAbort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
예제 #6
0
def make_executable_Java ():
    if not util.file_exists("solution.java"):
        raise Exception("solution.java does not exist")
    util.del_file("Main.java")
    util.system("javac solution.java")
    if not util.file_exists("Main.class"):
        raise Exception("error in Java compilation")
예제 #7
0
파일: hook.py 프로젝트: mortonfox/cr48
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))

    env = {}
    for k, v in args.iteritems():
        if util.safehasattr(v, '__call__'):
            v = v()
        if isinstance(v, dict):
            # make the dictionary element order stable across Python
            # implementations
            v = ('{' +
                 ', '.join('%r: %r' % i for i in sorted(v.iteritems())) +
                 '}')
        env['HG_' + k.upper()] = v

    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
        r = util.system(cmd, environ=env, cwd=cwd, out=ui)
    else:
        r = util.system(cmd, environ=env, cwd=cwd, out=ui.fout)
    if r:
        desc, r = util.explainexit(r)
        if throw:
            raise util.Abort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
예제 #8
0
def make_corrects_Java ():
    for f in glob.glob("*.cor"):
        util.del_file(f)
    inps = sorted(glob.glob("*.inp"))
    for inp in inps:
        tst = os.path.splitext(inp)[0]
        util.system("java Main <%s.inp >%s.cor" % (tst, tst))
예제 #9
0
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))

    env = {}
    for k, v in args.iteritems():
        if util.safehasattr(v, '__call__'):
            v = v()
        if isinstance(v, dict):
            # make the dictionary element order stable across Python
            # implementations
            v = ('{' +
                 ', '.join('%r: %r' % i for i in sorted(v.iteritems())) +
                 '}')
        env['HG_' + k.upper()] = v

    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
        r = util.system(cmd, environ=env, cwd=cwd, out=ui)
    else:
        r = util.system(cmd, environ=env, cwd=cwd, out=ui.fout)
    if r:
        desc, r = util.explainexit(r)
        if throw:
            raise util.Abort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
예제 #10
0
    def edit(self, text, user, extra={}):
        (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
                                      text=True)
        try:
            f = os.fdopen(fd, "w")
            f.write(text)
            f.close()

            environ = {'HGUSER': user}
            if 'transplant_source' in extra:
                environ.update({'HGREVISION': hex(extra['transplant_source'])})
            for label in ('source', 'rebase_source'):
                if label in extra:
                    environ.update({'HGREVISION': extra[label]})
                    break

            editor = self.geteditor()

            util.system("%s \"%s\"" % (editor, name),
                        environ=environ,
                        onerr=util.Abort, errprefix=_("edit failed"),
                        out=self.fout)

            f = open(name)
            t = f.read()
            f.close()
        finally:
            os.unlink(name)

        return t
예제 #11
0
 def info(self, generator):
     generator.add_include_dir('include/')
     if system() == 'Windows':
         generator.add_source_files(*glob('src/*'))
     elif system() == 'Linux':
         generator.add_source_files('src/nfd_common.c', 'src/nfd_gtk.c')
     else:
         generator.add_source_files('src/nfd_common.c', 'src/nfd_cocoa.m')
예제 #12
0
def create_service_win(svcName):
    if check_is_service_installed(svcName):
        pass
    else:
        sc_path = os.getenv("SYSTEMROOT", "") + os.sep + "System32" + os.sep + "sc"
        util.system(homedir + os.sep + "bin" + os.sep + "create_service.bat", is_admin=True)
        sdshow = subprocess.Popen(sc_path + " sdshow " + svcName, stdout=subprocess.PIPE).communicate()
        sd_value = sdshow[0].lstrip('\n').strip()
        new_sd_value = 'A;;RPWPDTLO;;;S-1-1-0'  # + sid_value
        # set the service descriptor for the bam with current user SID
        sd_set_cmd = sc_path + " sdset " + svcName + " {}({})".format(sd_value, new_sd_value)
        util.system(sd_set_cmd, is_admin=True)
예제 #13
0
def make_corrects_RunPython ():
    for f in glob.glob("*.cor"):
        util.del_file(f)
    inps = sorted(glob.glob("*.inp"))
    for inp in inps:
        tst = os.path.splitext(inp)[0]
        os.system("cat solution.py %s.inp > work.py" % tst)
        util.system("python3 work.py >%s.cor" % (tst, ))

        # additionally, create doctest-like session
        if tst == 'sample':
            python_doctest(tst)
예제 #14
0
def cmd_clean():
  """Drop database and remove all instances (useful for debugging).
  """
  for instance in all_instances():
    if instance.state == RUNNING:
      instance.stop()
    instance.purge()
    session.delete(instance)
    session.commit()

  #os.unlink(DB)
  system("rm -rf %s/nginx" % HOME)
예제 #15
0
def delete_service_win(svcName):
    import win32serviceutil

    is_service_installed = False
    try:
        win32serviceutil.QueryServiceStatus(svcName)
        is_service_installed = True
    except:
        is_service_installed = False
    if is_service_installed:
        sc_path = os.getenv("SYSTEMROOT",
                            "") + os.sep + "System32" + os.sep + "sc"
        util.system(sc_path + " delete " + svcName, is_admin=True)
예제 #16
0
def make_executable_GHC ():

    handler = util.read_yml("handler.yml")

    if handler["handler"] != "std":
        raise Exception("unknown handler")

    if not util.file_exists("solution.hs"):
        raise Exception("solution.hs does not exist")

    util.del_file("solution.exe")
    util.system("ghc solution.hs -o solution.exe")
    if not util.file_exists("solution.exe"):
        raise Exception("error in GHC compilation")
예제 #17
0
def make_executable_C ():

    handler = util.read_yml("handler.yml")

    if handler["handler"] != "std":
        raise Exception("unknown handler")

    if not util.file_exists("solution.c"):
        raise Exception("solution.c does not exist")

    util.del_file("solution.exe")
    util.system("%s %s solution.c -o solution.exe" % (cc, ccflags))
    if not util.file_exists("solution.exe"):
        raise Exception("error in C compilation")
예제 #18
0
 def info(self, generator):
     libs = "-lluasocket"
     if system() == 'Windows':
         libs += " -lws2_32"
     generator.add_library(libs)
     generator.add_link_dir('libs/')
     generator.add_include_dir('include/')
예제 #19
0
 def info(self, generator):
     if system() == 'Windows':
         generator.add_library('-llua51')
     else:
         generator.add_library('-lluajit')
     generator.add_link_dir('libs/')
     generator.add_include_dir('include/')
예제 #20
0
    def __init__(self, ui, path, create=False):
        self._url = path
        self.ui = ui
        self.pipeo = self.pipei = self.pipee = None

        u = util.url(path, parsequery=False, parsefragment=False)
        if u.scheme != 'ssh' or not u.host or u.path is None:
            self._abort(error.RepoError(_("couldn't parse location %s") % path))

        self.user = u.user
        if u.passwd is not None:
            self._abort(error.RepoError(_("password in URL not supported")))
        self.host = u.host
        self.port = u.port
        self.path = u.path or "."

        sshcmd = self.ui.config("ui", "ssh", "ssh")
        remotecmd = self.ui.config("ui", "remotecmd", "hg")

        args = util.sshargs(sshcmd, self.host, self.user, self.port)

        if create:
            cmd = '%s %s %s' % (sshcmd, args,
                util.shellquote("%s init %s" %
                    (_serverquote(remotecmd), _serverquote(self.path))))
            ui.debug('running %s\n' % cmd)
            res = util.system(cmd, out=ui.fout)
            if res != 0:
                self._abort(error.RepoError(_("could not create remote repo")))

        self._validaterepo(sshcmd, args, remotecmd)
예제 #21
0
파일: sshrepo.py 프로젝트: ezc/mercurial
    def __init__(self, ui, path, create=0):
        self._url = path
        self.ui = ui

        m = re.match(r'^ssh://(([^@]+)@)?([^:/]+)(:(\d+))?(/(.*))?$', path)
        if not m:
            self._abort(error.RepoError(
                _("couldn't parse location %s") % path))

        self.user = m.group(2)
        if self.user and ':' in self.user:
            self._abort(error.RepoError(_("password in URL not supported")))
        self.host = m.group(3)
        self.port = m.group(5)
        self.path = m.group(7) or "."

        sshcmd = self.ui.config("ui", "ssh", "ssh")
        remotecmd = self.ui.config("ui", "remotecmd", "hg")

        args = util.sshargs(sshcmd, self.host, self.user, self.port)

        if create:
            cmd = '%s %s "%s init %s"'
            cmd = cmd % (sshcmd, args, remotecmd, self.path)

            ui.note(_('running %s\n') % cmd)
            res = util.system(cmd)
            if res != 0:
                self._abort(error.RepoError(_("could not create remote repo")))

        self.validate_repo(ui, sshcmd, args, remotecmd)
예제 #22
0
def _xmerge(repo, mynode, orig, fcd, fco, fca, toolconf, files, labels=None):
    r = _premerge(repo, toolconf, files, labels=labels)
    if r:
        tool, toolpath, binary, symlink = toolconf
        a, b, c, back = files
        out = ""
        env = {
            'HG_FILE': fcd.path(),
            'HG_MY_NODE': short(mynode),
            'HG_OTHER_NODE': str(fco.changectx()),
            'HG_BASE_NODE': str(fca.changectx()),
            'HG_MY_ISLINK': 'l' in fcd.flags(),
            'HG_OTHER_ISLINK': 'l' in fco.flags(),
            'HG_BASE_ISLINK': 'l' in fca.flags(),
        }

        ui = repo.ui

        args = _toolstr(ui, tool, "args", '$local $base $other')
        if "$output" in args:
            out, a = a, back  # read input from backup, write to original
        replace = {'local': a, 'base': b, 'other': c, 'output': out}
        args = util.interpolate(r'\$', replace, args,
                                lambda s: util.shellquote(util.localpath(s)))
        r = util.system(toolpath + ' ' + args,
                        cwd=repo.root,
                        environ=env,
                        out=ui.fout)
        return True, r
    return False, 0
예제 #23
0
def _xmerge(repo, mynode, orig, fcd, fco, fca, toolconf, files):
    r = _premerge(repo, toolconf, files)
    if r:
        tool, toolpath, binary, symlink = toolconf
        a, b, c, back = files
        out = ""
        env = dict(HG_FILE=fcd.path(),
                   HG_MY_NODE=short(mynode),
                   HG_OTHER_NODE=str(fco.changectx()),
                   HG_BASE_NODE=str(fca.changectx()),
                   HG_MY_ISLINK='l' in fcd.flags(),
                   HG_OTHER_ISLINK='l' in fco.flags(),
                   HG_BASE_ISLINK='l' in fca.flags())

        ui = repo.ui

        args = _toolstr(ui, tool, "args", '$local $base $other')
        if "$output" in args:
            out, a = a, back # read input from backup, write to original
        replace = dict(local=a, base=b, other=c, output=out)
        args = util.interpolate(r'\$', replace, args,
                                lambda s: '"%s"' % util.localpath(s))
        r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env,
                        out=ui.fout)
        return True, r
    return False, 0
예제 #24
0
    def __init__(self, ui, path, create=False):
        self._url = path
        self.ui = ui

        u = util.url(path, parsequery=False, parsefragment=False)
        if u.scheme != "ssh" or not u.host or u.path is None:
            self._abort(error.RepoError(_("couldn't parse location %s") % path))

        self.user = u.user
        if u.passwd is not None:
            self._abort(error.RepoError(_("password in URL not supported")))
        self.host = u.host
        self.port = u.port
        self.path = u.path or "."

        sshcmd = self.ui.config("ui", "ssh", "ssh")
        remotecmd = self.ui.config("ui", "remotecmd", "hg")

        args = util.sshargs(sshcmd, self.host, self.user, self.port)

        if create:
            cmd = '%s %s "%s init %s"'
            cmd = cmd % (sshcmd, args, remotecmd, self.path)

            ui.note(_("running %s\n") % cmd)
            res = util.system(cmd)
            if res != 0:
                self._abort(error.RepoError(_("could not create remote repo")))

        self.validate_repo(ui, sshcmd, args, remotecmd)
예제 #25
0
    def __init__(self, ui, path, create=0):
        self._url = path
        self.ui = ui

        m = re.match(r'^ssh://(([^@]+)@)?([^:/]+)(:(\d+))?(/(.*))?$', path)
        if not m:
            self.abort(error.RepoError(_("couldn't parse location %s") % path))

        self.user = m.group(2)
        self.host = m.group(3)
        self.port = m.group(5)
        self.path = m.group(7) or "."

        sshcmd = self.ui.config("ui", "ssh", "ssh")
        remotecmd = self.ui.config("ui", "remotecmd", "hg")

        args = util.sshargs(sshcmd, self.host, self.user, self.port)

        if create:
            cmd = '%s %s "%s init %s"'
            cmd = cmd % (sshcmd, args, remotecmd, self.path)

            ui.note(_('running %s\n') % cmd)
            res = util.system(cmd)
            if res != 0:
                self.abort(error.RepoError(_("could not create remote repo")))

        self.validate_repo(ui, sshcmd, args, remotecmd)
예제 #26
0
def _xmerge(repo, mynode, orig, fcd, fco, fca, toolconf, files, labels=None):
    r = _premerge(repo, toolconf, files, labels=labels)
    if r:
        tool, toolpath, binary, symlink = toolconf
        a, b, c, back = files
        out = ""
        env = {'HG_FILE': fcd.path(),
               'HG_MY_NODE': short(mynode),
               'HG_OTHER_NODE': str(fco.changectx()),
               'HG_BASE_NODE': str(fca.changectx()),
               'HG_MY_ISLINK': 'l' in fcd.flags(),
               'HG_OTHER_ISLINK': 'l' in fco.flags(),
               'HG_BASE_ISLINK': 'l' in fca.flags(),
               }

        ui = repo.ui

        args = _toolstr(ui, tool, "args", '$local $base $other')
        if "$output" in args:
            out, a = a, back # read input from backup, write to original
        replace = {'local': a, 'base': b, 'other': c, 'output': out}
        args = util.interpolate(r'\$', replace, args,
                                lambda s: util.shellquote(util.localpath(s)))
        r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env,
                        out=ui.fout)
        return True, r
    return False, 0
예제 #27
0
def _xmerge(repo, mynode, orig, fcd, fco, fca, toolconf, files):
    r = _premerge(repo, toolconf, files)
    if r:
        tool, toolpath, binary, symlink = toolconf
        a, b, c, back = files
        out = ""
        env = dict(HG_FILE=fcd.path(),
                   HG_MY_NODE=short(mynode),
                   HG_OTHER_NODE=str(fco.changectx()),
                   HG_BASE_NODE=str(fca.changectx()),
                   HG_MY_ISLINK='l' in fcd.flags(),
                   HG_OTHER_ISLINK='l' in fco.flags(),
                   HG_BASE_ISLINK='l' in fca.flags())

        ui = repo.ui

        args = _toolstr(ui, tool, "args", '$local $base $other')
        if "$output" in args:
            out, a = a, back  # read input from backup, write to original
        replace = dict(local=a, base=b, other=c, output=out)
        args = util.interpolate(r'\$', replace, args,
                                lambda s: '"%s"' % util.localpath(s))
        r = util.system(toolpath + ' ' + args,
                        cwd=repo.root,
                        environ=env,
                        out=ui.fout)
        return True, r
    return False, 0
예제 #28
0
    def __init__(self, ui, path, create=False):
        self._url = path
        self.ui = ui
        self.pipeo = self.pipei = self.pipee = None

        u = util.url(path, parsequery=False, parsefragment=False)
        if u.scheme != 'ssh' or not u.host or u.path is None:
            self._abort(error.RepoError(
                _("couldn't parse location %s") % path))

        self.user = u.user
        if u.passwd is not None:
            self._abort(error.RepoError(_("password in URL not supported")))
        self.host = u.host
        self.port = u.port
        self.path = u.path or "."

        sshcmd = self.ui.config("ui", "ssh", "ssh")
        remotecmd = self.ui.config("ui", "remotecmd", "hg")

        args = util.sshargs(sshcmd, self.host, self.user, self.port)

        if create:
            cmd = '%s %s %s' % (sshcmd, args,
                                util.shellquote("%s init %s" %
                                                (_serverquote(remotecmd),
                                                 _serverquote(self.path))))
            ui.debug('running %s\n' % cmd)
            res = util.system(cmd)
            if res != 0:
                self._abort(error.RepoError(_("could not create remote repo")))

        self._validaterepo(sshcmd, args, remotecmd)
예제 #29
0
def publish_results(exp_name, results_dir):
    import logging
    log = logging.getLogger("sts.exp_lifecycle")
    res_git_dir = find_git_dir(results_dir)
    rel_results_dir = os.path.relpath(results_dir, res_git_dir)
    log.info("Publishing results to git dir "+res_git_dir)
    system("git add %s" % rel_results_dir, cwd=res_git_dir)
    system("git commit -m '%s'" % exp_name, cwd=res_git_dir)
    system("git pull --rebase", cwd=res_git_dir)
    system("git push", cwd=res_git_dir)
예제 #30
0
파일: ui.py 프로젝트: RayFerr000/PLTL
 def system(self, cmd, environ={}, cwd=None, onerr=None, errprefix=None):
     '''execute shell command with appropriate output stream. command
     output will be redirected if fout is not stdout.
     '''
     out = self.fout
     if util.any(s[1] for s in self._bufferstates):
         out = self
     return util.system(cmd, environ=environ, cwd=cwd, onerr=onerr,
                        errprefix=errprefix, out=out)
예제 #31
0
def make_executable_Haskell ():
    if not util.file_exists("solution.hs"):
        raise Exception("solution.hs does not exist")

    util.del_file("work")
    util.del_file("work.hi")
    util.del_file("work.o")
    util.copy_file("solution.hs", "work.hs")
    f = open("work.hs", "a")
    print >>f, """main = do print "OK" """
    f.close()

    util.system("ghc -O3 work.hs")
    if not util.file_exists("work"):
        raise Exception("error in haskell compilation")
    util.del_file("work")
    util.del_file("work.hi")
    util.del_file("work.o")
예제 #32
0
def filemerge(repo, fw, fd, fo, wctx, mctx):
    """perform a 3-way merge in the working directory

    fw = original filename in the working directory
    fd = destination filename in the working directory
    fo = filename in other parent
    wctx, mctx = working and merge changecontexts
    """
    def temp(prefix, ctx):
        pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
        (fd, name) = tempfile.mkstemp(prefix=pre)
        data = repo.wwritedata(ctx.path(), ctx.data())
        f = os.fdopen(fd, "wb")
        f.write(data)
        f.close()
        return name

    fcm = wctx.filectx(fw)
    fcmdata = wctx.filectx(fd).data()
    fco = mctx.filectx(fo)

    if not fco.cmp(fcmdata):  # files identical?
        return None

    fca = fcm.ancestor(fco)
    if not fca:
        fca = repo.filectx(fw, fileid=nullrev)
    a = repo.wjoin(fd)
    b = temp("base", fca)
    c = temp("other", fco)

    if fw != fo:
        repo.ui.status(_("merging %s and %s\n") % (fw, fo))
    else:
        repo.ui.status(_("merging %s\n") % fw)

    repo.ui.debug(_("my %s other %s ancestor %s\n") % (fcm, fco, fca))

    cmd = (os.environ.get("HGMERGE") or repo.ui.config("ui", "merge")
           or "hgmerge")
    r = util.system('%s "%s" "%s" "%s"' % (cmd, a, b, c),
                    cwd=repo.root,
                    environ={
                        'HG_FILE': fd,
                        'HG_MY_NODE': str(wctx.parents()[0]),
                        'HG_OTHER_NODE': str(mctx),
                        'HG_MY_ISLINK': fcm.islink(),
                        'HG_OTHER_ISLINK': fco.islink(),
                        'HG_BASE_ISLINK': fca.islink(),
                    })
    if r:
        repo.ui.warn(_("merging %s failed!\n") % fd)

    os.unlink(b)
    os.unlink(c)
    return r
예제 #33
0
 def system(self, cmd, environ={}, cwd=None, onerr=None, errprefix=None):
     '''execute shell command with appropriate output stream. command
     output will be redirected if fout is not stdout.
     '''
     return util.system(cmd,
                        environ=environ,
                        cwd=cwd,
                        onerr=onerr,
                        errprefix=errprefix,
                        out=self.fout)
예제 #34
0
파일: ui.py 프로젝트: helloandre/cr48
    def edit(self, text, user):
        (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt", text=True)
        try:
            f = os.fdopen(fd, "w")
            f.write(text)
            f.close()

            editor = self.geteditor()

            util.system(
                '%s "%s"' % (editor, name), environ={"HGUSER": user}, onerr=util.Abort, errprefix=_("edit failed")
            )

            f = open(name)
            t = f.read()
            f.close()
        finally:
            os.unlink(name)

        return t
예제 #35
0
파일: ui.py 프로젝트: as/9front-work
    def edit(self, text, user):
        (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
                                      text=True)
        try:
            f = os.fdopen(fd, "w")
            f.write(text)
            f.close()

            editor = self.geteditor()

            util.system("%s \"%s\"" % (editor, name),
                        environ={'HGUSER': user},
                        onerr=util.Abort, errprefix=_("edit failed"))

            f = open(name)
            t = f.read()
            f.close()
        finally:
            os.unlink(name)

        return t
예제 #36
0
def make_corrects_RunHaskell ():
    for f in glob.glob("*.cor"):
        util.del_file(f)
    inps = sorted(glob.glob("*.inp"))
    for inp in inps:
        tst = os.path.splitext(inp)[0]
        util.copy_file("solution.hs", "work.hs")
        if util.file_exists("judge.hs"):
            os.system("cat judge.hs >> work.hs")
        f = open("work.hs", "a")
        print >>f, "main = do"
        for line in open(tst+".inp").readlines():
            line = line.rstrip()
            if line.startswith("let "):
                print >>f, "    %s" % line
#            elif line.startswith("deb "):
#                print >>f, '    hPutStrLn stderr "%s"' % line
            else:
                print >>f, "    print (%s)" % line
        f.close()
        util.system("runhaskell work.hs >%s.cor" % (tst, ))
예제 #37
0
파일: dispatch.py 프로젝트: helloandre/cr48
 def fn(ui, *args):
     env = {'HG_ARGS': ' '.join((self.name,) + args)}
     def _checkvar(m):
         if int(m.groups()[0]) <= len(args):
             return m.group()
         else:
             return ''
     cmd = re.sub(r'\$(\d+)', _checkvar, self.definition[1:])
     replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
     replace['0'] = self.name
     replace['@'] = ' '.join(args)
     cmd = util.interpolate(r'\$', replace, cmd)
     return util.system(cmd, environ=env)
예제 #38
0
 def fn(ui, *args):
     env = {'HG_ARGS': ' '.join((self.name,) + args)}
     def _checkvar(m):
         if int(m.groups()[0]) <= len(args):
             return m.group()
         else:
             return ''
     cmd = re.sub(r'\$(\d+)', _checkvar, self.definition[1:])
     replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
     replace['0'] = self.name
     replace['@'] = ' '.join(args)
     cmd = util.interpolate(r'\$', replace, cmd)
     return util.system(cmd, environ=env)
예제 #39
0
파일: hook.py 프로젝트: saminigod/cygwin
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))
    env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    r = util.system(cmd, environ=env, cwd=cwd)
    if r:
        desc, r = util.explain_exit(r)
        if throw:
            raise util.Abort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))

    env = {}
    for k, v in args.iteritems():
        if hasattr(v, '__call__'):
            v = v()
        env['HG_' + k.upper()] = v

    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
        r = util.system(cmd, environ=env, cwd=cwd, out=ui)
    else:
        r = util.system(cmd, environ=env, cwd=cwd)
    if r:
        desc, r = util.explain_exit(r)
        if throw:
            raise util.Abort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
예제 #41
0
 def fn(ui, *args):
     env = {'HG_ARGS': ' '.join((self.name,) + args)}
     def _checkvar(m):
         if m.groups()[0] == '$':
             return m.group()
         elif int(m.groups()[0]) <= len(args):
             return m.group()
         else:
             ui.debug("No argument found for substitution "
                      "of %i variable in alias '%s' definition."
                      % (int(m.groups()[0]), self.name))
             return ''
     cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
     cmd = aliasinterpolate(self.name, args, cmd)
     return util.system(cmd, environ=env, out=ui.fout)
예제 #42
0
def make_corrects ():

    """Makes all correct files in the cwd."""

    make_executable()

    handler = util.read_yml("handler.yml")
    if handler.get('compilers', '') == 'RunHaskell':
        make_corrects_RunHaskell()
    elif handler.get('compilers', '') == 'RunPython':
        make_corrects_RunPython()
    elif handler.get('solution', '') == 'Python3':
        make_corrects_Python3()
    elif handler.get('solution', '') == 'Java':
        make_corrects_Java()
    else:
        if not util.file_exists("solution.exe"):
            raise Exception("solution.exe does not exist")
        for f in glob.glob("*.cor"):
            util.del_file(f)
        inps = sorted(glob.glob("*.inp"))
        for inp in inps:
            tst = os.path.splitext(inp)[0]
            util.system("./solution.exe < %s.inp > %s.cor" % (tst, tst))
예제 #43
0
            def fn(ui, *args):
                env = {'HG_ARGS': ' '.join((self.name, ) + args)}

                def _checkvar(m):
                    if m.groups()[0] == '$':
                        return m.group()
                    elif int(m.groups()[0]) <= len(args):
                        return m.group()
                    else:
                        ui.debug("No argument found for substitution "
                                 "of %i variable in alias '%s' definition." %
                                 (int(m.groups()[0]), self.name))
                        return ''

                cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
                cmd = aliasinterpolate(self.name, args, cmd)
                return util.system(cmd, environ=env, out=ui.fout)
예제 #44
0
 def fn(ui, *args):
     env = {'HG_ARGS': ' '.join((self.name,) + args)}
     def _checkvar(m):
         if m.groups()[0] == '$':
             return m.group()
         elif int(m.groups()[0]) <= len(args):
             return m.group()
         else:
             ui.debug("No argument found for substitution "
                      "of %i variable in alias '%s' definition."
                      % (int(m.groups()[0]), self.name))
             return ''
     cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
     replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
     replace['0'] = self.name
     replace['@'] = ' '.join(args)
     cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
     return util.system(cmd, environ=env, out=ui.fout)
예제 #45
0
 def fn(ui, *args):
     env = {'HG_ARGS': ' '.join((self.name,) + args)}
     def _checkvar(m):
         if m.groups()[0] == '$':
             return m.group()
         elif int(m.groups()[0]) <= len(args):
             return m.group()
         else:
             ui.debug("No argument found for substitution "
                      "of %i variable in alias '%s' definition."
                      % (int(m.groups()[0]), self.name))
             return ''
     cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
     replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
     replace['0'] = self.name
     replace['@'] = ' '.join(args)
     cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
     return util.system(cmd, environ=env, out=ui.fout)
예제 #46
0
        if isJson:
            jsonMsg = {}
            jsonMsg['status'] = "wip"
            jsonMsg['component'] = pgver
            jsonMsg['msg'] = startMsg
            print(json.dumps([jsonMsg]))
        else:
            print(startMsg)
        fh.write('set SVC_NAME="' + svcname + '"\n')
        fh.write(
            'set SVC_DESC="The worlds most advanced open source database."\n')
        fh.write('set DATA_DIR="' + datadir + '"\n')
        fh.write('set PG_VER=' + pgver + '\n')
        fh.write(pg_home + os.sep + 'create_service.bat\n')
    fh.close()
    util.system(cmd_file, is_admin=True)

elif util.get_platform() == "Darwin":

    import plistlib
    if not os.path.isdir(logdir):
        os.mkdir(logdir)
    plist_conf_dir = os.path.join(MY_HOME, 'conf', 'plist')
    if not os.path.isdir(plist_conf_dir):
        os.mkdir(plist_conf_dir)
    LAUNCHDIR = os.path.join(os.getenv("HOME", "~"), "Library", "LaunchAgents")
    if not os.path.isdir(LAUNCHDIR):
        os.mkdir(LAUNCHDIR)
    file_name = "bigsql." + pgver + ".plist"
    plist_filename = os.path.join(plist_conf_dir, file_name)
    plist_dict = {}
예제 #47
0
from __future__ import print_function, division
 
####################################################################
######          Copyright (c)  2015-2019 BigSQL           ##########
####################################################################

import os, sys
import util, startup

pgver = "pg9X"

autostart = util.get_column('autostart', pgver)
if autostart != "on":
  sys.exit(0)

dotver = pgver[2] + "." + pgver[3]
APG_HOME = os.getenv('APG_HOME', '')
svcname   = util.get_column('svcname', pgver, 'PostgreSQL ' + dotver + ' Server')

if util.get_platform() == "Windows":
  sc_path = os.getenv("SYSTEMROOT", "") + os.sep + "System32" + os.sep + "sc"
  command = sc_path + ' delete "' + svcname + '"'
  util.system(command, is_admin=True)
elif util.get_platform() == "Linux":
  startup.remove_linux("postgresql" + pgver[2:4], "85", "15")
예제 #48
0
 def read(self):
     util.system(['git', 'read-tree', '--reset',
                  self._tree], onerr=RuntimeError)
예제 #49
0
 def reload(self):
   system("supervisorctl -c %s/supervisor.conf update" % HOME)
예제 #50
0
def filemerge(repo, mynode, orig, fcd, fco, fca):
    """perform a 3-way merge in the working directory

    mynode = parent node before merge
    orig = original local filename before merge
    fco = other file context
    fca = ancestor file context
    fcd = local file context for current/destination file
    """
    def temp(prefix, ctx):
        pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
        (fd, name) = tempfile.mkstemp(prefix=pre)
        data = repo.wwritedata(ctx.path(), ctx.data())
        f = os.fdopen(fd, "wb")
        f.write(data)
        f.close()
        return name

    def isbin(ctx):
        try:
            return util.binary(ctx.data())
        except IOError:
            return False

    if not fco.cmp(fcd.data()):  # files identical?
        return None

    if fca == fco:  # backwards, use working dir parent as ancestor
        fca = fcd.parents()[0]

    ui = repo.ui
    fd = fcd.path()
    binary = isbin(fcd) or isbin(fco) or isbin(fca)
    symlink = 'l' in fcd.flags() + fco.flags()
    tool, toolpath = _picktool(repo, ui, fd, binary, symlink)
    ui.debug("picked tool '%s' for %s (binary %s symlink %s)\n" %
             (tool, fd, binary, symlink))

    if not tool or tool == 'internal:prompt':
        tool = "internal:local"
        if ui.promptchoice(
                _(" no tool found to merge %s\n"
                  "keep (l)ocal or take (o)ther?") % fd,
            (_("&Local"), _("&Other")), 0):
            tool = "internal:other"
    if tool == "internal:local":
        return 0
    if tool == "internal:other":
        repo.wwrite(fd, fco.data(), fco.flags())
        return 0
    if tool == "internal:fail":
        return 1

    # do the actual merge
    a = repo.wjoin(fd)
    b = temp("base", fca)
    c = temp("other", fco)
    out = ""
    back = a + ".orig"
    util.copyfile(a, back)

    if orig != fco.path():
        ui.status(_("merging %s and %s to %s\n") % (orig, fco.path(), fd))
    else:
        ui.status(_("merging %s\n") % fd)

    ui.debug("my %s other %s ancestor %s\n" % (fcd, fco, fca))

    # do we attempt to simplemerge first?
    if _toolbool(ui, tool, "premerge", not (binary or symlink)):
        r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
        if not r:
            ui.debug(" premerge successful\n")
            os.unlink(back)
            os.unlink(b)
            os.unlink(c)
            return 0
        util.copyfile(back, a)  # restore from backup and try again

    env = dict(HG_FILE=fd,
               HG_MY_NODE=short(mynode),
               HG_OTHER_NODE=str(fco.changectx()),
               HG_BASE_NODE=str(fca.changectx()),
               HG_MY_ISLINK='l' in fcd.flags(),
               HG_OTHER_ISLINK='l' in fco.flags(),
               HG_BASE_ISLINK='l' in fca.flags())

    if tool == "internal:merge":
        r = simplemerge.simplemerge(ui, a, b, c, label=['local', 'other'])
    elif tool == 'internal:dump':
        a = repo.wjoin(fd)
        util.copyfile(a, a + ".local")
        repo.wwrite(fd + ".other", fco.data(), fco.flags())
        repo.wwrite(fd + ".base", fca.data(), fca.flags())
        return 1  # unresolved
    else:
        args = _toolstr(ui, tool, "args", '$local $base $other')
        if "$output" in args:
            out, a = a, back  # read input from backup, write to original
        replace = dict(local=a, base=b, other=c, output=out)
        args = re.sub(
            "\$(local|base|other|output)",
            lambda x: '"%s"' % util.localpath(replace[x.group()[1:]]), args)
        r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env)

    if not r and _toolbool(ui, tool, "checkconflicts"):
        if re.match("^(<<<<<<< .*|=======|>>>>>>> .*)$", fcd.data()):
            r = 1

    if not r and _toolbool(ui, tool, "checkchanged"):
        if filecmp.cmp(repo.wjoin(fd), back):
            if ui.promptchoice(
                    _(" output file %s appears unchanged\n"
                      "was merge successful (yn)?") % fd,
                (_("&Yes"), _("&No")), 1):
                r = 1

    if _toolbool(ui, tool, "fixeol"):
        _matcheol(repo.wjoin(fd), back)

    if r:
        ui.warn(_("merging %s failed!\n") % fd)
    else:
        os.unlink(back)

    os.unlink(b)
    os.unlink(c)
    return r
예제 #51
0
import subprocess
import os
import sys

MY_HOME = os.getenv("MY_HOME", "")
sys.path.append(os.path.join(MY_HOME, 'hub', 'scripts'))
sys.path.append(os.path.join(MY_HOME, 'hub', 'scripts', 'lib'))

import util

util.set_lang_path()

pgver = "pg9X"

dotver = pgver[2] + "." + pgver[3]

datadir = util.get_column('datadir', pgver)

logdir = util.get_column('logdir', pgver)

autostart = util.get_column('autostart', pgver)

pg_ctl = os.path.join(MY_HOME, pgver, "bin", "pg_ctl")
logfile = util.get_column('logdir', pgver) + os.sep + "postgres.log"

util.read_env_file(pgver)

cmd = pg_ctl + ' start -s -w -D "' + datadir + '" ' + '-l "' + logfile + '"'
util.system(cmd)
예제 #52
0
sys.path.append(os.path.join(PGC_HOME, 'hub', 'scripts', 'lib'))

import util

util.set_lang_path()

pgver = "pg11"

dotver = pgver[2] + "." + pgver[3]

datadir = util.get_column('datadir', pgver)

logdir = util.get_column('logdir', pgver)

autostart = util.get_column('autostart', pgver)

pg_ctl = os.path.join(PGC_HOME, pgver, "bin", "pg_ctl")
logfile = util.get_column('logdir', pgver) + os.sep + "postgres.log"

util.read_env_file(pgver)

if util.get_platform() == "Windows":
    cmd = pg_ctl + ' start -s -w -D "' + datadir + '" '
    util.system(cmd)
elif util.get_platform() == "Darwin" and autostart == "on":
    postgres = os.path.join(PGC_HOME, pgver, "bin", "postgres")
    util.system(postgres + ' -D ' + datadir + ' -r ' + logfile)
else:
    cmd = pg_ctl + ' start -s -w -D "' + datadir + '" ' + '-l "' + logfile + '"'
    util.system(cmd)
예제 #53
0
def git_has_uncommitted_files(d):
  return system("git diff-files --quiet --ignore-submodules --", cwd=d) > 0 \
    or system("git diff-index --cached --quiet HEAD --ignore-submodules --", cwd=d) > 0
예제 #54
0
if not util.has_admin_rights():
    print "You must be an administrator/root to remove bam2."
    sys.exit(0)

if util.get_platform() == "Windows":
    import win32serviceutil
    is_service_installed = False
    try:
        win32serviceutil.QueryServiceStatus('bam')
        is_service_installed = True
    except:
        is_service_installed = False
    sc_path = os.getenv("SYSTEMROOT", "") + os.sep + "System32" + os.sep + "sc"
    if is_service_installed:
        util.system(sc_path+" delete bam", is_admin=True)
elif util.get_platform() == "Darwin":
    plist_conf_dir = os.path.join(PGC_HOME, 'conf', 'plist')
    launch_dir = os.path.join(os.getenv("HOME", "~"), "Library", "LaunchAgents")
    file_name = "bigsql.bam2.plist"
    plist_filename = os.path.join(plist_conf_dir, file_name)
    plist_link_file = os.path.join(launch_dir, file_name)
    if os.path.exists(plist_link_file):
        launctl_unload_cmd = "launchctl unload " + plist_link_file
        subprocess.Popen(launctl_unload_cmd, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, shell=True).communicate()
        remove_existing_plist_link = "rm " + os.path.join(launch_dir, file_name)
        subprocess.Popen(remove_existing_plist_link, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, shell=True).communicate()
        remove_existing_plist_file = "rm " + plist_filename
        subprocess.Popen(remove_existing_plist_file, stdout=subprocess.PIPE,
예제 #55
0
  jsonMsg = {}
  jsonMsg['status'] = "wip"
  jsonMsg['component'] = pgver
  jsonMsg['msg'] = msg
  print(json.dumps([jsonMsg]))
else:
  print(msg)

pg_ctl = os.path.join(homedir, "bin", "pg_ctl")

stop_cmd = pg_ctl + ' stop -s -w -m immediate -D "' + datadir + '"'

autostart = util.get_column('autostart', pgver)
if autostart == "on":
  if util.get_platform() == "Windows":
    rc = util.system(stop_cmd, is_admin=True)
  elif util.get_platform() == "Darwin":
    launctl_load_cmd = "launchctl stop bigsql." + pgver
    rc = util.system(stop_cmd)
  else:
    rc = startup.stop_linux("postgresql" + pgver[2:4])
else:
  rc = util.system(stop_cmd)

if (rc > 0):
  msg = "problem stopping " + pgver
  if isJson:
    jsonMsg = {}
    jsonMsg['status'] = "error"
    jsonMsg['component'] = pgver
    jsonMsg['msg'] = msg