|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google Inc. All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | +import { Observable } from 'rxjs'; |
| 9 | +import { Path, PathFragment } from '../path'; |
| 10 | +import { FileBuffer, FileBufferLike, Host, HostCapabilities, Stats } from './interface'; |
| 11 | + |
| 12 | +export interface SyncHostHandler<StatsT extends object = {}> { |
| 13 | + read(path: Path): FileBuffer; |
| 14 | + list(path: Path): PathFragment[]; |
| 15 | + |
| 16 | + exists(path: Path): boolean; |
| 17 | + isDirectory(path: Path): boolean; |
| 18 | + isFile(path: Path): boolean; |
| 19 | + |
| 20 | + stat(path: Path): Stats<StatsT> | null; |
| 21 | + |
| 22 | + write(path: Path, content: FileBufferLike): void; |
| 23 | + delete(path: Path): void; |
| 24 | + rename(from: Path, to: Path): void; |
| 25 | +} |
| 26 | + |
| 27 | +function wrapAction<T>(action: () => T): Observable<T> { |
| 28 | + return new Observable((subscriber) => { |
| 29 | + subscriber.next(action()); |
| 30 | + subscriber.complete(); |
| 31 | + }); |
| 32 | +} |
| 33 | + |
| 34 | +export function createSyncHost<StatsT extends object = {}>( |
| 35 | + handler: SyncHostHandler<StatsT>, |
| 36 | +): Host<StatsT> { |
| 37 | + return new (class { |
| 38 | + get capabilities(): HostCapabilities { |
| 39 | + return { synchronous: true }; |
| 40 | + } |
| 41 | + |
| 42 | + read(path: Path): Observable<FileBuffer> { |
| 43 | + return wrapAction(() => handler.read(path)); |
| 44 | + } |
| 45 | + |
| 46 | + list(path: Path): Observable<PathFragment[]> { |
| 47 | + return wrapAction(() => handler.list(path)); |
| 48 | + } |
| 49 | + |
| 50 | + exists(path: Path): Observable<boolean> { |
| 51 | + return wrapAction(() => handler.exists(path)); |
| 52 | + } |
| 53 | + |
| 54 | + isDirectory(path: Path): Observable<boolean> { |
| 55 | + return wrapAction(() => handler.isDirectory(path)); |
| 56 | + } |
| 57 | + |
| 58 | + isFile(path: Path): Observable<boolean> { |
| 59 | + return wrapAction(() => handler.isFile(path)); |
| 60 | + } |
| 61 | + |
| 62 | + stat(path: Path): Observable<Stats<StatsT> | null> { |
| 63 | + return wrapAction(() => handler.stat(path)); |
| 64 | + } |
| 65 | + |
| 66 | + write(path: Path, content: FileBufferLike): Observable<void> { |
| 67 | + return wrapAction(() => handler.write(path, content)); |
| 68 | + } |
| 69 | + |
| 70 | + delete(path: Path): Observable<void> { |
| 71 | + return wrapAction(() => handler.delete(path)); |
| 72 | + } |
| 73 | + |
| 74 | + rename(from: Path, to: Path): Observable<void> { |
| 75 | + return wrapAction(() => handler.rename(from, to)); |
| 76 | + } |
| 77 | + |
| 78 | + watch(): null { |
| 79 | + return null; |
| 80 | + } |
| 81 | + })(); |
| 82 | +} |
0 commit comments