/* eslint-disable no-console */

/**
 * Publishes pacts generated by the Pact tests. Only meant to run in CI.
 */

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const pact = require('@pact-foundation/pact-node');

const pactsFolder = path.resolve(__dirname, '../pacts');

try {
  const pactFiles = fs.readdirSync(pactsFolder);
  if (!pactFiles.length) throw new Error('No pacts found.');
} catch (e) {
  console.warn(e.message);
  console.log('Skipping pact publishing.');
  return;
}

const consumerVersion = execSync('git rev-parse --verify HEAD')
  .toString()
  .trim();

const branchName = execSync('git rev-parse --abbrev-ref HEAD')
  .toString()
  .trim();

const opts = {
  pactBroker: process.env.PACT_BROKER_URL,
  pactBrokerUsername: process.env.PACT_BROKER_BASIC_AUTH_USERNAME,
  pactBrokerPassword: process.env.PACT_BROKER_BASIC_AUTH_PASSWORD,
  pactFilesOrDirs: [pactsFolder],
  consumerVersion,
  tags: [branchName],
};

pact
  .publishPacts(opts)
  .then(() => {
    console.log('Pact successfully published!');
  })
  .catch(e => {
    console.log(`Pact failed to publish: ${e}`);
  });

/* eslint-disable no-console */

/**
 * Publishes pacts generated by the Pact tests. Only meant to run in CI.
 */

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const pact = require('@pact-foundation/pact-node');

let pactPaths = [];

try {
  const pactsFolder = path.resolve(__dirname, '../pacts');
  const pactFiles = fs.readdirSync(pactsFolder);
  if (!pactFiles.length) throw new Error('No pacts found.');
  pactPaths = pactFiles.map(pactFile => path.join(pactsFolder, pactFile));
} catch (e) {
  console.warn(e.message);
  console.log('Skipping pact publishing.');
  return;
}

const consumerVersion = execSync('git rev-parse --verify HEAD')
  .toString()
  .trim();

const branchName = execSync('git rev-parse --abbrev-ref HEAD')
  .toString()
  .trim();

const opts = {
  pactBroker: process.env.PACT_BROKER_URL,
  pactBrokerUsername: process.env.PACT_BROKER_BASIC_AUTH_USERNAME,
  pactBrokerPassword: process.env.PACT_BROKER_BASIC_AUTH_PASSWORD,
  consumerVersion,
  tags: [branchName],
};

// Individually publish each pact instead of the whole directory in order
// to properly tag them all. The Pact client was not originally meant to
// publish multiple pacts at once but is able to anyway. But as a result,
// tagging multiple pacts at once is not supported until a future release.
// https://github.com/pact-foundation/pact-js/issues/289
const publishPact = async pactPath => {
  try {
    await pact.publishPacts({ ...opts, pactFilesOrDirs: [pactPath] });
    console.log('Pact successfully published!');
  } catch (e) {
    console.log(`Pact at ${pactPath} failed to publish: ${e}`);
    process.exit(1);
  }
};

pactPaths.forEach(publishPact);

Tag all published pacts (#14550)