|
| 1 | +import { ISource } from '@alicloud/ros-cdk-ossdeployment/lib/source.cdk'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import * as ossDeployment from '@alicloud/ros-cdk-ossdeployment'; |
| 4 | +import path from 'node:path'; |
| 5 | +import JSZip from 'jszip'; |
| 6 | +import { logger } from './logger'; |
| 7 | +import { ActionContext, CdkAssets } from '../types'; |
| 8 | +import { get, isEmpty } from 'lodash'; |
| 9 | +import OSS from 'ali-oss'; |
| 10 | + |
| 11 | +const buildAssets = (rootPath: string, relativePath: string): Array<ISource> => { |
| 12 | + const location = path.resolve(rootPath, relativePath); |
| 13 | + if (!fs.existsSync(location)) { |
| 14 | + throw new Error(`Location: ${location} is not exists!`); |
| 15 | + } |
| 16 | + if (fs.lstatSync(location).isFile()) { |
| 17 | + return [ |
| 18 | + ossDeployment.Source.asset( |
| 19 | + location, |
| 20 | + {}, |
| 21 | + relativePath.substring(0, relativePath.lastIndexOf('/') + 1), |
| 22 | + ), |
| 23 | + ]; |
| 24 | + } |
| 25 | + return fs |
| 26 | + .readdirSync(location) |
| 27 | + .map((file) => buildAssets(rootPath, `${relativePath}/${file}`.replace(/^\//, ''))) |
| 28 | + .flat(); |
| 29 | +}; |
| 30 | + |
| 31 | +export const getAssets = (location: string): Array<ISource> => { |
| 32 | + return buildAssets(location, ''); |
| 33 | +}; |
| 34 | + |
| 35 | +const assembleFiles = (folder: string, zip: JSZip) => { |
| 36 | + const files = fs.readdirSync(folder); |
| 37 | + files.forEach((file) => { |
| 38 | + const filePath = path.join(folder, file); |
| 39 | + if (fs.lstatSync(filePath).isFile()) { |
| 40 | + const content = fs.readFileSync(filePath); |
| 41 | + zip.file(file, content); |
| 42 | + } else { |
| 43 | + const subZip = zip.folder(file); |
| 44 | + if (subZip) { |
| 45 | + assembleFiles(filePath, subZip); |
| 46 | + } |
| 47 | + } |
| 48 | + }); |
| 49 | +}; |
| 50 | + |
| 51 | +const zipAssets = async (assetsPath: string) => { |
| 52 | + const zip = new JSZip(); |
| 53 | + assembleFiles(assetsPath, zip); |
| 54 | + const zipPath = `${assetsPath.replace(/\/$/, '').trim()}.zip`; |
| 55 | + await zip |
| 56 | + .generateAsync({ type: 'nodebuffer' }) |
| 57 | + .then((content) => { |
| 58 | + fs.writeFileSync(zipPath, content); |
| 59 | + logger.info(`Folder compressed to: ${zipPath}`); |
| 60 | + }) |
| 61 | + .catch((e) => { |
| 62 | + logger.error(`Failed to compress folder: ${e}`); |
| 63 | + throw e; |
| 64 | + }); |
| 65 | + return zipPath; |
| 66 | +}; |
| 67 | + |
| 68 | +const constructAssets = async ({ files, rootPath }: CdkAssets, region: string) => { |
| 69 | + const assets = await Promise.all( |
| 70 | + Object.entries(files) |
| 71 | + .filter(([, fileItem]) => !fileItem.source.path.endsWith('.template.json')) |
| 72 | + .map(async ([, fileItem]) => { |
| 73 | + let sourcePath = `${rootPath}/${fileItem.source.path}`; |
| 74 | + if (fileItem.source.packaging === 'zip') { |
| 75 | + sourcePath = await zipAssets(`${rootPath}/${fileItem.source.path}`); |
| 76 | + } |
| 77 | + return { |
| 78 | + bucketName: get( |
| 79 | + fileItem, |
| 80 | + 'destinations.current_account-current_region.bucketName', |
| 81 | + '', |
| 82 | + ).replace('${ALIYUN::Region}', region), |
| 83 | + source: sourcePath, |
| 84 | + objectKey: get(fileItem, 'destinations.current_account-current_region.objectKey'), |
| 85 | + }; |
| 86 | + }), |
| 87 | + ); |
| 88 | + |
| 89 | + return !isEmpty(assets) ? assets : undefined; |
| 90 | +}; |
| 91 | + |
| 92 | +const ensureBucketExits = async (bucketName: string, ossClient: OSS) => |
| 93 | + await ossClient.getBucketInfo(bucketName).catch((err) => { |
| 94 | + if (err.code === 'NoSuchBucket') { |
| 95 | + logger.info(`Bucket: ${bucketName} not exists, creating...`); |
| 96 | + return ossClient.putBucket(bucketName, { |
| 97 | + storageClass: 'Standard', |
| 98 | + acl: 'private', |
| 99 | + dataRedundancyType: 'LRS', |
| 100 | + } as OSS.PutBucketOptions); |
| 101 | + } else { |
| 102 | + throw err; |
| 103 | + } |
| 104 | + }); |
| 105 | + |
| 106 | +export const publishAssets = async (assets: CdkAssets, context: ActionContext) => { |
| 107 | + const constructedAssets = await constructAssets(assets, context.region); |
| 108 | + |
| 109 | + if (!constructedAssets?.length) { |
| 110 | + logger.info('No assets to publish, skipped!'); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + const bucketName = constructedAssets[0].bucketName; |
| 115 | + |
| 116 | + const client = new OSS({ |
| 117 | + region: `oss-${context.region}`, |
| 118 | + accessKeyId: context.accessKeyId, |
| 119 | + accessKeySecret: context.accessKeySecret, |
| 120 | + bucket: bucketName, |
| 121 | + }); |
| 122 | + |
| 123 | + await ensureBucketExits(bucketName, client); |
| 124 | + |
| 125 | + const headers = { |
| 126 | + 'x-oss-storage-class': 'Standard', |
| 127 | + 'x-oss-object-acl': 'private', |
| 128 | + 'x-oss-forbid-overwrite': 'false', |
| 129 | + } as OSS.PutObjectOptions; |
| 130 | + |
| 131 | + await Promise.all( |
| 132 | + constructedAssets.map(async ({ source, objectKey }) => { |
| 133 | + await client.put(objectKey, path.normalize(source), { headers }); |
| 134 | + logger.info(`Upload file: ${source}) to bucket: ${bucketName} successfully!`); |
| 135 | + }), |
| 136 | + ); |
| 137 | + |
| 138 | + return bucketName; |
| 139 | +}; |
0 commit comments