Beispiel #1
0
        public async Task FacilityExists_Exists_ReturnsTrue()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var result = await repository.FacilityExistsAsync(RepositoryData.Facilities()[0].Id);

            result.ShouldBeTrue();
        }
Beispiel #2
0
        //  Other Methods
        //  =============

        /// <exception cref="Kallithea_Klone.MainActionException"></exception>
        private async Task Update(RepositoryData location)
        {
            string remotePath = GetDefaultRemotePath(location.URL);
            Uri    uri        = new Uri(remotePath);

            string     fullURL    = $"{uri.Scheme}://{HttpUtility.UrlEncode(AccountSettings.Username)}:{HttpUtility.UrlEncode(AccountSettings.Password)}@{uri.Host}{uri.PathAndQuery}";
            string     shelfName  = DateTime.Now.ToString(dateTimeFormat);
            CMDProcess cmdProcess = new CMDProcess("UPDATE", location.Name, new string[]
            {
                $"cd /d {location.URL}" +
                $"hg --config \"extensions.shelve = \" shelve --name {shelfName} {debugArg}" +
                $"hg pull {fullURL} {debugArg}" +
                $"hg update -m {debugArg}" +
                $"hg --config \"extensions.shelve = \" unshelve --name {shelfName} --tool :other {debugArg}"
            });

            try
            {
                await cmdProcess.Run();
            }
            catch (Exception e)
            {
                throw new MainActionException("Unable to start the necessary command window process", e);
            }

            cmdProcess.ReportErrorsAsync(Verb);
        }
Beispiel #3
0
        public async Task <int> MakeUpdatePullRequests(
            IGitDriver git,
            RepositoryData repository,
            IReadOnlyCollection <PackageUpdateSet> updates,
            NuGetSources sources,
            SettingsContainer settings)
        {
            int totalCount = 0;

            try
            {
                var groups = UpdateConsolidator.Consolidate(updates,
                                                            settings.UserSettings.ConsolidateUpdatesInSinglePullRequest);

                foreach (var updateSets in groups)
                {
                    var updatesMade = await MakeUpdatePullRequests(
                        git, repository,
                        sources, settings, updateSets);

                    totalCount += updatesMade;
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Updates failed", ex);
            }

            return(totalCount);
        }
Beispiel #4
0
        public async Task CreateRecord_Succeeds()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var record = new RetentionRecord()
            {
                Active            = true,
                BoxNumber         = "NewBox",
                ConsignmentNumber = "CN",
                EndYear           = 2020,
                FacilityId        = RepositoryData.Facilities()[0].Id,
                RetentionSchedule = "RS",
                ShelfNumber       = "SN",
                StartYear         = 2000,
            };
            var newRecord = new RetentionRecordCreateDto()
            {
                BoxNumber         = record.BoxNumber,
                ConsignmentNumber = record.ConsignmentNumber,
                EndYear           = record.EndYear,
                RetentionSchedule = record.RetentionSchedule,
                ShelfNumber       = record.ShelfNumber,
                StartYear         = record.StartYear
            };

            record.Id = await repository.CreateRetentionRecordAsync(record.FacilityId, newRecord);

            var result = await repository.GetRetentionRecordAsync(record.Id);

            result.Should().BeEquivalentTo(new RetentionRecordDetailDto(record));
        }
Beispiel #5
0
        public async Task UpdatePackageInProjects(
            IGitDriver git,
            PackageUpdateSet updateSet,
            RepositoryData repository)
        {
            try
            {
                _logger.Terse(UpdatesLogger.OldVersionsToBeUpdated(updateSet));

                git.Checkout(repository.DefaultBranch);

                // branch
                var branchName = BranchNamer.MakeName(updateSet);
                _logger.Verbose($"Using branch name: '{branchName}'");
                git.CheckoutNewBranch(branchName);

                await UpdateAllCurrentUsages(updateSet);

                var commitMessage = CommitWording.MakeCommitMessage(updateSet);
                git.Commit(commitMessage);

                git.Push("nukeeper_push", branchName);

                var prTitle = CommitWording.MakePullRequestTitle(updateSet);
                await MakeGitHubPullRequest(updateSet, repository, prTitle, branchName);

                git.Checkout(repository.DefaultBranch);
            }
            catch (Exception ex)
            {
                _logger.Error("Update failed", ex);
            }
        }
Beispiel #6
0
 /// <summary>
 /// Private ctor for singleton support.
 /// </summary>
 private UserData()
 {
     RepositoryInfo    = new RepositoryData();
     MainForm          = new MainFormData();
     View              = new ViewData();
     ObjectPermissions = new ObjectPermissionsGridData();
 }
Beispiel #7
0
        public static IList <T> LoadAll <T>(this RepositoryData item, SchemaPurpose[] schemaPurposesToInclude = null) where T : RepositoryLocalObjectData
        {
            Logger.Debug("Loading {0} for {1}", typeof(T).Name, item.Title);

            string filename  = string.Format("{0} - {1}.txt", typeof(T).Name, item.Title);
            var    subFolder = "Instances";
            var    items     = FileCache.LoadFromFile <IList <T> >(filename, subFolder);

            if (items == null)
            {
                items = TridionCoreServiceFactory.GetList <T>(item.Id, new RepositoryItemsFilterData
                {
                    BaseColumns    = ListBaseColumns.Extended,
                    ItemTypes      = new[] { ItemTypeResolver.GetItemType(typeof(T)) },
                    Recursive      = true,
                    SchemaPurposes = schemaPurposesToInclude,
                    ShowNewItems   = true
                });

                //Remove Local Copies
                items = items.Where(x => x.BluePrintInfo.IsShared == false || x.BluePrintInfo.IsLocalized == true).ToList();
                Logger.Debug("Found {0} {1} for {2}", items.Count, typeof(T).Name, item.Title);
                FileCache.SaveToFile(filename, items, subFolder);
            }
            else
            {
                Logger.Debug("Loading {0} {1} for {2} from cache", items.Count(), typeof(T).Name, item.Title);
                Logger.Debug("CACHE: {0},{1},{2}", items.Count(), typeof(T).Name, item.Title);
            }
            return(items);
        }
Beispiel #8
0
        private async Task <int> MakeUpdatePullRequests(
            IGitDriver git, RepositoryData repository,
            NuGetSources sources, SettingsContainer settings,
            IReadOnlyCollection <PackageUpdateSet> updates)
        {
            _logger.Normal(UpdatesLogger.OldVersionsToBeUpdated(updates));

            git.Checkout(repository.DefaultBranch);

            // branch
            var branchName = BranchNamer.MakeName(updates);

            _logger.Detailed($"Using branch name: '{branchName}'");
            git.CheckoutNewBranch(branchName);

            foreach (var updateSet in updates)
            {
                await _updateRunner.Update(updateSet, sources);

                var commitMessage = CommitWording.MakeCommitMessage(updateSet);
                git.Commit(commitMessage);
            }

            git.Push("nukeeper_push", branchName);

            var title = CommitWording.MakePullRequestTitle(updates);
            var body  = CommitWording.MakeCommitDetails(updates);
            await _gitHub.CreatePullRequest(repository, title, body, branchName,
                                            settings.SourceControlServerSettings.Labels);

            git.Checkout(repository.DefaultBranch);
            return(updates.Count);
        }
Beispiel #9
0
        public async Task UpdateFacility_State_Succeeds()
        {
            const string newState   = "Alabama";
            var          facilityId = RepositoryData.Facilities()[0].Id;

            using var repositoryHelper = CreateRepositoryHelper();
            using var repository       = repositoryHelper.GetFacilityRepository();
            var facility = ResourceHelper.GetFacilityDetail(facilityId);
            var updates  = new FacilityEditDto(facility)
            {
                State = newState
            };

            await repository.UpdateFacilityAsync(facilityId, updates);

            repositoryHelper.ClearChangeTracker();

            var expected = ResourceHelper.GetFacilityDetail(facilityId);

            expected.State = newState;

            var updatedFacility = await repository.GetFacilityAsync(facilityId);

            updatedFacility.Should().BeEquivalentTo(expected);
        }
Beispiel #10
0
        public static IRestResponse CreateRepository(RepositoryData repositoryData)
        {
            var restApi         = CreateRestApiHelper(PostRepo, out var restClient);
            var serializeObject = JsonConvert.SerializeObject(repositoryData);
            var restRequest     = restApi.CreatePostRequest(serializeObject);

            return(restApi.GetResponse(restClient, restRequest));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Repository"/> class.
        /// </summary>
        /// <param name="client"><see cref="T:TcmCoreService.Client" /></param>
        /// <param name="schemaData"><see cref="T:Tridion.ContentManager.CoreService.Client.RepositoryData" /></param>
        protected Repository(Client client, RepositoryData repositoryData)
            : base(client, repositoryData)
        {
            if (repositoryData == null)
                throw new ArgumentNullException("repositoryData");

            mRepositoryData = repositoryData;
        }
Beispiel #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Repository"/> class.
        /// </summary>
        /// <param name="client"><see cref="T:TcmCoreService.Client" /></param>
        /// <param name="schemaData"><see cref="T:Tridion.ContentManager.CoreService.Client.RepositoryData" /></param>
        protected Repository(Client client, RepositoryData repositoryData) : base(client, repositoryData)
        {
            if (repositoryData == null)
            {
                throw new ArgumentNullException("repositoryData");
            }

            mRepositoryData = repositoryData;
        }
Beispiel #13
0
        public void CreatesNewLineForEachOutputAndFormatsAccordinglyWhenCommitlistIsNull()
        {
            var expectedOutput = "";
            var repositoryData = new RepositoryData(null, "repositoryName", "username");

            var formattedData = repositoryData.ToString();

            Assert.AreEqual(formattedData, expectedOutput);
        }
Beispiel #14
0
        public async Task FacilityNumberExists_DuplicateIsIgnored_ReturnsFalse()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var ignoreId = RepositoryData.Facilities()[0].Id;
            var facName  = RepositoryData.Facilities()[0].Name;
            var result   = await repository.FacilityNumberExists(facName, ignoreId);

            result.ShouldBeFalse();
        }
Beispiel #15
0
        public static IRestResponse UpdateRepositoryName(string repositoryName,
                                                         RepositoryData repositoryData)
        {
            var restApi         = CreateRestApiHelper(DeleteRepo + repositoryName, out var restClient);
            var serializeObject = JsonConvert.SerializeObject(repositoryData);
            var restRequest     = restApi.CreatePatchRequest(serializeObject);

            return(restApi.GetResponse(restClient, restRequest));
        }
Beispiel #16
0
        public async Task GetFacility_ReturnsCorrectFacility()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var facility = RepositoryData.Facilities()[0];

            var result = await repository.GetFacilityAsync(facility.Id);

            result.Id.Should().Be(facility.Id);
            result.Name.Should().Be(facility.Name);
        }
Beispiel #17
0
        public async Task GetFacilityDetailListAsync_DefaultSpec_ReturnsActiveFacilities()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();

            var result = await repository.GetFacilityDetailListAsync(new FacilitySpec());

            var expectedCount = RepositoryData.Facilities().Count(e => e.Active);

            result.Count.ShouldEqual(expectedCount);
        }
Beispiel #18
0
        public async void GetReleases()
        {
            if (this.SelectedRepository == null)
            {
                this.CurrentRepository = null;
                return;
            }

            this.CurrentRepository = await this._client.GetRepository(this.SelectedRepository.Author, this.SelectedRepository.Name);
        }
Beispiel #19
0
        public async Task FacilityCount_DefaultSpec_ReturnsCountOfActiveFacilities()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var spec = new FacilitySpec();

            var result = await repository.CountAsync(spec);

            var expected = RepositoryData.Facilities().Count(e => e.Active);

            result.Should().Be(expected);
        }
Beispiel #20
0
        public void CreatesNewLineForEachOutputAndFormatsAccordinglyWhenOneCommitIsNull()
        {
            var fakeCommits = new List <GitHubCommit> {
                FakeGithubCommit, FakeGithubCommit2, Fake.GetNullCommit()
            };
            var repositoryData = new RepositoryData(fakeCommits, "repositoryName", "username");
            var expectedOutput = "[repositoryName]/[f78a226e32eb6a0320f2003859ed4d08caa53878]: refactoring [svitra]" + Environment.NewLine + "[repositoryName]/[6d95eaea321145383153692a802099577ea74c95]: cr changes [bleble]" + Environment.NewLine + "[repositoryName]/[]:  []";

            var formattedData = repositoryData.ToString();

            Assert.AreEqual(formattedData, expectedOutput);
        }
Beispiel #21
0
        public Task <RepositoryData> RepositoryAsync(CancellationToken cancel = default(CancellationToken))
        {
            var data = new RepositoryData
            {
                RepoPath   = Path.GetFullPath(ipfs.Options.Repository.Folder),
                Version    = "1",
                StorageMax = 0 // TODO: there is no storage max
            };

            GetDirStats(data.RepoPath, data, cancel);

            return(Task.FromResult(data));
        }
Beispiel #22
0
        public async Task FacilitySearch_DefaultSpec_ReturnsActiveFacilities()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();

            var result = await repository.GetFacilityPaginatedListAsync(new FacilitySpec(), 1, 999);

            var expectedCount = RepositoryData.Facilities().Count(e => e.Active);

            result.TotalCount.ShouldEqual(expectedCount);
            result.Items.Count.ShouldEqual(expectedCount);
            result.PageNumber.ShouldEqual(1);
            result.TotalPages.ShouldEqual(1);
        }
Beispiel #23
0
        private async Task <int> MakeUpdatePullRequests(
            IGitDriver git, RepositoryData repository,
            NuGetSources sources, SettingsContainer settings,
            IReadOnlyCollection <PackageUpdateSet> updates)
        {
            _logger.Normal(UpdatesLogger.OldVersionsToBeUpdated(updates));

            await git.Checkout(repository.DefaultBranch);

            // branch
            var branchWithChanges = BranchNamer.MakeName(updates, settings.BranchSettings.BranchNamePrefix);

            _logger.Detailed($"Using branch name: '{branchWithChanges}'");
            await git.CheckoutNewBranch(branchWithChanges);

            foreach (var updateSet in updates)
            {
                await _updateRunner.Update(updateSet, sources);

                var commitMessage = _collaborationFactory.CommitWorder.MakeCommitMessage(updateSet);
                await git.Commit(commitMessage);
            }

            await git.Push(repository.Remote, branchWithChanges);

            var title = _collaborationFactory.CommitWorder.MakePullRequestTitle(updates);
            var body  = _collaborationFactory.CommitWorder.MakeCommitDetails(updates);

            string qualifiedBranch;

            if (!repository.IsFork) //check if we are on a fork, if so qualify the branch name
            {
                qualifiedBranch = branchWithChanges;
            }
            else
            {
                qualifiedBranch = repository.Push.Owner + ":" + branchWithChanges;
            }

            var pullRequestRequest = new PullRequestRequest(qualifiedBranch, title, repository.DefaultBranch, settings.BranchSettings.DeleteBranchAfterMerge)
            {
                Body = body
            };

            await _collaborationFactory.CollaborationPlatform.OpenPullRequest(repository.Pull, pullRequestRequest, settings.SourceControlServerSettings.Labels);


            await git.Checkout(repository.DefaultBranch);

            return(updates.Count);
        }
Beispiel #24
0
        public async Task FacilityCount_WithDeleted_ReturnsCountOfAll()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var spec = new FacilitySpec()
            {
                ShowDeleted = true
            };

            var result = await repository.CountAsync(spec);

            var expected = RepositoryData.Facilities().Count;

            result.Should().Be(expected);
        }
        public static async Task <RepositoryData> GetRepository(this GitHubClient client, string owner, string repoName)
        {
            var releases = await client.GetReleases(owner, repoName);

            var repoInfo = new RepositoryData
            {
                Author   = owner,
                Name     = repoName,
                Releases = releases.ToArray()
            };

            repoInfo.DownloadCount = repoInfo.Releases.Sum(r => r.Downloads.Sum(d => d.DownloadCount));
            return(repoInfo);
        }
Beispiel #26
0
        public async Task UndeleteFacility_Succeeds()
        {
            var facility = RepositoryData.Facilities().First(e => e.Active);

            using var repositoryHelper = CreateRepositoryHelper();
            using var repository       = repositoryHelper.GetFacilityRepository();
            await repository.UndeleteFacilityAsync(facility.Id);

            repositoryHelper.ClearChangeTracker();

            var updatedFacility = await repository.GetFacilityAsync(facility.Id);

            updatedFacility.Active.ShouldBeTrue();
        }
Beispiel #27
0
        public async Task FacilitySearch_BeyondLastPage_ReturnsEmptyList()
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var spec = new FacilitySpec()
            {
                ShowDeleted = true
            };

            var result = await repository.GetFacilityPaginatedListAsync(spec, 999, 999);

            result.TotalCount.ShouldEqual(RepositoryData.Facilities().Count);
            result.Items.Count.ShouldEqual(0);
            result.PageNumber.ShouldEqual(999);
            result.TotalPages.ShouldEqual(1);
        }
Beispiel #28
0
        void GetDirStats(string path, RepositoryData data, CancellationToken cancel)
        {
            foreach (var file in Directory.EnumerateFiles(path))
            {
                cancel.ThrowIfCancellationRequested();
                ++data.NumObjects;
                data.RepoSize += (ulong)(new FileInfo(file).Length);
            }

            foreach (var dir in Directory.EnumerateDirectories(path))
            {
                cancel.ThrowIfCancellationRequested();
                GetDirStats(dir, data, cancel);
            }
        }
Beispiel #29
0
        // [InlineData("ghi")] Sqlite is case-sensitive by default
        public async Task FacilityCount_ByFacilityNumber_ReturnsCorrectCount(string facilityNumberSpec)
        {
            using var repository = CreateRepositoryHelper().GetFacilityRepository();
            var spec = new FacilitySpec()
            {
                FacilityNumber = facilityNumberSpec
            };

            var result = await repository.CountAsync(spec);

            var expected = RepositoryData.Facilities()
                           .Count(e => e.FacilityNumber.ToLower().Contains(facilityNumberSpec.ToLower()) && e.Active);

            result.Should().Be(expected);
        }
Beispiel #30
0
        public async Task <RepositoryData> StatisticsAsync(CancellationToken cancel = default)
        {
            var data = new RepositoryData
            {
                RepoPath   = Path.GetFullPath(_repositoryOptions.Folder),
                Version    = await VersionAsync(cancel).ConfigureAwait(false),
                StorageMax = 10000000000 // TODO: there is no storage max
            };

            var blockApi = (BlockApi)_blockApi;

            GetDirStats(blockApi.Store.Folder, data, cancel);

            return(data);
        }
Beispiel #31
0
        //  Other Methods
        //  =============

        /// <exception cref="Kallithea_Klone.MainActionException"></exception>
        public async Task CloneAsync(Uri host, RepositoryData location)
        {
            string     fullURL    = $"{host.Scheme}://{HttpUtility.UrlEncode(AccountSettings.Username)}:{HttpUtility.UrlEncode(AccountSettings.Password)}@{host.Host}{host.PathAndQuery}{location.URL}";
            CMDProcess cmdProcess = new CMDProcess("CLONE", location.Name, $"hg clone {fullURL} \"{RunLocation}\\{location.Name}\" {debugArg}");

            try
            {
                await cmdProcess.Run();
            }
            catch (Exception e)
            {
                throw new MainActionException("Unable to start the necessary command window process", e);
            }

            cmdProcess.ReportErrorsAsync(Verb);
        }
        /// <summary>
        /// Reload the <see cref="Repository" /> with the specified <see cref="T:Tridion.ContentManager.CoreService.Client.RepositoryData" />
        /// </summary>
        /// <param name="repositoryData"><see cref="T:Tridion.ContentManager.CoreService.Client.RepositoryData" /></param>
        protected void Reload(RepositoryData repositoryData)
        {
            if (repositoryData == null)
                throw new ArgumentNullException("repositoryData");

            mRepositoryData = repositoryData;
            base.Reload(repositoryData);

            mAccessControlList = null;
            mDefaultMultimediaSchema = null;
            mLocation = null;
            mMetadataSchema = null;
            mParents = null;
            mRootFolder = null;
            mTaskProcess = null;
        }
 protected override void Initialize(RequestContext requestContext)
 {
     if (Repository == null) { Repository = new RepositoryData(); }
     base.Initialize(requestContext);
 }