-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathImportCost.py
203 lines (168 loc) · 6.1 KB
/
ImportCost.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import sublime
import sublime_plugin
import os
import subprocess
import json
import sys
Path = os.path
PLUGIN_NAME = __package__
PLUGIN_PATH = Path.dirname(Path.realpath(__file__))
SETTINGS_FILE = '{0}.sublime-settings'.format(PLUGIN_NAME)
PLUGIN_NODE_PATH = Path.join(
Path.dirname(Path.realpath(__file__)),
'provider.js'
)
cache = {}
class ImportCostCommand(sublime_plugin.ViewEventListener):
def __init__(self, view):
self.view = view
self.base_path = None
self.phantoms = sublime.PhantomSet(view)
self.update_phantoms()
def on_load_async(self):
if self.get_setting('check_on_open', True):
self.update_phantoms()
def on_post_save_async(self):
if self.get_setting('check_on_save_only', True):
self.update_phantoms()
def on_modified_async(self):
# TODO: improve detection every time view get modified
if not self.get_setting('check_on_save_only', True):
self.update_phantoms()
def update_phantoms(self):
if self.is_file_allowed():
sublime.set_timeout_async(lambda: self.calc_imports(self.find_imports()))
def find_imports(self):
modules = []
# https://regex101.com/r/AwuYVR/6
es6 = self.view.find_all(
r'''(?:^import(?:(?![\n])\s+)(?:(?:[\"'\s]*(?:[\w*{}\n, ]+)from\s*)?[\"']\s*((?![.]{1,2}\/)[@\w\/_\-\.]+)\s*[\"']).*)|(?:(?:var)|(?:const)|(?:let))[\s\w]+=\s*(?:(?:await\s+)?import)[(\"']+((?![.]{1,2}\/)[@\w\/_\-\.]+)[)\"']+.*''', 0, r"$1", modules
)
es5 = self.view.find_all(
r'''require\(\s*['"](.+?)['"]\s*\)''', 0, r"$1", modules
)
if self.get_setting('debug', False):
print("detected import regions: %s" % [es6 + es5])
print("imported modules: %s" % modules)
return [es6 + es5, modules]
def calc_imports(self, imports):
# TODO: cache modules!
phantoms = []
lines, modules = imports
cnt = 0
final_data = []
final_modules = []
for module in modules:
if module and self.find_root_path(module):
final_modules.append(module)
final_data.append({"region": lines[cnt], "module": module})
cnt = cnt + 1
if len(final_modules) == 0:
return None
args = []
try:
args = json.dumps(final_modules)
except OSError:
print('Error trying to stringify json!')
return None
data = self.node_bridge([self.base_path, args])
json_data = json.loads(data)
cnt = 0
if self.get_setting('debug', False):
print(\
'\nImportCost: %s' % \
Path.join(Path.dirname(self.view.file_name()), self.view.file_name()) \
)
for module in final_data:
size_data = json_data[cnt]
if 'size' in size_data and size_data['size'] > 0:
if self.get_setting('debug', False):
print(\
"-> module: %s, size: %s (%s gzipped)" % \
(module['module'], size_data['size'], size_data['gzip']) \
)
line = self.view.line(module["region"].a)
# TODO: change to settings
kb = size_data['size'] / 1000
color = '#666'
if kb > self.get_setting('min_size_warning', 40.0):
color = 'var(--yellowish)'
if kb > self.get_setting('min_size_error', 80.0):
color = 'var(--redish)'
gziptxt = ''
if (self.get_setting('show_gzip', False)):
gzipkb = size_data['gzip'] / 1000
gziptxt = '<span style="color: color(%s blend(var(--background) 66%%));">(gzipped: %.2fkB)</span>' % (color, gzipkb)
phantoms.append(sublime.Phantom(
sublime.Region(line.b),
'''
<style>html, body {margin: 0; padding:0; background-color: transparent;}</style>
<span style="background-color: transparent; color: %s; padding: 0 15px; font-size: .9rem; line-height: 1.3rem;"><b>%.2fkB</b> %s</span>
''' % (color, kb, gziptxt),
sublime.LAYOUT_INLINE
))
cnt = cnt + 1
self.phantoms.update(phantoms)
def is_file_allowed(self):
filename = self.view.file_name()
if not filename:
return False
file_ext = Path.splitext(filename)[1][1:]
if file_ext in self.get_setting('extensions', ['js', 'jsx']):
return True
return False
def node_bridge(self, args=[]):
node_path = self.get_setting('node_path', '/usr/local/bin/node')
if (Path.isfile(node_path) == False):
print('Error: Couldn\'t find "node" in "%s"' % node_path)
return None
try:
process = subprocess.Popen(
[node_path, PLUGIN_NODE_PATH] + args,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
env=os.environ.copy(),
startupinfo=None,
shell=self.is_windows()
)
except OSError:
print('Error: Couldn\'t find "node" in "%s"' % node_path)
stdout, stderr = process.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if stderr:
print('Error: %s' % stderr)
return None
return stdout
def is_windows(self):
return sys.platform == "win32" or sys.platform == 'cygwin'
def get_setting(self, key, default_value=None):
settings = self.view.settings().get(PLUGIN_NAME)
if settings is None or settings.get(key) is None:
settings = sublime.load_settings(SETTINGS_FILE)
value = settings.get(key, default_value)
return value
def find_root_path(self, module_name = ''):
if module_name.startswith('./') or module_name.startswith('../'):
return False
if self.base_path and \
Path.isdir(Path.join(self.base_path, 'node_modules', module_name)):
# If we already have the base path, use this
return True
# Otherwise try to determine base path
i = 0
check_dir = Path.dirname(self.view.file_name())
node_dir = Path.join(check_dir, 'node_modules')
module_dir = Path.join(node_dir, module_name)
is_dir = Path.isdir(module_dir)
while (i < 20 and (is_dir is False)):
check_dir = Path.join(check_dir, '..')
node_dir = Path.join(check_dir, 'node_modules')
module_dir = Path.join(node_dir, module_name)
is_dir = Path.isdir(module_dir)
i = i + 1
if is_dir:
self.base_path = check_dir
return True
return False