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'] }], 'no-console': ['error', { allow: ['warn', 'error'] }],
}, },
}, },
{
files: ['apps/fixup/**/*', 'scripts/**/*'],
rules: {
'no-console': 'off',
},
},
{ {
files: ['e2e/**/*'], files: ['e2e/**/*'],
rules: { rules: {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,6 +3,7 @@ import json5 from 'json5'
import { basename, dirname, join, relative } from 'path' import { basename, dirname, join, relative } from 'path'
import prettier from 'prettier' import prettier from 'prettier'
import { fileURLToPath } from 'url' import { fileURLToPath } from 'url'
import { nicelog } from './nicelog'
const __filename = fileURLToPath(import.meta.url) const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename) const __dirname = dirname(__filename)
@ -61,16 +62,16 @@ export async function writeFile(filePath: string, contents: Buffer) {
// Ignore // Ignore
} }
if (existingContents && !existingContents.equals(contents)) { if (existingContents && !existingContents.equals(contents)) {
console.log( nicelog(
`Asset file ${relative( `Asset file ${relative(
REPO_ROOT, REPO_ROOT,
filePath filePath
)} has changed. Please run this script again and commit the changes.` )} has changed. Please run this script again and commit the changes.`
) )
console.log('Contents before:') nicelog('Contents before:')
console.log(existingContents.toString('utf-8')) nicelog(existingContents.toString('utf-8'))
console.log('\nContents after:') nicelog('\nContents after:')
console.log(contents.toString('utf-8')) nicelog(contents.toString('utf-8'))
process.exit(1) 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 path, { join } from 'path'
import { compare, parse } from 'semver' import { compare, parse } from 'semver'
import { BUBLIC_ROOT } from './file' import { BUBLIC_ROOT } from './file'
import { nicelog } from './nicelog'
export type PackageDetails = { export type PackageDetails = {
name: string name: string
@ -110,7 +111,7 @@ export async function publish() {
for (const packageDetails of publishOrder) { for (const packageDetails of publishOrder) {
const prereleaseTag = parse(packageDetails.version)?.prerelease[0] ?? 'latest' const prereleaseTag = parse(packageDetails.version)?.prerelease[0] ?? 'latest'
console.log( nicelog(
`Publishing ${packageDetails.name} with version ${packageDetails.version} under tag @${prereleaseTag}` `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 unscopedName = packageDetails.name.replace('@tldraw/', '')
const url = `https://registry.npmjs.org/@tldraw/${unscopedName}/-/${unscopedName}-${newVersion}.tgz` 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, { const res = await fetch(url, {
method: 'HEAD', method: 'HEAD',
}) })
@ -136,7 +137,7 @@ export async function publish() {
} }
break loop break loop
} catch (e) { } catch (e) {
console.log('Waiting for package to be published... attemptsRemaining', waitAttempts) nicelog('Waiting for package to be published... attemptsRemaining', waitAttempts)
waitAttempts-- waitAttempts--
await new Promise((resolve) => setTimeout(resolve, 3000)) await new Promise((resolve) => setTimeout(resolve, 3000))
} }

View file

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

View file

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

View file

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

View file

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