Skip to content

Instantly share code, notes, and snippets.

@ahmadbilaldev
Last active July 12, 2024 14:03
Show Gist options
  • Save ahmadbilaldev/aa5fc5e3e93c68c87c069b8298dc8002 to your computer and use it in GitHub Desktop.
Save ahmadbilaldev/aa5fc5e3e93c68c87c069b8298dc8002 to your computer and use it in GitHub Desktop.
GitHub files diff by commits
name: Diff Changed Files
on:
push:
branches:
- main
pull_request:
jobs:
diff-files:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
fetch-depth: 2
- name: Install Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm install
- name: Run diff script
run: node <PATH_TO_YOUR_SCRIPT>
env:
GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
const https = require('https');
const querystring = require('querystring');
// Replace <YOUR_ACCESS_TOKEN> with your personal access token
const accessToken = '<YOUR_ACCESS_TOKEN>';
// Replace <OWNER> and <REPO> with the owner and repository name
const owner = '<OWNER>';
const repo = '<REPO>';
// Replace <BASE_COMMIT_SHA> and <HEAD_COMMIT_SHA> with the commit SHAs
const baseCommitSha = '<BASE_COMMIT_SHA>';
const headCommitSha = '<HEAD_COMMIT_selectBox.value = e.target.value;
// Function to make a request to the GitHub API
function makeApiRequest(path, method = 'GET', data) {
const options = {
hostname: 'api.github.com',
port: 443,
path: `/repos/${owner}/${repo}${path}`,
method: method,
headers: {
'User-Agent': 'Node.js Script',
'Authorization': `token ${accessToken}`,
'Accept': 'application/vnd.github.v3+json'
}
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(JSON.parse(responseBody));
} else {
reject(new Error(`Request failed with status code ${res.statusCode}: ${responseBody}`));
}
});
});
req.on('error', (error) => {
reject(error);
});
if (data) {
req.write(JSON.stringify(data));
}
req.end();
});
}
// Function to get the files changed between two commits
async function getChangedFiles(baseSha, headSha) {
const baseTree = await makeApiRequest(`/commits/${baseSha}/tree`);
const headTree = await makeApiRequest(`/commits/${headSha}/tree`);
const baseTreeFiles = baseTree.tree.map(file => file.path);
const headTreeFiles = headTree.tree.map(file => file.path);
return headTreeFiles.filter(file => !baseTreeFiles.includes(file));
}
// Main function
async function main() {
try {
const changedFiles = await getChangedFiles(baseCommitSha, headCommitSha);
console.log('Changed files:', changedFiles);
} catch (error) {
console.error('An error occurred:', error.message);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment