返回

花式解锁 GitHub Commit 贡献图

前端

前言

GitHub 的 Commit 贡献图是一个很棒的功能,可以直观地展示你对项目的贡献。然而,默认的黑白线条图看起来有些单调,而且无法实时更新。通过一些巧妙的技巧,我们可以将贡献图升级为酷炫的贡献热力图,并实现实时展示的功能。

工具准备

在开始之前,我们需要安装一些必要的工具:

  • PM2:一个用于管理和监控 Node.js 应用程序的进程管理器。
  • fs:Node.js 内置的文件系统模块。
  • child_process:Node.js 内置的子进程模块。
  • schedule:一个用于在 Node.js 中调度任务的模块。

步骤 1:编辑文件内容

首先,我们需要编辑一个文件,该文件将包含我们的脚本。您可以使用您喜欢的文本编辑器,但我们推荐使用 Visual Studio Code。

// commit-graph.js

const fs = require('fs');
const child_process = require('child_process');

// GitHub 用户名
const username = 'YOUR_GITHUB_USERNAME';

// 贡献图保存路径
const filePath = 'commit-graph.svg';

// 获取贡献图数据
const getContributionData = () => {
  return new Promise((resolve, reject) => {
    child_process.exec(`git log --author="${username}" --since="6 months ago" --format="%ad"`, (error, stdout, stderr) => {
      if (error) {
        reject(error);
      } else {
        resolve(stdout);
      }
    });
  });
};

// 生成贡献热力图
const generateHeatmap = (data) => {
  const dates = data.split('\n');
  const heatmap = [];
  for (let i = 0; i < 7; i++) {
    heatmap.push(new Array(30).fill(0));
  }

  dates.forEach((date) => {
    const dateObj = new Date(date);
    const dayOfWeek = dateObj.getDay();
    const weekNumber = dateObj.getWeek();
    heatmap[dayOfWeek][weekNumber]++;
  });

  return heatmap;
};

// 绘制贡献热力图
const drawHeatmap = (heatmap) => {
  const svg = `<svg width="420" height="210">`;

  for (let i = 0; i < 7; i++) {
    for (let j = 0; j < 30; j++) {
      const color = heatmap[i][j] > 0 ? `rgb(${heatmap[i][j] * 10}, 0, 0)` : '#ffffff';
      svg += `<rect x="${i * 60}" y="${j * 7}" width="60" height="7" fill="${color}" />`;
    }
  }

  svg += `</svg>`;

  fs.writeFile(filePath, svg, (error) => {
    if (error) {
      console.log(error);
    } else {
      console.log('贡献热力图已生成');
    }
  });
};

// 定时任务
const scheduleTask = () => {
  const job = schedule.scheduleJob('0 0 * * *', () => {
    getContributionData()
      .then(generateHeatmap)
      .then(drawHeatmap)
      .catch((error) => {
        console.log(error);
      });
  });
};

// 启动定时任务
scheduleTask();

步骤 2:执行脚本

接下来,我们需要执行脚本。您可以使用以下命令:

node commit-graph.js

如果一切顺利,您应该会在当前目录下看到一个名为 commit-graph.svg 的文件。该文件包含了您的贡献热力图。

步骤 3:将贡献热力图添加到 GitHub

现在,您可以将贡献热力图添加到您的 GitHub 个人资料中。只需按照以下步骤操作:

  1. 访问您的 GitHub 个人资料。
  2. 点击“Contributions”标签。
  3. 点击“Edit profile”。
  4. 在“Profile details”部分,找到“Contribution graph”选项。
  5. 点击“Upload custom image”。
  6. 选择您之前保存的 commit-graph.svg 文件。
  7. 点击“Save”。

您的贡献热力图现在应该已经添加到您的 GitHub 个人资料中了。

总结

通过使用 PM2、fs、child_process 和 schedule 等工具,我们成功地将 GitHub 的 Commit 贡献图玩出了花样,从简单的黑白线条图升级为酷炫的贡献热力图,并实现了实时展示的功能。希望本文对您有所帮助。