AssignmentValidationService.cs 12 KB
Newer Older
Nathan Bean's avatar
Nathan Bean committed
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
using System;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using KSU.CS.Pendant.Server.Models;
using Microsoft.Extensions.Configuration;
using System.IO;
using LibGit2Sharp;
using System.IO.Compression;

namespace KSU.CS.Pendant.Server.Services
{
    public class AssignmentValidationService : IAssignmentValidationService
    {
        private readonly DataContext _context;
        private readonly string _rootPath;

        public AssignmentValidationService(DataContext context, IConfiguration configuration)
        {
            _context = context;
            _rootPath = configuration["Paths:HomeDir"];
        }

        #region Interface Methods

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
        /// <summary>
        /// Checks the <paramref name="milestone"/> assignment for the <paramref name="user"/>,
        /// generating a new Validation that describes what work still needs to be completed.
        /// </summary>
        /// <param name="user">The user whose milestone submission should be checked</param>
        /// <param name="milestone">The milestone the submission is for</param>
        public int Check(ValidationAttempt attempt)
        {
            return CheckAsync(attempt).GetAwaiter().GetResult();
        }

        /// <summary>
        /// Checks the <paramref name="milestone"/> assignment for the <paramref name="user"/>,
        /// generating a new Validation that describes what work still needs to be completed.
        /// </summary>
        /// <param name="user">The user whose milestone submission should be checked</param>
        /// <param name="milestone">The milestone the submission is for</param>
        public async Task<int> CheckAsync(ValidationAttempt attempt)
        {
            // Validate the assignment 
            var result = await ProgramVerifier.Verifier.Check(attempt.SolutionPath, attempt.Assignment.SpecificationPath);

            // Populate the ValidationAttempt
            attempt.DateTime = DateTime.Now;
            attempt.StructuralIssues = result.StructuralIssues.Select(issue => new ValidationIssue()
            {
                Message = issue
                // TODO: add assignment url for HelpUrl
            }).ToList();
            attempt.FunctionalIssues = result.FunctionalIssues.Select(issue => new ValidationIssue()
            {
                Message = issue
            }).ToList();
            attempt.DesignIssues = result.DesignIssues.Select(issue => new ValidationIssue()
            {
                Message = issue.Message,
                HelpUrl = issue.HelpUrl,
                SourceUrl = BuildGitHubSourceUrl(attempt.RepoUrl, attempt.CommitIdentifier, issue.Path, issue.Line)
            }).ToList();
            attempt.StyleIssues = result.StyleIssues.Select(issue => new ValidationIssue()
            {
                Message = issue.Message,
                HelpUrl = issue.HelpUrl,
                SourceUrl = BuildGitHubSourceUrl(attempt.RepoUrl, attempt.CommitIdentifier, issue.Path, issue.Line)
            }).ToList();

            _context.ValidationAttempts.Add(attempt);
            await _context.SaveChangesAsync();

            return attempt.IssueCount;
        }

Nathan Bean's avatar
Nathan Bean committed
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
        /// <summary>
        /// Checks the <paramref name="milestone"/> assignment for the <paramref name="user"/>,
        /// generating a new Validation that describes what work still needs to be completed.
        /// </summary>
        /// <param name="user">The user whose milestone submission should be checked</param>
        /// <param name="milestone">The milestone the submission is for</param>
        public void CheckMilestone(User user, MilestoneAssignment milestone)
        {
            CheckMilestoneAsync(user, milestone).GetAwaiter().GetResult();
        }

        /// <summary>
        /// Checks the <paramref name="milestone"/> assignment for the <paramref name="user"/>,
        /// generating a new Validation that describes what work still needs to be completed.
        /// </summary>
        /// <param name="user">The user whose milestone submission should be checked</param>
        /// <param name="milestone">The milestone the submission is for</param>
        public async Task CheckMilestoneAsync(User user, MilestoneAssignment milestone)
        {
            var ownerName = milestone.IterativeProject.GitHubOrganizationName;
            var repoName = $"{milestone.IterativeProject.RepositoryPrefix}-{user.GitHubAccount.Username}";
            var branchName = milestone.BranchName;

            // Clone the repo
            var studentPath = CloneAndCheckout(user, milestone, ownerName, repoName, branchName);

            // Validate the assignment 
            var result = await ProgramVerifier.Verifier.Check(studentPath, milestone.SpecificationPath);

            // Create the ValidationAttempt
            var attempt = new ValidationAttempt()
            {
                User = user,
                Assignment = milestone,
                SolutionPath = studentPath,
                DateTime = DateTime.Now,
                StructuralIssues = result.StructuralIssues.Select(issue => new ValidationIssue()
                {
                    Message = issue
                    // TODO: add assignment url for HelpUrl
                }).ToList(),
                FunctionalIssues = result.FunctionalIssues.Select(issue => new ValidationIssue()
                {
                    Message = issue
                }).ToList(),
                DesignIssues = result.DesignIssues.Select(issue => new ValidationIssue()
                {
                    Message = issue.Message,
                    HelpUrl = issue.HelpUrl,
                    SourceUrl = BuildGitHubSourceUrl(ownerName, repoName, branchName, issue.Path, issue.Line)
                }).ToList(),
                StyleIssues = result.StyleIssues.Select(issue => new ValidationIssue()
                {
                    Message = issue.Message,
                    HelpUrl = issue.HelpUrl,
                    SourceUrl = BuildGitHubSourceUrl(ownerName, repoName, branchName, issue.Path, issue.Line)
                }).ToList()
            };

            _context.ValidationAttempts.Add(attempt);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// Extracts and saves the <paramref name="assignment"/> specification into a local folder 
        /// and sets the path variable
        /// </summary>
        /// <param name="assignment">The assignment with the specification to save</param>
        /// <returns>True on success, false otherwise</returns>
        public bool SaveAssignmentSpecification(Assignment assignment)
        {
            return SaveAssignmentSpecificationAsync(assignment).GetAwaiter().GetResult();
        }

        /// <summary>
        /// Extracts and saves the <paramref name="assignment"/> specification into a local folder 
        /// and sets the path variable
        /// </summary>
        /// <param name="assignment">The assignment with the specification to save</param>
        /// <returns>True on success, false otherwise</returns>
        public async Task<bool> SaveAssignmentSpecificationAsync(Assignment assignment)
        {
            // Save the assignment specification
            try
            {
                var tmpPath = Path.GetTempFileName();
                var randomName = Path.GetRandomFileName();
                var specificationPath = Path.Combine(_rootPath, "specifications", randomName);

                using (var stream = System.IO.File.Create(tmpPath))
                {
                    await assignment.Specification.CopyToAsync(stream);
                }

                await Task.Run(() => ZipFile.ExtractToDirectory(tmpPath, specificationPath, true));

                await Task.Run(() => System.IO.File.Delete(tmpPath));

                // The unzipped file adds an extra directory - should be archive.FileName with the .zip dropped
                var dirName = Path.GetFileNameWithoutExtension(assignment.Specification.FileName);
                assignment.SpecificationPath = Path.Combine(specificationPath, dirName);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        #endregion

        #region Helper Methods

        /// <summary>
        /// Helper method that:
        /// 1. Clones the repo (if it does not yet exist) and 
        /// 2. Checks out the specified branch
        /// </summary>
        /// <param name="user">The user the repository belongs to</param>
        /// <param name="assignment">The assignment which this repo is associated with</param>
        /// <param name="ownerName">The owner of the repo (typically the organization the GitHub assignment was created from)</param>
        /// <param name="repoName">The name of the repository that is being cloned</param>
        /// <param name="branchName">The name of the branch to check out</param>
        /// <returns>The path to the cloned repo</returns>
        private string CloneAndCheckout(User user, Assignment assignment, string ownerName, string repoName, string branchName)
        {

            // git@github.com:ksu-cis/webhook-test-zombiepaladin.git
            var filePath = $"{_rootPath}\\submissions\\{assignment.ID}\\{user.ID}";
            var repoUrl = $"git@github.com:{ownerName}/{repoName}.git";

            // Clone the repo if it does not yet exist
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
                Repository.Clone(repoUrl, filePath);
            }

            using var repo = new Repository(filePath);

            // Create a local branch to track the remote one if it does not yet exist
            if (repo.Branches[branchName] is null)
            {
                Branch trackedBranch = repo.Branches[$"refs/remotes/origin/{branchName}"];
                Branch localBranch = repo.CreateBranch(branchName, trackedBranch.Tip);
                repo.Branches.Update(localBranch, b => b.TrackedBranch = trackedBranch.CanonicalName);
            }

            // Checkout the specified branch
            var branch = repo.Branches[branchName];
            if (branch != null) Commands.Checkout(repo, branch);

            return filePath;
        }

        /// <summary>
        /// A helper method to build a URL pointing at the specified <paramref name="line"/> number 
        /// in the file at <paramref name="path"/> in the branch <paramref name="branchName"/> found
        /// in the repo <paramref name="repoName"/> in the oranization <paramref name="ownerName"/>.
        /// </summary>
        /// <param name="ownerName">The organization that owns the repo</param>
        /// <param name="repoName">The name of the repo</param>
        /// <param name="branchName">The repo branch of interest</param>
        /// <param name="path">The path to the file of interest</param>
        /// <param name="line">The line number of that file to highlight</param>
        /// <returns></returns>
        private static string BuildGitHubSourceUrl(string ownerName, string repoName, string branchName, string path, string line)
        {
            if (path.Length == 0) return "";
            // Build the souceURL 
            var sb = new StringBuilder();
            sb.Append("https://github.com/");
            sb.Append(ownerName);
            sb.Append("/");
            sb.Append(repoName);
            sb.Append("/blob/");
            sb.Append(branchName);
            sb.Append(path);
            sb.Append("#L");
            sb.Append(line);
            return sb.ToString();
        }

261
262
263
264
265
266
267
268
269
270
271
272
273
274
        private static string BuildGitHubSourceUrl(string repoUrl, string commitIdentifier, string path, string line)
        {
            if (path.Length == 0) return "";
            // Build the souceURL 
            var sb = new StringBuilder();
            sb.Append(repoUrl);
            sb.Append("/tree/");
            sb.Append(commitIdentifier);
            sb.Append(path);
            sb.Append("#L");
            sb.Append(line);
            return sb.ToString();
        }

Nathan Bean's avatar
Nathan Bean committed
275
276
277
        #endregion
    }
}