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

drop file reader from jdl/core #27248

Merged
merged 3 commits into from
Sep 11, 2024
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
14 changes: 4 additions & 10 deletions cli/environment-builder.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* limitations under the License.
*/
import assert from 'assert';
import { existsSync, readFileSync } from 'fs';
import { existsSync } from 'fs';
import path, { dirname, resolve } from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import chalk from 'chalk';
Expand All @@ -27,6 +27,7 @@ import { QueuedAdapter } from '@yeoman/adapter';

import { createJHipsterLogger, packageNameToNamespace } from '../generators/base/support/index.js';
import { loadBlueprintsFromConfiguration, mergeBlueprints, parseBlueprintInfo } from '../generators/base/internal/index.js';
import { readCurrentPathYoRcFile } from '../lib/utils/yo-rc.js';
import { CLI_NAME, logger } from './utils.mjs';

const __filename = fileURLToPath(import.meta.url);
Expand All @@ -40,13 +41,6 @@ const defaultLookupOptions = {
customizeNamespace: ns => ns?.replaceAll(':generators:', ':'),
};

function loadYoRc(filePath = '.yo-rc.json') {
if (!existsSync(filePath)) {
return undefined;
}
return JSON.parse(readFileSync(filePath, { encoding: 'utf-8' }));
}

const createEnvironment = (options = {}) => {
options.adapter = options.adapter ?? new QueuedAdapter({ log: createJHipsterLogger() });
return new Environment({ newErrorHandler: true, ...options });
Expand Down Expand Up @@ -333,8 +327,8 @@ export default class EnvironmentBuilder {
* @returns {Blueprint[]}
*/
_getBlueprintsFromYoRc() {
const yoRc = loadYoRc();
if (!yoRc || !yoRc['generator-jhipster']) {
const yoRc = readCurrentPathYoRcFile();
if (!yoRc?.['generator-jhipster']) {
return [];
}
return loadBlueprintsFromConfiguration(yoRc['generator-jhipster']);
Expand Down
2 changes: 1 addition & 1 deletion generators/client/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const command = {
microfrontends: {
description: 'Microfrontends to load',
cli: {
type: String,
type: (val: string) => promptValueToMicrofrontends(val),
},
prompt: ({ jhipsterConfigWithDefaults: config }) => ({
when: answers => {
Expand Down
2 changes: 1 addition & 1 deletion lib/command/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ type PrepareConfigsWithType<U extends ParseableConfigs> = Simplify<{
? TupleToUnion<NormalizeChoices<U[K]['choices']>>
: WrapperToPrimitive<ConstructorReturn<GetType<U[K]>>> extends infer T
? T extends undefined
? string
? unknown
: T
: never;
}>;
Expand Down
14 changes: 14 additions & 0 deletions lib/command/types.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ type TestCommand = {
choices: ['foo', 'no'];
scope: 'storage';
};
unknownType: {
cli: {
type: () => any;
};
scope: 'storage';
};
};
};

Expand Down Expand Up @@ -66,6 +72,14 @@ const _choiceTypeError = {
choiceType: 'bar',
} satisfies StorageProperties;

const _unknownType = {
unknownType: true,
} satisfies StorageProperties;

const _unknownType2 = {
unknownType: 'string',
} satisfies StorageProperties;

type ApplicationProperties = ExportApplicationPropertiesFromCommand<TestCommand>;

const applicationChoiceType = {
Expand Down
6 changes: 3 additions & 3 deletions lib/jdl/converters/exporters/export-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import fs from 'fs';
import { doesFileExist } from '../../core/utils/file-utils.js';
import type { JHipsterYoRcContent } from '../../core/types/json-config.js';
import { mergeYoRcContent } from '../../../utils/yo-rc.js';
import { YO_RC_FILE, mergeYoRcContent, readYoRcFile } from '../../../utils/yo-rc.js';

export const GENERATOR_NAME = 'generator-jhipster';

Expand All @@ -29,10 +29,10 @@ export const GENERATOR_NAME = 'generator-jhipster';
* @param config the configuration.
* @param yoRcPath the yeoman conf file path
*/
export function writeConfigFile(config: JHipsterYoRcContent, yoRcPath = '.yo-rc.json') {
export function writeConfigFile(config: JHipsterYoRcContent, yoRcPath = YO_RC_FILE): void {
let newYoRc: JHipsterYoRcContent = { ...config };
if (doesFileExist(yoRcPath)) {
const yoRc = JSON.parse(fs.readFileSync(yoRcPath, { encoding: 'utf-8' }));
const yoRc = readYoRcFile(yoRcPath) as JHipsterYoRcContent;
newYoRc = mergeYoRcContent(yoRc, config);
}
fs.writeFileSync(yoRcPath, JSON.stringify(newYoRc, null, 2).concat('\n'));
Expand Down
18 changes: 8 additions & 10 deletions lib/jdl/converters/exporters/jhipster-entity-exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@
* limitations under the License.
*/

import path from 'path';

import { readJSONFile, toFilePath } from '../../core/readers/json-file-reader.js';
import { doesFileExist } from '../../core/utils/file-utils.js';
import type { JSONEntity } from '../../core/types/json-config.js';
import type { JhipsterJSONJDLExporterWrapper } from '../../core/types/exporter.js';
import applicationTypes from '../../../jhipster/application-types.js';
import { readEntityFile } from '../../../utils/yo-rc.js';

let configuration: any = {};

Expand Down Expand Up @@ -62,21 +59,22 @@ function init(passedConfiguration: JhipsterJSONJDLExporterWrapper) {
* Writes entities in a sub folder.
* @param subFolder the folder (to create) in which the JHipster entity folder will be.
*/
function updateEntities(subFolder: string): JSONEntity[] {
function updateEntities(applicationPath: string): JSONEntity[] {
return configuration.entities.map((entity: JSONEntity) => {
const filePath = path.join(subFolder, toFilePath(entity.name));
return updateEntityToGenerateWithExistingOne(filePath, entity);
return updateEntityToGenerateWithExistingOne(applicationPath, entity);
});
}

function updateEntityToGenerateWithExistingOne(filePath: string, entity: JSONEntity): JSONEntity {
if (doesFileExist(filePath)) {
const fileOnDisk = readJSONFile(filePath);
function updateEntityToGenerateWithExistingOne(applicationPath: string, entity: JSONEntity): JSONEntity {
try {
const fileOnDisk = readEntityFile<JSONEntity>(applicationPath, entity.name);
if (!entity.annotations?.changelogDate && fileOnDisk?.annotations?.changelogDate) {
entity.annotations = entity.annotations || {};
entity.annotations.changelogDate = fileOnDisk.annotations.changelogDate;
return { ...fileOnDisk, ...entity };
}
} catch {
// New entity
}
return entity;
}
Expand Down
2 changes: 0 additions & 2 deletions lib/jdl/converters/json-to-jdl-converter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,8 +417,6 @@ describe('jdl - JSONToJDLConverter', () => {
convertSingleContentToJDL({
'generator-jhipster': {
baseName: 'x',
blueprints: null,
microfrontends: undefined,
},
});
});
Expand Down
14 changes: 7 additions & 7 deletions lib/jdl/converters/json-to-jdl-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,11 @@ import fs from 'fs';
import JDLObject from '../core/models/jdl-object.js';
import mergeJDLObjects from '../core/models/jdl-object-merger.js';
import { doesDirectoryExist, doesFileExist } from '../core/utils/file-utils.js';
import { readJSONFile } from '../core/readers/json-file-reader.js';
import { removeFieldsWithNullishValues } from '../../utils/object.js';
import type JDLApplication from '../core/models/jdl-application.js';
import type { JDLRuntime } from '../core/types/runtime.js';
import { createRuntime, getDefaultRuntime } from '../core/runtime.js';
import { YO_RC_CONFIG_KEY } from '../../utils/yo-rc.js';
import { YO_RC_CONFIG_KEY, readEntityFile, readYoRcFile } from '../../utils/yo-rc.js';
import type { JDLApplicationConfig } from '../core/types/parsing.js';
import type { JHipsterYoRcContent, JSONEntity, PostProcessedJSONRootObject } from '../core/types/json-config.js';
import exportJDLObject from './exporters/jdl-exporter.js';
Expand All @@ -52,7 +51,7 @@ export function convertToJDL(
let jdlObject: JDLObject;
const runtime = definition ? createRuntime(definition) : getDefaultRuntime();
if (doesFileExist(path.join(directory, '.yo-rc.json'))) {
const yoRcFileContent: JHipsterYoRcContent = readJSONFile(path.join(directory, '.yo-rc.json'));
const yoRcFileContent: JHipsterYoRcContent = readYoRcFile(directory);
let entities: Map<string, JSONEntity> | undefined;
if (doesDirectoryExist(path.join(directory, '.jhipster'))) {
entities = getJSONEntityFiles(directory);
Expand Down Expand Up @@ -84,7 +83,7 @@ function getJDLObjectFromMultipleApplications(directory: string, runtime: JDLRun
let jdlObject = new JDLObject();
subDirectories.forEach(subDirectory => {
const applicationDirectory = path.join(directory, subDirectory);
const yoRcFileContent: JHipsterYoRcContent = readJSONFile(path.join(applicationDirectory, '.yo-rc.json'));
const yoRcFileContent: JHipsterYoRcContent = readYoRcFile(applicationDirectory);
let entities = new Map<string, JSONEntity>();
if (doesDirectoryExist(path.join(applicationDirectory, '.jhipster'))) {
entities = getJSONEntityFiles(applicationDirectory);
Expand Down Expand Up @@ -131,9 +130,10 @@ function getJSONEntityFiles(applicationDirectory: string): Map<string, JSONEntit
const entities = new Map<string, JSONEntity>();
fs.readdirSync(path.join(applicationDirectory, '.jhipster')).forEach(file => {
const entityName = file.slice(0, file.indexOf('.json'));
const jsonFilePath = path.join(applicationDirectory, '.jhipster', file);
if (fs.statSync(jsonFilePath).isFile() && file.endsWith('.json')) {
entities.set(entityName, readJSONFile(jsonFilePath));
try {
entities.set(entityName, readEntityFile(applicationDirectory, entityName));
} catch {
// Not an entity file, not adding
}
});
return entities;
Expand Down
6 changes: 1 addition & 5 deletions lib/jdl/core/__test-support__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import {
} from '../../jdl-importer.js';
import type { ParsedJDLApplication, ParsedJDLRoot } from '../types/parsed.js';
import definition from '../../../../generators/app/jdl/index.js';
import {
createJDLLinterFromContent as originalCreateJDLLinterFromContent,
createJDLLinterFromFile as originalCreateJDLLinterFromFile,
} from '../linters/jdl-linter.js';
import { createJDLLinterFromContent as originalCreateJDLLinterFromContent } from '../linters/jdl-linter.js';
import { convertApplications as originalConvertApplications } from '../../converters/parsed-jdl-to-jdl-object/application-converter.js';
import { createJDLApplication as originalCreateJDLApplication } from '../models/jdl-application-factory.js';
import type { JHipsterYoRcContentAndJDLWrapper } from '../../converters/json-to-jdl-application-converter.js';
Expand All @@ -33,7 +30,6 @@ export const parseFromFiles = (files: string[]) => originalParseFromFiles(files,
export const parseFromContent = (content: string) => originalParseFromContent(content, runtime);

export const createJDLLinterFromContent = (content: string) => originalCreateJDLLinterFromContent(content, runtime);
export const createJDLLinterFromFile = (file: string) => originalCreateJDLLinterFromFile(file, runtime);

export const convertApplications = (applications: ParsedJDLApplication[]) => originalConvertApplications(applications, runtime);
export const createJDLApplication = (config: any, namespaceConfigs?: Record<string, Record<string, any>> | undefined) =>
Expand Down
18 changes: 16 additions & 2 deletions lib/jdl/core/linters/jdl-linter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
* limitations under the License.
*/

import { writeFileSync } from 'fs';
import { readFileSync, writeFileSync } from 'fs';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import { expect } from 'chai';
import { beforeEach, describe, it, expect as jestExpect } from 'esmocha';
import { basicHelpers as helpers } from '../../../../lib/testing/index.js';
import { createJDLLinterFromContent, createJDLLinterFromFile, getTestFile } from '.././__test-support__/index.js';
import { createJDLLinterFromContent, getTestFile } from '.././__test-support__/index.js';
import type { JDLLinter } from './jdl-linter.js';
import type Issues from './issues/issues.js';
import type EnumIssue from './issues/enum-issue.js';
Expand All @@ -32,6 +32,20 @@ import type relationshipIssue from './issues/relationship-issue.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

/**
* Creates a new JDL linters from a JDL file.
* @param file - the JDL file.
* @return {Object} the JDL linters.
* @throws {Error} if the JDL file isn't passed.
*/
export function createJDLLinterFromFile(file: string): JDLLinter {
if (!file) {
throw new Error('A JDL file must be passed to create a new JDL linter.');
}
const jdlString = readFileSync(file, 'utf-8');
return createJDLLinterFromContent(jdlString);
}

describe('jdl - JDLLinter', () => {
beforeEach(async () => {
await helpers.prepareTemporaryDir();
Expand Down
19 changes: 2 additions & 17 deletions lib/jdl/core/linters/jdl-linter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
* limitations under the License.
*/

import { readFile } from '../readers/file-reader.js';
import * as JDLReader from '../readers/jdl-reader.js';
import type { JDLRuntime } from '../types/runtime.js';
import { getCstFromContent } from '../readers/jdl-reader.js';
import Issues from './issues/issues.js';
import type { EntityDeclaration } from './entity-linter.js';
import { checkEntities } from './entity-linter.js';
Expand All @@ -44,20 +43,6 @@ export function createJDLLinterFromContent(jdlString: string, runtime: JDLRuntim
return makeJDLLinter(jdlString, runtime);
}

/**
* Creates a new JDL linters from a JDL file.
* @param file - the JDL file.
* @return {Object} the JDL linters.
* @throws {Error} if the JDL file isn't passed.
*/
export function createJDLLinterFromFile(file: string, runtime: JDLRuntime): JDLLinter {
if (!file) {
throw new Error('A JDL file must be passed to create a new JDL linter.');
}
const jdlString = readFile(file);
return makeJDLLinter(jdlString, runtime);
}

type CST = {
children: {
entityDeclaration: EntityDeclaration[];
Expand All @@ -70,7 +55,7 @@ let cst: CST;
let issues: Issues;

function makeJDLLinter(content: any, runtime: JDLRuntime) {
cst = JDLReader.getCstFromContent(content, runtime);
cst = getCstFromContent(content, runtime);
issues = new Issues();

return {
Expand Down
Loading
Loading