-
-
Notifications
You must be signed in to change notification settings - Fork 440
/
Copy pathsketches-service-impl.ts
82 lines (76 loc) · 3.33 KB
/
sketches-service-impl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { injectable, inject } from "inversify";
import { SketchesService, Sketch } from "../common/protocol/sketches-service";
import URI from "@theia/core/lib/common/uri";
import { FileStat, FileSystem } from "@theia/filesystem/lib/common";
import * as fs from 'fs';
import * as path from 'path';
import { FileUri } from "@theia/core/lib/node";
export const ALLOWED_FILE_EXTENSIONS = [".c", ".cpp", ".h", ".hh", ".hpp", ".s", ".pde", ".ino"];
@injectable()
export class SketchesServiceImpl implements SketchesService {
@inject(FileSystem)
protected readonly filesystem: FileSystem;
async getSketches(fileStat?: FileStat): Promise<Sketch[]> {
const sketches: Sketch[] = [];
if (fileStat && fileStat.isDirectory) {
const uri = new URI(fileStat.uri);
const sketchFolderPath = await this.filesystem.getFsPath(uri.toString());
if (sketchFolderPath) {
const fileNames = fs.readdirSync(sketchFolderPath);
for (const fileName of fileNames) {
const filePath = path.join(sketchFolderPath, fileName);
if (this.isSketchFolder(filePath, fileName)) {
sketches.push({
name: fileName,
uri: FileUri.create(filePath).toString()
});
}
}
}
}
return sketches;
}
/**
* Return all allowed files.
* File extensions: "c", "cpp", "h", "hh", "hpp", "s", "pde", "ino"
*/
async getSketchFiles(sketchFileStat: FileStat): Promise<string[]> {
const uris: string[] = [];
const sketchUri = new URI(sketchFileStat.uri);
const sketchPath = await this.filesystem.getFsPath(sketchUri.toString());
if (sketchPath) {
if (sketchFileStat.isDirectory && this.isSketchFolder(sketchPath, sketchUri.displayName)) {
const fileNames = fs.readdirSync(sketchPath);
for (const fileName of fileNames) {
const filePath = path.join(sketchPath, fileName);
if (ALLOWED_FILE_EXTENSIONS.indexOf(path.extname(filePath)) !== -1
&& fs.existsSync(filePath)
&& fs.lstatSync(filePath).isFile()) {
uris.push(FileUri.create(filePath).toString())
}
}
} else {
const sketchDir = path.dirname(sketchPath);
if (sketchDir && this.isSketchFolder(sketchDir, sketchUri.path.dir.name)) {
const sketchFolderStat = await this.filesystem.getFileStat(sketchUri.path.dir.toString());
if (sketchFolderStat) {
const sketchDirContents = await this.getSketchFiles(sketchFolderStat);
uris.push(...sketchDirContents);
}
}
}
}
return uris;
}
protected isSketchFolder(path: string, name: string): boolean {
if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) {
const files = fs.readdirSync(path);
for (let i = 0; i < files.length; i++) {
if (files[i] === name + '.ino') {
return true;
}
}
}
return false;
}
}