Parse conventional commits

Release tools read commit messages written as type(scope): description. Write the parser.

What to build

A program that parses commit messages in the conventional style.

Requirements

  • A message is valid if it has the text : (a colon and a space) and the part before it, the head, is TYPE or TYPE(SCOPE), where TYPE is one of feat, fix, docs, test or chore, SCOPE is not empty, and the description after the colon is not blank.
  • For a valid message print N: type=TYPE scope=SCOPE desc=DESCRIPTION, with - as the scope when there is none. Remove spaces at both ends of the message and of the description.
  • For any other message print N: invalid.

Input

The first line has n (1 to 50). Each of the next n lines is a message. Number the messages from 1.

Output

n lines.

Constraints

1 ≤ n ≤ 50.

Example

Input:

3
feat(parser): support nested lists
docs: explain the install steps
update stuff

Output:

1: type=feat scope=parser desc=support nested lists
2: type=docs scope=- desc=explain the install steps
3: invalid

Why it works

Splitting once at the first colon and space separates the head from the description, and the head is then checked piece by piece, so every malformed message is rejected by exactly one failed check.

Examples

Example 1 · Input
3
feat(parser): support nested lists
docs: explain the install steps
update stuff
Expected output
1: type=feat scope=parser desc=support nested lists
2: type=docs scope=- desc=explain the install steps
3: invalid
Example 2 · Input
2
fix(cli): exit with code 1
chore: bump version
Expected output
1: type=fix scope=cli desc=exit with code 1
2: type=chore scope=- desc=bump version

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Split at the first ": " with message.partition(": ").

Hint 2

If the head has "(", it must end with ")" and the scope sits between the brackets.

Hint 3

Check the type, the scope and the description, and print invalid if any check fails.

Solution

Show one correct solution (try it yourself first)
TYPES = ["feat", "fix", "docs", "test", "chore"]
n = int(input())
for number in range(1, n + 1):
    message = input().strip()
    head, sep, description = message.partition(": ")
    description = description.strip()
    kind, scope, valid = head, "-", True
    if not sep or not description:
        valid = False
    elif "(" in head:
        kind, _, rest = head.partition("(")
        if not rest.endswith(")") or len(rest) < 2:
            valid = False
        else:
            scope = rest[:-1]
    if valid and kind not in TYPES:
        valid = False
    if valid:
        print(f"{number}: type={kind} scope={scope} desc={description}")
    else:
        print(f"{number}: invalid")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Commits and branches →