Skip to content

Commit

Permalink
fix: tests around renderText and paths
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisTowles committed Sep 26, 2022
1 parent 927443e commit e790ae2
Show file tree
Hide file tree
Showing 11 changed files with 247 additions and 85 deletions.
Binary file added playground/folder-test/test-icon1.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 0 additions & 9 deletions playground/folder-test/test.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
# Test Markdown

Test file without an image

![](2022-09-02-22-02-20.png)

![](.png)image.png




![](2022-09-03-22-03-43.png)
3 changes: 3 additions & 0 deletions playground/home.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Home Playground Markdown

Test file without an image
Binary file added playground/test-icon-root.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 12 additions & 12 deletions src/configuration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ describe('Configuration', () => {
expect(mockWorkspaceConfiguration.get(Constants.Config_ImageFolderPath)).toBe(__dirname);
})

it('check parse of default values', () => {
it('check parse of default values', async () => {


const config = parseConfigurationToConfig({
projectPath: __dirname,
editorOpenFilePath: __dirname,
const config = await parseConfigurationToConfig({
projectRootDirPath: __dirname,
editorOpenFilePath: __filename,
configuration: mockWorkspaceConfiguration,
})

Expand All @@ -35,7 +35,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: __dirname,
projectRootDirPath: __dirname,
})

// no replacement done
Expand All @@ -49,7 +49,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: __dirname,
projectRootDirPath: __dirname,
})

// should replace with folder of editor file
Expand All @@ -64,7 +64,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: __dirname,
projectRootDirPath: __dirname,
})

// should replace with folder of editor file and append another folder
Expand All @@ -81,7 +81,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: productRoot,
projectRootDirPath: productRoot,
})

// should replace with folder of editor file
Expand All @@ -96,7 +96,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: productRoot,
projectRootDirPath: productRoot,
})

// should replace with folder of editor file
Expand All @@ -112,7 +112,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: productRoot,
projectRootDirPath: productRoot,
})

// should replace with editor
Expand All @@ -129,7 +129,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: productRoot,
projectRootDirPath: productRoot,
})

let ext = path.extname(editorFile);
Expand All @@ -147,7 +147,7 @@ describe('Configuration', () => {
const alteredValue = replacePathVariable({
pathStr: originalPath,
editorOpenFilePath: editorFile,
projectRoot: productRoot,
projectRootDirPath: productRoot,
})

let ext = path.extname(editorFile);
Expand Down
41 changes: 25 additions & 16 deletions src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import { Constants } from "./constants";
import { WorkspaceConfiguration } from 'vscode';
import path from "path";
import { ILogger } from "./logger";
import { ensureFileAndGetItsDirectory } from "./folderUtil";

export interface Configuration {

readonly encodePathConfig: string;

readonly insertPatternConfig: string;
readonly showFilePathConfirmInputBox: boolean,
readonly filePathConfirmInputBoxMode: string;
readonly filePathConfirmInputBoxMode: FilePathConfirmInputBoxModeEnum;


readonly defaultImageName: string;
Expand All @@ -22,12 +23,20 @@ export interface Configuration {
// used for image url prefix and suffix
readonly imageUriPathPrefix: string;
readonly imageUriPathSuffix: string;
readonly projectRootPath: string;
readonly editorOpenFileFolderPath: string;
readonly projectRootDirPath: string;
readonly editorOpenFolderPath: string;

}

export const parseConfigurationToConfig = ({ projectPath, editorOpenFilePath, configuration }: { projectPath: string; editorOpenFilePath: string; configuration: WorkspaceConfiguration }): Configuration => {
export enum FilePathConfirmInputBoxModeEnum {
ONLY_NAME = "onlyName",
FULL_PATH = "fullPath",
}

export const parseConfigurationToConfig = async ({ projectRootDirPath, editorOpenFilePath, configuration }: { projectRootDirPath: string; editorOpenFilePath: string; configuration: WorkspaceConfiguration }): Promise<Configuration> => {

const editorOpenFolderPath = await ensureFileAndGetItsDirectory(editorOpenFilePath)


// Luxon Values used in ImageName = https://moment.github.io/luxon/#/formatting?id=table-of-tokens
let defaultImageName = configuration.get<string>(Constants.Config_DefaultImageName, "yyyy-LL-dd-HH-mm-ss");
Expand All @@ -44,7 +53,7 @@ export const parseConfigurationToConfig = ({ projectPath, editorOpenFilePath, co
let imageNameSuffix = configuration.get<string>(Constants.Config_ImageNameSuffix, '');

let showFilePathConfirmInputBox = configuration.get<boolean>(Constants.Config_ShowFilePathConfirmInputBox, true);
let filePathConfirmInputBoxMode = configuration.get<string>(Constants.Config_FilePathConfirmInputBoxMode, "inputBox");
let filePathConfirmInputBoxMode = configuration.get<FilePathConfirmInputBoxModeEnum>(Constants.Config_FilePathConfirmInputBoxMode, FilePathConfirmInputBoxModeEnum.FULL_PATH);


if (imageFolderPath.length !== imageFolderPath.trim().length) {
Expand All @@ -53,13 +62,13 @@ export const parseConfigurationToConfig = ({ projectPath, editorOpenFilePath, co
}


defaultImageName = replacePathVariable({ pathStr: defaultImageName, projectRoot: projectPath, editorOpenFilePath: editorOpenFilePath });
imageFolderPath = replacePathVariable({ pathStr: imageFolderPath, projectRoot: projectPath, editorOpenFilePath: editorOpenFilePath });
imageNamePrefix = replacePathVariable({ pathStr: imageNamePrefix, projectRoot: projectPath, editorOpenFilePath: editorOpenFilePath });
imageNameSuffix = replacePathVariable({ pathStr: imageNameSuffix, projectRoot: projectPath, editorOpenFilePath: editorOpenFilePath });
insertPatternConfig = replacePathVariable({ pathStr: insertPatternConfig, projectRoot: projectPath, editorOpenFilePath: editorOpenFilePath });

defaultImageName = replacePathVariable({ pathStr: defaultImageName, projectRootDirPath: projectRootDirPath, editorOpenFilePath: editorOpenFilePath });
imageFolderPath = replacePathVariable({ pathStr: imageFolderPath, projectRootDirPath: projectRootDirPath, editorOpenFilePath: editorOpenFilePath });
imageNamePrefix = replacePathVariable({ pathStr: imageNamePrefix, projectRootDirPath: projectRootDirPath, editorOpenFilePath: editorOpenFilePath });
imageNameSuffix = replacePathVariable({ pathStr: imageNameSuffix, projectRootDirPath: projectRootDirPath, editorOpenFilePath: editorOpenFilePath });
insertPatternConfig = replacePathVariable({ pathStr: insertPatternConfig, projectRootDirPath: projectRootDirPath, editorOpenFilePath: editorOpenFilePath });


const config: Configuration = {

// load other config
Expand All @@ -79,8 +88,8 @@ export const parseConfigurationToConfig = ({ projectPath, editorOpenFilePath, co

imageUriPathPrefix: imageUriPathPrefix,
imageUriPathSuffix: imageUriPathSuffix,
projectRootPath: projectPath,
editorOpenFileFolderPath: path.dirname(editorOpenFilePath),
projectRootDirPath: projectRootDirPath,
editorOpenFolderPath: editorOpenFolderPath,

};

Expand All @@ -90,17 +99,17 @@ export const parseConfigurationToConfig = ({ projectPath, editorOpenFilePath, co

// Variables that can be used to replace values in config paths
const PATH_VARIABLE_CURRENT_FILE_DIR = /\$\{currentFileDir\}/g;
const PATH_VARIABLE_PROJECT_ROOT = /\$\{projectRoot\}/g;
const PATH_VARIABLE_PROJECT_ROOT_DIR = /\$\{projectRoot\}/g;
const PATH_VARIABLE_CURRENT_FILE_NAME = /\$\{currentFileName\}/g;
const PATH_VARIABLE_CURRENT_FILE_NAME_WITHOUT_EXT = /\$\{currentFileNameWithoutExt\}/g;

export const replacePathVariable = ({ pathStr, projectRoot, editorOpenFilePath }: { pathStr: string; projectRoot: string; editorOpenFilePath: string }): string => {
export const replacePathVariable = ({ pathStr, projectRootDirPath, editorOpenFilePath }: { pathStr: string; projectRootDirPath: string; editorOpenFilePath: string }): string => {
let currentFileDir = path.dirname(editorOpenFilePath);
let ext = path.extname(editorOpenFilePath);
let fileName = path.basename(editorOpenFilePath);
let fileNameWithoutExt = path.basename(editorOpenFilePath, ext);

pathStr = pathStr.replace(PATH_VARIABLE_PROJECT_ROOT, projectRoot);
pathStr = pathStr.replace(PATH_VARIABLE_PROJECT_ROOT_DIR, projectRootDirPath);
pathStr = pathStr.replace(PATH_VARIABLE_CURRENT_FILE_DIR, currentFileDir);
pathStr = pathStr.replace(PATH_VARIABLE_CURRENT_FILE_NAME, fileName);
pathStr = pathStr.replace(PATH_VARIABLE_CURRENT_FILE_NAME_WITHOUT_EXT, fileNameWithoutExt);
Expand Down
30 changes: 26 additions & 4 deletions src/folderUtil.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { createImageDirWithImagePath, ensurePngAddedToFileName, makeImagePath, } from './folderUtil'
import { createImageDirWithImagePath, ensureFileAndGetItsDirectory, ensurePathIsDirectory, ensurePngAddedToFileName, makeImagePath, } from './folderUtil'
import * as path from 'path';

import * as fse from 'fs-extra';
Expand Down Expand Up @@ -28,7 +28,7 @@ describe('FolderUtil', () => {
})

it('create folder 01', async () => {
const testPath = path.join(__dirname, '..', 'dist', 'not-real-folder', 'notRealImage.png').toString();
const testPath = path.join(__dirname, '..', 'playground', 'folder-test', 'test-to-remove', 'notRealImage.png').toString();
const testDir = path.dirname(testPath);


Expand All @@ -37,7 +37,7 @@ describe('FolderUtil', () => {
// clean up created folder
let folderStat = await fse.stat(testDir)
if (folderStat.isDirectory()) {
await fse.rmdir(testDir);
await fse.rmdir(testDir, { recursive: true });
}
})
});
Expand Down Expand Up @@ -67,6 +67,28 @@ describe('FolderUtil', () => {
})


makeImagePath
it('ensureFileAndGetItsDirectory', async () => {
const dirName = await ensureFileAndGetItsDirectory(__filename);
expect(dirName).toBe(__dirname)
})


it('ensureFileAndGetItsDirectory - if given directory', async () => {

await expect(ensureFileAndGetItsDirectory(__dirname)).rejects.toThrow('Not a file but instead a directory:');
})


it('ensurePathIsDirectory', async () => {
const dirName = await ensurePathIsDirectory(__dirname);
expect(dirName).toBe(__dirname)
})


it('ensurePathIsDirectory - if given fileName', async () => {

await expect(ensurePathIsDirectory(__filename)).rejects.toThrow('Path is file instead of a directory:');
})


})
33 changes: 33 additions & 0 deletions src/folderUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,39 @@
import * as path from 'path';
import * as fse from 'fs-extra';


export const ensureFileAndGetItsDirectory = async (filePath: string): Promise<string> => {

if (await fse.pathExists (filePath)) {

let folderStat = await fse.stat(filePath)
if (folderStat.isDirectory()){
throw new Error(`Not a file but instead a directory: ${filePath}`);
}
} else {
throw new Error(`File not found: ${filePath}`);
}
return path.dirname(filePath);

}


export const ensurePathIsDirectory = async (dirPath: string): Promise<string> => {

if (await fse.pathExists (dirPath)) {

let folderStat = await fse.stat(dirPath)
if (!folderStat.isDirectory()){
throw new Error(`Path is file instead of a directory: ${dirPath}`);
}
} else {
throw new Error(`Path not found: ${dirPath}`);
}
return dirPath;

}


export const createImageDirWithImagePath = async (imagePath: string): Promise<string> => {

let imageDir = path.dirname(imagePath);
Expand Down
28 changes: 16 additions & 12 deletions src/paster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,15 @@ import { DateTime } from 'luxon';
import { win32CreateImageWithPowershell } from './osTools/win32';
import { macCreateImageWithAppleScript } from './osTools/macOS';
import { SaveClipboardImageToFileResult } from './dto/SaveClipboardImageToFileResult';
import { Configuration, parseConfigurationToConfig } from './configuration';
import { Configuration, FilePathConfirmInputBoxModeEnum, parseConfigurationToConfig } from './configuration';
import { Constants } from './constants';
import { renderTextWithImagePath } from './renderTextWithImagePath';


export class Paster {


static FILE_PATH_CONFIRM_INPUT_BOX_MODE_ONLY_NAME = "onlyName";
static FILE_PATH_CONFIRM_INPUT_BOX_MODE_PULL_PATH = "fullPath";


public static async paste(logger: ILogger): Promise<void> {
// get current edit file path
Expand All @@ -36,11 +35,11 @@ export class Paster {
}

let editorOpenFilePath = fileUri.fsPath;
let projectPath = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders[0].uri.fsPath : '';
let projectRootDirPath = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders[0].uri.fsPath : '';

logger.log(`projectPath = ${projectPath}`);
logger.log(`projectPath = ${projectRootDirPath}`);
logger.log(`editorOpenFilePath = ${editorOpenFilePath}`);
if (projectPath === '')
if (projectRootDirPath === '')
return;


Expand All @@ -56,8 +55,8 @@ export class Paster {
let config: Configuration;
try {

config = parseConfigurationToConfig({
projectPath,
config = await parseConfigurationToConfig({
projectRootDirPath,
editorOpenFilePath,
configuration: vscode.workspace.getConfiguration(Constants.ConfigurationName)
});
Expand Down Expand Up @@ -112,7 +111,7 @@ export class Paster {
return;
}

imagePath = renderTextWithImagePath({ languageId: editor.document.languageId, config, imageFilePath: imagePath, logger });
imagePath = await renderTextWithImagePath({ languageId: editor.document.languageId, config, imageFilePath: imagePath, logger });

editor.edit((edit) => {
let current = editor.selection;
Expand Down Expand Up @@ -151,7 +150,7 @@ export class Paster {
imageFileName = ensurePngAddedToFileName(imageFileName);

let filePathOrName;
if (config.filePathConfirmInputBoxMode == Paster.FILE_PATH_CONFIRM_INPUT_BOX_MODE_PULL_PATH) {
if (config.filePathConfirmInputBoxMode === FilePathConfirmInputBoxModeEnum.FULL_PATH) {
filePathOrName = makeImagePath({ fileName: imageFileName, imageFolderPath: config.imageFolderPath, editorOpenFilePath: editorOpenFilePath });
} else {
filePathOrName = imageFileName;
Expand All @@ -166,10 +165,15 @@ export class Paster {

if (userEnteredFileName) {
userEnteredFileName = ensurePngAddedToFileName(userEnteredFileName);

if (config.filePathConfirmInputBoxMode == Paster.FILE_PATH_CONFIRM_INPUT_BOX_MODE_ONLY_NAME) {


logger.debug(`userEnteredFileName = ${userEnteredFileName}`);
if (config.filePathConfirmInputBoxMode === FilePathConfirmInputBoxModeEnum.ONLY_NAME) {
filePathOrName = makeImagePath({ fileName: userEnteredFileName, imageFolderPath: config.imageFolderPath, editorOpenFilePath: editorOpenFilePath });
} else {
filePathOrName = userEnteredFileName
}

}

} else {
Expand Down

0 comments on commit e790ae2

Please sign in to comment.