├── .circleci └── config.yml ├── .gitignore ├── .gitmodules ├── .prettierignore ├── .prettierrc ├── .releaserc.json ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── docs ├── formatting.md └── grammar.md ├── gulpfile.ts ├── package.json ├── scripts ├── deploy-vsce.ts ├── gulp-build.ts ├── gulp-linter.ts ├── gulp-vscode.ts ├── package-linter.json ├── package-vscode.json └── utils.ts ├── src ├── analysis │ ├── actions.ts │ ├── blocks.ts │ ├── circular-dependencies.ts │ └── secrets.ts ├── api.ts ├── binding │ ├── binder.ts │ └── bound-nodes.ts ├── cli.ts ├── extension.ts ├── parsing │ ├── parser.ts │ └── syntax-nodes.ts ├── resources │ ├── grammar.json │ ├── language-configuration.json │ ├── logo.png │ └── snippets.json ├── scanning │ ├── scanner.ts │ └── tokens.ts ├── server.ts ├── services │ ├── completion.ts │ ├── diagnostics.ts │ ├── find-references.ts │ ├── folding.ts │ ├── formatting.ts │ ├── go-to-definition.ts │ └── renaming.ts └── util │ ├── cache.ts │ ├── compilation.ts │ ├── constants.ts │ ├── diagnostics.ts │ ├── highlight-range.ts │ └── ranges.ts ├── test ├── actions.spec.ts ├── binding.spec.ts ├── blocks.spec.ts ├── circular-dependencies.spec.ts ├── completion.spec.ts ├── external-tests.spec.ts ├── formatting.spec.ts ├── parsing.spec.ts ├── scanning.spec.ts ├── secrets.spec.ts └── utils.ts ├── tsconfig.json ├── tslint.json ├── typings ├── @octokit │ └── webhooks-definitions.d.ts └── jest-diff.d.ts └── yarn.lock /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | jobs: 4 | build: 5 | docker: 6 | - image: circleci/node:11.9.0 7 | steps: 8 | - checkout 9 | - run: 10 | name: Init Submodules 11 | command: git submodule init 12 | - run: 13 | name: Update Submodules 14 | command: git submodule update --remote 15 | - restore_cache: 16 | name: Restore Yarn Package Cache 17 | keys: 18 | - yarn-packages-{{ checksum "yarn.lock" }} 19 | - run: 20 | name: Install Dependencies 21 | command: yarn install --frozen-lockfile 22 | - save_cache: 23 | name: Save Yarn Package Cache 24 | key: yarn-packages-{{ checksum "yarn.lock" }} 25 | paths: 26 | - ~/.cache/yarn 27 | - run: 28 | name: Run Gulp CI 29 | command: yarn gulp ci 30 | - run: 31 | name: Semantic Release 32 | command: ./node_modules/.bin/semantic-release 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | 4 | # Output 5 | out/ 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "workflow-parser"] 2 | path = workflow-parser 3 | url = https://github.com/actions/workflow-parser 4 | branch = master 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | workflow-parser/ 4 | 5 | # Resources 6 | README.md 7 | CHANGELOG.md 8 | *.png 9 | 10 | # Misc 11 | yarn.lock 12 | .gitignore 13 | .prettierignore 14 | 15 | # Output 16 | out/ 17 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120, 3 | "proseWrap": "always", 4 | "trailingComma": "all" 5 | } 6 | -------------------------------------------------------------------------------- /.releaserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "branch": "master", 3 | "plugins": [ 4 | "@semantic-release/commit-analyzer", 5 | "@semantic-release/release-notes-generator", 6 | "@semantic-release/changelog", 7 | [ 8 | "@semantic-release/npm", 9 | { 10 | "pkgRoot": "./out/linter" 11 | } 12 | ], 13 | [ 14 | "./out/scripts/deploy-vsce", 15 | { 16 | "pkgRoot": "./out/vscode" 17 | } 18 | ], 19 | [ 20 | "@semantic-release/git", 21 | { 22 | "assets": ["package.json", "CHANGELOG.md"], 23 | "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}" 24 | } 25 | ], 26 | "@semantic-release/github" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["esbenp.prettier-vscode", "ms-vscode.vscode-typescript-tslint-plugin"] 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "extensionHost", 9 | "request": "launch", 10 | "name": "Launch Extension", 11 | "runtimeExecutable": "${execPath}", 12 | "args": ["--extensionDevelopmentPath=${workspaceFolder}/out/vscode"], 13 | "preLaunchTask": "update-vscode" 14 | }, 15 | { 16 | "type": "node", 17 | "request": "launch", 18 | "name": "Jest Current File", 19 | "program": "${workspaceFolder}/node_modules/.bin/jest", 20 | "args": ["${fileBasename}"], 21 | "outFiles": ["${workspaceFolder}/out/**"], 22 | "windows": { 23 | "program": "${workspaceFolder}/node_modules/jest/bin/jest" 24 | } 25 | } 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "tslint.ignoreDefinitionFiles": false, 3 | "editor.formatOnSave": true, 4 | "editor.formatOnPaste": true, 5 | "files.exclude": { 6 | "**/node_modules": true 7 | }, 8 | "search.exclude": { 9 | "**/out": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "update-vscode", 8 | "type": "shell", 9 | "command": "yarn", 10 | "group": "build", 11 | "args": ["gulp", "update-vscode"] 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [2.7.0](https://github.com/OmarTawfik/github-actions-js/compare/v2.6.1...v2.7.0) (2019-05-01) 2 | 3 | 4 | ### Features 5 | 6 | * allow optional commas in arrays ([#87](https://github.com/OmarTawfik/github-actions-js/issues/87)) ([c0346ad](https://github.com/OmarTawfik/github-actions-js/commit/c0346ad)) 7 | * match formatting indentation to terraform fmt ([#86](https://github.com/OmarTawfik/github-actions-js/issues/86)) ([5e0fff9](https://github.com/OmarTawfik/github-actions-js/commit/5e0fff9)) 8 | * support workflow on=schedule values ([#89](https://github.com/OmarTawfik/github-actions-js/issues/89)) ([ac44cf3](https://github.com/OmarTawfik/github-actions-js/commit/ac44cf3)), closes [#84](https://github.com/OmarTawfik/github-actions-js/issues/84) 9 | 10 | ## [2.6.1](https://github.com/OmarTawfik/github-actions-js/compare/v2.6.0...v2.6.1) (2019-03-22) 11 | 12 | 13 | ### Bug Fixes 14 | 15 | * allow "foo/bar@baz" values in uses property ([#81](https://github.com/OmarTawfik/github-actions-js/issues/81)) ([fdb6b9e](https://github.com/OmarTawfik/github-actions-js/commit/fdb6b9e)), closes [#77](https://github.com/OmarTawfik/github-actions-js/issues/77) 16 | 17 | # [2.6.0](https://github.com/OmarTawfik/github-actions-js/compare/v2.5.0...v2.6.0) (2019-03-14) 18 | 19 | 20 | ### Features 21 | 22 | * add completion service ([#74](https://github.com/OmarTawfik/github-actions-js/issues/74)) ([f63976c](https://github.com/OmarTawfik/github-actions-js/commit/f63976c)) 23 | 24 | # [2.5.0](https://github.com/OmarTawfik/github-actions-js/compare/v2.4.0...v2.5.0) (2019-03-14) 25 | 26 | 27 | ### Features 28 | 29 | * added formatting service ([#73](https://github.com/OmarTawfik/github-actions-js/issues/73)) ([b1092dc](https://github.com/OmarTawfik/github-actions-js/commit/b1092dc)), closes [#20](https://github.com/OmarTawfik/github-actions-js/issues/20) 30 | 31 | # [2.4.0](https://github.com/OmarTawfik/github-actions-js/compare/v2.3.0...v2.4.0) (2019-03-13) 32 | 33 | 34 | ### Features 35 | 36 | * provide brace matching ([e83ab47](https://github.com/OmarTawfik/github-actions-js/commit/e83ab47)), closes [#16](https://github.com/OmarTawfik/github-actions-js/issues/16) 37 | 38 | # [2.3.0](https://github.com/OmarTawfik/github-actions-js/compare/v2.2.0...v2.3.0) (2019-03-13) 39 | 40 | 41 | ### Features 42 | 43 | * added navigation services ([#71](https://github.com/OmarTawfik/github-actions-js/issues/71)) ([b3cde86](https://github.com/OmarTawfik/github-actions-js/commit/b3cde86)), closes [#67](https://github.com/OmarTawfik/github-actions-js/issues/67) 44 | 45 | # [2.2.0](https://github.com/OmarTawfik/github-actions-js/compare/v2.1.0...v2.2.0) (2019-03-12) 46 | 47 | 48 | ### Features 49 | 50 | * provide rename service ([#63](https://github.com/OmarTawfik/github-actions-js/issues/63)) ([17f8e79](https://github.com/OmarTawfik/github-actions-js/commit/17f8e79)), closes [#21](https://github.com/OmarTawfik/github-actions-js/issues/21) 51 | 52 | # [2.1.0](https://github.com/OmarTawfik/github-actions-js/compare/v2.0.2...v2.1.0) (2019-03-12) 53 | 54 | 55 | ### Features 56 | 57 | * add semantic folding feature to vscode ([#59](https://github.com/OmarTawfik/github-actions-js/issues/59)) ([9ae8037](https://github.com/OmarTawfik/github-actions-js/commit/9ae8037)), closes [#22](https://github.com/OmarTawfik/github-actions-js/issues/22) 58 | 59 | ## [2.0.2](https://github.com/OmarTawfik/github-actions-js/compare/v2.0.1...v2.0.2) (2019-03-12) 60 | 61 | 62 | ### Bug Fixes 63 | 64 | * install vscode dependencies before publishing ([#57](https://github.com/OmarTawfik/github-actions-js/issues/57)) ([f144021](https://github.com/OmarTawfik/github-actions-js/commit/f144021)) 65 | * remove scripts from vscode extension before publishing ([#58](https://github.com/OmarTawfik/github-actions-js/issues/58)) ([652f365](https://github.com/OmarTawfik/github-actions-js/commit/652f365)) 66 | 67 | ## [2.0.1](https://github.com/OmarTawfik/github-actions-js/compare/v2.0.0...v2.0.1) (2019-03-12) 68 | 69 | 70 | ### Bug Fixes 71 | 72 | * vsce deployment root path ([#56](https://github.com/OmarTawfik/github-actions-js/issues/56)) ([f82e5cb](https://github.com/OmarTawfik/github-actions-js/commit/f82e5cb)) 73 | 74 | # [2.0.0](https://github.com/OmarTawfik/github-actions-js/compare/v1.4.0...v2.0.0) (2019-03-12) 75 | 76 | 77 | ### Bug Fixes 78 | 79 | * vsce deployment script ([#55](https://github.com/OmarTawfik/github-actions-js/issues/55)) ([0ecec1f](https://github.com/OmarTawfik/github-actions-js/commit/0ecec1f)) 80 | 81 | 82 | ### BREAKING CHANGES 83 | 84 | * added all missing diagnostics from v1 85 | 86 | # [1.4.0](https://github.com/OmarTawfik/github-actions-js/compare/v1.3.0...v1.4.0) (2019-03-12) 87 | 88 | 89 | ### Features 90 | 91 | * publish vscode extension ([#52](https://github.com/OmarTawfik/github-actions-js/issues/52)) ([b28f5e7](https://github.com/OmarTawfik/github-actions-js/commit/b28f5e7)) 92 | 93 | # [1.3.0](https://github.com/OmarTawfik/github-actions-js/compare/v1.2.1...v1.3.0) (2019-03-12) 94 | 95 | 96 | ### Bug Fixes 97 | 98 | * report errors on duplicate actions or workflows ([#44](https://github.com/OmarTawfik/github-actions-js/issues/44)) ([5572f59](https://github.com/OmarTawfik/github-actions-js/commit/5572f59)), closes [#41](https://github.com/OmarTawfik/github-actions-js/issues/41) 99 | 100 | 101 | ### Features 102 | 103 | * report error when 'needs' refers to a non-existing action ([#46](https://github.com/OmarTawfik/github-actions-js/issues/46)) ([cc446d6](https://github.com/OmarTawfik/github-actions-js/commit/cc446d6)), closes [#7](https://github.com/OmarTawfik/github-actions-js/issues/7) 104 | * report errors on actions circular dependencies ([#47](https://github.com/OmarTawfik/github-actions-js/issues/47)) ([87ea513](https://github.com/OmarTawfik/github-actions-js/commit/87ea513)), closes [#11](https://github.com/OmarTawfik/github-actions-js/issues/11) 105 | * report errors on duplicate actions in resolves ([#48](https://github.com/OmarTawfik/github-actions-js/issues/48)) ([5e7db6d](https://github.com/OmarTawfik/github-actions-js/commit/5e7db6d)), closes [#37](https://github.com/OmarTawfik/github-actions-js/issues/37) 106 | * report errors on duplicate needs actions ([#49](https://github.com/OmarTawfik/github-actions-js/issues/49)) ([1e0fc49](https://github.com/OmarTawfik/github-actions-js/commit/1e0fc49)), closes [#42](https://github.com/OmarTawfik/github-actions-js/issues/42) 107 | * report errors on duplicate or too many actions ([#33](https://github.com/OmarTawfik/github-actions-js/issues/33)) ([f32daa3](https://github.com/OmarTawfik/github-actions-js/commit/f32daa3)), closes [#10](https://github.com/OmarTawfik/github-actions-js/issues/10) 108 | * report errors on invalid 'uses' values ([#50](https://github.com/OmarTawfik/github-actions-js/issues/50)) ([2cc08f5](https://github.com/OmarTawfik/github-actions-js/commit/2cc08f5)), closes [#6](https://github.com/OmarTawfik/github-actions-js/issues/6) 109 | * report errors on reserved environment variables ([#34](https://github.com/OmarTawfik/github-actions-js/issues/34)) ([73ba6aa](https://github.com/OmarTawfik/github-actions-js/commit/73ba6aa)) 110 | * report errors on unknown event types ([#45](https://github.com/OmarTawfik/github-actions-js/issues/45)) ([7b3720b](https://github.com/OmarTawfik/github-actions-js/commit/7b3720b)), closes [#4](https://github.com/OmarTawfik/github-actions-js/issues/4) 111 | * report errors on unresolved actions ([#38](https://github.com/OmarTawfik/github-actions-js/issues/38)) ([61a2eec](https://github.com/OmarTawfik/github-actions-js/commit/61a2eec)) 112 | 113 | ## [1.2.1](https://github.com/OmarTawfik/github-actions-js/compare/v1.2.0...v1.2.1) (2019-03-07) 114 | 115 | 116 | ### Bug Fixes 117 | 118 | * fix npm postinstall script ([#32](https://github.com/OmarTawfik/github-actions-js/issues/32)) ([c9a1e00](https://github.com/OmarTawfik/github-actions-js/commit/c9a1e00)) 119 | 120 | # [1.2.0](https://github.com/OmarTawfik/github-actions-js/compare/v1.1.0...v1.2.0) (2019-03-07) 121 | 122 | 123 | ### Features 124 | 125 | * reports errors on duplicate secrets ([#31](https://github.com/OmarTawfik/github-actions-js/issues/31)) ([32ebb36](https://github.com/OmarTawfik/github-actions-js/commit/32ebb36)), closes [#12](https://github.com/OmarTawfik/github-actions-js/issues/12) 126 | 127 | # [1.1.0](https://github.com/OmarTawfik/github-actions-js/compare/v1.0.0...v1.1.0) (2019-03-07) 128 | 129 | 130 | ### Features 131 | 132 | * report errors on too many secrets ([#27](https://github.com/OmarTawfik/github-actions-js/issues/27)) ([8ece721](https://github.com/OmarTawfik/github-actions-js/commit/8ece721)), closes [#9](https://github.com/OmarTawfik/github-actions-js/issues/9) 133 | 134 | # 1.0.0 (2019-03-06) 135 | 136 | 137 | ### Features 138 | 139 | * added binder ([#13](https://github.com/OmarTawfik/github-actions-js/issues/13)) ([16bf355](https://github.com/OmarTawfik/github-actions-js/commit/16bf355)) 140 | * added LSP + diagnostics service ([#23](https://github.com/OmarTawfik/github-actions-js/issues/23)) ([13bbf97](https://github.com/OmarTawfik/github-actions-js/commit/13bbf97)) 141 | * added parser ([#2](https://github.com/OmarTawfik/github-actions-js/issues/2)) ([b750f26](https://github.com/OmarTawfik/github-actions-js/commit/b750f26)) 142 | * added scanner + test ([#1](https://github.com/OmarTawfik/github-actions-js/issues/1)) ([20726c0](https://github.com/OmarTawfik/github-actions-js/commit/20726c0)) 143 | * added tsc, tslint, prettier, and a test source file ([4b92be1](https://github.com/OmarTawfik/github-actions-js/commit/4b92be1)) 144 | * added vscode extension with highlighting and snippets ([#15](https://github.com/OmarTawfik/github-actions-js/issues/15)) ([8112d1d](https://github.com/OmarTawfik/github-actions-js/commit/8112d1d)) 145 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Omar Tawfik 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GitHubActions.js [![CircleCI](https://circleci.com/gh/OmarTawfik/github-actions-js.png?style=svg)](https://circleci.com/gh/OmarTawfik/github-actions-js) 2 | 3 | Provides linting APIs on the command line, through Node.js, and rich code editing through VSCode. 4 | 5 | ### Using the NPM Package 6 | 7 | > https://www.npmjs.com/package/github-actions-linter 8 | 9 | Add the package through npm/yarn: 10 | 11 | ```bash 12 | $ npm i github-actions-linter 13 | $ yarn add github-actions-linter 14 | ``` 15 | 16 | Run linter through Node.js: 17 | 18 | ```ts 19 | import { lint } from "github-actions-linter"; 20 | 21 | const diagnostics = lint(code); 22 | console.log(diagnostics.length + " errors were found."); 23 | 24 | diagnostics.forEach(diagnostic => { 25 | console.log(diagnostic.message); 26 | }); 27 | ``` 28 | 29 | Or invoke through the CLI: 30 | 31 | ```bash 32 | $ github-actions-linter file1.workflow file2.workflow 33 | ``` 34 | 35 | It will exit cleanly if no errors were found, or with a positive error code (number of errors) if any existed: 36 | 37 | ![image](https://user-images.githubusercontent.com/15987992/53709938-bedad000-3def-11e9-8cc5-8ab55b1462e2.png) 38 | 39 | ### Using the VSCode Extension 40 | 41 | > https://marketplace.visualstudio.com/items?itemName=OmarTawfik.github-actions-vscode 42 | 43 | The VSCode extension provides many features, like inserting code snippets, colorization, formatting, and providing diagnostics as you type. 44 | 45 | ![image](https://user-images.githubusercontent.com/15987992/54337709-ed755980-45ec-11e9-9920-fd8e854437fb.gif) 46 | -------------------------------------------------------------------------------- /docs/formatting.md: -------------------------------------------------------------------------------- 1 | # Formatting Guidelines 2 | 3 | Following the ones used by `terraform fmt`: 4 | 5 | > https://www.terraform.io/docs/configuration/style.html 6 | 7 | - Indent two spaces for each nesting level. 8 | - Inside a block, arguments go together first, then blocks (separated by a blank line each). 9 | - Align their equal sign according to the longest key. 10 | -------------------------------------------------------------------------------- /docs/grammar.md: -------------------------------------------------------------------------------- 1 | # Workflow File Grammar 2 | 3 | This grammar is based on the one published by: 4 | 5 | > https://github.com/actions/workflow-parser/blob/master/language.md 6 | 7 | ## Scanner 8 | 9 | ```g4 10 | VERSION_KEYWORD : 'version' ; 11 | WORKFLOW_KEYWORD : 'workflow' ; 12 | ACTION_KEYWORD : 'action'; 13 | 14 | ON_KEYWORD : 'on' ; 15 | RESOLVES_KEYWORD : 'resolves' ; 16 | USES_KEYWORD : 'uses' ; 17 | NEEDS_KEYWORD : 'needs'; 18 | RUNS_KEYWORD : 'runs' ; 19 | ARGS_KEYWORD : 'args' ; 20 | ENV_KEYWORD : 'env' ; 21 | SECRETS_KEYWORD : 'secrets' ; 22 | 23 | EQUAL : '=' ; 24 | COMMA : ',' ; 25 | 26 | LEFT_CURLY_BRACKET = '{' ; 27 | RIGHT_CURLY_BRACKET = '}' ; 28 | LEFT_SQUARE_BRACKET = '[' ; 29 | RIGHT_SQUARE_BRACKET = ']' ; 30 | 31 | IDENTIFIER : [a-zA-Z_] [a-zA-Z0-9_]*; 32 | LINE_COMMENT : ('#' | '//') ~[\r\n]* ; 33 | 34 | INTEGER_LITERAL : [0-9]+ ; 35 | STRING_LITERAL : '"' (('\\' ["\\/bfnrt]) | ~["\\\u0000-\u001F\u007F])* '"' ; 36 | 37 | WS : [\n \t\r] -> skip; 38 | ``` 39 | 40 | ## Parser 41 | 42 | ```g4 43 | workflow_file : (version | block)* ; 44 | 45 | version : VERSION_KEYWORD EQUAL INTEGER_LITERAL ; 46 | 47 | block : block_type STRING_LITERAL LEFT_CURLY_BRACKET 48 | (property)* 49 | RIGHT_CURLY_BRACKET ; 50 | 51 | block_type : WORKFLOW_KEYWORD | ACTION_KEYWORD ; 52 | 53 | property : key EQUAL value ; 54 | 55 | key : ON_KEYWORD 56 | | RESOLVES_KEYWORD 57 | | USES_KEYWORD 58 | | NEEDS_KEYWORD 59 | | RUNS_KEYWORD 60 | | ARGS_KEYWORD 61 | | ENV_KEYWORD 62 | | SECRETS_KEYWORD ; 63 | 64 | value : STRING_LITERAL | string_array | env_variables ; 65 | 66 | string_array : LEFT_SQUARE_BRACKET 67 | (STRING_LITERAL COMMA?)* 68 | RIGHT_SQUARE_BRACKET ; 69 | 70 | env_variables : LEFT_CURLY_BRACKET (env_variable)* RIGHT_CURLY_BRACKET ; 71 | 72 | env_variable : IDENTIFIER EQUAL STRING_LITERAL COMMA? ; 73 | ``` 74 | -------------------------------------------------------------------------------- /gulpfile.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as gulp from "gulp"; 6 | import { BuildTasks } from "./scripts/gulp-build"; 7 | import { LinterTasks } from "./scripts/gulp-linter"; 8 | import { VSCodeTasks } from "./scripts/gulp-vscode"; 9 | 10 | // TODO: replace all module-like files with classes 11 | // TODO: Use discriminated unions instead of kinds and remove all casts 12 | 13 | // Called by debugger before launching 14 | gulp.task("update-vscode", gulp.series([BuildTasks.compile, VSCodeTasks.copyFiles, VSCodeTasks.generatePackageJson])); 15 | 16 | gulp.task( 17 | "ci", 18 | gulp.parallel([ 19 | gulp.series( 20 | BuildTasks.clean, 21 | BuildTasks.compile, 22 | gulp.parallel([ 23 | LinterTasks.copyFiles, 24 | LinterTasks.generateReadMe, 25 | LinterTasks.generatePackageJson, 26 | VSCodeTasks.copyFiles, 27 | VSCodeTasks.generateReadMe, 28 | VSCodeTasks.generatePackageJson, 29 | ]), 30 | ), 31 | BuildTasks.prettier, 32 | BuildTasks.tslint, 33 | BuildTasks.jestCI, 34 | ]), 35 | ); 36 | 37 | gulp.task("default", gulp.parallel(BuildTasks.jest)); 38 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "github-actions-js", 3 | "version": "1.0.0", 4 | "description": "A VSCode extension and a parser/linter for GitHub workflow/action files.", 5 | "publisher": "OmarTawfik", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/OmarTawfik/github-actions-js" 9 | }, 10 | "author": "Omar Tawfik ", 11 | "bugs": { 12 | "url": "https://github.com/OmarTawfik/github-actions-js/issues", 13 | "email": "OmarTawfik@users.noreply.github.com" 14 | }, 15 | "license": "MIT", 16 | "categories": [ 17 | "Programming Languages", 18 | "Snippets", 19 | "Linters", 20 | "Formatters" 21 | ], 22 | "scripts": { 23 | "gulp": "./node_modules/.bin/gulp", 24 | "postinstall": "node ./node_modules/vscode/bin/install" 25 | }, 26 | "engines": { 27 | "vscode": "^1.31.1" 28 | }, 29 | "commitlint": { 30 | "extends": [ 31 | "@commitlint/config-conventional" 32 | ] 33 | }, 34 | "husky": { 35 | "hooks": { 36 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" 37 | } 38 | }, 39 | "jest": { 40 | "preset": "ts-jest", 41 | "testEnvironment": "node", 42 | "rootDir": "./test" 43 | }, 44 | "keywords": [ 45 | "github", 46 | "actions", 47 | "workflows", 48 | "parser", 49 | "linter", 50 | "vscode", 51 | "extension" 52 | ], 53 | "devDependencies": { 54 | "@commitlint/cli": "7.5.0", 55 | "@commitlint/config-conventional": "7.5.0", 56 | "@semantic-release/changelog": "3.0.2", 57 | "@semantic-release/commit-analyzer": "6.1.0", 58 | "@semantic-release/git": "7.0.8", 59 | "@semantic-release/github": "5.2.10", 60 | "@semantic-release/npm": "5.1.4", 61 | "@semantic-release/release-notes-generator": "7.1.4", 62 | "@types/del": "3.0.1", 63 | "@types/execa": "0.9.0", 64 | "@types/fs-extra": "5.0.5", 65 | "@types/gulp": "4.0.5", 66 | "@types/gulp-change": "1.0.0", 67 | "@types/gulp-shell": "0.0.31", 68 | "@types/gulp-sourcemaps": "0.0.32", 69 | "@types/gulp-typescript": "2.13.0", 70 | "@types/jest": "24.0.3", 71 | "@types/joi": "14.3.2", 72 | "@types/lru-cache": "5.1.0", 73 | "@types/node": "11.9.0", 74 | "del": "3.0.0", 75 | "execa": "1.0.0", 76 | "fs-extra": "7.0.1", 77 | "gulp": "4.0.0", 78 | "gulp-change": "1.0.2", 79 | "gulp-merge-json": "1.3.1", 80 | "gulp-shell": "0.6.5", 81 | "gulp-sourcemaps": "2.6.4", 82 | "gulp-typescript": "5.0.0", 83 | "husky": "1.3.1", 84 | "jest": "23.6.0", 85 | "joi": "14.3.1", 86 | "prettier": "1.16.4", 87 | "prettier-check": "2.0.0", 88 | "semantic-release": "15.13.3", 89 | "ts-jest": "23.10.5", 90 | "ts-node": "8.0.2", 91 | "tslint": "5.12.1", 92 | "tslint-config-airbnb": "5.11.1", 93 | "tslint-config-prettier": "1.18.0", 94 | "typescript": "3.3.3", 95 | "vsce": "1.58.0", 96 | "vscode": "1.1.30" 97 | }, 98 | "dependencies": { 99 | "@octokit/webhooks-definitions": "1.1.2", 100 | "chalk": "2.4.2", 101 | "lru-cache": "5.1.1", 102 | "vscode-languageclient": "5.2.1", 103 | "vscode-languageserver": "5.2.1" 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /scripts/deploy-vsce.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as path from "path"; 6 | import * as execa from "execa"; 7 | import { pathExists, readJSON, writeJSON } from "fs-extra"; 8 | 9 | interface ConfigParams { 10 | readonly pkgRoot?: string; 11 | } 12 | 13 | interface Config { 14 | readonly rootPath: string; 15 | readonly packagePath: string; 16 | readonly packageContents: any; 17 | readonly VSCE_TOKEN: string; 18 | } 19 | 20 | interface Engine { 21 | nextRelease: { 22 | version: string; 23 | }; 24 | logger: { 25 | log: (value: string) => void; 26 | }; 27 | } 28 | 29 | async function clean(config: ConfigParams): Promise { 30 | if (!config.pkgRoot) { 31 | throw new Error(`'pkgRoot' option not set`); 32 | } 33 | 34 | const packagePath = path.resolve(config.pkgRoot, "package.json"); 35 | if (!(await pathExists(packagePath))) { 36 | throw new Error(`No package.json found at: ${packagePath}`); 37 | } 38 | 39 | const packageContents = await readJSON(packagePath); 40 | 41 | const VSCE_TOKEN = process.env.VSCE_TOKEN; 42 | if (!VSCE_TOKEN) { 43 | throw new Error(`Environment variable VSCE_TOKEN must be set.`); 44 | } 45 | 46 | return { 47 | packagePath, 48 | packageContents, 49 | VSCE_TOKEN, 50 | rootPath: config.pkgRoot, 51 | }; 52 | } 53 | 54 | export async function verifyConditions(config: ConfigParams, engine: Engine): Promise { 55 | engine.logger.log("Verifying the package."); 56 | await clean(config); 57 | } 58 | 59 | export async function prepare(config: ConfigParams, engine: Engine): Promise { 60 | engine.logger.log("Preparing the package."); 61 | const { packagePath, packageContents, rootPath } = await clean(config); 62 | 63 | packageContents.version = engine.nextRelease.version; 64 | await writeJSON(packagePath, packageContents); 65 | 66 | await execa("yarn", { 67 | stdio: "inherit", 68 | cwd: rootPath, 69 | }); 70 | } 71 | 72 | export async function publish(config: ConfigParams, engine: Engine): Promise { 73 | engine.logger.log("Publishing the package."); 74 | const { VSCE_TOKEN, rootPath } = await clean(config); 75 | 76 | const vsce = path.resolve("node_modules", ".bin", "vsce"); 77 | await execa(vsce, ["publish", "--pat", VSCE_TOKEN], { 78 | stdio: "inherit", 79 | cwd: rootPath, 80 | }); 81 | } 82 | -------------------------------------------------------------------------------- /scripts/gulp-build.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as path from "path"; 6 | import * as gulp from "gulp"; 7 | import * as typescript from "gulp-typescript"; 8 | import * as sourcemaps from "gulp-sourcemaps"; 9 | import * as del from "del"; 10 | import { outPath, rootPath, gulp_shell } from "./utils"; 11 | 12 | export module BuildTasks { 13 | export const clean = "build:clean"; 14 | export const compile = "build:compile"; 15 | export const jest = "build:jest"; 16 | export const jestCI = "build:jest-ci"; 17 | export const prettier = "build:prettier"; 18 | export const tslint = "build:tslint"; 19 | } 20 | 21 | gulp.task(BuildTasks.clean, () => { 22 | return del(outPath); 23 | }); 24 | 25 | gulp.task(BuildTasks.compile, () => { 26 | const project = typescript.createProject(path.join(rootPath, "tsconfig.json")); 27 | return project 28 | .src() 29 | .pipe(sourcemaps.init()) 30 | .pipe(project()) 31 | .pipe(sourcemaps.write()) 32 | .pipe(gulp.dest(outPath)); 33 | }); 34 | 35 | gulp_shell(BuildTasks.jest, () => { 36 | return [path.join(rootPath, "node_modules", ".bin", "jest"), "--verbose"]; 37 | }); 38 | 39 | gulp_shell(BuildTasks.jestCI, () => { 40 | return [path.join(rootPath, "node_modules", ".bin", "jest"), "--verbose", "--ci"]; 41 | }); 42 | 43 | gulp_shell(BuildTasks.prettier, () => { 44 | return [ 45 | path.join(rootPath, "node_modules", ".bin", "prettier-check"), 46 | path.join(rootPath, "*.*"), 47 | path.join(rootPath, "**", "*.*"), 48 | path.join(rootPath, "**", "**", "*.*"), 49 | path.join(rootPath, "**", "**", "**", "*.*"), 50 | ]; 51 | }); 52 | 53 | gulp_shell(BuildTasks.tslint, () => { 54 | return [path.join(rootPath, "node_modules", ".bin", "tslint"), "--project", path.join(rootPath, "tsconfig.json")]; 55 | }); 56 | -------------------------------------------------------------------------------- /scripts/gulp-linter.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as path from "path"; 6 | import * as gulp from "gulp"; 7 | import { outPath, gulp_mergePackageJson, gulp_extractReadMe } from "./utils"; 8 | 9 | const linterPath = path.join(outPath, "linter"); 10 | 11 | export module LinterTasks { 12 | export const copyFiles = "linter:copy-files"; 13 | export const generateReadMe = "linter:generate-read-me"; 14 | export const generatePackageJson = "linter:generate-package-json"; 15 | } 16 | 17 | gulp.task(LinterTasks.copyFiles, () => { 18 | return gulp.src([path.join(outPath, "src", "**")]).pipe(gulp.dest(linterPath)); 19 | }); 20 | 21 | gulp_extractReadMe(LinterTasks.generateReadMe, "linter", linterPath); 22 | 23 | gulp_mergePackageJson(LinterTasks.generatePackageJson, "package-linter.json", linterPath); 24 | -------------------------------------------------------------------------------- /scripts/gulp-vscode.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as path from "path"; 6 | import * as gulp from "gulp"; 7 | import { outPath, rootPath, gulp_mergePackageJson, gulp_extractReadMe } from "./utils"; 8 | 9 | const vsCodePath = path.join(outPath, "vscode"); 10 | 11 | export module VSCodeTasks { 12 | export const copyFiles = "vscode:copy-files"; 13 | export const generateReadMe = "vscode:generate-read-me"; 14 | export const generatePackageJson = "vscode:generate-package-json"; 15 | } 16 | 17 | gulp.task(VSCodeTasks.copyFiles, () => { 18 | return gulp 19 | .src([path.join(outPath, "src", "**"), path.join(rootPath, "src", "resources*", "**")]) 20 | .pipe(gulp.dest(vsCodePath)); 21 | }); 22 | 23 | gulp_extractReadMe(VSCodeTasks.generateReadMe, "vscode", vsCodePath); 24 | 25 | gulp_mergePackageJson(VSCodeTasks.generatePackageJson, "package-vscode.json", vsCodePath); 26 | -------------------------------------------------------------------------------- /scripts/package-linter.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "github-actions-linter", 3 | "description": "A parser/linter for GitHub workflows.", 4 | "main": "api.js", 5 | "bin": "cli.js" 6 | } 7 | -------------------------------------------------------------------------------- /scripts/package-vscode.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "github-actions-vscode", 3 | "displayName": "GitHub Actions", 4 | "description": "A VSCode extension for editing/linting GitHub actions/workflow files.", 5 | "main": "extension.js", 6 | "icon": "resources/logo.png", 7 | "activationEvents": ["onLanguage:github-actions"], 8 | "contributes": { 9 | "configurationDefaults": { 10 | "[github-actions]": { 11 | "editor.wordBasedSuggestions": false 12 | } 13 | }, 14 | "languages": [ 15 | { 16 | "id": "github-actions", 17 | "extensions": [".workflow"], 18 | "aliases": ["GitHub Actions", "GitHub Workflows"], 19 | "configuration": "./resources/language-configuration.json" 20 | } 21 | ], 22 | "grammars": [ 23 | { 24 | "language": "github-actions", 25 | "scopeName": "source.workflow", 26 | "path": "./resources/grammar.json" 27 | } 28 | ], 29 | "snippets": [ 30 | { 31 | "language": "github-actions", 32 | "path": "./resources/snippets.json" 33 | } 34 | ] 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /scripts/utils.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as path from "path"; 6 | import * as change from "gulp-change"; 7 | import * as gulp from "gulp"; 8 | import * as shell from "gulp-shell"; 9 | import * as merge from "gulp-merge-json"; 10 | 11 | export const rootPath = path.resolve(__dirname, ".."); 12 | export const outPath = path.join(rootPath, "out"); 13 | 14 | export function gulp_shell(taskName: string, factory: () => string[]): void { 15 | gulp.task(taskName, shell.task(factory().join(" "))); 16 | } 17 | 18 | export function gulp_mergePackageJson(taskName: string, specificPackage: string, outputFolder: string): void { 19 | gulp.task(taskName, () => { 20 | return gulp 21 | .src([path.join(rootPath, "package.json"), path.join(rootPath, "scripts", specificPackage)]) 22 | .pipe( 23 | merge({ 24 | fileName: "package.json", 25 | edit: contents => { 26 | contents.scripts = {}; // remove vscode postinstall step, as it is only needed during dev mode 27 | contents.devDependencies = {}; // Remove devDependencies to improve publish step speed 28 | return contents; 29 | }, 30 | }), 31 | ) 32 | .pipe(gulp.dest(outputFolder)); 33 | }); 34 | } 35 | 36 | export function gulp_extractReadMe(taskName: string, section: "linter" | "vscode", outputFolder: string): void { 37 | gulp.task(taskName, () => { 38 | return gulp 39 | .src(path.join(rootPath, "README.md")) 40 | .pipe( 41 | change(content => { 42 | const npmIndex = content.indexOf("###"); 43 | const vscodeIndex = content.indexOf("###", npmIndex + 1); 44 | 45 | if (content.indexOf("###", vscodeIndex + 1) >= 0) { 46 | throw new Error(`More than two headers found`); 47 | } 48 | 49 | switch (section) { 50 | case "linter": { 51 | return content.substring(0, vscodeIndex); 52 | } 53 | case "vscode": { 54 | return content.substring(0, npmIndex) + content.substring(vscodeIndex); 55 | } 56 | default: { 57 | throw new Error(`Unknown '${section}' section.`); 58 | } 59 | } 60 | }), 61 | ) 62 | .pipe(gulp.dest(outputFolder)); 63 | }); 64 | } 65 | -------------------------------------------------------------------------------- /src/analysis/actions.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { DiagnosticBag } from "../util/diagnostics"; 6 | import { BoundDocument } from "../binding/bound-nodes"; 7 | 8 | export function analyzeActions(document: BoundDocument, bag: DiagnosticBag): void { 9 | const actions = new Set(document.actions.map(action => action.name)); 10 | 11 | document.workflows.forEach(parent => { 12 | if (parent.resolves) { 13 | const localActions = new Set(); 14 | parent.resolves.actions.forEach(action => { 15 | if (!actions.has(action.value)) { 16 | bag.actionDoesNotExist(action.value, action.syntax.range); 17 | } 18 | if (localActions.has(action.value)) { 19 | bag.duplicateActions(action.value, action.syntax.range); 20 | } else { 21 | localActions.add(action.value); 22 | } 23 | }); 24 | } 25 | }); 26 | 27 | document.actions.forEach(parent => { 28 | if (parent.needs) { 29 | const localActions = new Set(); 30 | parent.needs.actions.forEach(action => { 31 | if (!actions.has(action.value)) { 32 | bag.actionDoesNotExist(action.value, action.syntax.range); 33 | } 34 | 35 | if (localActions.has(action.value)) { 36 | bag.duplicateActions(action.value, action.syntax.range); 37 | } else { 38 | localActions.add(action.value); 39 | } 40 | }); 41 | } 42 | }); 43 | } 44 | -------------------------------------------------------------------------------- /src/analysis/blocks.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { BoundDocument } from "../binding/bound-nodes"; 6 | import { DiagnosticBag } from "../util/diagnostics"; 7 | import { MAXIMUM_SUPPORTED_ACTIONS } from "../util/constants"; 8 | 9 | export function analyzeBlocks(document: BoundDocument, bag: DiagnosticBag): void { 10 | const definedBlocks = new Set(); 11 | 12 | document.actions.forEach(action => { 13 | if (definedBlocks.has(action.name)) { 14 | bag.duplicateBlock(action.name, action.syntax.name.range); 15 | } else { 16 | if (definedBlocks.size === MAXIMUM_SUPPORTED_ACTIONS) { 17 | bag.tooManyActions(action.syntax.name.range); 18 | } 19 | 20 | definedBlocks.add(action.name); 21 | } 22 | }); 23 | 24 | document.workflows.forEach(workflow => { 25 | if (definedBlocks.has(workflow.name)) { 26 | bag.duplicateBlock(workflow.name, workflow.syntax.name.range); 27 | } else { 28 | definedBlocks.add(workflow.name); 29 | } 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /src/analysis/circular-dependencies.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { BoundDocument, BoundStringValue } from "../binding/bound-nodes"; 6 | import { DiagnosticBag } from "../util/diagnostics"; 7 | import { Range } from "vscode-languageserver-types"; 8 | 9 | export function analyzeCircularDependencies(document: BoundDocument, bag: DiagnosticBag): void { 10 | const dependencies = new Map>(); 11 | 12 | document.actions.forEach(action => { 13 | if (action.needs) { 14 | dependencies.set(action.name, action.needs.actions); 15 | } else { 16 | dependencies.set(action.name, []); 17 | } 18 | 19 | check(action.name, action.syntax.name.range, new Set()); 20 | }); 21 | 22 | function check(action: string, range: Range, visited: Set): boolean { 23 | if (visited.has(action)) { 24 | bag.circularDependency(action, range); 25 | return true; 26 | } 27 | 28 | visited.add(action); 29 | 30 | const entry = dependencies.get(action); 31 | if (entry) { 32 | for (const dependency of entry) { 33 | if (check(dependency.value, dependency.syntax.range, visited)) { 34 | return true; 35 | } 36 | } 37 | } 38 | 39 | visited.delete(action); 40 | return false; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/analysis/secrets.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { BoundDocument } from "../binding/bound-nodes"; 6 | import { DiagnosticBag } from "../util/diagnostics"; 7 | import { MAXIMUM_SUPPORTED_SECRETS } from "../util/constants"; 8 | 9 | export function analyzeSecrets(document: BoundDocument, bag: DiagnosticBag): void { 10 | const allSecrets = new Set(); 11 | 12 | document.actions.forEach(action => { 13 | if (!action.secrets) { 14 | return; 15 | } 16 | 17 | const localSecrets = new Set(); 18 | action.secrets.secrets.forEach(secret => { 19 | if (localSecrets.has(secret.value)) { 20 | bag.duplicateSecrets(secret.value, secret.syntax.range); 21 | } else { 22 | localSecrets.add(secret.value); 23 | } 24 | 25 | if (!allSecrets.has(secret.value)) { 26 | if (allSecrets.size === MAXIMUM_SUPPORTED_SECRETS) { 27 | bag.tooManySecrets(secret.syntax.range); 28 | } 29 | allSecrets.add(secret.value); 30 | } 31 | }); 32 | }); 33 | } 34 | -------------------------------------------------------------------------------- /src/api.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { Compilation } from "./util/compilation"; 6 | import { Diagnostic } from "vscode-languageserver-types"; 7 | 8 | export { Range, Diagnostic } from "vscode-languageserver-types"; 9 | export { DiagnosticCode } from "./util/diagnostics"; 10 | 11 | export function lint(text: string): ReadonlyArray { 12 | return new Compilation(text).diagnostics; 13 | } 14 | -------------------------------------------------------------------------------- /src/binding/binder.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { DiagnosticBag } from "../util/diagnostics"; 6 | import { 7 | DocumentSyntax, 8 | VersionSyntax, 9 | BlockSyntax, 10 | SyntaxKind, 11 | BasePropertySyntax, 12 | StringPropertySyntax, 13 | ArrayPropertySyntax, 14 | ObjectPropertySyntax, 15 | } from "../parsing/syntax-nodes"; 16 | import { 17 | BoundDocument, 18 | BoundVersion, 19 | BoundAction, 20 | BoundWorkflow, 21 | BoundOn, 22 | BoundResolves, 23 | BoundNeeds, 24 | BoundRuns, 25 | BoundArgs, 26 | BoundEnv, 27 | BoundSecrets, 28 | BoundUses, 29 | BoundStringValue, 30 | BoundObjectMember, 31 | } from "./bound-nodes"; 32 | import { TokenKind } from "../scanning/tokens"; 33 | import * as webhooks from "@octokit/webhooks-definitions"; 34 | import { MAXIMUM_SUPPORTED_VERSION, USES_REGEX } from "../util/constants"; 35 | 36 | const ON_SCHEDULE_REGEX = /schedule\(.+\)/; 37 | 38 | export function bindDocument(root: DocumentSyntax, bag: DiagnosticBag): BoundDocument { 39 | let version: BoundVersion | undefined; 40 | const workflows = Array(); 41 | const actions = Array(); 42 | 43 | root.versions.forEach(syntax => { 44 | bindVersion(syntax); 45 | }); 46 | 47 | let reportedErrorOnMisplacedVersion = false; 48 | root.blocks.forEach(syntax => { 49 | if ( 50 | !reportedErrorOnMisplacedVersion && 51 | version && 52 | syntax.type.range.start.line < version.syntax.version.range.start.line 53 | ) { 54 | bag.versionAfterBlock(version.syntax.version.range); 55 | reportedErrorOnMisplacedVersion = true; 56 | } 57 | 58 | switch (syntax.type.kind) { 59 | case TokenKind.WorkflowKeyword: { 60 | bindWorkflow(syntax); 61 | break; 62 | } 63 | case TokenKind.ActionKeyword: { 64 | bindAction(syntax); 65 | break; 66 | } 67 | default: { 68 | throw new Error(`Unexpected block kind '${syntax.type.kind}' here.`); 69 | } 70 | } 71 | }); 72 | 73 | return new BoundDocument(version, workflows, actions, root); 74 | 75 | function bindVersion(syntax: VersionSyntax): void { 76 | if (version) { 77 | bag.multipleVersions(syntax.version.range); 78 | } else { 79 | let value = 0; 80 | if (syntax.integer.kind !== TokenKind.Missing) { 81 | value = parseInt(syntax.integer.text, 10); 82 | if (isNaN(value) || value < 0 || value > MAXIMUM_SUPPORTED_VERSION) { 83 | bag.unrecognizedVersion(syntax.integer.text, syntax.integer.range); 84 | } 85 | } 86 | version = new BoundVersion(value, syntax); 87 | } 88 | } 89 | 90 | function bindWorkflow(syntax: BlockSyntax): void { 91 | let on: BoundOn | undefined; 92 | let resolves: BoundResolves | undefined; 93 | 94 | syntax.properties.forEach(property => { 95 | switch (property.key.kind) { 96 | case TokenKind.OnKeyword: { 97 | if (on) { 98 | bag.propertyAlreadyDefined(property.key); 99 | } else { 100 | on = new BoundOn(bindString(property), property); 101 | if (on.event) { 102 | const { value } = on.event; 103 | if (!webhooks.some(definition => definition.name === value) && !ON_SCHEDULE_REGEX.test(value)) { 104 | bag.unrecognizedEvent(value, on.event.syntax.range); 105 | } 106 | } 107 | } 108 | break; 109 | } 110 | case TokenKind.ResolvesKeyword: { 111 | if (resolves) { 112 | bag.propertyAlreadyDefined(property.key); 113 | } else { 114 | resolves = new BoundResolves(bindStringOrArray(property), property); 115 | } 116 | break; 117 | } 118 | default: { 119 | bag.invalidProperty(property.key, syntax.type.kind); 120 | } 121 | } 122 | }); 123 | 124 | if (!on) { 125 | bag.propertyMustBeDefined(TokenKind.OnKeyword, syntax.type); 126 | } 127 | 128 | workflows.push(new BoundWorkflow(removeDoubleQuotes(syntax.name.text), on, resolves, syntax)); 129 | } 130 | 131 | function bindAction(syntax: BlockSyntax): void { 132 | let uses: BoundUses | undefined; 133 | let needs: BoundNeeds | undefined; 134 | let runs: BoundRuns | undefined; 135 | let args: BoundArgs | undefined; 136 | let env: BoundEnv | undefined; 137 | let secrets: BoundSecrets | undefined; 138 | 139 | syntax.properties.forEach(property => { 140 | switch (property.key.kind) { 141 | case TokenKind.UsesKeyword: { 142 | if (uses) { 143 | bag.propertyAlreadyDefined(property.key); 144 | } else { 145 | uses = new BoundUses(bindString(property), property); 146 | if (uses.value) { 147 | if (!USES_REGEX.test(uses.value.value)) { 148 | bag.invalidUses(uses.value.syntax.range); 149 | } 150 | } 151 | } 152 | break; 153 | } 154 | case TokenKind.NeedsKeyword: { 155 | if (needs) { 156 | bag.propertyAlreadyDefined(property.key); 157 | } else { 158 | needs = new BoundNeeds(bindStringOrArray(property), property); 159 | } 160 | break; 161 | } 162 | case TokenKind.RunsKeyword: { 163 | if (runs) { 164 | bag.propertyAlreadyDefined(property.key); 165 | } else { 166 | runs = new BoundRuns(bindStringOrArray(property), property); 167 | } 168 | break; 169 | } 170 | case TokenKind.ArgsKeyword: { 171 | if (args) { 172 | bag.propertyAlreadyDefined(property.key); 173 | } else { 174 | args = new BoundArgs(bindStringOrArray(property), property); 175 | } 176 | break; 177 | } 178 | case TokenKind.EnvKeyword: { 179 | if (env) { 180 | bag.propertyAlreadyDefined(property.key); 181 | } else { 182 | env = new BoundEnv(bindObject(property), property); 183 | env.variables.forEach(variable => { 184 | if (variable.name.startsWith("GITHUB_")) { 185 | bag.reservedEnvironmentVariable(variable.syntax.name.range); 186 | } 187 | }); 188 | } 189 | break; 190 | } 191 | case TokenKind.SecretsKeyword: { 192 | if (secrets) { 193 | bag.propertyAlreadyDefined(property.key); 194 | } else { 195 | secrets = new BoundSecrets(bindStringOrArray(property), property); 196 | } 197 | break; 198 | } 199 | default: { 200 | bag.invalidProperty(property.key, syntax.type.kind); 201 | } 202 | } 203 | }); 204 | 205 | if (!uses) { 206 | bag.propertyMustBeDefined(TokenKind.UsesKeyword, syntax.type); 207 | } 208 | 209 | actions.push(new BoundAction(removeDoubleQuotes(syntax.name.text), uses, needs, runs, args, env, secrets, syntax)); 210 | } 211 | 212 | function bindString(syntax: BasePropertySyntax | undefined): BoundStringValue | undefined { 213 | if (!syntax) { 214 | return undefined; 215 | } 216 | 217 | switch (syntax.kind) { 218 | case SyntaxKind.StringProperty: { 219 | const property = syntax as StringPropertySyntax; 220 | if (property.value && property.value.kind !== TokenKind.Missing) { 221 | const value = removeDoubleQuotes(property.value.text); 222 | return new BoundStringValue(value, property.value); 223 | } 224 | return undefined; 225 | } 226 | case SyntaxKind.ArrayProperty: { 227 | bag.valueIsNotString(syntax.key.range); 228 | return undefined; 229 | } 230 | case SyntaxKind.ObjectProperty: { 231 | bag.valueIsNotString(syntax.key.range); 232 | return undefined; 233 | } 234 | default: { 235 | throw new Error(`Unexpected Syntax kind '${syntax.kind}'`); 236 | } 237 | } 238 | } 239 | 240 | function bindStringOrArray(syntax: BasePropertySyntax | undefined): ReadonlyArray { 241 | if (!syntax) { 242 | return []; 243 | } 244 | 245 | switch (syntax.kind) { 246 | case SyntaxKind.StringProperty: { 247 | const property = syntax as StringPropertySyntax; 248 | if (property.value && property.value.kind !== TokenKind.Missing) { 249 | const value = removeDoubleQuotes(property.value.text); 250 | return [new BoundStringValue(value, property.value)]; 251 | } 252 | return []; 253 | } 254 | case SyntaxKind.ArrayProperty: { 255 | return (syntax as ArrayPropertySyntax).items 256 | .filter(item => item.value.kind !== TokenKind.Missing) 257 | .map(item => new BoundStringValue(removeDoubleQuotes(item.value.text), item.value)); 258 | } 259 | case SyntaxKind.ObjectProperty: { 260 | bag.valueIsNotStringOrArray(syntax.key.range); 261 | return []; 262 | } 263 | default: { 264 | throw new Error(`Unexpected Syntax kind '${syntax.kind}'`); 265 | } 266 | } 267 | } 268 | 269 | function bindObject(syntax: BasePropertySyntax | undefined): ReadonlyArray { 270 | if (!syntax) { 271 | return []; 272 | } 273 | 274 | switch (syntax.kind) { 275 | case SyntaxKind.StringProperty: { 276 | bag.valueIsNotAnObject(syntax.key.range); 277 | return []; 278 | } 279 | case SyntaxKind.ArrayProperty: { 280 | bag.valueIsNotAnObject(syntax.key.range); 281 | return []; 282 | } 283 | case SyntaxKind.ObjectProperty: { 284 | return (syntax as ObjectPropertySyntax).members 285 | .filter(member => member.name.kind !== TokenKind.Missing && member.value.kind !== TokenKind.Missing) 286 | .map(member => new BoundObjectMember(member.name.text, removeDoubleQuotes(member.value.text), member)); 287 | } 288 | default: { 289 | throw new Error(`Unexpected Syntax kind '${syntax.kind}'`); 290 | } 291 | } 292 | } 293 | 294 | function removeDoubleQuotes(value: string): string { 295 | if (value.length === 0) { 296 | return value; 297 | } 298 | 299 | if (!value.startsWith('"')) { 300 | throw new Error("value has to start with double quotes"); 301 | } 302 | 303 | if (value.endsWith('"')) { 304 | return value.substr(1, value.length - 2); 305 | } 306 | 307 | // in case of an incomplete token 308 | return value.substr(1); 309 | } 310 | } 311 | -------------------------------------------------------------------------------- /src/binding/bound-nodes.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { 6 | DocumentSyntax, 7 | BlockSyntax, 8 | VersionSyntax, 9 | ObjectMemberSyntax, 10 | BasePropertySyntax, 11 | } from "../parsing/syntax-nodes"; 12 | import { TokenWithTrivia } from "../scanning/tokens"; 13 | 14 | export enum BoundKind { 15 | // Top level 16 | Document, 17 | Version, 18 | Workflow, 19 | Action, 20 | 21 | // Properties 22 | On, 23 | Resolves, 24 | Uses, 25 | Needs, 26 | Runs, 27 | Args, 28 | Env, 29 | Secrets, 30 | 31 | // Values 32 | StringValue, 33 | ObjectMember, 34 | } 35 | 36 | export abstract class BaseBoundNode { 37 | protected constructor(public readonly kind: BoundKind) {} 38 | } 39 | 40 | export class BoundDocument extends BaseBoundNode { 41 | public constructor( 42 | public readonly version: BoundVersion | undefined, 43 | public readonly workflows: ReadonlyArray, 44 | public readonly actions: ReadonlyArray, 45 | public readonly syntax: DocumentSyntax, 46 | ) { 47 | super(BoundKind.Document); 48 | } 49 | } 50 | 51 | export class BoundVersion extends BaseBoundNode { 52 | public constructor(public readonly version: number, public readonly syntax: VersionSyntax) { 53 | super(BoundKind.Version); 54 | } 55 | } 56 | 57 | export class BoundWorkflow extends BaseBoundNode { 58 | public constructor( 59 | public readonly name: string, 60 | public readonly on: BoundOn | undefined, 61 | public readonly resolves: BoundResolves | undefined, 62 | public readonly syntax: BlockSyntax, 63 | ) { 64 | super(BoundKind.Workflow); 65 | } 66 | } 67 | 68 | export class BoundAction extends BaseBoundNode { 69 | public constructor( 70 | public readonly name: string, 71 | public readonly uses: BoundUses | undefined, 72 | public readonly needs: BoundNeeds | undefined, 73 | public readonly runs: BoundRuns | undefined, 74 | public readonly args: BoundArgs | undefined, 75 | public readonly env: BoundEnv | undefined, 76 | public readonly secrets: BoundSecrets | undefined, 77 | public readonly syntax: BlockSyntax, 78 | ) { 79 | super(BoundKind.Action); 80 | } 81 | } 82 | 83 | export class BoundOn extends BaseBoundNode { 84 | public constructor(public readonly event: BoundStringValue | undefined, public readonly syntax: BasePropertySyntax) { 85 | super(BoundKind.On); 86 | } 87 | } 88 | 89 | export class BoundResolves extends BaseBoundNode { 90 | public constructor( 91 | public readonly actions: ReadonlyArray, 92 | public readonly syntax: BasePropertySyntax, 93 | ) { 94 | super(BoundKind.Resolves); 95 | } 96 | } 97 | 98 | export class BoundUses extends BaseBoundNode { 99 | public constructor(public readonly value: BoundStringValue | undefined, public readonly syntax: BasePropertySyntax) { 100 | super(BoundKind.Uses); 101 | } 102 | } 103 | 104 | export class BoundNeeds extends BaseBoundNode { 105 | public constructor( 106 | public readonly actions: ReadonlyArray, 107 | public readonly syntax: BasePropertySyntax, 108 | ) { 109 | super(BoundKind.Needs); 110 | } 111 | } 112 | 113 | export class BoundRuns extends BaseBoundNode { 114 | public constructor( 115 | public readonly commands: ReadonlyArray, 116 | public readonly syntax: BasePropertySyntax, 117 | ) { 118 | super(BoundKind.Runs); 119 | } 120 | } 121 | 122 | export class BoundArgs extends BaseBoundNode { 123 | public constructor( 124 | public readonly args: ReadonlyArray, 125 | public readonly syntax: BasePropertySyntax, 126 | ) { 127 | super(BoundKind.Args); 128 | } 129 | } 130 | 131 | export class BoundEnv extends BaseBoundNode { 132 | public constructor( 133 | public readonly variables: ReadonlyArray, 134 | public readonly syntax: BasePropertySyntax, 135 | ) { 136 | super(BoundKind.Env); 137 | } 138 | } 139 | 140 | export class BoundSecrets extends BaseBoundNode { 141 | public constructor( 142 | public readonly secrets: ReadonlyArray, 143 | public readonly syntax: BasePropertySyntax, 144 | ) { 145 | super(BoundKind.Secrets); 146 | } 147 | } 148 | 149 | export class BoundStringValue extends BaseBoundNode { 150 | public constructor(public readonly value: string, public readonly syntax: TokenWithTrivia) { 151 | super(BoundKind.StringValue); 152 | } 153 | } 154 | 155 | export class BoundObjectMember extends BaseBoundNode { 156 | public constructor( 157 | public readonly name: string, 158 | public readonly value: string, 159 | public readonly syntax: ObjectMemberSyntax, 160 | ) { 161 | super(BoundKind.ObjectMember); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /*! 3 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 4 | */ 5 | 6 | import * as fs from "fs"; 7 | import { Compilation } from "./util/compilation"; 8 | import chalk from "chalk"; 9 | import { highlight } from "./util/highlight-range"; 10 | import { DiagnosticSeverity } from "vscode-languageserver-types"; 11 | import { severityToString } from "./util/diagnostics"; 12 | 13 | let errorsCount = 0; 14 | 15 | function reportError(message: string, severity: DiagnosticSeverity | undefined, file?: string): void { 16 | errorsCount += 1; 17 | 18 | console.error(`${chalk.red(severityToString(severity))}: ${chalk.grey(file ? `${file}: ` : "")}${message}`); 19 | } 20 | 21 | const files = process.argv.slice(2); 22 | if (files.length === 0) { 23 | reportError("No files passed to lint.", DiagnosticSeverity.Error); 24 | } 25 | 26 | files.forEach(file => { 27 | try { 28 | const text = fs.readFileSync(file, "utf8"); 29 | const compilation = new Compilation(text); 30 | 31 | if (compilation.diagnostics.length === 0) { 32 | console.info(`${chalk.green("VALID")}: ${chalk.gray(file)}`); 33 | } else { 34 | compilation.diagnostics.forEach(diagnostic => { 35 | reportError(diagnostic.message, diagnostic.severity, file); 36 | console.error(highlight(diagnostic.range, text)); 37 | }); 38 | } 39 | } catch (ex) { 40 | reportError(ex.toString(), DiagnosticSeverity.Error, file); 41 | } 42 | 43 | console.log(); 44 | }); 45 | 46 | process.exit(errorsCount); 47 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as path from "path"; 6 | import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from "vscode-languageclient"; 7 | import { LANGUAGE_NAME } from "./util/constants"; 8 | 9 | let client: LanguageClient | undefined; 10 | 11 | export function activate(): void { 12 | const runOptions = { 13 | module: path.join(__dirname, "server.js"), 14 | transport: TransportKind.ipc, 15 | }; 16 | 17 | const debugOptions = { 18 | ...runOptions, 19 | options: { execArgv: ["--nolazy", "--inspect=6009"] }, 20 | }; 21 | 22 | const serverOptions: ServerOptions = { 23 | run: runOptions, 24 | debug: debugOptions, 25 | }; 26 | 27 | const clientOptions: LanguageClientOptions = { 28 | documentSelector: [{ scheme: "file", language: LANGUAGE_NAME }], 29 | }; 30 | 31 | client = new LanguageClient(LANGUAGE_NAME, `${LANGUAGE_NAME} client`, serverOptions, clientOptions); 32 | client.start(); 33 | } 34 | 35 | export async function deactivate(): Promise { 36 | if (client) { 37 | await client.stop(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/parsing/parser.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { DiagnosticBag } from "../util/diagnostics"; 6 | import { Token, TokenKind, getTokenDescription, TokenWithTrivia } from "../scanning/tokens"; 7 | import { 8 | DocumentSyntax, 9 | VersionSyntax, 10 | BlockSyntax, 11 | BasePropertySyntax, 12 | ArrayPropertySyntax, 13 | ArrayItemSyntax, 14 | ObjectMemberSyntax, 15 | StringPropertySyntax, 16 | ObjectPropertySyntax, 17 | } from "./syntax-nodes"; 18 | 19 | interface ParseContext { 20 | readonly parent?: ParseContext; 21 | readonly supported: ReadonlyArray; 22 | } 23 | 24 | export function parseTokens(allTokens: ReadonlyArray, bag: DiagnosticBag): DocumentSyntax { 25 | const tokens = allTokens.filter(token => token.kind !== TokenKind.Unrecognized); 26 | const commentsAfter = extractCommentsAtEndOfFile(); 27 | 28 | const reportedErrors = Array(); 29 | 30 | let index = 0; 31 | const versions = Array(); 32 | const blocks = Array(); 33 | 34 | while (index < tokens.length) { 35 | parseTopLevelNode({ 36 | supported: [], 37 | }); 38 | } 39 | 40 | return new DocumentSyntax(versions, blocks, commentsAfter); 41 | 42 | function extractCommentsAtEndOfFile(): ReadonlyArray { 43 | let end = tokens.length - 1; 44 | while (end >= 0 && tokens[end].kind === TokenKind.Comment) { 45 | end -= 1; 46 | } 47 | 48 | const result = tokens.slice(end + 1); 49 | tokens.splice(end + 1); 50 | return result; 51 | } 52 | 53 | function parseTopLevelNode(context: ParseContext): void { 54 | const keywordKinds = [TokenKind.VersionKeyword, TokenKind.WorkflowKeyword, TokenKind.ActionKeyword]; 55 | const keyword = eat(context, ...keywordKinds); 56 | 57 | const innerContext = { 58 | parent: context, 59 | supported: keywordKinds, 60 | }; 61 | 62 | switch (keyword.kind) { 63 | case TokenKind.VersionKeyword: { 64 | parseVersion(keyword, innerContext); 65 | break; 66 | } 67 | case TokenKind.WorkflowKeyword: 68 | case TokenKind.ActionKeyword: { 69 | parseBlock(keyword, innerContext); 70 | break; 71 | } 72 | case TokenKind.Missing: { 73 | // move to the next token 74 | break; 75 | } 76 | default: { 77 | throw new Error(`Unexpected token '${getTokenDescription(keyword.kind)}' here.`); 78 | } 79 | } 80 | } 81 | 82 | function parseVersion(version: TokenWithTrivia, context: ParseContext): void { 83 | const equal = eat(context, TokenKind.Equal); 84 | const integer = eat(context, TokenKind.IntegerLiteral); 85 | 86 | versions.push(new VersionSyntax(version, equal, integer)); 87 | } 88 | 89 | function parseBlock(type: TokenWithTrivia, context: ParseContext): void { 90 | const name = eat(context, TokenKind.StringLiteral); 91 | const openBracket = eat(context, TokenKind.LeftCurlyBracket); 92 | 93 | const properties = parseProperties({ 94 | parent: context, 95 | supported: [TokenKind.RightCurlyBracket], 96 | }); 97 | 98 | const closeBracket = eat(context, TokenKind.RightCurlyBracket); 99 | blocks.push(new BlockSyntax(type, name, openBracket, properties, closeBracket)); 100 | } 101 | 102 | function parseProperties(context: ParseContext): ReadonlyArray { 103 | const properties: BasePropertySyntax[] = []; 104 | 105 | while (!isNext(TokenKind.RightCurlyBracket)) { 106 | const keyKinds = [ 107 | TokenKind.OnKeyword, 108 | TokenKind.ResolvesKeyword, 109 | TokenKind.UsesKeyword, 110 | TokenKind.NeedsKeyword, 111 | TokenKind.RunsKeyword, 112 | TokenKind.ArgsKeyword, 113 | TokenKind.EnvKeyword, 114 | TokenKind.SecretsKeyword, 115 | ]; 116 | 117 | const key = eat(context, ...keyKinds); 118 | if (key.kind === TokenKind.Missing) { 119 | // Stop looking for properties 120 | break; 121 | } 122 | 123 | properties.push( 124 | parseProperty(key, { 125 | parent: context, 126 | supported: keyKinds, 127 | }), 128 | ); 129 | } 130 | 131 | return properties; 132 | } 133 | 134 | function parseProperty(key: TokenWithTrivia, context: ParseContext): BasePropertySyntax { 135 | const equal = eat(context, TokenKind.Equal); 136 | const valueStart = eat(context, TokenKind.StringLiteral, TokenKind.LeftCurlyBracket, TokenKind.LeftSquareBracket); 137 | 138 | let property: BasePropertySyntax; 139 | switch (valueStart.kind) { 140 | case TokenKind.StringLiteral: { 141 | property = new StringPropertySyntax(key, equal, valueStart); 142 | break; 143 | } 144 | case TokenKind.LeftSquareBracket: { 145 | const items = parseArrayItems(context); 146 | const closeBracket = eat(context, TokenKind.RightSquareBracket); 147 | property = new ArrayPropertySyntax(key, equal, valueStart, items, closeBracket); 148 | break; 149 | } 150 | case TokenKind.LeftCurlyBracket: { 151 | const members = parseObjectMembers(context); 152 | const closeBracket = eat(context, TokenKind.RightCurlyBracket); 153 | property = new ObjectPropertySyntax(key, equal, valueStart, members, closeBracket); 154 | break; 155 | } 156 | case TokenKind.Missing: { 157 | // Insert missing value as a string property 158 | property = new StringPropertySyntax(key, equal, valueStart); 159 | break; 160 | } 161 | default: { 162 | throw new Error(`Unexpected token '${getTokenDescription(valueStart.kind)}' here.`); 163 | } 164 | } 165 | 166 | return property; 167 | } 168 | 169 | function parseArrayItems(context: ParseContext): ReadonlyArray { 170 | const items = Array(); 171 | 172 | while (!isNext(TokenKind.RightSquareBracket)) { 173 | const value = eat(context, TokenKind.StringLiteral); 174 | 175 | if (value.kind === TokenKind.Missing) { 176 | break; 177 | } 178 | 179 | let comma: TokenWithTrivia | undefined; 180 | if (isNext(TokenKind.Comma)) { 181 | comma = eat(context, TokenKind.Comma); 182 | } 183 | 184 | items.push(new ArrayItemSyntax(value, comma)); 185 | } 186 | 187 | return items; 188 | } 189 | 190 | function parseObjectMembers(context: ParseContext): ReadonlyArray { 191 | const members = Array(); 192 | 193 | while (!isNext(TokenKind.RightCurlyBracket)) { 194 | const name = eat(context, TokenKind.Identifier); 195 | 196 | if (name.kind === TokenKind.Missing) { 197 | break; 198 | } 199 | 200 | const equal = eat(context, TokenKind.Equal); 201 | const value = eat(context, TokenKind.StringLiteral); 202 | let comma: TokenWithTrivia | undefined; 203 | if (isNext(TokenKind.Comma)) { 204 | comma = eat(context, TokenKind.Comma); 205 | } 206 | 207 | members.push(new ObjectMemberSyntax(name, equal, value, comma)); 208 | } 209 | 210 | return members; 211 | } 212 | 213 | function isNext(kind: TokenKind): boolean { 214 | return index < tokens.length && tokens[index].kind === kind; 215 | } 216 | 217 | function eat(context: ParseContext, ...expected: TokenKind[]): TokenWithTrivia { 218 | const commentsBefore = eatComments(); 219 | 220 | while (true) { 221 | if (index >= tokens.length) { 222 | return { 223 | commentsBefore, 224 | ...missingToken(expected), 225 | }; 226 | } 227 | 228 | const current = tokens[index]; 229 | if (expected.includes(current.kind)) { 230 | index += 1; 231 | 232 | if (index < tokens.length) { 233 | const commentAfter = tokens[index]; 234 | if (commentAfter.kind === TokenKind.Comment && commentAfter.range.start.line === current.range.end.line) { 235 | index += 1; 236 | return { 237 | commentsBefore, 238 | ...current, 239 | commentAfter, 240 | }; 241 | } 242 | } 243 | 244 | return { 245 | commentsBefore, 246 | ...current, 247 | }; 248 | } 249 | 250 | let canBeHandledByParent = false; 251 | let currentContext: ParseContext | undefined = context; 252 | while (!canBeHandledByParent && currentContext) { 253 | canBeHandledByParent = currentContext.supported.includes(current.kind); 254 | currentContext = currentContext.parent; 255 | } 256 | 257 | if (canBeHandledByParent) { 258 | return { 259 | commentsBefore, 260 | ...missingToken(expected), 261 | }; 262 | } 263 | 264 | if (!reportedErrors[index]) { 265 | bag.unexpectedToken(current); 266 | reportedErrors[index] = true; 267 | } 268 | 269 | index += 1; 270 | } 271 | } 272 | 273 | function eatComments(): ReadonlyArray | undefined { 274 | let result: TokenWithTrivia[] | undefined; 275 | 276 | while (index < tokens.length && tokens[index].kind === TokenKind.Comment) { 277 | if (!result) { 278 | result = []; 279 | } 280 | 281 | result.push(tokens[index]); 282 | index += 1; 283 | } 284 | 285 | return result; 286 | } 287 | 288 | function missingToken(expected: TokenKind[]): Token { 289 | let missingIndex = index; 290 | const endOfFile = index >= tokens.length; 291 | if (endOfFile) { 292 | missingIndex = tokens.length - 1; 293 | } 294 | 295 | const range = tokens[missingIndex].range; 296 | if (!reportedErrors[missingIndex]) { 297 | bag.missingToken(expected, range, endOfFile); 298 | reportedErrors[missingIndex] = true; 299 | } 300 | 301 | return { 302 | range, 303 | kind: TokenKind.Missing, 304 | text: "", 305 | }; 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /src/parsing/syntax-nodes.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { Token, TokenKind, getTokenDescription, TokenWithTrivia } from "../scanning/tokens"; 6 | import { Range } from "vscode-languageserver-types"; 7 | import { comparePositions } from "../util/ranges"; 8 | 9 | export enum SyntaxKind { 10 | // Top level 11 | Document, 12 | Version, 13 | Block, 14 | 15 | // Strings 16 | StringProperty, 17 | 18 | // Arrays 19 | ArrayProperty, 20 | ArrayItem, 21 | 22 | // Objects 23 | ObjectProperty, 24 | ObjectMember, 25 | } 26 | 27 | function assertTokenKind(token: Token | undefined, ...acceptedKinds: TokenKind[]): void { 28 | if (token && token.kind !== TokenKind.Missing && !acceptedKinds.includes(token.kind)) { 29 | throw new Error(`Token was initialized with an invalid '${getTokenDescription(token.kind)}' kind.`); 30 | } 31 | } 32 | 33 | function combineRange(...items: (Token | BaseSyntaxNode | undefined)[]): Range { 34 | const validRanges = items.filter(item => !!item).map(item => item!.range); 35 | if (!validRanges.length) { 36 | return Range.create(0, 0, 0, 0); 37 | } 38 | 39 | validRanges.sort((a, b) => comparePositions(a.start, b.start)); 40 | return Range.create(validRanges[0].start, validRanges[validRanges.length - 1].end); 41 | } 42 | 43 | export abstract class BaseSyntaxNode { 44 | private lazyRange: Range | undefined; 45 | 46 | protected constructor(public readonly kind: SyntaxKind) {} 47 | 48 | public get range(): Range { 49 | if (!this.lazyRange) { 50 | this.lazyRange = this.calculateRange(); 51 | } 52 | return this.lazyRange; 53 | } 54 | 55 | protected abstract calculateRange(): Range; 56 | } 57 | 58 | export class DocumentSyntax extends BaseSyntaxNode { 59 | public constructor( 60 | public readonly versions: ReadonlyArray, 61 | public readonly blocks: ReadonlyArray, 62 | public readonly commentsAfter: ReadonlyArray, 63 | ) { 64 | super(SyntaxKind.Document); 65 | } 66 | 67 | protected calculateRange(): Range { 68 | return combineRange(...this.versions, ...this.blocks, ...this.commentsAfter); 69 | } 70 | } 71 | 72 | export class VersionSyntax extends BaseSyntaxNode { 73 | public constructor( 74 | public readonly version: TokenWithTrivia, 75 | public readonly equal: TokenWithTrivia, 76 | public readonly integer: TokenWithTrivia, 77 | ) { 78 | super(SyntaxKind.Version); 79 | assertTokenKind(version, TokenKind.VersionKeyword); 80 | assertTokenKind(equal, TokenKind.Equal); 81 | assertTokenKind(integer, TokenKind.IntegerLiteral); 82 | } 83 | 84 | protected calculateRange(): Range { 85 | return combineRange(this.version, this.equal, this.integer); 86 | } 87 | } 88 | 89 | export class BlockSyntax extends BaseSyntaxNode { 90 | public constructor( 91 | public readonly type: TokenWithTrivia, 92 | public readonly name: TokenWithTrivia, 93 | public readonly openBracket: TokenWithTrivia, 94 | public readonly properties: ReadonlyArray, 95 | public readonly closeBracket: TokenWithTrivia, 96 | ) { 97 | super(SyntaxKind.Block); 98 | assertTokenKind(type, TokenKind.ActionKeyword, TokenKind.WorkflowKeyword); 99 | assertTokenKind(name, TokenKind.StringLiteral); 100 | assertTokenKind(openBracket, TokenKind.LeftCurlyBracket); 101 | assertTokenKind(closeBracket, TokenKind.RightCurlyBracket); 102 | } 103 | 104 | protected calculateRange(): Range { 105 | return combineRange(this.type, this.name, this.openBracket, ...this.properties, this.closeBracket); 106 | } 107 | } 108 | 109 | export abstract class BasePropertySyntax extends BaseSyntaxNode { 110 | protected constructor( 111 | kind: SyntaxKind, 112 | public readonly key: TokenWithTrivia, 113 | public readonly equal: TokenWithTrivia, 114 | ) { 115 | super(kind); 116 | assertTokenKind( 117 | key, 118 | TokenKind.OnKeyword, 119 | TokenKind.ResolvesKeyword, 120 | TokenKind.UsesKeyword, 121 | TokenKind.NeedsKeyword, 122 | TokenKind.RunsKeyword, 123 | TokenKind.ArgsKeyword, 124 | TokenKind.EnvKeyword, 125 | TokenKind.SecretsKeyword, 126 | ); 127 | assertTokenKind(equal, TokenKind.Equal); 128 | } 129 | } 130 | 131 | export class StringPropertySyntax extends BasePropertySyntax { 132 | public constructor(key: TokenWithTrivia, equal: TokenWithTrivia, public readonly value: TokenWithTrivia | undefined) { 133 | super(SyntaxKind.StringProperty, key, equal); 134 | assertTokenKind(value, TokenKind.StringLiteral); 135 | } 136 | 137 | protected calculateRange(): Range { 138 | return combineRange(this.key, this.equal, this.value); 139 | } 140 | } 141 | 142 | export class ArrayPropertySyntax extends BasePropertySyntax { 143 | public constructor( 144 | key: TokenWithTrivia, 145 | equal: TokenWithTrivia, 146 | public readonly openBracket: TokenWithTrivia, 147 | public readonly items: ReadonlyArray, 148 | public readonly closeBracket: TokenWithTrivia, 149 | ) { 150 | super(SyntaxKind.ArrayProperty, key, equal); 151 | assertTokenKind(openBracket, TokenKind.LeftSquareBracket); 152 | assertTokenKind(closeBracket, TokenKind.RightSquareBracket); 153 | } 154 | 155 | protected calculateRange(): Range { 156 | return combineRange(this.openBracket, ...this.items, this.closeBracket); 157 | } 158 | } 159 | 160 | export class ArrayItemSyntax extends BaseSyntaxNode { 161 | public constructor(public readonly value: TokenWithTrivia, public readonly comma: TokenWithTrivia | undefined) { 162 | super(SyntaxKind.ArrayItem); 163 | assertTokenKind(value, TokenKind.StringLiteral); 164 | assertTokenKind(comma, TokenKind.Comma); 165 | } 166 | 167 | protected calculateRange(): Range { 168 | return combineRange(this.value, this.comma); 169 | } 170 | } 171 | 172 | export class ObjectPropertySyntax extends BasePropertySyntax { 173 | public constructor( 174 | key: TokenWithTrivia, 175 | equal: TokenWithTrivia, 176 | public readonly openBracket: TokenWithTrivia, 177 | public readonly members: ReadonlyArray, 178 | public readonly closeBracket: TokenWithTrivia, 179 | ) { 180 | super(SyntaxKind.ObjectProperty, key, equal); 181 | assertTokenKind(openBracket, TokenKind.LeftCurlyBracket); 182 | assertTokenKind(closeBracket, TokenKind.RightCurlyBracket); 183 | } 184 | 185 | protected calculateRange(): Range { 186 | return combineRange(this.openBracket, ...this.members, this.closeBracket); 187 | } 188 | } 189 | 190 | export class ObjectMemberSyntax extends BaseSyntaxNode { 191 | public constructor( 192 | public readonly name: TokenWithTrivia, 193 | public readonly equal: TokenWithTrivia, 194 | public readonly value: TokenWithTrivia, 195 | public readonly comma: TokenWithTrivia | undefined, 196 | ) { 197 | super(SyntaxKind.ObjectMember); 198 | assertTokenKind(name, TokenKind.Identifier); 199 | assertTokenKind(equal, TokenKind.Equal); 200 | assertTokenKind(value, TokenKind.StringLiteral); 201 | assertTokenKind(comma, TokenKind.Comma); 202 | } 203 | 204 | protected calculateRange(): Range { 205 | return combineRange(this.name, this.equal, this.value, this.comma); 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /src/resources/grammar.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", 3 | "name": "github-actions", 4 | "scopeName": "source.workflow", 5 | "patterns": [ 6 | { 7 | "include": "#comments" 8 | }, 9 | { 10 | "include": "#keywords" 11 | }, 12 | { 13 | "include": "#strings" 14 | }, 15 | { 16 | "include": "#integers" 17 | } 18 | ], 19 | "repository": { 20 | "comments": { 21 | "patterns": [ 22 | { 23 | "name": "comment", 24 | "match": "(#|//).*" 25 | } 26 | ] 27 | }, 28 | "keywords": { 29 | "patterns": [ 30 | { 31 | "name": "support.class", 32 | "match": "\\b(version|workflow|action)\\b" 33 | }, 34 | { 35 | "name": "support.variable", 36 | "match": "\\b(on|resolves|needs|uses|runs|args|env|secrets)\\b" 37 | } 38 | ] 39 | }, 40 | "strings": { 41 | "name": "string", 42 | "begin": "\"", 43 | "end": "\"", 44 | "patterns": [ 45 | { 46 | "name": "contents", 47 | "match": "\\\\." 48 | } 49 | ] 50 | }, 51 | "integers": { 52 | "patterns": [ 53 | { 54 | "name": "constant.numeric", 55 | "match": "[0-9]+" 56 | } 57 | ] 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/resources/language-configuration.json: -------------------------------------------------------------------------------- 1 | { 2 | "brackets": [["{", "}"], ["[", "]"]], 3 | "autoClosingPairs": [ 4 | { 5 | "open": "{", 6 | "close": "}" 7 | }, 8 | { 9 | "open": "[", 10 | "close": "]" 11 | }, 12 | { 13 | "open": "\"", 14 | "close": "\"", 15 | "notIn": ["string", "comment"] 16 | } 17 | ], 18 | "autoCloseBefore": "} \r\n\t", 19 | "surroundingPairs": [["{", "}"], ["[", "]"], ["\"", "\""]] 20 | } 21 | -------------------------------------------------------------------------------- /src/resources/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OmarTawfik/github-actions-js/99c6654dc968012f66908aa652c5c9889ccbe42d/src/resources/logo.png -------------------------------------------------------------------------------- /src/resources/snippets.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": { 3 | "prefix": "version", 4 | "description": "Insert version statement", 5 | "body": ["version = ${1:VERSION}"] 6 | }, 7 | "workflow": { 8 | "prefix": "workflow", 9 | "description": "Insert workflow block", 10 | "body": ["workflow \"${1:NAME}\" {", " on = \"${2:ON}\"", " resolves = [ \"${3:RESOLVES}\" ]", "}"] 11 | }, 12 | "action": { 13 | "prefix": "action", 14 | "description": "Insert action block", 15 | "body": [ 16 | "action \"${1:NAME}\" {", 17 | " uses = \"${2:USES}\"", 18 | " needs = [ ]", 19 | " runs = \"\"", 20 | " args = [ ]", 21 | " env = { }", 22 | " secrets = [ ]", 23 | "}" 24 | ] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/scanning/scanner.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { DiagnosticBag } from "../util/diagnostics"; 6 | import { Token, TokenKind } from "./tokens"; 7 | import { Range } from "vscode-languageserver-types"; 8 | 9 | export function scanText(text: string, bag: DiagnosticBag): ReadonlyArray { 10 | let index: number = 0; 11 | let line: number = 0; 12 | let character: number = 0; 13 | 14 | const tokens: Token[] = []; 15 | 16 | while (index < text.length) { 17 | scanNextToken(); 18 | } 19 | 20 | return tokens; 21 | 22 | function scanNextToken(): void { 23 | const current = text[index]; 24 | 25 | switch (current) { 26 | case "\r": { 27 | if (index + 1 < text.length && text[index + 1] === "\n") { 28 | index += 2; 29 | } else { 30 | index += 1; 31 | } 32 | 33 | line += 1; 34 | character = 0; 35 | break; 36 | } 37 | case "\n": { 38 | index += 1; 39 | line += 1; 40 | character = 0; 41 | break; 42 | } 43 | case " ": 44 | case "\t": { 45 | index += 1; 46 | character += 1; 47 | break; 48 | } 49 | case "=": { 50 | addToken(TokenKind.Equal, current); 51 | break; 52 | } 53 | case ",": { 54 | addToken(TokenKind.Comma, current); 55 | break; 56 | } 57 | case "{": { 58 | addToken(TokenKind.LeftCurlyBracket, current); 59 | break; 60 | } 61 | case "}": { 62 | addToken(TokenKind.RightCurlyBracket, current); 63 | break; 64 | } 65 | case "[": { 66 | addToken(TokenKind.LeftSquareBracket, current); 67 | break; 68 | } 69 | case "]": { 70 | addToken(TokenKind.RightSquareBracket, current); 71 | break; 72 | } 73 | case "#": { 74 | scanComment(); 75 | break; 76 | } 77 | case "/": { 78 | if (index + 1 < text.length && text[index + 1] === "/") { 79 | scanComment(); 80 | } else { 81 | const token = addToken(TokenKind.Unrecognized, current); 82 | bag.unrecognizedCharacter(current, token.range); 83 | } 84 | break; 85 | } 86 | case '"': { 87 | scanStringLiteral(); 88 | break; 89 | } 90 | default: { 91 | if ("0" <= current && current <= "9") { 92 | scanNumberLiteral(); 93 | } else if (current === "_" || ("a" <= current && current <= "z") || ("A" <= current && current <= "Z")) { 94 | scanKeywordOrIdentifier(); 95 | } else { 96 | const token = addToken(TokenKind.Unrecognized, current); 97 | bag.unrecognizedCharacter(current, token.range); 98 | } 99 | break; 100 | } 101 | } 102 | } 103 | 104 | function scanComment(): void { 105 | let lookAhead = index + 1; 106 | while (lookAhead < text.length) { 107 | const current = text[lookAhead]; 108 | if (current === "\r" || current === "\n") { 109 | break; 110 | } 111 | 112 | lookAhead += 1; 113 | } 114 | 115 | addToken(TokenKind.Comment, text.substring(index, lookAhead)); 116 | } 117 | 118 | function scanStringLiteral(): void { 119 | let lookAhead = index + 1; 120 | while (lookAhead < text.length) { 121 | const current = text[lookAhead]; 122 | switch (current) { 123 | case '"': { 124 | addToken(TokenKind.StringLiteral, text.substring(index, lookAhead + 1)); 125 | return; 126 | } 127 | case "\r": 128 | case "\n": { 129 | const token = addToken(TokenKind.StringLiteral, text.substring(index, lookAhead)); 130 | bag.unterminatedStringLiteral(token.range); 131 | return; 132 | } 133 | case "\\": { 134 | if (lookAhead + 1 < text.length) { 135 | const escaped = text[lookAhead + 1]; 136 | switch (escaped) { 137 | case "\\": 138 | case "/": 139 | case '"': 140 | case "b": 141 | case "f": 142 | case "n": 143 | case "r": 144 | case "t": { 145 | break; 146 | } 147 | default: { 148 | bag.unsupportedEscapeSequence(escaped, getRange(lookAhead + 1, 1)); 149 | break; 150 | } 151 | } 152 | lookAhead += 2; 153 | } else { 154 | lookAhead += 1; 155 | } 156 | break; 157 | } 158 | default: { 159 | if (current === "\u007F" || ("\u0000" <= current && current <= "\u001F")) { 160 | bag.unrecognizedCharacter(current, getRange(lookAhead, 1)); 161 | } 162 | 163 | lookAhead += 1; 164 | break; 165 | } 166 | } 167 | } 168 | 169 | const token = addToken(TokenKind.StringLiteral, text.substring(index, lookAhead)); 170 | bag.unterminatedStringLiteral(token.range); 171 | } 172 | 173 | function scanNumberLiteral(): void { 174 | let lookAhead = index + 1; 175 | while (lookAhead < text.length) { 176 | const current = text[lookAhead]; 177 | if ("0" <= current && current <= "9") { 178 | lookAhead += 1; 179 | } else { 180 | break; 181 | } 182 | } 183 | 184 | addToken(TokenKind.IntegerLiteral, text.substring(index, lookAhead)); 185 | } 186 | 187 | function scanKeywordOrIdentifier(): void { 188 | let lookAhead = index + 1; 189 | while (lookAhead < text.length) { 190 | const current = text[lookAhead]; 191 | if ( 192 | current === "_" || 193 | ("a" <= current && current <= "z") || 194 | ("A" <= current && current <= "Z") || 195 | ("0" <= current && current <= "9") 196 | ) { 197 | lookAhead += 1; 198 | } else { 199 | break; 200 | } 201 | } 202 | 203 | const length = lookAhead - index; 204 | const value = text.substr(index, length); 205 | 206 | switch (value) { 207 | case "version": { 208 | addToken(TokenKind.VersionKeyword, value); 209 | break; 210 | } 211 | case "workflow": { 212 | addToken(TokenKind.WorkflowKeyword, value); 213 | break; 214 | } 215 | case "action": { 216 | addToken(TokenKind.ActionKeyword, value); 217 | break; 218 | } 219 | case "on": { 220 | addToken(TokenKind.OnKeyword, value); 221 | break; 222 | } 223 | case "resolves": { 224 | addToken(TokenKind.ResolvesKeyword, value); 225 | break; 226 | } 227 | case "uses": { 228 | addToken(TokenKind.UsesKeyword, value); 229 | break; 230 | } 231 | case "needs": { 232 | addToken(TokenKind.NeedsKeyword, value); 233 | break; 234 | } 235 | case "runs": { 236 | addToken(TokenKind.RunsKeyword, value); 237 | break; 238 | } 239 | case "args": { 240 | addToken(TokenKind.ArgsKeyword, value); 241 | break; 242 | } 243 | case "env": { 244 | addToken(TokenKind.EnvKeyword, value); 245 | break; 246 | } 247 | case "secrets": { 248 | addToken(TokenKind.SecretsKeyword, value); 249 | break; 250 | } 251 | default: { 252 | addToken(TokenKind.Identifier, value); 253 | break; 254 | } 255 | } 256 | } 257 | 258 | function addToken(kind: TokenKind, contents: string): Token { 259 | const token = { 260 | kind, 261 | text: contents, 262 | range: getRange(character, contents.length), 263 | }; 264 | 265 | index += contents.length; 266 | character += contents.length; 267 | 268 | tokens.push(token); 269 | return token; 270 | } 271 | 272 | function getRange(character: number, length: number): Range { 273 | return Range.create(line, character, line, character + length); 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /src/scanning/tokens.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { Range } from "vscode-languageserver-types"; 6 | 7 | export enum TokenKind { 8 | // Top-level keywords 9 | VersionKeyword, 10 | WorkflowKeyword, 11 | ActionKeyword, 12 | 13 | // Bottom-level keywords 14 | OnKeyword, 15 | ResolvesKeyword, 16 | UsesKeyword, 17 | NeedsKeyword, 18 | RunsKeyword, 19 | ArgsKeyword, 20 | EnvKeyword, 21 | SecretsKeyword, 22 | 23 | // Punctuation 24 | Equal, 25 | Comma, 26 | 27 | // Brackets 28 | LeftCurlyBracket, 29 | RightCurlyBracket, 30 | LeftSquareBracket, 31 | RightSquareBracket, 32 | 33 | // Misc 34 | Identifier, 35 | Comment, 36 | 37 | // Literals 38 | IntegerLiteral, 39 | StringLiteral, 40 | 41 | // Generated 42 | Missing, 43 | Unrecognized, 44 | } 45 | 46 | export function getTokenDescription(kind: TokenKind): string { 47 | switch (kind) { 48 | case TokenKind.VersionKeyword: 49 | return "version"; 50 | case TokenKind.WorkflowKeyword: 51 | return "workflow"; 52 | case TokenKind.ActionKeyword: 53 | return "action"; 54 | 55 | case TokenKind.OnKeyword: 56 | return "on"; 57 | case TokenKind.ResolvesKeyword: 58 | return "resolves"; 59 | case TokenKind.UsesKeyword: 60 | return "uses"; 61 | case TokenKind.NeedsKeyword: 62 | return "needs"; 63 | case TokenKind.RunsKeyword: 64 | return "runs"; 65 | case TokenKind.ArgsKeyword: 66 | return "args"; 67 | case TokenKind.EnvKeyword: 68 | return "env"; 69 | case TokenKind.SecretsKeyword: 70 | return "secrets"; 71 | 72 | case TokenKind.Equal: 73 | return "="; 74 | case TokenKind.Comma: 75 | return ","; 76 | 77 | case TokenKind.LeftCurlyBracket: 78 | return "{"; 79 | case TokenKind.RightCurlyBracket: 80 | return "}"; 81 | case TokenKind.LeftSquareBracket: 82 | return "["; 83 | case TokenKind.RightSquareBracket: 84 | return "]"; 85 | 86 | case TokenKind.Identifier: 87 | return "identifier"; 88 | case TokenKind.Comment: 89 | return "comment"; 90 | 91 | case TokenKind.IntegerLiteral: 92 | return "integer"; 93 | case TokenKind.StringLiteral: 94 | return "string"; 95 | 96 | case TokenKind.Missing: 97 | return "missing"; 98 | case TokenKind.Unrecognized: 99 | return "unrecognized"; 100 | } 101 | } 102 | 103 | export interface Token { 104 | readonly kind: TokenKind; 105 | readonly range: Range; 106 | readonly text: string; 107 | } 108 | 109 | export interface TokenWithTrivia extends Token { 110 | readonly commentsBefore?: ReadonlyArray; 111 | readonly commentAfter?: TokenWithTrivia; 112 | } 113 | -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { 6 | createConnection, 7 | TextDocuments, 8 | IPCMessageReader, 9 | IPCMessageWriter, 10 | IConnection, 11 | ServerCapabilities, 12 | } from "vscode-languageserver"; 13 | import { DiagnosticsService } from "./services/diagnostics"; 14 | import { FoldingService } from "./services/folding"; 15 | import { RenamingService } from "./services/renaming"; 16 | import { FindReferencesService } from "./services/find-references"; 17 | import { GoToDefinitionService } from "./services/go-to-definition"; 18 | import { FormattingService } from "./services/formatting"; 19 | import { CompletionService } from "./services/completion"; 20 | 21 | export interface LanguageService { 22 | activate(connection: IConnection, documents: TextDocuments): void; 23 | fillCapabilities?(capabilities: ServerCapabilities): void; 24 | dispose?(): void; 25 | } 26 | 27 | const connection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process)); 28 | const documents: TextDocuments = new TextDocuments(); 29 | 30 | const services: ReadonlyArray = [ 31 | new CompletionService(), 32 | new DiagnosticsService(), 33 | new FindReferencesService(), 34 | new FoldingService(), 35 | new FormattingService(), 36 | new GoToDefinitionService(), 37 | new RenamingService(), 38 | ]; 39 | 40 | services.forEach(service => { 41 | service.activate(connection, documents); 42 | }); 43 | 44 | connection.onInitialize(() => { 45 | const capabilities: ServerCapabilities = { 46 | textDocumentSync: documents.syncKind, 47 | }; 48 | 49 | services.forEach(service => { 50 | if (service.fillCapabilities) { 51 | service.fillCapabilities(capabilities); 52 | } 53 | }); 54 | 55 | return { capabilities }; 56 | }); 57 | 58 | connection.onShutdown(() => { 59 | services.forEach(service => { 60 | if (service.dispose) { 61 | service.dispose(); 62 | } 63 | }); 64 | }); 65 | 66 | documents.listen(connection); 67 | connection.listen(); 68 | -------------------------------------------------------------------------------- /src/services/completion.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { 6 | IConnection, 7 | TextDocuments, 8 | ServerCapabilities, 9 | CompletionItem, 10 | Position, 11 | CompletionItemKind, 12 | } from "vscode-languageserver"; 13 | import { LanguageService } from "../server"; 14 | import { accessCache } from "../util/cache"; 15 | import { Compilation } from "../util/compilation"; 16 | import { rangeContains } from "../util/ranges"; 17 | import { TokenKind, getTokenDescription } from "../scanning/tokens"; 18 | import * as webhooks from "@octokit/webhooks-definitions"; 19 | import { 20 | SyntaxKind, 21 | ArrayPropertySyntax, 22 | StringPropertySyntax, 23 | BasePropertySyntax, 24 | BlockSyntax, 25 | } from "../parsing/syntax-nodes"; 26 | 27 | export class CompletionService implements LanguageService { 28 | public fillCapabilities(capabilities: ServerCapabilities): void { 29 | capabilities.completionProvider = { 30 | triggerCharacters: ['"'], 31 | }; 32 | } 33 | 34 | public activate(connection: IConnection, documents: TextDocuments): void { 35 | connection.onCompletion(params => { 36 | const { uri } = params.textDocument; 37 | const compilation = accessCache(documents, uri); 38 | return CompletionService.provideCompletion(compilation, params.position); 39 | }); 40 | } 41 | 42 | public static provideCompletion(compilation: Compilation, position: Position): CompletionItem[] { 43 | for (const block of compilation.syntax.blocks) { 44 | if (rangeContains(block.range, position)) { 45 | for (const property of block.properties) { 46 | if (rangeContains(property.range, position)) { 47 | switch (property.key.kind) { 48 | case TokenKind.ResolvesKeyword: 49 | case TokenKind.NeedsKeyword: { 50 | return provideActions(compilation, property, position); 51 | } 52 | case TokenKind.OnKeyword: { 53 | return provideEvents(property, position); 54 | } 55 | default: { 56 | return []; 57 | } 58 | } 59 | } 60 | } 61 | 62 | return provideProperties(block); 63 | } 64 | } 65 | 66 | return []; 67 | } 68 | } 69 | 70 | function provideEvents(property: BasePropertySyntax, position: Position): CompletionItem[] { 71 | if (!isInsideString(property, position)) { 72 | return []; 73 | } 74 | 75 | return webhooks.map(webhook => { 76 | return { 77 | label: webhook.name, 78 | kind: CompletionItemKind.Event, 79 | detail: `Insert the event '${webhook.name}'.`, 80 | }; 81 | }); 82 | } 83 | 84 | function provideActions(compilation: Compilation, property: BasePropertySyntax, position: Position): CompletionItem[] { 85 | if (!isInsideString(property, position)) { 86 | return []; 87 | } 88 | 89 | return Array(...compilation.actions.keys()).map(action => { 90 | return { 91 | label: action, 92 | kind: CompletionItemKind.Class, 93 | detail: `Insert the action '${action}'.`, 94 | }; 95 | }); 96 | } 97 | 98 | function provideProperties(block: BlockSyntax): CompletionItem[] { 99 | let kinds: TokenKind[]; 100 | switch (block.type.kind) { 101 | case TokenKind.WorkflowKeyword: { 102 | kinds = [TokenKind.OnKeyword, TokenKind.ResolvesKeyword]; 103 | break; 104 | } 105 | case TokenKind.ActionKeyword: { 106 | kinds = [ 107 | TokenKind.UsesKeyword, 108 | TokenKind.NeedsKeyword, 109 | TokenKind.RunsKeyword, 110 | TokenKind.ArgsKeyword, 111 | TokenKind.EnvKeyword, 112 | TokenKind.SecretsKeyword, 113 | ]; 114 | break; 115 | } 116 | default: { 117 | throw new Error(`Unexpected token kind '${block.type.kind}'`); 118 | } 119 | } 120 | 121 | return kinds.map(kind => { 122 | const text = getTokenDescription(kind); 123 | return { 124 | label: text, 125 | kind: CompletionItemKind.Property, 126 | detail: `Insert a new '${text}' property.`, 127 | }; 128 | }); 129 | } 130 | 131 | function isInsideString(property: BasePropertySyntax, position: Position): boolean { 132 | switch (property.kind) { 133 | case SyntaxKind.ArrayProperty: { 134 | return (property as ArrayPropertySyntax).items.some(item => rangeContains(item.value.range, position)); 135 | } 136 | case SyntaxKind.StringProperty: { 137 | const value = (property as StringPropertySyntax).value; 138 | return value ? rangeContains(value.range, position) : false; 139 | } 140 | case SyntaxKind.ObjectMember: { 141 | return false; 142 | } 143 | default: { 144 | throw new Error(`Unexpected syntax kind '${property.kind}'`); 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/services/diagnostics.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { IConnection, TextDocuments, Diagnostic } from "vscode-languageserver"; 6 | import { LanguageService } from "../server"; 7 | import { accessCache } from "../util/cache"; 8 | 9 | export class DiagnosticsService implements LanguageService { 10 | public activate(connection: IConnection, documents: TextDocuments): void { 11 | connection.onDidOpenTextDocument(params => { 12 | const { uri, version } = params.textDocument; 13 | connection.sendDiagnostics({ 14 | uri, 15 | diagnostics: provideDiagnostics(documents, uri, version), 16 | }); 17 | }); 18 | 19 | documents.onDidChangeContent(params => { 20 | const { uri, version } = params.document; 21 | connection.sendDiagnostics({ 22 | uri: params.document.uri, 23 | diagnostics: provideDiagnostics(documents, uri, version), 24 | }); 25 | }); 26 | 27 | connection.onDidCloseTextDocument(params => { 28 | connection.sendDiagnostics({ 29 | uri: params.textDocument.uri, 30 | diagnostics: [], 31 | }); 32 | }); 33 | 34 | function provideDiagnostics(documents: TextDocuments, uri: string, version: number): Diagnostic[] { 35 | const compilation = accessCache(documents, uri, version); 36 | return compilation.diagnostics.map(diagnostic => { 37 | return Diagnostic.create(diagnostic.range, diagnostic.message); 38 | }); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/services/find-references.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { IConnection, TextDocuments, ServerCapabilities, Location } from "vscode-languageserver"; 6 | import { LanguageService } from "../server"; 7 | import { accessCache } from "../util/cache"; 8 | 9 | export class FindReferencesService implements LanguageService { 10 | public fillCapabilities(capabilities: ServerCapabilities): void { 11 | capabilities.referencesProvider = true; 12 | } 13 | 14 | public activate(connection: IConnection, documents: TextDocuments): void { 15 | connection.onReferences(params => { 16 | const { uri } = params.textDocument; 17 | const compilation = accessCache(documents, uri); 18 | 19 | const target = compilation.getTargetAt(params.position); 20 | if (!target) { 21 | return undefined; 22 | } 23 | 24 | const action = compilation.actions.get(target.name); 25 | if (!action) { 26 | return undefined; 27 | } 28 | 29 | return action.references.map(range => Location.create(uri, range)); 30 | }); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/services/folding.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { IConnection, TextDocuments, FoldingRangeKind, FoldingRange, ServerCapabilities } from "vscode-languageserver"; 6 | import { LanguageService } from "../server"; 7 | import { accessCache } from "../util/cache"; 8 | 9 | export class FoldingService implements LanguageService { 10 | public fillCapabilities(capabilities: ServerCapabilities): void { 11 | capabilities.foldingRangeProvider = true; 12 | } 13 | 14 | public activate(connection: IConnection, documents: TextDocuments): void { 15 | connection.onFoldingRanges(params => { 16 | const { uri } = params.textDocument; 17 | const compilation = accessCache(documents, uri); 18 | 19 | return compilation.syntax.blocks.map(block => { 20 | const start = block.openBracket.range.start; 21 | const end = block.closeBracket.range.end; 22 | return FoldingRange.create(start.line, end.line, start.character, end.character, FoldingRangeKind.Region); 23 | }); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/services/formatting.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { IConnection, TextDocuments, ServerCapabilities, TextEdit, Range } from "vscode-languageserver"; 6 | import { LanguageService } from "../server"; 7 | import { accessCache } from "../util/cache"; 8 | import { Compilation } from "../util/compilation"; 9 | import { TokenWithTrivia, Token, TokenKind } from "../scanning/tokens"; 10 | import { 11 | BlockSyntax, 12 | StringPropertySyntax, 13 | ArrayPropertySyntax, 14 | ObjectPropertySyntax, 15 | SyntaxKind, 16 | } from "../parsing/syntax-nodes"; 17 | import { DiagnosticCode } from "../util/diagnostics"; 18 | 19 | const PARSE_ERRORS_MESSAGE = "Cannot format document with parsing errors."; 20 | 21 | export class FormattingService implements LanguageService { 22 | public fillCapabilities(capabilities: ServerCapabilities): void { 23 | capabilities.documentFormattingProvider = true; 24 | } 25 | 26 | public activate(connection: IConnection, documents: TextDocuments): void { 27 | connection.onDocumentFormatting(params => { 28 | const { uri } = params.textDocument; 29 | const compilation = accessCache(documents, uri); 30 | 31 | if (compilation.diagnostics.some(d => (d.code as number) < DiagnosticCode.PARSING_ERRORS_MARK)) { 32 | connection.window.showErrorMessage(PARSE_ERRORS_MESSAGE); 33 | return []; 34 | } 35 | 36 | const { insertSpaces, tabSize } = params.options; 37 | const indentationValue = insertSpaces ? " ".repeat(tabSize) : "\t"; 38 | 39 | const result = FormattingService.format(compilation, indentationValue); 40 | const fullRange = Range.create(0, 0, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); 41 | return [TextEdit.replace(fullRange, result)]; 42 | }); 43 | } 44 | 45 | public static format(compilation: Compilation, indentationValue: string): string { 46 | const lines = Array(); 47 | let indentationLevel = 0; 48 | let lastTokenAdded: Token | undefined; 49 | let currentLine = ""; 50 | 51 | compilation.syntax.commentsAfter.forEach(comment => { 52 | add(comment); 53 | }); 54 | 55 | compilation.syntax.versions.forEach(version => { 56 | add(version.version); 57 | add(version.equal); 58 | add(version.integer); 59 | }); 60 | 61 | compilation.syntax.blocks.forEach(block => { 62 | addBlockLikeSyntax({ 63 | firstToken: block.type, 64 | secondToken: block.name, 65 | openBracket: block.openBracket, 66 | addBody: () => addProperties(block), 67 | closeBracket: block.closeBracket, 68 | }); 69 | }); 70 | 71 | addLineBreak(true); 72 | addLineBreak(true); 73 | return lines.join("\n"); 74 | 75 | function addProperties(block: BlockSyntax): void { 76 | const strings = Array(); 77 | const arrays = Array(); 78 | const objects = Array(); 79 | 80 | block.properties.forEach(property => { 81 | switch (property.kind) { 82 | case SyntaxKind.StringProperty: 83 | strings.push(property as StringPropertySyntax); 84 | break; 85 | case SyntaxKind.ArrayProperty: 86 | arrays.push(property as ArrayPropertySyntax); 87 | break; 88 | case SyntaxKind.ObjectProperty: 89 | objects.push(property as ObjectPropertySyntax); 90 | break; 91 | default: 92 | throw new Error(`Syntax kind '${property.kind}' is not supported`); 93 | } 94 | }); 95 | 96 | const longestKeyLength = Math.max(...block.properties.map(s => s.key.text.length)); 97 | 98 | strings.forEach(property => { 99 | add(property.key); 100 | 101 | if (!property.key.commentAfter && !property.equal.commentsBefore) { 102 | currentLine += " ".repeat(longestKeyLength - property.key.text.length); 103 | } 104 | 105 | add(property.equal); 106 | add(property.value); 107 | addLineBreak(); 108 | }); 109 | 110 | arrays.forEach(property => { 111 | addBlockLikeSyntax({ 112 | longestKeyLength, 113 | firstToken: property.key, 114 | secondToken: property.equal, 115 | openBracket: property.openBracket, 116 | addBody: () => 117 | property.items.forEach(item => { 118 | add(item.value); 119 | add(item.comma, false); 120 | addLineBreak(); 121 | }), 122 | closeBracket: property.closeBracket, 123 | }); 124 | }); 125 | 126 | objects.forEach(property => { 127 | addBlockLikeSyntax({ 128 | longestKeyLength, 129 | firstToken: property.key, 130 | secondToken: property.equal, 131 | openBracket: property.openBracket, 132 | addBody: () => { 133 | const longestNameLength = Math.max(...property.members.map(member => member.name.text.length)); 134 | property.members.forEach(member => { 135 | add(member.name); 136 | 137 | if (!member.name.commentAfter && !member.equal.commentsBefore) { 138 | currentLine += " ".repeat(longestNameLength - member.name.text.length); 139 | } 140 | 141 | add(member.equal); 142 | add(member.value); 143 | add(member.comma, false); 144 | addLineBreak(); 145 | }); 146 | }, 147 | closeBracket: property.closeBracket, 148 | }); 149 | }); 150 | } 151 | 152 | function addBlockLikeSyntax(opts: { 153 | readonly longestKeyLength?: number; 154 | readonly firstToken: TokenWithTrivia; 155 | readonly secondToken: TokenWithTrivia; 156 | readonly openBracket: TokenWithTrivia; 157 | readonly addBody: Function; 158 | readonly closeBracket: TokenWithTrivia; 159 | }): void { 160 | addLineBreak(true); 161 | 162 | add(opts.firstToken); 163 | 164 | if (opts.longestKeyLength && !opts.firstToken.commentAfter && !opts.secondToken.commentsBefore) { 165 | currentLine += " ".repeat(opts.longestKeyLength - opts.firstToken.text.length); 166 | } 167 | 168 | indentationLevel += 1; 169 | 170 | add(opts.secondToken); 171 | add(opts.openBracket); 172 | addLineBreak(); 173 | 174 | opts.addBody(); 175 | addLineBreak(); 176 | 177 | indentationLevel -= 1; 178 | add(opts.closeBracket); 179 | addLineBreak(); 180 | } 181 | 182 | function addLineBreak(addEmpty: boolean = false): void { 183 | if (currentLine.length === 0) { 184 | if (!addEmpty || lines.length === 0 || lines[lines.length - 1].length === 0) { 185 | return; 186 | } 187 | 188 | if (lastTokenAdded) { 189 | switch (lastTokenAdded.kind) { 190 | case TokenKind.Comment: 191 | case TokenKind.LeftCurlyBracket: 192 | case TokenKind.LeftSquareBracket: 193 | return; 194 | default: 195 | break; 196 | } 197 | } 198 | } 199 | 200 | lines.push(currentLine); 201 | currentLine = ""; 202 | } 203 | 204 | function add(token: TokenWithTrivia | undefined, addSpace: boolean = true): void { 205 | if (!token) { 206 | return; 207 | } 208 | 209 | if (token.kind === TokenKind.Missing) { 210 | throw new Error(PARSE_ERRORS_MESSAGE); 211 | } 212 | 213 | if (token.commentsBefore) { 214 | token.commentsBefore.forEach(comment => { 215 | add(comment); 216 | addLineBreak(); 217 | }); 218 | } 219 | 220 | if (currentLine.length === 0) { 221 | currentLine = indentationValue.repeat(indentationLevel); 222 | } else if (addSpace) { 223 | currentLine += " "; 224 | } 225 | 226 | currentLine += token.text; 227 | lastTokenAdded = token; 228 | 229 | if (token.commentAfter) { 230 | add(token.commentAfter); 231 | addLineBreak(); 232 | } 233 | } 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/services/go-to-definition.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { IConnection, TextDocuments, ServerCapabilities, Position, Location } from "vscode-languageserver"; 6 | import { LanguageService } from "../server"; 7 | import { accessCache } from "../util/cache"; 8 | 9 | export class GoToDefinitionService implements LanguageService { 10 | public fillCapabilities(capabilities: ServerCapabilities): void { 11 | capabilities.definitionProvider = true; 12 | capabilities.typeDefinitionProvider = true; 13 | } 14 | 15 | public activate(connection: IConnection, documents: TextDocuments): void { 16 | connection.onDefinition(params => { 17 | return getDefinitionRange(params.textDocument.uri, params.position); 18 | }); 19 | 20 | connection.onTypeDefinition(params => { 21 | return getDefinitionRange(params.textDocument.uri, params.position); 22 | }); 23 | 24 | function getDefinitionRange(uri: string, position: Position): Location | undefined { 25 | const compilation = accessCache(documents, uri); 26 | 27 | const target = compilation.getTargetAt(position); 28 | if (!target) { 29 | return undefined; 30 | } 31 | 32 | const action = compilation.actions.get(target.name); 33 | if (!action) { 34 | return undefined; 35 | } 36 | 37 | return Location.create(uri, action.range); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/services/renaming.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { IConnection, TextDocuments, TextEdit, Range, ServerCapabilities } from "vscode-languageserver"; 6 | import { LanguageService } from "../server"; 7 | import { accessCache } from "../util/cache"; 8 | 9 | export class RenamingService implements LanguageService { 10 | public fillCapabilities(capabilities: ServerCapabilities): void { 11 | capabilities.renameProvider = { 12 | prepareProvider: true, 13 | }; 14 | } 15 | 16 | public activate(connection: IConnection, documents: TextDocuments): void { 17 | connection.onPrepareRename(params => { 18 | const { uri } = params.textDocument; 19 | const compilation = accessCache(documents, uri); 20 | 21 | const target = compilation.getTargetAt(params.position); 22 | if (!target) { 23 | return undefined; 24 | } 25 | 26 | return { 27 | placeholder: target.name, 28 | range: target.range, 29 | }; 30 | }); 31 | 32 | connection.onRenameRequest(params => { 33 | const { uri } = params.textDocument; 34 | const compilation = accessCache(documents, uri); 35 | 36 | const target = compilation.getTargetAt(params.position); 37 | if (!target) { 38 | return undefined; 39 | } 40 | 41 | const action = compilation.actions.get(target.name); 42 | if (!action) { 43 | return undefined; 44 | } 45 | 46 | return { 47 | changes: { 48 | [uri]: [action.range, ...action.references].map(range => { 49 | const { start, end } = range; 50 | return TextEdit.replace( 51 | Range.create(start.line, start.character + 1, end.line, end.character - 1), 52 | params.newName, 53 | ); 54 | }), 55 | }, 56 | }; 57 | }); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/util/cache.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as LRU from "lru-cache"; 6 | import { Compilation } from "./compilation"; 7 | import { TextDocuments } from "vscode-languageserver"; 8 | 9 | interface Entry { 10 | readonly version: number; 11 | readonly compilation: Compilation; 12 | } 13 | 14 | const cache = new LRU(10); 15 | 16 | export function accessCache(documents: TextDocuments, uri: string, version?: number): Compilation { 17 | const entry = cache.get(uri); 18 | if (entry && entry.version === version) { 19 | return entry.compilation; 20 | } 21 | 22 | const document = documents.get(uri); 23 | if (!document) { 24 | throw new Error(`Cannot find a document with uri: ${uri}`); 25 | } else if (entry && entry.version === document.version) { 26 | return entry.compilation; 27 | } 28 | 29 | const compilation = new Compilation(document.getText()); 30 | cache.set(uri, { 31 | compilation, 32 | version: document.version, 33 | }); 34 | 35 | return compilation; 36 | } 37 | -------------------------------------------------------------------------------- /src/util/compilation.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { DiagnosticBag } from "./diagnostics"; 6 | import { scanText } from "../scanning/scanner"; 7 | import { Token } from "../scanning/tokens"; 8 | import { DocumentSyntax } from "../parsing/syntax-nodes"; 9 | import { parseTokens } from "../parsing/parser"; 10 | import { BoundDocument } from "../binding/bound-nodes"; 11 | import { bindDocument } from "../binding/binder"; 12 | import { analyzeCircularDependencies } from "../analysis/circular-dependencies"; 13 | import { analyzeSecrets } from "../analysis/secrets"; 14 | import { analyzeBlocks } from "../analysis/blocks"; 15 | import { analyzeActions } from "../analysis/actions"; 16 | import { Range, Position, Diagnostic } from "vscode-languageserver-types"; 17 | import { rangeContains } from "./ranges"; 18 | 19 | export interface ActionSymbol { 20 | readonly name: string; 21 | readonly range: Range; 22 | readonly references: ReadonlyArray; 23 | } 24 | 25 | export class Compilation { 26 | private readonly bag: DiagnosticBag; 27 | 28 | private lazyActions: Map | undefined; 29 | 30 | public readonly tokens: ReadonlyArray; 31 | public readonly syntax: DocumentSyntax; 32 | public readonly document: BoundDocument; 33 | 34 | public constructor(public readonly text: string) { 35 | this.bag = new DiagnosticBag(); 36 | 37 | this.tokens = scanText(text, this.bag); 38 | this.syntax = parseTokens(this.tokens, this.bag); 39 | this.document = bindDocument(this.syntax, this.bag); 40 | 41 | analyzeActions(this.document, this.bag); 42 | analyzeBlocks(this.document, this.bag); 43 | analyzeCircularDependencies(this.document, this.bag); 44 | analyzeSecrets(this.document, this.bag); 45 | } 46 | 47 | public get diagnostics(): ReadonlyArray { 48 | return this.bag.diagnostics; 49 | } 50 | 51 | public get actions(): ReadonlyMap { 52 | if (!this.lazyActions) { 53 | this.lazyActions = new Map(); 54 | 55 | for (const node of this.document.actions) { 56 | const references = Array(); 57 | 58 | this.document.actions.forEach(action => { 59 | if (action.needs) { 60 | action.needs.actions.forEach(reference => { 61 | if (reference.value === node.name) { 62 | references.push(reference.syntax.range); 63 | } 64 | }); 65 | } 66 | }); 67 | 68 | this.document.workflows.forEach(workflow => { 69 | if (workflow.resolves) { 70 | workflow.resolves.actions.forEach(reference => { 71 | if (reference.value === node.name) { 72 | references.push(reference.syntax.range); 73 | } 74 | }); 75 | } 76 | }); 77 | 78 | this.lazyActions.set(node.name, { 79 | references, 80 | name: node.name, 81 | range: node.syntax.name.range, 82 | }); 83 | } 84 | } 85 | 86 | return this.lazyActions; 87 | } 88 | 89 | public getTargetAt( 90 | position: Position, 91 | ): 92 | | { 93 | name: string; 94 | range: Range; 95 | } 96 | | undefined { 97 | for (const action of this.actions.values()) { 98 | if (rangeContains(action.range, position)) { 99 | return { 100 | name: action.name, 101 | range: action.range, 102 | }; 103 | } 104 | 105 | for (const reference of action.references) { 106 | if (rangeContains(reference, position)) { 107 | return { 108 | name: action.name, 109 | range: reference, 110 | }; 111 | } 112 | } 113 | } 114 | 115 | return undefined; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/util/constants.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | export const MAXIMUM_SUPPORTED_VERSION = 0; 6 | export const MAXIMUM_SUPPORTED_SECRETS = 100; 7 | export const MAXIMUM_SUPPORTED_ACTIONS = 100; 8 | 9 | export const LANGUAGE_NAME = "github-actions"; 10 | 11 | export module USES_REGEX { 12 | const ALPHA_NUM = `[a-zA-Z0-9]`; 13 | const ALPHA_NUM_DASH = `[a-zA-Z0-9-]`; 14 | 15 | const DOCKER_HOST_COMPONENT = `(${ALPHA_NUM}|(${ALPHA_NUM}${ALPHA_NUM_DASH}*${ALPHA_NUM}))`; 16 | const DOCKER_REGISTRY = `(${DOCKER_HOST_COMPONENT}(\\.${DOCKER_HOST_COMPONENT})*(:[0-9]+)?\\/)`; 17 | const DOCKER_PATH_COMPONENT = `(${ALPHA_NUM}+([._-]${ALPHA_NUM}+)*)`; 18 | const DOCKER_TAG = `(:[a-zA-Z0-9_]+)`; 19 | const DOCKER_DIGEST_ALGORITHM = `[A-Za-z]${ALPHA_NUM}*`; 20 | const DOCKER_DIGEST = `(@${DOCKER_DIGEST_ALGORITHM}([+.-_]${DOCKER_DIGEST_ALGORITHM})*:[a-fA-F0-9]+)`; 21 | const DOCKER_USES = `docker:\\/\\/${DOCKER_REGISTRY}?${DOCKER_PATH_COMPONENT}(\\/${DOCKER_PATH_COMPONENT})*(${DOCKER_TAG}|${DOCKER_DIGEST})?`; 22 | 23 | const LOCAL_USES = `\\.\\/.*`; 24 | 25 | const REMOTE_OWNER = `${ALPHA_NUM}+(${ALPHA_NUM_DASH}${ALPHA_NUM}+)*`; 26 | const REMOTE_PATH = `(\\/[a-zA-Z0-9-_.]+)`; 27 | const REMOTE_REF = `@.+`; 28 | const REMOTE_USES = `${REMOTE_OWNER}${REMOTE_PATH}+${REMOTE_REF}`; 29 | 30 | const COMBINED = new RegExp(`^(${DOCKER_USES})|(${LOCAL_USES})|(${REMOTE_USES})$`); 31 | 32 | export function test(value: string): boolean { 33 | return COMBINED.test(value); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/util/diagnostics.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { TokenKind, getTokenDescription, Token } from "../scanning/tokens"; 6 | import { 7 | MAXIMUM_SUPPORTED_VERSION, 8 | MAXIMUM_SUPPORTED_SECRETS, 9 | MAXIMUM_SUPPORTED_ACTIONS, 10 | LANGUAGE_NAME, 11 | } from "./constants"; 12 | import { Range, Diagnostic, DiagnosticSeverity } from "vscode-languageserver-types"; 13 | 14 | export enum DiagnosticCode { 15 | // Scanning 16 | UnrecognizedCharacter, 17 | UnterminatedStringLiteral, 18 | UnsupportedEscapeSequence, 19 | 20 | // Parsing 21 | MissingToken, 22 | UnexpectedToken, 23 | 24 | // Divider 25 | PARSING_ERRORS_MARK, 26 | 27 | // Binding 28 | MultipleVersion, 29 | UnrecognizedVersion, 30 | VersionAfterBlock, 31 | ValueIsNotString, 32 | ValueIsNotStringOrArray, 33 | ValueIsNotAnObject, 34 | PropertyAlreadyDefined, 35 | PropertyMustBeDefined, 36 | InvalidProperty, 37 | DuplicateKey, 38 | 39 | // Block Analysis 40 | TooManyActions, 41 | DuplicateBlock, 42 | CircularDependency, 43 | 44 | // Property Analysis 45 | ActionDoesNotExist, 46 | TooManySecrets, 47 | DuplicateSecrets, 48 | DuplicateActions, 49 | ReservedEnvironmentVariable, 50 | UnrecognizedEvent, 51 | InvalidUses, 52 | } 53 | 54 | export function severityToString(severity: DiagnosticSeverity | undefined): string { 55 | switch (severity) { 56 | case undefined: 57 | case DiagnosticSeverity.Error: 58 | return "ERROR"; 59 | case DiagnosticSeverity.Warning: 60 | return "WARN"; 61 | default: 62 | throw new Error(`Unexpected severity: '${severity}'.`); 63 | } 64 | } 65 | 66 | export class DiagnosticBag { 67 | private readonly items: Diagnostic[]; 68 | 69 | public constructor() { 70 | this.items = []; 71 | } 72 | 73 | public get diagnostics(): ReadonlyArray { 74 | return this.items; 75 | } 76 | 77 | public unrecognizedCharacter(character: string, range: Range): void { 78 | this.items.push({ 79 | range, 80 | source: LANGUAGE_NAME, 81 | severity: DiagnosticSeverity.Error, 82 | code: DiagnosticCode.UnrecognizedCharacter, 83 | message: `The character '${character}' is unrecognizable.`, 84 | }); 85 | } 86 | 87 | public unterminatedStringLiteral(range: Range): void { 88 | this.items.push({ 89 | range, 90 | source: LANGUAGE_NAME, 91 | severity: DiagnosticSeverity.Error, 92 | code: DiagnosticCode.UnterminatedStringLiteral, 93 | message: `This string literal must end with double quotes.`, 94 | }); 95 | } 96 | 97 | public unsupportedEscapeSequence(character: string, range: Range): void { 98 | this.items.push({ 99 | range, 100 | source: LANGUAGE_NAME, 101 | severity: DiagnosticSeverity.Error, 102 | code: DiagnosticCode.UnsupportedEscapeSequence, 103 | message: `The character '${character}' is not a supported escape sequence.`, 104 | }); 105 | } 106 | 107 | public missingToken(kinds: TokenKind[], range: Range, endOfFile: boolean): void { 108 | this.items.push({ 109 | range, 110 | code: DiagnosticCode.MissingToken, 111 | source: LANGUAGE_NAME, 112 | severity: DiagnosticSeverity.Error, 113 | message: `A token of kind ${kinds.map(k => `'${getTokenDescription(k)}'`).join(" or ")} was expected ${ 114 | endOfFile ? "after this" : "here" 115 | }.`, 116 | }); 117 | } 118 | 119 | public unexpectedToken(token: Token): void { 120 | this.items.push({ 121 | range: token.range, 122 | code: DiagnosticCode.UnexpectedToken, 123 | source: LANGUAGE_NAME, 124 | severity: DiagnosticSeverity.Error, 125 | message: `A token of kind '${getTokenDescription(token.kind)}' was not expected here.`, 126 | }); 127 | } 128 | 129 | public multipleVersions(range: Range): void { 130 | this.items.push({ 131 | range, 132 | code: DiagnosticCode.MultipleVersion, 133 | source: LANGUAGE_NAME, 134 | severity: DiagnosticSeverity.Error, 135 | message: `A version is already specified for this document'. You can only specify one.`, 136 | }); 137 | } 138 | 139 | public unrecognizedVersion(version: string, range: Range): void { 140 | this.items.push({ 141 | range, 142 | code: DiagnosticCode.UnrecognizedVersion, 143 | source: LANGUAGE_NAME, 144 | severity: DiagnosticSeverity.Error, 145 | message: `The version '${version}' is not valid. Only versions up to '${MAXIMUM_SUPPORTED_VERSION}' are supported.`, 146 | }); 147 | } 148 | 149 | public versionAfterBlock(range: Range): void { 150 | this.items.push({ 151 | range, 152 | code: DiagnosticCode.VersionAfterBlock, 153 | source: LANGUAGE_NAME, 154 | severity: DiagnosticSeverity.Error, 155 | message: `Version must be specified before all actions or workflows are defined.`, 156 | }); 157 | } 158 | 159 | public valueIsNotString(range: Range): void { 160 | this.items.push({ 161 | range, 162 | code: DiagnosticCode.ValueIsNotString, 163 | source: LANGUAGE_NAME, 164 | severity: DiagnosticSeverity.Error, 165 | message: `Value must be a single string.`, 166 | }); 167 | } 168 | 169 | public valueIsNotStringOrArray(range: Range): void { 170 | this.items.push({ 171 | range, 172 | code: DiagnosticCode.ValueIsNotStringOrArray, 173 | source: LANGUAGE_NAME, 174 | severity: DiagnosticSeverity.Error, 175 | message: `Value must be a single string or an array of strings.`, 176 | }); 177 | } 178 | 179 | public valueIsNotAnObject(range: Range): void { 180 | this.items.push({ 181 | range, 182 | code: DiagnosticCode.ValueIsNotAnObject, 183 | source: LANGUAGE_NAME, 184 | severity: DiagnosticSeverity.Error, 185 | message: `Value must be an object.`, 186 | }); 187 | } 188 | 189 | public propertyAlreadyDefined(keyword: Token): void { 190 | this.items.push({ 191 | range: keyword.range, 192 | code: DiagnosticCode.PropertyAlreadyDefined, 193 | source: LANGUAGE_NAME, 194 | severity: DiagnosticSeverity.Error, 195 | message: `A property '${getTokenDescription(keyword.kind)}' is already defined in this block.`, 196 | }); 197 | } 198 | 199 | public propertyMustBeDefined(property: TokenKind, block: Token): void { 200 | this.items.push({ 201 | range: block.range, 202 | code: DiagnosticCode.PropertyMustBeDefined, 203 | source: LANGUAGE_NAME, 204 | severity: DiagnosticSeverity.Error, 205 | message: `This '${getTokenDescription(block.kind)}' must define a '${getTokenDescription(property)}' property.`, 206 | }); 207 | } 208 | 209 | public invalidProperty(property: Token, block: TokenKind): void { 210 | this.items.push({ 211 | range: property.range, 212 | code: DiagnosticCode.InvalidProperty, 213 | source: LANGUAGE_NAME, 214 | severity: DiagnosticSeverity.Error, 215 | message: `A property of kind '${getTokenDescription( 216 | property.kind, 217 | )}' cannot be defined for a '${getTokenDescription(block)}' block.`, 218 | }); 219 | } 220 | 221 | public duplicateKey(key: string, range: Range): void { 222 | this.items.push({ 223 | range, 224 | code: DiagnosticCode.DuplicateKey, 225 | source: LANGUAGE_NAME, 226 | severity: DiagnosticSeverity.Error, 227 | message: `A key with the name '${key}' is already defined.`, 228 | }); 229 | } 230 | 231 | public tooManyActions(range: Range): void { 232 | this.items.push({ 233 | range, 234 | code: DiagnosticCode.TooManyActions, 235 | source: LANGUAGE_NAME, 236 | severity: DiagnosticSeverity.Error, 237 | message: `Too many actions defined. The maximum currently supported is '${MAXIMUM_SUPPORTED_ACTIONS}'.`, 238 | }); 239 | } 240 | 241 | public duplicateBlock(duplicate: string, range: Range): void { 242 | this.items.push({ 243 | range, 244 | code: DiagnosticCode.DuplicateBlock, 245 | source: LANGUAGE_NAME, 246 | severity: DiagnosticSeverity.Error, 247 | message: `This file already defines another workflow or action with the name '${duplicate}'.`, 248 | }); 249 | } 250 | 251 | public circularDependency(action: string, range: Range): void { 252 | this.items.push({ 253 | range, 254 | code: DiagnosticCode.CircularDependency, 255 | source: LANGUAGE_NAME, 256 | severity: DiagnosticSeverity.Error, 257 | message: `The action '${action}' has a circular dependency on itself.`, 258 | }); 259 | } 260 | 261 | public actionDoesNotExist(action: string, range: Range): void { 262 | this.items.push({ 263 | range, 264 | code: DiagnosticCode.ActionDoesNotExist, 265 | source: LANGUAGE_NAME, 266 | severity: DiagnosticSeverity.Error, 267 | message: `The action '${action}' does not exist in the same workflow file.`, 268 | }); 269 | } 270 | 271 | public tooManySecrets(range: Range): void { 272 | this.items.push({ 273 | range, 274 | code: DiagnosticCode.TooManySecrets, 275 | source: LANGUAGE_NAME, 276 | severity: DiagnosticSeverity.Error, 277 | message: `Too many secrets defined. The maximum currently supported is '${MAXIMUM_SUPPORTED_SECRETS}'.`, 278 | }); 279 | } 280 | 281 | public duplicateSecrets(duplicate: string, range: Range): void { 282 | this.items.push({ 283 | range, 284 | code: DiagnosticCode.DuplicateSecrets, 285 | source: LANGUAGE_NAME, 286 | severity: DiagnosticSeverity.Error, 287 | message: `This property has duplicate '${duplicate}' secrets.`, 288 | }); 289 | } 290 | 291 | public duplicateActions(duplicate: string, range: Range): void { 292 | this.items.push({ 293 | range, 294 | code: DiagnosticCode.DuplicateActions, 295 | source: LANGUAGE_NAME, 296 | severity: DiagnosticSeverity.Error, 297 | message: `This property has duplicate '${duplicate}' actions.`, 298 | }); 299 | } 300 | 301 | public reservedEnvironmentVariable(range: Range): void { 302 | this.items.push({ 303 | range, 304 | code: DiagnosticCode.ReservedEnvironmentVariable, 305 | source: LANGUAGE_NAME, 306 | severity: DiagnosticSeverity.Error, 307 | message: `Environment variables starting with 'GITHUB_' are reserved.`, 308 | }); 309 | } 310 | 311 | public unrecognizedEvent(event: string, range: Range): void { 312 | this.items.push({ 313 | range, 314 | code: DiagnosticCode.UnrecognizedEvent, 315 | source: LANGUAGE_NAME, 316 | severity: DiagnosticSeverity.Error, 317 | message: `The event '${event}' is not a known event type or a schedule.`, 318 | }); 319 | } 320 | 321 | public invalidUses(range: Range): void { 322 | this.items.push({ 323 | range, 324 | code: DiagnosticCode.InvalidUses, 325 | source: LANGUAGE_NAME, 326 | severity: DiagnosticSeverity.Error, 327 | message: `The 'uses' property must be a path, a Docker image, or an owner/repo@ref remote.`, 328 | }); 329 | } 330 | } 331 | -------------------------------------------------------------------------------- /src/util/highlight-range.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { Range } from "vscode-languageserver-types"; 6 | 7 | export const EOL_REGEX = /\r?\n/; 8 | 9 | export function highlight(range: Range, text: string): string { 10 | if (range.start.line !== range.end.line) { 11 | throw new Error(`Cannot format a multi-line range`); 12 | } 13 | 14 | const result = Array(); 15 | 16 | const lines = text.split(EOL_REGEX); 17 | const { line, character: start } = range.start; 18 | const { character: end } = range.end; 19 | 20 | const firstLine = Math.max(0, line - 2); 21 | const lastLine = Math.min(line + 2, lines.length - 1); 22 | 23 | for (let i = firstLine; i <= lastLine; i += 1) { 24 | result.push(`${(i + 1).toString().padStart(3)} | ${lines[i]}`); 25 | if (i === line) { 26 | result.push(` | ${"".padStart(start)}${"".padStart(end - start, "^")}`); 27 | } 28 | } 29 | 30 | return result.join("\n"); 31 | } 32 | -------------------------------------------------------------------------------- /src/util/ranges.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { Range, Position, TextDocument } from "vscode-languageserver-types"; 6 | 7 | function before(first: Position, second: Position): boolean { 8 | if (first.line < second.line) { 9 | return true; 10 | } 11 | if (first.line > second.line) { 12 | return false; 13 | } 14 | return first.character < second.character; 15 | } 16 | 17 | export function comparePositions(first: Position, second: Position): number { 18 | if (first.line < second.line) { 19 | return -1; 20 | } 21 | if (first.line > second.line) { 22 | return 1; 23 | } 24 | return first.character - second.character; 25 | } 26 | 27 | export function rangeContains(range: Range, position: Position): boolean { 28 | return before(range.start, position) && before(position, range.end); 29 | } 30 | 31 | export function indexToPosition(text: string, index: number): Position { 32 | const document = TextDocument.create("", "", 1, text); 33 | return document.positionAt(index); 34 | } 35 | -------------------------------------------------------------------------------- /test/actions.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { expectDiagnostics } from "./utils"; 6 | 7 | describe(__filename, () => { 8 | it("reports error on resolving a non-existing action", () => { 9 | expectDiagnostics(` 10 | action "a" { 11 | uses = "./ci" 12 | } 13 | action "b" { 14 | uses = "./ci" 15 | } 16 | workflow "c" { 17 | on = "fork" 18 | resolves = [ 19 | "a", 20 | "b", 21 | "not_found" 22 | ] 23 | } 24 | `).toMatchInlineSnapshot(` 25 | " 26 | ERROR: The action 'not_found' does not exist in the same workflow file. 27 | 11 | \\"a\\", 28 | 12 | \\"b\\", 29 | 13 | \\"not_found\\" 30 | | ^^^^^^^^^^^ 31 | 14 | ] 32 | 15 | } 33 | " 34 | `); 35 | }); 36 | 37 | it("reports error on needing a non-existing action", () => { 38 | expectDiagnostics(` 39 | action "a" { 40 | uses = "./ci" 41 | } 42 | action "b" { 43 | uses = "./ci" 44 | } 45 | action "c" { 46 | uses = "./ci" 47 | needs = [ 48 | "a", 49 | "b", 50 | "not_found" 51 | ] 52 | } 53 | `).toMatchInlineSnapshot(` 54 | " 55 | ERROR: The action 'not_found' does not exist in the same workflow file. 56 | 11 | \\"a\\", 57 | 12 | \\"b\\", 58 | 13 | \\"not_found\\" 59 | | ^^^^^^^^^^^ 60 | 14 | ] 61 | 15 | } 62 | " 63 | `); 64 | }); 65 | 66 | it("reports errors on duplicate resolve actions", () => { 67 | expectDiagnostics(` 68 | action "b" { 69 | uses = "./ci" 70 | } 71 | workflow "c" { 72 | on = "fork" 73 | resolves = [ 74 | "b", 75 | "b" 76 | ] 77 | }`).toMatchInlineSnapshot(` 78 | " 79 | ERROR: This property has duplicate 'b' actions. 80 | 7 | resolves = [ 81 | 8 | \\"b\\", 82 | 9 | \\"b\\" 83 | | ^^^ 84 | 10 | ] 85 | 11 | } 86 | " 87 | `); 88 | }); 89 | 90 | it("reports errors on duplicate needs actions", () => { 91 | expectDiagnostics(` 92 | action "b" { 93 | uses = "./ci" 94 | } 95 | action "c" { 96 | uses = "./ci" 97 | needs = [ 98 | "b", 99 | "b" 100 | ] 101 | }`).toMatchInlineSnapshot(` 102 | " 103 | ERROR: This property has duplicate 'b' actions. 104 | 7 | needs = [ 105 | 8 | \\"b\\", 106 | 9 | \\"b\\" 107 | | ^^^ 108 | 10 | ] 109 | 11 | } 110 | " 111 | `); 112 | }); 113 | 114 | it("reports an error on invalid local 'uses' value", () => { 115 | expectDiagnostics(` 116 | action "a" { 117 | uses = "./ci" 118 | } 119 | action "b" { 120 | uses = "ci" 121 | } 122 | `).toMatchInlineSnapshot(` 123 | " 124 | ERROR: The 'uses' property must be a path, a Docker image, or an owner/repo@ref remote. 125 | 4 | } 126 | 5 | action \\"b\\" { 127 | 6 | uses = \\"ci\\" 128 | | ^^^^ 129 | 7 | } 130 | 8 | 131 | " 132 | `); 133 | }); 134 | 135 | it("reports an error on invalid remote 'uses' value", () => { 136 | expectDiagnostics(` 137 | action "a" { 138 | uses = "owner/repo@ref" 139 | } 140 | action "b" { 141 | uses = "owner/repo/path@ref" 142 | } 143 | action "c" { 144 | uses = "owner/repo" 145 | } 146 | action "d" { 147 | uses = "owner@ref" 148 | } 149 | `).toMatchInlineSnapshot(` 150 | " 151 | ERROR: The 'uses' property must be a path, a Docker image, or an owner/repo@ref remote. 152 | 7 | } 153 | 8 | action \\"c\\" { 154 | 9 | uses = \\"owner/repo\\" 155 | | ^^^^^^^^^^^^ 156 | 10 | } 157 | 11 | action \\"d\\" { 158 | ERROR: The 'uses' property must be a path, a Docker image, or an owner/repo@ref remote. 159 | 10 | } 160 | 11 | action \\"d\\" { 161 | 12 | uses = \\"owner@ref\\" 162 | | ^^^^^^^^^^^ 163 | 13 | } 164 | 14 | 165 | " 166 | `); 167 | }); 168 | 169 | it("reports an error on invalid docker 'uses' value", () => { 170 | expectDiagnostics(` 171 | action "a" { 172 | uses = "docker://image" 173 | } 174 | action "b" { 175 | uses = "docker://?" 176 | } 177 | `).toMatchInlineSnapshot(` 178 | " 179 | ERROR: The 'uses' property must be a path, a Docker image, or an owner/repo@ref remote. 180 | 4 | } 181 | 5 | action \\"b\\" { 182 | 6 | uses = \\"docker://?\\" 183 | | ^^^^^^^^^^^^ 184 | 7 | } 185 | 8 | 186 | " 187 | `); 188 | }); 189 | }); 190 | -------------------------------------------------------------------------------- /test/binding.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { expectDiagnostics } from "./utils"; 6 | 7 | describe(__filename, () => { 8 | it("reports no errors when no version is specified", () => { 9 | expectDiagnostics(``).toMatchInlineSnapshot(`""`); 10 | }); 11 | 12 | it("reports error on multiple versions", () => { 13 | expectDiagnostics(` 14 | version = 0 15 | version = 0 16 | `).toMatchInlineSnapshot(` 17 | " 18 | ERROR: A version is already specified for this document'. You can only specify one. 19 | 1 | 20 | 2 | version = 0 21 | 3 | version = 0 22 | | ^^^^^^^ 23 | 4 | 24 | " 25 | `); 26 | }); 27 | 28 | it("reports error on unsupported versions", () => { 29 | expectDiagnostics(` 30 | version = 1 31 | `).toMatchInlineSnapshot(` 32 | " 33 | ERROR: The version '1' is not valid. Only versions up to '0' are supported. 34 | 1 | 35 | 2 | version = 1 36 | | ^ 37 | 3 | 38 | " 39 | `); 40 | }); 41 | 42 | it("reports error on version after workflow", () => { 43 | expectDiagnostics(` 44 | workflow "x" { 45 | on = "fork" 46 | } 47 | version = 0 48 | `).toMatchInlineSnapshot(` 49 | " 50 | ERROR: Version must be specified before all actions or workflows are defined. 51 | 3 | on = \\"fork\\" 52 | 4 | } 53 | 5 | version = 0 54 | | ^^^^^^^ 55 | 6 | 56 | " 57 | `); 58 | }); 59 | 60 | it("reports error on version after action", () => { 61 | expectDiagnostics(` 62 | action "x" { 63 | uses = "./ci" 64 | } 65 | version = 0 66 | `).toMatchInlineSnapshot(` 67 | " 68 | ERROR: Version must be specified before all actions or workflows are defined. 69 | 3 | uses = \\"./ci\\" 70 | 4 | } 71 | 5 | version = 0 72 | | ^^^^^^^ 73 | 6 | 74 | " 75 | `); 76 | }); 77 | 78 | it("reports error on multiple on blocks", () => { 79 | expectDiagnostics(` 80 | workflow "x" { 81 | on = "fork" 82 | on = "fork" 83 | } 84 | `).toMatchInlineSnapshot(` 85 | " 86 | ERROR: A property 'on' is already defined in this block. 87 | 2 | workflow \\"x\\" { 88 | 3 | on = \\"fork\\" 89 | 4 | on = \\"fork\\" 90 | | ^^ 91 | 5 | } 92 | 6 | 93 | " 94 | `); 95 | }); 96 | 97 | it("reports error on multiple resolves blocks", () => { 98 | expectDiagnostics(` 99 | workflow "x" { 100 | on = "fork" 101 | resolves = [] 102 | resolves = [] 103 | } 104 | `).toMatchInlineSnapshot(` 105 | " 106 | ERROR: A property 'resolves' is already defined in this block. 107 | 3 | on = \\"fork\\" 108 | 4 | resolves = [] 109 | 5 | resolves = [] 110 | | ^^^^^^^^ 111 | 6 | } 112 | 7 | 113 | " 114 | `); 115 | }); 116 | 117 | it("reports error on invalid workflow property", () => { 118 | expectDiagnostics(` 119 | workflow "x" { 120 | on = "fork" 121 | needs = "ci" 122 | } 123 | `).toMatchInlineSnapshot(` 124 | " 125 | ERROR: A property of kind 'needs' cannot be defined for a 'workflow' block. 126 | 2 | workflow \\"x\\" { 127 | 3 | on = \\"fork\\" 128 | 4 | needs = \\"ci\\" 129 | | ^^^^^ 130 | 5 | } 131 | 6 | 132 | " 133 | `); 134 | }); 135 | 136 | it("reports error on string array in on property", () => { 137 | expectDiagnostics(` 138 | workflow "x" { 139 | on = [] 140 | } 141 | `).toMatchInlineSnapshot(` 142 | " 143 | ERROR: Value must be a single string. 144 | 1 | 145 | 2 | workflow \\"x\\" { 146 | 3 | on = [] 147 | | ^^ 148 | 4 | } 149 | 5 | 150 | " 151 | `); 152 | }); 153 | 154 | it("reports error on env variables in on property", () => { 155 | expectDiagnostics(` 156 | workflow "x" { 157 | on = {} 158 | } 159 | `).toMatchInlineSnapshot(` 160 | " 161 | ERROR: Value must be a single string. 162 | 1 | 163 | 2 | workflow \\"x\\" { 164 | 3 | on = {} 165 | | ^^ 166 | 4 | } 167 | 5 | 168 | " 169 | `); 170 | }); 171 | 172 | it("reports error on objects in resolves property", () => { 173 | expectDiagnostics(` 174 | workflow "x" { 175 | on = "fork" 176 | resolves = {} 177 | } 178 | `).toMatchInlineSnapshot(` 179 | " 180 | ERROR: Value must be a single string or an array of strings. 181 | 2 | workflow \\"x\\" { 182 | 3 | on = \\"fork\\" 183 | 4 | resolves = {} 184 | | ^^^^^^^^ 185 | 5 | } 186 | 6 | 187 | " 188 | `); 189 | }); 190 | 191 | it("reports error on strings in env property", () => { 192 | expectDiagnostics(` 193 | action "x" { 194 | uses = "./ci" 195 | env = "test" 196 | } 197 | `).toMatchInlineSnapshot(` 198 | " 199 | ERROR: Value must be an object. 200 | 2 | action \\"x\\" { 201 | 3 | uses = \\"./ci\\" 202 | 4 | env = \\"test\\" 203 | | ^^^ 204 | 5 | } 205 | 6 | 206 | " 207 | `); 208 | }); 209 | 210 | it("reports error on string arrays in env property", () => { 211 | expectDiagnostics(` 212 | action "x" { 213 | uses = "./ci" 214 | env = ["test"] 215 | } 216 | `).toMatchInlineSnapshot(` 217 | " 218 | ERROR: Value must be an object. 219 | 2 | action \\"x\\" { 220 | 3 | uses = \\"./ci\\" 221 | 4 | env = [\\"test\\"] 222 | | ^^^ 223 | 5 | } 224 | 6 | 225 | " 226 | `); 227 | }); 228 | 229 | it("reports errors on reserved environment variables", () => { 230 | expectDiagnostics(` 231 | action "x" { 232 | uses = "./ci" 233 | env = { 234 | GITHUB_ACTION = "1" 235 | GITHUBNOUNDERSCORE = "2" 236 | SOMETHING_ELSE = "3" 237 | } 238 | }`).toMatchInlineSnapshot(` 239 | " 240 | ERROR: Environment variables starting with 'GITHUB_' are reserved. 241 | 3 | uses = \\"./ci\\" 242 | 4 | env = { 243 | 5 | GITHUB_ACTION = \\"1\\" 244 | | ^^^^^^^^^^^^^ 245 | 6 | GITHUBNOUNDERSCORE = \\"2\\" 246 | 7 | SOMETHING_ELSE = \\"3\\" 247 | " 248 | `); 249 | }); 250 | 251 | it("reports errors on unknown events", () => { 252 | expectDiagnostics(` 253 | workflow "x" { 254 | on = "fork" 255 | } 256 | workflow "y" { 257 | on = "unknown" 258 | }`).toMatchInlineSnapshot(` 259 | " 260 | ERROR: The event 'unknown' is not a known event type or a schedule. 261 | 4 | } 262 | 5 | workflow \\"y\\" { 263 | 6 | on = \\"unknown\\" 264 | | ^^^^^^^^^ 265 | 7 | } 266 | " 267 | `); 268 | }); 269 | 270 | it("does not report errors on schedule values", () => { 271 | expectDiagnostics(` 272 | workflow "a" { 273 | on = "schedule(*/15 * * * *)" 274 | } 275 | workflow "b" { 276 | on = "schedule()" 277 | } 278 | workflow "c" { 279 | on = " schedule ( ) " 280 | } 281 | `).toMatchInlineSnapshot(` 282 | " 283 | ERROR: The event 'schedule()' is not a known event type or a schedule. 284 | 4 | } 285 | 5 | workflow \\"b\\" { 286 | 6 | on = \\"schedule()\\" 287 | | ^^^^^^^^^^^^ 288 | 7 | } 289 | 8 | workflow \\"c\\" { 290 | ERROR: The event ' schedule ( ) ' is not a known event type or a schedule. 291 | 7 | } 292 | 8 | workflow \\"c\\" { 293 | 9 | on = \\" schedule ( ) \\" 294 | | ^^^^^^^^^^^^^^^^^^^^ 295 | 10 | } 296 | 11 | 297 | " 298 | `); 299 | }); 300 | }); 301 | -------------------------------------------------------------------------------- /test/blocks.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { expectDiagnostics } from "./utils"; 6 | 7 | describe(__filename, () => { 8 | it("reports errors on two actions with the same name", () => { 9 | expectDiagnostics(` 10 | action "a" { 11 | uses = "./ci" 12 | } 13 | action "b" { 14 | uses = "./ci" 15 | } 16 | action "a" { 17 | uses = "./ci" 18 | } 19 | `).toMatchInlineSnapshot(` 20 | " 21 | ERROR: This file already defines another workflow or action with the name 'a'. 22 | 6 | uses = \\"./ci\\" 23 | 7 | } 24 | 8 | action \\"a\\" { 25 | | ^^^ 26 | 9 | uses = \\"./ci\\" 27 | 10 | } 28 | " 29 | `); 30 | }); 31 | 32 | it("reports errors on two workflows with the same name", () => { 33 | expectDiagnostics(` 34 | workflow "a" { 35 | on = "fork" 36 | } 37 | workflow "b" { 38 | on = "fork" 39 | } 40 | workflow "a" { 41 | on = "fork" 42 | } 43 | `).toMatchInlineSnapshot(` 44 | " 45 | ERROR: This file already defines another workflow or action with the name 'a'. 46 | 6 | on = \\"fork\\" 47 | 7 | } 48 | 8 | workflow \\"a\\" { 49 | | ^^^ 50 | 9 | on = \\"fork\\" 51 | 10 | } 52 | " 53 | `); 54 | }); 55 | 56 | it("reports errors on a workflow and an action with the same name", () => { 57 | expectDiagnostics(` 58 | action "a" { 59 | uses = "./ci" 60 | } 61 | workflow "b" { 62 | on = "fork" 63 | } 64 | workflow "a" { 65 | on = "fork" 66 | } 67 | `).toMatchInlineSnapshot(` 68 | " 69 | ERROR: This file already defines another workflow or action with the name 'a'. 70 | 6 | on = \\"fork\\" 71 | 7 | } 72 | 8 | workflow \\"a\\" { 73 | | ^^^ 74 | 9 | on = \\"fork\\" 75 | 10 | } 76 | " 77 | `); 78 | }); 79 | 80 | it("reports errors on too many actions", () => { 81 | expectDiagnostics(` 82 | action "action001" { uses = "./ci" } 83 | action "action002" { uses = "./ci" } 84 | action "action003" { uses = "./ci" } 85 | action "action004" { uses = "./ci" } 86 | action "action005" { uses = "./ci" } 87 | action "action006" { uses = "./ci" } 88 | action "action007" { uses = "./ci" } 89 | action "action008" { uses = "./ci" } 90 | action "action009" { uses = "./ci" } 91 | action "action010" { uses = "./ci" } 92 | action "action011" { uses = "./ci" } 93 | action "action012" { uses = "./ci" } 94 | action "action013" { uses = "./ci" } 95 | action "action014" { uses = "./ci" } 96 | action "action015" { uses = "./ci" } 97 | action "action016" { uses = "./ci" } 98 | action "action017" { uses = "./ci" } 99 | action "action018" { uses = "./ci" } 100 | action "action019" { uses = "./ci" } 101 | action "action020" { uses = "./ci" } 102 | action "action021" { uses = "./ci" } 103 | action "action022" { uses = "./ci" } 104 | action "action023" { uses = "./ci" } 105 | action "action024" { uses = "./ci" } 106 | action "action025" { uses = "./ci" } 107 | action "action026" { uses = "./ci" } 108 | action "action027" { uses = "./ci" } 109 | action "action028" { uses = "./ci" } 110 | action "action029" { uses = "./ci" } 111 | action "action030" { uses = "./ci" } 112 | action "action031" { uses = "./ci" } 113 | action "action032" { uses = "./ci" } 114 | action "action033" { uses = "./ci" } 115 | action "action034" { uses = "./ci" } 116 | action "action035" { uses = "./ci" } 117 | action "action036" { uses = "./ci" } 118 | action "action037" { uses = "./ci" } 119 | action "action038" { uses = "./ci" } 120 | action "action039" { uses = "./ci" } 121 | action "action040" { uses = "./ci" } 122 | action "action041" { uses = "./ci" } 123 | action "action042" { uses = "./ci" } 124 | action "action043" { uses = "./ci" } 125 | action "action044" { uses = "./ci" } 126 | action "action045" { uses = "./ci" } 127 | action "action046" { uses = "./ci" } 128 | action "action047" { uses = "./ci" } 129 | action "action048" { uses = "./ci" } 130 | action "action049" { uses = "./ci" } 131 | action "action050" { uses = "./ci" } 132 | action "action051" { uses = "./ci" } 133 | action "action052" { uses = "./ci" } 134 | action "action053" { uses = "./ci" } 135 | action "action054" { uses = "./ci" } 136 | action "action055" { uses = "./ci" } 137 | action "action056" { uses = "./ci" } 138 | action "action057" { uses = "./ci" } 139 | action "action058" { uses = "./ci" } 140 | action "action059" { uses = "./ci" } 141 | action "action060" { uses = "./ci" } 142 | action "action061" { uses = "./ci" } 143 | action "action062" { uses = "./ci" } 144 | action "action063" { uses = "./ci" } 145 | action "action064" { uses = "./ci" } 146 | action "action065" { uses = "./ci" } 147 | action "action066" { uses = "./ci" } 148 | action "action067" { uses = "./ci" } 149 | action "action068" { uses = "./ci" } 150 | action "action069" { uses = "./ci" } 151 | action "action070" { uses = "./ci" } 152 | action "action071" { uses = "./ci" } 153 | action "action072" { uses = "./ci" } 154 | action "action073" { uses = "./ci" } 155 | action "action074" { uses = "./ci" } 156 | action "action075" { uses = "./ci" } 157 | action "action076" { uses = "./ci" } 158 | action "action077" { uses = "./ci" } 159 | action "action078" { uses = "./ci" } 160 | action "action079" { uses = "./ci" } 161 | action "action080" { uses = "./ci" } 162 | action "action081" { uses = "./ci" } 163 | action "action082" { uses = "./ci" } 164 | action "action083" { uses = "./ci" } 165 | action "action084" { uses = "./ci" } 166 | action "action085" { uses = "./ci" } 167 | action "action086" { uses = "./ci" } 168 | action "action087" { uses = "./ci" } 169 | action "action088" { uses = "./ci" } 170 | action "action089" { uses = "./ci" } 171 | action "action090" { uses = "./ci" } 172 | action "action091" { uses = "./ci" } 173 | action "action092" { uses = "./ci" } 174 | action "action093" { uses = "./ci" } 175 | action "action094" { uses = "./ci" } 176 | action "action095" { uses = "./ci" } 177 | action "action096" { uses = "./ci" } 178 | action "action097" { uses = "./ci" } 179 | action "action098" { uses = "./ci" } 180 | action "action099" { uses = "./ci" } 181 | action "action100" { uses = "./ci" } 182 | action "action101" { uses = "./ci" } 183 | `).toMatchInlineSnapshot(` 184 | " 185 | ERROR: Too many actions defined. The maximum currently supported is '100'. 186 | 100 | action \\"action099\\" { uses = \\"./ci\\" } 187 | 101 | action \\"action100\\" { uses = \\"./ci\\" } 188 | 102 | action \\"action101\\" { uses = \\"./ci\\" } 189 | | ^^^^^^^^^^^ 190 | 103 | 191 | " 192 | `); 193 | }); 194 | }); 195 | -------------------------------------------------------------------------------- /test/circular-dependencies.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { expectDiagnostics } from "./utils"; 6 | 7 | describe(__filename, () => { 8 | it("reports error on cycling dependencies in actions", () => { 9 | expectDiagnostics(` 10 | action "a" { uses = "./ci" } 11 | action "b" { uses = "./ci" needs = ["a"] } 12 | action "c" { uses = "./ci" needs = ["a", "b", "e"] } 13 | action "d" { uses = "./ci" needs = ["c"] } 14 | action "e" { uses = "./ci" needs = ["c"] } 15 | `).toMatchInlineSnapshot(` 16 | " 17 | ERROR: The action 'e' has a circular dependency on itself. 18 | 2 | action \\"a\\" { uses = \\"./ci\\" } 19 | 3 | action \\"b\\" { uses = \\"./ci\\" needs = [\\"a\\"] } 20 | 4 | action \\"c\\" { uses = \\"./ci\\" needs = [\\"a\\", \\"b\\", \\"e\\"] } 21 | | ^^^ 22 | 5 | action \\"d\\" { uses = \\"./ci\\" needs = [\\"c\\"] } 23 | 6 | action \\"e\\" { uses = \\"./ci\\" needs = [\\"c\\"] } 24 | " 25 | `); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /test/completion.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { getMarkerPosition, TEST_MARKER } from "./utils"; 6 | import { Compilation } from "../src/util/compilation"; 7 | import { CompletionService } from "../src/services/completion"; 8 | 9 | describe(__filename, () => { 10 | it("completes nothing outside of blocks", () => { 11 | expectCompletionItems(` 12 | version = 0 13 | ${TEST_MARKER} 14 | `).toMatchInlineSnapshot(`Array []`); 15 | }); 16 | 17 | it("completes properties inside an action", () => { 18 | expectCompletionItems(` 19 | action "x" { 20 | ${TEST_MARKER} 21 | } 22 | `).toMatchInlineSnapshot(` 23 | Array [ 24 | "uses", 25 | "needs", 26 | "runs", 27 | "args", 28 | "env", 29 | "secrets", 30 | ] 31 | `); 32 | }); 33 | 34 | it("completes properties inside a workflow", () => { 35 | expectCompletionItems(` 36 | workflow "x" { 37 | ${TEST_MARKER} 38 | } 39 | `).toMatchInlineSnapshot(` 40 | Array [ 41 | "on", 42 | "resolves", 43 | ] 44 | `); 45 | }); 46 | 47 | it("completes nothing inside a string property that doesn't accept actions", () => { 48 | expectCompletionItems(` 49 | action "x" { 50 | uses = "${TEST_MARKER}" 51 | } 52 | `).toMatchInlineSnapshot(`Array []`); 53 | }); 54 | 55 | it("completes nothing inside an array property that doesn't accept actions", () => { 56 | expectCompletionItems(` 57 | action "x" { 58 | secrets = [ "${TEST_MARKER}" ] 59 | } 60 | `).toMatchInlineSnapshot(`Array []`); 61 | }); 62 | 63 | it("completes actions inside a string value", () => { 64 | expectCompletionItems(` 65 | action "to complete" { 66 | } 67 | workflow "x" { 68 | resolves = "${TEST_MARKER}" 69 | } 70 | `).toMatchInlineSnapshot(` 71 | Array [ 72 | "to complete", 73 | ] 74 | `); 75 | }); 76 | 77 | it("completes actions inside an array value", () => { 78 | expectCompletionItems(` 79 | action "to complete" { 80 | } 81 | workflow "x" { 82 | resolves = [ "${TEST_MARKER}" ] 83 | } 84 | `).toMatchInlineSnapshot(` 85 | Array [ 86 | "to complete", 87 | ] 88 | `); 89 | }); 90 | 91 | it("completes nothing inside an object value", () => { 92 | expectCompletionItems(` 93 | action "to complete" { 94 | } 95 | action "x" { 96 | env = { X = "${TEST_MARKER}" } 97 | } 98 | `).toMatchInlineSnapshot(`Array []`); 99 | }); 100 | 101 | it("completes a list of events inside a workflow", () => { 102 | expectCompletionItems(` 103 | workflow "x" { 104 | on = "${TEST_MARKER}" 105 | } 106 | `).toMatchInlineSnapshot(` 107 | Array [ 108 | "check_run", 109 | "check_suite", 110 | "commit_comment", 111 | "create", 112 | "delete", 113 | "deployment", 114 | "deployment_status", 115 | "fork", 116 | "github_app_authorization", 117 | "gollum", 118 | "installation", 119 | "installation_repositories", 120 | "issue_comment", 121 | "issues", 122 | "label", 123 | "marketplace_purchase", 124 | "member", 125 | "membership", 126 | "milestone", 127 | "organization", 128 | "org_block", 129 | "page_build", 130 | "project_card", 131 | "project_column", 132 | "project", 133 | "public", 134 | "pull_request", 135 | "pull_request_review", 136 | "pull_request_review_comment", 137 | "push", 138 | "release", 139 | "repository", 140 | "repository_import", 141 | "repository_vulnerability_alert", 142 | "security_advisory", 143 | "status", 144 | "team", 145 | "team_add", 146 | "watch", 147 | "ping", 148 | ] 149 | `); 150 | }); 151 | }); 152 | 153 | function expectCompletionItems(text: string): jest.Matchers { 154 | const { newText, position } = getMarkerPosition(text); 155 | const compilation = new Compilation(newText); 156 | 157 | const items = CompletionService.provideCompletion(compilation, position); 158 | return expect(items.map(item => item.label)); 159 | } 160 | -------------------------------------------------------------------------------- /test/external-tests.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import * as path from "path"; 6 | import * as fs from "fs"; 7 | import { EOL_REGEX } from "../src/util/highlight-range"; 8 | import * as joi from "joi"; 9 | import { Compilation } from "../src/util/compilation"; 10 | 11 | interface AssertionError { 12 | readonly line?: number; 13 | readonly severity: "ERROR" | "FATAL" | "WARN"; 14 | readonly message: string; 15 | } 16 | 17 | const assertionErrorSchema = joi.object().keys({ 18 | line: joi.number(), 19 | severity: joi 20 | .string() 21 | .valid("ERROR", "FATAL", "WARN") 22 | .required(), 23 | message: joi.string().required(), 24 | }); 25 | 26 | interface AssertionObject { 27 | readonly result: "success" | "failure"; 28 | readonly numActions: number; 29 | readonly numWorkflows: number; 30 | readonly errors?: ReadonlyArray; 31 | } 32 | 33 | const assertionObjectSchema = joi.object().keys({ 34 | result: joi 35 | .string() 36 | .valid("success", "failure") 37 | .required(), 38 | numActions: joi.number().required(), 39 | numWorkflows: joi.number().required(), 40 | errors: joi.array().items(assertionErrorSchema), 41 | }); 42 | 43 | describe(__filename, () => { 44 | const testsDirectory = path.resolve(__dirname, "..", "workflow-parser", "tests"); 45 | const allTests = [ 46 | ...collectTests(path.join(testsDirectory, "valid")), 47 | ...collectTests(path.join(testsDirectory, "invalid")), 48 | ]; 49 | 50 | allTests.forEach(testFile => { 51 | it(`matches results from external test ${testFile}`, () => { 52 | const text = fs.readFileSync(testFile, "utf8"); 53 | const assertion = extractAssertion(text); 54 | 55 | const compilation = new Compilation(text); 56 | if (compilation.diagnostics.length === 0) { 57 | expect(assertion.result).toBe("success"); 58 | } else { 59 | expect(assertion.result).toBe("failure"); 60 | } 61 | 62 | // TODO: complete the rest of the assertions 63 | }); 64 | }); 65 | }); 66 | 67 | function collectTests(directory: string): ReadonlyArray { 68 | const tests = fs 69 | .readdirSync(directory) 70 | .filter( 71 | file => 72 | file.endsWith(".workflow") && 73 | // TODO: remove after this is merged: https://github.com/actions/workflow-parser/pull/40 74 | !file.includes("actions-and-attributes.workflow") && 75 | // TODO: remove after this is merged: https://github.com/actions/workflow-parser/pull/39 76 | !file.includes("hcl-subset-2.workflow"), 77 | ) 78 | .map(file => path.join(directory, file)); 79 | 80 | expect(tests.length).toBeGreaterThan(0); 81 | return tests; 82 | } 83 | 84 | function extractAssertion(contents: string): AssertionObject { 85 | const assertionStart = "# ASSERT {"; 86 | const assertionStartIndex = contents.indexOf(assertionStart); 87 | expect(assertionStartIndex).toBeGreaterThanOrEqual(0); 88 | 89 | const rawLines = contents.substring(assertionStartIndex).split(EOL_REGEX); 90 | expect(rawLines[0]).toBe(assertionStart); 91 | expect(rawLines[rawLines.length - 2]).toBe("# }"); 92 | expect(rawLines[rawLines.length - 1]).toBe(""); 93 | 94 | const jsonObject = JSON.parse( 95 | [ 96 | "{", 97 | ...rawLines.slice(1, rawLines.length - 2).map(line => { 98 | const commentPrefix = "# "; 99 | expect(line.startsWith(commentPrefix)).toBeTruthy(); 100 | return line.substring(commentPrefix.length); 101 | }), 102 | "}", 103 | ].join(""), 104 | ); 105 | 106 | const result = joi.validate(jsonObject, assertionObjectSchema, { 107 | noDefaults: true, 108 | }); 109 | 110 | expect(result.error).toBeNull(); 111 | return result.value; 112 | } 113 | -------------------------------------------------------------------------------- /test/formatting.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { Compilation } from "../src/util/compilation"; 6 | import { FormattingService } from "../src/services/formatting"; 7 | 8 | describe(__filename, () => { 9 | it("formats a one line empty action", () => { 10 | expectFormatting(` 11 | action"x"{} 12 | `).toMatchInlineSnapshot(` 13 | "action \\"x\\" { 14 | } 15 | " 16 | `); 17 | }); 18 | 19 | it("formats a one line action with properties", () => { 20 | expectFormatting(` 21 | action "x" { uses="./ci" } 22 | `).toMatchInlineSnapshot(` 23 | "action \\"x\\" { 24 | uses = \\"./ci\\" 25 | } 26 | " 27 | `); 28 | }); 29 | 30 | it("formats an action with embedded comments", () => { 31 | expectFormatting(` 32 | # on start of line 33 | # should be aligned to start 34 | action "x" { 35 | # should be indented 36 | uses="./ci" // should be at end 37 | } 38 | `).toMatchInlineSnapshot(` 39 | "# on start of line 40 | # should be aligned to start 41 | action \\"x\\" { 42 | # should be indented 43 | uses = \\"./ci\\" // should be at end 44 | } 45 | " 46 | `); 47 | }); 48 | 49 | it("indents properties according to the longest key", () => { 50 | expectFormatting(` 51 | action "Go Modules" { 52 | uses = "actions-contrib/go@master" 53 | secrets = [] 54 | env = { 55 | X = "1", 56 | YYYYYY = "2", 57 | ZZZ = "3" 58 | } 59 | } 60 | `).toMatchInlineSnapshot(` 61 | "action \\"Go Modules\\" { 62 | uses = \\"actions-contrib/go@master\\" 63 | 64 | secrets = [ 65 | ] 66 | 67 | env = { 68 | X = \\"1\\", 69 | YYYYYY = \\"2\\", 70 | ZZZ = \\"3\\" 71 | } 72 | } 73 | " 74 | `); 75 | }); 76 | }); 77 | 78 | function expectFormatting(text: string): jest.Matchers { 79 | const compilation = new Compilation(text); 80 | const result = FormattingService.format(compilation, " "); 81 | 82 | const secondCompilation = new Compilation(result); 83 | const secondResult = FormattingService.format(secondCompilation, " "); 84 | expect(result).toBe(secondResult); 85 | 86 | return expect(result); 87 | } 88 | -------------------------------------------------------------------------------- /test/parsing.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { expectDiagnostics } from "./utils"; 6 | 7 | describe(__filename, () => { 8 | it("reports errors on invalid block starts", () => { 9 | expectDiagnostics(` 10 | x 11 | version = 0 12 | `).toMatchInlineSnapshot(` 13 | " 14 | ERROR: A token of kind 'identifier' was not expected here. 15 | 1 | 16 | 2 | x 17 | | ^ 18 | 3 | version = 0 19 | 4 | 20 | " 21 | `); 22 | }); 23 | 24 | it("reports errors on incomplete version block", () => { 25 | expectDiagnostics(` 26 | version 27 | `).toMatchInlineSnapshot(` 28 | " 29 | ERROR: A token of kind '=' was expected after this. 30 | 1 | 31 | 2 | version 32 | | ^^^^^^^ 33 | 3 | 34 | " 35 | `); 36 | }); 37 | 38 | it("recovers on incomplete version blocks", () => { 39 | expectDiagnostics(` 40 | version # no equal 41 | action "x" { 42 | uses = "./ci" 43 | } 44 | action "y" { 45 | uses = "./ci" 46 | } 47 | `).toMatchInlineSnapshot(` 48 | " 49 | ERROR: A token of kind '=' was expected here. 50 | 1 | 51 | 2 | version # no equal 52 | 3 | action \\"x\\" { 53 | | ^^^^^^ 54 | 4 | uses = \\"./ci\\" 55 | 5 | } 56 | " 57 | `); 58 | }); 59 | 60 | it("reports errors on missing values", () => { 61 | expectDiagnostics(` 62 | workflow "x" { 63 | on = "fork" 64 | } 65 | action "y" { 66 | uses 67 | } 68 | workflow "z" { 69 | on = 70 | } 71 | `).toMatchInlineSnapshot(` 72 | " 73 | ERROR: A token of kind '=' was expected here. 74 | 5 | action \\"y\\" { 75 | 6 | uses 76 | 7 | } 77 | | ^ 78 | 8 | workflow \\"z\\" { 79 | 9 | on = 80 | ERROR: A token of kind 'string' or '{' or '[' was expected here. 81 | 8 | workflow \\"z\\" { 82 | 9 | on = 83 | 10 | } 84 | | ^ 85 | 11 | 86 | " 87 | `); 88 | }); 89 | 90 | it("reports errors on extra commas in a string array", () => { 91 | expectDiagnostics(` 92 | action "a" { 93 | uses = "./ci" 94 | } 95 | action "b" { 96 | uses = "./ci" 97 | } 98 | workflow "x" { 99 | on = "fork" 100 | resolves = [ 101 | , "a", , "b", 102 | ] 103 | } 104 | `).toMatchInlineSnapshot(` 105 | " 106 | ERROR: A token of kind ',' was not expected here. 107 | 9 | on = \\"fork\\" 108 | 10 | resolves = [ 109 | 11 | , \\"a\\", , \\"b\\", 110 | | ^ 111 | 12 | ] 112 | 13 | } 113 | ERROR: A token of kind ',' was not expected here. 114 | 9 | on = \\"fork\\" 115 | 10 | resolves = [ 116 | 11 | , \\"a\\", , \\"b\\", 117 | | ^ 118 | 12 | ] 119 | 13 | } 120 | " 121 | `); 122 | }); 123 | 124 | it("does not report errors on missing commas", () => { 125 | expectDiagnostics(` 126 | action "a" { 127 | uses = "./ci" 128 | env = { 129 | A = "1", 130 | B = "2" 131 | C = "3" 132 | D = "4", 133 | } 134 | } 135 | action "b" { 136 | uses = "./ci" 137 | } 138 | action "c" { 139 | uses = "./ci" 140 | } 141 | workflow "x" { 142 | on = "fork" 143 | resolves = [ 144 | "a", 145 | "b" 146 | "c", 147 | ] 148 | } 149 | `).toMatchInlineSnapshot(`""`); 150 | }); 151 | }); 152 | -------------------------------------------------------------------------------- /test/scanning.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { expectDiagnostics } from "./utils"; 6 | 7 | describe(__filename, () => { 8 | it("reports errors on unrecognized characters", () => { 9 | expectDiagnostics(` 10 | workflow "x" { 11 | on = "fork" 12 | % 13 | } 14 | `).toMatchInlineSnapshot(` 15 | " 16 | ERROR: The character '%' is unrecognizable. 17 | 2 | workflow \\"x\\" { 18 | 3 | on = \\"fork\\" 19 | 4 | % 20 | | ^ 21 | 5 | } 22 | 6 | 23 | " 24 | `); 25 | }); 26 | 27 | it("reports errors on a single forward slash", () => { 28 | expectDiagnostics(` 29 | / 30 | `).toMatchInlineSnapshot(` 31 | " 32 | ERROR: The character '/' is unrecognizable. 33 | 1 | 34 | 2 | / 35 | | ^ 36 | 3 | 37 | " 38 | `); 39 | }); 40 | 41 | it("reports errors on unterminated strings (middle of file)", () => { 42 | expectDiagnostics(` 43 | workflow "something \\" else { 44 | { 45 | on = "fork" 46 | } 47 | `).toMatchInlineSnapshot(` 48 | " 49 | ERROR: This string literal must end with double quotes. 50 | 1 | 51 | 2 | workflow \\"something \\\\\\" else { 52 | | ^^^^^^^^^^^^^^^^^^^^ 53 | 3 | { 54 | 4 | on = \\"fork\\" 55 | " 56 | `); 57 | }); 58 | 59 | it("reports errors on unterminated strings (end of file)", () => { 60 | expectDiagnostics(` 61 | workflow "something 62 | { 63 | on = "fork" 64 | } 65 | `).toMatchInlineSnapshot(` 66 | " 67 | ERROR: This string literal must end with double quotes. 68 | 1 | 69 | 2 | workflow \\"something 70 | | ^^^^^^^^^^ 71 | 3 | { 72 | 4 | on = \\"fork\\" 73 | " 74 | `); 75 | }); 76 | 77 | it("reports errors on unrecognized escape sequences", () => { 78 | expectDiagnostics(` 79 | workflow "test\\m" { 80 | on = "fork" 81 | } 82 | `).toMatchInlineSnapshot(` 83 | " 84 | ERROR: The character 'm' is not a supported escape sequence. 85 | 1 | 86 | 2 | workflow \\"test\\\\m\\" { 87 | | ^ 88 | 3 | on = \\"fork\\" 89 | 4 | } 90 | " 91 | `); 92 | }); 93 | 94 | it("reports errors on unsupported characters in a string", () => { 95 | expectDiagnostics(` 96 | workflow "test \u0000 \u0002" { 97 | on = "fork" 98 | } 99 | `).toMatchInlineSnapshot(` 100 | " 101 | ERROR: The character '' is unrecognizable. 102 | 1 | 103 | 2 | workflow \\"test \\" { 104 | | ^ 105 | 3 | on = \\"fork\\" 106 | 4 | } 107 | ERROR: The character '' is unrecognizable. 108 | 1 | 109 | 2 | workflow \\"test \\" { 110 | | ^ 111 | 3 | on = \\"fork\\" 112 | 4 | } 113 | " 114 | `); 115 | }); 116 | }); 117 | -------------------------------------------------------------------------------- /test/secrets.spec.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { expectDiagnostics } from "./utils"; 6 | 7 | describe(__filename, () => { 8 | it("reports errors on duplicate secrets", () => { 9 | expectDiagnostics(` 10 | action "a" { 11 | uses = "./ci" 12 | secrets = [ 13 | "S1", 14 | "S2", 15 | "S1", ## should be reported 16 | "S3" 17 | ] 18 | } 19 | `).toMatchInlineSnapshot(` 20 | " 21 | ERROR: This property has duplicate 'S1' secrets. 22 | 5 | \\"S1\\", 23 | 6 | \\"S2\\", 24 | 7 | \\"S1\\", ## should be reported 25 | | ^^^^ 26 | 8 | \\"S3\\" 27 | 9 | ] 28 | " 29 | `); 30 | }); 31 | 32 | it("reports errors on too many secrets", () => { 33 | expectDiagnostics(` 34 | action "a" { 35 | uses = "./ci" 36 | secrets = [ 37 | "SECRET1", "SECRET2", "SECRET3", "SECRET4", "SECRET5", "SECRET6", "SECRET7", "SECRET8", "SECRET9", "SECRET10", 38 | "SECRET11", "SECRET12", "SECRET13", "SECRET14", "SECRET15", "SECRET16", "SECRET17", "SECRET18", "SECRET19", "SECRET20", 39 | "SECRET21", "SECRET22", "SECRET23", "SECRET24", "SECRET25", "SECRET26", "SECRET27", "SECRET28", "SECRET29", "SECRET30", 40 | "SECRET31", "SECRET32", "SECRET33", "SECRET34", "SECRET35", "SECRET36", "SECRET37", "SECRET38", "SECRET39", "SECRET40", 41 | "SECRET41", "SECRET42", "SECRET43", "SECRET44", "SECRET45", "SECRET46", "SECRET47", "SECRET48", "SECRET49", "SECRET50", 42 | "SECRET51", "SECRET52", "SECRET53", "SECRET54", "SECRET55", "SECRET56", "SECRET57", "SECRET58", "SECRET59", "SECRET60", 43 | "SECRET61", "SECRET62", "SECRET63", "SECRET64", "SECRET65", "SECRET66", "SECRET67", "SECRET68", "SECRET69", "SECRET70", 44 | "SECRET71", "SECRET72", "SECRET73", "SECRET74", "SECRET75", "SECRET76", "SECRET77", "SECRET78", "SECRET79", "SECRET80", 45 | "SECRET81", "SECRET82", "SECRET83", "SECRET84", "SECRET85", "SECRET86", "SECRET87", "SECRET88", "SECRET89", "SECRET90", 46 | "SECRET91", "SECRET92", "SECRET93", "SECRET94", "SECRET95", "SECRET96", "SECRET97", "SECRET98", "SECRET99", "SECRET100" 47 | ] 48 | } 49 | 50 | action "b" { 51 | uses = "./ci" 52 | secrets = [ 53 | "SECRET50" # Not a duplicate 54 | ] 55 | } 56 | 57 | action "c" { 58 | uses = "./ci" 59 | secrets = [ 60 | "EXTRA_1" # should be reported 61 | ] 62 | } 63 | 64 | action "d" { 65 | uses = "./ci" 66 | secrets = [ 67 | "EXTRA_2" # Should not be reported 68 | ] 69 | } 70 | `).toMatchInlineSnapshot(` 71 | " 72 | ERROR: Too many secrets defined. The maximum currently supported is '100'. 73 | 26 | uses = \\"./ci\\" 74 | 27 | secrets = [ 75 | 28 | \\"EXTRA_1\\" # should be reported 76 | | ^^^^^^^^^ 77 | 29 | ] 78 | 30 | } 79 | " 80 | `); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /test/utils.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | import { Compilation } from "../src/util/compilation"; 6 | import { highlight } from "../src/util/highlight-range"; 7 | import { Position } from "vscode-languageserver-types"; 8 | import { indexToPosition } from "../src/util/ranges"; 9 | import { severityToString } from "../src/util/diagnostics"; 10 | import { LANGUAGE_NAME } from "../src/util/constants"; 11 | 12 | export const TEST_MARKER = "$$"; 13 | 14 | export function expectDiagnostics(text: string): jest.Matchers { 15 | const compilation = new Compilation(text); 16 | 17 | if (!compilation.diagnostics.length) { 18 | return expect(""); 19 | } 20 | 21 | const actual = Array(...compilation.diagnostics); 22 | actual.sort((a, b) => { 23 | const from = a.range.start; 24 | const to = b.range.start; 25 | if (from.line === to.line) { 26 | return from.character - to.character; 27 | } 28 | return from.line - to.line; 29 | }); 30 | 31 | return expect( 32 | [ 33 | "", 34 | ...actual.map(diagnostic => { 35 | expect(diagnostic.source).toBe(LANGUAGE_NAME); 36 | return `${severityToString(diagnostic.severity)}: ${diagnostic.message}\n${highlight(diagnostic.range, text)}`; 37 | }), 38 | "", 39 | ].join("\n"), 40 | ); 41 | } 42 | 43 | export function getMarkerPosition( 44 | text: string, 45 | ): { 46 | newText: string; 47 | position: Position; 48 | } { 49 | const index = text.indexOf(TEST_MARKER); 50 | if (index < 0) { 51 | throw new Error(`Cannot find marker in text`); 52 | } 53 | 54 | const newText = text.replace(TEST_MARKER, ""); 55 | if (newText.indexOf(TEST_MARKER) >= 0) { 56 | throw new Error(`More than one marker exists in text`); 57 | } 58 | 59 | return { 60 | newText, 61 | position: indexToPosition(newText, index), 62 | }; 63 | } 64 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | // Compilation options 4 | "target": "es5", 5 | "module": "commonjs", 6 | "moduleResolution": "node", 7 | "typeRoots": ["./typings/"], 8 | "types": ["jest"], 9 | "lib": [], 10 | 11 | // Features 12 | "downlevelIteration": true, 13 | 14 | // Output files 15 | "declaration": true, 16 | "sourceMap": true, 17 | "inlineSources": true, 18 | 19 | // Diagnostics 20 | "strict": true, 21 | "noUnusedLocals": true, 22 | "noUnusedParameters": true, 23 | "noImplicitReturns": true, 24 | "noFallthroughCasesInSwitch": true 25 | }, 26 | "exclude": ["./out/"] 27 | } 28 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "linterOptions": { 4 | "exclude": ["./node_modules/**"] 5 | }, 6 | "extends": ["tslint-config-airbnb", "tslint-config-prettier"], 7 | "rules": { 8 | "file-header": [ 9 | true, 10 | "Copyright 2019 Omar Tawfik\\. Please see LICENSE file at the root of this repository\\.", 11 | "Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository." 12 | ], 13 | "typedef": [true, "call-signature", "parameter", "property-declaration"] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /typings/@octokit/webhooks-definitions.d.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | declare module "@octokit/webhooks-definitions" { 6 | const webhooks: ReadonlyArray<{ 7 | readonly name: string; 8 | }>; 9 | 10 | export = webhooks; 11 | } 12 | -------------------------------------------------------------------------------- /typings/jest-diff.d.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Omar Tawfik. Please see LICENSE file at the root of this repository. 3 | */ 4 | 5 | declare module "jest-diff" {} 6 | --------------------------------------------------------------------------------