feat: create base

This commit is contained in:
Matyáš Caras 2024-07-30 15:26:09 +02:00
commit 25bbdc5160
Signed by: hernik
GPG key ID: 2A3175F98820C5C6
13 changed files with 45911 additions and 0 deletions

1
.github/freelo.txt vendored Normal file
View file

@ -0,0 +1 @@
hernikplays:191118

21
.github/workflows/run.yml vendored Normal file
View file

@ -0,0 +1,21 @@
name: Run the action
on:
workflow_dispatch:
issues:
types: [opened, edited, closed, reopened, assigned, unassigned]
issue_comment:
types: [created, edited, deleted]
jobs:
run-my-action:
name: Checks if this action works
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: ./
with:
email: ""
api-key: ""
project-id: ""
task-id: ""

176
.gitignore vendored Normal file
View file

@ -0,0 +1,176 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Caches
.cache
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
# Gatsby files
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store
lib

7
LICENSE Normal file
View file

@ -0,0 +1,7 @@
Copyright 2024 Matyáš Caras
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights 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 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.

55
README.md Normal file
View file

@ -0,0 +1,55 @@
# Freelo Synchronization GitHub action
This action can be used for a one-way synchronization of GitHub issues into [Freelo](https://freelo.io)
## How to use
Example action.yml showcasing all supported `on` calls:
```yml
name: Run the action
on:
workflow_dispatch:
issues:
types: [opened, edited, closed, reopened, assigned, unassigned]
issue_comment:
types: [created, edited, deleted]
jobs:
run-my-action:
name: Sync stuff to Freelo
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: hernikplays/freelo-action@v1
with:
email: ""
api-key: ""
project-id: ""
task-id: ""
```
### Linking GitHub users to Freelo users
The action will look for a `freelo.txt` file inside of your `.github` folder (the one where Action workflows are stored).
In it you can map GitHub usernames to Freelo IDs, one user per line:
```
hernikplays:14832
john_doe:6586
```
If the file cannot be found, no mapping will be done and the action will simply put the GitHub username in the task description.
In case the file is not formatted correctly or another error occures, the action will throw an error.
### Security
Because I have not found any documentation on how Freelo handles sanitization of input, I've included the usage of [sanitize-html](https://www.npmjs.com/package/sanitize-html) to sanitize any user input. The only allowed tags are `"a","p","i","b","strong"`
## License
```
Copyright 2024 Matyáš Caras
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights 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 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.
```

24
action.yml Normal file
View file

@ -0,0 +1,24 @@
name: 'Sync Issues to Freelo'
description: 'One-way synchronization of GitHub issues to Freelo'
author: 'Matyáš Caras'
inputs:
email:
description: 'The e-mail address used for Freelo authentication'
required: true
api-key:
description: 'The API key used for Freelo authentication'
required: true
project-id:
description: 'ID of the project where tasks should be created'
required: true
github-token:
description: 'Your GitHub token used to operate on your repository (should be secrets.GITHUB_TOKEN)'
required: true
task-id:
description: 'If not empty, will submit created issues as a subtask to the set task; either this or tasklist-id has to be entered.'
tasklist-id:
description: 'ID of the tasklist where tasks from GitHub issues should be created; either this or task-id has to be entered.'
runs:
using: 'node20'
main: 'dist/index.js'

15
biome.json Normal file
View file

@ -0,0 +1,15 @@
{
"$schema": "https://biomejs.dev/schemas/1.8.3/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"files": {
"ignore": ["dist/*"]
}
}

BIN
bun.lockb Executable file

Binary file not shown.

45410
dist/index.js vendored Normal file

File diff suppressed because one or more lines are too long

22
package.json Normal file
View file

@ -0,0 +1,22 @@
{
"name": "freelo-action",
"module": "src/index.ts",
"type": "module",
"devDependencies": {
"@biomejs/biome": "^1.8.3",
"@types/bun": "latest",
"@types/sanitize-html": "^2.11.0"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"scripts": {
"build": "bun build ./src/index.ts --target node --outfile dist/index.js"
},
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.0",
"axios": "^1.7.2",
"sanitize-html": "^2.13.0"
}
}

13
src/freelo.ts Normal file
View file

@ -0,0 +1,13 @@
interface Label {
name: string;
color: string;
}
interface NewTask {
name: string;
labels?: Label[];
worker?: number;
comment?: { content: string };
}
export type { NewTask, Label };

140
src/index.ts Normal file
View file

@ -0,0 +1,140 @@
import { getInput, setFailed } from "@actions/core";
import { context, getOctokit } from "@actions/github";
import axios from "axios";
import sanitize from "sanitize-html";
import type { NewTask } from "./freelo";
// user input
const email = getInput("email");
const apiKey = getInput("api-key");
const projectId = getInput("project-id");
const taskId = getInput("task-id");
const tasklistId = getInput("tasklist-id");
const token = getInput("github-token");
if (!token) {
setFailed("No GitHub token passed");
throw new Error("No GitHub token passed");
}
// values from action
const octokit = getOctokit(token);
const action = context.payload.action;
const issue = context.payload.issue;
const comment = context.payload.comment;
// constants
const apiEndpoint = "https://api.freelo.io/v1";
const defaultHeaders = {
"User-Agent": "Freelo GitHub Action/1.0.0",
"Content-Type": "application/json",
};
const sanitizeOptions: sanitize.IOptions = {
allowedTags: ["a", "p", "i", "b", "strong"],
allowedAttributes: false,
};
try {
if (!action) {
throw new Error("No action was passed");
}
if (!email || !apiKey || !projectId) {
throw new Error(
"You are missing a required parameter. Check the documentation for details.",
);
}
if (issue) {
// is a created/edited/closed etc. issue
if (issue.pull_request) {
throw new Error("Pull requests are not yet supported");
}
// depending on whether taskId or tasklistId is set, do something
if (!tasklistId && !taskId) {
throw new Error("Either task-id or tasklist-id needs to be set!");
}
// Load GitHub:Freelo pairing if available
let userPairing: string[] | undefined;
try {
userPairing = (await Bun.file(".github/freelo.txt").text()).split("\n");
} catch (_) {
console.log("No freelo.txt found in .github folder, skipping");
}
if (tasklistId) {
switch (action) {
case "created": {
// New issue has been created, create a task in tasklist
const author =
userPairing &&
userPairing.filter((u) => u.includes(issue.user.login)).length > 0
? `<div><span data-freelo-mention="1" data-freelo-user-id="${userPairing.filter((u) => u.includes(issue.user.login))[0].split(":")[1]}">@${issue.user.login}</span></div>`
: `@${issue.user.login}`;
const taskComment = `
Created by: ${author}
Description: ${sanitize(issue.body ?? "None", sanitizeOptions)}
GitHub issue: <a href="${issue.url}">#${issue.number}</a>
(This action was performed automatically)
`;
const taskContent: NewTask = {
name: issue.title,
comment: {
content: taskComment,
},
};
const res = await axios.post(
`${apiEndpoint}/project/${projectId}/tasklist/${tasklistId}/tasks`,
taskContent,
{
headers: defaultHeaders,
auth: {
username: email,
password: apiKey,
},
},
);
// handle potential error response
if (res.status > 399) {
console.error(res.data);
throw new Error("Got an error response from Freelo API");
}
// create an issue comment so we can track if the task has been already created
octokit.rest.issues.createComment({
issue_number: issue.number,
owner: context.payload.repository?.name ?? "",
repo: context.payload.repository?.name ?? "",
body: `Freelo task assigned: <a href="https://app.freelo.io/task/${res.data.id}">${res.data.id}</a><br>Please do not edit or delete this comment as it is used to prevent duplication of tasks.`,
});
break;
}
case "edited":
break;
case "closed":
break;
case "reopened":
break;
case "assigned":
break;
case "unassigned":
break;
default:
throw new Error("Unknown action passed");
}
}
} else if (comment) {
// should be an issue comment
} else {
throw new Error(
"You are running this action through an unsupported trigger",
);
}
} catch (error) {
setFailed((error as Error)?.message ?? "Unknown error");
}

27
tsconfig.json Normal file
View file

@ -0,0 +1,27 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}