@tsplc/build 0.2.16 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cli.js +628 -352
  2. package/dist/cli.js.map +30 -28
  3. package/dist/index.js +548 -387
  4. package/dist/index.js.map +27 -25
  5. package/dist/libraries.js +68 -27
  6. package/dist/libraries.js.map +3 -3
  7. package/docker/Dockerfile +2 -0
  8. package/docker/Dockerfile.dockerignore +4 -1
  9. package/docker/Dockerfile.source +3 -0
  10. package/docker/config.ts +10 -5
  11. package/docker/runner.ts +140 -127
  12. package/package.json +54 -53
  13. package/python/build.py +183 -124
  14. package/python/codesys_online.py +44 -45
  15. package/python/hardware.py +9 -9
  16. package/python/test_build.py +3 -3
  17. package/python/test_codesys_online.py +18 -12
  18. package/python/test_installer_packages.py +1 -0
  19. package/python/worker.py +11 -7
  20. package/src/artifacts.ts +82 -60
  21. package/src/build.ts +71 -62
  22. package/src/cli.ts +109 -100
  23. package/src/controller-online.ts +400 -425
  24. package/src/controller-protocol.ts +140 -0
  25. package/src/controller-session.ts +466 -397
  26. package/src/device-tree.ts +19 -15
  27. package/src/diagnostics.ts +59 -49
  28. package/src/docker-build.ts +217 -156
  29. package/src/docker-context.ts +49 -27
  30. package/src/docker-run.ts +137 -111
  31. package/src/engineering-settings.ts +42 -0
  32. package/src/host/codesys-command.ts +35 -34
  33. package/src/host/codesys-host.ts +157 -129
  34. package/src/host/codesys-worker.ts +318 -301
  35. package/src/host/windows-path.ts +63 -59
  36. package/src/import-request.ts +24 -0
  37. package/src/index.ts +37 -31
  38. package/src/io.ts +152 -116
  39. package/src/libraries.ts +214 -146
  40. package/src/package-path.ts +3 -1
  41. package/src/run.ts +132 -108
  42. package/src/runtime-status.ts +25 -19
  43. package/src/sources.ts +264 -225
  44. package/src/st/declarations.ts +181 -193
  45. package/src/st/lexer.ts +102 -118
  46. package/src/st/parse.ts +193 -171
  47. package/src/st/reader.ts +47 -42
  48. package/src/__tests__/fixtures/xml/fb-simple.xml +0 -40
  49. package/src/__tests__/fixtures/xml/fb-state-machine.xml +0 -86
  50. package/src/__tests__/fixtures/xml/prg-cyclic.xml +0 -44
  51. package/src/config.ts +0 -12
@@ -5,13 +5,17 @@ import io
5
5
  import json
6
6
  import os
7
7
  import re
8
- import time
9
- from build import CompilerError, fail_on_errors, import_objects, keep_device_tree, open_template, reconcile, reported_errors
8
+ from build import (clear_diagnostics, fail_on_errors, import_source, keep_device_tree, open_template,
9
+ reported_errors, write_progress)
10
10
  from hardware import verify_pinned
11
11
  from System import Activator, AppDomain, Array, Enum, Environment, Object
12
12
  from System.Net import Dns, IPAddress
13
13
  from System.Reflection import BindingFlags, TargetInvocationException
14
14
 
15
+ # An application that was never compiled or downloaded reports this code and data ID.
16
+ EMPTY_GUID = '00000000-0000-0000-0000-000000000000'
17
+ GATEWAY_NAME = 'codesys-build'
18
+
15
19
 
16
20
  def core_application(online_application):
17
21
  # The shipped scripting wrapper omits Keep from its login switch. Its core
@@ -45,13 +49,17 @@ def session_login(core):
45
49
  raise RuntimeError('The controller does not contain this application')
46
50
 
47
51
 
48
- def controller_ids(core):
49
- ids = {'codeId': str(core.CodeId), 'dataId': str(core.DataId)}
50
- if any(value == '00000000-0000-0000-0000-000000000000' for value in ids.values()):
51
- raise RuntimeError('Controller application has no downloaded code/data identity')
52
+ def code_data_ids(compiled, missing):
53
+ ids = {'codeId': str(compiled.CodeId), 'dataId': str(compiled.DataId)}
54
+ if EMPTY_GUID in ids.values():
55
+ raise RuntimeError(missing)
52
56
  return ids
53
57
 
54
58
 
59
+ def controller_ids(core):
60
+ return code_data_ids(core, 'Controller application has no downloaded code/data identity')
61
+
62
+
55
63
  def controller_state(core):
56
64
  # Login updates IDs synchronously, but ApplicationState is timer-owned.
57
65
  # Query the original device's application-list service for a fresh state.
@@ -103,10 +111,7 @@ def consolidated_manager():
103
111
  def context_ids(context):
104
112
  if context is None:
105
113
  raise RuntimeError('Compiler context is unavailable')
106
- ids = {'codeId': str(context.CodeId), 'dataId': str(context.DataId)}
107
- if any(value == '00000000-0000-0000-0000-000000000000' for value in ids.values()):
108
- raise RuntimeError('Compiler context has no generated code/data identity')
109
- return ids
114
+ return code_data_ids(context, 'Compiler context has no generated code/data identity')
110
115
 
111
116
 
112
117
  def load_downloaded_reference(application):
@@ -119,12 +124,13 @@ def load_downloaded_reference(application):
119
124
  return context_ids(context)
120
125
 
121
126
 
122
- def fail_on_errors_after_transfer(engine, progress):
123
- """Like fail_on_errors, once the controller runs the verified application.
127
+ def report_errors_after_transfer(engine, progress):
128
+ """Reports the errors the engineering session holds once the controller runs the verified application.
124
129
 
125
- Logging in to a Linux SL controller loads its device's visualization placeholders, which
126
- nothing in a tsPLC project resolves. The application compiled without them, so the
127
- engineering session reports them rather than failing a completed transfer.
130
+ The application compiled without errors before the transfer, so these come from logging in, such
131
+ as the visualization placeholders a Linux SL controller's device loads, which nothing in a tsPLC
132
+ project resolves. Failing here would leave the controller running code the deployment never
133
+ recorded, so they are reported instead.
128
134
  """
129
135
  errors, unresolved = [], []
130
136
  for error in reported_errors(engine):
@@ -132,11 +138,11 @@ def fail_on_errors_after_transfer(engine, progress):
132
138
  if placeholder:
133
139
  unresolved.append(placeholder.group(1))
134
140
  else:
135
- errors.append(error)
141
+ errors.append(' '.join(error['text'].split()))
136
142
  if unresolved:
137
143
  progress('Ignoring library placeholders the login loaded but nothing resolves: ' + ', '.join(unresolved))
138
144
  if errors:
139
- raise CompilerError(errors)
145
+ progress('CODESYS reported after the transfer: ' + ' | '.join(errors))
140
146
 
141
147
 
142
148
  def controller_credentials(settings, credentials_file):
@@ -168,9 +174,9 @@ def connect_controller(engine, application, settings, credentials_file=None):
168
174
  device_ip = str(Dns.GetHostAddresses(settings['device']['host'])[0])
169
175
  gateways = engine.online.gateways
170
176
  # A warm worker connects for every operation, and gateway names needn't be unique.
171
- for stale in list(gateways.find_with_name('codesys-build')):
177
+ for stale in list(gateways.find_with_name(GATEWAY_NAME)):
172
178
  gateways.remove_gateway(stale)
173
- gateway = gateways.add_new_gateway('codesys-build', {0: gateway_ip, 1: settings['gateway']['port']})
179
+ gateway = gateways.add_new_gateway(GATEWAY_NAME, {0: gateway_ip, 1: settings['gateway']['port']})
174
180
  device.set_gateway_and_ip_address(gateway.guid, IPAddress.Parse(device_ip), settings['device']['port'])
175
181
  credentials = controller_credentials(settings, credentials_file)
176
182
  if credentials:
@@ -178,28 +184,29 @@ def connect_controller(engine, application, settings, credentials_file=None):
178
184
  return device, credentials
179
185
 
180
186
 
187
+ def open_operation_project(engine, request, prepared, progress):
188
+ """Returns the project, the channels it pinned, and a newly generated tree to keep once the operation works."""
189
+ if prepared is not None:
190
+ if os.path.normcase(prepared.path) == os.path.normcase(request['project']):
191
+ progress('Using the project opened ahead')
192
+ return prepared, {}, None
193
+ prepared.close()
194
+ # Operations reuse the downloaded project, which has its controller and tree; a download without one starts from the template.
195
+ if request['operation'] == 'download' and request.get('baseline') is None:
196
+ return open_template(engine, request, request['project'], request.get('devices'), request['caches'], progress)
197
+ progress('Opening project')
198
+ return engine.projects.open(request['project'], primary=True), {}, None
199
+
200
+
181
201
  def run_online(engine, request, prepared=None):
182
202
  """`prepared` is a project a warm worker opened ahead; an online change of that project uses it."""
183
203
  progress_path = request.get('progress')
184
204
  def progress(stage):
185
205
  if progress_path:
186
- with io.open(progress_path, 'a', encoding='utf-8') as output:
187
- output.write(u'{0}Z {1}\n'.format(time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime()), stage))
206
+ write_progress(progress_path, stage)
188
207
  progress('Starting; processor count {0}'.format(Environment.ProcessorCount))
189
208
  previous = request.get('baseline')
190
- # Operations reuse the downloaded project, which has its controller and tree; a download without one starts from the template.
191
- if prepared is not None and os.path.normcase(prepared.path) != os.path.normcase(request['project']):
192
- prepared.close()
193
- prepared = None
194
- if prepared is not None:
195
- progress('Using the project opened ahead')
196
- project, pinned, generated = prepared, {}, None
197
- elif request['operation'] == 'download' and previous is None:
198
- project, pinned, generated = open_template(engine, request, request['project'], request.get('devices'), request['caches'], progress)
199
- else:
200
- progress('Opening project')
201
- project = engine.projects.open(request['project'], primary=True)
202
- pinned, generated = {}, None
209
+ project, pinned, generated = open_operation_project(engine, request, prepared, progress)
203
210
  application = project.active_application
204
211
  online_app = None
205
212
  online_device = None
@@ -238,19 +245,11 @@ def run_online(engine, request, prepared=None):
238
245
  finally:
239
246
  core.Logout()
240
247
  # Only what changed since the baseline is written; a template gets every object.
241
- held = previous['objects'] if previous is not None else None
242
- gone = reconcile(application, held, request['objects']) if held is not None else []
243
- import_objects(engine, application, request, held, progress)
244
- for obj in gone:
245
- obj.remove()
246
- if request['symbols'] and not any(getattr(child, 'is_symbol_config', False) for child in application.get_children()):
247
- from System import Guid
248
- application.create_symbol_config(True, True, Guid('{0141eb75-141b-4ea1-9a8c-75f952b22a6c}'))
248
+ import_source(engine, application, request, previous['objects'] if previous is not None else None, progress)
249
249
  # Match the normal build's source/template lifecycle. Saving the edited
250
250
  # tree and clearing editor-load diagnostics happens before compilation.
251
251
  project.save()
252
- for category in engine.system.get_message_categories():
253
- engine.system.clear_messages(category)
252
+ clear_diagnostics(engine)
254
253
  if request['operation'] == 'download':
255
254
  # A full download replaces the previous compiler model. Use the
256
255
  # normal build's clean/rebuild path before opening the online session.
@@ -307,7 +306,7 @@ def run_online(engine, request, prepared=None):
307
306
  session_login(core)
308
307
  if controller_ids(core) != expected:
309
308
  raise RuntimeError('Controller did not retain the downloaded code/data identity')
310
- fail_on_errors_after_transfer(engine, progress)
309
+ report_errors_after_transfer(engine, progress)
311
310
  ids = controller_ids(core)
312
311
  state = controller_state(core)
313
312
  if state != 'run':
@@ -45,7 +45,7 @@ def host_parameters(device):
45
45
  return dict((parameter.id, parameter) for parameter in connectors[0].host_parameters)
46
46
 
47
47
 
48
- def child_device(engine, parent, spec):
48
+ def child_device(parent, spec):
49
49
  name, kind, identifier, version = spec
50
50
  parent.add(name, kind, identifier, version)
51
51
  matches = [child for child in parent.find(name, False) if getattr(child, "is_device", False)]
@@ -83,7 +83,7 @@ def settle(pinned):
83
83
  pin(channel, address)
84
84
 
85
85
 
86
- def pin_channels(engine, adapter, parameters, device):
86
+ def pin_channels(engine, parameters, device):
87
87
  """Give each raw payload byte the address of its offset, so AT declarations read it."""
88
88
  pinned = {}
89
89
  for direction, region, kind in (("inputs", "I", engine.ChannelType.Input), ("outputs", "Q", engine.ChannelType.Output)):
@@ -162,14 +162,14 @@ def add_modbus_channel(project, server, register):
162
162
  def configure_modbus(engine, project, ethernet, devices):
163
163
  """One Modbus TCP server per card with registers, with channels pinned like the EtherNet/IP bytes."""
164
164
  pinned = {}
165
- client = child_device(engine, ethernet, MODBUS_CLIENT)
165
+ client = child_device(ethernet, MODBUS_CLIENT)
166
166
  parameters = host_parameters(client)
167
167
  # The line runs unattended, so a card that restarts must come back on its own.
168
168
  set_parameter(parameters[MODBUS_AUTO_RECONNECT], "TRUE")
169
169
  # Status and request count are how the program learns a write finished.
170
170
  set_parameter(parameters[MODBUS_CHANNEL_STATUS], "TRUE")
171
171
  for device in devices:
172
- server = child_device(engine, client, (device["name"] + "_Modbus",) + MODBUS_SERVER)
172
+ server = child_device(client, (device["name"] + "_Modbus",) + MODBUS_SERVER)
173
173
  server.driver_info.always_update_variables = engine.AlwaysUpdateVariablesMode.OnlyIfUnused
174
174
  parameters = host_parameters(server)
175
175
  set_parameter(parameters[MODBUS_ADDRESS], ip_array(device["address"]))
@@ -222,26 +222,26 @@ def configure_device_tree(engine, project, tree, root, progress):
222
222
  if getattr(child, "is_device", False) and child.get_device_identification().type in (ETHERNET[1], SCANNER[1]):
223
223
  raise RuntimeError("Template already configures " + child.get_name() + "; remove it or codesys.deviceTree")
224
224
  progress("Generating EtherNet/IP device tree")
225
- ethernet = child_device(engine, controller, ETHERNET)
225
+ ethernet = child_device(controller, ETHERNET)
226
226
  parameters = host_parameters(ethernet)
227
227
  for key, identifier in ETHERNET_PARAMETERS:
228
228
  value = tree.get("ethernet", {}).get(key)
229
229
  if value is not None:
230
230
  set_parameter(parameters[identifier], string_literal(parameters[identifier], value) if key == "interface" else ip_array(value))
231
- scanner = child_device(engine, ethernet, SCANNER)
231
+ scanner = child_device(ethernet, SCANNER)
232
232
  pinned = {}
233
233
  for device in tree["devices"]:
234
234
  identity = import_device_description(engine, device, root)
235
- adapter = child_device(engine, scanner, (device["name"], identity.type, identity.id, identity.version))
235
+ adapter = child_device(scanner, (device["name"], identity.type, identity.id, identity.version))
236
236
  # CODESYS otherwise skips mapped variables no IEC code reads, such as inputs only clients observe.
237
237
  adapter.driver_info.always_update_variables = engine.AlwaysUpdateVariablesMode.OnlyIfUnused
238
238
  parameters = host_parameters(adapter)
239
239
  if device.get("address"):
240
- set_parameter(parameters[TARGET_ADDRESS], ip_array(device["address"], True))
240
+ set_parameter(parameters[TARGET_ADDRESS], ip_array(device["address"], hexadecimal=True))
241
241
  if device.get("rpiMicroseconds"):
242
242
  fields = [field for field in parameters[CONNECTION_SETTINGS] if field.identifier == "RPI"]
243
243
  set_parameter(fields[0], str(device["rpiMicroseconds"]))
244
- for address, channel in pin_channels(engine, adapter, parameters, device).items():
244
+ for address, channel in pin_channels(engine, parameters, device).items():
245
245
  if address in pinned:
246
246
  raise RuntimeError("{0} overlaps another adapter".format(address))
247
247
  pinned[address] = channel
@@ -550,7 +550,7 @@ class DeviceTreeTests(unittest.TestCase):
550
550
  "outputs": {"address": "%QB28", "size": 2},
551
551
  "comments": [{"address": "%IX17.4", "text": "Sensor"}, {"address": "%IB16", "text": "Count (2 bytes)"}],
552
552
  }
553
- pinned = pin_channels(self.engine, None, parameters, device)
553
+ pinned = pin_channels(self.engine, parameters, device)
554
554
  self.assertEqual(sorted(pinned), ["%IB16", "%IB17", "%IB18", "%QB28", "%QB29"])
555
555
  self.assertEqual([parameters[identifier].io_mapping.manual_iec_address for identifier in (100, 101, 102)], ["%IB16", "%IB17", "%IB18"])
556
556
  self.assertEqual([parameters[identifier].io_mapping.automatic_iec_address for identifier in (100, 101, 102)], [False, True, False])
@@ -570,9 +570,9 @@ class DeviceTreeTests(unittest.TestCase):
570
570
  def test_rejects_typed_channels_and_unplaced_directions(self):
571
571
  from hardware import pin_channels
572
572
  with self.assertRaisesRegex(RuntimeError, "reader inputs are not 2 raw byte channels"):
573
- pin_channels(self.engine, None, self.parameters(2, 0, 16), {"name": "reader", "inputs": {"address": "%IB0", "size": 2}})
573
+ pin_channels(self.engine, self.parameters(2, 0, 16), {"name": "reader", "inputs": {"address": "%IB0", "size": 2}})
574
574
  with self.assertRaisesRegex(RuntimeError, "reader has outputs without a configured address"):
575
- pin_channels(self.engine, None, self.parameters(0, 1), {"name": "reader"})
575
+ pin_channels(self.engine, self.parameters(0, 1), {"name": "reader"})
576
576
 
577
577
 
578
578
  if __name__ == "__main__":
@@ -23,6 +23,7 @@ with patch.dict(sys.modules, {
23
23
  IPAddress=SimpleNamespace(Parse=lambda address: address)),
24
24
  'System.Reflection': SimpleNamespace(BindingFlags=None, TargetInvocationException=TargetInvocationException),
25
25
  }):
26
+ import build
26
27
  import codesys_online
27
28
 
28
29
 
@@ -87,7 +88,6 @@ class OnlineLifecycleTests(unittest.TestCase):
87
88
  replacements = {
88
89
  'open_template': Mock(side_effect=lambda *args: self.events.append('template') or self.template),
89
90
  'keep_device_tree': Mock(),
90
- 'import_objects': Mock(side_effect=imported),
91
91
  'verify_pinned': Mock(),
92
92
  'core_application': Mock(return_value=self.core),
93
93
  'session_login': Mock(),
@@ -95,7 +95,6 @@ class OnlineLifecycleTests(unittest.TestCase):
95
95
  'controller_state': Mock(return_value='run'),
96
96
  'require_current_boot_project': Mock(),
97
97
  'load_downloaded_reference': Mock(return_value=self.ids),
98
- 'reconcile': Mock(return_value=[]),
99
98
  'generate_online_code': Mock(),
100
99
  'consolidated_manager': Mock(return_value=SimpleNamespace(GetCompileContext=Mock())),
101
100
  'context_ids': Mock(return_value=self.ids),
@@ -105,6 +104,10 @@ class OnlineLifecycleTests(unittest.TestCase):
105
104
  patcher = patch.multiple(codesys_online, **replacements)
106
105
  patcher.start()
107
106
  self.addCleanup(patcher.stop)
107
+ # build.import_source runs for real; only the steps it delegates to CODESYS are replaced.
108
+ patcher = patch.multiple(build, import_objects=Mock(side_effect=imported), reconcile=Mock(return_value=[]))
109
+ patcher.start()
110
+ self.addCleanup(patcher.stop)
108
111
  self.request = {
109
112
  'project': 'Application.project', 'operation': 'download', 'symbols': False, 'caches': 'C:\\controller',
110
113
  'objects': [], 'removeObjects': ['Visualization Manager'],
@@ -114,7 +117,7 @@ class OnlineLifecycleTests(unittest.TestCase):
114
117
 
115
118
  def test_download_rebuilds_imported_tree_before_online_login(self):
116
119
  result = codesys_online.run_online(self.engine, self.request)
117
- self.assertIsNone(codesys_online.import_objects.call_args.args[3])
120
+ self.assertIsNone(build.import_objects.call_args.args[3])
118
121
  self.assertEqual(self.events, ['template', 'import', 'clean', 'compile', 'generate', 'online-wrapper'])
119
122
  self.assertEqual(result['controllerIds'], self.ids)
120
123
  self.core.CreateBootProject.assert_called_once()
@@ -159,7 +162,7 @@ class OnlineLifecycleTests(unittest.TestCase):
159
162
  self.assertEqual(self.events, ['online-wrapper', 'import', 'compile'])
160
163
  codesys_online.open_template.assert_not_called()
161
164
  # Only what changed since the baseline is written.
162
- self.assertIs(codesys_online.import_objects.call_args.args[3], self.request['baseline']['objects'])
165
+ self.assertIs(build.import_objects.call_args.args[3], self.request['baseline']['objects'])
163
166
  self.app.clean.assert_not_called()
164
167
  self.app.rebuild.assert_not_called()
165
168
  self.app.generate_code.assert_not_called()
@@ -170,7 +173,7 @@ class OnlineLifecycleTests(unittest.TestCase):
170
173
  self.request.update(operation='online-change', baseline={
171
174
  'applicationGuid': self.app.guid, 'controllerIds': self.ids, 'objects': [],
172
175
  })
173
- codesys_online.reconcile.return_value = [SimpleNamespace(remove=lambda: self.events.append('remove'))]
176
+ build.reconcile.return_value = [SimpleNamespace(remove=lambda: self.events.append('remove'))]
174
177
  codesys_online.run_online(self.engine, self.request)
175
178
  self.assertEqual(self.events, ['online-wrapper', 'import', 'remove', 'compile'])
176
179
 
@@ -210,17 +213,20 @@ class OnlineLifecycleTests(unittest.TestCase):
210
213
  codesys_online.run_online(self.engine, self.request, self.project)
211
214
  codesys_online.open_template.assert_not_called()
212
215
  self.engine.projects.open.assert_not_called()
213
- self.assertIs(codesys_online.import_objects.call_args.args[3], self.request['baseline']['objects'])
216
+ self.assertIs(build.import_objects.call_args.args[3], self.request['baseline']['objects'])
214
217
  self.assertEqual(self.events, ['import', 'clean', 'compile', 'generate', 'online-wrapper'])
215
218
 
216
- def test_full_download_rejects_library_errors_reported_after_transfer(self):
219
+ def test_full_download_reports_errors_the_login_raises_after_transfer_and_completes(self):
217
220
  def report_library_error(core):
218
- self.messages.append(SimpleNamespace(text="Could not open library '#VisuShared'."))
221
+ self.messages.append(SimpleNamespace(text="Could not open library '#VisuShared'.\n{6d1d3e9c}"))
219
222
  codesys_online.session_login.side_effect = report_library_error
220
- with self.assertRaisesRegex(RuntimeError, "Could not open library '#VisuShared'"):
221
- codesys_online.run_online(self.engine, self.request)
222
- self.core.CreateBootProject.assert_called_once()
223
- self.project.close.assert_called_once()
223
+ with tempfile.TemporaryDirectory() as directory:
224
+ self.request['progress'] = os.path.join(directory, 'progress.log')
225
+ result = codesys_online.run_online(self.engine, self.request)
226
+ with open(self.request['progress']) as log:
227
+ self.assertIn("CODESYS reported after the transfer: Could not open library '#VisuShared'. {6d1d3e9c}",
228
+ log.read())
229
+ self.assertEqual(result['state'], 'run')
224
230
 
225
231
  def test_full_download_reports_device_placeholders_a_login_cannot_resolve(self):
226
232
  def report_unresolved_placeholder(core):
@@ -34,6 +34,7 @@ packages = {
34
34
  'CODESYS NetX 4.1.0.0': 'netx',
35
35
  'CODESYS EtherNetIP 4.9.1.0': 'ethernetip',
36
36
  'CODESYS SoftMotion 4.20.2.0': 'softmotion',
37
+ 'CODESYS Modbus 4.6.0.0': 'modbus',
37
38
  }
38
39
 
39
40
 
package/python/worker.py CHANGED
@@ -44,6 +44,16 @@ def run_build(engine, directory, loaded):
44
44
  raise
45
45
 
46
46
 
47
+ def run_controller_operation(engine, directory, loaded):
48
+ from codesys_online import run_online
49
+ prepared = loaded.pop("prepared", None)
50
+ close_loaded(loaded)
51
+ root = os.path.join(os.path.dirname(directory), "controller")
52
+ with io.open(os.path.join(root, "request.json"), encoding="utf-8") as source:
53
+ request = json.load(source)
54
+ write_json(engine, os.path.join(root, "result.json"), run_online(engine, request, prepared))
55
+
56
+
47
57
  def close_loaded(loaded):
48
58
  """Closes the project an earlier build or prepare left open."""
49
59
  for key in ("project", "prepared"):
@@ -72,13 +82,7 @@ def serve(engine, directory):
72
82
  close_loaded(loaded)
73
83
  loaded["prepared"] = engine.projects.open(command["project"], primary=True)
74
84
  elif command["action"] == "online":
75
- from codesys_online import run_online
76
- prepared = loaded.pop("prepared", None)
77
- close_loaded(loaded)
78
- root = os.path.join(os.path.dirname(directory), "controller")
79
- with io.open(os.path.join(root, "request.json"), encoding="utf-8") as source:
80
- request = json.load(source)
81
- write_json(engine, os.path.join(root, "result.json"), run_online(engine, request, prepared))
85
+ run_controller_operation(engine, directory, loaded)
82
86
  elif command["action"] == "login":
83
87
  from codesys_login import close_login, open_login, run_command
84
88
  arguments = command["arguments"]
package/src/artifacts.ts CHANGED
@@ -1,77 +1,99 @@
1
- import { copyFile, cp, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import {
2
+ copyFile,
3
+ cp,
4
+ readFile,
5
+ rename,
6
+ rm,
7
+ stat,
8
+ writeFile,
9
+ } from "node:fs/promises";
2
10
  import { resolve } from "node:path";
11
+ import { identifierPattern } from "@tsplc/iec/st";
3
12
  import { z } from "zod";
4
- import { cyclicTasksSchema } from "./config";
13
+ import { cyclicTasksSchema } from "@tsplc/config/build";
5
14
 
6
15
  export const buildFiles = {
7
- project: "Application.project",
8
- output: "runtime/Application.app",
9
- checksum: "runtime/Application.crc",
10
- receipt: "build.json",
11
- // Normalized EDS files of a generated device tree, imported by the worker.
12
- devices: "eds",
13
- // With a generated device tree: the project plus the descriptions an IDE needs.
14
- archive: "Application.projectarchive",
16
+ project: "Application.project",
17
+ output: "runtime/Application.app",
18
+ checksum: "runtime/Application.crc",
19
+ receipt: "build.json",
20
+ // Normalized EDS files of a generated device tree, imported by the worker.
21
+ devices: "eds",
22
+ // With a generated device tree: the project plus the descriptions an IDE needs.
23
+ archive: "Application.projectarchive",
15
24
  } as const;
16
25
 
17
26
  const receiptSchema = z.object({
18
- mode: z.literal("build"),
19
- application: z.string().regex(/^[A-Za-z_][A-Za-z_0-9]*$/),
20
- tasks: cyclicTasksSchema.optional(),
27
+ mode: z.literal("build"),
28
+ application: z.string().regex(identifierPattern),
29
+ tasks: cyclicTasksSchema.optional(),
21
30
  });
22
31
 
23
32
  /** A receipt is published last, after every artifact has been checked and replaced. */
24
33
  export const readBuild = async (directory: string) => {
25
- const receipt = receiptSchema.safeParse(
26
- JSON.parse(await readFile(resolve(directory, buildFiles.receipt), "utf8")),
27
- );
28
- if (!receipt.success) {
29
- throw new Error("CODESYS did not produce a valid build receipt", {
30
- cause: receipt.error,
31
- });
32
- }
33
- for (const file of [buildFiles.project, buildFiles.output, buildFiles.checksum]) {
34
- const artifact = await stat(resolve(directory, file));
35
- if (!artifact.isFile() || artifact.size === 0) {
36
- throw new Error(`CODESYS produced an empty artifact: ${file}`);
37
- }
38
- }
39
- return {
40
- ...receipt.data,
41
- directory,
42
- project: resolve(directory, buildFiles.project),
43
- output: resolve(directory, buildFiles.output),
44
- checksum: resolve(directory, buildFiles.checksum),
45
- };
34
+ const receipt = receiptSchema.safeParse(
35
+ JSON.parse(await readFile(resolve(directory, buildFiles.receipt), "utf8")),
36
+ );
37
+ if (!receipt.success) {
38
+ throw new Error("CODESYS did not produce a valid build receipt", {
39
+ cause: receipt.error,
40
+ });
41
+ }
42
+ for (const file of [
43
+ buildFiles.project,
44
+ buildFiles.output,
45
+ buildFiles.checksum,
46
+ ]) {
47
+ const artifact = await stat(resolve(directory, file));
48
+ if (!artifact.isFile() || artifact.size === 0) {
49
+ throw new Error(`CODESYS produced an empty artifact: ${file}`);
50
+ }
51
+ }
52
+ return {
53
+ ...receipt.data,
54
+ directory,
55
+ project: resolve(directory, buildFiles.project),
56
+ output: resolve(directory, buildFiles.output),
57
+ checksum: resolve(directory, buildFiles.checksum),
58
+ };
46
59
  };
47
60
 
48
61
  /** Publish a verified IDE build, with the completion receipt written last. */
49
62
  export const publishBuild = async (
50
- compiled: Awaited<ReturnType<typeof readBuild>>,
51
- outDir: string,
63
+ compiled: Awaited<ReturnType<typeof readBuild>>,
64
+ outDir: string,
52
65
  ) => {
53
- await copyFile(compiled.project, resolve(outDir, buildFiles.project));
54
- await rm(resolve(outDir, "runtime"), { recursive: true, force: true });
55
- await rename(resolve(compiled.directory, "runtime"), resolve(outDir, "runtime"));
56
- await rm(resolve(outDir, buildFiles.archive), { force: true });
57
- await cp(
58
- resolve(compiled.directory, buildFiles.archive),
59
- resolve(outDir, buildFiles.archive),
60
- ).catch((cause: unknown) => {
61
- if (!(cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT"))
62
- throw cause;
63
- });
64
- await writeFile(
65
- resolve(outDir, buildFiles.receipt),
66
- JSON.stringify(
67
- {
68
- mode: "build",
69
- application: compiled.application,
70
- ...(compiled.tasks && { tasks: compiled.tasks }),
71
- },
72
- null,
73
- 2,
74
- ),
75
- );
76
- return readBuild(outDir);
66
+ await copyFile(compiled.project, resolve(outDir, buildFiles.project));
67
+ await rm(resolve(outDir, "runtime"), { recursive: true, force: true });
68
+ await rename(
69
+ resolve(compiled.directory, "runtime"),
70
+ resolve(outDir, "runtime"),
71
+ );
72
+ await rm(resolve(outDir, buildFiles.archive), { force: true });
73
+ await cp(
74
+ resolve(compiled.directory, buildFiles.archive),
75
+ resolve(outDir, buildFiles.archive),
76
+ ).catch((cause: unknown) => {
77
+ if (!(
78
+ cause &&
79
+ typeof cause === "object" &&
80
+ "code" in cause &&
81
+ cause.code === "ENOENT"
82
+ )) {
83
+ throw cause;
84
+ }
85
+ });
86
+ await writeFile(
87
+ resolve(outDir, buildFiles.receipt),
88
+ JSON.stringify(
89
+ {
90
+ mode: "build",
91
+ application: compiled.application,
92
+ ...(compiled.tasks && { tasks: compiled.tasks }),
93
+ },
94
+ null,
95
+ 2,
96
+ ),
97
+ );
98
+ return readBuild(outDir);
77
99
  };