Exemple #1
0
        /// <summary>
        /// Parses a gitignore file.
        /// </summary>
        /// <param name="path">The path of the file to parse.</param>
        /// <param name="ignoreParentDirectories">If <c>true</c>, the gitignore files in parent directories will be included.</param>
        /// <returns>A list of <see cref="IgnoreRule"/> instances.</returns>
        public static IgnoreFile Parse(string path, bool includeParentDirectories = false)
        {
            var ignoreFile = new IgnoreFile(path);

            var currentDir = new DirectoryInfo(Path.GetDirectoryName(path));

            while (currentDir != null && currentDir.Exists)
            {
                var gitIgnoreFilename = Path.Combine(currentDir.FullName, ".gitignore");

                if (File.Exists(gitIgnoreFilename))
                {
                    var basePath = currentDir.FullName.Replace("\\", "/") + "/";

                    var localRules = new List <IgnoreRule>();

                    // Ignore .git folders by default
                    localRules.Add(IgnoreRule.Parse(basePath, ".git/"));

                    // Don't process parent folder if we are at the repository level
                    if (Directory.Exists(Path.Combine(currentDir.FullName, ".git")))
                    {
                        currentDir = null;
                    }

                    using (var stream = File.OpenText(gitIgnoreFilename))
                    {
                        string rule = null;

                        while (null != (rule = stream.ReadLine()))
                        {
                            // A blank line matches no files, so it can serve as a separator for readability.
                            if (string.IsNullOrWhiteSpace(rule))
                            {
                                continue;
                            }

                            // A line starting with # serves as a comment.
                            if (rule.StartsWith('#'))
                            {
                                continue;
                            }

                            var ignoreRule = IgnoreRule.Parse(basePath, rule);

                            if (ignoreRule != null)
                            {
                                localRules.Add(ignoreRule);
                            }
                        }
                    }

                    // Insert the rules from this folder at the top of the list, while preserving the file order
                    for (var i = 0; i < localRules.Count; i++)
                    {
                        ignoreFile.Rules.Insert(i, localRules[i]);
                    }

                    currentDir = currentDir?.Parent;
                }
            }

            return(ignoreFile);
        }