예제 #1
0
	def on_change(self, s):
		if self.panel:
			size = self.view.size()
			if s.endswith('\t'):
				basedir = gs.basedir_or_cwd(self.view.file_name())
				lc = 'go '
				hist = self.settings.get('cmd_hist')
				if gs.is_a(hist, {}):
					hist = hist.get(basedir)
					if hist and gs.is_a(hist, []):
						lc = hist[-1]
				s = s.strip()
				if s and s not in ('', 'go'):
					l = []
					for i in self.subcommands:
						if i.startswith(s):
							l.append(i)
					if len(l) == 1:
						s = '%s ' % l[0]
				elif lc:
					s = '%s ' % lc
				edit = self.panel.begin_edit()
				try:
					self.panel.replace(edit, sublime.Region(0, self.panel.size()), s)
				finally:
					self.panel.end_edit(edit)
예제 #2
0
 def on_change(self, s):
     if self.panel:
         size = self.view.size()
         if s.endswith('\t'):
             basedir = gs.basedir_or_cwd(self.view.file_name())
             lc = 'go '
             hist = self.settings.get('cmd_hist')
             if gs.is_a(hist, {}):
                 hist = hist.get(basedir)
                 if hist and gs.is_a(hist, []):
                     lc = hist[-1]
             s = s.strip()
             if s and s not in ('', 'go'):
                 l = []
                 for i in self.subcommands:
                     if i.startswith(s):
                         l.append(i)
                 if len(l) == 1:
                     s = '%s ' % l[0]
             elif lc:
                 s = '%s ' % lc
             edit = self.panel.begin_edit()
             try:
                 self.panel.replace(edit,
                                    sublime.Region(0, self.panel.size()), s)
             finally:
                 self.panel.end_edit(edit)
예제 #3
0
파일: mg9.py 프로젝트: muchenshou/GoSublime
def do(method, arg, shell=False):
	maybe_install()

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

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

	return res
예제 #4
0
def bcall(method, arg, shell=False):
    maybe_install()

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

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

    return res
예제 #5
0
def expand_jdata(v):
	if gs.is_a(v, {}):
		for k in v:
			v[k] = expand_jdata(v[k])
	elif gs.is_a_string(v) and v.startswith('base64:'):
		try:
			v = base64.b64decode(v[7:])
		except Exception:
			v = ''
			gs.error_traceback(DOMAIN)
	return v
예제 #6
0
def expand_jdata(v):
    if gs.is_a(v, {}):
        for k in v:
            v[k] = expand_jdata(v[k])
    elif gs.is_a_string(v) and v.startswith('base64:'):
        try:
            v = base64.b64decode(v[7:])
        except Exception:
            v = ''
            gs.error_traceback(DOMAIN)
    return v
예제 #7
0
def do_sync_active_view(view):
	fn = view.file_name()
	if fn:
		gs.set_attr('last_active_fn', fn)
		if fn.lower().endswith('.go'):
			gs.set_attr('last_active_go_fn', fn)

	if gs.is_pkg_view(view):
		m = {}
		psettings = view.settings().get('GoSublime')
		if psettings and gs.is_a(psettings, {}):
			m = gs.mirror_settings(psettings)
		gs.set_attr('last_active_project_settings', gs.dval(m, {}))
예제 #8
0
def do_sync_active_view(view):
	fn = view.file_name()
	if fn:
		gs.set_attr('last_active_fn', fn)
		if fn.lower().endswith('.go'):
			gs.set_attr('last_active_go_fn', fn)

	if gs.is_pkg_view(view):
		m = {}
		psettings = view.settings().get('GoSublime')
		if psettings and gs.is_a(psettings, {}):
			m = gs.mirror_settings(psettings)
		gs.set_attr('last_active_project_settings', gs.dval(m, {}))
예제 #9
0
def fix_shell_cmd(shell, cmd):
	if not gs.is_a(cmd, []):
		cmd = [cmd]

	if shell:
		sh = gs.setting('shell')
		cmd_str = ' '.join(cmd)
		if sh:
			shell = False
			cmd = []
			for v in sh:
				if v:
					cmd.append(str(v).replace('$CMD', cmd_str))
		else:
			cmd = [cmd_str]

	return (shell, [gs.astr(v) for v in cmd])
예제 #10
0
def fix_shell_cmd(shell, cmd):
    if not gs.is_a(cmd, []):
        cmd = [cmd]

    if shell:
        sh = gs.setting('shell')
        cmd_str = ' '.join(cmd)
        if sh:
            shell = False
            cmd = []
            for v in sh:
                if v:
                    cmd.append(str(v).replace('$CMD', cmd_str))
        else:
            cmd = [cmd_str]

    return (shell, [gs.astr(v) for v in cmd])
예제 #11
0
def fix_shell_cmd(shell, cmd):
	if not gs.is_a(cmd, []):
		cmd = [cmd]

	if shell:
		sh = gs.setting('shell')
		cmd_str = ' '.join(cmd)
		cmd_map = {'CMD': cmd_str}
		if sh:
			shell = False
			cmd = []
			for v in sh:
				if v:
					cmd.append(string.Template(v).safe_substitute(cmd_map))
		else:
			cmd = [cmd_str]

	return (shell, [gs.astr(v) for v in cmd])
예제 #12
0
def fix_shell_cmd(shell, cmd):
	if not gs.is_a(cmd, []):
		cmd = [cmd]

	if shell:
		sh = gs.setting('shell')
		cmd_str = ' '.join(cmd)
		cmd_map = {'CMD': cmd_str}
		if sh:
			shell = False
			cmd = []
			for v in sh:
				if v:
					cmd.append(string.Template(v).safe_substitute(cmd_map))
		else:
			cmd = [cmd_str]

	return (shell, [gs.astr(v) for v in cmd])
예제 #13
0
		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*(.*)',
			})
예제 #14
0
        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*(.*)',
                })
예제 #15
0
        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*(.*)",
                },
            )