-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathtasks.py
More file actions
2421 lines (1922 loc) · 72.7 KB
/
tasks.py
File metadata and controls
2421 lines (1922 loc) · 72.7 KB
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 datetime
import json
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
import time
from functools import wraps
from pathlib import Path
from platform import python_version
from typing import Optional
import invoke
from invoke import Collection, task
from invoke.exceptions import UnexpectedExit
def safe_value(fnc):
"""Helper function to safely get value from function, catching import exceptions."""
try:
return fnc()
except (ModuleNotFoundError, ImportError):
return wrap_color('N/A', '93') # Yellow color for "Not Available"
def is_true(x):
"""Shortcut function to determine if a value "looks" like a boolean."""
return str(x).strip().lower() in ['1', 'y', 'yes', 't', 'true', 'on']
def is_devcontainer_environment():
"""Check if the InvenTree environment is running in a development container."""
return is_true(os.environ.get('INVENTREE_DEVCONTAINER', 'False'))
def is_docker_environment():
"""Check if the InvenTree environment is running in a Docker container."""
return is_true(os.environ.get('INVENTREE_DOCKER', 'False'))
def is_rtd_environment():
"""Check if the InvenTree environment is running on ReadTheDocs."""
return is_true(os.environ.get('READTHEDOCS', 'False'))
def is_debug_environment():
"""Check if the InvenTree environment is running in a debug environment."""
return is_true(os.environ.get('INVENTREE_DEBUG', 'False')) or is_true(
os.environ.get('RUNNER_DEBUG', 'False')
)
def get_django_version():
"""Return the current Django version."""
from src.backend.InvenTree.InvenTree.version import (
inventreeDjangoVersion, # type: ignore[import]
)
return safe_value(inventreeDjangoVersion)
def get_inventree_version():
"""Return the current InvenTree version."""
from src.backend.InvenTree.InvenTree.version import (
inventreeVersion, # type: ignore[import]
)
return safe_value(inventreeVersion)
def get_inventree_api_version():
"""Return the current InvenTree API version."""
from src.backend.InvenTree.InvenTree.version import (
inventreeApiVersion, # type: ignore[import]
)
return safe_value(inventreeApiVersion)
def get_commit_hash():
"""Return the current git commit hash."""
from src.backend.InvenTree.InvenTree.version import (
inventreeCommitHash, # type: ignore[import]
)
return safe_value(inventreeCommitHash)
def get_commit_date():
"""Return the current git commit date."""
from src.backend.InvenTree.InvenTree.version import (
inventreeCommitDate, # type: ignore[import]
)
return safe_value(inventreeCommitDate)
def get_version_vals():
"""Get values from the VERSION file."""
version_file = local_dir().joinpath('VERSION')
if not version_file.exists():
return {}
try:
from dotenv import dotenv_values
return dotenv_values(version_file)
except ImportError:
error(
'ERROR: dotenv package not installed. You might not be running in the right environment.'
)
return {}
def is_pkg_installer(content: Optional[dict] = None, load_content: bool = False):
"""Check if the current environment is a package installer by VERSION/environment."""
if load_content:
content = get_version_vals()
return get_installer(content) == 'PKG'
def is_pkg_installer_by_path():
"""Check if the current environment is a package installer by checking the path."""
return len(sys.argv) >= 1 and sys.argv[0].startswith(
'/opt/inventree/env/bin/invoke'
)
def get_installer(content: Optional[dict] = None):
"""Get the installer for the current environment or a content dict."""
if content is None:
content = dict(os.environ)
return content.get('INVENTREE_PKG_INSTALLER')
# region execution logging helpers
def task_exception_handler(t, v, tb):
"""Handle exceptions raised by tasks.
The intent here is to provide more 'useful' error messages when tasks fail.
"""
sys.__excepthook__(t, v, tb)
if t is ModuleNotFoundError:
mod_name = str(v).split(' ')[-1].strip("'")
error(f'Error importing required module: {mod_name}')
warning('- Ensure the correct Python virtual environment is active')
warning(
'- Ensure that the invoke tool is installed in the active Python environment'
)
warning(
"- Ensure all required packages are installed by running 'invoke install'"
)
sys.excepthook = task_exception_handler
def wrap_color(text: str, color: str) -> str:
"""Wrap text in a color code."""
return f'\033[{color}m{text}\033[0m'
def success(*args):
"""Print a success message to the console."""
msg = ' '.join(map(str, args))
print(wrap_color(msg, '92'))
def error(*args):
"""Print an error message to the console."""
msg = ' '.join(map(str, args))
print(wrap_color(msg, '91'))
def warning(*args):
"""Print a warning message to the console."""
msg = ' '.join(map(str, args))
print(wrap_color(msg, '93'))
def info(*args):
"""Print an informational message to the console."""
msg = ' '.join(map(str, args))
print(wrap_color(msg, '94'))
def state_logger(fn=None, method_name=None):
"""Decorator to log state markers before/after function execution, optionally accepting arguments."""
def decorator(func):
func.method_name = method_name or func.__name__
@wraps(func)
def wrapped(c, *args, **kwargs):
do_log = is_debug_environment()
if do_log:
info(f'# task | {func.method_name} | start')
t1 = time.time()
try:
func(c, *args, **kwargs)
except KeyboardInterrupt:
error('INVE-W15: Process interrupted by user.')
sys.exit(1)
except UnexpectedExit:
error(f"Task '{func.method_name}' failed with an error.")
raise
t2 = time.time()
if do_log:
info(f'# task | {func.method_name} | done | elapsed: {t2 - t1:.2f}s')
return wrapped
if fn and callable(fn):
return decorator(fn)
elif fn and isinstance(fn, str):
method_name = fn
return decorator
# endregion
# region environment checks
def envcheck_invoke_version():
"""Check that the installed invoke version meets minimum requirements."""
MIN_INVOKE_VERSION: str = '2.0.0'
min_version = tuple(map(int, MIN_INVOKE_VERSION.split('.')))
invoke_version = tuple(map(int, invoke.__version__.split('.'))) # noqa: RUF048
if invoke_version < min_version:
error(f'The installed invoke version ({invoke.__version__}) is not supported!')
error(f'InvenTree requires invoke version {MIN_INVOKE_VERSION} or above')
sys.exit(1)
def envcheck_invoke_path():
"""Check that the path of the used invoke is correct."""
if is_docker_environment() or is_rtd_environment():
return
invoke_path: Path = Path(invoke.__file__)
env_path: Path = Path(sys.prefix).resolve()
loc_path: Path = Path(__file__).parent.resolve()
if not invoke_path.is_relative_to(loc_path) and not invoke_path.is_relative_to(
env_path
):
error('INVE-E2 - Wrong Invoke Path')
error(
f'The invoke tool `{invoke_path}` is not correctly located, ensure you are using the invoke installed in an environment in `{loc_path}` or `{env_path}`'
)
sys.exit(1)
def envcheck_python_version():
"""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: int = 3
REQ_MINOR: int = 9
version = sys.version.split(' ')[0]
valid: bool = 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:
error(f'The installed python version ({version}) is not supported!')
error(f'InvenTree requires Python {REQ_MAJOR}.{REQ_MINOR} or above')
sys.exit(1)
def envcheck_invoke_cmd():
"""Checks if the rights invoke command for the current environment is used."""
first_cmd = sys.argv[0].replace(sys.prefix, '')
intendded = ['/bin/invoke', '/bin/inv']
correct_cmd: Optional[str] = None
if is_rtd_environment() or is_docker_environment() or is_devcontainer_environment():
return # Skip invoke command check for Docker/RTD/DevContainer environments
elif is_pkg_installer(load_content=True) and not is_pkg_installer_by_path():
correct_cmd = 'inventree run invoke'
else:
warning('Unknown environment, not checking used invoke command')
if first_cmd not in intendded:
correct_cmd = correct_cmd if correct_cmd else 'invoke'
error('INVE-W9 - Wrong Invoke Environment')
error(
f'The detected invoke command `{first_cmd}` is not the intended one for this environment, ensure you are using one of the following command(s) `{correct_cmd}`'
)
def main():
"""Main function to check the execution environment."""
envcheck_invoke_version()
envcheck_python_version()
envcheck_invoke_path()
envcheck_invoke_cmd()
# endregion
def builtin_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_email: bool = False,
allow_plugins: bool = True,
allow_session: bool = True,
allow_sso: bool = True,
allow_tokens: bool = True,
):
"""Returns a list of content types to exclude from import / export.
Arguments:
allow_auth (bool): Allow user authentication data to be exported / imported
allow_email (bool): Allow email log data to be exported / imported
allow_plugins (bool): Allow plugin information to be exported / imported
allow_session (bool): Allow user session data to be exported / imported
allow_sso (bool): Allow SSO tokens to be exported / imported
allow_tokens (bool): Allow 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.dataoutput',
'common.newsfeedentry',
'common.notificationentry',
'common.notificationmessage',
'importer.dataimportsession',
'importer.dataimportcolumnmap',
'importer.dataimportrow',
]
# Optional exclude email message logs
if not allow_email:
excludes.extend(['common.emailmessage', 'common.emailthread'])
# Optionally exclude user auth data
if not allow_auth:
excludes.extend(['auth.group', 'auth.user', 'users.userprofile'])
# Optionally exclude user token information
if not allow_tokens:
excludes.extend(['users.apitoken'])
# Optionally exclude plugin information
if not allow_plugins:
excludes.extend([
'plugin.pluginconfig',
'plugin.pluginsetting',
'plugin.pluginusersetting',
])
# Optionally exclude SSO application information
if not allow_sso:
excludes.extend(['socialaccount.socialapp', 'socialaccount.socialtoken'])
# Optionally exclude user session information
if not allow_session:
excludes.extend(['sessions.session', 'usersessions.usersession'])
return ' '.join([f'--exclude {e}' for e in excludes])
# region file helpers
def local_dir() -> 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 manage_py_dir():
"""Returns the directory of the manage.py file."""
return local_dir().joinpath('src', 'backend', 'InvenTree')
def manage_py_path():
"""Return the path of the manage.py file."""
return manage_py_dir().joinpath('manage.py')
def _frontend_info():
"""Return the path of the frontend info directory."""
return manage_py_dir().joinpath('web', 'static', 'web', '.vite')
def version_target_pth():
"""Return the path of the target version file."""
return _frontend_info().joinpath('tag.txt')
def version_sha_pth():
"""Return the path of the SHA version file."""
return _frontend_info().joinpath('sha.txt')
def version_source_pth():
"""Return the path of the source version file."""
return _frontend_info().joinpath('source.txt')
# endregion
if __name__ in ['__main__', 'tasks']:
main()
def run(
c, cmd, path: Optional[Path] = None, pty: bool = False, hide: bool = 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.
hide (bool, optional): Hide the command output. Defaults to False.
env (dict, optional): Environment variables to pass to the command. Defaults to None.
"""
env = env or {}
path = path or local_dir()
try:
result = c.run(f'cd "{path}" && {cmd}', pty=pty, env=env, hide=hide)
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
return result
def manage(c, cmd, pty: bool = False, env=None, verbose: bool = False, **kwargs):
"""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.
verbose (bool, optional): Print verbose output from the command. Defaults to False.
"""
if verbose:
info(f'Running command: python3 manage.py {cmd}')
cmd += ' -v 1'
else:
cmd += ' -v 0'
return run(
c, f'python3 manage.py {cmd}', manage_py_dir(), pty=pty, env=env, **kwargs
)
def installed_apps(c) -> list[str]:
"""Returns a list of all installed apps, including plugins."""
result = manage(c, 'list_apps', pty=False, hide=True)
output = result.stdout.strip()
# Look for the expected pattern
match = re.findall(r'>>> (.*) <<<', output)
if not match:
raise ValueError(f"Unexpected output from 'list_apps' command: {output}")
return match[0].split(',')
def run_install(
c,
uv: bool,
install_file: Path,
run_preflight=True,
version_check=False,
pinned=True,
verbose: bool = False,
):
"""Run the installation of python packages from a requirements file.
Arguments:
c: Command line context.
uv: Whether to use UV (experimental package manager) instead of pip.
install_file: Path to the requirements file to install from.
run_preflight: Whether to run the preflight installation step (installing pip/uv itself). Default is True.
version_check: Whether to check for a version-specific requirements file. Default is False.
pinned: Whether to use the --require-hashes option when installing packages. Default is True.
verbose: Whether to print verbose output from pip install commands. Default is False.
"""
if version_check:
# Test if there is a version specific requirements file
sys_ver_s = python_version().split('.')
sys_string = f'{sys_ver_s[0]}.{sys_ver_s[1]}'
install_file_vers = install_file.parent.joinpath(
f'{install_file.stem}-{sys_string}{install_file.suffix}'
)
if install_file_vers.exists():
install_file = install_file_vers
info(f"Using version-specific requirements file '{install_file_vers}'")
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:
# Optionally run preflight first
if run_preflight:
run(
c,
f'pip3 install --no-cache-dir --disable-pip-version-check -U pip setuptools {"" if verbose else "--quiet"}',
)
info('Installed package manager')
run(
c,
f'pip3 install --no-cache-dir --disable-pip-version-check -U {"--require-hashes" if pinned else ""} -r {install_file} {"" if verbose else "--quiet"}',
)
else:
if run_preflight:
run(
c,
f'pip3 install --no-cache-dir --disable-pip-version-check -U uv setuptools {"" if verbose else "--quiet"}',
)
info('Installed package manager')
run(
c,
f'uv pip install -U {"--require-hashes" if pinned else ""} -r {install_file} {"" if verbose else "--quiet"}',
)
def yarn(c, cmd):
"""Runs a given command against the yarn package manager.
Args:
c: Command line context.
cmd: Yarn command to run.
"""
path = local_dir().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:
warning(
'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)
@state_logger
def check_file_existence(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']:
error('Cancelled export operation')
sys.exit(1)
@task(help={'verbose': 'Print verbose output from the command'})
@state_logger
def wait(c, verbose: bool = False):
"""Wait until the database connection is ready."""
return manage(c, 'wait_for_db', verbose=verbose)
# Install tasks
# region tasks
@task(
help={
'uv': 'Use UV (experimental package manager)',
'verbose': 'Print verbose output from installation commands',
}
)
@state_logger
def plugins(c, uv: bool = False, verbose: bool = False):
"""Installs all plugins as specified in 'plugins.txt'."""
from src.backend.InvenTree.InvenTree.config import ( # type: ignore[import]
get_plugin_file,
)
run_install(
c, uv, get_plugin_file(), run_preflight=False, pinned=False, verbose=verbose
)
# Collect plugin static files
manage(c, 'collectplugins', verbose=verbose)
@task(
help={
'uv': 'Use UV package manager (experimental)',
'skip_plugins': 'Skip plugin installation',
'dev': 'Install development requirements instead of production requirements',
'verbose': 'Print verbose output from pip install commands',
}
)
@state_logger
def install(
c,
uv: bool = False,
skip_plugins: bool = False,
dev: bool = False,
verbose: bool = False,
):
"""Install required python packages for InvenTree.
Arguments:
c: Command line context.
uv: Use UV package manager (experimental) instead of pip. Default is False.
skip_plugins: Skip plugin installation. Default is False.
dev: Install development requirements instead of production requirements. Default is False.
verbose: Print verbose output from pip install commands. Default is False.
"""
info('Installing required python packages...')
if dev:
run_install(
c,
uv,
local_dir().joinpath('src/backend/requirements-dev.txt'),
version_check=True,
verbose=verbose,
)
success('Dependency installation complete')
return
# Ensure path is relative to *this* directory
run_install(
c,
uv,
local_dir().joinpath('src/backend/requirements.txt'),
version_check=True,
verbose=verbose,
)
# Run plugins install
if not skip_plugins:
plugins(c, uv=uv, verbose=verbose)
# Compile license information
lic_path = manage_py_dir().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',
'verbose': 'Print verbose output from commands',
}
)
def setup_dev(c, tests: bool = False, verbose: bool = False):
"""Sets up everything needed for the dev environment."""
# Install required Python packages with PIP
install(c, uv=False, skip_plugins=True, dev=True, verbose=verbose)
# Install pre-commit hook
info('Installing pre-commit for checks before git commits...')
run(c, 'pre-commit install')
run(c, 'pre-commit autoupdate')
success('pre-commit set up complete')
# Set up test-data if flag is set
if tests:
setup_test(c, verbose=verbose)
# Setup / maintenance tasks
@task
def shell(c):
"""Launch a Django shell."""
manage(c, 'shell', pty=True)
@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."""
from src.backend.InvenTree.InvenTree.config import ( # type: ignore[import]
get_media_dir,
)
info(f'Rebuilding image thumbnails in {get_media_dir()}')
manage(c, 'rebuild_thumbnails', pty=True)
@task
@state_logger
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",
'username': "username of the user who's MFA should be disabled",
}
)
def remove_mfa(c, mail='', username=''):
"""Remove MFA for a user."""
if not mail and not username:
warning('You must provide a users mail or username')
return
manage(c, f'remove_mfa --mail {mail} --username {username}')
@task(
help={
'frontend': 'Build the frontend',
'clear': 'Remove existing static files',
'skip_plugins': 'Ignore collection of plugin static files',
}
)
@state_logger
def static(c, frontend=False, clear=True, skip_plugins=False):
"""Copies required static files to the STATIC_ROOT directory, as per Django requirements."""
if frontend and node_available():
frontend_compile(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(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_compile(c, extract=True)
# Update static files
if not ignore_static:
static(c)
success('Translation files built successfully')
@task(help={'verbose': 'Print verbose output'})
@state_logger('backend_trans')
def backend_trans(c, verbose: bool = False):
"""Compile backend Django translation files."""
info('Compiling backend translations...')
manage(c, 'compilemessages', verbose=verbose)
success('Backend translations compiled successfully')
@task(
help={
'clean': 'Clean up old backup files',
'compress': 'Compress the backup files',
'encrypt': 'Encrypt the backup files (requires GPG recipient to be set)',
'path': 'Specify path for generated backup files (leave blank for default path)',
'quiet': 'Suppress informational output (only show errors)',
'skip_db': 'Skip database backup step (only backup media files)',
'skip_media': 'Skip media backup step (only backup database files)',
}
)
@state_logger
def backup(
c,
clean: bool = False,
compress: bool = True,
encrypt: bool = False,
path=None,
quiet: bool = False,
skip_db: bool = False,
skip_media: bool = False,
):
"""Backup the database and media files."""
cmd = '--noinput -v 2'
if compress:
cmd += ' --compress'
if encrypt:
cmd += ' --encrypt'
# A path to the backup dir can be specified here
# If not specified, the default backup dir is used
if path:
path = Path(path)
if not os.path.isabs(path):
path = local_dir().joinpath(path).resolve()
cmd += f' -O {path}'
if clean:
cmd += ' --clean'
if quiet:
cmd += ' --quiet'
if skip_db:
info('Skipping database backup...')
else:
info('Backing up InvenTree database...')
manage(c, f'dbbackup {cmd}')
if skip_media:
info('Skipping media backup...')
else:
info('Backing up InvenTree media files...')
manage(c, f'mediabackup {cmd}')
if not skip_db or not skip_media:
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)',
'decrypt': 'Decrypt the backup files (requires GPG recipient to be set)',
'media_file': 'Specify filename of compressed media archive (leave blank to use most recent backup)',
'skip_db': 'Do not import database archive (media restore only)',
'skip_media': 'Do not import media archive (database restore only)',
'uncompress': 'Uncompress the backup files before restoring (default behavior)',
'restore_allow_newer_version': 'Allow restore from a newer version backup (use with caution)',
}
)
def restore(
c,
path=None,
db_file=None,
media_file=None,
decrypt: bool = False,
skip_db: bool = False,
skip_media: bool = False,
uncompress: bool = True,
restore_allow_newer_version: bool = False,
):
"""Restore the database and media files."""
base_cmd = '--noinput -v 2'
env = {}
if restore_allow_newer_version:
env['INVENTREE_BACKUP_RESTORE_ALLOW_NEWER_VERSION'] = 'True'
if uncompress:
base_cmd += ' --uncompress'
if decrypt:
base_cmd += ' --decrypt'
if path:
# Resolve the provided path
path = Path(path)
if not os.path.isabs(path):
path = local_dir().joinpath(path).resolve()
base_cmd += f' -I {path}'
if skip_db:
info('Skipping database archive...')
else:
info('Restoring InvenTree database')
cmd = f'dbrestore {base_cmd}'
if db_file:
cmd += f' -i {db_file}'
manage(c, cmd, env=env)
if skip_media:
info('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, env=env)