Skip to content

Commit

Permalink
Lints and formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
vidartf committed Nov 8, 2023
1 parent 1df3ea1 commit a2c17ee
Show file tree
Hide file tree
Showing 11 changed files with 90 additions and 100 deletions.
2 changes: 1 addition & 1 deletion js/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ export function createStaticCommands(
path,
});
} catch (e) {
void showErrorMessage("Could not create file", e);
void showErrorMessage("Could not create file", e as string);
return;
}
target.invalidate();
Expand Down
48 changes: 5 additions & 43 deletions js/src/drag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ import {
} from "@lumino/coreutils";

import {
Drag
Drag,
} from "@lumino/dragdrop";


Expand Down Expand Up @@ -133,11 +133,11 @@ export
function findChild(parent: HTMLElement | HTMLElement[], node: HTMLElement): HTMLElement | null {
// Work our way up the DOM to an element which has this node as parent
const parentIsArray = Array.isArray(parent);
const isDirectChild = (child: HTMLElement): boolean => {
const isDirectChild = (element: HTMLElement): boolean => {
if (parentIsArray) {
return (parent as HTMLElement[]).indexOf(child) > -1;
return parent.indexOf(element) > -1;
} else {
return child.parentElement === parent;
return element.parentElement === parent;
}
};
let candidate: HTMLElement | null = node;
Expand Down Expand Up @@ -517,7 +517,7 @@ abstract class DragDropWidgetBase extends DropWidget {
this.addMimeData(handle, this.drag.mimeData);

// Start the drag and remove the mousemove listener.
void this.drag.start(clientX, clientY).then(this.onDragComplete.bind(this));
void this.drag.start(clientX, clientY).then(action => this.onDragComplete(action));
document.removeEventListener("mousemove", this, true);
document.removeEventListener("mouseup", this, true);
}
Expand Down Expand Up @@ -872,41 +872,3 @@ namespace DragDropWidget {
interface IOptions extends DragWidget.IOptions, DropWidget.IOptions {
}
}


export
abstract class FriendlyDragDrop extends DragDropWidget {
private static _counter = 0;
private static _groups: {[key: number]: FriendlyDragDrop[]} = {};

static makeGroup() {
const id = this._counter++;
FriendlyDragDrop._groups[id] = [];
return id;
}

setFriendlyGroup(id: number) {
this._groupId = id;
FriendlyDragDrop._groups[id].push(this);
}

addToFriendlyGroup(other: FriendlyDragDrop) {
other.setFriendlyGroup(this._groupId);
}

get friends(): FriendlyDragDrop[] {
if (this._groupId === undefined) {
throw new Error("Uninitialized drag-drop group");
}
return FriendlyDragDrop._groups[this._groupId];
}

private _groupId: number;

protected validateSource(event: Drag.Event) {
if (this.acceptDropsFromExternalSource) {
return this.friends.indexOf(event.source) !== -1;
}
return super.validateSource(event);
}
}
4 changes: 2 additions & 2 deletions js/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ export async function migrateSettings(settings: ISettingRegistry.ISettings): Pro

/**
* Ensure undefined string values from settings that are required are translated to empty strings
* @param settingsResoruce
* @param settingsResoruce
* @returns A filled in setting object
*/
export function unpartialResource(settingsResource: IFSSettingsResource): IFSResource {
return {name: "", url: "", ...settingsResource};
return { name: "", url: "", ...settingsResource };
}
16 changes: 8 additions & 8 deletions js/tests/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { IFSSettingsResource } from "../src/filesystem";

describe("unpartialResource", () => {

it("should replace non-existing fields with empty string", () => {
it("should replace non-existing fields with empty string", () => {

// blank resource missing name and url (like after pressing "add")
let resource: IFSSettingsResource = {auth: "ask", defaultWritable: true};
let unpartialed = unpartialResource(resource);
// blank resource missing name and url (like after pressing "add")
const resource: IFSSettingsResource = { auth: "ask", defaultWritable: true };
const unpartialed = unpartialResource(resource);

expect(unpartialed.name).toEqual("")
expect(unpartialed.url).toEqual("")
})
})
expect(unpartialed.name).toEqual("");
expect(unpartialed.url).toEqual("");
});
});
1 change: 1 addition & 0 deletions jupyterfs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def open_fs(fs_url, **kwargs):
"""Wrapper around fs.open_fs with {{variable}} substitution"""
import fs
from .auth import stdin_prompt

# substitute credential variables via `getpass` queries
fs_url = stdin_prompt(fs_url)
return fs.open_fs(fs_url, **kwargs)
Expand Down
22 changes: 12 additions & 10 deletions jupyterfs/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,28 +42,30 @@ class DoubleBraceTemplate(_BaseTemplate):
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
# 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
# All Rights Reserved

def get_identifiers(self):
ids = []
for mo in self.pattern.finditer(self.template):
named = mo.group('named') or mo.group('braced')
named = mo.group("named") or mo.group("braced")
if named is not None and named not in ids:
# add a named group only the first time it appears
ids.append(named)
elif (named is None
and mo.group('invalid') is None
and mo.group('escaped') is None):
elif (
named is None
and mo.group("invalid") is None
and mo.group("escaped") is None
):
# If all the groups are None, there must be
# another group we're not expecting
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return ids

raise ValueError("Unrecognized named group in pattern", self.pattern)
return ids

setattr(DoubleBraceTemplate, "get_identifiers", get_identifiers)


def stdin_prompt(url):
from getpass import getpass

template = DoubleBraceTemplate(url)
subs = {}
for ident in template.get_identifiers():
Expand All @@ -74,7 +76,7 @@ def stdin_prompt(url):
def substituteAsk(resource):
if "tokenDict" in resource:
url = DoubleBraceTemplate(resource["url"]).safe_substitute(
{ k: urllib.parse.quote(v) for k, v in resource.pop("tokenDict").items() }
{k: urllib.parse.quote(v) for k, v in resource.pop("tokenDict").items()}
)
else:
url = resource["url"]
Expand Down
23 changes: 15 additions & 8 deletions jupyterfs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,25 @@ class JupyterFs(Configurable):
surface_init_errors = Bool(
default_value=False,
config=True,
help=_i18n("whether to surface init errors to the client")
help=_i18n("whether to surface init errors to the client"),
)

snippets = List(
config=True,
per_key_traits=Dict({
"label": Unicode(help="The designator to show to users"),
"caption": Unicode("", help="An optional, longer description to show to users"),
"pattern": Unicode("", help="A regular expression to match against the full URL of the entry, indicating if this snippet is valid for it"),
"template": Unicode(help="A template string to build up the snippet"),
}),
per_key_traits=Dict(
{
"label": Unicode(help="The designator to show to users"),
"caption": Unicode(
"", help="An optional, longer description to show to users"
),
"pattern": Unicode(
"",
help="A regular expression to match against the full URL of the entry, indicating if this snippet is valid for it",
),
"template": Unicode(help="A template string to build up the snippet"),
}
),
help=_i18n(
"per entry snippets for how to use it, e.g. a snippet for how to open a file from a given resource"
),
)
)
5 changes: 3 additions & 2 deletions jupyterfs/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ def _load_jupyter_server_extension(serverapp):
% url_path_join(base_url, resources_url)
)
web_app.add_handlers(
host_pattern, [
host_pattern,
[
(url_path_join(base_url, resources_url), MetaManagerHandler),
(url_path_join(base_url, "jupyterfs/snippets"), SnippetsHandler),
]
],
)
46 changes: 31 additions & 15 deletions jupyterfs/fsmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,9 @@ def _is_path_hidden(self, path, info):
import os

syspath = self._pyfilesystem_instance.getsyspath(path)
if os.path.exists(syspath) and not os.access(syspath, os.X_OK | os.R_OK):
if os.path.exists(syspath) and not os.access(
syspath, os.X_OK | os.R_OK
):
return True

except ResourceNotFound:
Expand Down Expand Up @@ -237,7 +239,7 @@ def exists(self, path):
def _base_model(self, path, info):
"""
Build the common base of a contents model
info (<Info>): FS Info object for file/dir at path -- used for values and reduces needed network calls
"""
try:
Expand Down Expand Up @@ -290,7 +292,6 @@ def _base_model(self, path, info):
except AttributeError:
model["writable"] = False
return model


def _dir_model(self, path, info, content=True):
"""Build a model for a directory
Expand All @@ -301,24 +302,31 @@ def _dir_model(self, path, info, content=True):

if not info.is_dir:
raise web.HTTPError(404, four_o_four)

elif not self.allow_hidden and self.is_hidden(path, info):
self.log.debug("Refusing to serve hidden directory %r, via 404 Error", path)
raise web.HTTPError(404, four_o_four)


model = self._base_model(path, info)
model["type"] = "directory"
model["size"] = None
if content:
model["content"] = contents = []

for dir_entry in self._pyfilesystem_instance.scandir(path, namespaces=("basic", "access", "details", "stat")):
for dir_entry in self._pyfilesystem_instance.scandir(
path, namespaces=("basic", "access", "details", "stat")
):
try:
if self.should_list(dir_entry.name):
if self.allow_hidden or not self._is_path_hidden(dir_entry.make_path(path), dir_entry):
if self.allow_hidden or not self._is_path_hidden(
dir_entry.make_path(path), dir_entry
):
contents.append(
self.get(path="%s/%s" % (path, dir_entry.name), content=False, info=dir_entry)
self.get(
path="%s/%s" % (path, dir_entry.name),
content=False,
info=dir_entry,
)
)
except PermissionDenied:
pass # Don't provide clues about protected files
Expand All @@ -327,7 +335,9 @@ def _dir_model(self, path, info, content=True):
# us from listing other entries
pass
except Exception as e:
self.log.warning("Error stat-ing %s: %s", dir_entry.make_path(path), e)
self.log.warning(
"Error stat-ing %s: %s", dir_entry.make_path(path), e
)

model["format"] = "json"
return model
Expand Down Expand Up @@ -374,7 +384,7 @@ def _file_model(self, path, info, content=True, format=None):
If 'text', the contents will be decoded as UTF-8.
If 'base64', the raw bytes contents will be encoded as base64.
If not specified, try to decode as UTF-8, and fall back to base64
info (<Info>): FS Info object for file at path
"""
model = self._base_model(path, info)
Expand Down Expand Up @@ -418,9 +428,13 @@ def get(self, path, content=True, type=None, format=None, info=None):
Args:
path (str): the API path that describes the relative path for the target
content (bool): Whether to include the contents in the reply
type (str): The requested type - 'file', 'notebook', or 'directory'. Will raise HTTPError 400 if the content doesn't match.
format (str): The requested format for file contents. 'text' or 'base64'. Ignored if this returns a notebook or directory model.
info (fs Info object): Optional FS Info. If present, it needs to include the following namespaces: "basic", "stat", "access", "details". Including it can avoid extraneous networkcalls.
type (str): The requested type - 'file', 'notebook', or 'directory'.
Will raise HTTPError 400 if the content doesn't match.
format (str):
The requested format for file contents. 'text' or 'base64'. Ignored if this returns a notebook or directory model.
info (fs Info object):
Optional FS Info. If present, it needs to include the following namespaces: "basic", "stat", "access", "details".
Including it can avoid extraneous networkcalls.
Returns
model (dict): the contents model. If content=True, returns the contents of the file or directory as well.
"""
Expand All @@ -429,8 +443,10 @@ def get(self, path, content=True, type=None, format=None, info=None):
# gather info - by doing here can minimise further network requests from underlying fs functions
if not info:
try:
info = self._pyfilesystem_instance.getinfo(path, namespaces=("basic", "stat", "access", "details"))
except:
info = self._pyfilesystem_instance.getinfo(
path, namespaces=("basic", "stat", "access", "details")
)
except Exception:
raise web.HTTPError(404, "No such file or directory: %s" % path)

if info.is_dir:
Expand Down
5 changes: 2 additions & 3 deletions jupyterfs/snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from .config import JupyterFs as JupyterFsConfig


class SnippetsHandler(APIHandler):
_jupyterfsConfig = None

Expand All @@ -25,6 +26,4 @@ def fsconfig(self):
@web.authenticated
def get(self):
"""Get the server-side configured snippets"""
self.write({
"snippets": self.fsconfig.snippets
})
self.write({"snippets": self.fsconfig.snippets})
Loading

0 comments on commit a2c17ee

Please sign in to comment.