-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdjangonaut.el
1430 lines (1159 loc) · 53.7 KB
/
djangonaut.el
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; djangonaut.el --- Minor mode to interact with Django projects -*- lexical-binding: t; -*-
;; Copyright (C) 2018 by Artem Malyshev
;; Author: Artem Malyshev <[email protected]>
;; URL: https://github.com/proofit404/djangonaut
;; Version: 0.0.1
;; Package-Requires: ((emacs "25.2") (magit-popup "2.6.0") (pythonic "0.1.0") (f "0.20.0") (s "1.12.0"))
;; Keywords: convenience django
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; See the README for more details.
;;; Code:
(require 'magit-popup)
(require 'ansi-color)
(require 'easymenu)
(require 'pythonic)
(require 'compile)
(require 'comint)
(require 'json)
(require 'f)
(require 's)
(defgroup djangonaut nil
"Minor mode to interact with Django projects"
:prefix "djangonaut-"
:group 'tools)
(defcustom djangonaut-keymap-prefix (kbd "C-c '")
"Djangonaut keymap prefix."
:type 'key-sequence)
(defcustom djangonaut-navigate-line-hook '(recenter)
"Hooks called after jumping to a place in the buffer.
Useful things to use here include `reposition-window',
`recenter', and `recenter-top-bottom' functions."
:type 'hook)
(defvar djangonaut-get-pythonpath-code "
from __future__ import print_function
from sys import path
print('\\n'.join(path))
" "Python source code to get PYTHONPATH.")
(defvar djangonaut-get-project-root-code "
from __future__ import print_function
from importlib import import_module
from os import environ
from os.path import dirname
settings_module = environ['DJANGO_SETTINGS_MODULE']
package_name = settings_module.split('.', 1)[0]
package = import_module(package_name)
project_root = dirname(dirname(package.__file__))
print(project_root, end='')
" "Python source code to get project root.")
(defvar djangonaut-get-commands-code "
from django.core.management import get_commands
for command in get_commands():
result[command] = ''
" "Python source code to get commands.")
(defvar djangonaut-get-command-definitions-code "
from importlib import import_module
from inspect import findsource, getsourcefile
from django.core.management import get_commands
for command_name, module_name in get_commands().items():
module = import_module(module_name + '.management.commands.' + command_name)
command = module.Command
try:
source = findsource(command)
except OSError:
pass
else:
result[command_name] = [getsourcefile(command), source[1]]
" "Python source code to get command definitions.")
(defvar djangonaut-get-command-arguments-code "
from importlib import import_module
from random import choice
from string import ascii_letters
from sys import argv
from django.core.management import get_commands
known_shortcuts = set([])
def get_free_shortcut(short):
result = short
while result in known_shortcuts:
result = choice(ascii_letters)
known_shortcuts.add(result)
return result
class Parser(object):
@staticmethod
def add_argument(*args, **kwargs):
assert 0 < len(args) < 3, 'Unsupported arguments: {0} {1}'.format(args, kwargs)
if kwargs.get('action') in ('store_true', 'store_false'):
target = result.setdefault('switches', [])
get_option = lambda x, end: x
else:
target = result.setdefault('options', [])
get_option = lambda x, end: x + end
data = {'optional': None, 'short': None, 'positional': None}
for arg in args:
if arg.startswith('--'):
data['optional'] = arg
elif arg.startswith('-'):
data['short'] = arg
else:
data['positional'] = arg
if data['positional']:
key = '='
option = ''
suffix = ''
elif data['short']:
key = data['short'][1]
option = data['optional'] or data['short']
suffix = '=' if data['optional'] else ' '
else:
key = data['optional'][2]
option = data['optional']
suffix = '='
name = get_option(option, suffix)
shortcut = get_free_shortcut(key)
description = kwargs.get('help') or data['positional'] or data['optional'] or data['short']
target.append([shortcut, description, name])
command_name = argv[-1]
module_name = get_commands()[command_name]
module = import_module(module_name + '.management.commands.' + command_name)
command = module.Command()
command.add_arguments(Parser)
" "Python source code to get command arguments.")
(defvar djangonaut-get-app-paths-code "
for app in apps.get_app_configs():
result[app.label] = app.path
" "Python source code to get app paths.")
(defvar djangonaut-get-admin-classes-code "
from inspect import findsource, getsourcefile
try:
from django.contrib.admin.sites import all_sites
except ImportError:
from gc import get_objects
from django.contrib.admin.sites import AdminSite
all_sites = []
for obj in get_objects():
if isinstance(obj, AdminSite):
all_sites.append(obj)
for site in all_sites:
for admin_instance in site._registry.values():
admin_class = admin_instance.__class__
try:
source = findsource(admin_class)
except OSError:
pass
else:
result[str(admin_instance)] = [getsourcefile(admin_class), source[1]]
" "Python source code to get admin classes.")
(defvar djangonaut-get-models-code "
from inspect import findsource, getsourcefile
for model in apps.get_models():
try:
source = findsource(model)
except OSError:
pass
else:
result[model._meta.app_label + '.' + model.__name__] = [getsourcefile(model), source[1]]
" "Python source code to get models.")
(defvar djangonaut-get-model-managers-code "
from gc import get_objects
from inspect import findsource, getsourcefile, getmodule, isclass
from django.db.models import Manager
for obj in get_objects():
if isclass(obj) and issubclass(obj, Manager):
name = getmodule(obj).__name__ + '.' + obj.__name__
try:
source = findsource(obj)
except OSError:
pass
else:
result[name] = [getsourcefile(obj), source[1]]
" "Python source code to get model managers.")
(defvar djangonaut-get-migrations-code "
from inspect import findsource, getsourcefile
from django.db.migrations.loader import MigrationLoader
loader = MigrationLoader(connection=None, load=False)
loader.load_disk()
for (label, module_name), migration in sorted(loader.disk_migrations.items()):
name = label + '.' + module_name
Migration = migration.__class__
try:
source = findsource(Migration)
except OSError:
pass
else:
result[name] = [getsourcefile(Migration), source[1]]
" "Python source code to get migrations.")
(defvar djangonaut-get-sql-functions-code "
from gc import get_objects
from inspect import findsource, getsourcefile, getmodule, isclass
from django.db.models import Func
for obj in get_objects():
if isclass(obj) and issubclass(obj, Func):
name = getmodule(obj).__name__ + '.' + obj.__name__
try:
source = findsource(obj)
except OSError:
pass
else:
result[name] = [getsourcefile(obj), source[1]]
" "Python source code to get sql functions.")
(defvar djangonaut-get-signal-receivers-code "
from gc import get_objects
from inspect import findsource, getsourcefile, getmodule
from weakref import ReferenceType
from django.dispatch.dispatcher import Signal
for obj in get_objects():
if isinstance(obj, Signal):
for lookup_key, receiver in obj.receivers:
if isinstance(receiver, ReferenceType):
receiver = receiver()
if receiver is None:
continue
name = getmodule(receiver).__name__ + '.' + receiver.__name__
try:
source = findsource(receiver)
except OSError:
pass
else:
result[name] = [getsourcefile(receiver), source[1]]
" "Python source code to get signal receivers.")
(defvar djangonaut-get-drf-serializers-code "
from gc import get_objects
from importlib import import_module
from inspect import findsource, getsourcefile, getmodule, isclass
from rest_framework.serializers import Serializer
import_module(settings.ROOT_URLCONF)
for obj in get_objects():
if isclass(obj) and issubclass(obj, Serializer):
name = getmodule(obj).__name__ + '.' + obj.__name__
try:
source = findsource(obj)
except OSError:
pass
else:
result[name] = [getsourcefile(obj), source[1]]
" "Python source code to get drf serializers.")
(defvar djangonaut-get-drf-permissions-code "
from gc import get_objects
from importlib import import_module
from inspect import findsource, getsourcefile, getmodule, isclass
from rest_framework.permissions import BasePermission
import_module(settings.ROOT_URLCONF)
for obj in get_objects():
if isclass(obj) and issubclass(obj, BasePermission):
name = getmodule(obj).__name__ + '.' + obj.__name__
try:
source = findsource(obj)
except OSError:
pass
else:
result[name] = [getsourcefile(obj), source[1]]
" "Python source code to get drf permissions.")
(defvar djangonaut-get-views-code "
from inspect import findsource, getsourcefile, getmodule, ismethod
try:
from django.urls import get_resolver, get_urlconf
except ImportError:
from django.core.urlresolvers import get_resolver, get_urlconf
try:
from django.urls.resolvers import LocalePrefixPattern, RegexPattern, RoutePattern, URLPattern, URLResolver
pattern_classes = (LocalePrefixPattern, RegexPattern, RoutePattern, URLPattern)
resolver_classes = (URLResolver,)
except ImportError:
try:
from django.urls import RegexURLPattern, RegexURLResolver
pattern_classes = (RegexURLPattern,)
resolver_classes = (RegexURLResolver,)
except ImportError:
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver
pattern_classes = (RegexURLPattern,)
resolver_classes = (RegexURLResolver,)
try:
from inspect import unwrap
except ImportError:
def unwrap(func):
while hasattr(func, '__wrapped__'):
func = func.__wrapped__
return func
def collect_views(resolver):
for pattern in resolver.url_patterns:
if isinstance(pattern, resolver_classes):
collect_views(pattern)
elif isinstance(pattern, pattern_classes):
view = pattern.callback
if hasattr(view, 'view_class'):
# Django as_view result.
view = view.view_class
name = getmodule(view).__name__ + '.' + view.__name__
elif hasattr(view, 'cls'):
# DRF as_view result.
view = view.cls
name = getmodule(view).__name__ + '.' + view.__name__
try:
source = findsource(view)
except OSError:
pass
else:
result[name] = [getsourcefile(view), source[1]]
for attrname in dir(view):
view_attr = getattr(view, attrname)
if getattr(view_attr, 'bind_to_methods', None):
# DRF ViewSet method view.
try:
source = findsource(view_attr)
except OSError:
pass
else:
result[name + '.' + attrname] = [getsourcefile(view_attr), source[1]]
continue
else:
view = unwrap(view)
if ismethod(view):
name = getmodule(view).__name__ + '.' + view.__self__.__class__.__name__ + '.' + view.__name__
else:
name = getmodule(view).__name__ + '.' + view.__name__
try:
source = findsource(view)
except OSError:
pass
else:
result[name] = [getsourcefile(view), source[1]]
collect_views(get_resolver(get_urlconf()))
" "Python source code to get views.")
(defvar djangonaut-get-middlewares-code "
from inspect import findsource, getsourcefile
from django.utils.module_loading import import_string
for name in getattr(settings, 'MIDDLEWARE', None) or settings.MIDDLEWARE_CLASSES:
middleware = import_string(name)
try:
source = findsource(middleware)
except OSError:
pass
else:
result[name] = [getsourcefile(middleware), source[1]]
" "Python source code to get middlewares.")
(defvar djangonaut-get-url-modules-code "
from types import ModuleType
try:
from django.urls import get_resolver, get_urlconf
except ImportError:
from django.core.urlresolvers import get_resolver, get_urlconf
try:
from django.urls import URLResolver
resolver_classes = (URLResolver,)
except ImportError:
try:
from django.urls import RegexURLResolver
resolver_classes = (RegexURLResolver,)
except ImportError:
from django.core.urlresolvers import RegexURLResolver
resolver_classes = (RegexURLResolver,)
def collect_url_modules(conf):
name = conf.urlconf_name
if isinstance(name, ModuleType):
name = name.__name__
result[name] = conf.urlconf_module.__file__
for pattern in conf.url_patterns:
if isinstance(pattern, resolver_classes) and not isinstance(pattern.urlconf_module, list):
collect_url_modules(pattern)
collect_url_modules(get_resolver(get_urlconf()))
" "Python source code to get url modules.")
(defvar djangonaut-get-forms-code "
from gc import get_objects
from importlib import import_module
from inspect import findsource, getsourcefile, getmodule, isclass
from django.forms.forms import BaseForm
from django.forms.formsets import BaseFormSet
import_module(settings.ROOT_URLCONF)
for obj in get_objects():
if isclass(obj) and issubclass(obj, (BaseForm, BaseFormSet)):
name = getmodule(obj).__name__ + '.' + obj.__name__
try:
source = findsource(obj)
except OSError:
pass
else:
result[name] = [getsourcefile(obj), source[1]]
" "Python source code to get forms.")
(defvar djangonaut-get-widgets-code "
from gc import get_objects
from importlib import import_module
from inspect import findsource, getsourcefile, getmodule, isclass
from django.forms.widgets import Widget
import_module(settings.ROOT_URLCONF)
for obj in get_objects():
if isclass(obj) and issubclass(obj, Widget):
name = getmodule(obj).__name__ + '.' + obj.__name__
try:
source = findsource(obj)
except OSError:
pass
else:
result[name] = [getsourcefile(obj), source[1]]
" "Python source code to get widgets.")
(defvar djangonaut-get-templates-code "
from os import walk
from os.path import join
from django.contrib.staticfiles.utils import matches_patterns
from django.template import engines
from django.template.backends.django import DjangoTemplates
from django.template.loaders.filesystem import Loader as FileSystemLoader
from django.template.loaders.app_directories import Loader as AppDirectoriesLoader
from django.template.utils import get_app_template_dirs
ignore_patterns = ['CVS', '.*', '*~']
for engine in engines.all():
if isinstance(engine, DjangoTemplates):
for loader in engine.engine.template_loaders:
if isinstance(loader, (FileSystemLoader, AppDirectoriesLoader)):
try:
dirs = loader.get_dirs()
except AttributeError:
if isinstance(loader, AppDirectoriesLoader):
dirs = get_app_template_dirs('templates')
else:
dirs = loader.engine.dirs
for template_directory in dirs:
for root, _, files in walk(template_directory):
for template in files:
template_path = join(root, template)
if not matches_patterns(template_path, ignore_patterns):
result.setdefault(template_path[len(template_directory) + 1:], template_path)
" "Python source code to get templates.")
(defvar djangonaut-get-template-tags-code "
from importlib import import_module
from inspect import findsource, getsourcefile
try:
from inspect import unwrap
except ImportError:
def unwrap(func):
while hasattr(func, '__wrapped__'):
func = func.__wrapped__
return func
libraries = collections.OrderedDict()
libraries['builtin'] = import_module('django.template.defaulttags').register
try:
from django.template.backends.django import get_installed_libraries
for library_name, library_path in get_installed_libraries().items():
libraries[library_name] = import_module(library_path).register
except ImportError:
from pkgutil import walk_packages
from django.template.base import get_templatetags_modules
for package_name in get_templatetags_modules():
package = import_module(package_name)
if hasattr(package, '__path__'):
for entry in walk_packages(package.__path__, package.__name__ + '.'):
module = import_module(entry[1])
if hasattr(module, 'register'):
libraries[entry[1][len(package_name) + 1:]] = module.register
for library_name, library in libraries.items():
for tag_name, tag in library.tags.items():
tag = unwrap(tag)
try:
try:
source = findsource(tag)
except OSError:
pass
else:
result[library_name + '.' + tag_name] = [getsourcefile(tag), source[1]]
except TypeError:
# This is Django 1.8 and we met functools.partial result. We take class defined
# in the decorator from bound keyword arguments. This class has a method with a
# closure where we can find decorated function.
tag = tag.keywords['node_class'].render.__closure__[-1].cell_contents
try:
source = findsource(tag)
except OSError:
pass
else:
result[library_name + '.' + tag_name] = [getsourcefile(tag), source[1]]
" "Python source code to get template tags.")
(defvar djangonaut-get-template-filters-code "
from importlib import import_module
from inspect import findsource, getsourcefile
try:
from inspect import unwrap
except ImportError:
def unwrap(func):
while hasattr(func, '__wrapped__'):
func = func.__wrapped__
return func
libraries = collections.OrderedDict()
libraries['builtin'] = import_module('django.template.defaulttags').register
try:
from django.template.backends.django import get_installed_libraries
for library_name, library_path in get_installed_libraries().items():
libraries[library_name] = import_module(library_path).register
except ImportError:
from pkgutil import walk_packages
from django.template.base import get_templatetags_modules
for package_name in get_templatetags_modules():
package = import_module(package_name)
if hasattr(package, '__path__'):
for entry in walk_packages(package.__path__, package.__name__ + '.'):
module = import_module(entry[1])
if hasattr(module, 'register'):
libraries[entry[1][len(package_name) + 1:]] = module.register
for library_name, library in libraries.items():
for filter_name, filter in library.filters.items():
filter = unwrap(filter)
try:
source = findsource(filter)
except OSError:
pass
else:
result[library_name + '.' + filter_name] = [getsourcefile(filter), source[1]]
" "Python source code to get template filters.")
(defvar djangonaut-get-static-files-code "
from django.contrib.staticfiles.finders import get_finders
ignore_patterns = ['CVS', '.*', '*~']
for finder in get_finders():
for path, storage in finder.list(ignore_patterns):
result.setdefault(path, storage.path(path))
" "Python source code to get static files.")
(defvar djangonaut-get-settings-path-code "
from importlib import import_module
from inspect import getsourcefile
from os import environ
settings_module = environ['DJANGO_SETTINGS_MODULE']
module = import_module(settings_module)
settings_path = getsourcefile(module)
result['settings_path'] = settings_path
" "Python source code to get settings path.")
(defvar djangonaut-wrapper-template "
from __future__ import print_function
import collections, json, os, sys, traceback
stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')
if not sys.path[0]:
del sys.path[0]
try:
from django.apps import apps
from django.conf import settings
apps.populate(settings.INSTALLED_APPS)
result = collections.OrderedDict()
%s
print(json.dumps(result), end='', file=stdout)
except:
traceback.print_exc(None, stdout)
raise
" "Try/except python wrapper to handle output redirection.")
(defvar djangonaut-app-paths-history nil)
(defvar djangonaut-commands-history nil)
(defvar djangonaut-admin-classes-history nil)
(defvar djangonaut-models-history nil)
(defvar djangonaut-model-managers-history nil)
(defvar djangonaut-migrations-history nil)
(defvar djangonaut-sql-functions-history nil)
(defvar djangonaut-signal-receivers-history nil)
(defvar djangonaut-drf-serializers-history nil)
(defvar djangonaut-drf-permissions-history nil)
(defvar djangonaut-views-history nil)
(defvar djangonaut-middlewares-history nil)
(defvar djangonaut-url-modules-history nil)
(defvar djangonaut-forms-history nil)
(defvar djangonaut-widgets-history nil)
(defvar djangonaut-templates-history nil)
(defvar djangonaut-template-tags-history nil)
(defvar djangonaut-template-filters-history nil)
(defvar djangonaut-static-files-history nil)
(defun djangonaut-get-pythonpath ()
"Execute and parse python code to get PYTHONPATH."
(split-string
(with-output-to-string
(with-current-buffer
standard-output
(hack-dir-local-variables-non-file-buffer)
(pythonic-call-process :buffer standard-output
:args (list "-c" djangonaut-get-pythonpath-code))))
nil t))
(defun djangonaut-get-project-root ()
"Execute and parse python code to get project root."
(with-output-to-string
(with-current-buffer
standard-output
(hack-dir-local-variables-non-file-buffer)
(pythonic-call-process :buffer standard-output
:args (list "-c" djangonaut-get-project-root-code)))))
(defun djangonaut-wrap (code)
"Wrap code with try/except CODE block."
(format djangonaut-wrapper-template
(s-join "\n " (s-split "\n" code))))
(defun djangonaut-call (code &rest args)
"Execute python CODE with ARGS. Show errors if occurs."
(let (exit-code output)
(setq output
(with-output-to-string
(with-current-buffer
standard-output
(hack-dir-local-variables-non-file-buffer)
(setq exit-code
(pythonic-call-process :buffer standard-output
:args `("-c"
,(djangonaut-wrap code)
,@args))))))
(when (not (zerop exit-code))
(djangonaut-show-error output (format "Python exit with status code %d" exit-code)))
output))
(defun djangonaut-read (str)
"Read JSON from Python process output STR."
(condition-case err
(let* ((json-key-type 'string)
(result (json-read-from-string str)))
(unless (listp result)
(signal 'json-error nil))
result)
((json-error wrong-type-argument)
(djangonaut-show-error str (error-message-string err)))))
(defun djangonaut-show-error (output error-message)
"Prepare and show OUTPUT in the ERROR-MESSAGE buffer."
(let* ((buffer (get-buffer-create "*Django*"))
(process (get-buffer-process buffer)))
(when (and process (process-live-p process))
(setq buffer (generate-new-buffer "*Django*")))
(with-current-buffer buffer
(let ((inhibit-read-only t))
(erase-buffer))
(fundamental-mode)
(insert output)
(goto-char (point-min))
(compilation-minor-mode 1)
(pop-to-buffer buffer)
(error error-message))))
(defun djangonaut-find-file (func prompt collection hist)
"Ask user to select some name and open its definition.
FUNC is function to open file. PROMPT and COLLECTION stands for
user input. HIST is a variable to store history of choices."
(let* ((key (completing-read prompt (mapcar 'car collection) nil t nil hist))
(value (cdr (assoc key collection))))
(apply func (pythonic-emacs-readable-file-name value) nil)))
(defun djangonaut-find-file-and-line (func prompt collection hist)
"Ask user to select some name and open its definition at the line number.
FUNC is function to open file. PROMPT and COLLECTION stands for
user input. HIST is a variable to store history of choices."
(let* ((key (completing-read prompt (mapcar 'car collection) nil t nil hist))
(code (cdr (assoc key collection)))
(value (elt code 0))
(lineno (elt code 1)))
(apply func (pythonic-emacs-readable-file-name value) nil)
(goto-char (point-min))
(forward-line lineno)
(run-hooks 'djangonaut-navigate-line-hook)))
(defun djangonaut-get-commands ()
"Execute and parse python code to get commands."
(mapcar 'car (djangonaut-read (djangonaut-call djangonaut-get-commands-code))))
(defun djangonaut-get-command-definitions ()
"Execute and parse python code to get command definitions."
(djangonaut-read (djangonaut-call djangonaut-get-command-definitions-code)))
(defun djangonaut-get-command-arguments (command)
"Execute and parse python code to get COMMAND arguments."
(djangonaut-read (djangonaut-call djangonaut-get-command-arguments-code command)))
(defun djangonaut-get-app-paths ()
"Execute and parse python code to get app paths."
(djangonaut-read (djangonaut-call djangonaut-get-app-paths-code)))
(defun djangonaut-get-admin-classes ()
"Execute and parse python code to get admin classes."
(djangonaut-read (djangonaut-call djangonaut-get-admin-classes-code)))
(defun djangonaut-get-models ()
"Execute and parse python code to get models."
(djangonaut-read (djangonaut-call djangonaut-get-models-code)))
(defun djangonaut-get-model-managers ()
"Execute and parse python code to get model managers."
(djangonaut-read (djangonaut-call djangonaut-get-model-managers-code)))
(defun djangonaut-get-migrations ()
"Execute and parse python code to get migrations."
(djangonaut-read (djangonaut-call djangonaut-get-migrations-code)))
(defun djangonaut-get-sql-functions ()
"Execute and parse python code to get sql functions."
(djangonaut-read (djangonaut-call djangonaut-get-sql-functions-code)))
(defun djangonaut-get-signal-receivers ()
"Execute and parse python code to get signal receivers."
(djangonaut-read (djangonaut-call djangonaut-get-signal-receivers-code)))
(defun djangonaut-get-drf-serializers ()
"Execute and parse python code to get drf serializers."
(djangonaut-read (djangonaut-call djangonaut-get-drf-serializers-code)))
(defun djangonaut-get-drf-permissions ()
"Execute and parse python code to get drf permissions."
(djangonaut-read (djangonaut-call djangonaut-get-drf-permissions-code)))
(defun djangonaut-get-views ()
"Execute and parse python code to get views."
(djangonaut-read (djangonaut-call djangonaut-get-views-code)))
(defun djangonaut-get-middlewares ()
"Execute and parse python code to get middlewares."
(djangonaut-read (djangonaut-call djangonaut-get-middlewares-code)))
(defun djangonaut-get-url-modules ()
"Execute and parse python code to get url modules."
(djangonaut-read (djangonaut-call djangonaut-get-url-modules-code)))
(defun djangonaut-get-forms ()
"Execute and parse python code to get forms."
(djangonaut-read (djangonaut-call djangonaut-get-forms-code)))
(defun djangonaut-get-widgets ()
"Execute and parse python code to get widgets."
(djangonaut-read (djangonaut-call djangonaut-get-widgets-code)))
(defun djangonaut-get-templates ()
"Execute and parse python code to get templates."
(djangonaut-read (djangonaut-call djangonaut-get-templates-code)))
(defun djangonaut-get-template-tags ()
"Execute and parse python code to get template tags."
(djangonaut-read (djangonaut-call djangonaut-get-template-tags-code)))
(defun djangonaut-get-template-filters ()
"Execute and parse python code to get template filters."
(djangonaut-read (djangonaut-call djangonaut-get-template-filters-code)))
(defun djangonaut-get-static-files ()
"Execute and parse python code to get static files."
(djangonaut-read (djangonaut-call djangonaut-get-static-files-code)))
(defun djangonaut-get-settings-path ()
"Execute and parse python code to get settings path."
(cdar (djangonaut-read (djangonaut-call djangonaut-get-settings-path-code))))
(defun djangonaut-run-management-command-dwim ()
"Run management command."
(interactive)
(call-interactively
(if current-prefix-arg
'djangonaut-run-popup-management-command
'djangonaut-run-management-command)))
(defun djangonaut-run-management-command (&rest command)
"Run management COMMAND in the comint buffer."
(interactive (split-string (completing-read "Command: " (djangonaut-get-commands) nil nil nil 'djangonaut-commands-history) " " t))
(let* ((buffer (get-buffer-create "*Django*"))
(process (get-buffer-process buffer)))
(when (and process (process-live-p process))
(setq buffer (generate-new-buffer "*Django*")))
(with-current-buffer buffer
(hack-dir-local-variables-non-file-buffer)
(pythonic-start-process :process "djangonaut"
:buffer buffer
:args (append (list "-m" "django") command)
:cwd (pythonic-emacs-readable-file-name (djangonaut-get-project-root))
:filter (lambda (process string)
(comint-output-filter process (ansi-color-apply string))))
(let ((inhibit-read-only t))
(erase-buffer))
(comint-mode)
(setq-local comint-prompt-read-only t)
(pop-to-buffer buffer))))
(defun djangonaut-run-popup-management-command (command)
"Run management COMMAND with arguments specified in the popup buffer."
(interactive (list (completing-read "Popup Command: " (djangonaut-get-commands) nil t nil 'djangonaut-commands-history)))
(let* ((arguments (djangonaut-get-command-arguments command))
(func-name (intern (concat "djangonaut-run-" (s-replace "_" "-" command) "-popup")))
(args-name (intern (concat "djangonaut-run-" (s-replace "_" "-" command) "-arguments")))
(popup `(magit-define-popup ,func-name ""
:switches ',(mapcar (lambda (x) (list (elt (elt x 0) 0) (elt x 1) (elt x 2)))
(cdr (assoc "switches" arguments)))
:options ',(mapcar (lambda (x) (list (elt (elt x 0) 0) (elt x 1) (elt x 2)))
(cdr (assoc "options" arguments)))
:actions '((?\ "Run" (lambda ()
(interactive)
(apply 'djangonaut-run-management-command ,command (,args-name)))))))
(func (eval popup)))
(funcall func)))
(defun djangonaut-dired-installed-apps ()
"Open application directory in the dired buffer."
(interactive)
(djangonaut-find-file #'dired "App: " (djangonaut-get-app-paths) 'djangonaut-app-paths-history))
(defun djangonaut-dired-installed-apps-other-window ()
"Open application directory in the dired buffer in the other window."
(interactive)
(djangonaut-find-file #'dired-other-window "App: " (djangonaut-get-app-paths) 'djangonaut-app-paths-history))
(defun djangonaut-find-management-command ()
"Open definition of the Django management command."
(interactive)
(djangonaut-find-file-and-line #'find-file "Command: " (djangonaut-get-command-definitions) 'djangonaut-commands-history))
(defun djangonaut-find-management-command-other-window ()
"Open definition of the Django management command in other window."
(interactive)
(djangonaut-find-file-and-line #'find-file-other-window "Command: " (djangonaut-get-command-definitions) 'djangonaut-commands-history))
(defun djangonaut-find-admin-class ()
"Open definition of the Django admin class."
(interactive)
(djangonaut-find-file-and-line #'find-file "Admin Class: " (djangonaut-get-admin-classes) 'djangonaut-admin-classes-history))
(defun djangonaut-find-admin-class-other-window ()
"Open definition of the Django admin class in the other window."
(interactive)
(djangonaut-find-file-and-line #'find-file-other-window "Admin Class: " (djangonaut-get-admin-classes) 'djangonaut-admin-classes-history))
(defun djangonaut-find-model ()
"Open definition of the Django model."
(interactive)
(djangonaut-find-file-and-line #'find-file "Model: " (djangonaut-get-models) 'djangonaut-models-history))
(defun djangonaut-find-model-other-window ()
"Open definition of the Django model in the other window."
(interactive)
(djangonaut-find-file-and-line #'find-file-other-window "Model: " (djangonaut-get-models) 'djangonaut-models-history))
(defun djangonaut-find-model-manager ()
"Open definition of the Django model manager."
(interactive)
(djangonaut-find-file-and-line #'find-file "Model Manager: " (djangonaut-get-model-managers) 'djangonaut-model-managers-history))
(defun djangonaut-find-model-manager-other-window ()
"Open definition of the Django model manager in the other window."