Пример #1
0
def sanity_check(env={}, error_log=False):
	if not env:
		env = gs.env()

	ns = '(not set)'

	sl = [
		('install state', gs.attr(_inst_name(), '')),
		('sublime.version', sublime.version()),
		('sublime.channel', sublime.channel()),
		('about.ann', gs.attr('about.ann', '')),
		('about.version', gs.attr('about.version', '')),
		('version', about.VERSION),
		('platform', about.PLATFORM),
		('~bin', '%s' % gs.home_path('bin')),
		('margo.exe', '%s (%s)' % _tp(_margo_bin())),
		('go.exe', '%s (%s)' % _tp(gs.which('go') or 'go')),
		('GOROOT', '%s' % env.get('GOROOT', ns)),
		('GOPATH', '%s' % env.get('GOPATH', ns)),
		('GOBIN', '%s (should usually be `%s`)' % (env.get('GOBIN', ns), ns)),
	]

	if error_log:
		try:
			with open(gs.home_path('log.txt'), 'r') as f:
				s = f.read().strip()
				sl.append(('error log', s))
		except Exception:
			pass

	return sl
Пример #2
0
def sanity_check(env={}, error_log=False):
    if not env:
        env = gs.env()

    ns = "(not set)"

    sl = [
        ("install state", gs.attr(_inst_name(), "")),
        ("sublime.version", sublime.version()),
        ("sublime.channel", sublime.channel()),
        ("about.ann", gs.attr("about.ann", "")),
        ("about.version", gs.attr("about.version", "")),
        ("version", about.VERSION),
        ("platform", about.PLATFORM),
        ("~bin", "%s" % gs.home_path("bin")),
        ("margo.exe", "%s (%s)" % _tp(_margo_bin())),
        ("go.exe", "%s (%s)" % _tp(gs.which("go") or "go")),
        ("GOROOT", "%s" % env.get("GOROOT", ns)),
        ("GOPATH", "%s" % env.get("GOPATH", ns)),
        ("GOBIN", "%s (should usually be `%s`)" % (env.get("GOBIN", ns), ns)),
    ]

    if error_log:
        try:
            with open(gs.home_path("log.txt"), "r") as f:
                s = f.read().strip()
                sl.append(("error log", s))
        except Exception:
            pass

    return sl
Пример #3
0
def cmd_9(view, edit, args, wd, rkey):
    if len(args) == 0 or args[0] not in ('run', 'replay', 'build'):
        push_output(view, rkey, ('9: invalid args %s' % args))
        return

    subcmd = args[0]
    cid = ''
    if subcmd == 'replay':
        cid = '9replay-%s' % wd
    cid, cb = _9_begin_call(subcmd, view, edit, args, wd, rkey, cid)

    a = {
        'cid': cid,
        'env': gs.env(),
        'dir': wd,
        'args': args[1:],
        'build_only': (subcmd == 'build'),
    }

    win = view.window()
    if win is not None:
        av = win.active_view()
        if av is not None:
            fn = av.file_name()
            if fn:
                _save_all(win, wd)
            else:
                if gs.is_go_source_view(av, False):
                    a['fn'] = gs.view_fn(av)
                    a['src'] = av.substr(sublime.Region(0, av.size()))

    sublime.set_timeout(lambda: mg9.acall('play', a, cb), 0)
Пример #4
0
def cmd_9(view, edit, args, wd, rkey):
	if len(args) == 0 or args[0] not in ('run', 'replay', 'build'):
		push_output(view, rkey, ('9: invalid args %s' % args))
		return

	subcmd = args[0]
	cid = ''
	if subcmd == 'replay':
		cid = '9replay-%s' % wd
	cid, cb = _9_begin_call(subcmd, view, edit, args, wd, rkey, cid)

	a = {
		'cid': cid,
		'env': gs.env(),
		'dir': wd,
		'args': args[1:],
		'build_only': (subcmd == 'build'),
	}

	win = view.window()
	if win is not None:
		av = win.active_view()
		if av is not None:
			fn = av.file_name()
			if fn:
				_save_all(win, wd)
			else:
				if gs.is_go_source_view(av, False):
					a['src'] = av.substr(sublime.Region(0, av.size()))

	sublime.set_timeout(lambda: mg9.acall('play', a, cb), 0)
Пример #5
0
def declarations(fn, src, pkg_dir, f):
    tid = gs.begin(DOMAIN, "Fetching declarations")

    def cb(res, err):
        gs.end(tid)
        f(res, err)

    return acall("declarations", {"fn": fn or "", "src": src, "env": gs.env(), "pkgDir": pkg_dir}, cb)
Пример #6
0
def pkg_dirs(f):
    tid = gs.begin(DOMAIN, "Fetching pkg dirs")

    def cb(res, err):
        gs.end(tid)
        f(res, err)

    acall("pkg_dirs", {"env": gs.env()}, cb)
Пример #7
0
def import_paths(fn, src, f):
    tid = gs.begin(DOMAIN, "Fetching import paths")

    def cb(res, err):
        gs.end(tid)
        f(res, err)

    acall("import_paths", {"fn": fn or "", "src": src or "", "env": gs.env()}, cb)
Пример #8
0
def pkg_dirs(f):
	tid = gs.begin(DOMAIN, 'Fetching pkg dirs')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	acall('pkg_dirs', {
		'env': gs.env(),
	}, cb)
Пример #9
0
def import_paths(fn, src, f):
	tid = gs.begin(DOMAIN, 'Fetching import paths')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	acall('import_paths', {
		'fn': fn or '',
		'src': src or '',
		'env': gs.env(),
	}, cb)
Пример #10
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)
Пример #11
0
def declarations(fn, src, pkg_dir, f):
	tid = gs.begin(DOMAIN, 'Fetching declarations')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	return acall('declarations', {
		'fn': fn or '',
		'src': src,
		'env': gs.env(),
		'pkgDir': pkg_dir,
	}, cb)
Пример #12
0
def _complete_opts(fn, src, pos):
    home = gs.home_path()
    builtins = gs.setting("autocomplete_builtins") is True or gs.setting("complete_builtins") is True
    return {
        "Dir": gs.basedir_or_cwd(fn),
        "Builtins": builtins,
        "Fn": fn or "",
        "Src": src or "",
        "Pos": pos or 0,
        "Home": home,
        "Env": gs.env({"XDG_CONFIG_HOME": home}),
    }
Пример #13
0
def doc(fn, src, offset, f):
	tid = gs.begin(DOMAIN, 'Fetching doc info')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	acall('doc', {
		'fn': fn or '',
		'src': src or '',
		'offset': offset or 0,
		'env': gs.env(),
		'tabIndent': gs.setting('fmt_tab_indent'),
		'tabWidth': gs.setting('fmt_tab_width'),
	}, cb)
Пример #14
0
def cmd_go(view, edit, args, wd, rkey):
    _save_all(view.window(), wd)

    cid, cb = _9_begin_call('go', view, edit, args, wd, rkey, '9go-%s' % wd)
    a = {
        'cid': cid,
        'env': gs.env(),
        'cwd': wd,
        'cmd': {
            'name': 'go',
            'args': args,
        }
    }
    sublime.set_timeout(lambda: mg9.acall('sh', a, cb), 0)
Пример #15
0
def _complete_opts(fn, src, pos):
	home = gs.home_path()
	builtins = (gs.setting('autocomplete_builtins') is True or gs.setting('complete_builtins') is True)
	return {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': home,
		'Env': gs.env({
			'XDG_CONFIG_HOME': home,
		}),
	}
Пример #16
0
def cmd_go(view, edit, args, wd, rkey):
	_save_all(view.window(), wd)

	cid, cb = _9_begin_call('go', view, edit, args, wd, rkey, '9go-%s' % wd)
	a = {
		'cid': cid,
		'env': gs.env(),
		'cwd': wd,
		'cmd': {
			'name': 'go',
			'args': args,
		}
	}
	sublime.set_timeout(lambda: mg9.acall('sh', a, cb), 0)
Пример #17
0
def sanity_check(env={}):
	if not env:
		env = gs.env()

	ns = '(not set)'

	return [
		('version', about.VERSION),
		('~bin', '%s' % gs.home_path('bin')),
		('MarGo', '%s (%s)' % _tp(_margo_bin())),
		('GOROOT', '%s' % env.get('GOROOT', ns)),
		('GOPATH', '%s' % env.get('GOPATH', ns)),
		('GOBIN', '%s (should usually be `%s`)' % (env.get('GOBIN', ns), ns)),
	]
Пример #18
0
def sanity_check(env={}):
    if not env:
        env = gs.env()

    ns = '(not set)'

    return [
        ('version', about.VERSION),
        ('platform', about.PLATFORM),
        ('~bin', '%s' % gs.home_path('bin')),
        ('MarGo', '%s (%s)' % _tp(_margo_bin())),
        ('GOROOT', '%s' % env.get('GOROOT', ns)),
        ('GOPATH', '%s' % env.get('GOPATH', ns)),
        ('GOBIN', '%s (should usually be `%s`)' % (env.get('GOBIN', ns), ns)),
    ]
Пример #19
0
def _init_shell_path():
    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)})
Пример #20
0
def _init_go_version():
	global GO_VERSION

	if GO_VERSION and GO_VERSION != about.DEFAULT_GO_VERSION:
		return

	tid = gs.begin(DOMAIN, 'Finding go version')

	bin = _go_bin()
	if bin:
		out, _, _ = gsshell.run(['go', 'version'], stderr=subprocess.STDOUT, env=gs.env())
		m = about.GO_VERSION_OUTPUT_PAT.search(out)
		if m:
			GO_VERSION = '-'.join(s for s in m.groups() if s)

	gs.end(tid)
Пример #21
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)
Пример #22
0
def complete(fn, src, pos):
	home = gs.home_path()
	builtins = (gs.setting('autocomplete_builtins') is True or gs.setting('complete_builtins') is True)
	res, err = bcall('gocode_complete', {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': home,
		'Env': gs.env({
			'XDG_CONFIG_HOME': home,
		}),
	})

	res = gs.dval(res.get('completions'), [])
	return res, err
Пример #23
0
def complete(fn, src, pos):
	home = gs.home_path()
	builtins = (gs.setting('autocomplete_builtins') is True or gs.setting('complete_builtins') is True)
	res, err = bcall('gocode_complete', {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': home,
		'Env': gs.env({
			'XDG_CONFIG_HOME': home,
		}),
	})

	res = gs.dval(res.get('completions'), [])
	return res, err
Пример #24
0
def _init_go_version():
    global GO_VERSION

    if GO_VERSION and GO_VERSION != about.DEFAULT_GO_VERSION:
        return

    tid = gs.begin(DOMAIN, 'Finding go version')

    bin = _go_bin()
    if bin:
        out, _, _ = gsshell.run(['go', 'version'],
                                stderr=subprocess.STDOUT,
                                env=gs.env())
        m = about.GO_VERSION_OUTPUT_PAT.search(out)
        if m:
            GO_VERSION = '-'.join(s for s in m.groups() if s)

    gs.end(tid)
Пример #25
0
def cmd_cd(view, edit, args, wd, rkey):
	try:
		if args:
			wd = args[0]
			wd = string.Template(wd).safe_substitute(gs.env())
			wd = os.path.expanduser(wd)
			wd = os.path.abspath(wd)
		else:
			fn = view.window().active_view().file_name()
			if fn:
				wd = os.path.dirname(fn)

		os.chdir(wd)
	except Exception as ex:
		push_output(view, rkey, 'Cannot chdir: %s' % ex)
		return

	push_output(view, rkey, '')
	view.run_command('gs9o_init', {'wd': wd})
Пример #26
0
def cmd_cd(view, edit, args, wd, rkey):
    try:
        if args:
            wd = args[0]
            wd = string.Template(wd).safe_substitute(gs.env())
            wd = os.path.expanduser(wd)
            wd = os.path.abspath(wd)
        else:
            fn = view.window().active_view().file_name()
            if fn:
                wd = os.path.dirname(fn)

        os.chdir(wd)
    except Exception as ex:
        push_output(view, rkey, 'Cannot chdir: %s' % ex)
        return

    push_output(view, rkey, '')
    view.run_command('gs9o_init', {'wd': wd})
Пример #27
0
def doc(fn, src, offset, f):
    tid = gs.begin(DOMAIN, "Fetching doc info")

    def cb(res, err):
        gs.end(tid)
        f(res, err)

    acall(
        "doc",
        {
            "fn": fn or "",
            "src": src or "",
            "offset": offset or 0,
            "env": gs.env(),
            "tabIndent": gs.setting("fmt_tab_indent"),
            "tabWidth": gs.setting("fmt_tab_width"),
        },
        cb,
    )
Пример #28
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()
Пример #29
0
def _init_shell_path():
	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)})
Пример #30
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()
Пример #31
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()
Пример #32
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()
Пример #33
0
def cmd_env(view, edit, args, wd, rkey):
    _env_settings(gs.env(), view, edit, args, wd, rkey)
Пример #34
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()
Пример #35
0
def cmd_env(view, edit, args, wd, rkey):
	_env_settings(gs.env(), view, edit, args, wd, rkey)
Пример #36
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()
            gs.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()