1
1
#!/usr/bin/env python
2
- import os
3
- import sys
4
2
import logging
5
- import datetime
6
3
import logging .handlers
4
+ import os
5
+ import sys
7
6
7
+ from pathlib import Path
8
8
9
9
logger = logging .getLogger (__name__ )
10
10
LOG_SIZE = 50 * (10 ** 6 ) # about 50 MB
11
11
LOG_COUNT = 5
12
- LOG_FILE = os .path .join (os .path .dirname (__file__ ), 'manage.log' )
13
12
14
- CONF_FILE = os .path .join (os .path .dirname (__file__ ), 'project.conf' )
13
+ THIS = Path (__file__ ).resolve ()
14
+ THIS_DIR = THIS .parent
15
+ LOG_FILE = THIS_DIR / 'manage.log'
16
+ CONF_FILE = THIS_DIR / 'project.conf'
15
17
16
18
17
- def activate_help ():
18
- import yaml
19
- with open (CONF_FILE ) as f :
20
- instance_name = yaml .load (f )['INSTANCE_NAME' ]
21
- return (
22
- 'ERROR: snodas.settings could not be imported.\n '
23
- 'It looks like you need to activate the conda environment '
24
- 'for this instance, which you can do by running '
25
- '`activate {}`' .format (instance_name )
26
- )
19
+ ACTIVATE_HELP : str = (
20
+ 'ERROR: snodas.settings could not be imported.\n '
21
+ 'It looks like you need to activate the proper conda/virtual environment.'
22
+ )
27
23
28
24
29
25
def install (help = False ):
30
- this_dir = os .path .dirname (os .path .realpath (__file__ ))
31
26
# first we append the path with the management package
32
27
# so we can import utils in the install module
33
- sys .path .append (
34
- os .path .join (
35
- this_dir ,
36
- 'snodas' ,
37
- 'management' ,
38
- )
39
- )
28
+ sys .path .append (str (THIS_DIR / 'snodas' / 'management' ))
29
+
40
30
# then we add the commands package to the path
41
31
# so we have access to the install module
42
- sys .path .append (
43
- os .path .join (
44
- this_dir ,
45
- 'snodas' ,
46
- 'management' ,
47
- 'commands' ,
48
- )
49
- )
32
+ sys .path .append (str (THIS_DIR / 'snodas' / 'management' / 'commands' ))
33
+
50
34
# and lastly we add the directory of this file
51
35
# to the path so we can import from setup.py
52
- sys .path .append (
53
- os .path .join (
54
- this_dir ,
55
- )
56
- )
57
- from install import Install
36
+ sys .path .append (str (THIS_DIR ))
37
+
38
+ from install import Install # type: ignore
39
+
58
40
if help :
59
41
Install .print_help (sys .argv [0 ], sys .argv [2 ])
60
42
else :
61
43
Install .run_from_argv (sys .argv )
62
44
63
45
64
46
def default_django_command ():
65
- os .environ .setdefault ("DJANGO_SETTINGS_MODULE" , "snodas.settings" )
47
+ from importlib .util import find_spec
48
+
49
+ os .environ .setdefault ('DJANGO_SETTINGS_MODULE' , 'snodas.settings' )
66
50
67
51
# check to make sure we can import the settings
68
52
# otherwise, we suspect the env has not been activated
@@ -71,14 +55,12 @@ def default_django_command():
71
55
# activated and this would not prevent execution. I should
72
56
# do some sort of more advanced check of the settings to verify that
73
57
# they match the current project.
74
- try :
75
- import snodas .settings
76
- except ImportError :
58
+ if find_spec ('snodas.settings' ) is None :
77
59
logger .debug (
78
- ' snodas.settings couldn\ ' t be imported; '
79
- 'looks like the correct env is not activated'
60
+ " snodas.settings couldn't be imported; "
61
+ 'looks like the correct env is not activated' ,
80
62
)
81
- print (activate_help ())
63
+ print (ACTIVATE_HELP ) # noqa: T201
82
64
return 1
83
65
84
66
# hacky workaround to allow snodas command to use the
@@ -89,20 +71,23 @@ def default_django_command():
89
71
# which fails either because snodas cannot be found, or
90
72
# sondas is found, and it is the snodas package in the
91
73
# current directory.)
92
- if len (sys .argv ) > 1 and \
93
- sys .argv [1 ] == 'runserver' and \
94
- not ('--help' in sys .argv or '-h' in sys .argv ):
74
+ if (
75
+ len (sys .argv ) > 1
76
+ and sys .argv [1 ] == 'runserver'
77
+ and not ('--help' in sys .argv or '-h' in sys .argv )
78
+ ):
95
79
logger .debug (
96
- 'rewritting sys.argv[0] from {} to {}' .format (
97
- sys .argv [0 ],
98
- __file__ ,
99
- )
80
+ 'rewritting sys.argv[0] from %s to %s' ,
81
+ sys .argv [0 ],
82
+ __file__ ,
100
83
)
101
84
sys .argv [0 ] = __file__
102
85
103
- from django .core .management import execute_from_command_line
86
+ from django .core .management import execute_from_command_line # type: ignore
87
+
104
88
logger .debug (
105
- 'executing from the command line with sys.argv: {}' .format (sys .argv )
89
+ 'executing from the command line with sys.argv: %s' ,
90
+ sys .argv ,
106
91
)
107
92
return execute_from_command_line (sys .argv )
108
93
@@ -114,41 +99,40 @@ def main():
114
99
backupCount = (LOG_COUNT - 1 ),
115
100
)
116
101
formatter = logging .Formatter (
117
- '%(asctime)s %(name)s [%(levelname)-5s] %(message)s'
102
+ '%(asctime)s %(name)s [%(levelname)-5s] %(message)s' ,
118
103
)
119
104
manage_log .setFormatter (formatter )
120
105
logger .setLevel (logging .DEBUG )
121
106
logger .addHandler (manage_log )
122
- #logging.basicConfig(
123
- # filename=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'manage_%s_%d.log' %(datetime.datetime.now().strftime('%y%m%d_%H%M%S'), os.getpid())),
124
- # filemode='w',
125
- # format='%(asctime)s [%(levelname)-5s] %(message)s',
126
- # level=logging.DEBUG,
127
- #)
128
107
129
108
if len (sys .argv ) > 1 and sys .argv [1 ] == 'install' :
130
109
logger .debug ('install command run' )
131
110
return install ()
132
- if len (sys .argv ) > 1 and \
133
- os .path .basename (sys .argv [0 ]) == 'manage.py' and \
134
- sys .argv [1 ] == 'help' and \
135
- sys .argv [2 ] == 'install' :
111
+
112
+ if (
113
+ len (sys .argv ) > 1
114
+ and Path (sys .argv [0 ]).name == 'manage.py'
115
+ and sys .argv [1 ] == 'help'
116
+ and sys .argv [2 ] == 'install'
117
+ ):
136
118
logger .debug ('install help run' )
137
119
return install (help = True )
138
- elif not os .path .isfile (CONF_FILE ):
139
- logger .error ('config file could not be loaded: {}' .format (CONF_FILE ))
140
- print ('ERROR: Could not find configuration file {}.' .format (CONF_FILE ))
141
- print ('Has this instance been installed? '
142
- 'Try running `python manage.py install`.' )
143
- else :
144
- try :
145
- return default_django_command ()
146
- except Exception as e :
147
- logger .exception (e )
148
- raise
149
- # before I was returning -1, but I don't know why anymore
150
- return - 1
120
+
121
+ if not CONF_FILE .is_file ():
122
+ logger .error ('config file could not be loaded: %s' , CONF_FILE )
123
+ print (f'ERROR: Could not find configuration file { CONF_FILE } .' ) # noqa: T201
124
+ print ( # noqa: T201
125
+ 'Has this instance been installed? '
126
+ 'Try running `python manage.py install`.' ,
127
+ )
128
+ return None
129
+
130
+ try :
131
+ return default_django_command ()
132
+ except Exception :
133
+ logger .exception ('Failure running CLI' )
134
+ raise
151
135
152
136
153
- if __name__ == " __main__" :
137
+ if __name__ == ' __main__' :
154
138
sys .exit (main ())
0 commit comments