Skip to content

Commit

Permalink
Upload Action
Browse files Browse the repository at this point in the history
  • Loading branch information
nivisi committed Dec 28, 2023
1 parent 864f40f commit 1a3f48b
Show file tree
Hide file tree
Showing 532 changed files with 192,815 additions and 2 deletions.
100 changes: 98 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,98 @@
# conventional_pull_requests
❤️‍🩹 A GitHub Action that helps to maintain conventional pull request names.
# Conventional Pull Requests [![version][version-img]][version-url]

❤️‍🩹 A GitHub Action that helps to maintain [conventional](https://www.conventionalcommits.org/en/v1.0.0/) pull request names.

## Overview

This GitHub Action designed to automate the validation and correction of Pull Request (PR) titles in collaborative software development environments. This Action helps maintain consistency and clarity in PR naming conventions, ensuring that all PRs adhere to predefined formatting rules.

## Features

- Validation: Checks if PR titles conform to specified formatting rules.
- Automatic Correction: Where possible, automatically corrects PR titles to meet the standards.
- Commenting: Posts a comment on the PR when a correction is made, providing visibility and feedback.

## Usage

To use this GitHub Action in your project, set up the workflow file:
- Create a `.github/workflows` directory in your repository if it doesn't exist.
- Add a new YAML file (e.g., `conventional-prs.yml`) in this directory.
- Define the workflow to trigger on PR events and run the Validator.

### Example

```yml
name: Convenitonal Pull Requests

on:
pull_request:
types:
# Configure these types yourself!
- opened
- edited
- reopened
- synchronize

workflow_dispatch:

jobs:
validate:

runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v2

- name: Validate PR Use Cases
uses: nivisi/conventional_pull_requests@1.0.0
with:
# GitHub Access Token
# Required. Default is ${{ github.token }}
github-token: ${{ github.token }}

# Message that will be posted as a comment in the PR
# In case the script finds an issue and will be capable of fixing it.
# {AUTHOR} will be the author of the PR
# {DIFF} is a suggested difference (old title vs new title)
message-to-post: |
Hey @{AUTHOR} 👋 I'm the PR Bot! 🤖 I noticed that the title of this Pull Request didn't match the required schema, so I've made a quick fix:
{DIFF}
```
## Examples
### Valid PR Titles
- `fix(ABC-1): Updates the UI of the Search Page`: Correct format with type, ticket number, and task description.
- `feat: New screen introduced`: Valid format with only type and task description.
- `feat(ABC-5,ABC-10): Something happened`: Correct format with multiple ticket numbers.

### Invalid PR Titles

### Auto-fixable

- `feat (ABC-10): Introduces new feature`: Invalid due to space before the colon.
- `fix(ABC-1) : Updates the UI`: Invalid due to space after ticket number and before the colon.
- `Feat(ABC-123): Adds feature`: Invalid due to uppercase type.
- `feat(abc-123): New feature`: Invalid due to lowercase ticket number.
- `feat(123-ABC): Wrong format`: Invalid ticket format.
- `feat(ABC-123,abc-456): Multi tickets`: Invalid due to lowercase ticket number in the second ticket.

### Not auto-fixable
- `: Implemented new algorithm`: Invalid due to missing type.
- `feat(): Empty ticket number`: Invalid due to empty ticket number.

## Contributing

Contributions to improve the Validator GitHub Action are welcome. Feel free to fork the repository, make your changes, and submit a pull request.

## TODO

- Follow more rules from the [ruleset](https://www.conventionalcommits.org/en/v1.0.0/#specification)
- Allow to restrict ticket prefixes

<!-- References -->
[version-img]: https://img.shields.io/badge/action-v1.0.0-black?logo=github
[version-url]: https://github.com/marketplace/actions/conventional_pull_requests
23 changes: 23 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: "Conventional Pull Requests"
description: "Checks that PR names follow the conventional commit structure. Tries to fix issues if possible."
branding:
icon: git-pull-request
color: green
inputs:
github-token:
description: "GitHub Access Token"
default: ${{ github.token }}
required: true
message-to-post:
description: "A message that will be posted as a comment. If not provided, no message is posted."
required: false
outputs:
is-valid:
description: "Whether the title is valid."
valid-title:
description: "Updated PR Title that is valid."
suggested-diff:
description: "A diff block that contains invalid and valid titles."
runs:
using: "node20"
main: "index.js"
51 changes: 51 additions & 0 deletions helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
function isValidTicketNumberFormat(ticketNumber) {
const upperCaseTicketNumber = ticketNumber.toUpperCase();
const ticketNumberRegex = /^[A-Z]+-\d+(\,[A-Z]+-\d+)*$/;
return ticketNumberRegex.test(upperCaseTicketNumber);
}

function validateType(prName) {
const typeSegment = prName.split(':')[0];
const typePart = typeSegment.includes('(') ? typeSegment.split('(')[0].trim() : typeSegment.trim();
return typePart.toLowerCase();
}

function validateTickets(prName) {
const ticketNumberMatch = prName.match(/\(([^\)]*)\)/);
if (!ticketNumberMatch) return '';
const ticketNumberSegment = ticketNumberMatch[1].trim().toUpperCase();
if (!isValidTicketNumberFormat(ticketNumberSegment)) {
return ''; // Return empty string if format is invalid
}
return `(${ticketNumberSegment})`; // Keep the valid format
}

function validateTask(prName) {
// Split the PR name by colon and take all parts after the first colon
const taskSegments = prName.split(':').slice(1);

// Join the segments back together to form the full task description
const taskDescription = taskSegments.join(':').trim();

return taskDescription;
}

function validatePrTitle(title) {
const type = validateType(title);
const tickets = validateTickets(title);
const task = validateTask(title);

if (!type || !task) {
return { isValid: false, validTitle: null, error: 'Invalid PR name format' };
}

const correctedPrTitle = `${type}${tickets}: ${task}`;
const isPrTitleValid = title === correctedPrTitle;

return { isValid: isPrTitleValid, validTitle: correctedPrTitle };
}


export default {
validatePrTitle
};
106 changes: 106 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
JavaScript Script for PR (Pull Request) Naming Validation
Overview:
This script validates and corrects the naming of pull requests (PRs) based
on specific formatting rules. It is designed for collaborative development
environments to ensure consistency and clarity in PR naming.
Functionality:
- Validates PR names against predefined rules.
- Corrects names where possible or flags them as invalid.
Use Cases:
1. Valid Scenarios:
- "fix(ABC-1): Updates the UI of the Search Page": Correct format with
type, ticket number, and task description.
- "feat: New screen introduced": Valid format with only type and task
description.
- "feat(ABC-5,ABC-10): Something happened": Correct format with multiple
ticket numbers.
- "nit: Updates README": Valid format with type and task description,
without a ticket number.
2. Invalid Scenarios:
- ": Implemented new algorithm": Invalid due to missing type.
- "feat (ABC-10): Introduces new feature": Invalid due to space before
the colon.
- "fix(ABC-1) : Updates the UI": Invalid due to space after ticket number
and before the colon.
- "Feat(ABC-123): Adds feature": Invalid due to uppercase type.
- "feat(abc-123): New feature": Invalid due to lowercase ticket number.
- "feat(123-ABC): Wrong format": Invalid ticket format.
- "feat(): Empty ticket number": Invalid due to empty ticket number.
- "feat(ABC-123,abc-456): Multi tickets": Invalid due to lowercase ticket
number in the second ticket.
*/

import { getInput, setFailed, setOutput } from '@actions/core';
import github, { getOctokit } from '@actions/github';

import helpers from './helpers.js';

async function run() {
try {
const token = getInput('github-token');
var messageToPost = getInput('message-to-post');

const octokit = getOctokit(token);

const { context } = github;
const prTitle = context.payload.pull_request.title;
const prNumber = context.payload.pull_request.number;
const repoName = context.repo.repo;
const repoOwner = context.repo.owner;

const validationResult = helpers.validatePrTitle(prTitle);

setOutput('isValid', validationResult.isValid ?? false);

if (validationResult.isValid == true) {
return;
}

if (!validationResult.validTitle) {
return;
}

const suggestedDiff = `\`\`\`diff
- ${prTitle}
+ ${validationResult.validTitle}
\`\`\``;

setOutput('valid-title', validationResult.validTitle);
setOutput('suggested-diff', suggestedDiff);

console.log("Updating PR Name to be " + validationResult.validTitle);

// Update PR title
await octokit.rest.pulls.update({
owner: repoOwner,
repo: repoName,
pull_number: prNumber,
title: validationResult.validTitle,
});

if (!messageToPost) {
return;
}

messageToPost = messageToPost.replace("{AUTHOR}", context.payload.pull_request.user.login).replace("{DIFF}", suggestedDiff)

console.log("Adding a comment");

// Create a comment on the PR
await octokit.rest.issues.createComment({
owner: repoOwner,
repo: repoName,
issue_number: prNumber,
body: messageToPost,
});
} catch (error) {
setFailed(`Action failed with error: ${error}`);
}
}

run();
1 change: 1 addition & 0 deletions node_modules/.bin/uuid

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 1a3f48b

Please sign in to comment.