/* eslint-disable no-console */
const semver = require('semver');
const cp = require('child_process');
const { basename } = require('path');

const { read: readConfig } = require("@changesets/config");
const readChangesets = require("@changesets/read").default;
const assembleReleasePlan = require("@changesets/assemble-release-plan").default;
const applyReleasePlan = require("@changesets/apply-release-plan").default;
const { getPackages } = require("@manypkg/get-packages");

function getNewVersion(version, type) {
  const gitHash = cp.spawnSync('git', ['rev-parse', '--short', 'HEAD']).stdout.toString().trim();
  
  return semver.inc(version, `pre${type}`, true, 'alpha-' + gitHash);
}

function getRelevantChangesets(baseBranch) {
  const comparePoint = cp.spawnSync('git', ['merge-base', `origin/${baseBranch}`, 'HEAD']).stdout.toString().trim();
  const listModifiedFiles = cp.spawnSync('git', ['diff', '--name-only', comparePoint]).stdout.toString().trim().split('\n');

  return listModifiedFiles.filter(f => f.startsWith('.changeset')).map(f => basename(f, '.md'));
}

async function updateVersions() {
  const cwd = process.cwd();
  const packages = await getPackages(cwd);
  const config = await readConfig(cwd, packages);
  const modifiedChangesets = getRelevantChangesets(config.baseBranch);
  const changesets = (await readChangesets(cwd)).filter(change => modifiedChangesets.includes(change.id));
  
  if (changesets.length === 0) {
    console.warn(`Unable to find any relevant package for canary publishing. Please make sure changesets exists!`);
    process.exit(1);
  } else {
    const releasePlan = assembleReleasePlan(changesets, packages, config, [], false);
    
    if (releasePlan.releases.length === 0) {
      console.warn(`Unable to find any relevant package for canary releasing. Please make sure changesets exists!`);
      process.exit(1);
    } else {
      for (const release of releasePlan.releases) {
        if (release.type !== 'none') {
          release.newVersion = getNewVersion(release.oldVersion, release.type);
        }
      }

      await applyReleasePlan(
        releasePlan,
        packages,
        {
          ...config,
          commit: false,
        },
        false,
        true
      );
    }
  }
}

updateVersions().then(() => {
  console.info(`Done!`)
}).catch(err => {
  console.error(err);
  process.exit(1);
});

@@ -610,18 +610,16 @@
 trim();%0A
-  
 %0A  retur
@@ -1320,17 +1320,16 @@
 esets = 
-(
 await re
@@ -1345,17 +1345,121 @@
 ets(cwd)
-)
+%0A  const allChangesets  =%0A    process.env.ON_DEMAND === 'yes'%0A      ? allChangesets%0A      : allChangesets
 .filter(
@@ -1509,18 +1509,16 @@
 e.id));%0A
-  
 %0A  if (c
@@ -1777,20 +1777,16 @@
 false);%0A
-    
 %0A    if 

fix publish script