Пример #1
0
        private static void Main(string[] args)
        {
            var result = CommandLine.Parser.Default.ParseArguments<Options>(args);
              if (!result.Errors.Any())
              {
            string url = result.Value.Repository;

            var brancOption = result.Value.Branch;
            var branchSepIndex = brancOption.IndexOf('/');
            if (branchSepIndex > 0)
            {
              var credentials = new UsernamePasswordCredentials
            {
              Username = result.Value.UserName,
              Password = result.Value.Password
            };
              CredentialsHandler credHandler = (s, fromUrl, types) => credentials;

              var remote = brancOption.Substring(0, branchSepIndex);
              var branch = brancOption.Substring(branchSepIndex+1, brancOption.Length - branchSepIndex-1);

              var workingDirectory = result.Value.LocalRepoPath;

              var isLocalRepoExist = Repository.Discover(workingDirectory);
              if (isLocalRepoExist == null)
              {
            var cloneOptions = new CloneOptions {CredentialsProvider = credHandler};
            Repository.Clone(url, workingDirectory, cloneOptions);
              }

              Repository repo = null;
              try
              {
            var tagName = result.Value.TagName;
            repo = new Repository(workingDirectory);
            //repo.Fetch(remote, new FetchOptions(){CredentialsProvider = credHandler});
            repo.Network.Pull(new Signature(result.Value.UserName,result.Value.Email, new DateTimeOffset()),
              new PullOptions() { FetchOptions = new FetchOptions() { CredentialsProvider = credHandler } });
            repo.ApplyTag(tagName);
            PushChanges(repo, credHandler, remote, branch, tagName);
            Console.WriteLine("Tagged :{0}", result.Value.TagName);
              }
              catch (Exception ex)
              {
            Console.WriteLine("Error happened {0}", ex.Message);
              }
              finally
              {
            if (repo != null) repo.Dispose();
              }
            }
              }
              Console.ReadLine();
        }
Пример #2
0
        static async Task <int> MainAsync(string[] args)
        {
            var projDir = Environment.CurrentDirectory;

            while (!File.Exists(projDir + "/CHANGELOG.md"))
            {
                projDir = Path.GetDirectoryName(projDir);
                if (string.IsNullOrWhiteSpace(projDir))
                {
                    Console.WriteLine("Cannot find CHANGELOG.md in some parent directory");
                    return(1);
                }
            }
            Console.WriteLine("Project root directory: " + projDir);
            var logLines    = File.ReadAllLines(projDir + "/CHANGELOG.md");
            var topVersion  = logLines.Where(s => s.StartsWith("## ")).FirstOrDefault();
            var lastVersion = logLines.Where(s => s.StartsWith("## ")).Skip(1).FirstOrDefault();

            if (logLines.Length < 5)
            {
                Console.WriteLine("CHANGELOG.md has less than 5 lines");
                return(1);
            }
            if (topVersion != "## [unreleased]")
            {
                Console.WriteLine("Top version should be ## [unreleased]");
                return(1);
            }
            if (lastVersion == null)
            {
                Console.WriteLine("Cannot find previous version");
                return(1);
            }
            using (var gitrepo = new LibGit2Sharp.Repository(projDir))
            {
                int workDirChangesCount = 0;
                using (var workDirChanges = gitrepo.Diff.Compare <TreeChanges>())
                    workDirChangesCount = workDirChanges.Count;
                if (workDirChangesCount > 0)
                {
                    Console.WriteLine("DANGER! THERE ARE " + workDirChangesCount + " CHANGES IN WORK DIR!");
                }
                var topVersionLine     = Array.IndexOf(logLines, topVersion);
                var lastVersionLine    = Array.IndexOf(logLines, lastVersion);
                var lastVersionNumber  = new System.Version(lastVersion.Substring(3));
                var patchVersionNumber = new System.Version(lastVersionNumber.Major, lastVersionNumber.Minor, lastVersionNumber.Build + 1);
                var minorVersionNumber = new System.Version(lastVersionNumber.Major, lastVersionNumber.Minor + 1, 0);
                var majorVersionNumber = new System.Version(lastVersionNumber.Major + 1, 0, 0);
                Console.WriteLine("Press 1 for Major " + majorVersionNumber.ToString(3));
                Console.WriteLine("Press 2 for Minor " + minorVersionNumber.ToString(3));
                Console.WriteLine("Press 3 for Patch " + patchVersionNumber.ToString(3));
                var choice = Console.ReadKey().KeyChar;
                Console.WriteLine();
                if (choice < '1' || choice > '3')
                {
                    Console.WriteLine("Not pressed 1, 2 or 3. Exiting.");
                    return(1);
                }
                if (choice == '1')
                {
                    lastVersionNumber = majorVersionNumber;
                }
                if (choice == '2')
                {
                    lastVersionNumber = minorVersionNumber;
                }
                if (choice == '3')
                {
                    lastVersionNumber = patchVersionNumber;
                }
                var newVersion = lastVersionNumber.ToString(3);
                Console.WriteLine("Building version " + newVersion);
                var outputLogLines  = logLines.ToList();
                var releaseLogLines = logLines.Skip(topVersionLine + 1).SkipWhile(s => string.IsNullOrWhiteSpace(s)).TakeWhile(s => !s.StartsWith("## ")).ToList();
                while (releaseLogLines.Count > 0 && string.IsNullOrWhiteSpace(releaseLogLines[releaseLogLines.Count - 1]))
                {
                    releaseLogLines.RemoveAt(releaseLogLines.Count - 1);
                }
                outputLogLines.Insert(topVersionLine + 1, "## " + newVersion);
                outputLogLines.Insert(topVersionLine + 1, "");
                if (Directory.Exists(projDir + "/bb/bin/Release/net5.0"))
                {
                    Directory.Delete(projDir + "/bb/bin/Release/net5.0", true);
                }
                BuildWinX64(projDir, newVersion);
                BuildLinuxX64(projDir, newVersion);
                BuildOsxX64(projDir, newVersion);
                var client = new GitHubClient(new ProductHeaderValue("bobril-bbcore-releaser"));
                client.SetRequestTimeout(TimeSpan.FromMinutes(15));
                var    fileNameOfToken = Environment.GetEnvironmentVariable("USERPROFILE") + "/.github/token.txt";
                string token;
                try
                {
                    token = File.ReadAllLines(fileNameOfToken).First();
                }
                catch
                {
                    Console.WriteLine("Cannot read github token from " + fileNameOfToken);
                    return(1);
                }
                client.Credentials = new Octokit.Credentials(token);
                var bbcoreRepo = (await client.Repository.GetAllForOrg("bobril")).First(r => r.Name == "bbcore");
                Console.WriteLine("bbcore repo id: " + bbcoreRepo.Id);
                File.WriteAllText(projDir + "/CHANGELOG.md", string.Join("", outputLogLines.Select(s => s + '\n')));
                Commands.Stage(gitrepo, "CHANGELOG.md");
                var author    = new LibGit2Sharp.Signature("Releaser", "*****@*****.**", DateTime.Now);
                var committer = author;
                var commit    = gitrepo.Commit("Released " + newVersion, author, committer);
                gitrepo.ApplyTag(newVersion);
                var options = new PushOptions();
                options.CredentialsProvider = (url, usernameFromUrl, types) =>
                                              new UsernamePasswordCredentials()
                {
                    Username = token,
                    Password = ""
                };
                gitrepo.Network.Push(gitrepo.Head, options);
                var release = new NewRelease(newVersion);
                release.Name       = newVersion;
                release.Body       = string.Join("", releaseLogLines.Select(s => s + '\n'));
                release.Prerelease = true;
                var release2 = await client.Repository.Release.Create(bbcoreRepo.Id, release);

                Console.WriteLine("release url:");
                Console.WriteLine(release2.HtmlUrl);
                var uploadAsset = await UploadWithRetry(projDir, client, release2, "win-x64.zip");

                Console.WriteLine("win-x64 url:");
                Console.WriteLine(uploadAsset.BrowserDownloadUrl);
                uploadAsset = await UploadWithRetry(projDir, client, release2, "linux-x64.zip");

                Console.WriteLine("linux-x64 url:");
                Console.WriteLine(uploadAsset.BrowserDownloadUrl);
                uploadAsset = await UploadWithRetry(projDir, client, release2, "osx-x64.zip");

                Console.WriteLine("osx-x64 url:");
                Console.WriteLine(uploadAsset.BrowserDownloadUrl);
                DockerBuild(projDir, newVersion);
                Console.WriteLine("Press Enter for finish");
                Console.ReadLine();
                return(0);
            }
        }
Пример #3
0
        public void GetGitVersion()
        {
            commitChangesToReadme(repo, "Hej", "Added Readme");

            verifyVersion(repo, 0, 0, 1, "beta.1");

            commitChangesToGitVersionFile(repo, "1.0.0", "Added .gitversion file with version = 1.0.0");

            verifyVersion(repo, 1, 0, 0, "beta.1");


            var featureBranch = repo.CreateBranch("feature");

            Commands.Checkout(repo, featureBranch);
            commitChangesToReadme(repo, "Hej2", "Changed Readme on feature branch");

            verifyVersion(repo, 1, 0, 0, "alpha.1.1", featureBranch.FriendlyName);

            Commands.Checkout(repo, "master");
            repo.Merge(featureBranch, me, noFastForward);

            verifyVersion(repo, 1, 0, 0, "beta.2");

            commitChangesToReadme(repo, "Version 2", "Bumped version to 2.0");
            commitChangesToGitVersionFile(repo, "2.0.0", "Updated version to 2.0.0 in .gitversion file");

            verifyVersion(repo, 2, 0, 0, "beta.1");


            repo.CreateBranch("release2x");
            Commands.Checkout(repo, "release2x");

            verifyVersion(repo, 2, 0, 0, "rc");

            Commands.Checkout(repo, "master");

            verifyVersion(repo, 2, 0, 0, "beta.1");

            Commands.Checkout(repo, "release2x");
            repo.ApplyTag("v2.0.0", me, "Official 2.0.0 release");

            verifyVersion(repo, 2, 0, 0, null);

            Commands.Checkout(repo, "master");
            commitChangesToGitVersionFile(repo, "2.1.0", "Bumped version to 2.1");
            verifyVersion(repo, 2, 1, 0, "beta.1");
            featureBranch = repo.CreateBranch("feature2");
            Commands.Checkout(repo, featureBranch);
            commitChangesToReadme(repo, "Version 2.1 something", "Changed readme");
            verifyVersion(repo, 2, 1, 0, "alpha.1.1", featureBranch.FriendlyName);
            Commands.Checkout(repo, "master");
            repo.Merge(featureBranch, me, noFastForward);
            verifyVersion(repo, 2, 1, 0, "beta.2");
            Commands.Checkout(repo, "release2x");
            repo.Merge("master", me, noFastForward);


            // At this point we have created the following git history:
            // *   Merge branch 'master' into 'rc2x'
            // |\
            // | *   (master) Merge branch 'feature2'
            // | |\
            // | | * (feature2) Changed readme
            // | |/
            // | *   (tag: v2.1) Bumped version to 2.1
            // |/
            // *     (tag: v2.0, release2x) Bumped version to 2.0
            var commit210rc = repo.Head.Tip;

            verifyVersion(repo, 2, 1, 0, "rc.1");

            var hotfixBranch = repo.CreateBranch("hotfix");

            Commands.Checkout(repo, hotfixBranch);
            commitChangesToReadme(repo, "Version 2.1 hotfix", "Changed readme on hotfix branch.");
            Commands.Checkout(repo, "release2x");
            repo.Merge(hotfixBranch, me, noFastForward);

            // At this point we have created the following git history:
            // *   (rc2x) Merge branch 'hotfix' into 'rc2x'
            // |\
            // | *   (hotfix) Changed readme on hotfix branch.
            // |/
            // *   Merge branch 'master' into 'rc2x'
            // |\
            // | *   (master) Merge branch 'feature2'
            // | |\
            // | | * (feature2) Changed readme
            // | |/
            // | *   (tag: v2.1) Bumped version to 2.1
            // |/
            // *     (tag: v2.0, release2x) Bumped version to 2.0
            new GitVersionAction()
            {
                PrintLog = "10", RepoPath = repo.Info.WorkingDirectory
            }.Execute(new System.Threading.CancellationToken());
            verifyVersion(repo, 2, 1, 0, "rc.2");

            // Now we will try to go back to a previous commit (not the HEAD):
            // This is what GitLab CI does, so important for us to support

            //Commands.Checkout(repo, shortHash211alpha);
            //verifyVersion(2, 1, 0, "alpha.1.1", shortHash211alpha + ".hotfix");   // TODO: This fails and we should try to improve. See TODO in GitVersionCalulator

            Commands.Checkout(repo, commit210rc);
            verifyVersion(repo, commit210rc, 2, 1, 0, "rc.1");
        }
Пример #4
0
        public string Commit(string message = "")
        {
            string commitId = null;
            var    now      = DateTime.Now;

            message = $"[{now.ToShortDateString()} {now.ToShortTimeString()}] {message}";

            using (var repo = new LibGit2Sharp.Repository(_repositoryFolderName))
            {
                var diffs = repo.Diff.Compare <TreeChanges>(null, true);

                if (diffs.Count() > 0)
                {
                    // This is a repository with existing submissions AND this
                    // commit has changes

                    foreach (var diff in diffs)
                    {
                        if (diff.Status == ChangeKind.Added)
                        {
                            repo.Index.Add(diff.Path);
                        }
                        else if (diff.Status == ChangeKind.Deleted)
                        {
                            repo.Index.Remove(diff.Path);
                        }
                        Commands.Stage(repo, diff.Path);
                    }

                    // TODO: Get Signature info from configuration file
                    Signature sig = new Signature("auger", "*****@*****.**", DateTimeOffset.Now);

                    try
                    {
                        commitId = _Retry(() =>
                        {
                            var commit = repo.Commit(message, sig, sig);
                            return(commit.Sha);
                        });

                        if (repo.Tags.Any(t => t.FriendlyName == "LATEST"))
                        {
                            repo.Tags.Remove("LATEST");
                        }
                        repo.ApplyTag("LATEST");
                        //repo.ApplyTag("DATETIME", sig, now.Ticks.ToString());
                    }
                    catch (EmptyCommitException) { } // ignore this but throw others
                }
                else if (!repo.Commits.Any())
                {
                    // This is the first commit for this repository

                    // TODO: Get Signature info from configuration file
                    Signature sig = new Signature("auger", "*****@*****.**", DateTimeOffset.Now);

                    commitId = _Retry(() => {
                        var commit = repo.Commit(message, sig, sig);
                        return(commit.Sha);
                    });

                    repo.ApplyTag("LATEST");
                    //repo.ApplyTag("DATETIME", sig, now.Ticks.ToString());
                }
                else
                {
                    // No changes to an existing repository. Return null for
                    // the commitId to indicate no change.
                }
            }
            _currentCommitId = commitId;
            return(commitId);
        }
Пример #5
0
        private void InitCoreTags(Repository repo)
        {
            // Create tags for Upvote, Downvote, and EmptyTree
            Tree emptyTree = repo.ObjectDatabase.CreateTree(new TreeDefinition());
            repo.ApplyTag(EMPTY_TREE, emptyTree.Sha);

            Blob upvote = repo.ObjectDatabase.CreateBlob(new MemoryStream(Encoding.ASCII.GetBytes(UPVOTE)));
            repo.ApplyTag(UPVOTE, upvote.Sha);

            Blob downvote = repo.ObjectDatabase.CreateBlob(new MemoryStream(Encoding.ASCII.GetBytes(DOWNVOTE)));
            repo.ApplyTag(DOWNVOTE, downvote.Sha);
        }