replace console.log with nicelog (#1496)

This PR replaces our `console.log` with `nicelog` so that I can more
easily grep for errant console.logs.

### Change Type

- [x] `internal` — Any other changes that don't affect the published
package (will not publish a new version)
This commit is contained in:
Steve Ruiz 2023-06-01 19:01:49 +01:00 committed by GitHub
parent 0c4174c0b8
commit a3c39cde4b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 80 additions and 78 deletions

View file

@ -58,12 +58,6 @@ module.exports = {
'no-console': ['error', { allow: ['warn', 'error'] }],
},
},
{
files: ['apps/fixup/**/*', 'scripts/**/*'],
rules: {
'no-console': 'off',
},
},
{
files: ['e2e/**/*'],
rules: {

View file

@ -58,7 +58,7 @@ You can subscribe to changes using `app.store.listen`. Each time a transaction c
```ts
app.store.listen(entry => {
console.log(entry) // { changes, source }
entry // { changes, source }
})
```

View file

@ -66,6 +66,7 @@
"@tldraw/tlstore": "workspace:*",
"@tldraw/tlvalidate": "workspace:*",
"@tldraw/ui": "workspace:*",
"@tldraw/utils": "workspace:*",
"lazyrepo": "0.0.0-alpha.26",
"rimraf": "^4.4.0",
"ts-node": "^10.9.1"

View file

@ -17,7 +17,7 @@ import {
import { getApiMarkdown } from './getApiMarkdown'
import { getSlug } from './utils'
const { log } = console
const { log: nicelog } = console
type InputCategory = {
id: string
@ -290,14 +290,14 @@ export async function generateContent(): Promise<GeneratedContent> {
const apiSection = await generateApiDocs()
log('• Generating site content (content.json)')
nicelog('• Generating site content (content.json)')
try {
const outputSections: Section[] = [...(sections as InputSection[]), apiSection]
.map((section) => generateSection(section, content, articles))
.filter((section) => section.categories.some((c) => c.articleIds.length > 0))
log('✔ Generated site content.')
nicelog('✔ Generated site content.')
// Write to disk
@ -310,7 +310,7 @@ export async function generateContent(): Promise<GeneratedContent> {
return contentComplete
} catch (error) {
log(`x Could not generate site content.`)
nicelog(`x Could not generate site content.`)
throw error
}

View file

@ -16,7 +16,7 @@ const clickableShapeCreators = [
{ tool: 'diamond', shape: 'geo' },
{ tool: 'pentagon', shape: 'geo' },
{ tool: 'hexagon', shape: 'geo' },
{ tool: 'octagon', shape: 'geo' },
// { tool: 'octagon', shape: 'geo' },
{ tool: 'star', shape: 'geo' },
{ tool: 'rhombus', shape: 'geo' },
{ tool: 'oval', shape: 'geo' },
@ -42,7 +42,7 @@ const draggableShapeCreators = [
{ tool: 'diamond', shape: 'geo' },
{ tool: 'pentagon', shape: 'geo' },
{ tool: 'hexagon', shape: 'geo' },
{ tool: 'octagon', shape: 'geo' },
// { tool: 'octagon', shape: 'geo' },
{ tool: 'star', shape: 'geo' },
{ tool: 'rhombus', shape: 'geo' },
{ tool: 'oval', shape: 'geo' },

View file

@ -1,7 +1,7 @@
import { TldrawFile } from '@tldraw/file-format'
import * as vscode from 'vscode'
import { defaultFileContents, fileExists, loadFile } from './file'
import { log } from './utils'
import { nicelog } from './utils'
export type DocumentChangeEventArgs =
| { reason: 'undo' | 'redo' }
@ -55,20 +55,20 @@ export class TLDrawDocument implements vscode.CustomDocument {
}
makeEdit(nextFile: TldrawFile) {
log('makeEdit')
nicelog('makeEdit')
const prevData = this.documentData
this.documentData = nextFile
this._onDidChange.fire({
label: 'edit',
undo: async () => {
log('undo')
nicelog('undo')
this.documentData = prevData
this._onDidChangeDocument.fire({
reason: 'undo',
})
},
redo: async () => {
log('redo')
nicelog('redo')
this.documentData = nextFile
this._onDidChangeDocument.fire({
reason: 'redo',
@ -82,7 +82,7 @@ export class TLDrawDocument implements vscode.CustomDocument {
}
private static async readFile(uri: vscode.Uri): Promise<TldrawFile> {
log('readFile')
nicelog('readFile')
if (uri.scheme === 'untitled') {
return defaultFileContents
@ -101,13 +101,13 @@ export class TLDrawDocument implements vscode.CustomDocument {
/** Called by VS Code when the user saves the document. */
async save(cancellation: vscode.CancellationToken): Promise<void> {
log('save')
nicelog('save')
await this.saveAs(this.uri, cancellation)
}
/** Called by VS Code when the user saves the document to a new location. */
async saveAs(targetResource: vscode.Uri, cancellation: vscode.CancellationToken): Promise<void> {
log('saveAs')
nicelog('saveAs')
if (cancellation.isCancellationRequested) {
return
}
@ -121,7 +121,7 @@ export class TLDrawDocument implements vscode.CustomDocument {
/** Called by VS Code when the user calls `revert` on a document. */
async revert(_cancellation: vscode.CancellationToken): Promise<void> {
log('revert')
nicelog('revert')
const diskContent = await TLDrawDocument.readFile(this.uri)
this.documentData = diskContent
@ -140,7 +140,7 @@ export class TLDrawDocument implements vscode.CustomDocument {
destination: vscode.Uri,
cancellation: vscode.CancellationToken
): Promise<vscode.CustomDocumentBackup> {
log('backup')
nicelog('backup')
this.lastBackupDestination = destination
await this.saveAs(destination, cancellation)

View file

@ -1,7 +1,7 @@
import * as vscode from 'vscode'
import { DocumentChangeEventArgs, TLDrawDocument } from './TldrawDocument'
import { TldrawWebviewManager } from './TldrawWebviewManager'
import { log } from './utils'
import { nicelog } from './utils'
// @ts-ignore
import type { VscodeMessage } from '../../messages'
@ -63,12 +63,12 @@ export class TldrawEditorProvider implements vscode.CustomEditorProvider<TLDrawD
openContext: { backupId?: string },
_token: vscode.CancellationToken
): Promise<TLDrawDocument> {
log('openCustomDocument')
nicelog('openCustomDocument')
const document: TLDrawDocument = await TLDrawDocument.create(uri, openContext.backupId)
this.disposables.push(
document.onDidChange((e) => {
log('onDidChange')
nicelog('onDidChange')
// Tell VS Code that the document has been edited by the use.
this._onDidChangeCustomDocument.fire({
@ -80,7 +80,7 @@ export class TldrawEditorProvider implements vscode.CustomEditorProvider<TLDrawD
this.disposables.push(
document.onDidChangeContent((e: DocumentChangeEventArgs) => {
log('onDidChange')
nicelog('onDidChange')
this.webviewPanels.forEach((w: vscode.WebviewPanel) => {
if (w.active) {
@ -102,7 +102,7 @@ export class TldrawEditorProvider implements vscode.CustomEditorProvider<TLDrawD
)
document.onDidDispose(() => {
log('onDidDispose document in provider')
nicelog('onDidDispose document in provider')
this.disposables.forEach((d) => d.dispose())
})
@ -114,7 +114,7 @@ export class TldrawEditorProvider implements vscode.CustomEditorProvider<TLDrawD
webviewPanel: vscode.WebviewPanel,
_token: vscode.CancellationToken
): Promise<void> {
log('resolveCustomEditor')
nicelog('resolveCustomEditor')
this.webviewPanels.push(webviewPanel)
webviewPanel.onDidDispose(() => {
this.webviewPanels = this.webviewPanels.filter((w) => w !== webviewPanel)

View file

@ -7,6 +7,7 @@ import { loadFile } from './file'
// @ts-ignore
import type { VscodeMessage } from '../../messages'
import { nicelog } from './utils'
export const GlobalStateKeys = {
ShowV1FileOpenWarning: 'showV1fileOpenWarning',
@ -186,13 +187,11 @@ export class WebViewMessageHandler {
for (const oldRecord of oldRecords) {
const newRecord = newRecords.find((r: any) => r.id === oldRecord.id)
if (!newRecord) {
// eslint-disable-next-line no-console
console.log('record missing in new doc', oldRecord)
nicelog('record missing in new doc', oldRecord)
continue
} else {
if (!isEqual(oldRecord, newRecord)) {
// eslint-disable-next-line no-console
console.log('record different', oldRecord, newRecord)
nicelog('record different', oldRecord, newRecord)
continue
}
}
@ -200,13 +199,11 @@ export class WebViewMessageHandler {
for (const newRecord of newRecords) {
const oldRecord = oldRecords.find((r: any) => r.id === newRecord.id)
if (!oldRecord) {
// eslint-disable-next-line no-console
console.log('record missing in oldDoc doc', newRecord)
nicelog('record missing in oldDoc doc', newRecord)
continue
} else {
if (!isEqual(newRecord, oldRecord)) {
// eslint-disable-next-line no-console
console.log('record different', newRecord, oldRecord)
nicelog('record different', newRecord, oldRecord)
continue
}
}

View file

@ -2,6 +2,7 @@ import { watch } from 'fs'
import path from 'path'
import * as vscode from 'vscode'
import { TldrawEditorProvider } from './TldrawEditorProvider'
import { nicelog } from './utils'
export function activate(context: vscode.ExtensionContext) {
try {
@ -10,8 +11,7 @@ export function activate(context: vscode.ExtensionContext) {
__dirname + '/extension.js',
{ persistent: false },
(eventType, filename) => {
// eslint-disable-next-line no-console
console.log('reloading[%s]', eventType, filename)
nicelog('reloading[%s]', eventType, filename)
extensionWatcher.close()
vscode.commands.executeCommand('workbench.action.reloadWindow')
}
@ -22,8 +22,7 @@ export function activate(context: vscode.ExtensionContext) {
editorpath + '/editor/index.js',
{ persistent: false },
(eventType, filename) => {
// eslint-disable-next-line no-console
console.log('reloading[%s]', eventType, filename)
nicelog('reloading[%s]', eventType, filename)
editorWatcher.close()
vscode.commands.executeCommand('workbench.action.reloadWindow')
}

View file

@ -1,6 +1,7 @@
import { createTLSchema } from '@tldraw/editor'
import { TldrawFile } from '@tldraw/file-format'
import * as vscode from 'vscode'
import { nicelog } from './utils'
export const defaultFileContents: TldrawFile = {
tldrawFileFormatVersion: 1,
@ -29,8 +30,7 @@ export async function fileExists(destination: vscode.Uri) {
return true
} catch (e: any) {
if (e.code !== 'FileNotFound') {
// eslint-disable-next-line no-console
console.log(e)
nicelog(e)
}
return false
}

View file

@ -1,6 +1,6 @@
const DEBUG_EVENTS = false
export const log = (...args: any[]) => {
export const nicelog = (...args: any[]) => {
if (process.env.NODE_ENV !== 'production' && DEBUG_EVENTS) {
// eslint-disable-next-line no-console
console.log(...args)

View file

@ -104,8 +104,6 @@ export function getStrokeOutlinePoints(
// Considering saving these and drawing them later? So that we can avoid
// crossing future points.
// console.log(nextDpr)
if (nextDpr > -0.62 && totalLength - strokePoint.runningLength > strokePoint.radius) {
// Draw a "soft" corner
const offset = prevVector.clone().mul(strokePoint.radius)

View file

@ -2,6 +2,7 @@ import { writeFileSync } from 'fs'
import { join, resolve } from 'path'
import { exec } from './lib/exec'
import { readFileIfExists } from './lib/file'
import { nicelog } from './lib/nicelog'
import { getAllWorkspacePackages } from './lib/workspace'
const packagesOurTypesCanDependOn = [
@ -28,13 +29,13 @@ async function main() {
}
const tempDir = (await exec('mktemp', ['-d'])).trim()
console.log(`Working in ${tempDir}`)
nicelog(`Working in ${tempDir}`)
const packages = (await getAllWorkspacePackages()).filter(
({ packageJson }) => !packageJson.private
)
console.log(
nicelog(
'Checking packages:',
packages.map(({ packageJson }) => packageJson.name)
)
@ -43,7 +44,7 @@ async function main() {
const unprefixedName = name.replace('@tldraw/', '')
const dtsFile = await readFileIfExists(join(relativePath, 'api', 'public.d.ts'))
if (!dtsFile) {
console.log(`No public.d.ts for ${name}, skipping`)
nicelog(`No public.d.ts for ${name}, skipping`)
continue
}
@ -52,7 +53,7 @@ async function main() {
tsconfig.files.push(`./${unprefixedName}.d.ts`)
}
console.log('Checking with tsconfig:', tsconfig)
nicelog('Checking with tsconfig:', tsconfig)
writeFileSync(`${tempDir}/tsconfig.json`, JSON.stringify(tsconfig, null, '\t'), 'utf8')
writeFileSync(`${tempDir}/package.json`, JSON.stringify({ dependencies: {} }, null, '\t'), 'utf8')

View file

@ -1,6 +1,7 @@
import kleur from 'kleur'
import path from 'path'
import { REPO_ROOT, writeJsonFile } from './lib/file'
import { nicelog } from './lib/nicelog'
import { getAllWorkspacePackages } from './lib/workspace'
function scriptPath(packageDir: string, scriptName: string) {
@ -94,7 +95,7 @@ async function main({ fix }: { fix?: boolean }) {
const actualScript = packageScripts[scriptName]
const expectedScript = getExpectedScript(packageDir)
if (actualScript !== expectedScript) {
console.log(
nicelog(
[
'❌ ',
kleur.red(`${name}: `),
@ -110,7 +111,7 @@ async function main({ fix }: { fix?: boolean }) {
needsFix.add(name)
errorCount++
} else {
console.log(
nicelog(
[
'✅ ',
kleur.green(`${name}: `),
@ -127,14 +128,14 @@ async function main({ fix }: { fix?: boolean }) {
if (fix) {
for (const { packageJson, name, relativePath } of packages) {
if (needsFix.has(name)) {
console.log(kleur.yellow(`Fixing ${name}...`))
nicelog(kleur.yellow(`Fixing ${name}...`))
await writeJsonFile(path.join(REPO_ROOT, relativePath, 'package.json'), packageJson)
}
}
console.log(kleur.yellow(`Fixed ${errorCount} errors`))
nicelog(kleur.yellow(`Fixed ${errorCount} errors`))
process.exit(0)
} else {
console.log(kleur.red(`Found ${errorCount} errors`))
nicelog(kleur.red(`Found ${errorCount} errors`))
process.exit(1)
}
}

View file

@ -1,4 +1,5 @@
import { execFile } from 'child_process'
import { nicelog } from './nicelog'
type ExecOpts = {
pwd?: string
@ -24,7 +25,7 @@ export async function exec(
env,
}: ExecOpts = {}
): Promise<string> {
console.log(`> $ ${command} ${args.join(' ')} (in ${pwd}))`)
nicelog(`> $ ${command} ${args.join(' ')} (in ${pwd}))`)
return new Promise((resolve, reject) => {
const data: string[] = []

View file

@ -3,6 +3,7 @@ import json5 from 'json5'
import { basename, dirname, join, relative } from 'path'
import prettier from 'prettier'
import { fileURLToPath } from 'url'
import { nicelog } from './nicelog'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
@ -61,16 +62,16 @@ export async function writeFile(filePath: string, contents: Buffer) {
// Ignore
}
if (existingContents && !existingContents.equals(contents)) {
console.log(
nicelog(
`Asset file ${relative(
REPO_ROOT,
filePath
)} has changed. Please run this script again and commit the changes.`
)
console.log('Contents before:')
console.log(existingContents.toString('utf-8'))
console.log('\nContents after:')
console.log(contents.toString('utf-8'))
nicelog('Contents before:')
nicelog(existingContents.toString('utf-8'))
nicelog('\nContents after:')
nicelog(contents.toString('utf-8'))
process.exit(1)
}

4
scripts/lib/nicelog.ts Normal file
View file

@ -0,0 +1,4 @@
export function nicelog(...args: any[]) {
// eslint-disable-next-line no-console
console.log(...args)
}

View file

@ -4,6 +4,7 @@ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'fs'
import path, { join } from 'path'
import { compare, parse } from 'semver'
import { BUBLIC_ROOT } from './file'
import { nicelog } from './nicelog'
export type PackageDetails = {
name: string
@ -110,7 +111,7 @@ export async function publish() {
for (const packageDetails of publishOrder) {
const prereleaseTag = parse(packageDetails.version)?.prerelease[0] ?? 'latest'
console.log(
nicelog(
`Publishing ${packageDetails.name} with version ${packageDetails.version} under tag @${prereleaseTag}`
)
@ -127,7 +128,7 @@ export async function publish() {
const unscopedName = packageDetails.name.replace('@tldraw/', '')
const url = `https://registry.npmjs.org/@tldraw/${unscopedName}/-/${unscopedName}-${newVersion}.tgz`
console.log('looking for package at url: ', url)
nicelog('looking for package at url: ', url)
const res = await fetch(url, {
method: 'HEAD',
})
@ -136,7 +137,7 @@ export async function publish() {
}
break loop
} catch (e) {
console.log('Waiting for package to be published... attemptsRemaining', waitAttempts)
nicelog('Waiting for package to be published... attemptsRemaining', waitAttempts)
waitAttempts--
await new Promise((resolve) => setTimeout(resolve, 3000))
}

View file

@ -1,4 +1,5 @@
import { exec } from './lib/exec'
import { nicelog } from './lib/nicelog'
import { getLatestVersion, publish, setAllVersions } from './lib/publishing'
async function main() {
@ -19,11 +20,11 @@ async function main() {
// module was called directly
const bumpType = (await exec('auto', ['version'])).trim() as 'major' | 'minor' | 'patch' | ''
console.log('bumpType', bumpType)
nicelog('bumpType', bumpType)
if (bumpType === '') {
console.log('nothing to do')
nicelog('nothing to do')
} else if (['major', 'minor', 'patch'].includes(bumpType)) {
console.log('setting canary versions')
nicelog('setting canary versions')
setCanaryVersions(bumpType)
publish()
} else {

View file

@ -3,6 +3,7 @@ import fetch from 'cross-fetch'
import { assert } from 'node:console'
import { parse } from 'semver'
import { exec } from './lib/exec'
import { nicelog } from './lib/nicelog'
import { getLatestVersion, publish, setAllVersions } from './lib/publishing'
async function main() {
@ -26,13 +27,13 @@ async function main() {
await auto.loadConfig()
const bump = await auto.getVersion()
if (!bump) {
console.log('nothing to do')
nicelog('nothing to do')
return
}
const latestVersion = parse(getLatestVersion())!
console.log('latestVersion', latestVersion)
nicelog('latestVersion', latestVersion)
const [prereleaseTag, prereleaseNumber] = latestVersion.prerelease
if (prereleaseTag && typeof prereleaseNumber !== 'number') {
@ -67,7 +68,7 @@ async function main() {
// finally, publish the packages [IF THIS STEP FAILS, RUN THE `publish-manual.ts` script locally]
await publish()
console.log('Notifying huppy of release...')
nicelog('Notifying huppy of release...')
const huppyResponse = await fetch('http://localhost:3000/api/on-release', {
method: 'POST',
headers: {
@ -75,7 +76,7 @@ async function main() {
},
body: JSON.stringify({ apiKey: huppyToken, tagToRelease: `v${nextVersion}`, canary: false }),
})
console.log(
nicelog(
`huppy: [${huppyResponse.status} ${huppyResponse.statusText}] ${await huppyResponse.text()}`
)
}

View file

@ -9,6 +9,7 @@ import {
writeJsonFile,
writeStringFile,
} from './lib/file'
import { nicelog } from './lib/nicelog'
// We'll need to copy the assets into these folders
const PUBLIC_FOLDER_PATHS = [join(BUBLIC_ROOT, 'packages', 'assets')]
@ -166,7 +167,7 @@ async function copyFonts() {
const itemWithoutExtension = item.replace(extension, '')
const name = FONT_MAPPING[itemWithoutExtension]
if (!name) {
console.log('Font mapping not found for', itemWithoutExtension)
nicelog('Font mapping not found for', itemWithoutExtension)
process.exit(1)
}
collectedAssetUrls.fonts[name] = `${folderName}/${item}`
@ -394,18 +395,18 @@ async function writeAssetDeclarationDTSFile(fileName: string, functionName: stri
// --- RUN
async function main() {
console.log('Copying icons...')
nicelog('Copying icons...')
await copyIcons()
console.log('Copying embed icons...')
nicelog('Copying embed icons...')
await copyEmbedIcons()
console.log('Copying fonts...')
nicelog('Copying fonts...')
await copyFonts()
console.log('Copying translations...')
nicelog('Copying translations...')
await copyTranslations()
console.log('Writing asset declaration file...')
nicelog('Writing asset declaration file...')
await writeUrlBasedAssetDeclarationFile()
await writeImportBasedAssetDeclarationFile()
console.log('Done!')
nicelog('Done!')
}
main()

View file

@ -1,6 +1,7 @@
import { execFileSync } from 'child_process'
import path, { join } from 'path'
import { REPO_ROOT, readJsonIfExists } from './lib/file'
import { nicelog } from './lib/nicelog'
import { getAllWorkspacePackages } from './lib/workspace'
async function main() {
@ -12,7 +13,7 @@ async function main() {
if (tsconfigExists) tsconfigFiles.push(tsconfigFile)
}
console.log('Typechecking files:', tsconfigFiles)
nicelog('Typechecking files:', tsconfigFiles)
const args = ['--build']
if (process.argv.includes('--force')) args.push('--force')