public static IndexDifferences FindDifferences(
            IFileSystem fileSystem,
            IEnumerable<LucenePackage> indexedPackages,
            CancellationToken cancellationToken,
            Action<SynchronizationState> setState,
            SynchronizationMode mode)
        {
            setState(SynchronizationState.ScanningFiles);

            var fileSystemPackages = fileSystem.GetFiles(string.Empty, "*" + Constants.PackageExtension, true)
                                               .WithCancellation(cancellationToken)
                                               .Where(file => !fileSystem.IsTempFile(file))
                                               .ToArray();

            setState(SynchronizationState.ScanningIndex);

            var indexedPackagesByPath = indexedPackages
                                            .WithCancellation(cancellationToken)
                                            .ToDictionary(pkg => pkg.Path, StringComparer.InvariantCultureIgnoreCase);

            setState(SynchronizationState.Comparing);

            var calc = new IndexDifferenceCalculator(fileSystem, fileSystemPackages, indexedPackagesByPath);

            return calc.Calculate(mode);
        }
 /// <summary>
 /// *.nupkg files in the root folder
 /// </summary>
 private IEnumerable <string> GetPackageFiles()
 {
     // Check top level directory
     foreach (var path in _fileSystem.GetFiles(String.Empty, _filter))
     {
         yield return(path);
     }
 }
Example #3
0
        public IEnumerable <string> GetFiles()
        {
            var files = fileSystem.GetFiles(importFolderConfiguration.ProcessingFolder, importFileSearchOption).ToList();

            // .Where(file => !capturedFiles.Contains(file)).ToList();

            files.AddRange(fileSystem.GetFiles(importFolderConfiguration.InitialFolder));

            if (files.Any())
            {
                return(files);
            }

            UnpackZipArchives();
            files = fileSystem.GetFiles(importFolderConfiguration.InitialFolder).ToList();

            return(files);
        }
Example #4
0
        public Task <QueryResult <FileMetadata> > GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var account = GetSyncAccounts()
                          .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var result = new QueryResult <FileMetadata>();

            if (!string.IsNullOrWhiteSpace(query.Id))
            {
                var file = _fileSystem.GetFileSystemInfo(query.Id);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFile).ToArray();
                }

                return(Task.FromResult(result));
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var fullPath = GetFullPath(query.FullPath, target);
                var file     = _fileSystem.GetFileSystemInfo(fullPath);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFile).ToArray();
                }

                return(Task.FromResult(result));
            }

            FileMetadata[] files;

            try
            {
                files = _fileSystem.GetFiles(account.Path, true)
                        .Select(GetFile)
                        .ToArray();
            }
            catch (DirectoryNotFoundException)
            {
                files = new FileMetadata[] { };
            }

            result.Items            = files;
            result.TotalRecordCount = files.Length;

            return(Task.FromResult(result));
        }
Example #5
0
        public IEnumerable <AppFile> GetFiles(string folderPath)
        {
            foreach (string filePath in _fileSystem.GetFiles(folderPath))
            {
                AppFile file = _fileSystem.CreateAppFile(filePath);

                yield return(file);
            }
        }
Example #6
0
        public AbsoluteDirectoryPath CreateProject(string name, Template template, Optional <AbsoluteDirectoryPath> destinationPath)
        {
            var location = destinationPath.HasValue ? destinationPath.Value : DirectoryPath.GetCurrentDirectory();

            var projectDir = location / name;

            if (_fileSystem.Exists(projectDir) &&
                (_fileSystem.GetFiles(projectDir).Any() || _fileSystem.GetDirectories(projectDir).Any()))
            {
                throw new ProjectFolderNotEmpty();
            }

            var environment = new TemplateVariableResolver().With("filename", name);

            TemplateSpawner.SpawnTemplate(template, projectDir, environment, _fileSystem);

            return(projectDir);
        }
        /// <summary>
        /// Gets files for a particular pattern recursively.
        /// </summary>
        /// <param name="fileSystem"></param>
        /// <param name="path"></param>
        /// <param name="filter"></param>
        /// <param name="option"> </param>
        /// <returns></returns>
        public static IEnumerable <string> GetFiles(this IFileSystem fileSystem, string path, string filter, SearchOption option)
        {
            if (option == SearchOption.TopDirectoryOnly)
            {
                return(fileSystem.GetFiles(path, filter));
            }

            return(fileSystem.GetFilesRecursive(path, filter));
        }
Example #8
0
        private void LoadPlugins(string directory)
        {
            var pluginDlls = _fileSystem.GetFiles(directory, "*.dll");

            foreach (var pluginDll in pluginDlls)
            {
                LoadPlugin(pluginDll);
            }
        }
        public override void TearDown()
        {
            if (fs.DirectoryExists("/upload/"))
            {
                try
                {
                    fs.DeleteDirectory("/upload/");
                }
                catch (Exception ex)
                {
                    Thread.Sleep(1000);
                    System.Diagnostics.Debug.WriteLine("Trying to recover from " + ex.Message + " with files: " + string.Join(", ", fs.GetDirectories("/upload/").Select(f => f.VirtualPath).Concat(fs.GetFiles("/upload/").Select(f => f.VirtualPath))));
                    fs.DeleteDirectory("/upload/");
                }
            }

            base.TearDown();
        }
Example #10
0
 protected override IEnumerable <IMacro> PerformGetAll(params string[] ids)
 {
     if (ids.Any())
     {
         foreach (var id in ids)
         {
             yield return(Get(id));
         }
     }
     else
     {
         var files = _fileSystem.GetFiles("", "*.macro");
         foreach (var file in files)
         {
             yield return(Get(file.Replace(".macro", "")));
         }
     }
 }
Example #11
0
 public void FindMigrations_NoFiles_IsNoMigrations()
 {
     using (_mocks.Record())
     {
         SetupResult.For(_configuration.MigrationsDirectory).Return("MigrationsDirectory");
         SetupResult.For(_fileSystem.GetFiles("MigrationsDirectory")).Return(new string[0]);
         SetupResult.For(_fileSystem.GetDirectories("MigrationsDirectory")).Return(new string[0]);
     }
     CollectionAssert.IsEmpty(new List <MigrationReference>(_target.FindMigrations()));
     _mocks.VerifyAll();
 }
        protected override ActionResult <TreeNodeCollection> GetTreeNodes(string id, FormCollection queryStrings)
        {
            var path = string.IsNullOrEmpty(id) == false && id != Constants.System.RootString
                ? WebUtility.UrlDecode(id).TrimStart("/")
                : "";

            var nodes       = new TreeNodeCollection();
            var directories = _fileSystem.GetDirectories(path);

            foreach (var directory in directories)
            {
                // We don't want any other directories under the root node other than the ones serving static files - App_Plugins and wwwroot
                if (id == Constants.System.RootString && directory != AppPlugins && directory != Webroot)
                {
                    continue;
                }

                var hasChildren = _fileSystem.GetFiles(directory).Any() || _fileSystem.GetDirectories(directory).Any();

                var name = Path.GetFileName(directory);
                var node = CreateTreeNode(WebUtility.UrlEncode(directory), path, queryStrings, name, Constants.Icons.Folder, hasChildren);

                if (node != null)
                {
                    nodes.Add(node);
                }
            }

            // Only get the files inside App_Plugins and wwwroot
            var files = _fileSystem.GetFiles(path).Where(x => x.StartsWith(AppPlugins) || x.StartsWith(Webroot));

            foreach (var file in files)
            {
                var name = Path.GetFileName(file);
                var node = CreateTreeNode(WebUtility.UrlEncode(file), path, queryStrings, name, Constants.Icons.DefaultIcon, false);

                if (node != null)
                {
                    nodes.Add(node);
                }
            }

            return(nodes);
        }
 public static IEnumerable <string> ResolveRefreshPaths(this IFileSystem fileSystem)
 {
     // Resolve all .refresh files from the website's bin directory. Once resolved, verify the path exists on disk and that they look like an assembly reference.
     return(from file in fileSystem.GetFiles("bin", "*" + RefreshFileExtension)
            let resolvedPath = SafeResolveRefreshPath(fileSystem, file)
                               where resolvedPath != null &&
                               fileSystem.FileExists(resolvedPath) &&
                               Constants.AssemblyReferencesExtensions.Contains(Path.GetExtension(resolvedPath))
                               select resolvedPath);
 }
Example #14
0
 public Project GetStatus()
 {
     return(new Project {
         Name = "Project",
         Files = from path in _fileSystem.GetFiles()
                 select new File {
             Path = path
         }
     });
 }
Example #15
0
 private static IEnumerable <IFile> GetFiles(IFileSystem fs)
 {
     foreach (var file in fs.GetFiles(new FilePath("rules"), ".json"))
     {
         if (!file.Name.StartsWith("__", StringComparison.OrdinalIgnoreCase))
         {
             yield return(file);
         }
     }
 }
        public static ulong GetDirectoryLength(this IFileSystem fileSystem, string directory)
        {
            ulong size = 0;

            foreach (var file in fileSystem.GetFiles(directory, "*", false))
            {
                size += (ulong)fileSystem.GetFileLength(file);
            }
            return(size);
        }
        public void GetFiles_Gets_Files_In_Directory()
        {
            // arrange
            var expected = new[] { testFile, testFile2 };

            // act
            var actual = fileSystem.GetFiles(testFolder);

            // assert
            Assert.Equal(expected.OrderBy(e => e), actual.OrderBy(a => a));
        }
Example #18
0
        private void DeleteOrphanFiles(string dir, IEnumerable <Image> images)
        {
            if (!_fs.DirectoryExists(dir))
            {
                return;
            }

            foreach (var file in _fs.GetFiles(dir))
            {
                if (!images.Any(x => x.Filename == Path.GetFileName(file)))
                {
                    _fs.DeleteFile(file);
                }
            }

            if (!_fs.GetFiles(dir).Any())
            {
                _fs.DeleteDirectory(dir);
            }
        }
        public IEnumerable <ReplicatedItem> GetItems()
        {
            if (_fs == null)
            {
                throw new Exception("no filesystem");
            }

            var items = _fs.GetFiles(_path).Where(f => f.Name.EndsWith(".xml")).Select(f => new ReplicatedItem(f));

            return(items);
        }
    private IEnumerable <string> GetLocales(string path)
    {
        var cultures = _jsLibFileSystem.GetFiles(path, "*.js").ToList();

        for (var i = 0; i < cultures.Count; i++)
        {
            cultures[i] = cultures[i].Substring(cultures[i].IndexOf(path, StringComparison.Ordinal) + path.Length + 1);
        }

        return(cultures);
    }
Example #21
0
        private IEnumerable <string> GetAssemblyListFromDirectory()
        {
            var fqfn      = _fileSystem.GetFiles(Arguments[0], "*.dll");
            var filenames = fqfn.Select(f =>
            {
                var sfn = new FileInfo(f);
                return(sfn.Name);
            });

            return(filenames);
        }
        public void TearDown()
        {
            //Delete all files
            var files = _fileSystem.GetFiles("", "*.css");

            foreach (var file in files)
            {
                _fileSystem.DeleteFile(file);
            }
            _fileSystem = null;
        }
Example #23
0
        internal static IEnumerable <string> GetFilesSafe(this IFileSystem fileSystem, string path, string filter)
        {
            try {
                return(fileSystem.GetFiles(path, filter));
            }
            catch (Exception e) {
                fileSystem.Logger.Log(MessageLevel.Warning, e.Message);
            }

            return(Enumerable.Empty <string>());
        }
Example #24
0
        public IEnumerable <FontFile> GetFallbackFontList()
        {
            var encodingOptions  = _serverConfigurationManager.GetEncodingOptions();
            var fallbackFontPath = encodingOptions.FallbackFontPath;

            if (!string.IsNullOrEmpty(fallbackFontPath))
            {
                var files     = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false);
                var fontFiles = files
                                .Select(i => new FontFile
                {
                    Name         = i.Name,
                    Size         = i.Length,
                    DateCreated  = _fileSystem.GetCreationTimeUtc(i),
                    DateModified = _fileSystem.GetLastWriteTimeUtc(i)
                })
                                .OrderBy(i => i.Size)
                                .ThenBy(i => i.Name)
                                .ThenByDescending(i => i.DateModified)
                                .ThenByDescending(i => i.DateCreated);
                // max total size 20M
                const int MaxSize     = 20971520;
                var       sizeCounter = 0L;
                foreach (var fontFile in fontFiles)
                {
                    sizeCounter += fontFile.Size;
                    if (sizeCounter >= MaxSize)
                    {
                        _logger.LogWarning("Some fonts will not be sent due to size limitations");
                        yield break;
                    }

                    yield return(fontFile);
                }
            }
            else
            {
                _logger.LogWarning("The path of fallback font folder has not been set");
                encodingOptions.EnableFallbackFont = false;
            }
        }
Example #25
0
        /// <summary>
        /// Returns all image files that match the fileName??.extension criteria.
        /// </summary>
        /// <param name="fileName">Name of the files without the index number.</param>
        /// <returns>The string of the files.</returns>
        public string[] GetAnimationFiles(string fileName)
        {
            string extension = "." + Purple.IO.Path.GetExtension(fileName);
            string path      = Purple.IO.Path.GetFolder(fileName);
            string name      = Purple.IO.Path.GetFileName(fileName);

            name = fileName.Remove(name.Length - extension.Length, extension.Length);

            string[] files = fileSystem.GetFiles(path, name + @"\d\d" + @"\" + extension + "$");
            Array.Sort(files);
            return(files);
        }
        private static IEnumerable <string> GetFilesRecursive(this IFileSystem fileSystem, string path, string filter)
        {
            var files = new List <string>();

            files.AddRange(fileSystem.GetFiles(path, filter));

            foreach (var subDir in fileSystem.GetDirectories(path))
            {
                files.AddRange(fileSystem.GetFilesRecursive(subDir, filter));
            }
            return(files.Distinct());
        }
Example #27
0
        public IEnumerable <string> GetSupportedMomentLocales()
        {
            const string momentLocaleFolder = "moment";
            var          cultures           = _jsLibFileSystem.GetFiles(momentLocaleFolder, "*.js").ToList();

            for (var i = 0; i < cultures.Count; i++)
            {
                cultures[i] = cultures[i]
                              .Substring(cultures[i].IndexOf(momentLocaleFolder, StringComparison.Ordinal) + momentLocaleFolder.Length + 1);
            }
            return(cultures);
        }
Example #28
0
        public IEnumerable <string> Gather(YamlConfig configuration)
        {
            var files = new List <string>();

            foreach (var kvp in configuration.Rules)
            {
                var theseFiles = _fileSystem.GetFiles(".", kvp.Key).Select(f => Path.GetFullPath(f));
                files.AddRange(theseFiles);
            }

            return(files);
        }
Example #29
0
 public void ProcessDirectoryFiles(EnumerationState state)
 {
     foreach (var file in fs.GetFiles(state.DirectoryName, "*.py", SearchOption.TopDirectoryOnly))
     {
         var xlator = new Translator(
             state.Namespace,
             fs.GetFileNameWithoutExtension(file),
             new FileSystem(),
             new ConsoleLogger());
         xlator.TranslateFile(file, file + ".cs");
     }
 }
Example #30
0
        IEnumerable <string> GetFiles(FolderFilter folderFilter)
        {
            string[] files;
            string   startFolder = Path.Combine(_RootFolder, folderFilter.Folder);

            if (_FileSystem.GetFiles(startFolder, folderFilter.FilePattern, folderFilter.IncludeSubfolders, out files))
            {
                foreach (string file in files)
                {
                    yield return(file);
                }
                yield break;
            }

            if (folderFilter.IncludeSubfolders)
            {
                Queue <string> folders = new Queue <string>();
                folders.Enqueue(startFolder);
                while (folders.Count != 0)
                {
                    string folder = folders.Dequeue();

                    if (_FileSystem.GetFiles(folder, folderFilter.FilePattern, false, out files))
                    {
                        foreach (string file in files)
                        {
                            yield return(file);
                        }
                    }

                    if (folderFilter.IncludeSubfolders && _FileSystem.GetFolders(folder, out files))
                    {
                        foreach (string subfolder in files)
                        {
                            folders.Enqueue(subfolder);
                        }
                    }
                }
            }
        }
Example #31
0
        public IEnumerable <PackageInfo> FindPackagesById(string packageId)
        {
            if (String.IsNullOrEmpty(packageId))
            {
                throw new ArgumentNullException("packageId");
            }

            // packages\{packageId}\{version}\{packageId}.nuspec
            return(_cache.GetOrAdd(packageId, id =>
            {
                var packages = new List <PackageInfo>();

                foreach (var versionDir in _repositoryRoot.GetDirectories(id))
                {
                    // versionDir = {packageId}\{version}
                    var folders = versionDir.Split(new[] { Path.DirectorySeparatorChar }, 2);

                    // Unknown format
                    if (folders.Length < 2)
                    {
                        continue;
                    }

                    var versionPart = folders[1];

                    // Get the version part and parse it
                    SemanticVersion version;
                    if (!SemanticVersion.TryParse(versionPart, out version))
                    {
                        continue;
                    }

                    // If we need to help ensure case-sensitivity, we try to get
                    // the package id in accurate casing by extracting the name of nuspec file
                    // Otherwise we just use the passed in package id for efficiency
                    if (_checkPackageIdCase)
                    {
                        var manifestFileName = Path.GetFileName(
                            _repositoryRoot.GetFiles(versionDir, "*" + Constants.ManifestExtension).FirstOrDefault());
                        if (string.IsNullOrEmpty(manifestFileName))
                        {
                            continue;
                        }
                        id = Path.GetFileNameWithoutExtension(manifestFileName);
                    }

                    packages.Add(new PackageInfo(_repositoryRoot, id, version, versionDir));
                }

                return packages;
            }));
        }
Example #32
0
 public DirectorySync(string directoryPath, ISyncFactory factory, IFileSystem fileSystem,
     IDirectoryValidator validator, IProjectFactory projectFactory)
 {
     var files = fileSystem.GetFiles(directoryPath, "*.csproj", SearchOption.AllDirectories);
     foreach (var file in files)
     {
         if (validator.IsDirectoryValid(file) && projectFactory.IsValidProject(file))
         {
             var project = factory.CreateProjectSynchronizer(file);
             _projects.Add(project);
         }
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RepositoryGroupManager"/> class.  Provides nested operations over RepositoryManager instances.
 /// </summary>
 /// <param name="repository">The repository.</param>
 /// <param name="fileSystem"> </param>
 /// <example>Can be a direct path to a repository.config file</example>
 ///   
 /// <example>Can be a path to a directory, which will recursively locate all contained repository.config files</example>
 public RepositoryGroupManager(string repository, IFileSystem fileSystem)
 {
     Contract.Requires(fileSystem != null);
     this.fileSystem = fileSystem;
     
     if (fileSystem.DirectoryExists(repository))
     {
         // we're dealing with a directory
         //TODO Does this by default do a recursive???
         RepositoryManagers = new ConcurrentBag<RepositoryManager>(fileSystem.GetFiles(repository, "repositories.config", SearchOption.AllDirectories).Select(file => new RepositoryManager(file, new RepositoryEnumerator(fileSystem), fileSystem)).ToList());
     }
     else if (fileSystem.FileExists(repository) && Path.GetFileName(repository) == "repositories.config")
         RepositoryManagers = new ConcurrentBag<RepositoryManager>(new List<RepositoryManager> { new RepositoryManager(repository, new RepositoryEnumerator(fileSystem), fileSystem) });
     else
         throw new ArgumentOutOfRangeException("repository");
 }
Example #34
0
        private static async Task<CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(
                fileSystem.GetFiles("GeneratedCode", "*.cs", SearchOption.AllDirectories)
                    .Select(each => new KeyValuePair<string, string>(each, fileSystem.ReadFileAsText(each))).ToArray(),
                ManagedAssets.FrameworkAssemblies.Concat(
                    AppDomain.CurrentDomain.GetAssemblies()
                        .Where(each => !each.IsDynamic && !string.IsNullOrEmpty(each.Location))
                        .Select(each => each.Location)
                        .Concat(new[]
                        {
                            Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                "Microsoft.Rest.ClientRuntime.dll"),
                            Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                "Microsoft.Rest.ClientRuntime.Azure.dll")
                        })
                ));

            return await compiler.Compile(Microsoft.Rest.CSharp.Compiler.Compilation.OutputKind.DynamicallyLinkedLibrary);
        }
Example #35
0
        private static FileSystemMetadata GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
        {
            var folder = Path.GetDirectoryName(playlist);

            var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty;

            try
            {
                return fileSystem.GetFiles(folder)
                    .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase) && Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
                    .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
                    .FirstOrDefault();
            }
            catch (DirectoryNotFoundException)
            {
                return null;
            }
        }
Example #36
0
        public static Project FromFile(string input, IFileSystem fileSystem)
        {
            var jObject = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(input);
            var project = new Project();

            foreach (var entry in jObject)
            {
                var kindObj = entry.Key;
                string[] list;
                if (entry.Value is JArray)
                    list = entry.Value.ToObject<string[]>();
                else
                    list = new[] {entry.Value.ToObject<string>()};

                foreach (var item in list)
                {
                    var info = fileSystem.GetFileInfo(PathInfo.Create(item));
                    if (info == null)
                    {
                        var globPattern = GlobPattern.Create(item);
                        if (!globPattern.IsWildcard)
                            throw new InvalidProjectFileException($"Could not find file {item}.");

                        var items = fileSystem.GetFiles(globPattern);
                        foreach (var file in items)
                        {
                            var fileItem = new FileProjectItem(kindObj, file, fileSystem);
                            ProjectItem existing;
                            if (!project.TryGetItemById(fileItem.Identifier, out existing))
                                project.AddItem(fileItem);
                        }

                        project.AddSubscription(fileSystem.Subscribe(globPattern, a =>
                        {
                            HandleChange(a, project, kindObj, fileSystem);
                        }));
                    }
                    else
                    {
                        AddFile(fileSystem, project, kindObj, info, item);
                    }
                }
            }

            return project;
        }
Example #37
0
        private static List<FileSystemMetadata> GetLastTranscodingFiles(string playlist, string segmentExtension, IFileSystem fileSystem, int count)
        {
            var folder = Path.GetDirectoryName(playlist);

            try
            {
				return fileSystem.GetFiles(folder)
                    .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase))
                    .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
                    .Take(count)
                    .ToList();
            }
            catch (DirectoryNotFoundException)
            {
                return new List<FileSystemMetadata>();
            }
        }
Example #38
0
        /// <summary>
        /// Loads the machine wide settings.
        /// </summary>
        /// <remarks>
        /// For example, if <paramref name="paths"/> is {"IDE", "Version", "SKU" }, then
        /// the files loaded are (in the order that they are loaded):
        ///     %programdata%\NuGet\Config\IDE\Version\SKU\*.config
        ///     %programdata%\NuGet\Config\IDE\Version\*.config
        ///     %programdata%\NuGet\Config\IDE\*.config
        ///     %programdata%\NuGet\Config\*.config
        /// </remarks>
        /// <param name="fileSystem">The file system in which the settings files are read.</param>
        /// <param name="paths">The additional paths under which to look for settings files.</param>
        /// <returns>The list of settings read.</returns>
        public static IEnumerable<Settings> LoadMachineWideSettings(
            IFileSystem fileSystem,
            params string[] paths)
        {
            List<Settings> settingFiles = new List<Settings>();
            string basePath = @"NuGet\Config";
            string combinedPath = Path.Combine(paths);

            while (true)
            {
                string directory = Path.Combine(basePath, combinedPath);

                // load setting files in directory
                foreach (var file in fileSystem.GetFiles(directory, "*.config", recursive: false))
                {
                    var settings = ReadSettings(fileSystem, file, true);
                    if (settings != null)
                    {
                        settingFiles.Add(settings);
                    }
                }

                if (combinedPath.Length == 0)
                {
                    break;
                }

                int index = combinedPath.LastIndexOf(Path.DirectorySeparatorChar);
                if (index < 0)
                {
                    index = 0;
                }
                combinedPath = combinedPath.Substring(0, index);
            }

            return settingFiles;
        }
Example #39
0
        private void CopyNativeBinaries(IProjectSystem projectSystem, IFileSystem packagesFileSystem, PackageName packageName)
        {
            const string nativeBinariesFolder = "NativeBinaries";

            string nativeBinariesPath = Path.Combine(packageName.Name, nativeBinariesFolder);
            if (packagesFileSystem.DirectoryExists(nativeBinariesPath))
            {
                IEnumerable<string> nativeFiles = packagesFileSystem.GetFiles(nativeBinariesPath, "*.*", recursive: true);
                foreach (string file in nativeFiles)
                {
                    string targetPath = Path.Combine(Constants.BinDirectory, file.Substring(nativeBinariesPath.Length + 1));  // skip over NativeBinaries/ word
                    using (Stream stream = packagesFileSystem.OpenFile(file)) 
                    {
                        projectSystem.AddFile(targetPath, stream);
                    }
                }
            }
        }
Example #40
0
 private IEnumerable<string> SearchFilesWithinOneSubFolders(IFileSystem fileSystem, string folder, string extension)
 {
     // get files directly under 'folder' or files under subfolders of 'folder'
     return fileSystem.GetFiles(folder, extension)
                      .Concat(fileSystem.GetDirectories(folder).SelectMany(subFolder => fileSystem.GetFiles(subFolder, extension)));
 }
Example #41
0
        protected async Task<CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(
                fileSystem.GetFiles("GeneratedCode", "*.cs", SearchOption.AllDirectories)
                    .Select(each => new KeyValuePair<string, string>(each, fileSystem.ReadFileAsText(each))).ToArray(),
                ManagedAssets.FrameworkAssemblies.Concat(
                    AppDomain.CurrentDomain.GetAssemblies()
                        .Where(each => !each.IsDynamic && !string.IsNullOrEmpty(each.Location) )
                        .Select(each => each.Location)
                        .Concat(new[]
                        {
                            Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                "Microsoft.Rest.ClientRuntime.dll"),
                            Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                "Microsoft.Rest.ClientRuntime.Azure.dll")
                        })
                    ));
            var result = await compiler.Compile(OutputKind.DynamicallyLinkedLibrary);
            
            // if it failed compiling and we're in an interactive session
            if (!result.Succeeded && System.Environment.OSVersion.Platform == PlatformID.Win32NT && System.Environment.UserInteractive)
            {
                var error = result.Messages.FirstOrDefault(each => each.Severity == DiagnosticSeverity.Error);
                if (error != null)
                {
                    // use this to dump the files to disk for examination
                    // open in Favorite Code Editor
                    InspectWithFavoriteCodeEditor(fileSystem.SaveFilesToTemp(GetType().Name), error.Location.GetMappedLineSpan());
                }
            }

            return result;
        }