-
-
Notifications
You must be signed in to change notification settings - Fork 791
/
tasks.py
1572 lines (1240 loc) · 45.3 KB
/
tasks.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
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
"""Tasks for automating certain actions and interacting with InvenTree from the CLI."""
import json
import os
import pathlib
import re
import shutil
import subprocess
import sys
from pathlib import Path
from platform import python_version
from typing import Optional
from invoke import Collection, task
from invoke.exceptions import UnexpectedExit
def success(*args):
"""Print a success message to the console."""
msg = ' '.join(map(str, args))
print(f'\033[92m{msg}\033[0m')
def error(*args):
"""Print an error message to the console."""
msg = ' '.join(map(str, args))
print(f'\033[91m{msg}\033[0m')
def warning(*args):
"""Print a warning message to the console."""
msg = ' '.join(map(str, args))
print(f'\033[93m{msg}\033[0m')
def info(*args):
"""Print an informational message to the console."""
msg = ' '.join(map(str, args))
print(f'\033[94m{msg}\033[0m')
def checkPythonVersion():
"""Check that the installed python version meets minimum requirements.
If the python version is not sufficient, exits with a non-zero exit code.
"""
REQ_MAJOR = 3
REQ_MINOR = 9
version = sys.version.split(' ')[0]
valid = True
if sys.version_info.major < REQ_MAJOR or (
sys.version_info.major == REQ_MAJOR and sys.version_info.minor < REQ_MINOR
):
valid = False
if not valid:
print(f'The installed python version ({version}) is not supported!')
print(f'InvenTree requires Python {REQ_MAJOR}.{REQ_MINOR} or above')
sys.exit(1)
if __name__ in ['__main__', 'tasks']:
checkPythonVersion()
def apps():
"""Returns a list of installed apps."""
return [
'build',
'common',
'company',
'importer',
'machine',
'order',
'part',
'report',
'stock',
'users',
'plugin',
'InvenTree',
'generic',
'machine',
'web',
]
def content_excludes(
allow_auth: bool = True,
allow_tokens: bool = True,
allow_plugins: bool = True,
allow_sso: bool = True,
):
"""Returns a list of content types to exclude from import/export.
Arguments:
allow_tokens (bool): Allow tokens to be exported/importe
allow_plugins (bool): Allow plugin information to be exported/imported
allow_sso (bool): Allow SSO tokens to be exported/imported
"""
excludes = [
'contenttypes',
'auth.permission',
'error_report.error',
'admin.logentry',
'django_q.schedule',
'django_q.task',
'django_q.ormq',
'exchange.rate',
'exchange.exchangebackend',
'common.notificationentry',
'common.notificationmessage',
'user_sessions.session',
'importer.dataimportsession',
'importer.dataimportcolumnmap',
'importer.dataimportrow',
'report.labeloutput',
'report.reportoutput',
]
# Optionally exclude user auth data
if not allow_auth:
excludes.append('auth.group')
excludes.append('auth.user')
# Optionally exclude user token information
if not allow_tokens:
excludes.append('users.apitoken')
# Optionally exclude plugin information
if not allow_plugins:
excludes.append('plugin.pluginconfig')
excludes.append('plugin.pluginsetting')
# Optionally exclude SSO application information
if not allow_sso:
excludes.append('socialaccount.socialapp')
excludes.append('socialaccount.socialtoken')
return ' '.join([f'--exclude {e}' for e in excludes])
def localDir() -> Path:
"""Returns the directory of *THIS* file.
Used to ensure that the various scripts always run
in the correct directory.
"""
return Path(__file__).parent.resolve()
def managePyDir():
"""Returns the directory of the manage.py file."""
return localDir().joinpath('src', 'backend', 'InvenTree')
def managePyPath():
"""Return the path of the manage.py file."""
return managePyDir().joinpath('manage.py')
def run(c, cmd, path: Optional[Path] = None, pty=False, env=None):
"""Runs a given command a given path.
Args:
c: Command line context.
cmd: Command to run.
path: Path to run the command in.
pty (bool, optional): Run an interactive session. Defaults to False.
"""
env = env or {}
path = path or localDir()
try:
c.run(f'cd "{path}" && {cmd}', pty=pty, env=env)
except UnexpectedExit as e:
error(f"ERROR: InvenTree command failed: '{cmd}'")
warning('- Refer to the error messages in the log above for more information')
raise e
def manage(c, cmd, pty: bool = False, env=None):
"""Runs a given command against django's "manage.py" script.
Args:
c: Command line context.
cmd: Django command to run.
pty (bool, optional): Run an interactive session. Defaults to False.
env (dict, optional): Environment variables to pass to the command. Defaults to None.
"""
run(c, f'python3 manage.py {cmd}', managePyDir(), pty, env)
def yarn(c, cmd):
"""Runs a given command against the yarn package manager.
Args:
c: Command line context.
cmd: Yarn command to run.
"""
path = localDir().joinpath('src', 'frontend')
run(c, cmd, path, False)
def node_available(versions: bool = False, bypass_yarn: bool = False):
"""Checks if the frontend environment (ie node and yarn in bash) is available."""
def ret(val, val0=None, val1=None):
if versions:
return val, val0, val1
return val
def check(cmd):
try:
return str(
subprocess.check_output([cmd], stderr=subprocess.STDOUT, shell=True),
encoding='utf-8',
).strip()
except subprocess.CalledProcessError:
return None
except FileNotFoundError:
return None
yarn_version = check('yarn --version')
node_version = check('node --version')
# Either yarn is available or we don't care about yarn
yarn_passes = bypass_yarn or yarn_version
# Print a warning if node is available but yarn is not
if node_version and not yarn_passes:
print(
'Node is available but yarn is not. Install yarn if you wish to build the frontend.'
)
# Return the result
return ret(yarn_passes and node_version, node_version, yarn_version)
def check_file_existance(filename: Path, overwrite: bool = False):
"""Checks if a file exists and asks the user if it should be overwritten.
Args:
filename (str): Name of the file to check.
overwrite (bool, optional): Overwrite the file without asking. Defaults to False.
"""
if filename.is_file() and overwrite is False:
response = input(
'Warning: file already exists. Do you want to overwrite? [y/N]: '
)
response = str(response).strip().lower()
if response not in ['y', 'yes']:
print('Cancelled export operation')
sys.exit(1)
# Install tasks
@task(help={'uv': 'Use UV (experimental package manager)'})
def plugins(c, uv=False):
"""Installs all plugins as specified in 'plugins.txt'."""
from src.backend.InvenTree.InvenTree.config import get_plugin_file
plugin_file = get_plugin_file()
info(f"Installing plugin packages from '{plugin_file}'")
# Install the plugins
if not uv:
run(c, f"pip3 install --disable-pip-version-check -U -r '{plugin_file}'")
else:
run(c, 'pip3 install --no-cache-dir --disable-pip-version-check uv')
run(c, f"uv pip install -r '{plugin_file}'")
# Collect plugin static files
manage(c, 'collectplugins')
@task(
help={
'uv': 'Use UV package manager (experimental)',
'skip_plugins': 'Skip plugin installation',
}
)
def install(c, uv=False, skip_plugins=False):
"""Installs required python packages."""
# Ensure path is relative to *this* directory
INSTALL_FILE = localDir().joinpath('src/backend/requirements.txt')
info(f"Installing required python packages from '{INSTALL_FILE}'")
if not Path(INSTALL_FILE).is_file():
raise FileNotFoundError(f"Requirements file '{INSTALL_FILE}' not found")
# Install required Python packages with PIP
if not uv:
run(
c,
'pip3 install --no-cache-dir --disable-pip-version-check -U pip setuptools',
)
run(
c,
f'pip3 install --no-cache-dir --disable-pip-version-check -U --require-hashes -r {INSTALL_FILE}',
)
else:
run(
c,
'pip3 install --no-cache-dir --disable-pip-version-check -U uv setuptools',
)
run(c, f'uv pip install -U --require-hashes -r {INSTALL_FILE}')
# Run plugins install
if not skip_plugins:
plugins(c, uv=uv)
# Compile license information
lic_path = managePyDir().joinpath('InvenTree', 'licenses.txt')
run(
c,
f'pip-licenses --format=json --with-license-file --no-license-path > {lic_path}',
)
success('Dependency installation complete')
@task(help={'tests': 'Set up test dataset at the end'})
def setup_dev(c, tests=False):
"""Sets up everything needed for the dev environment."""
info("Installing required python packages from 'src/backend/requirements-dev.txt'")
# Install required Python packages with PIP
run(c, 'pip3 install -U --require-hashes -r src/backend/requirements-dev.txt')
# Install pre-commit hook
info('Installing pre-commit for checks before git commits...')
run(c, 'pre-commit install')
# Update all the hooks
run(c, 'pre-commit autoupdate')
success('pre-commit set up complete')
# Set up test-data if flag is set
if tests:
setup_test(c)
# Setup / maintenance tasks
@task
def superuser(c):
"""Create a superuser/admin account for the database."""
manage(c, 'createsuperuser', pty=True)
@task
def rebuild_models(c):
"""Rebuild database models with MPTT structures."""
info('Rebuilding internal database structures')
manage(c, 'rebuild_models', pty=True)
@task
def rebuild_thumbnails(c):
"""Rebuild missing image thumbnails."""
info('Rebuilding image thumbnails')
manage(c, 'rebuild_thumbnails', pty=True)
@task
def clean_settings(c):
"""Clean the setting tables of old settings."""
info('Cleaning old settings from the database')
manage(c, 'clean_settings')
success('Settings cleaned successfully')
@task(help={'mail': "mail of the user who's MFA should be disabled"})
def remove_mfa(c, mail=''):
"""Remove MFA for a user."""
if not mail:
warning('You must provide a users mail')
return
manage(c, f'remove_mfa {mail}')
@task(
help={
'frontend': 'Build the frontend',
'clear': 'Remove existing static files',
'skip_plugins': 'Ignore collection of plugin static files',
}
)
def static(c, frontend=False, clear=True, skip_plugins=False):
"""Copies required static files to the STATIC_ROOT directory, as per Django requirements."""
manage(c, 'prerender')
if frontend and node_available():
frontend_trans(c)
frontend_build(c)
info('Collecting static files...')
cmd = 'collectstatic --no-input --verbosity 0'
if clear:
cmd += ' --clear'
manage(c, cmd)
# Collect plugin static files
if not skip_plugins:
manage(c, 'collectplugins')
success('Static files collected successfully')
@task
def translate_stats(c):
"""Collect translation stats.
The file generated from this is needed for the UI.
"""
# Recompile the translation files (.mo)
# We do not run 'invoke dev.translate' here, as that will touch the source (.po) files too!
try:
manage(c, 'compilemessages', pty=True)
except Exception:
warning('WARNING: Translation files could not be compiled:')
path = managePyDir().joinpath('script', 'translation_stats.py')
run(c, f'python3 {path}')
@task(post=[translate_stats])
def translate(c, ignore_static=False, no_frontend=False):
"""Rebuild translation source files. Advanced use only!
Note: This command should not be used on a local install,
it is performed as part of the InvenTree translation toolchain.
"""
info('Building translation files')
# Translate applicable .py / .html / .js files
manage(c, 'makemessages --all -e py,html,js --no-wrap')
manage(c, 'compilemessages')
if not no_frontend and node_available():
frontend_install(c)
frontend_trans(c)
frontend_build(c)
# Update static files
if not ignore_static:
static(c)
success('Translation files built successfully')
@task(
help={
'clean': 'Clean up old backup files',
'path': 'Specify path for generated backup files (leave blank for default path)',
}
)
def backup(c, clean=False, path=None):
"""Backup the database and media files."""
info('Backing up InvenTree database...')
cmd = '--noinput --compress -v 2'
if path:
# Resolve the provided path
path = Path(path)
if not os.path.isabs(path):
path = localDir().joinpath(path).resolve()
cmd += f' -O {path}'
if clean:
cmd += ' --clean'
manage(c, f'dbbackup {cmd}')
info('Backing up InvenTree media files...')
manage(c, f'mediabackup {cmd}')
success('Backup completed successfully')
@task(
help={
'path': 'Specify path to locate backup files (leave blank for default path)',
'db_file': 'Specify filename of compressed database archive (leave blank to use most recent backup)',
'media_file': 'Specify filename of compressed media archive (leave blank to use most recent backup)',
'ignore_media': 'Do not import media archive (database restore only)',
'ignore_database': 'Do not import database archive (media restore only)',
}
)
def restore(
c,
path=None,
db_file=None,
media_file=None,
ignore_media=False,
ignore_database=False,
):
"""Restore the database and media files."""
base_cmd = '--noinput --uncompress -v 2'
if path:
# Resolve the provided path
path = Path(path)
if not os.path.isabs(path):
path = localDir().joinpath(path).resolve()
base_cmd += f' -I {path}'
if ignore_database:
print('Skipping database archive...')
else:
info('Restoring InvenTree database')
cmd = f'dbrestore {base_cmd}'
if db_file:
cmd += f' -i {db_file}'
manage(c, cmd)
if ignore_media:
print('Skipping media restore...')
else:
info('Restoring InvenTree media files')
cmd = f'mediarestore {base_cmd}'
if media_file:
cmd += f' -i {media_file}'
manage(c, cmd)
@task(post=[rebuild_models, rebuild_thumbnails])
def migrate(c):
"""Performs database migrations.
This is a critical step if the database schema have been altered!
"""
info('Running InvenTree database migrations...')
# Run custom management command which wraps migrations in "maintenance mode"
manage(c, 'makemigrations')
manage(c, 'runmigrations', pty=True)
manage(c, 'migrate --run-syncdb')
manage(c, 'remove_stale_contenttypes --include-stale-apps --no-input', pty=True)
success('InvenTree database migrations completed')
@task(help={'app': 'Specify an app to show migrations for (leave blank for all apps)'})
def showmigrations(c, app=''):
"""Show the migration status of the database."""
manage(c, f'showmigrations {app}', pty=True)
@task(
post=[clean_settings, translate_stats],
help={
'skip_backup': 'Skip database backup step (advanced users)',
'frontend': 'Force frontend compilation/download step (ignores INVENTREE_DOCKER)',
'no_frontend': 'Skip frontend compilation/download step',
'skip_static': 'Skip static file collection step',
'uv': 'Use UV (experimental package manager)',
},
)
def update(
c,
skip_backup: bool = False,
frontend: bool = False,
no_frontend: bool = False,
skip_static: bool = False,
uv: bool = False,
):
"""Update InvenTree installation.
This command should be invoked after source code has been updated,
e.g. downloading new code from GitHub.
The following tasks are performed, in order:
- install
- backup (optional)
- migrate
- frontend_compile or frontend_download (optional)
- static (optional)
- clean_settings
- translate_stats
"""
info('Updating InvenTree installation...')
# Ensure required components are installed
install(c, uv=uv)
if not skip_backup:
backup(c)
# Perform database migrations
migrate(c)
# Stop here if we are not building/downloading the frontend
# If:
# - INVENTREE_DOCKER is set (by the docker image eg.) and not overridden by `--frontend` flag
# - `--no-frontend` flag is set
if (os.environ.get('INVENTREE_DOCKER', False) and not frontend) or no_frontend:
print('Skipping frontend update!')
frontend = False
no_frontend = True
else:
info('Updating frontend...')
# Decide if we should compile the frontend or try to download it
if node_available(bypass_yarn=True):
frontend_compile(c)
else:
frontend_download(c)
if not skip_static:
static(c, frontend=not no_frontend)
success('InvenTree update complete!')
# Data tasks
@task(
help={
'filename': "Output filename (default = 'data.json')",
'overwrite': 'Overwrite existing files without asking first (default = False)',
'include_permissions': 'Include user and group permissions in the output file (default = False)',
'include_tokens': 'Include API tokens in the output file (default = False)',
'exclude_plugins': 'Exclude plugin data from the output file (default = False)',
'include_sso': 'Include SSO token data in the output file (default = False)',
'retain_temp': 'Retain temporary files (containing permissions) at end of process (default = False)',
}
)
def export_records(
c,
filename='data.json',
overwrite=False,
include_permissions=False,
include_tokens=False,
exclude_plugins=False,
include_sso=False,
retain_temp=False,
):
"""Export all database records to a file.
Write data to the file defined by filename.
If --overwrite is not set, the user will be prompted about overwriting an existing files.
If --include-permissions is not set, the file defined by filename will have permissions specified for a user or group removed.
If --delete-temp is not set, the temporary file (which includes permissions) will not be deleted. This file is named filename.tmp
For historical reasons, calling this function without any arguments will thus result in two files:
- data.json: does not include permissions
- data.json.tmp: includes permissions
If you want the script to overwrite any existing files without asking, add argument -o / --overwrite.
If you only want one file, add argument - d / --delete-temp.
If you want only one file, with permissions, then additionally add argument -i / --include-permissions
"""
# Get an absolute path to the file
target = Path(filename)
if not target.is_absolute():
target = localDir().joinpath(filename).resolve()
info(f"Exporting database records to file '{target}'")
check_file_existance(target, overwrite)
tmpfile = f'{target}.tmp'
excludes = content_excludes(
allow_tokens=include_tokens,
allow_plugins=not exclude_plugins,
allow_sso=include_sso,
)
cmd = f"dumpdata --natural-foreign --indent 2 --output '{tmpfile}' {excludes}"
# Dump data to temporary file
manage(c, cmd, pty=True)
info('Running data post-processing step...')
# Post-process the file, to remove any "permissions" specified for a user or group
with open(tmpfile, encoding='utf-8') as f_in:
data = json.loads(f_in.read())
data_out = []
if include_permissions is False:
for entry in data:
model_name = entry.get('model', None)
# Ignore any temporary settings (start with underscore)
if model_name in ['common.inventreesetting', 'common.inventreeusersetting']:
if entry['fields'].get('key', '').startswith('_'):
continue
if model_name == 'auth.group':
entry['fields']['permissions'] = []
if model_name == 'auth.user':
entry['fields']['user_permissions'] = []
data_out.append(entry)
# Write the processed data to file
with open(target, 'w', encoding='utf-8') as f_out:
f_out.write(json.dumps(data_out, indent=2))
if not retain_temp:
print('Removing temporary files')
os.remove(tmpfile)
success('Data export completed')
@task(
help={
'filename': 'Input filename',
'clear': 'Clear existing data before import',
'retain_temp': 'Retain temporary files at end of process (default = False)',
},
post=[rebuild_models, rebuild_thumbnails],
)
def import_records(
c, filename='data.json', clear: bool = False, retain_temp: bool = False
):
"""Import database records from a file."""
# Get an absolute path to the supplied filename
target = Path(filename)
if not target.is_absolute():
target = localDir().joinpath(filename)
if not target.exists():
error(f"ERROR: File '{target}' does not exist")
sys.exit(1)
if clear:
delete_data(c, force=True)
info(f"Importing database records from '{target}'")
# We need to load 'auth' data (users / groups) *first*
# This is due to the users.owner model, which has a ContentType foreign key
authfile = f'{target}.auth.json'
# Pre-process the data, to remove any "permissions" specified for a user or group
datafile = f'{target}.data.json'
with open(target, encoding='utf-8') as f_in:
try:
data = json.loads(f_in.read())
except json.JSONDecodeError as exc:
error(f'ERROR: Failed to decode JSON file: {exc}')
sys.exit(1)
auth_data = []
load_data = []
for entry in data:
if 'model' in entry:
# Clear out any permissions specified for a group
if entry['model'] == 'auth.group':
entry['fields']['permissions'] = []
# Clear out any permissions specified for a user
if entry['model'] == 'auth.user':
entry['fields']['user_permissions'] = []
# Save auth data for later
if entry['model'].startswith('auth.'):
auth_data.append(entry)
else:
load_data.append(entry)
else:
warning('WARNING: Invalid entry in data file')
print(entry)
# Write the auth file data
with open(authfile, 'w', encoding='utf-8') as f_out:
f_out.write(json.dumps(auth_data, indent=2))
# Write the processed data to the tmp file
with open(datafile, 'w', encoding='utf-8') as f_out:
f_out.write(json.dumps(load_data, indent=2))
excludes = content_excludes(allow_auth=False)
# Import auth models first
info('Importing user auth data...')
cmd = f"loaddata '{authfile}'"
manage(c, cmd, pty=True)
# Import everything else next
info('Importing database records...')
cmd = f"loaddata '{datafile}' -i {excludes}"
manage(c, cmd, pty=True)
if not retain_temp:
info('Removing temporary files')
os.remove(datafile)
os.remove(authfile)
info('Data import completed')
@task
def delete_data(c, force=False):
"""Delete all database records!
Warning: This will REALLY delete all records in the database!!
"""
info('Deleting all data from InvenTree database...')
if force:
manage(c, 'flush --noinput')
else:
manage(c, 'flush')
@task(post=[rebuild_models, rebuild_thumbnails])
def import_fixtures(c):
"""Import fixture data into the database.
This command imports all existing test fixture data into the database.
Warning:
- Intended for testing / development only!
- Running this command may overwrite existing database data!!
- Don't say you were not warned...
"""
fixtures = [
# Build model
'build',
# Common models
'settings',
# Company model
'company',
'price_breaks',
'supplier_part',
# Order model
'order',
# Part model
'bom',
'category',
'params',
'part',
'test_templates',
# Stock model
'location',
'stock_tests',
'stock',
# Users
'users',
]
command = 'loaddata ' + ' '.join(fixtures)
manage(c, command, pty=True)
# Execution tasks
@task
def wait(c):
"""Wait until the database connection is ready."""
info('Waiting for database connection...')
return manage(c, 'wait_for_db')
@task(
pre=[wait],
help={
'address': 'Server address:port (default=0.0.0.0:8000)',
'workers': 'Specify number of worker threads (override config file)',
},
)
def gunicorn(c, address='0.0.0.0:8000', workers=None):
"""Launch a gunicorn webserver.
Note: This server will not auto-reload in response to code changes.
"""
config_file = localDir().joinpath('contrib', 'container', 'gunicorn.conf.py')
cmd = (
f'gunicorn -c {config_file} InvenTree.wsgi -b {address} --chdir {managePyDir()}'
)
if workers:
cmd += f' --workers={workers}'
info(f'Starting Gunicorn Server: {cmd}')
run(c, cmd, pty=True)
@task(pre=[wait], help={'address': 'Server address:port (default=127.0.0.1:8000)'})
def server(c, address='127.0.0.1:8000'):
"""Launch a (development) server using Django's in-built webserver.
Note: This is *not* sufficient for a production installation.
"""
manage(c, f'runserver {address}', pty=True)
@task(pre=[wait])
def worker(c):
"""Run the InvenTree background worker process."""
manage(c, 'qcluster', pty=True)
# Testing tasks
@task
def render_js_files(c):
"""Render templated javascript files (used for static testing)."""
manage(c, 'test InvenTree.ci_render_js')
@task(post=[translate_stats, static, server])
def test_translations(c):
"""Add a fictional language to test if each component is ready for translations."""
import django
from django.conf import settings
# setup django
base_path = Path.cwd()
new_base_path = pathlib.Path('InvenTree').resolve()
sys.path.append(str(new_base_path))
os.chdir(new_base_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'InvenTree.settings')
django.setup()
# Add language
info('Add dummy language...')
manage(c, 'makemessages -e py,html,js --no-wrap -l xx')
# change translation
info('Fill in dummy translations...')
file_path = pathlib.Path(settings.LOCALE_PATHS[0], 'xx', 'LC_MESSAGES', 'django.po')
new_file_path = str(file_path) + '_new'
# compile regex
reg = re.compile(
r'[a-zA-Z0-9]{1}' # match any single letter and number
+ r'(?![^{\(\<]*[}\)\>])' # that is not inside curly brackets, brackets or a tag
+ r'(?<![^\%][^\(][)][a-z])' # that is not a specially formatted variable with singles
+ r'(?![^\\][\n])' # that is not a newline
)
last_string = ''
# loop through input file lines
with open(file_path, encoding='utf-8') as file_org:
with open(new_file_path, 'w', encoding='utf-8') as file_new:
for line in file_org:
if line.startswith('msgstr "'):
# write output -> replace regex matches with x in the read in (multi)string
file_new.write(f'msgstr "{reg.sub("x", last_string[7:-2])}"\n')
last_string = '' # reset (multi)string
elif line.startswith('msgid "'):
last_string = (
last_string + line
) # a new translatable string starts -> start append
file_new.write(line)
else:
if last_string:
last_string = (
last_string + line
) # a string is being read in -> continue appending
file_new.write(line)
# change out translation files
file_path.rename(str(file_path) + '_old')
new_file_path.rename(file_path)
# compile languages
info('Compile languages ...')
manage(c, 'compilemessages')
# reset cwd
os.chdir(base_path)
# set env flag
os.environ['TEST_TRANSLATIONS'] = 'True'
@task(
help={
'disable_pty': 'Disable PTY',
'runtest': 'Specify which tests to run, in format <module>.<file>.<class>.<method>',