]>
git.proxmox.com Git - mirror_linux-firmware.git/blob - contrib/process_linux_firmware.py
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 reply
["To"] = ", ".join(
83 email
.utils
.formataddr(t
)
84 for t
in email
.utils
.getaddresses(
85 orig
.get_all("from", []) + orig
.get_all("to", []) + orig
.get_all("cc", [])
89 reply
["From"] = "linux-firmware@kernel.org"
90 reply
["Subject"] = "Re: {}".format(orig
["Subject"])
91 reply
["In-Reply-To"] = orig
["Message-Id"]
92 reply
["References"] = orig
["Message-Id"]
93 reply
["Thread-Topic"] = orig
["Thread-Topic"]
94 reply
["Thread-Index"] = orig
["Thread-Index"]
97 "Your request has been forwarded by the Linux Firmware Kernel robot.\n"
98 "Please follow up at https://gitlab.com/kernel-firmware/linux-firmware/-/merge_requests to ensure it gets merged\n"
99 "Your request is '{}'".format(branch
)
101 reply
.set_content(content
)
103 mailserver
= smtplib
.SMTP(server
, port
)
105 mailserver
.starttls()
107 mailserver
.login(user
, password
)
108 mailserver
.sendmail(reply
["From"], reply
["To"], reply
.as_string())
112 def create_pr(remote
, branch
):
120 "merge_request.create",
122 "merge_request.remove_source_branch",
124 "merge_request.target=main",
126 "merge_request.title={}".format(branch
),
131 def refresh_branch():
132 quiet_cmd(["git", "checkout", "main"])
133 quiet_cmd(["git", "pull"])
136 def delete_branch(branch
):
137 quiet_cmd(["git", "checkout", "main"])
138 quiet_cmd(["git", "branch", "-D", branch
])
141 def process_pr(url
, num
, remote
):
142 branch
= "robot/pr-{}-{}".format(num
, int(time
.time()))
143 cmd
= ["b4", "pr", "-b", branch
, url
]
146 except subprocess
.CalledProcessError
:
147 logging
.warning("Failed to apply PR")
150 # determine if it worked (we can't tell unfortunately by return code)
151 cmd
= ["git", "branch", "--list", branch
]
152 logging
.debug("Running {}".format(cmd
))
153 result
= subprocess
.check_output(cmd
)
156 logging
.info("Forwarding PR for {}".format(branch
))
158 create_pr(remote
, branch
)
159 delete_branch(branch
)
164 def process_patch(mbox
, num
, remote
):
165 # create a new branch for the patch
166 branch
= "robot/patch-{}-{}".format(num
, int(time
.time()))
167 cmd
= ["git", "checkout", "-b", branch
]
172 logging
.debug("Running {}".format(cmd
))
173 p
= subprocess
.Popen(
174 cmd
, stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
176 stdout
, stderr
= p
.communicate(mbox
.encode("utf-8"))
177 for line
in stdout
.splitlines():
178 logging
.debug(line
.decode("utf-8"))
179 for line
in stderr
.splitlines():
180 logging
.debug(line
.decode("utf-8"))
181 if p
.returncode
!= 0:
182 quiet_cmd(["git", "am", "--abort"])
184 logging
.info("Opening PR for {}".format(branch
))
186 create_pr(remote
, branch
)
188 delete_branch(branch
)
189 if p
.returncode
== 0:
194 def update_database(conn
, url
):
198 """CREATE TABLE IF NOT EXISTS firmware (url text, processed integer default 0, spam integer default 0)"""
202 if os
.path
.exists(url
):
203 with
open(url
, "r") as f
:
207 logging
.info("Fetching {}".format(url
))
208 atom
= fetch_url(url
)
210 # Parse the atom and extract the URLs
211 feed
= feedparser
.parse(atom
)
213 # Insert the URLs into the database (oldest first)
214 feed
["entries"].reverse()
215 for entry
in feed
["entries"]:
216 c
.execute("SELECT url FROM firmware WHERE url = ?", (entry
.link
,))
219 c
.execute("INSERT INTO firmware VALUES (?, ?, ?)", (entry
.link
, 0, 0))
221 # Commit the changes and close the connection
225 def process_database(conn
, remote
):
228 # get all unprocessed urls that aren't spam
229 c
.execute("SELECT url FROM firmware WHERE processed = 0 AND spam = 0")
236 logging
.info("No new entries")
241 # loop over all unprocessed urls
245 msg
= "Processing ({}%)".format(round(num
/ len(rows
) * 100))
246 print(msg
, end
="\r", flush
=True)
248 url
= "{}raw".format(row
[0])
249 logging
.debug("Processing {}".format(url
))
250 mbox
= fetch_url(url
)
251 classification
= classify_content(mbox
)
253 if classification
== ContentType
.PATCH
:
254 logging
.debug("Processing patch ({})".format(row
[0]))
255 branch
= process_patch(mbox
, num
, remote
)
257 if classification
== ContentType
.PULL_REQUEST
:
258 logging
.debug("Processing PR ({})".format(row
[0]))
259 branch
= process_pr(row
[0], num
, remote
)
261 if classification
== ContentType
.SPAM
:
262 logging
.debug("Marking spam ({})".format(row
[0]))
263 c
.execute("UPDATE firmware SET spam = 1 WHERE url = ?", (row
[0],))
265 if classification
== ContentType
.REPLY
:
266 logging
.debug("Ignoring reply ({})".format(row
[0]))
268 c
.execute("UPDATE firmware SET processed = 1 WHERE url = ?", (row
[0],))
270 print(" " * len(msg
), end
="\r", flush
=True)
277 reply_email(mbox
, branch
)
279 logging
.info("Finished processing {} new entries".format(len(rows
)))
282 if __name__
== "__main__":
283 parser
= argparse
.ArgumentParser(description
="Process linux-firmware mailing list")
284 parser
.add_argument("--url", default
=URL
, help="URL to get ATOM feed from")
287 default
=os
.path
.join("contrib", "linux_firmware.db"),
288 help="sqlite database to store entries in",
290 parser
.add_argument("--dry", action
="store_true", help="Don't open pull requests")
292 "--debug", action
="store_true", help="Enable debug logging to console"
294 parser
.add_argument("--remote", default
="origin", help="Remote to push to")
296 "--refresh-cycle", default
=0, help="How frequently to run (in minutes)"
298 args
= parser
.parse_args()
300 if not os
.path
.exists("WHENCE"):
302 "Please run this script from the root of the linux-firmware repository"
308 "{prefix}-{date}.{suffix}".format(
309 prefix
="linux_firmware", suffix
="txt", date
=date
.today()
313 format
="%(asctime)s %(levelname)s:\t%(message)s",
319 # set a format which is simpler for console use
320 console
= logging
.StreamHandler()
322 console
.setLevel(logging
.DEBUG
)
324 console
.setLevel(logging
.INFO
)
325 formatter
= logging
.Formatter("%(asctime)s : %(levelname)s : %(message)s")
326 console
.setFormatter(formatter
)
327 logging
.getLogger("").addHandler(console
)
330 conn
= sqlite3
.connect(args
.database
)
331 # update the database
332 update_database(conn
, args
.url
)
339 # process the database
340 process_database(conn
, remote
)
344 if args
.refresh_cycle
:
345 logging
.info("Sleeping for {} minutes".format(args
.refresh_cycle
))
346 time
.sleep(int(args
.refresh_cycle
) * 60)