Esempio n. 1
0
	def jump_to_imports(self):
		view = gs.active_valid_go_view()
		if not view:
			return

		last_import = gs.attr('last_import_path.%s' % gs.view_fn(view), '')
		r = None
		if last_import:
			offset = len(last_import) + 2
			last_import = re.escape(last_import)
			pat = '(?s)import.*?(?:"%s"|`%s`)' % (last_import, last_import)
			r = view.find(pat, 0)

		if not r:
			offset = 1
			pat = '(?s)import.*?["`]'
			r = view.find(pat, 0)

		if not r:
			gs.notice(DOMAIN, "cannot find import declarations")
			return

		pt = r.end() - offset
		row, col = view.rowcol(pt)
		loc = Loc(view.file_name(), row, col)
		self.jump_to((view, loc))
Esempio n. 2
0
def show_pkgfiles(dirname):
	ents = []
	m = {}

	try:
		dirname = os.path.abspath(dirname)
		for fn in gs.list_dir_tree(dirname, ext_filter, gs.setting('fn_exclude_prefixes', [])):
			name = os.path.relpath(fn, dirname).replace('\\', '/')
			m[name] = fn
			ents.append(name)
	except Exception as ex:
		gs.notice(DOMAIN, 'Error: %s' % ex)

	if ents:
		ents.sort(key = lambda a: a.lower())

		try:
			s = " ../  ( current: %s )" % dirname
			m[s] = os.path.join(dirname, "..")
			ents.insert(0, s)
		except Exception:
			pass

		def cb(i, win):
			if i >= 0:
				fn = m[ents[i]]
				if os.path.isdir(fn):
					win.run_command("gs_browse_files", {"dir": fn})
				else:
					gs.focus(fn, 0, 0, win)
		gs.show_quick_panel(ents, cb)
	else:
		gs.show_quick_panel([['', 'No files found']])
Esempio n. 3
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())
Esempio n. 4
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())
Esempio n. 5
0
    def jump_to_imports(self):
        view = gs.active_valid_go_view()
        if not view:
            return

        last_import = gs.attr('last_import_path.%s' % gs.view_fn(view), '')
        r = None
        if last_import:
            offset = len(last_import) + 2
            last_import = re.escape(last_import)
            pat = '(?s)import.*?(?:"%s"|`%s`)' % (last_import, last_import)
            r = view.find(pat, 0)

        if not r:
            offset = 1
            pat = '(?s)import.*?["`]'
            r = view.find(pat, 0)

        if not r:
            gs.notice(DOMAIN, "cannot find import declarations")
            return

        pt = r.end() - offset
        row, col = view.rowcol(pt)
        loc = Loc(view.file_name(), row, col)
        self.jump_to((view, loc))
Esempio n. 6
0
def show_pkgfiles(dirname):
    ents = []
    m = {}

    try:
        dirname = os.path.abspath(dirname)
        for fn in gs.list_dir_tree(dirname, ext_filter,
                                   gs.setting('fn_exclude_prefixes', [])):
            name = os.path.relpath(fn, dirname).replace('\\', '/')
            m[name] = fn
            ents.append(name)
    except Exception as ex:
        gs.notice(DOMAIN, 'Error: %s' % ex)

    if ents:
        ents.sort(key=lambda a: a.lower())

        try:
            s = " ../  ( current: %s )" % dirname
            m[s] = os.path.join(dirname, "..")
            ents.insert(0, s)
        except Exception:
            pass

        def cb(i, win):
            if i >= 0:
                fn = m[ents[i]]
                if os.path.isdir(fn):
                    win.run_command("gs_browse_files", {"dir": fn})
                else:
                    gs.focus(fn, 0, 0, win)

        gs.show_quick_panel(ents, cb)
    else:
        gs.show_quick_panel([['', 'No files found']])
Esempio n. 7
0
		def f(im, err):
			if err:
				gs.notice(DOMAIN, err)
				return

			delete_imports = []
			add_imports = []
			for path in im.get('paths', []):
				skipAdd = False
				for i in im.get('imports', []):
					if i.get('path') == path:
						skipAdd = True
						name = i.get('name', '')
						if not name:
							name = basename(path)
						if name == path:
							delete_imports.append(('%sdelete: %s' % (indent, name), i))
						else:
							delete_imports.append(('%sdelete: %s ( %s )' % (indent, name, path), i))

				if not skipAdd:
					add_imports.append(('%s%s' % (indent, path), {'path': path, 'add': True}))
			for i in sorted(delete_imports):
				self.add_item(i[0], self.toggle_import, (view, i[1]))
			if len(delete_imports) > 0:
				self.add_item(' ', self.show_palette, 'imports')
			for i in sorted(add_imports):
				self.add_item(i[0], self.toggle_import, (view, i[1]))

			self.do_show_panel()
Esempio n. 8
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)
Esempio n. 9
0
 def run(self):
     tid = gs.begin(self.domain, self.msg, self.set_status)
     try:
         self.f()  # WARN (CEV): Error
     except Exception:
         gs.notice(self.domain, gs.traceback())
     finally:
         gs.end(tid)
Esempio n. 10
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)
Esempio n. 11
0
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
Esempio n. 12
0
def snippet_match(ctx, m):
	try:
		for k,p in m.get('match', {}).items():
			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
Esempio n. 13
0
def snippet_match(ctx, m):
    try:
        for k, p in m.get('match', {}).items():
            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
Esempio n. 14
0
    def show_palette(self, palette, direct=False):
        view = gs.active_valid_go_view(self.window)
        if not view:
            return

        palette = palette.lower().strip()
        if palette == 'auto':
            palette = self.last_activate_palette
        elif palette == 'main':
            palette = ''

        pcb = None
        if palette:
            pcb = self.palettes.get(palette)
            if pcb:
                self.last_activate_palette = palette
            else:
                gs.notice(DOMAIN, 'Invalid palette `%s`' % palette)
                palette = ''

        if not direct and len(self.bookmarks) > 0:
            loc = self.bookmarks[-1]
            line = 'line %d' % (loc.row + 1)
            if view.file_name() == loc.fn:
                fn = ''
            else:
                fn = relpath(loc.fn, dirname(loc.fn))
                if fn.startswith('..'):
                    fn = loc.fn
                fn = '%s ' % fn
            self.add_item(u'\u2190 Go Back (%s%s)' % (fn, line),
                          self.jump_back, None)

        if not direct and palette:
            self.add_item(u'@%s \u21B5' % palette.title(), self.show_palette,
                          'main')

        li1 = len(self.items)
        if pcb:
            pcb(view, direct)

        if not direct:
            for k in sorted(self.palettes.keys()):
                if k:
                    if k != palette:
                        ttl = '@' + k.title()
                        if k == 'errors':
                            fr = gslint.ref(view.file_name())
                            if not fr or len(fr.reports) == 0:
                                continue
                            ttl = '%s (%d)' % (ttl, len(fr.reports))
                        itm = ttl
                        self.add_item(itm, self.show_palette, k)
Esempio n. 15
0
        def f(im, err):
            if err:
                gs.notice(DOMAIN, err)
                return

            delete_imports = []
            add_imports = []
            paths = im.get('paths', {})
            use_named = gs.setting('use_named_imports') is True
            for path in paths:
                skipAdd = False
                for i in im.get('imports', []):
                    if i.get('path') == path:
                        skipAdd = True
                        name = i.get('name', '')
                        if not name:
                            name = basename(path)
                        if name == path:
                            delete_imports.append(
                                ('%sdelete: %s' % (indent, name), i))
                        else:
                            delete_imports.append(
                                ('%sdelete: %s ( %s )' % (indent, name, path),
                                 i))

                if not skipAdd:
                    title = paths[path]
                    s = '%s%s' % (indent, path)
                    m = {
                        'path': path,
                        'add': True,
                    }
                    name = title.split()[0] if title else ''
                    if name and name != path and not path.endswith(
                            '/%s' % name):
                        s = '%s (%s)' % (s, name)
                        if use_named:
                            m['name'] = name

                    if '[vendored]' in title:
                        s = s + ' [vendored]'

                    add_imports.append((s, m))

            for i in sorted(delete_imports):
                self.add_item(i[0], self.toggle_import, (view, i[1]))
            if len(delete_imports) > 0:
                self.add_item(' ', self.show_palette, 'imports')
            for i in sorted(add_imports):
                self.add_item(i[0], self.toggle_import, (view, i[1]))

            self.do_show_panel()
Esempio n. 16
0
    def show_palette(self, palette, direct=False):
        view = gs.active_valid_go_view(self.window)
        if not view:
            return

        palette = palette.lower().strip()
        if palette == "auto":
            palette = self.last_activate_palette
        elif palette == "main":
            palette = ""

        pcb = None
        if palette:
            pcb = self.palettes.get(palette)
            if pcb:
                self.last_activate_palette = palette
            else:
                gs.notice(DOMAIN, "Invalid palette `%s`" % palette)
                palette = ""

        if not direct and len(self.bookmarks) > 0:
            loc = self.bookmarks[-1]
            line = "line %d" % (loc.row + 1)
            if view.file_name() == loc.fn:
                fn = ""
            else:
                fn = relpath(loc.fn, dirname(loc.fn))
                if fn.startswith(".."):
                    fn = loc.fn
                fn = "%s " % fn
            self.add_item(u"\u2190 Go Back (%s%s)" % (fn, line), self.jump_back, None)

        if not direct and palette:
            self.add_item(u"@%s \u21B5" % palette.title(), self.show_palette, "main")

        li1 = len(self.items)
        if pcb:
            pcb(view, direct)

        if not direct:
            for k in sorted(self.palettes.keys()):
                if k:
                    if k != palette:
                        ttl = "@" + k.title()
                        if k == "errors":
                            fr = gslint.ref(view.file_name())
                            if not fr or len(fr.reports) == 0:
                                continue
                            ttl = "%s (%d)" % (ttl, len(fr.reports))
                        itm = ttl
                        self.add_item(itm, self.show_palette, k)
Esempio n. 17
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)
Esempio n. 18
0
	def show_palette(self, palette, direct=False):
		view = gs.active_valid_go_view(self.window)
		if not view:
			return

		palette = palette.lower().strip()
		if palette == 'auto':
			palette = self.last_activate_palette
		elif palette == 'main':
			palette = ''

		pcb = None
		if palette:
			pcb = self.palettes.get(palette)
			if pcb:
				self.last_activate_palette = palette
			else:
				gs.notice(DOMAIN, 'Invalid palette `%s`' % palette)
				palette = ''

		if not direct and len(self.bookmarks) > 0:
			loc = self.bookmarks[-1]
			line = 'line %d' % (loc.row + 1)
			if view.file_name() == loc.fn:
				fn = ''
			else:
				fn = relpath(loc.fn, dirname(loc.fn))
				if fn.startswith('..'):
					fn = loc.fn
				fn = '%s ' % fn
			self.add_item(u'\u2190 Go Back (%s%s)' % (fn, line), self.jump_back, None)

		if not direct and palette:
			self.add_item(u'@%s \u21B5' % palette.title(), self.show_palette, 'main')

		li1 = len(self.items)
		if pcb:
			pcb(view, direct)

		if not direct:
			for k in sorted(self.palettes.keys()):
				if k:
					if k != palette:
						ttl = '@' + k.title()
						if k == 'errors':
							fr = gslint.ref(view.file_name())
							if not fr or len(fr.reports) == 0:
								continue
							ttl = '%s (%d)' % (ttl, len(fr.reports))
						itm = ttl
						self.add_item(itm, self.show_palette, k)
Esempio n. 19
0
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
Esempio n. 20
0
	def on_output_done(self):
		ex = self.exception()
		if ex:
			self.on_output(self, 'Error: ' % ex)

		if self.show_summary:
			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())
Esempio n. 21
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)
Esempio n. 22
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)
Esempio n. 23
0
		def f(res, err):
			if err:
				gs.notice(DOMAIN, err)
				return

			ents, m = handle_pkgdirs_res(res)
			if ents:
				def cb(i, win):
					if i >= 0:
						dirname = gs.basedir_or_cwd(m[ents[i]])
						win.run_command('gs_browse_files', {'dir': dirname})
				gs.show_quick_panel(ents, cb)
			else:
				gs.show_quick_panel([['', 'No source directories found']])
Esempio n. 24
0
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)
        try:
            view.run_command(cmd, args)
        except Exception as ex:
            gs.notice(DOMAIN, 'Error %s' % ex)
        finally:
            gs.end(tid)
Esempio n. 25
0
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)
		try:
			view.run_command(cmd, args)
		except Exception as ex:
			gs.notice(DOMAIN, 'Error %s' % ex)
		finally:
			gs.end(tid)
Esempio n. 26
0
def _send():
	while True:
		try:
			try:
				method, arg, cb = gs.mg9_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([_margo_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)

				if gs.PY3K:
					proc.stdin.write(bytes(ln, 'UTF-8'))
				else:
					proc.stdin.write(ln)
			except Exception:
				killSrv()
				gs.println(gs.traceback())
		except Exception:
			gs.println(gs.traceback())
			break
Esempio n. 27
0
		def f(im, err):
			if err:
				gs.notice(DOMAIN, err)
				return

			delete_imports = []
			add_imports = []
			paths = im.get('paths', {})
			use_named = gs.setting('use_named_imports') is True
			for path in paths:
				skipAdd = False
				for i in im.get('imports', []):
					if i.get('path') == path:
						skipAdd = True
						name = i.get('name', '')
						if not name:
							name = basename(path)
						if name == path:
							delete_imports.append(('%sdelete: %s' % (indent, name), i))
						else:
							delete_imports.append(('%sdelete: %s ( %s )' % (indent, name, path), i))

				if not skipAdd:
					title = paths[path]
					s = '%s%s' % (indent, path)
					m = {
						'path': path,
						'add': True,
					}
					name = title.split()[0] if title else ''
					if name and name != path and not path.endswith('/%s' % name):
						s = '%s (%s)' % (s, name)
						if use_named:
							m['name'] = name

					if '[vendored]' in title:
						s = s + ' [vendored]'

					add_imports.append((s, m))

			for i in sorted(delete_imports):
				self.add_item(i[0], self.toggle_import, (view, i[1]))
			if len(delete_imports) > 0:
				self.add_item(' ', self.show_palette, 'imports')
			for i in sorted(add_imports):
				self.add_item(i[0], self.toggle_import, (view, i[1]))

			self.do_show_panel()
Esempio n. 28
0
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
Esempio n. 29
0
        def f(res, err):
            if err:
                gs.notice(DOMAIN, err)
                return

            ents, m = handle_pkgdirs_res(res)
            if ents:

                def cb(i, win):
                    if i >= 0:
                        dirname = gs.basedir_or_cwd(m[ents[i]])
                        win.run_command('gs_browse_files', {'dir': dirname})

                gs.show_quick_panel(ents, cb)
            else:
                gs.show_quick_panel([['', 'No source directories found']])
Esempio n. 30
0
            def f(res, err):
                if err:
                    gs.notice(DOMAIN, err)
                    return

                ents, m = handle_pkgdirs_res(res)
                if ents:
                    ents.insert(0, "Current Package")

                    def cb(i, win):
                        if i == 0:
                            self.present_current()
                        elif i >= 1:
                            self.present('', '', os.path.dirname(m[ents[i]]))

                    gs.show_quick_panel(ents, cb)
                else:
                    gs.show_quick_panel([['', 'No source directories found']])
Esempio n. 31
0
			def f(res, err):
				if err:
					gs.notice(DOMAIN, err)
					return

				ents, m = handle_pkgdirs_res(res)
				if ents:
					ents.insert(0, "Current Package")

					def cb(i, win):
						if i == 0:
							self.present_current()
						elif i >= 1:
							self.present('', '', os.path.dirname(m[ents[i]]))

					gs.show_quick_panel(ents, cb)
				else:
					gs.show_quick_panel([['', 'No source directories found']])
Esempio n. 32
0
def resolve_snippets(ctx):
    cl = set()
    types = [""] if ctx.get("local") else ctx.get("types", [""])
    vars = {}
    for k, v in ctx.items():
        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)
Esempio n. 33
0
def resolve_snippets(ctx):
    cl = set()
    types = [''] if ctx.get('local') else ctx.get('types')
    vars = {}
    for k, v in ctx.items():
        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)
Esempio n. 34
0
        def f(im, err):
            if err:
                gs.notice(DOMAIN, err)
                return

            delete_imports = []
            add_imports = []
            paths = im.get("paths", {})
            for path in paths:
                skipAdd = False
                for i in im.get("imports", []):
                    if i.get("path") == path:
                        skipAdd = True
                        name = i.get("name", "")
                        if not name:
                            name = basename(path)
                        if name == path:
                            delete_imports.append(("%sdelete: %s" % (indent, name), i))
                        else:
                            delete_imports.append(
                                ("%sdelete: %s ( %s )" % (indent, name, path), i)
                            )

                if not skipAdd:
                    s = "%s%s" % (indent, path)
                    m = {"path": path, "add": True}

                    nm = paths[path]
                    if nm and nm != path and not path.endswith("/%s" % nm):
                        s = "%s (%s)" % (s, nm)
                        if gs.setting("use_named_imports") is True:
                            m["name"] = nm

                    add_imports.append((s, m))

            for i in sorted(delete_imports):
                self.add_item(i[0], self.toggle_import, (view, i[1]))
            if len(delete_imports) > 0:
                self.add_item(" ", self.show_palette, "imports")
            for i in sorted(add_imports):
                self.add_item(i[0], self.toggle_import, (view, i[1]))

            self.do_show_panel()
Esempio n. 35
0
    def toggle_import(self, a):
        view, decl = a
        im, err = mg9.imports(view.file_name(),
                              view.substr(sublime.Region(0, view.size())),
                              [decl])

        if err:
            gs.notice(DOMAIN, err)
        else:
            src = im.get('src', '')
            line_ref = im.get('lineRef', 0)
            r = view.full_line(view.text_point(max(0, line_ref - 1), 0))
            if not src or line_ref < 1 or not r:
                return

            view.run_command(
                'gs_patch_imports', {
                    'pos': r.end(),
                    'content': src,
                    'added_path': (decl.get('path') if decl.get('add') else '')
                })
Esempio n. 36
0
	def toggle_import(self, a):
		view, decl = a
		im, err = mg9.imports(
			view.file_name(),
			view.substr(sublime.Region(0, view.size())),
			[decl]
		)

		if err:
			gs.notice(DOMAIN, err)
		else:
			src = im.get('src', '')
			line_ref = im.get('lineRef', 0)
			r = view.full_line(view.text_point(max(0, line_ref-1), 0))
			if not src or line_ref < 1 or not r:
				return

			view.run_command('gs_patch_imports', {
				'pos': r.end(),
				'content': src,
				'added_path': (decl.get('path') if decl.get('add') else '')
			})
Esempio n. 37
0
def resolve_snippets(ctx):
	cl = set()
	types = [''] if ctx.get('local') else ctx.get('types')
	vars = {}
	for k,v in ctx.items():
		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)
Esempio n. 38
0
    def toggle_import(self, a):
        view, decl = a
        im, err = mg9.imports(
            view.file_name(), view.substr(sublime.Region(0, view.size())), [decl]
        )

        if err:
            gs.notice(DOMAIN, err)
        else:
            src = im.get("src", "")
            line_ref = im.get("lineRef", 0)
            r = view.full_line(view.text_point(max(0, line_ref - 1), 0))
            if not src or line_ref < 1 or not r:
                return

            view.run_command(
                "gs_patch_imports",
                {
                    "pos": r.end(),
                    "content": src,
                    "added_path": (decl.get("path") if decl.get("add") else ""),
                },
            )
Esempio n. 39
0
def do_comp_lint_callback(res, err):
    if err:
        gs.notice(DOMAIN, err)
    if "filename" not in res:
        gs.notice(DOMAIN, "comp_lint: missing filename")
        return

    filename = res["filename"]
    fileref = ref(filename, False)
    if not fileref:
        return

    reports = {}
    if res.get("top_level_error", None):
        gs.notice(DOMAIN, res["top_level_error"])
        reports[0] = Report(row=0, col=0, msg=res["top_level_error"])

    if "errors" in res:
        try:
            for rep in res.get("errors", []):
                if rep["file"] != filename:
                    continue
                row = int(rep["row"]) - 1
                col = int(rep["col"]) - 1
                if col < 0:
                    col = 0
                msg = rep["message"]
                if row in reports:
                    reports[row].msg = "%s\n%s" % (reports[row].msg, msg)
                    reports[row].col = max(reports[row].col, col)
                else:
                    reports[row] = Report(row=row, col=col, msg=msg)
        except:
            gs.notice(DOMAIN, gs.traceback())

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

    sublime.set_timeout(cb, 0)
Esempio n. 40
0
    def run(self, edit):
        view = self.view
        pt = gs.sel(view).begin()
        if view.substr(sublime.Region(pt - 1, pt)) == '(':
            depth = 1
        else:
            depth = 0
        c = ''
        while True:
            line = view.line(pt)
            scope = view.scope_name(pt)
            if 'string' in scope or 'comment' in scope:
                pt = view.extract_scope(pt).begin() - 1
                continue

            c = view.substr(sublime.Region(pt - 1, pt))
            if not c:
                pt = -1
                break

            if c.isalpha() and depth >= 0:
                while c.isalpha() or c == '.':
                    pt += 1
                    c = view.substr(sublime.Region(pt - 1, pt))

                # curly braces ftw
                break  # break outer while loop
            if c == ')':
                depth -= 1
            elif c == '(':
                depth += 1
                i = pt
                while True:
                    pc = view.substr(sublime.Region(i - 1, i))
                    if pc == '.' or pc.isalpha():
                        i -= 1
                    else:
                        break

                if i != pt:
                    pt = i
                    continue

            pt -= 1
            if pt <= line.begin():
                pt = -1
                break

        while not c.isalpha() and pt > 0:
            pt -= 1
            c = view.substr(sublime.Region(pt - 1, pt))

        if pt <= 0 or view.scope_name(pt).strip() == 'source.go':
            self.show_hint("// can't find selector")
            return

        line = view.line(pt)
        line_start = line.begin()

        s = view.substr(line)
        if not s:
            self.show_hint('// no source')
            return

        scopes = [
            'support.function.any-method.go',
            'meta.function-call.go',
            'support.function.builtin.go',
        ]
        found = False
        while True:
            scope = view.scope_name(pt).strip()
            for s in scopes:
                if scope.endswith(s):
                    found = True
                    break

            if found or pt <= line_start:
                break

            pt -= 1

        if not found:
            self.show_hint("// can't find function call")
            return

        s = view.substr(sublime.Region(line_start, pt))
        m = END_SELECTOR_PAT.match(s)
        if not m:
            self.show_hint("// can't match selector")
            return

        offset = (line_start + m.end())
        sel = m.group(1)
        name = m.group(2)
        candidates = []
        src = view.substr(sublime.Region(0, view.size()))
        fn = view.file_name()
        candidates, err = mg9.complete(fn, src, offset)
        if err:
            gs.notice(DOMAIN, err)
        else:
            c = {}
            for i in candidates:
                if i['name'] == name:
                    if c:
                        c = None
                        break
                    c = i

            if not c:
                self.show_hint('// no candidates found')
                return

            s = '// %s %s\n%s' % (c['name'], c['class'], c['type'])
            self.show_hint(s)
Esempio n. 41
0
 def run(self):
     try:
         self.f()
     except Exception:
         gs.notice(self.domain, gs.traceback())
Esempio n. 42
0
    def complete(self, fn, offset, src, func_name_only):
        comps = []
        autocomplete_tests = gs.setting('autocomplete_tests', False)
        autocomplete_closures = gs.setting('autocomplete_closures', False)
        ents, err = mg9.complete(fn, src, offset)
        if err:
            gs.notice(DOMAIN, err)

        name_fx = None
        name_fx_pat = gs.setting('autocomplete_filter_name')
        if name_fx_pat:
            try:
                name_fx = re.compile(name_fx_pat)
            except Exception as ex:
                gs.notice(DOMAIN, 'Cannot filter completions: %s' % ex)

        for ent in ents:
            if name_fx and name_fx.search(ent['name']):
                continue

            tn = ent['type']
            cn = ent['class']
            nm = ent['name']
            is_func = (cn == 'func')
            is_func_type = (cn == 'type' and tn.startswith('func('))

            if is_func:
                if nm in ('main', 'init'):
                    continue

                if not autocomplete_tests and nm.startswith(
                    ('Test', 'Benchmark', 'Example')):
                    continue

            if is_func or is_func_type:
                s_sfx = u'\u0282'
                t_sfx = gs.CLASS_PREFIXES.get('type', '')
                f_sfx = gs.CLASS_PREFIXES.get('func', '')
                params, ret = declex(tn)
                decl = []
                for i, p in enumerate(params):
                    n, t = p
                    if t.startswith('...'):
                        n = '...'
                    decl.append('${%d:%s}' % (i + 1, n))
                decl = ', '.join(decl)
                ret = ret.strip('() ')

                if is_func:
                    if func_name_only:
                        comps.append((
                            '%s\t%s %s' % (nm, ret, f_sfx),
                            nm,
                        ))
                    else:
                        comps.append((
                            '%s\t%s %s' % (nm, ret, f_sfx),
                            '%s(%s)' % (nm, decl),
                        ))
                else:
                    comps.append((
                        '%s\t%s %s' % (nm, tn, t_sfx),
                        nm,
                    ))

                    if autocomplete_closures:
                        comps.append((
                            '%s {}\tfunc() {...} %s' % (nm, s_sfx),
                            '%s {\n\t${0}\n}' % tn,
                        ))
            elif cn != 'PANIC':
                comps.append((
                    '%s\t%s %s' % (nm, tn, self.typeclass_prefix(cn, tn)),
                    nm,
                ))
        return comps
Esempio n. 43
0
def install(aso_tokens, force_install):
	if gs.attr(INSTALL_ATTR_NAME, '') != "":
		gs.notify(DOMAIN, 'Installation aborted. Install command already called for GoSublime %s.' % about.VERSION)
		return

	gs.set_attr(INSTALL_ATTR_NAME, 'busy')

	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 = gs.ustr(m_out)
		err = gs.ustr(err)
		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([about.MARGO_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' % (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)

	gs.set_attr(INSTALL_ATTR_NAME, 'done')

	e = gs.env()
	a = [
		'GoSublime init (%0.3fs)' % (time.time() - init_start),
	]
	sl = [('install margo', m_out)]
	sl.extend(sanity_check(e))
	a.extend(sanity_check_sl(sl))
	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')
		old_pat = re.compile(r'^gosublime.r\d{2}.\d{2}.\d{2}-\d+.margo.exe$')
		for fn in os.listdir(d):
			try:
				if fn != about.MARGO_EXE and (about.MARGO_EXE_PAT.match(fn) or old_pat.match(fn)):
					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()
Esempio n. 44
0
def install(aso_install_vesion, force_install):
    global INSTALL_EXE

    if gs.attr(_inst_name(), '') != "":
        gs.notify(
            DOMAIN,
            'Installation aborted. Install command already called for GoSublime %s.'
            % INSTALL_VERSION)
        return

    _init_go_version()
    INSTALL_EXE = INSTALL_EXE.replace('_%s.exe' % about.DEFAULT_GO_VERSION,
                                      '_%s.exe' % GO_VERSION)
    about.MARGO_EXE = INSTALL_EXE

    is_update = about.VERSION != INSTALL_VERSION

    gs.set_attr(_inst_name(), 'busy')

    init_start = time.time()

    if not is_update and not force_install and _bins_exist(
    ) and aso_install_vesion == INSTALL_VERSION:
        m_out = 'no'
    else:
        gs.notify('GoSublime', 'Installing MarGo')
        start = time.time()

        go_bin = _go_bin()
        if go_bin:
            cmd = [go_bin, 'build', '-o', _margo_bin(INSTALL_EXE)]
            cwd = _margo_src()
            ev.debug('%s.build' % DOMAIN, {
                'cmd': cmd,
                'cwd': cwd,
            })
            m_out, err, _ = _run(cmd, cwd=cwd)
        else:
            m_out = ''
            err = 'Cannot find the `go` exe'

        m_out = gs.ustr(m_out)
        err = gs.ustr(err)
        m_out, m_ok = _so(m_out, err, start, time.time())

        if m_ok:

            def f():
                gs.aso().set('install_version', INSTALL_VERSION)
                gs.save_aso()

            sublime.set_timeout(f, 0)

    if not is_update:
        gs.notify('GoSublime', 'Syncing environment variables')
        out, err, _ = gsshell.run([INSTALL_EXE, '-env'],
                                  cwd=gs.home_dir_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' % (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)

    gs.set_attr(_inst_name(), 'done')

    if is_update:
        gs.show_output(
            'GoSublime-source', '\n'.join([
                'GoSublime source has been updated.',
                'New version: `%s`, current version: `%s`' %
                (INSTALL_VERSION, about.VERSION),
                'Please restart Sublime Text to complete the update.',
            ]))
    else:
        e = gs.env()
        a = [
            'GoSublime init %s (%0.3fs)' %
            (INSTALL_VERSION, time.time() - init_start),
        ]
        sl = [('install margo', m_out)]
        sl.extend(sanity_check(e))
        a.extend(sanity_check_sl(sl))
        gs.println(*a)

        missing = [k for k in ('GOROOT', 'GOPATH') if not e.get(k)]
        if missing:
            missing_message = '\n'.join([
                'Missing required environment variables: %s' %
                ' '.join(missing),
                'See the `Quirks` section of USAGE.md for info',
            ])

            cb = lambda ok: gs.show_output(
                DOMAIN, missing_message, merge_domain=True, print_output=False)
            gs.error(DOMAIN, missing_message)
            gs.focus(gs.dist_path('USAGE.md'), focus_pat='^Quirks', cb=cb)

        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:
            bin_dirs = [
                gs.home_path('bin'),
                os.path.join(sublime.packages_path(), 'User', 'GoSublime', '9',
                             'bin'),
            ]

            l = []
            for d in bin_dirs:
                try:
                    for fn in os.listdir(d):
                        if fn != INSTALL_EXE and about.MARGO_EXE_PAT.match(fn):
                            l.append(os.path.join(d, fn))
                except Exception:
                    pass

            for fn in l:
                try:
                    gs.println("GoSublime: removing old binary: `%s'" % fn)
                    os.remove(fn)
                except Exception:
                    report_x()

        except Exception:
            report_x()
Esempio n. 45
0
 def dispatch(self, f, msg, set_status=False):
     try:
         self.q.put((f, msg, set_status))
     except Exception:
         gs.notice(self.domain, traceback())
Esempio n. 46
0
	def tip(self, edit):
		view = self.view
		pt = gs.sel(view).begin()
		if view.substr(sublime.Region(pt-1, pt)) == '(':
			depth = 1
		else:
			depth = 0
		c = ''
		while True:
			line = view.line(pt)
			scope = view.scope_name(pt)
			if 'string' in scope or 'comment' in scope:
				pt = view.extract_scope(pt).begin() - 1
				continue

			c = view.substr(sublime.Region(pt-1, pt))
			if not c:
				pt = -1
				break

			if c.isalpha() and depth >= 0:
				while c.isalpha() or c == '.':
					pt += 1
					c = view.substr(sublime.Region(pt-1, pt))

				# curly braces ftw
				break # break outer while loop
			if c == ')':
				depth -= 1
			elif c == '(':
				depth += 1
				i = pt
				while True:
					pc = view.substr(sublime.Region(i-1, i))
					if pc == '.' or pc.isalpha():
						i -= 1
					else:
						break

				if i != pt:
					pt = i
					continue

			pt -= 1
			if pt <= line.begin():
				pt = -1
				break

		while not c.isalpha() and pt > 0:
			pt -= 1
			c = view.substr(sublime.Region(pt-1, pt))

		if pt <= 0 or view.scope_name(pt).strip() == 'source.go':
			return ({}, "can't find selector")

		line = view.line(pt)
		line_start = line.begin()

		s = view.substr(line)
		if not s:
			return ({}, 'no source')

		scopes = [
			'support.function.any-method.go',
			'meta.function-call.go',
			'support.function.builtin.go',
		]
		found = False
		while True:
			scope = view.scope_name(pt).strip()
			for s in scopes:
				if scope.endswith(s):
					found = True
					break

			if found or pt <= line_start:
				break

			pt -= 1

		if not found:
			return ({}, "can't find function call")

		s = view.substr(sublime.Region(line_start, pt))
		m = END_SELECTOR_PAT.match(s)
		if not m:
			return ({}, "can't match selector")

		offset = (line_start + m.end())
		sel = m.group(1)
		name = m.group(2)
		candidates = []
		src = view.substr(sublime.Region(0, view.size()))
		fn = view.file_name()
		candidates, err = mg9.complete(fn, src, offset)
		if err:
			gs.notice(DOMAIN, err)
		else:
			c = {}
			for i in candidates:
				if i['name'] == name:
					if c:
						c = None
						break
					c = i

			if c:
				return (c, '')

			return ({}, 'no candidates found')
Esempio n. 47
0
def install(aso_install_vesion, force_install):
	if gs.attr(_inst_name(), '') != "":
		gs.notify(DOMAIN, 'Installation aborted. Install command already called for GoSublime %s.' % INSTALL_VERSION)
		return

	is_update = about.VERSION != INSTALL_VERSION

	gs.set_attr(_inst_name(), 'busy')

	init_start = time.time()

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

	if not is_update and not force_install and _bins_exist() and aso_install_vesion == INSTALL_VERSION:
		m_out = 'no'
	else:
		gs.notify('GoSublime', 'Installing MarGo')
		start = time.time()

		vars = ['%PATH%', '$PATH']
		out, err, _ = gsshell.run('echo %s' % os.pathsep.join(vars), shell=True, stderr=subprocess.PIPE, env=gs.env())
		if not err:
			pl = []
			for p in out.strip().split(os.pathsep):
				p = os.path.normcase(p)
				if p not in vars and p not in pl:
					pl.append(p)

			if pl:
				gs.environ9.update({'PATH': os.pathsep.join(pl)})

		go_exe = gs.which('go')
		if go_exe:
			cmd = [go_exe, 'build', '-o', _margo_bin(INSTALL_EXE)]
			cwd = _margo_src()
			ev.debug('%s.build' % DOMAIN, {
				'cmd': cmd,
				'cwd': cwd,
			})
			m_out, err, _ = _run(cmd, cwd=cwd)
		else:
			m_out = ''
			err = 'Cannot find the `go` exe'

		m_out = gs.ustr(m_out)
		err = gs.ustr(err)
		m_out, m_ok = _so(m_out, err, start, time.time())

		if m_ok:
			def f():
				gs.aso().set('install_version', INSTALL_VERSION)
				gs.save_aso()

			sublime.set_timeout(f, 0)

	if not is_update:
		gs.notify('GoSublime', 'Syncing environment variables')
		out, err, _ = gsshell.run([about.MARGO_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' % (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)

	gs.set_attr(_inst_name(), 'done')

	if is_update:
		gs.show_output('GoSublime-source', '\n'.join([
			'GoSublime source has been updated.',
			'New version: `%s`, current version: `%s`' % (INSTALL_VERSION, about.VERSION),
			'Please restart Sublime Text to complete the update.',
		]))
	else:
		e = gs.env()
		a = [
			'GoSublime init %s (%0.3fs)' % (INSTALL_VERSION, time.time() - init_start),
		]
		sl = [('install margo', m_out)]
		sl.extend(sanity_check(e))
		a.extend(sanity_check_sl(sl))
		gs.println(*a)

		missing = [k for k in ('GOROOT', 'GOPATH') if not e.get(k)]
		if missing:
			missing_message = '\n'.join([
				'Missing required environment variables: %s' % ' '.join(missing),
				'See the `Quirks` section of USAGE.md for info',
			])

			cb = lambda ok: gs.show_output(DOMAIN, missing_message, merge_domain=True, print_output=False)
			gs.error(DOMAIN, missing_message)
			gs.focus(gs.dist_path('USAGE.md'), focus_pat='^Quirks', cb=cb)

		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')
			old_pat = re.compile(r'^gosublime.r\d{2}.\d{2}.\d{2}-\d+.margo.exe$')
			for fn in os.listdir(d):
				try:
					if fn != about.MARGO_EXE and (about.MARGO_EXE_PAT.match(fn) or old_pat.match(fn)):
						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()
Esempio n. 48
0
	def complete(self, fn, offset, src, func_name_only):
		comps = []
		autocomplete_tests = gs.setting('autocomplete_tests', False)
		autocomplete_closures = gs.setting('autocomplete_closures', False)
		ents, err = mg9.complete(fn, src, offset)
		if err:
			gs.notice(DOMAIN, err)

		name_fx = None
		name_fx_pat = gs.setting('autocomplete_filter_name')
		if name_fx_pat:
			try:
				name_fx = re.compile(name_fx_pat)
			except Exception as ex:
				gs.notice(DOMAIN, 'Cannot filter completions: %s' % ex)

		for ent in ents:
			if name_fx and name_fx.search(ent['name']):
				continue

			tn = ent['type']
			cn = ent['class']
			nm = ent['name']
			is_func = (cn == 'func')
			is_func_type = (cn == 'type' and tn.startswith('func('))

			if is_func:
				if nm in ('main', 'init'):
					continue

				if not autocomplete_tests and nm.startswith(('Test', 'Benchmark', 'Example')):
					continue

			if is_func or is_func_type:
				s_sfx = u'\u0282'
				t_sfx = gs.CLASS_PREFIXES.get('type', '')
				f_sfx = gs.CLASS_PREFIXES.get('func', '')
				params, ret = declex(tn)
				decl = []
				for i, p in enumerate(params):
					n, t = p
					if t.startswith('...'):
						n = '...'
					decl.append('${%d:%s}' % (i+1, n))
				decl = ', '.join(decl)
				ret = ret.strip('() ')

				if is_func:
					if func_name_only:
						comps.append((
							'%s\t%s %s' % (nm, ret, f_sfx),
							nm,
						))
					else:
						comps.append((
							'%s\t%s %s' % (nm, ret, f_sfx),
							'%s(%s)' % (nm, decl),
						))
				else:
					comps.append((
						'%s\t%s %s' % (nm, tn, t_sfx),
						nm,
					))

					if autocomplete_closures:
						comps.append((
							'%s {}\tfunc() {...} %s' % (nm, s_sfx),
							'%s {\n\t${0}\n}' % tn,
						))
			elif cn != 'PANIC':
				comps.append((
					'%s\t%s %s' % (nm, tn, self.typeclass_prefix(cn, tn)),
					nm,
				))
		return comps
Esempio n. 49
0
def _send():
	while True:
		try:
			try:
				method, arg, cb = gs.mg9_send_q.get()

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

					if gs.attr(_inst_name(), '') != "busy":
						maybe_install()

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

					while gs.attr(_inst_name(), '') == "busy":
						time.sleep(0.100)

					mg_bin = _margo_bin()
					cmd = [
						mg_bin,
						'-oom', gs.setting('margo_oom', 0),
						'-poll', 30,
						'-tag', TAG,
					]

					if os.path.exists(mg_bin):
						proc, _, err = gsshell.proc(cmd, stderr=gs.LOGFILE ,env={
							'GOGC': 10,
							'XDG_CONFIG_HOME': gs.home_path(),
						})
					else:
						proc = None
						err = "Can't find the MarGo binary at `%s`" % mg_bin

					if err or not proc or proc.poll() is not None:
						killSrv()

						gs.notice(DOMAIN, 'Cannot start MarGo:\n%s' % err)
						try:
							cb({}, 'Abort. Cannot start MarGo')
						except:
							pass

						continue

					gs.set_attr(PROC_ATTR_NAME, proc)
					gsq.launch(DOMAIN, lambda: _read_stdout(proc))

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

				header, err = gs.json_encode(req.header())
				if err:
					_cb_err(cb, 'Failed to construct ipc header: %s' % err)
					continue

				body, err = gs.json_encode(arg)
				if err:
					_cb_err(cb, 'Failed to construct ipc body: %s' % err)
					continue

				ev.debug(DOMAIN, 'margo request: %s ' % header)

				ln = '%s %s\n' % (header, body)

				try:
					if gs.PY3K:
						proc.stdin.write(bytes(ln, 'UTF-8'))
					else:
						proc.stdin.write(ln)

				except Exception as ex:
					_cb_err(cb, 'Cannot talk to MarGo: %s' % err)
					killSrv()
					gs.println(gs.traceback())

			except Exception:
				killSrv()
				gs.println(gs.traceback())
		except Exception:
			gs.println(gs.traceback())
			break
Esempio n. 50
0
def install(aso_tokens, force_install):
	k = 'mg9.install.%s' % about.VERSION
	if gs.attr(k, False):
		gs.error(DOMAIN, 'Installation aborted. Install command already called for GoSublime %s.' % about.VERSION)
		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([about.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' % (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 != about.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()
Esempio n. 51
0
def _send():
    while True:
        try:
            try:
                method, arg, cb = gs.mg9_send_q.get()

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

                    if gs.attr(INSTALL_ATTR_NAME) != "busy":
                        maybe_install()

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

                    while gs.attr(INSTALL_ATTR_NAME) == "busy":
                        time.sleep(0.100)

                    proc, _, err = gsshell.proc(
                        [_margo_bin(), '-poll', 30, '-tag', TAG],
                        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)

                header, err = gs.json_encode(req.header())
                if err:
                    _cb_err('Failed to construct ipc header: ' % err)
                    continue

                body, err = gs.json_encode(arg)
                if err:
                    _cb_err(cb, 'Failed to construct ipc body: ' % err)
                    continue

                gs.debug(DOMAIN, 'margo request: %s ' % header)

                ln = '%s %s\n' % (header, body)

                if gs.PY3K:
                    proc.stdin.write(bytes(ln, 'UTF-8'))
                else:
                    proc.stdin.write(ln)
            except Exception:
                killSrv()
                gs.println(gs.traceback())
        except Exception:
            gs.println(gs.traceback())
            break
Esempio n. 52
0
def _send():
	while True:
		try:
			try:
				method, arg, cb = gs.mg9_send_q.get()

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

					if gs.attr(INSTALL_ATTR_NAME) != "busy":
						maybe_install()

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

					while gs.attr(INSTALL_ATTR_NAME) == "busy":
						time.sleep(0.100)

					proc, _, err = gsshell.proc([_margo_bin(), '-poll', 30, '-tag', TAG], 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)

				header, err = gs.json_encode(req.header())
				if err:
					_cb_err('Failed to construct ipc header: ' % err)
					continue

				body, err = gs.json_encode(arg)
				if err:
					_cb_err(cb, 'Failed to construct ipc body: ' % err)
					continue

				gs.debug(DOMAIN, 'margo request: %s ' % header)

				ln = '%s %s\n' % (header, body)

				if gs.PY3K:
					proc.stdin.write(bytes(ln, 'UTF-8'))
				else:
					proc.stdin.write(ln)
			except Exception:
				killSrv()
				gs.println(gs.traceback())
		except Exception:
			gs.println(gs.traceback())
			break