コード例 #1
0
        void CreateTempAssemblyInfo(VersionVariables versionVariables)
        {
            if (IntermediateOutputPath == null)
            {
                var tempFileName = string.Format("AssemblyInfo_{0}_{1}.g.cs", Path.GetFileNameWithoutExtension(ProjectFile), Path.GetRandomFileName());
                AssemblyInfoTempFilePath = Path.Combine(TempFileTracker.TempPath, tempFileName);
            }
            else
            {
                AssemblyInfoTempFilePath = Path.Combine(IntermediateOutputPath, "GitVersionTaskAssemblyInfo.g.cs");
            }

            var assemblyInfoBuilder = new AssemblyInfoBuilder();
            var assemblyInfo = assemblyInfoBuilder.GetAssemblyInfoText(versionVariables, RootNamespace).Trim();

            // We need to try to read the existing text first if the file exists and see if it's the same
            // This is to avoid writing when there's no differences and causing a rebuild
            try
            {
                if (File.Exists(AssemblyInfoTempFilePath))
                {
                    var content = File.ReadAllText(AssemblyInfoTempFilePath, Encoding.UTF8).Trim();
                    if (string.Equals(assemblyInfo, content, StringComparison.Ordinal))
                        return; // nothign to do as the file matches what we'd create
                }
            }
            catch (Exception)
            {
                // Something happened reading the file, try to overwrite anyway
            }

            File.WriteAllText(AssemblyInfoTempFilePath, assemblyInfo, Encoding.UTF8);
        }
コード例 #2
0
ファイル: GitVersionCache.cs プロジェクト: qetza/GitVersion
        public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache)
        {
            var cacheDir = PrepareCacheDirectory(gitPreparer);
            var cacheFileName = GetCacheFileName(cacheKey, cacheDir);

            variablesFromCache.FileName = cacheFileName;

            Dictionary<string, string> dictionary;
            using (Logger.IndentLog("Creating dictionary"))
            {
                dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
            }

            Action writeCacheOperation = () =>
            {
                using (var stream = fileSystem.OpenWrite(cacheFileName))
                {
                    using (var sw = new StreamWriter(stream))
                    {
                        using (Logger.IndentLog("Storing version variables to cache file " + cacheFileName))
                        {
                            var serializer = new Serializer();
                            serializer.Serialize(sw, dictionary);
                        }
                    }
                }
            };

            var retryOperation = new OperationWithExponentialBackoff<IOException>(new ThreadSleep(), writeCacheOperation, maxRetries: 6);
            retryOperation.Execute();
        }
コード例 #3
0
ファイル: AppVeyor.cs プロジェクト: pierrebakker/GitVersion
        public override string GenerateSetVersionMessage(VersionVariables variables)
        {
            var buildNumber = Environment.GetEnvironmentVariable("APPVEYOR_BUILD_NUMBER");

            var restBase = Environment.GetEnvironmentVariable("APPVEYOR_API_URL");

            var request = (HttpWebRequest)WebRequest.Create(restBase + "api/build");
            request.Method = "PUT";

            var data = string.Format("{{ \"version\": \"{0} (Build {1})\" }}", variables.FullSemVer, buildNumber);
            var bytes = Encoding.UTF8.GetBytes(data);
            request.ContentLength = bytes.Length;
            request.ContentType = "application/json";

            using (var writeStream = request.GetRequestStream())
            {
                writeStream.Write(bytes, 0, bytes.Length);
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
                {
                    var message = string.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    return message;
                }
            }

            return string.Format("Set AppVeyor build number to '{0} (Build {1})'.", variables.FullSemVer, buildNumber);
        }
コード例 #4
0
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Console.WriteLine("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem);

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var backupAssemblyInfo = assemblyInfoFile + ".bak";
                var localAssemblyInfo = assemblyInfoFile;
                fileSystem.Copy(assemblyInfoFile, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var assemblyVersion = variables.AssemblySemVer;
                var assemblyInfoVersion = variables.InformationalVersion;
                var assemblyFileVersion = variables.MajorMinorPatch + ".0";
                var fileContents = fileSystem.ReadAllText(assemblyInfoFile)
                    .RegexReplace(@"AssemblyVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyVersion(\"{0}\")", assemblyVersion))
                    .RegexReplace(@"AssemblyInformationalVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion))
                    .RegexReplace(@"AssemblyFileVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion));

                fileSystem.WriteAllText(assemblyInfoFile, fileContents);
            }
        }
コード例 #5
0
        public static VersionVariables GetVariablesFor(SemanticVersion semanticVersion, EffectiveConfiguration config, bool isCurrentCommitTagged)
        {
            if (config.VersioningMode == VersioningMode.ContinuousDeployment && !isCurrentCommitTagged)
            {
                semanticVersion = new SemanticVersion(semanticVersion);
                // Continuous Deployment always requires a pre-release tag unless the commit is tagged
                if (!semanticVersion.PreReleaseTag.HasTag())
                {
                    semanticVersion.PreReleaseTag.Name = config.ContinuousDeploymentFallbackTag;
                }

                // For continuous deployment the commits since tag gets promoted to the pre-release number
                semanticVersion.PreReleaseTag.Number = semanticVersion.BuildMetaData.CommitsSinceTag;
                semanticVersion.BuildMetaData.CommitsSinceTag = null;
            }

            var semverFormatValues = new SemanticVersionFormatValues(semanticVersion, config);

            string informationalVersion;

            if (string.IsNullOrEmpty(config.AssemblyInformationalFormat))
            {
                informationalVersion = semverFormatValues.DefaultInformationalVersion;
            }
            else
            {
                try
                {
                    informationalVersion = config.AssemblyInformationalFormat.FormatWith(semverFormatValues);
                }
                catch (FormatException formex)
                {
                    throw new WarningException(string.Format("Unable to format AssemblyInformationalVersion.  Check your format string: {0}", formex.Message));
                }
            }

            var variables = new VersionVariables(
                semverFormatValues.Major,
                semverFormatValues.Minor,
                semverFormatValues.Patch,
                semverFormatValues.BuildMetaData,
                semverFormatValues.BuildMetaDataPadded,
                semverFormatValues.FullBuildMetaData,
                semverFormatValues.BranchName,
                semverFormatValues.Sha,
                semverFormatValues.MajorMinorPatch,
                semverFormatValues.SemVer,
                semverFormatValues.LegacySemVer,
                semverFormatValues.LegacySemVerPadded,
                semverFormatValues.FullSemVer,
                semverFormatValues.AssemblySemVer,
                semverFormatValues.PreReleaseTag,
                semverFormatValues.PreReleaseTagWithDash,
                informationalVersion,
                semverFormatValues.CommitDate,
                semverFormatValues.NuGetVersion,
                semverFormatValues.NuGetVersionV2);

            return variables;
        }
コード例 #6
0
    public string GetAssemblyInfoText(VersionVariables vars, string rootNamespace, ProjectType projectType)
    {
        string assemblyInfoFormat;
        if (projectType == ProjectType.CSharp)
        {
            assemblyInfoFormat = csharpAssemblyInfoFormat;
        }
        else if (projectType == ProjectType.FSharp)
        {
            assemblyInfoFormat = fsharpAssemblyInfoFormat;
        }
        else
        {
            throw new ArgumentException("ProjectType");
        }

        var v = vars.ToList();

        var assemblyInfo = string.Format(
        assemblyInfoFormat,
        vars.AssemblySemVer,
        vars.MajorMinorPatch + ".0",
        vars.InformationalVersion,
        GenerateStaticVariableMembers(v, projectType),
        rootNamespace);

        return assemblyInfo;
    }
コード例 #7
0
        public static IEnumerable<string> GenerateBuildLogOutput(IBuildServer buildServer, VersionVariables variables)
        {
            var output = new List<string>();

            foreach (var variable in variables)
            {
                output.AddRange(buildServer.GenerateSetParameterMessage(variable.Key, variable.Value));
            }

            return output;
        }
コード例 #8
0
ファイル: VsoAgent.cs プロジェクト: pierrebakker/GitVersion
        public override string GenerateSetVersionMessage(VersionVariables variables)
        {
            // For VSO, we'll get the Build Number and insert GitVersion variables where
            // specified

            var buildNum = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER");

            buildNum = variables.Aggregate(buildNum, (current, kvp) => 
                current.RegexReplace(string.Format(@"\$\(GITVERSION_{0}\)", kvp.Key), kvp.Value ?? string.Empty, RegexOptions.IgnoreCase));

            return string.Format("##vso[build.updatebuildnumber]{0}", buildNum);
        }
コード例 #9
0
    public string GetAssemblyInfoText(VersionVariables vars, string assemblyName)
    {
        var v = vars.ToList();

        var assemblyInfo = string.Format(
        @"using System;
        using System.Reflection;

        [assembly: AssemblyVersion(""{0}"")]
        [assembly: AssemblyFileVersion(""{1}"")]
        [assembly: AssemblyInformationalVersion(""{2}"")]
        [assembly: {6}.ReleaseDate(""{3}"")]
        [assembly: {6}.GitVersionInformation()]

        namespace {6}
        {{
        [System.Runtime.CompilerServices.CompilerGenerated]
        [AttributeUsage(AttributeTargets.Assembly)]
        sealed class ReleaseDateAttribute : System.Attribute
        {{
        public string Date {{ get; private set; }}

        public ReleaseDateAttribute(string date)
        {{
            Date = date;
        }}
        }}

        [System.Runtime.CompilerServices.CompilerGenerated]
        static class GitVersionInformation
        {{
        {4}
        }}

        [System.Runtime.CompilerServices.CompilerGenerated]
        [AttributeUsage(AttributeTargets.Assembly)]
        sealed class GitVersionInformationAttribute : System.Attribute
        {{
        {5}
        }}
        }}
        ",
        vars.AssemblySemVer,
        vars.MajorMinorPatch + ".0",
        vars.InformationalVersion,
        vars.CommitDate,
        GenerateStaticVariableMembers(v),
        GenerateAttributeVariableMembers(v),
        assemblyName);

        return assemblyInfo;
    }
コード例 #10
0
 void WriteIntegrationParameters(IEnumerable<IBuildServer> applicableBuildServers, VersionVariables variables)
 {
     foreach (var buildServer in applicableBuildServers)
     {
         logger.LogInfo(string.Format("Executing GenerateSetVersionMessage for '{0}'.", buildServer.GetType().Name));
         logger.LogInfo(buildServer.GenerateSetVersionMessage(variables));
         logger.LogInfo(string.Format("Executing GenerateBuildLogOutput for '{0}'.", buildServer.GetType().Name));
         foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(buildServer, variables))
         {
             logger.LogInfo(buildParameter);
         }
     }
 }
コード例 #11
0
 public bool TryGetVersion(string directory, out VersionVariables versionVariables, bool noFetch, Authentication authentication)
 {
     try
     {
         versionVariables = ExecuteGitVersion(null, null, authentication, null, noFetch, directory, null);
         return true;
     }
     catch (Exception ex)
     {
         Logger.WriteWarning("Could not determine assembly version: " + ex);
         versionVariables = null;
         return false;
     }
 }
コード例 #12
0
 public static bool TryGetVersion(string directory, out VersionVariables versionVariables, bool noFetch, Authentication authentication, IFileSystem fileSystem)
 {
     try
     {
         versionVariables = GetVersion(directory, authentication, noFetch, fileSystem);
         return true;
     }
     catch (Exception ex)
     {
         Logger.WriteWarning("Could not determine assembly version: " + ex.Message);
         versionVariables = null;
         return false;
     }
 }
コード例 #13
0
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Logger.WriteInfo("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem).ToList();
            Logger.WriteInfo(string.Format("Found {0} files", assemblyInfoFiles.Count));

            var assemblyVersion = variables.AssemblySemVer;
            var assemblyVersionRegex = new Regex(@"AssemblyVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyVersionString = !string.IsNullOrWhiteSpace(assemblyVersion) ? string.Format("AssemblyVersion(\"{0}\")", assemblyVersion) : null;
            var assemblyInfoVersion = variables.InformationalVersion;
            var assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyInfoVersionString = string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion);
            var assemblyFileVersion = variables.MajorMinorPatch + ".0";
            var assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyFileVersionString = string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion);

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var backupAssemblyInfo = assemblyInfoFile.FullName + ".bak";
                var localAssemblyInfo = assemblyInfoFile.FullName;
                fileSystem.Copy(assemblyInfoFile.FullName, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var fileContents = fileSystem.ReadAllText(assemblyInfoFile.FullName);
                var appendedAttributes = false;
                if (!string.IsNullOrWhiteSpace(assemblyVersion))
                {
                    fileContents = ReplaceOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                }
                fileContents = ReplaceOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                fileContents = ReplaceOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes);

                if (appendedAttributes)
                {
                    // If we appended any attributes, put a new line after them
                    fileContents += Environment.NewLine;
                }
                fileSystem.WriteAllText(assemblyInfoFile.FullName, fileContents);
            }
        }
コード例 #14
0
        static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, VersionVariables variables)
        {
            if (string.IsNullOrEmpty(args.Exec)) return false;

            Logger.WriteInfo(string.Format("Launching {0} {1}", args.Exec, args.ExecArgs));
            var results = ProcessHelper.Run(
                Logger.WriteInfo, Logger.WriteError,
                null, args.Exec, args.ExecArgs, workingDirectory,
                GetEnvironmentalVariables(variables));
            if (results != 0)
                throw new WarningException(string.Format("Execution of {0} failed, non-zero return code", args.Exec));

            return true;
        }
コード例 #15
0
        static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, VersionVariables variables)
        {
            if (string.IsNullOrEmpty(args.Proj)) return false;

            Logger.WriteInfo(string.Format("Launching {0} \"{1}\" {2}", MsBuild, args.Proj, args.ProjArgs));
            var results = ProcessHelper.Run(
                Logger.WriteInfo, Logger.WriteError,
                null, MsBuild, string.Format("\"{0}\" {1}", args.Proj, args.ProjArgs), workingDirectory,
                GetEnvironmentalVariables(variables));

            if (results != 0)
                throw new WarningException("MsBuild execution failed, non-zero return code");

            return true;
        }
コード例 #16
0
ファイル: BuildServerBase.cs プロジェクト: qetza/GitVersion
        public virtual void WriteIntegration(Action<string> writer, VersionVariables variables)
        {
            if (writer == null)
            {
                return;
            }

            writer(string.Format("Executing GenerateSetVersionMessage for '{0}'.", GetType().Name));
            writer(GenerateSetVersionMessage(variables));
            writer(string.Format("Executing GenerateBuildLogOutput for '{0}'.", GetType().Name));
            foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(this, variables))
            {
                writer(buildParameter);
            }
        }
コード例 #17
0
        public static string ToJson(VersionVariables variables)
        {
            var builder = new StringBuilder();
            builder.AppendLine("{");
            var last = variables.Last().Key;
            foreach (var variable in variables)
            {
                var isLast = (variable.Key == last);
                int value;
                if (int.TryParse(variable.Value, out value))
                    builder.AppendLineFormat("  \"{0}\":{1}{2}", variable.Key, value, isLast ? string.Empty : ",");
                else
                    builder.AppendLineFormat("  \"{0}\":\"{1}\"{2}", variable.Key, variable.Value, isLast ? string.Empty : ",");
            }

            builder.Append("}");
            return builder.ToString();
        }
コード例 #18
0
ファイル: VsoAgent.cs プロジェクト: qetza/GitVersion
        public override string GenerateSetVersionMessage(VersionVariables variables)
        {
            // For VSO, we'll get the Build Number and insert GitVersion variables where
            // specified
            var buildNum = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER");

            var newBuildNum = variables.Aggregate(buildNum, (current, kvp) =>
                current.RegexReplace(string.Format(@"\$\(GITVERSION_{0}\)", kvp.Key), kvp.Value ?? string.Empty, RegexOptions.IgnoreCase));

            // If no variable substitution has happened, use FullSemVer
            if (buildNum == newBuildNum)
            {
                var buildNumber = variables.FullSemVer.EndsWith("+0") ? variables.FullSemVer.Substring(0, variables.FullSemVer.Length - 2) : variables.FullSemVer;
                return string.Format("##vso[build.updatebuildnumber]{0}", buildNumber);
            }

            return string.Format("##vso[build.updatebuildnumber]{0}", newBuildNum);
        }
コード例 #19
0
    public override string GetAssemblyInfoText(VersionVariables vars, string rootNamespace)
    {
        var v = vars.ToList();

        // TODO: Consolidate this with GitVersion.VersionAssemblyInfoResources.AssemblyVersionInfoTemplates. @asbjornu
        var assemblyInfo = string.Format(
        @"//------------------------------------------------------------------------------
        // <auto-generated>
        //     This code was generated by a tool.
        //     GitVersion
        //
        //     Changes to this file may cause incorrect behavior and will be lost if
        //     the code is regenerated.
        // </auto-generated>
        //------------------------------------------------------------------------------

        using System;
        using System.Reflection;

        [assembly: AssemblyVersion(""{0}"")]
        [assembly: AssemblyFileVersion(""{1}"")]
        [assembly: AssemblyInformationalVersion(""{2}"")]

        namespace {4}
        {{

        [global::System.Runtime.CompilerServices.CompilerGenerated]
        static class GitVersionInformation
        {{
        {3}
        }}

        }}
        ",
        vars.AssemblySemVer,
        vars.MajorMinorPatch + ".0",
        vars.InformationalVersion,
        GenerateStaticVariableMembers(v),
        rootNamespace);

        return assemblyInfo;
    }
コード例 #20
0
        public static VersionVariables GetVariablesFor(
            SemanticVersion semanticVersion, AssemblyVersioningScheme assemblyVersioningScheme,
            VersioningMode mode, string continuousDeploymentFallbackTag,
            bool currentCommitIsTagged)
        {
            var bmd = semanticVersion.BuildMetaData;
            if (mode == VersioningMode.ContinuousDeployment && !currentCommitIsTagged)
            {
                semanticVersion = new SemanticVersion(semanticVersion);
                // Continuous Deployment always requires a pre-release tag unless the commit is tagged
                if (!semanticVersion.PreReleaseTag.HasTag())
                {
                    semanticVersion.PreReleaseTag.Name = continuousDeploymentFallbackTag;
                }

                // For continuous deployment the commits since tag gets promoted to the pre-release number
                semanticVersion.PreReleaseTag.Number = semanticVersion.BuildMetaData.CommitsSinceTag;
                semanticVersion.BuildMetaData.CommitsSinceTag = null;
            }

            var variables = new VersionVariables(
                major: semanticVersion.Major.ToString(),
                minor: semanticVersion.Minor.ToString(),
                patch: semanticVersion.Patch.ToString(),
                preReleaseTag: semanticVersion.PreReleaseTag,
                preReleaseTagWithDash: semanticVersion.PreReleaseTag.HasTag() ? "-" + semanticVersion.PreReleaseTag : null,
                buildMetaData: bmd,
                fullBuildMetaData: bmd.ToString("f"),
                majorMinorPatch: string.Format("{0}.{1}.{2}", semanticVersion.Major, semanticVersion.Minor, semanticVersion.Patch),
                semVer: semanticVersion.ToString(),
                legacySemVer: semanticVersion.ToString("l"),
                legacySemVerPadded: semanticVersion.ToString("lp"),
                assemblySemVer: semanticVersion.GetAssemblyVersion(assemblyVersioningScheme),
                fullSemVer: semanticVersion.ToString("f"),
                informationalVersion: semanticVersion.ToString("i"),
                branchName: bmd.Branch,
                sha: bmd.Sha,
                commitDate: bmd.CommitDate.UtcDateTime.ToString("yyyy-MM-dd"));

            return variables;
        }
コード例 #21
0
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Logger.WriteInfo("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem);
            Logger.WriteInfo(string.Format("Found {0} files", assemblyInfoFiles.Count()));

            var assemblyVersion = variables.AssemblySemVer;
            var assemblyVersionRegex = new Regex(@"AssemblyVersion\(""[^""]*""\)");
            var assemblyVersionString = string.Format("AssemblyVersion(\"{0}\")", assemblyVersion);
            var assemblyInfoVersion = variables.InformationalVersion;
            var assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion\(""[^""]*""\)");
            var assemblyInfoVersionString = string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion);
            var assemblyFileVersion = variables.MajorMinorPatch + ".0";
            var assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion\(""[^""]*""\)");
            var assemblyFileVersionString = string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion);

            foreach (var assemblyInfoFile in assemblyInfoFiles.Select(f => new FileInfo(f)))
            {
                var backupAssemblyInfo = assemblyInfoFile.FullName + ".bak";
                var localAssemblyInfo = assemblyInfoFile.FullName;
                fileSystem.Copy(assemblyInfoFile.FullName, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var fileContents = fileSystem.ReadAllText(assemblyInfoFile.FullName);
                fileContents = ReplaceOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString);
                fileContents = ReplaceOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString);
                fileContents = ReplaceOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString);

                fileSystem.WriteAllText(assemblyInfoFile.FullName, fileContents);
            }
        }
コード例 #22
0
        public void WriteVariablesToDiskCache(IRepository repo, string gitDir, VersionVariables variablesFromCache)
        {
            var cacheFileName = GetCacheFileName(GetKey(repo, gitDir), GetCacheDir(gitDir));
            variablesFromCache.FileName = cacheFileName;

            using (var stream = fileSystem.OpenWrite(cacheFileName))
            {
                using (var sw = new StreamWriter(stream))
                {
                    Dictionary<string, string> dictionary;
                    using (Logger.IndentLog("Creating dictionary"))
                    {
                        dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
                    }

                    using (Logger.IndentLog("Storing version variables to cache file " + cacheFileName))
                    {
                        var serializer = new Serializer();
                        serializer.Serialize(sw, dictionary);
                    }
                }
            }
        }
コード例 #23
0
    public override string GetAssemblyInfoText(VersionVariables vars, string rootNamespace)
    {
        var v = vars.ToList();

        // TODO: Consolidate this with GitVersion.VersionAssemblyInfoResources.AssemblyVersionInfoTemplates. @asbjornu
        var assemblyInfo = string.Format(
        @"'------------------------------------------------------------------------------
        ' <auto-generated>
        '     This code was generated by a tool.
        '     GitVersion
        '
        '     Changes to this file may cause incorrect behavior and will be lost if
        '     the code is regenerated.
        ' </auto-generated>
        '------------------------------------------------------------------------------

        Imports System
        Imports System.Reflection

        <Assembly: AssemblyVersion(""{0}"")>
        <Assembly: AssemblyFileVersion(""{1}"")>
        <Assembly: AssemblyInformationalVersion(""{2}"")>

        <Global.System.Runtime.CompilerServices.CompilerGenerated()> _
        NotInheritable Class GitVersionInformation
        Private Sub New()
        End Sub
        {3}
        End Class
        ",
        vars.AssemblySemVer,
        vars.MajorMinorPatch + ".0",
        vars.InformationalVersion,
        GenerateStaticVariableMembers(v));

        return assemblyInfo;
    }
コード例 #24
0
    public string GetAssemblyInfoText(VersionVariables vars)
    {
        var assemblyInfo = string.Format(@"
        using System;
        using System.Reflection;

        [assembly: AssemblyVersion(""{0}"")]
        [assembly: AssemblyFileVersion(""{1}"")]
        [assembly: AssemblyInformationalVersion(""{2}"")]
        [assembly: ReleaseDate(""{3}"")]

        [System.Runtime.CompilerServices.CompilerGenerated]
        sealed class ReleaseDateAttribute : System.Attribute
        {{
        public string Date {{ get; private set; }}

        public ReleaseDateAttribute(string date)
        {{
        Date = date;
        }}
        }}

        [System.Runtime.CompilerServices.CompilerGenerated]
        static class GitVersionInformation
        {{
        {4}
        }}

        ",
        vars.AssemblySemVer,
         vars.MajorMinorPatch + ".0",
         vars.InformationalVersion,
            vars.CommitDate,
            GenerateVariableMembers(vars));

        return assemblyInfo;
    }
コード例 #25
0
ファイル: Jenkins.cs プロジェクト: thoemmi/GitVersion
 private void WriteVariablesFile(VersionVariables variables)
 {
     File.WriteAllLines(file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables));
 }
コード例 #26
0
 public override string GenerateSetVersionMessage(VersionVariables variables) => string.Empty;
コード例 #27
0
ファイル: Jenkins.cs プロジェクト: thoemmi/GitVersion
 public override string GenerateSetVersionMessage(VersionVariables variables)
 {
     return(variables.FullSemVer);
 }
コード例 #28
0
ファイル: Jenkins.cs プロジェクト: Exterazzo/GitVersion
 public override string GenerateSetVersionMessage(VersionVariables variables)
 {
     return variables.FullSemVer;
 }
コード例 #29
0
ファイル: Jenkins.cs プロジェクト: Exterazzo/GitVersion
 void WriteVariablesFile(VersionVariables variables)
 {
     File.WriteAllLines(_file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables));
 }
コード例 #30
0
        public void Execute(VersionVariables variables, AssemblyInfoContext context)
        {
            if (context.EnsureAssemblyInfo)
            {
                throw new WarningException($"Configuration setting {nameof(context.EnsureAssemblyInfo)} is not valid when updating project files!");
            }

            var projectFilesToUpdate = GetProjectFiles(context).ToList();

            var assemblyVersion     = variables.AssemblySemVer;
            var assemblyInfoVersion = variables.InformationalVersion;
            var assemblyFileVersion = variables.AssemblySemFileVer;

            foreach (var projectFile in projectFilesToUpdate)
            {
                var localProjectFile = projectFile.FullName;

                var originalFileContents = fileSystem.ReadAllText(localProjectFile);
                var fileXml = XElement.Parse(originalFileContents);

                if (!CanUpdateProjectFile(fileXml))
                {
                    log.Warning($"Unable to update file: {localProjectFile}");
                    continue;
                }

                var backupProjectFile = localProjectFile + ".bak";
                fileSystem.Copy(localProjectFile, backupProjectFile, true);

                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localProjectFile))
                    {
                        fileSystem.Delete(localProjectFile);
                    }

                    fileSystem.Move(backupProjectFile, localProjectFile);
                });

                cleanupBackupTasks.Add(() => fileSystem.Delete(backupProjectFile));

                if (!string.IsNullOrWhiteSpace(assemblyVersion))
                {
                    UpdateProjectVersionElement(fileXml, AssemblyVersionElement, assemblyVersion);
                }

                if (!string.IsNullOrWhiteSpace(assemblyFileVersion))
                {
                    UpdateProjectVersionElement(fileXml, FileVersionElement, assemblyFileVersion);
                }

                if (!string.IsNullOrWhiteSpace(assemblyInfoVersion))
                {
                    UpdateProjectVersionElement(fileXml, InformationalVersionElement, assemblyInfoVersion);
                }

                var outputXmlString = fileXml.ToString();
                if (originalFileContents != outputXmlString)
                {
                    fileSystem.WriteAllText(localProjectFile, outputXmlString);
                }
            }

            CommitChanges();
        }
コード例 #31
0
 public abstract string GetAssemblyInfoText(VersionVariables vars, string rootNamespace);
コード例 #32
0
 public abstract string?GenerateSetVersionMessage(VersionVariables variables);
コード例 #33
0
ファイル: TeamCity.cs プロジェクト: franknarf8/GitVersion
 public override string GenerateSetVersionMessage(VersionVariables variables) => $"##teamcity[buildNumber '{ServiceMessageEscapeHelper.EscapeValue(variables.FullSemVer)}']";
コード例 #34
0
        public static IEnumerable <string> GenerateBuildLogOutput(IBuildServer buildServer, VersionVariables variables)
        {
            var output = new List <string>();

            foreach (var variable in variables)
            {
                output.AddRange(buildServer.GenerateSetParameterMessage(variable.Key, variable.Value));
            }

            return(output);
        }
コード例 #35
0
 public static bool GetVersionVariables(InputBase input, out VersionVariables versionVariables)
 => new ExecuteCore(new FileSystem()).TryGetVersion(input.SolutionDirectory, out versionVariables, input.NoFetch, new Authentication());
コード例 #36
0
ファイル: VariableProvider.cs プロジェクト: zionyx/GitVersion
        public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, EffectiveConfiguration config, bool isCurrentCommitTagged)
        {
            var isContinuousDeploymentMode = config.VersioningMode == VersioningMode.ContinuousDeployment && !isCurrentCommitTagged;

            if (isContinuousDeploymentMode)
            {
                semanticVersion = new SemanticVersion(semanticVersion);
                // Continuous Deployment always requires a pre-release tag unless the commit is tagged
                if (!semanticVersion.PreReleaseTag.HasTag())
                {
                    semanticVersion.PreReleaseTag.Name = config.GetBranchSpecificTag(log, semanticVersion.BuildMetaData.Branch, null);
                    if (string.IsNullOrEmpty(semanticVersion.PreReleaseTag.Name))
                    {
                        semanticVersion.PreReleaseTag.Name = config.ContinuousDeploymentFallbackTag;
                    }
                }
            }

            // Evaluate tag number pattern and append to prerelease tag, preserving build metadata
            var appendTagNumberPattern = !string.IsNullOrEmpty(config.TagNumberPattern) && semanticVersion.PreReleaseTag.HasTag();

            if (appendTagNumberPattern)
            {
                var match       = Regex.Match(semanticVersion.BuildMetaData.Branch, config.TagNumberPattern);
                var numberGroup = match.Groups["number"];
                if (numberGroup.Success)
                {
                    semanticVersion.PreReleaseTag.Name += numberGroup.Value.PadLeft(config.BuildMetaDataPadding, '0');
                }
            }

            if (isContinuousDeploymentMode || appendTagNumberPattern || config.VersioningMode == VersioningMode.Mainline)
            {
                PromoteNumberOfCommitsToTagNumber(semanticVersion);
            }

            var semverFormatValues = new SemanticVersionFormatValues(semanticVersion, config);

            var informationalVersion = CheckAndFormatString(config.AssemblyInformationalFormat, semverFormatValues, semverFormatValues.InformationalVersion, "AssemblyInformationalVersion");

            var assemblyFileSemVer = CheckAndFormatString(config.AssemblyFileVersioningFormat, semverFormatValues, semverFormatValues.AssemblyFileSemVer, "AssemblyFileVersioningFormat");

            var assemblySemVer = CheckAndFormatString(config.AssemblyVersioningFormat, semverFormatValues, semverFormatValues.AssemblySemVer, "AssemblyVersioningFormat");

            var variables = new VersionVariables(
                semverFormatValues.Major,
                semverFormatValues.Minor,
                semverFormatValues.Patch,
                semverFormatValues.BuildMetaData,
                semverFormatValues.BuildMetaDataPadded,
                semverFormatValues.FullBuildMetaData,
                semverFormatValues.BranchName,
                semverFormatValues.EscapedBranchName,
                semverFormatValues.Sha,
                semverFormatValues.ShortSha,
                semverFormatValues.MajorMinorPatch,
                semverFormatValues.SemVer,
                semverFormatValues.LegacySemVer,
                semverFormatValues.LegacySemVerPadded,
                semverFormatValues.FullSemVer,
                assemblySemVer,
                assemblyFileSemVer,
                semverFormatValues.PreReleaseTag,
                semverFormatValues.PreReleaseTagWithDash,
                semverFormatValues.PreReleaseLabel,
                semverFormatValues.PreReleaseNumber,
                semverFormatValues.WeightedPreReleaseNumber,
                informationalVersion,
                semverFormatValues.CommitDate,
                semverFormatValues.NuGetVersion,
                semverFormatValues.NuGetVersionV2,
                semverFormatValues.NuGetPreReleaseTag,
                semverFormatValues.NuGetPreReleaseTagV2,
                semverFormatValues.VersionSourceSha,
                semverFormatValues.CommitsSinceVersionSource,
                semverFormatValues.CommitsSinceVersionSourcePadded,
                semverFormatValues.UncommittedChanges);

            return(variables);
        }
コード例 #37
0
 void WriteIntegrationParameters(IEnumerable <IBuildServer> applicableBuildServers, VersionVariables variables)
 {
     foreach (var buildServer in applicableBuildServers)
     {
         logger.LogInfo(string.Format("Executing GenerateSetVersionMessage for '{0}'.", buildServer.GetType().Name));
         logger.LogInfo(buildServer.GenerateSetVersionMessage(variables));
         logger.LogInfo(string.Format("Executing GenerateBuildLogOutput for '{0}'.", buildServer.GetType().Name));
         foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(buildServer, variables))
         {
             logger.LogInfo(buildParameter);
         }
     }
 }
コード例 #38
0
ファイル: CodeBuild.cs プロジェクト: nils-a/GitVersion
 public override void WriteIntegration(Action <string?> writer, VersionVariables variables, bool updateBuildNumber = true)
 {
     base.WriteIntegration(writer, variables, updateBuildNumber);
     writer($"Outputting variables to '{this.file}' ... ");
     File.WriteAllLines(this.file, GenerateBuildLogOutput(variables));
 }
コード例 #39
0
 public void WriteIntegration(Action <string> writer, VersionVariables variables, bool updateBuildNumber = true)
 {
     throw new NotImplementedException();
 }
コード例 #40
0
 public AssemblyInfoFileUpdater(string assemblyInfoFileName, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, ILog log, bool ensureAssemblyInfo) :
     this(new HashSet <string> {
     assemblyInfoFileName
 }, workingDirectory, variables, fileSystem, log, ensureAssemblyInfo)
 {
 }
コード例 #41
0
 public abstract string GetAssemblyInfoText(VersionVariables vars, string rootNamespace);
コード例 #42
0
        public AssemblyInfoFileUpdater(ISet <string> assemblyInfoFileNames, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, ILog log, bool ensureAssemblyInfo)
        {
            this.assemblyInfoFileNames = assemblyInfoFileNames;
            this.workingDirectory      = workingDirectory;
            this.variables             = variables;
            this.fileSystem            = fileSystem;
            this.log = log;
            this.ensureAssemblyInfo = ensureAssemblyInfo;

            templateManager = new TemplateManager(TemplateType.VersionAssemblyInfoResources);
        }
コード例 #43
0
ファイル: CodeBuild.cs プロジェクト: simundhe22/GitVersion
 public override void WriteIntegration(Action <string> writer, VersionVariables variables)
 {
     base.WriteIntegration(writer, variables);
     writer($"Outputting variables to '{file}' ... ");
     File.WriteAllLines(file, GenerateBuildLogOutput(variables));
 }
コード例 #44
0
 public GitVersionTaskExecutor(IGitVersionTool gitVersionTool, IOptions <Arguments> options)
 {
     this.gitVersionTool = gitVersionTool ?? throw new ArgumentNullException(nameof(gitVersionTool));
     this.options        = options ?? throw new ArgumentNullException(nameof(options));
     versionVariables    = gitVersionTool.CalculateVersionVariables();
 }
コード例 #45
0
ファイル: BuildServerBase.cs プロジェクト: qetza/GitVersion
 public abstract string GenerateSetVersionMessage(VersionVariables variables);
コード例 #46
0
ファイル: MyGet.cs プロジェクト: franknarf8/GitVersion
 public override string?GenerateSetVersionMessage(VersionVariables variables) => null;
コード例 #47
0
ファイル: Jenkins.cs プロジェクト: Exterazzo/GitVersion
 public override void WriteIntegration(Action<string> writer, VersionVariables variables)
 {
     base.WriteIntegration(writer, variables);
     writer(string.Format("Outputting variables to '{0}' ... ", _file));
     WriteVariablesFile(variables);
 }
コード例 #48
0
 public void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task)
 {
     versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log);
     gitVersionOutputTool.OutputVariables(versionVariables, false);
 }
コード例 #49
0
 private void WriteVariablesFile(VersionVariables variables)
 {
     File.WriteAllLines(file, GenerateBuildLogOutput(variables));
 }
コード例 #50
0
 public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer;
コード例 #51
0
 protected bool GetVersionVariables(out VersionVariables versionVariables)
 {
     return(!ExecuteCore.TryGetVersion(SolutionDirectory, out versionVariables, NoFetch, new Authentication()));
 }
コード例 #52
0
 public override void WriteIntegration(Action <string?> writer, VersionVariables variables, bool updateBuildNumber = true)
 {
     base.WriteIntegration(writer, variables, updateBuildNumber);
     writer($"Outputting variables to '{this.file}' ... ");
     WriteVariablesFile(variables);
 }
コード例 #53
0
ファイル: Jenkins.cs プロジェクト: thoemmi/GitVersion
 public override void WriteIntegration(Action <string> writer, VersionVariables variables)
 {
     base.WriteIntegration(writer, variables);
     writer($"Outputting variables to '{file}' ... ");
     WriteVariablesFile(variables);
 }
コード例 #54
0
        public void Execute(VersionVariables variables, AssemblyInfoContext context)
        {
            var assemblyInfoFiles = GetAssemblyInfoFiles(context).ToList();

            log.Info("Updating assembly info files");
            log.Info($"Found {assemblyInfoFiles.Count} files");

            var assemblyVersion       = variables.AssemblySemVer;
            var assemblyVersionString = !string.IsNullOrWhiteSpace(assemblyVersion) ? $"AssemblyVersion(\"{assemblyVersion}\")" : null;

            var assemblyInfoVersion       = variables.InformationalVersion;
            var assemblyInfoVersionString = !string.IsNullOrWhiteSpace(assemblyInfoVersion) ? $"AssemblyInformationalVersion(\"{assemblyInfoVersion}\")" : null;

            var assemblyFileVersion       = variables.AssemblySemFileVer;
            var assemblyFileVersionString = !string.IsNullOrWhiteSpace(assemblyFileVersion) ? $"AssemblyFileVersion(\"{assemblyFileVersion}\")" : null;

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var localAssemblyInfo  = assemblyInfoFile.FullName;
                var backupAssemblyInfo = localAssemblyInfo + ".bak";
                fileSystem.Copy(localAssemblyInfo, backupAssemblyInfo, true);

                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                    {
                        fileSystem.Delete(localAssemblyInfo);
                    }

                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });

                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var originalFileContents = fileSystem.ReadAllText(localAssemblyInfo);
                var fileContents         = originalFileContents;
                var appendedAttributes   = false;

                if (!string.IsNullOrWhiteSpace(assemblyVersion))
                {
                    fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                }

                if (!string.IsNullOrWhiteSpace(assemblyFileVersion))
                {
                    fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                }

                if (!string.IsNullOrWhiteSpace(assemblyInfoVersion))
                {
                    fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                }

                if (appendedAttributes)
                {
                    // If we appended any attributes, put a new line after them
                    fileContents += NewLine;
                }

                if (originalFileContents != fileContents)
                {
                    fileSystem.WriteAllText(localAssemblyInfo, fileContents);
                }
            }
            CommitChanges();
        }
コード例 #55
0
ファイル: GitVersionCache.cs プロジェクト: thoemmi/GitVersion
        public void WriteVariablesToDiskCache(IGitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache)
        {
            var cacheDir      = PrepareCacheDirectory(gitPreparer);
            var cacheFileName = GetCacheFileName(cacheKey, cacheDir);

            variablesFromCache.FileName = cacheFileName;

            Dictionary <string, string> dictionary;

            using (log.IndentLog("Creating dictionary"))
            {
                dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
            }

            void WriteCacheOperation()
            {
                using var stream = fileSystem.OpenWrite(cacheFileName);
                using var sw     = new StreamWriter(stream);
                using (log.IndentLog("Storing version variables to cache file " + cacheFileName))
                {
                    var serializer = new Serializer();
                    serializer.Serialize(sw, dictionary);
                }
            }

            var retryOperation = new OperationWithExponentialBackoff <IOException>(new ThreadSleep(), log, WriteCacheOperation, maxRetries: 6);

            retryOperation.ExecuteAsync().Wait();
        }
コード例 #56
0
ファイル: MyGet.cs プロジェクト: ruhullahshah/GitVersion
 public override string GenerateSetVersionMessage(VersionVariables variables)
 {
     return(null);
 }
コード例 #57
0
 static KeyValuePair<string, string>[] GetEnvironmentalVariables(VersionVariables variables)
 {
     return variables
         .Select(v => new KeyValuePair<string, string>("GitVersion_" + v.Key, v.Value))
         .ToArray();
 }
コード例 #58
0
ファイル: ContinuaCi.cs プロジェクト: ruhullahshah/GitVersion
 public override string GenerateSetVersionMessage(VersionVariables variables)
 {
     return($"@@continua[setBuildVersion value='{variables.FullSemVer}']");
 }
コード例 #59
0
        public override string GenerateSetVersionMessage(VersionVariables variables)
        {
            // There is no equivalent function in GitHub Actions.

            return(string.Empty);
        }
コード例 #60
0
 public override void WriteIntegration(Action <string> writer, VersionVariables variables)
 {
     base.WriteIntegration(writer, variables);
     writer($"Outputting variables to '{propertiesFileName}' ... ");
     File.WriteAllLines(propertiesFileName, BuildOutputFormatter.GenerateBuildLogOutput(this, variables));
 }