Add and configure ESLint and update configuration for Prettier (#391)

* Apply ESLint config and update Prettier

* Update dependencies and rebuild

* Update docs
This commit is contained in:
Ivan 2023-03-09 14:43:05 +02:00 committed by GitHub
parent 926f442022
commit c82240598b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 3145 additions and 967 deletions

6
.eslintignore Normal file
View File

@ -0,0 +1,6 @@
# Ignore list
/*
# Do not ignore these folders:
!__tests__/
!src/

49
.eslintrc.js Normal file
View File

@ -0,0 +1,49 @@
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:eslint-plugin-jest/recommended',
'eslint-config-prettier'
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'eslint-plugin-jest'],
rules: {
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-ignore': 'allow-with-description'
}
],
'no-console': 'error',
'yoda': 'error',
'prefer-const': [
'error',
{
destructuring: 'all'
}
],
'no-control-regex': 'off',
'no-constant-condition': ['error', {checkLoops: false}]
},
overrides: [
{
files: ['**/*{test,spec}.ts'],
rules: {
'@typescript-eslint/no-unused-vars': 'off',
'jest/no-standalone-expect': 'off',
'jest/no-conditional-expect': 'off',
'no-console': 'off',
}
}
],
env: {
node: true,
es6: true,
'jest/globals': true
}
};

1
.gitattributes vendored
View File

@ -1 +1,2 @@
* text=auto eol=lf
.licenses/** -diff linguist-generated=true

View File

@ -2,9 +2,9 @@ name: CodeQL analysis
on:
push:
branches: [ main ]
branches: [main]
pull_request:
branches: [ main ]
branches: [main]
schedule:
- cron: '0 3 * * 0'

View File

@ -207,8 +207,8 @@ jobs:
- name: Setup dotnet 7.0 with preview quality
uses: ./
with:
dotnet-version: "7.0"
dotnet-quality: "preview"
dotnet-version: '7.0'
dotnet-quality: 'preview'
- name: Verify preview version
shell: pwsh
run: |
@ -233,7 +233,7 @@ jobs:
uses: ./
id: step1
with:
dotnet-version: "6.0.401"
dotnet-version: '6.0.401'
- name: Verify value of the dotnet-version output
shell: pwsh

View File

@ -2,3 +2,4 @@
. "$(dirname -- "$0")/_/husky.sh"
npm run format
npm run lint:fix

View File

@ -3,3 +3,4 @@
# Tests are not run at push time since they can take 2-4 minutes to complete
npm run format-check
npm run lint

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
# Ignore list
/*
# Do not ignore these folders:
!__tests__/
!.github/
!src/

10
.prettierrc.js Normal file
View File

@ -0,0 +1,10 @@
module.exports = {
printWidth: 80,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: false,
arrowParens: 'avoid'
};

View File

@ -1,12 +0,0 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid",
"parser": "typescript",
"endOfLine": "auto"
}

View File

@ -9,20 +9,20 @@ const fakeSourcesDirForTesting = path.join(
's'
);
const invalidNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>`;
const invalidNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>`;
const emptyNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const emptyNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>`;
const nugetorgNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const nugetorgNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources>
</configuration>`;
const gprnugetorgNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const gprnugetorgNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="GPR" value="https://nuget.pkg.github.com/OwnerName/index.json" protocolVersion="3" />
@ -30,14 +30,14 @@ const gprnugetorgNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
</packageSources>
</configuration>`;
const gprNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const gprNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="GPR" value="https://nuget.pkg.github.com/OwnerName/index.json" protocolVersion="3" />
</packageSources>
</configuration>`;
const twogprNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const twogprNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="GPR-GitHub" value="https://nuget.pkg.github.com/OwnerName/index.json" protocolVersion="3" />
@ -45,21 +45,21 @@ const twogprNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
</packageSources>
</configuration>`;
const spaceNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const spaceNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="GPR GitHub" value="https://nuget.pkg.github.com/OwnerName/index.json" protocolVersion="3" />
</packageSources>
</configuration>`;
const azureartifactsNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const azureartifactsNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="AzureArtifacts" value="https://pkgs.dev.azure.com/amullans/_packaging/GitHubBuilds/nuget/v3/index.json" protocolVersion="3" />
</packageSources>
</configuration>`;
const azureartifactsnugetorgNuGetConfig: string = `<?xml version="1.0" encoding="utf-8"?>
const azureartifactsnugetorgNuGetConfig = `<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="AzureArtifacts" value="https://pkgs.dev.azure.com/amullans/_packaging/GitHubBuilds/nuget/v3/index.json" protocolVersion="3" />

View File

@ -1,19 +1,19 @@
import cscFile from '../.github/csc.json';
describe('csc tests', () => {
it('Valid regular expression', async () => {
var cscFile = require('../.github/csc.json');
var regex = cscFile['problemMatcher'][0]['pattern'][0]['regexp'];
const regex = cscFile['problemMatcher'][0]['pattern'][0]['regexp'];
console.log(regex);
var re = new RegExp(regex);
const re = new RegExp(regex);
// Ideally we would verify that this
var stringsToMatch = [
const stringsToMatch = [
'Program.cs(10,79): error CS1002: ; expected [/Users/zacharyeisinger/Documents/repo/setup-dotnet/__tests__/sample-broken-csproj/sample.csproj]',
"S:\\Msbuild\\src\\Build\\Evaluation\\ExpressionShredder.cs(33,7): error CS1003: Syntax error, ',' expected [S:\\msbuild\\src\\Build\\Microsoft.Build.csproj > Properties:prop]"
];
stringsToMatch.forEach(string => {
var matchStr = string.match(re);
const matchStr = string.match(re);
console.log(matchStr);
expect(matchStr).toEqual(expect.anything());
});

View File

@ -68,8 +68,8 @@ describe('DotnetCoreInstaller tests', () => {
expect(fs.existsSync(path.join(toolDir, 'dotnet'))).toBe(true);
}
expect(process.env.DOTNET_ROOT).toBeDefined;
expect(process.env.PATH).toBeDefined;
expect(process.env.DOTNET_ROOT).toBeDefined();
expect(process.env.PATH).toBeDefined();
expect(process.env.DOTNET_ROOT).toBe(toolDir);
expect(process.env.PATH?.startsWith(toolDir)).toBe(true);
}, 600000);
@ -83,15 +83,15 @@ describe('DotnetCoreInstaller tests', () => {
expect(fs.existsSync(path.join(toolDir, 'dotnet'))).toBe(true);
}
expect(process.env.DOTNET_ROOT).toBeDefined;
expect(process.env.PATH).toBeDefined;
expect(process.env.DOTNET_ROOT).toBeDefined();
expect(process.env.PATH).toBeDefined();
expect(process.env.DOTNET_ROOT).toBe(toolDir);
expect(process.env.PATH?.startsWith(toolDir)).toBe(true);
}, 600000); //This needs some time to download on "slower" internet connections
it('Acquires generic version of dotnet if no matching version is installed', async () => {
await getDotnet('3.1');
var directory = fs
const directory = fs
.readdirSync(path.join(toolDir, 'sdk'))
.filter(fn => fn.startsWith('3.1.'));
expect(directory.length > 0).toBe(true);
@ -101,17 +101,16 @@ describe('DotnetCoreInstaller tests', () => {
expect(fs.existsSync(path.join(toolDir, 'dotnet'))).toBe(true);
}
expect(process.env.DOTNET_ROOT).toBeDefined;
expect(process.env.PATH).toBeDefined;
expect(process.env.DOTNET_ROOT).toBeDefined();
expect(process.env.PATH).toBeDefined();
expect(process.env.DOTNET_ROOT).toBe(toolDir);
expect(process.env.PATH?.startsWith(toolDir)).toBe(true);
}, 600000); //This needs some time to download on "slower" internet connections
it('Returns string with installed SDK version', async () => {
const version = '3.1.120';
let installedVersion: string;
installedVersion = await getDotnet(version);
const installedVersion = await getDotnet(version);
expect(installedVersion).toBe('3.1.120');
}, 600000);
@ -143,7 +142,7 @@ describe('DotnetCoreInstaller tests', () => {
}, 30000);
it('Uses an up to date powershell download script', async () => {
var httpCallbackClient = new hc.HttpClient('setup-dotnet-test', [], {
const httpCallbackClient = new hc.HttpClient('setup-dotnet-test', [], {
allowRetries: true,
maxRetries: 3
});
@ -180,7 +179,7 @@ describe('DotnetVersionResolver tests', () => {
);
const versionObject = await dotnetVersionResolver.createDotNetVersion();
expect(!!versionObject.value).toBeTruthy;
expect(!!versionObject.value).toBe(true);
}
);
@ -223,15 +222,27 @@ describe('DotnetVersionResolver tests', () => {
);
each(['3.1', '3.1.x', '3.1.*', '3.1.X']).test(
"if version: '%s' that can be resolved to 'channel' option is supplied, it should set quality flag to 'true' and type to 'channel' in version object",
"if version: '%s' that can be resolved to 'channel' option is supplied, it should set type to 'channel' in version object",
async version => {
const dotnetVersionResolver = new installer.DotnetVersionResolver(
version
);
const versionObject = await dotnetVersionResolver.createDotNetVersion();
expect(versionObject.type.toLowerCase().includes('channel')).toBeTruthy;
expect(versionObject.qualityFlag).toBeTruthy;
expect(versionObject.type.toLowerCase().includes('channel')).toBe(true);
}
);
each(['6.0', '6.0.x', '6.0.*', '6.0.X']).test(
"if version: '%s' that can be resolved to 'channel' option is supplied and its major tag is >= 6, it should set type to 'channel' and qualityFlag to 'true' in version object",
async version => {
const dotnetVersionResolver = new installer.DotnetVersionResolver(
version
);
const versionObject = await dotnetVersionResolver.createDotNetVersion();
expect(versionObject.type.toLowerCase().includes('channel')).toBe(true);
expect(versionObject.qualityFlag).toBe(true);
}
);
@ -243,8 +254,8 @@ describe('DotnetVersionResolver tests', () => {
);
const versionObject = await dotnetVersionResolver.createDotNetVersion();
expect(versionObject.type.toLowerCase().includes('version')).toBeTruthy;
expect(versionObject.qualityFlag).toBeFalsy;
expect(versionObject.type.toLowerCase().includes('version')).toBe(true);
expect(versionObject.qualityFlag).toBe(false);
}
);
@ -259,11 +270,11 @@ describe('DotnetVersionResolver tests', () => {
const nonWindowsRegEx = new RegExp(/^--[vc]/);
if (IS_WINDOWS) {
expect(windowsRegEx.test(versionObject.type)).toBeTruthy;
expect(nonWindowsRegEx.test(versionObject.type)).toBeFalsy;
expect(windowsRegEx.test(versionObject.type)).toBe(true);
expect(nonWindowsRegEx.test(versionObject.type)).toBe(false);
} else {
expect(nonWindowsRegEx.test(versionObject.type)).toBeTruthy;
expect(windowsRegEx.test(versionObject.type)).toBeFalsy;
expect(nonWindowsRegEx.test(versionObject.type)).toBe(true);
expect(windowsRegEx.test(versionObject.type)).toBe(false);
}
}
);
@ -276,10 +287,7 @@ function normalizeFileContents(contents: string): string {
.replace(new RegExp('\r', 'g'), '\n');
}
async function getDotnet(
version: string,
quality: string = ''
): Promise<string> {
async function getDotnet(version: string, quality = ''): Promise<string> {
const dotnetInstaller = new installer.DotnetCoreInstaller(
version,
quality as QualityOptions

View File

@ -21,11 +21,11 @@ if (IS_WINDOWS) {
const tempDir = path.join(__dirname, 'runner', 'temp2');
describe('setup-dotnet tests', () => {
let getInputSpy = jest.spyOn(core, 'getInput');
let getMultilineInputSpy = jest.spyOn(core, 'getMultilineInput');
let setOutputSpy = jest.spyOn(core, 'setOutput');
const getInputSpy = jest.spyOn(core, 'getInput');
const getMultilineInputSpy = jest.spyOn(core, 'getMultilineInput');
const setOutputSpy = jest.spyOn(core, 'setOutput');
let inputs = {} as any;
const inputs = {} as any;
beforeAll(async () => {
process.env.RUNNER_TOOL_CACHE = toolDir;
@ -74,7 +74,7 @@ describe('setup-dotnet tests', () => {
await setup.run();
expect(setOutputSpy).toBeCalledWith('dotnet-version', '6.0.401');
expect(setOutputSpy).toHaveBeenCalledWith('dotnet-version', '6.0.401');
}, 400000);
it("Sets output with the version specified in global.json, if it's present", async () => {
@ -93,6 +93,6 @@ describe('setup-dotnet tests', () => {
await setup.run();
expect(setOutputSpy).toBeCalledWith('dotnet-version', '3.0.103');
expect(setOutputSpy).toHaveBeenCalledWith('dotnet-version', '3.0.103');
}, 400000);
});

18
dist/index.js vendored
View File

@ -45,7 +45,7 @@ function configAuthentication(feedUrl, existingFileLocation = '', processRoot =
}
exports.configAuthentication = configAuthentication;
function isValidKey(key) {
return /^[\w\-\.]+$/i.test(key);
return /^[\w\-.]+$/i.test(key);
}
function getExistingNugetConfig(processRoot) {
const defaultConfigName = 'nuget.config';
@ -60,9 +60,9 @@ function getExistingNugetConfig(processRoot) {
function writeFeedToFile(feedUrl, existingFileLocation, tempFileLocation) {
var _a, _b;
core.info(`dotnet-auth: Finding any source references in ${existingFileLocation}, writing a new temporary configuration file with credentials to ${tempFileLocation}`);
let sourceKeys = [];
const sourceKeys = [];
let owner = core.getInput('owner');
let sourceUrl = feedUrl;
const sourceUrl = feedUrl;
if (!owner) {
owner = github.context.repo.owner;
}
@ -132,7 +132,7 @@ function writeFeedToFile(feedUrl, existingFileLocation, tempFileLocation) {
}
];
if (!sourceKeys.length) {
let keystring = 'Source';
const keystring = 'Source';
xmlSource[1].configuration.push({
packageSources: [
{
@ -300,9 +300,9 @@ class DotnetVersionResolver {
return __awaiter(this, void 0, void 0, function* () {
const response = yield httpClient.getJson(DotnetVersionResolver.DotNetCoreIndexUrl);
const result = response.result || {};
let releasesInfo = result['releases-index'];
let releaseInfo = releasesInfo.find(info => {
let sdkParts = info['channel-version'].split('.');
const releasesInfo = result['releases-index'];
const releaseInfo = releasesInfo.find(info => {
const sdkParts = info['channel-version'].split('.');
return sdkParts[0] === versionParts[0];
});
if (!releaseInfo) {
@ -408,8 +408,8 @@ class DotnetCoreInstaller {
outputDotnetVersion(version) {
return __awaiter(this, void 0, void 0, function* () {
const installationPath = process.env['DOTNET_INSTALL_DIR'];
let versionsOnRunner = yield (0, promises_1.readdir)(path_1.default.join(installationPath.replace(/'/g, ''), 'sdk'));
let installedVersion = semver_1.default.maxSatisfying(versionsOnRunner, version, {
const versionsOnRunner = yield (0, promises_1.readdir)(path_1.default.join(installationPath.replace(/'/g, ''), 'sdk'));
const installedVersion = semver_1.default.maxSatisfying(versionsOnRunner, version, {
includePrerelease: true
});
return installedVersion;

View File

@ -61,6 +61,7 @@ Pull requests are the easiest way to contribute changes to git repos at GitHub.
- To implement new features or fix bugs, you need to make changes to the `.ts` files, which are located in the `src` folder
- To comply with the code style, **you need to run the `format` script**
- To lint the code, **you need to run the `lint:fix` script**
- To transpile source code to `javascript` we use [NCC](https://github.com/vercel/ncc). **It is very important to run the `build` script after making changes**, otherwise your changes will not get into the final `javascript` build
**Learn more about how to implement tests:**

2137
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,9 +6,10 @@
"main": "lib/setup-dotnet.js",
"scripts": {
"build": "tsc && ncc build",
"format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts",
"lint": "echo \"Fake command that does nothing. It is used in reusable workflows\"",
"format": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --write **/*.{ts,yml,yaml}",
"format-check": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --check **/*.{ts,yml,yaml}",
"lint": "eslint --config ./.eslintrc.js **/*.ts",
"lint:fix": "eslint --config ./.eslintrc.js **/*.ts --fix",
"prepare": "husky install",
"test": "jest --coverage --config ./jest.config.js",
"update-installers": "nwget https://dot.net/v1/dotnet-install.ps1 -O externals/install-dotnet.ps1 && nwget https://dot.net/v1/dotnet-install.sh -O externals/install-dotnet.sh"
@ -37,11 +38,16 @@
"@types/jest": "^27.0.2",
"@types/node": "^16.11.25",
"@types/semver": "^6.2.2",
"@typescript-eslint/eslint-plugin": "^5.54.0",
"@typescript-eslint/parser": "^5.54.0",
"@vercel/ncc": "^0.33.4",
"eslint": "^8.35.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-jest": "^27.2.1",
"husky": "^8.0.1",
"jest": "^27.2.5",
"jest-circus": "^27.2.5",
"prettier": "^2.7.1",
"prettier": "^2.8.4",
"ts-jest": "^27.0.5",
"typescript": "^4.8.4",
"wget-improved": "^3.2.1"

View File

@ -6,7 +6,7 @@ import {XMLParser, XMLBuilder} from 'fast-xml-parser';
export function configAuthentication(
feedUrl: string,
existingFileLocation: string = '',
existingFileLocation = '',
processRoot: string = process.cwd()
) {
const existingNuGetConfig: string = path.resolve(
@ -26,7 +26,7 @@ export function configAuthentication(
}
function isValidKey(key: string): boolean {
return /^[\w\-\.]+$/i.test(key);
return /^[\w\-.]+$/i.test(key);
}
function getExistingNugetConfig(processRoot: string) {
@ -48,9 +48,9 @@ function writeFeedToFile(
core.info(
`dotnet-auth: Finding any source references in ${existingFileLocation}, writing a new temporary configuration file with credentials to ${tempFileLocation}`
);
let sourceKeys: string[] = [];
const sourceKeys: string[] = [];
let owner: string = core.getInput('owner');
let sourceUrl: string = feedUrl;
const sourceUrl: string = feedUrl;
if (!owner) {
owner = github.context.repo.owner;
}
@ -130,7 +130,7 @@ function writeFeedToFile(
];
if (!sourceKeys.length) {
let keystring = 'Source';
const keystring = 'Source';
xmlSource[1].configuration.push({
packageSources: [

View File

@ -88,10 +88,10 @@ export class DotnetVersionResolver {
DotnetVersionResolver.DotNetCoreIndexUrl
);
const result = response.result || {};
let releasesInfo: any[] = result['releases-index'];
const releasesInfo: any[] = result['releases-index'];
let releaseInfo = releasesInfo.find(info => {
let sdkParts: string[] = info['channel-version'].split('.');
const releaseInfo = releasesInfo.find(info => {
const sdkParts: string[] = info['channel-version'].split('.');
return sdkParts[0] === versionParts[0];
});
@ -106,7 +106,7 @@ export class DotnetVersionResolver {
return releaseInfo['channel-version'];
}
static DotNetCoreIndexUrl: string =
static DotNetCoreIndexUrl =
'https://dotnetcli.azureedge.net/dotnet/release-metadata/releases-index.json';
}
@ -252,11 +252,11 @@ export class DotnetCoreInstaller {
private async outputDotnetVersion(version): Promise<string> {
const installationPath = process.env['DOTNET_INSTALL_DIR']!;
let versionsOnRunner: string[] = await readdir(
const versionsOnRunner: string[] = await readdir(
path.join(installationPath.replace(/'/g, ''), 'sdk')
);
let installedVersion = semver.maxSatisfying(versionsOnRunner, version, {
const installedVersion = semver.maxSatisfying(versionsOnRunner, version, {
includePrerelease: true
})!;

View File

@ -13,7 +13,7 @@ const qualityOptions = [
'ga'
] as const;
export type QualityOptions = typeof qualityOptions[number];
export type QualityOptions = (typeof qualityOptions)[number];
export async function run() {
try {
@ -100,7 +100,7 @@ export async function run() {
}
function getVersionFromGlobalJson(globalJsonPath: string): string {
let version: string = '';
let version = '';
const globalJson = JSON.parse(
// .trim() is necessary to strip BOM https://github.com/nodejs/node/issues/20649
fs.readFileSync(globalJsonPath, {encoding: 'utf8'}).trim()

View File

@ -49,7 +49,8 @@
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"resolveJsonModule": true, /* Allows importing modules with a '.json' extension, which is a common practice in node projects. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */