diff --git a/bashUtils/index.sh b/bashUtils/index.sh new file mode 100644 index 0000000..fa50f98 --- /dev/null +++ b/bashUtils/index.sh @@ -0,0 +1,39 @@ + +export UNAME="$(uname)" +setopt aliases complete_aliases +unsetopt multios + +function jjOsPackageMamanger { + + SUPPORTED_PACKAGE_MANAGERS=("apt-get -y" "brew" "yum -y") + + for i in "${SUPPORTED_PACKAGE_MANAGERS[@]}"; do + PACKAGE_MANAGER=($i) + if test "$( which "$PACKAGE_MANAGER" )"; then + echo "$(which ${PACKAGE_MANAGER[0]}) ${PACKAGE_MANAGER[1]} $1" + return 0 + fi + done + return 1 +} + +function jjIsFileOlderDuration { + if [[ ! $(find "$1" -newermt "$2 ago") ]]; then + return 0 + fi + return 1 +} + + +function jjIsFileNewerFile { + if [[ "$1" -nt "$2" ]]; then + echo "File ($(date -r $1)) '$1' is newer than" + echo "file ($(date -r $2)) '$2'!" + return 0 + fi + return 1 +} + +function jjCliLog { + "$JJ_SOURCE_DIR/helpers/jjLogger.ts" $1 ${@:2} +} diff --git a/bin/run.cmd b/bin/run.cmd deleted file mode 100644 index 968fc30..0000000 --- a/bin/run.cmd +++ /dev/null @@ -1,3 +0,0 @@ -@echo off - -node "%~dp0\run" %* diff --git a/bin/run.ts b/bin/run.ts index 166e6a5..b9f168f 100755 --- a/bin/run.ts +++ b/bin/run.ts @@ -2,10 +2,32 @@ -import {execute, settings} from '@oclif/core' +import { execute, settings } from '@oclif/core' +import { execSync } from 'child_process' + +try { + // // Source asdf from your shell profile and capture environment variables + // const asdfEnv = execSync('source ~/.asdf/asdf.sh && env', { shell: '/bin/bash' }) + // .toString() + // .split('\n') + // .reduce((acc, line) => { + // const [key, value] = line.split('='); + // if (key && value) acc[key] = value; + // return acc; + // }, {}); + + // // Add the asdf environment to the current process + // Object.assign(process.env, asdfEnv); + + // // Now, asdf is available in process.env, and you can use it + // console.log(execSync('asdf list all nodejs').toString()); + +} catch (error) { + console.error(`Failed to load asdf: ${error.message}`); +} // process.env.DEBUG="" settings.performanceEnabled = true -await execute({dir: import.meta.url}) +await execute({ dir: import.meta.url }) diff --git a/bun.lockb b/bun.lockb index 31bf609..87cadbe 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/helpers/jjEnsure.ts b/helpers/jjEnsure.ts index e772545..ce9e961 100644 --- a/helpers/jjEnsure.ts +++ b/helpers/jjEnsure.ts @@ -36,6 +36,7 @@ export const jjEnsure = async (opts) => { if (_.isEmpty(jjYamlObj?.environments || {})) { opts.context.error(`Wrong ${answer.jjYamlPath} file`) } + jjConfigs.jjWorkSpacePath = path.dirname(answer.jjYamlPath) jjConfigs.jjYamlObj = jjYamlObj @@ -43,6 +44,7 @@ export const jjEnsure = async (opts) => { } else { jjConfigs.jjYamlPath = await fs.readFile(jjConfigs.configSaveFilePath, "utf8") + jjConfigs.jjWorkSpacePath = path.dirname(jjConfigs.jjYamlPath) const jjYamlRawContent = await fs.readFile(jjConfigs.jjYamlPath, "utf8") const jjYamlObj: any = YAML.load(jjYamlRawContent) if (_.isEmpty(jjYamlObj?.environments || {})) { @@ -51,4 +53,6 @@ export const jjEnsure = async (opts) => { jjConfigs.jjYamlObj = jjYamlObj } + jjConfigs.processEnvs.JJ_WORKSPACE_DIR = jjConfigs.jjWorkSpacePath + } \ No newline at end of file diff --git a/helpers/jjLogger.ts b/helpers/jjLogger.ts new file mode 100755 index 0000000..39edbb3 --- /dev/null +++ b/helpers/jjLogger.ts @@ -0,0 +1,131 @@ +#!/usr/bin/env bun +import { pino, type LoggerOptions, type Level } from 'pino'; +import os from 'os'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import chalk from 'chalk'; +import { customLevels } from './pino-pretty-transport'; +import _ from 'lodash' + +export const jjLoggerObj = {} + +const __filename = fileURLToPath(import.meta.url); + +const logFilePath = `${process.env.JJ_SOURCE_DIR}/~~tmp/jj.log`; +jjLoggerObj['logFilePath'] = logFilePath + + + +export const jjLogger = pino({ + customLevels: customLevels, + level: 'info', + base: { + host: os.hostname(), + filename: path.basename(__filename), + app: 'jj', + }, + transport: { + targets: [ + { + target: 'pino/file', + options: { destination: logFilePath, mkdir: true }, + level: 'info', + }, + { + target: './pino-pretty-transport', + }, + + ], + + } +}); + +jjLoggerObj['jjLogger'] = jjLogger + + +export const makeJJlogger = (opt) => { + const childJJLogger = jjLogger.child({ + ...opt + }) + + return childJJLogger +} +jjLoggerObj['makeJJlogger'] = makeJJlogger + +export const jjLog = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.log(message); +} +jjLoggerObj['jjLog'] = jjLog +// jjLog('jjLog', { test1: 'test1' }) + +export const jjLogInfo = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.info(message, opt); +} +jjLoggerObj['jjLogInfo'] = jjLogInfo +// jjLogInfo('jjLogInfo', { test1: 'test1' }) + +export const jjLogHeading = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.heading(`======================================================= + ${message} +========================================================`, opt); +} +jjLoggerObj['jjLogHeading'] = jjLogHeading +// jjLogHeading('jjLogHeading', { test1: 'test1' }) + +export const jjLogAction = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.action(`${message}`, opt); +} +jjLoggerObj['jjLogAction'] = jjLogAction +// jjLogAction('jjLogAction', { test1: 'test1' }) +export const jjLogError = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.error(message, opt); +} +jjLoggerObj['jjLogError'] = jjLogError +// jjLogError('jjLogError') + +export const jjLogWarning = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.warn(message, opt); +} +jjLoggerObj['jjLogWarning'] = jjLogWarning +// jjLogWarning('jjLogWarning', { test1: 'test1' }) + +export const jjLogSuccess = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.success(message, opt); +} +jjLoggerObj['jjLogSuccess'] = jjLogSuccess +// jjLogSuccess('jjLogSuccess', { test1: 'test1' }) + +export const jjBgRed = (message, opt = {}) => { + const cLogger = makeJJlogger(opt) + cLogger.bgRed(message, opt); +} +jjLoggerObj['jjBgRed'] = jjBgRed +// jjBgRed('jjBgRed', { test1: 'test1' }) + + + + + +if (_.get(process.argv, "[1]", "")?.includes('helpers/jjLogger.ts')) { + const args = [...process.argv] + args.shift() + args.shift() + if (args.length > 0) { + const loggerCal = jjLoggerObj[args[0]] + args.shift() + const [, ...restArgs] = [, ...args] + const message = restArgs[0] + if(!message){ + process.exit(0) + } + restArgs.shift() + loggerCal(message, { ...restArgs }) + } +} \ No newline at end of file diff --git a/helpers/pino-pretty-transport.ts b/helpers/pino-pretty-transport.ts new file mode 100644 index 0000000..d0a9240 --- /dev/null +++ b/helpers/pino-pretty-transport.ts @@ -0,0 +1,160 @@ +import _ from 'lodash'; +import pino from 'pino'; +import chalk from 'chalk'; +import moment from 'moment'; +import { safeStringify } from './safeJson'; + + +export const customLevels = { + ...pino.levels.values, + log: 31, + action: 32, + heading: 33, + success: 35, + bgRed: 36 +}; + + +// https://github.com/chalk/chalk + +const customColors = { + trace: "cyan", + debug: "blue", + info: "reset", + warn: "yellow", + error: "red", + fatal: "red", + log: 'white', + action: 'magenta', + heading: 'whiteBright', + success: "green", + bgRed: 'bgRed' +} +const customBold = { + trace: false, + debug: false, + info: false, + warn: true, + error: true, + fatal: true, + log: false, + action: true, + heading: true, + success: true, + bgRed: true +} + +const customLevelsById = {} + +Object.keys(customLevels).forEach((levelKey) => { + customLevelsById[customLevels[levelKey]] = { + levelKey, + color: customColors[levelKey], + isBold: customBold[levelKey] || false + } +}) + +function hostFormat(str) { + if (str.length < 9) { + const firstPart = str.slice(0, 5); + const remainingPart = str.slice(5); + return `${firstPart}#${remainingPart}`; + } + const firstPart = str.slice(0, 5); + const lastPart = str.slice(-4); + return `${firstPart}#${lastPart}`; +} + +function messageMultilineToArray(message) { + // Split the message by newline characters (\n or \r\n) + const lines = message.split(/\r?\n/); + return lines; +} + +function formatLogLevelString(str) { + const newStr = str.slice(0, 3); + if (newStr.length < 3) { + return newStr.padEnd(3, ' '); // Pad with spaces to reach 3 characters + } + return newStr.slice(0, 3); // Trim to 25 characters +} + +function removeTrailingNewline(str) { + return str.replace(/[\r\n]+$/, ''); +} + +export default (opts) => require('pino-pretty')({ + ...opts, + customLevels: Object.entries(customLevels).map(([key, value]) => (`${key}:${value}`)).join(','), + customColors: customColors, + colorize: true, + colorizeObjects: true, + // crlf: true, + ignore: 'time,level', + // singleLine: true, + hideObject: true, + // levelLabel: 'levelLabel', // --levelLabel + // translateTime: 'SYS:standard', + // include: 'host,pid,time,level,filename,app', // --include + + // sync: true + // messageFormat: (log, messageKey, levelLabel) => { + // // do some log message customization + // return ""; + // } + messageFormat: (log, messageKey) => { + + const logConfigObj = customLevelsById[log.level] + + const cloneLog = _.cloneDeep(log) + let prefixMessage = `` + + if (cloneLog.time) { + prefixMessage += `${moment(cloneLog.time).format('DDHHmmss')}#` + delete cloneLog.time + } + if (cloneLog.host) { + prefixMessage += `${hostFormat(cloneLog.host)}_` + delete cloneLog.host + } + if (cloneLog.app) { + prefixMessage += `${cloneLog.app}=` + delete cloneLog.app + } + if (cloneLog.filename) { + prefixMessage += `${cloneLog.filename} ` + delete cloneLog.filename + } + + prefixMessage += formatLogLevelString(`${logConfigObj.levelKey.toUpperCase()}: `) + + const messageList = messageMultilineToArray(cloneLog[messageKey]) + + delete cloneLog.msg + delete cloneLog.level + + let message = '' + messageList.forEach(mes=> { + message += `${prefixMessage} ${mes}\n` + }) + + message = removeTrailingNewline(message) + + if (!_.isEmpty(cloneLog)) { + message += `\n${prefixMessage} ${safeStringify(cloneLog)}` + } + + + + + if (logConfigObj.color?.startsWith('bg')) { + return chalk[logConfigObj.color](message) + } + if (logConfigObj.isBold) { + return chalk.bold[logConfigObj.color](message) + } + return chalk[logConfigObj.color](message) + + + } +}) \ No newline at end of file diff --git a/helpers/safeJson.ts b/helpers/safeJson.ts new file mode 100644 index 0000000..e43d0eb --- /dev/null +++ b/helpers/safeJson.ts @@ -0,0 +1,13 @@ +export function safeStringify(obj) { + const seen = new WeakSet(); + + return JSON.stringify(obj, (key, value) => { + if (typeof value === "object" && value !== null) { + if (seen.has(value)) { + return `[Circular ${key}]`; // Label circular reference with the key + } + seen.add(value); + } + return value; + }); +} diff --git a/jj.filelocation b/jj.filelocation new file mode 100644 index 0000000..e69de29 diff --git a/jj.sh b/jj.sh new file mode 100755 index 0000000..c12c7a8 --- /dev/null +++ b/jj.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env zsh + +set - + + +jjCpmmandRunPoint=$(echo ${BASH_SOURCE[0]}) + + + + +function findJJSource { + # @source http://stackoverflow.com/a/246128/330439 + local SOURCE="$jjCpmmandRunPoint" + local DIR="" + while [[ -h "$SOURCE" ]]; do + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" + done + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + while [[ ! -e "${DIR}/jj.filelocation" ]]; do + DIR=$(dirname "${DIR}") + done + echo "${DIR}" +} + + +export JJ_SOURCE_DIR=$(findJJSource) + +if [[ -e ~/.bun/bin/bun ]]; then + export PATH="~/.bun/bin:${PATH}" +fi + +__bunVersionExpect="1.1.34" +__currentBunVersion=$(bun --version || true) +if [[ "$__currentBunVersion" != "${__bunVersionExpect}" ]]; then + rm -rf ~/.bun/bin/bun + curl -fsSL https://bun.sh/install | bash -s "bun-v$__bunVersionExpect" + export PATH="~/.bun/bin:${PATH}" +fi + + +mkdir -p "$JJ_SOURCE_DIR/~~tmp" + +alias jj="$JJ_SOURCE_DIR/jj.sh" + + +source "$JJ_SOURCE_DIR/bashUtils/index.sh" + +# jjCliLog jjLog testjjLog a b c s +# jjCliLog jjLogInfo testjjLogInfo +# jjCliLog jjLogHeading testjjLogHeading + + +export ASDF_DIR="$JJ_SOURCE_DIR/~~asdf_gc" +export ASDF_DATA_DIR="$JJ_SOURCE_DIR/~~asdf_gc" +export ASDF_VERSION=v0.14.1 + + +# if [[ ! -e $JJ_SOURCE_DIR/~~tmp/pa ]]; then +# echo "asdadasd" +# fi + + + + +# $JJ_SOURCE_DIR/bin/run.ts $@ \ No newline at end of file diff --git a/package.json b/package.json index a36b56f..8d362f8 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "version": "0.0.7", "author": "Jason Jafari", "bin": { - "jj": "./bin/run.ts" + "jj": "./jj.sh" }, "bugs": "https://github.com/https://github.com/jafarijason/jj/jj/issues", "dependencies": { @@ -19,9 +19,15 @@ "@oclif/plugin-version": "^2.2.15", "@oclif/plugin-warn-if-update-available": "^3.1.21", "@oclif/plugin-which": "^3.2.17", + "chalk": "^5.3.0", + "flatted": "^3.3.1", "fs-extra": "^11.2.0", "inquirer": "^12.0.1", - "lodash": "^4.17.21" + "lodash": "^4.17.21", + "moment": "^2.30.1", + "pino": "^9.5.0", + "pino-pretty": "^12.1.0", + "winston": "^3.16.0" }, "devDependencies": { "@oclif/prettier-config": "^0.2.1", diff --git a/src/hooks/prerun/customPreRun.ts b/src/hooks/prerun/customPreRun.ts index 654ae21..9a1c64f 100644 --- a/src/hooks/prerun/customPreRun.ts +++ b/src/hooks/prerun/customPreRun.ts @@ -2,15 +2,25 @@ import { Hook, Command } from '@oclif/core' import fs from 'fs-extra'; import _ from 'lodash'; import { jjEnsure } from '@helpers/jjEnsure'; +import { jjConfigs } from '@src/index'; const hook: Hook<'prerun'> = async function (opts) { - + await jjEnsure(opts) + + + + + + + Object.assign(process.env, jjConfigs.processEnvs); + + // srmVersion // console.log(opts.Command.flags) // console.log(opts.Command.args) diff --git a/src/index.ts b/src/index.ts index cbb3748..d98d35e 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,7 @@ #!/usr/bin/env bun -export const jjConfigs: any = {} +export const jjConfigs: any = { + processEnvs: {} +} export { run } from '@oclif/core'