21
const { resolve: resolvePath, join: joinPath, basename } = require('path');
22
const { promises: fs } = require('fs');
23
const { execFile: execFileCb } = require('child_process');
24
const { promisify } = require('util');
26
const execFile = promisify(execFileCb);
28
const FOSSA_YAML_HEAD = `
31
server: https://app.fossa.com
37
const IGNORED_DIRS = ['node_modules', 'dist', 'bin', '.git'];
40
async function findPackageJsonDirs(dir, depth = 0) {
44
const files = await fs.readdir(dir);
45
const paths = await Promise.all(
47
.filter(file => !IGNORED_DIRS.includes(file))
49
const path = joinPath(dir, file);
51
if ((await fs.stat(path)).isDirectory()) {
52
return findPackageJsonDirs(path, depth + 1);
53
} else if (file === 'package.json') {
63
async function generateConfig(paths) {
64
let content = FOSSA_YAML_HEAD;
66
for (const path of paths) {
68
- name: ${basename(path)}
81
async function runAnalyze(githubRef) {
82
for (let attempt = 1; attempt <= 3; attempt++) {
83
console.error(`Running fossa analyze, attempt ${attempt}`);
85
const { stdout, stderr } = await execFile(
87
['analyze', '--branch', githubRef],
90
console.error(stderr);
99
process.stderr.write(error.stderr);
102
process.stdout.write(error.stdout);
104
if (error.stderr && error.stderr.includes('502 Bad Gateway')) {
105
console.error('Encountered 502 during fossa analysis upload, retrying');
108
throw new Error(`Fossa analyze failed with code ${error.code}`);
112
console.error('Maximum number of retries reached, skipping fossa analysis');
115
async function main() {
116
const githubRef = process.env.GITHUB_REF;
118
throw new Error('GITHUB_REF is not set');
121
if (!process.env.FOSSA_API_KEY) {
122
throw new Error('FOSSA_API_KEY is not set');
125
process.cwd(resolvePath(__dirname, '..'));
127
const packageJsonPaths = await findPackageJsonDirs('.');
129
const configContents = await generateConfig(packageJsonPaths);
131
await fs.writeFile('.fossa.yml', configContents, 'utf8');
133
console.error(`Generated fossa config:\n${configContents}`);
135
await runAnalyze(githubRef);
138
main().catch(error => {
139
console.error(error.stack);