Update to labeler v2 (#4)

* labeler v2

* update docs
This commit is contained in:
Shawn Napora
2019-08-08 13:07:40 -04:00
committed by Danny McCormick
parent ab3b5b5adc
commit 7d083c498f
21 changed files with 5592 additions and 1793 deletions

14
.github/main.workflow vendored
View File

@@ -1,14 +0,0 @@
workflow "Lint JavaScript" {
on = "push"
resolves = ["Lint", "Formatting"]
}
action "Lint" {
uses = "actions/npm@v2.0.0"
runs = "npx eslint --no-eslintrc --env es6 --parser-options ecmaVersion:2018 entrypoint.js"
}
action "Formatting" {
uses = "actions/npm@v2.0.0"
runs = "npx prettier -c --no-semi --no-bracket-spacing --single-quote entrypoint.js"
}

View File

@@ -1,76 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [INSERT EMAIL ADDRESS]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@@ -1,33 +0,0 @@
## Contributing
[fork]: https://github.com/actions/labeler/fork
[pr]: https://github.com/actions/labeler/compare
[code-of-conduct]: https://github.com/actions/labeler/blob/master/CODE_OF_CONDUCT.md
Hi there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great.
Contributions to this project are [released](https://help.github.com/articles/github-terms-of-service/#6-contributions-under-repository-license) to the public under the [project's open source license](LICENSE.md).
Please note that this project is released with a [Contributor Code of Conduct][code-of-conduct]. By participating in this project you agree to abide by its terms.
## Submitting a pull request
0. [Fork][fork] and clone the repository
0. Configure and install the dependencies: `script/bootstrap`
0. Make sure the tests pass on your machine: `rake`
0. Create a new branch: `git checkout -b my-branch-name`
0. Make your change, add tests, and make sure the tests still pass
0. Push to your fork and [submit a pull request][pr]
0. Pat your self on the back and wait for your pull request to be reviewed and merged.
Here are a few things you can do that will increase the likelihood of your pull request being accepted:
- Write tests.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
## Resources
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)
- [GitHub Help](https://help.github.com)

View File

@@ -1,20 +0,0 @@
FROM node:slim
LABEL "name"="labeler"
LABEL "maintainer"="GitHub Actions <support+actions@github.com>"
LABEL "version"="1.0.0"
LABEL "com.github.actions.name"="PR Labeller"
LABEL "com.github.actions.description"="An action that labels pull requests according to changed files"
LABEL "com.github.actions.icon"="tag"
LABEL "com.github.actions.color"="orange"
COPY *.md /
COPY package*.json ./
RUN npm ci
COPY entrypoint.js /entrypoint.js
ENTRYPOINT ["node", "/entrypoint.js"]

View File

@@ -1,6 +1,7 @@
MIT License
Copyright (c) 2019 GitHub
The MIT License (MIT)
Copyright (c) 2018 GitHub, Inc. and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -9,13 +10,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -1,50 +1,32 @@
# Pull Request Labeller
# Pull Request Labeler
This action labels pull requests by comparing their changed files to a configuration file in the repository.
Pull request labeler triages PRs based on the paths that are modified in the PR.
For example, a configuration file at `.github/triage.yml` may look like this:
To use, create a `.github/labeler.yml` file with a list of labels and [minimatch](https://github.com/isaacs/minimatch)
globs to match to apply the label.
```yaml
design:
- src/frontend/**/*.css
- src/frontend/**/*.png
server:
- src/server/**/*
Example:
```
label1:
- example1/**/*
And the action would be used like this:
label2: example2/*
```workflow
workflow "Apply PR labels" {
on = "pull_request"
resolves = "Apply labels"
}
action "On sync" {
uses = "actions/bin/filter@master"
args = "action synchronize"
}
action "Apply labels" {
uses = "actions/labeller@v1.0.0"
needs = "On sync"
env = {LABEL_SPEC_FILE=".github/triage.yml"}
secrets = ["GITHUB_TOKEN"]
}
label3:
- example3/*
- example3/**/*.yml
```
Then create a workflow:
```
name: "Pull Request Labeler"
on:
- pull-request
Now, whenever a user pushes to a pull request, this action will determine whether any changed files in that pull request match the specification file (note: this action uses [minimatch](https://github.com/isaacs/minimatch) to determine matches). If there are matches, the action will apply the appropriate labels to the pull request.
## Contributing
Check out [this doc](CONTRIBUTING.md).
## License
This action is released under the [MIT license](LICENSE.md).
Container images built with this project include third party materials. See [THIRD_PARTY_NOTICE.md](THIRD_PARTY_NOTICE.md) for details.
## Current Status
This action is in active development.
jobs:
triage:
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@v2
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
```

File diff suppressed because it is too large Load Diff

4
__tests__/main.test.ts Normal file
View File

@@ -0,0 +1,4 @@
describe('TODO - Add a test suite', () => {
it('TODO - Add a test', async () => {
});
});

12
action.yml Normal file
View File

@@ -0,0 +1,12 @@
name: 'Pull Request Triager'
description: 'Label pull requests by files altered'
author: 'GitHub'
inputs:
repo-token:
description: 'The GITHUB_TOKEN secret'
configuration-path:
description: 'The path for the label configurations'
default: '.github/labeler.yml'
runs:
using: 'node12'
main: 'lib/main.js'

22
docs/contributors.md Normal file
View File

@@ -0,0 +1,22 @@
# Contributors
### Checkin
- Do checkin source (src)
- Do checkin build output (lib)
- Do checkin runtime node_modules
- Do not checkin devDependency node_modules (husky can help see below)
### devDependencies
In order to handle correctly checking in node_modules without devDependencies, we run [Husky](https://github.com/typicode/husky) before each commit.
This step ensures that formatting and checkin rules are followed and that devDependencies are excluded. To make sure Husky runs correctly, please use the following workflow:
```
npm install # installs all devDependencies including Husky
git add abc.ext # Add the files you've changed. This should include files in src, lib, and node_modules (see above)
git commit -m "Informative commit message" # Commit. This will run Husky
```
During the commit step, Husky will take care of formatting all files with [Prettier](https://github.com/prettier/prettier) as well as pruning out devDependencies using `npm prune --production`.
It will also make sure these changes are appropriately included in your commit (no further work is needed)

View File

@@ -1,103 +0,0 @@
const {Toolkit} = require('actions-toolkit')
const fs = require('fs')
const minimatch = require('minimatch')
const yaml = require('js-yaml')
const tools = new Toolkit()
main().catch(err => {
tools.log.fatal(err)
tools.exit.failure()
})
async function main() {
const specFile = readSpecFile()
const changedFiles = await getChangedFiles()
for (const label in specFile) {
let globs
if (typeof specFile[label] === 'string') {
globs = [specFile[label]]
} else if (Array.isArray(specFile[label])) {
globs = specFile[label]
} else {
throw new Error('Spec file values must be strings or arrays of strings')
}
for (const glob of globs) {
for (const changedFile of changedFiles) {
if (minimatch(changedFile, glob)) {
await tools.github.issues.addLabels(
tools.context.issue({labels: [label]})
)
}
}
}
}
}
async function getChangedFiles(changedFiles = [], cursor = null) {
const [nextCursor, paths] = await queryChangedFiles(cursor)
if (paths.length < 100) {
return changedFiles.concat(paths)
}
return getChangedFiles(changedFiles.concat(paths), nextCursor)
}
async function queryChangedFiles(cursor) {
const result = await tools.github.graphql(
`
query($owner: String!, $repo: String!, $number: Int!, $cursor: String) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
files(first: 100, after: $cursor) {
edges {
cursor
}
nodes {
path
}
}
}
}
}
`,
tools.context.issue({cursor})
)
const nextCursor = result.repository.pullRequest.files.edges.cursor
const paths = result.repository.pullRequest.files.nodes.map(node => node.path)
return [nextCursor, paths]
}
function readSpecFile() {
const specFilePath = process.env.LABEL_SPEC_FILE
let specFile
try {
specFile = yaml.safeLoad(fs.readFileSync(specFilePath))
} catch (err) {
if (err.code === 'ERR_INVALID_ARG_TYPE') {
tools.log.error('You must provide a LABEL_SPEC_FILE environment variable')
}
if (err.code === 'ENOENT') {
tools.log.error(
`Expected a configuration file at "${specFilePath}", but no file was found`
)
}
if (err.name === 'YAMLException') {
tools.log.error('Configuration file is not valid YAML')
}
throw err
}
return specFile
}

11
jest.config.js Normal file
View File

@@ -0,0 +1,11 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
testRunner: 'jest-circus/runner',
transform: {
'^.+\\.ts$': 'ts-jest'
},
verbose: true
}

5424
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,54 @@
{
"name": "action-labeller",
"name": "labeler",
"version": "2.0.0",
"private": true,
"description": "Labels pull requests by files altered",
"main": "lib/main.js",
"scripts": {
"build": "tsc",
"format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/labeler.git"
},
"keywords": [
"actions",
"node",
"setup"
],
"author": "GitHub",
"license": "MIT",
"main": "index.js",
"dependencies": {
"actions-toolkit": "^1.6.0",
"js-yaml": "^3.13.0",
"minimatch": "^3.0.4"
"@actions/core": "file:toolkit/actions-core-0.0.0.tgz",
"@actions/exec": "file:toolkit/actions-exec-0.0.0.tgz",
"@actions/github": "file:toolkit/actions-github-0.0.0.tgz",
"@actions/io": "file:toolkit/actions-io-0.0.0.tgz",
"@actions/tool-cache": "file:toolkit/actions-tool-cache-0.0.0.tgz",
"js-yaml": "^3.13.1",
"minimatch": "^3.0.4",
"semver": "^6.1.1"
},
"devDependencies": {
"@types/jest": "^24.0.13",
"@types/node": "^12.0.4",
"@types/semver": "^6.0.0",
"@types/minimatch": "^3.0.0",
"@types/js-yaml": "^3.12.1",
"husky": "^2.3.0",
"jest": "^24.8.0",
"jest-circus": "^24.7.1",
"prettier": "^1.17.1",
"ts-jest": "^24.0.2",
"typescript": "^3.5.1"
},
"husky": {
"skipCI": true,
"hooks": {
"pre-commit": "npm run build && npm run format",
"post-commit": "npm prune --production && git add node_modules/* && git commit -m \"Husky commit correct node modules\""
}
}
}

146
src/main.ts Normal file
View File

@@ -0,0 +1,146 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
import * as yaml from 'js-yaml';
import {Minimatch} from 'minimatch';
async function run() {
try {
const token = core.getInput('repo-token', {required: true});
const configPath = core.getInput('configuration-path', {required: true});
const prNumber = getPrNumber();
if (!prNumber) {
console.log('Could not get pull request number from context, exiting');
return;
}
const client = new github.GitHub(token);
core.debug(`fetching changed files for pr #${prNumber}`);
const changedFiles: string[] = await getChangedFiles(client, prNumber);
const labelGlobs: Map<string, string[]> = await getLabelGlobs(
client,
configPath
);
const labels: string[] = [];
for (const [label, globs] of labelGlobs.entries()) {
core.debug(`processing ${label}`);
if (checkGlobs(changedFiles, globs)) {
labels.push(label);
}
}
if (labels.length > 0) {
await addLabels(client, prNumber, labels);
}
} catch (error) {
core.error(error);
core.setFailed(error.message);
}
}
function getPrNumber(): number | undefined {
const pullRequest = github.context.payload.pull_request;
if (!pullRequest) {
return undefined;
}
return pullRequest.number;
}
async function getChangedFiles(
client: github.GitHub,
prNumber: number
): Promise<string[]> {
const listFilesResponse = await client.pulls.listFiles({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: prNumber
});
const changedFiles = listFilesResponse.data.map(f => f.filename);
core.debug('found changed files:');
for (const file of changedFiles) {
core.debug(' ' + file);
}
return changedFiles;
}
async function getLabelGlobs(
client: github.GitHub,
configurationPath: string
): Promise<Map<string, string[]>> {
const configurationContent: string = await fetchContent(
client,
configurationPath
);
// loads (hopefully) a `{[label:string]: string | string[]}`, but is `any`:
const configObject: any = yaml.safeLoad(configurationContent);
// transform `any` => `Map<string,string[]>` or throw if yaml is malformed:
return getLabelGlobMapFromObject(configObject);
}
async function fetchContent(
client: github.GitHub,
repoPath: string
): Promise<string> {
const response = await client.repos.getContents({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
path: repoPath
});
return Buffer.from(response.data.content, 'base64').toString();
}
function getLabelGlobMapFromObject(configObject: any): Map<string, string[]> {
const labelGlobs: Map<string, string[]> = new Map();
for (const label in configObject) {
if (typeof configObject[label] === 'string') {
labelGlobs.set(label, [configObject[label]]);
} else if (configObject[label] instanceof Array) {
labelGlobs.set(label, configObject[label]);
} else {
throw Error(
`found unexpected type for label ${label} (should be string or array of globs)`
);
}
}
return labelGlobs;
}
function checkGlobs(changedFiles: string[], globs: string[]): boolean {
for (const glob of globs) {
core.debug(` checking pattern ${glob}`);
const matcher = new Minimatch(glob);
for (const changedFile of changedFiles) {
core.debug(` - ${changedFile}`);
if (matcher.match(changedFile)) {
core.debug(` ${changedFile} matches`);
return true;
}
}
}
return false;
}
async function addLabels(
client: github.GitHub,
prNumber: number,
labels: string[]
) {
await client.issues.addLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: prNumber,
labels: labels
});
}
run();

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

63
tsconfig.json Normal file
View File

@@ -0,0 +1,63 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./lib", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
},
"exclude": ["node_modules", "**/*.test.ts"]
}