Simplify User ID parsing (#1862)

This commit is contained in:
martgil 2025-06-12 18:27:42 +08:00 committed by GitHub
parent b31bc89854
commit 66baa5f57b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -87,15 +87,36 @@ class UserIDPacket {
* The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`, * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,
* since they interfere with `comment` parsing. * since they interfere with `comment` parsing.
*/ */
const re = /^(?<name>[^()]+\s+)?(?<comment>\([^()]+\)\s+)?(?<email><\S+@\S+>)$/;
const matches = re.exec(userID); const isValidEmail = str => /^[^\s@]+@[^\s@]+$/.test(str); // enforce single @ and no whitespace
if (matches !== null) { const firstBracket = userID.indexOf('<');
const { name, comment, email } = matches.groups; const lastBracket = userID.lastIndexOf('>');
this.comment = comment?.replace(/^\(|\)|\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace if (
this.name = name?.trim() || ''; firstBracket !== -1 &&
this.email = email.substring(1, email.length - 1); // remove brackets lastBracket !== -1 &&
} else if (/^[^\s@]+@[^\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace lastBracket > firstBracket
this.email = userID; ) {
const potentialEmail = userID.substring(firstBracket + 1, lastBracket);
if (isValidEmail(potentialEmail)) {
this.email = potentialEmail;
const beforeEmail = userID.substring(0, firstBracket).trim();
const firstParen = beforeEmail.indexOf('(');
const lastParen = beforeEmail.lastIndexOf(')');
if (firstParen !== -1 && lastParen !== -1 && lastParen > firstParen) {
this.comment = beforeEmail
.substring(firstParen + 1, lastParen)
.trim();
this.name = beforeEmail.substring(0, firstParen).trim();
} else {
this.name = beforeEmail;
this.comment = '';
}
}
} else if (isValidEmail(userID.trim())) {
// unbracketed email case
this.email = userID.trim();
this.name = '';
this.comment = '';
} }
this.userID = userID; this.userID = userID;