public void FindSolutionFolderAndNotSln()
        {
            var finder = new FileFinder(Environment.CurrentDirectory);

            var solutionFolder = finder.FindSolutionFolder();

            Assert.That(solutionFolder, !Contains.Substring(".sln"));
        }
Example #2
0
        public void TestIncludeSingleFile()
        {
        	IFile expected = new FileMock("OMNSetup.msi");
        	IFolder root = new FolderMock("root", new FolderMock("Bin", expected, new FileMock("OtherFile.ext")));
        	FileFinder finder = new FileFinder(root);
            
			Assert.AreEqual(expected, finder.FindAll(new InclusionPattern(@"Bin\OMNSetup.msi")).Single());
        }
Example #3
0
		public void TestIncludeMultipleFiles()
		{
			IFile[] files = new IFile[] { new FileMock("OMNSetup.msi"), new FileMock("OtherFile.ext") };
			IFolder root = new FolderMock("root", new FolderMock("Bin", files));
			FileFinder finder = new FileFinder(root);

			Assert.AreEqual(files, finder.FindAll(new InclusionPattern(@"Bin\*")).ToArray());
		}
        /// <summary>
        /// Instantiates a new instance of the <see cref="FileFinder"/> class with its <see cref="P:FileFinder.Paths"/> 
        /// collection filled with the <see cref="GlobalProbePaths"/> and <see cref="PrivateProbePaths"/> paths.
        /// </summary>
        /// <returns>Never returns null.</returns>
        public FileFinder CreateFileFinder()
        {
            FileFinder fileFinder = new FileFinder();
            fileFinder.Paths.AddRange(PrivateProbePaths);
            fileFinder.Paths.AddRange(GlobalProbePaths);

            return fileFinder;
        }
        public void FindSolutionFolder()
        {
            var finder = new FileFinder(Environment.CurrentDirectory);

            var solutionFolder = finder.FindSolutionFolder();

            Trace.WriteLine(solutionFolder);
            Assert.IsNotNull(solutionFolder);
        }
        public void FindProjectFiles()
        {
            var finder = new FileFinder(Environment.CurrentDirectory);

            var solutionFolder = finder.FindSolutionFolder();

            var packageFiles = finder.FindProjectFilesInSolution(solutionFolder);

            Assert.Greater(packageFiles.Count(), 0);
        }
        public void FindNuGetRepositoryInSolution()
        {
            var finder = new FileFinder(Environment.CurrentDirectory);

            var solutionFolder = finder.FindSolutionFolder();

            var repositoryFile = finder.FindNuGetRepositoryInSolution(solutionFolder);

            Assert.IsTrue(File.Exists(repositoryFile));
        }
Example #8
0
        public SoundManager(IntPtr Handle,IEnumerable<DirectoryInfo> DirSource)
        {
            //Core = new WaveOut(Handle);

            foreach (var iterate in DirSource)
            {

                FileFinder ff = new FileFinder(iterate.FullName, "*.ogg", (a)=>!a.Attributes.HasFlag(FileAttributes.Directory), (a) => LoadSound(a.FullPath), true);
                ff.Start();

            }
        }
Example #9
0
        public void IntegrationTestingAgainstLocalFolder()
        {
            //---------------Set up test pack-------------------
            var sut = new FileFinder();

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            sut.Find("C:\\code\\Chillisoft\\Mastery@Work", "package.json");

            //---------------Test Result -----------------------
            CollectionAssert.IsNotEmpty(sut.Paths);
        }
Example #10
0
        public Task<ExecutionResult> Execute(IReplWindow window, string arguments) {
            var finder = new FileFinder(arguments);

            var eval = window.Evaluator as BasePythonReplEvaluator;
            if (eval != null && eval.CurrentOptions != null) {
                finder.Search(eval.CurrentOptions.WorkingDirectory);
                finder.SearchAll(eval.CurrentOptions.SearchPaths, ';');
            }

            finder.ThrowIfNotFound();
#if DEV14_OR_LATER
            string commandPrefix = "$";
#else
            string commandPrefix = (string)window.GetOptionValue(ReplOptions.CommandPrefix);
#endif
            string lineBreak = window.TextView.Options.GetNewLineCharacter();

            IEnumerable<string> lines = File.ReadLines(finder.Filename);
            IEnumerable<string> submissions;

            if (eval != null) {
                submissions = eval.JoinCode(lines).Where(CommentPrefixPredicate);
            } else {
                // v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
                // and using this class it would be hit.
                var submissionList = new List<string>();
                var currentSubmission = new List<string>();

                foreach (var line in lines) {
                    if (line.StartsWith(_commentPrefix)) {
                        continue;
                    }

                    if (line.StartsWith(commandPrefix)) {
                        AddSubmission(submissionList, currentSubmission, lineBreak);

                        submissionList.Add(line);
                        currentSubmission.Clear();
                    } else {
                        currentSubmission.Add(line);
                    }
                }

                AddSubmission(submissionList, currentSubmission, lineBreak);

                submissions = submissionList;
            }

            window.Submit(submissions);
            return ExecutionResult.Succeeded;
        }
Example #11
0
        protected override void ProcessRecord()
        {
            System.IO.Directory.SetCurrentDirectory(this.SessionState.Path.CurrentLocation.Path);

            var includes = (Includes ?? new[] {Source.Directory}).Select(d => d.FullName);

            var fileFinder = new FileFinder(includes);

            Generator generator = new Generator(fileFinder, Namespace);

            string result = generator.Process(Source.FullName);

            WriteObject(result);
        }
Example #12
0
		public void SetUpFolderLayout()
		{
			root = CreateFolderBuilder()
				.EnterFolder("Bin")
					.AddFiles("OMNSetup.msi", "OtherFile.txt")
				.LeaveFolder()
				.EnterFolder("Doc")
					.EnterFolder("Api")
						.AddFiles("api.chm")
					.LeaveFolder()
				.LeaveFolder()
				.GetFolder();
			finder = new FileFinder(root);
		}
        public void Gather_GivenNoFolders_ShouldDoNothing()
        {
            //---------------Set up test pack-------------------
            var sut = Create();
            var finder = new FileFinder();
            //---------------Assert Precondition----------------
            CollectionAssert.IsEmpty(finder.Paths);

            //---------------Execute Test ----------------------
            sut.Gather(finder);

            //---------------Test Result -----------------------
            CollectionAssert.IsEmpty(sut.Scores);
        }
Example #14
0
        public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) {
            var finder = new FileFinder(arguments);

            var eval = window.GetPythonEvaluator();
            if (eval != null) {
                finder.Search(eval.Configuration.WorkingDirectory);
                foreach (var p in eval.Configuration.SearchPaths) {
                    finder.Search(p);
                }
            }

            finder.ThrowIfNotFound();
            string commandPrefix = "$";
            string lineBreak = window.TextView.Options.GetNewLineCharacter();

            IEnumerable<string> lines = File.ReadLines(finder.Filename);
            IEnumerable<string> submissions;

            if (eval != null) {
                submissions = ReplEditFilter.JoinToCompleteStatements(lines, eval.LanguageVersion).Where(CommentPrefixPredicate);
            } else {
                // v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
                // and using this class it would be hit.
                var submissionList = new List<string>();
                var currentSubmission = new List<string>();

                foreach (var line in lines) {
                    if (line.StartsWith(_commentPrefix)) {
                        continue;
                    }

                    if (line.StartsWith(commandPrefix)) {
                        AddSubmission(submissionList, currentSubmission, lineBreak);

                        submissionList.Add(line);
                        currentSubmission.Clear();
                    } else {
                        currentSubmission.Add(line);
                    }
                }

                AddSubmission(submissionList, currentSubmission, lineBreak);

                submissions = submissionList;
            }

            window.SubmitAsync(submissions);
            return ExecutionResult.Succeeded;
        }
        public void IntegrationTestingAgainstLocalFileSystem()
        {
            //---------------Set up test pack-------------------
            var nugetFinder = new FileFinder();
            nugetFinder.Find("C:\\code\\SPAR\\Liquor", "packages.config");

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var scorer = new NugetScorer();
            scorer.Gather(nugetFinder);

            //---------------Test Result -----------------------
            CollectionAssert.IsNotEmpty(scorer.Scores);
        }
        /// <summary>
        /// Gets a FileInfo on the Master Sample Submission Excel file from James
        /// </summary>
        /// <returns>FileInfo - on the file</returns>
        public static FileInfo GetFileInfoForMasterSampleSubmissionFile()
        {

            FileInfo master = null;
            FileFinder masterlocater = new FileFinder();
            masterlocater._basefolder = SampleSubmissionMasterStartingPath;
            string sampleSubmissionMasterFilename;
            sampleSubmissionMasterFilename =
                masterlocater.FindByPartialFilename(SampleSubmissionMasterPartialFilename).FirstOrDefault();
            if (sampleSubmissionMasterFilename != null)
            {
                master = new FileInfo(sampleSubmissionMasterFilename);
            }
            else
            {
                throw new FileNotFoundException(string.Format("Cannot find the master Sample Submission Excel file in {0}",
                    SampleSubmissionMasterStartingPath));
            }
            return master;
        }
        public static async ValueTask InitializeAsync(
            this FileToken token,
            Options options,
            string destination = null)
        {
            if (token.FileType == FileType.Markdown ||
                token.FileType == FileType.Yaml)
            {
                var found = await FileTokenCacheUtility.TryFindCachedVersionAsync(token, options, destination);

                if (!found)
                {
                    var lines = await File.ReadAllLinesAsync(token.FilePath);

                    var dir  = token.DirectoryName;
                    var type = token.FileType;

                    if (type == FileType.Markdown && Metadata.TryParse(lines, out var metadata))
                    {
                        token.Header = metadata;
                    }

                    foreach (var(tokenType, tokenValue, lineNumber) in
                             lines.SelectMany((line, lineNumber) => FindAllTokensInLine(line, lineNumber + 1, TokenExpressions.FileTypeToExpressionMap[type]))
                             .Where(tuple => !string.IsNullOrEmpty(tuple.Item2)))
                    {
                        if (tokenType == TokenType.CodeFence)
                        {
                            token.CodeFenceSlugs[lineNumber] = tokenValue;
                            continue;
                        }

                        if (tokenType == TokenType.Xref)
                        {
                            token.Xrefs.Add(tokenValue);
                            continue;
                        }

                        if (tokenType == TokenType.Unrecognizable)
                        {
                            continue;
                        }

                        var(isFound, fullPath) = await FileFinder.TryFindFileAsync(options, dir, tokenValue);

                        if (isFound && !string.IsNullOrWhiteSpace(fullPath))
                        {
                            var file = new FileInfo(fullPath.NormalizePathDelimitors());
                            switch (file.GetFileType())
                            {
                            case FileType.Image:
                                token.ImagesReferenced.Add(file.FullName);
                                break;

                            case FileType.Markdown:
                                token.TopicsReferenced.Add(file.FullName);
                                break;
                            }
                        }
                    }

                    await FileTokenCacheUtility.CacheTokenAsync(token, options, destination);
                }
            }
        }
Example #18
0
        void Init()
        {
            FileFinderSettings settingsManager = null;

            menuState = new AutoConfigurableMenuState();
            {
                //menuState.AddMenuItem(new MenuItem() { Text = "Create DB" }, () => {
                //	//Вроде і без цього робить
                //	//if(!System.IO.File.Exists(dbName))
                //	//SQLiteConnection.CreateFile(dbName);

                //	//DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SQLite");

                //	//DbConnection connection = factory.CreateConnection();
                //	//connection.ConnectionString = connectionString;
                //	//connection.Open();

                //	//DbDataAdapter dataAdapter = factory.CreateDataAdapter();
                //	//dataAdapter.SelectCommand = factory.CreateCommand();
                //	//dataAdapter.SelectCommand.Connection = connection;
                //	//dataAdapter.SelectCommand.CommandText = "select * from file";

                //	//DataSet dataSet = new DataSet("files");
                //	//dataAdapter.Fill(dataSet, "files");


                //	//DataTable table = new DataTable("file");
                //	//DataColumn column = new DataColumn("IdFile", typeof(int)) {
                //	//	AllowDBNull = false,
                //	//	ReadOnly = false,
                //	//	Unique = true,
                //	//	AutoIncrement = true,
                //	//	AutoIncrementSeed = 1,
                //	//	AutoIncrementStep = 1,
                //	//	Caption = "Id file",
                //	//};
                //	//table.Columns.Add(column);

                //	//column = new DataColumn("PathToFile", typeof(string)) {
                //	//	AllowDBNull = false,
                //	//	ReadOnly = false,
                //	//	Caption = "Path to file",
                //	//};
                //	//table.Columns.Add(column);

                //	//column = new DataColumn("FileSize", typeof(ulong)) {
                //	//	AllowDBNull = false,
                //	//	ReadOnly = false,
                //	//	Caption = "File size",
                //	//};
                //	//table.Columns.Add(column);

                //	//dataSet.Tables.Add(table);

                //	//DataRow row = table.NewRow();
                //	//row[1] = "test\\test.jpg";
                //	//row[2] = 666;
                //	//dataSet.Tables[0].Rows.Add(row);
                //	//dataSet.AcceptChanges();

                //	//foreach(DataTable t in dataSet.Tables) {
                //	//	Console.WriteLine($" => {t.TableName}");
                //	//	foreach(DataRow r in t.Rows) {
                //	//		Console.WriteLine($"{r[0]}\t{r[1]}\t{r[2]}");
                //	//	}
                //	//}


                //	////Треба для БД які представлені 1 файлом. Наприклад SQLite
                //	//if(factory is IDisposable disposable)
                //	//	disposable.Dispose();



                //	DataSet dataSet = new DataSet();
                //	dataSet.ReadXml(@".\files.xml");

                //	foreach(DataTable t in dataSet.Tables) {
                //		Console.WriteLine($" => {t.TableName}");
                //		foreach(DataRow r in t.Rows) {
                //			Console.WriteLine($"{r[0]}\t{r[1]}");
                //		}
                //	}

                //	return menuState;
                //});
            }

            menuState.AddMenuItem(new MenuItem()
            {
                Text = "Parse, create and fill DB"
            }, () => {
                FileFinderSettings settings = new FileFinderSettings();
                settings.ReadFromXml(@".\settings.xml");
                FileFinder fileFinder = new FileFinder(settings);

                new MenuItem()
                {
                    Text = "Start file parsing.\n", TextColor = attentionColor
                }.Print();
                fileFinder.Find();
                new MenuItem()
                {
                    Text = "End file parsing.\n", TextColor = attentionColor
                }.Print();

                new MenuItem()
                {
                    Text = "Start saving as DB.\n", TextColor = attentionColor
                }.Print();
                {
                    EzDBAccess.EzDBList <DBFileInfo> tmpList = new EzDBAccess.EzDBList <DBFileInfo>("System.Data.SqlClient", @"Server=(localdb)\mssqllocaldb; Database=master; Integrated Security=True", true);
                }
                //fileFinder.SaveAsXml(@".\files.xml");

                DataSet dataSet = new DataSet();
                //dataSet.ReadXml(@".\files.xml");

                using (SqlConnection connection = new SqlConnection(connectionString)) {
                    connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter("select * from DBFileInfo", connection);
                    adapter.Fill(dataSet);
                    foreach (var i in fileFinder.Files)
                    {
                        DataRow row = dataSet.Tables[0].NewRow();
                        row[1]      = i.FullName;
                        row[2]      = i.Length;
                        dataSet.Tables[0].Rows.Add(row);
                    }
                    SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
                    adapter.Update(dataSet);
                    //dataSet.AcceptChanges();
                    //dataSet.Clear();
                    //adapter.Fill(dataSet);

                    adapter.Dispose();
                }

                new MenuItem()
                {
                    Text = "End saving as DB.\n", TextColor = attentionColor
                }.Print();


                dataSet.Dispose();

                return(menuState);
            });

            menuState.AddMenuItem(new MenuItem()
            {
                Text = "Print files"
            }, () => {
                //dataSet.ReadXml(@".\files.xml");
                try {
                    using (SqlConnection connection = new SqlConnection(connectionString)) {
                        connection.Open();
                        SqlDataAdapter adapter = new SqlDataAdapter("select * from DBFileInfo", connection);
                        DataSet dataSet        = new DataSet();
                        adapter.Fill(dataSet);
                        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);

                        int[] columnWidths = new int[] { 7, 50, 10 };
                        foreach (DataTable t in dataSet.Tables)
                        {
                            Console.WriteLine($" => {t.TableName}");
                            for (byte i = 0; i < t.Columns.Count; ++i)
                            {
                                string str = t.Columns[i].ToString();
                                if (str.Length > columnWidths[i])
                                {
                                    str = str.Substring(0, columnWidths[i] - 3) + "...";
                                }
                                str  = str.PadRight(columnWidths[i]);
                                str += ' ';
                                Console.Write(str);
                            }
                            Console.WriteLine();

                            foreach (DataRow r in t.Rows)
                            {
                                for (byte i = 0; i < t.Columns.Count; ++i)
                                {
                                    string str = r[i].ToString();
                                    if (str.Length > columnWidths[i])
                                    {
                                        str = str.Substring(0, columnWidths[i] - 3) + "...";
                                    }
                                    str  = str.PadRight(columnWidths[i]);
                                    str += ' ';
                                    Console.Write(str);
                                }
                                Console.WriteLine();
                            }
                        }

                        commandBuilder.Dispose();
                        dataSet.Dispose();
                        adapter.Dispose();
                    }
                }
                catch (Exception ex) {
                    new MenuItem()
                    {
                        Text = "Cant read from DB. Choose ", PreText = "Error: ", PreTextColor = ConsoleColor.Red
                    }.Print();
                    new MenuItem()
                    {
                        Text = "Parse, create and fill DB ", TextColor = ConsoleColor.Blue
                    }.Print();
                    new MenuItem()
                    {
                        Text = "before print files\n"
                    }.Print();
                }

                return(menuState);
            });

            menuState.AddMenuItem(new MenuItem()
            {
                Text = "Settings file finder"
            }, () => {
                settingsManager = new FileFinderSettings();
                settingsManager.ReadFromXml(@".\settings.xml");
                return(settingsState);
            });


            menuState.AddMenuItem(new MenuItem()
            {
                Text = "Exit"
            }, () => null);

            settingsState = new AutoConfigurableMenuState();

            settingsState.AddMenuItem(new MenuItem()
            {
                Text = "Set max path length", InBrakesText = "Щоб шукати не у всiй системi.", InBrakesTextColor = attentionColor
            }, () => {
                ushort rez = ushort.MaxValue;
                do
                {
                    if (rez == 0)
                    {
                        new MenuItem()
                        {
                            Text = "Cant parse number\n", PreText = "Error: ", PreTextColor = ConsoleColor.Red
                        }
                    }
                    .Print();
                    Console.Write("New length: ");
                } while(!ushort.TryParse(Console.ReadLine(), out rez));
Example #19
0
        /// <summary>
        /// Creates a stuklijst. Once the stuklijst has been created it can be accessed from the Stuklijst property.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public bool Create(string file)
        {
            serienummerLijst = new SerienummerLijst();
            List <string> lines = new List <string>();

            try
            {
                //csv bestand inlezen
                using (StreamReader rdr = new StreamReader(file))
                {
                    while (!rdr.EndOfStream)
                    {
                        lines.Add(rdr.ReadLine().Replace("\"", string.Empty));
                    }
                }

                //lineseparator bepalen
                separator = DetermineSeparator(lines[0]);

                //product bepalen
                string[] cells = lines[rijProduct].Split(separator.Value);
                serienummerLijst.Product = cells[kolomProduct].Replace("\"", string.Empty);

                //logo bepalen
                string cell = lines[logoRow].Split(separator.Value)[logoTitleColumn];
                if (cell.ToLower() == "logo")
                {
                    serienummerLijst.LogoImage = lines[logoRow].Split(separator.Value)[logovalueColumn];
                }

                //bepalen of het CE logo afgedrukt moet worden
                cell = lines[ceMarkRow].Split(separator.Value)[cemarkTitleColumn];
                if (cell.ToLower() == "ce-mark")
                {
                    serienummerLijst.PrintCeLogo = lines[ceMarkRow].Split(separator.Value)[cemarkValueColumn].ToLower() == "yes";
                }
                else
                {
                    serienummerLijst.PrintCeLogo = true;
                }

                BepaalItems(lines);


                //labels bepalen
                for (int lineNumber = dataStartReadRow; lineNumber < lines.Count; lineNumber++)
                {
                    string line = lines[lineNumber];
                    if (LineIsEmpty(line))
                    {
                        break;
                    }
                    //de artikelen lezen
                    cells = line.Split(separator.Value);
                    string jaar       = cells[kolomJaar].Replace("\"", string.Empty);
                    string batch      = cells[kolomBatch].Replace("\"", string.Empty);
                    string volgNummer = cells[kolomVolgnummer].Replace("\"", string.Empty);

                    string item1 = cells[item1Column].Replace("\"", string.Empty);
                    string item2 = cells[item2Column].Replace("\"", string.Empty);
                    string item3 = cells[item3Column].Replace("\"", string.Empty);
                    string item4 = cells[item4Column].Replace("\"", string.Empty);

                    serienummerLijst.AddSerienummer(jaar, batch, volgNummer, item1, item2, item3, item4);
                }

                FileFinder finder = new FileFinder();
                finder.Find(serienummerLijst.LogoImage);
            }
            catch (IOException ex)
            {
                Message = ex.Message;
                return(false);
            }

            return(true);
        }
Example #20
0
        public async Task CanReadCsvFile()
        {
            // Arrange
            normalizer.Path = FileFinder.FindCsv("monolithic.csv");

            // Act
            var rows = await normalizer.RunAsync();

            // Assert
            rows.Should().HaveCount(4);

            // Element name
            rows[0].ElementName.Should().Be("element1");
            rows[1].ElementName.Should().Be("element1");
            rows[2].ElementName.Should().Be("element1");
            rows[3].ElementName.Should().Be("element2");

            // Attribute name
            rows[0].AttributeName.Should().BeNullOrEmpty();
            rows[1].AttributeName.Should().Be("kind");
            rows[2].AttributeName.Should().BeNullOrEmpty();
            rows[3].AttributeName.Should().BeNullOrEmpty();

            // Child element name
            rows[0].ChildElementName.Should().BeNullOrEmpty();
            rows[1].ChildElementName.Should().BeNullOrEmpty();
            rows[2].ChildElementName.Should().Be("name");
            rows[3].ChildElementName.Should().BeNullOrEmpty();

            // Data type
            rows[0].DataType.Should().BeNullOrEmpty();
            rows[1].DataType.Should().Be("string");
            rows[2].DataType.Should().Be("int");
            rows[3].DataType.Should().BeNullOrEmpty();

            // Max length
            rows[0].MaxLength.Should().BeNullOrEmpty();
            rows[1].MaxLength.Should().Be("13");
            rows[2].MaxLength.Should().Be("2");
            rows[3].MaxLength.Should().BeNullOrEmpty();

            // Required
            rows[0].Required.Should().BeNullOrEmpty();
            rows[1].Required.Should().Be("required");
            rows[2].Required.Should().Be("optional");
            rows[3].Required.Should().BeNullOrEmpty();

            // Min occurences
            rows[0].MinOccurs.Should().BeNullOrEmpty();
            rows[1].MinOccurs.Should().BeNullOrEmpty();
            rows[2].MinOccurs.Should().Be("1");
            rows[3].MinOccurs.Should().BeNullOrEmpty();

            // Max occurences
            rows[0].MaxOccurs.Should().BeNullOrEmpty();
            rows[1].MaxOccurs.Should().BeNullOrEmpty();
            rows[2].MaxOccurs.Should().Be("unbounded");
            rows[3].MaxOccurs.Should().BeNullOrEmpty();

            // Enum values
            rows[0].EnumValues.Should().BeNullOrEmpty();
            rows[1].EnumValues.Should().BeNullOrEmpty();
            rows[2].EnumValues.Should().Be("A|B");
            rows[3].EnumValues.Should().BeNullOrEmpty();

            // Comment
            rows[0].Comment.Should().Be("the first entity");
            rows[1].Comment.Should().Be("the kind of thing");
            rows[2].Comment.Should().BeNullOrEmpty();
            rows[3].Comment.Should().Be("the second entity");
        }
Example #21
0
 public JsonConfigAdapter(FileFinder fileFinder) : base(fileFinder)
 {
 }
Example #22
0
 public override void Load()
 {
     texture = LoadTexture(FileFinder.ResourcePath(Filepath));
     Image   = new Sprite(texture);
     RefreshOrigin(Image, Origin, CustomOrigin);
 }
 /// <summary>
 /// Gets a FileInfo for a file being searched for
 /// </summary>
 /// <param name="filename">string - the file name</param>
 /// <param name="startingfolder">string - the starting folder for the search</param>
 /// <returns></returns>
 public static FileInfo UseFileFinderToGetFileInfo(string filename, string startingfolder)
 {
     FileFinder ff = new FileFinder { _basefolder = startingfolder };
     IQueryable<string> file = ff.FindFileByName(filename);
     string sourceFileName = file.FirstOrDefault();
     if (sourceFileName == null)
         throw new FileNotFoundException(string.Format("Unable to find {0} in the Fermentation folder on James",
             filename));
     FileInfo info = new FileInfo(sourceFileName);
     return info;
 }
Example #24
0
 public FileReader()
 {
     _sshConn    = new SSHConnection();
     _fileFinder = new FileFinder();
     _fileFinder.ListFiles();
 }
        static void Main(string[] args)
        {
            bool   showHelp      = false;
            string targetPath    = "";
            string symlinkPath   = "";
            string searchPattern = "";

            var p = new OptionSet {
                {
                    "h|help",
                    "Show this message and exit.",
                    v => showHelp = v != null
                },
                {
                    "t|target=",
                    "The {PATH} to the files symlinks will refer to.",
                    v => targetPath = v
                },
                {
                    "d|destination=",
                    "The {PATH} to the files symlinks will be created for.",
                    v => symlinkPath = v
                },
                {
                    "s|searchPattern=",
                    "Pipe (|) delimited list of search patterns used to find files. Each pattern is passed directly to Directory.GetFiles so see docs for that.",
                    v => searchPattern = v
                }
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);

                if (showHelp)
                {
                    p.WriteOptionDescriptions(Console.Out);
                    return;
                }

                ValidatePaths(targetPath, symlinkPath);

                if (string.IsNullOrWhiteSpace(searchPattern))
                {
                    searchPattern = "";
                }

                Console.WriteLine("Starting...");
                Console.WriteLine("Finding files in target directory...");

                var targetFinder = new FileFinder(targetPath, searchPattern);
                targetFinder.Find();

                Console.WriteLine("{0} files found in target directory.", targetFinder.Files.Count);
                Console.WriteLine("Finding files in destination directory...");

                var destinationFinder = new FileFinder(symlinkPath, searchPattern);
                destinationFinder.Find();

                Console.WriteLine("{0} files found in destination directory.", destinationFinder.Files.Count);
                Console.WriteLine("Finding matching files. This can take some time...");

                var matchFinder = new MatchFinder(targetFinder, destinationFinder);
                matchFinder.Find();

                int matchCount = matchFinder.Matches.Count;

                Console.WriteLine("{0} matching files found.", matchCount);

                if (matchCount > 0)
                {
                    Console.WriteLine("Making symbolic links...");

                    Parallel.ForEach(
                        matchFinder.Matches,
                        match =>
                    {
                        Console.WriteLine("Linking to " + ShortenPath(match.TargetPath));

                        var linker = new FileMatchSymlinker(match);
                        linker.Create();
                    });
                }

                Console.WriteLine("Done. Exiting.");
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `--help' for more information.");
            }

            if (Debugger.IsAttached)
            {
                Console.WriteLine("Click any key to exit.");
                Console.ReadKey();
            }
        }
Example #26
0
 public FilePath(string basePath, string fullPath, FileFinder fileFinder)
 {
     BasePath   = basePath;
     FullPath   = fullPath;
     FileFinder = fileFinder;
 }
Example #27
0
        private void ProcessFile([NotNull] FileInfo droppedFile)
        {
            if ((droppedFile.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
            {
                Logger.Error($"{droppedFile.FullName} is a directory, ignoring.");
                return;
            }

            if (!droppedFile.IsMovieFile())
            {
                Logger.Info($"{droppedFile.FullName} is not a movie file, ignoring.");
                return;
            }

            ShowItem bestShow = cbShowList.SelectedItem == "<Auto>"
                ? FinderHelper.FindBestMatchingShow(droppedFile, mDoc.Library.Shows)
                : mDoc.Library.Shows.FirstOrDefault(item => item.ShowName == cbShowList.SelectedItem);

            if (bestShow is null)
            {
                if (TVSettings.Instance.AutoAddAsPartOfQuickRename)
                {
                    List <ShowItem> addedShows = FinderHelper.FindShows(new List <string> {
                        droppedFile.Name
                    }, mDoc);
                    bestShow = addedShows.FirstOrDefault();
                }

                if (bestShow is null)
                {
                    Logger.Info($"Cannot find show for {droppedFile.FullName}, ignoring this file.");
                    return;
                }
            }

            if (!FinderHelper.FindSeasEp(droppedFile, out int seasonNum, out int episodeNum, out int _, bestShow,
                                         out TVSettings.FilenameProcessorRE _))
            {
                Logger.Info($"Cannot find episode for {bestShow.ShowName} for {droppedFile.FullName}, ignoring this file.");
                return;
            }

            SeriesInfo s = bestShow.TheSeries();

            if (s is null)
            {
                //We have not downloaded the series, so have to assume that we need the episode/file
                Logger.Info(
                    $"Can't rename file for {bestShow.ShowName} for {droppedFile.FullName}, as it has not been downloaded yet, ignoring this file.");

                return;
            }

            try
            {
                Episode          ep      = s.GetEpisode(seasonNum, episodeNum, bestShow.DvdOrder);
                ProcessedEpisode episode = new ProcessedEpisode(ep, bestShow);

                string filename = TVSettings.Instance.FilenameFriendly(
                    TVSettings.Instance.NamingStyle.NameFor(episode, droppedFile.Extension,
                                                            droppedFile.DirectoryName.Length));

                FileInfo targetFile =
                    new FileInfo(droppedFile.DirectoryName + Path.DirectorySeparatorChar + filename);

                if (droppedFile.FullName == targetFile.FullName)
                {
                    Logger.Info(
                        $"Can't rename file for {bestShow.ShowName} for {droppedFile.FullName}, as it already has the appropriate name.");

                    return;
                }

                mDoc.TheActionList.Add(new ActionCopyMoveRename(droppedFile, targetFile, episode));

                // if we're copying/moving a file across, we might also want to make a thumbnail or NFO for it
                mDoc.TheActionList.AddRange(new DownloadIdentifiersController().ProcessEpisode(episode, targetFile));

                //If keep together is active then we may want to copy over related files too
                if (TVSettings.Instance.KeepTogether)
                {
                    FileFinder.KeepTogether(mDoc.TheActionList, false, true);
                }
            }
            catch (SeriesInfo.EpisodeNotFoundException)
            {
                Logger.Info(
                    $"Can't rename file for {bestShow.ShowName} for {droppedFile.FullName}, as it does not have Episode {episodeNum} for Season {seasonNum}.");
            }
        }
Example #28
0
 //[SetUp]
 public void SetUp()
 {
     _selenium =
         new SeleniumAdapter(new ChromeDriver(Path.GetDirectoryName(FileFinder.Find("chromedriver.exe")),
                                              new ChromeOptions()));
 }
Example #29
0
        public PcbGamePatch buildPcbGamePatch()
        {
            //target game 목록 생성
            List <TargetGame> targetGames = TargetGameFactory.buildAllGames();

            //target game의 exefile들을 검색하여 위치 파악
            List <string> exeFiles = new List <string>();
            List <string> verFiles = new List <string>();

            foreach (TargetGame aGame in targetGames)
            {
                exeFiles.Add(aGame.Exefile);
                if (aGame.IsVerFileOtherPath)
                {
                    verFiles.Add(aGame.VersionFile);
                }
            }

            FileFinder    finder     = new FileFinder("*.exe", exeFiles);
            List <string> foundFiles = finder.findFilePath();

            finder = new FileFinder("*.upf", verFiles);
            List <string> foundVerFiles = finder.findFilePath();

            //            Dictionary<string, string> foundExeFileMap = TargetGameFactory.buildFoundExeFileMap(foundFiles, targetGames);
            targetGames = TargetGameFactory.matchFoundExeFileAndVerFile(foundFiles, foundVerFiles, targetGames);

            //target game 별로 version 체크
            PcbGamePatch pcbGamePatch = new PcbGamePatch();

            pcbGamePatch.pcbGames = new List <PcbGame>();

            foreach (TargetGame aGame in targetGames)
            {
                //exefile 존재 여부 체크
                string exeFilePath = aGame.ExeFilePath;
                if (exeFilePath == null)
                {
                    Console.WriteLine("[buildPcbGamePatch] exeFile is not found! gsn:{0}, exefile:{1}", aGame.Gsn, aGame.Exefile);
                    continue;
                }

                //version file 여부 체크
                if (aGame.VersionFile == null)
                {
                    //설치여부만 체크
                    pcbGamePatch.pcbGames.Add(new PcbGame(aGame.Gsn, aGame.Exefile, "N/A", VersionChecker.checkLastWriteTime(exeFilePath)));
                }
                else
                {
                    //string versionFilePath = FileFinder.findOneFilePath(gameInstallPath, aGame.VersionFile);

                    if (aGame.VerionFilePath == null)
                    {
                        continue;
                    }

                    //Console.WriteLine("[buildPcbGamePatch] versionFilePath:{0}", aGame.VerionFilePath);

                    //버전파일 체크
                    switch (aGame.VersionFileFormat)
                    {
                    case Fileformat.XML:
                        pcbGamePatch.pcbGames.Add(new PcbGame(aGame.Gsn, aGame.Exefile, VersionChecker.checkXmlFile(aGame.VerionFilePath), VersionChecker.checkLastWriteTime(exeFilePath)));
                        break;

                    case Fileformat.JSON:
                        pcbGamePatch.pcbGames.Add(new PcbGame(aGame.Gsn, aGame.Exefile, VersionChecker.checkJsonFile(aGame.VerionFilePath), VersionChecker.checkLastWriteTime(exeFilePath)));
                        break;

                    case Fileformat.BIN:
                        pcbGamePatch.pcbGames.Add(new PcbGame(aGame.Gsn, aGame.Exefile, VersionChecker.checkLastWriteTime(aGame.VerionFilePath), VersionChecker.checkLastWriteTime(exeFilePath)));
                        break;

                    default:
                        //no process
                        Console.WriteLine("[buildPcbGamePatch] not supprot version formant:{0}", aGame.VersionFileFormat);
                        break;
                    }
                }
            }

            //set agent version
            pcbGamePatch.version = PcbAgent.AGENT_VERSION;

            return(pcbGamePatch);
        }
 /// <summary>
 /// Metoda wyszukuj¹ca wskazany plik graficzny i zwracaj¹ca jego
 /// zawartoœæ. Metoda szuka wszystkich obrazów w podkatalogu images
 /// katalogu, w którym znajduje siê ta jednostka kompilacji.
 /// </summary>
 /// <param name="imageName">nazwa pliku graficznego</param>
 /// <returns>obraz</returns>
 public static Image GetImage(String imageName)
 {
     return(Image.FromFile(FileFinder.GetFileName("images", imageName)));
 }
Example #31
0
        private void ProcessFile([NotNull] FileInfo droppedFile, IDialogParent owner)
        {
            if ((droppedFile.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
            {
                Logger.Error($"{droppedFile.FullName} is a directory, ignoring.");
                return;
            }

            if (!droppedFile.IsMovieFile())
            {
                Logger.Info($"{droppedFile.FullName} is not a movie file, ignoring.");
                return;
            }

            // Note that the extension of the file may not be fi.extension as users can put ".mkv.t" for example as an extension
            string otherExtension = TVSettings.Instance.FileHasUsefulExtensionDetails(droppedFile, true);

            ShowConfiguration?bestShow = (string)cbShowList.SelectedItem == "<Auto>"
                ? FinderHelper.FindBestMatchingShow(droppedFile.FullName, mDoc.TvLibrary.Shows)
                : mDoc.TvLibrary.Shows.FirstOrDefault(item => item.ShowName == (string)cbShowList.SelectedItem);

            if (bestShow is null)
            {
                if (TVSettings.Instance.AutoAddAsPartOfQuickRename)
                {
                    List <MediaConfiguration> addedShows = FinderHelper.FindMedia(new List <FileInfo> {
                        droppedFile
                    }, mDoc, owner);
                    bestShow = addedShows.OfType <ShowConfiguration>().FirstOrDefault();

                    if (bestShow != null)
                    {
                        mDoc.Add(bestShow);
                        mDoc.TvAddedOrEdited(true, false, false, parent, bestShow);

                        Logger.Info($"Added new show called: {bestShow.ShowName}");
                    }
                }

                if (bestShow is null)
                {
                    Logger.Info($"Cannot find show for {droppedFile.FullName}, ignoring this file.");
                    return;
                }
            }

            if (!FinderHelper.FindSeasEp(droppedFile, out int seasonNum, out int episodeNum, out int _, bestShow,
                                         out TVSettings.FilenameProcessorRE _))
            {
                Logger.Info($"Cannot find episode for {bestShow.ShowName} for {droppedFile.FullName}, ignoring this file.");
                return;
            }

            try
            {
                ProcessedEpisode episode = bestShow.GetEpisode(seasonNum, episodeNum);

                string filename = TVSettings.Instance.FilenameFriendly(
                    TVSettings.Instance.NamingStyle.NameFor(episode, otherExtension,
                                                            droppedFile.DirectoryName.Length));

                FileInfo targetFile =
                    new FileInfo(droppedFile.DirectoryName.EnsureEndsWithSeparator() + filename);

                if (droppedFile.FullName == targetFile.FullName)
                {
                    Logger.Info(
                        $"Can't rename file for {bestShow.ShowName} for {droppedFile.FullName}, as it already has the appropriate name.");

                    return;
                }

                mDoc.TheActionList.Add(new ActionCopyMoveRename(droppedFile, targetFile, episode, mDoc));

                // if we're copying/moving a file across, we might also want to make a thumbnail or NFO for it
                mDoc.TheActionList.AddNullableRange(new DownloadIdentifiersController().ProcessEpisode(episode, targetFile));

                //If keep together is active then we may want to copy over related files too
                if (TVSettings.Instance.KeepTogether)
                {
                    FileFinder.KeepTogether(mDoc.TheActionList, false, true, mDoc);
                }
            }
            catch (ShowConfiguration.EpisodeNotFoundException)
            {
                Logger.Info(
                    $"Can't rename file for {bestShow.ShowName} for {droppedFile.FullName}, as it does not have Episode {episodeNum} for Season {seasonNum}.");
            }
        }
Example #32
0
    //TODO: wrap all the file creation/access parts in try-catches
    bool StageMod(string modpath, string modname)
    {
        if (!File.Exists(modpath))
        {
            return(false);
        }

        string extractTo   = TempExtractionFolderPath;
        string zipfilePath = modpath;

        if (!Directory.Exists(extractTo))
        {
            Directory.CreateDirectory(extractTo);
        }

        bool abort = false;

        try
        {
            Debug.Log("Source zip file: " + zipfilePath);
            Debug.Log("Printing unzipped files");

            ZipFile zip = new ZipFile(File.OpenRead(zipfilePath));
            foreach (ZipEntry e in zip)
            {
                Debug.Log(e.Name);
                byte[] buffer      = new byte[4096];
                Stream zipStream   = zip.GetInputStream(e);
                String fullZipPath = Path.Combine(extractTo, e.Name);
                Debug.Log(fullZipPath + " is your full path");
                if (!e.IsFile)
                {
                    Directory.CreateDirectory(fullZipPath);
                    continue;
                }
                using (FileStream streamWriter = File.Create(fullZipPath)) {
                    StreamUtils.Copy(zipStream, streamWriter, buffer);
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Error extracting mod: " + e.Message);
            System.Windows.Forms.MessageBox.Show("Error extracting mod from " + zipfilePath + " to " + extractTo + " --- Error: " + e.Message);
            abort = true;
        }

        if (abort)
        {
            return(false);
        }

        Debug.Log("Searching for dlls in " + extractTo);
        List <string> dllFiles = FileFinder.FindFiles(extractTo, "dll", true);

        //NOTE: May need to revisit this for mods that have no dll files, if any ever exist
        if (dllFiles.Count < 1)
        {
            Debug.LogError("No dlls found in mod!");
            System.Windows.Forms.MessageBox.Show("No dlls found in mod!");
            return(false);
        }

        stagedPaths[modname] = new List <string>();

        //create a staged path using each dll
        foreach (string dllFile in dllFiles)
        {
            Debug.Log("Mod dll found at: " + dllFile);

            //Parse the path to get the root of the dll
            int startIndex = dllFile.IndexOf("Temp") + "Temp".Length;
            int length     = dllFile.IndexOf('\\', startIndex + 1) - startIndex;

            string localModPath = "";

            Debug.Log("dll path parsing: startIndex = " + startIndex);

            if (length < 0)
            {
                length = 0;
            }
            else
            {
                Debug.Log("dll path parsing: length = " + length);

                localModPath = dllFile.Substring(startIndex, length);
            }

            if (localModPath.TrimEnd('/').Contains("hollow_knight_Data"))
            {
                //for some reason, the root folder of lightbringer is never "extracted" so see if we can kinda cheat here
                stagedPaths[modname].Add(extractTo + "/");
            }
            else
            {
                stagedPaths[modname].Add(extractTo + localModPath + "/");
            }

            Debug.Log("Root folder for dll: " + localModPath);
        }

        Debug.Log("Decompressed and staged " + modname);

        return(true);
    }
Example #33
0
        public static void LoadUserSettings()
        {
            UserData = new Preferences();
            string dataFilePath = GetDataFilePath();

            if (File.Exists(dataFilePath))
            {
                UserData = ObjectSerializer.Deserialize <Preferences>(dataFilePath);
            }
            foreach (Category concernedCategory in UserData.ListChildren)
            {
                foreach (Game concernedGame in concernedCategory.ListChildren)
                {
                    concernedGame.DOSEXEPath         = concernedGame.DOSEXEPath.Replace("AppPath", PathFinder.GetStartupPath());
                    concernedGame.DBConfPath         = concernedGame.DBConfPath.Replace("AppPath", PathFinder.GetStartupPath());
                    concernedGame.AdditionalCommands = concernedGame.AdditionalCommands.Replace("AppPath", PathFinder.GetStartupPath());
                    concernedGame.Directory          = concernedGame.Directory.Replace("AppPath", PathFinder.GetStartupPath());
                    concernedGame.CDPath             = concernedGame.CDPath.Replace("AppPath", PathFinder.GetStartupPath());
                    concernedGame.SetupEXEPath       = concernedGame.SetupEXEPath.Replace("AppPath", PathFinder.GetStartupPath());
                    concernedGame.Icon = concernedGame.Icon.Replace("AppPath", PathFinder.GetStartupPath());
                }
            }
            UserData.DBDefaultConfFilePath = UserData.DBDefaultConfFilePath.Replace("AppPath", PathFinder.GetStartupPath());
            UserData.DBDefaultLangFilePath = UserData.DBDefaultLangFilePath.Replace("AppPath", PathFinder.GetStartupPath());
            UserData.DBPath           = UserData.DBPath.Replace("AppPath", PathFinder.GetStartupPath());
            UserData.ConfigEditorPath = UserData.ConfigEditorPath.Replace("AppPath", PathFinder.GetStartupPath());
            UserData.ConfigEditorAdditionalParameters = UserData.ConfigEditorAdditionalParameters.Replace("AppPath", PathFinder.GetStartupPath());

            if (string.IsNullOrWhiteSpace(UserData.DBPath))
            {
                UserData.DBPath = FileFinder.SearchDOSBox(dataFilePath, UserData.PortableMode);
            }
            else if (File.Exists(UserData.DBPath) == false)
            {
                UserData.DBPath = FileFinder.SearchDOSBox(dataFilePath, UserData.PortableMode);
            }
            if (string.IsNullOrWhiteSpace(UserData.ConfigEditorPath))
            {
                UserData.ConfigEditorPath = FileFinder.SearchCommonTextEditor();
            }
            else if (File.Exists(UserData.ConfigEditorPath) == false)
            {
                UserData.ConfigEditorPath = FileFinder.SearchCommonTextEditor();
            }

            if (string.IsNullOrWhiteSpace(UserData.DBDefaultConfFilePath))
            {
                UserData.DBDefaultConfFilePath = FileFinder.SearchDOSBoxConf(dataFilePath, UserData.DBPath);
            }
            else if (File.Exists(UserData.DBDefaultConfFilePath) == false)
            {
                UserData.DBDefaultConfFilePath = FileFinder.SearchDOSBoxConf(dataFilePath, UserData.DBPath);
            }

            if (string.IsNullOrWhiteSpace(UserData.DBDefaultLangFilePath) == false)
            {
                UserData.DBDefaultLangFilePath = FileFinder.SearchDOSBoxLanguageFile(dataFilePath, UserData.DBPath);
            }
            else if (File.Exists(UserData.DBDefaultLangFilePath) == false)
            {
                UserData.DBDefaultLangFilePath = FileFinder.SearchDOSBoxLanguageFile(dataFilePath, UserData.DBPath);
            }
        }
Example #34
0
        /// <summary>
        /// Add a default file finder that has a content folder and a backup location. The
        /// edity folder in the content folder is not considered content.
        /// This will only do something if you have not previously registered a IFileFinder service.
        /// </summary>
        /// <param name="services">The service collection.</param>
        /// <returns></returns>
        public static IServiceCollection AddDefaultFileFinder(this IServiceCollection services)
        {
            services.TryAddScoped <IFileFinder>(s =>
            {
                var userInfo               = s.GetRequiredService <IUserInfo>();
                var projectFinder          = s.GetRequiredService <ProjectFinder>();
                var phaseDetector          = s.GetRequiredService <IPhaseDetector>();
                var compileRequestDetector = s.GetRequiredService <ICompileRequestDetector>();

                String projectFolder;
                if (compileRequestDetector.IsCompileRequest)
                {
                    projectFolder = projectFinder.PublishedProjectPath;
                }
                else
                {
                    projectFolder = projectFinder.GetUserProjectPath(userInfo.UniqueUserName);
                }

                //Any folders that can write should use these permissions, they will prevent the writing of .draft files.
                var sharedWritePermissions = new DraftFilePermissions(s.GetRequiredService <IHttpContextAccessor>());

                //Folder blacklist
                var edityFolderList = new PathList();
                edityFolderList.AddDirectory("edity");

                //Editor core location
                var backupPermissions = new DefaultFileFinderPermissions();
                backupPermissions.WritePermission.Permit          = false;
                backupPermissions.TreatAsContentPermission.Permit = false;
                var editorCoreFinder = new FileFinder(projectFinder.EdityCorePath, backupPermissions);

                //Site specific files, not editable
                var projectBackupPermissions = new DefaultFileFinderPermissions();
                projectBackupPermissions.WritePermission.Permit = false;
                projectBackupPermissions.TreatAsContentPermission.Permissions = new PathBlacklist(edityFolderList);
                var siteFileFinder = new FileFinder(projectFinder.SitePath, projectBackupPermissions, editorCoreFinder);

                //Project location
                var contentFolderPermissions = new DefaultFileFinderPermissions();
                contentFolderPermissions.TreatAsContentPermission.Permissions = new PathBlacklist(edityFolderList);
                contentFolderPermissions.WritePermission.Permissions          = sharedWritePermissions;

                //Always use the git draft manager for the project content, this way you can actually create drafts.
                var draftManager = new GitDraftManager(new PathBlacklist(edityFolderList));
                IFileStreamManager streamManager = null;

                if (phaseDetector.Phase == Phases.Draft || compileRequestDetector.IsCompileRequest)
                {
                    //If the request is in draft mode, change the content to only files with draft files and change the file stream
                    //manager to read published versions out of git
                    var oldPermissions = contentFolderPermissions.TreatAsContentPermission.Permissions;
                    contentFolderPermissions.TreatAsContentPermission.Permissions = new MustHaveGitDraftFile(draftManager, oldPermissions);
                    streamManager = new GitDraftFileStreamManager(draftManager);
                }

                return(new FileFinder(projectFolder, contentFolderPermissions, siteFileFinder, streamManager, draftManager));
            });

            return(services);
        }
Example #35
0
        static void Main()
        {
            FileFinder myProgram = new FileFinder();

            myProgram.Run();
        }
Example #36
0
        public Task <ExecutionResult> Execute(IInteractiveWindow window, string arguments)
        {
            var finder = new FileFinder(arguments);

            var eval = window.GetPythonEvaluator();

            if (eval != null)
            {
                finder.Search(eval.Configuration.WorkingDirectory);
                foreach (var p in eval.Configuration.SearchPaths)
                {
                    finder.Search(p);
                }
            }

            finder.ThrowIfNotFound();
            string commandPrefix = "$";
            string lineBreak     = window.TextView.Options.GetNewLineCharacter();

            IEnumerable <string> lines = File.ReadLines(finder.Filename);
            IEnumerable <string> submissions;

            if (eval != null)
            {
                submissions = ReplEditFilter.JoinToCompleteStatements(lines, eval.LanguageVersion).Where(CommentPrefixPredicate);
            }
            else
            {
                // v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
                // and using this class it would be hit.
                var submissionList    = new List <string>();
                var currentSubmission = new List <string>();

                foreach (var line in lines)
                {
                    if (line.StartsWith(_commentPrefix))
                    {
                        continue;
                    }

                    if (line.StartsWith(commandPrefix))
                    {
                        AddSubmission(submissionList, currentSubmission, lineBreak);

                        submissionList.Add(line);
                        currentSubmission.Clear();
                    }
                    else
                    {
                        currentSubmission.Add(line);
                    }
                }

                AddSubmission(submissionList, currentSubmission, lineBreak);

                submissions = submissionList;
            }

            window.SubmitAsync(submissions);
            return(ExecutionResult.Succeeded);
        }
Example #37
0
 public XmlConfigAdapter(FileFinder fileFinder) : base(fileFinder)
 {
 }
Example #38
0
 public XInputMaskScanner()
 {
     ff            = new FileFinder();
     ff.FileFound += ff_FileFound;
 }
Example #39
0
        public void Zip(string workingDirectory, string zipFilePath, params string[] filePatterns)
        {
            Console.WriteLine("Creating zip file...");

            Console.WriteLine("  Zip file path: " + zipFilePath);

            if (!Directory.Exists(Path.GetDirectoryName(zipFilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(zipFilePath));
            }

            var zipFileName = Path.GetFileNameWithoutExtension(zipFilePath);

            // Zip up the files
            ZipOutputStream s = new ZipOutputStream(
                File.Create(zipFilePath)
                );

            Console.WriteLine("  Current directory: " + workingDirectory);

            s.SetLevel(9); // 0-9, 9 being the highest compression

            byte[] buffer = new byte[4096];

            foreach (string patternLine in filePatterns)
            {
                if (!String.IsNullOrEmpty(patternLine))
                {
                    Console.WriteLine("  Specified pattern/file: " + patternLine);

                    string pattern = patternLine;

                    if (patternLine.IndexOf("|") > -1)
                    {
                        pattern = patternLine.Split('|')[0];
                    }

                    string shortPattern = pattern.Replace(workingDirectory, "");

                    Console.WriteLine("  Short pattern: " + shortPattern);

                    var foundFiles = FileFinder.FindFiles(workingDirectory, shortPattern);

                    Console.WriteLine("    Zipping...");

                    int found = 0;

                    foreach (string foundFile in foundFiles)
                    {
                        Console.WriteLine("    " + foundFile.Replace(workingDirectory, ""));

                        var internalPath = GetZipInternalPath(
                            workingDirectory,
                            zipFileName,
                            foundFile,
                            patternLine
                            );

                        ZipEntry entry = new ZipEntry(
                            internalPath
                            );

                        entry.DateTime = File.GetLastWriteTime(foundFile);

                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(foundFile))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0,
                                                      buffer.Length);

                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }

                        found++;
                    }

                    Console.WriteLine("    Found " + found.ToString() + " files.");
                }
            }

            s.Finish();
            s.Close();
        }
 public void HasWriteAccesInBinFolder() => FileFinder.HasWriteAccessToAssemblyLocationFolder().Should().BeTrue();
Example #41
0
 public void FileFinder_InvalidCharactersInPathPattern()
 {
     var finder = new FileFinder(new Mock <IFileSystem>().Object, "C:/test <");
 }
Example #42
0
 public FileZipper()
 {
     Mover      = new DirectoryMover();
     FileFinder = new FileFinder();
 }
Example #43
0
 public void FileFinder_NullPattern()
 {
     var fileSystem = new Mock <IFileSystem>();
     var finder     = new FileFinder(fileSystem.Object, null);
 }
Example #44
0
 public void GetDirectories_NullFileSystem()
 {
     var finder = new FileFinder(null, "");
 }
Example #45
0
        public void Throws_Exception_On_Empty_Parameters()
        {
            var finder = new FileFinder((IFileSystem)_fileSystem.Object);

            finder.Find(new[] { "" }, new[] { @"*.txt" }, 0);
        }
Example #46
0
        public Task <ExecutionResult> Execute(IReplWindow window, string arguments)
        {
            var finder = new FileFinder(arguments);

            var eval = window.Evaluator as BasePythonReplEvaluator;

            if (eval != null && eval.CurrentOptions != null)
            {
                finder.Search(eval.CurrentOptions.WorkingDirectory);
                finder.SearchAll(eval.CurrentOptions.SearchPaths, ';');
            }

            finder.ThrowIfNotFound();
#if DEV14_OR_LATER
            string commandPrefix = "$";
#else
            string commandPrefix = (string)window.GetOptionValue(ReplOptions.CommandPrefix);
#endif
            string lineBreak = window.TextView.Options.GetNewLineCharacter();

            IEnumerable <string> lines = File.ReadLines(finder.Filename);
            IEnumerable <string> submissions;

            if (eval != null)
            {
                submissions = eval.JoinCode(lines).Where(CommentPrefixPredicate);
            }
            else
            {
                // v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
                // and using this class it would be hit.
                var submissionList    = new List <string>();
                var currentSubmission = new List <string>();

                foreach (var line in lines)
                {
                    if (line.StartsWith(_commentPrefix))
                    {
                        continue;
                    }

                    if (line.StartsWith(commandPrefix))
                    {
                        AddSubmission(submissionList, currentSubmission, lineBreak);

                        submissionList.Add(line);
                        currentSubmission.Clear();
                    }
                    else
                    {
                        currentSubmission.Add(line);
                    }
                }

                AddSubmission(submissionList, currentSubmission, lineBreak);

                submissions = submissionList;
            }

            window.Submit(submissions);
            return(ExecutionResult.Succeeded);
        }
 public void Initialize()
 {
     _fileFinder = new FileFinder();
 }