Skip to content

Commit

Permalink
fix: cleanup configuration load
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisTowles committed Sep 25, 2022
1 parent a9aa08a commit f1da289
Show file tree
Hide file tree
Showing 13 changed files with 258 additions and 173 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@ logs
node_modules
temp
*.vsix


playground/*.png
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"cSpell.words": [
"luxon",
"upath"
]
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@
},
"pasteImage.defaultName": {
"type": "string",
"default": "Y-MM-DD-HH-mm-ss",
"description": "The default image file name. The value of this config will be pass to the 'format' function of moment library(a js time manipulation library), you can read document https://momentjs.com/docs/#/displaying/format/ for advanced usage."
"default": "yyyy-LL-mm-HH-mm-ss",
"description": "The default image file name. The value of this config will be pass to the 'format' function of moment library(a js time manipulation library), you can read document https://moment.github.io/luxon/#/formatting?id=table-of-tokens for advanced usage."
},
"pasteImage.namePrefix": {
"type": "string",
Expand Down
118 changes: 118 additions & 0 deletions src/configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { Constants } from "./constants";
import vscode from 'vscode';
import path from "path";
import { ILogger } from "./logger";

export interface Configuration {
prefixConfig: string;
suffixConfig: string;
forceUnixStyleSeparatorConfig: string;
encodePathConfig: string;
namePrefixConfig: string;
nameSuffixConfig: string;
insertPatternConfig: string;
showFilePathConfirmInputBox: boolean,
filePathConfirmInputBoxMode: string;
defaultNameConfig: string;
folderPathConfig: string;
basePathConfig: string;

}

const PATH_VARIABLE_CURRENT_FILE_DIR = /\$\{currentFileDir\}/g;
const PATH_VARIABLE_PROJECT_ROOT = /\$\{projectRoot\}/g;
const PATH_VARIABLE_CURRENT_FILE_NAME = /\$\{currentFileName\}/g;
const PATH_VARIABLE_CURRENT_FILE_NAME_WITHOUT_EXT = /\$\{currentFileNameWithoutExt\}/g;



export const loadConfiguration = ({ projectPath, filePath }: { projectPath: string; filePath: string;}): Configuration => {
const configuration = vscode.workspace.getConfiguration(Constants.ConfigurationName)


let defaultNameConfig = configuration['defaultName']
let folderPathConfig = configuration['path']
let basePathConfig = configuration['basePath']
let prefixConfig = configuration['prefix'];
let suffixConfig = configuration['suffix'];
let forceUnixStyleSeparatorConfig = configuration['forceUnixStyleSeparator'];

let encodePathConfig = configuration['encodePath'];
let namePrefixConfig = configuration['namePrefix'];
let nameSuffixConfig = configuration['nameSuffix'];
let insertPatternConfig = configuration['insertPattern'];
let showFilePathConfirmInputBox= configuration['showFilePathConfirmInputBox'] || false;
let filePathConfirmInputBoxMode = configuration['filePathConfirmInputBoxMode'];


// load config pasteImage.defaultName

if (!defaultNameConfig) {
defaultNameConfig = "yyyy-LL-dd-HH-mm-ss"
}

// load config pasteImage.path

if (!folderPathConfig) {
folderPathConfig = "${currentFileDir}";
}
if (folderPathConfig.length !== folderPathConfig.trim().length) {
const errorMsg = `The config ${Constants.ConfigurationName}.path = '${folderPathConfig}' is invalid. please check your config.`;
throw new Error(errorMsg);
}

if (!basePathConfig) {
basePathConfig = "";
}

if (basePathConfig.length !== basePathConfig.trim().length) {
const errorMsg = `The config pasteImage.path = '${basePathConfig}' is invalid. please check your config.`;
throw new Error(errorMsg);
}

forceUnixStyleSeparatorConfig = !!forceUnixStyleSeparatorConfig;

defaultNameConfig = replacePathVariable(defaultNameConfig, projectPath, filePath, (x) => `[${x}]`);
folderPathConfig = replacePathVariable(folderPathConfig, projectPath, filePath);
basePathConfig = replacePathVariable(basePathConfig, projectPath, filePath);
namePrefixConfig = replacePathVariable(namePrefixConfig, projectPath, filePath);
nameSuffixConfig = replacePathVariable(nameSuffixConfig, projectPath, filePath);
insertPatternConfig = replacePathVariable(insertPatternConfig, projectPath, filePath);


const config: Configuration = {

// load other config
defaultNameConfig: defaultNameConfig,
prefixConfig: prefixConfig,
suffixConfig: suffixConfig,
forceUnixStyleSeparatorConfig: forceUnixStyleSeparatorConfig,
encodePathConfig: encodePathConfig,
namePrefixConfig: namePrefixConfig,
nameSuffixConfig: nameSuffixConfig,
insertPatternConfig: insertPatternConfig,
showFilePathConfirmInputBox: showFilePathConfirmInputBox,
filePathConfirmInputBoxMode: filePathConfirmInputBoxMode,
folderPathConfig: folderPathConfig,
basePathConfig: basePathConfig,

};

return config;

}


export const replacePathVariable = (pathStr: string, projectRoot: string, curFilePath: string, postFunction: (val: string) => string = (x) => x): string => {
let currentFileDir = path.dirname(curFilePath);
let ext = path.extname(curFilePath);
let fileName = path.basename(curFilePath);
let fileNameWithoutExt = path.basename(curFilePath, ext);

pathStr = pathStr.replace(PATH_VARIABLE_PROJECT_ROOT, postFunction(projectRoot));
pathStr = pathStr.replace(PATH_VARIABLE_CURRENT_FILE_DIR, postFunction(currentFileDir));
pathStr = pathStr.replace(PATH_VARIABLE_CURRENT_FILE_NAME, postFunction(fileName));
pathStr = pathStr.replace(PATH_VARIABLE_CURRENT_FILE_NAME_WITHOUT_EXT, postFunction(fileNameWithoutExt));
return pathStr;
}

8 changes: 8 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

export class Constants {
public static ExtensionName = 'vscode-markdown-paste-image';
public static vsCommandName = 'extension.pasteImage'; // match the command in package.json
public static ConfigurationName = 'pasteImage'; // match the command in package.json
public static ChannelLogName = 'Markdown Paste Image'; // match the command in package.json

}
37 changes: 23 additions & 14 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, makeImagePath, } from './folderUtil'
import { createImageDirWithImagePath, ensurePngAddedToFileName, makeImagePath, } from './folderUtil'
import * as path from 'path';

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

describe('makeImagePath', () => {

const testPath = path.join(__dirname, '..', 'src', 'test').toString();
it('image page 01', async () => {


expect(await makeImagePath({
folderPathFromConfig: "docs/img",
fileName: 'notRealFile.png',
filePath: testPath
})).contain('/src/docs/img/notRealFile.png')
})
const testPath = path.join(__dirname, '..', 'src', 'test').toString();
it('makeImagePath', async () => {

});

expect(await makeImagePath({
folderPathConfig: "docs/img",
fileName: 'notRealFile.png',
filePath: testPath
})).contain('/src/docs/img/notRealFile.png')
})


it('ensurePngAddedToFileName - add .png', async () => {
expect(ensurePngAddedToFileName('notRealFile')).toBe('notRealFile.png')
})

it('ensurePngAddedToFileName - already had', async () => {
expect(ensurePngAddedToFileName('file.png')).toBe('file.png')
})

it('ensurePngAddedToFileName - already had but not lower case', async () => {
expect(ensurePngAddedToFileName('file.PnG')).toBe('file.PnG')
})

})
17 changes: 12 additions & 5 deletions src/folderUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,24 @@ export const createImageDirWithImagePath = async (imagePath: string): Promise<st
* create directory for image when directory does not exist
*/

export const makeImagePath = ({ folderPathFromConfig, fileName, filePath }: { folderPathFromConfig: string; fileName: string; filePath: string; }): string => {
export const makeImagePath = ({ folderPathConfig, fileName, filePath }: { folderPathConfig: string; fileName: string; filePath: string; }): string => {
// image output path
let folderPath = path.dirname(filePath);
let imagePath = "";

// generate image path
if (path.isAbsolute(folderPathFromConfig)) {
imagePath = path.join(folderPathFromConfig, fileName);
if (path.isAbsolute(folderPathConfig)) {
imagePath = path.join(folderPathConfig, fileName);
} else {
imagePath = path.join(folderPath, folderPathFromConfig, fileName);
imagePath = path.join(folderPath, folderPathConfig, fileName);
}

return imagePath;
}
}


export const ensurePngAddedToFileName = (userEnteredFileName: string): string => {
if (!userEnteredFileName.toLowerCase().endsWith('.png'))
userEnteredFileName += '.png';
return userEnteredFileName;
}
11 changes: 4 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import vscode from 'vscode';
import { Constants } from './constants';
import { Logger } from './logger';
import { Paster } from './paster';

export function activate(context: vscode.ExtensionContext) {

const logger = new Logger();
logger.log('Congratulations, your extension "vscode-markdown-paste-image" is now active!');
logger.log(`Congratulations, your extension "${Constants.ExtensionName}" is now active!`);

// const config = workspace.getConfiguration('pasteImage')

let disposable = vscode.commands.registerCommand('extension.pasteImage', async () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
// log.showInformationMessage('Markdown Image Paste test!');

let disposable = vscode.commands.registerCommand(Constants.vsCommandName, async () => {

try {
await Paster.paste(logger);
} catch (ex) {
Expand Down
6 changes: 2 additions & 4 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { DateTime } from 'luxon';
import { OutputChannel, window } from 'vscode'

const padLeft = (nr: number, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);

import { Constants } from './constants';
export interface ILogger {
debug(...args: any[]): void;
log(...args: any[]) : void;
Expand All @@ -16,7 +14,7 @@ export class Logger implements ILogger {
readonly isDebug: boolean;

constructor() {
this.channel = window.createOutputChannel('Markdown Paste Image')
this.channel = window.createOutputChannel(Constants.ChannelLogName)
this.isDebug = process.env.NODE_ENV === 'development'
}

Expand Down
10 changes: 6 additions & 4 deletions src/osTools/linux.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@ import * as fse from 'fs-extra';
import { ILogger } from "../logger";
import { SaveClipboardImageToFileResult } from "../dto/SaveClipboardImageToFileResult";



export const linuxCreateImageWithXClip = async ({ imagePath, logger }: { imagePath: string; logger: ILogger; }): Promise<SaveClipboardImageToFileResult> =>{
let scriptPath = path.join(__dirname, '../res/linux.sh');

if(! await fse.pathExists(scriptPath)) {
logger.showErrorMessage(`Script file not found: ${scriptPath}`);
const errorMsg = `Script file not found: ${scriptPath}`
logger.showErrorMessage(errorMsg);
throw new Error(errorMsg);
}

return new Promise<SaveClipboardImageToFileResult>((resolve, reject) => {


let outputData: string = '';

Expand Down
34 changes: 17 additions & 17 deletions src/osTools/mac-os.ts → src/osTools/macOS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,40 @@ import * as fse from 'fs-extra';
import { ILogger } from "../logger";
import { SaveClipboardImageToFileResult } from "../dto/SaveClipboardImageToFileResult";

export const macCreateImageWithAppleScript = async ({ imagePath, logger }: { imagePath: string; logger: ILogger; }): Promise<SaveClipboardImageToFileResult> =>{

return new Promise<SaveClipboardImageToFileResult>(async (resolve, reject) => {
export const macCreateImageWithAppleScript = async ({ imagePath, logger }: { imagePath: string; logger: ILogger; }): Promise<SaveClipboardImageToFileResult> => {

// Mac
let scriptPath = path.join(__dirname, '../../res/mac.applescript');
// Mac
let scriptPath = path.join(__dirname, '../res/mac.applescript');


if(! await fse.pathExists(scriptPath)) {
logger.showErrorMessage(`Script file not found: ${scriptPath}`);
}
if (! await fse.pathExists(scriptPath)) {
const errorMsg = `Script file not found: ${scriptPath}`
logger.showErrorMessage(errorMsg);
throw new Error(errorMsg);
}

return new Promise<SaveClipboardImageToFileResult>(async (resolve, reject) => {

let ascript = spawn('osascript', [scriptPath, imagePath]);
ascript.on('error', function (e) {
let appleScript = spawn('osascript', [scriptPath, imagePath]);
appleScript.on('error', function (e) {
logger.showErrorMessage(e.message);
reject(e);
});
ascript.on('exit', function (code, signal) {
appleScript.on('exit', function (code, signal) {
// console.log('exit',code,signal);
});
ascript.stdout.on('data', function (data: Buffer) {

appleScript.stdout.on('data', function (data: Buffer) {

resolve({
success: true,
noImageInClipboard: false,
imagePath: imagePath,
scriptOutput: [data.toString().trim()],

});
});



});
}

0 comments on commit f1da289

Please sign in to comment.