Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fallback session state to file#526

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
ShMcK merged 5 commits intomasterfromfallback-to-file
Nov 21, 2021
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletionsdocs/docs/env-vars.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,8 @@ CodeRoad has a number of configurations:

- `CODEROAD_WEBHOOK_TOKEN` - an optional token for authenticating/authorizing webhook endpoints. Passed to the webhook endpoint in a `CodeRoad-User-Token` header.

- `CODEROAD_SESSION_STORAGE_PATH` - the path to a directory for writing session storage to files. Helps preserves state across containers. Example: `../tmp`.

## How to Use Variables

### Local
Expand Down
4 changes: 2 additions & 2 deletionssrc/actions/onStartup.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,8 @@ const onStartup = async (context: Context): Promise<void> => {

// NEW: no stored tutorial, must start new tutorial
if (!tutorial || !tutorial.id) {
if (!!TUTORIAL_URL) {
//NEW_FROM_URL
if (TUTORIAL_URL) {
//if a tutorial URL is added, launch on startup
try {
const tutorialRes = await fetch(TUTORIAL_URL)
const tutorial = await tutorialRes.json()
Expand Down
3 changes: 3 additions & 0 deletionssrc/environment.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,3 +46,6 @@ export const CONTENT_SECURITY_POLICY_EXEMPTIONS: string | null =

// optional token for authorization/authentication of webhook calls
export const WEBHOOK_TOKEN = process.env.CODEROAD_WEBHOOK_TOKEN || null

// a path to write session state to a file. Useful for maintaining session across containers
export const SESSION_STORAGE_PATH = process.env.CODEROAD_SESSION_STORAGE_PATH || null
1 change: 1 addition & 0 deletionssrc/services/context/state/Position.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ class Position {
setTutorial(workspaceState: vscode.Memento, tutorial: TT.Tutorial): void {
this.storage = new Storage<T.Position>({
key: `coderoad:position:${tutorial.id}:${tutorial.version}`,
filePath: 'coderoad_position',
storage: workspaceState,
defaultValue,
})
Expand Down
1 change: 1 addition & 0 deletionssrc/services/context/state/Tutorial.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ class Tutorial {
constructor(workspaceState: vscode.Memento) {
this.storage = new Storage<TT.Tutorial | null>({
key: 'coderoad:currentTutorial',
filePath: 'coderoad_tutorial',
storage: workspaceState,
defaultValue: null,
})
Expand Down
24 changes: 20 additions & 4 deletionssrc/services/node/index.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,25 +7,41 @@ import { WORKSPACE_ROOT } from '../../environment'
const asyncExec = promisify(cpExec)
const asyncRemoveFile = promisify(fs.unlink)
const asyncReadFile = promisify(fs.readFile)
const asyncWriteFile = promisify(fs.writeFile)

interface ExecParams {
command: string
dir?: string
}

// correct paths to be from workspace root rather than extension folder
const getWorkspacePath = (...paths: string[]) => {
return join(WORKSPACE_ROOT, ...paths)
}

export const exec = (params: ExecParams): Promise<{ stdout: string; stderr: string }> | never => {
const cwd = join(WORKSPACE_ROOT, params.dir || '')
return asyncExec(params.command, { cwd })
}

export const exists = (...paths: string[]): boolean | never => {
return fs.existsSync(join(WORKSPACE_ROOT,...paths))
return fs.existsSync(getWorkspacePath(...paths))
}

export const removeFile = (...paths: string[]) => {
return asyncRemoveFile(join(WORKSPACE_ROOT, ...paths))
return asyncRemoveFile(getWorkspacePath(...paths))
}

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}`)
})
}

export const readFile = (...paths: string[]) => {
return asyncReadFile(join(...paths))
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}`)
})
}
50 changes: 48 additions & 2 deletionssrc/services/storage/index.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import * as vscode from 'vscode'
import { readFile, writeFile } from '../node'
import { SESSION_STORAGE_PATH } from '../../environment'

// NOTE: localStorage is not available on client
// and must be stored in editor
Expand All@@ -8,31 +10,75 @@ import * as vscode from 'vscode'
// forcing it to be passed in through activation and down to other tools
class Storage<T> {
private key: string
private filePath: string
private storage: vscode.Memento
private defaultValue: T
constructor({ key, storage, defaultValue }: { key: string; storage: vscode.Memento; defaultValue: T }) {
constructor({
key,
filePath,
storage,
defaultValue,
}: {
key: string
filePath: string
storage: vscode.Memento
defaultValue: T
}) {
this.storage = storage
this.key = key
this.filePath = filePath
this.defaultValue = defaultValue
}
public get = async (): Promise<T> => {
const value: string | undefined = await this.storage.get(this.key)
if (value) {
return JSON.parse(value)
} else if (SESSION_STORAGE_PATH) {
try {
// optionally read from file as a fallback to local storage
const sessionFile = await readFile(SESSION_STORAGE_PATH, `${this.filePath}.json`)
if (!sessionFile) {
throw new Error('No session file found')
}
const data: T = JSON.parse(sessionFile)

if (data) {
// validate session
const keys = Object.keys(data)
if (keys.length) {
return data
}
}
} catch (err) {
console.warn(`Failed to read or parse session file: ${SESSION_STORAGE_PATH}/${this.filePath}.json`)
}
}
return this.defaultValue
}
public set = (value: T): void => {
const stringValue = JSON.stringify(value)
this.storage.update(this.key, stringValue)
this.writeToSessionFile(stringValue)
}
public update = async (value: T): Promise<void> => {
const current = await this.get()
const next = JSON.stringify({
...current,
...value,
})
this.storage.update(this.key, next)
await this.storage.update(this.key, next)

this.writeToSessionFile(next)
}
public writeToSessionFile(data: string) {
// optionally write state to file, useful when state cannot be controlled across containers
if (SESSION_STORAGE_PATH) {
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`)
}
}
}
public reset = () => {
this.set(this.defaultValue)
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp