def on_margo_done(c): s = '\n'.join(c.consume_outq()) x = c.exception() if x: gs.notice(DOMAIN, 'MarGo Error: %s\nOutput: %s' % (x, s)) else: gs.println('%s: MarGo: %s' % (DOMAIN, s))
def print_install_log(c, s): e = gs.env() dur = c.ended - c.started pkgdir = sublime.packages_path() subl9_status = (BUNDLE_GOSUBLIME9.replace(pkgdir, 'Packages'), os.path.exists(BUNDLE_GOSUBLIME9)) margo_status = (BUNDLE_GOCODE.replace(pkgdir, 'Packages'), os.path.exists(BUNDLE_GOCODE)) gocode_status = (BUNDLE_MARGO.replace(pkgdir, 'Packages'), os.path.exists(BUNDLE_MARGO)) gs.println( 'GoSublime: %s done %0.3fs' % (DOMAIN, dur), '| Bundle GOPATH: %s' % BUNDLE_GOPATH.replace(pkgdir, 'Packages'), '| Bundle GOBIN: %s' % BUNDLE_GOBIN.replace(pkgdir, 'Packages'), '| Bundle Gocode: %s (exists: %s)' % gocode_status, '| Bundle GoSublime9: %s (exists: %s)' % subl9_status, '| Bundle MarGo: %s (exists: %s)' % margo_status, '| User GOROOT: %s' % e.get('GOROOT', '(NOT SET)'), '| User GOPATH: %s' % e.get('GOPATH', '(NOT SET)'), '| User GOBIN: %s (should usually be `NOT SET\')' % e.get('GOBIN', '(NOT SET)'), s) CRITICAL_ENV_VARS = ('GOROOT', 'GOPATH') unset_vars = [var for var in CRITICAL_ENV_VARS if not e.get(var)] if unset_vars: tpl = 'check the console for error messages: the following environment variables are not set: %s' gs.notice(DOMAIN, tpl % ', '.join(unset_vars))
def f(): out, err, _ = gs.runcmd(['go', 'get', '-u', '-v', GOCODE_REPO, MARGO_REPO]) margo.bye_ni() call_cmd(['gocode', 'close']) gs.notice(DOMAIN, '%s done' % msg) gs.println(DOMAIN, '%s done\n%s%s' % (msg, out, err)) do_hello()
def do_hello(): global hello_sarting if hello_sarting: return hello_sarting = True tid = gs.begin(DOMAIN, 'Starting Gocode', False) call_cmd([mg9.GOCODE_BIN]) gs.end(tid) margo_cmd = list(gs.setting('margo_cmd', [])) margo_cmd = [ mg9.MARGO0_BIN, "-d", "-call", "replace", "-addr", gs.setting('margo_addr', '') ] tid = gs.begin(DOMAIN, 'Starting MarGo', False) out, err, _ = gs.runcmd(margo_cmd) gs.end(tid) out = out.strip() err = err.strip() if err: gs.notice(DOMAIN, err) elif out: gs.println(DOMAIN, 'MarGo started %s' % out) hello_sarting = False
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
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 f(docs, err): doc = '' if err: self.show_output('// Error: %s' % err) elif docs: if mode == "goto": fn = '' flags = 0 if len(docs) > 0: d = docs[0] fn = d.get('fn', '') row = d.get('row', 0) col = d.get('col', 0) if fn: gs.println('opening %s:%s:%s' % (fn, row, col)) gs.focus(fn, row, col) return self.show_output("%s: cannot find definition" % DOMAIN) elif mode == "hint": s = [] for d in docs: name = d.get('name', '') if name: kind = d.get('kind', '') pkg = d.get('pkg', '') if pkg: name = '%s.%s' % (pkg, name) src = d.get('src', '') if src: src = '\n//\n%s' % src doc = '// %s %s%s' % (name, kind, src) s.append(doc) doc = '\n\n\n'.join(s).strip() self.show_output(doc or "// %s: no docs found" % DOMAIN)
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)
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
def print_install_log(c, s): e = gs.env() dur = c.ended - c.started pkgdir = sublime.packages_path() subl9_status = (BUNDLE_GOSUBLIME9.replace(pkgdir, 'Packages'), os.path.exists(BUNDLE_GOSUBLIME9)) margo_status = (BUNDLE_GOCODE.replace(pkgdir, 'Packages'), os.path.exists(BUNDLE_GOCODE)) gocode_status = (BUNDLE_MARGO.replace(pkgdir, 'Packages'), os.path.exists(BUNDLE_MARGO)) gs.println( 'GoSublime: %s done %0.3fs' % (DOMAIN, dur), '| Bundle GOPATH: %s' % BUNDLE_GOPATH.replace(pkgdir, 'Packages'), '| Bundle GOBIN: %s' % BUNDLE_GOBIN.replace(pkgdir, 'Packages'), '| Bundle Gocode: %s (exists: %s)' % gocode_status, '| Bundle GoSublime9: %s (exists: %s)' % subl9_status, '| Bundle MarGo: %s (exists: %s)' % margo_status, '| User GOROOT: %s' % e.get('GOROOT', '(NOT SET)'), '| User GOPATH: %s' % e.get('GOPATH', '(NOT SET)'), '| User GOBIN: %s (should usually be `NOT SET\')' % e.get('GOBIN', '(NOT SET)'), s ) CRITICAL_ENV_VARS = ('GOROOT', 'GOPATH') unset_vars = [var for var in CRITICAL_ENV_VARS if not e.get(var)] if unset_vars: tpl = 'check the console for error messages: the following environment variables are not set: %s' gs.notice(DOMAIN, tpl % ', '.join(unset_vars))
def f(docs, err): doc = "" if err: self.show_output("// Error: %s" % err) elif docs: if mode == "goto": fn = "" flags = 0 if len(docs) > 0: d = docs[0] fn = d.get("fn", "") row = d.get("row", 0) col = d.get("col", 0) if fn: gs.println("opening %s:%s:%s" % (fn, row, col)) gs.focus(fn, row, col) return self.show_output("%s: cannot find definition" % DOMAIN) elif mode == "hint": s = [] for d in docs: name = d.get("name", "") if name: kind = d.get("kind", "") pkg = d.get("pkg", "") if pkg: name = "%s.%s" % (pkg, name) src = d.get("src", "") if src: src = "\n//\n%s" % src doc = "// %s %s%s" % (name, kind, src) s.append(doc) doc = "\n\n\n".join(s).strip() self.show_output(doc or "// %s: no docs found" % DOMAIN)
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
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
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
def do_post_save(view): if not gs.is_pkg_view(view): return for c in gs.setting('on_save', []): cmd = c.get('cmd', '') args = c.get('args', {}) msg = 'running on_save command %s' % cmd tid = gs.begin(DOMAIN, msg, set_status=False) gs.println(msg) try: view.run_command(cmd, args) except Exception as ex: gs.notice(DOMAIN, 'Error %s' % ex) finally: gs.end(tid)
def do_post_save(view): if not gs.is_pkg_view(view): return domain = 'GoSublime-On-Save' for c in gs.setting('on_save', []): cmd = c.get('cmd', '') args = c.get('args', {}) msg = 'running on_save command %s' % cmd tid = gs.begin(domain, msg, set_status=False) gs.println(msg) try: view.run_command(cmd, args) except Exception as ex: gs.notice(domain, 'Error %s' % ex) finally: gs.end(tid)
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
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))
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
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
def run(self, edit): vsize = self.view.size() src = self.view.substr(sublime.Region(0, vsize)) if not src.strip(): return src, err = mg9.fmt(self.view.file_name(), src) if err: gs.println(DOMAIN, "cannot fmt file. error: `%s'" % err) return if not src.strip(): gs.println(DOMAIN, "cannot fmt file. it appears to be empty") return _, err = gspatch.merge(self.view, vsize, src) if err: msg = 'PANIC: Cannot fmt file. Check your source for errors (and maybe undo any changes).' sublime.error_message("%s: %s: Merge failure: `%s'" % (DOMAIN, msg, err))
def install(aso_tokens, force_install): init_start = time.time() try: os.makedirs(gs.home_path("bin")) except: pass if not force_install and aso_tokens == _gen_tokens(): m_out = "no" g_out = "no" else: 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()) # on windows the file cannot be replaced if it's running so close gocode first. # in theory, mg9 has the same issue but since it's attached to a st2 instance, # the only way to close it is to close st2 (which we're presumably already doing) start = time.time() if os.path.exists(GOCODE_BIN): _run([GOCODE_BIN, "close"]) g_out, err, _ = _run(["go", "build", "-o", GOCODE_BIN], cwd=GOCODE_SRC) g_out, g_ok = _so(g_out, err, start, time.time()) if m_ok and g_ok: def f(): gs.aso().set("mg9_install_tokens", _gen_tokens()) gs.save_aso() sublime.set_timeout(f, 0) a = ( "GoSublime init (%0.3fs)" % (time.time() - init_start), "| install margo9: %s" % m_out, "| install gocode: %s" % g_out, "| ~bin: %s" % gs.home_path("bin"), "| margo9: %s (%s)" % _tp(MARGO9_BIN), "| gocode: %s (%s)" % _tp(GOCODE_BIN), ) gs.println(*a)
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
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
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)
def do_hello(): global hello_sarting if hello_sarting: return hello_sarting = True margo_cmd = [ mg9.MARGO0_BIN, "-d", "-call", "replace", "-addr", gs.setting('margo_addr', '') ] tid = gs.begin(DOMAIN, 'Starting MarGo', False) out, err, _ = gsshell.run(margo_cmd) gs.end(tid) out = out.strip() err = err.strip() if err: gs.notice(DOMAIN, err) elif out: gs.println(DOMAIN, 'MarGo started %s' % out) hello_sarting = False
def install(aso_tokens, force_install): 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') 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, '| ~bin: %s' % gs.home_path('bin'), '| margo0: %s (%s)' % _tp(MARGO0_BIN), '| margo9: %s (%s)' % _tp(MARGO9_BIN), '| GOROOT: %s' % e.get('GOROOT', '(not set)'), '| GOPATH: %s' % e.get('GOPATH', '(not set)'), '| GOBIN: %s (should usually be (not set))' % e.get('GOBIN', '(not set)'), ) 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()
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)
def install(aso_tokens, force_install): 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' g_out = 'no' else: 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(GOCODE_BIN): margo.bye_ni() 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()) # on windows the file cannot be replaced if it's running so close gocode first. # in theory, mg9 has the same issue but since it's attached to a st2 instance, # the only way to close it is to close st2 (which we're presumably already doing) start = time.time() if os.path.exists(GOCODE_BIN): _run([GOCODE_BIN, 'close']) g_out, err, _ = _run(['go', 'build', '-o', GOCODE_BIN], cwd=GOCODE_SRC) g_out, g_ok = _so(g_out, err, start, time.time()) if m_ok and m0_ok and g_ok: def f(): gs.aso().set('mg9_install_tokens', _gen_tokens()) gs.save_aso() sublime.set_timeout(f, 0) out, err, _ = gsshell.run([MARGO9_EXE, '-env'], cwd=gs.home_path(), shell=True) 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, '| install gocode: %s' % g_out, '| ~bin: %s' % gs.home_path('bin'), '| margo0: %s (%s)' % _tp(MARGO0_BIN), '| margo9: %s (%s)' % _tp(MARGO9_BIN), '| gocode: %s (%s)' % _tp(GOCODE_BIN), '| GOROOT: %s' % e.get('GOROOT', '(not set)'), '| GOPATH: %s' % e.get('GOPATH', '(not set)'), '| GOBIN: %s (should usually be (not set))' % e.get('GOBIN', '(not set)'), ) 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))
def cb(s): file_name = self.view.file_name() or '' s = GO_PLAY_PAT.sub(r'\1go run\2', s) s = s.strip() if s and s.lower() != "go" and self.change_history: hist = self.settings.get('cmd_hist') if not gs.is_a(hist, {}): hist = {} basedir = gs.basedir_or_cwd(file_name) hist[basedir] = [s] # todo: store a list of historical commands hst = {} for k in hist: # :| hst[gs.ustr(k)] = gs.ustr(hist[k]) self.settings.set('cmd_hist', hst) sublime.save_settings('GoSublime-GsShell.sublime-settings') if GO_SHARE_PAT.match(s): s = '' host = "play.golang.org" warning = 'Are you sure you want to share this file. It will be public on %s' % host if not sublime.ok_cancel_dialog(warning): return try: c = httplib.HTTPConnection(host) src = gs.astr(self.view.substr(sublime.Region(0, self.view.size()))) c.request('POST', '/share', src, {'User-Agent': 'GoSublime'}) s = 'http://%s/p/%s' % (host, c.getresponse().read()) except Exception as ex: s = 'Error: %s' % ex self.show_output(s, focus=True) return if GO_RUN_PAT.match(s): if not file_name: # todo: clean this up after the command runs err = '' tdir, _ = gs.temp_dir('play') file_name = hashlib.sha1(gs.view_fn(self.view) or 'a').hexdigest() file_name = os.path.join(tdir, ('%s.go' % file_name)) try: with open(file_name, 'w') as f: src = gs.astr(self.view.substr(sublime.Region(0, self.view.size()))) f.write(src) except Exception as ex: err = str(ex) if err: self.show_output('Error: %s' % err) return s = ['go', 'run', file_name] self.view.window().run_command("exec", { 'kill': True }) if gs.is_a(s, []): use_shell = False else: use_shell = True s = [s] gs.println('running %s' % ' '.join(s)) self.view.window().run_command("exec", { 'shell': use_shell, 'env': gs.env(), 'cmd': s, 'file_regex': '^(.+\.go):([0-9]+):(?:([0-9]+):)?\s*(.*)', })
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()
def cb(s): file_name = self.view.file_name() or '' s = GO_PLAY_PAT.sub(r'\1go run\2', s) s = s.strip() if s and s.lower() != "go" and self.change_history: hist = self.settings.get('cmd_hist') if not gs.is_a(hist, {}): hist = {} basedir = gs.basedir_or_cwd(file_name) hist[basedir] = [s ] # todo: store a list of historical commands hst = {} for k in hist: # :| hst[gs.ustr(k)] = gs.ustr(hist[k]) self.settings.set('cmd_hist', hst) sublime.save_settings('GoSublime-GsShell.sublime-settings') if GO_SHARE_PAT.match(s): s = '' host = "play.golang.org" warning = 'Are you sure you want to share this file. It will be public on %s' % host if not sublime.ok_cancel_dialog(warning): return try: c = httplib.HTTPConnection(host) src = gs.astr( self.view.substr(sublime.Region(0, self.view.size()))) c.request('POST', '/share', src, {'User-Agent': 'GoSublime'}) s = 'http://%s/p/%s' % (host, c.getresponse().read()) except Exception as ex: s = 'Error: %s' % ex self.show_output(s, focus=True) return if GO_RUN_PAT.match(s): if not file_name: # todo: clean this up after the command runs err = '' tdir, _ = gs.temp_dir('play') file_name = hashlib.sha1(gs.view_fn(self.view) or 'a').hexdigest() file_name = os.path.join(tdir, ('%s.go' % file_name)) try: with open(file_name, 'w') as f: src = gs.astr( self.view.substr( sublime.Region(0, self.view.size()))) f.write(src) except Exception as ex: err = str(ex) if err: self.show_output('Error: %s' % err) return s = ['go', 'run', file_name] self.view.window().run_command("exec", {'kill': True}) if gs.is_a(s, []): use_shell = False else: use_shell = True s = [s] gs.println('running %s' % ' '.join(s)) self.view.window().run_command( "exec", { 'shell': use_shell, 'env': gs.env(), 'cmd': s, 'file_regex': '^(.+\.go):([0-9]+):(?:([0-9]+):)?\s*(.*)', })
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()
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)
def _dump(res, err): gs.println(json.dumps({"res": res, "err": err}, sort_keys=True, indent=2))
def _dump(res, err): gs.println(json.dumps({ 'res': res, 'err': err, }, sort_keys=True, indent=2))
def check_depends(): gr = gs.go_env_goroot() if not gr: gs.notice(DOMAIN, 'The `go` command cannot be found') return e = gs.env() if not e.get('GOROOT'): os.environ['GOROOT'] = gr elif not e.get('GOPATH'): gs.notice(DOMAIN, "GOPATH and/or GOROOT appear to be unset") gs.println( 'GoSublime: checking dependencies', ('\tGOROOT is: %s' % e.get('GOROOT', gr)), ('\tGOPATH is: %s' % e.get('GOPATH', '')) ) missing = [] for cmd in ('gocode', 'MarGo'): if not call_cmd([cmd, '--help']): missing.append(cmd) if missing: def cb(i, _): if i == 0: run_go_get() items = [[ 'GoSublime depends on gocode and MarGo', 'Install %s (using `go get`)' % ', '.join(missing), 'gocode repo: %s' % GOCODE_REPO, 'MarGo repo: %s' % MARGO_REPO, ]] gs.show_quick_panel(items, cb) gs.println(DOMAIN, '\n'.join(items[0])) return changelog_fn = os.path.join(sublime.packages_path(), 'GoSublime', "CHANGELOG.md") try: with open(changelog_fn) as f: s = f.read() except IOError: gs.notice(DOMAIN, traceback.format_exc()) return changes = split_changes(s) if changes: def cb(): settings_fn = 'GoSublime-GsDepends.sublime-settings' settings = sublime.load_settings(settings_fn) new_rev = changes[-1][0] old_rev = settings.get('tracking_rev', '') def on_panel_close(i, win): if i > 0: settings.set('tracking_rev', new_rev) sublime.save_settings(settings_fn) win.open_file(changelog_fn) if i == 1: run_go_get() if new_rev > old_rev: items = [ [ " ", "GoSublime updated to %s" % new_rev, " ", ], [ "Install/Update dependencies: Gocode, MarGo", "go get -u %s" % GOCODE_REPO, "go get -u %s" % MARGO_REPO, ], [ "View changelog", "Packages/GoSublime/CHANGELOG.md" " ", ] ] gs.show_quick_panel(items, on_panel_close) sublime.set_timeout(cb, 0) else: margo.call( path='/', args='hello', message='hello MarGo' )
def cb(s): file_name = self.view.file_name() or "" s = GO_PLAY_PAT.sub(r"\1go run\2", s) s = s.strip() if s and s.lower() != "go" and self.change_history: hist = self.settings.get("cmd_hist") if not gs.is_a(hist, {}): hist = {} basedir = gs.basedir_or_cwd(file_name) hist[basedir] = [s] # todo: store a list of historical commands hst = {} for k in hist: # :| hst[gs.ustr(k)] = gs.ustr(hist[k]) self.settings.set("cmd_hist", hst) sublime.save_settings("GoSublime-GsShell.sublime-settings") if GO_SHARE_PAT.match(s): s = "" host = "play.golang.org" warning = "Are you sure you want to share this file. It will be public on %s" % host if not sublime.ok_cancel_dialog(warning): return try: c = httplib.HTTPConnection(host) src = gs.astr(self.view.substr(sublime.Region(0, self.view.size()))) c.request("POST", "/share", src, {"User-Agent": "GoSublime"}) s = "http://%s/p/%s" % (host, c.getresponse().read()) except Exception as ex: s = "Error: %s" % ex self.show_output(s, focus=True) return if GO_RUN_PAT.match(s): if not file_name: # todo: clean this up after the command runs err = "" tdir, _ = gs.temp_dir("play") file_name = hashlib.sha1(gs.view_fn(self.view) or "a").hexdigest() file_name = os.path.join(tdir, ("%s.go" % file_name)) try: with open(file_name, "w") as f: src = gs.astr(self.view.substr(sublime.Region(0, self.view.size()))) f.write(src) except Exception as ex: err = str(ex) if err: self.show_output("Error: %s" % err) return s = ["go", "run", file_name] self.view.window().run_command("exec", {"kill": True}) if gs.is_a(s, []): use_shell = False else: use_shell = True s = [s] gs.println("running %s" % " ".join(s)) self.view.window().run_command( "exec", { "shell": use_shell, "env": gs.env(), "cmd": s, "file_regex": "^(.+\.go):([0-9]+):(?:([0-9]+):)?\s*(.*)", }, )
def install(aso_tokens, force_install): 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') 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, '| ~bin: %s' % gs.home_path('bin'), '| margo0: %s (%s)' % _tp(MARGO0_BIN), '| margo9: %s (%s)' % _tp(MARGO9_BIN), '| GOROOT: %s' % e.get('GOROOT', '(not set)'), '| GOPATH: %s' % e.get('GOPATH', '(not set)'), '| GOBIN: %s (should usually be (not set))' % e.get('GOBIN', '(not set)'), ) 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)))
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()