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

Creating FilePathsArray class that extends array and offers filtering functionality #467

Merged
merged 1 commit into from
Jun 2, 2020
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import { OCTANE_ES_LINT_CONFIG, OCTANE_TEMPLATE_LINT_CONFIG } from '../utils/lin

import OctaneMigrationStatusTaskResult from '../results/octane-migration-status-task-result';

const micromatch = require('micromatch');

export default class OctaneMigrationStatusTask extends BaseTask implements Task {
meta = {
taskName: 'octane-migration-status',
Expand Down Expand Up @@ -58,13 +56,13 @@ export default class OctaneMigrationStatusTask extends BaseTask implements Task
}

private async runEsLint(): Promise<ESLintReport> {
let jsPaths = micromatch(this.context.paths, '**/*.js');
let jsPaths = this.context.paths.filterByGlob('**/*.js');

return this.eslintParser.execute(jsPaths);
}

private async runTemplateLint(): Promise<TemplateLintReport> {
let hbsPaths = micromatch(this.context.paths, '**/*.hbs');
let hbsPaths = this.context.paths.filterByGlob('**/*.hbs');

return this.templateLinter.execute(hbsPaths);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import EmberInRepoAddonEnginesTaskResult from '../results/ember-in-repo-addons-e
import { PackageJson } from 'type-fest';
import { readJsonSync } from 'fs-extra';

const micromatch = require('micromatch');

export default class EmberInRepoAddonsEnginesTask extends BaseTask implements Task {
meta: TaskMetaData = {
taskName: 'ember-in-repo-addons-engines',
Expand All @@ -23,8 +21,7 @@ export default class EmberInRepoAddonsEnginesTask extends BaseTask implements Ta

result.inRepoAddons = [];
result.inRepoEngines = [];

let packageJsonPaths: string[] = micromatch(this.context.paths, ['**/*package.json']);
let packageJsonPaths: string[] = this.context.paths.filterByGlob('**/*package.json');

packageJsonPaths.forEach((pathName: string) => {
let packageJson: PackageJson = getPackageJson(pathName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import { transformESLintReport } from '../utils/transformers';

import EmberTestTypesTaskResult from '../results/ember-test-types-task-result';

const micromatch = require('micromatch');

export default class EmberTestTypesTask extends BaseTask implements Task {
meta = {
taskName: 'ember-test-types',
Expand All @@ -33,7 +31,7 @@ export default class EmberTestTypesTask extends BaseTask implements Task {
let createEslintParser = this.context.parsers.get('eslint')!;
this.eslintParser = createEslintParser(EMBER_TEST_TYPES);

this.testFiles = micromatch(this.context.paths, '**/*test.js');
this.testFiles = this.context.paths.filterByGlob('**/*test.js');
}

async run(): Promise<TaskResult> {
Expand Down
4 changes: 1 addition & 3 deletions packages/checkup-plugin-ember/src/tasks/ember-types-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { Category, Priority, Task, TaskResult, BaseTask, toTaskItemData } from '

import EmberTypesTaskResult from '../results/ember-types-task-result';

const micromatch = require('micromatch');

const SEARCH_PATTERNS = [
{ patternName: 'components', pattern: ['**/components/**/*.js'] },
{ patternName: 'controllers', pattern: ['**/controllers/**/*.js'] },
Expand All @@ -30,7 +28,7 @@ export default class EmberTypesTask extends BaseTask implements Task {
async run(): Promise<TaskResult> {
let result = new EmberTypesTaskResult(this.meta);
result.types = SEARCH_PATTERNS.map((pattern) => {
return toTaskItemData(pattern.patternName, micromatch(this.context.paths, pattern.pattern));
return toTaskItemData(pattern.patternName, this.context.paths.filterByGlob(pattern.pattern));
});

return result;
Expand Down
1 change: 0 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"is-valid-glob": "^1.0.0",
"json-stable-stringify": "^1.0.1",
"lodash": "^4.17.15",
"micromatch": "^4.0.2",
"npm-check": "^5.9.2",
"p-map": "^4.0.0",
"promise.hash.helper": "^1.0.7",
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
readConfig,
registerParser,
ui,
getFilePaths,
} from '@checkup/core';

import { BaseCommand } from '../base-command';
Expand All @@ -21,7 +22,6 @@ import TaskList from '../task-list';
import { flags } from '@oclif/command';
import { getPackageJson } from '../helpers/get-package-json';
import { getReporter } from '../reporters';
import { getFilePaths } from '../helpers/get-paths';
import LinesOfCodeTask from '../tasks/lines-of-code-task';
import EslintDisableTask from '../tasks/eslint-disable-task';
import OutdatedDependenciesTask from '../tasks/outdated-dependencies-task';
Expand Down
3 changes: 1 addition & 2 deletions packages/cli/src/tasks/eslint-disable-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
import EslintDisableTaskResult from '../results/eslint-disable-task-result';

const fs = require('fs');
const micromatch = require('micromatch');
const recast = require('recast');
const babel = require('@babel/parser');

Expand All @@ -29,7 +28,7 @@ export default class EslintDisableTask extends BaseTask implements Task {
async run(): Promise<TaskResult> {
let result: EslintDisableTaskResult = new EslintDisableTaskResult(this.meta);

let jsPaths = micromatch(this.context.paths, '**/*.js');
let jsPaths = this.context.paths.filterByGlob('**/*.js');
result.eslintDisables = await getEslintDisables(jsPaths);

return result;
Expand Down
3 changes: 1 addition & 2 deletions packages/cli/src/tasks/lines-of-code-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import LinesOfCodeTaskResult from '../results/lines-of-code-task-result';

const fs = require('fs');
const sloc = require('sloc');
const micromatch = require('micromatch');

interface GroupedFiles {
paths: string[];
Expand Down Expand Up @@ -75,7 +74,7 @@ export default class LinesOfCodeTask extends BaseTask implements Task {
this.filesGroupedByType = [...fileExensionsInRepo].map((ext) => {
return {
ext,
paths: micromatch(this.context.paths, `**/*.${ext}`),
paths: this.context.paths.filterByGlob(`**/*.${ext}`),
// if sloc doesnt support the extension, the LOC will be correct, but the breakdowns (# comments, todos, etc) will be wrong
exensionSupportedBySloc: FILE_EXTENSIONS_SUPPORTED.includes(ext),
};
Expand Down
15 changes: 15 additions & 0 deletions packages/core/__tests__/utils/file-paths-array-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

import { FilePathsArray } from '../../src/utils/file-paths-array';

describe('FilePathsArray', function () {
it('returns all files when no patterns are provided', function () {
let files = new FilePathsArray(...['foo.js', 'blue.hbs', 'goo.hbs']);

expect(files.filterByGlob('**.js')).toMatchInlineSnapshot(`
Array [
"foo.js",
]
`);
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

import { CheckupProject } from '@checkup/test-helpers';
import { getFilePaths } from '../src/helpers/get-paths';
import { getFilePaths } from '../../src/utils/get-paths';

const APP_NAME = 'foo-app';

Expand Down Expand Up @@ -33,7 +33,7 @@ describe('getFilePaths', function () {
let files = getFilePaths(project.baseDir);

expect(filterFilePathResults(files)).toMatchInlineSnapshot(`
Array [
FilePathsArray [
"/bar/index.js",
"/baz/index.js",
"/foo/index.hbs",
Expand All @@ -46,19 +46,29 @@ describe('getFilePaths', function () {
it('returns all files when no patterns are provided and a base path other than "." is provided', function () {
let files = getFilePaths(`${project.baseDir}/baz`);
expect(filterFilePathResults(files)).toMatchInlineSnapshot(`
Array [
FilePathsArray [
"/baz/index.js",
]
`);
});

it('filterByGlob works', function () {
let files = getFilePaths(project.baseDir);

expect(filterFilePathResults(files.filterByGlob('**/*.hbs'))).toMatchInlineSnapshot(`
Array [
"/foo/index.hbs",
]
`);
});
});

describe('glob', function () {
it('resolves a glob pattern', function () {
let files = getFilePaths(project.baseDir, ['**/*.hbs']);

expect(filterFilePathResults(files)).toMatchInlineSnapshot(`
Array [
FilePathsArray [
"/foo/index.hbs",
]
`);
Expand All @@ -68,7 +78,7 @@ describe('getFilePaths', function () {
let files = getFilePaths(project.baseDir, ['*']);

expect(filterFilePathResults(files)).toMatchInlineSnapshot(`
Array [
FilePathsArray [
"/index.js",
"/package.json",
]
Expand All @@ -79,7 +89,7 @@ describe('getFilePaths', function () {
let files = getFilePaths(`${project.baseDir}/baz`, ['**']);

expect(filterFilePathResults(files)).toMatchInlineSnapshot(`
Array [
FilePathsArray [
"/baz/index.js",
]
`);
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export { default as CheckupError } from './errors/checkup-error';
export { getPluginName, normalizePackageName, getShorthandName } from './utils/plugin-name';
export { exec } from './utils/exec';
export { ui } from './utils/ui';
export { getFilePaths } from './utils/get-paths';
export { FilePathsArray } from './utils/file-paths-array';
export { toPairs, toTaskData, toTaskItemData, toPercent } from './utils/data-transformers';

export * from './types/cli';
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/types/tasks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CreateParser, Parser, ParserName, ParserOptions, ParserReport } from './parsers';
import { FilePathsArray } from '../utils/file-paths-array';
import { JsonObject, PackageJson } from 'type-fest';

import { CheckupConfig } from './config';
Expand Down Expand Up @@ -26,7 +27,7 @@ export interface TaskContext {
readonly parsers: Map<ParserName, CreateParser<ParserOptions, Parser<ParserReport>>>;
readonly config: CheckupConfig;
readonly pkg: PackageJson;
readonly paths: string[];
readonly paths: FilePathsArray;
}

export interface TaskResult {
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/utils/file-paths-array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const micromatch = require('micromatch');

export class FilePathsArray extends Array<string> {
filterByGlob(glob: string | string[]) {
return micromatch(this, glob);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { join, resolve } from 'path';
import { existsSync } from 'fs';
import { FilePathsArray } from './file-paths-array';

const micromatch = require('micromatch');
const isValidGlob = require('is-valid-glob');
Expand All @@ -24,7 +25,7 @@ export function getFilePaths(
basePath: string,
globs: string[] = [],
excludePaths: string[] = []
): string[] {
): FilePathsArray {
let mergedPathsToIgnore = [...excludePaths, ...PATHS_TO_IGNORE];

if (globs.length > 0) {
Expand All @@ -42,35 +43,38 @@ function expandFileGlobs(
filePatterns: string[],
basePath: string,
excludePaths: string[]
): string[] {
return filePatterns.flatMap((pattern) => {
let isLiteralPath = !isValidGlob(pattern) && existsSync(pattern);
): FilePathsArray {
return new FilePathsArray(
...filePatterns.flatMap((pattern) => {
let isLiteralPath = !isValidGlob(pattern) && existsSync(pattern);

if (isLiteralPath) {
let isIgnored = !micromatch.isMatch(pattern, PATHS_TO_IGNORE);
if (isLiteralPath) {
let isIgnored = !micromatch.isMatch(pattern, PATHS_TO_IGNORE);

if (!isIgnored) {
return pattern;
}
if (!isIgnored) {
return pattern;
}

return [];
}
return [];
}

let expandedGlobs = globby.sync(pattern, {
cwd: basePath,
ignore: excludePaths,
gitignore: true,
}) as string[];
let expandedGlobs = globby.sync(pattern, {
cwd: basePath,
ignore: excludePaths,
gitignore: true,
}) as string[];

return resolveFilePaths(expandedGlobs, basePath);
});
return resolveFilePaths(expandedGlobs, basePath);
})
);
}

function resolveFilePaths(filePaths: string[], basePath: string): string[] {
function resolveFilePaths(filePaths: string[], basePath: string): FilePathsArray {
if (basePath !== '.') {
return filePaths.map((pathName: string) => {
let resolvedPaths = filePaths.map((pathName: string) => {
return join(resolve(basePath), pathName);
});
return new FilePathsArray(...resolvedPaths);
}
return filePaths;
return new FilePathsArray(...filePaths);
}
6 changes: 3 additions & 3 deletions packages/test-helpers/src/checkup-fixturify-project.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

import { CheckupConfig, mergeConfig } from '@checkup/core';
import { CheckupConfig, mergeConfig, FilePathsArray } from '@checkup/core';

import { PackageJson } from 'type-fest';
import Plugin from './plugin';
Expand Down Expand Up @@ -85,10 +85,10 @@ export default class CheckupFixturifyProject extends Project {
this.pkg = packageJsonContent;
}

get filePaths(): string[] {
get filePaths(): FilePathsArray {
if (this._hasWritten) {
let allFiles = walkSync(this.baseDir, { directories: false });
return resolveFilePaths(allFiles, this.baseDir);
return new FilePathsArray(...resolveFilePaths(allFiles, this.baseDir));
} else {
throw new Error('You must call writeSync on your project before getting the file paths.');
}
Expand Down
12 changes: 9 additions & 3 deletions packages/test-helpers/src/get-task-context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { TaskContext, getRegisteredParsers, RunFlags, CheckupConfig } from '@checkup/core';
import {
TaskContext,
getRegisteredParsers,
RunFlags,
CheckupConfig,
FilePathsArray,
} from '@checkup/core';

import { PackageJson } from 'type-fest';

Expand All @@ -7,7 +13,7 @@ type TaskContextArgs = {
cliFlags: Partial<RunFlags>;
config: Partial<CheckupConfig>;
pkg: PackageJson;
paths: string[];
paths: FilePathsArray;
};

const DEFAULT_FLAGS: RunFlags = {
Expand Down Expand Up @@ -38,7 +44,7 @@ export function getTaskContext({
cliFlags,
config,
pkg = DEFAULT_PACKAGE_JSON,
paths = [],
paths = new FilePathsArray(),
}: Partial<TaskContextArgs> = {}): TaskContext {
return {
cliArguments,
Expand Down