comparison libervia/server/tasks/implicit/task_js_modules.py @ 1254:780dbc2f4853

server (tasks): new `js_modules` implicit task: /!\ either `yarn` (preferred) or `npm` (fallback) is a new dependency This task will install JS modules specified in `browser_meta.js` using either `yarn` or `npm`. A mapping for Brython can also be specified in browser metadata, in this case Python modules will be created and put in the `js_modules` python package.
author Goffi <goffi@goffi.org>
date Wed, 29 Apr 2020 17:39:11 +0200
parents
children 0b269d4a46a3
comparison
equal deleted inserted replaced
1253:6d49fae517ba 1254:780dbc2f4853
1 #!/ur/bin/env python3
2
3 import json
4 from pathlib import Path
5 from sat.core.i18n import _
6 from sat.core.log import getLogger
7 from sat.core import exceptions
8 from libervia.server.constants import Const as C
9 from libervia.server.tasks import task
10
11
12 log = getLogger(__name__)
13
14
15 class Task(task.Task):
16
17 async def prepare(self):
18 if "js" not in self.resource.browser_modules:
19 raise exceptions.CancelError(f"No JS module needed")
20
21 async def start(self):
22 js_data = self.resource.browser_modules['js']
23 package = js_data.get('package', {})
24 package_path = self.build_path / 'package.json'
25 with package_path.open('w') as f:
26 json.dump(package, f)
27
28 try:
29 cmd = self.findCommand('yarn')
30 except exceptions.NotFound:
31 cmd = self.findCommand('npm')
32 await self.runCommand(cmd, 'install', path=str(self.build_path))
33
34 try:
35 brython_map = js_data['brython_map']
36 except KeyError:
37 pass
38 else:
39 log.info(_("creating JS modules mapping for Brython"))
40 js_modules_path = self.build_path / 'js_modules'
41 js_modules_path.mkdir(exist_ok=True)
42 init_path = js_modules_path / '__init__.py'
43 init_path.touch()
44
45 for module_name, module_data in brython_map.items():
46 log.debug(f"generating mapping for {module_name}")
47 if ' ' in module_name:
48 raise ValueError(
49 f"module {module_name!r} has space(s), it must not!")
50 module_path = js_modules_path / f"{module_name}.py"
51 if isinstance(module_data, str):
52 module_data = {'path': module_data}
53 try:
54 js_path = module_data.pop('path')
55 except KeyError:
56 raise ValueError(
57 f'module data for {module_name} must have a "path" key')
58 module_data['path'] = Path('node_modules') / js_path.strip(' /')
59 export = module_data.get('export') or [module_name]
60 export_objects = '\n'.join(f'{e} = window.{e}' for e in export)
61
62 with module_path.open('w') as f:
63 f.write(f"""\
64 #!/usr/bin/env python3
65 from browser import window, load
66 {module_data.get('extra_import', '')}
67
68 load("{Path('/').joinpath(C.BUILD_DIR, module_data['path'])}")
69 {export_objects}
70 {module_data.get('extra_init', '')}
71 """)