def cmd_tskill(view, edit, args, wd, rkey): if len(args) > 0: l = [] for tid in args: tid = tid.lstrip('#') tid = tid_alias.get('%s-%s' % (tid, wd), tid) l.append('kill %s: %s' % (tid, ('yes' if gs.cancel_task(tid) else 'no'))) push_output(view, rkey, '\n'.join(l)) return try: now = datetime.datetime.now().replace(microsecond=0) with gs.sm_lck: tasks = sorted(gs.sm_tasks.items()) l = [] for tid, t in tasks: if t['cancel']: pfx = '#%s' % tid else: pfx = '(uninterruptible)' l.append('%s %s %s: %s' % (pfx, (now - t['start'].replace(microsecond=0)), t['domain'], t['message'])) s = '\n'.join(l) except Exception as ex: gs.error_traceback(DOMAIN) s = 'Error: %s' % ex push_output(view, rkey, s)
def act_on_path(view, path): if URL_PATH_PAT.match(path): if path.lower().startswith('gs.packages://'): path = os.path.join(sublime.packages_path(), path[14:]) else: try: if not URL_SCHEME_PAT.match(path): path = 'http://%s' % path gs.notify(DOMAIN, 'open url: %s' % path) webbrowser.open_new_tab(path) return True except Exception: gs.error_traceback(DOMAIN) return False wd = view.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=view.window()) return True else: gs.notify(DOMAIN, "Invalid path `%s'" % path) return False
def act_on_path(view, path): is_vfn = gs.VFN_ID_PAT.match(path) row = 0 col = 0 if not is_vfn: if URL_PATH_PAT.match(path): if path.lower().startswith('gs.packages://'): path = os.path.join(sublime.packages_path(), path[14:]) else: try: if not URL_SCHEME_PAT.match(path): path = 'http://%s' % path gs.notify(DOMAIN, 'open url: %s' % path) webbrowser.open_new_tab(path) return True except Exception: gs.error_traceback(DOMAIN) return False wd = view.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 is_vfn or os.path.exists(path): gs.focus(path, row, col, win=view.window()) return True else: gs.notify(DOMAIN, "Invalid path `%s'" % path) return False
def _save_all(win, wd): if gs.setting('autosave') is True and win is not None: 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) == wd: v.run_command('gs_fmt_save') except Exception: gs.error_traceback(DOMAIN)
def _recv(): while True: try: ln = gs.mg9_recv_q.get() try: ln = ln.strip() if ln: r, _ = gs.json_decode(ln, {}) token = r.get("token", "") tag = r.get("tag", "") k = REQUEST_PREFIX + token req = gs.attr(k, {}) gs.del_attr(k) if req and req.f: if tag != TAG: gs.notice( DOMAIN, "\n".join( [ "GoSublime/MarGo appears to be out-of-sync.", "Maybe restart Sublime Text.", "Received tag `%s', expected tag `%s'. " % (tag, TAG), ] ), ) err = r.get("error", "") gs.debug( DOMAIN, "margo response: %s" % { "method": req.method, "tag": tag, "token": token, "dur": "%0.3fs" % (time.time() - req.tm), "err": err, "size": "%0.1fK" % (len(ln) / 1024.0), }, ) dat = expand_jdata(r.get("data", {})) try: keep = req.f(dat, err) is True if keep: req.tm = time.time() gs.set_attr(k, req) except Exception: gs.error_traceback(DOMAIN) else: gs.debug(DOMAIN, "Ignoring margo: token: %s" % token) except Exception: gs.println(gs.traceback()) except Exception: gs.println(gs.traceback()) break
def _recv(): while True: try: ln = gs.mg9_recv_q.get() try: ln = ln.strip() if ln: r, _ = gs.json_decode(ln, {}) token = r.get('token', '') tag = r.get('tag', '') k = REQUEST_PREFIX + token req = gs.attr(k, {}) gs.del_attr(k) if req and req.f: if tag != TAG: gs.notice( DOMAIN, "\n".join([ "GoSublime/MarGo appears to be out-of-sync.", "Maybe restart Sublime Text.", "Received tag `%s', expected tag `%s'. " % (tag, TAG), ])) err = r.get('error', '') ev.debug( DOMAIN, "margo response: %s" % { 'method': req.method, 'tag': tag, 'token': token, 'dur': '%0.3fs' % (time.time() - req.tm), 'err': err, 'size': '%0.1fK' % (len(ln) / 1024.0), }) dat = expand_jdata(r.get('data', {})) try: keep = req.f(dat, err) is True if keep: req.tm = time.time() gs.set_attr(k, req) except Exception: gs.error_traceback(DOMAIN) else: ev.debug(DOMAIN, 'Ignoring margo: token: %s' % token) except Exception: gs.println(gs.traceback()) except Exception: gs.println(gs.traceback()) break
def run(self): pkg_name = "main" view = gs.active_valid_go_view() try: basedir = gs.basedir_or_cwd(view and view.file_name()) for fn in os.listdir(basedir): if fn.endswith(".go"): name, _ = mg9.pkg_name(os.path.join(basedir, fn), "") if name: pkg_name = name break except Exception: gs.error_traceback("GsNewGoFile") self.window.new_file().run_command("gs_create_new_go_file", {"pkg_name": pkg_name, "file_name": "main.go"})
def expand_jdata(v): if gs.is_a(v, {}): for k in v: v[k] = expand_jdata(v[k]) else: if gs.PY3K and isinstance(v, bytes): v = gs.ustr(v) if gs.is_a_string(v) and v.startswith('base64:'): try: v = gs.ustr(base64.b64decode(v[7:])) except Exception: v = '' gs.error_traceback(DOMAIN) return v
def _recv(): while True: try: ln = gs.mg9_recv_q.get() try: ln = ln.strip() if ln: r, _ = gs.json_decode(ln, {}) token = r.get('token', '') tag = r.get('tag', '') k = REQUEST_PREFIX+token req = gs.attr(k, {}) gs.del_attr(k) if req and req.f: if tag != TAG: gs.notice(DOMAIN, "\n".join([ "GoSublime/MarGo appears to be out-of-sync.", "Maybe restart Sublime Text.", "Received tag `%s', expected tag `%s'. " % (tag, TAG), ])) err = r.get('error', '') ev.debug(DOMAIN, { '_mode': 'response', 'method': req.method, 'tag': tag, 'token': token, 'dur': '%0.3fs' % (time.time() - req.tm), 'err': err, 'size': '%0.1fK' % (len(ln)/1024.0), }) dat = expand_jdata(r.get('data', {})) try: keep = req.f(dat, err) is True if keep: req.tm = time.time() gs.set_attr(k, req) except Exception: gs.error_traceback(DOMAIN) else: ev.debug(DOMAIN, 'Ignoring margo: token: %s' % token) except Exception: gs.print_traceback() except Exception: gs.print_traceback() break
def run(self): pkg_name = 'main' view = gs.active_valid_go_view() try: basedir = gs.basedir_or_cwd(view and view.file_name()) for fn in os.listdir(basedir): if fn.endswith('.go'): name, _ = mg9.pkg_name(os.path.join(basedir, fn), '') if name: pkg_name = name break except Exception: gs.error_traceback('GsNewGoFile') self.window.new_file().run_command('gs_create_new_go_file', { 'pkg_name': pkg_name, 'file_name': 'main.go', })
def expand_jdata(v): """Expands a byte or base64 encoded string. """ if gs.is_a(v, {}): for k in v: v[k] = expand_jdata(v[k]) elif gs.is_a(v, []): v = [expand_jdata(e) for e in v] else: if gs.PY3K and isinstance(v, bytes): v = gs.ustr(v) if gs.is_a_string(v) and v.startswith("base64:"): try: v = gs.ustr(base64.b64decode(v[7:])) except Exception: v = "" gs.error_traceback(DOMAIN) return v
def ext_main_file(install=False): src_dir = ext_pkg_path() def ext_fn(): l = sorted(glob.glob('%s/*.go' % src_dir)) return l[0] if l else '' fn = ext_fn() if fn or not install: return fn try: gs.mkdirp(src_dir) with open('%s/gosublime.go' % src_dir, 'x') as f: f.write(DEFAULT_EXT_SRC) except FileExistsError: pass except Exception: gs.error_traceback(DOMAIN, status_txt='Cannot create default extension package') return ext_fn()
def act_on_path(view, path): row = 0 col = 0 m = gs.VFN_ID_PAT.match(path) if m: path = "gs.view://%s" % m.group(1) m2 = gs.ROWCOL_PAT.match(m.group(2)) if m2: row = int(m2.group(1)) - 1 if m2.group(1) else 0 col = int(m2.group(2)) - 1 if m2.group(2) else 0 else: if URL_PATH_PAT.match(path): if path.lower().startswith("gs.packages://"): path = os.path.join(gs.packages_dir(), path[14:]) else: try: if not URL_SCHEME_PAT.match(path): path = "http://%s" % path gs.notify(DOMAIN, "open url: %s" % path) webbrowser.open_new_tab(path) return True except Exception: gs.error_traceback(DOMAIN) return False wd = view.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 m or os.path.exists(path): gs.focus(path, row, col, win=view.window()) return True else: gs.notify(DOMAIN, "Invalid path `%s'" % path) return False
def run(self, edit): v = self.view sel = gs.sel(v) if (sel.end() - sel.begin()) == 0: pos = sel.begin() inscope = lambda p: v.score_selector(p, 'path.9o') > 0 if not inscope(pos): pos -= 1 if not inscope(pos): return r = v.extract_scope(pos) else: r = sel path = v.substr(r) if URL_PATH_PAT.match(path): if path.lower().startswith('gs.packages://'): path = os.path.join(sublime.packages_path(), path[14:]) else: try: if not URL_SCHEME_PAT.match(path): path = 'http://%s' % path gs.notify(DOMAIN, 'open url: %s' % path) webbrowser.open_new_tab(path) except Exception: gs.error_traceback(DOMAIN) return 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.notify(DOMAIN, "Invalid path `%s'" % path)
def ext_main_file(install=False): src_dir = ext_pkg_path() def ext_fn(): l = sorted(glob.glob('%s/*.go' % src_dir)) return l[0] if l else '' fn = ext_fn() if fn or not install: return fn try: gs.mkdirp(src_dir) with open('%s/gosublime.go' % src_dir, 'x') as f: f.write(DEFAULT_EXT_SRC) except FileExistsError: pass except Exception: gs.error_traceback( DOMAIN, status_txt='Cannot create default extension package') return ext_fn()
def run(self, edit): v = self.view sel = gs.sel(v) if (sel.end() - sel.begin()) == 0: pos = sel.begin() inscope = lambda p: v.score_selector(p, 'path.9o') > 0 if not inscope(pos): pos -= 1 if not inscope(pos): return r = v.extract_scope(pos) else: r = sel path = v.substr(r) if URL_PATH_PAT.match(path): if path.lower().startswith('gs.packages://'): path = os.path.join(sublime.packages_path(), path[14:]) else: try: if not URL_SCHEME_PAT.match(path): path = 'http://%s' % path gs.notify(DOMAIN, 'open url: %s' % path) webbrowser.open_new_tab(path) except Exception: gs.error_traceback(DOMAIN) return 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.notify(DOMAIN, "Invalid path `%s'" % path)
def _recv(): while True: try: ln = gs.mg9_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', ''), )) dat = expand_jdata(r.get('data', {})) err = r.get('error', '') try: keep = req.f(dat, err) is not True if keep: req.tm = time.time() gs.set_attr(k, req) except Exception: gs.error_traceback(DOMAIN) else: gs.debug(DOMAIN, 'Ignoring margo: token: %s' % token) except Exception: gs.println(gs.traceback()) except Exception: gs.println(gs.traceback()) break
def _call(cb, res, err): try: cb(res, err) except Exception: gs.error_traceback(DOMAIN)
def run(self, edit, save_hist=False): view = self.view pos = gs.sel(view).begin() line = view.line(pos) wd = view.settings().get('9o.wd') try: os.chdir(wd) except Exception: gs.error_traceback(DOMAIN) ln = view.substr(line).split('#', 1) if len(ln) == 2: cmd = ln[1].strip() if cmd: vs = view.settings() aso = gs.aso() hkey = _hkey(wd) hist = gs.dval(aso.get(hkey), []) m = HIST_EXPAND_PAT.match(cmd) if m: pfx = m.group(1) hl = len(hist) idx = hl - int(m.group(2)) cmd = '' if idx >= 0 and idx < hl: cmd = hist[idx] if pfx == '^' or not cmd: view.replace(edit, line, ('%s# %s' % (ln[0], cmd))) return elif save_hist: try: hist.remove(cmd) except ValueError: pass hist.append(cmd) aso.set(hkey, hist) gs.save_aso() if not cmd: view.run_command('gs9o_init') return view.replace(edit, line, (u'[ `%s` %s ]' % (cmd, HOURGLASS))) rkey = '9o.exec.%s' % uuid.uuid4() view.add_regions(rkey, [sublime.Region(line.begin(), view.size())], '') view.run_command('gs9o_init') nv = sh.env() anv = nv.copy() seen = {} am = aliases() while True: cli = cmd.split(' ', 1) nm = cli[0] if not nm: break ag = cli[1].strip() if len(cli) == 2 else '' alias = am.get(nm, '') if not alias: break if alias in seen: gs.error(DOMAIN, 'recursive alias detected: `%s`' % alias) break seen[alias] = True anv['_args'] = ag cmd = string.Template(alias).safe_substitute(anv) if nm != 'sh': f = builtins().get(nm) if f: args = [] if ag: args = [_exparg(s, nv) for s in shlex.split(gs.astr(ag))] f(view, edit, args, wd, rkey) return if nm == 'sh': args = sh.cmd(ag) else: args = sh.cmd(cmd) cmd_sh(view, edit, args, wd, rkey) else: view.insert(edit, gs.sel(view).begin(), '\n')
def run(self, edit, save_hist=False): view = self.view pos = gs.sel(view).begin() line = view.line(pos) wd = view.settings().get('9o.wd') try: os.chdir(wd) except Exception: gs.error_traceback(DOMAIN) ln = view.substr(line).split('#', 1) if len(ln) == 2: cmd = ln[1].strip() if cmd: vs = view.settings() aso = gs.aso() hkey = _hkey(wd) hist = gs.dval(aso.get(hkey), []) m = HIST_EXPAND_PAT.match(cmd) if m: pfx = m.group(1) hl = len(hist) idx = hl - int(m.group(2)) cmd = '' if idx >= 0 and idx < hl: cmd = hist[idx] if pfx == '^' or not cmd: view.replace(edit, line, ('%s# %s' % (ln[0], cmd))) return elif save_hist: try: hist.remove(cmd) except ValueError: pass hist.append(cmd) aso.set(hkey, hist) gs.save_aso() if not cmd: view.run_command('gs9o_init') return view.replace(edit, line, (u'[ `%s` %s ]' % (cmd, HOURGLASS))) rkey = '9o.exec.%s' % uuid.uuid4() view.add_regions(rkey, [sublime.Region(line.begin(), view.size())], '') view.run_command('gs9o_init') nv = sh.env() anv = nv.copy() seen = {} am = aliases() while True: cli = cmd.split(' ', 1) nm = cli[0] if not nm: break ag = cli[1].strip() if len(cli) == 2 else '' alias = am.get(nm, '') if not alias: break if alias in seen: gs.error(DOMAIN, 'recursive alias detected: `%s`' % alias) break seen[alias] = True anv['_args'] = ag cmd = string.Template(alias).safe_substitute(anv) if nm != 'sh': f = builtins().get(nm) if f: args = [] if ag: args = [ _exparg(s, nv) for s in shlex.split(gs.astr(ag)) ] f(view, edit, args, wd, rkey) return if nm == 'sh': args = sh.cmd(ag) else: args = sh.cmd(cmd) cmd_sh(view, edit, args, wd, rkey) else: view.insert(edit, gs.sel(view).begin(), '\n')
def _recv(): """Polls the mg9_recv_q queue parsing responses. """ # TODO: REFACTOR. while True: try: ln = gs.mg9_recv_q.get() try: ln = ln.strip() if ln: r, _ = gs.json_decode(ln, {}) token = r.get("token", "") tag = r.get("tag", "") k = REQUEST_PREFIX + token # TODO: try req = gs.del_attr(k) req = gs.attr(k, {}) gs.del_attr(k) if req and req.f: if tag != TAG: gs.notice( DOMAIN, "\n".join( [ "GoSublime/MarGo appears to be out-of-sync.", "Maybe restart Sublime Text.", "Received tag `%s', expected tag `%s'. " % (tag, TAG), ] ), ) err = r.get("error", "") # TODO: Check if debug is enabled (len()). ev.debug( DOMAIN, "margo response: %s" % { "method": req.method, "tag": tag, "token": token, "dur": "%0.3fs" % (time.time() - req.tm), "err": err, "size": "%0.1fK" % (len(ln) / 1024.0), }, ) # CEV: req.f is the callback 'cb' set in _send(). # dat = expand_jdata(r.get("data", {})) try: # Add request back to the attr dict. # # TODO: Document, which calls keep the request. keep = req.f(dat, err) is True if keep: req.tm = time.time() gs.set_attr(k, req) except Exception: gs.error_traceback(DOMAIN) else: ev.debug(DOMAIN, "Ignoring margo: token: %s" % token) except Exception: gs.println(gs.traceback()) except Exception: gs.println(gs.traceback()) break