Ejemplo n.º 1
0
        public virtual bool ShouldDisplay(GitContext context, ReadOnlyCollection<string> files)
        {
            foreach (var file in files)
                if (ShouldDisplay(context, file))
                    return true;

            return false;
        }
Ejemplo n.º 2
0
 public virtual void PerformAction(GitContext context, string file)
 {
 }
Ejemplo n.º 3
0
 public virtual void PerformAction(GitContext context, ReadOnlyCollection<string> files)
 {
     foreach (var file in files)
         PerformAction(context, file);
 }
Ejemplo n.º 4
0
 public virtual bool ShouldDisplay(GitContext context, string file)
 {
     return false;
 }
Ejemplo n.º 5
0
        private static int OnCloudCommand(string project, IReadOnlyList <string> metadata, string version, string ciSystem, bool allVars, bool commonVars, IReadOnlyList <string> define)
        {
            string searchPath = GetSpecifiedOrCurrentDirectoryPath(project);

            if (!Directory.Exists(searchPath))
            {
                Console.Error.WriteLine("\"{0}\" is not an existing directory.", searchPath);
                return((int)ExitCodes.NoGitRepo);
            }

            ICloudBuild activeCloudBuild = CloudBuild.Active;

            if (!string.IsNullOrEmpty(ciSystem))
            {
                int matchingIndex = Array.FindIndex(CloudProviderNames, m => string.Equals(m, ciSystem, StringComparison.OrdinalIgnoreCase));
                if (matchingIndex == -1)
                {
                    Console.Error.WriteLine("No cloud provider found by the name: \"{0}\"", ciSystem);
                    return((int)ExitCodes.NoCloudBuildProviderMatch);
                }

                activeCloudBuild = CloudBuild.SupportedCloudBuilds[matchingIndex];
            }

            using var context = GitContext.Create(searchPath, writable: AlwaysUseLibGit2);
            var oracle = new VersionOracle(context, cloudBuild: activeCloudBuild);

            if (metadata != null)
            {
                oracle.BuildMetadata.AddRange(metadata);
            }

            var variables = new Dictionary <string, string>();

            if (allVars)
            {
                foreach (var pair in oracle.CloudBuildAllVars)
                {
                    variables.Add(pair.Key, pair.Value);
                }
            }

            if (commonVars)
            {
                foreach (var pair in oracle.CloudBuildVersionVars)
                {
                    variables.Add(pair.Key, pair.Value);
                }
            }

            if (define != null)
            {
                foreach (string def in define)
                {
                    string[] split = def.Split(new char[] { '=' }, 2);
                    if (split.Length < 2)
                    {
                        Console.Error.WriteLine($"\"{def}\" is not in the NAME=VALUE syntax required for cloud variables.");
                        return((int)ExitCodes.BadCloudVariable);
                    }

                    if (variables.ContainsKey(split[0]))
                    {
                        Console.Error.WriteLine($"Cloud build variable \"{split[0]}\" specified more than once.");
                        return((int)ExitCodes.DuplicateCloudVariable);
                    }

                    variables[split[0]] = split[1];
                }
            }

            if (activeCloudBuild != null)
            {
                if (string.IsNullOrEmpty(version))
                {
                    version = oracle.CloudBuildNumber;
                }

                activeCloudBuild.SetCloudBuildNumber(version, Console.Out, Console.Error);

                foreach (var pair in variables)
                {
                    activeCloudBuild.SetCloudBuildVariable(pair.Key, pair.Value, Console.Out, Console.Error);
                }

                return((int)ExitCodes.OK);
            }
            else
            {
                Console.Error.WriteLine("No cloud build detected.");
                return((int)ExitCodes.NoCloudBuildEnvDetected);
            }
        }
Ejemplo n.º 6
0
        private static int OnTagCommand(string project, string versionOrRef)
        {
            if (string.IsNullOrEmpty(versionOrRef))
            {
                versionOrRef = DefaultRef;
            }

            string searchPath = GetSpecifiedOrCurrentDirectoryPath(project);

            using var context = (LibGit2Context)GitContext.Create(searchPath, writable: true);
            if (context is null)
            {
                Console.Error.WriteLine("No git repo found at or above: \"{0}\"", searchPath);
                return((int)ExitCodes.NoGitRepo);
            }

            var repository = context.Repository;

            if (!context.TrySelectCommit(versionOrRef))
            {
                if (!Version.TryParse(versionOrRef, out Version parsedVersion))
                {
                    Console.Error.WriteLine($"\"{versionOrRef}\" is not a simple a.b.c[.d] version spec or git reference.");
                    return((int)ExitCodes.InvalidVersionSpec);
                }

                string repoRelativeProjectDir = GetRepoRelativePath(searchPath, repository);
                var    candidateCommits       = LibGit2GitExtensions.GetCommitsFromVersion(context, parsedVersion).ToList();
                if (candidateCommits.Count == 0)
                {
                    Console.Error.WriteLine("No commit with that version found.");
                    return((int)ExitCodes.NoMatchingVersion);
                }
                else if (candidateCommits.Count > 1)
                {
                    PrintCommits(false, context, candidateCommits, includeOptions: true);
                    int selection;
                    do
                    {
                        Console.Write("Enter selection: ");
                    }while (!int.TryParse(Console.ReadLine(), out selection) || selection > candidateCommits.Count || selection < 1);
                    context.TrySelectCommit(candidateCommits[selection - 1].Sha);
                }
                else
                {
                    context.TrySelectCommit(candidateCommits.Single().Sha);
                }
            }

            var oracle = new VersionOracle(context, CloudBuild.Active);

            if (!oracle.VersionFileFound)
            {
                Console.Error.WriteLine("No version.json file found in or above \"{0}\" in commit {1}.", searchPath, context.GitCommitId);
                return((int)ExitCodes.NoVersionJsonFound);
            }

            oracle.PublicRelease = true; // assume a public release so we don't get a redundant -gCOMMITID in the tag name
            string tagName = $"v{oracle.SemVer2}";

            try
            {
                context.ApplyTag(tagName);
            }
            catch (LibGit2Sharp.NameConflictException)
            {
                var  taggedCommit = repository.Tags[tagName].Target as LibGit2Sharp.Commit;
                bool correctTag   = taggedCommit?.Sha == context.GitCommitId;
                Console.Error.WriteLine("The tag {0} is already defined ({1}).", tagName, correctTag ? "to the right commit" : $"expected {context.GitCommitId} but was on {taggedCommit.Sha}");
                return((int)(correctTag ? ExitCodes.OK : ExitCodes.TagConflict));
            }

            Console.WriteLine("{0} tag created at {1}.", tagName, context.GitCommitId);
            Console.WriteLine("Remember to push to a remote: git push origin {0}", tagName);

            return((int)ExitCodes.OK);
        }
Ejemplo n.º 7
0
        private static int OnGetVersionCommand(string project, IReadOnlyList <string> metadata, string format, string variable, string commitIsh)
        {
            if (string.IsNullOrEmpty(format))
            {
                format = DefaultOutputFormat;
            }

            if (string.IsNullOrEmpty(commitIsh))
            {
                commitIsh = DefaultRef;
            }

            string searchPath = GetSpecifiedOrCurrentDirectoryPath(project);

            using var context = GitContext.Create(searchPath, writable: AlwaysUseLibGit2);
            if (!context.IsRepository)
            {
                Console.Error.WriteLine("No git repo found at or above: \"{0}\"", searchPath);
                return((int)ExitCodes.NoGitRepo);
            }

            if (!context.TrySelectCommit(commitIsh))
            {
                Console.Error.WriteLine("rev-parse produced no commit for {0}", commitIsh);
                return((int)ExitCodes.BadGitRef);
            }

            var oracle = new VersionOracle(context, CloudBuild.Active);

            if (metadata != null)
            {
                oracle.BuildMetadata.AddRange(metadata);
            }

            // Take the PublicRelease environment variable into account, since the build would as well.
            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("PublicRelease")) && bool.TryParse(Environment.GetEnvironmentVariable("PublicRelease"), out bool publicRelease))
            {
                oracle.PublicRelease = publicRelease;
            }

            if (string.IsNullOrEmpty(variable))
            {
                switch (format.ToLowerInvariant())
                {
                case "text":
                    Console.WriteLine("Version:                      {0}", oracle.Version);
                    Console.WriteLine("AssemblyVersion:              {0}", oracle.AssemblyVersion);
                    Console.WriteLine("AssemblyInformationalVersion: {0}", oracle.AssemblyInformationalVersion);
                    Console.WriteLine("NuGetPackageVersion:          {0}", oracle.NuGetPackageVersion);
                    Console.WriteLine("NpmPackageVersion:            {0}", oracle.NpmPackageVersion);
                    break;

                case "json":
                    var converters = new JsonConverter[]
                    {
                        new Newtonsoft.Json.Converters.VersionConverter(),
                    };
                    Console.WriteLine(JsonConvert.SerializeObject(oracle, Formatting.Indented, converters));
                    break;

                default:
                    Console.Error.WriteLine("Unsupported format: {0}", format);
                    return((int)ExitCodes.UnsupportedFormat);
                }
            }
            else
            {
                if (format != "text")
                {
                    Console.Error.WriteLine("Format must be \"text\" when querying for an individual variable's value.");
                    return((int)ExitCodes.UnsupportedFormat);
                }

                var property = oracle.GetType().GetProperty(variable, CaseInsensitiveFlags);
                if (property == null)
                {
                    Console.Error.WriteLine("Variable \"{0}\" not a version property.", variable);
                    return((int)ExitCodes.BadVariable);
                }

                Console.WriteLine(property.GetValue(oracle));
            }

            return((int)ExitCodes.OK);
        }
Ejemplo n.º 8
0
        private static int OnInstallCommand(string path, string version, IReadOnlyList <string> source)
        {
            if (!SemanticVersion.TryParse(string.IsNullOrEmpty(version) ? DefaultVersionSpec : version, out var semver))
            {
                Console.Error.WriteLine($"\"{version}\" is not a semver-compliant version spec.");
                return((int)ExitCodes.InvalidVersionSpec);
            }

            var options = new VersionOptions
            {
                Version = semver,
                PublicReleaseRefSpec = new string[]
                {
                    @"^refs/heads/master$",
                    @"^refs/heads/v\d+(?:\.\d+)?$",
                },
                CloudBuild = new VersionOptions.CloudBuildOptions
                {
                    BuildNumber = new VersionOptions.CloudBuildNumberOptions
                    {
                        Enabled = true,
                    },
                },
            };
            string searchPath = GetSpecifiedOrCurrentDirectoryPath(path);

            if (!Directory.Exists(searchPath))
            {
                Console.Error.WriteLine("\"{0}\" is not an existing directory.", searchPath);
                return((int)ExitCodes.NoGitRepo);
            }

            using var context = GitContext.Create(searchPath, writable: true);
            if (!context.IsRepository)
            {
                Console.Error.WriteLine("No git repo found at or above: \"{0}\"", searchPath);
                return((int)ExitCodes.NoGitRepo);
            }

            if (string.IsNullOrEmpty(path))
            {
                path = context.WorkingTreePath;
            }

            var existingOptions = context.VersionFile.GetVersion();

            if (existingOptions != null)
            {
                if (!string.IsNullOrEmpty(version))
                {
                    var setVersionExitCode = OnSetVersionCommand(path, version);
                    if (setVersionExitCode != (int)ExitCodes.OK)
                    {
                        return(setVersionExitCode);
                    }
                }
            }
            else
            {
                string versionJsonPath = context.VersionFile.SetVersion(path, options);
                context.Stage(versionJsonPath);
            }

            // Create/update the Directory.Build.props file in the directory of the version.json file to add the NB.GV package.
            string             directoryBuildPropsPath = Path.Combine(path, "Directory.Build.props");
            ProjectRootElement propsFile = File.Exists(directoryBuildPropsPath)
                ? ProjectRootElement.Open(directoryBuildPropsPath)
                : ProjectRootElement.Create(directoryBuildPropsPath);

            const string PackageReferenceItemType = "PackageReference";

            if (!propsFile.Items.Any(i => i.ItemType == PackageReferenceItemType && i.Include == PackageId))
            {
                // Validate given sources
                foreach (var src in source)
                {
                    // TODO: Can declare Option<Uri> to validate argument during parsing.
                    if (!Uri.TryCreate(src, UriKind.Absolute, out var _))
                    {
                        Console.Error.WriteLine($"\"{src}\" is not a valid NuGet package source.");
                        return((int)ExitCodes.InvalidNuGetPackageSource);
                    }
                }

                string packageVersion = GetLatestPackageVersionAsync(PackageId, path, source).GetAwaiter().GetResult();
                if (string.IsNullOrEmpty(packageVersion))
                {
                    string verifyPhrase = source.Any()
                        ? "Please verify the given 'source' option(s)."
                        : "Please verify the package sources in the NuGet.Config files.";
                    Console.Error.WriteLine($"Latest stable version of the {PackageId} package could not be determined. " + verifyPhrase);
                    return((int)ExitCodes.PackageIdNotFound);
                }

                var item = propsFile.AddItem(
                    PackageReferenceItemType,
                    PackageId,
                    new Dictionary <string, string>
                {
                    { "Version", packageVersion },
                    { "PrivateAssets", "all" },
                });
                item.Condition = "!Exists('packages.config')";

                propsFile.Save(directoryBuildPropsPath);
            }

            context.Stage(directoryBuildPropsPath);

            return((int)ExitCodes.OK);
        }
Ejemplo n.º 9
0
 protected override GitContext CreateGitContext(string path, string committish = null) => GitContext.Create(path, committish, writable: true);
 public FavoriteController()
 {
     db = new GitContext();
 }