Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added recursive option to monitorFile #345

Merged
merged 2 commits into from
Mar 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions src/utils/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,24 +75,50 @@ const fileMonitors: Map<Gio.FileMonitor, boolean> = new Map;
export function monitorFile(
path: string,
callback?: (file: Gio.File, event: Gio.FileMonitorEvent) => void,
flags = Gio.FileMonitorFlags.NONE,
options: { flags: Gio.FileMonitorFlags; recursive: boolean } = {
flags: Gio.FileMonitorFlags.NONE,
recursive: true,
},
) {
// FIXME: remove the checking in the next release
// @ts-expect-error
if (flags === 'file' || flags === 'directory') {
throw Error(
`${flags}` + ' passed as a parameter in `monitorFile`. ' +
'Specifying the type is no longer required.',
if (typeof options === 'number') {
console.warn(
`${options}` +
' passed as a parameter in `options`.\n' +
'options parameter should be {flags: Gio.FileMonitorFlags, recursive: boolean}.',
);
}

try {
const file = Gio.File.new_for_path(path);
const mon = file.monitor(flags, null);
const mon = file.monitor(options.flags, null);

if (callback)
mon.connect('changed', (_, file, _f, event) => callback(file, event));

// If recursive is enabled enumerate files in the subfolders
const enumerator = file.enumerate_children('standard::*',
Gio.FileQueryInfoFlags.NONE, null);
while (options.recursive) {
try {
const fileInfo = enumerator.next_file(null);

if (!fileInfo)
break;

const fileType = fileInfo.get_file_type();
if (fileType === Gio.FileType.DIRECTORY) {
const subfolder = file.get_child(fileInfo.get_name());
const subfolderPath = subfolder.get_path();

if (subfolderPath !== null)
monitorFile(subfolderPath, callback, options);
}
} catch (error) {
logError(error);
}
}

// we need to save a reference in case the user doesn't
// otherwise GC will pick it up
fileMonitors.set(mon, true);
Expand Down