-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #43 from HubSpot/add/logging-utils
Port logging utils
- Loading branch information
Showing
12 changed files
with
526 additions
and
73 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
|
||
import path from 'path'; | ||
import fs from 'fs'; | ||
import semver from 'semver'; | ||
import { pathToFileURL } from 'url'; | ||
import { getExt } from '../path'; | ||
import { throwError, throwErrorWithMessage } from '../../errors/standardErrors'; | ||
import { FieldsJs } from './handleFieldsJS'; | ||
import { i18n } from '../../utils/lang'; | ||
|
||
const i18nKey = 'processFieldsJs'; | ||
|
||
const { dirName, fieldOptions, filePath, writeDir } = process.env; | ||
const baseName = path.basename(filePath!); | ||
|
||
const FieldErrors = { | ||
IsNotFunction: 'IsNotFunction', | ||
DoesNotReturnArray: 'DoesNotReturnArray', | ||
}; | ||
|
||
//TODO - Figure out agnostic logging | ||
console.info( | ||
i18n(`${i18nKey}.converting`, { | ||
src: dirName + `/${baseName}`, | ||
dest: dirName + '/fields.json', | ||
}) | ||
); | ||
|
||
/* | ||
* How this works: dynamicImport() will always return either a Promise or undefined. | ||
* In the case when it's a Promise, its expected that it will resolve to a function. | ||
* This function has optional return type of Promise<Array> | Array. In order to have uniform handling, | ||
* we wrap the return value of the function in a Promise.resolve(), and then process. | ||
*/ | ||
|
||
const fieldsPromise = dynamicImport(filePath!).catch(e => throwError(e)); | ||
|
||
fieldsPromise.then(fieldsFunc => { | ||
const fieldsFuncType = typeof fieldsFunc; | ||
if (fieldsFuncType !== 'function') { | ||
throwErrorWithMessage(`${i18nKey}.${FieldErrors.IsNotFunction}`, { | ||
path: filePath!, | ||
}); | ||
} | ||
return Promise.resolve(fieldsFunc(fieldOptions)).then(fields => { | ||
if (!Array.isArray(fields)) { | ||
throwErrorWithMessage(`${i18nKey}.${FieldErrors.DoesNotReturnArray}`, { | ||
path: filePath!, | ||
}); | ||
} | ||
|
||
const finalPath = path.join(writeDir!, '/fields.json'); | ||
|
||
return fieldsArrayToJson(fields).then(json => { | ||
if (!fs.existsSync(writeDir!)) { | ||
fs.mkdirSync(writeDir!, { recursive: true }); | ||
} | ||
fs.writeFileSync(finalPath, json); | ||
|
||
//TODO - Figure out agnostic logging | ||
console.log( | ||
i18n(`${i18nKey}.converted`, { | ||
src: dirName + `/${baseName}`, | ||
dest: dirName + '/fields.json', | ||
}) | ||
); | ||
if (process) { | ||
process.send!({ | ||
action: 'COMPLETE', | ||
finalPath, | ||
}); | ||
} | ||
}); | ||
}); | ||
}); | ||
|
||
/* | ||
* Polyfill for `Array.flat(Infinity)` since the `flat` is only available for Node v11+ | ||
* https://stackoverflow.com/a/15030117 | ||
*/ | ||
function flattenArray(arr: Array<any>): Array<any> { | ||
return arr.reduce((flat, toFlatten) => { | ||
return flat.concat( | ||
Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten | ||
); | ||
}, []); | ||
} | ||
|
||
async function fieldsArrayToJson(fields: Array<FieldsJs>): Promise<string> { | ||
const allFields = await Promise.all(flattenArray(fields)); | ||
const jsonFields = allFields.map(field => { | ||
return typeof field['toJSON'] === 'function' ? field.toJSON() : field; | ||
}); | ||
return JSON.stringify(jsonFields, null, 2); | ||
} | ||
|
||
/** | ||
* Takes in a path to a javascript file and either dynamically imports it or requires it, and returns, depending on node version. | ||
* @param {string} filePath - Path to javascript file | ||
* @returns {Promise | undefined} - Returns _default_ exported content if ESM, or exported module content if CJS, or undefined if node version < 13.2 and file is .mjs. | ||
*/ | ||
async function dynamicImport(filePath: string): Promise<any> { | ||
if (semver.gte(process.version, '13.2.0')) { | ||
const exported = await import(pathToFileURL(filePath).toString()).then( | ||
content => content.default | ||
); | ||
return exported; | ||
} else { | ||
if (getExt(filePath) == 'mjs') { | ||
throwErrorWithMessage(`${i18nKey}.invalidMjsFile`); | ||
} | ||
return require(filePath); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import fs from 'fs-extra'; | ||
import path from 'path'; | ||
import os from 'os'; | ||
import { checkGitInclusion } from '../../utils/git'; | ||
import { logger } from './logger'; | ||
import { i18n } from '../../utils/lang'; | ||
import { DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME } from '../../constants/config'; | ||
|
||
const GITIGNORE_FILE = '.gitignore'; | ||
|
||
const i18nKey = 'debug.git'; | ||
|
||
export function checkAndWarnGitInclusion(configPath: string): void { | ||
try { | ||
const { inGit, configIgnored } = checkGitInclusion(configPath); | ||
|
||
if (!inGit || configIgnored) return; | ||
logger.warn(i18n(`${i18nKey}.securityIssue`)); | ||
logger.warn(i18n(`${i18nKey}.configFileTracked`)); | ||
logger.warn(i18n(`${i18nKey}.fileName`, { configPath })); | ||
logger.warn(i18n(`${i18nKey}.remediate`)); | ||
logger.warn(i18n(`${i18nKey}.moveConfig`, { homeDir: os.homedir() })); | ||
logger.warn(i18n(`${i18nKey}.addGitignore`, { configPath })); | ||
logger.warn(i18n(`${i18nKey}.noRemote`)); | ||
} catch (e) { | ||
// fail silently | ||
logger.debug(i18n(`${i18nKey}.checkFailed`)); | ||
} | ||
} | ||
|
||
export function checkAndUpdateGitignore(configPath: string): void { | ||
try { | ||
const { configIgnored, gitignoreFiles } = checkGitInclusion(configPath); | ||
if (configIgnored) return; | ||
|
||
let gitignoreFilePath = | ||
gitignoreFiles && gitignoreFiles.length ? gitignoreFiles[0] : null; | ||
|
||
if (!gitignoreFilePath) { | ||
gitignoreFilePath = path.resolve(configPath, GITIGNORE_FILE); | ||
|
||
fs.writeFileSync(gitignoreFilePath, ''); | ||
} | ||
|
||
const gitignoreContents = fs.readFileSync(gitignoreFilePath).toString(); | ||
const updatedContents = `${gitignoreContents.trim()}\n\n# HubSpot config file\n${DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME}\n`; | ||
fs.writeFileSync(gitignoreFilePath, updatedContents); | ||
} catch (e) { | ||
// fail silently | ||
logger.debug(i18n(`${i18nKey}.checkFailed`)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { | ||
checkAndWarnGitInclusion as __checkAndWarnGitInclusion, | ||
checkAndUpdateGitignore as __checkAndUpdateGitignore, | ||
} from './git'; | ||
import { outputLogs as __outputLogs } from './logs' | ||
|
||
export const checkAndWarnGitInclusion = __checkAndWarnGitInclusion; | ||
export const checkAndUpdateGitignore = __checkAndUpdateGitignore; | ||
export const outputLogs = __outputLogs; | ||
|
Oops, something went wrong.