]>
git.proxmox.com Git - mirror_linux-firmware.git/blob - contrib/process_linux_firmware.py
4ef0aa760692f6fe6c4051b6d210cbf54215ef8d
14 from datetime
import date
17 URL
= "https://lore.kernel.org/linux-firmware/new.atom"
20 class ContentType(Enum
):
28 "diff --git": ContentType
.PATCH
,
29 "Signed-off-by:": ContentType
.PATCH
,
30 "are available in the Git repository at": ContentType
.PULL_REQUEST
,
34 def classify_content(content
):
35 # load content into the email library
36 msg
= email
.message_from_string(content
)
39 subject
= msg
["Subject"]
41 return ContentType
.REPLY
42 if "PATCH" in subject
:
43 return ContentType
.PATCH
45 for part
in msg
.walk():
46 if part
.get_content_type() == "text/plain":
47 body
= part
.get_payload(decode
=True).decode("utf-8")
48 for key
in content_types
.keys():
50 return content_types
[key
]
52 return ContentType
.SPAM
56 with urllib
.request
.urlopen(url
) as response
:
57 return response
.read().decode("utf-8")
61 logging
.debug("Running {}".format(cmd
))
62 output
= subprocess
.check_output(cmd
, stderr
=subprocess
.STDOUT
)
66 def reply_email(content
, branch
):
67 if "SMTP_USER" in os
.environ
:
68 user
= os
.environ
["SMTP_USER"]
69 if "SMTP_PASS" in os
.environ
:
70 password
= os
.environ
["SMTP_PASS"]
71 if "SMTP_SERVER" in os
.environ
:
72 server
= os
.environ
["SMTP_SERVER"]
73 if "SMTP_PORT" in os
.environ
:
74 port
= os
.environ
["SMTP_PORT"]
75 if not user
or not password
or not server
or not port
:
76 logging
.debug("Missing SMTP configuration, not sending email")
79 reply
= email
.message
.EmailMessage()
81 orig
= email
.message_from_string(content
)
82 targets
= email
.utils
.getaddresses(
83 orig
.get_all("to", []) + orig
.get_all("cc", []) + orig
.get_all("from", [])
85 for target
in targets
:
86 reply
["To"] += email
.utils
.formataddr(target
)
88 reply
["From"] = "linux-firmware@kernel.org"
89 reply
["Subject"] = "Re: {}".format(orig
["Subject"])
90 reply
["In-Reply-To"] = orig
["Message-Id"]
91 reply
["References"] = orig
["Message-Id"]
92 reply
["Thread-Topic"] = orig
["Thread-Topic"]
93 reply
["Thread-Index"] = orig
["Thread-Index"]
96 "Your request has been forwarded by the Linux Firmware Kernel robot.\n"
97 "Please follow up at https://gitlab.com/kernel-firmware/linux-firmware/-/merge_requests to ensure it gets merged\n"
98 "Your request is '{}'".format(branch
)
100 reply
.set_content(content
)
102 mailserver
= smtplib
.SMTP(server
, port
)
104 mailserver
.starttls()
106 mailserver
.login(user
, password
)
107 mailserver
.sendmail(reply
["From"], reply
["To"], reply
.as_string())
111 def create_pr(remote
, branch
):
119 "merge_request.create",
121 "merge_request.remove_source_branch",
123 "merge_request.target=main",
125 "merge_request.title={}".format(branch
),
130 def refresh_branch():
131 quiet_cmd(["git", "checkout", "main"])
132 quiet_cmd(["git", "pull"])
135 def delete_branch(branch
):
136 quiet_cmd(["git", "checkout", "main"])
137 quiet_cmd(["git", "branch", "-D", branch
])
140 def process_pr(url
, num
, remote
):
141 branch
= "robot/pr-{}-{}".format(num
, int(time
.time()))
142 cmd
= ["b4", "pr", "-b", branch
, url
]
145 except subprocess
.CalledProcessError
:
146 logging
.warning("Failed to apply PR")
149 # determine if it worked (we can't tell unfortunately by return code)
150 cmd
= ["git", "branch", "--list", branch
]
151 logging
.debug("Running {}".format(cmd
))
152 result
= subprocess
.check_output(cmd
)
155 logging
.info("Forwarding PR for {}".format(branch
))
157 create_pr(remote
, branch
)
158 delete_branch(branch
)
163 def process_patch(mbox
, num
, remote
):
164 # create a new branch for the patch
165 branch
= "robot/patch-{}-{}".format(num
, int(time
.time()))
166 cmd
= ["git", "checkout", "-b", branch
]
170 cmd
= ["b4", "shazam", "-m", "-"]
171 logging
.debug("Running {}".format(cmd
))
172 p
= subprocess
.Popen(
173 cmd
, stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
175 stdout
, stderr
= p
.communicate(mbox
.encode("utf-8"))
176 for line
in stdout
.splitlines():
177 logging
.debug(line
.decode("utf-8"))
178 for line
in stderr
.splitlines():
179 logging
.debug(line
.decode("utf-8"))
180 if p
.returncode
!= 0:
181 quiet_cmd(["git", "am", "--abort"])
183 logging
.info("Opening PR for {}".format(branch
))
185 create_pr(remote
, branch
)
187 delete_branch(branch
)
188 if p
.returncode
== 0:
193 def update_database(conn
, url
):
197 """CREATE TABLE IF NOT EXISTS firmware (url text, processed integer default 0, spam integer default 0)"""
201 if os
.path
.exists(url
):
202 with
open(url
, "r") as f
:
206 logging
.info("Fetching {}".format(url
))
207 atom
= fetch_url(url
)
209 # Parse the atom and extract the URLs
210 feed
= feedparser
.parse(atom
)
212 # Insert the URLs into the database (oldest first)
213 feed
["entries"].reverse()
214 for entry
in feed
["entries"]:
215 c
.execute("SELECT url FROM firmware WHERE url = ?", (entry
.link
,))
218 c
.execute("INSERT INTO firmware VALUES (?, ?, ?)", (entry
.link
, 0, 0))
220 # Commit the changes and close the connection
224 def process_database(conn
, remote
):
227 # get all unprocessed urls that aren't spam
228 c
.execute("SELECT url FROM firmware WHERE processed = 0 AND spam = 0")
235 logging
.info("No new entries")
240 # loop over all unprocessed urls
244 msg
= "Processing ({}%)".format(round(num
/ len(rows
) * 100))
245 print(msg
, end
="\r", flush
=True)
247 url
= "{}raw".format(row
[0])
248 logging
.debug("Processing {}".format(url
))
249 mbox
= fetch_url(url
)
250 classification
= classify_content(mbox
)
252 if classification
== ContentType
.PATCH
:
253 logging
.debug("Processing patch ({})".format(row
[0]))
254 branch
= process_patch(mbox
, num
, remote
)
256 if classification
== ContentType
.PULL_REQUEST
:
257 logging
.debug("Processing PR ({})".format(row
[0]))
258 branch
= process_pr(row
[0], num
, remote
)
260 if classification
== ContentType
.SPAM
:
261 logging
.debug("Marking spam ({})".format(row
[0]))
262 c
.execute("UPDATE firmware SET spam = 1 WHERE url = ?", (row
[0],))
264 if classification
== ContentType
.REPLY
:
265 logging
.debug("Ignoring reply ({})".format(row
[0]))
267 c
.execute("UPDATE firmware SET processed = 1 WHERE url = ?", (row
[0],))
269 print(" " * len(msg
), end
="\r", flush
=True)
276 reply_email(mbox
, branch
)
278 logging
.info("Finished processing {} new entries".format(len(rows
)))
281 if __name__
== "__main__":
282 parser
= argparse
.ArgumentParser(description
="Process linux-firmware mailing list")
283 parser
.add_argument("--url", default
=URL
, help="URL to get ATOM feed from")
286 default
=os
.path
.join("contrib", "linux_firmware.db"),
287 help="sqlite database to store entries in",
289 parser
.add_argument("--dry", action
="store_true", help="Don't open pull requests")
291 "--debug", action
="store_true", help="Enable debug logging to console"
293 parser
.add_argument("--remote", default
="origin", help="Remote to push to")
295 "--refresh-cycle", default
=0, help="How frequently to run (in minutes)"
297 args
= parser
.parse_args()
299 if not os
.path
.exists("WHENCE"):
301 "Please run this script from the root of the linux-firmware repository"
307 "{prefix}-{date}.{suffix}".format(
308 prefix
="linux_firmware", suffix
="txt", date
=date
.today()
312 format
="%(asctime)s %(levelname)s:\t%(message)s",
318 # set a format which is simpler for console use
319 console
= logging
.StreamHandler()
321 console
.setLevel(logging
.DEBUG
)
323 console
.setLevel(logging
.INFO
)
324 formatter
= logging
.Formatter("%(asctime)s : %(levelname)s : %(message)s")
325 console
.setFormatter(formatter
)
326 logging
.getLogger("").addHandler(console
)
329 conn
= sqlite3
.connect(args
.database
)
330 # update the database
331 update_database(conn
, args
.url
)
338 # process the database
339 process_database(conn
, remote
)
343 if args
.refresh_cycle
:
344 logging
.info("Sleeping for {} minutes".format(args
.refresh_cycle
))
345 time
.sleep(int(args
.refresh_cycle
) * 60)