Skip to content

Commit

Permalink
Upgrade glob, rename helper methods, fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kmturley committed Jan 22, 2024
1 parent 4da4fee commit d9948eb
Show file tree
Hide file tree
Showing 11 changed files with 493 additions and 97 deletions.
443 changes: 411 additions & 32 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"@vscode/sudo-prompt": "^9.3.1",
"adm-zip": "^0.4.16",
"fs-extra": "^10.1.0",
"glob": "^7.1.6",
"glob": "^10.3.6",
"node-fetch": "^2.6.1",
"nodejs-fs-utils": "^1.2.5",
"readline-sync": "^1.4.10",
Expand Down
12 changes: 6 additions & 6 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import fetch from 'node-fetch';
import { log } from './utils';

async function get(url: string): Promise<string> {
async function apiBuffer(url: string): Promise<Buffer> {
log('⤓', url);
return fetch(url).then((res: any) => res.text());
return fetch(url).then((res: any) => res.buffer());
}

async function getJSON(url: string): Promise<any> {
async function apiJson(url: string): Promise<any> {
log('⤓', url);
return fetch(url).then((res: any) => res.json());
}

async function getRaw(url: string): Promise<Buffer> {
async function apiText(url: string): Promise<string> {
log('⤓', url);
return fetch(url).then((res: any) => res.buffer());
return fetch(url).then((res: any) => res.text());
}

export { get, getJSON, getRaw };
export { apiBuffer, apiJson, apiText };
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
fileDelete,
fileExists,
fileJsonCreate,
fileJsonLoad,
fileReadJson,
} from './file';
import { configDefaults } from './config-defaults';

Expand All @@ -21,7 +21,7 @@ dirCreate(appDir);
if (!fileExists(CONFIG_FILE_PATH)) {
fileJsonCreate(CONFIG_FILE_PATH, configDefaults(appDir, dirPlugins(), dirPresets(), dirProjects()));
}
const config: ConfigInterface = fileJsonLoad(CONFIG_FILE_PATH);
const config: ConfigInterface = fileReadJson(CONFIG_FILE_PATH);

function configDelete(): boolean | void {
return fileDelete(CONFIG_FILE_PATH);
Expand Down
90 changes: 52 additions & 38 deletions src/file.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
import AdmZip from 'adm-zip';
import { execFileSync, execSync } from 'child_process';
import fs from 'fs-extra';
import glob from 'glob';
import {
chmodSync,
existsSync,
mkdirSync,
moveSync,
readdirSync,
readFileSync,
rmSync,
statSync,
unlinkSync,
writeFileSync,
} from 'fs-extra';
import { globSync } from 'glob';
import os from 'os';
import path from 'path';
import { PlatformsSupported } from './types/config';
Expand Down Expand Up @@ -59,7 +70,7 @@ function dirContains(dirParent: string, dirChild: string): boolean {
function dirCreate(dirPath: string): string | boolean {
if (!dirExists(dirPath)) {
log('+', dirPath);
fs.mkdirSync(dirPath, { recursive: true });
mkdirSync(dirPath, { recursive: true });
return dirPath;
}
return false;
Expand All @@ -68,29 +79,29 @@ function dirCreate(dirPath: string): string | boolean {
function dirDelete(dirPath: string): void | boolean {
if (dirExists(dirPath)) {
log('-', dirPath);
return fs.rmSync(dirPath, { recursive: true });
return rmSync(dirPath, { recursive: true });
}
return false;
}

function dirEmpty(dirPath: string): boolean {
const files: string[] = fs.readdirSync(dirPath);
const files: string[] = readdirSync(dirPath);
return files.length === 0 || (files.length === 1 && files[0] === '.DS_Store');
}

function dirExists(dirPath: string): boolean {
return fs.existsSync(dirPath);
return existsSync(dirPath);
}

function dirIs(dirPath: string): boolean {
return fs.statSync(dirPath).isDirectory();
return statSync(dirPath).isDirectory();
}

function dirMove(dirPath: string, newPath: string): void | boolean {
if (dirExists(dirPath)) {
log('-', dirPath);
log('+', newPath);
return fs.moveSync(dirPath, newPath, { overwrite: true });
return moveSync(dirPath, newPath, { overwrite: true });
}
return false;
}
Expand Down Expand Up @@ -129,20 +140,17 @@ function dirProjects(): string {

function dirRead(dirPath: string, options?: any): string[] {
log('⌕', dirPath);
// Glob returns relative paths with forward slashes on Windows
// Convert every path to a Windows compatible path
// https://github.com/isaacs/node-glob/issues/419
// Glob now expects forward slashes on Windows
// Convert backslashes from path.join() to forwardslashes
if (process.platform === 'win32') {
return glob.sync(dirPath, options).map((subDirPath: string) => {
return subDirPath.split('/').join(path.sep);
});
dirPath = dirPath.replace(/\\/g, '/');
}
return glob.sync(dirPath, options);
return globSync(dirPath, options);
}

function dirRename(oldPath: string, newPath: string): void | boolean {
if (dirExists(oldPath)) {
return fs.moveSync(oldPath, newPath, { overwrite: true });
return moveSync(oldPath, newPath, { overwrite: true });
}
return false;
}
Expand All @@ -168,51 +176,38 @@ function fileAdd(filePath: string, fileName: string, fileType: string, json: any

function fileCreate(filePath: string, data: string | Buffer): void {
log('+', filePath);
return fs.writeFileSync(filePath, data);
return writeFileSync(filePath, data);
}

function fileDate(filePath: string): Date {
return fs.statSync(filePath).mtime;
return statSync(filePath).mtime;
}

function fileDelete(filePath: string): boolean | void {
if (fileExists(filePath)) {
log('-', filePath);
return fs.unlinkSync(filePath);
return unlinkSync(filePath);
}
return false;
}

function fileExec(filePath: string): void {
return fs.chmodSync(filePath, '755');
return chmodSync(filePath, '755');
}

function fileExists(filePath: string): boolean {
return fs.existsSync(filePath);
return existsSync(filePath);
}

function fileJsonCreate(filePath: string, data: object): void {
return fileCreate(filePath, JSON.stringify(data, null, 2));
}

function fileJsonLoad(filePath: string): any {
if (fileExists(filePath)) {
log('⎋', filePath);
return JSON.parse(fs.readFileSync(filePath).toString());
}
return false;
}

function fileLoad(filePath: string): Buffer {
log('⎋', filePath);
return fs.readFileSync(filePath);
}

function fileMove(dirPath: string, newPath: string): void | boolean {
if (fileExists(dirPath)) {
log('-', dirPath);
log('+', newPath);
return fs.moveSync(dirPath, newPath, { overwrite: true });
return moveSync(dirPath, newPath, { overwrite: true });
}
return false;
}
Expand All @@ -234,6 +229,24 @@ function fileOpen(filePath: string): Buffer {
return execSync(`${command} "${filePath}"`);
}

function fileRead(filePath: string): Buffer {
log('⎋', filePath);
return readFileSync(filePath);
}

function fileReadJson(filePath: string): any {
if (fileExists(filePath)) {
log('⎋', filePath);
return JSON.parse(readFileSync(filePath).toString());
}
return false;
}

function fileReadString(filePath: string): string {
log('⎋', filePath);
return readFileSync(filePath).toString();
}

function fileSize(filePath: string): number {
return fsUtils.fsizeSync(filePath);
}
Expand Down Expand Up @@ -277,7 +290,7 @@ function runCliAsAdmin(args: string): Promise<string> {

function zipCreate(filesPath: string, zipPath: string): void {
if (fileExists(zipPath)) {
fs.unlinkSync(zipPath);
unlinkSync(zipPath);
}
const zip: AdmZip = new AdmZip();
const pathList: string[] = dirRead(filesPath);
Expand Down Expand Up @@ -325,10 +338,11 @@ export {
fileExec,
fileExists,
fileJsonCreate,
fileJsonLoad,
fileLoad,
fileMove,
fileOpen,
fileRead,
fileReadJson,
fileReadString,
fileSize,
isAdmin,
runCliAsAdmin,
Expand Down
14 changes: 8 additions & 6 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ import {
fileDate,
fileExists,
fileJsonCreate,
fileJsonLoad,
fileReadJson,
fileMove,
isAdmin,
runCliAsAdmin,
zipCreate,
zipExtract,
} from './file';
import { getJSON, getRaw } from './api';
import { apiBuffer, apiJson } from './api';
import {
getPlatform,
isTests,
Expand Down Expand Up @@ -64,7 +64,7 @@ async function pluginCreate(dir: string, template: keyof PluginTemplate = 'stein
if (dirExists(dir)) {
throw Error(`Directory already exists: ${dir}`);
}
const data: Buffer = await getRaw(configGet('pluginTemplate').replace('${template}', template));
const data: Buffer = await apiBuffer(configGet('pluginTemplate').replace('${template}', template));
const tempDir: string = path.join(dirAppData(), 'studiorack', 'temp', template);
dirCreate(tempDir);
zipExtract(data, tempDir);
Expand Down Expand Up @@ -112,7 +112,7 @@ async function pluginGetLocal(id: string, version?: string): Promise<PluginLocal

async function pluginsGet(type: string = 'index'): Promise<PluginPack> {
const url: string = configGet('pluginRegistry').replace('${type}', type);
return await getJSON(url).then((data) => {
return await apiJson(url).then((data) => {
return data.objects;
});
}
Expand All @@ -128,7 +128,7 @@ async function pluginsGetLocal(): Promise<PluginLocal[]> {
const pluginsFound: { [property: string]: PluginLocal } = {};
pluginPaths.forEach((pluginPath: string) => {
const relativePath: string = pluginPath.replace(configGet('pluginFolder') + path.sep, '');
let plugin: PluginLocal = fileJsonLoad(`${pathGetWithoutExt(pluginPath)}.json`);
let plugin: PluginLocal = fileReadJson(`${pathGetWithoutExt(pluginPath)}.json`);
if (!plugin) {
// If there is no metadata json file, attempt to auto create one using validator
if (pathGetExt(pluginPath) === 'vst3') {
Expand All @@ -149,6 +149,7 @@ async function pluginsGetLocal(): Promise<PluginLocal[]> {
const pluginId: string = `${plugin.repo}/${plugin.id}`;
if (pluginsFound[pluginId]) {
pluginsFound[pluginId].paths.push(pluginPath);
pluginsFound[pluginId].paths.sort();
} else {
pluginsFound[pluginId] = plugin;
}
Expand Down Expand Up @@ -199,7 +200,7 @@ async function pluginInstall(id: string, version?: string): Promise<PluginLocal>
throw Error(`Unsupported file type ${pluginExt}`);
}
// Download the plugin data
const pluginData: Buffer = await getRaw(pluginUrl);
const pluginData: Buffer = await apiBuffer(pluginUrl);
const [pluginOwner, pluginRepo] = plugin.repo.split('/');
const dirTemp: string = path.join(dirAppData(), 'studiorack', 'downloads', pluginOwner, pluginRepo, plugin.id);
dirCreate(dirTemp);
Expand Down Expand Up @@ -256,6 +257,7 @@ async function pluginInstall(id: string, version?: string): Promise<PluginLocal>
plugin.paths.push(pluginPath);
}
}
plugin.paths.sort();
plugin.status = 'installed';
return plugin;
}
Expand Down
6 changes: 3 additions & 3 deletions src/project.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'path';
import { configGet } from './config';
import { dirCreate, dirRead, fileAdd, fileDate, fileJsonCreate, fileJsonLoad, fileOpen } from './file';
import { dirCreate, dirRead, fileAdd, fileDate, fileJsonCreate, fileReadJson, fileOpen } from './file';
import {
pathGetDirectory,
pathGetExt,
Expand Down Expand Up @@ -100,7 +100,7 @@ async function projectsGetLocal(): Promise<ProjectLocal[]> {
projectPaths.forEach((projectPath: string) => {
if (projectPath.includes('/Backup/')) return;
const relativePath: string = projectPath.replace(configGet('projectFolder') + path.sep, '');
let project: any = fileJsonLoad(`${pathGetWithoutExt(projectPath)}.json`);
let project: any = fileReadJson(`${pathGetWithoutExt(projectPath)}.json`);
if (!project) {
project = projectValidate(projectPath, { files: true, json: true });
}
Expand Down Expand Up @@ -131,7 +131,7 @@ async function projectInstall(dir: string, id?: string, version?: string): Promi
}

function projectLoad(dir: string): ProjectLocal {
const projectJson: ProjectLocal = fileJsonLoad(dir);
const projectJson: ProjectLocal = fileReadJson(dir);
if (projectJson && !projectJson.plugins) {
projectJson.plugins = {};
}
Expand Down
6 changes: 3 additions & 3 deletions src/tool.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { execSync } from 'child_process';
import path from 'path';

import { dirAppData, dirExists, dirRead, fileExec, fileExists, zipExtract } from './file';
import { dirAppData, dirRead, fileExec, fileExists, zipExtract } from './file';
import { getPlatform, log } from './utils';
import { getRaw } from './api';
import { apiBuffer } from './api';
import { configGet } from './config';
import { ConfigInterface } from './types/config';
import { Tools } from './types/tool';
Expand Down Expand Up @@ -40,7 +40,7 @@ function toolGetPath(type: keyof Tools): string {
async function toolInstall(type: keyof Tools): Promise<string> {
if (!toolInstalled(type)) {
const toolUrl: string = configGet(`${type}Url` as keyof ConfigInterface).replace('${platform}', getPlatform());
const data: Buffer = await getRaw(toolUrl);
const data: Buffer = await apiBuffer(toolUrl);
zipExtract(data, toolBinDir);
fileExec(toolGetPath(type));
}
Expand Down
8 changes: 4 additions & 4 deletions tests/api.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { get, getJSON, getRaw } from '../src/api';
import { apiBuffer, apiJson, apiText } from '../src/api';

const API_URL: string = 'https://jsonplaceholder.typicode.com/todos/1';
const API_TEXT: string = `{
Expand All @@ -21,13 +21,13 @@ const API_BUFFER: Buffer = Buffer.from([
]);

test('Get plain text', async () => {
expect(await get(API_URL)).toEqual(API_TEXT);
expect(await apiText(API_URL)).toEqual(API_TEXT);
});

test('Get json', async () => {
expect(await getJSON(API_URL)).toEqual(API_JSON);
expect(await apiJson(API_URL)).toEqual(API_JSON);
});

test('Get raw buffer', async () => {
expect(await getRaw(API_URL)).toEqual(API_BUFFER);
expect(await apiBuffer(API_URL)).toEqual(API_BUFFER);
});
4 changes: 2 additions & 2 deletions tests/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import {
fileExec,
fileExists,
fileJsonCreate,
fileJsonLoad,
fileLoad,
fileRead,
fileReadJson,
fileMove,
fileOpen,
fileSize,
Expand Down
Loading

0 comments on commit d9948eb

Please sign in to comment.