Skip to content

Commit

Permalink
Randomize Favicon Names & Fix Randomized Paths
Browse files Browse the repository at this point in the history
  • Loading branch information
xbubbo committed Nov 22, 2024
1 parent e590122 commit 4ea85e9
Show file tree
Hide file tree
Showing 2 changed files with 179 additions and 103 deletions.
4 changes: 2 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import { server as wisp } from "@mercuryworkshop/wisp-js/server";
import { build } from "astro";
import Fastify from "fastify";
import INConfig from "./config";
import { RandomizeNames, Revert } from "./randomize";
import { Main, Revert } from "./randomize";

async function Start() {
const FirstRun = process.env.FIRST === "true";

if (!fs.existsSync("dist")) {
RandomizeNames();
Main();
console.log("Interstellar's not built yet! Building now...");

await build({}).catch((err) => {
Expand Down
278 changes: 177 additions & 101 deletions randomize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,151 +2,227 @@ import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";

const RenamedFiles: { [key: string]: string } = {};
const PageRoutes: { [key: string]: string } = {};
const FilesMap: { [original: string]: string } = {};
const RouteMap: { [original: string]: string } = {};
const FaviconMap: { [original: string]: string } = {};

export function randomizeName(filePath: string): string {
const extname = path.extname(filePath);
return `${Math.random().toString(36).slice(2, 11)}${extname}`;
export function RandomizeNames(filePath: string): string {
const extension = path.extname(filePath);
return `${Math.random().toString(36).slice(2, 11)}${extension}`;
}

export function findFiles(dir: string, filePattern: RegExp): string[] {
let results: string[] = [];
const list = fs.readdirSync(dir);
export function FindFiles(directory: string, pattern: RegExp): string[] {
let MatchedFiles: string[] = [];
const files = fs.readdirSync(directory);

for (const file of list) {
const resolvedFile = path.resolve(dir, file);
const stat = fs.statSync(resolvedFile);
for (const file of files) {
const FullPath = path.resolve(directory, file);
const stats = fs.statSync(FullPath);

if (stat.isDirectory()) {
results = results.concat(findFiles(resolvedFile, filePattern));
} else if (filePattern.test(file)) {
results.push(resolvedFile);
if (stats.isDirectory()) {
MatchedFiles = MatchedFiles.concat(FindFiles(FullPath, pattern));
} else if (pattern.test(file)) {
MatchedFiles.push(FullPath);
}
}

return results;
return MatchedFiles;
}

export function RandomizeNames() {
const filesToRename = [
...findFiles(path.join(process.cwd(), "src", "components"), /\.astro$/),
...findFiles(path.join(process.cwd(), "src", "layouts"), /\.astro$/),
...findFiles(path.join(process.cwd(), "src", "lib"), /\.ts$/),
...findFiles(path.join(process.cwd(), "src", "pages"), /\.astro$/),
...findFiles(path.join(process.cwd(), "src", "pages", "e"), /\.ts$/),
export function RandomizeFavicons() {
const FaviconDir = path.join(
process.cwd(),
"public",
"assets",
"media",
"favicons",
);

if (!fs.existsSync(FaviconDir)) {
return;
}

const Favicons = fs.readdirSync(FaviconDir);

for (const file of Favicons) {
const OriginalPath = path.join(FaviconDir, file);
const RandomizedName = RandomizeNames(file);
const NewPath = path.join(FaviconDir, RandomizedName);

fs.renameSync(OriginalPath, NewPath);
FaviconMap[file] = RandomizedName;
}

UpdateFaviconRoutes();
}

export function UpdateFaviconRoutes() {
const FilesToUpdate = [
...FindFiles(path.join(process.cwd(), "src"), /\.astro$/),
...FindFiles(path.join(process.cwd(), "src"), /\.ts$/),
];

for (const file of FilesToUpdate) {
let content = fs.readFileSync(file, "utf-8");

for (const [OldName, RandomizedName] of Object.entries(FaviconMap)) {
const patterns = [
`/assets/media/favicons/${OldName}`,
`assets/media/favicons/${OldName}`,
`'${OldName}'`,
`"${OldName}"`,
];

for (const pattern of patterns) {
content = content.replace(
new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
pattern.startsWith("/")
? `/assets/media/favicons/${RandomizedName}`
: pattern.startsWith("assets")
? `assets/media/favicons/${RandomizedName}`
: pattern.startsWith("'")
? `'${RandomizedName}'`
: `"${RandomizedName}"`,
);
}
}

fs.writeFileSync(file, content, "utf-8");
}
}

export function Main() {
RandomizeFavicons();

const FilesToProcess = [
...FindFiles(path.join(process.cwd(), "src", "components"), /\.astro$/),
...FindFiles(path.join(process.cwd(), "src", "layouts"), /\.astro$/),
...FindFiles(path.join(process.cwd(), "src", "lib"), /\.ts$/),
...FindFiles(path.join(process.cwd(), "src", "pages"), /\.astro$/),
...FindFiles(path.join(process.cwd(), "src", "pages", "e"), /\.ts$/),
];

for (const file of filesToRename) {
for (const file of FilesToProcess) {
if (path.basename(file) === "index.astro") {
continue;
}

const newName = randomizeName(file);
const oldPath = path.resolve(file);
const newPath = path.resolve(path.dirname(file), newName);
RenamedFiles[oldPath] = newPath;
fs.renameSync(oldPath, newPath);
const RandomizedName = RandomizeNames(file);
const OriginalPath = path.resolve(file);
const NewPath = path.resolve(path.dirname(file), RandomizedName);

FilesMap[OriginalPath] = NewPath;

if (file.startsWith(path.join(process.cwd(), "src", "pages"))) {
const oldRoute = oldPath
.replace(`${process.cwd()}/src/pages`, "")
.replace(/\\/g, "/");
const newRoute = newPath
.replace(`${process.cwd()}/src/pages`, "")
.replace(/\\/g, "/");
PageRoutes[oldRoute] = newRoute;
const OriginalRoute = OriginalPath.replace(
path.join(process.cwd(), "src", "pages"),
"",
)
.replace(/\\/g, "/")
.replace(/\.astro$/, "");

const NewRoute = NewPath.replace(path.join(process.cwd(), "src", "pages"), "")
.replace(/\\/g, "/")
.replace(/\.astro$/, "");

RouteMap[OriginalRoute] = NewRoute;

if (OriginalRoute.startsWith("/")) {
RouteMap[OriginalRoute.substring(1)] = NewRoute.startsWith("/")
? NewRoute.substring(1)
: NewRoute;
} else {
RouteMap[OriginalRoute] = NewRoute;
}
}
}

updateImports();
updatePageRoutes();
UpdateImports();
UpdateRoutes();

for (const [OriginalPath, NewPath] of Object.entries(FilesMap)) {
fs.renameSync(OriginalPath, NewPath);
}

console.log("Routes updated:", RouteMap);
}

export function updateImports() {
const allFiles = [
...findFiles(path.join(process.cwd(), "src"), /\.astro$/),
...findFiles(path.join(process.cwd(), "src"), /\.ts$/),
export function UpdateRoutes() {
const FilesToUpdate = [
...FindFiles(path.join(process.cwd(), "src"), /\.astro$/),
...FindFiles(path.join(process.cwd(), "src"), /\.ts$/),
];

for (const file of allFiles) {
let fileContent = fs.readFileSync(file, "utf-8");
const rootPath = process.cwd();

for (const [oldPath, newPath] of Object.entries(RenamedFiles)) {
const oldImportPathAlias = oldPath
.replace(`${rootPath}/src/components`, "@/components")
.replace(`${rootPath}/src/layouts`, "@/layouts")
.replace(`${rootPath}/src/lib`, "@/lib")
.replace(/\\/g, "/");

const newImportPathAlias = newPath
.replace(`${rootPath}/src/components`, "@/components")
.replace(`${rootPath}/src/layouts`, "@/layouts")
.replace(`${rootPath}/src/lib`, "@/lib")
.replace(/\\/g, "/");

const oldImportPathAbs = oldPath.replace(rootPath, "").replace(/\\/g, "/");

const newImportPathAbs = newPath.replace(rootPath, "").replace(/\\/g, "/");

fileContent = fileContent.replace(
new RegExp(`['"]${oldImportPathAlias}['"]`, "g"),
`'${newImportPathAlias}'`,
);
fileContent = fileContent.replace(
new RegExp(`['"]${oldImportPathAbs}['"]`, "g"),
`'${newImportPathAbs}'`,
);
for (const file of FilesToUpdate) {
let content = fs.readFileSync(file, "utf-8");

for (const [OriginalRoute, NewRoute] of Object.entries(RouteMap)) {
const routePattern = new RegExp(`(['"\`])${OriginalRoute}(['"\`])`, "g");

content = content.replace(routePattern, `$1${NewRoute}$2`);
}

fs.writeFileSync(file, fileContent, "utf-8");
fs.writeFileSync(file, content, "utf-8");
}
}

export function updatePageRoutes() {
const allFiles = [
...findFiles(path.join(process.cwd(), "src"), /\.astro$/),
...findFiles(path.join(process.cwd(), "src"), /\.ts$/),
export function UpdateImports() {
const FilesToUpdate = [
...FindFiles(path.join(process.cwd(), "src"), /\.astro$/),
...FindFiles(path.join(process.cwd(), "src"), /\.ts$/),
];

for (const file of allFiles) {
let fileContent = fs.readFileSync(file, "utf-8");

for (const [oldRoute, newRoute] of Object.entries(PageRoutes)) {
fileContent = fileContent.replace(
new RegExp(`['"]${oldRoute.replace(".astro", "")}['"]`, "g"),
`'${newRoute.replace(".astro", "")}'`,
);
const root = process.cwd();

for (const file of FilesToUpdate) {
let content = fs.readFileSync(file, "utf-8");

for (const [OriginalPath, NewPath] of Object.entries(FilesMap)) {
const OriginalName = path.basename(OriginalPath);
const RandomizedName = path.basename(NewPath);

const OriginalPatterns = [
`@/components/${OriginalName}`,
`@/layouts/${OriginalName}`,
`@/lib/${OriginalName}`,
OriginalPath.replace(root, "").replace(/\\/g, "/"),
OriginalName,
];

const NewPatterns = [
`@/components/${RandomizedName}`,
`@/layouts/${RandomizedName}`,
`@/lib/${RandomizedName}`,
NewPath.replace(root, "").replace(/\\/g, "/"),
RandomizedName,
];

OriginalPatterns.forEach((pattern, index) => {
content = content.replace(
new RegExp(`['"]${pattern.replace(/\./g, "\\.")}['"]`, "g"),
`'${NewPatterns[index]}'`,
);
});
}

fs.writeFileSync(file, fileContent, "utf-8");
}
}

export function renameEDirectory() {
const eDirPath = path.join(process.cwd(), "src", "pages", "e");
if (fs.existsSync(eDirPath)) {
const newEDirName = `/${Math.random().toString(36).slice(2, 6)}`;
const newEDirPath = path.join(process.cwd(), "src", "pages", newEDirName);
fs.renameSync(eDirPath, newEDirPath);
fs.writeFileSync(file, content, "utf-8");
}
}

export async function Revert() {
try {
console.log("Reverting Changes.");
execSync("git restore src/", { cwd: process.cwd(), stdio: "inherit" });
execSync("git clean -fdx src/", { cwd: process.cwd(), stdio: "inherit" });

await new Promise((resolve) => setTimeout(resolve, 2000));
execSync("git restore src/ public/", { cwd: process.cwd(), stdio: "inherit" });
execSync("git clean -fdx src/ public/", {
cwd: process.cwd(),
stdio: "inherit",
});
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log("Revert completed.");
} catch (error) {
console.error(
"Error during revert:",
"Error while reverting:",
error instanceof Error ? error.message : error,
);
}
}

updateImports();

0 comments on commit 4ea85e9

Please sign in to comment.