def on_done(self, s): s = s.strip() if s: self.settings.set('last_command', s) sublime.save_settings('GoSublime-GsShell.sublime-settings') if GO_RUN_PAT.match(s): s = 'go run *.go' gpat = ' *.go' if gpat in s: fns = [] for fn in os.listdir(os.path.dirname(self.view.file_name())): if fn.endswith('.go') and fn[0] not in ('.', '_') and not fn.endswith('_test.go'): fns.append(fn) fns = ' '.join(fns) if fns: s = s.replace(gpat, ' '+fns) self.view.window().run_command("exec", { 'kill': True }) self.view.window().run_command("exec", { 'shell': True, 'env': gs.env(), 'cmd': [s], 'file_regex': '^(.+\.go):([0-9]+):(?:([0-9]+):)?\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 declarations(fn, src, pkg_dir, f): return acall('declarations', { 'fn': fn or '', 'src': src, 'env': gs.env(), 'pkg_dir': pkg_dir, }, f)
def declarations(filename, src, pkg_dir=''): return post('/declarations', { 'fn': filename or '', 'src': src, 'env': gs.env(), 'pkg_dir': pkg_dir, }, {})
def call(path='/', args={}, default={}, cb=None, message=''): try: if args is None: a = '' elif isinst(args, {}): a = { 'env': gs.env(), 'tab_indent': gs.setting('fmt_tab_indent'), 'tab_width': gs.setting('fmt_tab_width'), } for k, v in args.iteritems(): if v is None: v = '' a[k] = v else: a = args except: a = args def f(): res, err = post(path, a, default, False, True) if cb: sublime.set_timeout(lambda: cb(res, err), 0) dispatch(f, 'call %s: %s' % (path, message))
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 cmd_9(view, edit, args, wd, r): if len(args) == 1 and args[0] == "play": dmn = '%s: 9 play' % DOMAIN cid = '9play-%s' % uuid.uuid4() def cancel(): mg9.acall('kill', {'cid': cid}, None) tid = gs.begin(dmn, "9 play", set_status=False, cancel=cancel) def cb(res, err): out = '\n'.join(s for s in (res.get('out'), res.get('err')) if s) if not out: out = err def f(): gs.end(tid) view.insert(edit, r.end(), '\n%s' % out) view.run_command('gs_commander_init') sublime.set_timeout(f, 0) a = { 'cid': cid, 'env': gs.env(), 'dir': wd, } av = sublime.active_window().active_view() if av and not av.file_name() and gs.is_go_source_view(av, False): a['src'] = av.substr(sublime.Region(0, av.size())) mg9.acall('play', a, cb) else: view.insert(edit, r.end(), ('Invalid args %s' % args)) view.run_command('gs_commander_init')
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: _save_all(win, wd) else: if gs.is_go_source_view(av, False): a['src'] = av.substr(sublime.Region(0, av.size())) mg9.acall('play', a, cb)
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 call(path='/', args={}, default={}, cb=None, message=''): try: if args is None: a = '' elif isinst(args, {}): a = { 'env': gs.env(), 'tab_indent': gs.setting('fmt_tab_indent'), 'tab_width': gs.setting('fmt_tab_width'), } for k, v in args.items(): if v is None: v = '' a[k] = v else: a = args except: a = args def f(): res, err = post(path, a, default, False, True) if cb: sublime.set_timeout(lambda: cb(res, err), 0) dispatch(f, 'call %s: %s' % (path, message))
def complete(self, fn, offset, src, func_name_only): global last_gopath gopath = gs.env().get('GOPATH') if gopath and gopath != last_gopath: out, _, _ = gsshell.run(cmd=['go', 'env', 'GOOS', 'GOARCH']) vars = out.strip().split() if len(vars) == 2: last_gopath = gopath libpath = os.path.join(gopath, 'pkg', '_'.join(vars)) gsshell.run(cmd=['gocode', 'set', 'lib-path', libpath], cwd=gsbundle.BUNDLE_GOBIN) comps = [] cmd = gs.setting('gocode_cmd', 'gocode') offset = 'c%s' % offset args = [cmd, "-f=json", "autocomplete", fn, offset] js, err, _ = gsshell.run(cmd=args, input=src) if err: gs.notice(DOMAIN, err) else: try: js = json.loads(js) if js and js[1]: for ent in js[1]: tn = ent['type'] cn = ent['class'] nm = ent['name'] sfx = self.typeclass_prefix(cn, tn) if cn == 'func': if nm in ('main', 'init'): continue act = gs.setting('autocomplete_tests', False) if not act and nm.startswith( ('Test', 'Benchmark', 'Example')): continue params, ret = declex(tn) ret = ret.strip('() ') if func_name_only: a = nm else: a = [] for i, p in enumerate(params): n, t = p if t.startswith('...'): n = '...' a.append('${%d:%s}' % (i + 1, n)) a = '%s(%s)' % (nm, ', '.join(a)) comps.append(('%s\t%s %s' % (nm, ret, sfx), a)) elif cn != 'PANIC': comps.append(('%s\t%s %s' % (nm, tn, sfx), nm)) except KeyError as e: gs.notice( DOMAIN, 'Error while running gocode, possibly malformed data returned: %s' % e) except ValueError as e: gs.notice(DOMAIN, "Error while decoding gocode output: %s" % e) return comps
def doc(fn, src, offset, f): return acall('doc', { 'fn': fn or '', 'src': src or '', 'offset': offset or 0, 'env': gs.env(), 'tabIndent': gs.setting('fmt_tab_indent'), 'tabWidth': gs.setting('fmt_tab_width'), }, f)
def pkg_dirs(f): tid = gs.begin(DOMAIN, 'Fetching pkg dirs') def cb(res, err): gs.end(tid) f(res, err) acall('pkg_dirs', { 'env': gs.env(), }, cb)
def import_paths(fn, src, f): tid = gs.begin(DOMAIN, 'Fetching import paths') def cb(res, err): gs.end(tid) f(res, err) acall('import_paths', { 'fn': fn or '', 'src': src or '', 'env': gs.env(), }, cb)
def complete(self, fn, offset, src, func_name_only): global last_gopath gopath = gs.env().get('GOPATH') if gopath and gopath != last_gopath: out, _, _ = gsshell.run(cmd=['go', 'env', 'GOOS', 'GOARCH']) vars = out.strip().split() if len(vars) == 2: last_gopath = gopath libpath = os.path.join(gopath, 'pkg', '_'.join(vars)) gsshell.run(cmd=['gocode', 'set', 'lib-path', libpath], cwd=gsbundle.BUNDLE_GOBIN) comps = [] cmd = gs.setting('gocode_cmd', 'gocode') offset = 'c%s' % offset args = [cmd, "-f=json", "autocomplete", fn, offset] js, err, _ = gsshell.run(cmd=args, input=src) if err: gs.notice(DOMAIN, err) else: try: js = json.loads(js) if js and js[1]: for ent in js[1]: tn = ent['type'] cn = ent['class'] nm = ent['name'] sfx = self.typeclass_prefix(cn, tn) if cn == 'func': if nm in ('main', 'init'): continue act = gs.setting('autocomplete_tests', False) if not act and nm.startswith(('Test', 'Benchmark', 'Example')): continue params, ret = declex(tn) ret = ret.strip('() ') if func_name_only: a = nm else: a = [] for i, p in enumerate(params): n, t = p if t.startswith('...'): n = '...' a.append('${%d:%s}' % (i+1, n)) a = '%s(%s)' % (nm, ', '.join(a)) comps.append(('%s\t%s %s' % (nm, ret, sfx), a)) elif cn != 'PANIC': comps.append(('%s\t%s %s' % (nm, tn, sfx), nm)) except KeyError as e: gs.notice(DOMAIN, 'Error while running gocode, possibly malformed data returned: %s' % e) except ValueError as e: gs.notice(DOMAIN, "Error while decoding gocode output: %s" % e) return comps
def cmd_go(view, edit, args, wd, rkey): cid, cb = _9_begin_call('go', view, edit, args, wd, rkey, '') a = { 'cid': cid, 'env': gs.env(), 'cwd': wd, 'cmd': { 'name': 'go', 'args': args, } } mg9.acall('sh', a, cb)
def declarations(fn, src, pkg_dir, f): tid = gs.begin(DOMAIN, 'Fetching declarations') def cb(res, err): gs.end(tid) f(res, err) return acall('declarations', { 'fn': fn or '', 'src': src, 'env': gs.env(), 'pkgDir': pkg_dir, }, cb)
def _sanity_check(env={}): if not env: env = gs.env() return [ ('version', REV), ('~bin', '%s' % gs.home_path('bin')), ('MarGo', '%s (%s)' % _tp(MARGO_BIN)), ('GOROOT', '%s' % env.get('GOROOT', '(not set)')), ('GOPATH', '%s' % env.get('GOPATH', '(not set)')), ('GOBIN', '%s (should usually be (not set))' % env.get('GOBIN', '(not set)')), ]
def _sanity_check(env={}): if not env: env = gs.env() return [ ("version", REV), ("~bin", "%s" % gs.home_path("bin")), ("margo0", "%s (%s)" % _tp(MARGO0_BIN)), ("margo9", "%s (%s)" % _tp(MARGO9_BIN)), ("GOROOT", "%s" % env.get("GOROOT", "(not set)")), ("GOPATH", "%s" % env.get("GOPATH", "(not set)")), ("GOBIN", "%s (should usually be (not set))" % env.get("GOBIN", "(not set)")), ]
def doc(fn, src, offset, f): tid = gs.begin(DOMAIN, 'Fetching doc info') def cb(res, err): gs.end(tid) f(res, err) acall('doc', { 'fn': fn or '', 'src': src or '', 'offset': offset or 0, 'env': gs.env(), 'tabIndent': gs.setting('fmt_tab_indent'), 'tabWidth': gs.setting('fmt_tab_width'), }, cb)
def cmd_go(view, edit, args, wd, rkey): _save_all(view.window(), wd) cid, cb = _9_begin_call('go', view, edit, args, wd, rkey, '9go-%s' % wd) a = { 'cid': cid, 'env': gs.env(), 'cwd': wd, 'cmd': { 'name': 'go', 'args': args, } } mg9.acall('sh', a, cb)
def doc(fn, src, offset, f): tid = gs.begin(DOMAIN, 'Fetching doc info') def cb(res, err): gs.end(tid) f(res, err) acall( 'doc', { 'fn': fn or '', 'src': src or '', 'offset': offset or 0, 'env': gs.env(), 'tabIndent': gs.setting('fmt_tab_indent'), 'tabWidth': gs.setting('fmt_tab_width'), }, cb)
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)
def complete(fn, src, pos): home = gs.home_path() builtins = (gs.setting('autocomplete_builtins') is True or gs.setting('complete_builtins') is True) res, err = bcall('gocode_complete', { 'Dir': gs.basedir_or_cwd(fn), 'Builtins': builtins, 'Fn': fn or '', 'Src': src or '', 'Pos': pos or 0, 'Home': home, 'Env': gs.env({ 'XDG_CONFIG_HOME': home, }), }) res = gs.dval(res.get('completions'), []) return res, err
def complete(fn, src, pos): home = gs.home_path() builtins = gs.setting("autocomplete_builtins") is True or gs.setting("complete_builtins") is True res, err = bcall( "gocode_complete", { "Dir": gs.basedir_or_cwd(fn), "Builtins": builtins, "Fn": fn or "", "Src": src or "", "Pos": pos or 0, "Home": home, "Env": gs.env({"XDG_CONFIG_HOME": home}), }, ) res = gs.dval(res.get("completions"), []) return res, err
def call(path="/", args={}, default={}, cb=None, message=""): try: if args is None: a = "" elif isinst(args, {}): a = {"env": gs.env(), "tab_indent": gs.setting("fmt_tab_indent"), "tab_width": gs.setting("fmt_tab_width")} for k, v in args.iteritems(): if v is None: v = "" a[k] = v else: a = args except: a = args def f(): res, err = post(path, a, default, False, True) if cb: sublime.set_timeout(lambda: cb(res, err), 0) dispatch(f, "call %s: %s" % (path, message))
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 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(): 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): 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 cmd_env(view, edit, args, wd, rkey): _env_settings(gs.env(), view, edit, args, wd, rkey)
def check_depends(view): global dep_check_done if dep_check_done: return if not view or not view.window(): sublime.set_timeout(lambda: check_depends(view), 1000) return if not gs.is_go_source_view(view): return dep_check_done = True e = gs.env() if not (e.get('GOROOT') and e.get('GOPATH')): gs.notice(DOMAIN, "GOPATH and/or GOROOT appear to be unset") if not call_cmd(['go', '--help']): gs.notice(DOMAIN, 'The `go` command cannot be found') return missing = [] cmds = [ ['gocode', '--help'], ['MarGo', '--help'], ] for cmd in cmds: if not call_cmd(cmd): missing.append(cmd[0]) if missing: def cb(i): if i == 0: run_go_get(view) items = [[ 'GoSublime depends on gocode and MarGo', 'Install %s (using `go get`)' % ', '.join(missing), 'gocode repo: %s' % GOCODE_REPO, 'MarGo repo: %s' % MARGO_REPO, ]] view.window().show_quick_panel(items, cb) 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: win = sublime.active_window() if win: 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): if i == 1 or i == 2: view = win.open_file(changelog_fn) if i == 1: run_go_get(view) settings.set('tracking_rev', new_rev) sublime.save_settings(settings_fn) 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" " ", ] ] win.show_quick_panel(items, on_panel_close) return gsq.dispatch(hello)
def pkg_dirs(f): acall('pkg_dirs', { 'env': gs.env(), }, f)
def import_paths(fn, src, f): acall('import_paths', { 'fn': fn or '', 'src': src or '', 'env': gs.env(), }, f)
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 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 self.change_history: hist = self.settings.get('cmd_hist') if not isinstance(hist, dict): hist = {} basedir = gs.basedir_or_cwd(file_name) hist[basedir] = [s] # todo: store a list of historical commands self.settings.set('cmd_hist', hist) 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 = 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) return if GO_RUN_PAT.match(s): if not file_name: # todo: clean this up after the command runs f, err = gs.temp_file(suffix='.go', prefix=DOMAIN+'-play.', delete=False) if err: self.show_output(err) return else: try: src = self.view.substr(sublime.Region(0, self.view.size())) if isinstance(src, unicode): src = src.encode('utf-8') f.write(src) f.close() except Exception as ex: self.show_output('Error: %s' % ex) return file_name = f.name s = 'go run "%s"' % file_name else: gpat = ' *.go' if gpat in s: fns = [] for fn in os.listdir(os.path.dirname(self.view.file_name())): if fn.endswith('.go') and fn[0] not in ('.', '_') and not fn.endswith('_test.go'): fns.append('"%s"' % fn) fns = ' '.join(fns) if fns: s = s.replace(gpat, ' '+fns) self.view.window().run_command("exec", { 'kill': True }) self.view.window().run_command("exec", { 'shell': True, 'env': gs.env(), 'cmd': [s], 'file_regex': '^(.+\.go):([0-9]+):(?:([0-9]+):)?\s*(.*)', })
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()