python-fitparse 2.10.0__tar.gz → 2.12.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-fitparse
3
- Version: 2.10.0
3
+ Version: 2.12.0
4
4
  Summary: Python library to parse ANT/Garmin .FIT files
5
5
  Project-URL: Homepage, https://github.com/nbr23/python-fitparse
6
6
  Project-URL: Repository, https://github.com/nbr23/python-fitparse
@@ -65,6 +65,9 @@ class DeveloperDataMixin:
65
65
  field_name = message.get_raw_value('field_name')
66
66
  units = message.get_raw_value("units")
67
67
  native_field_num = message.get_raw_value('native_field_num')
68
+ native_mesg_num = message.get_raw_value('native_mesg_num')
69
+ scale = message.get_raw_value('scale')
70
+ offset = message.get_raw_value('offset')
68
71
 
69
72
  for name, value in (('developer_data_index', dev_data_index),
70
73
  ('field_definition_number', field_def_num),
@@ -76,6 +79,10 @@ class DeveloperDataMixin:
76
79
  field_name = "unnamed_dev_field_%s" % field_def_num
77
80
  if not isinstance(units, str):
78
81
  units = None
82
+ if not isinstance(scale, int):
83
+ scale = None
84
+ if not isinstance(offset, int):
85
+ offset = None
79
86
  base_type = BASE_TYPES.get(base_type_id)
80
87
  if base_type is None:
81
88
  warnings.warn(
@@ -102,6 +109,9 @@ class DeveloperDataMixin:
102
109
  type=base_type,
103
110
  name=field_name,
104
111
  units=units,
112
+ scale=scale,
113
+ offset=offset,
114
+ native_mesg_num=native_mesg_num,
105
115
  native_field_num=native_field_num
106
116
  )
107
117
 
@@ -139,11 +149,14 @@ class DeveloperDataMixin:
139
149
  class FitFileDecoder(DeveloperDataMixin):
140
150
  """Basic decoder for fit files"""
141
151
 
142
- def __init__(self, fileish, *args, check_crc=True, data_processor=None, **kwargs):
152
+ def __init__(self, fileish, *args, check_crc=True, allow_truncated=False, data_processor=None, **kwargs):
143
153
  self._file = fileish_open(fileish, 'rb')
144
154
 
145
155
  self.check_crc = check_crc
156
+ self.allow_truncated = allow_truncated
157
+ self.truncated = None
146
158
  self._crc = None
159
+ self._in_header = False
147
160
 
148
161
  # Get total filesize
149
162
  self._file.seek(0, os.SEEK_END)
@@ -198,11 +211,12 @@ class FitFileDecoder(DeveloperDataMixin):
198
211
  return unpacked if (len(unpacked) > 1) or always_tuple else unpacked[0]
199
212
 
200
213
  def _read_and_assert_crc(self, allow_zero=False):
201
- # CRC Calculation is little endian from SDK
202
- # TODO - How to handle the case of unterminated file? Error out and have user retry with check_crc=false?
203
- crc_computed, crc_read = self._crc.value, self._read_struct(Crc.FMT)
204
214
  if not self.check_crc:
215
+ # A missing or short CRC at the end of the file is tolerated when checking is off
216
+ self._file.read(struct.calcsize(Crc.FMT))
205
217
  return
218
+ # CRC Calculation is little endian from SDK
219
+ crc_computed, crc_read = self._crc.value, self._read_struct(Crc.FMT)
206
220
  if crc_computed == crc_read or (allow_zero and crc_read == 0):
207
221
  return
208
222
  raise FitCRCError('CRC Mismatch [computed: {}, read: {}]'.format(
@@ -221,6 +235,7 @@ class FitFileDecoder(DeveloperDataMixin):
221
235
  self._crc = Crc()
222
236
  self._local_mesgs = {}
223
237
 
238
+ segment_start = self._file.tell()
224
239
  header_data = self._read(12)
225
240
  if header_data[8:12] != b'.FIT':
226
241
  raise FitHeaderError("Invalid .FIT File Header")
@@ -248,12 +263,26 @@ class FitFileDecoder(DeveloperDataMixin):
248
263
 
249
264
  # After we've consumed the header, set the bytes left to be read
250
265
  self._bytes_left = data_size
266
+ self._segment_end = segment_start + header_size + data_size + struct.calcsize(Crc.FMT)
251
267
 
252
268
  def _parse_message(self):
269
+ try:
270
+ return self._read_message()
271
+ except FitEOFError as e:
272
+ if not (self.allow_truncated and self._truncated()):
273
+ raise
274
+ self.truncated = e
275
+ self._complete = True
276
+ self.close()
277
+ return None
278
+
279
+ def _truncated(self):
280
+ return self._in_header or self._filesize < self._segment_end
281
+
282
+ def _read_message(self):
253
283
  # When done, calculate the CRC and return None
254
284
  if self._bytes_left <= 0:
255
- # Don't assert CRC if requested not
256
- if not self._complete and self.check_crc:
285
+ if not self._complete:
257
286
  self._read_and_assert_crc()
258
287
 
259
288
  if self._file.tell() >= self._filesize:
@@ -262,8 +291,10 @@ class FitFileDecoder(DeveloperDataMixin):
262
291
  return None
263
292
 
264
293
  # Still have data left in the file - assuming chained fit files
294
+ self._in_header = True
265
295
  self._parse_file_header()
266
- return self._parse_message()
296
+ self._in_header = False
297
+ return self._read_message()
267
298
 
268
299
  header = self._parse_message_header()
269
300
 
@@ -319,19 +350,12 @@ class FitFileDecoder(DeveloperDataMixin):
319
350
  )
320
351
  base_type = BASE_TYPE_BYTE
321
352
 
322
- # If the field has components that are accumulators
323
- # start recording their accumulation at 0
324
- if field and field.components:
325
- for component in field.components:
326
- if component.accumulate:
327
- accumulators = self._accumulators.setdefault(global_mesg_num, {})
328
- accumulators[component.def_num] = 0
329
-
330
353
  field_defs.append(FieldDefinition(
331
354
  field=field,
332
355
  def_num=field_def_num,
333
356
  base_type=base_type,
334
357
  size=field_size,
358
+ unpacker=self._field_unpacker(endian, base_type, field_size),
335
359
  ))
336
360
 
337
361
  dev_field_defs = []
@@ -344,8 +368,9 @@ class FitFileDecoder(DeveloperDataMixin):
344
368
  field=field,
345
369
  dev_data_index=dev_data_index,
346
370
  def_num=field_def_num,
347
- size=field_size
348
- ))
371
+ size=field_size,
372
+ unpacker=self._field_unpacker(endian, field.type, field_size),
373
+ ))
349
374
 
350
375
  def_mesg = DefinitionMessage(
351
376
  header=header,
@@ -358,24 +383,32 @@ class FitFileDecoder(DeveloperDataMixin):
358
383
  self._local_mesgs[header.local_mesg_num] = def_mesg
359
384
  return def_mesg
360
385
 
386
+ @staticmethod
387
+ def _field_unpacker(endian, base_type, size):
388
+ # Struct to read n base types (field def size / base type size)
389
+ count = int(size / base_type.size)
390
+ return struct.Struct(endian + str(count) + base_type.fmt) if count > 0 else None
391
+
361
392
  def _parse_raw_values_from_data_message(self, def_mesg):
362
393
  # Go through mesg's field defs and read them
363
394
  raw_values = []
364
395
  for field_def in def_mesg.field_defs + def_mesg.dev_field_defs:
365
396
  base_type = field_def.base_type
366
397
  is_byte = base_type.name == 'byte'
367
- # Struct to read n base types (field def size / base type size)
368
- struct_fmt = str(int(field_def.size / base_type.size)) + base_type.fmt
398
+ unpacker = field_def.unpacker
399
+ if unpacker is None:
400
+ raise FitParseError("Invalid struct format: %s0%s" % (def_mesg.endian, base_type.fmt))
369
401
 
370
- # Extract the raw value, ask for a tuple if it's a byte type
371
402
  try:
372
- raw_value = self._read_struct(
373
- struct_fmt, endian=def_mesg.endian, always_tuple=is_byte,
374
- )
403
+ raw_value = unpacker.unpack(self._read(unpacker.size))
375
404
  except FitEOFError:
405
+ if self.allow_truncated:
406
+ raise
376
407
  # file was suddenly terminated
377
408
  warnings.warn("File was terminated unexpectedly, some data will not be loaded.")
378
409
  break
410
+ if len(raw_value) == 1 and not is_byte:
411
+ raw_value = raw_value[0]
379
412
 
380
413
  # If the field returns with a tuple of values it's definitely an
381
414
  # oddball, but we'll parse it on a per-value basis it.
@@ -390,20 +423,39 @@ class FitFileDecoder(DeveloperDataMixin):
390
423
  return raw_values
391
424
 
392
425
  @staticmethod
393
- def _resolve_subfield(field, def_mesg, raw_values):
426
+ def _resolve_subfield(field, ref_values):
394
427
  # Resolve into (field, parent) ie (subfield, field) or (field, None)
395
428
  if field.subfields:
396
429
  for sub_field in field.subfields:
397
- # Go through reference fields for this sub field
398
430
  for ref_field in sub_field.ref_fields:
399
- # Go through field defs AND their raw values
400
- for field_def, raw_value in zip(def_mesg.field_defs, raw_values):
401
- # If there's a definition number AND raw value match on the
402
- # reference field, then we return this subfield
403
- if (field_def.def_num == ref_field.def_num) and (ref_field.raw_value == raw_value):
404
- return sub_field, field
431
+ if ref_values.get(ref_field.def_num) == ref_field.raw_value:
432
+ return sub_field, field
405
433
  return field, None
406
434
 
435
+ def _reference_values(self, def_mesg, raw_values):
436
+ ref_values = {
437
+ field_def.def_num: raw_value
438
+ for field_def, raw_value in zip(def_mesg.field_defs, raw_values)
439
+ if raw_value is not None
440
+ }
441
+ native = dict(ref_values)
442
+ for field_def, raw_value in zip(def_mesg.field_defs, raw_values):
443
+ if not field_def.field:
444
+ continue
445
+ field, _ = self._resolve_subfield(field_def.field, native)
446
+ # Accumulating components are skipped so this pass leaves the accumulators
447
+ # alone; references are enums, which never accumulate.
448
+ for component in field.components or ():
449
+ if component.accumulate:
450
+ continue
451
+ try:
452
+ cmp_raw_value = component.render(raw_value)
453
+ except ValueError:
454
+ continue
455
+ if cmp_raw_value is not None:
456
+ ref_values.setdefault(component.def_num, self._apply_scale_offset(component, cmp_raw_value))
457
+ return ref_values
458
+
407
459
  def _apply_scale_offset(self, field, raw_value):
408
460
  # Apply numeric transformations (scale+offset)
409
461
  if isinstance(raw_value, tuple):
@@ -427,6 +479,58 @@ class FitFileDecoder(DeveloperDataMixin):
427
479
 
428
480
  return base_value
429
481
 
482
+ def _expand_components(self, def_mesg, field, raw_value, ref_values, field_datas, path):
483
+ for component in field.components or ():
484
+ # Render its raw value
485
+ try:
486
+ cmp_raw_value = component.render(raw_value)
487
+ except ValueError:
488
+ continue
489
+
490
+ # Apply accumulated value
491
+ if component.accumulate and cmp_raw_value is not None:
492
+ accumulator = self._accumulators.setdefault(def_mesg.mesg_num, {})
493
+ cmp_raw_value = self._apply_compressed_accumulation(
494
+ cmp_raw_value, accumulator.get(component.def_num, 0), component.bits,
495
+ )
496
+ accumulator[component.def_num] = cmp_raw_value
497
+
498
+ # Apply scale and offset from component, not from the dynamic field
499
+ # as they may differ
500
+ cmp_raw_value = self._apply_scale_offset(component, cmp_raw_value)
501
+
502
+ # Extract the component's dynamic field from def_mesg
503
+ cmp_field = def_mesg.mesg_type.fields[component.def_num]
504
+
505
+ # Resolve a possible subfield
506
+ cmp_field, cmp_parent_field = self._resolve_subfield(cmp_field, ref_values)
507
+ cmp_value = cmp_field.render(cmp_raw_value)
508
+
509
+ # Plop it on field_datas
510
+ field_datas.append(
511
+ FieldData(
512
+ field_def=None,
513
+ field=cmp_field,
514
+ parent_field=cmp_parent_field,
515
+ value=cmp_value,
516
+ raw_value=cmp_raw_value,
517
+ )
518
+ )
519
+
520
+ # As in the FIT SDK, a target's own components (speed -> enhanced_speed) expand from
521
+ # its raw value; path stops a profile cycle from recursing forever
522
+ if cmp_field.components and cmp_field.def_num not in path:
523
+ self._expand_components(
524
+ def_mesg, cmp_field, self._unapply_scale_offset(cmp_field, cmp_raw_value), ref_values,
525
+ field_datas, path + (cmp_field.def_num,),
526
+ )
527
+
528
+ @staticmethod
529
+ def _unapply_scale_offset(field, value):
530
+ if not isinstance(value, (int, float)):
531
+ return None
532
+ return round((value + (field.offset or 0)) * (field.scale or 1))
533
+
430
534
  def _parse_data_message_components(self, header):
431
535
  def_mesg = self._local_mesgs.get(header.local_mesg_num)
432
536
  if not def_mesg:
@@ -434,6 +538,7 @@ class FitFileDecoder(DeveloperDataMixin):
434
538
  header.local_mesg_num))
435
539
 
436
540
  raw_values = self._parse_raw_values_from_data_message(def_mesg)
541
+ ref_values = self._reference_values(def_mesg, raw_values)
437
542
  field_datas = [] # TODO: I don't love this name, update on DataMessage too
438
543
 
439
544
  # TODO: Maybe refactor this and make it simpler (or at least broken
@@ -441,46 +546,9 @@ class FitFileDecoder(DeveloperDataMixin):
441
546
  for field_def, raw_value in zip(def_mesg.field_defs + def_mesg.dev_field_defs, raw_values):
442
547
  field, parent_field = field_def.field, None
443
548
  if field:
444
- field, parent_field = self._resolve_subfield(field, def_mesg, raw_values)
445
-
446
- # Resolve component fields
447
- if field.components:
448
- for component in field.components:
449
- # Render its raw value
450
- try:
451
- cmp_raw_value = component.render(raw_value)
452
- except ValueError:
453
- continue
454
-
455
- # Apply accumulated value
456
- if component.accumulate and cmp_raw_value is not None:
457
- accumulator = self._accumulators[def_mesg.mesg_num]
458
- cmp_raw_value = self._apply_compressed_accumulation(
459
- cmp_raw_value, accumulator[component.def_num], component.bits,
460
- )
461
- accumulator[component.def_num] = cmp_raw_value
462
-
463
- # Apply scale and offset from component, not from the dynamic field
464
- # as they may differ
465
- cmp_raw_value = self._apply_scale_offset(component, cmp_raw_value)
466
-
467
- # Extract the component's dynamic field from def_mesg
468
- cmp_field = def_mesg.mesg_type.fields[component.def_num]
469
-
470
- # Resolve a possible subfield
471
- cmp_field, cmp_parent_field = self._resolve_subfield(cmp_field, def_mesg, raw_values)
472
- cmp_value = cmp_field.render(cmp_raw_value)
473
-
474
- # Plop it on field_datas
475
- field_datas.append(
476
- FieldData(
477
- field_def=None,
478
- field=cmp_field,
479
- parent_field=cmp_parent_field,
480
- value=cmp_value,
481
- raw_value=cmp_raw_value,
482
- )
483
- )
549
+ field, parent_field = self._resolve_subfield(field, ref_values)
550
+
551
+ self._expand_components(def_mesg, field, raw_value, ref_values, field_datas, (field.def_num,))
484
552
 
485
553
  # TODO: Do we care about a base_type and a resolved field mismatch?
486
554
  # My hunch is we don't
@@ -623,12 +691,13 @@ class DataProcessorMixin:
623
691
  class UncachedFitFile(DataProcessorMixin, FitFileDecoder):
624
692
  """FitFileDecoder with data processing"""
625
693
 
626
- def __init__(self, fileish, *args, check_crc=True, data_processor=None, **kwargs):
694
+ def __init__(self, fileish, *args, check_crc=True, allow_truncated=False, data_processor=None, **kwargs):
627
695
  # Ensure all optional params are passed as kwargs
628
696
  super().__init__(
629
697
  fileish,
630
698
  *args,
631
699
  check_crc=check_crc,
700
+ allow_truncated=allow_truncated,
632
701
  data_processor=data_processor,
633
702
  **kwargs
634
703
  )
@@ -1,5 +1,3 @@
1
- #!/usr/bin/env python
2
-
3
1
  import argparse
4
2
  import codecs
5
3
  import datetime
@@ -1,5 +1,5 @@
1
1
  import datetime
2
- from fitparse.utils import scrub_method_name, is_iterable
2
+ from fitparse.utils import FitParseError, scrub_method_name, is_iterable
3
3
 
4
4
  # Datetimes (uint32) represent seconds since this UTC_REFERENCE
5
5
  UTC_REFERENCE = 631065600 # timestamp for UTC 00:00 Dec 31 1989
@@ -58,10 +58,17 @@ class FitFileDataProcessor:
58
58
  'process_message_%s' % data_message.def_mesg.name), data_message)
59
59
 
60
60
  def _run_processor(self, processor_name, data):
61
+ processors = vars(self).setdefault('_processors', {})
61
62
  try:
62
- getattr(self, processor_name)(data)
63
- except AttributeError:
64
- pass
63
+ processor = processors[processor_name]
64
+ except KeyError:
65
+ processor = processors[processor_name] = getattr(self, processor_name, None)
66
+ if processor is None:
67
+ return
68
+ try:
69
+ processor(data)
70
+ except AttributeError as e:
71
+ raise FitParseError("%s failed: %s" % (processor_name, e)) from e
65
72
 
66
73
  def process_type_bool(self, field_data):
67
74
  if field_data.value is not None:
@@ -1,8 +1,8 @@
1
1
  # ***************** BEGIN AUTOMATICALLY GENERATED FIT PROFILE ******************
2
2
  # *************************** DO NOT EDIT THIS FILE ****************************
3
- # *********** EXPORTED PROFILE FROM SDK VERSION 21.221 ON 2026-11-03 ***********
4
- # ********* PARSED 220 TYPES (4819 VALUES), 128 MESSAGES (1599 FIELDS) *********
5
- # ***************************** APPLIED 2 PATCHES ******************************
3
+ # *********** EXPORTED PROFILE FROM SDK VERSION 21.221 ON 2026-11-10 ***********
4
+ # ********* PARSED 220 TYPES (4819 VALUES), 129 MESSAGES (1606 FIELDS) *********
5
+ # ***************************** APPLIED 8 PATCHES ******************************
6
6
 
7
7
  from fitparse.records import (
8
8
  ComponentField,
@@ -6249,6 +6249,11 @@ MESSAGE_TYPES = {
6249
6249
  name='location',
6250
6250
  mesg_num=29,
6251
6251
  fields={
6252
+ 0: Field( # Label shown on the device, defaults to the save date and time (e.g. 22 Feb 15:12)
6253
+ name='name',
6254
+ type=BASE_TYPES[0x07], # string
6255
+ def_num=0,
6256
+ ),
6252
6257
  1: Field(
6253
6258
  name='position_lat',
6254
6259
  type=BASE_TYPES[0x85], # sint32
@@ -6261,21 +6266,18 @@ MESSAGE_TYPES = {
6261
6266
  def_num=2,
6262
6267
  units='semicircles',
6263
6268
  ),
6264
- 3: Field(
6265
- name='count',
6266
- type=BASE_TYPES[0x84], # uint16
6267
- def_num=3,
6268
- ),
6269
- 4: Field( # UTC timestamp used to set the devices clock and date
6270
- name='clock_time',
6269
+ 4: Field( # Inferred from saved locations: values follow the standard FIT altitude encoding
6270
+ name='altitude',
6271
6271
  type=BASE_TYPES[0x84], # uint16
6272
6272
  def_num=4,
6273
- units='min',
6273
+ scale=5,
6274
+ offset=500,
6275
+ units='m',
6274
6276
  ),
6275
- 8: Field( # Used to correlate UTC to system time if the timestamp of the message is in system time. This UTC time is derived from the GPS data.
6276
- name='date',
6277
- type=BASE_TYPES[0x07], # string
6278
- def_num=8,
6277
+ 254: Field(
6278
+ name='message_index',
6279
+ type=FIELD_TYPES['message_index'],
6280
+ def_num=254,
6279
6281
  ),
6280
6282
  },
6281
6283
  ),
@@ -6340,6 +6342,19 @@ MESSAGE_TYPES = {
6340
6342
  253: FIELD_TYPE_TIMESTAMP, # Whole second part of UTC timestamp at the time the system timestamp was recorded.
6341
6343
  },
6342
6344
  ),
6345
+ 397: MessageType( # Undocumented per-minute skin temperature, found only in SkinTemp files
6346
+ name='skin_temp_sample',
6347
+ mesg_num=397,
6348
+ fields={
6349
+ 1: Field( # Inferred: one per minute over the day before skin_temp_overnight, -11 to +5; the baseline is unconfirmed, the sleep-window mean sits about 1 C below average_deviation
6350
+ name='deviation',
6351
+ type=BASE_TYPES[0x88], # float32
6352
+ def_num=1,
6353
+ units='C',
6354
+ ),
6355
+ 253: FIELD_TYPE_TIMESTAMP,
6356
+ },
6357
+ ),
6343
6358
 
6344
6359
 
6345
6360
  # ************************* Activity File Messages *************************
@@ -9301,6 +9316,11 @@ MESSAGE_TYPES = {
9301
9316
  scale=100,
9302
9317
  units='m',
9303
9318
  ),
9319
+ 90: Field( # Inferred: -7 to 9 on real runs, and never present before six minutes into the activity
9320
+ name='performance_condition',
9321
+ type=BASE_TYPES[0x01], # sint8
9322
+ def_num=90,
9323
+ ),
9304
9324
  91: Field( # Includes atmospheric pressure
9305
9325
  name='absolute_pressure',
9306
9326
  type=BASE_TYPES[0x86], # uint32
@@ -9460,6 +9480,24 @@ MESSAGE_TYPES = {
9460
9480
  scale=100,
9461
9481
  units='percent',
9462
9482
  ),
9483
+ 136: Field( # Inferred: equals heart_rate in all but 2 of 171,509 records
9484
+ name='wrist_heart_rate',
9485
+ type=BASE_TYPES[0x02], # uint8
9486
+ def_num=136,
9487
+ units='bpm',
9488
+ ),
9489
+ 137: Field( # Inferred: starts near 100 and falls over an activity, never below stamina
9490
+ name='stamina_potential',
9491
+ type=BASE_TYPES[0x02], # uint8
9492
+ def_num=137,
9493
+ units='percent',
9494
+ ),
9495
+ 138: Field( # Inferred: 1 to 100, never above stamina_potential
9496
+ name='stamina',
9497
+ type=BASE_TYPES[0x02], # uint8
9498
+ def_num=138,
9499
+ units='percent',
9500
+ ),
9463
9501
  139: Field(
9464
9502
  name='core_temperature',
9465
9503
  type=BASE_TYPES[0x84], # uint16
@@ -9467,6 +9505,12 @@ MESSAGE_TYPES = {
9467
9505
  scale=100,
9468
9506
  units='C',
9469
9507
  ),
9508
+ 143: Field( # Inferred: within 0.3 on average of the stress_level body_battery of the same 3-minute slot
9509
+ name='body_battery',
9510
+ type=BASE_TYPES[0x02], # uint8
9511
+ def_num=143,
9512
+ units='percent',
9513
+ ),
9470
9514
  253: FIELD_TYPE_TIMESTAMP,
9471
9515
  },
9472
9516
  ),
@@ -49,7 +49,7 @@ class DefinitionMessage(RecordBase):
49
49
 
50
50
 
51
51
  class FieldDefinition(RecordBase):
52
- __slots__ = ('field', 'def_num', 'base_type', 'size')
52
+ __slots__ = ('field', 'def_num', 'base_type', 'size', 'unpacker')
53
53
 
54
54
  @property
55
55
  def name(self):
@@ -69,7 +69,7 @@ class FieldDefinition(RecordBase):
69
69
 
70
70
 
71
71
  class DevFieldDefinition(RecordBase):
72
- __slots__ = ('field', 'dev_data_index', 'base_type', 'def_num', 'size')
72
+ __slots__ = ('field', 'dev_data_index', 'base_type', 'def_num', 'size', 'unpacker')
73
73
 
74
74
  def __init__(self, **kwargs):
75
75
  super().__init__(**kwargs)
@@ -159,12 +159,15 @@ class DataMessage(RecordBase):
159
159
  class FieldData(RecordBase):
160
160
  __slots__ = ('field_def', 'field', 'parent_field', 'value', 'raw_value', 'units')
161
161
 
162
- def __init__(self, *args, **kwargs):
163
- super().__init__(self, *args, **kwargs)
164
- if not self.units and self.field:
165
- # Default to units on field, otherwise None.
166
- # NOTE:Not a property since you may want to override this in a data processor
167
- self.units = self.field.units
162
+ def __init__(self, field_def=None, field=None, parent_field=None, value=None, raw_value=None, units=None):
163
+ self.field_def = field_def
164
+ self.field = field
165
+ self.parent_field = parent_field
166
+ self.value = value
167
+ self.raw_value = raw_value
168
+ # Default to units on field, otherwise None.
169
+ # NOTE:Not a property since you may want to override this in a data processor
170
+ self.units = field.units if not units and field else units
168
171
 
169
172
  @property
170
173
  def name(self):
@@ -287,9 +290,10 @@ class SubField(FieldAndSubFieldBase):
287
290
 
288
291
 
289
292
  class DevField(FieldAndSubFieldBase):
290
- __slots__ = ('dev_data_index', 'def_num', 'type', 'name', 'units', 'native_field_num',
291
- # The rest of these are just to be compatible with Field objects. They're always None
292
- 'scale', 'offset', 'components', 'subfields')
293
+ __slots__ = ('dev_data_index', 'def_num', 'type', 'name', 'units', 'scale', 'offset',
294
+ 'native_mesg_num', 'native_field_num',
295
+ # Only for compatibility with Field objects; always None
296
+ 'components', 'subfields')
293
297
  field_type = 'devfield'
294
298
 
295
299
 
@@ -10,15 +10,15 @@ MESSAGE_INFO = MessageInfo(
10
10
  group_name='',
11
11
  fields=[
12
12
  FieldInfo(
13
- name='date',
13
+ name='name',
14
14
  type='string',
15
- num=8,
15
+ num=0,
16
16
  scale=None,
17
17
  offset=None,
18
18
  units=None,
19
19
  components=[],
20
20
  subfields=[],
21
- comment='Used to correlate UTC to system time if the timestamp of the message is in system time. This UTC time is derived from the GPS data.'
21
+ comment='Label shown on the device, defaults to the save date and time (e.g. 22 Feb 15:12)'
22
22
  ),
23
23
  FieldInfo(
24
24
  name='position_lat',
@@ -43,27 +43,27 @@ MESSAGE_INFO = MessageInfo(
43
43
  comment=''
44
44
  ),
45
45
  FieldInfo(
46
- name='count',
46
+ name='altitude',
47
47
  type='uint16',
48
- num=3,
49
- scale=None,
50
- offset=None,
51
- units=None,
48
+ num=4,
49
+ scale=5,
50
+ offset=500,
51
+ units='m',
52
52
  components=[],
53
53
  subfields=[],
54
- comment=''
54
+ comment='Inferred from saved locations: values follow the standard FIT altitude encoding'
55
55
  ),
56
56
  FieldInfo(
57
- name='clock_time',
58
- type='uint16',
59
- num=4,
57
+ name='message_index',
58
+ type='message_index',
59
+ num=254,
60
60
  scale=None,
61
61
  offset=None,
62
- units='min',
62
+ units=None,
63
63
  components=[],
64
64
  subfields=[],
65
- comment='UTC timestamp used to set the devices clock and date'
65
+ comment=''
66
66
  ),
67
67
  ],
68
68
  comment=''
69
- )
69
+ )
@@ -0,0 +1,69 @@
1
+ # patches/message_types/record.py
2
+ import sys
3
+ import os
4
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
5
+ from generate_profile import MessageInfo, FieldInfo
6
+
7
+ MESSAGE_INFO = MessageInfo(
8
+ name='record',
9
+ num=20,
10
+ group_name='',
11
+ fields=[
12
+ FieldInfo(
13
+ name='performance_condition',
14
+ type='sint8',
15
+ num=90,
16
+ scale=None,
17
+ offset=None,
18
+ units=None,
19
+ components=[],
20
+ subfields=[],
21
+ comment='Inferred: -7 to 9 on real runs, and never present before six minutes into the activity'
22
+ ),
23
+ FieldInfo(
24
+ name='wrist_heart_rate',
25
+ type='uint8',
26
+ num=136,
27
+ scale=None,
28
+ offset=None,
29
+ units='bpm',
30
+ components=[],
31
+ subfields=[],
32
+ comment='Inferred: equals heart_rate in all but 2 of 171,509 records'
33
+ ),
34
+ FieldInfo(
35
+ name='stamina_potential',
36
+ type='uint8',
37
+ num=137,
38
+ scale=None,
39
+ offset=None,
40
+ units='percent',
41
+ components=[],
42
+ subfields=[],
43
+ comment='Inferred: starts near 100 and falls over an activity, never below stamina'
44
+ ),
45
+ FieldInfo(
46
+ name='stamina',
47
+ type='uint8',
48
+ num=138,
49
+ scale=None,
50
+ offset=None,
51
+ units='percent',
52
+ components=[],
53
+ subfields=[],
54
+ comment='Inferred: 1 to 100, never above stamina_potential'
55
+ ),
56
+ FieldInfo(
57
+ name='body_battery',
58
+ type='uint8',
59
+ num=143,
60
+ scale=None,
61
+ offset=None,
62
+ units='percent',
63
+ components=[],
64
+ subfields=[],
65
+ comment='Inferred: within 0.3 on average of the stress_level body_battery of the same 3-minute slot'
66
+ ),
67
+ ],
68
+ comment=''
69
+ )
@@ -0,0 +1,37 @@
1
+ # patches/message_types/skin_temp_sample.py
2
+ import sys
3
+ import os
4
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
5
+ from generate_profile import MessageInfo, FieldInfo
6
+
7
+ MESSAGE_INFO = MessageInfo(
8
+ name='skin_temp_sample',
9
+ num=397,
10
+ group_name='',
11
+ fields=[
12
+ FieldInfo(
13
+ name='deviation',
14
+ type='float32',
15
+ num=1,
16
+ scale=None,
17
+ offset=None,
18
+ units='C',
19
+ components=[],
20
+ subfields=[],
21
+ comment='Inferred: one per minute over the day before skin_temp_overnight, -11 to +5; '
22
+ 'the baseline is unconfirmed, the sleep-window mean sits about 1 C below average_deviation'
23
+ ),
24
+ FieldInfo(
25
+ name='timestamp',
26
+ type='date_time',
27
+ num=253,
28
+ scale=None,
29
+ offset=None,
30
+ units='s',
31
+ components=[],
32
+ subfields=[],
33
+ comment=''
34
+ ),
35
+ ],
36
+ comment='Undocumented per-minute skin temperature, found only in SkinTemp files'
37
+ )
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-fitparse"
7
- version = "2.10.0"
7
+ version = "2.12.0"
8
8
  description = "Python library to parse ANT/Garmin .FIT files"
9
9
  authors = [
10
10
  {name = "David Cooper", email = "dave@kupesoft.com"},
@@ -33,7 +33,7 @@ Repository = "https://github.com/nbr23/python-fitparse"
33
33
  Issues = "https://github.com/nbr23/python-fitparse/issues"
34
34
 
35
35
  [project.scripts]
36
- fitdump = "scripts.fitdump:main"
36
+ fitdump = "fitparse.fitdump:main"
37
37
 
38
38
  # Dependencies needed for profile generation
39
39
  [project.optional-dependencies]
@@ -44,7 +44,6 @@ generate = [
44
44
 
45
45
  [tool.hatch.build.targets.wheel]
46
46
  packages = ["fitparse"]
47
- artifacts = ["scripts/fitdump"]
48
47
 
49
48
  [tool.hatch.build.targets.sdist]
50
49
  include = [
@@ -18,6 +18,7 @@
18
18
 
19
19
  from collections import namedtuple
20
20
  import datetime
21
+ import hashlib
21
22
  import os
22
23
  import re
23
24
  import sys
@@ -32,6 +33,8 @@ import glob
32
33
 
33
34
  FIELD_NUM_TIMESTAMP = 253
34
35
 
36
+ DOWNLOAD_TIMEOUT = 60
37
+
35
38
  XLS_HEADER_MAGIC = b'\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1'
36
39
 
37
40
  SYMBOL_NAME_SCRUBBER = re.compile(r'\W|^(?=\d)')
@@ -545,10 +548,12 @@ def parse_messages(messages_rows, type_list):
545
548
  )
546
549
 
547
550
  assert len(subfield.ref_fields) == len(ref_field_names)
548
- if "alert_type" not in ref_field_names:
549
- field.subfields.append(subfield)
551
+ field.subfields.append(subfield)
552
+
553
+ return message_list
550
554
 
551
- # Resolve reference fields for subfields and components
555
+
556
+ def resolve_references(message_list, type_list):
552
557
  for message in message_list.messages:
553
558
  for field in message.fields:
554
559
  for sub_field in field.subfields:
@@ -572,8 +577,6 @@ def parse_messages(messages_rows, type_list):
572
577
  )
573
578
  bit_offset += component.bits
574
579
 
575
- return message_list
576
-
577
580
 
578
581
  def get_xls_and_version_from_zip(path):
579
582
  archive = zipfile.ZipFile(path, 'r')
@@ -591,41 +594,40 @@ def get_xls_and_version_from_zip(path):
591
594
  except KeyError:
592
595
  return archive.open('Profile.xlsx'), profile_version
593
596
 
597
+
598
+ class PatchError(Exception):
599
+ pass
600
+
601
+
602
+ PATCH_ATTRIBUTES = {
603
+ 'message_types': ('MESSAGE_INFO', lambda info: info.num),
604
+ 'field_types': ('TYPE_INFO', lambda info: info.name),
605
+ }
606
+
607
+
594
608
  def load_patches_from_directory(patches_dir, patch_type):
595
- patches = {}
609
+ if patch_type not in PATCH_ATTRIBUTES:
610
+ raise PatchError(f"Unknown patch type {patch_type}")
611
+ attribute, key_of = PATCH_ATTRIBUTES[patch_type]
596
612
 
613
+ patches = {}
597
614
  if not os.path.exists(patches_dir):
598
615
  return patches
599
616
 
600
- patch_files = glob.glob(os.path.join(patches_dir, "*.py"))
617
+ for patch_file in sorted(glob.glob(os.path.join(patches_dir, "*.py"))):
618
+ spec = importlib.util.spec_from_file_location("patch_module", patch_file)
619
+ patch_module = importlib.util.module_from_spec(spec)
620
+ spec.loader.exec_module(patch_module)
601
621
 
602
- for patch_file in patch_files:
603
- try:
604
- spec = importlib.util.spec_from_file_location("patch_module", patch_file)
605
- patch_module = importlib.util.module_from_spec(spec)
606
- spec.loader.exec_module(patch_module)
622
+ if not hasattr(patch_module, attribute):
623
+ raise PatchError(f"{patch_file} has no {attribute}")
624
+ patch_obj = getattr(patch_module, attribute)
625
+ patch_key = key_of(patch_obj)
626
+ if patch_key in patches:
627
+ raise PatchError(f"{patch_file} patches {patch_type} {patch_key}, already patched by another file")
607
628
 
608
- if patch_type == 'message_types':
609
- if not hasattr(patch_module, 'MESSAGE_INFO'):
610
- print(f"Warning: {patch_file} missing MESSAGE_INFO, skipping")
611
- continue
612
- patch_obj = patch_module.MESSAGE_INFO
613
- patch_key = patch_obj.num
614
- elif patch_type == 'field_types':
615
- if not hasattr(patch_module, 'TYPE_INFO'):
616
- print(f"Warning: {patch_file} missing TYPE_INFO, skipping")
617
- continue
618
- patch_obj = patch_module.TYPE_INFO
619
- patch_key = patch_obj.name
620
- else:
621
- print(f"Warning: Unknown patch type {patch_type}")
622
- continue
623
-
624
- print(f"Loaded patch: {patch_type} - {patch_key}")
625
- patches[patch_key] = patch_obj
626
-
627
- except Exception as e:
628
- print(f"Error loading patch {patch_file}: {e}")
629
+ print(f"Loaded patch: {patch_type} - {patch_key}")
630
+ patches[patch_key] = patch_obj
629
631
 
630
632
  return patches
631
633
 
@@ -642,6 +644,69 @@ def load_field_type_patches():
642
644
  return load_patches_from_directory(patches_dir, 'field_types')
643
645
 
644
646
 
647
+ def merge_type_values(existing_type, patch_type_info):
648
+ if existing_type.base_type != patch_type_info.base_type:
649
+ raise PatchError(
650
+ f"Field type {existing_type.name} is {existing_type.base_type} in the SDK, "
651
+ f"the patch declares {patch_type_info.base_type}"
652
+ )
653
+ existing_values = {normalize_def_num(v.value): v for v in existing_type.values}
654
+ added = 0
655
+ for patch_value in patch_type_info.values:
656
+ official = existing_values.get(normalize_def_num(patch_value.value))
657
+ if official is None:
658
+ existing_type.values.append(patch_value)
659
+ added += 1
660
+ print(f" Added value: {existing_type.name}.{patch_value.name} ({patch_value.value})")
661
+ elif official.name != patch_value.name:
662
+ raise PatchError(
663
+ f"{existing_type.name} value {patch_value.value} is '{official.name}' in the SDK, "
664
+ f"the patch names it '{patch_value.name}'"
665
+ )
666
+ else:
667
+ print(f" Redundant value: {existing_type.name}.{patch_value.name} is in the SDK, remove it from the patch")
668
+ return added
669
+
670
+
671
+ def merge_subfields(message_name, existing_field, patch_field):
672
+ existing_names = {s.name for s in existing_field.subfields}
673
+ added = 0
674
+ for patch_subfield in patch_field.subfields:
675
+ if patch_subfield.name in existing_names:
676
+ print(f" Redundant subfield: {message_name}.{existing_field.name}.{patch_subfield.name} is in the SDK")
677
+ else:
678
+ existing_field.subfields.append(patch_subfield)
679
+ added += 1
680
+ print(f" Added subfield: {message_name}.{existing_field.name}.{patch_subfield.name}")
681
+ return added
682
+
683
+
684
+ def merge_message_fields(existing_message, patch_message_info):
685
+ if existing_message.name != patch_message_info.name:
686
+ raise PatchError(
687
+ f"Message {patch_message_info.num} is '{existing_message.name}' in the SDK, "
688
+ f"the patch names it '{patch_message_info.name}'"
689
+ )
690
+ existing_fields = {normalize_def_num(f.num): f for f in existing_message.fields}
691
+ added = 0
692
+ for patch_field in patch_message_info.fields:
693
+ official = existing_fields.get(normalize_def_num(patch_field.num))
694
+ if official is None:
695
+ existing_message.fields.append(patch_field)
696
+ added += 1
697
+ print(f" Added field: {existing_message.name}.{patch_field.name} (def_num {patch_field.num})")
698
+ elif official.name != patch_field.name:
699
+ raise PatchError(
700
+ f"{existing_message.name} field {patch_field.num} is '{official.name}' in the SDK, "
701
+ f"the patch names it '{patch_field.name}'"
702
+ )
703
+ else:
704
+ added += merge_subfields(existing_message.name, official, patch_field)
705
+ print(f" Field {existing_message.name}.{patch_field.name} is in the SDK now, "
706
+ f"only its patched subfields still apply")
707
+ return added
708
+
709
+
645
710
  def apply_patches(type_list, message_list):
646
711
  print("Loading patches...")
647
712
  applied = 0
@@ -650,36 +715,28 @@ def apply_patches(type_list, message_list):
650
715
  if field_type_patches:
651
716
  print(f"Applying {len(field_type_patches)} field type patches...")
652
717
  for patch_name, patch_type_info in field_type_patches.items():
653
- if not type_list.get(patch_name, raise_exception=False):
718
+ existing_type = type_list.get(patch_name, raise_exception=False)
719
+ if existing_type:
720
+ applied += merge_type_values(existing_type, patch_type_info)
721
+ else:
654
722
  type_list.types.append(patch_type_info)
655
723
  applied += 1
656
724
  print(f" Added field type: {patch_name}")
657
- else:
658
- print(f" Skipped field type: {patch_name} (already exists in generated profile)")
659
725
 
660
726
  message_type_patches = load_message_type_patches()
661
727
  if message_type_patches:
662
728
  print(f"Applying {len(message_type_patches)} message type patches...")
663
729
  for patch_num, patch_message_info in message_type_patches.items():
664
- existing_message = None
665
- for msg in message_list.messages:
666
- if msg.num == patch_num:
667
- existing_message = msg
668
- break
669
-
670
- if not existing_message:
730
+ existing_message = next(
731
+ (m for m in message_list.messages if normalize_def_num(m.num) == normalize_def_num(patch_num)),
732
+ None,
733
+ )
734
+ if existing_message:
735
+ applied += merge_message_fields(existing_message, patch_message_info)
736
+ else:
671
737
  message_list.messages.append(patch_message_info)
672
738
  applied += 1
673
739
  print(f" Added message type: {patch_message_info.name} (num: {patch_num})")
674
- else:
675
- existing_nums = {normalize_def_num(f.num) for f in existing_message.fields}
676
- for patch_field in patch_message_info.fields:
677
- if normalize_def_num(patch_field.num) in existing_nums:
678
- print(f" Skipped field: {existing_message.name}.{patch_field.name} (def_num {patch_field.num} already defined)")
679
- else:
680
- existing_message.fields.append(patch_field)
681
- applied += 1
682
- print(f" Added field: {existing_message.name}.{patch_field.name} (def_num {patch_field.num})")
683
740
 
684
741
  return applied
685
742
 
@@ -688,10 +745,8 @@ def download_latest_sdk(path):
688
745
  repo_url = 'https://api.github.com/repos/garmin/fit-sdk-tools/releases/latest'
689
746
  print("Fetching latest SDK release from GitHub...")
690
747
 
691
- r = requests.get(repo_url)
692
- if r.status_code != 200:
693
- print(f"Failed to fetch GitHub releases: {r.status_code}")
694
- sys.exit(1)
748
+ r = requests.get(repo_url, timeout=DOWNLOAD_TIMEOUT)
749
+ r.raise_for_status()
695
750
 
696
751
  release_data = r.json()
697
752
 
@@ -705,16 +760,29 @@ def download_latest_sdk(path):
705
760
  print("Couldn't find Profile.xlsx in latest release. Exiting.")
706
761
  sys.exit(1)
707
762
 
763
+ algorithm, _, expected_digest = (profile_asset.get('digest') or '').partition(':')
764
+ if algorithm != 'sha256' or not expected_digest:
765
+ print("Profile.xlsx has no sha256 digest in the release metadata. Exiting.")
766
+ sys.exit(1)
767
+
708
768
  download_url = profile_asset['browser_download_url']
709
769
  print("Downloading Profile.xlsx from %s" % download_url)
710
770
 
711
- r = requests.get(download_url, stream=True)
771
+ r = requests.get(download_url, stream=True, timeout=DOWNLOAD_TIMEOUT)
772
+ r.raise_for_status()
712
773
 
774
+ sha256 = hashlib.sha256()
713
775
  with open(path, 'wb') as f:
714
776
  for chunk in r.iter_content(chunk_size=1024):
715
777
  if chunk:
778
+ sha256.update(chunk)
716
779
  f.write(chunk)
717
780
 
781
+ if sha256.hexdigest() != expected_digest:
782
+ print("Profile.xlsx sha256 {} does not match the release digest {}. Exiting.".format(
783
+ sha256.hexdigest(), expected_digest))
784
+ sys.exit(1)
785
+
718
786
  tag_name = release_data.get('tag_name', '')
719
787
  version_match = re.search(r'(\d+\.\d+)', tag_name)
720
788
  if version_match:
@@ -754,6 +822,7 @@ def main(input_xls_or_zip, output_py_path=None):
754
822
  message_list = parse_messages(messages_rows, type_list)
755
823
 
756
824
  patches_applied = apply_patches(type_list, message_list)
825
+ resolve_references(message_list, type_list)
757
826
 
758
827
  mesg_num_declarations = []
759
828
  for mesg_name in MESSAGE_NUM_DECLARATIONS:
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env python
2
+
3
+ import importlib.machinery
4
+ import importlib.util
5
+ import itertools
6
+ import os
7
+ import sys
8
+ from dataclasses import dataclass, field
9
+
10
+ _module_ids = itertools.count()
11
+
12
+
13
+ @dataclass
14
+ class ProfileDiff:
15
+ added: list = field(default_factory=list)
16
+ removed: list = field(default_factory=list)
17
+ renamed: list = field(default_factory=list)
18
+ changed: list = field(default_factory=list)
19
+
20
+ @property
21
+ def breaking(self):
22
+ return bool(self.removed or self.renamed)
23
+
24
+ def __bool__(self):
25
+ return bool(self.added or self.removed or self.renamed or self.changed)
26
+
27
+
28
+ def load_profile(path):
29
+ name = 'profile_snapshot_%d' % next(_module_ids)
30
+ loader = importlib.machinery.SourceFileLoader(name, path)
31
+ spec = importlib.util.spec_from_loader(name, loader)
32
+ module = importlib.util.module_from_spec(spec)
33
+ loader.exec_module(module)
34
+ return module.FIELD_TYPES, module.MESSAGE_TYPES
35
+
36
+
37
+ def _components(components):
38
+ return tuple(
39
+ (c.name, c.def_num, c.scale, c.offset, c.units, c.accumulate, c.bits, c.bit_offset)
40
+ for c in components or ()
41
+ )
42
+
43
+
44
+ def _field_shape(f):
45
+ return {
46
+ 'type': f.type.name,
47
+ 'scale': f.scale,
48
+ 'offset': f.offset,
49
+ 'units': f.units,
50
+ 'components': _components(f.components),
51
+ }
52
+
53
+
54
+ def _subfield_shape(s):
55
+ shape = _field_shape(s)
56
+ shape['ref_fields'] = tuple((r.def_num, r.raw_value) for r in s.ref_fields or ())
57
+ return shape
58
+
59
+
60
+ def _describe_change(label, old_shape, new_shape):
61
+ changes = [
62
+ '{} {!r} -> {!r}'.format(key, old_shape[key], new_shape[key])
63
+ for key in old_shape
64
+ if old_shape[key] != new_shape[key]
65
+ ]
66
+ return '{}: {}'.format(label, ', '.join(changes)) if changes else None
67
+
68
+
69
+ def _diff_keyed(old, new, describe, diff, on_common=None):
70
+ for key in sorted(new.keys() - old.keys()):
71
+ diff.added.append(describe(key, new[key]))
72
+ for key in sorted(old.keys() - new.keys()):
73
+ diff.removed.append(describe(key, old[key]))
74
+ for key in sorted(old.keys() & new.keys()):
75
+ if on_common:
76
+ on_common(key, old[key], new[key])
77
+
78
+
79
+ def _diff_types(old_types, new_types, diff):
80
+ def common(name, old, new):
81
+ if old.base_type.name != new.base_type.name:
82
+ diff.changed.append('type `{}`: base_type {} -> {}'.format(name, old.base_type.name, new.base_type.name))
83
+ old_values, new_values = old.values or {}, new.values or {}
84
+ _diff_keyed(
85
+ old_values, new_values,
86
+ lambda value, label: 'value `{}.{}` ({})'.format(name, label, value),
87
+ diff,
88
+ )
89
+ for value in sorted(old_values.keys() & new_values.keys()):
90
+ if old_values[value] != new_values[value]:
91
+ diff.renamed.append('value `{}` {}: `{}` -> `{}`'.format(
92
+ name, value, old_values[value], new_values[value]))
93
+
94
+ _diff_keyed(old_types, new_types, lambda name, _: 'type `{}`'.format(name), diff, common)
95
+
96
+
97
+ def _diff_subfields(label, old_field, new_field, diff):
98
+ old_subs = {s.name: s for s in old_field.subfields or ()}
99
+ new_subs = {s.name: s for s in new_field.subfields or ()}
100
+
101
+ def common(name, old, new):
102
+ change = _describe_change('subfield `{}.{}`'.format(label, name), _subfield_shape(old), _subfield_shape(new))
103
+ if change:
104
+ diff.changed.append(change)
105
+
106
+ _diff_keyed(old_subs, new_subs, lambda name, _: 'subfield `{}.{}`'.format(label, name), diff, common)
107
+
108
+
109
+ def _diff_fields(mesg_name, old_fields, new_fields, diff):
110
+ def common(def_num, old, new):
111
+ if old.name != new.name:
112
+ diff.renamed.append('field `{}` {}: `{}` -> `{}`'.format(mesg_name, def_num, old.name, new.name))
113
+ label = '{}.{}'.format(mesg_name, new.name)
114
+ change = _describe_change('field `{}`'.format(label), _field_shape(old), _field_shape(new))
115
+ if change:
116
+ diff.changed.append(change)
117
+ _diff_subfields(label, old, new, diff)
118
+
119
+ _diff_keyed(
120
+ old_fields, new_fields,
121
+ lambda def_num, f: 'field `{}.{}` ({})'.format(mesg_name, f.name, def_num),
122
+ diff, common,
123
+ )
124
+
125
+
126
+ def _diff_messages(old_messages, new_messages, diff):
127
+ def common(mesg_num, old, new):
128
+ if old.name != new.name:
129
+ diff.renamed.append('message {}: `{}` -> `{}`'.format(mesg_num, old.name, new.name))
130
+ _diff_fields(new.name, old.fields, new.fields, diff)
131
+
132
+ _diff_keyed(
133
+ old_messages, new_messages,
134
+ lambda mesg_num, m: 'message `{}` ({})'.format(m.name, mesg_num),
135
+ diff, common,
136
+ )
137
+
138
+
139
+ def diff_profiles(old, new):
140
+ diff = ProfileDiff()
141
+ _diff_types(old[0], new[0], diff)
142
+ _diff_messages(old[1], new[1], diff)
143
+ return diff
144
+
145
+
146
+ def render_markdown(diff):
147
+ if not diff:
148
+ return 'No changes to the decoded profile.\n'
149
+ sections = [
150
+ ('Removed', diff.removed),
151
+ ('Renamed', diff.renamed),
152
+ ('Added', diff.added),
153
+ ('Changed', diff.changed),
154
+ ]
155
+ out = ['## Profile changes', '']
156
+ if diff.breaking:
157
+ out += ['**Removals or renames: this update breaks existing consumers and needs a patch or a manual decision.**', '']
158
+ for title, entries in sections:
159
+ if entries:
160
+ out += ['### {} ({})'.format(title, len(entries)), '']
161
+ out += ['- {}'.format(entry) for entry in entries]
162
+ out.append('')
163
+ return '\n'.join(out)
164
+
165
+
166
+ def main(argv):
167
+ if len(argv) != 3:
168
+ print('Usage: %s <old profile.py> <new profile.py>' % os.path.basename(argv[0]), file=sys.stderr)
169
+ return 2
170
+ diff = diff_profiles(load_profile(argv[1]), load_profile(argv[2]))
171
+ sys.stdout.write(render_markdown(diff))
172
+ return 1 if diff.breaking else 0
173
+
174
+
175
+ if __name__ == '__main__':
176
+ sys.exit(main(sys.argv))