|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +from django.core.management import BaseCommand |
| 4 | +from git import Actor, Repo |
| 5 | +from tqdm import tqdm |
| 6 | +from wiki.models import ArticleRevision |
| 7 | + |
| 8 | + |
| 9 | +class Command(BaseCommand): |
| 10 | + def handle(self, *args, **kwargs): |
| 11 | + path = Path("repo") |
| 12 | + repo = Repo.init(path) |
| 13 | + |
| 14 | + for revision in tqdm( |
| 15 | + ArticleRevision.objects.filter( |
| 16 | + article__other_read=True, |
| 17 | + ) |
| 18 | + .select_related("article", "user") |
| 19 | + .iterator(chunk_size=500), |
| 20 | + total=ArticleRevision.objects.filter(article__other_read=True).count(), |
| 21 | + ): |
| 22 | + url: str = revision.article.get_absolute_url() |
| 23 | + if not url.startswith("/wiki/online"): |
| 24 | + continue |
| 25 | + # remove inital /, makes path absolute which we do not want |
| 26 | + |
| 27 | + repo_relative = ( |
| 28 | + Path(url.replace("/wiki/online/", "src/content/docs/")) / "index.md" |
| 29 | + ) |
| 30 | + file = path / repo_relative |
| 31 | + if revision.deleted: |
| 32 | + file.unlink() |
| 33 | + else: |
| 34 | + file.parent.mkdir(parents=True, exist_ok=True) |
| 35 | + file.touch(exist_ok=True) |
| 36 | + |
| 37 | + file.write_text(f"""--- |
| 38 | ++title: "{revision.title}" |
| 39 | ++--- |
| 40 | ++ |
| 41 | + {revision.content}""") |
| 42 | + repo.index.add([repo_relative]) |
| 43 | + |
| 44 | + author_info = revision.user |
| 45 | + if author_info is not None: |
| 46 | + author = Actor(author_info.first_name, author_info.email) |
| 47 | + else: |
| 48 | + author = Actor(f"Ukjent (brukerid {revision.user_id})", None) |
| 49 | + repo.index.commit( |
| 50 | + revision.user_message, |
| 51 | + author=author, |
| 52 | + committer=author, |
| 53 | + author_date=revision.created, |
| 54 | + commit_date=revision.created, |
| 55 | + skip_hooks=True, |
| 56 | + ) |
| 57 | + |
| 58 | + repo.index.write() |
0 commit comments