Skip to content

Commit

Permalink
fix: move filenameUtils from shared to studio-pure-functions (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
standeren authored Nov 22, 2024
1 parent ef816fa commit 77e8aa2
Show file tree
Hide file tree
Showing 19 changed files with 209 additions and 171 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SelectedSchemaEditor } from './SelectedSchemaEditor';
import type { DataModelMetadata } from 'app-shared/types/DataModelMetadata';
import { SchemaGenerationErrorsPanel } from './SchemaGenerationErrorsPanel';
import { useAddXsdMutation } from '../../../hooks/mutations/useAddXsdMutation';
import { isXsdFile } from 'app-shared/utils/filenameUtils';
import { FileNameUtils } from '@studio/pure-functions';

export interface SchemaEditorWithToolbarProps {
createPathOption?: boolean;
Expand All @@ -32,7 +32,7 @@ export const SchemaEditorWithToolbar = ({

useEffect(() => {
dataModels.forEach((model) => {
if (model.repositoryRelativeUrl && isXsdFile(model.repositoryRelativeUrl)) {
if (model.repositoryRelativeUrl && FileNameUtils.isXsdFile(model.repositoryRelativeUrl)) {
addXsdFromRepo(model.repositoryRelativeUrl);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { useQueryClient } from '@tanstack/react-query';
import { QueryKey } from 'app-shared/types/QueryKey';
import { useStudioEnvironmentParams } from 'app-shared/hooks/useStudioEnvironmentParams';
import { mergeJsonAndXsdData } from 'app-development/utils/metadataUtils';
import { extractFilename, removeSchemaExtension } from 'app-shared/utils/filenameUtils';
import { FileNameUtils } from '@studio/pure-functions';
export interface SelectedSchemaEditorProps {
modelPath: string;
}
Expand Down Expand Up @@ -111,6 +111,6 @@ const SchemaEditorWithDebounce = ({ jsonSchema, modelPath }: SchemaEditorWithDeb
};

const extractModelNameFromPath = (path: string): string => {
const filename = extractFilename(path);
return removeSchemaExtension(filename);
const filename = FileNameUtils.extractFilename(path);
return FileNameUtils.removeSchemaExtension(filename);
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import type { StudioButtonProps } from '@studio/components';
import { StudioFileUploader, StudioSpinner } from '@studio/components';
import { FileNameUtils } from '@studio/pure-functions';
import { useTranslation } from 'react-i18next';
import { useUploadDataModelMutation } from '../../../../../hooks/mutations/useUploadDataModelMutation';
import type { AxiosError } from 'axios';
Expand All @@ -10,7 +11,6 @@ import type { MetadataOption } from '../../../../../types/MetadataOption';
import { useStudioEnvironmentParams } from 'app-shared/hooks/useStudioEnvironmentParams';
import { useAppMetadataQuery } from 'app-shared/hooks/queries';
import { useValidationAlert } from './useValidationAlert';
import { removeExtension } from 'app-shared/utils/filenameUtils';
import {
doesFileExistInMetadataWithClassRef,
doesFileExistInMetadataWithoutClassRef,
Expand Down Expand Up @@ -65,7 +65,7 @@ export const XSDUpload = ({
if (fileNameError) {
validationAlert(fileNameError);
}
const fileNameWithoutExtension = removeExtension(file.name);
const fileNameWithoutExtension = FileNameUtils.removeExtension(file.name);
if (doesFileExistInMetadataWithClassRef(appMetadata, fileNameWithoutExtension)) {
const userConfirmed = window.confirm(
t('schema_editor.error_upload_data_model_id_exists_override_option'),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ApplicationMetadata } from 'app-shared/types/ApplicationMetadata';
import { removeExtension } from 'app-shared/utils/filenameUtils';
import { FileNameUtils } from '@studio/pure-functions';
import type { FileNameError } from './FileNameError';

export const doesFileExistInMetadataWithClassRef = (
Expand Down Expand Up @@ -28,7 +28,7 @@ export const findFileNameError = (
fileName: string,
appMetadata: ApplicationMetadata,
): FileNameError | null => {
const fileNameWithoutExtension = removeExtension(fileName);
const fileNameWithoutExtension = FileNameUtils.removeExtension(fileName);
if (!isNameFormatValid(fileNameWithoutExtension)) {
return 'invalidFileName';
} else if (doesFileExistInMetadata(appMetadata, fileNameWithoutExtension)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ import { createQueryClientMock } from 'app-shared/mocks/queryClientMock';
import { waitFor } from '@testing-library/react';
import { QueryKey } from 'app-shared/types/QueryKey';
import { queriesMock } from 'app-shared/mocks/queriesMock';
import { createJsonModelPathMock } from 'app-shared/mocks/modelPathMocks';
import { createJsonModelPathMock, createXsdModelPathMock } from 'app-shared/mocks/modelPathMocks';
import {
createJsonMetadataMock,
createXsdMetadataMock,
} from 'app-shared/mocks/dataModelMetadataMocks';
import { app, org } from '@studio/testing/testids';

const modelName = 'modelName';
const modelPath = createJsonModelPathMock(modelName);
const modelJsonPath = createJsonModelPathMock(modelName);
const modelXsdPath = createXsdModelPathMock(modelName);
const modelMetadataJson = createJsonMetadataMock(modelName);
const modelMetadataXsd = createXsdMetadataMock(modelName);

Expand All @@ -29,38 +30,62 @@ describe('useDeleteDataModelMutation', () => {
renderHookResult: { result },
} = render({}, client);
expect(result.current).toBeDefined();
result.current.mutate(modelPath);
result.current.mutate(modelJsonPath);
await waitFor(() => result.current.isSuccess);
expect(queriesMock.deleteDataModel).toHaveBeenCalledTimes(1);
expect(queriesMock.deleteDataModel).toHaveBeenCalledWith(org, app, modelPath);
expect(queriesMock.deleteDataModel).toHaveBeenCalledWith(org, app, modelJsonPath);
});

it('Removes the metadata instances from the query cache', async () => {
it('Removes the metadata instances from the query cache when model is json', async () => {
const client = createQueryClientMock();
client.setQueryData([QueryKey.DataModelsJson, org, app], [modelMetadataJson]);
client.setQueryData([QueryKey.DataModelsXsd, org, app], [modelMetadataXsd]);
const {
renderHookResult: { result },
} = render({}, client);
result.current.mutate(modelPath);
result.current.mutate(modelJsonPath);
await waitFor(() => result.current.isSuccess);
expect(client.getQueryData([QueryKey.DataModelsJson, org, app])).toEqual([]);
expect(client.getQueryData([QueryKey.DataModelsXsd, org, app])).toEqual([]);
});

it('Removes the schema queries from the query cache', async () => {
it('Removes the metadata instances from the query cache when model is xsd', async () => {
const client = createQueryClientMock();
client.setQueryData([QueryKey.DataModelsJson, org, app], [modelMetadataJson]);
client.setQueryData([QueryKey.DataModelsXsd, org, app], [modelMetadataXsd]);
const {
renderHookResult: { result },
} = render({}, client);
result.current.mutate(modelPath);
result.current.mutate(modelXsdPath);
await waitFor(() => result.current.isSuccess);
expect(client.getQueryData([QueryKey.JsonSchema, org, app, modelPath])).toBeUndefined();
expect(
client.getQueryData([QueryKey.JsonSchema, org, app, modelMetadataXsd.repositoryRelativeUrl]),
).toBeUndefined();
expect(client.getQueryData([QueryKey.DataModelsJson, org, app])).toEqual([]);
expect(client.getQueryData([QueryKey.DataModelsXsd, org, app])).toEqual([]);
});

it('Removes the schema queries from the query cache when model is json', async () => {
const client = createQueryClientMock();
client.setQueryData([QueryKey.DataModelsJson, org, app], [modelMetadataJson]);
client.setQueryData([QueryKey.DataModelsXsd, org, app], [modelMetadataXsd]);
const {
renderHookResult: { result },
} = render({}, client);
result.current.mutate(modelJsonPath);
await waitFor(() => result.current.isSuccess);
expect(client.getQueryData([QueryKey.JsonSchema, org, app, modelJsonPath])).toBeUndefined();
expect(client.getQueryData([QueryKey.JsonSchema, org, app, modelXsdPath])).toBeUndefined();
});

it('Removes the schema queries from the query cache when model is xsd', async () => {
const client = createQueryClientMock();
client.setQueryData([QueryKey.DataModelsJson, org, app], [modelMetadataJson]);
client.setQueryData([QueryKey.DataModelsXsd, org, app], [modelMetadataXsd]);
const {
renderHookResult: { result },
} = render({}, client);
result.current.mutate(modelXsdPath);
await waitFor(() => result.current.isSuccess);
expect(client.getQueryData([QueryKey.JsonSchema, org, app, modelJsonPath])).toBeUndefined();
expect(client.getQueryData([QueryKey.JsonSchema, org, app, modelXsdPath])).toBeUndefined();
});

it('Invalidates the appMetadataModelIds and appMetadata from the cache', async () => {
Expand All @@ -71,7 +96,7 @@ describe('useDeleteDataModelMutation', () => {
const {
renderHookResult: { result },
} = render({}, client);
result.current.mutate(modelPath);
result.current.mutate(modelJsonPath);
await waitFor(() => result.current.isSuccess);
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(2);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useServicesContext } from 'app-shared/contexts/ServicesContext';
import { QueryKey } from 'app-shared/types/QueryKey';
import { useStudioEnvironmentParams } from 'app-shared/hooks/useStudioEnvironmentParams';
import { isXsdFile } from 'app-shared/utils/filenameUtils';
import { FileNameUtils } from '@studio/pure-functions';
import type { DataModelMetadata } from 'app-shared/types/DataModelMetadata';

export const useDeleteDataModelMutation = () => {
Expand All @@ -11,10 +11,12 @@ export const useDeleteDataModelMutation = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (modelPath: string) => {
const jsonSchemaPath = isXsdFile(modelPath)
const jsonSchemaPath = FileNameUtils.isXsdFile(modelPath)
? modelPath.replace('.xsd', '.schema.json')
: modelPath;
const xsdPath = isXsdFile(modelPath) ? modelPath : modelPath.replace('.schema.json', '.xsd');
const xsdPath = FileNameUtils.isXsdFile(modelPath)
? modelPath
: modelPath.replace('.schema.json', '.xsd');
queryClient.setQueryData(
[QueryKey.DataModelsJson, org, app],
(oldData: DataModelMetadata[]) => removeDataModelFromList(oldData, jsonSchemaPath),
Expand Down
5 changes: 2 additions & 3 deletions frontend/app-development/utils/metadataUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import type {
DataModelMetadataJson,
DataModelMetadataXsd,
} from 'app-shared/types/DataModelMetadata';
import { ArrayUtils, StringUtils } from '@studio/pure-functions';
import { ArrayUtils, StringUtils, FileNameUtils } from '@studio/pure-functions';
import type { MetadataOption } from '../types/MetadataOption';
import type { MetadataOptionsGroup } from '../types/MetadataOptionsGroup';
import { removeSchemaExtension } from 'app-shared/utils/filenameUtils';

/**
* Filters out items from the Xsd data list if there are items in the Json data list with the same name.
Expand Down Expand Up @@ -43,7 +42,7 @@ export const mergeJsonAndXsdData = (
* @returns The MetadataOption object.
*/
export const convertMetadataToOption = (metadata: DataModelMetadata): MetadataOption => {
let label = removeSchemaExtension(metadata.fileName);
let label = FileNameUtils.removeSchemaExtension(metadata.fileName);
if (metadata.fileType === '.xsd') {
label += ' (XSD)';
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { FileNameUtils } from './FilenameUtils';

describe('FileNameUtils', () => {
describe('removeExtension', () => {
it('Removes extension from filename if it exists', () => {
expect(FileNameUtils.removeExtension('filename.txt')).toEqual('filename');
expect(FileNameUtils.removeExtension('filename.xsd')).toEqual('filename');
expect(FileNameUtils.removeExtension('.abc')).toEqual('');
expect(FileNameUtils.removeExtension('filename.schema.json')).toEqual('filename.schema');
});

it('Removes the extension for filenames with special characters', () => {
expect(FileNameUtils.removeExtension('file name.txt')).toBe('file name');
expect(FileNameUtils.removeExtension('my-file.name$!.txt')).toBe('my-file.name$!');
expect(FileNameUtils.removeExtension('.hiddenfile.txt')).toBe('.hiddenfile');
expect(FileNameUtils.removeExtension('file123.456.txt')).toBe('file123.456');
});

it('Returns same input string if there is no extension', () => {
expect(FileNameUtils.removeExtension('filename')).toEqual('filename');
expect(FileNameUtils.removeExtension('')).toEqual('');
});

it('returns an empty string if the filename starts with dot', () => {
expect(FileNameUtils.removeExtension('.hiddenfile')).toBe('');
expect(FileNameUtils.removeExtension('.')).toBe('');
});
});

describe('removeSchemaExtension', () => {
it('Removes .schema.json extension from filename if it exists', () => {
expect(FileNameUtils.removeSchemaExtension('filename.schema.json')).toEqual('filename');
expect(FileNameUtils.removeSchemaExtension('filename.SCHEMA.JSON')).toEqual('filename');
});

it('Removes .xsd extension from filename if it exists', () => {
expect(FileNameUtils.removeSchemaExtension('filename.xsd')).toEqual('filename');
expect(FileNameUtils.removeSchemaExtension('filename.XSD')).toEqual('filename');
});

it('Returns entire input string if there is no .schema.json or .xsd extension', () => {
expect(FileNameUtils.removeSchemaExtension('filename.xml')).toEqual('filename.xml');
});
});

describe('isXsdFile', () => {
it('Returns true if filename has an XSD extension', () => {
expect(FileNameUtils.isXsdFile('filename.xsd')).toBe(true);
expect(FileNameUtils.isXsdFile('filename.XSD')).toBe(true);
});

it('Returns false if filename does not have an XSD extension', () => {
expect(FileNameUtils.isXsdFile('filename.schema.json')).toBe(false);
expect(FileNameUtils.isXsdFile('filename')).toBe(false);
});
});

describe('extractFilename', () => {
it('Returns filename if path contains a slash', () => {
expect(FileNameUtils.extractFilename('/path/to/filename')).toEqual('filename');
expect(FileNameUtils.extractFilename('/path/to/filename.json')).toEqual('filename.json');
});

it('Returns path if path does not contain a slash', () => {
expect(FileNameUtils.extractFilename('filename')).toEqual('filename');
expect(FileNameUtils.extractFilename('filename.json')).toEqual('filename.json');
});
});

describe('removeFileNameFromPath', () => {
it('Returns file path without file name', () => {
expect(FileNameUtils.removeFileNameFromPath('/path/to/filename')).toEqual('/path/to/');
expect(FileNameUtils.removeFileNameFromPath('/path/to/filename.json')).toEqual('/path/to/');
});

it('Returns file path without file name and last slash if "excludeLastSlash" is true', () => {
expect(FileNameUtils.removeFileNameFromPath('/path/to/filename', true)).toEqual('/path/to');
expect(FileNameUtils.removeFileNameFromPath('/path/to/filename.json', true)).toEqual(
'/path/to',
);
});

it('Returns empty string if path is only fileName', () => {
expect(FileNameUtils.removeFileNameFromPath('filename')).toEqual('');
expect(FileNameUtils.removeFileNameFromPath('filename.json')).toEqual('');
});

it('Returns empty string if path is only fileName and "excludeLastSlash" is true', () => {
expect(FileNameUtils.removeFileNameFromPath('filename', true)).toEqual('');
expect(FileNameUtils.removeFileNameFromPath('filename.json', true)).toEqual('');
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { StringUtils } from '@studio/pure-functions';

export class FileNameUtils {
/**
* Remove extension from filename.
* @param filename
* @returns filename without extension
*/
static removeExtension = (filename: string): string => {
const indexOfLastDot = filename.lastIndexOf('.');
return indexOfLastDot < 0 ? filename : filename.substring(0, indexOfLastDot);
};

/**
* Remove json.schema or .xsd extension from filename.
* @param filename
* @returns filename without extension if the extension is ".schema.json" or ".xsd", otherwise the filename is returned unchanged.
*/
static removeSchemaExtension = (filename: string): string =>
StringUtils.removeEnd(filename, '.schema.json', '.xsd');

/**
* Remove json.schema or .xsd extension from filename.
* @param filename
* @returns filename without extension if the extension is ".schema.json" or ".xsd", otherwise the filename is returned unchanged.
*/
static isXsdFile = (filename: string): boolean => filename.toLowerCase().endsWith('.xsd');

static extractFilename = (path: string): string => {
const indexOfLastSlash = path.lastIndexOf('/');
return indexOfLastSlash < 0 ? path : path.substring(indexOfLastSlash + 1);
};

static removeFileNameFromPath = (path: string, excludeLastSlash: boolean = false): string => {
const fileName = this.extractFilename(path);
const indexOfLastSlash = path.lastIndexOf('/');
return path.slice(
0,
path.lastIndexOf(excludeLastSlash && indexOfLastSlash > 0 ? '/' + fileName : fileName),
);
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { FileNameUtils } from './FilenameUtils';
1 change: 1 addition & 0 deletions frontend/libs/studio-pure-functions/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './ArrayUtils';
export * from './BlobDownloader';
export * from './DateUtils';
export * from './FileNameUtils';
export * from './NumberUtils';
export * from './ObjectUtils';
export * from './ScopedStorage';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import cn from 'classnames';
import { convertPureGitDiffToUserFriendlyDiff } from './FilePathUtils';
import { ChevronRightIcon } from '@studio/icons';
import { useTranslation } from 'react-i18next';
import { extractFilename, removeFileNameFromPath } from 'app-shared/utils/filenameUtils';
import { FileNameUtils } from '@studio/pure-functions';
import type { QueryStatus } from '@tanstack/react-query';

export interface FilePathProps {
Expand All @@ -20,7 +20,7 @@ export const FilePath = ({ filePath, diff, repoDiffStatus }: FilePathProps) => {
return <FilePathWithoutDiff filePath={filePath} />;
}

const fileName = extractFilename(filePath);
const fileName = FileNameUtils.extractFilename(filePath);
const linesToRender = convertPureGitDiffToUserFriendlyDiff(diff);

return (
Expand Down Expand Up @@ -56,8 +56,8 @@ type FormattedFilePathProps = {
};

const FormattedFilePath = ({ filePath }: FormattedFilePathProps) => {
const fileName = extractFilename(filePath);
const filePathWithoutName = removeFileNameFromPath(filePath, true);
const fileName = FileNameUtils.extractFilename(filePath);
const filePathWithoutName = FileNameUtils.removeFileNameFromPath(filePath, true);

return (
<>
Expand Down
Loading

0 comments on commit 77e8aa2

Please sign in to comment.