예제 #1
0
def resolve_snippets(ctx):
	cl = set()
	types = [''] if ctx.get('local') else ctx.get('types')
	vars = {}
	for k,v in ctx.iteritems():
		if gs.is_a_string(v):
			vars[k] = v

	try:
		snips = []
		snips.extend(gs.setting('default_snippets', []))
		snips.extend(gs.setting('snippets', []))
		for m in snips:
			try:
				if snippet_match(ctx, m):
					for ent in m.get('snippets', []):
						text = ent.get('text', '')
						title = ent.get('title', '')
						value = ent.get('value', '')
						if text and value:
							for typename in types:
								vars['typename'] = typename
								vars['typename_abbr'] = typename[0].lower() if typename else ''
								txt, ttl, val = expand_snippet_vars(vars, text, title, value)
								s = u'%s\t%s \u0282' % (txt, ttl)
								cl.add((s, val))
			except:
				gs.notice(DOMAIN, gs.traceback())
	except:
		gs.notice(DOMAIN, gs.traceback())
	return list(cl)
예제 #2
0
def resolve_snippets(ctx):
    cl = set()
    types = [''] if ctx.get('local') else ctx.get('types')
    vars = {}
    for k, v in ctx.iteritems():
        if gs.is_a_string(v):
            vars[k] = v

    try:
        snips = []
        snips.extend(gs.setting('default_snippets', []))
        snips.extend(gs.setting('snippets', []))
        for m in snips:
            try:
                if snippet_match(ctx, m):
                    for ent in m.get('snippets', []):
                        text = ent.get('text', '')
                        title = ent.get('title', '')
                        value = ent.get('value', '')
                        if text and value:
                            for typename in types:
                                vars['typename'] = typename
                                vars['typename_abbr'] = typename[0].lower(
                                ) if typename else ''
                                txt, ttl, val = expand_snippet_vars(
                                    vars, text, title, value)
                                s = u'%s\t%s \u0282' % (txt, ttl)
                                cl.add((s, val))
            except:
                gs.notice(DOMAIN, gs.traceback())
    except:
        gs.notice(DOMAIN, gs.traceback())
    return list(cl)
예제 #3
0
def _recv():
    while True:
        try:
            ln = _recv_q.get()
            try:
                ln = ln.strip()
                if ln:
                    r, _ = gs.json_decode(ln, {})
                    token = r.get('token', '')
                    k = REQUEST_PREFIX + token
                    req = gs.attr(k)
                    gs.del_attr(k)
                    if req and req.f:
                        gs.debug(
                            DOMAIN,
                            "margo response: method: %s, token: %s, dur: %0.3fs, err: `%s'"
                            % (
                                req.method,
                                req.token,
                                (time.time() - req.tm),
                                r.get('error', ''),
                            ))
                        keep = req.f(r.get('data', {}), r.get('error',
                                                              '')) is not True
                        if keep:
                            req.tm = time.time()
                            gs.set_attr(k, req)
                    else:
                        gs.debug(DOMAIN, 'Ignoring margo: token: %s' % token)

            except Exception:
                gs.println(gs.traceback())
        except Exception:
            gs.println(gs.traceback())
            break
예제 #4
0
파일: mg9.py 프로젝트: timicx/GoSublime
def _recv():
	while True:
		try:
			ln = _recv_q.get()
			try:
				ln = ln.strip()
				if ln:
					r, _ = gs.json_decode(ln, {})
					token = r.get('token', '')
					k = REQUEST_PREFIX+token
					req = gs.attr(k)
					gs.del_attr(k)
					if req and req.f:
						gs.debug(DOMAIN, "margo response: method: %s, token: %s, dur: %0.3fs, err: `%s'" % (
							req.method,
							req.token,
							(time.time() - req.tm),
							r.get('error', ''),
						))
						keep = req.f(r.get('data', {}), r.get('error', '')) is not True
						if keep:
							req.tm = time.time()
							gs.set_attr(k, req)
					else:
						gs.debug(DOMAIN, 'Ignoring margo: token: %s' % token)

			except Exception:
				gs.println(gs.traceback())
		except Exception:
			gs.println(gs.traceback())
			break
예제 #5
0
def _send():
    while True:
        try:
            try:
                method, arg, cb = _send_q.get()

                proc = gs.attr(PROC_ATTR_NAME)
                if not proc or proc.poll() is not None:
                    if proc:
                        try:
                            proc.kill()
                            proc.stdout.close()
                        except:
                            pass

                    maybe_install()

                    if not gs.checked(DOMAIN, 'launch _recv'):
                        gsq.launch(DOMAIN, _recv)

                    proc, _, err = gsshell.proc([MARGO9_BIN, '-poll=30'],
                                                stderr=gs.LOGFILE,
                                                env={
                                                    'XDG_CONFIG_HOME':
                                                    gs.home_path(),
                                                })
                    gs.set_attr(PROC_ATTR_NAME, proc)

                    if not proc:
                        gs.notice(DOMAIN, 'Cannot MarGo: %s' % err)
                        continue

                    gsq.launch(DOMAIN, lambda: _read_stdout(proc))

                req = Request(f=cb, method=method)
                gs.set_attr(REQUEST_PREFIX + req.token, req)

                gs.debug(
                    DOMAIN, 'margo request: method: %s, token: %s' %
                    (req.method, req.token))

                header, _ = gs.json_encode({
                    'method': method,
                    'token': req.token
                })
                body, _ = gs.json_encode(arg)
                ln = '%s %s\n' % (header, body)
                proc.stdin.write(ln)
            except Exception:
                gs.println(gs.traceback())
        except Exception:
            gs.println(gs.traceback())
            break
예제 #6
0
def bcall(method, arg, shell=False):
    maybe_install()

    header, _ = gs.json_encode({"method": method, "token": "mg9.call"})
    body, _ = gs.json_encode(arg)
    s = "%s %s" % (header, body)
    s = "base64:%s" % base64.b64encode(s)
    out, err, _ = gsshell.run([MARGO9_BIN, "-do", s], stderr=gs.LOGFILE, shell=shell)
    res = {"error": err}

    if out:
        try:
            for ln in out.split("\n"):
                ln = ln.strip()
                if ln:
                    r, err = gs.json_decode(ln, {})
                    if err:
                        res = {"error": "Invalid response %s" % err}
                    else:
                        if r.get("token") == "mg9.call":
                            res = r.get("data") or {}
                            if gs.is_a({}, res) and r.get("error"):
                                r["error"] = res["error"]
                            return res
                        res = {"error": "Unexpected response %s" % r}
        except Exception:
            res = {"error": gs.traceback()}

    return res
예제 #7
0
	def run(self, edit):
		v = self.view
		pos = gs.sel(v).begin()
		inscope = lambda p: v.score_selector(p, 'path.9o') > 0
		if not inscope(pos):
			pos -= 1
			if not inscope(pos):
				return

		path = v.substr(v.extract_scope(pos))
		if URL_PATH_PAT.match(path):
			try:
				if not URL_SCHEME_PAT.match(path):
					path = 'http://%s' % path
				gs.notice(DOMAIN, 'open url: %s' % path)
				webbrowser.open_new_tab(path)
			except Exception:
				gs.notice(DOMAIN, gs.traceback())
		else:
			wd = v.settings().get('9o.wd') or active_wd()
			m = SPLIT_FN_POS_PAT.match(path)
			path = gs.apath((m.group(1) if m else path), wd)
			row = max(0, int(m.group(2))-1 if (m and m.group(2)) else 0)
			col = max(0, int(m.group(3))-1 if (m and m.group(3)) else 0)

			if os.path.exists(path):
				gs.focus(path, row, col, win=self.view.window())
			else:
				gs.notice(DOMAIN, "Invalid path `%s'" % path)
예제 #8
0
	def write_lines(self, view, edit, lines):
		for ln in lines:
			try:
				view.insert(edit, view.size(), u'%s\n' % ln)
			except Exception:
				gs.println(gs.traceback(DOMAIN))
		view.show(view.line(view.size() - 1).begin())
    def run(self, edit):
        v = self.view
        pos = v.sel()[0].begin()
        inscope = lambda p: v.score_selector(p, 'path.gscommander') > 0
        if not inscope(pos):
            pos -= 1
            if not inscope(pos):
                return

        path = v.substr(v.extract_scope(pos))
        if URL_PATH_PAT.match(path):
            try:
                if not URL_SCHEME_PAT.match(path):
                    path = 'http://%s' % path
                gs.notice(DOMAIN, 'open url: %s' % path)
                webbrowser.open_new_tab(path)
            except Exception:
                gs.notice(DOMAIN, gs.traceback())
        else:
            wd = v.settings().get('gscommander.wd') or active_wd()
            m = SPLIT_FN_POS_PAT.match(path)
            path = gs.apath((m.group(1) if m else path), wd)
            row = max(0, int(m.group(2)) - 1 if (m and m.group(2)) else 0)
            col = max(0, int(m.group(3)) - 1 if (m and m.group(3)) else 0)

            if os.path.exists(path):
                gs.focus(path, row, col, win=self.view.window())
            else:
                gs.notice(DOMAIN, "Invalid path `%s'" % path)
예제 #10
0
    def run(self):
        self.started = time.time()
        tid = gs.begin(DOMAIN,
                       self.message,
                       set_status=False,
                       cancel=self.cancel)
        try:
            try:
                self.p = gs.popen(self.cmd,
                                  shell=self.shell,
                                  stderr=subprocess.STDOUT,
                                  environ=self.env,
                                  cwd=self.cwd,
                                  bufsize=1)

                CommandStdoutReader(self, self.p.stdout).start()
            except Exception as ex:
                self.x = ex
            finally:
                self.rcode = self.p.wait() if self.p else False
        finally:
            gs.end(tid)
            self.ended = time.time()
            self.on_done(self)

            for f in self.done:
                try:
                    f(self)
                except Exception:
                    gs.notice(DOMAIN, gs.traceback())
예제 #11
0
파일: mg9.py 프로젝트: muchenshou/GoSublime
def do(method, arg, shell=False):
	maybe_install()

	header, _ = gs.json_encode({'method': method, 'token': 'mg9.call'})
	body, _ = gs.json_encode(arg)
	s = '%s %s' % (header, body)
	s = 'base64:%s' % base64.b64encode(s)
	out, err, _ = gsshell.run([MARGO9_BIN, '-do', s], stderr=None, shell=shell)
	res = {'error': err}

	if out:
		try:
			for ln in out.split('\n'):
				ln = ln.strip()
				if ln:
					r, err = gs.json_decode(ln, {})
					if err:
						res = {'error': 'Invalid response %s' % err}
					else:
						if r.get('token') == 'mg9.call':
							res = r.get('data') or {}
							if gs.is_a({}, res) and r.get('error'):
								r['error'] = res['error']
							return res
						res = {'error': 'Unexpected response %s' % r}
		except Exception:
			res = {'error': gs.traceback()}

	return res
예제 #12
0
 def write_lines(self, view, edit, lines):
     for ln in lines:
         try:
             view.insert(edit, view.size(), u'%s\n' % ln)
         except Exception:
             gs.println(gs.traceback(DOMAIN))
     view.show(view.line(view.size() - 1).begin())
예제 #13
0
def cmd_9(view, edit, args, wd, rkey):
	if len(args) == 0 or args[0] not in ('play', 'build'):
		push_output(view, rkey, ('9: invalid args %s' % args))
		return

	subcmd = args[0]
	cid, cb = _9_begin_call(subcmd, view, edit, args, wd, rkey)
	a = {
		'cid': cid,
		'env': gs.env(),
		'dir': wd,
		'args': args[1:],
		'build_only': (subcmd == 'build'),
	}

	win = view.window()
	if win is not None:
		av = win.active_view()
		if av is not None:
			fn = av.file_name()
			if fn:
				basedir = gs.basedir_or_cwd(fn)
				for v in win.views():
					try:
						fn = v.file_name()
						if fn and v.is_dirty() and fn.endswith('.go') and os.path.dirname(fn) == basedir:
							v.run_command('gs_fmt_save')
					except Exception:
						gs.println(gs.traceback())
			else:
				if gs.is_go_source_view(av, False):
					a['src'] = av.substr(sublime.Region(0, av.size()))

	mg9.acall('play', a, cb)
예제 #14
0
파일: gsq.py 프로젝트: quarnster/GoSublime
 def run(self):
     tid = gs.begin(self.domain, self.msg, self.set_status)
     try:
         self.f()
     except Exception:
         gs.notice(self.domain, gs.traceback())
     finally:
         gs.end(tid)
예제 #15
0
 def run(self):
     tid = gs.begin(self.domain, self.msg, self.set_status)
     try:
         self.f()
     except Exception:
         gs.notice(self.domain, gs.traceback())
     finally:
         gs.end(tid)
예제 #16
0
def do_comp_lint(dirname, fn):
    fr = ref(fn, False)
    reports = {}
    if not fr:
        return

    fn = gs.apath(fn, dirname)
    bindir, _ = gs.temp_dir('bin')
    local_env = {
        'GOBIN': bindir,
    }

    pat = r'%s:(\d+)(?:[:](\d+))?\W+(.+)\s*' % re.escape(os.path.basename(fn))
    pat = re.compile(pat, re.IGNORECASE)
    for c in gs.setting('comp_lint_commands'):
        try:
            cmd = c.get('cmd')
            if not cmd:
                continue
            cmd_domain = ' '.join(cmd)

            shell = c.get('shell') is True
            env = {} if c.get('global') is True else local_env
            out, err, _ = gsshell.run(cmd=cmd,
                                      shell=shell,
                                      cwd=dirname,
                                      env=env)
            if err:
                gs.notice(DOMAIN, err)

            out = out.replace('\r',
                              '').replace('\n ',
                                          '\\n ').replace('\n\t', '\\n\t')
            for m in pat.findall(out):
                try:
                    row, col, msg = m
                    row = int(row) - 1
                    col = int(col) - 1 if col else 0
                    msg = msg.replace('\\n', '\n').strip()
                    if row >= 0 and msg:
                        msg = '%s: %s' % (cmd_domain, msg)
                        if reports.get(row):
                            reports[row].msg = '%s\n%s' % (reports[row].msg,
                                                           msg)
                            reports[row].col = max(reports[row].col, col)
                        else:
                            reports[row] = Report(row, col, msg)
                except:
                    pass
        except:
            gs.notice(DOMAIN, gs.traceback())

    def cb():
        fr.reports = reports
        fr.state = 1
        highlight(fr)

    sublime.set_timeout(cb, 0)
예제 #17
0
def _send():
	while True:
		try:
			try:
				method, arg, cb = _send_q.get()

				proc = gs.attr(PROC_ATTR_NAME)
				if not proc or proc.poll() is not None:
					if proc:
						try:
							proc.kill()
							proc.stdout.close()
						except:
							pass

					maybe_install()

					if not gs.checked(DOMAIN, 'launch _recv'):
						gsq.launch(DOMAIN, _recv)

					proc, _, err = gsshell.proc([MARGO9_BIN, '-poll=30'], stderr=gs.LOGFILE ,env={
						'XDG_CONFIG_HOME': gs.home_path(),
					})
					gs.set_attr(PROC_ATTR_NAME, proc)

					if not proc:
						gs.notice(DOMAIN, 'Cannot MarGo: %s' % err)
						continue

					gsq.launch(DOMAIN, lambda: _read_stdout(proc))

				req = Request(f=cb, method=method)
				gs.set_attr(REQUEST_PREFIX+req.token, req)

				gs.debug(DOMAIN, 'margo request: method: %s, token: %s' % (req.method, req.token))

				header, _ = gs.json_encode({'method': method, 'token': req.token})
				body, _ = gs.json_encode(arg)
				ln = '%s %s\n' % (header, body)
				proc.stdin.write(ln)
			except Exception:
				gs.println(gs.traceback())
		except Exception:
			gs.println(gs.traceback())
			break
예제 #18
0
    def run(self):
        try:
            while True:
                line = self.stdout.readline()

                if not line:
                    self.c.close_stdout()
                    break

                if not self.c.output_started:
                    self.c.output_started = time.time()

                try:
                    self.c.on_output(self.c, gs.ustr(line.rstrip('\r\n')))
                except Exception:
                    gs.println(gs.traceback(DOMAIN))
        except Exception:
            gs.println(gs.traceback(DOMAIN))
예제 #19
0
	def run(self):
		try:
			while True:
				line = self.stdout.readline()

				if not line:
					self.c.close_stdout()
					break

				if not self.c.output_started:
					self.c.output_started = time.time()

				try:
					self.c.on_output(self.c, gs.ustr(line.rstrip('\r\n')))
				except Exception:
					gs.println(gs.traceback(DOMAIN))
		except Exception:
			gs.println(gs.traceback(DOMAIN))
예제 #20
0
def _recv():
	while True:
		try:
			ln = _recv_q.get()
			try:
				ln = ln.strip()
				if ln:
					r, _ = gs.json_decode(ln, {})
					token = r.get('token', '')
					f = _stash.get(token)
					if f:
						del _stash[token]
						f(r.get('data', {}), r.get('error', ''))
			except Exception:
				gs.println(gs.traceback())
		except Exception:
			gs.println(gs.traceback())
			break
예제 #21
0
def _send():
    while True:
        try:
            try:
                method, arg, cb = _send_q.get()

                proc = gs.attr(PROC_ATTR_NAME)
                if not proc or proc.poll() is not None:
                    killSrv()
                    maybe_install()

                    if not gs.checked(DOMAIN, "launch _recv"):
                        gsq.launch(DOMAIN, _recv)

                    proc, _, err = gsshell.proc(
                        [MARGO9_BIN, "-poll=30"], stderr=gs.LOGFILE, env={"XDG_CONFIG_HOME": gs.home_path()}
                    )
                    gs.set_attr(PROC_ATTR_NAME, proc)

                    if not proc:
                        gs.notice(DOMAIN, "Cannot start MarGo: %s" % err)
                        try:
                            cb({}, "Abort. Cannot start MarGo")
                        except:
                            pass
                        continue

                    gsq.launch(DOMAIN, lambda: _read_stdout(proc))

                req = Request(f=cb, method=method)
                gs.set_attr(REQUEST_PREFIX + req.token, req)

                gs.debug(DOMAIN, "margo request: method: %s, token: %s" % (req.method, req.token))

                header, _ = gs.json_encode({"method": method, "token": req.token})
                body, _ = gs.json_encode(arg)
                ln = "%s %s\n" % (header, body)
                proc.stdin.write(ln)
            except Exception:
                killSrv()
                gs.println(gs.traceback())
        except Exception:
            gs.println(gs.traceback())
            break
예제 #22
0
def _send():
    while True:
        try:
            try:
                method, arg, cb = _send_q.get()

                proc = gs.attr("mg9.proc")
                if not proc or proc.poll() is not None:
                    if proc:
                        try:
                            proc.kill()
                            proc.stdout.close()
                        except:
                            pass

                    maybe_install()

                    if not gs.checked(DOMAIN, "launch _recv"):
                        gsq.launch(DOMAIN, _recv)

                        # ideally the env should be setup before-hand with a bcall
                        # so we won't run this through the shell
                    proc, _, err = gsshell.proc([MARGO9_BIN], stderr=gs.LOGFILE)
                    gs.set_attr("mg9.proc", proc)

                    if not proc:
                        gs.notice(DOMAIN, "Cannot start MarGo9: %s" % err)
                        continue

                    gsq.launch(DOMAIN, lambda: _read_stdout(proc))

                token = "mg9.autoken.%s" % uuid.uuid4()
                _stash[token] = cb

                header, _ = gs.json_encode({"method": method, "token": token})
                body, _ = gs.json_encode(arg)
                ln = "%s %s\n" % (header, body)
                proc.stdin.write(ln)
            except Exception:
                gs.println(gs.traceback())
        except Exception:
            gs.println(gs.traceback())
            break
예제 #23
0
def _send():
	while True:
		try:
			try:
				method, arg, cb = _send_q.get()

				proc = gs.attr('mg9.proc')
				if not proc or proc.poll() is not None:
					if proc:
						try:
							proc.kill()
							proc.stdout.close()
						except:
							pass

					maybe_install()

					if not gs.checked(DOMAIN, 'launch _recv'):
						gsq.launch(DOMAIN, _recv)

					proc, _, err = gsshell.proc([MARGO9_BIN, '-poll=5'], stderr=gs.LOGFILE)
					gs.set_attr('mg9.proc', proc)

					if not proc:
						gs.notice(DOMAIN, 'Cannot start MarGo9: %s' % err)
						continue

					gsq.launch(DOMAIN, lambda: _read_stdout(proc))

				token = 'mg9.autoken.%s' % uuid.uuid4()
				_stash[token] = cb

				header, _ = gs.json_encode({'method': method, 'token': token})
				body, _ = gs.json_encode(arg)
				ln = '%s %s\n' % (header, body)
				proc.stdin.write(ln)
			except Exception:
				gs.println(gs.traceback())
		except Exception:
			gs.println(gs.traceback())
			break
예제 #24
0
def snippet_match(ctx, m):
    try:
        for k, p in m.get('match', {}).iteritems():
            q = ctx.get(k, '')
            if p and gs.is_a_string(p):
                if not re.search(p, str(q)):
                    return False
            elif p != q:
                return False
    except:
        gs.notice(DOMAIN, gs.traceback())
    return True
예제 #25
0
def snippet_match(ctx, m):
	try:
		for k,p in m.get('match', {}).iteritems():
			q = ctx.get(k, '')
			if p and gs.is_a_string(p):
				if not re.search(p, str(q)):
					return False
			elif p != q:
				return False
	except:
		gs.notice(DOMAIN, gs.traceback())
	return True
예제 #26
0
	def on_output_done(self):
		ex = self.exception()
		if ex:
			self.on_output(self, 'Error: ' % ex)

		t = (max(0, self.ended - self.started), max(0, self.output_started - self.started))
		self.do_insert(['[ elapsed: %0.3fs, startup: %0.3fs]\n' % t])

		for f in self.output_done:
			try:
				f(self)
			except Exception:
				gs.notice(DOMAIN, gs.traceback())
예제 #27
0
def do_comp_lint(dirname, fn):
	fr = ref(fn, False)
	reports = {}
	if not fr:
		return

	fn = gs.apath(fn, dirname)
	bindir, _ = gs.temp_dir('bin')
	local_env = {
		'GOBIN': bindir,
	}

	pat = r'%s:(\d+)(?:[:](\d+))?\W+(.+)\s*' % re.escape(os.path.basename(fn))
	pat = re.compile(pat, re.IGNORECASE)
	for c in gs.setting('comp_lint_commands'):
		try:
			cmd = c.get('cmd')
			if not cmd:
				continue
			cmd_domain = ' '.join(cmd)

			shell = c.get('shell') is True
			env = {} if c.get('global') is True else local_env
			out, err, _ = gsshell.run(cmd=cmd, shell=shell, cwd=dirname, env=env)
			if err:
				gs.notice(DOMAIN, err)

			out = out.replace('\r', '').replace('\n ', '\\n ').replace('\n\t', '\\n\t')
			for m in pat.findall(out):
				try:
					row, col, msg = m
					row = int(row)-1
					col = int(col)-1 if col else 0
					msg = msg.replace('\\n', '\n').strip()
					if row >= 0 and msg:
						msg = '%s: %s' % (cmd_domain, msg)
						if reports.get(row):
							reports[row].msg = '%s\n%s' % (reports[row].msg, msg)
							reports[row].col = max(reports[row].col, col)
						else:
							reports[row] = Report(row, col, msg)
				except:
					pass
		except:
			gs.notice(DOMAIN, gs.traceback())

	def cb():
		fr.reports = reports
		fr.state = 1
		highlight(fr)
	sublime.set_timeout(cb, 0)
예제 #28
0
파일: gscomplete.py 프로젝트: ski/GoSublime
def resolve_snippets(ctx):
    cl = set()
    types = [""] if ctx.get("local") else ctx.get("types")
    vars = {}
    for k, v in ctx.iteritems():
        if gs.is_a_string(v):
            vars[k] = v

    try:
        snips = []
        snips.extend(gs.setting("default_snippets", []))
        snips.extend(gs.setting("snippets", []))
        for m in snips:
            try:
                if snippet_match(ctx, m):
                    for ent in m.get("snippets", []):
                        text = ent.get("text", "")
                        title = ent.get("title", "")
                        value = ent.get("value", "")
                        if text and value:
                            for typename in types:
                                vars["typename"] = typename
                                if typename:
                                    if len(typename) > 1 and typename[0].islower() and typename[1].isupper():
                                        vars["typename_abbr"] = typename[1].lower()
                                    else:
                                        vars["typename_abbr"] = typename[0].lower()
                                else:
                                    vars["typename_abbr"] = ""

                                txt, ttl, val = expand_snippet_vars(vars, text, title, value)
                                s = u"%s\t%s \u0282" % (txt, ttl)
                                cl.add((s, val))
            except:
                gs.notice(DOMAIN, gs.traceback())
    except:
        gs.notice(DOMAIN, gs.traceback())
    return list(cl)
예제 #29
0
    def on_output_done(self):
        ex = self.exception()
        if ex:
            self.on_output(self, 'Error: ' % ex)

        t = (max(0, self.ended - self.started),
             max(0, self.output_started - self.started))
        self.do_insert(['[ elapsed: %0.3fs, startup: %0.3fs]\n' % t])

        for f in self.output_done:
            try:
                f(self)
            except Exception:
                gs.notice(DOMAIN, gs.traceback())
예제 #30
0
def _read_stdout(proc):
    try:
        while True:
            ln = proc.stdout.readline()
            if not ln:
                break

            _recv_q.put(ln)
    except Exception:
        gs.println(gs.traceback())

        proc.stdout.close()
        proc.wait()
        proc = None
예제 #31
0
    def run(self):
        while True:
            try:
                f, msg, set_status = self.q.get()
                tid = gs.begin(self.domain, msg, set_status)

                try:
                    f()
                except Exception:
                    gs.notice(self.domain, gs.traceback())
            except:
                pass

            gs.end(tid)
예제 #32
0
파일: gsq.py 프로젝트: quarnster/GoSublime
    def run(self):
        while True:
            try:
                f, msg, set_status = self.q.get()
                tid = gs.begin(self.domain, msg, set_status)

                try:
                    f()
                except Exception:
                    gs.notice(self.domain, gs.traceback())
            except:
                pass

            gs.end(tid)
예제 #33
0
파일: mg9.py 프로젝트: timicx/GoSublime
def _read_stdout(proc):
	try:
		while True:
			ln = proc.stdout.readline()
			if not ln:
				break

			_recv_q.put(ln)
	except Exception:
		gs.println(gs.traceback())

		proc.stdout.close()
		proc.wait()
		proc = None
예제 #34
0
def run(cmd=[], shell=False, env={}, cwd=None, input=None, stderr=subprocess.STDOUT):
	out = u""
	err = u""
	exc = None

	try:
		p, opts, err = proc(cmd, input=input, shell=shell, stderr=stderr, env=env, cwd=cwd)
		if p:
			out, _ = p.communicate(input=opts.get('input'))
			out = gs.ustr(out) if out else u''
	except Exception as ex:
		err = u'Error communicating with command %s: %s' % (opts.get('cmd'), gs.traceback())
		exc = ex

	return (out, err, exc)
예제 #35
0
파일: mg9.py 프로젝트: alexogar/GoSublime
def _read_stdout(proc):
	try:
		import sys
		while True:
			ln = proc.stdout.readline().decode(sys.getdefaultencoding())
			if not ln:
				break

			_recv_q.put(ln)
	except Exception:
		gs.println(gs.traceback())

		proc.stdout.close()
		proc.wait()
		proc = None
예제 #36
0
def run(cmd=[], shell=False, env={}, cwd=None, input=None, stderr=subprocess.STDOUT):
	out = ""
	err = ""
	exc = None

	try:
		p, opts, err = proc(cmd, input=input, shell=shell, stderr=stderr, env=env, cwd=cwd)
		if p:
			out, _ = p.communicate(input=opts.get('input'))
			out = gs.ustr(out) if out else ''
	except Exception as ex:
		err = 'Error communicating with command %s: %s' % (opts.get('cmd'), gs.traceback())
		exc = ex

	return (out, err, exc)
예제 #37
0
def proc(cmd, shell=False, env={}, cwd=None, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0):
	env = gs.env(env)
	shell, cmd = fix_shell_cmd(shell, cmd)

	if input is not None:
		input = gs.astr(input)

	if cwd:
		try:
			os.makedirs(cwd)
		except Exception:
			pass
	else:
		# an empty string isn't a valid value so just always set it None
		cwd = None

	try:
		setsid = os.setsid
	except Exception:
		setsid = None

	opts = {
		'cmd': cmd,
		'shell': shell,
		'env': env,
		'input': input,
	}

	p = None
	err = ''
	try:
		p = subprocess.Popen(
			cmd,
			stdout=stdout,
			stderr=stderr,
			stdin=stdin,
			startupinfo=gs.STARTUP_INFO,
			shell=shell,
			env=env,
			cwd=cwd,
			preexec_fn=setsid,
			bufsize=bufsize
		)
	except Exception:
		err = 'Error running command %s: %s' % (cmd, gs.traceback())

	return (p, opts, err)
예제 #38
0
def proc(cmd, shell=False, env={}, cwd=None, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0):
	env = gs.env(env)
	shell, cmd = fix_shell_cmd(shell, cmd)

	if input is not None:
		input = gs.astr(input)

	if cwd:
		try:
			os.makedirs(cwd)
		except Exception:
			pass
	else:
		# an empty string isn't a valid value so just always set it None
		cwd = None

	try:
		setsid = os.setsid
	except Exception:
		setsid = None

	opts = {
		'cmd': cmd,
		'shell': shell,
		'env': env,
		'input': input,
	}

	p = None
	err = ''
	try:
		p = subprocess.Popen(
			cmd,
			stdout=stdout,
			stderr=stderr,
			stdin=stdin,
			startupinfo=gs.STARTUP_INFO,
			shell=shell,
			env=env,
			cwd=cwd,
			preexec_fn=setsid,
			bufsize=bufsize
		)
	except Exception:
		err = 'Error running command %s: %s' % (cmd, gs.traceback())

	return (p, opts, err)
예제 #39
0
def run(cmd=[], shell=False, env={}, cwd=None, input=None):
	out = u""
	err = u""
	exc = None

	try:
		env = fix_env(env)
		shell, cmd = fix_shell_cmd(shell, cmd)
		p = gs.popen(cmd, shell=shell, stderr=subprocess.STDOUT, environ=env, cwd=cwd)
		if input is not None:
			input = gs.astr(input)
		out, _ = p.communicate(input=input)
		out = gs.ustr(out) if out else u''
	except Exception as ex:
		err = u'Error while running %s: %s' % (cmd, gs.traceback())
		exc = ex

	return (out, err, exc)
예제 #40
0
def run(cmd=[], shell=False, env={}, cwd=None, input=None):
	out = u""
	err = u""
	exc = None

	try:
		env = fix_env(env)
		shell, cmd = fix_shell_cmd(shell, cmd)
		p = gs.popen(cmd, shell=shell, stderr=subprocess.STDOUT, environ=env, cwd=cwd)
		if input is not None:
			input = gs.astr(input)
		out, _ = p.communicate(input=input)
		out = gs.ustr(out) if out else u''
	except Exception as ex:
		err = u'Error while running %s: %s' % (cmd, gs.traceback())
		exc = ex

	return (out, err, exc)
예제 #41
0
def cmd_9(view, edit, args, wd, rkey):
    if len(args) == 0 or args[0] not in ('run', 'replay', 'build'):
        push_output(view, rkey, ('9: invalid args %s' % args))
        return

    subcmd = args[0]
    cid = ''
    if subcmd == 'replay':
        cid = '9replay-%s' % wd
    cid, cb = _9_begin_call(subcmd, view, edit, args, wd, rkey, cid)

    a = {
        'cid': cid,
        'env': gs.env(),
        'dir': wd,
        'args': args[1:],
        'build_only': (subcmd == 'build'),
    }

    win = view.window()
    if win is not None:
        av = win.active_view()
        if av is not None:
            fn = av.file_name()
            if fn:
                basedir = gs.basedir_or_cwd(fn)
                for v in win.views():
                    try:
                        fn = v.file_name()
                        if fn and v.is_dirty() and fn.endswith(
                                '.go') and os.path.dirname(fn) == basedir:
                            v.run_command('gs_fmt_save')
                    except Exception:
                        gs.println(gs.traceback())
            else:
                if gs.is_go_source_view(av, False):
                    a['src'] = av.substr(sublime.Region(0, av.size()))

    mg9.acall('play', a, cb)
예제 #42
0
	def run(self):
		self.started = time.time()
		tid = gs.begin(DOMAIN, self.message, set_status=False, cancel=self.cancel)
		try:
			try:
				self.p = gs.popen(self.cmd, shell=self.shell, stderr=subprocess.STDOUT,
					environ=self.env, cwd=self.cwd, bufsize=1)

				CommandStdoutReader(self, self.p.stdout).start()
			except Exception as ex:
				self.x = ex
			finally:
				self.rcode = self.p.wait() if self.p else False
		finally:
			gs.end(tid)
			self.ended = time.time()
			self.on_done(self)

			for f in self.done:
				try:
					f(self)
				except Exception:
					gs.notice(DOMAIN, gs.traceback())
예제 #43
0
def install(aso_tokens, force_install):
    k = "mg9.install.%s" % REV
    if gs.attr(k, False):
        gs.error(DOMAIN, "Installation aborted. Install command already called for GoSublime %s." % REV)
        return

    gs.set_attr(k, True)

    init_start = time.time()

    try:
        os.makedirs(gs.home_path("bin"))
    except:
        pass

    if not force_install and _bins_exist() and aso_tokens == _gen_tokens():
        m0_out = "no"
        m_out = "no"
    else:
        gs.notify("GoSublime", "Installing MarGo0")
        start = time.time()
        m0_out, err, _ = _run(["go", "build", "-o", MARGO0_BIN], cwd=MARGO0_SRC)
        m0_out, m0_ok = _so(m0_out, err, start, time.time())

        if os.path.exists(MARGO0_BIN):
            margo.bye_ni()

        gs.notify("GoSublime", "Installing MarGo9")
        start = time.time()
        m_out, err, _ = _run(["go", "build", "-o", MARGO9_BIN], cwd=MARGO9_SRC)
        m_out, m_ok = _so(m_out, err, start, time.time())

        if m_ok and m0_ok:

            def f():
                gs.aso().set("mg9_install_tokens", _gen_tokens())
                gs.save_aso()

            sublime.set_timeout(f, 0)

    gs.notify("GoSublime", "Syncing environment variables")
    out, err, _ = gsshell.run([MARGO9_EXE, "-env"], cwd=gs.home_path(), shell=True)

    # notify this early so we don't mask any notices below
    gs.notify("GoSublime", "Ready")
    _check_changes()

    if err:
        gs.notice(DOMAIN, "Cannot run get env vars: %s" % (MARGO9_EXE, err))
    else:
        env, err = gs.json_decode(out, {})
        if err:
            gs.notice(DOMAIN, "Cannot load env vars: %s\nenv output: %s" % (err, out))
        else:
            gs.environ9.update(env)

    e = gs.env()
    a = [
        "GoSublime init (%0.3fs)" % (time.time() - init_start),
        "| install margo0: %s" % m0_out,
        "| install margo9: %s" % m_out,
    ]
    a.extend(["| %14s: %s" % ln for ln in _sanity_check(e)])
    gs.println(*a)

    missing = [k for k in ("GOROOT", "GOPATH") if not e.get(k)]
    if missing:
        gs.notice(DOMAIN, "Missing environment variable(s): %s" % ", ".join(missing))

    killSrv()
    start = time.time()
    # acall('ping', {}, lambda res, err: gs.println('MarGo Ready %0.3fs' % (time.time() - start)))

    report_x = lambda: gs.println("GoSublime: Exception while cleaning up old binaries", gs.traceback())
    try:
        d = gs.home_path("bin")
        for fn in os.listdir(d):
            try:
                if fn not in (MARGO9_EXE, MARGO0_EXE) and fn.startswith(("gosublime", "gocode", "margo")):
                    fn = os.path.join(d, fn)
                    gs.println("GoSublime: removing old binary: %s" % fn)
                    os.remove(fn)
            except Exception:
                report_x()
    except Exception:
        report_x()
예제 #44
0
def install(aso_tokens, force_install):
    k = 'mg9.install.%s' % REV
    if gs.attr(k, False):
        gs.error(
            DOMAIN,
            'Installation aborted. Install command already called for GoSublime %s.'
            % REV)
        return

    gs.set_attr(k, True)

    init_start = time.time()

    try:
        os.makedirs(gs.home_path('bin'))
    except:
        pass

    if not force_install and _bins_exist() and aso_tokens == _gen_tokens():
        m_out = 'no'
    else:
        gs.notify('GoSublime', 'Installing MarGo')
        start = time.time()
        m_out, err, _ = _run(['go', 'build', '-o', MARGO_BIN], cwd=MARGO_SRC)
        m_out, m_ok = _so(m_out, err, start, time.time())

        if m_ok:

            def f():
                gs.aso().set('mg9_install_tokens', _gen_tokens())
                gs.save_aso()

            sublime.set_timeout(f, 0)

    gs.notify('GoSublime', 'Syncing environment variables')
    out, err, _ = gsshell.run([MARGO_EXE, '-env'],
                              cwd=gs.home_path(),
                              shell=True)

    # notify this early so we don't mask any notices below
    gs.notify('GoSublime', 'Ready')
    _check_changes()

    if err:
        gs.notice(DOMAIN, 'Cannot run get env vars: %s' % (MARGO_EXE, err))
    else:
        env, err = gs.json_decode(out, {})
        if err:
            gs.notice(DOMAIN,
                      'Cannot load env vars: %s\nenv output: %s' % (err, out))
        else:
            gs.environ9.update(env)

    e = gs.env()
    a = [
        'GoSublime init (%0.3fs)' % (time.time() - init_start),
        '| install margo: %s' % m_out,
    ]
    a.extend(['| %14s: %s' % ln for ln in _sanity_check(e)])
    gs.println(*a)

    missing = [k for k in ('GOROOT', 'GOPATH') if not e.get(k)]
    if missing:
        gs.notice(DOMAIN,
                  "Missing environment variable(s): %s" % ', '.join(missing))

    killSrv()
    start = time.time()
    # acall('ping', {}, lambda res, err: gs.println('MarGo Ready %0.3fs' % (time.time() - start)))

    report_x = lambda: gs.println(
        "GoSublime: Exception while cleaning up old binaries", gs.traceback())
    try:
        d = gs.home_path('bin')
        for fn in os.listdir(d):
            try:
                if fn != MARGO_EXE and fn.startswith(
                    ('gosublime', 'gocode', 'margo')):
                    fn = os.path.join(d, fn)
                    gs.println("GoSublime: removing old binary: %s" % fn)
                    os.remove(fn)
            except Exception:
                report_x()
    except Exception:
        report_x()

    gsq.launch(DOMAIN, margo.bye_ni)
예제 #45
0
 def run(self):
     try:
         self.f()
     except Exception:
         gs.notice(self.domain, gs.traceback())
예제 #46
0
def install(aso_tokens, force_install):
	k = 'mg9.install.%s' % REV
	if gs.attr(k, False):
		gs.error(DOMAIN, 'Installation aborted. Install command already called for GoSublime %s.' % REV)
		return

	gs.set_attr(k, True)

	init_start = time.time()

	try:
		os.makedirs(gs.home_path('bin'))
	except:
		pass

	if not force_install and _bins_exist() and aso_tokens == _gen_tokens():
		m_out = 'no'
	else:
		gs.notify('GoSublime', 'Installing MarGo')
		start = time.time()
		m_out, err, _ = _run(['go', 'build', '-o', MARGO_BIN], cwd=MARGO_SRC)
		m_out, m_ok = _so(m_out, err, start, time.time())

		if m_ok:
			def f():
				gs.aso().set('mg9_install_tokens', _gen_tokens())
				gs.save_aso()

			sublime.set_timeout(f, 0)

	gs.notify('GoSublime', 'Syncing environment variables')
	out, err, _ = gsshell.run([MARGO_EXE, '-env'], cwd=gs.home_path(), shell=True)

	# notify this early so we don't mask any notices below
	gs.notify('GoSublime', 'Ready')
	_check_changes()

	if err:
		gs.notice(DOMAIN, 'Cannot run get env vars: %s' % (MARGO_EXE, err))
	else:
		env, err = gs.json_decode(out, {})
		if err:
			gs.notice(DOMAIN, 'Cannot load env vars: %s\nenv output: %s' % (err, out))
		else:
			gs.environ9.update(env)

	e = gs.env()
	a = [
		'GoSublime init (%0.3fs)' % (time.time() - init_start),
		'| install margo: %s' % m_out,
	]
	a.extend(['| %14s: %s' % ln for ln in _sanity_check(e)])
	gs.println(*a)

	missing = [k for k in ('GOROOT', 'GOPATH') if not e.get(k)]
	if missing:
		gs.notice(DOMAIN, "Missing environment variable(s): %s" % ', '.join(missing))

	killSrv()
	start = time.time()
	# acall('ping', {}, lambda res, err: gs.println('MarGo Ready %0.3fs' % (time.time() - start)))

	report_x = lambda: gs.println("GoSublime: Exception while cleaning up old binaries", gs.traceback())
	try:
		d = gs.home_path('bin')
		for fn in os.listdir(d):
			try:
				if fn != MARGO_EXE and fn.startswith(('gosublime', 'gocode', 'margo')):
					fn = os.path.join(d, fn)
					gs.println("GoSublime: removing old binary: %s" % fn)
					os.remove(fn)
			except Exception:
				report_x()
	except Exception:
		report_x()

	gsq.launch(DOMAIN, margo.bye_ni)
예제 #47
0
파일: gsq.py 프로젝트: quarnster/GoSublime
 def run(self):
     try:
         self.f()
     except Exception:
         gs.notice(self.domain, gs.traceback())