Skip to content

Commit

Permalink
run and install prettier on cli
Browse files Browse the repository at this point in the history
  • Loading branch information
polypixeldev committed Sep 18, 2024
1 parent d0a70de commit acb5c9c
Show file tree
Hide file tree
Showing 9 changed files with 208 additions and 153 deletions.
1 change: 1 addition & 0 deletions cli/.prettierc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
169 changes: 96 additions & 73 deletions cli/commands/caddy.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,101 @@
module.exports = function ({ program }) {
const caddy = program.command("caddy")
caddy
.command('list')
.description('lists all domains you have configured in caddy')
.option('--user [user]', 'allows you to add a domain on behalf of a user (requires sudo)')
.action(async (options) => {
const domainsRes = await fetch(`http://localhost:999/list${options.user ? `?impersonateUser=${options.user}` : ""}`);
const caddy = program.command("caddy");
caddy
.command("list")
.description("lists all domains you have configured in caddy")
.option(
"--user [user]",
"allows you to add a domain on behalf of a user (requires sudo)",
)
.action(async (options) => {
const domainsRes = await fetch(
`http://localhost:999/list${options.user ? `?impersonateUser=${options.user}` : ""}`,
);

if (domainsRes.status !== 200) {
console.error(await domainsRes.text() || domainsRes.statusText)
process.exit(1);
} else {
console.log(await domainsRes.text())
}
});
caddy
.command('add <domain>')
.description('adds a domain to caddy')
.option('--proxy [proxy]', 'changes where the domain should be proxied to (advanced)')
.option('--user [user]', "allows you to list a different user's domains (requires sudo)")
.action(async (domain, options) => {
const addRes = await fetch(`http://localhost:999/domain/new${options.user ? `?impersonateUser=${options.user}` : ""}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
domain,
proxy: options?.proxy
})
});
if (domainsRes.status !== 200) {
console.error((await domainsRes.text()) || domainsRes.statusText);
process.exit(1);
} else {
console.log(await domainsRes.text());
}
});
caddy
.command("add <domain>")
.description("adds a domain to caddy")
.option(
"--proxy [proxy]",
"changes where the domain should be proxied to (advanced)",
)
.option(
"--user [user]",
"allows you to list a different user's domains (requires sudo)",
)
.action(async (domain, options) => {
const addRes = await fetch(
`http://localhost:999/domain/new${options.user ? `?impersonateUser=${options.user}` : ""}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
domain,
proxy: options?.proxy,
}),
},
);

if (addRes.status !== 200) {
console.error(await addRes.text() || addRes.statusText)
process.exit(1);
} else {
console.log(await addRes.text())
}
});
caddy
.command('rm <domain>')
.description('removes a domain from caddy')
.option('--user [user]', 'allows you to add a domain on behalf of a user (requires sudo)')
.action(async (domain, options) => {
const removeRes = await fetch(`http://localhost:999/domain/delete${options.user ? `?impersonateUser=${options.user}` : ""}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
domain
})
});
if (addRes.status !== 200) {
console.error((await addRes.text()) || addRes.statusText);
process.exit(1);
} else {
console.log(await addRes.text());
}
});
caddy
.command("rm <domain>")
.description("removes a domain from caddy")
.option(
"--user [user]",
"allows you to add a domain on behalf of a user (requires sudo)",
)
.action(async (domain, options) => {
const removeRes = await fetch(
`http://localhost:999/domain/delete${options.user ? `?impersonateUser=${options.user}` : ""}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
domain,
}),
},
);

if (removeRes.status !== 200) {
console.error(await removeRes.text() || removeRes.statusText)
process.exit(1);
} else {
console.log(await removeRes.text())
}
});
caddy
.command('reload')
.description('reloads the global caddy instance (admins only)')
.action(async () => {
const reloadRes = await fetch(`http://localhost:999/reload${options.user ? `?impersonateUser=${options.user}` : ""}`, {
method: "POST",
});
if (removeRes.status !== 200) {
console.error((await removeRes.text()) || removeRes.statusText);
process.exit(1);
} else {
console.log(await removeRes.text());
}
});
caddy
.command("reload")
.description("reloads the global caddy instance (admins only)")
.action(async () => {
const reloadRes = await fetch(
`http://localhost:999/reload${options.user ? `?impersonateUser=${options.user}` : ""}`,
{
method: "POST",
},
);

if (reloadRes.status !== 200) {
console.error(await reloadRes.text() || reloadRes.statusText)
process.exit(1);
} else {
console.log(await reloadRes.text())
}
});
}
if (reloadRes.status !== 200) {
console.error((await reloadRes.text()) || reloadRes.statusText);
process.exit(1);
} else {
console.log(await reloadRes.text());
}
});
};
25 changes: 13 additions & 12 deletions cli/commands/db.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
module.exports = function ({ program, run }) {
const db = program.command("db")
const db = program.command("db");

db
.command('create <name>')
.description('Create a new Postgres database')
.action((name) => {
if (/[^a-z0-9]/gi.test(name)) {
console.error("Your database name can only include alphanumeric characters (a-Z, 0-9)")
process.exit(1)
}
run(`sudo -u postgres /usr/local/nest/cli/helpers/create_db.sh ${name}`);
});
}
db.command("create <name>")
.description("Create a new Postgres database")
.action((name) => {
if (/[^a-z0-9]/gi.test(name)) {
console.error(
"Your database name can only include alphanumeric characters (a-Z, 0-9)",
);
process.exit(1);
}
run(`sudo -u postgres /usr/local/nest/cli/helpers/create_db.sh ${name}`);
});
};
26 changes: 13 additions & 13 deletions cli/commands/get_port.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
const net = require('node:net');
const net = require("node:net");

module.exports = function ({ program, run }) {
program
.command('get_port')
.description('Get an open port to use for your app')
.action(() => {
const server = net.createServer();
server.listen(0, '127.0.0.1', () => {
const port = server.address().port;
console.log(`Port ${port} is free to use!`);
server.close();
});
});
}
program
.command("get_port")
.description("Get an open port to use for your app")
.action(() => {
const server = net.createServer();
server.listen(0, "127.0.0.1", () => {
const port = server.address().port;
console.log(`Port ${port} is free to use!`);
server.close();
});
});
};
65 changes: 43 additions & 22 deletions cli/commands/resources.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,48 @@
const fs = require('node:fs');
const fs = require("node:fs");

module.exports = function ({ program, run }) {
program
.command('resources')
.description('See your Nest resource usage and limits')
.action(() => {
if (!process.getuid()){
console.log("Root doesn't have any limits.")
process.exit(0)
}
const output = run(`quota`).toString();
const numbers = output.split("\n").find(line => line.includes("/dev/sda")).match(/\d+/g);
const array = numbers.map(Number)
const blockSize = 1024;
program
.command("resources")
.description("See your Nest resource usage and limits")
.action(() => {
if (!process.getuid()) {
console.log("Root doesn't have any limits.");
process.exit(0);
}
const output = run(`quota`).toString();
const numbers = output
.split("\n")
.find((line) => line.includes("/dev/sda"))
.match(/\d+/g);
const array = numbers.map(Number);
const blockSize = 1024;

const usedGB = (array[1] * blockSize) / (1024 ** 3);
const quotaGB = (array[2] * blockSize) / (1024 ** 3);
const usedGB = (array[1] * blockSize) / 1024 ** 3;
const quotaGB = (array[2] * blockSize) / 1024 ** 3;

console.log(`Disk usage: ${usedGB.toFixed(2)} GB used out of ${quotaGB.toFixed(2)} GB limit`);
console.log(
`Disk usage: ${usedGB.toFixed(2)} GB used out of ${quotaGB.toFixed(2)} GB limit`,
);

const userId = process.getuid()
const memoryUsage = (parseFloat(fs.readFileSync(`/sys/fs/cgroup/user.slice/user-${userId}.slice/memory.current`)) / (1024 * 1024 * 1024)).toFixed(2);
const memoryLimit = (parseFloat(fs.readFileSync(`/sys/fs/cgroup/user.slice/user-${userId}.slice/memory.high`)) / (1024 * 1024 * 1024)).toFixed(2);
console.log(`Memory usage: ${memoryUsage} GB used out of ${memoryLimit} GB limit`);
});
}
const userId = process.getuid();
const memoryUsage = (
parseFloat(
fs.readFileSync(
`/sys/fs/cgroup/user.slice/user-${userId}.slice/memory.current`,
),
) /
(1024 * 1024 * 1024)
).toFixed(2);
const memoryLimit = (
parseFloat(
fs.readFileSync(
`/sys/fs/cgroup/user.slice/user-${userId}.slice/memory.high`,
),
) /
(1024 * 1024 * 1024)
).toFixed(2);
console.log(
`Memory usage: ${memoryUsage} GB used out of ${memoryLimit} GB limit`,
);
});
};
30 changes: 16 additions & 14 deletions cli/commands/setup.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
module.exports = function ({ program, run }) {
const setup = program.command('setup');
setup
.command('docker')
.description('Set up rootless docker, so you can run docker containers')
.action(() => {
run('dockerd-rootless-setuptool.sh install');
run(`sed -i '/^ExecStart/ s/$/ --exec-opt native.cgroupdriver=cgroupfs /' ~/.config/systemd/user/docker.service`);
run('systemctl --user daemon-reload');
run('systemctl --user enable docker');
run('systemctl --user restart docker');
run('docker context use rootless');
console.log('Successfully configured docker.');
});
}
const setup = program.command("setup");
setup
.command("docker")
.description("Set up rootless docker, so you can run docker containers")
.action(() => {
run("dockerd-rootless-setuptool.sh install");
run(
`sed -i '/^ExecStart/ s/$/ --exec-opt native.cgroupdriver=cgroupfs /' ~/.config/systemd/user/docker.service`,
);
run("systemctl --user daemon-reload");
run("systemctl --user enable docker");
run("systemctl --user restart docker");
run("docker context use rootless");
console.log("Successfully configured docker.");
});
};
37 changes: 18 additions & 19 deletions cli/index.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
#!/usr/bin/node
const { Command } = require('commander');
const { Command } = require("commander");
const program = new Command();
const { execSync } = require('child_process');
const { execSync } = require("child_process");

require("dotenv").config();

function run(command) {
try {
console.log(`> ${command}`)
return execSync(command, { stdio: 'pipe' }).toString();
} catch (error) {
console.error(error.message);
process.exit(1);
}
try {
console.log(`> ${command}`);
return execSync(command, { stdio: "pipe" }).toString();
} catch (error) {
console.error(error.message);
process.exit(1);
}
}
program
.name('nest')
.description('A command-line interface for Nest tools and services')
.version(require("./package.json").version);
.name("nest")
.description("A command-line interface for Nest tools and services")
.version(require("./package.json").version);

require("./commands/setup")({ program, run });
require("./commands/db")({ program, run });
require("./commands/caddy")({ program, run });
require("./commands/resources")({ program, run });
require("./commands/get_port")({ program, run });

require("./commands/setup")({ program, run })
require("./commands/db")({ program, run })
require("./commands/caddy")({ program, run })
require("./commands/resources")({ program, run })
require("./commands/get_port")({ program, run })

program.parse(process.argv);
program.parse(process.argv);
Loading

0 comments on commit acb5c9c

Please sign in to comment.