my eye

__init__.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
"""
Manage code on your website.

- Implements [PEP 503 -- Simple Repository API][0] managing Python packages.

[0]: https://www.python.org/dev/peps/pep-0503/

"""

# TODO PEP 592 -- Adding "Yank" Support to the Simple API
# TODO PEP 658 -- Serve Distribution Metadata in the Simple Repository API

import os
import pathlib
import random
import re
import shutil
import string
import subprocess
import time

import gmpg
import pkg_resources
import semver
import web
import webagt
from RestrictedPython import (
    compile_restricted,
    limited_builtins,
    safe_builtins,
    utility_builtins,
)
from RestrictedPython.Eval import (
    default_guarded_getattr,
    default_guarded_getitem,
    default_guarded_getiter,
)
from RestrictedPython.PrintCollector import PrintCollector

app = web.application(
    __name__,
    prefix="code",
    args={
        "project": r"[A-Za-z0-9\.-][A-Za-z0-9\._-]+",
        "commit_id": r"[a-f0-9]{3,40}",
        "release": r"((\d+\.)?\d+\.)?\d+",
        "filename": r"[\w./\-]+",
        "package": r"[\w.-]+",
        "namespace": r"[\w._/]+",
    },
    model={
        "projects": {
            "name": "TEXT UNIQUE",
            "pypi": "TEXT UNIQUE",
            "visibility": "TEXT",
        },
        "packages": {
            "project_id": "INTEGER",
            "filename": "TEXT",
            "author": "TEXT",
            "author_email": "TEXT",
            "classifiers": "JSON",
            "home_page": "TEXT",
            "keywords": "JSON",
            "license": "TEXT",
            "project_urls": "JSON",
            "requires_dist": "JSON",
            "requires_python": "TEXT",
            "sha256_digest": "TEXT",
            "summary": "TEXT",
            "version": "TEXT",
        },
    },
)

code_dir = pathlib.Path("code/meta")


def run_ci(project):
    """
    Run continuous integration pipeline.

    Execute tests.

    """
    project_dir = code_dir / project
    testing_dir = project_dir / "testing"
    shutil.rmtree(testing_dir, ignore_errors=True)
    gmpg.clone_repo(project_dir / "source.git", testing_dir)
    admin_home = "/home/admin"
    env = os.environ.copy()
    env["HOME"] = admin_home
    print(
        subprocess.run(
            [f"{admin_home}/bin/act", "--artifact-server-path", "artifacts"],
            cwd=testing_dir,
            env=env,
        )
    )
    for artifact in (testing_dir / "artifacts/1/analysis").iterdir():
        shortened = artifact.name[:-2]
        artifact.rename(testing_dir / shortened)
        subprocess.run(["gunzip", shortened], cwd=testing_dir)
    with (testing_dir / "deps.svg").open("r+") as fp:
        deps_graph = fp.read()
        fp.seek(0)
        fp.write(deps_graph.replace("black", "#586e75").replace("white", "#002b36"))
        fp.truncate()


def get_package_releases(project):
    versions = list(
        reversed(
            sorted(
                app.model.get_package_versions(project),
                key=semver.parse_version_info,
            )
        )
    )
    return [
        (
            version,
            web.application("webint_posts").model.read(
                f"code/projects/{project}/releases/{version}"
            )["resource"],
        )
        for version in versions
    ]


@app.query
def search(db, query):
    """Search for `query` in commited code."""
    files = {}
    context = "2"
    for file in (
        subprocess.run(
            [
                "ag",
                "--ackmate",
                "-B",
                context,
                "-A",
                context,
                "-G",
                ".*/working",
                query,
            ],
            cwd=code_dir,
            capture_output=True,
        )
        .stdout.decode()
        .split("\n\n")
    ):
        filename, _, blocks_text = file.partition("\n")
        blocks = {}
        for block_text in blocks_text.split("\n--\n"):
            starting_line = block_text.partition(":")[0].partition(";")[0]
            block = "\n".join(
                [line.partition(":")[2] for line in block_text.splitlines()]
            )
            blocks[starting_line] = block
        files[filename.lstrip(":").partition("/working/")[::2]] = blocks
    return files


@app.query
def create_project(db, name):
    """Create a project."""
    db.insert("projects", name=name, pypi=name, visibility="public")
    project_dir = code_dir / name
    bare_repo = project_dir / "source.git"
    working_repo = project_dir / "working"
    repo = gmpg.get_repo(bare_repo, init=True, bare=True)
    repo.update_server_info()
    repo.config("http.receivepack", "true")
    post_receive_hook = bare_repo / "hooks/post-receive"
    with post_receive_hook.open("w") as fp:
        fp.write(
            "\n".join(
                (
                    "#!/bin/sh",
                    "git -C $PWD/../working --git-dir=.git pull origin main --rebase",
                    f"wget --method=post -qO- {web.tx.origin}/code/projects/{name}",
                )
            )
        )
    gmpg.clone_repo(bare_repo, working_repo)
    subprocess.run(["chmod", "775", post_receive_hook])
    subprocess.run(["chgrp", "www-data", bare_repo, working_repo, "-R"])
    subprocess.run(["chmod", "g+w", bare_repo, working_repo, "-R"])
    if not (code_dir / "gitpasswd").exists():
        token = web.application("webint_auth").model.generate_local_token(
            "/code", "webint_code", "git_owner"
        )
        subprocess.run(["htpasswd", "-cb", code_dir / "gitpasswd", "owner", token])
    web.application("webint_posts").model.create(
        "entry",
        url=f"/code/projects/{name}",
        content=(
            f"Created repository <a href=/code/projects/{name}><code>{name}</code></a>"
        ),
    )


@app.query
def get_projects(db):
    """Return a list of project names."""
    visibility_wheres = ["public"]
    if web.tx.user.is_owner:
        visibility_wheres.extend(["protected", "private"])
    return [
        r["name"]
        for r in db.select(
            "projects",
            what="name",
            order="name",
            where=" OR ".join(len(visibility_wheres) * ["visibility = ?"]),
            vals=visibility_wheres,
        )
    ]


@app.query
def get_pypi_projects(db):
    """Return a list of PyPI project names."""
    return [r["pypi"] for r in db.select("projects", what="pypi", order="name")]


@app.query
def get_project_from_name(db, name):
    """Return the project associated with project name."""
    try:
        return db.select("projects", where="name = ?", vals=[name])[0]
    except IndexError:
        return None


@app.query
def get_project_from_pypi_name(db, pypi_name):
    """Return the project name associated with pypi package name."""
    try:
        return db.select("projects", where="pypi = ?", vals=[pypi_name])[0]
    except IndexError:
        return None


@app.query
def create_package(db, form):
    """Create a project."""
    project_id = db.select(
        "projects", what="rowid, name", where="pypi = ?", vals=[form.name]
    )[0]["rowid"]
    return db.insert(
        "packages",
        project_id=project_id,
        filename=form.content.fileobj.filename,
        author=form.author,
        author_email=form.author_email,
        # classifiers=form.classifiers,
        home_page=form.home_page,
        # keywords=form.keywords.split(","),
        license=form.license,
        # project_urls=form.project_urls if "project_urls" in form else [],
        # requires_dist=form.requires_dist,
        requires_python=form.requires_python,
        sha256_digest=form.sha256_digest,
        summary=form.summary,
        version=form.version,
    )


@app.query
def get_packages(db, project):
    """Return a list of packages for given project."""
    return db.select(
        "packages",
        join="""projects ON packages.project_id = projects.rowid""",
        where="projects.pypi = ?",
        vals=[project],
    )


@app.query
def get_package_versions(db, project):
    """Return a list of packages for given project."""
    return [
        r["version"]
        for r in db.select(
            "packages",
            what="DISTINCT version",
            join="""projects ON packages.project_id = projects.rowid""",
            where="projects.name = ?",
            vals=[project],
            order="version",
        )
    ]


@app.control("")
class Code:
    """Code index."""

    def get(self):
        """Return a list of projects."""
        return app.view.index(
            None,  # get_versions("webint"),
            web.get_apps(),
            app.model.get_projects(),
        )


@app.control("snippets")
class Snippets:
    """Code snippets."""

    def get(self):
        return ""

    def post(self):
        code = web.form("code").code
        builtins = dict(safe_builtins)
        builtins.update(**limited_builtins)
        builtins.update(**utility_builtins)
        env = {
            "__builtins__": builtins,
            "_getiter_": default_guarded_getiter,
            "_getattr_": default_guarded_getattr,
            "_getitem_": default_guarded_getitem,
            "_print_": PrintCollector,
        }
        secret = "".join(random.choices(string.ascii_lowercase, k=20))
        try:
            exec(
                compile_restricted(f"{code}\n{secret} = printed", "<string>", "exec"),
                env,
            )
        except Exception as err:
            result = err.args[0]
        else:
            result = env[secret]
        return app.view.snippets.snippet(code, result)


@app.control("projects")
class Projects:
    """List of projects."""

    owner_only = ["post"]

    def get(self):
        """Return a list of projects."""
        return app.view.projects(app.model.get_projects())

    def post(self):
        """Create a project."""
        project = web.form("project").project
        app.model.create_project(project)
        return web.Created(app.view.project.created(project), f"/{project}")


@app.control("projects/{project}")
class Project:
    """Project index."""

    def get(self, project):
        """Return details about the project."""
        mentions = web.application(
            "webint_mentions"
        ).model.get_received_mentions_by_target(
            f"{web.tx.origin}/{web.tx.request.uri.path}"
        )
        project_dir = code_dir / project
        try:
            with (project_dir / "working" / "README.md").open() as fp:
                readme = fp.read()
        except FileNotFoundError:
            readme = None
        try:
            pyproject = gmpg.get_current_project(project_dir / "testing")
        except FileNotFoundError:
            pyproject = None
        testing_dir = project_dir / "testing"
        try:
            api_python = web.load(path=testing_dir / "api_python.json")
        except FileNotFoundError:
            api_python = {}
        try:
            test_results = gmpg.analysis._parse_junit(testing_dir / "test_results.xml")
        except FileNotFoundError:
            test_results = {}
        try:
            test_coverage = gmpg.analysis._parse_coverage(
                testing_dir / "test_coverage.xml"
            )
        except FileNotFoundError:
            test_coverage = {}
        return app.view.project.index(
            project,
            gmpg.get_repo(project_dir / "working"),
            readme,
            get_package_releases(project),
            pyproject,
            api_python,
            test_results,
            test_coverage,
            mentions,
        )

    def post(self, project):
        web.enqueue(run_ci, project)
        return "CI enqueued"

    def delete(self, project):
        """Delete the project."""
        return "deleted"


@app.control("projects/{project}.git")
class ProjectGitRedirect:
    """Project .git redirect."""

    def get(self, project):
        """Redirect to main project index."""
        raise web.SeeOther(project)


@app.control("projects/{project}/api/{namespace}.svg")
class ProjectAPIDeps:
    """Project's API in JSON."""

    def get(self, project, namespace):
        """Return the API's JSON."""
        return code_dir / project / "testing" / "deps.svg"


@app.control("projects/{project}/api/{namespace}")
class ProjectAPINamespace:
    """Project's API namespace."""

    def get(self, project, namespace):
        """Return the API's namespace."""
        details = web.load(path=code_dir / project / "testing" / "api_python.json")
        return app.view.project.namespace(project, namespace, details)


@app.control("projects/{project}/api.json")
class ProjectAPIJSON:
    """Project's API in JSON."""

    def get(self, project):
        """Return the API's JSON."""
        return code_dir / project / "testing" / "api_python.json"


@app.control("projects/{project}/settings")
class ProjectSettings:
    """Project settings."""

    def get(self, project):
        """Return settings for the project."""
        return app.view.project.settings(project)

    def post(self, project):
        form = web.form("visibility")
        return form.visibility


@app.control("projects/{project}/files(/{filename})?")
class ProjectRepoFile:
    """A file in a project's repository."""

    def get(self, project, filename=""):
        """Return a view of the repository's file."""
        project_dir = code_dir / project
        filepath = project_dir / "working" / filename
        try:
            with filepath.open() as fp:
                content = fp.read()
        except IsADirectoryError:
            content = filepath.iterdir()
        except UnicodeDecodeError:
            content = None
        testing_dir = project_dir / "testing"
        try:
            test_coverage = gmpg.analysis._parse_coverage(
                testing_dir / "test_coverage.xml"
            )[filename][1]
        except (FileNotFoundError, KeyError):
            test_coverage = None
        return app.view.project.repository_file(
            project, filename, content, test_coverage
        )


@app.control("projects/{project}/raw(/{filename})?")
class ProjectRepoRawFile:
    """A file in a project's repository."""

    def get(self, project, filename=""):
        """Return a view of the repository's file."""
        return code_dir / project / "working" / filename


@app.control("projects/{project}/commits")
class ProjectCommitLog:
    """A commit log of a project's repository."""

    def get(self, project):
        """Return a view of the repository's commit."""
        repo = gmpg.get_repo(code_dir / project / "working")
        return app.view.project.commit_log(project, repo)


@app.control("projects/{project}/commits/{commit_id}")
class ProjectCommit:
    """A commit to a project's repository."""

    def get(self, project, commit_id=None):
        """Return a view of the repository's commit."""
        repo = gmpg.get_repo(code_dir / project / "working")
        full_commit_id = repo.git("rev-parse", commit_id)[0]
        if commit_id != full_commit_id:
            raise web.SeeOther(f"/code/projects/{project}/commits/{full_commit_id}")
        return app.view.project.commit(project, repo, commit_id)


@app.control("projects/{project}/releases")
class ProjectReleases:
    """A project's release."""

    def get(self, project):
        """Return a view of the package file."""
        return f"releases for {project}"
        # files = sorted((code_dir / project / "releases" / release).iterdir())
        # return app.view.project.release(project, release, files)


@app.control("projects/{project}/releases/{release}")
class ProjectRelease:
    """A project's release."""

    def get(self, project, release):
        """Return a view of the package file."""
        pypi_name = app.model.get_project_from_name(project)["pypi"].replace("-", "_")
        files = sorted(
            (code_dir / project / "releases" / f"{pypi_name}-{release}").iterdir()
        )

        package_releases = get_package_releases(project)
        previous_release = None
        for package_release, _ in reversed(package_releases):
            if release == package_release:
                break
            previous_release = package_release
        next_release = None
        for package_release, _ in package_releases:
            if release == package_release:
                break
            next_release = package_release
        repo = gmpg.get_repo(code_dir / project / "source.git")
        log = None
        if previous_release:
            log = repo.log(f"{previous_release}..{release}")
        return app.view.project.release(
            project,
            release,
            files,
            log,
            previous_release,
            next_release,
        )


@app.control("projects/{project}/releases/{release}/files(/{filename})?")
class ProjectReleaseFile:
    """A file in a project's release."""

    def get(self, project, release, filename=""):
        """Return a view of the release's file."""
        pypi_name = app.model.get_project_from_name(project)["pypi"].replace("-", "_")
        filepath = code_dir / project / "releases" / f"{pypi_name}-{release}" / filename
        try:
            with filepath.open() as fp:
                content = fp.read()
        except IsADirectoryError:
            content = filepath.iterdir()
        return app.view.project.release_file(project, release, filename, content)


@app.control("projects/{project}/issues")
class ProjectIssues:
    """A project's issues."""

    def get(self, project):
        """Return a view of the package's issues."""
        mentions = web.application(
            "webint_mentions"
        ).model.get_received_mentions_by_target(
            f"{web.tx.origin}/{web.tx.request.uri.path}"
        )
        return [dict(r) for r in mentions]
        # files = sorted((code_dir / project / "releases" / release).iterdir())
        # return app.view.project.release(project, release, files)


def split_release(release) -> tuple:
    """Return a 4-tuple of the parts in given `release` (eg foo-1.2.3 -> foo,1,2,3)."""
    if match := re.match(r"([\w.-]+)\-(\d+\.\d+\.\d+.*)", release):
        return match.groups()
    return ()


@app.control("pypi")
class PyPIIndex:
    """PyPI repository in Simple Repository format."""

    # TODO owner_only = ["post"]

    def get(self):
        """Return a view of the simplified list of projects in repository."""
        return app.view.pypi.index(app.model.get_pypi_projects())

    def post(self):
        """Accept PyPI package upload."""
        form = web.form(":action")
        if form[":action"] not in ("sig_upload", "file_upload"):
            raise web.BadRequest(f"Provided `:action={form[':action']}` not supported.")
        try:
            release_file = form.content.save(file_dir="/tmp")
        except FileExistsError:
            return
        release_name, release_remaining = split_release(release_file.name)
        project = app.model.get_project_from_pypi_name(
            release_name.replace("_", "-").replace(".", "-")
        )
        releases_dir = code_dir / project["name"] / "releases"
        releases_dir.mkdir(exist_ok=True)
        release_file = release_file.replace(
            releases_dir / f"{release_name}-{release_remaining}"
        )
        if release_file.suffix == ".asc":
            upload_type = "signature"
            suffix = ".asc"
        else:
            upload_type = "package"
            suffix = ""
            if release_file.suffix == ".gz":
                subprocess.run(
                    [
                        "tar",
                        "xf",
                        release_file.name,
                    ],
                    cwd=releases_dir,
                )
                project_prefix = f"/code/projects/{project['name']}"
                release_version = release_remaining.removesuffix(".tar.gz")
                web.application("webint_posts").model.create(
                    "entry",
                    url=f"{project_prefix}/releases/{release_version}",
                    content=(
                        f"Released <a href={project_prefix}><code>{project['name']}"
                        f"</code></a> <code>{release_version}</code>"
                    ),
                    visibility="public",
                )
            app.model.create_package(form)
        raise web.Created(
            f"{upload_type.capitalize()} has been uploaded.",
            f"/{project['name']}/packages/{form.content.fileobj.filename}{suffix}",
        )


@app.control("pypi/{project}")
class PyPIProject:
    """PyPI project in Simple Repository format."""

    def get(self, project):
        """Return a view of the simplified list of packages in given `project`."""
        if packages := app.model.get_packages(project):
            return app.view.pypi.project(project, packages)
        raise web.SeeOther(f"https://pypi.org/simple/{project}")


@app.control("search")
class Search:
    """Search all code."""

    def get(self):
        """"""
        try:
            query = web.form("q").q
        except web.BadRequest:
            return app.view.search.index()
        return app.view.search.results(query, app.model.search(query))