File size: 4,359 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Attention: use all node builtin modules except `ali-oss`
// Must keep our ak/sk safe

const OSS = require('ali-oss');
const path = require('path');
const fs = require('fs');
const assert = require('assert');

// node scripts/visual-regression/upload.js ./visualRegressionReport.tar.gz --ref=pr-id
// node scripts/visual-regression/upload.js ./imageSnapshots.tar.gz --ref=master-commitId

const args = process.argv.slice(2);
if (args.length < 2) {
  console.error('Usage: node scripts/visual-regression/upload.js <tarFilePath> --ref=<refValue>');
  process.exit(1);
}

const ALI_OSS_BUCKET = 'antd-visual-diff';

function retry(promise, retries, delay = 3000) {
  return new Promise((resolve, reject) => {
    const attempt = () => {
      promise.then(resolve).catch((error) => {
        if (retries > 0) {
          setTimeout(() => {
            attempt();
          }, delay);
          retries--;
        } else {
          reject(error);
        }
      });
    };

    attempt();
  });
}

/**
 * Extract the tar file path and ref value from the cli arguments
 * @param {string[]} cliArgs
 */
function parseArgs(cliArgs) {
  const filepath = cliArgs[0];
  let refValue = '';

  for (let i = 1; i < cliArgs.length; i++) {
    if (cliArgs[i].startsWith('--ref=')) {
      refValue = cliArgs[i].substring(6);
      break;
    }
  }

  assert(filepath, 'filepath is required');
  assert(refValue, 'refValue is required');

  return [filepath, refValue];
}

async function walkDir(dirPath) {
  const fileList = [];

  const files = await fs.promises.readdir(dirPath);

  for (const file of files) {
    const filePath = path.join(dirPath, file);
    const fileStat = fs.statSync(filePath);

    if (fileStat.isDirectory()) {
      // Recursively call this func for subdirs

      fileList.push(...(await walkDir(filePath)));
    } else {
      fileList.push(filePath);
    }
  }

  return fileList;
}

/**
 *
 * @param {import('ali-oss')} client
 * @param {*} filePath
 * @param {*} refValue
 */
async function uploadFile(client, filePath, refValue) {
  const headers = {
    // https://help.aliyun.com/zh/oss/user-guide/object-acl
    'x-oss-object-acl': 'public-read',
    // https://help.aliyun.com/zh/oss/developer-reference/prevent-objects-from-being-overwritten-by-objects-that-have-the-same-names-3
    'x-oss-forbid-overwrite': 'false',
    'Content-Disposition': 'inline',
  };
  // Set content-type to allow individual preview of images
  if (path.extname(filePath) === '.png') {
    headers['Content-Type'] = 'image/png';
  }

  console.log('Uploading file: %s', filePath);
  try {
    const targetFilePath = path.relative(process.cwd(), filePath);
    const r1 = await client.put(`${refValue}/${targetFilePath}`, filePath, {
      headers,
      timeout: 60000 * 2,
    });
    console.log('Uploading file successfully: %s', r1.name);
  } catch (err) {
    console.error('Uploading file failed: %s', err);
    throw err;
  }
}

async function boot() {
  const [fileOrFolderName, refValue] = parseArgs(args);

  // check if exists
  const workspacePath = path.resolve(process.cwd(), fileOrFolderName);

  if (!fs.existsSync(workspacePath)) {
    console.error('File not exists: %s', workspacePath);
    process.exit(1);
  }

  const client = new OSS({
    endpoint: 'oss-accelerate.aliyuncs.com',
    accessKeyId: process.env.ALI_OSS_AK_ID,
    accessKeySecret: process.env.ALI_OSS_AK_SECRET,
    bucket: ALI_OSS_BUCKET,
  });

  // if is a file then upload it directly
  const stat = fs.statSync(workspacePath);
  if (stat.isFile()) {
    const doUpload = uploadFile(client, workspacePath, refValue);
    try {
      await retry(doUpload, 3);
    } catch (err) {
      console.error(
        'Uploading file `%s` failed after retry %s, error: %s',
        fileOrFolderName,
        3,
        err,
      );
      process.exit(1);
    }
    return;
  }

  if (stat.isDirectory()) {
    const fileList = await walkDir(workspacePath);
    for (const file of fileList) {
      const doUpload = uploadFile(client, file, refValue);
      try {
        await retry(doUpload, 3);
      } catch (err) {
        console.warn(
          'Skip uploading file `%s` in folder `%s` failed after retry %s, error: %s',
          path.relative(workspacePath, file),
          fileOrFolderName,
          3,
          err,
        );
      }
    }
  }
}

boot();