Skip to content
Merged
Show file tree
Hide file tree
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
57 changes: 52 additions & 5 deletions app/nullius/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ class Workspace:
def imports_dir(self) -> str:
return os.path.join(self.dir, "imported")

@property
def kept(self) -> list:
"""Its job roots in its own ``imported/``: conversions kept from before."""
return [r for r in self.job_roots if _inside(r, self.imports_dir)]

@property
def walked(self) -> list:
"""The folders its jobs are read from (``walked``)."""
return walked(self)

@property
def jobs_dir(self) -> str:
return os.path.join(self.dir, "jobs")
Expand All @@ -123,6 +133,17 @@ def n_cached(self) -> int:
return 0


def _inside(path: str, folder: str) -> bool:
"""*path* is *folder* or in it, both made absolute."""
folder = os.path.abspath(folder)
return os.path.commonpath([os.path.abspath(path), folder]) == folder


def in_imports(ws: Workspace, path: str) -> bool:
"""*path* is in *ws*'s own ``imported/``: a conversion kept from before, never deleted from disk alone."""
return _inside(path, ws.imports_dir)


def _path(home_dir: str, name: str) -> str:
return os.path.join(home_dir, name, "workspace.json")

Expand Down Expand Up @@ -314,8 +335,7 @@ def every(home_dir: str) -> list:
def walked(ws: Workspace) -> list:
"""The folders *ws*'s jobs are read from, open or closed: its roots, then the job roots
it kept in its own ``imported/``, converted before."""
kept = [r for r in ws.job_roots if os.path.commonpath([os.path.abspath(r), ws.imports_dir]) == ws.imports_dir]
return list(dict.fromkeys([*ws.roots, *kept]))
return list(dict.fromkeys([*ws.roots, *ws.kept]))


def last_open(home_dir: str) -> Workspace | None:
Expand Down Expand Up @@ -373,11 +393,13 @@ def rename(home_dir: str, ws: Workspace, label: str) -> Workspace:
with everything in it - parsed jobs, imports, judgements - so a
workspace never carries one name on the page and another on disk. A
label with nothing to slug keeps the name it has. The roots it reads
stay where they are."""
stay where they are; those in its ``imported/`` are named where they
moved, then their parses dropped: a failure there leaves the rename made,
the next Refresh clears them."""
label = (label or "").strip()
if not label or not os.path.isdir(ws.dir):
return ws
name = slug(label)
name, moved = slug(label), {}
with _locked(ws): # the lock moves with the folder
now = _still(ws, load(home_dir, ws.name))
if now is None:
Expand All @@ -387,16 +409,41 @@ def rename(home_dir: str, ws: Workspace, label: str) -> Workspace:
taken = {w.name for w in list_all(home_dir)} | set(os.listdir(home_dir))
name = _free(name, taken - {ws.name})
new_dir = os.path.join(home_dir, name)
old_dir, old_imports = now.dir, os.path.abspath(now.imports_dir)
os.rename(ws.dir, new_dir)
from nullius.judge import store
store.unmark(ws.dir, to=new_dir)
now.name, now.dir = name, new_dir

def there(r):
return os.path.join(os.path.abspath(now.imports_dir), os.path.relpath(os.path.abspath(r), old_imports)) if _inside(r, old_imports) else r
moved = {there(r): r for r in [*now.roots, *now.job_roots] if _inside(r, old_imports)}
now.roots, now.job_roots = [there(r) for r in now.roots], [there(r) for r in now.job_roots]
with _DECODED_LOCK: # parses held under the old folder are read nowhere now
for path in [p for p in _DECODED if _inside(p, old_dir)]:
del _DECODED[path]
now.label = label
save(now)
ws.name, ws.dir, ws.label, ws.roots = now.name, now.dir, now.label, now.roots
if moved: # under the lock: a rename after this one moves none of them
try:
_drop_moved(now, moved)
except OSError:
pass
ws.name, ws.dir, ws.label, ws.roots, ws.job_roots = now.name, now.dir, now.label, now.roots, now.job_roots
return ws


def _drop_moved(ws: Workspace, moved: dict) -> None:
"""The parses of the job folders under *moved*'s folders (new path: old path), kept by
their old path, dropped: in the index or not, as a load that began before wrote them."""
old = [os.path.join(was, os.path.relpath(d, now)) for now, was in moved.items() for d in parse.find_job_dirs([now])]

def drop(index):
for d in {*old, *(d for d in index if _under(d, moved.values()))}:
_drop(ws, index, d)
_update_index(ws, drop)


def touch(ws: Workspace) -> None:
"""*ws* opened now: its state alone is written, its record is left as it is."""
_set_state(ws, opened=_now(), closed=False)
Expand Down
2 changes: 1 addition & 1 deletion app/nullius/workspace_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def _list(args) -> int:
opened = (ws.opened or "")[:16].replace("T", " ")
print(f"{ws.name:<{width}} {ws.label}")
print(f"{'':<{width}} cached runs {r['n_cached']} · opened {opened or '—'}")
for root in ws.roots:
for root in workspace.walked(ws):
print(f"{'':<{width}} root {root}")
for job in r["jobs"]:
print(f"{'':<{width}} job {job['job_id']} ({job['n_trials']} trial(s))")
Expand Down
2 changes: 1 addition & 1 deletion app/templates/runs/start.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ <h2 id="start-ws-title">Or open a workspace</h2>
<li><form method="post" action="{{ url_for('workspace_open', name=ws.name) }}"><input type="hidden" name="csrf" value="{{ csrf_token() }}">
<button class="start-ws-row" type="submit">
<span class="ws-avatar" style="--hue:{{ ws_hue(ws.name) }}">{{ ws.label[:2]|upper }}</span>
<span class="start-ws-text"><span>{{ ws.label }}</span><small>{{ ws.n_cached }} run{{ '' if ws.n_cached == 1 else 's' }} · {{ ws.roots|length }} folder{{ '' if ws.roots|length == 1 else 's' }}{% if ws.opened %} · opened {{ ws.opened[:10] }}{% endif %}</small></span>
<span class="start-ws-text"><span>{{ ws.label }}</span><small>{{ ws.n_cached }} run{{ '' if ws.n_cached == 1 else 's' }} · {% set n = ws.walked|length %}{{ n }} folder{{ '' if n == 1 else 's' }}{% if ws.opened %} · opened {{ ws.opened[:10] }}{% endif %}</small></span>
<span class="start-go">Open <svg class="ic" aria-hidden="true"><use href="#i-chevron-right"/></svg></span>
</button>
</form></li>
Expand Down
6 changes: 3 additions & 3 deletions app/templates/workspaces/workspaces.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
workspace records it; never opened sorts last, newest first). #}
{% macro launches(ws) %}{% set n = n_launches[ws.name] %}{% if n %}<a class="btn ghost sm count-btn" href="{{ url_for('launches_page', ws=ws.name) }}" aria-label="Launches of {{ ws.label }}: {{ n }}" title="Launches of {{ ws.label }}"><svg class="ic" aria-hidden="true"><use href="#i-launches"/></svg>{{ n }}</a>
{%- else %}{{ greyed('Launches of ' ~ ws.label ~ ': 0', '', 'No launches in ' ~ ws.label, 'none-' ~ ws.name, icon='launches', class='btn ghost sm count-btn', text='0') }}{% endif %}{% endmacro %}
{% macro roots(ws) %}<button type="button" class="btn ghost sm count-btn ws-roots-btn" data-ask="{{ url_for('workspace_roots', name=ws.name) }}" aria-haspopup="dialog" aria-label="Roots of {{ ws.label }}: {{ ws.roots|length }}" title="Roots"><svg class="ic" aria-hidden="true"><use href="#i-folder"/></svg>{{ ws.roots|length }}</button>{% endmacro %}
{% macro roots(ws) %}{% set n = ws.walked|length %}<button type="button" class="btn ghost sm count-btn ws-roots-btn" data-ask="{{ url_for('workspace_roots', name=ws.name) }}" aria-haspopup="dialog" aria-label="Roots of {{ ws.label }}: {{ n }}" title="Roots"><svg class="ic" aria-hidden="true"><use href="#i-folder"/></svg>{{ n }}</button>{% endmacro %}
{#- A workspace's rename: the pencil, and the form it swaps in for the name (the page's script); `view` the one to return to. #}
{% macro pencil(ws) %}<button type="button" class="icon-btn ws-edit" aria-label="Rename workspace {{ ws.label }}" title="Rename"><svg class="ic"><use href="#i-pencil"/></svg></button>{% endmacro %}
{% macro rename(ws, view=none) %}<form method="post" action="{{ url_for('workspace_rename') }}" class="ws-rename" hidden>
Expand Down Expand Up @@ -43,7 +43,7 @@
{%- set open %}{% if current %}<span class="ok" role="img" aria-label="Open" title="Open">●</span>{% endif %}{% endset %}
{%- set _ = items.append(dict(open=open, name=dict(text=ws.label, class='ws-name', after=pencil(ws) ~ rename(ws, 'cards')), disk=ws.name if labels.count(ws.label) > 1 else '', runs=counts[ws.name].runs, checks=counts[ws.name].checks,
opened=dict(text=ws.opened[:16]|replace('T', ' '), value=opened(ws)), launches=dict(text=launches(ws), value=n_launches[ws.name]),
roots=dict(text=roots(ws), value=ws.roots|length),
roots=dict(text=roots(ws), value=ws.walked|length),
actions=dict(title='Delete workspace', attrs={'data-ask': 'ws-ask-delete', 'data-label': ws.label, 'data-action': url_for('workspace_delete', name=ws.name), 'aria-haspopup': 'dialog', 'aria-label': 'Delete workspace ' ~ ws.label}),
search=ws.label ~ ' ' ~ ws.name)) %}
{%- endfor %}
Expand All @@ -63,7 +63,7 @@
{%- elif c.key == 'checks' %}{% call cell(c) %}{{ counts[ws.name].checks }}{% endcall %}
{%- elif c.key == 'opened' %}{% call cell(c, sort=opened(ws), class='mono faint nowrap') %}{{ ws.opened[:16]|replace('T', ' ') }}{% endcall %}
{%- elif c.key == 'launches' %}{% call cell(c) %}{{ launches(ws) }}{% endcall %}
{%- elif c.key == 'roots' %}{% call cell(c, sort=ws.roots|length) %}{{ roots(ws) }}{% endcall %}
{%- elif c.key == 'roots' %}{% call cell(c, sort=ws.walked|length) %}{{ roots(ws) }}{% endcall %}
{%- elif c.key == 'actions' %}{% call cell(c, class='acts-col') %}
<button type="button" class="icon-btn danger" data-ask="ws-ask-delete" data-label="{{ ws.label }}" data-action="{{ url_for('workspace_delete', name=ws.name) }}" aria-haspopup="dialog" aria-label="Delete workspace {{ ws.label }}" title="Delete workspace">{{ trash }}</button>
{% endcall %}
Expand Down
4 changes: 3 additions & 1 deletion app/tests/field_contract.json
Original file line number Diff line number Diff line change
Expand Up @@ -645,12 +645,14 @@
"imports_dir",
"job_roots",
"jobs_dir",
"kept",
"label",
"n_cached",
"name",
"opened",
"roots",
"uid"
"uid",
"walked"
]
}
}
3 changes: 3 additions & 0 deletions app/tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,9 @@ def test_the_home_is_workspaces_dir_when_not_named(self):
out = self.sh("workspace_cli", "list", env={"WORKSPACES_DIR": home})
self.assertEqual(out.returncode, 0, out.stderr)
self.assertIn(ws.name, out.stdout)
kept = os.path.join(ws.imports_dir, "kept"); os.makedirs(kept)
ws.job_roots = [kept]; workspace.save(ws) # a conversion kept from before: listed with the roots
self.assertIn(f"root {kept}", self.sh("workspace_cli", "list", env={"WORKSPACES_DIR": home}).stdout)
# The per-user location is independent of cwd; use an empty profile.
profile = os.path.join(self.tmp, "empty-profile")
out = self.sh("workspace_cli", "list", env={"WORKSPACES_DIR": "", "NULLIUS_HOME": profile})
Expand Down
56 changes: 56 additions & 0 deletions app/tests/test_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,62 @@ def forget_meanwhile(ws, job_dir, *rest): # the other re
workspace.load_jobs(self.ws, [self.root, other, *made])
self.assertEqual(sorted(workspace.job_index(self.ws)), sorted([self.job_dir, late, made[0]]))

def test_a_rename_names_its_kept_conversions_where_they_moved(self):
"""A conversion kept in its own ``imported/`` moves with the folder and is read there; an
external root keeps its path; the parse of the old path goes."""
kept, late = _job_dir(self.ws.imports_dir, "kept"), _job_dir(self.ws.imports_dir, "late")
self.ws.roots, self.ws.job_roots = [self.root, kept], [self.root, kept, late]; workspace.save(self.ws)
workspace.load_jobs(self.ws, [self.root, kept])
workspace.load_job(self.ws, late, {}) # parsed by a load the rename overtook: not in the index
self.assertEqual(len(workspace.walked(self.ws)), 3) # a folder held twice is one
old = self.ws.dir
workspace.rename(self.home, self.ws, "moved")
moved = [os.path.join(self.home, "moved", "imported", n) for n in ("kept", "late")]
self.assertEqual((workspace.load(self.home, "moved").roots, workspace.load(self.home, "moved").job_roots),
([self.root, moved[0]], [self.root, *moved]))
self.assertEqual((self.ws.job_roots, workspace.walked(self.ws)), ([self.root, *moved], [self.root, *moved]))
self.assertEqual(sorted(workspace.job_index(self.ws)), [self.job_dir])
self.assertEqual(self.ws.n_cached, 1)
self.assertFalse([p for p in workspace._DECODED if p.startswith(old + os.sep)])

def test_a_rename_is_made_whole_when_its_parses_cannot_be_dropped(self):
kept = _job_dir(self.ws.imports_dir, "kept")
self.ws.job_roots = [kept]; workspace.save(self.ws)
with patch.object(workspace, "_update_index", side_effect=PermissionError):
workspace.rename(self.home, self.ws, "moved")
again = workspace.load(self.home, "moved", strict=True)
self.assertEqual((self.ws.name, again.job_roots), ("moved", [os.path.join(self.home, "moved", "imported", "kept")]))

def test_a_rename_under_a_relative_home(self):
here = os.getcwd(); os.chdir(self.home); self.addCleanup(os.chdir, here)
ws = workspace.create("ws", [self.root], label="rel")
kept = os.path.abspath(_job_dir(ws.imports_dir, "kept"))
ws.job_roots = [kept]; workspace.save(ws)
workspace.rename("ws", ws, "moved")
os.chdir(here) # read again from elsewhere, by the absolute home
again = workspace.load(os.path.join(self.home, "ws"), "moved", strict=True)
self.assertEqual(workspace.walked(again), [self.root, os.path.join(self.home, "ws", "moved", "imported", "kept")])

def test_two_renames_at_once_leave_one_parse(self):
"""A rename that starts while another drops its parses waits for it: none is left under a name passed through."""
kept = _job_dir(self.ws.imports_dir, "kept")
self.ws.job_roots = [kept]; workspace.save(self.ws)
workspace.load_jobs(self.ws, workspace.walked(self.ws))
paused, go, drop_moved = threading.Event(), threading.Event(), workspace._drop_moved

def slow(*args):
paused.set(); go.wait(5)
return drop_moved(*args)
with patch.object(workspace, "_drop_moved", side_effect=slow):
first = threading.Thread(target=workspace.rename, args=(self.home, workspace.load(self.home, self.ws.name), "second"))
first.start(); paused.wait(5)
second = threading.Thread(target=workspace.rename, args=(self.home, workspace.load(self.home, "second"), "third"))
second.start(); second.join(0.3); go.set(); first.join(5); second.join(5)
final = workspace.load(self.home, "third")
workspace.load_jobs(final, workspace.walked(final))
self.assertEqual((sorted(workspace.job_index(final)), final.n_cached),
(sorted([self.job_dir, os.path.join(self.home, "third", "imported", "kept")]), 2))

def test_a_slower_load_leaves_the_entry_a_newer_one_wrote(self):
parse_job = parse.parse_job

Expand Down
19 changes: 19 additions & 0 deletions app/ui_tests/test_run_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1426,6 +1426,25 @@ def test_unlink_takes_the_root_out_of_that_workspace_only(self):
self.assertIn(root, self.other().roots)
self.assertTrue((self.run_dir / "jobs").is_dir()) # its files stay

def test_a_kept_conversion_is_listed_and_unlinked(self):
"""A conversion kept from before, read through ``job_roots`` alone, is one of the
dialog's roots: unlinked, it leaves the workspace and its files stay."""
kept = self._job_dir(self.ws.imports_dir, "kept")
held = workspace.load(self.home, self.ws.name); held.job_roots = [kept]; workspace.save(held)
self.assertIn('aria-label="Roots of witty pelican: 2"', self.row(self.ws))
dialog = self.roots(self.ws)
self.assertIn(f'aria-label="Unlink {kept}"', dialog)
self.assertRegex(dialog, self.greyed(kept, "A kept conversion: unlink it instead"))
ask = self.get(f"/workspaces/{self.ws.name}/roots/ask?root={kept}")
self.assertEqual((ask.status_code, ask.get_data(as_text=True)), (409, "Delete folder: A kept conversion: unlink it instead"))
r = self.client.post(f"/workspaces/{self.ws.name}/roots/delete", data={"csrf": self.csrf, "root": kept},
headers={"Origin": "http://localhost"}); self.addCleanup(r.close)
self.assertEqual((r.status_code, workspace.load(self.home, self.ws.name).job_roots), (302, [kept]))
self.assertEqual(self.post(f"/workspaces/{self.ws.name}/roots/unlink", root=kept).status_code, 302)
self.assertEqual(workspace.load(self.home, self.ws.name).job_roots, [])
self.assertEqual(web.shared.STATE["job_roots"], [str(self.run_dir / "jobs")])
self.assertTrue(os.path.isdir(kept)) # its files stay

def test_delete_refuses_a_folder_outside_storage(self):
outside = self.tmp / "elsewhere"; self._job_dir(str(outside), "x-a")
link = self.tmp / "runs" / "link"; link.symlink_to(outside, target_is_directory=True) # a link out of the runs root
Expand Down
Loading
Loading