Skip to content

Commit 8575e89

Browse files
committed
refactor: leave only fs related functions in utils.ts
1 parent 07f0353 commit 8575e89

File tree

4 files changed

+42
-111
lines changed

4 files changed

+42
-111
lines changed

src/configuration.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,3 +985,11 @@ export class Features {
985985
}
986986
}
987987

988+
export function getWorkspacePgSrcFile(workspace: vscode.Uri, ...paths: string[]) {
989+
const customDir = VsCodeSettings.getSrcPath();
990+
if (customDir) {
991+
return utils.joinPath(workspace, customDir, ...paths);
992+
}
993+
994+
return utils.joinPath(workspace, ...paths);
995+
}

src/extension.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import { Commands,
1111
openConfigFileCommand,
1212
refreshConfigCommand,
1313
setupConfiguration,
14-
Features } from './configuration';
14+
Features,
15+
getWorkspacePgSrcFile } from './configuration';
1516
import { setupPgConfSupport } from './pgconf';
1617
import { PgindentDocumentFormatterProvider,
1718
setupFormatting } from './formatter';
@@ -84,7 +85,7 @@ async function promptExtensionName() {
8485

8586
const workspace = await promptWorkspace();
8687
return {
87-
path: utils.getWorkspacePgSrcFile(workspace.uri, 'contrib', extensionName),
88+
path: getWorkspacePgSrcFile(workspace.uri, 'contrib', extensionName),
8889
name: extensionName,
8990
};
9091
}
@@ -430,9 +431,9 @@ async function findAllFilesWithNodeTags(folders: readonly vscode.WorkspaceFolder
430431
*/
431432
let file;
432433
if (16_00_00 <= pgversion) {
433-
file = utils.getWorkspacePgSrcFile(folder.uri, 'src', 'include', 'nodes', 'nodetags.h');
434+
file = getWorkspacePgSrcFile(folder.uri, 'src', 'include', 'nodes', 'nodetags.h');
434435
} else {
435-
file = utils.getWorkspacePgSrcFile(folder.uri, 'src', 'include', 'nodes', 'nodes.h');
436+
file = getWorkspacePgSrcFile(folder.uri, 'src', 'include', 'nodes', 'nodes.h');
436437
}
437438

438439
if (await utils.fileExists(file)) {
@@ -455,7 +456,7 @@ async function findAllFilesWithNodeTags(folders: readonly vscode.WorkspaceFolder
455456
}
456457
} else {
457458
for (const folder of folders) {
458-
uri = utils.getWorkspacePgSrcFile(folder.uri, customFile);
459+
uri = getWorkspacePgSrcFile(folder.uri, customFile);
459460
if (await utils.fileExists(uri)) {
460461
break;
461462
}

src/formatter.ts

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as path from 'path';
22
import * as os from 'os';
33
import * as cp from 'child_process';
4+
import * as crypto from 'crypto';
45

56
import * as vscode from 'vscode';
67

@@ -9,11 +10,19 @@ import { Log as logger } from './logger';
910
import { getWellKnownBuiltinContribs } from './constants';
1011
import { Configuration,
1112
getWorkspaceFolder,
12-
VsCodeSettings } from './configuration';
13+
VsCodeSettings,
14+
getWorkspacePgSrcFile } from './configuration';
1315
import { PghhError } from './error';
1416

1517
class FormattingError extends PghhError {}
1618

19+
async function createTempFile(template: string, content: string) {
20+
const filename = template.replace('{}', crypto.randomUUID().toString());
21+
const tempFile = vscode.Uri.file(path.join(os.tmpdir(), filename));
22+
await utils.writeFile(tempFile, content);
23+
return tempFile;
24+
}
25+
1726
class ShellExecError extends PghhError {
1827
constructor(public command: string,
1928
public stderr: string,
@@ -88,7 +97,7 @@ export class PgindentDocumentFormatterProvider implements vscode.DocumentFormatt
8897
private savedPgbsdPath?: vscode.Uri;
8998

9099
private async getPgConfigPath(workspace: vscode.Uri) {
91-
const possiblePgConfigPath = utils.getWorkspacePgSrcFile(
100+
const possiblePgConfigPath = getWorkspacePgSrcFile(
92101
workspace, 'src', 'bin', 'pg_config', 'pg_config');
93102
if (await utils.fileExists(possiblePgConfigPath)) {
94103
return possiblePgConfigPath;
@@ -166,7 +175,7 @@ export class PgindentDocumentFormatterProvider implements vscode.DocumentFormatt
166175
* Actually clone sources. Note that here we are only if we are running
167176
* in pg version 16< where pg_bsd_indent
168177
*/
169-
const pgindentDir = utils.getWorkspacePgSrcFile(
178+
const pgindentDir = getWorkspacePgSrcFile(
170179
workspace, 'src', 'tools', 'pgindent');
171180
logger.info('cloning pg_bsd_indent repository');
172181
/* XXX: maybe better to download archive, not full history? */
@@ -244,7 +253,7 @@ export class PgindentDocumentFormatterProvider implements vscode.DocumentFormatt
244253
* - src/tools/pgindent/pg_bsd_indent (PG <16)
245254
* - not exist: download + build
246255
*/
247-
let pgBsdIndentDir = utils.getWorkspacePgSrcFile(
256+
let pgBsdIndentDir = getWorkspacePgSrcFile(
248257
workspace, 'src', 'tools', 'pg_bsd_indent');
249258

250259
/* src/tools/pg_bsd_indent */
@@ -262,7 +271,7 @@ export class PgindentDocumentFormatterProvider implements vscode.DocumentFormatt
262271
}
263272

264273
/* src/tools/pgindent/pg_bsd_indent */
265-
pgBsdIndentDir = utils.getWorkspacePgSrcFile(
274+
pgBsdIndentDir = getWorkspacePgSrcFile(
266275
workspace, 'src', 'tools', 'pgindent', 'pg_bsd_indent');
267276
const pgBsdIndent = utils.joinPath(pgBsdIndentDir, 'pg_bsd_indent');
268277
if (await utils.fileExists(pgBsdIndent)) {
@@ -302,7 +311,7 @@ export class PgindentDocumentFormatterProvider implements vscode.DocumentFormatt
302311
if (path.isAbsolute(t)) {
303312
typedefFile = vscode.Uri.file(t);
304313
} else {
305-
typedefFile = utils.getWorkspacePgSrcFile(workspace, t);
314+
typedefFile = getWorkspacePgSrcFile(workspace, t);
306315
}
307316

308317
if (!await utils.fileExists(typedefFile)) {
@@ -397,7 +406,7 @@ export class PgindentDocumentFormatterProvider implements vscode.DocumentFormatt
397406
return this.savedPgindentPath;
398407
}
399408

400-
const pgindentPath = utils.getWorkspacePgSrcFile(
409+
const pgindentPath = getWorkspacePgSrcFile(
401410
workspace, 'src', 'tools', 'pgindent', 'pgindent');
402411
if (!await utils.fileExists(pgindentPath)) {
403412
vscode.window.showErrorMessage(`could not find pgindent at ${pgindentPath.fsPath}`);
@@ -505,7 +514,7 @@ export class PgindentDocumentFormatterProvider implements vscode.DocumentFormatt
505514
const pgindent = await this.getPgindent(workspace);
506515
const pg_bsd_indent = await this.getPgBsdIndent(workspace, pgindent);
507516
const content = this.getDocumentContent(document);
508-
const tempDocument = await utils.createTempFile('pghh-{}.c', content);
517+
const tempDocument = await createTempFile('pghh-{}.c', content);
509518
try {
510519
return await this.runPgindentRebuildBsd(
511520
document.uri, tempDocument, pg_bsd_indent, pgindent, workspace);

src/utils.ts

Lines changed: 11 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,40 @@
11
import * as vscode from 'vscode';
22
import * as path from 'path';
3-
import * as https from 'https';
4-
import * as os from 'os';
5-
import * as crypto from 'crypto';
6-
import { VsCodeSettings } from './configuration';
73

84
export function joinPath(base: vscode.Uri, ...paths: string[]) {
95
return vscode.Uri.joinPath(base, ...paths);
106
}
117

12-
function statFile(uri: vscode.Uri): Thenable<vscode.FileStat> {
13-
return vscode.workspace.fs.stat(uri);
14-
}
15-
168
/**
179
* Check that file exists on given fs path
1810
*
1911
* @param path Path to test for file
20-
* @returns true if file exists, false if not
21-
* @throws Error if {@link path} points to existing fs entry, but not file
22-
* i.e. directory
12+
* @returns true if file exists, false if does not exist or it's not a file
2313
*/
2414
export async function fileExists(path: vscode.Uri): Promise<boolean> {
2515
try {
26-
const result = await statFile(path);
16+
const result = await vscode.workspace.fs.stat(path);
2717
return !!(result.type & vscode.FileType.File);
2818
} catch {
2919
return false;
3020
}
3121
}
3222

3323
/**
34-
* Check that at specified path exists some entry.
35-
* No matter what - file or directory. Just something
24+
* Check that directory exists on given fs path
25+
*
26+
* @returns true if directory exists, false if does not exist or it's not a directory
3627
*/
37-
export async function fsEntryExists(path: vscode.Uri): Promise<boolean> {
38-
try {
39-
await statFile(path);
40-
return true;
41-
} catch {
42-
return false;
43-
}
44-
}
45-
4628
export async function directoryExists(path: vscode.Uri) {
4729
try {
48-
const result = await statFile(path);
30+
const result = await vscode.workspace.fs.stat(path);
4931
return !!(result.type & vscode.FileType.Directory);
5032
} catch {
5133
return false;
5234
}
5335
}
5436

55-
export async function createDirectory(path: vscode.Uri): Promise<void> {
37+
export function createDirectory(path: vscode.Uri) {
5638
return vscode.workspace.fs.createDirectory(path);
5739
}
5840

@@ -61,19 +43,8 @@ export async function directoryEmpty(path: vscode.Uri) {
6143
return files.length === 0;
6244
}
6345

64-
export async function copyFile(file: vscode.Uri, targetFile: vscode.Uri) {
65-
await vscode.workspace.fs.copy(file, targetFile);
66-
}
67-
68-
export async function createTempFile(template: string, content: string) {
69-
const filename = template.replace('{}', crypto.randomUUID().toString());
70-
const tempFile = vscode.Uri.joinPath(vscode.Uri.file(os.tmpdir()), filename);
71-
await vscode.workspace.fs.writeFile(tempFile, new TextEncoder().encode(content));
72-
return tempFile;
73-
}
74-
75-
export async function deleteFile(file: vscode.Uri) {
76-
await vscode.workspace.fs.delete(file, { useTrash: false });
46+
export function deleteFile(file: vscode.Uri) {
47+
return vscode.workspace.fs.delete(file, { useTrash: false, recursive: false });
7748
}
7849

7950
export async function readFile(path: vscode.Uri) {
@@ -85,64 +56,6 @@ export function writeFile(path: vscode.Uri, data: string): Thenable<void> {
8556
return vscode.workspace.fs.writeFile(path, new TextEncoder().encode(data));
8657
}
8758

88-
export function getFileName(path: vscode.Uri) {
89-
const parts = path.fsPath.split('/');
90-
return parts[parts.length - 1];
91-
}
92-
93-
/**
94-
* Download file and return it's content.
95-
*
96-
* @param url Url of file to download
97-
* @returns Contents of file
98-
*/
99-
export async function downloadFile(url: string) {
100-
return new Promise<string>((resolve, reject) => {
101-
const request = https.get(url, (res) => {
102-
if (res.statusCode !== 200) {
103-
reject(new Error(`could not download file from ${url}: ` +
104-
`unsuccessful status code ${res.statusCode}`));
105-
res.resume();
106-
return;
107-
}
108-
109-
const chunks: string[] = [];
110-
111-
/* For now expect only utf8 content */
112-
res.setEncoding('utf8');
113-
res.on('data', (chunk) => {
114-
chunks.push(chunk);
115-
});
116-
117-
res.on('end', () => {
118-
resolve(chunks.join(''));
119-
});
120-
121-
res.on('error', (err) => {
122-
reject(err);
123-
});
124-
125-
});
126-
127-
request.on('error', (err) => {
128-
reject(err);
129-
});
130-
});
131-
}
132-
export function getWorkspacePgSrcFile(workspace: vscode.Uri, ...paths: string[]) {
133-
const customDir = VsCodeSettings.getSrcPath();
134-
if (customDir) {
135-
return joinPath(workspace, customDir, ...paths);
136-
}
137-
138-
return joinPath(workspace, ...paths);
139-
}
140-
141-
export function getPgSrcFile(...paths: string[]) {
142-
const customDir = VsCodeSettings.getSrcPath();
143-
if (customDir) {
144-
return path.join(customDir, ...paths);
145-
}
146-
147-
return path.join(...paths);
59+
export function getFileName(file: vscode.Uri) {
60+
return path.basename(file.fsPath);
14861
}

0 commit comments

Comments
 (0)