|
1 | 1 | import * as fs from 'fs'; |
2 | 2 | import { Item } from 'qiita-js-2'; |
3 | | -import { Uri, window, workspace } from 'vscode'; |
| 3 | +import { TextDocument, Uri, window, workspace } from 'vscode'; |
4 | 4 | import * as nls from 'vscode-nls'; |
| 5 | +import { client } from '../client'; |
| 6 | +import { handleErrorMessage } from '../utils/errorHandler'; |
5 | 7 |
|
6 | 8 | const localize = nls.loadMessageBundle(); |
7 | 9 |
|
| 10 | +/** |
| 11 | + * ワークスペース内でQiitaから同期したファイルを保存したときに呼ばれるイベントリスナ |
| 12 | + * @param item 投稿の元データ |
| 13 | + * @param document 保存されたドキュメント |
| 14 | + */ |
| 15 | +export const updater = async (item: Item, document: TextDocument) => { |
| 16 | + const body = document.getText(); |
| 17 | + |
| 18 | + if (body === item.body) { |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + try { |
| 23 | + await client.updateItem(item.id, { |
| 24 | + title: item.title, |
| 25 | + tags: item.tags, |
| 26 | + body, |
| 27 | + }); |
| 28 | + |
| 29 | + fs.writeFileSync(document.uri.path, document.getText()); |
| 30 | + |
| 31 | + window.showInformationMessage('updated'); |
| 32 | + } catch (error) { |
| 33 | + handleErrorMessage(error); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +/** |
| 38 | + * アイテムを開くコマンドハンドラーを返す関数 |
| 39 | + * @param storagePath 拡張機能のストレージのpath |
| 40 | + */ |
8 | 41 | export function openItem (storagePath?: string) { |
9 | 42 | return async (item: Item) => { |
10 | | - try { |
11 | | - const filePath = `${storagePath}/${item.id}.md`; |
12 | | - const fileUri = `file://${filePath}`; |
| 43 | + if (!storagePath) { |
| 44 | + return; |
| 45 | + } |
13 | 46 |
|
14 | | - if (!storagePath) { |
15 | | - return; |
16 | | - } |
| 47 | + try { |
| 48 | + const fileUri = Uri.parse(`file://${storagePath}/${item.id}.md`); |
17 | 49 |
|
| 50 | + // 拡張機能用ディレクトリがない場合初期化 |
18 | 51 | if (!fs.existsSync(storagePath)) { |
19 | 52 | fs.mkdirSync(storagePath); |
20 | 53 | } |
21 | 54 |
|
22 | | - fs.writeFileSync(filePath, item.body); |
| 55 | + // まだファイルをローカルに保存していない場合初期化 |
| 56 | + if (!fs.existsSync(fileUri.fsPath)) { |
| 57 | + fs.writeFileSync(fileUri.fsPath, item.body); |
| 58 | + } |
23 | 59 |
|
24 | | - const document = await workspace.openTextDocument(Uri.parse(fileUri)); |
| 60 | + const document = await workspace.openTextDocument(fileUri); |
25 | 61 | await window.showTextDocument(document); |
| 62 | + |
| 63 | + // 保存時にアップデートするためのイベントリスナを追加 |
| 64 | + workspace.onDidSaveTextDocument(async (updatedDocument) => { |
| 65 | + if (updatedDocument.uri.path === fileUri.path) { |
| 66 | + await updater(item, updatedDocument); |
| 67 | + } |
| 68 | + }); |
26 | 69 | } catch (error) { |
27 | 70 | window.showErrorMessage(localize( |
28 | 71 | 'commands.openItem.failure.fallback', |
|
0 commit comments