summary refs log tree commit diff stats
path: root/ganarchy/core.py
blob: b1025d1afbb7a2da441e61f9b4bcb17beb07bd1e (plain) (blame)
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
# This file is part of GAnarchy - decentralized project hub
# Copyright (C) 2020  Soni L.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

"""Core logic of GAnarchy.
"""

import hashlib
import hmac
import re
from urllib import parse

import ganarchy.git
import ganarchy.dirs
import ganarchy.data

# Currently we only use one git repo, at CACHE_HOME
# TODO optimize
GIT = ganarchy.git.Git(ganarchy.dirs.CACHE_HOME)

class Repo:
    """A GAnarchy repo.

    Args:
        dbconn (ganarchy.db.Database): The database connection.
        project_commit (str): The project commit.
        url (str): The git URL.
        branch (str): The branch.
        head_commit (str): The last known head commit.

    Attributes:
        branch (str or None): The remote git branch.
        branchname (str): The local git branch.
    """
    # TODO fill in Attributes.

    def __init__(self, dbconn, project_commit, url, branch, head_commit):
        self.url = url
        self.branch = branch
        self.project_commit = project_commit
        self.errormsg = None
        self.erroring = False
        self.message = None
        self.hash = None
        self.branchname = None
        self.head = None

        if not self._check_branch():
            return

        if not branch:
            self.branchname = "gan" + hashlib.sha256(url.encode("utf-8")).hexdigest()
            self.head = "HEAD"
        else:
            self.branchname = "gan" + hmac.new(branch.encode("utf-8"), url.encode("utf-8"), "sha256").hexdigest()
            self.head = "refs/heads/" + branch

        if head_commit:
            self.hash = head_commit
        else:
            try: # FIXME should we even do this?
                self.hash = GIT.get_hash(self.branchname)
            except ganarchy.git.GitError:
                self.erroring = True

        self.refresh_metadata()

    def _check_branch(self):
        """Checks if ``self.branch`` is a valid git branch name, or None. Sets
        ``self.errormsg`` and ``self.erroring`` accordingly.

        Returns:
            bool: True if valid, False otherwise.
        """
        if not self.branch:
            return True
        try:
            GIT.check_branchname(self.branch)
            return True
        except ganarchy.git.GitError as e:
            self.erroring = True
            self.errormsg = e
            return False

    def refresh_metadata(self):
        """Refreshes repo metadata.
        """
        if not self._check_branch():
            return
        try:
            self.message = GIT.get_commit_message(self.branchname)
        except ganarchy.git.GitError as e:
            self.erroring = True
            self.errormsg = e

    # FIXME maybe this shouldn't be "public"?
    # reasoning: this update() isn't reflected in the db.
    # but this might be handy for dry runs.
    # alternatively: change the return to be the new head commit,
    # and update things accordingly.
    def update(self, *, dry_run=False):
        """Updates the git repo, returning a commit count.

        Args:
            dry_run (bool): To simulate an update without doing anything.
                In particular, without fetching commits.
        """
        if not self._check_branch():
            return None
        if not dry_run:
            try:
                GIT.force_fetch(self.url, self.head, self.branchname)
            except ganarchy.git.GitError as e:
                # This may error for various reasons, but some
                # are important: dead links, etc
                self.erroring = True
                self.errormsg = e
                return None
        pre_hash = self.hash
        try:
            post_hash = GIT.get_hash(self.branchname)
        except ganarchy.git.GitError as e:
            # This should never happen, but maybe there's some edge cases?
            # TODO check
            self.erroring = True
            self.errormsg = e
            return None
        self.hash = post_hash
        if not pre_hash:
            pre_hash = post_hash
        count = GIT.get_count(pre_hash, post_hash)
        try:
            GIT.check_history(self.branchname, self.project_commit)
            self.refresh_metadata()
            return count
        except ganarchy.git.GitError as e:
            self.erroring = True
            self.errormsg = e
            return None

class Project:
    """A GAnarchy project.

    Args:
        dbconn (ganarchy.db.Database): The database connection.
        project_commit (str): The project commit.

    Attributes:
        commit (str): The project commit.
        repos (list, optional): Repos associated with this project.
        title (str, optional): Title of the project.
        description (str, optional): Description of the project.
        commit_body (str, optional): Raw commit message for title and
            description.
        exists (bool): Whether the project exists in our git cache.
    """

    def __init__(self, dbconn, project_commit):
        self.commit = project_commit
        self.refresh_metadata()
        self.repos = None
        self._dbconn = dbconn

    def load_repos(self):
        """Loads the repos into this project.

        If repos have already been loaded, re-loads them.
        """
        repos = []
        for url, branch, head_commit in self._dbconn.list_repobranches(self.commit):
            repos.append(
                Repo(self._dbconn, self.commit, url, branch, head_commit)
            )
        self.repos = repos

    def refresh_metadata(self):
        """Refreshes project metadata.
        """
        try:
            project = GIT.get_commit_message(self.commit)
            project_title, project_desc = (lambda x: x.groups() if x is not None else ('', None))(re.fullmatch('^\\[Project\\]\s+(.+?)(?:\n\n(.+))?$', project, flags=re.ASCII|re.DOTALL|re.IGNORECASE))
            if not project_title.strip(): # FIXME
                project_title, project_desc = ("Error parsing project commit",)*2
            # if project_desc: # FIXME
            #     project_desc = project_desc.strip()
            self.exists = True
            self.commit_body = project
            self.title = project_title
            self.description = project_desc
        except ganarchy.git.GitError:
            self.exists = False
            self.commit_body = None
            self.title = None
            self.description = None

    def update(self, *, dry_run=False):
        """Updates the project and its repos.
        """
        # TODO? check if working correctly
        results = []
        if self.repos is not None:
            for repo in self.repos:
                results.append((repo, repo.update(dry_run=dry_run)))
        self.refresh_metadata()
        if self.repos is not None:
            results.sort(key=lambda x: x[1] or -1, reverse=True)
            if not dry_run:
                entries = []
                for (repo, count) in results:
                    if count is not None:
                        entries.append((
                            self.commit,
                            repo.url,
                            repo.branch,
                            repo.hash,
                            count
                        ))
                self._dbconn.insert_activities(entries)
        return results

class GAnarchy:
    """A GAnarchy instance.

    Args:
        dbconn (ganarchy.db.Database): The database connection.
        config (ganarchy.data.DataSource): The (effective) config.

    Attributes:
        base_url (str): Instance base URL.
        title (str): Instance title.
        projects (list, optional): Projects associated with this instance.
    """

    def __init__(self, dbconn, config):
        self.title = None
        self.base_url = None
        self.projects = None
        self._dbconn = dbconn
        self._config = config
        self.load_metadata()

    def load_metadata(self):
        """Loads instance metadata from config.

        If instance metadata has already been loaded, re-loads it.
        """
        try:
            base_url = self._config.get_property_value(
                ganarchy.data.DataProperty.INSTANCE_BASE_URL
            )
        except LookupError:
            # FIXME use a more appropriate error type
            raise ValueError

        try:
            title = self._config.get_property_value(
                ganarchy.data.DataProperty.INSTANCE_TITLE
            )
        except LookupError:
            title = "GAnarchy on " + parse.urlparse(base_url).hostname

        self.title = title
        self.base_url = base_url

    def load_projects(self):
        """Loads the projects into this GAnarchy instance.

        If projects have already been loaded, re-loads them.
        """
        projects = []
        for project in self._dbconn.list_projects():
            projects.append(Project(self._dbconn, project))
        projects.sort(key=lambda p: p.title or "") # sort projects by title
        self.projects = projects