|
| 1 | +/* |
| 2 | + * This file is part of Cockpit. |
| 3 | + * |
| 4 | + * Copyright (C) 2025 Red Hat, Inc. |
| 5 | + * |
| 6 | + * This program is free software: you can redistribute it and/or modify |
| 7 | + * it under the terms of the GNU General Public License as published by |
| 8 | + * the Free Software Foundation, either version 3 of the License, or |
| 9 | + * (at your option) any later version. |
| 10 | + * |
| 11 | + * This program is distributed in the hope that it will be useful, |
| 12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | + * GNU General Public License for more details. |
| 15 | + * |
| 16 | + * You should have received a copy of the GNU General Public License |
| 17 | + * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 18 | + */ |
| 19 | + |
| 20 | +'use strict'; |
| 21 | + |
| 22 | +import { join_data } from 'cockpit/_internal/common.ts'; |
| 23 | +import { Channel, ChannelPayload, ChannelOptions, BaseChannelOptions } from 'cockpit/channel.ts'; |
| 24 | + |
| 25 | +interface PathOptions extends BaseChannelOptions { |
| 26 | + payload?: never; |
| 27 | +} |
| 28 | + |
| 29 | +interface ReadOptions { |
| 30 | + payload?: never; |
| 31 | + max_read_size?: number; |
| 32 | + path?: string, |
| 33 | +} |
| 34 | + |
| 35 | +export class Path { |
| 36 | + filename: string; |
| 37 | + #options: PathOptions; |
| 38 | + |
| 39 | + constructor(filename: string, options?: PathOptions) { |
| 40 | + this.filename = filename; |
| 41 | + this.#options = options || {}; |
| 42 | + } |
| 43 | + |
| 44 | + // eslint-disable-next-line max-len |
| 45 | + async read<P extends ChannelPayload = string>(options: ChannelOptions<P> & ReadOptions): Promise<{ tag: string, content: P }> { |
| 46 | + const data: P[] = []; |
| 47 | + // HACK: jelle is misunderstanding TypeScript here, obviously I can't |
| 48 | + // pass `path: this.filename` to `new Channel` as it is not a valid |
| 49 | + // option, but why does this hack work? |
| 50 | + const global_options = { ...this.#options, path: this.filename }; |
| 51 | + const channel = new Channel<P>({ ...global_options, ...options, payload: 'fsread1' }); |
| 52 | + |
| 53 | + channel.on('data', chunk => { |
| 54 | + data.push(chunk); |
| 55 | + }); |
| 56 | + |
| 57 | + await channel.wait(); |
| 58 | + |
| 59 | + return new Promise((resolve, reject) => { |
| 60 | + channel.on('close', message => { |
| 61 | + if (message.problem) { |
| 62 | + // TODO: BasicError |
| 63 | + reject(message.problem); |
| 64 | + } else { |
| 65 | + // StrOrBytes it not assignable to P |
| 66 | + resolve({ tag: message.tag as string, content: join_data(data, channel.binary) as P }); |
| 67 | + } |
| 68 | + }); |
| 69 | + }); |
| 70 | + } |
| 71 | +} |
0 commit comments