@eljs/utils
Version:
Collection of nodejs utility.
390 lines (388 loc) • 11.3 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/git/meta.ts
var meta_exports = {};
__export(meta_exports, {
getGitBranch: () => getGitBranch,
getGitCommitSha: () => getGitCommitSha,
getGitLatestTag: () => getGitLatestTag,
getGitRepository: () => getGitRepository,
getGitRepositorySync: () => getGitRepositorySync,
getGitUpstreamBranch: () => getGitUpstreamBranch,
getGitUrl: () => getGitUrl,
getGitUrlSync: () => getGitUrlSync,
getGitUser: () => getGitUser,
getGitUserSync: () => getGitUserSync,
getProjectGitDir: () => getProjectGitDir,
getProjectGitDirSync: () => getProjectGitDirSync,
gitUrlAnalysis: () => gitUrlAnalysis
});
module.exports = __toCommonJS(meta_exports);
var import_cp = require("../cp");
var import_file = require("../file");
var import_type = require("../type");
var import_execa = __toESM(require("execa"));
var import_ini = __toESM(require("ini"));
var import_node_os = __toESM(require("node:os"));
var import_node_path = __toESM(require("node:path"));
var import_node_url = require("node:url");
async function getGitUrl(cwd, exact) {
const gitDir = exact ? import_node_path.default.join(cwd, ".git") : await getProjectGitDir(cwd) || "";
if (!await (0, import_file.isPathExists)(gitDir)) {
return "";
}
try {
const parsed = import_ini.default.parse(await (0, import_file.readFile)(import_node_path.default.join(gitDir, "config")));
if (parsed['remote "origin"']) {
return parsed['remote "origin"'].url;
}
} catch (err) {
}
return "";
}
function getGitUrlSync(cwd, exact) {
const gitDir = exact ? import_node_path.default.join(cwd, ".git") : getProjectGitDirSync(cwd) || "";
if (!(0, import_file.isPathExistsSync)(gitDir)) {
return "";
}
try {
const parsed = import_ini.default.parse((0, import_file.readFileSync)(import_node_path.default.join(gitDir, "config")));
if (parsed['remote "origin"']) {
return parsed['remote "origin"'].url;
}
} catch (err) {
}
return "";
}
async function getGitBranch(options) {
return (0, import_cp.run)("git", ["rev-parse", "--abbrev-ref", "HEAD"], options).then(
(data) => {
return data.stdout.trim();
}
);
}
async function getGitUpstreamBranch(options) {
try {
const upstream = await (0, import_cp.run)(
"git",
["rev-parse", "--abbrev-ref", "@{u}"],
options
).then((data) => {
return data.stdout.trim();
});
return upstream;
} catch (err) {
return null;
}
}
async function getGitCommitSha(short, options) {
if ((0, import_type.isObject)(short)) {
options = short;
short = false;
}
const cliArgs = ["rev-parse", ...short ? ["--short"] : [], "HEAD"].filter(
Boolean
);
return (0, import_cp.run)("git", cliArgs, options).then((data) => {
return data.stdout.trim();
});
}
async function getGitLatestTag(match, args, options) {
if ((0, import_type.isObject)(match)) {
options = match;
args = [];
match = void 0;
}
if ((0, import_type.isObject)(args)) {
options = args;
args = [];
}
const cliArgs = [
"describe",
"--tags",
"--match",
match || "*",
...args ? args : []
].filter(Boolean);
try {
const { stdout } = await (0, import_cp.run)("git", cliArgs, options);
return stdout.trim();
} catch (error) {
return null;
}
}
function gitUrlAnalysis(url) {
var _a, _b;
if (!url) {
return null;
}
try {
let repo = "";
let hostname = "";
if (url.startsWith("git")) {
const pieces = url.split(":");
hostname = pieces[0].split("@")[1];
repo = pieces[1].replace(/\.git$/, "");
} else if (url.startsWith("http")) {
const parsedUrl = new import_node_url.URL(url);
hostname = parsedUrl.hostname || "";
repo = ((_b = (_a = parsedUrl.pathname) == null ? void 0 : _a.slice(1)) == null ? void 0 : _b.replace(/\.git$/, "")) || "";
} else {
return null;
}
let group = "";
let name = "";
repo.split("/").forEach((str, index, arr) => {
if (index === arr.length - 1) {
name = str;
} else {
group += `/${str}`;
}
});
group = group.substring(1);
return {
name,
group,
href: `https://${hostname}/${group}/${name}`,
https: `https://${hostname}/${group}/${name}.git`,
ssh: `git@${hostname}:${group}/${name}.git`
};
} catch (err) {
return null;
}
}
async function getGitRepository(dir, exact) {
const gitDir = exact ? import_node_path.default.join(dir, ".git") : await getProjectGitDir(dir) || "";
if (!await (0, import_file.isPathExists)(gitDir)) {
return null;
}
const gitRepo = {
name: "",
group: "",
href: "",
https: "",
ssh: "",
branch: "",
author: "",
email: ""
};
try {
const config = import_ini.default.parse(await (0, import_file.readFile)(import_node_path.default.join(gitDir, "config")));
if (config['remote "origin"']) {
gitRepo.ssh = config['remote "origin"'].url;
if (gitRepo.ssh) {
Object.assign(gitRepo, gitUrlAnalysis(gitRepo.ssh));
}
}
if (config["user"]) {
gitRepo.author = config["user"].name;
gitRepo.email = config["user"].email;
}
const gitHead = await (0, import_file.readFile)(import_node_path.default.join(gitDir, "HEAD"));
gitRepo.branch = gitHead.replace("ref: refs/heads/", "").replace(import_node_os.EOL, "");
} catch (err) {
return null;
}
return gitRepo;
}
function getGitRepositorySync(dir, exact) {
const gitDir = exact ? import_node_path.default.join(dir, ".git") : getProjectGitDirSync(dir) || "";
if (!(0, import_file.isPathExistsSync)(gitDir)) {
return null;
}
const gitRepo = {
name: "",
group: "",
href: "",
https: "",
ssh: "",
branch: "",
author: "",
email: ""
};
try {
const config = import_ini.default.parse((0, import_file.readFileSync)(import_node_path.default.join(gitDir, "config")));
if (config['remote "origin"']) {
gitRepo.ssh = config['remote "origin"'].url;
if (gitRepo.ssh) {
Object.assign(gitRepo, gitUrlAnalysis(gitRepo.ssh));
}
}
if (config["user"]) {
gitRepo.author = config["user"].name;
gitRepo.email = config["user"].email;
}
const gitHead = (0, import_file.readFileSync)(import_node_path.default.join(gitDir, "HEAD"));
gitRepo.branch = gitHead.replace("ref: refs/heads/", "").replace(import_node_os.EOL, "");
} catch (err) {
return null;
}
return gitRepo;
}
async function getGitUser() {
let user = {
name: "",
email: ""
};
try {
const gitConfig = (await (0, import_execa.default)("git", ["config", "--list"])).stdout;
if (gitConfig) {
const config = /* @__PURE__ */ Object.create(null);
gitConfig.split(import_node_os.EOL).forEach((line) => {
const [key, value] = line.split("=");
config[key] = value;
});
if (config["user.email"]) {
user = {
name: config["user.email"].split("@")[0],
email: config["user.email"]
};
} else {
user = {
name: config["user.name"],
email: ""
};
}
}
} catch (err) {
}
if (user.email.match(/\.com$/)) {
return user;
}
try {
const gitFile = import_node_path.default.join(import_node_os.default.homedir(), ".gitconfig");
const parsed = import_ini.default.parse(await (0, import_file.readFile)(gitFile));
const { name, email } = parsed.user;
if (email) {
user = {
name: email.split("@")[0],
email
};
} else {
user = {
name,
email: ""
};
}
} catch (err) {
}
return user;
}
function getGitUserSync() {
let user = {
name: "",
email: ""
};
try {
const gitConfig = import_execa.default.sync("git", ["config", "--list"]).stdout;
if (gitConfig) {
const config = /* @__PURE__ */ Object.create(null);
gitConfig.split(import_node_os.EOL).forEach((line) => {
const [key, value] = line.split("=");
config[key] = value;
});
if (config["user.email"]) {
user = {
name: config["user.email"].split("@")[0],
email: config["user.email"]
};
} else {
user = {
name: config["user.name"],
email: ""
};
}
}
} catch (err) {
}
if (user.email.match(/\.com$/)) {
return user;
}
try {
const gitFile = import_node_path.default.join(import_node_os.default.homedir(), ".gitconfig");
const parsed = import_ini.default.parse((0, import_file.readFileSync)(gitFile));
const { name, email } = parsed.user;
if (email) {
user = {
name: email.split("@")[0],
email
};
} else {
user = {
name,
email: ""
};
}
} catch (err) {
}
return user;
}
async function getProjectGitDir(dir) {
let cur = dir;
while (cur) {
if (await (0, import_file.isPathExists)(import_node_path.default.join(cur, ".git", "config"))) {
return import_node_path.default.join(cur, ".git");
}
const parent = import_node_path.default.dirname(cur);
if (parent === cur) {
break;
} else {
cur = parent;
}
}
}
function getProjectGitDirSync(dir) {
let cur = dir;
while (cur) {
if ((0, import_file.isPathExistsSync)(import_node_path.default.join(cur, ".git", "config"))) {
return import_node_path.default.join(cur, ".git");
}
const parent = import_node_path.default.dirname(cur);
if (parent === cur) {
break;
} else {
cur = parent;
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getGitBranch,
getGitCommitSha,
getGitLatestTag,
getGitRepository,
getGitRepositorySync,
getGitUpstreamBranch,
getGitUrl,
getGitUrlSync,
getGitUser,
getGitUserSync,
getProjectGitDir,
getProjectGitDirSync,
gitUrlAnalysis
});