public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCodeCommitConfig config = new AmazonCodeCommitConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCodeCommitClient client = new AmazonCodeCommitClient(creds, config);

            ListApprovalRuleTemplatesResponse resp = new ListApprovalRuleTemplatesResponse();

            do
            {
                ListApprovalRuleTemplatesRequest req = new ListApprovalRuleTemplatesRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.ListApprovalRuleTemplates(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.ApprovalRuleTemplateNames)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        public static List <Difference> GetDifferences(AmazonCodeCommitClient codeCommit, string repositoryName, string afterCommitSpecifier)
        {
            var result = new List <Difference>();
            GetDifferencesRequest  request;
            GetDifferencesResponse response;
            string nextToken = String.Empty;
            int    count     = 0;

            do
            {
                count++;
                Console.WriteLine($"Count: {count}; RepositoryName: {repositoryName}; AfterCommitSpecifier: {afterCommitSpecifier}; Next: {nextToken}");
                request = new GetDifferencesRequest()
                {
                    RepositoryName       = repositoryName,
                    AfterCommitSpecifier = afterCommitSpecifier
                };
                if (!String.IsNullOrWhiteSpace(nextToken))
                {
                    request.NextToken = nextToken;
                }
                response = codeCommit.GetDifferencesAsync(request).GetAwaiter().GetResult();

                result.AddRange(response.Differences);
                nextToken = response.NextToken;
            } while (!String.IsNullOrEmpty(nextToken));

            return(result);
        }
        public static Cc2AfConfig GetCc2AfConfig(AmazonCodeCommitClient codeCommit, string repositoryName, string afterCommitSpecifier, string configPath)
        {
            Cc2AfConfig result;
            var         differences = GetDifferences(codeCommit, repositoryName, afterCommitSpecifier);

            var configDiff = GetConfigurationDifference(differences, configPath);

            if (configDiff == null)
            {
                var ex = new FileNotFoundException($"Unable to find Cc2Fa Configuration YAML file '{configPath}'.", configPath);
                throw ex;
            }

            var configBlob = codeCommit.GetBlobAsync(new GetBlobRequest()
            {
                BlobId         = configDiff.AfterBlob.BlobId,
                RepositoryName = repositoryName
            }).GetAwaiter().GetResult();

            using (var reader = new StreamReader(configBlob.Content))
            {
                result = YamlDeserializer.Deserialize <Cc2AfConfig>(reader);
            }

            return(result);
        }
Exemple #4
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCodeCommitConfig config = new AmazonCodeCommitConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCodeCommitClient client = new AmazonCodeCommitClient(creds, config);

            GetCommentsForComparedCommitResponse resp = new GetCommentsForComparedCommitResponse();

            do
            {
                GetCommentsForComparedCommitRequest req = new GetCommentsForComparedCommitRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.GetCommentsForComparedCommit(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.CommentsForComparedCommitData)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Exemple #5
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                System.Console.WriteLine("Parameters: <CodeCommit Repository Name> <AWS Region>");
                Environment.Exit(1);
            }
            var repositoryName = args[0];
            var awsRegion      = RegionEndpoint.GetBySystemName(args[1]);

            try
            {
                using (var ccClient = new AmazonCodeCommitClient(awsRegion))
                {
                    var triggerRequest = new PutRepositoryTriggersRequest()
                    {
                        RepositoryName = repositoryName,
                        Triggers       = new List <RepositoryTrigger>()
                    };
                    var response = ccClient.PutRepositoryTriggersAsync(triggerRequest).GetAwaiter().GetResult();
                    System.Console.WriteLine(JsonConvert.SerializeObject(response));
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// gets the Repository information
        /// </summary>
        /// <param name="codeCommit"></param>
        /// <param name="repositoryName"></param>
        /// <param name="commitId"></param>
        /// <returns></returns>
        private GetRepositoryResponse GetRepositoryInfo(AmazonCodeCommitClient codeCommit, string repositoryName)
        {
            GetRepositoryRequest repoRequest = new GetRepositoryRequest()
            {
                RepositoryName = repositoryName
            };
            GetRepositoryResponse returnValue = codeCommit.GetRepositoryAsync(repoRequest).GetAwaiter().GetResult();

            return(returnValue);
        }
        /// <summary>
        /// gets the commit information
        /// </summary>
        /// <param name="codeCommit"></param>
        /// <param name="repositoryName"></param>
        /// <param name="commitId"></param>
        /// <returns></returns>
        private GetCommitResponse GetCommitInfo(AmazonCodeCommitClient codeCommit, string repositoryName, string commitId)
        {
            GetCommitRequest commitRequest = new GetCommitRequest()
            {
                RepositoryName = repositoryName,
                CommitId       = commitId
            };
            GetCommitResponse returnValue = codeCommit.GetCommitAsync(commitRequest).GetAwaiter().GetResult();

            return(returnValue);
        }
        protected IAmazonCodeCommit CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonCodeCommitConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonCodeCommitClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Exemple #9
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCodeCommitConfig config = new AmazonCodeCommitConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCodeCommitClient client = new AmazonCodeCommitClient(creds, config);

            DescribeMergeConflictsResponse resp = new DescribeMergeConflictsResponse();

            do
            {
                DescribeMergeConflictsRequest req = new DescribeMergeConflictsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxMergeHunks = maxItems
                };

                resp = client.DescribeMergeConflicts(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.DestinationCommitId)
                {
                    AddObject(obj);
                }

                foreach (var obj in resp.SourceCommitId)
                {
                    AddObject(obj);
                }

                foreach (var obj in resp.BaseCommitId)
                {
                    AddObject(obj);
                }

                foreach (var obj in resp.ConflictMetadata)
                {
                    AddObject(obj);
                }

                foreach (var obj in resp.MergeHunks)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        //= GetBranchInfo(codeCommit, repositoryName, refBranch);
        /// <summary>
        /// gets the commit information
        /// </summary>
        /// <param name="codeCommit"></param>
        /// <param name="repositoryName"></param>
        /// <param name="branchName"></param>
        /// <returns></returns>
        private GetBranchResponse GetBranchInfo(AmazonCodeCommitClient codeCommit, string repositoryName, string branchName)
        {
            GetBranchRequest branchRequest = new GetBranchRequest()
            {
                RepositoryName = repositoryName,
                BranchName     = branchName
            };
            GetBranchResponse returnValue = null;

            try
            {
                returnValue = codeCommit.GetBranchAsync(branchRequest).GetAwaiter().GetResult();
            }
            catch (BranchDoesNotExistException)
            {
                returnValue = null;
            }
            return(returnValue);
        }
        /// <summary>
        /// A function to handle a CodeCommit Event.
        /// </summary>
        /// <param name="commitEvent"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public void FunctionHandler(CodeCommitEvent commitEvent, ILambdaContext context)
        {
            string repositoryName = commitEvent.Records[0].RepositoryName;
            string branch         = commitEvent.Records[0].codecommit.references[0].Branch;
            string commit         = commitEvent.Records[0].codecommit.references[0].commit;
            string region         = commitEvent.Records[0].awsRegion;

            string configPath = Environment.GetEnvironmentVariable(ConfigPathEnvVar);

            configPath = String.IsNullOrWhiteSpace(configPath) ? ConfigPathDefault : configPath;

            var codeCommit = new AmazonCodeCommitClient(RegionEndpoint.GetBySystemName(region));
            var repository = codeCommit.GetRepositoryAsync(
                new GetRepositoryRequest()
            {
                RepositoryName = repositoryName
            }
                ).GetAwaiter().GetResult();

            var config = GetCc2AfConfig(codeCommit, repositoryName, commit, configPath);

            var srcBranch = String.IsNullOrWhiteSpace(config.CodeCommitBranch) ? SrcBranchDefault : config.CodeCommitBranch;

            HttpResponseMessage response = null;

            if (branch == srcBranch)
            {
                var deploymentPassword = ConvertFromEncryptedBase64(config.DeploymentPassword);
                var codeCommitPassword = ConvertFromEncryptedBase64(config.CodeCommitPassword);

                response = InvokeDeployment(http:               Http,
                                            deploymentAppUrl:   config.DeploymentTriggerUrl,
                                            deploymentAppName:  config.DeploymentAppName,
                                            deploymentUser:     config.DeploymentUser,
                                            deploymentPassword: deploymentPassword,
                                            codeCommitHttpsUrl: repository.RepositoryMetadata.CloneUrlHttp,
                                            codeCommitUser:     config.CodeCommitUser,
                                            codeCommitPassword: codeCommitPassword);
            }
            WriteResults(response, configPath, config, repository, region, repositoryName, branch, commit, srcBranch);
        }
        public void HandleBranchEvent(BranchTypes.CodeCommitBranchEvent input, ILambdaContext context)
        {
            Console.WriteLine("Starting HandleBranchEvent");
            if (_Enabled)
            {
                string commitId  = "Unknown CommitID";
                string refBranch = "Unknown Branch";

                BranchTypes.Record     ccRecord     = input.Records[0];
                BranchTypes.Codecommit commitRecord = ccRecord.Codecommit;
                //I have only seen multiple references nodes in the test data
                //so we only process record [0]
                if (null != commitRecord && null != commitRecord.References && commitRecord.References.Length > 0)
                {
                    bool isDelete  = false;
                    bool isCreated = false;
                    BranchTypes.Reference ccRef = commitRecord.References[0];
                    commitId  = ccRef.Commit;
                    refBranch = ccRef.Ref;
                    if (ccRef.Deleted.HasValue)
                    {
                        isDelete = ccRef.Deleted.Value;
                    }
                    else if (ccRef.Created.HasValue)
                    {
                        isCreated = true;
                    }

                    string[] branchParts                 = refBranch.Split('/');
                    string   branchName                  = branchParts[branchParts.Length - 1];
                    string   eventSourceARN              = ccRecord.EventSourceArn;
                    string[] eventSourcARNParts          = eventSourceARN.Split(':');
                    string   repositoryName              = eventSourcARNParts[5];
                    string   regionName                  = eventSourcARNParts[3];
                    Amazon.RegionEndpoint regionEndPoint = Amazon.RegionEndpoint.GetBySystemName(regionName);
                    string   userIdentityARN             = ccRecord.UserIdentityArn;
                    string   eventTimeAsText             = ccRecord.EventTime;
                    DateTime eventTime = DateTime.Parse(eventTimeAsText).ToUniversalTime();
                    DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(eventTime, _TimeZone);

                    using (AmazonCodeCommitClient codeCommit = new AmazonCodeCommitClient(_AwsCredentials, regionEndPoint))
                    {
                        GetRepositoryResponse repositoryInfo = GetRepositoryInfo(codeCommit, repositoryName);
                        GetCommitResponse     commitInfo     = GetCommitInfo(codeCommit, repositoryName, commitId);
                        string authorName          = userIdentityARN.LastSplitElement('/');
                        string notificationMessage = "Unknown Lambda Event";
                        if (isCreated)
                        {
                            notificationMessage = GenerateBranchCreateMessage(authorName, localTime, repositoryName, branchName);
                        }
                        else if (isDelete)
                        {
                            notificationMessage = GenerateBranchDeleteMessage(authorName, localTime, repositoryName, branchName);
                        }
                        else
                        {
                            string commitParentId = "HEAD";
                            if (commitInfo.Commit.Parents.Count > 0)
                            {
                                commitParentId = commitInfo.Commit.Parents[0];
                            }
                            List <Difference> commitDifferences = GetCommitDifferences(codeCommit, repositoryName, commitId, commitParentId, _MaxChangesWarningThreshold);
                            if (_MaxChangesWarningThreshold > 0 && commitDifferences.Count >= _MaxChangesWarningThreshold)
                            {
                                notificationMessage = GenerateBranchWarningMessage(authorName, commitId, localTime, commitInfo.Commit.Message, repositoryName, branchName);
                            }
                            else
                            {
                                notificationMessage = GenerateBranchCommitMessage(authorName, commitId, localTime, commitInfo.Commit.Message, repositoryName, branchName, commitDifferences);
                            }
                        }
                        ChannelClient teamsClient = new ChannelClient(_TeamsChannelUrls);
                        teamsClient.PostMessage(notificationMessage);
                    }
                }
                else
                {
                    Console.WriteLine("No References node, nothing to process");
                }
            }
            Console.WriteLine("Completed HandleBranchEvent");
        }