const {
    exec
} = require('child_process');
const addFileToOSSSync = require('./oss');
const ora = require('ora')

// 查看git冲突
exec(`git status`, (error, stdout, stderr) => {
    if (error) {
        console.error(`${error}`);
        return;
    }
   if(stdout.split('Untracked files:').length>1){
     let package =stdout.split('Untracked files:')[1].match(/package\/.*\/.*/g)
    //  提交新增的package;
    if(!package){
        package =stdout.split('Untracked files:')[1].match(/package\/.*/g)
    }
      gitCommit(package);
   }
  

});

const gitCommit = (package)=>{
    // 提交到git
    let message  = package.join('');
    exec(`git add . && git commit -am '${message}' && git push`, (error, stdout, stderr) => {
        if (error) {
            console.error(`============exec error: ${error}`);
            return;
        }
        console.log(stdout);
        // // 获取提交成功的文件目录
         initOssList(package);
    
    });

}


const initOssList = (package) => {
    // 初始化上传目录
    if (package) {
        const spinner = ora(`正在上传，请稍等...`).start();
        let cwdUrl = process.cwd().replace(/\\/g, '/');
        package.forEach(option => {
            let lastIndex = option.lastIndexOf('/');
            let src = option.substring(0,lastIndex);
            let dist = src.replace('package', 'CDN');
            // 上传到oss
            console.log(src,dist);
            addFileToOSSSync(`${cwdUrl}/${src}`, dist,spinner);
            
        });
        // let ossList = package.reduce((arr, option) => {
        //     let items = option.split('/');
        //     let path = [];
        //     items.findIndex((x) => {
        //         path.push(x);
        //         // 查找版本号
        //         return /^([0-9]\d|[0-9])(.([0-9]\d|\d)){2}$/.test(x);
        //     })
        //     let src = path.join('/');
        //     let dist = src.replace('package', 'CDN');

        //     if (!arr.includes(option)) {
        //         arr.push(option);
        //         // 上传到oss
        //         addFileToOSSSync(`${cwdUrl}/${src}`, dist,spinner);

        //     }
        //     return arr;

        // }, [])

    }
}
