add envision-cli 0.0.6

This commit is contained in:
2024-11-29 13:32:58 +08:00
parent 35cec990c6
commit 2145fca826
5 changed files with 171 additions and 23 deletions

View File

@@ -1,22 +1,23 @@
import fs from 'fs/promises';
import fs, { createReadStream } from 'fs';
import path from 'path';
import * as tar from 'tar';
import glob from 'fast-glob';
import { program, Command } from '@/program.ts';
import { getConfig } from '@/module/index.ts';
import { getBaseURL, getConfig } from '@/module/index.ts';
import { fileIsExist } from '@/uitls/file.ts';
import ignore from 'ignore';
import FormData from 'form-data';
// 查找文件(忽略大小写)
async function findFileInsensitive(targetFile: string): Promise<string | null> {
const files = await fs.readdir('.');
const files = fs.readdirSync('.');
const matchedFile = files.find((file) => file.toLowerCase() === targetFile.toLowerCase());
return matchedFile || null;
}
// 递归收集文件信息
async function collectFileInfo(filePath: string, baseDir = '.'): Promise<any[]> {
const stats = await fs.stat(filePath);
const stats = fs.statSync(filePath);
const relativePath = path.relative(baseDir, filePath);
if (stats.isFile()) {
@@ -24,7 +25,7 @@ async function collectFileInfo(filePath: string, baseDir = '.'): Promise<any[]>
}
if (stats.isDirectory()) {
const files = await fs.readdir(filePath);
const files = fs.readdirSync(filePath);
const results = await Promise.all(files.map((file) => collectFileInfo(path.join(filePath, file), baseDir)));
return results.flat();
}
@@ -37,7 +38,7 @@ async function loadNpmIgnore(cwd: string): Promise<ignore.Ignore> {
const ig = ignore.default();
try {
const content = await fs.readFile(npmIgnorePath, 'utf-8');
const content = fs.readFileSync(npmIgnorePath, 'utf-8');
ig.add(content);
} catch (err) {
console.warn('.npmignore not found, using default ignore rules');
@@ -68,14 +69,14 @@ const pack = async () => {
const cwd = process.cwd();
const collection: Record<string, any> = {};
const packageJsonPath = path.join(cwd, 'package.json');
if (!(await fileIsExist(packageJsonPath))) {
if (!fileIsExist(packageJsonPath)) {
console.error('package.json not found');
return;
}
let packageJson;
try {
const packageContent = await fs.readFile(packageJsonPath, 'utf-8');
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
packageJson = JSON.parse(packageContent);
} catch (error) {
console.error('Invalid package.json:', error);
@@ -139,6 +140,11 @@ const pack = async () => {
} catch (error) {
console.error('Error creating tarball:', error);
}
const readme = await findFileInsensitive('README.md');
if (readme) {
const readmeContent = fs.readFileSync(readme, 'utf-8');
collection.readme = readmeContent;
}
return { collection, outputFilePath };
};
const packByIgnore = async () => {
@@ -148,7 +154,7 @@ const packByIgnore = async () => {
const packageJsonPath = path.join(cwd, 'package.json');
let packageJson;
try {
const packageContent = await fs.readFile(packageJsonPath, 'utf-8');
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
packageJson = JSON.parse(packageContent);
} catch (error) {
console.error('Invalid package.json:', error);
@@ -195,6 +201,11 @@ const packByIgnore = async () => {
} catch (error) {
console.error('Error creating tarball:', error);
}
const readme = await findFileInsensitive('README.md');
if (readme) {
const readmeContent = fs.readFileSync(readme, 'utf-8');
collection.readme = readmeContent;
}
return { collection, outputFilePath };
};
const publishCommand = new Command('publish')
@@ -204,13 +215,66 @@ const publishCommand = new Command('publish')
.action(async (options) => {
const { key, version } = options;
const config = await getConfig();
const form = new FormData();
console.log('发布逻辑实现', { key, version, config });
});
const uploadFiles = async (filePath: string, collection: any): Promise<any> => {
const config = await getConfig();
const form = new FormData();
const filename = path.basename(filePath);
try {
console.log('upload file', filePath);
form.append('file', createReadStream(filePath));
} catch (error) {
console.error('Error reading file:', error);
return;
}
form.append('collection', JSON.stringify(collection));
console.log('upload file', filename);
return await new Promise((resolve) => {
const _baseURL = getBaseURL();
const url = new URL(_baseURL);
console.log('upload url', url.hostname, url.protocol, url.port);
form.submit(
{
path: '/api/micro-app/upload',
host: url.hostname,
protocol: url.protocol as any,
port: url.port,
method: 'POST',
headers: {
Authorization: 'Bearer ' + config.token,
...form.getHeaders(),
},
},
(err, res) => {
if (err) {
console.error('Error uploading file:', err.message);
return;
}
console.log('upload success');
// 处理服务器响应
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
try {
const res = JSON.parse(body);
console.log('upload success', res);
resolve(res);
} catch (e) {
resolve({ code: 500, message: body });
}
});
},
);
});
};
const packCommand = new Command('pack')
.description('打包应用, 默认使用 package.json 中的 files 字段')
.option('-i, --ignore', '使用 .npmignore 文件模式去忽略文件进行打包, 不需要package.json中的files字段')
.option('-p, --publish', '打包并发布')
.action(async (opts) => {
let value: { collection: Record<string, any>; outputFilePath: string };
if (opts.ignore) {
@@ -218,6 +282,11 @@ const packCommand = new Command('pack')
} else {
value = await pack();
}
if (opts.publish && value?.collection) {
console.log('\n\npublish');
const { collection, outputFilePath } = value;
await uploadFiles(outputFilePath, collection);
}
//
});