製作可全局執行的NPM包:批量清理github倉庫

不知什麼時候開始,自家github堆滿了倉庫代碼。。。各種demo開頭的項目,還有些空倉庫,啥都沒寫的。自然,程序員寫的最差的代碼就是以前寫的代碼了,爲了維護心中美好的光輝形象,我決定——————
2015723155143.png

不過,刪除過程確實麻煩了些,身爲“頭腦簡單,四肢發達” ,哦不對,“四肢簡單,頭腦發達”的程序員,怎麼會甘心做苦力勞動呢?我決定搞個命令行批量執行下。
圖片描述

找到github API文檔

要刪除當然是要找API啦,不過,我開始想的是用puppeteer無頭chrome搞的,後來發現直接有API,就直接用嘍。
刪除git倉庫需要認證權限,我這裏直接用Basic Auth驗證,簡單!Basic驗證,簡單說就是在請求頭裏,搞個Authorization:用戶名:密碼

命令行工具

必須是要美美的命令行優化工具啦,I pick這個inquirer。 有一些帶顏色的終端字看着還是ok的,所以還帶上了chalk這個庫。

just do it

具體的代碼,調用API,實在簡單,看看就好:

#!/usr/bin/env node

var inquirer = require('inquirer');
var axios = require('axios');
var chalk = require('chalk');
var log = console.log;

var api = {
  user: async () => {
    return await axios({
      url: 'https://api.github.com/user',
      method: 'GET',
    });
  },
  repos: async () => {
    return await axios({
      url: 'https://api.github.com/user/repos',
      method: 'GET',
    });
  },
  deleteRepos: async (user, name) => {
    return await axios({
      method: 'DELETE',
      url: `https://api.github.com/repos/${user}/${name}`,
    });
  },
  login: async () => {
    return await inquirer.prompt([
      {
        name: 'username',
        message: 'username?'
      },
      {
        name: 'password',
        type: 'password',
        message: 'password?'
      }
    ]);
  },
  listRepos: async (repos) => {
    var list = [];
    repos.forEach(v => {
      var desc = v.description === null ? '' : v.description;
      list.push({name: v.full_name + ' ' + desc});
    });
    return await inquirer.prompt([
      {
        type: 'checkbox',
        name: 'rep',
        message: 'select need cleared repos',
        choices: list
      }
    ]);
  }
};

(async () => {
  var inf = await api.login();
  var base64 = new Buffer.from(inf.username + ':' + inf.password).toString('base64');
  axios.interceptors.request.use(config => {
    config.headers = {
      Authorization: 'Basic ' + base64
    };
    return config;
  });
  var user = await api.user();
  log(`welcome ! ${chalk.green(user.data.name || user.data.login)}`);
  var repos = await api.repos();
  var selectRepos = await api.listRepos(repos.data);
  for (var j = 0; j < selectRepos.rep.length; j++) {
    var name = selectRepos.rep[j].indexOf(' ') === -1 ? selectRepos.rep[j] : selectRepos.rep[j].substring(0, selectRepos.rep[j].indexOf(' '));
    await api.deleteRepos(user.data.login, name);
  }
  log(chalk.green('successfull!'));
})();

npm打包發佈

就這樣打包,肯定不會有全局執行文件滴。

首先你需要在主執行的js的第一行寫上

#!/usr/bin/env node

大家都知道,這是linux中指定文件執行解釋器的意思,windows系統沒用,但是配合上npm就有用啦,且先寫着。

然後:在package.json中,敲下如下代碼:

 "bin": {
    "ngit": "index.js"
  },

ngit說明全局執行命令叫ngit, index.js是執行文件。

ok,最後npm publish發佈

npm install -g nodejs-github

再到cmd中,輸入

ngit

就會直接執行代碼啦,呼呼呼呼呼呼~~

github: https://github.com/chendonming/nodejs-github
npm: nodejs-github

各位看官闊以看下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章