Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rules): natural-order rule #38

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .scriptlintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
{
"strict": true
}
"strict": true,
"rules": {
"alphabetic-order": false,
"natural-order": true
}
}
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Your `package.json`'s `"scripts"` section should…
- _abstract script names from their implementation (`test`, not `jest`)_
- _use namespaces to categorize scripts (`"test:unit": "jest"`)_
- _use `:` as a namespace separator_
- _have the scripts in alphabetic order_
- _have the scripts in alphabetic or ["natural order"](https://github.com/peerigon/scriptlint/wiki/natural-order)
- _have a trigger script for all hooks (ex: if you have `prefoobar`, there must be a `foobar` script)_
- _use `camelCase` for all script names_
- _not alias `devDependencies` (no `"jest": "jest"`)_
Expand Down Expand Up @@ -89,6 +89,9 @@ href="https://github.com/peerigon/scriptlint/wiki/uses-allowed-namespace">uses-a
<li><a
href="https://github.com/peerigon/scriptlint/wiki/alphabetic-order">alphabetic-order</a>
</li>
<li><a
href="https://github.com/peerigon/scriptlint/wiki/natural-order">natural-order</a>
</li>
<li><a href="https://github.com/peerigon/scriptlint/wiki/correct-casing">correct-casing</a>
</li>
<li><a href="https://github.com/peerigon/scriptlint/wiki/no-aliases">no-aliases</a>
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
"other:selfupdate": "updtr",
"other:watch": "nodemon -e js,ts --watch src --exec 'run-p build:dev'",
"prepublishOnly": "run-p build",
"pretest": "run-s build",
"start": "node dist/index.js",
"pretest": "run-s build",
"test": "run-s test:exports test:lint test:types test:unit:ci test:self",
"test:exports": "ts-unused-exports tsconfig.json --ignoreFiles src/index.ts",
"test:lint": "eslint ./src ./tests --ext js,ts,tsx",
Expand Down Expand Up @@ -85,4 +85,4 @@
"cosmiconfig": "^7.0.0",
"detect-indent": "^6.0.0"
}
}
}
3 changes: 2 additions & 1 deletion src/cliConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export default (argv: Array<string>): CliConfig => {

program.parse(argv);

const cliConfig: CliConfig = { packageFile };
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const cliConfig: CliConfig = { packageFile: packageFile ?? process.cwd() };

if (program.fix !== undefined) {
cliConfig.fix = program.fix;
Expand Down
3 changes: 2 additions & 1 deletion src/cliModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export default (argv: Array<string>) => {

const userConfig = loadUserConfig();
const cliConfig = loadCliConfig(argv);

const config = {
...DEFAULT_CONFIG,
...{ json: false },
Expand All @@ -51,7 +52,7 @@ export default (argv: Array<string>) => {
writePackageScripts,
readPackageScripts,
} = userPackageScriptContext(
makePackageFilePath(config.packageFile ?? process.cwd())
makePackageFilePath(config.packageFile)
);

const scripts = readPackageScripts(config.ignoreScripts);
Expand Down
2 changes: 1 addition & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const DEFAULT_CONFIG: Config = {
fix: false,
json: false,
config: false,
packageFile: undefined,
packageFile: process.cwd(),
rules: {},
customRules: [],
ignoreScripts: [],
Expand Down
9 changes: 8 additions & 1 deletion src/defaultRuleSets.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import defaultRules from "./rules";
import { Rule } from "./types";

export const optionalRules = ["natural-order"];

const strict = defaultRules
.map((r: Rule) => r.name)
.filter((r) => !optionalRules.includes(r));

const ruleSets = {
default: [
"mandatory-test",
"mandatory-start",
"mandatory-dev",
"no-default-test",
],
strict: defaultRules.map((r: Rule) => r.name),
strict,
optionalRules,
};

export default ruleSets;
39 changes: 22 additions & 17 deletions src/loadRules.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import defaultRuleSets from "./defaultRuleSets";
import defaultRuleSets, {optionalRules} from "./defaultRuleSets";
import defaultRules from "./rules";
// Types
import { Rule } from "./types";
Expand Down Expand Up @@ -32,31 +32,36 @@ const loadDefaultRulesFromSet = (strict: boolean): Array<Rule> => {
.filter((r): r is Rule => r !== null);
};

const loadOptionalRules = (): Array<Rule> => {
return optionalRules
.map((name: string) => getRuleByName(defaultRules, name))
.filter((r): r is Rule => r !== null);
};

export const loadRulesFromRuleConfig = (
strict: boolean,
rulesConfig?: RulesConfig,
customRules?: Array<Rule>
): Array<Rule> => {
const optionalRules = loadOptionalRules();
const rules = loadDefaultRulesFromSet(strict);

const loadedCustomRules =
rulesConfig && customRules
? customRules.filter((cr: Rule) => rulesConfig[cr.name])
: [];

const loadedRules = [...loadedCustomRules, ...rules];

// standard rulesets apply
if (!rulesConfig) {
return loadedRules;
return rules;
}

return loadedRules
.map((rule: Rule) => {
if (rule.name in rulesConfig && rulesConfig[rule.name] === false) {
return null;
}
// there's custom rules loaded
const loadedCustomRules = customRules
? customRules.filter((cr: Rule) => rulesConfig[cr.name])
: [];

return rule;
})
.filter((r): r is Rule => r !== null);
// there's enabled optional rules
const enabledOptionalRules = optionalRules.filter(
({ name }) => name in rulesConfig && Boolean(rulesConfig[name])
);

return [...loadedCustomRules, ...enabledOptionalRules, ...rules].filter(
({ name }) => !(name in rulesConfig) || rulesConfig[name] !== false
);
};
2 changes: 1 addition & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default (moduleConfig: Partial<Config>) => {

if (!moduleConfig.packageScripts && moduleConfig.packageFile) {
const { readPackageScripts } = userPackageScriptContext(
makePackageFilePath(config.packageFile ?? "")
makePackageFilePath(config.packageFile)
);

scripts = readPackageScripts(config.ignoreScripts);
Expand Down
2 changes: 2 additions & 0 deletions src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import noAliases from "./no-aliases";
import prePostTriggerDefined from "./prepost-trigger-defined";
import usesAllowedNamespace from "./uses-allowed-namespace";
import alphabeticOrder from "./alphabetic-order";
import naturalOrder from "./natural-order";
import { Rule } from "../types";

const rules: Array<Rule> = [
Expand All @@ -18,6 +19,7 @@ const rules: Array<Rule> = [
usesAllowedNamespace,
prePostTriggerDefined,
alphabeticOrder,
naturalOrder,
makeForbidUnixOperators(/rm /, "rm -rf", "rimraf"),
makeForbidUnixOperators(
/ && /,
Expand Down
84 changes: 84 additions & 0 deletions src/rules/natural-order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { PackageScripts } from "../types";
import { objectFromEntries } from "../utils";

type EntryInfo = {
order: number;
namespace: string;
entry: [string, string];
};

const prepareEntryInfo = (entry: [string, string]) => {
const name = entry[0];
const namespace = name.split(":")[0];

if (name.startsWith("pre")) {
return {
order: 0,
namespace: namespace.substr(3),
entry,
};
}
if (name.startsWith("post")) {
return {
order: 2,
namespace: namespace.substr(4),
entry,
};
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice 👍 😁


return {
order: 1,
namespace,
entry,
};
};

export const sortScripts = (scripts: PackageScripts): PackageScripts => {
// prepare namespace and order info
const entries = Object.entries(scripts).map(prepareEntryInfo);

return objectFromEntries(
entries
// make unique namespace groups
.map((e: EntryInfo) => e.namespace)
.filter(
(name: string, i: number, a: Array<string>) =>
a.indexOf(name) === i
)
.sort()
.map((name: string) =>
entries.filter((e: EntryInfo) => e.namespace === name)
)
// sort inside the group
.map((group: Array<EntryInfo>) =>
// sort `1-title` vs `2-title` etc.
group.sort((a: EntryInfo, b: EntryInfo) =>
`${a.order}-${a.entry[0]}`.localeCompare(
`${b.order}-${b.entry[0]}`
)
)
)
// flatten array
.reduce(
(flatted: Array<EntryInfo>, group: Array<EntryInfo>) => [
...flatted,
...group,
],
[]
)
// reduce to entries again
.map((f: EntryInfo) => f.entry)
);
};

export default {
name: "natural-order",
isObjectRule: true,
message: "scripts must be in 'natural' order",
validate: (scripts: PackageScripts) => {
const sorted = sortScripts(scripts);

return Object.keys(sorted).join("|") === Object.keys(scripts).join("|");
},
fix: (scripts: PackageScripts) => sortScripts(scripts),
};
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export type PackageScripts = {

export type Config = {
strict: boolean;
packageFile?: string;
packageFile: string;
packageScripts?: PackageScripts;
fix: boolean;
json: boolean;
Expand Down
7 changes: 7 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,10 @@ export const patchScriptObjectEntry = (
return k === fromKey ? [toKey, value] : [k, v];
})
);

type ObjectFromEntries = {[key: string]: any};
export const objectFromEntries = <T>(iterable: Array<[string, T]>): ObjectFromEntries => iterable.reduce((obj, [key, value]) => {
obj[key] = value;

return obj
}, {} as ObjectFromEntries)
2 changes: 1 addition & 1 deletion tests/cliConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe("cliConfig.ts", () => {
"-f",
]);

expect(packageFile).not.toBeDefined();
expect(packageFile).toEqual(process.cwd());

expect(config).toEqual({
fix: true,
Expand Down
14 changes: 13 additions & 1 deletion tests/loadRules.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { loadRulesFromRuleConfig, getRuleByName } from "../src/loadRules";
import defaultRules from "../src/rules";
import {optionalRules} from "../src/defaultRuleSets";

describe("loadRules.ts", () => {
const defaultRulesLoaded = loadRulesFromRuleConfig(false);
Expand Down Expand Up @@ -28,8 +29,19 @@ describe("loadRules.ts", () => {
).toBe(customRule.name);
});

it("loads optional rules", () => {
const rulesWithCustomRule = loadRulesFromRuleConfig(
false,
{
"natural-order": true,
}
);

expect(rulesWithCustomRule.map(r => r.name)[0]).toBe("natural-order");
});

it("loads correct amount of rules", () => {
expect(strictRulesLoaded.length).toBe(defaultRules.length);
expect(strictRulesLoaded.length).toBe(defaultRules.length - optionalRules.length);
});

test("getRuleByName() nulls on unknown name", () => {
Expand Down
Loading