import fs from 'fs';
import path from 'path';
import axios from 'axios';
import AWS from 'aws-sdk';
export async function handler(event) {
try {
// GitHub 웹훅 이벤트 데이터 가져오기
const eventData = JSON.parse(JSON.stringify(event));
// 필요한 데이터 추출
const repositoryName = eventData.repository.name;
const repositoryUrl = eventData.repository.html_url;
const commitId = eventData.after;
// 웹사이트 배포 로직 작성
const bucketName = 'YOUR_BUCKET_NAME';
const specificFolder = 'BUILD_FOLDER_PATH';
await uploadWebsiteFolderToS3(bucketName, specificFolder);
// 배포 완료 메시지 출력
console.log(`Website deployed for repository: ${repositoryName}`);
console.log(`Commit ID: ${commitId}`);
console.log(`Website URL: ${repositoryUrl}`);
return {
statusCode: 200,
body: 'Website deployed successfully'
};
} catch (error) {
console.error('Error deploying website:', error);
return {
statusCode: 500,
body: 'Error deploying website'
};
}
}
// 특정 폴더 내의 파일들을 S3에 업로드하는 함수
async function uploadWebsiteFolderToS3(bucketName, specificFolder) {
const fileList = await listFiles(specificFolder);
// 파일을 순회하며 S3에 업로드
for (const file of fileList) {
const fileContent = fs.readFileSync(file.path);
const s3Params = {
Bucket: bucketName,
Key: file.relativePath,
Body: fileContent
};
// AWS.S3 객체를 직접 사용
await new AWS.S3().putObject(s3Params).promise();
}
}
// 특정 폴더 내의 파일 목록을 가져오는 함수
async function listFiles(specificFolder) {
const fileList = [];
// GitHub API를 사용하여 특정 폴더의 파일 목록 가져오기
const apiUrl = `https://api.github.com/repos/{owner}/{repo}/contents/${specificFolder}`;
const githubAccessToken = 'YOUR_GITHUB_ACCESS_TOKEN'; // GitHub 액세스 토큰을 설정해야 합니다
const options = {
headers: {
'User-Agent': 'AWS Lambda',
'Authorization': `Bearer ${githubAccessToken}`
}
};
const response = await axios.get(apiUrl, options);
const items = response.data;
// 각 파일에 대해 로컬 경로와 상대 경로를 설정하고 목록에 추가
for (const item of items) {
if (item.type === 'file') {
const fileUrl = item.download_url;
const fileName = path.basename(fileUrl);
const fileRelativePath = path.join(specificFolder, fileName);
const localFilePath = path.join(tempDir, fileName);
const fileResponse = await axios.get(fileUrl, { responseType: 'arraybuffer' });
await fs.promises.writeFile(localFilePath, fileResponse.data);
fileList.push({
path: localFilePath,
relativePath: fileRelativePath
});
} else if (item.type === 'dir') {
const subFolder = item.path;
const subFiles = await listFiles(subFolder);
fileList.push(...subFiles);
}
}
return fileList;
}