Best JavaScript code snippet using root
utils.ts
Source:utils.ts
1import chalk from "chalk";2import fs from "fs-extra";3import inquirer from "inquirer";4import path from "path";5import semver from "semver";6import {7 exec,8 getFirstCommitId,9 getGitRemoteUrl,10 getGroupedCommits,11 getPackageDirs,12 getPreTag,13 GroupedCommitsItem14} from "@siujs/utils";15const execFnCache = {} as Record<"dryRun" | "run", (bin: string, args: string[], opts?: Record<string, any>) => any>;16export function runWhetherDry(isDryRun?: boolean) {17 return isDryRun18 ? execFnCache.dryRun ||19 (execFnCache.dryRun = (bin: string, args: string[], opts = {}) =>20 console.log(chalk.yellow(`[dryrun] ${bin} ${args.join(" ")}`), opts))21 : execFnCache.run ||22 (execFnCache.run = (bin: string, args: string[], opts = {}) => exec(bin, args, { stdio: "inherit", ...opts }));23}24/**25 *26 * Push git commits to server repo27 *28 * steps:29 * `git push`: push commits30 * `git push --tags`: push local tags31 *32 * @param isDryRun whether is dry run33 */34export async function gitPush(isDryRun: boolean) {35 const run = runWhetherDry(isDryRun);36 await run("git", ["push"]);37 await run("git", ["push", "--tags"]);38}39/**40 *41 * Publish package to npm repository42 *43 * @param cwd current workspace directory44 * @param registry specific npm registory url string45 * @param isDryRun whether is dry run46 */47export async function npmPublish(cwd: string, registry: string, isDryRun?: boolean) {48 const run = runWhetherDry(isDryRun);49 await run("npm", ["publish", "--access", "public", "--registry", registry].filter(Boolean), {50 cwd,51 stdio: "inherit"52 });53}54/**55 *56 * Add local git tag57 *58 * @param version new version string, no `v` prefix59 * @param cwd current workspace directory - monorepo project root60 * @param isDryRun whether is dry run61 */62export async function addGitTag(version: string, cwd: string, isDryRun?: boolean) {63 const run = runWhetherDry(isDryRun);64 await run("git", ["tag", `v${version}`], { cwd, stdio: "inherit" });65}66/**67 *68 * Add local git tag only for monorepo package when use `independent` mode69 *70 * @param version new version string, no `v` prefix71 * @param pkgCwd current workspace directory - specific monorepo package root72 * @param isDryRun whether is dry run73 */74export async function addGitTagOfPackage(75 version: string,76 pkgCwd: string | { cwd: string; pkgShortName: string },77 isDryRun?: boolean78) {79 let cwd = "",80 pkgShortName;81 if (typeof pkgCwd === "string") {82 cwd = pkgCwd;83 pkgShortName = path.basename(cwd);84 } else {85 cwd = pkgCwd.cwd;86 pkgShortName = pkgCwd.pkgShortName;87 }88 await runWhetherDry(isDryRun)("git", ["tag", `${pkgShortName}-v${version}`], { cwd, stdio: "inherit" });89}90/**91 *92 * Add and commit local changes to git store93 *94 * @param version new version string, no `v` prefix95 * @param cwd current workspace directory - monorepo project root96 * @param isDryRun whether is dry run97 */98export async function commitChanges(version: string, cwd: string, isDryRun?: boolean) {99 const run = runWhetherDry(isDryRun);100 await run("git", ["add", cwd]);101 await run("git", ["commit", "-m", `release: v${version}`]);102}103/**104 *105 * Add and commit local changes to git store only for monorepo package when use `independent` mode106 *107 * @param version new version string, no `v` prefix108 * @param pkgCwd current workspace directory - specific monorepo package root109 * @param isDryRun whether is dry run110 */111export async function commitChangesOfPackage(112 version: string,113 pkgCwd: string | { cwd: string; pkgShortName: string },114 isDryRun?: boolean115) {116 const run = runWhetherDry(isDryRun);117 let cwd = "",118 pkgShortName;119 if (typeof pkgCwd === "string") {120 cwd = pkgCwd;121 pkgShortName = path.basename(cwd);122 } else {123 cwd = pkgCwd.cwd;124 pkgShortName = pkgCwd.pkgShortName;125 }126 await run("git", ["add", cwd]);127 await run("git", ["commit", "-m", `chore(release): ${pkgShortName}-v${version}`]);128}129/**130 *131 * Update `version` field in root package.json132 *133 * @param version new version string, no `v` prefix134 * @param cwd current workspace directory - monorepo project root135 */136export async function updatePkgVersion(version: string, cwd: string) {137 const metaPath = path.resolve(cwd, "package.json");138 const pkgData = await fs.readJSON(metaPath);139 pkgData.version = version;140 await fs.writeJSON(metaPath, pkgData, { spaces: 2 });141}142/**143 *144 * Update `version` field of interdependent packages145 *146 * @param version new version string, no `v` prefix147 * @param cwd current workspace directory - monorepo project root148 */149export async function updateCrossDeps(150 version: string,151 extra?: {152 cwd: string;153 workspace?: string;154 pkgs?: string[];155 pkgDatas?: any[];156 }157) {158 extra = {159 cwd: process.cwd(),160 workspace: "packages",161 ...(extra || {})162 };163 const pkgsRoot = path.resolve(extra.cwd, extra.workspace);164 if (!extra.pkgs || !extra.pkgs.length) {165 extra.pkgs = await getPackageDirs(extra.cwd, extra.workspace);166 }167 if (!extra.pkgDatas || !extra.pkgDatas.length) {168 extra.pkgDatas = (169 await Promise.all(extra.pkgs.map(dir => fs.readJSON(path.resolve(pkgsRoot, dir, "package.json"))))170 ).filter(p => !p.private);171 }172 const pkgMetas = extra.pkgDatas.reduce((prev, meta) => {173 prev[meta.name] = meta;174 return prev;175 }, {}) as Record<string, Record<string, any>>;176 const depTypes = ["dependencies", "peerDependencies"];177 const metas = Object.values(pkgMetas);178 depTypes.forEach(depType => {179 metas.forEach(meta => {180 meta.version = version;181 if (!meta[depType]) return;182 Object.keys(meta[depType]).forEach(key => {183 if (pkgMetas[key]) {184 meta[depType][key] = version;185 }186 });187 });188 });189 await Promise.all([190 ...Object.keys(pkgMetas).map((value, index) =>191 fs.writeJSON(path.resolve(pkgsRoot, extra.pkgs[index], "package.json"), pkgMetas[value], { spaces: 2 })192 )193 ]);194}195/**196 *197 * @param cwd current workspace directory - monorepo project root or specific monorepo package root198 */199export async function chooseVersion(cwd: string, pkg?: string) {200 // eslint-disable-next-line @typescript-eslint/no-var-requires201 const currentVersion = require(path.resolve(cwd, "package.json")).version;202 const preIdArr = semver.prerelease(currentVersion);203 const preId = preIdArr && preIdArr[0];204 const versionIncrements = [205 "patch",206 "minor",207 "major",208 ...(preId ? ["prepatch", "preminor", "premajor", "prerelease"] : [])209 ] as semver.ReleaseType[];210 const inc = (i: semver.ReleaseType) => semver.inc(currentVersion, i, preId);211 // no explicit version, offer suggestions212 const { release } = await inquirer.prompt({213 type: "list",214 name: "release",215 message: "Select release type" + (pkg ? ` of '${pkg}'` : ""),216 choices: versionIncrements.map(i => `${i} (${inc(i)})`).concat(["custom", "cancel"])217 });218 switch (release) {219 case "custom":220 return (221 await inquirer.prompt({222 type: "input",223 name: "version",224 message: "Input custom version",225 default: currentVersion226 })227 ).version;228 /* istanbul ignore next */229 case "cancel":230 return;231 default:232 return release.match(/\((.*)\)/)[1];233 }234}235/**236 *237 *238 *239 * @param item commit item240 * @param remoteUrl [optional] git remote url241 */242export function normalizeChangeLogInlineMsg(item: GroupedCommitsItem, remoteUrl?: string) {243 const ref = /\(#\d+\)/.test(item.header)244 ? ""245 : ` ([${item.extra.hash.substring(0, 7)}](${remoteUrl}/commit/${item.extra.hash}))`;246 return (item.scope ? ` **${item.scope}**: ` : "") + item.subject.trim() + ref;247}248/**249 *250 * Get new changelog content251 *252 * @param version new version string, no `v` prefix253 * @param opts generation options254 */255export async function getNewChangedLog(256 version: string,257 opts: {258 cwd?: string;259 versionPrefix?: string;260 allowTypes?: string[];261 type2Title?: Record<string, string>;262 normalizeCommitMsg?: (item: GroupedCommitsItem, remoteUrl?: string) => string;263 } = {264 cwd: process.cwd()265 }266) {267 let tag,268 remoteUrl = "";269 [tag, remoteUrl] = await Promise.all([getPreTag(opts.versionPrefix), getGitRemoteUrl(opts.cwd || process.cwd())]);270 !tag && (tag = await getFirstCommitId(false));271 const groupedCommits = await getGroupedCommits(tag);272 const {273 allowTypes = ["feat", "fix", "perf", "refactor"],274 type2Title = {275 feat: "Features",276 fix: "Bug Fixes",277 perf: "Performance Improvements",278 refactor: "Code Refactoring"279 },280 normalizeCommitMsg = normalizeChangeLogInlineMsg281 } = opts;282 let arr: string[];283 const [date] = new Date().toISOString().split("T");284 const newLog = [`## [v${version}](${remoteUrl}/compare/${tag}...v${version}) (${date})`];285 if (groupedCommits.breaking.length) {286 arr = groupedCommits.breaking.map(item => normalizeCommitMsg(item, remoteUrl)).filter(Boolean);287 if (arr.length) {288 newLog.push(`### BREAKING CHANGES\n\n- ${arr.join("\n- ")}`.trim());289 }290 }291 return Object.keys(groupedCommits)292 .filter(key => allowTypes.includes(key))293 .reduce((prev, type) => {294 arr = groupedCommits[type].map(item => normalizeCommitMsg(item, remoteUrl)).filter(Boolean);295 arr.length && prev.push(`### ${type2Title[type] || type}\n\n- ${arr.join("\n- ")}`.trim());296 return prev;297 }, newLog)298 .filter(Boolean)299 .join("\n\n");300}301/**302 *303 * Append new content to CHANGELOG.md304 *305 * @param newLog new changelog content306 * @param cwd current workspace directory307 *308 * @returns full content309 */310export async function appendChangedLog(newLog: string, cwd: string) {311 // eslint-disable-next-line @typescript-eslint/no-var-requires312 const meta = require(path.resolve(cwd, "package.json"));313 const title = `# ${meta.name} ChangeLog`;314 const logPath = path.resolve(cwd, "CHANGELOG.md");315 const logFile = (await fs.readFile(logPath).catch(() => "")).toString();316 const oldLog = logFile.startsWith(title) ? logFile.slice(title.length).trim() : logFile;317 const content = [title, newLog, oldLog].filter(Boolean).join("\n\n");318 await fs.writeFile(logPath, content, {319 encoding: "utf-8"320 });321 return content;322}323/**324 *325 * Update `CHANGELOG.md` content326 *327 * @param version new version string, no `v` prefix328 * @param cwd current workspace directory - monorepo project root of specific monorepo package root329 * @param pkg [option] specific monorepo package name330 * @param isDryRun whether is dry run331 */332export async function updateChangelog(333 version: string,334 cwd: string,335 pkg?: string | { pkg: string; pkgShortName: string; needScope?: boolean },336 isDryRun?: boolean337) {338 let pkgName = "",339 pkgShortName = "";340 let needScope = true;341 if (typeof pkg === "string") {342 pkgName = pkg;343 needScope = true;344 } else {345 pkg = pkg || { pkg: "", pkgShortName: "" };346 pkgName = pkg.pkg;347 pkgShortName = pkg.pkgShortName;348 needScope = pkg.needScope;349 }350 const opts = pkgName351 ? {352 versionPrefix: (pkgShortName || pkgName) + "-",353 normalizeCommitMsg: (item: GroupedCommitsItem, remoteUrl?: string) =>354 !item.scope || pkgName === item.scope || item.scope === pkgShortName355 ? normalizeChangeLogInlineMsg(356 needScope ? item : ({ ...item, scope: null } as GroupedCommitsItem),357 remoteUrl358 )359 : ""360 }361 : {};362 const newLog = await getNewChangedLog(version, opts);363 if (isDryRun) return newLog;364 return await appendChangedLog(newLog, cwd);...
index.js
Source:index.js
...13 const threshold = args.getThresholdDate() || {14 duration: args.getThresholdDuration(),15 unit: args.getThresholdUnit()16 };17 const isDryRun = !!args.isDryRun();18 const response = await proxy.getArtifacts(threshold, isDryRun);19 let shouldDelete = true;20 shouldDelete = await promptDeletion(isDryRun);21 if (shouldDelete && response.length !== 0) {22 const deletedResponse = await proxy.deleteArtifacts(response, isDryRun);23 const dryrunPrefix = isDryRun ? chalk.yellowBright.bgBlue('***') : '';24 const dryRunCaption = isDryRun ? chalk.white.underline.bold('DRY RUN:') : '';25 logger.info("%s %s Total of %s artifacts were deleted using %s for a threshold of: %s and filter of %s for repositories.", dryrunPrefix,26 dryRunCaption, response.length, filesize(deletedResponse.totalSize), moment(threshold).format('LLL'),27 args.getPrefixFilter() ? args.getPrefixFilter() : 'NONE');28 if (args.getThresholdKeep()) {29 logger.info("Kept the %s newest artifacts per package", args.getThresholdKeep());30 }31 }...
Using AI Code Generation
1const rootCommand = require('./root-command');2const childCommand = require('./child-command');3const grandChildCommand = require('./grand-child-command');4rootCommand.isDryRun();5childCommand.isDryRun();6grandChildCommand.isDryRun();7const childCommand = require('./child-command');8const grandChildCommand = require('./grand-child-command');9const rootCommand = {10 isDryRun: function() {11 childCommand.isDryRun();12 grandChildCommand.isDryRun();13 }14}15const grandChildCommand = require('./grand-child-command');16const childCommand = {17 isDryRun: function() {18 grandChildCommand.isDryRun();19 }20}21const grandChildCommand = {22 isDryRun: function() {23 }24}25const rootCommand = require('./root-command');26const childCommand = require('./child-command');27const grandChildCommand = require('./grand-child-command');28rootCommand.isDryRun();
Using AI Code Generation
1var root = this.getRoot();2var isDryRun = root.isDryRun();3var root = this.getRoot();4var isDryRun = root.isDryRun();5var root = this.getRoot();6var isDryRun = root.isDryRun();7var root = this.getRoot();8var isDryRun = root.isDryRun();9var root = this.getRoot();10var isDryRun = root.isDryRun();11var root = this.getRoot();12var isDryRun = root.isDryRun();13var root = this.getRoot();14var isDryRun = root.isDryRun();15var root = this.getRoot();16var isDryRun = root.isDryRun();17var root = this.getRoot();18var isDryRun = root.isDryRun();19var root = this.getRoot();20var isDryRun = root.isDryRun();21var root = this.getRoot();22var isDryRun = root.isDryRun();23var root = this.getRoot();24var isDryRun = root.isDryRun();25var root = this.getRoot();26var isDryRun = root.isDryRun();27var root = this.getRoot();28var isDryRun = root.isDryRun();
Using AI Code Generation
1const rootModule = require('module');2const isDryRun = rootModule.isDryRun();3if (isDryRun) {4 console.log('dry run');5} else {6 console.log('not a dry run');7}
Using AI Code Generation
1var root = require('./root');2root.isDryRun();3var isDryRun = function() {4 return true;5}6module.exports = {7}8var root = require('./root');9root.isDryRun();10var isDryRun = function() {11 return true;12}13module.exports = {14 isDryRun: isDryRun.bind(this)15}16var myFunc = function() {17 return this;18}19var myObj = {20}21var myBoundFunc = myFunc.bind(myObj);22var myResult = myBoundFunc();23console.log(myResult);24{ name: 'John' }
Using AI Code Generation
1const { isDryRun } = require('root-command');2const { isDryRun } = require('root-command');3const { isDryRun } = require('root-command');4const { isDryRun } = require('root-command');5const { isDryRun } = require('root-command');6const { isDryRun } = require('root-command');7const { isDryRun } = require('root-command');8const { isDryRun } = require('root-command');9const { isDryRun } = require('root-command');10const { isDryRun } = require('root-command');11const { isDryRun } = require('root-command');12const { isDryRun } = require('root-command');13const { isDryRun } = require('root-command');14const { isDryRun } = require('root-command');
Using AI Code Generation
1const { isDryRun } = require('..')2const { isDryRun } = require('../sub')3const { isDryRun } = require('../sub/subsub')4const { isDryRun } = require('../sub/subsub/subsubsub')5const { isDryRun } = require('../sub/subsub/subsubsub/subsubsubsub')6const { isDryRun } = require('../sub/subsub/subsubsub/subsubsubsub/subsubsubsubsub')7const { isDryRun } = require('../sub/subsub/subsubsub/subsubsubsub/subsubsubsubsub/subsubsubsubsubsub')8const { isDryRun } = require('../sub/subsub/subsubsub/subsubsubsub/subsubsubsubsub/subsubsubsubsubsub/subsubsubsubsubsubsub')9const { isDryRun } = require('../sub/subsub/subsubsub/subsubsubsub/subsubsubsubsub/subsubsubsubsubsub/subsubsubsubsubsubsub/subsubsubsubsubsubsubsub')10const { isDryRun } = require('../sub/subsub/subsubsub/subsubsubsub/subsubsubsubsub/subsubsubsubsubsub/subsub
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!