Compare commits

...

80 Commits

Author SHA1 Message Date
TrymPet
7c9fa20219
Merge pull request #2 from stilobique/master
Update dependency
2024-02-12 11:30:21 +01:00
Aurelien Vaillant
3d18ab00c5
Merge pull request #1 from stilobique/upgrade-node-vs
Update action.yml
2024-02-10 16:41:13 +01:00
Aurelien Vaillant
20dadea389
Update action.yml 2024-02-10 16:12:30 +01:00
Trym Lund Flogard
a496fd037d Merge branch 'v2' of github.com:trympet/nextcloud-artifacts-action 2021-11-14 18:43:47 +01:00
Trym Lund Flogard
61ff55deae format 2021-11-14 18:43:26 +01:00
Trym Lund Flogard
b357f186aa delete temp file after zip 2021-11-14 18:42:22 +01:00
TrymPet
dec03f56e0
Update README.md 2021-07-15 01:35:30 +02:00
TrymPet
62e99ad6b2
Merge pull request #1 from dojineko/set-output
set output SHAREABLE_URL
2021-06-18 20:05:05 +02:00
dojineko
5825f9614a set output SHAREABLE_URL 2021-06-19 01:32:53 +09:00
Trym Lund Flogard
e1264cbb56 package and build 2021-06-08 17:11:30 +02:00
Trym Lund Flogard
7d73f7e889 update max content length 2021-06-08 17:10:34 +02:00
Trym Lund Flogard
81238124ba update package 2021-06-08 16:57:54 +02:00
Trym Lund Flogard
935313b418 use buffered upload 2021-06-08 16:56:45 +02:00
Trym Lund Flogard
995999b60c remove js file 2021-06-08 16:55:21 +02:00
Trym Lund Flogard
cd4f651c13 update workspace 2021-06-08 16:55:03 +02:00
TrymPet
c80beab5e4
Update README.md 2021-06-05 14:44:29 +02:00
Trym Lund Flogard
71897dd340 update name 2021-06-05 14:25:23 +02:00
Trym Lund Flogard
7ca2f4d4fb more cleanup 2021-06-05 14:21:53 +02:00
Trym Lund Flogard
2b05098faf remove unused param 2021-06-05 14:14:54 +02:00
Trym Lund Flogard
78aff342ff format 2021-06-05 14:12:01 +02:00
Trym Lund Flogard
bcd3d376b1 lint 2021-06-05 14:11:48 +02:00
Trym Lund Flogard
565777588d cleanup 2021-06-05 14:11:25 +02:00
Trym Lund Flogard
7fe0b3a0b9 test 2021-06-05 14:00:02 +02:00
Trym Lund Flogard
2e7f2059ee test 2021-06-05 13:57:28 +02:00
Trym Lund Flogard
f7ad337105 tesst 2021-06-05 13:54:25 +02:00
Trym Lund Flogard
b7837011bd test 2021-06-05 13:50:02 +02:00
Trym Lund Flogard
d363b4a3d0 fix IO await 2021-06-05 13:47:27 +02:00
Trym Lund Flogard
40bfed39fc await remote stream 2021-06-05 13:39:59 +02:00
Trym Lund Flogard
4ab7fcecfe set content type header 2021-06-05 13:34:52 +02:00
Trym Lund Flogard
a5df11eaca debug 2021-06-05 13:30:57 +02:00
Trym Lund Flogard
02b35dd9a1 error handling 2021-06-05 13:27:25 +02:00
Trym Lund Flogard
b52e167ab0 test 2021-06-05 13:21:45 +02:00
Trym Lund Flogard
a48c618622 test output link 2021-06-05 13:13:36 +02:00
Trym Lund Flogard
8167ea6a3e ignore tests 2021-06-05 13:10:53 +02:00
Trym Lund Flogard
7a45cee3de add simple integration test 2021-06-05 13:09:07 +02:00
Trym Lund Flogard
518c6f09f4 update formatting 2021-06-05 13:08:14 +02:00
Trym Lund Flogard
200441494b update rules 2021-06-05 11:58:22 +02:00
Trym Lund Flogard
68c752a9df eslint 2021-06-05 11:54:54 +02:00
Trym Lund Flogard
f07d8c68b0 update package json 2021-06-05 11:45:53 +02:00
Trym Lund Flogard
ea9ac9cb73 fix empty file 2021-06-02 21:09:26 +02:00
Trym Lund Flogard
c1ee7f2095 change ctor 2021-06-02 21:08:44 +02:00
Trym Lund Flogard
cfb60b9a7f test 2021-06-02 20:21:59 +02:00
Trym Lund Flogard
ab2bf8a4ac test 2021-06-02 20:19:43 +02:00
Trym Lund Flogard
51f5e63425 test 2021-06-02 20:12:51 +02:00
Trym Lund Flogard
cbff2d05e7 test 2021-06-02 20:10:05 +02:00
Trym Lund Flogard
6226379dbd test 2021-06-02 20:03:09 +02:00
Trym Lund Flogard
1f2878a134 test 2021-06-02 20:00:10 +02:00
Trym Lund Flogard
a96cb53d3a a 2021-06-02 19:56:10 +02:00
Trym Lund Flogard
4669814861 test 2021-06-02 19:53:32 +02:00
Trym Lund Flogard
4ac99d8b52 test 2021-06-02 19:51:36 +02:00
Trym Lund Flogard
3cf7a462d4 test 2021-06-02 19:45:24 +02:00
Trym Lund Flogard
a54a89d701 test 2021-06-02 19:39:26 +02:00
Trym Lund Flogard
0c1792a993 test 2021-06-02 19:38:09 +02:00
Trym Lund Flogard
e97b799152 test 2021-06-02 19:35:57 +02:00
Trym Lund Flogard
d873964202 test 2021-06-02 19:26:46 +02:00
Trym Lund Flogard
5b01b7a17b fix path format 2021-06-02 19:21:08 +02:00
Trym Lund Flogard
2431c40b14 test 2021-06-02 19:17:08 +02:00
Trym Lund Flogard
c38757acba test 2021-06-02 19:08:27 +02:00
Trym Lund Flogard
ae39220a7a test 2021-06-02 19:00:35 +02:00
Trym Lund Flogard
f5a8d5a548 test 2021-06-02 18:56:19 +02:00
Trym Lund Flogard
ac058f2460 test 2021-06-02 18:56:10 +02:00
Trym Lund Flogard
71d45ee738 test 2021-06-02 18:51:56 +02:00
Trym Lund Flogard
353b719074 test 2021-06-02 18:43:40 +02:00
Trym Lund Flogard
cb9c817940 test 2021-06-02 18:41:08 +02:00
Trym Lund Flogard
80a86a24ab test 2021-06-02 18:39:35 +02:00
Trym Lund Flogard
18228c6e6d test 2021-06-02 18:39:26 +02:00
Trym Lund Flogard
70ba52c79f build 2021-06-02 18:36:53 +02:00
Trym Lund Flogard
4e614273b8 more logging 2021-06-02 18:36:35 +02:00
Trym Lund Flogard
77a901b885 log response 2021-06-02 18:28:35 +02:00
Trym Lund Flogard
03e2a736d6 use dav client 2021-06-02 18:23:33 +02:00
Trym Lund Flogard
438fd898e1 test 2021-06-02 17:06:14 +02:00
Trym Lund Flogard
e8b44e8c3b test 2021-06-02 17:04:43 +02:00
Trym Lund Flogard
75e2916679 test 2021-06-02 17:00:08 +02:00
Trym Lund Flogard
e96c1262aa fix directory exists 2021-06-02 16:40:06 +02:00
Trym Lund Flogard
83cbe577f4 fix uuid 2021-06-02 16:36:55 +02:00
Trym Lund Flogard
146df697b5 test 2021-06-02 16:28:31 +02:00
Trym Lund Flogard
6def34f2d3 more impor tfix 2021-06-02 16:24:13 +02:00
Trym Lund Flogard
1cb76bcfb4 fix imports 2021-06-02 16:20:16 +02:00
Trym Lund Flogard
a87ab4cf3b exclide node modules 2021-06-02 16:17:19 +02:00
Trym Lund Flogard
7189094530 add github 2021-06-02 16:14:41 +02:00
27 changed files with 24961 additions and 1064 deletions

3
.eslintignore Normal file
View File

@ -0,0 +1,3 @@
dist/
lib/
node_modules/

57
.eslintrc Normal file
View File

@ -0,0 +1,57 @@
{
"plugins": ["jest", "@typescript-eslint"],
"extends": ["plugin:github/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"project": "./tsconfig.json"
},
"rules": {
"camelcase": "off",
"eslint-comments/no-use": "off",
"import/no-namespace": "off",
"no-shadow": "off",
"no-unused-vars": "off",
"prefer-template": "off",
"semi": [ "error", "never"],
"@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}],
"@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-comment": "error",
"@typescript-eslint/consistent-type-assertions": "error",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/func-call-spacing": ["error", "never"],
"@typescript-eslint/no-array-constructor": "error",
"@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-extraneous-class": "error",
"@typescript-eslint/no-for-in-array": "error",
"@typescript-eslint/no-inferrable-types": "error",
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/no-shadow": "error",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-unused-vars": ["error", {"varsIgnorePattern": "^_"}],
"@typescript-eslint/no-useless-constructor": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"@typescript-eslint/semi": ["error", "never"],
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error"
},
"env": {
"node": true,
"es6": true,
"jest/globals": true
}
}

5
.prettierignore Normal file
View File

@ -0,0 +1,5 @@
dist/
lib/
node_modules/
__tests__/__outputs__
__tests__/__snapshots__

10
.prettierrc.json Normal file
View File

@ -0,0 +1,10 @@
{
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "avoid"
}

View File

@ -1 +1,29 @@
# nextcloud-artifacts-action # Nextcloud Artifact Upload Action
Upload artifacts to nextcloud and output a shareable URL.
### How it looks:
![image](https://user-images.githubusercontent.com/23460729/120891750-7f247380-c60a-11eb-9998-3b3b7f61066f.png)
### Example:
Simple example. Globbing is supported.
```yaml
on:
pull_request:
push:
jobs:
build-test:
name: Build & Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2 # checkout the repo
- name: Nextcloud Artifact
uses: trympet/nextcloud-artifacts-action@v2
with:
name: 'my-artifact' # Name of the artifact
path: 'bin/**/*.exe' # Globbing supported
nextcloud-url: 'https://nextcloud.example.com' # Nextcloud URL
nextcloud-username: ${{ secrets.NEXTCLOUD_USERNAME }} # Username from repository secret
nextcloud-password: ${{ secrets.NEXTCLOUD_PASSWORD }} # Password from repository secret
```

View File

@ -0,0 +1,37 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { Inputs } from '../../src/Inputs'
import { NoFileOption } from '../../src/NoFileOption'
export class InputsDouble implements Inputs {
get ArtifactName(): string {
return process.env['ARTIFACT_NAME']!
}
get ArtifactPath(): string {
return process.env['ARTIFACT_PATH']!
}
get Retention(): string {
return ''
}
get Endpoint(): URL {
return new URL(process.env['ENDPOINT']!)
}
get Username(): string {
return process.env['USERNAME']!
}
get Password(): string {
return process.env['PASSWORD']!
}
get Token(): string {
return process.env['TOKEN']!
}
get NoFileBehvaior(): NoFileOption {
return NoFileOption.error
}
}

View File

View File

@ -0,0 +1,9 @@
import { NextcloudArtifact } from '../src/nextcloud/NextcloudArtifact'
import { InputsDouble } from './doubles/InputsDouble'
describe('integration tests', () => {
it('works', async () => {
const artifact = new NextcloudArtifact(new InputsDouble())
await artifact.run()
})
})

1
__tests__/setup.ts Normal file
View File

@ -0,0 +1 @@
require('dotenv').config()

View File

@ -25,11 +25,10 @@ inputs:
error: Fail the action with an error message error: Fail the action with an error message
ignore: Do not output any warnings or errors, the action does not fail ignore: Do not output any warnings or errors, the action does not fail
default: 'warn' default: 'warn'
retention-days: token:
description: > description: GitHub Access Token
Duration after which artifact will expire in days. 0 means using default retention. required: false
Minimum 1 day. default: ${{ github.token }}
Maximum 90 days unless changed from the repository settings page.
runs: runs:
using: 'node12' using: 'node20'
main: 'dist/index.js' main: 'dist/index.js'

15952
dist/index.js vendored

File diff suppressed because one or more lines are too long

1
dist/index.js.map vendored Normal file

File diff suppressed because one or more lines are too long

2386
dist/licenses.txt vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/sourcemap-register.js vendored Normal file

File diff suppressed because one or more lines are too long

12
jest.config.js Normal file
View File

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

6519
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,35 +1,70 @@
{ {
"name": "nextcloud-artifacts-action", "name": "nextcloud-artifacts-action",
"version": "1.0.0", "version": "2.0.0",
"description": "", "description": "",
"main": "lib/nextcloud-artifacts.js", "main": "lib/nextcloud-artifacts.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "build": "tsc",
"build": "npx tsc && npx @vercel/ncc build" "format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts",
"lint": "eslint src/**/*.ts",
"package": "ncc build --source-map --license licenses.txt",
"test": "jest --ci"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/trympet/nextcloud-artifacts-action.git" "url": "git+https://github.com/trympet/nextcloud-artifacts-action.git"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "Trym Lund Flogard <trym@flogard.no>",
"license": "ISC", "license": "GPL-2.0-only",
"bugs": { "bugs": {
"url": "https://github.com/trympet/nextcloud-artifacts-action/issues" "url": "https://github.com/trympet/nextcloud-artifacts-action/issues"
}, },
"homepage": "https://github.com/trympet/nextcloud-artifacts-action#readme", "homepage": "https://github.com/trympet/nextcloud-artifacts-action#readme",
"dependencies": { "dependencies": {
"@actions/core": "^1.3.0", "@actions/core": "^1.3.0",
"@actions/exec": "^1.0.4",
"@actions/github": "^5.0.0",
"@actions/glob": "^0.1.2", "@actions/glob": "^0.1.2",
"archiver": "^5.3.0", "archiver": "^5.3.0",
"btoa": "^1.2.1", "btoa": "^1.2.1",
"node-fetch": "^2.6.1" "node-fetch": "^2.6.1",
"uuid": "^8.3.2",
"webdav": "^4.6.0"
}, },
"devDependencies": { "devDependencies": {
"@octokit/types": "^6.16.2",
"@octokit/webhooks": "^9.6.3",
"@types/archiver": "^5.1.0", "@types/archiver": "^5.1.0",
"@types/btoa": "^1.2.3", "@types/btoa": "^1.2.3",
"@types/jest": "^26.0.23",
"@types/node": "^15.6.2", "@types/node": "^15.6.2",
"@types/node-fetch": "^2.5.10", "@types/node-fetch": "^2.5.10",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "^4.16.1",
"@typescript-eslint/parser": "^4.16.1",
"@vercel/ncc": "^0.28.6",
"dotenv": "^10.0.0",
"eslint": "^7.21.0",
"eslint-plugin-github": "^4.1.3",
"eslint-plugin-jest": "^24.1.7",
"jest": "^26.6.3",
"jest-circus": "^26.6.3",
"jest-junit": "^12.0.0",
"js-yaml": "^4.0.0",
"prettier": "2.2.1",
"ts-jest": "^26.5.3",
"typescript": "^4.3.2" "typescript": "^4.3.2"
},
"jest-junit": {
"suiteName": "jest tests",
"outputDirectory": "__tests__/__results__",
"outputName": "jest-junit.xml",
"ancestorSeparator": " ",
"uniqueOutputName": "false",
"suiteNameTemplate": "{filepath}",
"classNameTemplate": "{classname}",
"titleTemplate": "{title}"
} }
} }

45
src/ActionInputs.ts Normal file
View File

@ -0,0 +1,45 @@
import * as core from '@actions/core'
import { NoFileOption } from './NoFileOption'
import { Inputs } from './Inputs'
import { URL } from 'url'
export class ActionInputs implements Inputs {
get ArtifactName(): string {
return core.getInput('name', { required: false }) || 'Nextcloud Artifact'
}
get ArtifactPath(): string {
return core.getInput('path', { required: true })
}
get Endpoint(): URL {
return new URL(core.getInput('nextcloud-url', { required: true }))
}
get Username(): string {
return core.getInput('nextcloud-username', { required: true })
}
get Password(): string {
return core.getInput('nextcloud-password', { required: true })
}
get Token(): string {
return core.getInput('token', { required: true })
}
get NoFileBehvaior(): NoFileOption {
const notFoundAction = core.getInput('if-no-files-found', { required: false }) || NoFileOption.warn
const noFileBehavior: NoFileOption = NoFileOption[notFoundAction as keyof typeof NoFileOption]
if (!noFileBehavior) {
core.setFailed(
`Unrecognized ${'ifNoFilesFound'} input. Provided: ${notFoundAction}. Available options: ${Object.keys(
NoFileOption
)}`
)
}
return noFileBehavior
}
}

View File

@ -10,20 +10,17 @@ export class FileFinder {
followSymbolicLinks: true, followSymbolicLinks: true,
implicitDescendants: true, implicitDescendants: true,
omitBrokenSymbolicLinks: true omitBrokenSymbolicLinks: true
}; }
private globOptions: glob.GlobOptions private globOptions: glob.GlobOptions
public constructor(private searchPath: string, globOptions?: glob.GlobOptions) { constructor(private searchPath: string, globOptions?: glob.GlobOptions) {
this.globOptions = globOptions || FileFinder.DefaultGlobOptions; this.globOptions = globOptions || FileFinder.DefaultGlobOptions
} }
public async findFiles() { async findFiles() {
const searchResults: string[] = [] const searchResults: string[] = []
const globber = await glob.create( const globber = await glob.create(this.searchPath, this.globOptions)
this.searchPath,
this.globOptions
);
const rawSearchResults: string[] = await globber.glob() const rawSearchResults: string[] = await globber.glob()
@ -53,9 +50,7 @@ export class FileFinder {
set.add(searchResult.toLowerCase()) set.add(searchResult.toLowerCase())
} }
} else { } else {
debug( debug(`Removing ${searchResult} from rawSearchResults because it is a directory`)
`Removing ${searchResult} from rawSearchResults because it is a directory`
)
} }
} }
@ -63,13 +58,9 @@ export class FileFinder {
const searchPaths: string[] = globber.getSearchPaths() const searchPaths: string[] = globber.getSearchPaths()
if (searchPaths.length > 1) { if (searchPaths.length > 1) {
info( info(`Multiple search paths detected. Calculating the least common ancestor of all paths`)
`Multiple search paths detected. Calculating the least common ancestor of all paths`
)
const lcaSearchPath = this.getMultiPathLCA(searchPaths) const lcaSearchPath = this.getMultiPathLCA(searchPaths)
info( info(`The least common ancestor is ${lcaSearchPath}. This will be the root directory of the artifact`)
`The least common ancestor is ${lcaSearchPath}. This will be the root directory of the artifact`
)
return { return {
filesToUpload: searchResults, filesToUpload: searchResults,

View File

@ -1,43 +1,18 @@
import core from '@actions/core'; import { URL } from 'url'
import { NoFileOption } from './NoFileOption'; import { NoFileOption } from './NoFileOption'
export class Inputs { export interface Inputs {
static get ArtifactName(): string { readonly ArtifactName: string
return core.getInput("name");
}
static get ArtifactPath(): string { readonly ArtifactPath: string
return core.getInput("path");
}
static get Retention(): string { readonly Endpoint: URL
return core.getInput("retention-days");
}
static get Endpoint(): string { readonly Username: string
return core.getInput("nextcloud-url");
}
static get Username(): string { readonly Password: string
return core.getInput("nextcloud-username");
}
static get Password(): string { readonly Token: string
return core.getInput("nextcloud-password");
}
static get NoFileBehvaior(): NoFileOption { readonly NoFileBehvaior: NoFileOption
const notFoundAction = core.getInput("if-no-files-found");
const noFileBehavior: NoFileOption = NoFileOption[notFoundAction as keyof typeof NoFileOption];
if (!noFileBehavior) {
core.setFailed(
`Unrecognized ${"ifNoFilesFound"} input. Provided: ${notFoundAction}. Available options: ${Object.keys(
NoFileOption
)}`
);
}
return noFileBehavior;
}
} }

View File

@ -12,5 +12,5 @@ export enum NoFileOption {
/** /**
* Do not output any warnings or errors, the action does not fail * Do not output any warnings or errors, the action does not fail
*/ */
ignore = 'ignore', ignore = 'ignore'
} }

View File

@ -1,5 +1,15 @@
import { Inputs } from './Inputs'; import { NextcloudArtifact } from './nextcloud/NextcloudArtifact'
import { NextcloudArtifact } from './nextcloud/NextcloudArtifact'; import * as core from '@actions/core'
import { ActionInputs } from './ActionInputs'
var artifact = new NextcloudArtifact(Inputs.ArtifactName, Inputs.ArtifactPath, Inputs.NoFileBehvaior); async function run() {
artifact.run(); try {
const artifact = new NextcloudArtifact(new ActionInputs())
await artifact.run()
core.info('Finished')
} catch (error) {
core.setFailed(error.message)
}
}
run()

View File

@ -1,63 +1,154 @@
import core from '@actions/core'; import * as core from '@actions/core'
import { FileFinder } from '../FileFinder'; import * as github from '@actions/github'
import { Inputs } from '../Inputs'; import { GitHub } from '@actions/github/lib/utils'
import { NextcloudClient } from './NextcloudClient';
import { NoFileOption } from '../NoFileOption'; import { FileFinder } from '../FileFinder'
import { Inputs } from '../Inputs'
import { NextcloudClient } from './NextcloudClient'
import { NoFileOption } from '../NoFileOption'
export class NextcloudArtifact { export class NextcloudArtifact {
public constructor( readonly octokit: InstanceType<typeof GitHub>
private name: string, readonly context = NextcloudArtifact.getCheckRunContext()
private path: string, readonly token: string
private errorBehavior: NoFileOption) { } readonly name: string
readonly artifactTitle: string
readonly path: string
readonly errorBehavior: NoFileOption
public async run() { constructor(private inputs: Inputs) {
const fileFinder = new FileFinder(this.path); this.token = inputs.Token
const files = await fileFinder.findFiles(); this.name = inputs.ArtifactName
this.artifactTitle = `Nextcloud - ${this.name}`
this.path = inputs.ArtifactPath
this.errorBehavior = inputs.NoFileBehvaior
this.name = inputs.ArtifactName
this.octokit = github.getOctokit(this.token)
}
async run() {
const fileFinder = new FileFinder(this.path)
const files = await fileFinder.findFiles()
if (files.filesToUpload.length > 0) { if (files.filesToUpload.length > 0) {
await this.uploadFiles(files); await this.uploadFiles(files)
} } else {
else { this.logNoFilesFound()
this.logNoFilesFound();
} }
} }
private async uploadFiles(files: { filesToUpload: string[]; rootDirectory: string; }) { private static getCheckRunContext(): { sha: string; runId: number } {
this.logUpload(files.filesToUpload.length, files.rootDirectory); if (github.context.eventName === 'workflow_run') {
core.info('Action was triggered by workflow_run: using SHA and RUN_ID from triggering workflow')
const event = github.context.payload
if (!event.workflow_run) {
throw new Error("Event of type 'workflow_run' is missing 'workflow_run' field")
}
return {
sha: event.workflow_run.head_commit.id,
runId: event.workflow_run.id
}
}
const client = new NextcloudClient(Inputs.Endpoint, this.name, files.rootDirectory); const runId = github.context.runId
if (github.context.payload.pull_request) {
core.info(`Action was triggered by ${github.context.eventName}: using SHA from head of source branch`)
const pr = github.context.payload.pull_request
return { sha: pr.head.sha, runId }
}
await client.uploadFiles(files.filesToUpload); return { sha: github.context.sha, runId }
}
private async uploadFiles(files: { filesToUpload: string[]; rootDirectory: string }) {
this.logUpload(files.filesToUpload.length, files.rootDirectory)
const createResp = await this.octokit.rest.checks.create({
head_sha: this.context.sha,
name: this.artifactTitle,
status: 'in_progress',
output: {
title: `Nextcloud - ${this.name}`,
summary: 'Uploading...'
},
...github.context.repo
})
const client = new NextcloudClient(
this.inputs.Endpoint,
this.name,
files.rootDirectory,
this.inputs.Username,
this.inputs.Password
)
try {
const shareableUrl = await client.uploadFiles(files.filesToUpload)
core.setOutput('SHAREABLE_URL', shareableUrl)
core.info(`Nextcloud shareable URL: ${shareableUrl}`)
const resp = await this.octokit.rest.checks.update({
check_run_id: createResp.data.id,
conclusion: 'success',
status: 'completed',
output: {
title: this.artifactTitle,
summary: shareableUrl
},
...github.context.repo
})
core.info(`Check run create response: ${resp.status}`)
core.info(`Check run URL: ${resp.data.url}`)
core.info(`Check run HTML: ${resp.data.html_url}`)
} catch (error) {
await this.trySetFailed(createResp.data.id)
core.setFailed(error)
}
}
private async trySetFailed(checkId: number) {
try {
await this.octokit.rest.checks.update({
check_run_id: checkId,
conclusion: 'failure',
status: 'completed',
output: {
title: this.artifactTitle,
summary: 'Check failed.'
},
...github.context.repo
})
return true
} catch (error) {
core.error(`Failed to update check status to failure`)
return false
}
} }
private logUpload(fileCount: number, rootDirectory: string) { private logUpload(fileCount: number, rootDirectory: string) {
const s = fileCount === 1 ? '' : 's'; const s = fileCount === 1 ? '' : 's'
core.info( core.info(`With the provided path, there will be ${fileCount} file${s} uploaded`)
`With the provided path, there will be ${fileCount} file${s} uploaded` core.debug(`Root artifact directory is ${rootDirectory}`)
);
core.debug(`Root artifact directory is ${rootDirectory}`);
if (fileCount > 10000) { if (fileCount > 10000) {
core.warning( core.warning(
`There are over 10,000 files in this artifact, consider create an archive before upload to improve the upload performance.` `There are over 10,000 files in this artifact, consider create an archive before upload to improve the upload performance.`
); )
} }
} }
private logNoFilesFound() { private logNoFilesFound() {
const errorMessage = `No files were found with the provided path: ${this.path}. No artifacts will be uploaded.`; const errorMessage = `No files were found with the provided path: ${this.path}. No artifacts will be uploaded.`
switch (this.errorBehavior) { switch (this.errorBehavior) {
case NoFileOption.warn: { case NoFileOption.warn: {
core.warning(errorMessage); core.warning(errorMessage)
break; break
} }
case NoFileOption.error: { case NoFileOption.error: {
core.setFailed(errorMessage); core.setFailed(errorMessage)
break; break
} }
case NoFileOption.ignore: { case NoFileOption.ignore: {
core.info(errorMessage); core.info(errorMessage)
break; break
} }
} }
} }

View File

@ -1,161 +1,167 @@
import * as fsSync from 'fs' import * as fsSync from 'fs'
import * as path from 'path' import * as path from 'path'
import core from '@actions/core'; import * as core from '@actions/core'
import * as os from 'os'; import * as os from 'os'
import { randomUUID } from 'crypto'; import * as archiver from 'archiver'
import * as archiver from 'archiver'; import fetch, { HeadersInit } from 'node-fetch'
import { URL } from 'url'; import btoa from 'btoa'
import fetch, { HeadersInit } from 'node-fetch'; import { v4 as uuidv4 } from 'uuid'
import { Inputs } from '../Inputs'; import * as webdav from 'webdav'
import btoa from 'btoa'; import { URL } from 'url'
const fs = fsSync.promises; const fs = fsSync.promises
interface FileSpec { interface FileSpec {
absolutePath: string, absolutePath: string
uploadPath: string uploadPath: string
} }
export class NextcloudClient { export class NextcloudClient {
private guid: string; private guid: string
private headers: HeadersInit; private headers: HeadersInit
private davClient
public constructor( constructor(
private endpoint: string, private endpoint: URL,
private artifact: string, private artifact: string,
private rootDirectory: string) { private rootDirectory: string,
this.guid = randomUUID(); private username: string,
this.headers = {'Authorization': 'Basic ' + btoa(`${Inputs.Username}:${Inputs.Password}`)}; private password: string
) {
this.guid = uuidv4()
this.headers = { Authorization: 'Basic ' + Buffer.from(`${this.username}:${this.password}`).toString('base64') }
this.davClient = webdav.createClient(`${this.endpoint.href}remote.php/dav/files/${this.username}`, {
username: this.username,
password: this.password,
maxBodyLength: 1024 ** 3
})
} }
public async uploadFiles(files: string[]) { async uploadFiles(files: string[]): Promise<string> {
const spec = this.uploadSpec(files); core.info('Preparing upload...')
var zip = await this.zipFiles(spec); const spec = this.uploadSpec(files)
const path = await this.upload(zip); core.info('Zipping files...')
await this.shareFile(path); const zip = await this.zipFiles(spec)
try {
core.info('Uploading to Nextcloud...')
const filePath = await this.upload(zip)
core.info(`Remote file path: ${filePath}`)
return await this.shareFile(filePath)
} finally {
await fs.unlink(zip)
}
} }
private uploadSpec(files: string[]): FileSpec[] { private uploadSpec(files: string[]): FileSpec[] {
const specifications = []; const specifications = []
if (!fsSync.existsSync(this.rootDirectory)) { if (!fsSync.existsSync(this.rootDirectory)) {
throw new Error(`this.rootDirectory ${this.rootDirectory} does not exist`); throw new Error(`this.rootDirectory ${this.rootDirectory} does not exist`)
} }
if (!fsSync.lstatSync(this.rootDirectory).isDirectory()) { if (!fsSync.lstatSync(this.rootDirectory).isDirectory()) {
throw new Error(`this.rootDirectory ${this.rootDirectory} is not a valid directory`); throw new Error(`this.rootDirectory ${this.rootDirectory} is not a valid directory`)
} }
// Normalize and resolve, this allows for either absolute or relative paths to be used let root = path.normalize(this.rootDirectory)
let root = path.normalize(this.rootDirectory); root = path.resolve(root)
root = path.resolve(root);
/*
Example to demonstrate behavior
Input:
artifactName: my-artifact
rootDirectory: '/home/user/files/plz-upload'
artifactFiles: [
'/home/user/files/plz-upload/file1.txt',
'/home/user/files/plz-upload/file2.txt',
'/home/user/files/plz-upload/dir/file3.txt'
]
Output:
specifications: [
['/home/user/files/plz-upload/file1.txt', 'my-artifact/file1.txt'],
['/home/user/files/plz-upload/file1.txt', 'my-artifact/file2.txt'],
['/home/user/files/plz-upload/file1.txt', 'my-artifact/dir/file3.txt']
]
*/
for (let file of files) { for (let file of files) {
if (!fsSync.existsSync(file)) { if (!fsSync.existsSync(file)) {
throw new Error(`File ${file} does not exist`); throw new Error(`File ${file} does not exist`)
} }
if (!fsSync.lstatSync(file).isDirectory()) { if (!fsSync.lstatSync(file).isDirectory()) {
// Normalize and resolve, this allows for either absolute or relative paths to be used file = path.normalize(file)
file = path.normalize(file); file = path.resolve(file)
file = path.resolve(file);
if (!file.startsWith(root)) { if (!file.startsWith(root)) {
throw new Error(`The rootDirectory: ${root} is not a parent directory of the file: ${file}`); throw new Error(`The rootDirectory: ${root} is not a parent directory of the file: ${file}`)
} }
// Check for forbidden characters in file paths that will be rejected during upload
const uploadPath = file.replace(root, '');
/*
uploadFilePath denotes where the file will be uploaded in the file container on the server. During a run, if multiple artifacts are uploaded, they will all
be saved in the same container. The artifact name is used as the root directory in the container to separate and distinguish uploaded artifacts
path.join handles all the following cases and would return 'artifact-name/file-to-upload.txt const uploadPath = file.replace(root, '')
join('artifact-name/', 'file-to-upload.txt')
join('artifact-name/', '/file-to-upload.txt')
join('artifact-name', 'file-to-upload.txt')
join('artifact-name', '/file-to-upload.txt')
*/
specifications.push({ specifications.push({
absolutePath: file, absolutePath: file,
uploadPath: path.join(this.artifact, uploadPath) uploadPath: path.join(this.artifact, uploadPath)
}); })
} } else {
else { core.debug(`Removing ${file} from rawSearchResults because it is a directory`)
// Directories are rejected by the server during upload
core.debug(`Removing ${file} from rawSearchResults because it is a directory`);
} }
} }
return specifications; return specifications
} }
private async zipFiles(specs: FileSpec[]): Promise<string> { private async zipFiles(specs: FileSpec[]): Promise<string> {
const tempArtifactDir = path.join(os.tmpdir(), this.guid); const tempArtifactDir = path.join(os.tmpdir(), this.guid)
const artifactPath = path.join(tempArtifactDir, `artifact-${this.artifact}`); const artifactPath = path.join(tempArtifactDir, `artifact-${this.artifact}`)
await fs.mkdir(artifactPath, { recursive: true }); await fs.mkdir(path.join(artifactPath, this.artifact), { recursive: true })
for (let spec of specs) { const copies = []
await fs.copyFile(spec.absolutePath, path.join(artifactPath, spec.uploadPath)); for (const spec of specs) {
const dstpath = path.join(artifactPath, spec.uploadPath)
const dstDir = path.dirname(dstpath)
if (!fsSync.existsSync(dstDir)) {
await fs.mkdir(dstDir, { recursive: true })
} }
const archivePath = path.join(artifactPath, `${this.artifact}.zip`); copies.push(fs.copyFile(spec.absolutePath, dstpath))
await this.zip(path.join(artifactPath, this.artifact), archivePath); }
return archivePath; await Promise.all(copies)
core.info(`files: ${await fs.readdir(path.join(artifactPath, this.artifact))}`)
const archivePath = path.join(artifactPath, `${this.artifact}.zip`)
await this.zip(path.join(artifactPath, this.artifact), archivePath)
return archivePath
} }
private async zip(dirpath: string, destpath: string) { private async zip(dirpath: string, destpath: string) {
const archive = archiver.create('zip', { zlib: { level: 9 } }); const archive = archiver.create('zip', { zlib: { level: 9 } })
const stream = fsSync.createWriteStream(destpath); const stream = archive.directory(dirpath, false).pipe(fsSync.createWriteStream(destpath))
archive.directory(dirpath, false)
.on('error', e => Promise.reject())
.on('close', () => Promise.resolve())
.pipe(stream);
return archive.finalize(); await archive.finalize()
return await new Promise<void>((resolve, reject) => {
stream.on('error', e => reject(e)).on('close', () => resolve())
})
} }
private async upload(file: string) { private async upload(file: string): Promise<string> {
const filePath = `/artifacts/${this.guid}/${this.artifact}`; const remoteFileDir = `/artifacts/${this.guid}`
const url = this.endpoint + `/remote.php/dav/files/${Inputs.Username}` + filePath; if (!(await this.davClient.exists(remoteFileDir))) {
const stream = fsSync.createReadStream(file); await this.davClient.createDirectory(remoteFileDir, { recursive: true })
const res = await fetch(url, {
method: 'PUT',
body: stream,
headers: this.headers
});
core.debug(await res.json())
return filePath;
} }
private async shareFile(nextcloudPath: string) { const remoteFilePath = `${remoteFileDir}/${this.artifact}.zip`
const url = this.endpoint + `/ocs/v2.php/apps/files_sharing/api/v1/shares`; core.debug(`Transferring file... (${file})`)
await this.davClient.putFileContents(remoteFilePath, await fs.readFile(file))
return remoteFilePath
}
private async shareFile(remoteFilePath: string): Promise<string> {
const url = `${this.endpoint.href}ocs/v2.php/apps/files_sharing/api/v1/shares`
const body = { const body = {
path: nextcloudPath, path: remoteFilePath,
shareType: 3, shareType: 3,
publicUpload: "false", publicUpload: 'false',
permissions: 1, permissions: 1
}; }
const res = await fetch(url, { const res = await fetch(url, {
method: 'PUT', method: 'POST',
headers: this.headers, headers: Object.assign(this.headers, {
body: JSON.stringify(body), 'OCS-APIRequest': true,
}); 'Content-Type': 'application/json'
}),
body: JSON.stringify(body)
})
core.debug(await res.json()) const result = await res.text()
core.debug(`Share response: ${result}`)
const re = /<url>(?<share_url>.*)<\/url>/
const match = re.exec(result)
core.debug(`Match groups:\n${JSON.stringify(match?.groups)}`)
const sharableUrl = (match?.groups || {})['share_url']
if (!sharableUrl) {
throw new Error(`Failed to parse or find sharable URL:\n${result}`)
}
return sharableUrl
} }
} }

View File

@ -1,14 +1,16 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ "target": "ES2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"strict": true, /* Enable all strict type-checking options. */ "strict": true, /* Enable all strict type-checking options. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"skipLibCheck": true, /* Skip type checking of declaration files. */ "skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"noImplicitAny": true,
"rootDir": "src", "rootDir": "src",
"outDir": "lib", "outDir": "lib",
"sourceMap": true, "sourceMap": true,
"lib": ["es6"] "lib": ["ES2019"]
} },
"exclude": ["node_modules", "__tests__/**/*.ts"]
} }

8
workspace.code-workspace Normal file
View File

@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}