"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.publishProject=publishProject;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _fs=_interopRequireDefault(require("fs"));
var _path=_interopRequireDefault(require("path"));
var _open=_interopRequireDefault(require("open"));
var _listr=_interopRequireDefault(require("listr"));
var _execa=_interopRequireDefault(require("execa"));

var _newGithubReleaseUrl=_interopRequireDefault(require("new-github-release-url"));
var _rxjs=require("rxjs");

var _corenode=require("corenode");

var _builder=_interopRequireDefault(require("@corenode/builder"));



var _getChangelogs=_interopRequireDefault(require("../getChangelogs"));function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable});keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach(function(key){(0,_defineProperty2.default)(target,key,source[key])})}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}}return target}let _require=require("@corenode/utils"),verbosity=_require.verbosity,objectToArrayMap=_require.objectToArrayMap;verbosity=verbosity.options({method:"[PUBLISH]"});

function publishProject(args){
return new Promise((resolve,reject)=>{
let projectPackages=(0,_corenode.getPackages)();

const gitRemote=(0,_corenode.getGit)();
const isProject=(0,_corenode.isProjectMode)();

let config={
skipStatus:false,
skipBuild:false,
npm:false,
github:false,
preRelease:false,
next:false};


if(typeof args!=="undefined"){
config=_objectSpread(_objectSpread({},config),args);
}

let tasks={
checkGit:{
title:"\uD83D\uDCDD Checking git status",
skip:()=>config.skipStatus===true,
task:()=>{
return new Promise((res,rej)=>{
const gitStatus=_execa.default.sync("git",["status","--porcelain"]).stdout;
if(gitStatus.length){
return rej(new Error("\u26D4\uFE0F Your git status is not clean"));
}
return res(gitStatus);
});
}},

buildProject:{
title:"\uD83D\uDCE6 Building project",
skip:()=>config.skipBuild===true,
task:()=>{
return new Promise((res,rej)=>{
(0,_builder.default)({buildBuilder:true}).
then(done=>res()).
catch(error=>rej(new Error(`Failed build! > ${error.message}`)));
});
}},

npmRelease:{
title:"\uD83D\uDCE2 Publish on NPM",
enabled:()=>config.npm===true,
task:()=>{
return new _rxjs.Observable(observer=>{
let publishCount=Number(0);
if(!Array.isArray(projectPackages)&&!isProject){
projectPackages=["_"];
}

projectPackages.forEach((pkg,index)=>{
const packagePath=isProject?_path.default.resolve(process.cwd(),`packages/${pkg}`):process.cwd();
const pkgJSON=_path.default.resolve(packagePath,"package.json");
const cliArgs=["publish"];

if(config.next){
cliArgs.push("--tag","next");
}

if(_fs.default.existsSync(pkgJSON)){
try{const _require2=
require(pkgJSON),name=_require2.name;
const logOutput=`[${publishCount}/${projectPackages.length}] Published npm package ${name}[${index}]`;

(0,_execa.default)("npm",cliArgs,{cwd:packagePath}).
then(stdout=>{
publishCount+=1;
verbosity.dump(logOutput);
observer.next(logOutput);

if(publishCount==projectPackages.length-1){
verbosity.dump(`NPM Release successfuly finished with [${projectPackages.length}] packages > ${projectPackages}`);
observer.complete();
}
});
}catch(error){
observer.next(`❌ Failed to publish > ${name} > ${error}`);
}
}else{
const errstr=`❌ ${pkg} has no valid package.json`;
verbosity.dump(errstr);
observer.next(errstr);
}

});
});
}},

githubPublish:{
title:"\uD83D\uDCE2 Publish on Github",
enabled:()=>config.github===true,
task:(ctx,_task)=>{
return new Promise((res,rej)=>{
let changelogNotes="";
const releaseTag=`v${(0,_corenode.getVersion)()}`;

try{
changelogNotes=(0,_getChangelogs.default)(gitRemote);
}catch(error){
verbosity.options({dumpFile:true,method:false}).warn(`⚠️  Get changelogs failed!\n`);

}

try{
_execa.default.sync("git",["tag",releaseTag]);
_execa.default.sync("git",["push","origin","master","--tags"]);

const githubReleaseUrl=(0,_newGithubReleaseUrl.default)({
repoUrl:gitRemote,
tag:releaseTag,
body:changelogNotes,
isPrerelease:config.preRelease});


console.log(`\n ⚠️  Continue github release manualy > ${githubReleaseUrl}`);
(0,_open.default)(githubReleaseUrl);

return res();
}catch(error){
verbosity.dump(error);
return _task.skip(`❌ Failed github publish, skipping`);
}
});
}}};



new _listr.default(objectToArrayMap(tasks).map(task=>{return task.value}),{collapse:false}).run().
then(response=>{
console.log(`✅ Publish done`);
return resolve(true);
}).catch(error=>{
verbosity.options({dumpFile:true,method:false}).error(`❌ Failed publish >`,error);
return reject(error);
});
});
}