Skip to content

Commit d0f0e43

Browse files
committed
Migrate to TypeScript
1 parent 0dc4ef5 commit d0f0e43

File tree

7 files changed

+501
-948
lines changed

7 files changed

+501
-948
lines changed

.github/workflows/compile.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ jobs:
1515
- name: Compile with ncc
1616
run: |
1717
npm install
18-
npx ncc build index.js -o dist
18+
npx ncc build index.ts -o dist
1919
- name: Push
2020
env:
2121
DIR: dist

.github/workflows/test.yml

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ jobs:
2121
with:
2222
node-version: 20
2323
- name: Compile
24-
run: npm install && npx ncc build index.js -o dist
24+
run: |
25+
npm install
26+
npx tsc
2527
- uses: ./
2628
with:
2729
skip-commit: true
@@ -45,7 +47,9 @@ jobs:
4547
with:
4648
node-version: 20
4749
- name: Compile
48-
run: npm install && npx ncc build index.js -o dist
50+
run: |
51+
npm install
52+
npx tsc
4953
- uses: ./
5054
continue-on-error: ${{ matrix.os == 'macos-latest' }}
5155
with:

dist/index.js

Lines changed: 402 additions & 891 deletions
Large diffs are not rendered by default.

index.js renamed to index.ts

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
const core = require('@actions/core');
2-
const exec = require('@actions/exec');
3-
const glob = require('@actions/glob');
4-
const github = require('@actions/github');
5-
const path = require('path');
1+
import * as core from '@actions/core';
2+
import * as exec from '@actions/exec';
3+
import * as glob from '@actions/glob';
4+
import * as github from '@actions/github';
5+
import * as path from 'path';
66

7-
function getInput(inputAlternativeNames, { required = false } = {}) {
8-
if (!(inputAlternativeNames && inputAlternativeNames.length)) throw new Error("inputAlternativeNames is empty");
7+
function getInput(inputAlternativeNames: string[], { required = false } = {}) {
8+
if (inputAlternativeNames.length === 0) throw new Error("inputAlternativeNames is empty");
99
let val = "";
1010
for (const [i, inputName] of inputAlternativeNames.entries()) {
1111
val = core.getInput(inputName, {
@@ -21,40 +21,38 @@ const owner = 'google';
2121
const repo = 'google-java-format';
2222
const githubToken = getInput(['githubToken', 'github-token'], { required: false });
2323
const commitMessage = getInput(['commitMessage', 'commit-message'], { required: false });
24-
const executable = path.join(process.env.HOME || process.env.USERPROFILE, 'google-java-format.jar');
24+
const executable = path.join((process.env.HOME || process.env.USERPROFILE)!, 'google-java-format.jar');
2525
const apiReleases = `https://api.github.com/repos/${owner}/${repo}/releases`;
2626

27-
class ExecResult {
28-
constructor(exitCode, stdOut, stdErr) {
29-
this.exitCode = exitCode;
30-
this.stdOut = stdOut;
31-
this.stdErr = stdErr;
32-
}
27+
interface ExecResult {
28+
exitCode: number;
29+
stdOut: string;
30+
stdErr: string;
3331
}
3432

35-
async function executeGJF(args = []) {
36-
const arguments = [];
33+
async function executeGJF(args: string[] = []) {
34+
const allArgs = new Array<string>();
3735
const javaVersion = await getJavaVersion();
3836
// see https://github.com/google/google-java-format#jdk-16
3937
if (javaVersion !== undefined && javaVersion >= 11)
40-
arguments.push(...['api', 'file', 'parser', 'tree', 'util']
38+
allArgs.push(...['api', 'file', 'parser', 'tree', 'util']
4139
.flatMap(l => ['--add-exports', `jdk.compiler/com.sun.tools.javac.${l}=ALL-UNNAMED`]));
42-
arguments.push('-jar', executable);
43-
arguments.push(...args);
40+
allArgs.push('-jar', executable);
41+
allArgs.push(...args);
4442
const options = {
4543
cwd: process.env.GITHUB_WORKSPACE,
4644
ignoreReturnCode: true
4745
}
48-
const exitCode = await exec.exec('java', arguments, options);
46+
const exitCode = await exec.exec('java', allArgs, options);
4947
if (exitCode !== 0) {
5048
throw `Google Java Format failed with exit code ${exitCode}`;
5149
}
5250
}
5351

54-
async function execute(command, { silent = false, ignoreReturnCode = false } = {}) {
52+
async function execute(command: string, { silent = false, ignoreReturnCode = false } = {}): Promise<ExecResult> {
5553
let stdErr = '';
5654
let stdOut = '';
57-
const options = {
55+
const options: exec.ExecOptions = {
5856
silent: silent,
5957
ignoreReturnCode: true,
6058
listeners: {
@@ -63,18 +61,18 @@ async function execute(command, { silent = false, ignoreReturnCode = false } = {
6361
}
6462
};
6563
core.debug(`Executing: ${command}`);
66-
const exitCode = await exec.exec(command, null, options);
64+
const exitCode = await exec.exec(command, undefined, options);
6765
core.debug(`Exit code: ${exitCode}`);
6866
if (!ignoreReturnCode && exitCode !== 0) {
6967
command = command.split(' ')[0];
7068
throw `The command '${command}' failed with exit code ${exitCode}`;
7169
}
72-
return new ExecResult(exitCode, stdOut, stdErr);
70+
return { exitCode, stdOut, stdErr };
7371
}
7472

75-
async function curl(url, arguments) {
73+
async function curl(url: string, args?: string) {
7674
let command = `curl -sL "${url}"`;
77-
if (arguments) command += ` ${arguments}`;
75+
if (args) command += ` ${args}`;
7876
return await execute(command, { silent: !core.isDebug() });
7977
}
8078

@@ -91,7 +89,7 @@ async function listGJFReleases() {
9189
return releases.data;
9290
}
9391

94-
async function getRelease(releaseId) {
92+
async function getRelease(releaseId: number) {
9593
if (!githubToken) {
9694
const url = `${apiReleases}/${releaseId}`;
9795
core.debug(`URL: ${url}`);
@@ -108,21 +106,23 @@ async function getRelease(releaseId) {
108106
}
109107

110108
async function getJavaVersion() {
111-
let javaVersion = await execute('java -version', { silent: !core.isDebug() });
112-
javaVersion = javaVersion.stdErr
109+
const javaVersion = await execute('java -version', { silent: !core.isDebug() });
110+
let versionNumber = javaVersion.stdErr
113111
.split('\n')[0]
114-
.match(RegExp(/[0-9\.]+/))[0];
115-
core.debug(`Extracted version number: ${javaVersion}`);
116-
if (javaVersion.startsWith('1.')) javaVersion = javaVersion.replace(RegExp(/^1\./), '');
117-
javaVersion = javaVersion.split('\.')[0];
118-
return parseInt(javaVersion);
112+
.match(RegExp(/[0-9\.]+/))?.[0];
113+
if (!versionNumber) throw new Error("Cannot find Java version number");
114+
core.debug(`Extracted version number: ${versionNumber}`);
115+
if (versionNumber.startsWith('1.')) versionNumber = versionNumber.replace(RegExp(/^1\./), '');
116+
versionNumber = versionNumber.split('\.')[0];
117+
return parseInt(versionNumber);
119118
}
120119

121120
async function getReleaseId() {
122121
let releaseId = 'latest';
123122
const releases = await listGJFReleases();
124123
core.debug(`releases is ${typeof releases}`);
125-
const findRelease = function (name) { return releases.find(r => r['name'] === name); };
124+
// TODO model type
125+
const findRelease = function (name: string) { return releases.find((r: any) => r['name'] === name); };
126126
// Check if a specific version is requested
127127
const input = core.getInput('version');
128128
if (input) {
@@ -162,7 +162,8 @@ async function run() {
162162
core.debug(`release is ${typeof release}`);
163163
const assets = release['assets'];
164164
core.debug(`assets is ${typeof assets}`);
165-
const downloadUrl = assets.find(asset => asset['name'].endsWith('all-deps.jar'))['browser_download_url'];
165+
// TODO model type of asset
166+
const downloadUrl = assets.find((asset: any) => asset['name'].endsWith('all-deps.jar'))['browser_download_url'];
166167
core.info(`Downloading executable to ${executable}`);
167168
await curl(downloadUrl, `-o ${executable}`)
168169
await executeGJF(['--version']);

package-lock.json

Lines changed: 36 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"description": "Automatically format your Java files using Google Java Style guidelines.",
55
"main": "index.js",
66
"scripts": {
7-
"prepare": "ncc build index.js -o dist",
7+
"prepare": "ncc build index.ts -o dist",
88
"test": "echo \"Error: no test specified\" && exit 1"
99
},
1010
"repository": {
@@ -19,12 +19,14 @@
1919
},
2020
"homepage": "https://github.com/axel-op/googlejavaformat-action#readme",
2121
"dependencies": {
22-
"@actions/core": "^1.9.1",
22+
"@actions/core": "^1.11.1",
2323
"@actions/exec": "^1.1.0",
2424
"@actions/github": "^5.0.0",
25-
"@actions/glob": "^0.2.0"
25+
"@actions/glob": "^0.2.0",
26+
"typescript": "^5.7.3"
2627
},
2728
"devDependencies": {
29+
"@types/node": "^22.13.1",
2830
"@vercel/ncc": "^0.38.1"
2931
}
3032
}

tsconfig.json

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"compilerOptions": {
3+
"outDir": "./built",
4+
"allowJs": true,
5+
"module": "NodeNext",
6+
"moduleResolution": "nodenext",
7+
"noEmit": true,
8+
"noImplicitAny": true,
9+
"noImplicitThis": true,
10+
"strictNullChecks": true,
11+
"target": "ES2022"
12+
},
13+
"files": ["index.ts"],
14+
}

0 commit comments

Comments
 (0)