index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const core = require('@actions/core');
  2. const S3 = require('aws-sdk/clients/s3');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const shortid = require('shortid');
  6. const klawSync = require('klaw-sync');
  7. const slash = require('slash');
  8. const { lookup } = require('mime-types');
  9. const AWS_KEY_ID = core.getInput('aws_key_id', {
  10. required: true
  11. });
  12. const SECRET_ACCESS_KEY = core.getInput('aws_secret_access_key', {
  13. required: true
  14. });
  15. const BUCKET = core.getInput('aws_bucket', {
  16. required: true
  17. });
  18. const SOURCE_DIR = core.getInput('source_dir', {
  19. required: true
  20. });
  21. const DESTINATION_DIR = core.getInput('destination_dir', {
  22. required: false
  23. });
  24. const s3 = new S3({
  25. accessKeyId: AWS_KEY_ID,
  26. secretAccessKey: SECRET_ACCESS_KEY
  27. });
  28. const destinationDir = DESTINATION_DIR === '/' ? shortid() : DESTINATION_DIR;
  29. const paths = klawSync(SOURCE_DIR, {
  30. nodir: true
  31. });
  32. function upload(params) {
  33. return new Promise(resolve => {
  34. s3.upload(params, (err, data) => {
  35. if (err) core.error(err);
  36. core.info(`uploaded - ${data.Key}`);
  37. core.info(`located - ${data.Location}`);
  38. resolve(data.Location);
  39. });
  40. });
  41. }
  42. function run() {
  43. const sourceDir = slash(path.join(process.cwd(), SOURCE_DIR));
  44. return Promise.all(
  45. paths.map(p => {
  46. const fileStream = fs.createReadStream(p.path);
  47. const bucketPath = slash(path.join(destinationDir, slash(path.relative(sourceDir, p.path))));
  48. const params = {
  49. Bucket: BUCKET,
  50. ACL: 'public-read',
  51. Body: fileStream,
  52. Key: bucketPath,
  53. ContentType: lookup(p.path) || 'text/plain'
  54. };
  55. return upload(params);
  56. })
  57. );
  58. }
  59. run()
  60. .then(locations => {
  61. core.info(`object key - ${destinationDir}`);
  62. core.info(`object locations - ${locations}`);
  63. core.setOutput('object_key', destinationDir);
  64. core.setOutput('object_locations', locations);
  65. })
  66. .catch(err => {
  67. core.error(err);
  68. core.setFailed(err.message);
  69. });