Skip to content

Feature/output channel #557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 3, 2022
Prev Previous commit
Next Next commit
update logging across app
Signed-off-by: shmck <shawn.j.mckay@gmail.com>
  • Loading branch information
ShMcK committed Jan 2, 2022
commit 47ad9f84fb5c00050b8d3e156eb1680f97d8f7d0
3 changes: 2 additions & 1 deletion src/actions/onRunReset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Context from '../services/context/context'
import reset from '../services/reset'
import * as hooks from '../services/hooks'
import getCommitHashByPosition from '../services/reset/lastHash'
import logger from '../services/logger'

type ResetAction = {
type: 'LATEST' | 'POSITION'
Expand All @@ -22,7 +23,7 @@ const onRunReset = async (action: ResetAction, context: Context): Promise<void>
const branch = tutorial?.config.repo.branch

if (!branch) {
console.error('No repo branch found for tutorial')
logger('Error: No repo branch found for tutorial')
return
}

Expand Down
34 changes: 18 additions & 16 deletions src/services/git/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ const stashAllFiles = async (): Promise<never | void> => {
// stash files including untracked (eg. newly created file)
const { stderr } = await exec({ command: `git stash --include-untracked` })
if (stderr) {
console.error(stderr)
logger(`Error: ${stderr}`)
throw new Error('Error stashing files')
}
}

const cherryPickCommit = async (commit: string, count = 0): Promise<never | void> => {
if (count > 1) {
console.warn('cherry-pick failed')
logger('cherry-pick failed')
return
}
try {
Expand All @@ -26,8 +26,8 @@ const cherryPickCommit = async (commit: string, count = 0): Promise<never | void
if (!stdout) {
throw new Error('No cherry-pick output')
}
} catch (error) {
console.log('cherry-pick-commit failed')
} catch (error: any) {
logger(`cherry-pick-commit failed: ${error.message}`)
// stash all files if cherry-pick fails
await stashAllFiles()
return cherryPickCommit(commit, ++count)
Expand All @@ -50,10 +50,10 @@ export function loadCommit(commit: string): Promise<never | void> {
export async function saveCommit(message: string): Promise<never | void> {
const { stdout, stderr } = await exec({ command: `git commit -am '${message}'` })
if (stderr) {
console.error(stderr)
logger(`Error: ${stderr}`)
throw new Error('Error saving progress to Git')
}
logger(['save with commit & continue stdout', stdout])
logger(stdout)
}

export async function clear(): Promise<Error | void> {
Expand All @@ -63,9 +63,9 @@ export async function clear(): Promise<Error | void> {
if (!stderr) {
return
}
console.error(stderr)
} catch (error) {
console.error(error)
logger(`Error: ${stderr}`)
} catch (error: any) {
logger(`Error: ${error.message}`)
}
throw new Error('Error cleaning up current unsaved work')
}
Expand Down Expand Up @@ -127,7 +127,7 @@ export async function addRemote(repo: string): Promise<never | void> {

// validate the response is acceptable
if (!alreadyExists && !successfulNewBranch) {
console.error(stderr)
logger(`Error: ${stderr}`)
throw new Error('Error adding git remote')
}
}
Expand All @@ -142,7 +142,8 @@ export async function checkRemoteExists(): Promise<boolean> {
// string match on remote output
// TODO improve the specificity of this regex
return !!stdout.match(gitOrigin)
} catch (error) {
} catch (error: any) {
logger(`Warn: ${error.message}`)
return false
}
}
Expand All @@ -168,8 +169,9 @@ export async function loadCommitHistory(): Promise<string[]> {
}
// string match on remote output
return stdout.split('\n')
} catch (error) {
} catch (error: any) {
// likely no git setup or no commits
logger(`Warn: ${error.message}`)
return []
}
}
Expand All @@ -189,8 +191,8 @@ export async function getCommitMessage(hash: string): Promise<string | null> {
}
// string match on remote output
return stdout
} catch (error) {
logger('error', error)
} catch (error: any) {
logger(`Error: ${error.message}`)
// likely no git commit message found
return null
}
Expand All @@ -204,8 +206,8 @@ export async function commitsExistsByMessage(message: string): Promise<boolean>
return false
}
return !!stdout.length
} catch (error) {
logger('error', error)
} catch (error: any) {
logger(`Error: ${error.message}`)
// likely no commit found
return false
}
Expand Down
3 changes: 2 additions & 1 deletion src/services/hooks/utils/openFiles.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { join } from 'path'
import * as vscode from 'vscode'
import logger from '../../logger'

const openFiles = async (files: string[] = []): Promise<void> => {
if (!files.length) {
Expand All @@ -16,7 +17,7 @@ const openFiles = async (files: string[] = []): Promise<void> => {
const doc = await vscode.workspace.openTextDocument(absoluteFilePath)
await vscode.window.showTextDocument(doc, vscode.ViewColumn.One)
} catch (error: any) {
console.log(`Failed to open file ${filePath}: ${error.message}`)
logger(`Failed to open file ${filePath}: ${error.message}`)
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/services/hooks/utils/runCommands.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { exec } from '../../node'
import { send } from '../../../commands'
import logger from '../../logger'

const runCommands = async (commands: string[] = []): Promise<void> => {
if (!commands.length) {
Expand All @@ -14,9 +15,9 @@ const runCommands = async (commands: string[] = []): Promise<void> => {
let result: { stdout: string; stderr: string }
try {
result = await exec({ command })
console.log(result)
logger(result)
} catch (error: any) {
console.error(`Command failed: ${error.message}`)
logger(`Command failed: ${error.message}`)
send({ type: 'COMMAND_FAIL', payload: { process: { ...process, status: 'FAIL' } } })
return
}
Expand Down
2 changes: 0 additions & 2 deletions src/services/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ export type Log = any
const logChannel = getOutputChannel('CodeRoad (Logs)')

const logger = (...messages: Log[]): void => {
// Inside vscode, you console.log does not allow more than 1 param
// to get around it, we can log with multiple log statements
for (const message of messages) {
if (typeof message === 'object') {
logChannel.appendLine(message)
Expand Down
5 changes: 3 additions & 2 deletions src/services/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as fs from 'fs'
import { join } from 'path'
import { promisify } from 'util'
import { WORKSPACE_ROOT } from '../../environment'
import logger from '../logger'

const asyncExec = promisify(cpExec)
const asyncRemoveFile = promisify(fs.unlink)
Expand Down Expand Up @@ -35,13 +36,13 @@ export const removeFile = (...paths: string[]) => {
export const readFile = (...paths: string[]): Promise<string | void> => {
const filePath = getWorkspacePath(...paths)
return asyncReadFile(getWorkspacePath(...paths), 'utf8').catch((err) => {
console.warn(`Failed to read from ${filePath}: ${err.message}`)
logger(`Failed to read from ${filePath}: ${err.message}`)
})
}

export const writeFile = (data: any, ...paths: string[]): Promise<void> => {
const filePath = getWorkspacePath(...paths)
return asyncWriteFile(filePath, data).catch((err) => {
console.warn(`Failed to write to ${filePath}: ${err.message}`)
logger(`Failed to write to ${filePath}: ${err.message}`)
})
}
9 changes: 4 additions & 5 deletions src/services/reset/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { exec, removeFile } from '../node'

import logger from '../logger'
interface Input {
hash: string
branch: string
Expand All @@ -17,13 +17,13 @@ const reset = async ({ branch, hash }: Input): Promise<void> => {
try {
// if no git init, will initialize
// otherwise re-initializes git
await exec({ command: 'git init' }).catch(console.log)
await exec({ command: 'git init' }).catch(logger)

// capture current branch
const hasBranch = await exec({ command: 'git branch --show-current' })
const localBranch = hasBranch.stdout
// check if coderoad remote exists
const hasRemote = await exec({ command: 'git remote -v' }).catch(console.warn)
const hasRemote = await exec({ command: 'git remote -v' }).catch(logger)
if (!hasRemote || !hasRemote.stdout || !hasRemote.stdout.length) {
throw new Error('No remote found')
} else if (!hasRemote.stdout.match(new RegExp(remote))) {
Expand Down Expand Up @@ -64,8 +64,7 @@ const reset = async ({ branch, hash }: Input): Promise<void> => {
command: `git reset --hard ${hash}`,
})
} catch (error: any) {
console.error('Error resetting')
console.error(error.message)
logger(`Error resetting: ${error.message}`)
}
}

Expand Down
13 changes: 8 additions & 5 deletions src/services/storage/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as vscode from 'vscode'
import { readFile, writeFile } from '../node'
import { SESSION_STORAGE_PATH } from '../../environment'
import logger from '../logger'

// NOTE: localStorage is not available on client
// and must be stored in editor
Expand Down Expand Up @@ -46,17 +47,17 @@ class Storage<T> {
return data
}
}
} catch (err) {
console.warn(`Failed to read or parse session file: ${SESSION_STORAGE_PATH}/${this.filePath}.json`)
} catch (err: any) {
logger(`Failed to read or parse session file: ${SESSION_STORAGE_PATH}/${this.filePath}.json: ${err.message}`)
}
}
const value: string | undefined = await this.storage.get(this.key)
if (value) {
// 2. read from local storage
try {
return JSON.parse(value)
} catch (err) {
console.warn(`Failed to parse session state from local storage: ${value}`)
} catch (err: any) {
logger(`Failed to parse session state from local storage: ${value}: ${err.message}`)
}
}
// 3. fallback to the default
Expand All @@ -83,7 +84,9 @@ class Storage<T> {
try {
writeFile(data, SESSION_STORAGE_PATH, `${this.filePath}.json`)
} catch (err: any) {
console.warn(`Failed to write coderoad session to path: ${SESSION_STORAGE_PATH}/${this.filePath}.json`)
logger(
`Failed to write coderoad session to path: ${SESSION_STORAGE_PATH}/${this.filePath}.json: ${err.message}`,
)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/services/testRunner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ const createTestRunner = (data: TT.Tutorial, callbacks: Callbacks): ((params: an
// calculate level & step from position
const level: TT.Level | null = data.levels.find((l) => l.id === position.levelId) || null
if (!level) {
console.warn(`Level "${position.levelId}" not found`)
logger(`Error: Level "${position.levelId}" not found`)
return
}
const step: TT.Step | null = level.steps.find((s) => s.id === position.stepId) || null
if (!step) {
console.warn(`Step "${position.stepId}" not found`)
logger(`Error: Step "${position.stepId}" not found`)
return
}

Expand Down
3 changes: 2 additions & 1 deletion src/services/webview/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as vscode from 'vscode'
import { asyncReadFile } from '../node'
import { onError } from '../telemetry'
import { CONTENT_SECURITY_POLICY_EXEMPTIONS } from '../../environment'
import logger from '../logger'

const getNonce = (): string => {
let text = ''
Expand Down Expand Up @@ -142,8 +143,8 @@ async function render(panel: vscode.WebviewPanel, rootPath: string): Promise<voi
// set view
panel.webview.html = html
} catch (error: any) {
logger(`Error: ${error.message}`)
onError(error)
console.error(error)
}
}

Expand Down
3 changes: 2 additions & 1 deletion web-app/src/components/Error/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { css, jsx } from '@emotion/core'
import Markdown from '../Markdown'
import Button from '../../components/Button'
import { Theme } from '../../styles/theme'
import logger from '../../services/logger'

const styles = {
container: (theme: Theme) => ({
Expand Down Expand Up @@ -42,7 +43,7 @@ const ErrorMarkdown = ({ error, send }: Props) => {
React.useEffect(() => {
if (error) {
// log error
console.log(`ERROR in markdown: ${error.message}`)
logger(`ERROR in markdown: ${error.message}`)
}
}, [error])

Expand Down
4 changes: 2 additions & 2 deletions web-app/src/components/ErrorBoundary/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ class ErrorBoundary extends React.Component {
// Display fallback UI
this.setState({ errorMessage: error.message })
// You can also log the error to an error reporting service
logger('ERROR in component:', JSON.stringify(error))
logger('ERROR info:', JSON.stringify(info))
logger(`ERROR in component: ${JSON.stringify(error)}`)
logger(`ERROR info:: ${JSON.stringify(info)}`)
}

public render() {
Expand Down
9 changes: 5 additions & 4 deletions web-app/src/components/Markdown/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import MarkdownIt from 'markdown-it'
import Prism from 'prismjs'
import { css, jsx, InterpolationWithTheme } from '@emotion/core'
import { css, jsx } from '@emotion/core'
// @ts-ignore no types for package
import markdownEmoji from 'markdown-it-emoji'
import * as React from 'react'
// load prism styles & language support
import './prism'
import logger from '../../services/logger'

// markdown highlighter instance
const md: MarkdownIt = new MarkdownIt({
Expand All @@ -17,8 +18,8 @@ const md: MarkdownIt = new MarkdownIt({

try {
hl = Prism.highlight(str, Prism.languages[lang], lang)
} catch (error) {
console.error(error)
} catch (error: any) {
logger(`Error highlighing markdown: ${error.message}`)
hl = md.utils.escapeHtml(str)
}

Expand Down Expand Up @@ -66,7 +67,7 @@ const Markdown = (props: Props) => {
} catch (error) {
const message = `Failed to parse markdown for ${props.children}`
// TODO: onError(new Error(message))
console.log(message)
logger(message)
html = `<div style='background-color: #FFB81A; padding: 0.5rem;'>
<strong style='padding-bottom: 0.5rem;'>ERROR: Failed to parse markdown</strong>
<p>${props.children}</p>
Expand Down
3 changes: 2 additions & 1 deletion web-app/src/components/Router/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react'
import logger from '../../services/logger'

interface RouterProps {
children: any
Expand Down Expand Up @@ -41,7 +42,7 @@ export const Router = ({ children, route }: RouterProps) => {
}
const message = `No Route matches for "${JSON.stringify(route)}"`
// TODO: onError(new Error(message))
console.warn(message)
logger(message)
return null
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Dialog } from '@alifd/next'
import useFetch from '../../services/hooks/useFetch'
import * as TT from 'typings/tutorial'
import LoadingPage from '../Loading'
import logger from '../../services/logger'

interface Props {
url: string
Expand All @@ -16,7 +17,7 @@ const LoadTutorialSummary = (props: Props) => {
return <LoadingPage text="Loading tutorial summary..." />
}
if (error) {
console.log(`Failed to load tutorial summary: ${error}`)
logger(`Failed to load tutorial summary: ${error}`)
return <div>Error loading summary</div>
}
if (!data) {
Expand Down
Loading