def run(self, edit):
        view = self.view
        pos = gs.sel(view).begin()
        line = view.line(pos)
        wd = view.settings().get('9o.wd')

        ln = view.substr(line).split('#', 1)
        if len(ln) == 2:
            cmd = ln[1].strip()
            if cmd:
                vs = view.settings()
                lc_key = '%s.last_command' % DOMAIN
                if cmd.startswith('#'):
                    rep = vs.get(lc_key, '')
                    if rep:
                        view.replace(edit, line,
                                     ('%s# %s %s' %
                                      (ln[0], rep, cmd.lstrip('# \t'))))
                    return
                elif cmd == '!!':
                    cmd = vs.get(lc_key, '')
                else:
                    vs.set(lc_key, cmd)

            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')

            cli = cmd.split(' ', 1)

            # todo: move this into margo
            if cli[0] == 'sh':

                def on_done(c):
                    out = gs.ustr('\n'.join(c.consume_outq()))
                    sublime.set_timeout(lambda: push_output(view, rkey, out),
                                        0)

                c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
                c.on_done = on_done
                c.start()
                return

            f = globals().get('cmd_%s' % cli[0])
            if f:
                args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
                f(view, edit, args, wd, rkey)
            else:
                push_output(view, rkey, 'Invalid command %s' % cli)
        else:
            view.insert(edit, gs.sel(view).begin(), '\n')
Beispiel #2
0
	def run(self, edit):
		view = self.view
		pos = gs.sel(view).begin()
		line = view.line(pos)
		wd = view.settings().get('9o.wd')

		ln = view.substr(line).split('#', 1)
		if len(ln) == 2:
			cmd = ln[1].strip()
			if cmd:
				vs = view.settings()
				lc_key = '%s.last_command' % DOMAIN
				if cmd.startswith('#'):
					rep = vs.get(lc_key, '')
					if rep:
						view.replace(edit, line, ('%s# %s %s' % (ln[0], rep, cmd.lstrip('# \t'))))
					return
				elif cmd == '!!':
					cmd = vs.get(lc_key, '')
				else:
					vs.set(lc_key, cmd)

			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')

			cli = cmd.split(' ', 1)

			# todo: move this into margo
			if cli[0] == 'sh':
				def on_done(c):
					out = gs.ustr('\n'.join(c.consume_outq()))
					sublime.set_timeout(lambda: push_output(view, rkey, out), 0)

				c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
				c.on_done = on_done
				c.start()
				return

			f = globals().get('cmd_%s' % cli[0])
			if f:
				args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
				f(view, edit, args, wd, rkey)
			else:
				push_output(view, rkey, 'Invalid command %s' % cli)
		else:
			view.insert(edit, gs.sel(view).begin(), '\n')
Beispiel #3
0
	def run(self, edit):
		v = self.view
		pos = v.sel()[0].begin()
		line = v.line(pos)
		wd = v.settings().get('gscommander.wd')

		ln = v.substr(line).split('#', 1)
		if len(ln) == 2:
			cmd = ln[1].strip()
			vs = v.settings()
			lc_key = '%s.last_command' % DOMAIN
			if cmd[0] == '#':
				rep = vs.get(lc_key, '')
				if rep:
					v.replace(edit, line, ('%s# %s %s' % (ln[0], rep, cmd[1:])))
				return
			elif cmd == '!!':
				cmd = vs.get(lc_key, '')
			else:
				vs.set(lc_key, cmd)

			if not cmd:
				v.run_command('gs_commander_init')
				return

			cli = cmd.split(' ', 1)
			f = globals().get('cmd_%s' % cli[0])
			if f:
				args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
				f(v, edit, args, wd, line)
				return

			v.replace(edit, line, ('[ %s ]' % cmd))
			c = gsshell.ViewCommand(cmd=cmd, shell=True, view=v, cwd=wd)

			def on_output_done(c):
				def cb():
					win = sublime.active_window()
					if win is not None:
						win.run_command("gs_commander_open")
				sublime.set_timeout(cb, 0)

			oo = c.on_output
			def on_output(c, ln):
				oo(c, '\t'+ln)

			c.on_output = on_output
			c.output_done.append(on_output_done)
			c.start()
		else:
			v.insert(edit, v.sel()[0].begin(), '\n')
Beispiel #4
0
def proc(cmd, shell=False, env={}, cwd=None, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0):
	env = gs.env(env)
	shell, cmd = fix_shell_cmd(shell, cmd)

	if input is not None:
		input = gs.astr(input)

	if cwd:
		try:
			os.makedirs(cwd)
		except Exception:
			pass
	else:
		# an empty string isn't a valid value so just always set it None
		cwd = None

	try:
		setsid = os.setsid
	except Exception:
		setsid = None

	opts = {
		'cmd': cmd,
		'shell': shell,
		'env': env,
		'input': input,
	}

	p = None
	err = ''
	try:
		p = subprocess.Popen(
			cmd,
			stdout=stdout,
			stderr=stderr,
			stdin=stdin,
			startupinfo=gs.STARTUP_INFO,
			shell=shell,
			env=env,
			cwd=cwd,
			preexec_fn=setsid,
			bufsize=bufsize
		)
	except Exception:
		err = 'Error running command %s: %s' % (cmd, gs.traceback())

	return (p, opts, err)
Beispiel #5
0
def proc(cmd, shell=False, env={}, cwd=None, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0):
	env = gs.env(env)
	shell, cmd = fix_shell_cmd(shell, cmd)

	if input is not None:
		input = gs.astr(input)

	if cwd:
		try:
			os.makedirs(cwd)
		except Exception:
			pass
	else:
		# an empty string isn't a valid value so just always set it None
		cwd = None

	try:
		setsid = os.setsid
	except Exception:
		setsid = None

	opts = {
		'cmd': cmd,
		'shell': shell,
		'env': env,
		'input': input,
	}

	p = None
	err = ''
	try:
		p = subprocess.Popen(
			cmd,
			stdout=stdout,
			stderr=stderr,
			stdin=stdin,
			startupinfo=gs.STARTUP_INFO,
			shell=shell,
			env=env,
			cwd=cwd,
			preexec_fn=setsid,
			bufsize=bufsize
		)
	except Exception:
		err = 'Error running command %s: %s' % (cmd, gs.traceback())

	return (p, opts, err)
Beispiel #6
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])
Beispiel #7
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])
Beispiel #8
0
def run(cmd=[], shell=False, env={}, cwd=None, input=None):
	out = u""
	err = u""
	exc = None

	try:
		env = fix_env(env)
		shell, cmd = fix_shell_cmd(shell, cmd)
		p = gs.popen(cmd, shell=shell, stderr=subprocess.STDOUT, environ=env, cwd=cwd)
		if input is not None:
			input = gs.astr(input)
		out, _ = p.communicate(input=input)
		out = gs.ustr(out) if out else u''
	except Exception as ex:
		err = u'Error while running %s: %s' % (cmd, gs.traceback())
		exc = ex

	return (out, err, exc)
Beispiel #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)
		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])
def run(cmd=[], shell=False, env={}, cwd=None, input=None):
	out = u""
	err = u""
	exc = None

	try:
		env = fix_env(env)
		shell, cmd = fix_shell_cmd(shell, cmd)
		p = gs.popen(cmd, shell=shell, stderr=subprocess.STDOUT, environ=env, cwd=cwd)
		if input is not None:
			input = gs.astr(input)
		out, _ = p.communicate(input=input)
		out = gs.ustr(out) if out else u''
	except Exception as ex:
		err = u'Error while running %s: %s' % (cmd, gs.traceback())
		exc = ex

	return (out, err, exc)
Beispiel #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])
Beispiel #12
0
    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')

        ln = view.substr(line).split('#', 1)
        if len(ln) == 2:
            cmd = ln[1].strip()
            if cmd:
                vs = view.settings()
                aso = gs.aso()
                hkey = '9o.hist.%s' % 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')

            cli = cmd.split(' ', 1)

            # todo: move this into margo
            if cli[0] == 'sh':

                def on_done(c):
                    out = gs.ustr('\n'.join(c.consume_outq()))
                    sublime.set_timeout(lambda: push_output(view, rkey, out),
                                        0)

                c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
                c.on_done = on_done
                c.start()
                return

            f = globals().get('cmd_%s' % cli[0])
            if f:
                args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
                f(view, edit, args, wd, rkey)
            else:
                push_output(view, rkey, 'Invalid command %s' % cli)
        else:
            view.insert(edit, gs.sel(view).begin(), '\n')
Beispiel #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*(.*)',
			})
Beispiel #14
0
	def run(self, edit):
		view = self.view
		pos = gs.sel(view).begin()
		line = view.line(pos)
		wd = view.settings().get('9o.wd')

		ln = view.substr(line).split('#', 1)
		if len(ln) == 2:
			cmd = ln[1].strip()
			if cmd:
				vs = view.settings()
				aso = gs.aso()
				hkey = '9o.hist.%s' % wd
				hist = gs.dval(aso.get(hkey), [])

				m = HIST_EXPAND_PAT.match(cmd)
				if m:
					pfx = m.group(1)
					idx = int(m.group(2))-1
					cmd = hist[-idx] if idx < len(hist) else ''
					if pfx == '^' or not cmd:
						view.replace(edit, line, ('%s# %s' % (ln[0], cmd)))
						return
				else:
					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')

			cli = cmd.split(' ', 1)

			# todo: move this into margo
			if cli[0] == 'sh':
				def on_done(c):
					out = gs.ustr('\n'.join(c.consume_outq()))
					sublime.set_timeout(lambda: push_output(view, rkey, out), 0)

				c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
				c.on_done = on_done
				c.start()
				return

			f = globals().get('cmd_%s' % cli[0])
			if f:
				args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
				f(view, edit, args, wd, rkey)
			else:
				push_output(view, rkey, 'Invalid command %s' % cli)
		else:
			view.insert(edit, gs.sel(view).begin(), '\n')
Beispiel #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*(.*)',
                })
Beispiel #16
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*(.*)",
                },
            )