forked from vladimirnani/DjangoCommands
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdjango-commands.py
670 lines (514 loc) · 21.2 KB
/
django-commands.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
import sublime
import sublime_plugin
import threading
import subprocess
import os
import glob
import re
from ntpath import basename as ntbasename, split as ntsplit
from shutil import which
from platform import system
from functools import partial
from collections import OrderedDict
from urllib.parse import urlencode
SETTINGS_FILE = 'DjangoCommands.sublime-settings'
PLATFORM = system()
LATEST_DJANGO_RELEASE = 1.8
TERMINAL = ''
def log(message):
print(' - Django: {0}'.format(message))
class DjangoCommand(sublime_plugin.WindowCommand):
project_true = True
def __init__(self, *args, **kwargs):
self.settings = sublime.load_settings(SETTINGS_FILE)
self.interpreter_versions = {2: "python2",
3: "python3"} if PLATFORM is not "Windows" else {2: "python", 3: "python"}
log("{} ready".format(self.__class__.__name__))
sublime_plugin.WindowCommand.__init__(self, *args, **kwargs)
def get_manage_py(self):
return self.settings.get('django_project_root')or self.find_manage_py()
def get_executable(self):
self.project_true = self.settings.get('project_override')
settings_interpreter = self.settings.get('python_bin')
project = self.window.project_data()
settings_exists = 'settings' in project.keys()
if settings_exists and self.project_true:
project_interpreter = project['settings'].get('python_interpreter')
if project_interpreter is not None and self.project_true is True:
return project_interpreter
elif project_interpreter is not None and self.project_true is False:
return settings_interpreter
else:
version = self.settings.get("python_version")
return which(self.interpreter_versions[version])
elif settings_interpreter is not None:
return settings_interpreter
else:
version = self.settings.get("python_version")
return which(self.interpreter_versions[version])
def get_version(self):
binary = self.get_executable()
command = [binary, '-c', 'import django;print(django.get_version())']
# Hide the console window on Windows
startupinfo = None
if PLATFORM == 'Windows':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_output(command, startupinfo=startupinfo)
version = re.match(r'(\d\.\d)', output.decode('utf-8')).group(0)
if float(version) > LATEST_DJANGO_RELEASE:
version = 'dev'
return version
def find_manage_py(self):
for path in sublime.active_window().folders():
for root, dirs, files in os.walk(path):
if 'manage.py' in files:
return os.path.join(root, 'manage.py')
def choose(self, choices, action):
on_input = partial(action, choices)
self.window.show_quick_panel(choices, on_input)
def go_to_project_home(self):
try:
if self.manage_py is None:
return
except:
return
base_dir = os.path.abspath(os.path.join(self.manage_py, os.pardir))
os.chdir(base_dir)
def format_command(self, command):
binary = self.get_executable()
self.manage_py = self.get_manage_py()
self.go_to_project_home()
command = "{} {} {}".format(binary, self.manage_py, command)
return command
def define_terminal(self):
global TERMINAL
if PLATFORM == "Linux":
TERMINAL = self.settings.get('linux_terminal')
if TERMINAL is None:
TERMINAL = self.settings.get(
'linux-terminal', 'gnome-terminal')
def run_command(self, command):
self.define_terminal()
command = self.format_command(command)
thread = CommandThread(command)
thread.start()
class CommandThread(threading.Thread):
def __init__(self, command, cwd='.'):
self.command = command
self.cwd = cwd
threading.Thread.__init__(self)
def run(self):
command = "{}".format(self.command)
env = os.environ.copy()
if PLATFORM == 'Windows':
command = [
'cmd.exe',
'/k', "{} && timeout /T 10 && exit".format(command)
]
if PLATFORM == 'Linux':
command = [
TERMINAL,
'-e', 'bash -c \"{0}; read line\"'.format(command)
]
if PLATFORM == 'Darwin':
command = [
'osascript',
'-e', 'tell app "Terminal" to activate',
'-e', 'tell application "System Events" to tell process \
"Terminal" to keystroke "t" using command down',
'-e', 'tell application "Terminal" to \
do script "{0}" in front window'.format(command)
]
log('Command is : {0}'.format(str(command)))
subprocess.Popen(command, env=env, cwd=self.cwd)
class DjangoSimpleCommand(DjangoCommand):
command = ''
extra_args = []
def get_command(self):
return "{} {}".format(self.command, " ".join(self.extra_args))
def run(self):
self.extra_args = []
command = self.get_command()
self.run_command(command)
class DjangoAppCommand(DjangoCommand):
command = ''
extra_args = []
app_descriptor = 'models.py'
def find_apps(self):
apps = set()
for project_folder in sublime.active_window().folders():
dirs = [x[0] for x in os.walk(project_folder)]
for dir in dirs:
dir = os.path.expanduser(dir)
pattern = os.path.join(dir, "*", self.app_descriptor)
apps.update(list(map(lambda x: x, glob.glob(pattern))))
return sorted(apps)
def prettify(self, app_dir, base_dir):
name = app_dir.replace(base_dir, '')
name = name.replace(self.app_descriptor, '')
name = name[1:-1]
name = name.replace(os.path.sep, '.')
return name
def on_choose_app(self, apps, index):
if index == -1:
return
name = apps[index]
self.run_command(
"{} {} {}".format(self.command,
"".join(name),
" ".join(self.extra_args)))
def run(self):
self.go_to_project_home()
choices = self.find_apps()
self.manage_py = self.get_manage_py()
base_dir = os.path.dirname(self.manage_py)
choices = [self.prettify(path, base_dir) for path in choices]
self.choose(choices, self.on_choose_app)
class DjangoOtherCommand(DjangoSimpleCommand):
def get_commands(self):
forSplit = self.format_command('help --commands')
command = forSplit.split(' ')
out = str(subprocess.check_output(command))
out = re.search('b\'(.*)\'', out).group(1)
commands = out.split(
'\\n')[:-1] if PLATFORM is not "Windows" else out.split('\\r\\n')[:-1]
return commands
def on_choose_command(self, commands, index):
if index == -1:
return
name = commands[index]
self.run_command(name)
def run(self):
commands = self.get_commands()
self.choose(commands, self.on_choose_command)
class DjangoRunCommand(DjangoSimpleCommand):
command = 'runserver'
def run(self):
port = self.settings.get('server_port', "127.0.0.1")
host = self.settings.get('server_host', "8000")
self.extra_args = [host, port]
inComannd = "{} {}:{}".format(self.command, host, port)
self.run_command(inComannd)
class DjangoRunCustomCommand(DjangoSimpleCommand):
def get_script(self, executable, script_name):
return os.path.join(os.path.dirname(executable), script_name)
def run(self):
project = self.window.project_data()
p_settings = 'settings' in project.keys()
self.custom_command = project['settings'].get('server_custom_command') if p_settings else None
self.define_terminal()
executable = self.get_executable()
script = self.custom_command.get('command')
script = script if os.path.exists(script) else self.get_script(executable, script)
commands = [executable, script, " ".join(self.custom_command.get('args'))] if self.custom_command.get(
'run_with_python', True) else ["", script, " ".join(self.custom_command.get('args'))]
thread = CommandThread("{} {} {}".format(*commands), cwd=os.path.dirname(self.get_manage_py()))
thread.start()
class DjangoSyncdbCommand(DjangoSimpleCommand):
command = 'syncdb'
class DjangoShellCommand(DjangoSimpleCommand):
command = 'shell'
class DjangoDbShellCommand(DjangoSimpleCommand):
command = 'dbshell'
class DjangoCheckCommand(DjangoSimpleCommand):
command = 'check'
class DjangoHelpCommand(DjangoSimpleCommand):
command = 'help'
class DjangoMigrateCommand(DjangoSimpleCommand):
command = 'migrate'
class DjangoMigrateAppCommand(DjangoAppCommand):
command = 'migrate'
class DjangoTestAllCommand(DjangoSimpleCommand):
command = 'test'
class DjangoTestAppCommand(DjangoAppCommand):
command = 'test'
app_descriptor = 'tests.py'
class DjangoMakeMigrationCommand(DjangoSimpleCommand):
command = 'makemigrations'
class DjangoInitialSchemaMigrationCommand(DjangoAppCommand):
command = 'schemamigration'
extra_args = ['--initial']
class DjangoSchemaMigrationCommand(DjangoAppCommand):
command = 'schemamigration'
extra_args = ['--auto']
class DjangoListMigrationsCommand(DjangoSimpleCommand):
command = 'migrate'
extra_args = ['--list']
class DjangoSqlMigrationCommand(DjangoAppCommand):
command = 'sqlmigrate'
def path_leaf(self, path):
head, tail = ntsplit(path)
return os.path.splitext(tail)[0] or os.path.splitext(ntbasename(head))[0]
def is_enabled(self):
return float(self.get_version()) >= 1.7 or self.get_version() == 'dev'
def on_choose_migration(self, apps, index):
if index == -1:
return
self.extra_args.append(apps[index])
self.run_command(
"{} {} {}".format(self.command, self.name, " ".join(self.extra_args)))
def on_app_selected(self, apps, index):
self.name = apps[index]
path = os.path.join(
os.path.dirname(self.find_apps()[index]), 'migrations')
migrations = [
path for path in map(self.path_leaf, glob.iglob(os.path.join(path, r'*.py')))]
migrations.remove('__init__')
sublime.set_timeout(
lambda: self.choose(migrations, self.on_choose_migration), 20)
def run(self):
self.extra_args = []
self.go_to_project_home()
choices = self.find_apps()
self.manage_py = self.get_manage_py()
base_dir = os.path.dirname(self.manage_py)
choices = [self.prettify(path, base_dir) for path in choices]
self.choose(choices, self.on_app_selected)
class DjangoCustomCommand(DjangoCommand):
def run(self):
caption = "Django manage.py command"
self.window.show_input_panel(caption, '', self.on_done, None, None)
def on_done(self, command):
command = command
if command.strip() == '':
return
self.run_command(command)
class VirtualEnvCommand(DjangoCommand):
command = ''
extra_args = []
def is_enabled(self):
return self.settings.get('python_bin') is not None
def run(self):
self.define_terminal()
self.manage_py = self.get_manage_py()
self.go_to_project_home()
bin_dir = os.path.dirname(self.settings.get('python_bin'))
command = "{} {}".format(
os.path.join(bin_dir, self.command), " ".join(self.extra_args))
thread = CommandThread(command)
thread.start()
class TerminalHereCommand(VirtualEnvCommand):
command = 'activate'
def run(self):
self.define_terminal()
self.manage_py = self.get_manage_py()
self.go_to_project_home()
bin_dir = os.path.dirname(self.settings.get('python_bin'))
if PLATFORM == 'Windows':
command = 'cmd /k {}'.format(
os.path.join(bin_dir, self.command))
if PLATFORM == 'Linux' or PLATFORM == 'Darwin':
command = "bash --rcfile <(echo '. ~/.bashrc && . {}')".format(
os.path.join(bin_dir, self.command))
thread = CommandThread(command)
thread.start()
class PipFreezeCommand(VirtualEnvCommand):
command = 'pip'
extra_args = ['freeze']
class PipFreezeToFileCommand(VirtualEnvCommand):
command = 'pip'
extra_args = ['freeze']
def on_done(self, filename):
self.extra_args.append('>')
self.extra_args.append(filename)
VirtualEnvCommand.run(self)
def run(self):
self.window.show_input_panel(
"File name", "requirements.txt", self.on_done, None, None)
class PipInstallPackagesCommand(VirtualEnvCommand):
command = 'pip'
extra_args = ['install']
def appendPackages(self, text):
self.extra_args.append(text)
super(PipInstallPackagesCommand, self).run()
def run(self):
self.window.show_input_panel(
'Packages', '', self.appendPackages, None, None)
class PipInstallRequirementsCommand(VirtualEnvCommand):
command = 'pip'
extra_args = ['install', '-r']
file_name = 'requirements.txt'
def another_file(self, text):
self.extra_args.append(text)
super(PipInstallRequirementsCommand, self).run()
def run(self):
self.extra_args = ['install', '-r']
if os.path.exists(self.file_name):
self.extra_args.append(self.file_name)
super(PipInstallRequirementsCommand, self).run()
else:
sublime.message_dialog('requirements.txt not found')
self.window.show_input_panel(
'File to install', '', self.another_file, None, None)
class SetVirtualEnvCommand(VirtualEnvCommand):
def is_enabled(self):
return True
def find_virtualenvs(self, venv_paths):
binary = "Scripts" if PLATFORM == 'Windows' else "bin"
venvs = set()
for path in venv_paths:
path = os.path.expanduser(path)
pattern = os.path.join(path, "*", binary, "activate_this.py")
venvs.update(list(map(os.path.dirname, glob.glob(pattern))))
return sorted(venvs)
def set_virtualenv(self, venvs, index):
if index == -1:
return
name, directory = venvs[index]
log('Virtual environment "{0}" is set'.format(name))
binary = os.path.join(directory, 'python')
self.settings.set("python_bin", binary)
sublime.save_settings(SETTINGS_FILE)
def run(self):
venv_paths = self.settings.get("python_virtualenv_paths", [])
choices = self.find_virtualenvs(venv_paths)
choices = [[path.split(os.path.sep)[-2], path] for path in choices]
self.choose(choices, self.set_virtualenv)
class ChangeDefaultCommand(VirtualEnvCommand):
def use_default(self):
self.settings.erase('python_bin')
sublime.save_settings(SETTINGS_FILE)
def run(self):
self.use_default()
class DjangoClickCommand(sublime_plugin.TextCommand):
TEMPLATE_DIR = 'templates'
def parse_tag(self, line):
RE_PARAMS = re.compile(r'(with)|(\w+=[\'"]\w+[\'"])')
RE_BLOCK = re.compile(
r'.*{%%\s*(?P<tag>%s)\s+(?P<names>.+)?[\'"]?\s*%%}'
% '|'.join(['include', 'extends', 'includeblocks']))
RE_NAMES = re.compile(r'[\'"]([/\.\-_a-zA-Z0-9\s]+)[\'"]')
line = re.sub(RE_PARAMS, "", line)
match = re.match(RE_BLOCK, line)
if match:
targets = re.findall(RE_NAMES, match.groupdict()['names'])
return match.groupdict()['tag'], targets
return None, []
def run(self, edit):
region = self.view.sel()[0]
line = self.view.line(region)
line_contents = self.view.substr(line)
tag, targets = self.parse_tag(line_contents)
if tag:
# get the base-path of current file
base, current_file = self.view.file_name().split(
'%(separator)stemplates%(separator)s' % dict(
separator=os.path.sep), 1)
for one in targets:
tar = os.path.join(base, self.TEMPLATE_DIR, one)
if os.path.isfile(tar):
window = sublime.active_window()
window.open_file(tar, sublime.ENCODED_POSITION)
else:
for root, dirs, filenames in os.walk(base):
for f in filenames:
if f == one:
tar = os.path.join(root, one)
window = sublime.active_window()
if os.path.exists(tar):
window.open_file(
tar, sublime.ENCODED_POSITION)
class DjangoBoilerPlate(sublime_plugin.WindowCommand):
options = ['urls', 'models', 'views', 'admin', 'forms', 'tests']
def on_done(self, index):
if index < 0:
return
urls = """from django.conf.urls import patterns, include, url
urlpatterns = [
# Examples:
# url(r'^$', 'example.views.home', name='home'),
# url(r'^blog/', include(blog.urls)),
]
"""
admin = """from django.contrib import admin
# Register your models here.
"""
views = """from django.shortcuts import render
# Create your views here.
"""
models = """from django.db import models
# Define your models here
"""
forms = """from django import forms
# Create your forms here
"""
tests = """from django.test import TestCase
# Create your tests here.
"""
actions = OrderedDict()
for option in self.options:
actions[option] = eval(option)
text = actions[self.options[index]]
self.view = self.window.active_view()
self.view.run_command('write_helper', {"text": text})
def run(self):
self.window.show_quick_panel(self.options, self.on_done)
class WriteHelperCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
self.view.insert(edit, 0, text)
class DjangoNewProjectCommand(SetVirtualEnvCommand):
def folder_selected(self, index):
self.create_project(directory=self.window.folders()[index])
def check_folders(self, name):
if len(self.window.folders()) == 1:
self.create_project(name=name, directory=self.window.folders()[0])
else:
self.name = name
self.window.show_quick_panel(
self.window.folders(), self.folder_selected)
def create_project(self, **kwargs):
name = kwargs.get('name')
directory = kwargs.get('directory')
if name is not None:
pass
else:
name = self.name
order = os.path.join(
os.path.abspath(os.path.dirname(self.interpreter)), "django-admin.py")
command = [self.interpreter, order, "startproject", name, directory]
log(command)
subprocess.Popen(command)
def set_interpreter(self, index):
if index == -1:
return
name, self.interpreter = self.choices[index]
if name is not "default":
self.interpreter = os.path.join(self.interpreter, 'python')
self.window.show_input_panel(
"Project name", "", self.check_folders, None, None)
def run(self):
venv_paths = self.settings.get("python_virtualenv_paths", [])
version = self.settings.get("python_version")
envs = self.find_virtualenvs(venv_paths)
self.choices = [[path.split(os.path.sep)[-2], path] for path in envs]
self.choices.append(
["default", which(self.interpreter_versions[version])])
sublime.message_dialog(
"Select a python interpreter for the new project")
self.window.show_quick_panel(self.choices, self.set_interpreter)
class DjangoNewAppCommand(DjangoSimpleCommand):
command = 'startapp'
def create_app(self, text):
self.extra_args.append(text)
command = self.format_command(self.get_command())
subprocess.Popen(command.split(' '), env=os.environ.copy())
def run(self):
self.window.show_input_panel(
"App name", '', self.create_app, None, None)
class DjangoOpenDocsCommand(DjangoCommand):
def run(self):
version = self.get_version()
url = "https://docs.djangoproject.com/en/{}/".format(version)
self.window.run_command('open_url', {'url': url})
class DjangoSearchDocsCommand(DjangoCommand):
def on_done(self, text):
releases = {'1.3': 5, '1.4': 6, '1.5': 7,
'1.6': 9, '1.7': 11, '1.8': 13, 'dev': 1}
release = releases[self.get_version()]
params = {'q': text, 'release': release}
url = "https://docs.djangoproject.com/search/?{}".format(
urlencode(params))
self.window.run_command('open_url', {'url': url})
def run(self):
self.window.show_input_panel('Search:', '', self.on_done, None, None)