Skip to content

Commit

Permalink
Refactor CLI help and logging, add error handling and improve code or…
Browse files Browse the repository at this point in the history
…ganization
  • Loading branch information
Explosion-Scratch committed Aug 24, 2024
1 parent 5e153b0 commit f1e5261
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 87 deletions.
12 changes: 6 additions & 6 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,15 @@ const confirm = async (q) => {

const showHelp = () => {
console.log(`
Usage:
\x1b[1mUsage:\x1b[0m
${NAME} [options] [config file path] [output file path]
Note: All arguments are optional, this is an interactive tool mainly.
\x1b[33mNote: All arguments are optional, this is an interactive tool mainly.\x1b[0m
Options:
--help, -h Show this help message
--launch Launch Firefox after profile creation
--output <path> Profile output path
\x1b[1mOptions:\x1b[0m
\x1b[32m--help, -h\x1b[0m Show this help message
\x1b[32m--launch\x1b[0m Launch Firefox after profile creation
\x1b[32m--output <path>\x1b[0m Profile output path
`);
process.exit(0);
};
Expand Down
45 changes: 30 additions & 15 deletions handlers/contentcss.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,40 @@ export default function handle({
options = {},
enabled = [],
}) {
log.info(`Starting handle function with ${enabled.length} enabled modules`);
let out = `/* ${defaultPrefs.preamble} */\n\n\n`;

for (let p of enabled) {
log.debug(`usercss: Enabling module ${p}`);
copyFilesToProfile(join(profilePath, "chrome", "content_css_files"), [
join(modulesPath, p),
try {
copyFilesToProfile(join(profilePath, "chrome", "content_css_files"), [
join(modulesPath, p),
]);
log.info(`Successfully copied module ${p} to profile`);
} catch (error) {
log.error(`Failed to copy module ${p} to profile: ${error.message}`);
}
}

try {
copyFilesToProfile(join(profilePath, "chrome"), [
{
name: "userContent.css",
append: true,
content:
`/* ${defaultPrefs.preamble} */\n\n` +
enabled
.map(
(i) =>
`@import url(${JSON.stringify(`content_css_files/${i}`)});`,
)
.join("\n"),
},
]);
log.info("Successfully created userContent.css");
} catch (error) {
log.error(`Failed to create userContent.css: ${error.message}`);
}
copyFilesToProfile(join(profilePath, "chrome"), [
{
name: "userContent.css",
append: true,
content:
`/* ${defaultPrefs.preamble} */\n\n` +
enabled
.map(
(i) => `@import url(${JSON.stringify(`content_css_files/${i}`)});`,
)
.join("\n"),
},
]);

log.debug("handle function completed");
}
25 changes: 5 additions & 20 deletions handlers/extensions.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,6 @@ export default async function handle({
options = {},
enabled = [],
}) {
// const policiesPath = join(appPath, "Contents", "Resources", "policies.json");
// let policies = readJSON(policiesPath);

// policies = {
// ...policies,
// ExtensionUpdate: true,
// };
// policies.ExtensionSettings = policies.ExtensionSettings || {};

let out = "/// BEGIN EXTENSIONS\n";
let prefs = {
"extensions.webextensions.uuids": {},
Expand All @@ -53,21 +44,19 @@ export default async function handle({
}
}
const install_url = `https://addons.mozilla.org/firefox/downloads/latest/${ext.slug}/platform:3/${ext.slug}.xpi`;
// Download the extension
log.info(`Downloading extension: ${ext.slug}`);
const buff = await fetch(install_url).then((r) => r.arrayBuffer());
log.debug(`Extension downloaded: ${ext.slug}`);
copyFilesToProfile(profilePath, [
{
name: `extensions/${ext.id}.xpi`,
content: Buffer.from(buff),
},
]);
// policies.ExtensionSettings[ext.id] = {
// install_url,
// installation_mode: "force_installed",
// };
prefs["extensions.webextensions.uuids"][ext.id] = ext.uuid;
prefs[`extensions.webextensions.ExtensionStorageIDB.migrated.${ext.id}`] =
true;
log.debug(`Extension installed: ${ext.slug}`);
}
prefs["extensions.webextensions.uuids"] = JSON.stringify({
...defaultExtensions,
Expand All @@ -78,17 +67,13 @@ export default async function handle({
.join("\n");
out += "\n/// END EXTENSIONS";

log.info("Writing user preferences");
copyFilesToProfile(profilePath, [
{
name: "user.js",
append: true,
content: out,
},
]);
// copyFilesToProfile(dirname(policiesPath), [
// {
// name: "policies.json",
// content: JSON.stringify(policies, null, 2),
// },
// ]);
log.debug("User preferences written successfully");
}
39 changes: 27 additions & 12 deletions handlers/repo.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ export default async function handle({
options = {},
enabled = [],
}) {
log.info(`Starting to handle ${enabled.length} enabled modules`);
for (let p of enabled) {
log.debug(`Processing module: ${p}`);
const repo = { ...readJSON(join(modulesPath, p)), ...(options[p] || {}) };
if (repo.prefs) {
log.info(`Applying preferences for module: ${p}`);
for (let [k, v] of Object.entries(repo.prefs)) {
copyFilesToProfile(profilePath, [
{
Expand All @@ -29,40 +32,43 @@ export default async function handle({
}\nuser_pref("${k}", ${JSON.stringify(v)});`,
},
]);
log.debug(`Applied preference: ${k} = ${JSON.stringify(v)}`);
}
}

const PATH = resolve(profilePath, "repos", repo.id);
log.info(`Setting up repository at: ${PATH}`);

if (repo.useReleases) {
const id = repo.url.replace(/\/$/, "").split("/").slice(-2).join("/");
log.debug('Getting latest release for "' + id + '"');
log.debug(`Getting latest release for: ${id}`);
const tags = await fetch(
`https://api.github.com/repos/${id}/releases/latest`
`https://api.github.com/repos/${id}/releases/latest`,
).then((r) => r.json());
const url = tags.assets.find((i) =>
i.name.startsWith(repo.useReleases)
i.name.startsWith(repo.useReleases),
)?.browser_download_url;
if (!url) {
log.error(`Failed to find download URL for ${id}`);
throw new Error("Couldn't find download url");
}
const ZIP_PATH = `${PATH}.zip`;
log.info("Downloading ZIP from releases ", url);
log.info(`Downloading ZIP from releases: ${url}`);
const buf = Buffer.from(await fetch(url).then((r) => r.arrayBuffer()));
ensureFolder(dirname(ZIP_PATH));
writeFileSync(ZIP_PATH, buf);
log.info("Unzipping " + ZIP_PATH);
log.info(`Unzipping ${ZIP_PATH}`);
await exec(
`unzip ${JSON.stringify(ZIP_PATH)} -d ${JSON.stringify(PATH)}`
`unzip ${JSON.stringify(ZIP_PATH)} -d ${JSON.stringify(PATH)}`,
);
log.debug("Done unzipping, removing file " + ZIP_PATH);
log.debug(`Finished unzipping, removing file: ${ZIP_PATH}`);
rmSync(ZIP_PATH);
} else {
log.info('Cloning repo "' + repo.url + '"');
log.info(`Cloning repo: ${repo.url}`);
await exec(
`git clone ${JSON.stringify(repo.url)} ${JSON.stringify(PATH)}`
`git clone ${JSON.stringify(repo.url)} ${JSON.stringify(PATH)}`,
);
log.debug("Done cloning repo");
log.debug(`Finished cloning repo: ${repo.url}`);
}
let bypass = false;
const custom = {
Expand All @@ -71,13 +77,15 @@ export default async function handle({
};
if (repo.userChrome) {
bypass = true;
log.info(`Writing custom userChrome.css for ${repo.id}`);
writeFileSync(resolve(PATH, custom.userChrome + ".css"), repo.userChrome);
}
if (repo.userContent) {
bypass = true;
log.info(`Writing custom userContent.css for ${repo.id}`);
writeFileSync(
resolve(PATH, custom.userContent + ".css"),
repo.userContent
repo.userContent,
);
}
const filesToLink = bypass
Expand All @@ -98,10 +106,11 @@ export default async function handle({
let alreadyDone = [];
for (let [k, v] of filesToLink) {
if (alreadyDone.includes(k)) {
log.debug(`Skipping duplicate file: ${k}`);
continue;
}
if (existsSync(v)) {
log.debug(`repo: Enabling module ${p} - ${k}`);
log.info(`Enabling module ${p} - ${k}`);
copyFilesToProfile(join(profilePath, "chrome"), [
{
name: k,
Expand All @@ -112,10 +121,13 @@ export default async function handle({
},
]);
alreadyDone.push(k);
} else {
log.warn(`File not found: ${v}`);
}
}

if (existsSync(resolve(PATH, "user.js"))) {
log.info(`Importing user.js from ${repo.id}`);
copyFilesToProfile(profilePath, [
{
name: "user.js",
Expand All @@ -127,7 +139,10 @@ export default async function handle({
readFileSync(resolve(PATH, "user.js"), "utf-8"),
},
]);
} else {
log.debug(`No user.js found for ${repo.id}`);
}
}
log.info("Finished handling all enabled modules");
return;
}
35 changes: 24 additions & 11 deletions handlers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,33 @@ export default function handle({
options = {},
enabled = [],
}) {
log.info("Starting userjs handling");
let out = `/* ${defaultPrefs.preamble} */\n\n\n`;

for (let p of enabled) {
log.debug(`userjs: Enabling module ${p}`);
out += `/// BEGIN_MODULE: ${p}\n${
readFile(`${modulesPath}/${p}`)?.trim() ||
"/// ERROR: Couldn't find module " + p
}\n/// END_MODULE: ${p}\n\n`;
const moduleContent = readFile(`${modulesPath}/${p}`);
if (moduleContent) {
out += `/// BEGIN_MODULE: ${p}\n${moduleContent.trim()}\n/// END_MODULE: ${p}\n\n`;
} else {
log.error(`Couldn't find module ${p}`);
out += `/// ERROR: Couldn't find module ${p}\n\n`;
}
}
copyFilesToProfile(profilePath, [
{
name: "user.js",
append: true,
content: out,
},
]);

log.info("Copying files to profile");
try {
copyFilesToProfile(profilePath, [
{
name: "user.js",
append: true,
content: out,
},
]);
log.debug("Files copied successfully");
} catch (error) {
log.error("Error copying files to profile:", error);
}

log.info("userjs handling completed");
}
43 changes: 27 additions & 16 deletions handlers/usercss.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,37 @@ export default function handle({
options = {},
enabled = [],
}) {
log.info(`Starting usercss handling for profile: ${profilePath}`);
let out = `/* ${defaultPrefs.preamble} */\n\n\n`;

for (let p of enabled) {
log.debug(`usercss: Enabling module ${p}`);
copyFilesToProfile(join(profilePath, "chrome", "css_files"), [
join(modulesPath, p),
try {
copyFilesToProfile(join(profilePath, "chrome", "css_files"), [
join(modulesPath, p),
]);
log.info(`Successfully copied module ${p} to profile`);
} catch (error) {
log.error(`Failed to copy module ${p} to profile: ${error.message}`);
}
}

try {
copyFilesToProfile(join(profilePath, "chrome"), [
{
name: "userChrome.css",
append: true,
content:
`/* ${defaultPrefs.preamble} */\n\n` +
enabled
.map((i) => `@import url(${JSON.stringify(`css_files/${i}`)});`)
.join("\n"),
},
]);
log.info("Successfully created or updated userChrome.css");
} catch (error) {
log.error(`Failed to create or update userChrome.css: ${error.message}`);
}
copyFilesToProfile(join(profilePath, "chrome"), [
{
name: "userChrome.css",
append: true,
content:
`/* ${defaultPrefs.preamble} */\n\n` +
enabled
.map(
(i) =>
`@import url(${JSON.stringify(`css_files/${i}`)});`
)
.join("\n"),
},
]);

log.info("Finished usercss handling");
}
8 changes: 4 additions & 4 deletions helpers/log.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const log = {
debug: console.log,
error: console.error,
info: console.info,
warn: console.warn,
debug: (...args) => console.log("\x1b[36m[DEBUG]\x1b[0m", ...args),
error: (...args) => console.error("\x1b[31m[ERROR]\x1b[0m", ...args),
info: (...args) => console.info("\x1b[34m[INFO]\x1b[0m", ...args),
warn: (...args) => console.warn("\x1b[33m[WARN]\x1b[0m", ...args),
};

export default log;
12 changes: 9 additions & 3 deletions modules/repos/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,21 @@
"handler": "handlers/repo.js",
"buildOrder": 10,
"modules": {
"minifox.json": {
"description": "Minifox Theme"
},
"animatedfox.json": {
"description": "AnimatedFox Theme"
},
"ff-ultima.json": {
"description": "Completely customizable firefox theme"
},
"firefox-ui-fix.json": {
"description": "Firefox UI fix"
},
"materialfox.json": {
"description": "MaterialFox Theme"
},
"minifox.json": {
"description": "Minifox Theme"
},
"safari-style.json": {
"description": "Safari Style"
},
Expand Down

0 comments on commit f1e5261

Please sign in to comment.