public static RepositoryInfo GetRepositoryInfo(this ICakeContext context, RepositoryInfoOptions options = null)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     return(RepositoryInfo.LoadFromPath(context.Environment.WorkingDirectory.FullPath, options));
 }
Example #2
0
 /// <summary>
 /// Creates a new <see cref="RepositoryInfo"/> based on a path (that can be below the folder with the '.git' sub folder).
 /// </summary>
 /// <param name="path">The path to lookup.</param>
 /// <param name="options">Optional <see cref="RepositoryInfoOptions"/>.</param>
 /// <returns>An immutable RepositoryInfo instance. Never null.</returns>
 public static RepositoryInfo LoadFromPath(string path, RepositoryInfoOptions options = null)
 {
     if (path == null)
     {
         throw new ArgumentNullException(nameof(path));
     }
     using (var repo = GitHelper.LoadFromPath(path))
     {
         return(new RepositoryInfo(repo, options, repo != null ? repo.Info.WorkingDirectory : null));
     }
 }
 /// <summary>
 /// Creates a new <see cref="RepositoryInfo"/> based on a path (that can be below the folder with the '.git' sub folder).
 /// </summary>
 /// <param name="path">The path to lookup.</param>
 /// <param name="options">Optional <see cref="RepositoryInfoOptions"/>.</param>
 /// <returns>An immutable RepositoryInfo instance. Never null.</returns>
 public static RepositoryInfo LoadFromPath(string path, RepositoryInfoOptions options = null)
 {
     if (path == null)
     {
         throw new ArgumentNullException(nameof(path));
     }
     path = Repository.Discover(path);
     using (var repo = path != null ? new Repository(path) : null)
     {
         return(new RepositoryInfo(repo, options));
     }
 }
Example #4
0
        /// <summary>
        /// Creates a new <see cref="SimpleRepositoryInfo"/> based on a path (that can be below the folder with the '.git' sub folder).
        /// </summary>
        /// <param name="path">The path to lookup.</param>
        /// <param name="logger">Logger that will be used.</param>
        /// <param name="optionsChecker">
        /// Optional action that accepts the logger, a boolean that is true if a RepositoryInfo.xml has been
        /// found, and the <see cref="RepositoryInfoOptions"/> that will be used.
        /// </param>
        /// <returns>An immutable SimpleRepositoryInfo instance.</returns>
        static public SimpleRepositoryInfo LoadFromPath(ILogger logger, string path, Action <ILogger, bool, RepositoryInfoOptions> optionsChecker = null)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            RepositoryInfo info = RepositoryInfo.LoadFromPath(path, gitPath =>
            {
                string optionFile = Path.Combine(gitPath, "RepositoryInfo.xml");
                bool fileExists   = File.Exists(optionFile);
                var options       = fileExists ? RepositoryInfoOptions.Read(optionFile) : new RepositoryInfoOptions();
                optionsChecker?.Invoke(logger, fileExists, options);
                return(options);
            });

            return(new SimpleRepositoryInfo(logger, info));
        }
        /// <summary>
        /// Reads <see cref="RepositoryInfoOptions"/> from a xml element.
        /// </summary>
        /// <param name="e">Xml element.</param>
        /// <returns>Returns a configured <see cref="RepositoryInfoOptions"/>.</returns>
        public static RepositoryInfoOptions Read(XElement e)
        {
            var info = new RepositoryInfoOptions();

            var eD = e.Element(SGVSchema.Debug);

            if (eD != null)
            {
                var attrIgnoreDirty = eD.Attribute(SGVSchema.IgnoreDirtyWorkingFolder);
                info.IgnoreDirtyWorkingFolder = attrIgnoreDirty != null ? attrIgnoreDirty.Value == "true" || attrIgnoreDirty.Value == "1" : false;
            }

            var eS = e.Element(SGVSchema.StartingVersionForCSemVer);

            if (eS != null)
            {
                info.StartingVersionForCSemVer = eS.Value;
            }

            var eR = e.Element(SGVSchema.RemoteName);

            if (eR != null)
            {
                info.RemoteName = eR.Value;
            }

            var eP = e.Element(SGVSchema.PossibleVersionsMode);

            if (eP != null)
            {
                info.PossibleVersionsMode = (PossibleVersionsMode)Enum.Parse(typeof(PossibleVersionsMode), eP.Value);
            }

            info.Branches = e.Elements(SGVSchema.Branches)
                            .Elements(SGVSchema.Branch)
                            .Select(b => new RepositoryInfoOptionsBranch(b)).ToList();

            info.IgnoreModifiedFiles.UnionWith(e.Elements(SGVSchema.IgnoreModifiedFiles).Elements(SGVSchema.Add).Select(i => i.Value));

            return(info);
        }
        /// <summary>
        /// Reads <see cref="RepositoryInfoOptions"/> from a xml element.
        /// </summary>
        /// <param name="e">Xml element.</param>
        /// <returns>Returns a configured <see cref="RepositoryInfoOptions"/>.</returns>
        public static RepositoryInfoOptions Read(XElement e)
        {
            var info = new RepositoryInfoOptions();

            info.IgnoreDirtyWorkingFolder = (bool?)e.Element(SGVSchema.Debug)
                                            ?.Attribute(SGVSchema.IgnoreDirtyWorkingFolder) ?? false;

            info.StartingVersionForCSemVer = (string)e.Element(SGVSchema.StartingVersionForCSemVer);


            info.SingleMajor = (int?)e.Element(SGVSchema.SingleMajor);

            info.OnlyPatch = (bool?)e.Element(SGVSchema.OnlyPatch) ?? false;

            info.Branches = e.Elements(SGVSchema.Branches)
                            .Elements(SGVSchema.Branch)
                            .Select(b => new RepositoryInfoOptionsBranch(b)).ToList();

            info.IgnoreModifiedFiles.UnionWith(e.Elements(SGVSchema.IgnoreModifiedFiles).Elements(SGVSchema.Add).Select(i => i.Value));

            info.RemoteName = (string)e.Element(SGVSchema.RemoteName);

            return(info);
        }
Example #7
0
        /// <summary>
        /// Reads <see cref="RepositoryInfoOptions"/> from a xml element.
        /// </summary>
        /// <param name="e">Xml element.</param>
        /// <returns>Returns a configured <see cref="RepositoryInfoOptions"/>.</returns>
        public static RepositoryInfoOptions Read( XElement e )
        {
            var info = new RepositoryInfoOptions();

            var eD = e.Element( SGVSchema.Debug );
            if( eD != null )
            {
                var attrIgnoreDirty = eD.Attribute( SGVSchema.IgnoreDirtyWorkingFolder );
                info.IgnoreDirtyWorkingFolder = attrIgnoreDirty != null ? attrIgnoreDirty.Value == "true" || attrIgnoreDirty.Value == "1" : false;
            }

            var eS = e.Element( SGVSchema.StartingVersionForCSemVer );
            if( eS != null ) info.StartingVersionForCSemVer = eS.Value;

            var eR = e.Element( SGVSchema.RemoteName );
            if( eR != null ) info.RemoteName = eR.Value;

            var eP = e.Element( SGVSchema.PossibleVersionsMode );
            if( eP != null ) info.PossibleVersionsMode = (PossibleVersionsMode)Enum.Parse( typeof( PossibleVersionsMode), eP.Value );

            info.Branches = e.Elements( SGVSchema.Branches )
                                    .Elements( SGVSchema.Branch )
                                    .Select( b => new RepositoryInfoOptionsBranch( b ) ).ToList();

            info.IgnoreModifiedFiles.UnionWith( e.Elements( SGVSchema.IgnoreModifiedFiles ).Elements( SGVSchema.Add ).Select( i => i.Value ) );

            return info;
        }
Example #8
0
 public RepositoryInfo GetRepositoryInfo(RepositoryInfoOptions options = null)
 {
     return(RepositoryInfo.LoadFromPath(Path, options));
 }
        /// <summary>
        /// Initializes a new <see cref="RepositoryInfo"/> on a <see cref="Repository"/>.
        /// </summary>
        /// <param name="r">The rpository (can be invalid and even null).</param>
        /// <param name="options">Optional options.</param>
        public RepositoryInfo(Repository r, RepositoryInfoOptions options = null)
        {
            Options       = options ?? new RepositoryInfoOptions();
            CommitDateUtc = InformationalVersion.ZeroCommitDate;
            if (r == null)
            {
                RepositoryError = "No Git repository.";
            }
            else
            {
                Commit commit;
                CIBranchVersionMode ciVersionMode;
                string ciBuildName;
                RepositoryError = TryFindCommit(options, r, out commit, out ciVersionMode, out ciBuildName);
                Debug.Assert((ciVersionMode != CIBranchVersionMode.None) == (ciBuildName != null));
                if (commit != null)
                {
                    CommitSha           = commit.Sha;
                    CommitDateUtc       = commit.Author.When.UtcDateTime;
                    IsDirtyExplanations = ComputeIsDirty(r, commit, options);
                    if (!IsDirty || options.IgnoreDirtyWorkingFolder)
                    {
                        StringBuilder errors    = new StringBuilder();
                        TagCollector  collector = new TagCollector(errors,
                                                                   r,
                                                                   options.StartingVersionForCSemVer,
                                                                   options.OverriddenTags,
                                                                   options.SingleMajor);
                        if (errors.Length == 0)
                        {
                            ExistingVersions = collector.ExistingVersions.TagCommits;

                            var info = collector.GetCommitInfo(commit);
                            Debug.Assert(info != null);

                            CommitInfo = info;

                            var rawPossible = info.PossibleVersions;
                            IEnumerable <CSVersion> possibles = rawPossible;
                            if (options.OnlyPatch)
                            {
                                possibles = possibles.Where(v => v.IsPatch);
                            }
                            if (options.SingleMajor.HasValue)
                            {
                                possibles = possibles.Where(v => v.Major == options.SingleMajor.Value);
                            }
                            PossibleVersions = possibles != rawPossible?possibles.ToList() : rawPossible;

                            var rawNextPossible = info.NextPossibleVersions;
                            IEnumerable <CSVersion> nextPossibles = rawNextPossible;
                            if (options.OnlyPatch)
                            {
                                nextPossibles = nextPossibles.Where(v => v.IsPatch);
                            }
                            if (options.SingleMajor.HasValue)
                            {
                                nextPossibles = nextPossibles.Where(v => v.Major == options.SingleMajor.Value);
                            }
                            NextPossibleVersions = nextPossibles != rawNextPossible?nextPossibles.ToList() : rawNextPossible;

                            var thisCommit = info.BasicInfo?.UnfilteredThisCommit;
                            if (info.BasicInfo?.BestCommit?.ThisTag > thisCommit?.ThisTag)
                            {
                                BetterExistingVersion = info.BasicInfo.BestCommit;
                            }
                            if (thisCommit != null)
                            {
                                if (PossibleVersions.Contains(thisCommit.ThisTag))
                                {
                                    ValidReleaseTag = thisCommit.ThisTag;
                                }
                                else
                                {
                                    ReleaseTagIsNotPossibleError = true;
                                    errors.Append("Release tag '")
                                    .Append(thisCommit.ThisTag.ParsedText)
                                    .AppendLine("' is not valid here. ");
                                    errors.Append("Valid tags are: ")
                                    .Append(string.Join(", ", PossibleVersions))
                                    .AppendLine();
                                    if (PossibleVersions != rawPossible &&
                                        rawPossible.Contains(thisCommit.ThisTag))
                                    {
                                        errors.AppendLine("Note: this version is invalid because of <SingleMajor> or <OnlyPatch> setting in RepositoryInfo.xml.");
                                    }
                                }
                            }
                            else
                            {
                                // There is no release tag on the commit point.
                                if (ciBuildName != null)
                                {
                                    CIRelease = CIReleaseInfo.Create(commit, ciVersionMode, ciBuildName, errors, info.BasicInfo);
                                }
                            }
                        }
                        if (errors.Length > 0)
                        {
                            ReleaseTagError = errors.ToString();
                        }
                    }

                    // Conclusion:
                    if (CIRelease != null)
                    {
                        //ContentOrFinalNuGetVersion =
                        FinalNuGetVersion = CIRelease.BuildVersionNuGet;
                        FinalSemVersion   = CIRelease.BuildVersion;
                    }
                    else if (ValidReleaseTag != null)
                    {
                        FinalNuGetVersion = SVersion.Parse(ValidReleaseTag.ToString(CSVersionFormat.NuGetPackage), false);
                        FinalSemVersion   = ValidReleaseTag;
                    }
                }
            }
            // Handles FinalInformationalVersion and SVersion.ZeroVersion for versions if needed.
            if (FinalSemVersion == null)
            {
                FinalSemVersion           = SVersion.ZeroVersion;
                FinalNuGetVersion         = SVersion.ZeroVersion;
                FinalInformationalVersion = InformationalVersion.ZeroInformationalVersion;
            }
            else
            {
                FinalInformationalVersion = InformationalVersion.BuildInformationalVersion(FinalSemVersion.NormalizedText, FinalNuGetVersion.NormalizedText, CommitSha, CommitDateUtc);
            }
        }
Example #10
0
 public RepositoryInfo GetRepositoryInfo( RepositoryInfoOptions options = null )
 {
     return RepositoryInfo.LoadFromPath( Path, options );
 }
 /// <summary>
 /// Creates a new <see cref="RepositoryInfo"/> based on a path (that can be below the folder with the '.git' sub folder). 
 /// </summary>
 /// <param name="path">The path to lookup.</param>
 /// <param name="options">Optional <see cref="RepositoryInfoOptions"/>.</param>
 /// <returns>An immutable RepositoryInfo instance. Never null.</returns>
 public static RepositoryInfo LoadFromPath( string path, RepositoryInfoOptions options = null )
 {
     if( path == null ) throw new ArgumentNullException( nameof( path ) );
     using( var repo = GitHelper.LoadFromPath( path ) )
     {
         return new RepositoryInfo( repo, options, repo != null ? repo.Info.WorkingDirectory : null );
     }
 }
Example #12
0
 public static RepositoryInfo GetRepositoryInfo( this ICakeContext context, RepositoryInfoOptions options = null )
 {
     if( context == null ) throw new ArgumentNullException( "context" );
     return RepositoryInfo.LoadFromPath( context.Environment.WorkingDirectory.FullPath, options );
 }
 string ComputeIsDirty( Repository r, Commit commit, RepositoryInfoOptions options )
 {
     RepositoryStatus repositoryStatus = r.RetrieveStatus();
     int addedCount = repositoryStatus.Added.Count();
     int missingCount = repositoryStatus.Missing.Count();
     int removedCount = repositoryStatus.Removed.Count();
     int stagedCount = repositoryStatus.Staged.Count();
     StringBuilder b = null;
     if( addedCount > 0 || missingCount > 0 || removedCount > 0 || stagedCount > 0 )
     {
         b = new StringBuilder( "Found: " );
         if( addedCount > 0 ) b.AppendFormat( "{0} file(s) added", addedCount );
         if( missingCount > 0 ) b.AppendFormat( "{0}{1} file(s) missing", b.Length > 10 ? ", " : null, missingCount );
         if( removedCount > 0 ) b.AppendFormat( "{0}{1} file(s) removed", b.Length > 10 ? ", " : null, removedCount );
         if( stagedCount > 0 ) b.AppendFormat( "{0}{1} file(s) staged", b.Length > 10 ? ", " : null, removedCount );
     }
     else
     {
         int fileCount = 0;
         foreach( StatusEntry m in repositoryStatus.Modified )
         {
             string path = m.FilePath;
             if( !options.IgnoreModifiedFiles.Contains( path )
                 && (options.IgnoreModifiedFilePredicate == null
                     || !options.IgnoreModifiedFilePredicate( new ModifiedFile( r, commit, m, path ) )) )
             {
                 ++fileCount;
                 if( !options.IgnoreModifiedFileFullProcess )
                 {
                     Debug.Assert( b == null );
                     b = new StringBuilder( "At least one Modified file found: " );
                     b.Append( path );
                     break;
                 }
                 if( b == null )
                 {
                     b = new StringBuilder( "Modified file(s) found: " );
                     b.Append( path );
                 }
                 else if( fileCount <= 10 ) b.Append( ", " ).Append( path );
             }
         }
         if( fileCount > 10 ) b.AppendFormat( ", and {0} other file(s)", fileCount - 10 );
     }
     if( b == null ) return null;
     b.Append( '.' );
     return b.ToString();
 }
        string TryFindCommit( RepositoryInfoOptions options, Repository r, out Commit commit, out CIBranchVersionMode ciVersionMode, out string branchNameForCIVersion )
        {
            ciVersionMode = CIBranchVersionMode.None;
            commit = null;
            branchNameForCIVersion = null;
            string commitSha = options.StartingCommitSha;

            // Find current commit (the head) if none is provided.
            if( string.IsNullOrWhiteSpace( commitSha ) )
            {
                IEnumerable<string> branchNames;
                if( string.IsNullOrWhiteSpace( options.StartingBranchName ) )
                {
                    // locCommit is here because one cannot use an out parameter inside a lambda.
                    var locCommit = commit = r.Head.Tip;
                    if( locCommit == null ) return "Unitialized Git repository.";
                    // Save the branches!
                    // By doing this, when we are in 'Detached Head' state (the head of the repository is on a commit and not on a branch: git checkout <sha>),
                    // we can detect that it is the head of a branch and hence apply possible options (mainly CI) for it.
                    // We take into account only the branches from options.RemoteName remote here.
                    string branchName = r.Head.FriendlyName;
                    if( branchName == "(no branch)" )
                    {
                        string remotePrefix = options.RemoteName + '/';
                        branchNames = r.Branches
                                        .Where( b => b.Tip == locCommit && (!b.IsRemote || b.FriendlyName.StartsWith( remotePrefix )) )
                                        .Select( b => b.IsRemote ? b.FriendlyName.Substring( remotePrefix.Length ) : b.FriendlyName );
                    }
                    else branchNames = new[] { branchName };
                }
                else
                {
                    Branch br = r.Branches[options.StartingBranchName] ?? r.Branches[ options.RemoteName + '/' + options.StartingBranchName];
                    if( br == null ) return string.Format( "Unknown StartingBranchName: '{0}' (also tested on remote '{1}/{0}').", options.StartingBranchName, options.RemoteName );
                    commit = br.Tip;
                    branchNames = new[] { options.StartingBranchName };
                }
                RepositoryInfoOptionsBranch bOpt;
                if( options.Branches != null
                    && (bOpt = options.Branches.FirstOrDefault( b => branchNames.Contains( b.Name ) )) != null
                    && bOpt.CIVersionMode != CIBranchVersionMode.None )
                {
                    ciVersionMode = bOpt.CIVersionMode;
                    branchNameForCIVersion = string.IsNullOrWhiteSpace( bOpt.VersionName ) ? bOpt.Name : bOpt.VersionName;
                }
            }
            else
            {
                commit = r.Lookup<Commit>( commitSha );
                if( commit == null ) return string.Format( "Commit '{0}' not found.", commitSha );
            }
            return null;
        }
 RepositoryInfo( Repository r, RepositoryInfoOptions options, string gitSolutionDir )
     : this()
 {
     if( options == null ) options = new RepositoryInfoOptions();
     Options = options;
     if( r == null ) RepositoryError = "No Git repository.";
     else
     {
         Debug.Assert( gitSolutionDir != null && gitSolutionDir[gitSolutionDir.Length-1] == Path.DirectorySeparatorChar );
         GitSolutionDirectory = gitSolutionDir;
         Commit commit;
         CIBranchVersionMode ciVersionMode;
         string ciBuildName;
         RepositoryError = TryFindCommit( options, r, out commit, out ciVersionMode, out ciBuildName );
         Debug.Assert( (ciVersionMode != CIBranchVersionMode.None) == (ciBuildName != null) );
         if( commit != null )
         {
             CommitSha = commit.Sha;
             CommitDateUtc = commit.Author.When.ToUniversalTime().DateTime;
             IsDirtyExplanations = ComputeIsDirty( r, commit, options );
             if( !IsDirty || options.IgnoreDirtyWorkingFolder )
             {
                 StringBuilder errors = new StringBuilder();
                 TagCollector collector = new TagCollector( errors,
                                                             r,
                                                             options.StartingVersionForCSemVer,
                                                             c => c.Sha == CommitSha ? ReleaseTagParsingMode.RaiseErrorOnMalformedTag : ReleaseTagParsingMode.IgnoreMalformedTag,
                                                             options.OverriddenTags );
                 if( errors.Length == 0 )
                 {
                     CommitVersionInfo info = collector.GetVersionInfo( commit );
                     ExistingVersions = collector.ExistingVersions.TagCommits;
                     PossibleVersions = info.PossibleVersions;
                     PossibleVersionsStrict = info.PossibleVersionsStrict;
                     PreviousRelease = info.PreviousCommit;
                     PreviousMaxRelease = info.PreviousMaxCommit;
                     if( info.ThisCommit != null )
                     {
                         bool strictMode = options.PossibleVersionsMode.IsStrict();
                         var possibleSet = strictMode ? info.PossibleVersionsStrict : info.PossibleVersions;
                         if( possibleSet.Contains( info.ThisCommit.ThisTag ) )
                         {
                             ValidReleaseTag = info.ThisCommit.ThisTag;
                         }
                         else
                         {
                             ReleaseTagIsNotPossibleError = true;
                             errors.Append( "Release tag '" )
                                    .Append( info.ThisCommit.ThisTag.OriginalTagText )
                                    .Append( "' is not valid here. Valid tags are: " )
                                    .Append( string.Join( ", ", possibleSet ) )
                                    .AppendLine();
                             if( strictMode && info.PossibleVersions.Contains( info.ThisCommit.ThisTag ))
                             {
                                 if( options.PossibleVersionsMode == PossibleVersionsMode.Default )
                                 {
                                     errors.Append( "Consider setting <PossibleVersionsMode>AllSuccessors</PossibleVersionsMode> in RepositoryInfo.xml to allow this version." );
                                 }
                                 else
                                 {
                                     errors.Append( "Current <PossibleVersionsMode>Restricted</PossibleVersionsMode> in RepositoryInfo.xml forbids this version." );
                                 }
                             }
                         }
                     }
                     else
                     {
                         if( ciBuildName != null )
                         {
                             CIRelease = CIReleaseInfo.Create( commit, ciVersionMode, ciBuildName, errors, info );
                         }
                     }
                 }
                 if( errors.Length > 0 ) SetError( errors, out ReleaseTagErrorLines, out ReleaseTagErrorText );
             }
         }
     }
 }
Example #16
0
 RepositoryInfo(Repository r, RepositoryInfoOptions options, string gitSolutionDir)
     : this()
 {
     if (options == null)
     {
         options = new RepositoryInfoOptions();
     }
     Options = options;
     if (r == null)
     {
         RepositoryError = "No Git repository.";
     }
     else
     {
         Debug.Assert(gitSolutionDir != null && gitSolutionDir[gitSolutionDir.Length - 1] == Path.DirectorySeparatorChar);
         GitSolutionDirectory = gitSolutionDir;
         Commit commit;
         CIBranchVersionMode ciVersionMode;
         string ciBuildName;
         RepositoryError = TryFindCommit(options, r, out commit, out ciVersionMode, out ciBuildName);
         Debug.Assert((ciVersionMode != CIBranchVersionMode.None) == (ciBuildName != null));
         if (commit != null)
         {
             CommitSha           = commit.Sha;
             CommitDateUtc       = commit.Author.When.ToUniversalTime().DateTime;
             IsDirtyExplanations = ComputeIsDirty(r, commit, options);
             if (!IsDirty || options.IgnoreDirtyWorkingFolder)
             {
                 StringBuilder errors    = new StringBuilder();
                 TagCollector  collector = new TagCollector(errors,
                                                            r,
                                                            options.StartingVersionForCSemVer,
                                                            c => c.Sha == CommitSha ? ReleaseTagParsingMode.RaiseErrorOnMalformedTag : ReleaseTagParsingMode.IgnoreMalformedTag,
                                                            options.OverriddenTags);
                 if (errors.Length == 0)
                 {
                     CommitVersionInfo info = collector.GetVersionInfo(commit);
                     ExistingVersions       = collector.ExistingVersions.TagCommits;
                     PossibleVersions       = info.PossibleVersions;
                     PossibleVersionsStrict = info.PossibleVersionsStrict;
                     PreviousRelease        = info.PreviousCommit;
                     PreviousMaxRelease     = info.PreviousMaxCommit;
                     if (info.ThisCommit != null)
                     {
                         bool strictMode  = options.PossibleVersionsMode.IsStrict();
                         var  possibleSet = strictMode ? info.PossibleVersionsStrict : info.PossibleVersions;
                         if (possibleSet.Contains(info.ThisCommit.ThisTag))
                         {
                             ValidReleaseTag = info.ThisCommit.ThisTag;
                         }
                         else
                         {
                             ReleaseTagIsNotPossibleError = true;
                             errors.Append("Release tag '")
                             .Append(info.ThisCommit.ThisTag.OriginalTagText)
                             .Append("' is not valid here. Valid tags are: ")
                             .Append(string.Join(", ", possibleSet))
                             .AppendLine();
                             if (strictMode && info.PossibleVersions.Contains(info.ThisCommit.ThisTag))
                             {
                                 if (options.PossibleVersionsMode == PossibleVersionsMode.Default)
                                 {
                                     errors.Append("Consider setting <PossibleVersionsMode>AllSuccessors</PossibleVersionsMode> in RepositoryInfo.xml to allow this version.");
                                 }
                                 else
                                 {
                                     errors.Append("Current <PossibleVersionsMode>Restricted</PossibleVersionsMode> in RepositoryInfo.xml forbids this version.");
                                 }
                             }
                         }
                     }
                     else
                     {
                         if (ciBuildName != null)
                         {
                             CIRelease = CIReleaseInfo.Create(commit, ciVersionMode, ciBuildName, errors, info);
                         }
                     }
                 }
                 if (errors.Length > 0)
                 {
                     SetError(errors, out ReleaseTagErrorLines, out ReleaseTagErrorText);
                 }
             }
         }
     }
 }
Example #17
0
 bool ComputeIsDirty( Repository r, Commit commit, RepositoryInfoOptions options )
 {
     bool isDirty = false;
     RepositoryStatus repositoryStatus = r.RetrieveStatus();
     if( repositoryStatus.Added.Any()
         || repositoryStatus.Missing.Any()
         || repositoryStatus.Removed.Any()
         || repositoryStatus.Staged.Any() ) return true;
     foreach( StatusEntry m in repositoryStatus.Modified )
     {
         if( !options.IgnoreModifiedFiles.Contains( m.FilePath )
             && (options.IgnoreModifiedFilePredicate == null || !options.IgnoreModifiedFilePredicate( new ModifiedFile( r, commit, m ) )) )
         {
             isDirty = true;
             if( !options.IgnoreModifiedFileFullProcess ) break;
         }
     }
     return isDirty;
 }
        string ComputeIsDirty(Repository r, Commit commit, RepositoryInfoOptions options)
        {
            RepositoryStatus repositoryStatus = r.RetrieveStatus();
            int           addedCount          = repositoryStatus.Added.Count();
            int           missingCount        = repositoryStatus.Missing.Count();
            int           removedCount        = repositoryStatus.Removed.Count();
            int           stagedCount         = repositoryStatus.Staged.Count();
            StringBuilder b = null;

            if (addedCount > 0 || missingCount > 0 || removedCount > 0 || stagedCount > 0)
            {
                b = new StringBuilder("Found: ");
                if (addedCount > 0)
                {
                    b.AppendFormat("{0} file(s) added", addedCount);
                }
                if (missingCount > 0)
                {
                    b.AppendFormat("{0}{1} file(s) missing", b.Length > 10 ? ", " : null, missingCount);
                }
                if (removedCount > 0)
                {
                    b.AppendFormat("{0}{1} file(s) removed", b.Length > 10 ? ", " : null, removedCount);
                }
                if (stagedCount > 0)
                {
                    b.AppendFormat("{0}{1} file(s) staged", b.Length > 10 ? ", " : null, removedCount);
                }
            }
            else
            {
                int fileCount = 0;
                foreach (StatusEntry m in repositoryStatus.Modified)
                {
                    string path = m.FilePath;
                    if (!options.IgnoreModifiedFiles.Contains(path) &&
                        (options.IgnoreModifiedFilePredicate == null ||
                         !options.IgnoreModifiedFilePredicate(new ModifiedFile(r, commit, m, path))))
                    {
                        ++fileCount;
                        if (!options.IgnoreModifiedFileFullProcess)
                        {
                            Debug.Assert(b == null);
                            b = new StringBuilder("At least one Modified file found: ");
                            b.Append(path);
                            break;
                        }
                        if (b == null)
                        {
                            b = new StringBuilder("Modified file(s) found: ");
                            b.Append(path);
                        }
                        else if (fileCount <= 10)
                        {
                            b.Append(", ").Append(path);
                        }
                    }
                }
                if (fileCount > 10)
                {
                    b.AppendFormat(", and {0} other file(s)", fileCount - 10);
                }
            }
            if (b == null)
            {
                return(null);
            }
            b.Append('.');
            return(b.ToString());
        }
        string TryFindCommit(RepositoryInfoOptions options, Repository r, out Commit commit, out CIBranchVersionMode ciVersionMode, out string branchNameForCIVersion)
        {
            ciVersionMode          = CIBranchVersionMode.None;
            commit                 = null;
            branchNameForCIVersion = null;
            string commitSha = options.StartingCommitSha;

            // Find current commit (the head) if none is provided.
            if (string.IsNullOrWhiteSpace(commitSha))
            {
                IEnumerable <string> branchNames;
                if (string.IsNullOrWhiteSpace(options.StartingBranchName))
                {
                    // locCommit is here because one cannot use an out parameter inside a lambda.
                    var locCommit = commit = r.Head.Tip;
                    if (locCommit == null)
                    {
                        return("Unitialized Git repository.");
                    }
                    // Save the branches!
                    // By doing this, when we are in 'Detached Head' state (the head of the repository is on a commit and not on a branch: git checkout <sha>),
                    // we can detect that it is the head of a branch and hence apply possible options (mainly CI) for it.
                    // We take into account only the branches from options.RemoteName remote here.
                    string branchName = r.Head.FriendlyName;
                    if (branchName == "(no branch)")
                    {
                        string remotePrefix = options.RemoteName + '/';
                        branchNames = r.Branches
                                      .Where(b => b.Tip == locCommit && (!b.IsRemote || b.FriendlyName.StartsWith(remotePrefix)))
                                      .Select(b => b.IsRemote ? b.FriendlyName.Substring(remotePrefix.Length) : b.FriendlyName);
                    }
                    else
                    {
                        branchNames = new[] { branchName }
                    };
                }
                else
                {
                    string remotePrefix    = options.RemoteName + '/';
                    string localBranchName = options.StartingBranchName.StartsWith(remotePrefix)
                                                ? options.StartingBranchName.Substring(remotePrefix.Length)
                                                : options.StartingBranchName;
                    Branch br = r.Branches[options.StartingBranchName];
                    if (br == null && ReferenceEquals(localBranchName, options.StartingBranchName))
                    {
                        string remoteName = remotePrefix + options.StartingBranchName;
                        br = r.Branches[remoteName];
                        if (br == null)
                        {
                            return($"Unknown StartingBranchName: '{options.StartingBranchName}' (also tested on remote '{remoteName}').");
                        }
                    }
                    if (br == null)
                    {
                        return($"Unknown (remote) StartingBranchName: '{options.StartingBranchName}'.");
                    }
                    commit      = br.Tip;
                    branchNames = new[] { localBranchName };
                }
                RepositoryInfoOptionsBranch bOpt;
                if (options.Branches != null &&
                    (bOpt = options.Branches.FirstOrDefault(b => branchNames.Contains(b.Name))) != null &&
                    bOpt.CIVersionMode != CIBranchVersionMode.None)
                {
                    ciVersionMode          = bOpt.CIVersionMode;
                    branchNameForCIVersion = string.IsNullOrWhiteSpace(bOpt.VersionName) ? bOpt.Name : bOpt.VersionName;
                }
            }
            else
            {
                commit = r.Lookup <Commit>(commitSha);
                if (commit == null)
                {
                    return($"Commit '{commitSha}' not found.");
                }
            }
            return(null);
        }