changelog.py (1991B)
1 # This Source Code Form is subject to the terms of the Mozilla Public 2 # License, v. 2.0. If a copy of the MPL was not distributed with this 3 # file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 # 5 # This module needs to stay Python 2 and 3 compatible 6 # 7 """ 8 Maintains a unique file that lists all artifacts operations. 9 """ 10 11 import json 12 import os 13 import sys 14 from datetime import datetime 15 16 17 # XXX we should do one per platform and use platform-changelog.json as a name 18 class Changelog: 19 def __init__(self, archives_dir): 20 self.archives_dir = archives_dir 21 self.location = os.path.join(archives_dir, "changelog.json") 22 if os.path.exists(self.location): 23 with open(self.location) as f: 24 self._data = json.loads(f.read()) 25 if "changes" not in self._data: 26 self._data["changes"] = [] 27 else: 28 self._data = {"changes": []} 29 30 def append(self, action, platform=sys.platform, **metadata): 31 now = datetime.timestamp(datetime.now()) 32 log = {"action": action, "platform": platform, "when": now} 33 log.update(metadata) 34 # adding taskcluster specific info if we see it in the env 35 for key in ( 36 "TC_SCHEDULER_ID", 37 "TASK_ID", 38 "TC_OWNER", 39 "TC_SOURCE", 40 "TC_PROJECT", 41 ): 42 if key in os.environ: 43 log[key] = os.environ[key] 44 self._data["changes"].append(log) 45 46 def save(self, archives_dir=None): 47 if archives_dir is not None and archives_dir != self.archives_dir: 48 self.location = os.path.join(archives_dir, "changelog.json") 49 # we need to resolve potential r/w conflicts on TC here 50 with open(self.location, "w") as f: 51 f.write(json.dumps(self._data)) 52 53 def history(self): 54 """From older to newer""" 55 return sorted( 56 self._data["changes"], key=lambda entry: entry["when"], reverse=True 57 )