-
Notifications
You must be signed in to change notification settings - Fork 3
/
02-build-index-db.py
212 lines (172 loc) · 6.75 KB
/
02-build-index-db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import hashlib
import os
import time
import re
import yaml
import sqlite3
from sqlite3 import Error
from subprocess import check_output
db_path = ".tmp/source/Public/index.db"
def get_id(con, cursor, table, field, value, force_new=False):
cursor.execute('SELECT rowid FROM {} WHERE {} = "{}";'.format(table, field, value))
row = cursor.fetchall()
if len(row) == 0 or force_new:
cursor.execute('SELECT MAX(rowid) + 1 FROM {}'.format(table))
id_ = cursor.fetchall()[0][0]
if not id_:
id_ = 1
cursor.execute(
'INSERT INTO {} (rowid, {}) VALUES (?,?)'.format(table, field),
(id_, value)
)
con.commit()
return id_
return row[0][0]
def normalize(name):
return name.replace(' ', '').lower()
def register_manifest(con, cursor, data, pathParts, manifest, manifestFilename, manifestHash:bytes):
# IDS
id_ = get_id(con, cursor, 'ids', 'id', data['PackageIdentifier'])
# NAMES
if not 'PackageName' in data:
data['PackageName'] = data['PackageIdentifier'].split('.')[-1]
name = get_id(con, cursor, 'names', 'name', data['PackageName'])
# MONIKERS
if not 'Moniker' in data:
data['Moniker'] = data['PackageName'].lower()
moniker = get_id(con, cursor, 'monikers', 'moniker', data['Moniker'])
# VERSION
version = get_id(con, cursor, 'versions', 'version', data['PackageVersion'])
# PATHPARTS
parent_pathpart = 1
for part in pathParts[1:]:
pathpart = get_id(con, cursor, 'pathparts', 'pathpart', part)
cursor.execute('UPDATE pathparts SET parent={} WHERE rowid={};'.format(parent_pathpart, pathpart))
parent_pathpart = pathpart
pathpart = get_id(con, cursor, 'pathparts', 'pathpart', manifestFilename, True)
cursor.execute('UPDATE pathparts SET parent={} WHERE rowid={};'.format(parent_pathpart, pathpart))
con.commit()
# MANIFEST
cursor.execute(
'''INSERT INTO manifest (rowid, id, name, moniker, version, channel, pathpart, arp_min_version, arp_max_version, hash) VALUES (?,?,?,?,?,?,?,?,?,?)''',
(manifest, id_, name, moniker, version, 1, pathpart, 1, 1, manifestHash)
)
con.commit()
# NORM_NAMES
norm_name = get_id(con, cursor, 'norm_names', 'norm_name', normalize(data['PackageName']))
cursor.execute(
'INSERT INTO norm_names_map (manifest, norm_name) VALUES (?,?)',
(manifest, norm_name)
)
con.commit()
# NORM_PUBLISHERS
if not 'Publisher' in data:
data['Publisher'] = data['PackageIdentifier'].split('.')[0]
norm_publisher = get_id(con, cursor, 'norm_publishers', 'norm_publisher', normalize(data['Publisher']))
cursor.execute(
'INSERT INTO norm_publishers_map (manifest, norm_publisher) VALUES (?,?)',
(manifest, norm_publisher)
)
con.commit()
# TAGS
if 'Tags' in data:
for _tag in data['Tags']:
tag = get_id(con, cursor, 'tags', 'tag', _tag)
cursor.execute('INSERT INTO tags_map (manifest, tag) VALUES (?,?)', (manifest, tag))
con.commit()
# COMMANDS
if 'Commands' in data:
for _command in data['Commands']:
command = get_id(con, cursor, 'commands', 'command', _command)
cursor.execute(
'INSERT INTO commands_map (manifest, command) VALUES (?,?)',
(manifest, command)
)
con.commit()
# PFNS
if 'Installers' in data:
if 'PackageFamilyName' in data['Installers'][0]:
pfn = get_id(con, cursor, 'pfns', 'pfn', data['Installers'][0]['PackageFamilyName'])
cursor.execute('INSERT INTO pfns_map (manifest, pfn) VALUES (?,?)', (manifest, pfn))
con.commit()
# PRODUCTCODES
if 'ProductCode' in data['Installers'][0]:
productcode = get_id(
con, cursor, 'productcodes', 'productcode',
data['Installers'][0]['ProductCode']
)
cursor.execute(
'INSERT INTO productcodes_map (manifest, productcode) VALUES (?,?)',
(manifest, productcode)
)
con.commit()
# UPGRADECODES
if 'UpgradeCode' in data['Installers'][0]['AppsAndFeaturesEntries'][0]:
upgradecode = get_id(
con, cursor, 'upgradecodes', 'upgradecode',
data['Installers'][0]['AppsAndFeaturesEntries'][0]['UpgradeCode']
)
cursor.execute(
'INSERT INTO upgradecodes_map (manifest, upgradecode) VALUES (?,?)',
(manifest, upgradecode)
)
con.commit()
def create_catalog(con):
cursor = con.cursor()
# CREATE SQLITE DATABASE
manifest = 1
cursor.execute(
'INSERT INTO pathparts (rowid,pathpart) VALUES (?,?)',
(1, 'manifests')
)
con.commit()
cursor.execute(
'UPDATE metadata SET value=? WHERE name=?;',
(int(time.time()), 'lastwritetime')
)
con.commit()
for (root,_,files) in os.walk('manifests'):
if re.match('.*(?:[0-9]+\\.?){2,3}\\.[0-9]+$', root):
pathParts = root.split(os.path.sep)
packageName = ".".join(pathParts[2:-1])
manifestFilename = ""
packageData = {}
fileHash = b''
for file in files:
if file.endswith(".yaml"):
filename = os.path.join(root, file)
with open(filename, 'r') as stream:
try:
data = yaml.safe_load(stream)
print('processing', data['PackageIdentifier'], data['PackageVersion'])
except yaml.YAMLError as exc:
print(exc)
break
with open(filename,"rb") as f:
bytes = f.read() # read entire file as bytes
fileHash = hashlib.sha256(bytes).digest()
if data['ManifestType'] == 'merged':
packageData = data
manifestFilename = file
break
register_manifest(con, cursor, packageData, pathParts, manifest, manifestFilename, fileHash)
manifest += 1
if __name__ == '__main__':
if os.path.exists(db_path):
os.remove(db_path)
else:
os.makedirs(os.path.dirname(db_path))
con = None
try:
con = sqlite3.connect(db_path)
sql_file = open("index.db.sql")
sql_as_string = sql_file.read()
cur = con.cursor()
cur.executescript(sql_as_string)
con.commit()
create_catalog(con)
except Error as e:
print(e)
finally:
if con:
con.close()