private void GitBasedTest(string gitignore, string[] files) { // setup gitignore gitFixture.AddTrackedFileToRepo(".gitignore", gitignore); // add untracked files to filesystem files.ToList().ForEach(file => { if (file.EndsWith("/")) { // create directory gitFixture.AddUntrackedDirToRepo(file); } else { gitFixture.AddUntrackedFileToRepo(file); } }); // get results of git var gitUntrackedFiles = gitFixture.GetUntrackedFiles().Select(se => se.FilePath).ToList(); // setup ignore var ignore = new Ignore(); ignore.Add(gitignore.Split("\n")); // get results of ignore var ignoreFilteredFiles = ignore.Filter(files); Assert.Equal(gitUntrackedFiles.OrderBy(a => a), ignoreFilteredFiles.OrderBy(a => a)); }
/// <summary> /// Conditions for files/fodlers which should not be synced. /// </summary> /// <param name="paths">Paths</param> public void AddIgnore(params string[] regexes) { foreach (var regex in regexes) { if (regex != "" && !Ignore.Contains(regex)) { Ignore.Add(regex); } } }
/// <summary> /// Discard from counting if the file should be excluded. /// Handles both <see cref="Context.Context.Included"/> and <see cref="Context.Context.Excluded"/>. /// </summary> /// <param name="gitFilePatch">Git file patch.</param> /// <param name="includedPatterns">Gitignore style patterns to include.</param> /// <param name="excludedPatterns">Gitignore style patterns to exclude.</param> /// <returns>True if the file patch is excluded, false otherwise.</returns> public static bool RemoveNotIncludedOrExcluded( this GitFilePatch gitFilePatch, IEnumerable <string> includedPatterns, IEnumerable <string> excludedPatterns) { ArgumentCheck.ParameterIsNotNull(gitFilePatch, nameof(gitFilePatch)); var ignore = new Ignore(); // if included patterns are specified, do not consider excluded patterns var includedPatternList = includedPatterns?.ToList(); if (includedPatternList != null && includedPatternList.Any()) { ignore.Add(includedPatternList); // not ignored by ignore effectively means this is not a match // and must be excluded if (!ignore.IsIgnored(gitFilePatch.FilePath)) { gitFilePatch.DiscardFromCounting = true; return(true); } return(false); } var excludedPatternList = excludedPatterns?.ToList(); if (excludedPatternList == null) { return(false); } ignore.Add(excludedPatternList); if (ignore.IsIgnored(gitFilePatch.FilePath)) { gitFilePatch.DiscardFromCounting = true; return(true); } return(false); }
static void KeepAsmDefActive() { var file_name = Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(Selection.activeObject)); var active = Ignore.Contains(file_name); if (!active) { Ignore.Add(file_name); } else { Ignore.Remove(file_name); } Menu.SetChecked("Assets/Keep AsmDef active", !active); }
// ReSharper disable once UnusedMember.Local // ReSharper disable once UnusedParameter.Local // ReSharper disable once RedundantAssignment private static bool Prefix(string[] guids, string fileName, bool needsPackageManagerManifest) { // we want to patch this if there's packages in here var anyFileInPackages = guids.Select(AssetDatabase.GUIDToAssetPath).Any(x => x.StartsWith("Packages/", StringComparison.Ordinal)); if (anyFileInPackages && needsPackageManagerManifest) { throw new ArgumentException("When exporting Hybrid Packages, please don't enable the \"Include Dependencies\" option. Specify dependencies via package.json."); } // custom package export - constructing .unitypackage while respecting AssetDatabase, // hidden top-level folders (end with ~) and .npmignore/.gitignore if (anyFileInPackages) { var sw = new Stopwatch(); sw.Start(); EditorUtility.DisplayProgressBar("Creating .unitypackage", "Collecting Packages", 0f); Profiler.BeginSample("Collecting Packages"); // get all packages we want to export var packageRoots = new HashSet <string>(); // the resulting project-relative paths (not absolute paths) var exportPaths = new HashSet <string>(); // all the currently selected files from AssetDB should be exported anyways var assetDatabasePaths = guids.Select(AssetDatabase.GUIDToAssetPath).ToList(); foreach (var p in assetDatabasePaths) { exportPaths.Add(p); } foreach (var path0 in assetDatabasePaths) { var path = path0; if (!path.StartsWith("Packages/", StringComparison.Ordinal)) { continue; } path = path.Substring("Packages/".Length); var indexOfSlash = path.IndexOf("/", StringComparison.Ordinal); var packageName = path.Substring(0, indexOfSlash); path = "Packages/" + packageName; if (!packageRoots.Contains(path)) { packageRoots.Add(path); } } Profiler.EndSample(); #region Handle file ignore var ignoreFiles = new List <(string dir, Ignore ignore)>(); // collect npm and gitignore files in all subdirectories void CollectIgnoreFiles(string directory) { Profiler.BeginSample(nameof(CollectIgnoreFiles)); ignoreFiles.Clear(); var di = new DirectoryInfo(directory); void AddToIgnore(List <(string dir, Ignore ignore)> ignoreList, string searchPattern, SearchOption searchOption) { try { foreach (var file in di.GetFiles(searchPattern, searchOption)) { var ignore = new Ignore(); ignore.Add(File.ReadAllLines(file.FullName).Where(x => !string.IsNullOrWhiteSpace(x.Trim()) && !x.TrimStart().StartsWith("#", StringComparison.Ordinal))); var fileDirectory = file.Directory; if (fileDirectory != null) { ignoreFiles.Add((fileDirectory.FullName.Replace("\\", "/"), ignore)); } } } catch (IOException) { // ignore } } // find all ignore files in subdirectories AddToIgnore(ignoreFiles, ".gitignore", SearchOption.AllDirectories); AddToIgnore(ignoreFiles, ".npmignore", SearchOption.AllDirectories); var upwardsIgnoreFiles = new List <(string, Ignore)>(); bool folderIsInsideGitRepository = false; try { // find ignore files up to directory root or until a .git folder is found while (di.Parent != null) { di = di.Parent; AddToIgnore(upwardsIgnoreFiles, ".gitignore", SearchOption.TopDirectoryOnly); AddToIgnore(upwardsIgnoreFiles, ".npmignore", SearchOption.TopDirectoryOnly); // we should stop at a git repo (.git folder) or a submodule (.git file) if (di.GetDirectories(".git", SearchOption.TopDirectoryOnly).Any() || di.GetFiles(".git", SearchOption.TopDirectoryOnly).Any()) { folderIsInsideGitRepository = true; break; } } } catch (IOException) { folderIsInsideGitRepository = false; upwardsIgnoreFiles.Clear(); } // if we found any upwards git folder we add those ignore files to our list here, otherwise // let's assume this isn't inside a git repo and we shouldn't look at those. if (folderIsInsideGitRepository) { ignoreFiles.AddRange(upwardsIgnoreFiles); } Profiler.EndSample(); } bool IsIgnored(string filePath) { Profiler.BeginSample(nameof(IsIgnored)); filePath = filePath.Replace("\\", "/"); foreach (var ig in ignoreFiles) { var dirLength = ig.dir.Length + 1; // check if the file is a sub file of the ignore file // because we dont want to apply ignore patterns to external files // e.g. a file in "stuff/material" should not be affected from "myFolder/.gitignore" if (filePath.StartsWith(ig.dir)) { var checkedPath = filePath.Substring(dirLength); if (ig.ignore.IsIgnored(checkedPath)) { Debug.Log("<b>File will be ignored:</b> " + filePath + ", location of .ignore: " + ig.dir); Profiler.EndSample(); return(true); } } } Profiler.EndSample(); return(false); } #endregion int counter = 0; int length = packageRoots.Count; foreach (var root in packageRoots) { EditorUtility.DisplayProgressBar("Creating .unitypackage", "Collecting Files for Package: " + root, counter / (float)length); counter++; Profiler.BeginSample("Collecting Files for Package: " + root); var fullPath = Path.GetFullPath(root); CollectIgnoreFiles(root); // include all hidden directories (end with ~) foreach (var directory in new DirectoryInfo(root).GetDirectories("*", SearchOption.AllDirectories)) { try { if (directory.Name.StartsWith(".", StringComparison.Ordinal)) { continue; } // this is a hidden folder. We want to include it in our export to catch // - Samples~ // - Documentation~ // - Templates~ // and so on. if (directory.Name.EndsWith("~", StringComparison.Ordinal)) { // add all files in this directory foreach (var file in directory.GetFiles("*", SearchOption.AllDirectories)) { if (defaultNpmIgnore.Contains(file.Name)) { continue; } if (file.Extension.EndsWith(".meta", StringComparison.OrdinalIgnoreCase)) { continue; } if (currentUploadConfig && currentUploadConfig.respectIgnoreFiles && IsIgnored(file.FullName)) { continue; } var projectRelativePath = file.FullName.Replace(fullPath, root); exportPaths.Add(projectRelativePath); } } } catch (IOException) { // } } Profiler.EndSample(); } // Debug.Log("<b>" + fileName + "</b>" + "\n" + string.Join("\n", exportPaths)); EditorUtility.DisplayProgressBar("Creating .unitypackage", "Start Packing to " + fileName, 0.2f); Profiler.BeginSample("Create .unitypackage"); var dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/Unity/AssetStoreTools/Export"; var guidToFile = new Dictionary <string, string>(); foreach (var path in exportPaths.OrderByDescending(x => AssetDatabase.GetMainAssetTypeAtPath(x) != null)) { UnitypackageExporter.AddToUnityPackage(path, dir, ref guidToFile); } var compressionStrength = currentUploadConfig ? currentUploadConfig.compressionStrength : Zipper.CompressionStrength.Normal; if (!Zipper.TryCreateTgz(dir, fileName, compressionStrength)) { Profiler.EndSample(); throw new Exception("Failed creating .unitypackage " + fileName); } EditorUtility.RevealInFinder(fileName); Directory.Delete(dir, true); Profiler.EndSample(); EditorUtility.DisplayProgressBar("Creating .unitypackage", "Done", 1f); EditorUtility.ClearProgressBar(); Debug.Log("Created .unitypackage at " + fileName + " in " + (sw.ElapsedMilliseconds / 1000f).ToString("F2") + "s"); return(false); } // Debug.Log("<b>" + fileName + "</b>" + "\n" + string.Join("\n", guids.Select(AssetDatabase.GUIDToAssetPath))); return(true); }