mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 20:59:56 -05:00
repos: search Repos by name and README
repository_fts (FTS5, external content) indexes each Repo's search_name (name and owner) and readme_text; a name match outranks a README mention. The downloader stores the README as plain text (markdown syntax removed so snippets read well), writing it only when it changed. * POST /api/repos/search: by search and/or Tag, with README headlines. * /api/search_other_estimates takes an optional search_str and returns repo_count, so Repos count toward the global search's Other tab. * /api/search_suggestions suggests Repos by name. The repository FTS DDL is installed only once the repository table exists: the baseline migration also runs install_raw_ddl, before that table is created. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f49288b8ec
commit
5c80ad7ba4
12 changed files with 391 additions and 13 deletions
39
alembic/versions/2026_10_06_1300_repository_search.py
Normal file
39
alembic/versions/2026_10_06_1300_repository_search.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
"""Search git Repos by name and README: repository.search_name/readme_text and repository_fts.
|
||||
|
||||
Revision ID: 2026_10_06_1300
|
||||
Revises: 2026_10_06_1200
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_06_1300'
|
||||
down_revision = '2026_10_06_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
from wrolpi.schema_ddl import install_raw_ddl
|
||||
|
||||
op.add_column('repository', sa.Column('search_name', sa.String(), nullable=True))
|
||||
op.add_column('repository', sa.Column('readme_text', sa.Text(), nullable=True))
|
||||
op.execute('''
|
||||
UPDATE repository SET search_name = TRIM(
|
||||
COALESCE((SELECT name FROM collection WHERE collection.id = repository.collection_id), '')
|
||||
|| ' ' || COALESCE(owner, ''))
|
||||
''')
|
||||
|
||||
# Creates repository_fts and its triggers now that the columns exist. The README text is filled by the next
|
||||
# update of each Repo.
|
||||
install_raw_ddl(op.get_bind())
|
||||
op.execute("INSERT INTO repository_fts(repository_fts) VALUES('rebuild')")
|
||||
|
||||
|
||||
def downgrade():
|
||||
for name in ('repository_fts_ai', 'repository_fts_ad', 'repository_fts_au'):
|
||||
op.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||
op.execute('DROP TABLE IF EXISTS repository_fts')
|
||||
with op.batch_alter_table('repository') as batch_op:
|
||||
batch_op.drop_column('readme_text')
|
||||
batch_op.drop_column('search_name')
|
||||
|
|
@ -45,6 +45,19 @@ async def post_repo(request: Request, body: schema.RepoCreateRequest):
|
|||
return json_response(dict(repo=repo.__json__()), status=HTTPStatus.CREATED)
|
||||
|
||||
|
||||
@repos_bp.post('/search')
|
||||
@openapi.definition(
|
||||
summary='Search git Repos by their name and README, and/or by Tag',
|
||||
body=schema.RepoSearchRequest,
|
||||
validate=True,
|
||||
)
|
||||
async def post_search_repos(request: Request, body: schema.RepoSearchRequest):
|
||||
limit = min(max(body.limit, 1), 100)
|
||||
repos, total = lib.search_repos(request.ctx.session, body.search_str, body.tag_names, limit=limit,
|
||||
offset=max(body.offset, 0))
|
||||
return json_response(dict(repos=repos, totals=dict(repos=total)))
|
||||
|
||||
|
||||
@repos_bp.get('/<repo_id:int>')
|
||||
@openapi.definition(summary='Get a git Repo')
|
||||
async def get_repo(request: Request, repo_id: int):
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ from wrolpi.common import logger
|
|||
from wrolpi.dates import now
|
||||
from wrolpi.downloader import Downloader, Download, DownloadContext, DownloadResult, make_progress_callback
|
||||
from wrolpi.errors import DownloadError
|
||||
from .lib import git_command, git_env, find_readme, get_repo_size, is_valid_branch
|
||||
from .lib import git_command, git_env, find_readme, get_repo_size, is_valid_branch, read_readme_text
|
||||
from .models import Repository
|
||||
|
||||
__all__ = ['GitDownloader', 'git_downloader', 'PreparedRepo', 'ExecutedRepo', 'parse_git_progress']
|
||||
|
|
@ -49,6 +49,7 @@ class ExecutedRepo:
|
|||
head_message: str
|
||||
size: int
|
||||
readme_path: Optional[str]
|
||||
readme_text: Optional[str]
|
||||
|
||||
|
||||
class GitCancelled(Exception):
|
||||
|
|
@ -178,6 +179,8 @@ class GitDownloader(Downloader):
|
|||
|
||||
head_sha, head_date, head_message = head.split('\x00', 2)
|
||||
size = await asyncio.to_thread(get_repo_size, directory)
|
||||
readme_path = find_readme(directory)
|
||||
readme_text = await asyncio.to_thread(read_readme_text, directory / readme_path) if readme_path else None
|
||||
return ExecutedRepo(
|
||||
repository_id=prepared.repository_id,
|
||||
default_branch=default_branch,
|
||||
|
|
@ -185,7 +188,8 @@ class GitDownloader(Downloader):
|
|||
head_date=datetime.fromisoformat(head_date),
|
||||
head_message=head_message,
|
||||
size=size,
|
||||
readme_path=find_readme(directory),
|
||||
readme_path=readme_path,
|
||||
readme_text=readme_text,
|
||||
)
|
||||
|
||||
def finalize_download(self, session: Session, download: Download, executed: ExecutedRepo) -> DownloadResult:
|
||||
|
|
@ -198,6 +202,9 @@ class GitDownloader(Downloader):
|
|||
repo.head_message = executed.head_message
|
||||
repo.size = executed.size
|
||||
repo.readme_path = executed.readme_path
|
||||
if repo.readme_text != executed.readme_text:
|
||||
# Only write a changed README; every write re-indexes it.
|
||||
repo.readme_text = executed.readme_text
|
||||
repo.last_fetch = now()
|
||||
logger.info(f'Updated repo {repo.url} to {executed.head_sha}')
|
||||
return DownloadResult(success=True, location=repo.location)
|
||||
|
|
|
|||
|
|
@ -4,12 +4,13 @@ import pathlib
|
|||
import re
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional
|
||||
from typing import List, Optional, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy import func, text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from wrolpi import fts
|
||||
from wrolpi.cmd import GIT_BIN
|
||||
from wrolpi.collections.models import Collection
|
||||
from wrolpi.common import ConfigFile, get_media_directory, get_relative_to_media_directory, logger, \
|
||||
|
|
@ -20,6 +21,7 @@ from wrolpi.errors import UnknownDirectory, ValidationError
|
|||
from wrolpi.events import Events
|
||||
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod
|
||||
from wrolpi.tags import Tag
|
||||
from wrolpi.vars import FILE_MAX_TEXT_SIZE
|
||||
from .errors import InvalidRepo, RepoConflict
|
||||
from .models import Repository, REPO_MODES
|
||||
|
||||
|
|
@ -27,7 +29,7 @@ logger = logger.getChild(__name__)
|
|||
|
||||
__all__ = ['ParsedRepoURL', 'parse_repo_url', 'repo_url_key', 'git_command', 'git_env', 'create_repository',
|
||||
'update_repository', 'delete_repository', 'get_repositories', 'list_repo_tree', 'find_readme',
|
||||
'repo_destination_variables', 'is_valid_branch', 'ReposConfig', 'repos_config', 'get_repos_config', 'save_repos_config',
|
||||
'repo_destination_variables', 'is_valid_branch', 'read_readme_text', 'search_repos', 'count_repos', 'search_repos_by_name', 'ReposConfig', 'repos_config', 'get_repos_config', 'save_repos_config',
|
||||
'import_repos_config', 'DEFAULT_REPO_FREQUENCY']
|
||||
|
||||
DEFAULT_REPO_FREQUENCY = DownloadFrequency.weekly.value
|
||||
|
|
@ -171,6 +173,36 @@ def find_readme(directory: pathlib.Path) -> Optional[str]:
|
|||
return None
|
||||
|
||||
|
||||
MARKDOWN_SUFFIXES = ('.md', '.markdown')
|
||||
MARKDOWN_PATTERNS = [
|
||||
(re.compile(r'<!--.*?-->', re.DOTALL), ' '),
|
||||
(re.compile(r'<[^>\n]+>'), ' '), # HTML tags.
|
||||
(re.compile(r'^\s*\[[^\]]+\]:\s*\S+.*$', re.MULTILINE), ''), # Link reference definitions.
|
||||
(re.compile(r'!\[([^\]]*)\]\([^)]*\)'), r'\1'), # Images (and badges) become their alt text.
|
||||
(re.compile(r'\[([^\]]*)\]\([^)]*\)'), r'\1'), # Links become their text.
|
||||
(re.compile(r'^\s*(```|~~~).*$', re.MULTILINE), ''), # Code fences.
|
||||
(re.compile(r'^\s{0,3}#{1,6}\s*', re.MULTILINE), ''), # Headings.
|
||||
(re.compile(r'^\s{0,3}>\s?', re.MULTILINE), ''), # Block quotes.
|
||||
(re.compile(r'^\s*\|?[\s:|-]+\|[\s:|-]*$', re.MULTILINE), ''), # Table separator rows.
|
||||
(re.compile(r'[*`|]+'), ' '), # Emphasis, inline code, table cells.
|
||||
(re.compile(r'[ \t]+'), ' '),
|
||||
(re.compile(r'\n\s*\n+'), '\n'),
|
||||
]
|
||||
|
||||
|
||||
def read_readme_text(path: pathlib.Path) -> Optional[str]:
|
||||
"""Read a README as plain text for search; markdown syntax is removed so snippets read well."""
|
||||
try:
|
||||
with path.open('rb') as fh:
|
||||
text = fh.read(FILE_MAX_TEXT_SIZE).decode(errors='replace')
|
||||
except (FileNotFoundError, IsADirectoryError):
|
||||
return None
|
||||
if path.suffix.lower() in MARKDOWN_SUFFIXES:
|
||||
for pattern, replacement in MARKDOWN_PATTERNS:
|
||||
text = pattern.sub(replacement, text)
|
||||
return text.strip() or None
|
||||
|
||||
|
||||
def repo_destination_variables(collection: Collection) -> dict:
|
||||
"""Variables for `repos_destination` which are stored on the Repository (not the Collection)."""
|
||||
session = Session.object_session(collection)
|
||||
|
|
@ -237,7 +269,8 @@ def create_repository(session: Session, url: str, tag_name: str = None, frequenc
|
|||
session.add(collection)
|
||||
session.flush([collection])
|
||||
repo = Repository(url=parsed.url, host=parsed.host, owner=parsed.owner, mode=mode, branch=branch,
|
||||
collection_id=collection.id)
|
||||
collection=collection)
|
||||
repo.update_search_name()
|
||||
session.add(repo)
|
||||
session.flush([repo])
|
||||
|
||||
|
|
@ -322,6 +355,76 @@ def get_repositories(session: Session) -> List[dict]:
|
|||
return [i.__json__() for i in repos]
|
||||
|
||||
|
||||
def _repo_search_sql(search_str: Optional[str], tag_names: Optional[List[str]]) \
|
||||
-> Optional[Tuple[str, str, dict, bool]]:
|
||||
"""The FROM and WHERE of a Repo search by name/README and Tag, its params, and whether it uses FTS.
|
||||
|
||||
Returns None when nothing can match."""
|
||||
tag_names = tag_names or []
|
||||
if len(tag_names) > 1:
|
||||
# A Repo has one Tag.
|
||||
return None
|
||||
search = fts.repository_search_join(search_str) if search_str else None
|
||||
if search is None and (search_str and search_str.strip() or not tag_names):
|
||||
# Nothing usable to search, or nothing to filter by.
|
||||
return None
|
||||
|
||||
from_sql = 'repository r JOIN collection c ON c.id = r.collection_id'
|
||||
where, params = [], {}
|
||||
if search:
|
||||
from_sql = f'{from_sql} {search.join}'
|
||||
params.update(search.params)
|
||||
if tag_names:
|
||||
from_sql = f'{from_sql} JOIN tag t ON t.id = c.tag_id'
|
||||
where.append('t.name = :tag_name')
|
||||
params['tag_name'] = tag_names[0]
|
||||
return from_sql, (f"WHERE {' AND '.join(where)}" if where else ''), params, search is not None
|
||||
|
||||
|
||||
def search_repos(session: Session, search_str: str = None, tag_names: List[str] = None, limit: int = 20,
|
||||
offset: int = 0) -> Tuple[List[dict], int]:
|
||||
"""Find Repos by their name and README (and/or their Tag). Returns the Repos (best match first, each with a
|
||||
`readme_headline`) and the total count."""
|
||||
query = _repo_search_sql(search_str, tag_names)
|
||||
if query is None:
|
||||
return [], 0
|
||||
from_sql, where, params, is_fts = query
|
||||
select = 'r.id, fts.readme_headline' if is_fts else 'r.id, NULL'
|
||||
order_by = 'fts.ts_rank DESC, LOWER(c.name)' if is_fts else 'LOWER(c.name)'
|
||||
rows = session.execute(text(
|
||||
f'SELECT {select}, COUNT(*) OVER() FROM {from_sql} {where} ORDER BY {order_by} LIMIT :limit OFFSET :offset'
|
||||
), dict(params, limit=limit, offset=offset)).fetchall()
|
||||
if not rows:
|
||||
return [], 0
|
||||
|
||||
repos = session.query(Repository).options(*Repository.json_options()) \
|
||||
.filter(Repository.id.in_([i[0] for i in rows])).all()
|
||||
repos = {i.id: i for i in repos}
|
||||
results = [dict(repos[id_].__json__(), readme_headline=headline) for id_, headline, _ in rows if id_ in repos]
|
||||
return results, rows[0][2]
|
||||
|
||||
|
||||
def count_repos(session: Session, search_str: str = None, tag_names: List[str] = None) -> int:
|
||||
"""The number of Repos `search_repos` would find."""
|
||||
query = _repo_search_sql(search_str, tag_names)
|
||||
if query is None:
|
||||
return 0
|
||||
from_sql, where, params, _ = query
|
||||
return session.execute(text(f'SELECT COUNT(*) FROM {from_sql} {where}'), params).scalar()
|
||||
|
||||
|
||||
async def search_repos_by_name(session: Session, name: str, limit: int = 5) -> List[dict]:
|
||||
"""Repos whose name contains `name`, for the search suggestions."""
|
||||
if not name:
|
||||
return []
|
||||
repos = session.query(Repository).options(*Repository.json_options()) \
|
||||
.join(Collection, Collection.id == Repository.collection_id) \
|
||||
.filter(Collection.name.ilike(f'%{name}%')) \
|
||||
.order_by(func.lower(Collection.name)) \
|
||||
.limit(limit).all()
|
||||
return [dict(id=i.id, name=i.name, tag_name=i.tag_name, location=i.location) for i in repos]
|
||||
|
||||
|
||||
@dataclass
|
||||
class RepoTreeEntry:
|
||||
name: str
|
||||
|
|
@ -475,6 +578,7 @@ class ReposConfig(ConfigFile):
|
|||
|
||||
collection = repo.collection
|
||||
collection.name = name
|
||||
repo.update_search_name()
|
||||
collection.description = data.get('description')
|
||||
collection.tag = Tag.get_or_create_tag(session, tag_name) if tag_name else None
|
||||
if directory:
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import pathlib
|
|||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger, Text
|
||||
from sqlalchemy.orm import relationship, Session, joinedload, selectinload
|
||||
from sqlalchemy.orm import relationship, Session, joinedload, selectinload, deferred
|
||||
|
||||
from wrolpi.collections.models import Collection
|
||||
from wrolpi.common import Base, ModelHelper, get_relative_to_media_directory
|
||||
|
|
@ -39,6 +39,9 @@ class Repository(ModelHelper, Base):
|
|||
size = Column(BigInteger)
|
||||
# The README in the repo's root directory, relative to the repo.
|
||||
readme_path = Column(String)
|
||||
# Searched by `repository_fts` (see wrolpi.fts); kept current by `update_search_name` and the downloader.
|
||||
search_name = Column(String)
|
||||
readme_text = deferred(Column(Text))
|
||||
|
||||
collection_id = Column(Integer, ForeignKey('collection.id', ondelete='CASCADE'), nullable=False, unique=True)
|
||||
# Joined: a Repository's name, directory and Tag live on its Collection.
|
||||
|
|
@ -65,6 +68,10 @@ class Repository(ModelHelper, Base):
|
|||
downloads = [i for i in self.collection.downloads if i.frequency] if self.collection else []
|
||||
return downloads[0] if downloads else None
|
||||
|
||||
def update_search_name(self):
|
||||
"""The Repo is found by its name and its owner."""
|
||||
self.search_name = ' '.join(i for i in (self.name, self.owner) if i)
|
||||
|
||||
@property
|
||||
def location(self) -> str:
|
||||
return f'/repos/{self.id}'
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, List
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -13,6 +13,14 @@ class RepoCreateRequest:
|
|||
description: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class RepoSearchRequest:
|
||||
search_str: Optional[str] = None
|
||||
tag_names: List[str] = field(default_factory=list)
|
||||
limit: int = 20
|
||||
offset: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class RepoUpdateRequest:
|
||||
description: Optional[str] = None
|
||||
|
|
|
|||
129
modules/repos/test/test_search.py
Normal file
129
modules/repos/test/test_search.py
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import json
|
||||
import sqlite3
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.repos import lib
|
||||
from modules.repos.models import Repository
|
||||
|
||||
|
||||
def set_readme(session, repo: Repository, readme_text: str):
|
||||
repo.readme_text = readme_text
|
||||
session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_repos(test_session, async_client, test_wrolpi_config):
|
||||
"""Repos are found by their name, owner, and README; a name match outranks a README mention."""
|
||||
kiwix = lib.create_repository(test_session, 'https://github.com/kiwix/kiwix-tools', tag_name='software')
|
||||
maps = lib.create_repository(test_session, 'https://github.com/protomaps/basemaps')
|
||||
set_readme(test_session, kiwix, 'Kiwix tools serve Zim files offline.')
|
||||
set_readme(test_session, maps, 'Vector basemaps. Works with kiwix-tools and offline maps.')
|
||||
|
||||
def names(search_str=None, tag_names=None):
|
||||
repos, total = lib.search_repos(test_session, search_str, tag_names)
|
||||
assert total == len(repos)
|
||||
return [i['name'] for i in repos]
|
||||
|
||||
assert names('kiwix') == ['kiwix-tools', 'basemaps']
|
||||
assert names('protomaps') == ['basemaps'] # The owner.
|
||||
assert names('vector') == ['basemaps']
|
||||
assert set(names('offline')) == {'kiwix-tools', 'basemaps'}
|
||||
assert names('zim -vector') == ['kiwix-tools']
|
||||
assert names('nothing') == []
|
||||
|
||||
repos, _ = lib.search_repos(test_session, 'vector')
|
||||
assert repos[0]['readme_headline'] == '<b>Vector</b> basemaps. Works with kiwix-tools and offline maps.'
|
||||
|
||||
# Tags.
|
||||
assert names('offline', ['software']) == ['kiwix-tools']
|
||||
assert names(tag_names=['software']) == ['kiwix-tools']
|
||||
assert names('offline', ['software', 'other']) == []
|
||||
assert names('offline', ['other']) == []
|
||||
|
||||
# Nothing to search.
|
||||
assert names() == []
|
||||
assert names('!!!') == []
|
||||
|
||||
assert lib.count_repos(test_session, 'offline') == 2
|
||||
assert lib.count_repos(test_session, 'offline', ['software']) == 1
|
||||
assert lib.count_repos(test_session) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_index_follows_changes(test_session, test_directory, async_client, test_wrolpi_config):
|
||||
"""The search index follows README changes, renames from the config, and deletes."""
|
||||
repo = lib.create_repository(test_session, 'https://github.com/a/b')
|
||||
set_readme(test_session, repo, 'first readme')
|
||||
assert lib.count_repos(test_session, 'first') == 1
|
||||
|
||||
set_readme(test_session, repo, 'second readme')
|
||||
assert lib.count_repos(test_session, 'first') == 0
|
||||
assert lib.count_repos(test_session, 'second') == 1
|
||||
|
||||
lib.ReposConfig._import_repo(test_session, dict(url='https://github.com/a/b', name='renamed'))
|
||||
test_session.commit()
|
||||
assert lib.count_repos(test_session, 'renamed') == 1
|
||||
|
||||
await lib.delete_repository(test_session, repo.id)
|
||||
assert lib.count_repos(test_session, 'second') == 0
|
||||
assert lib.count_repos(test_session, 'renamed') == 0
|
||||
|
||||
# The index matches its content.
|
||||
with sqlite3.connect(test_directory / 'config/wrolpi.db') as conn:
|
||||
conn.execute("INSERT INTO repository_fts(repository_fts, rank) VALUES('integrity-check', 1)")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_downloader_indexes_readme(test_session, git_remote_factory, repos_download_manager):
|
||||
"""The downloader stores the README as plain text, and keeps it current."""
|
||||
readme = '# Example\n\n[](https://ci) An **offline** [library](https://docs).\n'
|
||||
remote = git_remote_factory(files={'README.md': readme})
|
||||
repo = lib.create_repository(test_session, remote.url)
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
test_session.expire_all()
|
||||
assert repo.readme_text == 'Example\nCI An offline library.'
|
||||
assert lib.count_repos(test_session, 'library') == 1
|
||||
|
||||
remote.git('rm', '--quiet', 'README.md')
|
||||
remote.commit({'readme.txt': 'Plain *text*'}, 'Plain README')
|
||||
download = repo.download
|
||||
download.renew()
|
||||
test_session.commit()
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
test_session.expire_all()
|
||||
assert repo.readme_path == 'readme.txt'
|
||||
assert repo.readme_text == 'Plain *text*'
|
||||
assert lib.count_repos(test_session, 'library') == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_api(test_session, async_client, test_wrolpi_config):
|
||||
kiwix = lib.create_repository(test_session, 'https://github.com/kiwix/kiwix-tools', tag_name='software')
|
||||
set_readme(test_session, kiwix, 'Serve Zim files offline.')
|
||||
lib.create_repository(test_session, 'https://github.com/a/b')
|
||||
|
||||
body = dict(search_str='zim')
|
||||
request, response = await async_client.post('/api/repos/search', content=json.dumps(body))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['totals'] == dict(repos=1)
|
||||
repo, = response.json['repos']
|
||||
assert repo['name'] == 'kiwix-tools'
|
||||
assert repo['readme_headline'] == 'Serve <b>Zim</b> files offline.'
|
||||
assert 'readme_text' not in repo
|
||||
|
||||
# The global search's "Other" estimate counts Repos by the search, and by Tag.
|
||||
request, response = await async_client.post('/api/search_other_estimates', content=json.dumps(body))
|
||||
assert response.json['others'] == dict(channel_count=0, repo_count=1)
|
||||
body = dict(tag_names=['software'])
|
||||
request, response = await async_client.post('/api/search_other_estimates', content=json.dumps(body))
|
||||
assert response.json['others'] == dict(channel_count=0, repo_count=1)
|
||||
body = dict(tag_names=['software'], search_str='nothing')
|
||||
request, response = await async_client.post('/api/search_other_estimates', content=json.dumps(body))
|
||||
assert response.json['others'] == dict(channel_count=0, repo_count=0)
|
||||
|
||||
# Repos are suggested by name.
|
||||
request, response = await async_client.post('/api/search_suggestions', content=json.dumps(dict(search_str='kiw')))
|
||||
assert response.json['repos'] == [
|
||||
dict(id=kiwix.id, name='kiwix-tools', tag_name='software', location=f'/repos/{kiwix.id}')]
|
||||
|
|
@ -2855,16 +2855,20 @@ def extract_headlines(entries: List[str], search_str: str) -> List[Tuple[str, fl
|
|||
return fts.headline_texts(entries, search_str, tokens=8)
|
||||
|
||||
|
||||
async def search_other_estimates(session: Session, tag_names: List[str]) -> dict:
|
||||
"""Estimate other things that are Tagged."""
|
||||
async def search_other_estimates(session: Session, tag_names: List[str], search_str: str = None) -> dict:
|
||||
"""Estimate other things that are Tagged, or match the search (Repos by their name and README)."""
|
||||
from sqlalchemy import func
|
||||
from wrolpi.collections.models import Collection
|
||||
from wrolpi.tags import Tag
|
||||
from modules.videos.models import Channel
|
||||
from modules.repos.lib import count_repos
|
||||
|
||||
repo_count = count_repos(session, search_str, tag_names)
|
||||
|
||||
if not tag_names:
|
||||
return dict(
|
||||
channel_count=0,
|
||||
repo_count=repo_count,
|
||||
)
|
||||
|
||||
# TODO handle multiple tags
|
||||
|
|
@ -2876,6 +2880,7 @@ async def search_other_estimates(session: Session, tag_names: List[str]) -> dict
|
|||
|
||||
others = dict(
|
||||
channel_count=channel_count,
|
||||
repo_count=repo_count,
|
||||
)
|
||||
return others
|
||||
|
||||
|
|
|
|||
|
|
@ -97,8 +97,47 @@ FTS_DDL = [
|
|||
''',
|
||||
]
|
||||
|
||||
# A Repo's name outranks a mention in its README.
|
||||
REPOSITORY_BM25_WEIGHTS = 'bm25(10.0, 1.0)'
|
||||
|
||||
# Installed only once the `repository` table exists (see `schema_ddl.install_raw_ddl`); the baseline migration
|
||||
# runs before that table is created.
|
||||
REPOSITORY_FTS_DDL = [
|
||||
f'''
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS repository_fts USING fts5(
|
||||
search_name, readme_text,
|
||||
content='repository',
|
||||
content_rowid='id',
|
||||
tokenize='{TOKENIZER}'
|
||||
)
|
||||
''',
|
||||
f'''
|
||||
INSERT INTO repository_fts(repository_fts, rank) VALUES('rank', '{REPOSITORY_BM25_WEIGHTS}')
|
||||
''',
|
||||
'''
|
||||
CREATE TRIGGER IF NOT EXISTS repository_fts_ai AFTER INSERT ON repository BEGIN
|
||||
INSERT INTO repository_fts(rowid, search_name, readme_text)
|
||||
VALUES (new.id, new.search_name, new.readme_text);
|
||||
END
|
||||
''',
|
||||
'''
|
||||
CREATE TRIGGER IF NOT EXISTS repository_fts_ad AFTER DELETE ON repository BEGIN
|
||||
INSERT INTO repository_fts(repository_fts, rowid, search_name, readme_text)
|
||||
VALUES ('delete', old.id, old.search_name, old.readme_text);
|
||||
END
|
||||
''',
|
||||
'''
|
||||
CREATE TRIGGER IF NOT EXISTS repository_fts_au AFTER UPDATE OF search_name, readme_text ON repository BEGIN
|
||||
INSERT INTO repository_fts(repository_fts, rowid, search_name, readme_text)
|
||||
VALUES ('delete', old.id, old.search_name, old.readme_text);
|
||||
INSERT INTO repository_fts(rowid, search_name, readme_text)
|
||||
VALUES (new.id, new.search_name, new.readme_text);
|
||||
END
|
||||
''',
|
||||
]
|
||||
|
||||
# FTS5 shadow tables (and the virtual tables themselves); excluded from alembic autogenerate.
|
||||
FTS_TABLE_PREFIXES = ('file_group_fts', 'doc_section_fts')
|
||||
FTS_TABLE_PREFIXES = ('file_group_fts', 'doc_section_fts', 'repository_fts')
|
||||
|
||||
|
||||
_ITEM_RE = re.compile(r'-?"[^"]*"?|\S+')
|
||||
|
|
@ -235,6 +274,20 @@ def file_group_search_join(search_str: str, deep: bool = False, headlines: bool
|
|||
params={param_name: match})
|
||||
|
||||
|
||||
def repository_search_join(search_str: str, alias: str = 'r', param_name: str = 'repo_match',
|
||||
start: str = '<b>', stop: str = '</b>', tokens: int = 16) -> Optional[FileGroupSearch]:
|
||||
"""Join `repository` (aliased `alias`) to its FTS5 matches. Provides `fts.ts_rank` and `fts.readme_headline`.
|
||||
|
||||
Returns None when there is nothing usable to search."""
|
||||
match = translate_websearch(search_str)
|
||||
if match is None:
|
||||
return None
|
||||
join = (f"JOIN (SELECT rowid, -rank AS ts_rank, "
|
||||
f"snippet(repository_fts, 1, '{start}', '{stop}', '…', {tokens}) AS readme_headline "
|
||||
f"FROM repository_fts WHERE repository_fts MATCH :{param_name}) fts ON fts.rowid = {alias}.id")
|
||||
return FileGroupSearch(join=join, where='', rank_select='fts.ts_rank AS ts_rank', params={param_name: match})
|
||||
|
||||
|
||||
def file_group_headline_selects(start: str = '<b>', stop: str = '</b>', tokens: int = 16) -> str:
|
||||
"""SELECT fragments producing the b/c/d headline columns from the joined FTS table.
|
||||
|
||||
|
|
|
|||
|
|
@ -789,6 +789,7 @@ async def post_search_suggestions(request: Request, body: schema.SearchSuggestio
|
|||
from modules.videos.channel.lib import search_channels_by_name
|
||||
from modules.archive.lib import search_domains_by_name
|
||||
from modules.docs.lib import search_authors_by_name, search_subjects_by_name
|
||||
from modules.repos.lib import search_repos_by_name
|
||||
|
||||
session = request.ctx.session
|
||||
# Run sequentially: a SQLAlchemy Session is not safe for concurrent use, and
|
||||
|
|
@ -799,12 +800,14 @@ async def post_search_suggestions(request: Request, body: schema.SearchSuggestio
|
|||
domains = await search_domains_by_name(session, body.search_str)
|
||||
authors = await search_authors_by_name(session, body.search_str)
|
||||
subjects = await search_subjects_by_name(session, body.search_str)
|
||||
repos = await search_repos_by_name(session, body.search_str)
|
||||
|
||||
ret = dict(
|
||||
channels=channels,
|
||||
domains=domains,
|
||||
authors=authors,
|
||||
subjects=subjects,
|
||||
repos=repos,
|
||||
)
|
||||
return json_response(ret)
|
||||
|
||||
|
|
@ -843,7 +846,7 @@ async def post_search_file_estimates(request: Request, body: schema.SearchFileEs
|
|||
)
|
||||
async def post_search_other_estimates(request: Request, body: schema.SearchOtherEstimateRequest):
|
||||
"""Used by the Global search to suggest FileGroup count to the user."""
|
||||
others = await search_other_estimates(request.ctx.session, body.tag_names)
|
||||
others = await search_other_estimates(request.ctx.session, body.tag_names, body.search_str)
|
||||
ret = dict(others=others)
|
||||
return json_response(ret)
|
||||
|
||||
|
|
|
|||
|
|
@ -506,3 +506,4 @@ class SearchFileEstimateRequest:
|
|||
@dataclass
|
||||
class SearchOtherEstimateRequest:
|
||||
tag_names: List[str] = field(default_factory=list)
|
||||
search_str: Optional[str] = None
|
||||
|
|
|
|||
|
|
@ -186,3 +186,12 @@ def install_raw_ddl(conn):
|
|||
|
||||
for statement in [*TRIGGER_DDL, *fts.FTS_DDL]:
|
||||
conn.execute(statement)
|
||||
|
||||
# DDL for tables created after the baseline migration (which also calls this function).
|
||||
if _table_exists(conn, 'repository'):
|
||||
for statement in fts.REPOSITORY_FTS_DDL:
|
||||
conn.execute(statement)
|
||||
|
||||
|
||||
def _table_exists(conn, name: str) -> bool:
|
||||
return conn.execute(f"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '{name}'").fetchone() is not None
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue