def extract_path(cmd, delim=':'):
"""Return the user's PATH as a colon-delimited list."""
from . import persist
persist.debug('user shell:', cmd[0])
out = run_shell_cmd(cmd).decode()
path = out.split('__SUBL_PATH__', 2)
if len(path) > 1:
path = path[1]
return ':'.join(path.strip().split(delim))
else:
persist.printf('Could not parse shell PATH output:\n' + (out if out else '<empty>'))
sublime.error_message(
'SublimeLinter could not determine your shell PATH. '
'It is unlikely that any linters will work. '
'\n\n'
'Please see the troubleshooting guide for info on how to debug PATH problems.')
return ''
python类error_message()的实例源码
def run_terminal(self, dir_, parameters):
try:
if not dir_:
raise NotFoundError('The file open in the selected view has ' +
'not yet been saved')
for k, v in enumerate(parameters):
parameters[k] = v.replace('%CWD%', dir_)
args = [TerminalSelector.get()]
args.extend(parameters)
encoding = locale.getpreferredencoding(do_setlocale=True)
if sys.version_info >= (3,):
cwd = dir_
else:
cwd = dir_.encode(encoding)
subprocess.Popen(args, cwd=cwd)
except (OSError) as exception:
print(str(exception))
sublime.error_message('Terminal: The terminal ' +
TerminalSelector.get() + ' was not found')
except (Exception) as exception:
sublime.error_message('Terminal: ' + str(exception))
def start_server(project):
if not tern_command: return None
if time.time() - project.last_failed < 30: return None
env = None
if platform.system() == "Darwin":
env = os.environ.copy()
env["PATH"] += ":/usr/local/bin"
proc = subprocess.Popen(tern_command + tern_arguments, cwd=project.dir, env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=windows)
output = ""
while True:
line = proc.stdout.readline().decode("utf-8")
if not line:
sublime.error_message("Failed to start server" + (output and ":\n" + output))
project.last_failed = time.time()
return None
match = re.match("Listening on port (\\d+)", line)
if match:
project.proc = proc
return int(match.group(1))
else:
output += line
def run(self, edit, **args):
data = run_command(self.view, {"type": "definition", "lineCharPositions": True})
if data is None: return
file = data.get("file", None)
if file is not None:
# Found an actual definition
row, col = self.view.rowcol(self.view.sel()[0].b)
cur_pos = self.view.file_name() + ":" + str(row + 1) + ":" + str(col + 1)
jump_stack.append(cur_pos)
if len(jump_stack) > 50: jump_stack.pop(0)
real_file = (os.path.join(get_pfile(self.view).project.dir, file) +
":" + str(data["start"]["line"] + 1) + ":" + str(data["start"]["ch"] + 1))
sublime.active_window().open_file(real_file, sublime.ENCODED_POSITION)
else:
url = data.get("url", None)
if url is None:
sublime.error_message("Could not find a definition")
else:
webbrowser.open(url)
def compile_deps(path, config):
files, root = deps.get(path)
config['root'] = root
config['file'] = path
autoload_frameworks(config)
struct = config["output"]["structure"]
if not struct or struct == "nested":
return compile.nested(files, config)
elif type(struct) is list and len(struct) is 2 and struct[0] == "nested":
return compile.nested(files, config, struct[1])
elif struct == "flat":
return compile.flat(files, config)
else:
sublime.error_message(u"Unknown output structure: {0}".format(struct))
return
def _compile(files, config, outfile_for):
flags = to_flags(config['compile'])
compiled = []
for f in files:
in_file = os.path.join(config['root'], f)
out_file = outfile_for(f)
# Make sure output folder exists
mkdir_p(os.path.dirname(out_file))
command = [sass.path] + flags + [in_file, out_file]
p = Popen(command, stdout=PIPE, stderr=PIPE, **_platform_opts)
out, err = p.communicate()
if err:
print(u"Error: {0}".format(err))
print(u"Command: {0}".format(" ".join(command)))
sublime.error_message(u"Failed to compile {0}\n\nView error with Ctrl+`".format(f))
return
compiled.append(f)
return compiled
def guess_root(file):
'''
For projects without .libsass.json configs, search for the most distant
parent directory that still has a .sass or .scss file
'''
def is_sass(file):
ext = os.path.splitext(file)[1]
return ext in ['.sass', '.scss']
for i, path in enumerate(subpaths(file)):
(_, _, files) = next(os.walk(path))
if not any([is_sass(f) for f in files]):
break
if not is_sass(file):
sublime.error_message("Please save the file")
assert is_sass(file)
assert i > 0
return subpaths(file)[i-1]
def _run(self, thread, count=0):
"""Evaluate environment in a separate thread and show an activity
indicator. Inspect thread at regular intervals until it's finished, at
which point `make_requests` can be invoked. Return if thread times out.
"""
REFRESH_MULTIPLIER = 2
activity = self.get_activity_indicator(count//REFRESH_MULTIPLIER, self.ACTIVITY_SPACES)
if count > 0: # don't distract user with RequesterEnv status if env can be evaluated quickly
self.view.set_status('requester.activity', '{} {}'.format('RequesterEnv', activity))
if thread.is_alive():
timeout = self.config.get('timeout_env', None)
if timeout is not None and count * self.REFRESH_MS/REFRESH_MULTIPLIER > timeout * 1000:
sublime.error_message('Timeout Error: environment took too long to parse')
self.view.set_status('requester.activity', '')
return
sublime.set_timeout(lambda: self._run(thread, count+1), self.REFRESH_MS/REFRESH_MULTIPLIER)
else:
requests = self.get_requests()
self.view.set_status('requester.activity', '')
self.make_requests(requests, self._env)
def get_env_dict_from_string(s):
"""What it sounds like.
http://stackoverflow.com/questions/5362771/load-module-from-string-in-python
"""
try:
del sys.modules['requester.env'] # this avoids a subtle bug, DON'T REMOVE
except KeyError:
pass
if not s:
return {}
env = imp.new_module('requester.env')
try:
exec(s, env.__dict__)
except Exception as e:
sublime.error_message('EnvBlock Error:\n{}'.format(e))
return {}
else:
return dict(env.__dict__)
def run(self, edit, back):
view = self.view
if not view.settings().get('requester.response_view', False):
return
reqs = load_history(rev=False)
index = view.settings().get('requester.request_history_index', len(reqs)-1)
total = len(reqs)
if back:
index -= 1
else:
index += 1
if index < 0 or index >= len(reqs):
return
try:
params_dict = reqs[index][1]
except IndexError as e:
sublime.error_message('RequestHistory Error: {}'.format(e))
return
view.settings().set('requester.request_history_index', index)
populate_staging_view(view, total-index-1, total, **params_dict)
def run_initial_request(self, req, filename):
requests_method = getattr(requests, req.method.lower())
try:
res = requests_method(*req.args, stream=True, **req.kwargs)
except Exception as e:
sublime.error_message('Download Error: {}'.format(e))
return
response = Response(req, res, None)
self.handle_response(response)
self.handle_responses([response])
self.persist_requests([response]) # persist initial request before starting download
if res.status_code != 200:
sublime.error_message(
'Download Error: response status code is not 200\n\n{}'.format(truncate(res.text, 500))
)
if sublime.load_settings('Requester.sublime-settings').get('only_download_for_200', True):
return
self.download_file(res, filename)
def run(self, edit):
curls = self.get_curls()
requests = []
for curl in curls:
try:
request = curl_to_request(curl)
except Exception as e:
sublime.error_message('Conversion Error: {}'.format(e))
traceback.print_exc()
else:
requests.append(request)
if not requests:
return
header = '# import from cURL'
view = self.view.window().new_file()
view.run_command('requester_replace_view_text',
{'text': header + '\n\n\n' + '\n\n\n'.join(requests) + '\n', 'point': 0})
view.set_syntax_file('Packages/Requester/syntax/requester-source.sublime-syntax')
view.set_name('requests')
view.set_scratch(True)
def get_curls(self):
"""Parses curls from multiple selections. If nothing is highlighted,
cursor's current line is taken as selection.
"""
view = self.view
curls = []
for region in view.sel():
if not region.empty():
selection = view.substr(region)
else:
selection = view.substr(view.line(region))
try:
curls_ = self.parse_curls(selection)
except Exception as e:
sublime.error_message('Parse Error: {}'.format(e))
traceback.print_exc()
else:
for curl in curls_:
curls.append(curl)
return curls
def get_requests(self):
"""Parses only first highlighted selection.
"""
view = self.view
self._tests = []
for region in view.sel():
if not region.empty():
selection = view.substr(region)
try:
self._tests = parse_tests(selection)
except Exception as e:
sublime.error_message('Parse Error: there may be unbalanced brackets in tests')
print(e)
break # only parse first selection
return [test.request for test in self._tests]
def get_requests(self):
"""Parses URL from first selection, and passes it in special `explore` arg
to call to requests.
"""
view = self.view
if not view or not view.settings().get('requester.response_view', False):
sublime.error_message('Explore Error: you can only explore URLs from response tabs')
return []
try:
url = view.substr(view.sel()[0]).replace('"', '')
except:
return []
if not url:
return []
self._explore_url = url
try:
request = self.get_replay_request()
except:
return []
unclosed = request[:-1].strip()
if unclosed[-1] == ',':
unclosed = unclosed[:-1]
return ["{}, explore=({}, {}))".format(unclosed, repr(request), repr(url))]
def plugin_loaded():
global currentSettings, language, currentView
currentSettings = sublime.load_settings(setting_file)
language = currentSettings.get('language')
currentView = sublime.active_window().active_view()
docphpPath = getDocphpPath()
if not os.path.isdir(docphpPath + 'language'):
os.makedirs(docphpPath + 'language')
if not callable(sublime_symbol.symbol_at_point) or not callable(sublime_symbol.navigate_to_symbol):
sublime.error_message('Cannot find symbol_at_point from Default.sublime-package\n\nPlease restore the file which usually replaced by outdated localizations')
from package_control import events
if events.install(package_name) or not language:
currentView.run_command('docphp_checkout_language', {"is_init": True, "set_fallback": True})
def languageExists(languageName=None, fallback=False):
if not languageName:
languageName = language
if not language:
currentView.run_command('docphp_checkout_language', {"is_init": True, "set_fallback": True})
return False
if languageName not in docphp_languages and not loadLanguage():
if fallback:
begin = 'The fallback'
else:
begin = 'The'
print(getAllLanguages())
show_name = getAllLanguages()[languageName]['name']
sublime.error_message(begin + ' language "' + show_name +
'" has not yet installed.\nYou can use\n\n DocPHP: checkout language\n\ncommand to checkout a language pack.')
return False
return True
def load_settings(self, project_dir):
project_setting_file = RemoteGDBSettings.project_setting_file(project_dir)
if not os.path.exists(project_setting_file):
return False
try:
with open(project_setting_file) as data_file:
json_str = ""
for line in data_file.readlines():
line = line.strip()
if len(line) == 0:
continue
if line.startswith("//"):
continue
json_str += line
json_str += "\n"
self.data = json.loads(json_str)
except Exception as err:
print(err)
# sublime.error_message("some errors exist in project setting file!")
return False
return True
def run(self, index=None, **args):
command = args.get('command')
active_file_path = self.__active_file_path()
active_folders = sublime.active_window().folders()
if command == 'mlist':
self.__beagle = Phoenix(active_file_path + 'beagle_migrations', self.__patterns(), active_folders)
self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file)
else:
if not active_folders:
active_folders = os.path.split(active_file_path)[0]
sublime.error_message("SideBar is empty!")
if active_file_path:
if self.__patterns():
self.__beagle = Phoenix(active_file_path, self.__patterns(), active_folders)
self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file)
else:
self.__status_msg("Patterns are not loaded!")
else:
self.__status_msg("No open files")
def get_transformation_list(self, settings, view):
'''Generates a ranked list of available transformations.'''
# score the transformations and rank them
ranked = {}
for label, setting in settings['transformations'].items():
for scope in setting['scope']:
score = view.score_selector(0, scope)
if not score:
continue
if label not in ranked or ranked[label] < score:
ranked[label] = score
if not len(ranked):
sublime.error_message('No transformations configured for the syntax '+ view.settings().get('syntax'))
return
# reverse sort
transformation_list = list(OrderedDict(sorted(
ranked.items(), key=lambda t: t[1])).keys())
transformation_list.reverse()
return transformation_list
def load_folder_settings_file(folder_settings_file):
try:
folder_settings_file = open(folder_settings_file, "r")
except IOError as e:
sublime.error_message("Error: spandoc.json exists, but could not be read. Exception: " + str(e))
folder_settings_file.close()
else:
settings_file_commented = folder_settings_file.read()
folder_settings_file.close()
# debug("settings_file_commented: " + str(settings_file_commented))
try:
settings_file = sublime.decode_value(settings_file_commented)
except (KeyError, ValueError) as e:
sublime.error_message("JSON Error: Cannot parse spandoc.json. See console for details. Exception: " + str(e))
return None
# debug("settings_file: " + str(settings_file))
return settings_file
def calc_width(view):
'''
return float width, which must be
0.0 < width < 1.0 (other values acceptable, but cause unfriendly layout)
used in show.show() and "outline_select" command with other_group=True
'''
width = view.settings().get('outline_width', 0.3)
if isinstance(width, float):
width -= width//1 # must be less than 1
elif isinstance(width, int if ST3 else long): # assume it is pixels
wport = view.viewport_extent()[0]
width = 1 - round((wport - width) / wport, 2)
if width >= 1:
width = 0.9
else:
sublime.error_message(u'FileBrowser:\n\noutline_width set to '
u'unacceptable type "%s", please change it.\n\n'
u'Fallback to default 0.3 for now.' % type(width))
width = 0.3
return width or 0.1 # avoid 0.0
def on_done(self, paths, relative_to_project, name):
if relative_to_project or s.get('new_folders_relative_to_project_root', False):
paths = SideBarProject().getDirectories()
if paths:
paths = [SideBarItem(paths[0], True)]
if not paths:
paths = SideBarSelection(paths).getSelectedDirectoriesOrDirnames()
else:
paths = SideBarSelection(paths).getSelectedDirectoriesOrDirnames()
for item in paths:
item = SideBarItem(item.join(name), True)
if item.exists():
sublime.error_message("Unable to create folder, folder or file exists.")
self.run(paths, name)
return
else:
item.create()
if not item.exists():
sublime.error_message("Unable to create folder:\n\n"+item.path())
self.run(paths, name)
return
SideBarProject().refresh();
def run(self, paths = [], application = "", extensions = "", args=[]):
application_dir, application_name = os.path.split(application)
if extensions == '*':
extensions = '.*'
if extensions == '':
items = SideBarSelection(paths).getSelectedItems()
else:
items = SideBarSelection(paths).getSelectedFilesWithExtension(extensions)
import subprocess
try:
for item in items:
if sublime.platform() == 'osx':
subprocess.Popen(['open', '-a', application] + args + [item.name()], cwd=item.dirname())
elif sublime.platform() == 'windows':
subprocess.Popen([application_name] + args + [escapeCMDWindows(item.path())], cwd=expandVars(application_dir), shell=True)
else:
subprocess.Popen([application_name] + args + [escapeCMDWindows(item.name())], cwd=item.dirname())
except:
sublime.error_message('Unable to "Open With..", probably incorrect path to application.')
def run(self):
old = self.old
new = self.new
key = self.key
window_set_status(key, 'Duplicating…')
item = SideBarItem(old, os.path.isdir(old))
try:
if not item.copy(new):
window_set_status(key, '')
if SideBarItem(new, os.path.isdir(new)).overwrite():
self.run()
else:
SideBarDuplicateCommand(sublime_plugin.WindowCommand).run([old], new)
return
except:
window_set_status(key, '')
sublime.error_message("Unable to copy:\n\n"+old+"\n\nto\n\n"+new)
SideBarDuplicateCommand(sublime_plugin.WindowCommand).run([old], new)
return
item = SideBarItem(new, os.path.isdir(new))
if item.isFile():
item.edit();
SideBarProject().refresh();
window_set_status(key, '')
def get_base64_saver(loading, url):
def callback(content):
if isinstance(content, urllib.error.HTTPError):
if content.getcode() == 404:
loading[url] = 404
return
elif isinstance(content, urllib.error.URLError):
if (content.reason.errno == 11001 and
content.reason.strerror == 'getaddrinfo failed'):
loading[url] = 404
return
return sublime.error_message('An unexpected error has occured: ' +
str(content))
loading[url] = to_base64(content=content)
return callback
def _get_apple_clang_version_str(cls, output_text):
version_regex = re.compile("\d\.\d\.*\d*")
match = version_regex.search(output_text)
if match:
version_str = match.group()
# throw away the patch number
osx_version = version_str[:3]
try:
# info from this table:
# https://gist.github.com/yamaya/2924292
version_str = OSX_CLANG_VERSION_DICT[osx_version]
except Exception as e:
sublime.error_message("Version '{}' of AppleClang is not "
"supported yet. Please open an issue "
"for it".format(osx_version))
raise e
log.warning("OSX version %s reported. Reducing it to %s.",
osx_version,
version_str)
log.info("Found clang version %s", version_str)
return version_str
else:
raise RuntimeError(" Couldn't find clang version in clang version "
"output.")
def info(self, tooltip_request, settings):
"""Provide information about object in given location.
Using the current translation unit it queries libclang for available
information about cursor.
Args:
tooltip_request (tools.ActionRequest): A request for action
from the plugin.
settings: All plugin settings.
Returns:
(tools.ActionRequest, str): completion request along with the
info details read from the translation unit.
"""
# This is a dummy implementation that just shows an error to the user.
sublime.error_message(DUMMY_INFO_MSG)
def extract_path(cmd, delim=':'):
"""Return the user's PATH as a colon-delimited list."""
from . import persist
persist.debug('user shell:', cmd[0])
out = run_shell_cmd(cmd).decode()
path = out.split('__SUBL_PATH__', 2)
if len(path) > 1:
path = path[1]
return ':'.join(path.strip().split(delim))
else:
persist.printf('Could not parse shell PATH output:\n' + (out if out else '<empty>'))
sublime.error_message(
'SublimeLinter could not determine your shell PATH. '
'It is unlikely that any linters will work. '
'\n\n'
'Please see the troubleshooting guide for info on how to debug PATH problems.')
return ''
def _wait_for_finish_and_notify_user(self, i=1, dir=-1):
""" Displays animated Message as long as TSS is initing. Is recoursive function. """
if self.get_initialisation_error_message():
sublime.error_message('Typescript initializion error for : %s\n >>> %s\n ArcticTypescript is disabled until you restart sublime.'
% (self.project.tsconfigfile, self.get_initialisation_error_message()))
set_plugin_temporarily_disabled()
return
if not self.is_initialized():
(i, dir) = self._display_animated_init_message(i, dir)
# recursive:
sublime.set_timeout(lambda: self._wait_for_finish_and_notify_user(i, dir), 100)
else:
# starting finished ->
MESSAGE.show('Typescript project intialized for file : %s' % self.project.tsconfigfile, True, with_panel=False)
self.project.on_services_started()