Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
352 changes: 181 additions & 171 deletions check_kernel_commits.py

Large diffs are not rendered by default.

675 changes: 374 additions & 301 deletions ciq-cherry-pick.py

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions ciq-tag.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#!/usr/bin/env python3

import ciq_tag
import click
import logging
import os
from enum import Enum
import sys
import logging
from enum import Enum

import click

import kt.ktlib.ciq_tag as ciq_tag

DEFAULT_LOGLEVEL = "INFO"

Expand Down
43 changes: 6 additions & 37 deletions jira_pr_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from jira import JIRA

from kt.ktlib.commit_header import CommitHeader
from release_config import jira_field_map, release_map

CVE_PATTERN = r"CVE-\d{4}-\d{4,7}"
Expand Down Expand Up @@ -154,47 +155,15 @@ def main():
sys.exit(1)

commit_msg = result.stdout.strip()
commit_header = CommitHeader.from_commit_body(commit_body=commit_msg)
print(commit_header)
lines = commit_msg.split("\n")

# Extract summary line (first line)
summary = lines[0] if lines else ""

# Extract header (start after first blank line, end at next blank line)
header_lines = []
in_header = False
vuln_tickets = []
commit_cves = []

for i, line in enumerate(lines):
if i == 0: # Skip summary line
continue
if not in_header and line.strip() == "": # First blank line, start of header
in_header = True
continue
if in_header and line.strip() == "": # Second blank line, end of header
break
if in_header:
header_lines.append(line)
stripped = line.strip()

# Check for jira line with VULN
if stripped.lower().startswith("jira ") and "vuln-" in stripped.lower():
parts = stripped.split()
for part in parts[1:]: # Skip 'jira' keyword
if part.upper().startswith("VULN-"):
vuln_tickets.append(part.upper())

# Check for CVE line
# Assume format: "cve CVE-YYYY-NNNN", "cve-bf CVE-YYYY-NNNN", or "cve-pre CVE-YYYY-NNNN"
# There will only be one CVE per line, but possibly multiple CVEs listed
if stripped.lower().startswith(("cve ", "cve-bf ", "cve-pre ")):
parts = stripped.split()
for part in parts[1:]: # Skip 'cve'/'cve-bf'/'cve-pre' keyword/tag
# CVES always start with CVE-
if part.upper().startswith("CVE-"):
commit_cves.append(part.upper())

header = "\n".join(header_lines)
vuln_tickets = [t.upper() for t in commit_header.jiras() if t.upper().startswith("VULN-")]
commit_cves = commit_header.all_cves()

# Check VULN tickets against merge target
lts_match = None
Expand Down Expand Up @@ -324,7 +293,7 @@ def main():
{
"sha": sha,
"summary": summary,
"header": header,
"header": commit_header.to_str(),
"full_message": commit_msg,
"vuln_tickets": vuln_tickets,
"lts_match": lts_match,
Expand Down
33 changes: 14 additions & 19 deletions kt/ktlib/ciq_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

import git

from kt.ktlib.commit_header import CommitHeader


def process_full_commit_message(commit):
"""Process the full git commit message specific to the CIQ Kernel Tools.
Expand Down Expand Up @@ -106,34 +108,26 @@ def get_backport_commit_data(repo, branch, common_ancestor, allow_duplicates=Fal
return upstream_commits, True


def CIQ_cherry_pick_commit_standardization(lines, commit, tags=None, jira="", optional_msg=""):
def CIQ_cherry_pick_commit_standardization(lines, commit_header: CommitHeader):
"""Standardize CIQ the cherry-pick commit message.
Parameters:
lines: Original SHAS commit message.
commit: The commit SHA1 that was cherry-picked.
tags: A list of tags to add to the commit message.
jira: The JIRA number to add to the commit message, this can be a comma separated list.
optional_msg: An optional message to add to the commit message. Traditionally used for `upstream-diff`.
commit_header: CommitHeader dataclass that represents ciq custom tags.

Return: The modified commit message passed in as lines.
"""

# assemble in reverse by inserting lines below first blank line (line 2)
lines.insert(2, "\n")
if optional_msg != "":
lines.insert(2, f"{optional_msg}\n")
lines.insert(2, f"commit {commit}\n")
if tags:
for tag in tags[::-1]:
lines.insert(2, f"{tag}\n")
if jira:
for i in jira.split(","):
lines.insert(2, f"jira {i.strip()}\n")
lines.insert(2, f"{commit_header.to_str()}\n")
Comment thread
Copilot marked this conversation as resolved.
Resolved

# We Need to indent lines that have email addresss as some tooling in the community
# will atttempt to read these lines and email everyone on the list. We do not want
# to annoy the community when doing our own work.
for i in range(5, len(lines)):
# The header is inserted as a single multi-line element, so the first body
# line sits at index 4; start there so a trailer with no prose body before
# it is still indented.
for i in range(4, len(lines)):
# The (cherry picked from commit <sha1>) line is the indicator we cherry-picked
if lines[i].lstrip().startswith("(cherry picked from commit"):
break
Expand All @@ -151,13 +145,13 @@ def CIQ_cherry_pick_commit_standardization(lines, commit, tags=None, jira="", op
return lines


def CIQ_original_commit_author_to_tag_string(repo_path, sha):
"""This will grab the original commit author and return the "tag" we use for the CIQ based header
def CIQ_original_commit_author(repo_path, sha):
"""This will return the original commit author
Parameters:
repo_path: pwd to the repository with the kernel mainline remote
sha: this is the full commit sha we're going to backport

Return: String for Tag
Return: String for author
"""
git_auth_res = subprocess.run(
["git", "show", '--pretty="%aN <%aE>"', "--no-patch", sha],
Expand All @@ -169,7 +163,8 @@ def CIQ_original_commit_author_to_tag_string(repo_path, sha):
print(f"[FAILED] git show --pretty='%aN <%aE>' --no-patch {sha}")
print(f"[FAILED][STDERR:{git_auth_res.returncode}] {git_auth_res.stderr.decode('utf-8')}")
return None
return "commit-author " + git_auth_res.stdout.decode("utf-8").replace('"', "").strip()

return git_auth_res.stdout.decode("utf-8").replace('"', "").strip()


def CIQ_run_git(repo_path, args):
Expand Down
7 changes: 6 additions & 1 deletion ciq_tag.py → kt/ktlib/ciq_tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ def keyword_regex_seeker(keyword_regex):
def seeker(string):
logger.debug(f"Searched text: {repr(string)}")
logger.debug(f"Regex: {repr(keyword_regex)}")
m = re.search(keyword_regex, string, re.MULTILINE)
# Case-insensitive: the pre-library helpers matched tags with
# re.IGNORECASE (e.g. 'Cve CVE-2026-1234'), keep that tolerance.
m = re.search(keyword_regex, string, re.MULTILINE | re.IGNORECASE)
logger.debug(f"Result: {m}")
return (m.start(), m.end(1), m.end()) if m else None

Expand Down Expand Up @@ -76,6 +78,9 @@ class CiqTag(Enum):
REBUILD_FUZZ = ["Rebuild_FUZZ"]
COMMIT_AUTHOR = ["commit-author"]
COMMIT = ["commit"]
COMMIT_SOURCE = ["commit-source"]
COMMIT_SOURCE_SHA = ["commit-source-sha"]
COMMIT_SOURCE_AUTHOR = ["commit-source-author"]
EMPTY_COMMIT = (["Empty-Commit"], True)
UPSTREAM_DIFF = (["upstream-diff"], True)

Expand Down
184 changes: 184 additions & 0 deletions kt/ktlib/commit_header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
from __future__ import annotations

import inspect
import re
from dataclasses import asdict, dataclass
from typing import Optional

from kt.ktlib.ciq_tag import CiqMsg


@dataclass
class CommitHeader:
"""
Name-field view of the CIQ tag block in a commit message.
At the moment it represents only commits for cve fixes.
"""

jira: Optional[str] = None
# TODO maybe have a union of these cve_bf, cve_pre and cve) idk
cve: Optional[str] = None
cve_bf: Optional[str] = None
cve_pre: Optional[str] = None
commit_author: Optional[str] = None
commit: Optional[str] = None
commit_source: Optional[str] = None
commit_source_sha: Optional[str] = None
commit_source_author: Optional[str] = None
upstream_diff: Optional[str] = None

# There are a pile of other tags that have not been codified consistently keep them rather than silently
# dropping them. Provides the option of using them in the future if needed.
extras: Optional[dict] = None

def __post_init__(self):
# Every value of every tag as parsed: not a dataclass field. Ignored by asdict()/to_str().
# populated by from_ciq_msg()
self._raw_tags: dict = {}

@classmethod
def from_dict(cls, env):
params = inspect.signature(cls).parameters
known = {k: v for k, v in env.items() if k in params and k != "extras"}
# CVE numbers are matched case-insensitively upstream and always stored
# upper-cased (CVE-\d{4}-\d+); tag values with extra prose are kept as-is.
for key in ("cve", "cve_bf", "cve_pre"):
value = known.get(key)
if value and re.fullmatch(r"(?i)cve-\d{4}-\d+", value.strip()):
known[key] = value.strip().upper()
extras = {k: v for k, v in env.items() if k not in params and v is not None}
header = cls(**known)
if extras:
header.extras = extras
return header

@classmethod
def from_ciq_msg(cls, ciq_msg: CiqMsg) -> CommitHeader:
# CiqMsg has multible values for tags and their values. The scalar
# fields keep the first value; every occurrence is collected in
# _raw_tags so callers (jiras(), upstream_commits()) can see them all.
msg_dict = {}
raw: dict = {}
for tag, value in ciq_msg._tags_dict.items():
# TODO a bug here around upstream-diff from CiqMsg, this is an workaround
if type(tag.value) is tuple:
name = tag.value[0][0]
else:
name = tag.value[0]

tag_name = name.replace("-", "_")
for v in value: # Collect all tags.
raw.setdefault(tag_name, []).append(v[1]._value)
msg_dict[tag_name] = raw[tag_name][0] # use the first value for the tag

header = cls.from_dict(msg_dict)
header._raw_tags = raw

return header

@classmethod
def from_commit_body(cls, commit_body: str) -> CommitHeader:
if commit_body and not commit_body.endswith("\n"):
commit_body += "\n"
ciq_msg = CiqMsg(commit_body)
return cls.from_ciq_msg(ciq_msg=ciq_msg)
Comment on lines +83 to +84

def to_str(self) -> str:
lines = []
for key, value in asdict(self).items():
if key == "extras" or not value:
continue
if key == "jira" and "," in value:
lines += [f"jira {t.strip()}" for t in value.split(",") if t.strip()]
else:
lines.append(f"{key.replace('_', '-')} {value}")

if self.extras:
lines += [f"{k.replace('_', '-')} {v}" for k, v in self.extras.items()]

return "\n".join(lines)

def jiras(self) -> list:
# Return a list of individual jira tickets. Handles both repeated
# `jira <ticket>` lines and comma-separated values on one line.
tickets = []
for value in self._raw_tags.get("jira", [self.jira]):
if not value:
continue
tickets += [t.strip() for t in value.split(",") if t.strip()]
return tickets

def upstream_commits(self) -> list:
# Return a list of upstream commits in a message, there should NOT be more than one but in the event there is
# return them all
if self._raw_tags and "commit" in self._raw_tags:
return [c for c in self._raw_tags["commit"] if c and c != "-"]
return [self.commit] if (self.commit and self.commit != "-") else []

def is_cve(self) -> bool:
return self.cve or self.cve_bf or self.cve_pre

# A commit header may have multiple cve tags. But we are interested if it has the cve tag, since that
# is the commit it represents
# If not cve tag, check cve-bf or cve-pre
# we may have situations where a commit has (cve, cve-pre) or (cve, cve-bf) because a deps may be a cve itself, because we do not enforce this, but our current tooling uses only tag
def cve_number(self) -> str:
if self.cve:
return self.cve

if self.cve_bf:
return self.cve_bf

if self.cve_pre:
return self.cve_pre

def set_cve(self, cve_number):
# Make sure only one cve tag is used
# Our current tooling uses only 1 tag at the moment, but this may change and result in a commit that has 2 cve tags (cve, cve-bf) or (cve, cve-pre) for commits that are deps but cve as well
original_tags = ", ".join(
f"{t} {v}" for t, v in (("cve", self.cve), ("cve-bf", self.cve_bf), ("cve-pre", self.cve_pre)) if v
)
self.cve_bf = None
self.cve_pre = None
self.cve = cve_number
print(f"CVE {cve_number} for hash {self.commit} and original tags {original_tags}")

def make_it_cve_bf(self):
# Interchange cve with cve-bf
if not self.is_cve():
return

# It already has a cve_bf val, it's fine
if self.cve_bf:
return

self.cve_bf = self.cve
self.cve = None

def all_cves(self) -> list:
"""Return a list of cve numbers.

A tag value may list several CVEs comma-separated (cve CVE-1, CVE-2);
split those into individual numbers.
"""

cves = []
for value in (self.cve, self.cve_bf, self.cve_pre):
if not value:
continue
cves += [c.strip() for c in value.split(",") if c.strip()]
Comment on lines +166 to +169

return cves

def extract_upstream_name_and_sha(self):
"""Return a pair of (commit_source, commit_source_sha) if source is not mainline
Otherwise returns (None, commit) if the source is mainline
"""

if self.commit_source_sha:
return (self.commit_source, self.commit_source_sha)

if self.commit and self.commit != "-":
return (None, self.commit)

return (None, None)
Loading
Loading