import sys import json from dbaccess import execQuery from misc import idToText, printJSONHeader class ListContexts: def __init__(self, ranked_only): self.ranked_only = ranked_only def rankingsExist(self, contextId): rankings = execQuery( "SELECT id FROM ranking WHERE context2Id = %s LIMIT 1", (contextId,)) return len(rankings) > 0 def execute(self): # Get all host/platform/branch/sha1 combinations: contexts = execQuery( "SELECT id, hostId, platformId, branchId, sha1Id," " EXTRACT(EPOCH FROM timestamp)::INT" " FROM context" " ORDER BY hostId, platformId," " branchId, timestamp DESC;", ()) \ + [(-1, -1, -1, -1, -1, -1)] # Sentinel value self.contexts = [] if not len(contexts): return id, host, platform, branch, sha1, timestamp = contexts[0] curHost, curPlatform, curBranch = host, platform, branch rankings_exist = self.rankingsExist(id) rankings_exist_count = 1 if rankings_exist else 0 curSnapshots = [] if (not self.ranked_only) or rankings_exist: curSnapshots = [ (idToText('sha1', sha1), timestamp, 1 if rankings_exist else 0)] for (id, host, platform, branch, sha1, timestamp) in contexts[1:]: if (host, platform, branch) != (curHost, curPlatform, curBranch): if (not self.ranked_only) or (rankings_exist_count > 0): assert len(curSnapshots) > 0 self.contexts.append({ 'host' : idToText('host', curHost), 'platform' : idToText('platform', curPlatform), 'branch' : idToText('branch', curBranch), 'snapshots' : curSnapshots }) rankings_exist_count = 0 curHost, curPlatform, curBranch = host, platform, branch curSnapshots = [] rankings_exist = self.rankingsExist(id) if rankings_exist: rankings_exist_count = rankings_exist_count + 1 if (not self.ranked_only) or rankings_exist: curSnapshots.append( (idToText('sha1', sha1), timestamp, 1 if rankings_exist else 0)) self.writeOutput() def writeOutputAsJSON(self): printJSONHeader() json.dump({ 'contexts' : self.contexts }, sys.stdout) class ListContextsAsJSON(ListContexts): def writeOutput(self): self.writeOutputAsJSON()