Skip to content

Commit

Permalink
style: setup prettier eslint and vscode settings properly
Browse files Browse the repository at this point in the history
  • Loading branch information
d-koppenhagen committed Dec 14, 2021
1 parent d357c2a commit b474104
Show file tree
Hide file tree
Showing 8 changed files with 134 additions and 120 deletions.
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Editor configuration, see https://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false
18 changes: 5 additions & 13 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,27 +1,19 @@
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "prettier"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"plugin:prettier/recommended"
],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"rules": {
"prettier/prettier": [
"error",
{
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": false,
"bracketSpacing": true,
"printWidth": 120,
"tabWidth": 2,
"semi": false
"semi": true
}
],
// octokit/rest requires parameters that are not in camelcase
// "camelcase": "off",
"@typescript-eslint/camelcase": ["error", {"properties": "never"}]
]
},
"env": {
"node": true,
Expand All @@ -32,4 +24,4 @@
"ecmaVersion": 2018,
"sourceType": "module"
}
}
}
6 changes: 6 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

*.js.map
*.d.ts
*.md
*.min.*
dist/**/*
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"printWidth": 120,
"singleQuote": true,
"trailingComma": "all"
}
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
100 changes: 50 additions & 50 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,94 +1,94 @@
import * as github from '@actions/github'
import * as core from '@actions/core'
import * as exec from '@actions/exec'
import * as io from '@actions/io'
import * as path from 'path'
import run from '../index'
import * as github from '@actions/github';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as io from '@actions/io';
import * as path from 'path';
import run from '../index';

const originalContext = {...github.context}
const originalGitHubWorkspace = process.env['GITHUB_WORKSPACE']
const gitHubWorkspace = path.resolve('/checkout-tests/workspace')
const originalContext = { ...github.context };
const originalGitHubWorkspace = process.env['GITHUB_WORKSPACE'];
const gitHubWorkspace = path.resolve('/checkout-tests/workspace');

type InputsMock = {
[name: string]: string
}
[name: string]: string;
};

let inputs: InputsMock = {}
let execSpy: jest.SpyInstance
let inputs: InputsMock = {};
let execSpy: jest.SpyInstance;

beforeAll(() => {
execSpy = jest.spyOn(exec, 'exec').mockImplementation(jest.fn())
jest.spyOn(io, 'cp').mockImplementation(jest.fn())
execSpy = jest.spyOn(exec, 'exec').mockImplementation(jest.fn());
jest.spyOn(io, 'cp').mockImplementation(jest.fn());

jest.spyOn(core, 'getInput').mockImplementation((name: string) => {
return inputs[name]
})
return inputs[name];
});

jest.spyOn(github.context, 'repo', 'get').mockImplementation(() => {
return {
owner: 'enriikke',
repo: 'enriikke.github.io',
}
})
};
});

github.context.ref = 'refs/heads/some-ref'
github.context.sha = '1234567890123456789012345678901234567890'
github.context.ref = 'refs/heads/some-ref';
github.context.sha = '1234567890123456789012345678901234567890';

process.env['GITHUB_WORKSPACE'] = gitHubWorkspace
})
process.env['GITHUB_WORKSPACE'] = gitHubWorkspace;
});

afterAll(() => {
delete process.env['GITHUB_WORKSPACE']
delete process.env['GITHUB_WORKSPACE'];
if (originalGitHubWorkspace) {
process.env['GITHUB_WORKSPACE'] = originalGitHubWorkspace
process.env['GITHUB_WORKSPACE'] = originalGitHubWorkspace;
}

github.context.ref = originalContext.ref
github.context.sha = originalContext.sha
github.context.ref = originalContext.ref;
github.context.sha = originalContext.sha;

jest.restoreAllMocks()
})
jest.restoreAllMocks();
});

beforeEach(() => {
jest.resetModules()
jest.resetModules();
inputs = {
'access-token': 'SECRET',
'skip-publish': 'true',
}
})
};
});

describe('scully Publish action', () => {
it('returns an error when no access token is given', async () => {
inputs['access-token'] = ''
const setFailedSpy = jest.spyOn(core, 'setFailed')
inputs['access-token'] = '';
const setFailedSpy = jest.spyOn(core, 'setFailed');

await run()
await run();

expect(setFailedSpy).toBeCalledWith(
'No personal access token found. Please provide one by setting the `access-token` input for this action.',
)
})
);
});

it('skips if deploy branch is the same as the current git head', async () => {
inputs['deploy-branch'] = 'some-ref'
github.context.ref = 'refs/heads/some-ref'
inputs['deploy-branch'] = 'some-ref';
github.context.ref = 'refs/heads/some-ref';

await expect(run()).resolves.not.toThrowError()
})
await expect(run()).resolves.not.toThrowError();
});

it('calls scully build without args', async () => {
inputs['scully-args'] = ''
inputs['scully-args'] = '';

await run()
await run();

expect(execSpy).toBeCalledWith('yarn run build', [])
})
expect(execSpy).toBeCalledWith('yarn run build', []);
});

it('calls scully build with args', async () => {
inputs['scully-args'] = '--prefix-paths --no-uglify'
inputs['scully-args'] = '--prefix-paths --no-uglify';

await run()
await run();

expect(execSpy).toBeCalledWith('yarn run build', ['--', '--prefix-paths', '--no-uglify'])
})
})
expect(execSpy).toBeCalledWith('yarn run build', ['--', '--prefix-paths', '--no-uglify']);
});
});
98 changes: 46 additions & 52 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,56 @@


import * as core from '@actions/core'
import * as exec from '@actions/exec'
import * as github from '@actions/github'
import * as io from '@actions/io'
import * as ioUtil from '@actions/io/lib/io-util'
import * as lockfile from '@yarnpkg/lockfile'
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as github from '@actions/github';
import * as io from '@actions/io';
import * as ioUtil from '@actions/io/lib/io-util';
import * as lockfile from '@yarnpkg/lockfile';
import semver from 'semver';
import { readFileSync } from 'fs';

const DEFAULT_DEPLOY_BRANCH = 'master'
const DEFAULT_DEPLOY_BRANCH = 'master';

async function run(): Promise<void> {
try {
const accessToken = core.getInput("access-token");
const accessToken = core.getInput('access-token');
if (!accessToken) {
core.setFailed(
"No personal access token found. Please provide one by setting the `access-token` input for this action."
'No personal access token found. Please provide one by setting the `access-token` input for this action.',
);
return;
}

let deployBranch = core.getInput("deploy-branch");
let deployBranch = core.getInput('deploy-branch');
if (!deployBranch) deployBranch = DEFAULT_DEPLOY_BRANCH;

if (github.context.ref === `refs/heads/${deployBranch}`) {
console.log(`Triggered by branch used to deploy: ${github.context.ref}.`);
console.log("Nothing to deploy.");
console.log('Nothing to deploy.');
return;
}

const pkgManager = (await ioUtil.exists("./yarn.lock")) ? "yarn" : "npm";
const installCmd = pkgManager === "yarn" ? "install --frozen-lockfile" : "ci"
const pkgManager = (await ioUtil.exists('./yarn.lock')) ? 'yarn' : 'npm';
const installCmd = pkgManager === 'yarn' ? 'install --frozen-lockfile' : 'ci';
console.log(`Installing your site's dependencies using ${pkgManager}.`);
await exec.exec(`${pkgManager} ${installCmd}`);
console.log("Finished installing dependencies.");
console.log('Finished installing dependencies.');

let buildArgs = core.getInput("build-args").trim();
let buildArgs = core.getInput('build-args').trim();
// Add dashes if a user passes args and doesnt have them.
if (buildArgs !== "" && buildArgs.indexOf("-- ") !== 0) {
if (buildArgs !== '' && buildArgs.indexOf('-- ') !== 0) {
buildArgs = `-- ${buildArgs}`;
}

let scullyArgs = core.getInput("scully-args").trim();
let scullyArgs = core.getInput('scully-args').trim();
// Remove dashes if the scullyArgs have them
// This is because we now pass --nw by default.
if (scullyArgs.indexOf("-- ") === 0) {
if (scullyArgs.indexOf('-- ') === 0) {
scullyArgs = scullyArgs.slice(3);
}

console.log("Ready to build your Scully site!");
console.log('Ready to build your Scully site!');
console.log(`Building with: ${pkgManager} run build ${buildArgs}`);
await exec.exec(`${pkgManager} run build ${buildArgs}`, []);
console.log("Finished building your site.");
console.log('Finished building your site.');

// determine the scully version
let scullyVersion;
Expand All @@ -61,7 +59,9 @@ async function run(): Promise<void> {
const yarnLockRaw = readFileSync('./yarn.lock', 'utf8');
const yarnLockParsed = lockfile.parse(yarnLockRaw);
// result contains a list with e.g. "@scullyio/scully@^0.0.85" as key, so we have to find teh matching object key
const getScullyChildObjectKey = Object.keys(yarnLockParsed.object).filter((p: string) => /@scullyio\/scully/.test(p));
const getScullyChildObjectKey = Object.keys(yarnLockParsed.object).filter((p: string) =>
/@scullyio\/scully/.test(p),
);
// use the found key to get the version from the object
scullyVersion = yarnLockParsed.object[getScullyChildObjectKey[0]].version;
} else {
Expand All @@ -75,47 +75,41 @@ async function run(): Promise<void> {
// add the `--nw` flag if scully version is below or equal `0.0.85`
if (semver.lte(scullyVersion, '0.0.85')) {
console.log(`Scully Version is less then '0.0.85', adding '--nw' flag`);
scullyArgs = `--nw ${scullyArgs}`
scullyArgs = `--nw ${scullyArgs}`;
}

await exec.exec(`${pkgManager} run scully -- ${scullyArgs}`, []);
console.log("Finished Scullying your site.");
console.log('Finished Scullying your site.');

const cnameExists = await ioUtil.exists("./CNAME");
const cnameExists = await ioUtil.exists('./CNAME');
if (cnameExists) {
console.log("Copying CNAME over.");
await io.cp("./CNAME", "./dist/static/CNAME", { force: true });
console.log("Finished copying CNAME.");
console.log('Copying CNAME over.');
await io.cp('./CNAME', './dist/static/CNAME', { force: true });
console.log('Finished copying CNAME.');
}

const repo = `${github.context.repo.owner}/${github.context.repo.repo}`;
const repoURL = `https://${accessToken}@github.com/${repo}.git`;
console.log("Ready to deploy your new shiny site!");
console.log('Ready to deploy your new shiny site!');
console.log(`Deploying to repo: ${repo} and branch: ${deployBranch}`);
console.log(
"You can configure the deploy branch by setting the `deploy-branch` input for this action."
);
await exec.exec(`git init`, [], { cwd: "./dist/static" });
console.log('You can configure the deploy branch by setting the `deploy-branch` input for this action.');
await exec.exec(`git init`, [], { cwd: './dist/static' });
await exec.exec(`git config user.name`, [github.context.actor], {
cwd: "./dist/static"
cwd: './dist/static',
});
await exec.exec(`git config user.email`, [`${github.context.actor}@users.noreply.github.com`], {
cwd: './dist/static',
});
await exec.exec(`git add`, ['.'], { cwd: './dist/static' });
await exec.exec(`git commit`, ['-m', `deployed via Scully Publish Action 🎩 for ${github.context.sha}`], {
cwd: './dist/static',
});
await exec.exec(
`git config user.email`,
[`${github.context.actor}@users.noreply.github.com`],
{ cwd: "./dist/static" }
);
await exec.exec(`git add`, ["."], { cwd: "./dist/static" });
await exec.exec(
`git commit`,
["-m", `deployed via Scully Publish Action 🎩 for ${github.context.sha}`],
{ cwd: "./dist/static" }
);
await exec.exec(`git push`, ["-f", repoURL, `master:${deployBranch}`], {
cwd: "./dist/static"
await exec.exec(`git push`, ['-f', repoURL, `master:${deployBranch}`], {
cwd: './dist/static',
});
console.log("Finished deploying your site.");
console.log('Finished deploying your site.');

console.log("Enjoy! ✨");
console.log('Enjoy! ✨');
core.setOutput('success', true);
} catch (error) {
if (error instanceof Error) core.setFailed(error.message);
Expand All @@ -124,7 +118,7 @@ async function run(): Promise<void> {

// Don't auto-execute in the test environment
if (process.env['NODE_ENV'] !== 'test') {
run()
run();
}

export default run
export default run;
Loading

0 comments on commit b474104

Please sign in to comment.