mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-22 16:06:19 -05:00
repos: history, Download ZIP, and submodules
* GET /api/repos/<id>/log: the checked out branch's commits, newest first, a page at a time, with the total. The repo page has a Files | History toggle (the tree is only listed for Files). * GET /api/repos/<id>/archive.zip: `git archive HEAD` streamed to the browser; the file name is reduced to safe characters. Everything is read from the database before the response starts, because the request's session closes once a streamed response begins. * repository.submodules (default off): submodules are checked out with the repo's mode and the same git restrictions, and removed when the option is turned off. A submodule that cannot be downloaded (e.g. an ssh URL) does not stop the repo from updating; the download is retried with the submodule's error. * The README speed test bound is loose enough for a busy machine. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0d1a988fa6
commit
03e3476631
14 changed files with 579 additions and 31 deletions
22
alembic/versions/2026_10_06_1400_repository_submodules.py
Normal file
22
alembic/versions/2026_10_06_1400_repository_submodules.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
"""A git Repo can also download its submodules: repository.submodules.
|
||||
|
||||
Revision ID: 2026_10_06_1400
|
||||
Revises: 2026_10_06_1300
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_06_1400'
|
||||
down_revision = '2026_10_06_1300'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('repository', sa.Column('submodules', sa.Boolean(), server_default=sa.false(), nullable=False))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table('repository') as batch_op:
|
||||
batch_op.drop_column('submodules')
|
||||
|
|
@ -2582,3 +2582,17 @@ export async function searchRepos(searchStr, tagNames) {
|
|||
}
|
||||
await reposError(response, 'Failed to search repos.');
|
||||
}
|
||||
|
||||
// The commits of a repo's checked out branch, newest first: {commits: [{sha, author, date, message}], total}.
|
||||
export async function getRepoLog(repoId, offset = 0, limit = 50) {
|
||||
const response = await apiGet(`${REPOS_API}/${repoId}/log?limit=${limit}&offset=${offset}`);
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
await reposError(response, 'Failed to fetch the repo history.');
|
||||
}
|
||||
|
||||
// A ZIP of a repo's checked out files; the browser downloads it.
|
||||
export function repoArchiveURL(repoId) {
|
||||
return `${REPOS_API}/${repoId}/archive.zip`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {IconBrandGit, IconFile, IconFolder, IconGitBranch, IconGitCommit} from "
|
|||
import {
|
||||
Anchor,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Checkbox,
|
||||
Grid,
|
||||
Group,
|
||||
|
|
@ -42,7 +43,9 @@ import {
|
|||
getCollectionTagInfo,
|
||||
getFile,
|
||||
getRepo,
|
||||
getRepoLog,
|
||||
getRepoTree,
|
||||
repoArchiveURL,
|
||||
tagCollection,
|
||||
updateRepo,
|
||||
updateRepoNow,
|
||||
|
|
@ -364,12 +367,90 @@ export function RepoReadme({repo, readmePath}) {
|
|||
</Panel>;
|
||||
}
|
||||
|
||||
/** A page of a repo's commits, newest first. */
|
||||
export function RepoHistoryTable({commits}) {
|
||||
return <Table striped>
|
||||
<Table.Body>
|
||||
{commits.map(commit => <Table.Row key={commit.sha}>
|
||||
<Table.Cell style={{whiteSpace: 'nowrap', width: '1%'}}><code>{commit.sha.slice(0, 7)}</code></Table.Cell>
|
||||
<Table.Cell style={{overflowWrap: 'anywhere'}}>
|
||||
{commit.message}
|
||||
<div style={{color: 'var(--muted)'}}><small>{commit.author}</small></div>
|
||||
</Table.Cell>
|
||||
<Table.Cell style={{textAlign: 'right', color: 'var(--muted)', whiteSpace: 'nowrap'}}>
|
||||
{isoDatetimeToAgoPopup(commit.date)}
|
||||
</Table.Cell>
|
||||
</Table.Row>)}
|
||||
</Table.Body>
|
||||
</Table>;
|
||||
}
|
||||
|
||||
const HISTORY_PAGE_SIZE = 50;
|
||||
|
||||
/** A repo's commits, a page at a time. */
|
||||
export function RepoHistory({repo}) {
|
||||
const [commits, setCommits] = useState(null); // null=loading, undefined=error
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
|
||||
const fetchPage = async (offset) => {
|
||||
const log = await getRepoLog(repo.id, offset, HISTORY_PAGE_SIZE);
|
||||
setTotal(log.total);
|
||||
return log.commits;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
setCommits(null);
|
||||
fetchPage(0)
|
||||
.then(page => current && setCommits(page))
|
||||
.catch(e => {
|
||||
console.error(e);
|
||||
if (current) setCommits(undefined);
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [repo.id, repo.head_sha]);
|
||||
|
||||
if (commits === undefined) {
|
||||
return <ErrorMessage>Could not fetch the repo's history</ErrorMessage>;
|
||||
}
|
||||
if (commits === null) {
|
||||
return <Loading/>;
|
||||
}
|
||||
|
||||
const loadMore = async () => {
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
const page = await fetchPage(commits.length);
|
||||
setCommits([...commits, ...page]);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
};
|
||||
|
||||
return <Panel>
|
||||
<Header as='h4'>{total === 1 ? '1 commit' : `${total} commits`}</Header>
|
||||
{repo.mode === 'snapshot' && <p style={{color: 'var(--muted)'}}>
|
||||
A snapshot only keeps the latest commit. Change the repo's mode to Full history to keep all of them.
|
||||
</p>}
|
||||
<RepoHistoryTable commits={commits}/>
|
||||
{commits.length < total && <Button onClick={loadMore} disabled={loadingMore}>Load more</Button>}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export function RepoViewPage() {
|
||||
const {repoId} = useParams();
|
||||
const {repo, refetch} = useRepo(repoId);
|
||||
const [path, setPath] = useOneQuery('path');
|
||||
const [view, setView] = useOneQuery('view');
|
||||
const {setPreviewFile} = useContext(FilePreviewContext);
|
||||
const tree = useRepoTree(repoId, path || '', !!repo?.head_sha);
|
||||
// The files are only listed when they are shown.
|
||||
const tree = useRepoTree(repoId, path || '', !!repo?.head_sha && view !== 'history');
|
||||
|
||||
useTitle(repo?.name ? `${repo.name} Repo` : 'Repo');
|
||||
|
||||
|
|
@ -393,8 +474,11 @@ export function RepoViewPage() {
|
|||
}
|
||||
};
|
||||
|
||||
const showHistory = view === 'history';
|
||||
let files = null;
|
||||
if (repo.head_sha) {
|
||||
if (repo.head_sha && showHistory) {
|
||||
files = <RepoHistory repo={repo}/>;
|
||||
} else if (repo.head_sha) {
|
||||
if (tree === undefined) {
|
||||
files = <ErrorMessage>Could not list the repo's files</ErrorMessage>;
|
||||
} else if (tree === null) {
|
||||
|
|
@ -416,8 +500,19 @@ export function RepoViewPage() {
|
|||
<BackButton/>
|
||||
<Button component={Link} to={`/repos/${repoId}/edit`} icon='edit'>Edit</Button>
|
||||
<APIButton color='blue' icon='refresh' onClick={handleUpdate} obeyWROLMode={true}>Update Now</APIButton>
|
||||
{repo.head_sha && <Button component='a' href={repoArchiveURL(repo.id)} download icon='download'>
|
||||
Download ZIP
|
||||
</Button>}
|
||||
</div>
|
||||
<RepoSummary repo={repo}/>
|
||||
{repo.head_sha && <ButtonGroup>
|
||||
<Button size='small' variant={showHistory ? 'default' : 'filled'} onClick={() => setView(null)}>
|
||||
Files
|
||||
</Button>
|
||||
<Button size='small' variant={showHistory ? 'filled' : 'default'} onClick={() => setView('history')}>
|
||||
History
|
||||
</Button>
|
||||
</ButtonGroup>}
|
||||
{files}
|
||||
</>;
|
||||
}
|
||||
|
|
@ -442,6 +537,7 @@ export function RepoNewPage() {
|
|||
const [frequency, setFrequency] = useState(String(weeklyOption.value));
|
||||
const [mode, setMode] = useState('full');
|
||||
const [branch, setBranch] = useState('');
|
||||
const [submodules, setSubmodules] = useState(false);
|
||||
const [description, setDescription] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
|
|
@ -459,6 +555,7 @@ export function RepoNewPage() {
|
|||
frequency: parseInt(frequency),
|
||||
mode,
|
||||
branch: branch.trim() || null,
|
||||
submodules,
|
||||
description: description.trim() || null,
|
||||
});
|
||||
toast({type: 'success', title: 'Repo added', description: repo.name, time: 3000});
|
||||
|
|
@ -512,7 +609,8 @@ export function RepoNewPage() {
|
|||
/>
|
||||
</Grid.Col>
|
||||
<RepoSettingsFields frequency={frequency} setFrequency={setFrequency} mode={mode}
|
||||
setMode={setMode} branch={branch} setBranch={setBranch}/>
|
||||
setMode={setMode} branch={branch} setBranch={setBranch}
|
||||
submodules={submodules} setSubmodules={setSubmodules}/>
|
||||
<Grid.Col span={12}>
|
||||
<Textarea
|
||||
label='Description'
|
||||
|
|
@ -534,7 +632,10 @@ export function RepoNewPage() {
|
|||
}
|
||||
|
||||
/** The update frequency, mode and branch of a Repo; shared by the new and edit pages. */
|
||||
export function RepoSettingsFields({frequency, setFrequency, mode, setMode, branch, setBranch, disabled}) {
|
||||
export function RepoSettingsFields({
|
||||
frequency, setFrequency, mode, setMode, branch, setBranch, submodules,
|
||||
setSubmodules, disabled,
|
||||
}) {
|
||||
return <>
|
||||
<Grid.Col span={{base: 12, sm: 4}}>
|
||||
<Select
|
||||
|
|
@ -568,6 +669,16 @@ export function RepoSettingsFields({frequency, setFrequency, mode, setMode, bran
|
|||
disabled={disabled}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={12}>
|
||||
<Checkbox
|
||||
label='Include submodules'
|
||||
description='Also download the other repos this repo includes. Only https:// submodules can be
|
||||
downloaded.'
|
||||
checked={submodules}
|
||||
onChange={(e) => setSubmodules(e.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</Grid.Col>
|
||||
</>;
|
||||
}
|
||||
|
||||
|
|
@ -579,6 +690,7 @@ export function RepoEditPage() {
|
|||
const [frequency, setFrequency] = useState(String(weeklyOption.value));
|
||||
const [mode, setMode] = useState('full');
|
||||
const [branch, setBranch] = useState('');
|
||||
const [submodules, setSubmodules] = useState(false);
|
||||
const [description, setDescription] = useState('');
|
||||
const [tagModalOpen, setTagModalOpen] = useState(false);
|
||||
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
|
||||
|
|
@ -593,6 +705,7 @@ export function RepoEditPage() {
|
|||
setFrequency(String(repo.frequency || weeklyOption.value));
|
||||
setMode(repo.mode || 'full');
|
||||
setBranch(repo.branch || '');
|
||||
setSubmodules(!!repo.submodules);
|
||||
setDescription(repo.description || '');
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
|
|
@ -613,6 +726,7 @@ export function RepoEditPage() {
|
|||
frequency: parseInt(frequency),
|
||||
mode,
|
||||
branch: branch.trim(),
|
||||
submodules,
|
||||
});
|
||||
toast({type: 'success', title: 'Repo Updated', description: repo.name, time: 3000});
|
||||
await refetch();
|
||||
|
|
@ -673,6 +787,7 @@ export function RepoEditPage() {
|
|||
<Grid>
|
||||
<RepoSettingsFields frequency={frequency} setFrequency={setFrequency} mode={mode}
|
||||
setMode={setMode} branch={branch} setBranch={setBranch}
|
||||
submodules={submodules} setSubmodules={setSubmodules}
|
||||
disabled={wrolMode}/>
|
||||
<Grid.Col span={12}>
|
||||
<Textarea
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import {
|
|||
RepoViewPage,
|
||||
safeRepoHref,
|
||||
} from './Repos';
|
||||
import {createRepo, deleteRepo, fetchRepos, getFile, getRepo, getRepoTree, updateRepo} from '../api';
|
||||
import {createRepo, deleteRepo, fetchRepos, getFile, getRepo, getRepoLog, getRepoTree, updateRepo} from '../api';
|
||||
import {FilePreviewContext} from './FilePreview';
|
||||
|
||||
jest.mock('../api', () => ({
|
||||
|
|
@ -19,6 +19,7 @@ jest.mock('../api', () => ({
|
|||
fetchRepos: jest.fn(),
|
||||
getFile: jest.fn(),
|
||||
getRepo: jest.fn(),
|
||||
getRepoLog: jest.fn(),
|
||||
getRepoTree: jest.fn(),
|
||||
updateRepo: jest.fn(),
|
||||
}));
|
||||
|
|
@ -148,11 +149,51 @@ describe('RepoViewPage', () => {
|
|||
expect(updateQuery).toHaveBeenCalledWith({path: ''}, false);
|
||||
});
|
||||
|
||||
it('offers a ZIP of the files', async () => {
|
||||
renderViewPage({repo: repoFixture()});
|
||||
await flush();
|
||||
const link = screen.getByText('Download ZIP').closest('a');
|
||||
expect(link).toHaveAttribute('href', expect.stringMatching(/\/api\/repos\/1\/archive\.zip$/));
|
||||
expect(link).toHaveAttribute('download');
|
||||
});
|
||||
|
||||
it('shows the history instead of the files', async () => {
|
||||
getRepoLog.mockResolvedValue({
|
||||
total: 51,
|
||||
commits: [{sha: 'abcdef1234', author: 'Ada', date: '2026-09-30T14:02:00Z', message: 'Fix the mimetype'}],
|
||||
});
|
||||
const updateQuery = jest.fn();
|
||||
renderViewPage({repo: repoFixture(), query: {searchParams: new URLSearchParams('view=history'), updateQuery}});
|
||||
await flush();
|
||||
|
||||
expect(getRepoLog).toHaveBeenCalledWith(1, 0, 50);
|
||||
expect(getRepoTree).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('51 commits')).toBeInTheDocument();
|
||||
expect(screen.getByText('abcdef1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Ada')).toBeInTheDocument();
|
||||
|
||||
// The next page is appended.
|
||||
getRepoLog.mockResolvedValue({
|
||||
total: 51,
|
||||
commits: [{sha: '0123456789', author: 'Ben', date: '2026-09-01T00:00:00Z', message: 'Older'}],
|
||||
});
|
||||
fireEvent.click(screen.getByText('Load more'));
|
||||
await flush();
|
||||
expect(getRepoLog).toHaveBeenLastCalledWith(1, 1, 50);
|
||||
expect(screen.getByText('abcdef1')).toBeInTheDocument();
|
||||
expect(screen.getByText('0123456')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByText('Files'));
|
||||
expect(updateQuery).toHaveBeenCalledWith({view: null}, false);
|
||||
});
|
||||
|
||||
it('explains a repo that is not downloaded yet', async () => {
|
||||
renderViewPage({repo: repoFixture({head_sha: null, head_message: null, head_date: null})});
|
||||
await flush();
|
||||
expect(screen.getByText('Not downloaded yet')).toBeInTheDocument();
|
||||
expect(getRepoTree).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText('Download ZIP')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('History')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps showing the files when the last update failed', async () => {
|
||||
|
|
@ -192,7 +233,7 @@ describe('RepoNewPage', () => {
|
|||
|
||||
expect(createRepo).toHaveBeenCalledWith({
|
||||
url: 'https://github.com/kiwix/kiwix-tools', name: null, tag_name: null, frequency: 604800,
|
||||
mode: 'full', branch: 'dev', description: null,
|
||||
mode: 'full', branch: 'dev', submodules: false, description: null,
|
||||
});
|
||||
expect(screen.getByText('repo page')).toBeInTheDocument();
|
||||
});
|
||||
|
|
@ -213,11 +254,14 @@ describe('RepoEditPage', () => {
|
|||
await flush();
|
||||
expect(screen.getByLabelText('Branch')).toHaveValue('dev');
|
||||
|
||||
expect(screen.getByLabelText('Include submodules')).not.toBeChecked();
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ''}});
|
||||
fireEvent.click(screen.getByLabelText('Include submodules'));
|
||||
fireEvent.click(screen.getByText('Save'));
|
||||
await flush();
|
||||
expect(updateRepo).toHaveBeenCalledWith('1', {
|
||||
description: 'Tools', frequency: 604800, mode: 'full', branch: '',
|
||||
description: 'Tools', frequency: 604800, mode: 'full', branch: '', submodules: true,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ import {contrastingColor} from './Common';
|
|||
import {navBarStyle, navColorNames, useNavColors} from '../themes/navColors';
|
||||
import {IconMenu2} from '@tabler/icons-react';
|
||||
import {BookmarkAddForms, BookmarkMenuItems, BookmarkTable} from './Bookmarks';
|
||||
import {RepoBreadcrumb, RepoStatusIcon, RepoSummary, RepoTreeTable} from './Repos';
|
||||
import {RepoBreadcrumb, RepoHistoryTable, RepoStatusIcon, RepoSummary, RepoTreeTable} from './Repos';
|
||||
|
||||
/*
|
||||
* A gallery of every component in the library, in the current theme.
|
||||
|
|
@ -182,6 +182,11 @@ const sampleFailedRepo = {
|
|||
download_error: "git ls-remote failed (128): remote: Repository not found.\nfatal: repository " +
|
||||
"'https://github.com/example/gone-upstream/' not found",
|
||||
};
|
||||
const sampleRepoCommits = [
|
||||
{sha: '3f9c2a1e7b', author: 'Ada Example', date: '2026-09-30T14:02:00Z',
|
||||
message: 'Serve Zim files with the correct mimetype'},
|
||||
{sha: '91b0d44c02', author: 'Ben Example', date: '2026-09-12T09:15:00Z', message: 'Merge pull request #42'},
|
||||
];
|
||||
const sampleRepoEntries = [
|
||||
{name: 'docs', path: 'src/docs', is_dir: true, size: null},
|
||||
{name: 'kiwix-serve.cpp', path: 'src/kiwix-serve.cpp', is_dir: false, size: 48_210},
|
||||
|
|
@ -1159,6 +1164,9 @@ export function ThemeSamplePage() {
|
|||
<RepoTreeTable path='src' entries={sampleRepoEntries} onOpenDirectory={() => null}
|
||||
onOpenFile={() => null}/>
|
||||
</div>
|
||||
<div style={{marginTop: 12}}>
|
||||
<RepoHistoryTable commits={sampleRepoCommits}/>
|
||||
</div>
|
||||
<div style={{marginTop: 12}}>
|
||||
<RepoSummary repo={sampleFailedRepo}/>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ async def post_repo(request: Request, body: schema.RepoCreateRequest):
|
|||
branch=body.branch or None,
|
||||
name=body.name or None,
|
||||
description=body.description or None,
|
||||
submodules=body.submodules,
|
||||
)
|
||||
repo = Repository.find_by_id(session, repo.id, options=Repository.json_options())
|
||||
return json_response(dict(repo=repo.__json__()), status=HTTPStatus.CREATED)
|
||||
|
|
@ -75,7 +76,7 @@ async def get_repo(request: Request, repo_id: int):
|
|||
async def put_repo(request: Request, repo_id: int, body: schema.RepoUpdateRequest):
|
||||
session = request.ctx.session
|
||||
lib.update_repository(session, repo_id, description=body.description, frequency=body.frequency,
|
||||
mode=body.mode, branch=body.branch)
|
||||
mode=body.mode, branch=body.branch, submodules=body.submodules)
|
||||
repo = Repository.find_by_id(session, repo_id, options=Repository.json_options())
|
||||
return json_response(dict(repo=repo.__json__()))
|
||||
|
||||
|
|
@ -108,3 +109,32 @@ async def get_repo_tree(request: Request, repo_id: int):
|
|||
repo = Repository.find_by_id(request.ctx.session, repo_id)
|
||||
tree = lib.list_repo_tree(repo, request.args.get('path', ''))
|
||||
return json_response(tree)
|
||||
|
||||
|
||||
@repos_bp.get('/<repo_id:int>/log')
|
||||
@openapi.definition(summary="The commits of a git Repo's checked out branch, newest first")
|
||||
@openapi.parameter('limit', int, 'query', description='At most 100', required=False)
|
||||
@openapi.parameter('offset', int, 'query', required=False)
|
||||
async def get_repo_log(request: Request, repo_id: int):
|
||||
repo = Repository.find_by_id(request.ctx.session, repo_id)
|
||||
try:
|
||||
limit = int(request.args.get('limit', 50))
|
||||
offset = int(request.args.get('offset', 0))
|
||||
except ValueError:
|
||||
raise ValidationError('limit and offset must be numbers')
|
||||
log = await lib.get_repo_log(repo, limit=limit, offset=offset)
|
||||
return json_response(log)
|
||||
|
||||
|
||||
@repos_bp.get('/<repo_id:int>/archive.zip')
|
||||
@openapi.definition(summary="Download a ZIP of a git Repo's checked out files")
|
||||
async def get_repo_archive(request: Request, repo_id: int):
|
||||
repo = Repository.find_by_id(request.ctx.session, repo_id)
|
||||
# Read everything from the database before the response starts; the request's session closes then.
|
||||
directory = lib.get_repo_root(repo)
|
||||
name = lib.repo_archive_name(repo)
|
||||
response = await request.respond(content_type='application/zip', headers={
|
||||
'Content-Disposition': f'attachment; filename="{name}.zip"',
|
||||
})
|
||||
await lib.stream_repo_archive(directory, name, response.send)
|
||||
await response.eof()
|
||||
|
|
|
|||
|
|
@ -44,6 +44,16 @@ class GitRemote:
|
|||
def head(self) -> str:
|
||||
return self.git('rev-parse', 'HEAD')
|
||||
|
||||
def add_submodule(self, path: str, submodule: 'GitRemote') -> str:
|
||||
"""Add `submodule` (at its current commit) at `path`, and commit it."""
|
||||
gitmodules = self.path / '.gitmodules'
|
||||
existing = gitmodules.read_text() if gitmodules.exists() else ''
|
||||
gitmodules.write_text(f'{existing}[submodule "{path}"]\n\tpath = {path}\n\turl = {submodule.url}\n')
|
||||
self.git('update-index', '--add', '--cacheinfo', f'160000,{submodule.head},{path}')
|
||||
self.git('add', '.gitmodules')
|
||||
self.git('commit', '--quiet', '-m', f'Add submodule {path}')
|
||||
return self.head
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def git_remote_factory(tmp_path_factory) -> Callable[..., GitRemote]:
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ class PreparedRepo:
|
|||
directory: pathlib.Path
|
||||
mode: str
|
||||
branch: Optional[str]
|
||||
submodules: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -50,6 +51,8 @@ class ExecutedRepo:
|
|||
size: int
|
||||
readme_path: Optional[str]
|
||||
readme_text: Optional[str]
|
||||
# The repo was updated, but its submodules were not.
|
||||
submodules_error: Optional[str] = None
|
||||
|
||||
|
||||
class GitCancelled(Exception):
|
||||
|
|
@ -76,7 +79,7 @@ class GitDownloader(Downloader):
|
|||
raise DownloadError(f'No Repo for this download, add it on the Repos page: {download.url}')
|
||||
directory = repo.collection.get_or_set_directory(session)
|
||||
return PreparedRepo(repository_id=repo.id, url=repo.url, directory=directory, mode=repo.mode,
|
||||
branch=repo.branch)
|
||||
branch=repo.branch, submodules=repo.submodules)
|
||||
|
||||
async def _git(self, download: Download, ctx: DownloadContext, cwd: pathlib.Path, *args,
|
||||
config: tuple = (), progress: bool = False, check: bool = True) -> str:
|
||||
|
|
@ -146,6 +149,33 @@ class GitDownloader(Downloader):
|
|||
await git('gc', '--prune=now', '--quiet',
|
||||
config=('gc.reflogExpire=now', 'gc.reflogExpireUnreachable=now'))
|
||||
|
||||
async def _update_submodules(self, download: Download, ctx: DownloadContext, prepared: PreparedRepo) \
|
||||
-> Optional[str]:
|
||||
"""Check out (or remove) the submodules of the checked out commit. Returns an error, if any.
|
||||
|
||||
Submodules are fetched with the same restrictions as the repo (`git_command` options are inherited by the
|
||||
git commands that git runs)."""
|
||||
directory = prepared.directory
|
||||
git = lambda *args, **kwargs: self._git(download, ctx, directory, *args, **kwargs) # noqa: E731
|
||||
if not prepared.submodules:
|
||||
if (directory / '.git/modules').is_dir():
|
||||
# Submodules were turned off; the repo is a mirror of only its own files now.
|
||||
await git('submodule', 'deinit', '--all', '--force', check=False)
|
||||
return None
|
||||
if not (directory / '.gitmodules').is_file():
|
||||
return None
|
||||
|
||||
args = ['submodule', 'update', '--init', '--recursive', '--force', '--progress']
|
||||
if prepared.mode == 'snapshot':
|
||||
args.extend(['--depth', '1'])
|
||||
try:
|
||||
await git('submodule', 'sync', '--recursive')
|
||||
await git(*args, progress=True)
|
||||
except DownloadError as e:
|
||||
logger.warning(f'Failed to update submodules of {prepared.url}', exc_info=e)
|
||||
return str(e)
|
||||
return None
|
||||
|
||||
async def _is_ancestor(self, download: Download, ctx: DownloadContext, directory: pathlib.Path,
|
||||
ancestor: str, descendant: str) -> bool:
|
||||
cmd = git_command('merge-base', '--is-ancestor', ancestor, descendant)
|
||||
|
|
@ -170,6 +200,7 @@ class GitDownloader(Downloader):
|
|||
await self._update(download, ctx, prepared, branch)
|
||||
else:
|
||||
await self._clone(download, ctx, prepared, branch)
|
||||
submodules_error = await self._update_submodules(download, ctx, prepared)
|
||||
|
||||
head = await self._git(download, ctx, directory, 'log', '-1', '--format=%H%x00%cI%x00%s')
|
||||
except GitCancelled as e:
|
||||
|
|
@ -190,6 +221,7 @@ class GitDownloader(Downloader):
|
|||
size=size,
|
||||
readme_path=readme_path,
|
||||
readme_text=readme_text,
|
||||
submodules_error=submodules_error,
|
||||
)
|
||||
|
||||
def finalize_download(self, session: Session, download: Download, executed: ExecutedRepo) -> DownloadResult:
|
||||
|
|
@ -207,6 +239,10 @@ class GitDownloader(Downloader):
|
|||
repo.readme_text = executed.readme_text
|
||||
repo.last_fetch = now()
|
||||
logger.info(f'Updated repo {repo.url} to {executed.head_sha}')
|
||||
if executed.submodules_error:
|
||||
# The repo is current, but the download is retried so its submodules are too.
|
||||
return DownloadResult(success=False, location=repo.location,
|
||||
error=f'The repo was updated, but its submodules were not: {executed.submodules_error}')
|
||||
return DownloadResult(success=True, location=repo.location)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ from sqlalchemy import func, text
|
|||
from sqlalchemy.orm import Session
|
||||
|
||||
from wrolpi import fts
|
||||
from wrolpi.cmd import GIT_BIN
|
||||
from wrolpi.cmd import GIT_BIN, run_command
|
||||
from wrolpi.collections.models import Collection
|
||||
from wrolpi.common import ConfigFile, get_media_directory, get_relative_to_media_directory, logger, \
|
||||
escape_file_name, background_task
|
||||
|
|
@ -31,8 +31,10 @@ 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', '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']
|
||||
'repo_destination_variables', 'is_valid_branch', 'read_readme_text', 'search_repos', 'count_repos',
|
||||
'search_repos_by_name', 'get_repo_log', 'get_repo_root', 'repo_archive_name', 'stream_repo_archive',
|
||||
'ReposConfig', 'repos_config', 'get_repos_config', 'save_repos_config', 'import_repos_config',
|
||||
'DEFAULT_REPO_FREQUENCY']
|
||||
|
||||
DEFAULT_REPO_FREQUENCY = DownloadFrequency.weekly.value
|
||||
|
||||
|
|
@ -283,7 +285,7 @@ def _validate_frequency(frequency: int):
|
|||
|
||||
def create_repository(session: Session, url: str, tag_name: str = None, frequency: int = DEFAULT_REPO_FREQUENCY,
|
||||
mode: str = 'full', branch: str = None, name: str = None, description: str = None,
|
||||
directory: pathlib.Path = None) -> Repository:
|
||||
directory: pathlib.Path = None, submodules: bool = False) -> Repository:
|
||||
"""Create a Repo (Collection + Repository + recurring Download). The download clones it."""
|
||||
parsed = parse_repo_url(url)
|
||||
_validate_mode(mode)
|
||||
|
|
@ -305,7 +307,7 @@ 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=collection)
|
||||
submodules=bool(submodules), collection=collection)
|
||||
repo.update_search_name()
|
||||
session.add(repo)
|
||||
session.flush([repo])
|
||||
|
|
@ -327,7 +329,7 @@ def create_repository(session: Session, url: str, tag_name: str = None, frequenc
|
|||
|
||||
|
||||
def update_repository(session: Session, repo_id: int, description: str = None, frequency: int = None,
|
||||
mode: str = None, branch: str = None) -> Repository:
|
||||
mode: str = None, branch: str = None, submodules: bool = None) -> Repository:
|
||||
"""Change a Repo's settings. An empty `branch` follows the remote's default branch."""
|
||||
repo = Repository.find_by_id(session, repo_id)
|
||||
if description is not None:
|
||||
|
|
@ -339,6 +341,8 @@ def update_repository(session: Session, repo_id: int, description: str = None, f
|
|||
branch = branch.strip() or None
|
||||
_validate_branch(branch)
|
||||
repo.branch = branch
|
||||
if submodules is not None:
|
||||
repo.submodules = bool(submodules)
|
||||
if frequency is not None:
|
||||
_validate_frequency(frequency)
|
||||
if download := repo.download:
|
||||
|
|
@ -474,6 +478,73 @@ async def search_repos_by_name(session: Session, name: str, limit: int = 5) -> L
|
|||
return [dict(id=i.id, name=i.name, tag_name=i.tag_name, location=i.location) for i in repos]
|
||||
|
||||
|
||||
# Fields of one commit, and the end of a commit, in `git log` output.
|
||||
LOG_FIELD, LOG_RECORD = '\x1f', '\x1e'
|
||||
LOG_FORMAT = LOG_FIELD.join(('%H', '%an', '%cI', '%s')) + LOG_RECORD
|
||||
MAXIMUM_LOG_LIMIT = 100
|
||||
|
||||
|
||||
def get_repo_root(repo: Repository) -> pathlib.Path:
|
||||
directory = repo.directory
|
||||
if not repo.head_sha or not directory or not (directory / '.git').exists():
|
||||
raise UnknownDirectory('Repo has not been downloaded')
|
||||
return directory
|
||||
|
||||
|
||||
async def _git_output(directory: pathlib.Path, *args) -> Optional[str]:
|
||||
"""Run a read-only git command in a Repo; None when it fails."""
|
||||
result = await run_command(git_command(*args), cwd=directory, timeout=60, env=git_env(), log_command=False)
|
||||
if result.return_code != 0:
|
||||
logger.warning(f'git {args[0]} failed in {directory}: {result.stderr.decode(errors="replace")}')
|
||||
return None
|
||||
return result.stdout.decode(errors='replace')
|
||||
|
||||
|
||||
async def get_repo_log(repo: Repository, limit: int = 50, offset: int = 0) -> dict:
|
||||
"""The commits of the checked out branch, newest first: {commits: [{sha, author, date, message}], total}."""
|
||||
directory = get_repo_root(repo)
|
||||
limit = min(max(int(limit), 1), MAXIMUM_LOG_LIMIT)
|
||||
offset = max(int(offset), 0)
|
||||
|
||||
output = await _git_output(directory, 'log', f'--max-count={limit}', f'--skip={offset}',
|
||||
f'--format={LOG_FORMAT}', 'HEAD', '--')
|
||||
total = await _git_output(directory, 'rev-list', '--count', 'HEAD', '--')
|
||||
commits = []
|
||||
for record in (output or '').split(LOG_RECORD):
|
||||
record = record.strip('\n')
|
||||
if not record:
|
||||
continue
|
||||
sha, author, date, message = record.split(LOG_FIELD, 3)
|
||||
commits.append(dict(sha=sha, author=author, date=date, message=message))
|
||||
return dict(commits=commits, total=int(total.strip()) if total else len(commits))
|
||||
|
||||
|
||||
def repo_archive_name(repo: Repository) -> str:
|
||||
"""The name of a Repo's ZIP (without `.zip`), safe for a header and as the directory in the ZIP."""
|
||||
name = re.sub(r'[^A-Za-z0-9._-]+', '_', repo.name or 'repo').strip('._') or 'repo'
|
||||
return f'{name}-{repo.head_sha[:7]}' if repo.head_sha else name
|
||||
|
||||
|
||||
async def stream_repo_archive(directory: pathlib.Path, name: str, send) -> None:
|
||||
"""Stream a ZIP of the checked out commit of the repo in `directory` to `send` (an async callable taking
|
||||
bytes). The ZIP's files are in the directory `name`.
|
||||
|
||||
Takes no Repository: the request's session is closed once a streamed response starts. git writes the ZIP as
|
||||
it reads the repo, so a large repo is never held in memory."""
|
||||
cmd = git_command('archive', '--format=zip', f'--prefix={name}/', 'HEAD')
|
||||
proc = await asyncio.create_subprocess_exec(*cmd, cwd=directory, env=git_env(), stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.DEVNULL)
|
||||
try:
|
||||
while chunk := await proc.stdout.read(64 * 1024):
|
||||
await send(chunk)
|
||||
await proc.wait()
|
||||
finally:
|
||||
if proc.returncode is None:
|
||||
# The client went away.
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
|
||||
|
||||
@dataclass
|
||||
class RepoTreeEntry:
|
||||
name: str
|
||||
|
|
@ -547,6 +618,7 @@ class ReposConfig(ConfigFile):
|
|||
tag_name: software
|
||||
mode: full
|
||||
branch: null
|
||||
submodules: false
|
||||
frequency: 604800
|
||||
"""
|
||||
file_name = 'repos.yaml'
|
||||
|
|
@ -623,7 +695,7 @@ class ReposConfig(ConfigFile):
|
|||
if not repo:
|
||||
return create_repository(session, parsed.url, tag_name=tag_name, frequency=frequency, mode=mode,
|
||||
branch=data.get('branch'), name=name, description=data.get('description'),
|
||||
directory=directory)
|
||||
directory=directory, submodules=bool(data.get('submodules')))
|
||||
|
||||
collection = repo.collection
|
||||
collection.name = name
|
||||
|
|
@ -633,6 +705,7 @@ class ReposConfig(ConfigFile):
|
|||
if directory:
|
||||
collection.directory = directory
|
||||
repo.mode = mode
|
||||
repo.submodules = bool(data.get('submodules'))
|
||||
branch = data.get('branch') or None
|
||||
_validate_branch(branch)
|
||||
repo.branch = branch
|
||||
|
|
@ -660,6 +733,7 @@ class ReposConfig(ConfigFile):
|
|||
description=repo.collection.description,
|
||||
mode=repo.mode,
|
||||
branch=repo.branch,
|
||||
submodules=repo.submodules,
|
||||
frequency=download.frequency if download else None,
|
||||
)
|
||||
data.append(entry)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import pathlib
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger, Text
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger, Text, Boolean, false
|
||||
from sqlalchemy.orm import relationship, Session, joinedload, selectinload, deferred
|
||||
|
||||
from wrolpi.collections.models import Collection
|
||||
|
|
@ -31,6 +31,8 @@ class Repository(ModelHelper, Base):
|
|||
mode = Column(String, nullable=False, default='full')
|
||||
# The branch to check out; None follows the remote's default branch.
|
||||
branch = Column(String)
|
||||
# Also download the repo's submodules.
|
||||
submodules = Column(Boolean, nullable=False, default=False, server_default=false())
|
||||
default_branch = Column(String)
|
||||
head_sha = Column(String)
|
||||
head_date = Column(TZDateTime)
|
||||
|
|
@ -99,6 +101,7 @@ class Repository(ModelHelper, Base):
|
|||
'owner': self.owner,
|
||||
'mode': self.mode,
|
||||
'branch': self.branch,
|
||||
'submodules': self.submodules,
|
||||
'default_branch': self.default_branch,
|
||||
'head_sha': self.head_sha,
|
||||
'head_date': self.head_date,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ class RepoCreateRequest:
|
|||
branch: Optional[str] = None
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
submodules: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -27,3 +28,4 @@ class RepoUpdateRequest:
|
|||
frequency: Optional[int] = None
|
||||
mode: Optional[str] = None
|
||||
branch: Optional[str] = None
|
||||
submodules: Optional[bool] = None
|
||||
|
|
|
|||
|
|
@ -18,9 +18,10 @@ async def test_dump_and_import(test_session, test_directory, async_client, test_
|
|||
assert config.get_file().is_file()
|
||||
assert config.repos == [
|
||||
dict(name='b', url='https://github.com/a/b', directory='repos/b', tag_name=None, description=None,
|
||||
mode='snapshot', branch='dev', frequency=DownloadFrequency.weekly),
|
||||
mode='snapshot', branch='dev', submodules=False, frequency=DownloadFrequency.weekly),
|
||||
dict(name='kiwix-tools', url='https://github.com/kiwix/kiwix-tools', directory='repos/software/kiwix-tools',
|
||||
tag_name='software', description='Tools', mode='full', branch=None, frequency=DownloadFrequency.daily),
|
||||
tag_name='software', description='Tools', mode='full', branch=None, submodules=False,
|
||||
frequency=DownloadFrequency.daily),
|
||||
]
|
||||
|
||||
# Lose the database.
|
||||
|
|
|
|||
186
modules/repos/test/test_extras.py
Normal file
186
modules/repos/test/test_extras.py
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
import io
|
||||
import subprocess
|
||||
import zipfile
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
from mock import mock
|
||||
|
||||
from modules.repos import lib
|
||||
from modules.repos.models import Repository
|
||||
from wrolpi.downloader import Download, DownloadStatus
|
||||
|
||||
|
||||
def git(directory, *args) -> str:
|
||||
return subprocess.run(['git', '-c', 'safe.directory=*', *args], cwd=directory, check=True,
|
||||
capture_output=True).stdout.decode().strip()
|
||||
|
||||
|
||||
async def update(test_session, repos_download_manager):
|
||||
download = test_session.query(Download).one()
|
||||
download.renew()
|
||||
test_session.commit()
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
test_session.expire_all()
|
||||
return test_session.query(Download).one()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_log(test_session, async_client, git_remote_factory, repos_download_manager):
|
||||
"""The history of the checked out branch, newest first, a page at a time."""
|
||||
remote = git_remote_factory()
|
||||
second = remote.commit({'a.txt': 'a'}, 'Second')
|
||||
third = remote.commit({'b.txt': 'b'}, 'Third: with a | and a\ttab')
|
||||
repo = lib.create_repository(test_session, remote.url)
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
|
||||
request, response = await async_client.get(f'/api/repos/{repo.id}/log?limit=2')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['total'] == 3
|
||||
assert [(i['sha'], i['message']) for i in response.json['commits']] == \
|
||||
[(third, 'Third: with a | and a\ttab'), (second, 'Second')]
|
||||
assert response.json['commits'][0]['author'] == 'WROLPi Test'
|
||||
assert response.json['commits'][0]['date']
|
||||
|
||||
request, response = await async_client.get(f'/api/repos/{repo.id}/log?limit=2&offset=2')
|
||||
assert [i['message'] for i in response.json['commits']] == ['Initial commit']
|
||||
|
||||
request, response = await async_client.get(f'/api/repos/{repo.id}/log?limit=nope')
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_log_not_downloaded(test_session, async_client, test_wrolpi_config):
|
||||
repo = lib.create_repository(test_session, 'https://github.com/a/b')
|
||||
request, response = await async_client.get(f'/api/repos/{repo.id}/log')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
request, response = await async_client.get(f'/api/repos/{repo.id}/archive.zip')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive(test_session, async_client, git_remote_factory, repos_download_manager):
|
||||
"""A ZIP of the checked out commit; local changes and `.git` are not in it."""
|
||||
remote = git_remote_factory(files={'README.md': '# Example', 'src/main.c': 'int main;'})
|
||||
repo = lib.create_repository(test_session, remote.url, name='my "repo"\r\nX-Evil: 1')
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
test_session.expire_all()
|
||||
(repo.directory / 'untracked.txt').write_text('local')
|
||||
|
||||
request, response = await async_client.get(f'/api/repos/{repo.id}/archive.zip')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.headers['content-type'] == 'application/zip'
|
||||
# The name is safe in a header.
|
||||
name = f'my_repo_X-Evil_1-{repo.head_sha[:7]}'
|
||||
assert response.headers['content-disposition'] == f'attachment; filename="{name}.zip"'
|
||||
assert 'x-evil' not in response.headers
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
|
||||
assert sorted(archive.namelist()) == [f'{name}/', f'{name}/README.md', f'{name}/src/', f'{name}/src/main.c']
|
||||
assert archive.read(f'{name}/src/main.c') == b'int main;'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submodules(test_session, git_remote_factory, repos_download_manager):
|
||||
"""Submodules are only downloaded when the Repo asks for them, and are removed when it no longer does."""
|
||||
library = git_remote_factory('library', files={'lib.c': 'v1'})
|
||||
remote = git_remote_factory()
|
||||
remote.add_submodule('vendor/library', library)
|
||||
|
||||
repo = lib.create_repository(test_session, remote.url)
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
submodule = repo.directory / 'vendor/library'
|
||||
assert not (submodule / 'lib.c').exists()
|
||||
|
||||
lib.update_repository(test_session, repo.id, submodules=True)
|
||||
download = await update(test_session, repos_download_manager)
|
||||
assert download.status == DownloadStatus.complete
|
||||
assert (submodule / 'lib.c').read_text() == 'v1'
|
||||
# The submodule has its history, like the Repo.
|
||||
assert git(submodule, 'rev-list', '--count', 'HEAD') == '1'
|
||||
|
||||
# A new submodule commit is checked out when the Repo points at it.
|
||||
library.commit({'lib.c': 'v2'}, 'v2')
|
||||
remote.git('update-index', '--cacheinfo', f'160000,{library.head},vendor/library')
|
||||
remote.git('commit', '--quiet', '-m', 'Bump library')
|
||||
await update(test_session, repos_download_manager)
|
||||
assert (submodule / 'lib.c').read_text() == 'v2'
|
||||
|
||||
lib.update_repository(test_session, repo.id, submodules=False)
|
||||
await update(test_session, repos_download_manager)
|
||||
assert not (submodule / 'lib.c').exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submodule_failure(test_session, git_remote_factory, repos_download_manager):
|
||||
"""A submodule which cannot be downloaded (e.g. an ssh URL) does not stop the Repo from updating."""
|
||||
library = git_remote_factory('library')
|
||||
remote = git_remote_factory()
|
||||
remote.add_submodule('vendor/library', library)
|
||||
# Rewrite the submodule's URL to one git may not use.
|
||||
(remote.path / '.gitmodules').write_text(
|
||||
'[submodule "vendor/library"]\n\tpath = vendor/library\n\turl = ssh://git@git.example.com/owner/library\n')
|
||||
(remote.path / 'new.txt').write_text('new')
|
||||
# Not `remote.commit`, whose `add --all` would delete the submodule (it is not checked out in the remote).
|
||||
remote.git('add', '.gitmodules', 'new.txt')
|
||||
remote.git('commit', '--quiet', '-m', 'ssh submodule')
|
||||
head = remote.head
|
||||
|
||||
repo = lib.create_repository(test_session, remote.url, submodules=True)
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
test_session.expire_all()
|
||||
|
||||
download = test_session.query(Download).one()
|
||||
assert download.status == DownloadStatus.deferred
|
||||
assert 'its submodules were not' in download.error
|
||||
# The Repo itself is current.
|
||||
assert repo.head_sha == head
|
||||
assert (repo.directory / 'new.txt').is_file()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submodules_api_and_config(test_session, async_client, test_wrolpi_config, await_switches):
|
||||
body = '{"url": "https://github.com/a/b", "submodules": true}'
|
||||
request, response = await async_client.post('/api/repos', content=body)
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
assert response.json['repo']['submodules'] is True
|
||||
repo_id = response.json['repo']['id']
|
||||
|
||||
await await_switches()
|
||||
assert lib.get_repos_config().repos[0]['submodules'] is True
|
||||
|
||||
request, response = await async_client.put(f'/api/repos/{repo_id}', content='{"submodules": false}')
|
||||
assert response.json['repo']['submodules'] is False
|
||||
|
||||
# Restored from the config.
|
||||
config = lib.get_repos_config()
|
||||
data = config.read_config_file()
|
||||
data['repos'][0]['submodules'] = True
|
||||
data['version'] += 1
|
||||
config.write_config_data(data, config.get_file())
|
||||
config.import_config()
|
||||
test_session.expire_all()
|
||||
assert test_session.query(Repository).one().submodules is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_after_session_closes(test_session, async_client, git_remote_factory, repos_download_manager):
|
||||
"""In production the request's session is closed once a streamed response starts; the ZIP must not need it."""
|
||||
from sanic import Request
|
||||
|
||||
remote = git_remote_factory()
|
||||
repo = lib.create_repository(test_session, remote.url)
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
|
||||
original_respond = Request.respond
|
||||
|
||||
async def respond_and_close_session(self, *args, **kwargs):
|
||||
response = await original_respond(self, *args, **kwargs)
|
||||
test_session.expunge_all()
|
||||
return response
|
||||
|
||||
with mock.patch.object(Request, 'respond', respond_and_close_session):
|
||||
request, response = await async_client.get(f'/api/repos/{repo.id}/archive.zip')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
|
||||
assert any(i.endswith('/README.md') for i in archive.namelist())
|
||||
|
|
@ -151,21 +151,24 @@ def test_read_readme_text_refuses_symlinks(tmp_path):
|
|||
|
||||
|
||||
@pytest.mark.parametrize('text', [
|
||||
'|' + ' ' * 100_000 + 'x',
|
||||
'-' * 100_000 + 'x',
|
||||
'<!--' * 25_000,
|
||||
'![' * 50_000,
|
||||
'[' * 50_000 + '(' * 50_000,
|
||||
'<' * 100_000,
|
||||
'\n' + ' \n' * 50_000 + 'x',
|
||||
'#' * 100_000,
|
||||
'> ' * 50_000,
|
||||
pytest.param('|' + ' ' * 100_000 + 'x', id='table-spaces'),
|
||||
pytest.param('-' * 100_000 + 'x', id='dashes'),
|
||||
pytest.param('<!--' * 25_000, id='unclosed-comments'),
|
||||
pytest.param('![' * 50_000, id='image-brackets'),
|
||||
pytest.param('[' * 50_000 + '(' * 50_000, id='link-brackets'),
|
||||
pytest.param('<' * 100_000, id='angles'),
|
||||
pytest.param('\n' + ' \n' * 50_000 + 'x', id='blank-lines'),
|
||||
pytest.param('#' * 100_000, id='hashes'),
|
||||
pytest.param('> ' * 50_000, id='quotes'),
|
||||
])
|
||||
def test_markdown_to_text_is_linear(text):
|
||||
"""A README is untrusted; converting the largest README must never take long."""
|
||||
"""A README is untrusted; converting the largest README must never take long.
|
||||
|
||||
Each case takes milliseconds; the patterns this replaced took minutes. The bound is loose so a busy machine
|
||||
does not fail it."""
|
||||
start = time.monotonic()
|
||||
lib.markdown_to_text(text)
|
||||
assert time.monotonic() - start < 1
|
||||
assert time.monotonic() - start < 5
|
||||
|
||||
|
||||
def test_markdown_to_text():
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue