🎨 Unified code style

This commit is contained in:
Tw93
2023-06-24 20:17:52 +08:00
parent 07938f02f4
commit 00c01a9638
23 changed files with 107 additions and 117 deletions

View File

@@ -1,17 +1,17 @@
import path from 'path';
import fsExtra from "fs-extra";
import chalk from "chalk";
import fsExtra from 'fs-extra';
import chalk from 'chalk';
import prompts from 'prompts';
import { PakeAppOptions } from '@/types';
import { checkRustInstalled, installRust } from '@/helpers/rust';
import { mergeConfig } from "@/helpers/merge";
import { mergeConfig } from '@/helpers/merge';
import tauriConfig from '@/helpers/tauriConfig';
import { npmDirectory } from '@/utils/dir';
import { getSpinner } from "@/utils/info";
import { getSpinner } from '@/utils/info';
import { shellExec } from '@/utils/shell';
import { isChinaDomain } from '@/utils/ip';
import { IS_MAC } from "@/utils/platform";
import { IS_MAC } from '@/utils/platform';
import logger from '@/options/logger';
export default abstract class BaseBuilder {
@@ -23,8 +23,8 @@ export default abstract class BaseBuilder {
async prepare() {
if (!IS_MAC) {
logger.info('⚙︎ The first use requires installing system dependencies.');
logger.info('⚙︎ See more in https://tauri.app/v1/guides/getting-started/prerequisites.');
logger.info(' The first use requires installing system dependencies.');
logger.info(' See more in https://tauri.app/v1/guides/getting-started/prerequisites.');
}
if (!checkRustInstalled()) {
@@ -42,14 +42,14 @@ export default abstract class BaseBuilder {
}
}
const isChina = await isChinaDomain("www.npmjs.com");
const isChina = await isChinaDomain('www.npmjs.com');
const spinner = getSpinner('Installing package...');
if (isChina) {
logger.info("⚙︎ Located in China, using npm/rsProxy CN mirror.");
const rustProjectDir = path.join(npmDirectory, 'src-tauri', ".cargo");
logger.info('✺ Located in China, using npm/rsProxy CN mirror.');
const rustProjectDir = path.join(npmDirectory, 'src-tauri', '.cargo');
await fsExtra.ensureDir(rustProjectDir);
const projectCnConf = path.join(npmDirectory, "src-tauri", "rust_proxy.toml");
const projectConf = path.join(rustProjectDir, "config");
const projectCnConf = path.join(npmDirectory, 'src-tauri', 'rust_proxy.toml');
const projectConf = path.join(rustProjectDir, 'config');
await fsExtra.copy(projectCnConf, projectConf);
await shellExec(`cd "${npmDirectory}" && npm install --registry=https://registry.npmmirror.com`);
} else {
@@ -89,7 +89,7 @@ export default abstract class BaseBuilder {
abstract getFileName(): string;
protected getBuildCommand(): string {
return "npm run build";
return 'npm run build';
}
protected getBasePath(): string {
@@ -97,11 +97,6 @@ export default abstract class BaseBuilder {
}
protected getBuildAppPath(npmDirectory: string, fileName: string, fileType: string): string {
return path.join(
npmDirectory,
this.getBasePath(),
fileType.toLowerCase(),
`${fileName}.${fileType}`
);
return path.join(npmDirectory, this.getBasePath(), fileType.toLowerCase(), `${fileName}.${fileType}`);
}
}

View File

@@ -3,22 +3,21 @@ import { PakeAppOptions } from '@/types';
import tauriConfig from '@/helpers/tauriConfig';
export default class LinuxBuilder extends BaseBuilder {
constructor(options: PakeAppOptions) {
super(options);
}
getFileName(): string {
const { name } = this.options;
const arch = process.arch === "x64" ? "amd64" : process.arch;
const arch = process.arch === 'x64' ? 'amd64' : process.arch;
return `${name}_${tauriConfig.package.version}_${arch}`;
}
// Customize it, considering that there are all targets.
async build(url: string) {
const targetTypes = ["deb", "appimage"];
const targetTypes = ['deb', 'appimage'];
for (const target of targetTypes) {
if (this.options.targets === target || this.options.targets === "all") {
if (this.options.targets === target || this.options.targets === 'all') {
await this.buildAndCopy(url, target);
}
}

View File

@@ -5,7 +5,7 @@ import BaseBuilder from './BaseBuilder';
export default class MacBuilder extends BaseBuilder {
constructor(options: PakeAppOptions) {
super(options);
this.options.targets = "dmg";
this.options.targets = 'dmg';
}
getFileName(): string {
@@ -14,7 +14,7 @@ export default class MacBuilder extends BaseBuilder {
if (this.options.multiArch) {
arch = 'universal';
} else {
arch = process.arch === "arm64" ? "aarch64" : process.arch;
arch = process.arch === 'arm64' ? 'aarch64' : process.arch;
}
return `${name}_${tauriConfig.package.version}_${arch}`;
}

View File

@@ -5,7 +5,7 @@ import tauriConfig from '@/helpers/tauriConfig';
export default class WinBuilder extends BaseBuilder {
constructor(options: PakeAppOptions) {
super(options);
this.options.targets = "msi";
this.options.targets = 'msi';
}
getFileName(): string {

5
bin/cli.ts vendored
View File

@@ -33,14 +33,13 @@ program
.option('--debug', 'Debug mode', DEFAULT.debug)
.version(packageJson.version, '-v, --version', 'Output the current version')
.action(async (url: string, options: PakeCliOptions) => {
await checkUpdateTips();
if (!url) {
program.outputHelp((str) => {
program.outputHelp(str => {
return str
.split('\n')
.filter((line) => !/((-h,|--help)|((-v|-V),|--version))\s+.+$/.test(line))
.filter(line => !/((-h,|--help)|((-v|-V),|--version))\s+.+$/.test(line))
.join('\n');
});
process.exit(0);

19
bin/helpers/merge.ts vendored
View File

@@ -5,11 +5,7 @@ import { npmDirectory } from '@/utils/dir';
import logger from '@/options/logger';
import { PakeAppOptions, PlatformMap } from '@/types';
export async function mergeConfig(
url: string,
options: PakeAppOptions,
tauriConf: any,
) {
export async function mergeConfig(url: string, options: PakeAppOptions, tauriConf: any) {
const {
width,
height,
@@ -61,7 +57,7 @@ export async function mergeConfig(
const filesToCopyBack = ['cli.js', 'about_pake.html'];
await Promise.all(
filesToCopyBack.map((file) =>
filesToCopyBack.map(file =>
fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file)),
),
);
@@ -72,8 +68,7 @@ export async function mergeConfig(
} else {
tauriConf.pake.windows[0].url_type = 'web';
// Set the secure domain for calling window.__TAURI__ to the application domain that has been set.
tauriConf.tauri.security.dangerousRemoteDomainIpcAccess[0].domain =
new URL(url).hostname;
tauriConf.tauri.security.dangerousRemoteDomainIpcAccess[0].domain = new URL(url).hostname;
}
const platformMap: PlatformMap = {
@@ -95,7 +90,8 @@ export async function mergeConfig(
delete tauriConf.tauri.bundle.deb.files;
const validTargets = ['all', 'deb', 'appimage'];
if (validTargets.includes(options.targets)) {
tauriConf.tauri.bundle.targets = options.targets === 'all' ? ['deb', 'appimage'] : [options.targets];
tauriConf.tauri.bundle.targets =
options.targets === 'all' ? ['deb', 'appimage'] : [options.targets];
} else {
logger.warn(
`✼ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`,
@@ -165,9 +161,7 @@ export async function mergeConfig(
trayIconPath = `png/${name.toLowerCase()}${iconExt}`;
await fsExtra.copy(systemTrayIcon, trayIcoPath);
} else {
logger.warn(
`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`,
);
logger.warn(`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`);
logger.warn(`✼ Default system tray icon will be used.`);
}
} catch {
@@ -192,7 +186,6 @@ export async function mergeConfig(
const pakeConfigPath = path.join(npmDirectory, 'src-tauri/pake.json');
await fsExtra.writeJson(pakeConfigPath, tauriConf.pake, { spaces: 4 });
let tauriConf2 = JSON.parse(JSON.stringify(tauriConf));
delete tauriConf2.pake;
delete tauriConf2.tauri.bundle;

6
bin/helpers/rust.ts vendored
View File

@@ -1,13 +1,13 @@
import chalk from "chalk";
import chalk from 'chalk';
import shelljs from 'shelljs';
import { getSpinner } from "@/utils/info";
import { getSpinner } from '@/utils/info';
import { IS_WIN } from '@/utils/platform';
import { shellExec } from '@/utils/shell';
import { isChinaDomain } from '@/utils/ip';
export async function installRust() {
const isInChina = await isChinaDomain("sh.rustup.rs");
const isInChina = await isChinaDomain('sh.rustup.rs');
const rustInstallScriptForMac = isInChina
? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh'
: "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";

View File

@@ -7,10 +7,10 @@ import LinuxConf from '../../src-tauri/tauri.linux.conf.json';
const platformConfigs = {
win32: WinConf,
darwin: MacConf,
linux: LinuxConf
linux: LinuxConf,
};
const {platform} = process;
const { platform } = process;
// @ts-ignore
const platformConfig = platformConfigs[platform];
@@ -21,7 +21,7 @@ let tauriConfig = {
},
package: CommonConf.package,
build: CommonConf.build,
pake: pakeConf
pake: pakeConf,
};
export default tauriConfig;

11
bin/options/icon.ts vendored
View File

@@ -1,14 +1,13 @@
import path from 'path';
import axios from 'axios';
import fsExtra from "fs-extra";
import fsExtra from 'fs-extra';
import chalk from 'chalk';
import { dir } from 'tmp-promise';
import logger from './logger';
import { npmDirectory } from '@/utils/dir';
import { IS_LINUX, IS_WIN } from '@/utils/platform';
import { getSpinner } from "@/utils/info";
import { getSpinner } from '@/utils/info';
import { fileTypeFromBuffer } from 'file-type';
import { PakeAppOptions } from '@/types';
@@ -21,7 +20,11 @@ export async function handleIcon(options: PakeAppOptions) {
}
} else {
logger.warn('✼ No icon given, default in use. For a custom icon, use --icon option.');
const iconPath = IS_WIN ? 'src-tauri/png/icon_256.ico' : IS_LINUX ? 'src-tauri/png/icon_512.png' : 'src-tauri/icons/icon.icns';
const iconPath = IS_WIN
? 'src-tauri/png/icon_256.ico'
: IS_LINUX
? 'src-tauri/png/icon_512.png'
: 'src-tauri/icons/icon.icns';
return path.join(npmDirectory, iconPath);
}
}

11
bin/options/index.ts vendored
View File

@@ -1,5 +1,5 @@
import fsExtra from "fs-extra";
import logger from "@/options/logger";
import fsExtra from 'fs-extra';
import logger from '@/options/logger';
import { handleIcon } from './icon';
import { getDomain } from '@/utils/url';
@@ -20,14 +20,17 @@ function isValidName(name: string, platform: NodeJS.Platform): boolean {
return !!name && reg.test(name);
}
export default async function handleOptions(options: PakeCliOptions, url: string): Promise<PakeAppOptions> {
export default async function handleOptions(
options: PakeCliOptions,
url: string,
): Promise<PakeAppOptions> {
const { platform } = process;
const isActions = process.env.GITHUB_ACTIONS;
let name = options.name;
const pathExists = await fsExtra.pathExists(url);
if (!options.name) {
const defaultName = pathExists ? "" : resolveAppName(url, platform);
const defaultName = pathExists ? '' : resolveAppName(url, platform);
const promptMessage = 'Enter your application name';
const namePrompt = await promptText(promptMessage, defaultName);
name = namePrompt || defaultName;

10
bin/options/logger.ts vendored
View File

@@ -3,20 +3,20 @@ import log from 'loglevel';
const logger = {
info(...msg: any[]) {
log.info(...msg.map((m) => chalk.white(m)));
log.info(...msg.map(m => chalk.white(m)));
},
debug(...msg: any[]) {
log.debug(...msg);
},
error(...msg: any[]) {
log.error(...msg.map((m) => chalk.red(m)));
log.error(...msg.map(m => chalk.red(m)));
},
warn(...msg: any[]) {
log.info(...msg.map((m) => chalk.yellow(m)));
log.info(...msg.map(m => chalk.yellow(m)));
},
success(...msg: any[]) {
log.info(...msg.map((m) => chalk.green(m)));
}
log.info(...msg.map(m => chalk.green(m)));
},
};
export default logger;

1
bin/types.ts vendored
View File

@@ -1,4 +1,3 @@
export interface PlatformMap {
[key: string]: any;
}

5
bin/utils/dir.ts vendored
View File

@@ -5,7 +5,4 @@ import { fileURLToPath } from 'url';
const currentModulePath = fileURLToPath(import.meta.url);
// Resolve the parent directory of the current module
export const npmDirectory = path.join(
path.dirname(currentModulePath),
'..'
);
export const npmDirectory = path.join(path.dirname(currentModulePath), '..');

30
bin/utils/info.ts vendored
View File

@@ -1,14 +1,11 @@
import crypto from 'crypto';
import prompts from "prompts";
import ora from "ora";
import prompts from 'prompts';
import ora from 'ora';
import chalk from 'chalk';
// Generates an identifier based on the given URL.
export function getIdentifier(url: string) {
const postFixHash = crypto.createHash('md5')
.update(url)
.digest('hex')
.substring(0, 6);
const postFixHash = crypto.createHash('md5').update(url).digest('hex').substring(0, 6);
return `pake-${postFixHash}`;
}
@@ -28,17 +25,12 @@ export function capitalizeFirstLetter(string: string) {
export function getSpinner(text: string) {
const loadingType = {
"interval": 80,
"frames": [
"✦",
"✶",
"✺",
"✵",
"✸",
"✴︎",
"✹",
"✺",
]
}
return ora({ text: `${chalk.blue(text)}\n`, spinner: loadingType, color: 'blue' }).start();
interval: 80,
frames: ['✦', '✶', '✺', '✵', '✸', '✹', '✺'],
};
return ora({
text: `${chalk.cyan(text)}\n`,
spinner: loadingType,
color: 'cyan',
}).start();
}

5
bin/utils/ip.ts vendored
View File

@@ -13,13 +13,13 @@ const ping = async (host: string) => {
// Prevent timeouts from affecting user experience.
const requestPromise = new Promise<number>((resolve, reject) => {
const req = http.get(`http://${ip.address}`, (res) => {
const req = http.get(`http://${ip.address}`, res => {
const delay = new Date().getTime() - start.getTime();
res.resume();
resolve(delay);
});
req.on('error', (err) => {
req.on('error', err => {
reject(err);
});
});
@@ -33,7 +33,6 @@ const ping = async (host: string) => {
return Promise.race([requestPromise, timeoutPromise]);
};
async function isChinaDomain(domain: string): Promise<boolean> {
try {
const [ip] = await resolve(domain);

6
bin/utils/shell.ts vendored
View File

@@ -1,9 +1,9 @@
import shelljs from "shelljs";
import { npmDirectory } from "./dir";
import shelljs from 'shelljs';
import { npmDirectory } from './dir';
export function shellExec(command: string) {
return new Promise<number>((resolve, reject) => {
shelljs.exec(command, { async: true, silent: false, cwd: npmDirectory }, (code) => {
shelljs.exec(command, { async: true, silent: false, cwd: npmDirectory }, code => {
if (code === 0) {
resolve(0);
} else {

3
bin/utils/url.ts vendored
View File

@@ -9,7 +9,7 @@ export function getDomain(inputUrl: string): string | null {
const parsed = psl.parse(url.hostname);
// If domain is available, split it and return the SLD.
if ("domain" in parsed && parsed.domain) {
if ('domain' in parsed && parsed.domain) {
return parsed.domain.split('.')[0];
} else {
return null;
@@ -19,7 +19,6 @@ export function getDomain(inputUrl: string): string | null {
}
}
// Appends 'https://' protocol to the URL if not present.
export function appendProtocol(inputUrl: string): string {
try {