/* 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}`);
  });

@@ -260,24 +260,53 @@
 ct-node');%0A%0A
+let pactPaths = %5B%5D;%0A%0Atry %7B%0A  
 const pactsF
@@ -349,23 +349,16 @@
 pacts');
-%0A%0Atry %7B
 %0A  const
@@ -460,16 +460,91 @@
 und.');%0A
+  pactPaths = pactFiles.map(pactFile =%3E path.join(pactsFolder, pactFile));%0A
 %7D catch 
@@ -1008,42 +1008,8 @@
 RD,%0A
-  pactFilesOrDirs: %5BpactsFolder%5D,%0A
   co
@@ -1053,50 +1053,479 @@
 %7D;%0A%0A
-pact%0A  .publishPacts(opts)%0A  .then(() =%3E %7B
+// Individually publish each pact instead of the whole directory in order%0A// to properly tag them all. The Pact client was not originally meant to%0A// publish multiple pacts at once but is able to anyway. But as a result,%0A// tagging multiple pacts at once is not supported until a future release.%0A// https://github.com/pact-foundation/pact-js/issues/289%0Aconst publishPact = async pactPath =%3E %7B%0A  try %7B%0A    await pact.publishPacts(%7B ...opts, pactFilesOrDirs: %5BpactPath%5D %7D);
 %0A   
@@ -1577,23 +1577,18 @@
 %0A  %7D
-)%0A  .
+ 
 catch
+ 
 (e
- =%3E
+)
  %7B%0A 
@@ -1607,16 +1607,31 @@
 og(%60Pact
+ at $%7BpactPath%7D
  failed 
@@ -1652,12 +1652,67 @@
 e%7D%60);%0A  
-%7D
+  process.exit(1);%0A  %7D%0A%7D;%0A%0ApactPaths.forEach(publishPact
 );%0A

Tag all published pacts (#14550)