salopensource / sal-scripts

Apache License 2.0
23 stars 31 forks source link

Fix handling bytes-like product-name from ioreg #100

Closed octomike closed 2 years ago

octomike commented 2 years ago

Currently, some of our new M1 devices have an empty friendly name in Sal. This is due to two reasons:

  1. the system profiler readout seems to be broken due to a minor type confusion
  2. (fallback) online lookup won't work anymore because of the new randomized serial numbers

This trivial PR hopefully fixes the sp readout. Did this actually work before on some machines before?

Current behaviour tested on multiple M1 machines:

/usr/local/sal/Python.framework/Versions/Current/bin/python3
Python 3.9.7 (v3.9.7:1016ef3790, Aug 30 2021, 16:25:35)
[Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import plistlib
>>> cmd = ["/usr/sbin/ioreg", "-arc", "IOPlatformDevice", "-k", "product-name"]
>>> out = subprocess.check_output(cmd)
>>> data = plistlib.loads(out)
>>> data[0].get('product-name')
b'MacBook Pro (14-inch, 2021)\x00'
>>> data[0].get('product-name').encode('ascii', 'ignore')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'

All machines that I tested this on returned a bytes-like from plistlib.loads() and thus needed a decode(). There was also a trailing 0-byte character, which I remove in a slightly excessive way, just to be sure there are no spaces preceding or succeeding it.

>>> data[0].get('product-name').decode('ascii', 'ignore').strip().strip('\x00').strip()
'MacBook Pro (14-inch, 2021)'

I would have also liked to skip the online lookup when we have a randomized serial at hand, but I'm not sure how to "detect" randomness. :) First I thought the new style serials were exactly 10 characters in length, but apparently that's not always the case.