-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathindex.ts
215 lines (189 loc) · 6.02 KB
/
index.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/**
* @module @xmcl/system
*/
import { open, readEntry, readAllEntries } from '@xmcl/unzip'
import { access as saccess, stat as sstat, writeFile as swriteFile, readFile as sreadFile, readdir as sreaddir } from 'fs'
import { promisify } from 'util'
import { join, sep } from 'path'
import { FileSystem } from './system'
import { ZipFile, Entry } from 'yauzl'
const access = promisify(saccess)
const stat = promisify(sstat)
const writeFile = promisify(swriteFile)
const readFile = promisify(sreadFile)
const readdir = promisify(sreaddir)
export async function openFileSystem(basePath: string | Uint8Array): Promise<FileSystem> {
if (typeof basePath === 'string') {
const fstat = await stat(basePath)
if (fstat.isDirectory()) {
return new NodeFileSystem(basePath)
} else {
const zip = await open(basePath)
const entries = await readAllEntries(zip)
const entriesRecord: Record<string, Entry> = {}
for (const entry of entries) {
entriesRecord[entry.fileName] = entry
}
return new NodeZipFileSystem(basePath, zip, entriesRecord)
}
} else {
const zip = await open(basePath as Buffer)
const entries = await readAllEntries(zip)
const entriesRecord: Record<string, Entry> = {}
for (const entry of entries) {
entriesRecord[entry.fileName] = entry
}
return new NodeZipFileSystem('', zip, entriesRecord)
}
}
export function resolveFileSystem(base: string | Uint8Array | FileSystem): Promise<FileSystem> {
if (typeof base === 'string' || base instanceof Uint8Array || base instanceof Buffer) {
return openFileSystem(base)
} else {
return Promise.resolve(base)
}
}
class NodeFileSystem extends FileSystem {
sep = sep
type = 'path' as const
writeable = true
join(...paths: string[]): string {
return join(...paths)
}
getUrl(name: string) {
return `file://${this.join(this.root, name)}`
}
isDirectory(name: string): Promise<boolean> {
return stat(join(this.root, name)).then((s) => s.isDirectory())
}
writeFile(name: string, data: Uint8Array): Promise<void> {
return writeFile(join(this.root, name), data)
}
existsFile(name: string): Promise<boolean> {
return access(join(this.root, name)).then(() => true, () => false)
}
readFile(name: any, encoding?: any) {
return readFile(join(this.root, name), { encoding }) as any
}
listFiles(name: string): Promise<string[]> {
return readdir(join(this.root, name))
}
cd(name: string): void {
this.root = join(this.root, name)
}
constructor(public root: string) { super() }
}
class NodeZipFileSystem extends FileSystem {
sep = '/'
type = 'zip' as const
writeable = false
private zipRoot = ''
private fileRoot: string
constructor(root: string, private zip: ZipFile, private entries: Record<string, Entry>) {
super()
this.fileRoot = root
}
isClosed(): boolean {
return !this.zip.isOpen
}
close(): void {
this.zip.close()
}
get root() { return this.fileRoot + (this.zipRoot.length === 0 ? '' : `/${this.zipRoot}`) }
protected normalizePath(name: string): string {
if (name.startsWith('/')) {
name = name.substring(1)
}
if (this.zipRoot !== '') {
name = [this.zipRoot, name].join('/')
}
return name
}
join(...paths: string[]): string {
return paths.join('/')
}
isDirectory(name: string): Promise<boolean> {
name = this.normalizePath(name)
if (name === '') {
return Promise.resolve(true)
}
if (this.entries[name]) {
return Promise.resolve(name.endsWith('/'))
}
if (this.entries[name + '/']) {
return Promise.resolve(true)
}
// the root dir won't have entries
// therefore we need to do an extra track here
const entries = Object.keys(this.entries)
return Promise.resolve(entries.some((e) => e.startsWith(name + '/')))
}
existsFile(name: string): Promise<boolean> {
name = this.normalizePath(name)
if (this.entries[name] ||
this.entries[name + '/']) { return Promise.resolve(true) }
// the root dir won't have entries
// therefore we need to do an extra track here
const entries = Object.keys(this.entries)
return Promise.resolve(entries.some((e) => e.startsWith(name + '/')))
}
async readFile(name: string, encoding?: 'utf-8' | 'base64'): Promise<any> {
name = this.normalizePath(name)
const entry = this.entries[name]
if (!entry) { throw new Error(`Not found file named ${name}`) }
const buffer = await readEntry(this.zip, entry)
if (encoding === 'utf-8') {
return buffer.toString('utf-8')
}
if (encoding === 'base64') {
return buffer.toString('base64')
}
return buffer
}
listFiles(name: string): Promise<string[]> {
name = this.normalizePath(name)
return Promise.resolve([
...new Set(Object.keys(this.entries)
.filter((n) => n.startsWith(name))
.map((n) => n.substring(name.length))
.map((n) => n.startsWith('/') ? n.substring(1) : n)
.map((n) => n.split('/')[0])),
])
}
cd(name: string): void {
if (name.startsWith('/')) {
this.zipRoot = name.substring(1)
return
}
const paths = name.split('/')
for (const path of paths) {
if (path === '.') {
continue
} else if (path === '..') {
const sub = this.zipRoot.split('/')
if (sub.length > 0) {
sub.pop()
this.zipRoot = sub.join('/')
}
} else {
if (this.zipRoot === '') {
this.zipRoot = path
} else {
this.zipRoot += `/${path}`
}
}
}
}
async walkFiles(startingDir: string, walker: (path: string) => void | Promise<void>) {
startingDir = this.normalizePath(startingDir)
const root = startingDir.startsWith('/') ? startingDir.substring(1) : startingDir
for (const child of Object.keys(this.entries).filter((e) => e.startsWith(root))) {
if (child.endsWith('/')) { continue }
const result = walker(child)
if (result instanceof Promise) {
await result
}
}
}
}
export * from './system'