Esempio n. 1
0
        public static async Task RunInstallationMessage(
            [QueueTrigger("installationmessage")] InstallationMessage installationMessage,
            [Table("installation")] ICollector <Installation> installations,
            [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation,
            [Queue("openprmessage")] ICollector <OpenPrMessage> openPrMessages,
            TraceWriter log,
            ExecutionContext context)
        {
            // if not already installed
            if (installation == null)
            {
                installations.Add(new Installation(installationMessage.InstallationId, installationMessage.RepoName)
                {
                    AccessTokensUrl = installationMessage.AccessTokensUrl,
                    CloneUrl        = installationMessage.CloneUrl,
                    Owner           = installationMessage.Owner,
                });
            }

            var installationTokenParameters = new InstallationTokenParameters
            {
                AccessTokensUrl = installationMessage.AccessTokensUrl,
                AppId           = KnownGitHubs.AppId,
            };

            // good for ~10 minutes
            var installationToken = await InstallationToken.GenerateAsync(
                installationTokenParameters,
                File.OpenText(Path.Combine(context.FunctionDirectory, $"..\\{KnownGitHubs.AppPrivateKey}")));

            var compressImagesParameters = new CompressimagesParameters
            {
                CloneUrl            = installationMessage.CloneUrl,
                LocalPath           = LocalPath.CloneDir(Environment.GetEnvironmentVariable("TMP"), installationMessage.RepoName),
                Password            = installationToken.Token,
                RepoName            = installationMessage.RepoName,
                RepoOwner           = installationMessage.Owner,
                PgpPrivateKeyStream = File.OpenRead(Path.Combine(context.FunctionDirectory, $"..\\{KnownGitHubs.PGPPrivateKeyFilename}")),
                PgPPassword         = File.ReadAllText(Path.Combine(context.FunctionDirectory, $"..\\{KnownGitHubs.PGPPasswordFilename}"))
            };

            var didCompress = CompressImages.Run(compressImagesParameters);

            if (didCompress)
            {
                openPrMessages.Add(new OpenPrMessage
                {
                    InstallationId = installationMessage.InstallationId,
                    RepoName       = installationMessage.RepoName,
                });
            }
        }
Esempio n. 2
0
        public static bool Run(CompressimagesParameters parameters)
        {
            CredentialsHandler credentialsProvider =
                (url, user, cred) =>
                new UsernamePasswordCredentials {
                Username = KnownGitHubs.Username, Password = parameters.Password
            };

            // clone
            var cloneOptions = new CloneOptions
            {
                CredentialsProvider = credentialsProvider,
            };

            Repository.Clone(parameters.CloneUrl, parameters.LocalPath, cloneOptions);

            var repo   = new Repository(parameters.LocalPath);
            var remote = repo.Network.Remotes["origin"];

            // check if we have the branch already or this is empty repo
            try
            {
                if (repo.Network.ListReferences(remote, credentialsProvider).Any() == false)
                {
                    return(false);
                }

                if (repo.Network.ListReferences(remote, credentialsProvider).Any(x => x.CanonicalName == $"refs/heads/{KnownGitHubs.BranchName}"))
                {
                    return(false);
                }
            }
            catch
            {
                // ignore
            }

            var repoConfiguration = new RepoConfiguration();

            try
            {
                // see if .imgbotconfig exists in repo root
                var repoConfigJson = File.ReadAllText(parameters.LocalPath + "\\.imgbotconfig");
                if (!string.IsNullOrEmpty(repoConfigJson))
                {
                    repoConfiguration = JsonConvert.DeserializeObject <RepoConfiguration>(repoConfigJson);
                }
            }
            catch
            {
                // ignore
            }

            if (Schedule.ShouldOptimizeImages(repoConfiguration, repo) == false)
            {
                return(false);
            }

            // check out the branch
            repo.CreateBranch(KnownGitHubs.BranchName);
            var branch = Commands.Checkout(repo, KnownGitHubs.BranchName);

            // optimize images
            var imagePaths      = ImageQuery.FindImages(parameters.LocalPath, repoConfiguration);
            var optimizedImages = OptimizeImages(repo, parameters.LocalPath, imagePaths);

            if (optimizedImages.Length == 0)
            {
                return(false);
            }

            // create commit message based on optimizations
            var commitMessage = CommitMessage.Create(optimizedImages);

            // commit
            var signature = new Signature(KnownGitHubs.ImgBotLogin, KnownGitHubs.ImgBotEmail, DateTimeOffset.Now);

            repo.Commit(commitMessage, signature, signature);

            // We just made a normal commit, now we are going to capture all the values generated from that commit
            // then rewind and make a signed commit

            var commitBuffer = Commit.CreateBuffer(
                repo.Head.Tip.Author,
                repo.Head.Tip.Committer,
                repo.Head.Tip.Message,
                repo.Head.Tip.Tree,
                repo.Head.Tip.Parents,
                true,
                null);

            var signedCommitData = CommitSignature.Sign(commitBuffer + "\n", parameters.PgpPrivateKeyStream, parameters.PgPPassword);

            repo.Reset(ResetMode.Soft, repo.Head.Commits.Skip(1).First().Sha);
            var commitToKeep = repo.ObjectDatabase.CreateCommitWithSignature(commitBuffer, signedCommitData);

            repo.Refs.UpdateTarget(repo.Refs.Head, commitToKeep);
            var branchAgain = Commands.Checkout(repo, KnownGitHubs.BranchName);

            repo.Reset(ResetMode.Hard, commitToKeep.Sha);

            // push to GitHub
            repo.Network.Push(remote, $"refs/heads/{KnownGitHubs.BranchName}", new PushOptions
            {
                CredentialsProvider = credentialsProvider,
            });

            return(true);
        }