summaryrefslogtreecommitdiff
path: root/worker/GitWorker.py
blob: e124b1fc4db2c6838e65457d2f01b7cd432346f6 (plain)
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
from util import Logger, getProjRepoName, passCodeQuality, getAllFiles
from shutil import ignore_patterns, copytree, rmtree
import multiprocessing
import traceback
import git
import os


class GitWorker():
    def __init__(self,
                 args,
                 hgroups,
                 language,
                 mandatoryFiles,
                 optionalFiles,
                 logger=Logger(),
                 processCount=16):
        self.args = args
        self.hgroups = hgroups
        self.language = language
        self.logger = logger
        self.processCount = processCount
        self.mandatoryFiles = mandatoryFiles
        self.optionalFiles = optionalFiles
        self.moss = None

    @classmethod
    def isREADME(cls, fn):
        fn = fn.lower()
        if len(fn) < 6: return False
        if len(fn) == 6: return fn == "readme"
        return fn[:7] == "readme."

    def checkIndvProcess(self, groupNum, hwNum):
        tidy = self.args.tidy
        repoName = f"hgroup-{groupNum:02}"
        repoDir = os.path.join("hwrepos", repoName)
        hwDir = os.path.join(repoDir, f"h{hwNum}")
        if not os.path.exists(repoDir):
            repo = git.Repo.clone_from(
                f"https://focs.ji.sjtu.edu.cn/git/vg101/{repoName}",
                repoDir,
                branch="master")
        else:
            repo = git.Repo(repoDir)
        repo.git.fetch("--all", "-f")
        remoteBranches = [ref.name for ref in repo.remote().refs]
        scores = {
            stuName: {
                "indvFailSubmit": 0,
                "indvUntidy": 0,
                "indvLowCodeQuality": 0,
                "indvComment": [],
            }
            for _, stuName in self.hgroups[repoName]
        }
        for stuID, stuName in self.hgroups[repoName]:
            try:
                if f"origin/{stuID}" not in remoteBranches:
                    self.logger.warning(
                        f"{repoName} {stuID} {stuName} branch missing")
                    scores[stuName]["indvFailSubmit"] = 1
                    scores[stuName]["indvComment"].append(
                        "individual branch individual branch missing")
                    continue
                repo.git.reset("--hard", f"origin/{stuID}")
                repo.git.clean("-d", "-f", "-x")
                self.logger.debug(f"{repoName} {stuID} {stuName} pull succeed")
                if self.args.dir:
                    copytree(repoDir,
                             os.path.join("indv",
                                          f"{repoName} {stuID} {stuName}"),
                             ignore=ignore_patterns(".git"))
                if not os.path.exists(hwDir):
                    self.logger.warning(
                        f"{repoName} {stuID} {stuName} h{hwNum} dir missing")
                    scores[stuName]["indvFailSubmit"] = 1
                    scores[stuName]["indvComment"].append(
                        f"individual branch h{hwNum} dir missing")
                else:
                    for fn, path in [
                        (fn, os.path.join(hwDir, fn)) for fn in
                        [*self.mandatoryFiles, *self.optionalFiles]
                    ]:
                        if os.path.exists(path):
                            if not passCodeQuality(path, self.language):
                                scores[stuName]["indvLowCodeQuality"] = 1
                                scores[stuName]["indvComment"].append(
                                    f"individual {fn} low quality")
                                self.logger.warning(
                                    f"{repoName} {stuID} {stuName} {fn} low quality"
                                )
                            continue
                        if fn in self.mandatoryFiles:
                            self.logger.warning(
                                f"{repoName} {stuID} {stuName} h{hwNum}/{fn} file missing"
                            )
                            scores[stuName]["indvFailSubmit"] = 1
                            scores[stuName]["indvComment"].append(
                                f"individual branch h{hwNum}/{fn} file missing")
                    if not list(filter(GitWorker.isREADME, os.listdir(hwDir))):
                        self.logger.warning(
                            f"{repoName} {stuID} {stuName} h{hwNum}/README file missing"
                        )
                        scores[stuName]["indvFailSubmit"] = 1
                        scores[stuName]["indvComment"].append(
                            f"individual branch h{hwNum}/README file missing")
                if not tidy: continue
                dirList = list(
                    filter(
                        lambda x: x not in
                        [".gitignore", ".git", *[f"h{n}" for n in range(20)]
                         ] and not GitWorker.isREADME(x), os.listdir(repoDir)))
                if dirList:
                    self.logger.warning(
                        f"{repoName} {stuID} {stuName} untidy {', '.join(dirList)}"
                    )
                    scores[stuName]["indvUntidy"] = 1
                    scores[stuName]["indvComment"].append(
                        f"individual branch redundant files: {', '.join(dirList)}"
                    )
                if os.path.exists(hwDir):
                    dirList = os.listdir(hwDir)
                    dirList = list(
                        filter(
                            lambda x: x not in self.mandatoryFiles and x not in
                            self.optionalFiles and not GitWorker.isREADME(x),
                            dirList))
                    if dirList:
                        self.logger.warning(
                            f"{repoName} {stuID} {stuName} h{hwNum}/ untidy {', '.join(dirList)}"
                        )
                        scores[stuName]["indvUntidy"] = 1
                        scores[stuName]["indvComment"].append(
                            f"individual branch redundant files: {', '.join(dirList)}"
                        )
            except Exception:
                self.logger.error(f"{repoName} {stuID} {stuName} error")
                self.logger.error(traceback.format_exc())
        return scores

    def checkGroupProcess(self, groupNum, hwNum):
        tidy = self.args.tidy
        repoName = f"hgroup-{groupNum:02}"
        repoDir = os.path.join("hwrepos", repoName)
        hwDir = os.path.join(repoDir, f"h{hwNum}")
        if not os.path.exists(repoDir):
            repo = git.Repo.clone_from(
                f"https://focs.ji.sjtu.edu.cn/git/vg101/{repoName}",
                repoDir,
                branch="master")
        else:
            repo = git.Repo(repoDir)
        repo.git.fetch("--tags", "--all", "-f")
        tagNames = [tag.name for tag in repo.tags]
        scores = {
            stuName: {
                "groupFailSubmit": 0,
                "groupUntidy": 0,
                "groupLowCodeQuality": 0,
                "groupComment": [],
            }
            for _, stuName in self.hgroups[repoName]
        }
        if f"h{hwNum}" not in tagNames:
            self.logger.warning(f"{repoName} tags/h{hwNum} missing")
            for _, stuName in self.hgroups[repoName]:
                scores[stuName]["groupFailSubmit"] = 1
                scores[stuName]["groupComment"].append(
                    f"tags/h{hwNum} missing")
            return scores
        repo.git.reset("--hard", f"origin/master")
        repo.git.clean("-d", "-f", "-x")
        repo.git.checkout(f"tags/h{hwNum}")
        self.logger.debug(f"{repoName} checkout to tags/h{hwNum} succeed")
        if not os.path.exists(hwDir):
            self.logger.warning(f"{repoName} h{hwNum} dir missing")
            for _, stuName in self.hgroups[repoName]:
                scores[stuName]["groupFailSubmit"] = 1
                scores[stuName]["groupComment"].append(
                    f"tags/h{hwNum} h{hwNum} dir missing")
        else:
            for fn, path in [
                (fn, os.path.join(hwDir, fn))
                    for fn in [*self.mandatoryFiles, *self.optionalFiles]
            ]:
                if os.path.exists(path):
                    if not passCodeQuality(path, self.language):
                        for _, stuName in self.hgroups[repoName]:
                            scores[stuName]["groupLowCodeQuality"] = 1
                            scores[stuName]["groupComment"].append(
                                f"group {fn} low quality")
                        self.logger.warning(f"{repoName} {fn} low quality")
                    continue
                if fn in self.mandatoryFiles:
                    self.logger.warning(f"{repoName} h{hwNum}/{fn} file missing")
                    for _, stuName in self.hgroups[repoName]:
                        scores[stuName]["groupFailSubmit"] = 1
                        scores[stuName]["groupComment"].append(
                            f"tags/h{hwNum} h{hwNum}/{fn} missing")
            if not list(filter(GitWorker.isREADME, os.listdir(hwDir))):
                self.logger.warning(f"{repoName} h{hwNum}/README file missing")
                for _, stuName in self.hgroups[repoName]:
                    scores[stuName]["groupFailSubmit"] = 1
                    scores[stuName]["groupComment"].append(
                        f"tags/h{hwNum} h{hwNum}/README file missing")
        if not tidy: return scores
        dirList = os.listdir(repoDir)
        dirList = list(
            filter(
                lambda x: x not in [
                    ".gitignore", ".git", ".gitea",
                    *[f"h{n}" for n in range(20)]
                ] and not GitWorker.isREADME(x), dirList))
        if dirList:
            self.logger.warning(f"{repoName} untidy {', '.join(dirList)}")
            for _, stuName in self.hgroups[repoName]:
                scores[stuName]["groupUntidy"] = 1
                scores[stuName]["groupComment"].append(
                    f"tags/h{hwNum} redundant files: {', '.join(dirList)}")
        if os.path.exists(hwDir):
            dirList = os.listdir(hwDir)
            dirList = list(
                filter(
                    lambda x: x not in self.mandatoryFiles and x not in self.
                    optionalFiles and not GitWorker.isREADME(x), dirList))
            if dirList:
                self.logger.warning(
                    f"{repoName} h{hwNum} untidy {', '.join(dirList)}")
                for _, stuName in self.hgroups[repoName]:
                    scores[stuName]["groupUntidy"] = 1
                    scores[stuName]["groupComment"].append(
                        f"tags/h{hwNum} redundant files: {', '.join(dirList)}")
        return scores

    def checkProjProcess(self, id_, name, projNum, milestoneNum):
        stuName = name
        repoName = getProjRepoName([id_, name, projNum, milestoneNum])
        repoDir = os.path.join("projrepos", f"p{projNum}", repoName)
        scores = {
            stuName: {
                "projComment": [],
            }
        }
        if not os.path.exists(repoDir):
            repo = git.Repo.clone_from(
                f"https://focs.ji.sjtu.edu.cn/git/vg101/{repoName}", repoDir)
        else:
            repo = git.Repo(os.path.join("projrepos", f"p{projNum}", repoName))
            repo.git.fetch("--tags", "--all", "-f")
            remoteBranches = [ref.name for ref in repo.remote().refs]
            if "origin/master" not in remoteBranches:
                self.logger.warning(f"{repoName} master branch missing")
                scores[stuName]["projComment"].append(f"master branch missing")
                return scores
            repo.git.reset("--hard", "origin/master")
            repo.git.clean("-d", "-f", "-x")
        if milestoneNum:
            repo.git.fetch("--tags", "--all", "-f")
            tagNames = [tag.name for tag in repo.tags]
            if f"m{milestoneNum}" not in tagNames:
                self.logger.warning(f"{repoName} tags/m{milestoneNum} missing")
                scores[stuName]["projComment"].append(
                    f"tags/m{milestoneNum} missing")
                return scores
            repo.git.checkout(f"tags/m{milestoneNum}", "-f")
            self.logger.debug(
                f"{repoName} checkout to tags/m{milestoneNum} succeed")
            if not list(filter(GitWorker.isREADME, os.listdir(repoDir))):
                self.logger.warning(f"{repoName} README file missing")
                scores[stuName]["projComment"].append(f"README file missing")
            language = ["matlab", "c", "cpp"]
            if projNum == 1:
                for fn in list(
                        filter(lambda x: x.endswith(".m"),
                               os.listdir(repoDir))):
                    path = os.path.join(repoDir, fn)
                    if not passCodeQuality(path, language[projNum - 1]):
                        self.logger.warning(f"{repoName} {fn} low quality")
                        scores[stuName]["projComment"].append(
                            f"{fn} low quality")
            elif projNum == 2:
                for fn in getAllFiles(repoDir):
                    if (fn.endswith(".c")
                            or fn.endswith(".h")) and not passCodeQuality(
                                os.path.join(repoDir, fn),
                                language[projNum - 1]):
                        self.logger.warning(f"{repoName} {fn} low quality")
                        scores[stuName]["projComment"].append(
                            f"{fn} low quality")
        else:
            self.logger.debug(f"{repoName} pull succeed")
        return scores

    def checkIndv(self):
        if self.args.dir:
            if os.path.exists(os.path.join("indv")):
                rmtree(os.path.join("indv"))
        hwNum = self.args.hw
        if self.args.rejudge < 0:
            with multiprocessing.Pool(self.processCount) as p:
                res = p.starmap(self.checkIndvProcess,
                                [(i, hwNum)
                                 for i in range(len(self.hgroups.keys()))])
        else:
            res = [self.checkIndvProcess(self.args.rejudge, hwNum)]
        return {k: v for d in res for k, v in d.items()}

    def checkGroup(self):
        hwNum = self.args.hw
        if self.args.rejudge < 0:
            with multiprocessing.Pool(self.processCount) as p:
                res = p.starmap(self.checkGroupProcess,
                                [(i, hwNum)
                                 for i in range(len(self.hgroups.keys()))])
        else:
            res = [self.checkGroupProcess(self.args.rejudge, hwNum)]
        return {k: v for d in res for k, v in d.items()}

    def checkProj(self, projNum, milestoneNum):
        milestoneNum = 0 if milestoneNum is None else milestoneNum
        if projNum in [1, 2]:
            infos = [[*info, projNum, milestoneNum]
                     for hgroup in self.hgroups.values() for info in hgroup]
        elif projNum in [3]:
            infos = []
            return
        else:
            return
        with multiprocessing.Pool(self.processCount) as p:
            res = p.starmap(self.checkProjProcess, infos)
        return {k: v for d in res for k, v in d.items()}