Exemplo n.º 1
0
        public async Task CreateOrUpdateRepoSettingsAsync(RepoSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (string.IsNullOrEmpty(settings.Id))
            {
                settings.Id = $"{settings.OwnerId}/{settings.RepositoryId}";
            }
            var validator         = new RepoSettingsValidator();
            var validationResults = await validator.ValidateAsync(settings);

            if (!validationResults.IsValid)
            {
                throw new ValidationException("Invalid repo settings", validationResults);
            }
            var updateResponse = await _client.IndexDocumentAsync(settings);

            if (!updateResponse.IsValid)
            {
                throw new OwnerSettingsStoreException($"Error updating repo settings for owner/repo ID {settings.RepositoryId}");
            }

            await _client.RefreshAsync(Indices.Index <RepoSettings>());
        }
Exemplo n.º 2
0
        public ActionResult ManageRepo(string repoName, RepoSettings settings)
        {
            var resourceInfo = this.FileManager.GetResourceInfo(repoName);

            if (resourceInfo.Type != ResourceType.Directory)
            {
                return(HttpNotFound());
            }

            var repo = GitUtilities.GetRepoInfo(resourceInfo.FullPath);

            if (!repo.IsGitRepo)
            {
                return(HttpNotFound());
            }

            if (!ModelState.IsValid)
            {
                return(View(settings));
            }

            io::File.WriteAllText(Path.Combine(resourceInfo.FullPath, "description"), settings.Description);
            if (repo.IsArchived != settings.IsArchived)
            {
                GitUtilities.ToggleArchived(resourceInfo.FullPath);
            }

            return(RedirectToAction("ViewRepo", "Browse", new { repo = repoName }));
        }
Exemplo n.º 3
0
        public async Task ItCanCreateAndRetrieveRepoSettings()
        {
            var repoSettings = new RepoSettings
            {
                OwnerId      = "owner-1",
                RepositoryId = "repo-1",
                OwnerIsOrg   = false,
                LastModified = DateTime.UtcNow
            };

            await _store.CreateOrUpdateRepoSettingsAsync(repoSettings);

            var retrievedRepoSettings = await _store.GetRepoSettingsAsync("owner-1", "repo-1");

            retrievedRepoSettings.Id.Should().Be("owner-1/repo-1");
            retrievedRepoSettings.OwnerId.Should().Be("owner-1");
            retrievedRepoSettings.RepositoryId.Should().Be("repo-1");
            (retrievedRepoSettings.OwnerIsOrg).Should().BeFalse();
            retrievedRepoSettings.LastModified.Should().BeCloseTo(repoSettings.LastModified);

            var retrievedByIdRepoSettings = await _store.GetRepoSettingsByIdAsync("owner-1/repo-1");

            retrievedByIdRepoSettings.Id.Should().Be("owner-1/repo-1");
            retrievedByIdRepoSettings.OwnerId.Should().Be("owner-1");
            retrievedByIdRepoSettings.RepositoryId.Should().Be("repo-1");
            (retrievedByIdRepoSettings.OwnerIsOrg).Should().BeFalse();
            retrievedByIdRepoSettings.LastModified.Should().BeCloseTo(repoSettings.LastModified);
        }
Exemplo n.º 4
0
        public GitCore(IOptions <RepoSettings> settings, ILogger <GitCore> logger)
        {
            this.logger  = logger;
            repoSettings = settings.Value;

            Directory.CreateDirectory(repoSettings.Root);
        }
Exemplo n.º 5
0
 public RepositoryInfo(RepoSettings s)
 {
     this.OwnerId           = s.OwnerId;
     this.RepoId            = s.RepositoryId;
     this.DataDockImportUrl = $"/dashboard/import/{OwnerId}/{RepoId}";
     this.OwnerAvatar       = s.OwnerAvatar;
 }
        public DashboardMenuViewComponentTests()
        {
            _mockHttpContext       = new Mock <HttpContext>();
            _mockRepoSettingsStore = new Mock <IRepoSettingsStore>();

            var repo1 = new RepoSettings
            {
                OwnerId      = "owner-1",
                RepositoryId = "repo-1",
                Id           = "owner-1/repo-1",
                OwnerIsOrg   = false
            };
            var repo2 = new RepoSettings
            {
                OwnerId      = "owner-1",
                RepositoryId = "repo-2",
                Id           = "owner-1/repo-2",
                OwnerIsOrg   = false
            };
            var repo3 = new RepoSettings
            {
                OwnerId      = "owner-1",
                RepositoryId = "repo-3",
                Id           = "owner-1/repo-3",
                OwnerIsOrg   = false
            };
            var repos = new List <RepoSettings> {
                repo1, repo2, repo3
            };

            _mockRepoSettingsStore.Setup(m => m.GetRepoSettingsForOwnerAsync(It.IsAny <string>()))
            .Returns(Task.FromResult <IEnumerable <RepoSettings> >(repos));
        }
Exemplo n.º 7
0
        public static IReadOnlyCollection <string> Exec(string command, RepoSettings repoSettings, string projectsPath)
        {
            var projectPath = Path.Combine(projectsPath, repoSettings.ActualFolderName);

            if (!Directory.Exists(projectPath))
            {
                throw new CcException($"Path \"{projectPath}\" not found");
            }

            var startInfo = new ProcessStartInfo
            {
                WorkingDirectory       = projectPath,
                WindowStyle            = ProcessWindowStyle.Hidden,
                FileName               = "cmd.exe",
                RedirectStandardInput  = false,
                UseShellExecute        = false,
                Arguments              = "/C " + command,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            var outputList = new List <string>();
            var errorList  = new List <string>();

            using (var process = new Process())
            {
                process.StartInfo = startInfo;

                process.OutputDataReceived += (sender, args) =>
                {
                    if (args.Data != null)
                    {
                        outputList.Add(args.Data);
                    }
                };
                process.ErrorDataReceived += (sender, args) =>
                {
                    if (args.Data != null)
                    {
                        errorList.Add(args.Data);
                    }
                };

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    throw new GitException(outputList, errorList);
                }

                return(outputList);
            }
        }
Exemplo n.º 8
0
        public static string GetCurrentBranch(RepoSettings repoSettings, string projectsPath)
        {
            var result = Exec("git rev-parse --abbrev-ref HEAD", repoSettings, projectsPath);

            if (!result.Any() || result.Count > 1)
            {
                throw new CcException("Current git branch not found");
            }

            return(result.First());
        }
Exemplo n.º 9
0
        private static string GetScmBranchField(string currentBranch, RepoSettings repoSettings, CommonSettings commonSettings)
        {
            var commitData = GitHelper.Exec("git rev-parse HEAD", repoSettings, commonSettings.ProjectsPath);

            if (!commitData.Any() || commitData.Count > 1)
            {
                throw new CcException("Current commit hash not found");
            }

            return($"Branch: {currentBranch}\n\nCommit Hash: {commitData.First()}");
        }
Exemplo n.º 10
0
 public RepoSettingsViewModel(RepoSettings repoSettings)
 {
     OwnerId                 = repoSettings.OwnerId;
     RepoId                  = repoSettings.RepositoryId;
     OwnerIsOrg              = repoSettings.OwnerIsOrg;
     DefaultPublisherName    = repoSettings.DefaultPublisher?.Label;
     DefaultPublisherType    = repoSettings.DefaultPublisher?.Type;
     DefaultPublisherEmail   = repoSettings.DefaultPublisher?.Email;
     DefaultPublisherWebsite = repoSettings.DefaultPublisher?.Website;
     SearchButtons           = repoSettings.SearchButtons;
     LastModifiedBy          = repoSettings.LastModifiedBy;
     LastModified            = repoSettings.LastModified;
 }
Exemplo n.º 11
0
        private async Task InitializeRepository()
        {
            for (var o = 0; o < 5; o++)
            {
                for (var r = 0; r < 5; r++)
                {
                    var repoSettings = new RepoSettings
                    {
                        OwnerId      = "owner-" + o,
                        RepositoryId = "repo-" + r,
                        LastModified = DateTime.UtcNow
                    };

                    await Store.CreateOrUpdateRepoSettingsAsync(repoSettings);
                }
            }
        }
Exemplo n.º 12
0
 private static IReadOnlyCollection <string> GetBranchFileContent(
     string branchName,
     string fileName,
     string projectsPath,
     RepoSettings repoSettings)
 {
     try
     {
         return(GitHelper.Exec(
                    $"git show {branchName}:{fileName}".Replace(
                        Path.Combine(projectsPath, repoSettings.ActualFolderName) + "\\",
                        string.Empty)
                    .Replace("\\", "/"),
                    repoSettings,
                    projectsPath));
     }
     catch (Exception)
     {
         ConsoleHelper.WriteLineColor(
             "Error: Unable to fetch mainbranch content. Fetching current file content",
             ConsoleColor.Red);
         return(File.ReadAllLines(fileName));
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Check that the user has access to the org and repo then
        /// return the settings for that repository, create settings if none exists
        /// </summary>
        /// <param name="user"></param>
        /// <param name="ownerId"></param>
        /// <param name="repoId"></param>
        /// <returns></returns>
        public async Task <RepoSettings> CheckRepoSettingsAsync(ClaimsPrincipal user, string ownerId, string repoId)
        {
            var repo = await CheckGitHubRepository(user.Identity, ownerId, repoId);

            try
            {
                var repoSettings = await _repoSettingsStore.GetRepoSettingsAsync(ownerId, repoId);

                if (string.IsNullOrEmpty(repoSettings.CloneUrl))
                {
                    repoSettings.CloneUrl = repo.CloneUrl;
                    await _repoSettingsStore.CreateOrUpdateRepoSettingsAsync(repoSettings);
                }
                return(repoSettings);
            }
            catch (RepoSettingsNotFoundException)
            {
                var newRepoSettings = new RepoSettings
                {
                    OwnerId      = ownerId,
                    RepositoryId = repoId,
                    CloneUrl     = repo.CloneUrl,
                    OwnerIsOrg   = !user.Identity.Name.Equals(ownerId, StringComparison.InvariantCultureIgnoreCase),
                    OwnerAvatar  = repo.Owner?.AvatarUrl
                };

                await _repoSettingsStore.CreateOrUpdateRepoSettingsAsync(newRepoSettings);

                return(newRepoSettings);
            }
            catch (Exception e)
            {
                Log.Error($"Error checking repo settings for '{ownerId}/{repoId}", e);
                throw;
            }
        }
Exemplo n.º 14
0
 public static string GetMainBranch(RepoSettings repoSettings)
 {
     return(string.IsNullOrWhiteSpace(repoSettings?.MainBranch)
         ? "develop"
         : repoSettings.MainBranch);
 }
Exemplo n.º 15
0
        private static string GetDescription(string mainBranch, IReadOnlyCollection <FilePart> fileParts, string projectsPath, RepoSettings repoSettings)
        {
            //            const string template = @"h4. Issue Locations
            //{noformat} [
            //    {
            //        ""endLine"": %end_line%,
            //        ""fileName"": ""%file_name%"",
            //        ""startColumn"": %start_column%,
            //        ""startLine"": %start_line%
            //    }
            //] {noformat}
            //h4. Code
            //{code:java}%code%{code}";

            const string template = @"h4. Issue Locations 
{noformat} %fileParts% {noformat} 
h4. Code 
{code:java}%code%{code}";

            var first = fileParts.First();
            IEnumerable <string> contentLines = GetBranchFileContent(mainBranch, first.FileName, projectsPath, repoSettings).ToList();

            if (!first.Whole)
            {
                contentLines = contentLines.Skip(first.StartLine - 1).Take(first.EndLine - first.StartLine + 1);
            }
            else
            {
                first.StartLine = 1;
                first.EndLine   = contentLines.Count();
            }

            var content = string.Join("\r\n", contentLines);

            const int maxDescriptionSize = 50 * 1024;

            if (content.Length > maxDescriptionSize)
            {
                content = content.Substring(0, maxDescriptionSize);
            }

            var startColumn = content.TakeWhile(c => c == ' ' || c == '\t').Count();

            var strFileParts = JsonConvert.SerializeObject(fileParts.Select(p => new
            {
                endLine     = p.EndLine,
                fileName    = GetFileName(p.FileName, projectsPath, repoSettings.ActualFolderName),
                startColumn = startColumn,
                startLine   = p.StartLine
            }), Formatting.Indented);

            return(template
                   .Replace("%fileParts%", strFileParts)
                   .Replace("%code%", content));
        }