Skip to content

Commit

Permalink
add /remove command
Browse files Browse the repository at this point in the history
  • Loading branch information
3vorp committed Jan 18, 2025
1 parent 4773d9f commit 52eed0e
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 35 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@
"prettier": "prettier \"{,!(node_modules)/**/}*.ts\" --config .prettierrc --write"
},
"devDependencies": {
"@types/node": "^22.10.5",
"@types/node": "^22.10.7",
"nodemon": "^3.1.9",
"prettier": "^3.4.2"
},
"dependencies": {
"@napi-rs/canvas": "^0.1.65",
"@octokit/rest": "^20.1.1",
"axios": "^1.7.9",
"cron": "^3.3.2",
"cron": "^3.5.0",
"discord.js": "^14.16.3",
"dotenv": "^16.4.7",
"gif-encoder-2": "^1.0.5",
Expand Down
28 changes: 14 additions & 14 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 12 additions & 11 deletions resources/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,20 @@
"error": "One of my developers made an error while making this command! Don't worry, the error is not on your side. Please contact <@360249987927638016>, <@473860522710794250>, or <@173336582265241601> if this keeps occurring.",
"maintenance": "I'm currently under maintenance, please try again later.",
"description": {
"autopush": "Push textures from a result channel to GitHub.",
"channelpush": "Send textures to council and result channels.",
"behave": "(⌯˃̶᷄ ﹏ ˂̶᷄⌯)",
"autopush": "Push textures from a result channel to GitHub.",
"channelpush": "Send textures to council and result channels.",
"behave": "(⌯˃̶᷄ ﹏ ˂̶᷄⌯)",
"feedback": "Create a new suggestion or bug report on our GitHub bug tracker.",
"backup": "Back up all files to the GitHub Database repository.",
"hotfix": "Fix something (may change at any time).",
"ping": "Pong!",
"reload": "Reloads all commands.",
"restart": "Restart the bot.",
"say": "Make the bot say something.",
"shutdown": "Stops the bot.",
"status": "Changes the bot's status."
},
"hotfix": "Fix something (may change at any time).",
"ping": "Pong!",
"reload": "Reloads all commands.",
"restart": "Restart the bot.",
"say": "Make the bot say something.",
"shutdown": "Stops the bot.",
"status": "Changes the bot's status.",
"remove": "Remove files from a pack repository. This does not remove contributions or other pack-specific data."
},
"feedback_sent": "Your ticket will be created shortly on GitHub. Thank you for helping us improve the bot!",
"backup_failed": "At least one collection could not be backed up. Please check the developer logs for more information.",
"behave": "I'm so sorry! (⌯˃̶᷄ ﹏ ˂̶᷄⌯)",
Expand Down
113 changes: 113 additions & 0 deletions src/commands/submission/remove.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import strings from "@resources/strings.json";
import settings from "@resources/settings.json";

import { Command } from "@interfaces/discord";
import { EmbedBuilder, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { MinecraftEdition, Pack, PackFile, Path, Texture } from "@interfaces/database";
import axios from "axios";
import { deleteFromGitHub } from "@functions/pushToGitHub";
import addDeleteButton from "@helpers/addDeleteButton";

const DEBUG = process.env.DEBUG.toLowerCase() === "true";

export default {
data: new SlashCommandBuilder()
.setName("remove")
.setDescription(strings.command.description.remove)
.addStringOption((option) =>
option
.setName("pack")
.setDescription("Which pack to remove textures from.")
.addChoices(
{ name: "All", value: "all" },
...Object.values(require("@resources/packs.json")).map((pack: Pack) => ({
name: pack.name,
value: pack.id,
})),
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName("texture")
.setDescription("Texture name or ID to find (first name will be chosen so be careful).")
.setRequired(true),
)
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
.setDMPermission(false),
async execute(interaction) {
interaction.deferReply();
const submissions: PackFile = require("@resources/packs.json");
const pack = interaction.options.getString("pack", true);
const texture = interaction.options.getString("texture", true);

const cleanedTextureName = texture
.trim()
.replace(".png", "")
.replace("#", "")
.replace(/ /g, "_");

const noResultEmbed = new EmbedBuilder()
.setTitle("No results found!")
.setDescription(`No results were found for ${cleanedTextureName}. Have you made a typo?`)
.setColor(settings.colors.red);

let results: Texture | Texture[];
try {
results = (
await axios.get(
`${process.env.API_URL}textures/${encodeURIComponent(cleanedTextureName)}/all`,
)
).data;
} catch {
return interaction.editReply({
embeds: [noResultEmbed],
});
}

results = Array.isArray(results) ? results : [results];
if (!results.length)
return interaction.editReply({
embeds: [noResultEmbed],
});

// take first result
const { name, uses, paths } = results[0];

// grouped by edition -> version -> path name
const groupedPaths = uses.reduce<Record<string, Record<string, string[]>>>((acc, cur) => {
acc[cur.edition] ||= {};
for (const path of paths.filter((p) => p.use === cur.id)) {
// add path to every version it's in
for (const version of path.versions) {
acc[cur.edition][version] ||= [];
acc[cur.edition][version].push(path.name);
}
}
return acc;
}, {});

for (const [edition, versions] of Object.entries(groupedPaths)) {
const { org, repo } = submissions[pack].github[edition as MinecraftEdition];
for (const [version, paths] of Object.entries(versions)) {
try {
await deleteFromGitHub(org, repo, version, `Delete ${name}`, paths);
if (DEBUG) console.log(`Deleted: ${org}/${repo}:${version} (${name})`);
} catch {
// can also be an auth error or really anything but this is most likely
if (DEBUG) console.log(`Branch ${version} doesn't exist for pack ${repo}!`);
}
}
}

return interaction
.editReply({
embeds: [
new EmbedBuilder()
.setTitle(`Successfully removed texture ${name} from pack ${submissions[pack].name}`)
.setColor(settings.colors.green),
],
})
.then((msg) => addDeleteButton(msg));
},
} as Command;
56 changes: 53 additions & 3 deletions src/functions/pushToGitHub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,56 @@ export default async function pushToGitHub(
return newCommit.sha;
}

/**
* Remove files from a GitHub repository by name
* @author Evorp
* @param org GitHub organization name
* @param repo GitHub repository name
* @param branch branch name
* @param commitMessage
* @param filePaths Paths to delete
* @returns sent commit sha
*/
export async function deleteFromGitHub(
org: string,
repo: string,
branch: string,
commitMessage: string,
filePaths: string[],
) {
const octo = new Octokit({ auth: process.env.GIT_TOKEN });
const { commitSha, treeSha } = await getCurrentCommit(octo, org, repo, branch);

const treeItems = filePaths.map(
(path) =>
({
path,
mode: "100644",
// null means deletion
sha: null,
}) as const,
);

const { data: newTreeData } = await octo.git.createTree({
owner: org,
repo,
tree: treeItems,
base_tree: treeSha,
});

const commitData = await createNewCommit(
octo,
org,
repo,
commitMessage,
newTreeData.sha,
commitSha,
);

await setBranchToCommit(octo, org, repo, branch, commitData.sha);
return commitData.sha;
}

/**
* Get current commit of a branch from a repository
* @param octo
Expand Down Expand Up @@ -186,22 +236,22 @@ async function createNewTree(
* @param repo GitHub repository of the organisation
* @param message Commit message
* @param currentTreeSha
* @param currentCommitSha
* @param lastCommitSha
*/
async function createNewCommit(
octo: Octokit,
org: string,
repo: string,
message: string,
currentTreeSha: string,
currentCommitSha: string,
lastCommitSha: string,
) {
const { data } = await octo.git.createCommit({
owner: org,
repo,
message,
tree: currentTreeSha,
parents: [currentCommitSha],
parents: [lastCommitSha],
});
return data;
}
Expand Down
9 changes: 4 additions & 5 deletions src/functions/submission/pushTextures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { existsSync, rmSync } from "fs";
import formattedDate from "@helpers/formattedDate";

import pushToGitHub from "@functions/pushToGitHub";
import type { PackFile } from "@interfaces/database";
import type { MinecraftEdition, PackFile } from "@interfaces/database";
import { join } from "path";
const DEBUG = process.env.DEBUG.toLowerCase() === "true";
const DEV = process.env.DEV.toLowerCase() === "true";
Expand All @@ -23,14 +23,13 @@ export default async function pushTextures(
const settings = require("@resources/settings.json");

const packs: PackFile = require("@resources/packs.json");
const editions = Object.keys(settings.versions).filter((k) => k !== "id");
for (const edition of editions) {
const packGitHub = packs[pack].github[edition];
for (const edition of Object.keys(settings.versions)) {
const packGitHub = packs[pack].github[edition as MinecraftEdition];
if (!packGitHub) {
if (DEBUG) console.log(`${pack} doesn't support ${edition} yet!`);
continue;
}
for (const branch of settings.versions[edition]) {
for (const branch of settings.versions[edition] as string) {
const path = join(basePath, packGitHub.repo, branch);

// don't create empty commits
Expand Down

0 comments on commit 52eed0e

Please sign in to comment.