How to use environmentHash method in Best

Best JavaScript code snippet using best

index.js

Source:index.js Github

copy

Full Screen

1const fs = require("fs");2const path = require("path");3const crypto = require("crypto");45const androidStudioLogging = require("../../script-helpers/android-studio-logging");67const transmutations = require("./transmutations");8const cache = require("../../cache");9const CACHE_VERSION = require("../config").CACHE_VERSION;10const commandLineInterface = require("../../command-line-interface");11const safeFsUtils = require("../../script-helpers/safe-fs-utils");12const makeWorkersPool = require("./workers-pool");13const folderScanner = require("./folder-scanner");14const loadFrontmatter = require("./frontmatter-parser");1516const BUILD_ROOT_DIRS = (require("./get-build-root"))();1718const SRC_DIRECTORY = BUILD_ROOT_DIRS.src19const COMPILED_RESULT_DIRECTORY = BUILD_ROOT_DIRS.gen;20const ASSETS_DIRECTORY = BUILD_ROOT_DIRS.asset;21const TEST_DIRECTORY = BUILD_ROOT_DIRS.test2223module.exports = (async function main() {24 await transmutations.loadTaskList();25 await compileAllFromSourceDirectory();26 27 androidStudioLogging.printTypeCounts();28});2930async function compileAllFromSourceDirectory() {31 const compilerWorkers = makeWorkersPool();32 const autoautoFileContexts = [];33 34 const preprocessInputs = {};35 const codebaseTransmutationWrites = {};36 await evaluateCodebaseTasks(autoautoFileContexts, transmutations.getPreProcessTransmutations(), preprocessInputs, codebaseTransmutationWrites);37 38 const environmentHash = makeEnvironmentHash(CACHE_VERSION, preprocessInputs, process.argv);3940 //the folderScanner will give once for each file.41 //this way, we don't have to wait for ALL filenames in order to start compiling.42 //it starts after the first one!43 const aaFiles = folderScanner(SRC_DIRECTORY, ".autoauto");44 const jobPromises = [];45 46 for await(const file of aaFiles) {47 jobPromises.push(48 makeContextAndCompileFile(file, compilerWorkers, autoautoFileContexts, preprocessInputs, environmentHash)49 );50 }51 52 await Promise.all(jobPromises);5354 await evaluateCodebaseTasks(autoautoFileContexts, transmutations.getPostProcessTransmutations(), {}, codebaseTransmutationWrites);55 writeWrittenFiles({ writtenFiles: codebaseTransmutationWrites});56 57 compilerWorkers.close();58}5960function makeContextAndCompileFile(filename, compilerWorkers, autoautoFileContexts, preprocessInputs, environmentHash) {61 const fileContext = makeFileContext(filename, preprocessInputs, environmentHash);62 const cacheEntry = getCacheEntry(fileContext);6364 return new Promise(function(resolve, reject) {65 if(cacheEntry) {66 androidStudioLogging.sendMessages(cacheEntry.log);67 writeAndCallback(cacheEntry.data, autoautoFileContexts, resolve);68 } else {69 compilerWorkers.giveJob(fileContext, function(run) {70 saveCacheEntry(run);71 androidStudioLogging.sendMessages(run.log);72 writeAndCallback(run.fileContext, autoautoFileContexts, resolve);73 });74 }75 });76}7778function saveCacheEntry(finishedRun) {79 if(finishedRun.success && commandLineInterface["no-cache-save"] == false) {80 cache.save(mFileCacheKey(finishedRun.fileContext), {81 subkey: finishedRun.fileContext.cacheKey,82 data: finishedRun.fileContext,83 log: finishedRun.log84 });85 }86}8788function getCacheEntry(fileContext) {89 if(commandLineInterface["no-cache"]) return false;9091 const cacheEntry = cache.get(mFileCacheKey(fileContext), false);9293 if(cacheEntry.subkey == fileContext.cacheKey) return cacheEntry;94 else return false;95}9697function mFileCacheKey(fileContext) {98 return "autoauto compiler file cache " + fileContext.sourceFullFileName;99}100101function writeAndCallback(finishedFileContext, autoautoFileContexts, cb) {102 autoautoFileContexts.push(finishedFileContext);103 writeWrittenFiles(finishedFileContext);104 cb(finishedFileContext);105}106107async function evaluateCodebaseTasks(allFileContexts, codebaseTasks, codebaseInputs, codebaseTransmutationWrites) {108 for(const transmut of codebaseTasks) {109 const o = makeCodebaseContext(codebaseTransmutationWrites);110 const mutFunc = require(transmut.sourceFile);111 await mutFunc(o, allFileContexts);112 codebaseInputs[transmut.id] = o.output;113 }114}115116function sha(s) {117 return crypto.createHash("sha256").update(s).digest("hex");118}119120function makeCodebaseContext(codebaseTransmutationWrites) {121 return {122 output: undefined,123 writtenFiles: codebaseTransmutationWrites,124 resultRoot: COMPILED_RESULT_DIRECTORY,125 assetsRoot: ASSETS_DIRECTORY,126 sourceRoot: SRC_DIRECTORY,127 testRoot: TEST_DIRECTORY128 }129}130131function makeFileContext(file, preprocessInputs, environmentHash) {132 133 const resultFile = getResultFor(file);134 const fileContent = fs.readFileSync(file).toString();135 const frontmatter = loadFrontmatter(fileContent);136137 const tPath = transmutations.expandTasks(frontmatter.compilerMode || "default", file);138 139 const ctx = {140 sourceBaseFileName: path.basename(file),141 sourceDir: path.dirname(file),142 sourceFullFileName: file,143 sourceRoot: SRC_DIRECTORY,144 resultBaseFileName: path.basename(resultFile),145 resultDir: path.dirname(resultFile),146 resultFullFileName: resultFile,147 resultRoot: COMPILED_RESULT_DIRECTORY,148 assetsRoot: ASSETS_DIRECTORY,149 testRoot: TEST_DIRECTORY,150 fileFrontmatter: frontmatter,151 fileContentText: fileContent,152 lastInput: fileContent,153 inputs: {},154 cacheKey: undefined,155 writtenFiles: {},156157 transmutations: tPath,158 readsAllFiles: tPath.map(x=>x.readsFiles || []).flat()159 };160 161 Object.assign(ctx.inputs, preprocessInputs);162 ctx.cacheKey = makeCacheKey(ctx, environmentHash);163164 return ctx;165}166167function writeWrittenFiles(fileContext) {168 for(const filename in fileContext.writtenFiles) {169 const content = fileContext.writtenFiles[filename];170 if(typeof content !== "boolean") {171 safeFsUtils.safeWriteFileEventually(filename, content);172 }173 }174}175176function makeEnvironmentHash(cacheVersion, preprocessInputs, argv) {177 return cacheVersion + "\0" + keyJsonHash(preprocessInputs) + "\0" + argv.join(" ");178}179180function keyJsonHash(object) {181 let t = [];182 for(const key in object) {183 t.push(sha(JSON.stringify(object[key])));184 }185 return t.join("");186}187188/**189 * 190 * @param {import("./transmutations").TransmutateContext} fileContext 191 */192function makeCacheKey(fileContext, environmentHash) {193 const readFileShas = fileContext.readsAllFiles.map(x=>sha(safeFsUtils.cachedSafeReadFile(x))).join("\t");194 const transmutationIdList = fileContext.transmutations.map(x=>x.id).join("\t");195196 const keyDataToSha = [environmentHash, readFileShas,197 fileContext.sourceFullFileName, fileContext.fileContentText, transmutationIdList];198199 return sha(keyDataToSha.join("\0"));200}201202function getResultFor(filename) {203 const folder = path.dirname(filename);204 205 const packageFolder = folder206 .replace(SRC_DIRECTORY, "").toLowerCase();207 208 const javaFileName = jClassIfy(filename) + ".java";209 210 return path.join(COMPILED_RESULT_DIRECTORY, packageFolder, javaFileName);211}212213function jClassIfy(str) {214 const p = str.split(/\/|\\/);215 const s = p[p.length - 1].split(".")[0];216 return s.split("-").map(x=>capitalize(x)).join("");217}218function capitalize(str) {219 return str[0].toUpperCase() + str.substring(1); ...

Full Screen

Full Screen

jsify-css.js

Source:jsify-css.js Github

copy

Full Screen

1'use strict';2const cssnano = require('cssnano');3const fs = require('fs');4const path = require('path');5const postcss = require('postcss');6const postcssImport = require('postcss-import');7const {8 TransformCache,9 batchedRead,10 md5,11} = require('../../common/transform-cache');12const {log} = require('../../common/logging');13const {red} = require('../../common/colors');14// NOTE: see https://github.com/ai/browserslist#queries for `browsers` list15const browsersList = {16 overrideBrowserslist: [17 'last 5 ChromeAndroid versions',18 'last 5 iOS versions',19 'last 3 FirefoxAndroid versions',20 'last 5 Android versions',21 'last 2 ExplorerMobile versions',22 'last 2 OperaMobile versions',23 'last 2 OperaMini versions',24 ],25};26// See https://cssnano.co/docs/what-are-optimisations for full list.27// We try and turn off any optimization that is marked unsafe.28const cssNanoDefaultOptions = {29 autoprefixer: false,30 convertValues: false,31 discardUnused: false,32 cssDeclarationSorter: false,33 // `mergeIdents` this is only unsafe if you rely on those animation names in34 // JavaScript.35 mergeIdents: true,36 reduceIdents: false,37 reduceInitial: false,38 zindex: false,39 svgo: {40 encode: true,41 },42};43const packageJsonPath = path.join(__dirname, '..', '..', '..', 'package.json');44let environmentHash = null;45/** @return {Promise<string>} */46function getEnvironmentHash() {47 if (environmentHash) {48 return environmentHash;49 }50 // We want to set environmentHash to a promise synchronously s.t.51 // we never end up with multiple calculations at the same time.52 environmentHash = Promise.resolve().then(async () => {53 const packageJsonHash = md5(await fs.promises.readFile(packageJsonPath));54 const cssOptions = JSON.stringify({cssNanoDefaultOptions, browsersList});55 return md5(packageJsonHash, cssOptions);56 });57 return environmentHash;58}59/**60 * Used to cache css transforms done by postcss.61 * @const {TransformCache}62 */63let transformCache;64/**65 * @typedef {{css: string, warnings: string[]}}:66 */67let CssTransformResultDef;68/**69 * Transform a css string using postcss.70 * @param {string} contents the css text to transform71 * @param {!Object=} opt_filename the filename of the file being transformed. Used for sourcemaps generation.72 * @return {!Promise<CssTransformResultDef>} that resolves with the css content after73 * processing74 */75async function transformCssString(contents, opt_filename) {76 const hash = md5(contents);77 return transformCss(contents, hash, opt_filename);78}79/**80 * 'Jsify' a CSS file - Adds vendor specific css prefixes to the css file,81 * compresses the file, removes the copyright comment, and adds the sourceURL82 * to the stylesheet83 *84 * @param {string} filename css file85 * @return {!Promise<string>} that resolves with the css content after86 * processing87 */88async function jsifyCssAsync(filename) {89 const {contents, hash: filehash} = await batchedRead(filename);90 const hash = md5(filehash, await getEnvironmentHash());91 const result = await transformCss(contents, hash, filename);92 result.warnings.forEach((warn) => log(red(warn)));93 return result.css + '\n/*# sourceURL=/' + filename + '*/';94}95/**96 * @param {string} contents97 * @param {string} hash98 * @param {string=} opt_filename99 * @return {Promise<CssTransformResultDef>}100 */101async function transformCss(contents, hash, opt_filename) {102 if (!transformCache) {103 transformCache = new TransformCache('.css-cache', '.css');104 }105 const cached = transformCache.get(hash);106 if (cached) {107 return JSON.parse((await cached).toString());108 }109 const transformed = transform(contents, opt_filename);110 transformCache.set(111 hash,112 transformed.then((r) => JSON.stringify(r))113 );114 return transformed;115}116/**117 * @param {string} contents118 * @param {string=} opt_filename119 * @return {Promise<CssTransformResultDef>}120 */121async function transform(contents, opt_filename) {122 const cssnanoTransformer = cssnano({123 preset: ['default', cssNanoDefaultOptions],124 });125 const {default: autoprefixer} = await import('autoprefixer'); // Lazy-imported to speed up task loading.126 const cssprefixer = autoprefixer(browsersList);127 const transformers = [postcssImport, cssprefixer, cssnanoTransformer];128 return postcss129 .default(transformers)130 .process(contents, {'from': opt_filename})131 .then((result) => ({132 css: result.css,133 warnings: result.warnings().map((warning) => warning.toString()),134 }));135}136module.exports = {137 jsifyCssAsync,138 transformCssString,...

Full Screen

Full Screen

test_environment_hash.ts

Source:test_environment_hash.ts Github

copy

Full Screen

...3import { createVirtualFileSystemCache } from '../../file_system/test_utils';4test('should handle no specified targets', (t) => {5 const files = {};6 const cache = createVirtualFileSystemCache(files);7 return environmentHash(cache)8 .then(hash => {9 t.is(hash, '___');10 });11});12test('should produce hashes that include a murmur hash of the textual content', (t) => {13 const files = {14 '/foo.js': 'test',15 };16 const cache = createVirtualFileSystemCache(files);17 cache.files.get('/foo.js').setModifiedTime('test');18 return environmentHash(cache, {files: ['/foo.js']})19 .then(hash => {20 t.is(hash, '3127628307_3127628307__');21 });22});23test('should compute hashes of the textual content and modified times of the specified files ', (t) => {24 const files = {25 '/foo.js': 'foo',26 '/bar.json': 'bar'27 };28 const cache = createVirtualFileSystemCache(files);29 return environmentHash(cache, {files: ['/foo.js', '/bar.json']})30 .then(hash => {31 t.is(hash, '2764362941_1706884430__');32 const files = {33 '/foo.js': 'foo',34 '/bar.json': 'bar++'35 };36 const cache = createVirtualFileSystemCache(files);37 return environmentHash(cache, {files: ['/foo.js', '/bar.json']})38 .then(hash => {39 t.is(hash, '962598314_1706884430__');40 const cache = createVirtualFileSystemCache(files);41 cache.files.get('/bar.json').setModifiedTime('test');42 return environmentHash(cache, {files: ['/foo.js', '/bar.json']})43 .then(hash => {44 t.is(hash, '962598314_3854409749__');45 });46 });47 });48});49test('should compute hashes from the modified times of each item within the specified directories', (t) => {50 const files = {51 '/foo/bar.js': 'bar',52 '/foo/woz.js': 'woz'53 };54 const directories = {55 '/foo': [56 'bar.js',57 'woz.js'58 ]59 };60 const cache = createVirtualFileSystemCache(files, directories);61 return environmentHash(cache, {directories: ['/foo']})62 .then(hash => {63 t.is(hash, '__1706884430');64 const files = {65 '/foo/bar.js': 'bar',66 '/foo/woz.js': 'woz++'67 };68 const cache = createVirtualFileSystemCache(files, directories);69 return environmentHash(cache, {directories: ['/foo']})70 .then(hash => {71 t.is(hash, '__1706884430');72 const cache = createVirtualFileSystemCache(files, directories);73 cache.files.get('/foo/bar.js').setModifiedTime('test');74 return environmentHash(cache, {directories: ['/foo']})75 .then(hash => {76 t.is(hash, '__68303964');77 });78 });79 });80});81test('should allow relative paths for files and directories', (t) => {82 const files = {83 '/foo/bar.js': 'foo bar',84 '/foo/woz/woz.js': 'foo woz woz',85 '/bar/woz.js': 'bar woz',86 '/woz/woz.js': 'woz woz'87 };88 const directories = {89 '/foo': ['bar.js', 'woz'],90 '/foo/woz': ['woz.js'],91 '/woz': ['woz.js'],92 };93 const cache = createVirtualFileSystemCache(files, directories);94 return environmentHash(cache, {95 root: '/foo',96 directories: [97 'woz',98 '/woz'99 ],100 files: [101 'bar.js',102 '/bar/woz.js',103 'bar.js'104 ]105 })106 .then(hash => {107 t.is(hash, '3641327672_1774342414_3127134693_3127134693');108 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestPractices = require('./BestPractices');2var bestPractices = new BestPractices();3var environmentHash = bestPractices.environmentHash();4console.log(environmentHash);5var BestPractices = require('./BestPractices');6var bestPractices = new BestPractices();7var environmentHash = bestPractices.environmentHash();8console.log(environmentHash);9var BestPractices = require('./BestPractices');10var bestPractices = new BestPractices();11var environmentHash = bestPractices.environmentHash();12console.log(environmentHash);13var BestPractices = require('./BestPractices');14var bestPractices = new BestPractices();15var environmentHash = bestPractices.environmentHash();16console.log(environmentHash);17var BestPractices = require('./BestPractices');18var bestPractices = new BestPractices();19var environmentHash = bestPractices.environmentHash();20console.log(environmentHash);21var BestPractices = require('./BestPractices');22var bestPractices = new BestPractices();23var environmentHash = bestPractices.environmentHash();24console.log(environmentHash);25var BestPractices = require('./BestPractices');26var bestPractices = new BestPractices();27var environmentHash = bestPractices.environmentHash();28console.log(environmentHash);

Full Screen

Using AI Code Generation

copy

Full Screen

1var test4 = function() {2 console.log("Test 4");3 var b = new Bestiary();4 var e1 = new Environment(1, "test1", "test1");5 var e2 = new Environment(2, "test2", "test2");6 var e3 = new Environment(3, "test3", "test3");7 var e4 = new Environment(4, "test4", "test4");8 var e5 = new Environment(5, "test5", "test5");9 b.addEnvironment(e1);10 b.addEnvironment(e2);11 b.addEnvironment(e3);12 b.addEnvironment(e4);13 b.addEnvironment(e5);14 var hash = b.environmentHash();15 console.log(hash);16 console.log("Should be: 1,2,3,4,5");17 console.log("Test 4 Complete");18}19var test5 = function() {20 console.log("Test 5");21 var b = new Bestiary();22 var e1 = new Environment(1, "test1", "test1");23 var e2 = new Environment(2, "test2", "test2");24 var e3 = new Environment(3, "test3", "test3");25 var e4 = new Environment(4, "test4", "test4");26 var e5 = new Environment(5, "test5", "test5");27 b.addEnvironment(e1);28 b.addEnvironment(e2);29 b.addEnvironment(e3);30 b.addEnvironment(e4);31 b.addEnvironment(e5);32 var hash = b.environmentHash();33 console.log(hash);34 console.log("Should be: 1,2,3,4,5");35 console.log("Test 5 Complete");36}37var test6 = function() {38 console.log("Test 6");39 var b = new Bestiary();40 var e1 = new Environment(1, "test1", "test1");41 var e2 = new Environment(2, "test2", "test2");42 var e3 = new Environment(

Full Screen

Using AI Code Generation

copy

Full Screen

1var express = require('express');2var app = express();3app.get('/test4', function (req, res) {4 var port = process.env.PORT;5 res.send('Hello World!');6});7app.listen(3000, function () {8 console.log('Example app listening on port 3000!');9});10var express = require('express');11var app = express();12app.get('/test5', function (req, res) {13 var port = process.env.PORT;14 res.send('Hello World!');15});16app.listen(3000, function () {17 console.log('Example app listening on port 3000!');18});19var express = require('express');20var app = express();21app.get('/test6', function (req, res) {22 var port = process.env.PORT;23 res.send('Hello World!');24});25app.listen(3000, function () {26 console.log('Example app listening on port 3000!');27});28var express = require('express');29var app = express();30app.get('/test7', function (req, res) {31 var port = process.env.PORT;32 res.send('Hello World!');33});34app.listen(3000, function () {35 console.log('Example app listening on port 3000!');36});37var express = require('express');38var app = express();39app.get('/test8', function (req, res) {40 var port = process.env.PORT;41 res.send('Hello World!');42});43app.listen(3000, function () {44 console.log('Example app listening on port 3000!');45});

Full Screen

Using AI Code Generation

copy

Full Screen

1var bpc = require('./BestPracticeChecker.js');2var fs = require('fs');3var code = fs.readFileSync('test4.js', 'utf8');4var result = bpc.environmentHash(code);5console.log(result);6var bpc = require('./BestPracticeChecker.js');7var fs = require('fs');8var code = fs.readFileSync('test5.js', 'utf8');9var result = bpc.environmentHash(code);10console.log(result);11var bpc = require('./BestPracticeChecker.js');12var fs = require('fs');13var code = fs.readFileSync('test6.js', 'utf8');14var result = bpc.environmentHash(code);15console.log(result);16var bpc = require('./BestPracticeChecker.js');17var fs = require('fs');18var code = fs.readFileSync('test7.js', 'utf8');19var result = bpc.environmentHash(code);20console.log(result);21var bpc = require('./BestPracticeChecker.js');22var fs = require('fs');23var code = fs.readFileSync('test8.js', 'utf8');24var result = bpc.environmentHash(code);25console.log(result);26var bpc = require('./BestPracticeChecker.js');27var fs = require('fs');28var code = fs.readFileSync('test9.js', 'utf8');29var result = bpc.environmentHash(code);30console.log(result);31var bpc = require('./BestPracticeChecker.js');32var fs = require('fs');

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful