public Func <Capture> GccLinkClib(FileRef mainObj, params FileRef[] objs) { var output = mainObj.Exe; //var mustBuild = objs.Concat(Enumerable.Repeat(mainObj.Obj, 1)) // .Any(obj => obj.NewerThan(output)); var mustBuild = true; if (mustBuild) { var objNames = string.Join(" ", objs.Select(sourceFile => sourceFile.Obj)); var arguments = $"{mainObj.Obj} " + $"{objNames} " + $"-mconsole " + //$"-nostdlib " + //$"--entry=Entry " + $"-L{Mingw.Lib} " + //$"-lkernel32 " + //$"-lgcc " + $"-o {output} " + ""; var description = $"link {mainObj.Obj} {objNames} => {mainObj.Exe}"; return(() => Mingw.GCC(description, arguments)); } return(() => Capture.Ok); }
public bool testExtractFileRefInfo() { TestUtilities.vbtitle("testing FileRef handling"); FileRef fileRef = "cat/file"; DirName dtest = RepoEnvironment.checkout.extractCategory(fileRef); FileName ftest = RepoEnvironment.checkout.extractFileName(fileRef); bool result1 = (dtest == "cat") && (ftest == "file"); TestUtilities.checkResult(result1, string.Format("valid FileRef \"{0}\" - ", fileRef)); fileRef = "cat/"; dtest = RepoEnvironment.checkout.extractCategory(fileRef); ftest = RepoEnvironment.checkout.extractFileName(fileRef); bool result2 = (dtest == "cat") && (ftest == ""); TestUtilities.checkResult(result2, string.Format("empty file in FileRef \"{0}\" - ", fileRef)); fileRef = "/file"; dtest = RepoEnvironment.checkout.extractCategory(fileRef); ftest = RepoEnvironment.checkout.extractFileName(fileRef); bool result3 = (dtest == "") && (ftest == "file"); TestUtilities.checkResult(result3, string.Format("empty category in FileRef \"{0}\" - ", fileRef)); fileRef = "abcdefg"; dtest = RepoEnvironment.checkout.extractCategory(fileRef); ftest = RepoEnvironment.checkout.extractFileName(fileRef); bool result4 = (dtest == "") && (ftest == ""); TestUtilities.checkResult(result4, string.Format("invalid FileRef \"{0}\" - ", fileRef)); return(result1 && result2 && result3 && result4); }
public void Build() { var lingu = new LinguContext(); var projectDir = DirRef.ProjectDir(); var ponyDir = projectDir.Dir("Ponies"); Environment.CurrentDirectory = ponyDir; var file = FileRef.From("./Pony.Grammar"); var dumps = FileRef.From("./Pony").Add(".Out"); var source = Source.FromFile(file); var parseTree = lingu.Try(source); if (parseTree != null) { new TreeDumper(dumps.Add(".Tree")).Dump(parseTree); var ast = new TreeBuilder().Visit(parseTree); if (ast != null) { var grammar = new GrammarBuilder(ast).Build(); if (grammar != null) { new Dumper(grammar).Dump(dumps); new CSharpWriter(grammar, file, ponyDir).Write(); } } } }
internal DataNodeInfo GetDataNodeInfo() { bool shouldSerialize = true; if (nodeInfo != null) { shouldSerialize = false; } else { nodeInfo = new DataNodeInfo(); } nodeInfo.Name = Name; nodeInfo.Comment = Comment; // We always serialize if this node represents a FileRef. This is because FileRef is a public property, // so someone could have modified it. if (shouldSerialize || FileRefFullPath != null) { // if we dont have a datanodeinfo it could be either // a direct object OR a fileref if (FileRefFullPath != null) { nodeInfo.ValueData = FileRef.ToString(); nodeInfo.MimeType = null; nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXFileRef), typeNameConverter); } else { // serialize to string inside the nodeInfo FillDataNodeInfoFromObject(nodeInfo, value); } } return(nodeInfo); }
private async Task Query(string fileName) { if (!IsFileSystemReady) { ShowErrorMessage("File system is not open", PPError.Failed); return; } using (var fileRef = new FileRef(fileSystem, fileName)) { var fileInfo = await fileRef.QueryAsync(); var strInfo = new List <string>(); strInfo.Add($"QueryResult: {fileInfo.QueryResult}"); strInfo.Add($"Size: {fileInfo.Size}"); strInfo.Add($"Type: {fileInfo.Type}"); strInfo.Add($"SystemType: {fileInfo.SystemType}"); strInfo.Add($"CreationTime: {fileInfo.UTCCreationTime.ToLocalTime()}"); strInfo.Add($"LastAccessTime: {fileInfo.UTCLastAccessTime.ToLocalTime()}"); strInfo.Add($"LastModifiedTime: {fileInfo.UTCLastModifiedTime.ToLocalTime()}"); if (fileInfo.QueryResult != PPError.Ok) { ShowErrorMessage("Query failed", fileInfo.QueryResult); return; } PostArrayMessage("QUERY", strInfo.ToArray()); ShowStatusMessage("Query success"); } }
private async Task Rename(string oldName, string newName) { if (!IsFileSystemReady) { ShowErrorMessage("File system is not open", PPError.Failed); return; } using (var refOld = new FileRef(fileSystem, oldName)) using (var refNew = new FileRef(fileSystem, newName)) { var fileInfo = await refOld.QueryAsync(); var strInfo = new StringBuilder(); strInfo.Append($"QueryResult {fileInfo.QueryResult}\n"); strInfo.Append($"Size {fileInfo.Size}\n"); strInfo.Append($"Type {fileInfo.Type}\n"); strInfo.Append($"SystemType {fileInfo.SystemType}\n"); strInfo.Append($"CreationTime {fileInfo.UTCCreationTime}\n"); strInfo.Append($"LastAccessTime {fileInfo.UTCLastAccessTime}\n"); strInfo.Append($"LastModifiedTime {fileInfo.UTCLastModifiedTime}\n"); LogToConsole(PPLogLevel.Log, strInfo.ToString()); var result = await refOld.RenameAsync(refNew); if (result != PPError.Ok) { ShowErrorMessage("Rename failed", result); return; } ShowStatusMessage("Rename success"); } }
private async Task List(string dir_name) { if (!IsFileSystemReady) { ShowErrorMessage("File system is not open", PPError.Failed); return; } //using (var fileRef = new FileRef(fileSystem, dir_name)) //{ var fileRef = new FileRef(fileSystem, dir_name); var listResult = await fileRef.ReadDirectoryEntriesAsync(); if (listResult.Result != PPError.Ok) { ShowErrorMessage("List failed", listResult.Result); return; } var entries = new List <string>(); foreach (var entry in listResult.Entries) { Console.WriteLine(entry.FileRef.Name); entries.Add(entry.FileRef.Name); } PostArrayMessage("LIST", entries.ToArray()); ShowStatusMessage("List success"); //} }
public void Dump(FileRef dests) { var grammarDump = dests.Add(".Grammar"); var terminals = dests.Add(".Terminals"); var nonterminals = dests.Add(".Nonterminals"); var sets = dests.Add(".Sets"); var table = dests.Add(".Table"); var cores = dests.Add(".Cores"); using (var writer = new StreamWriter(grammarDump)) { new GrammarDumper(Grammar).Dump(new TextIWriter(writer)); } using (var writer = new StreamWriter(terminals)) { new TerminalDumper(Grammar).Dump(new TextIWriter(writer)); } using (var writer = new StreamWriter(nonterminals)) { new NonterminalDumper(Grammar).Dump(new TextIWriter(writer)); } using (var writer = new StreamWriter(sets)) { new SetDumper(Grammar).Dump(new TextIWriter(writer)); } using (var writer = new StreamWriter(table)) { new TableDumper(Grammar).Dump(new TextIWriter(writer)); } using (var writer = new StreamWriter(cores)) { new CoresDumper(Grammar).Dump(new TextIWriter(writer)); } }
private async Task Delete(string fileName) { if (!IsFileSystemReady) { ShowErrorMessage("File system is not open", PPError.Failed); return; } using (var fileref = new FileRef(fileSystem, fileName)) { var result = await fileref.DeleteAsync(); if (result == PPError.Filenotfound) { ShowErrorMessage("File/Directory not found", result); return; } else if (result != PPError.Ok) { ShowErrorMessage("Deletion failed", result); return; } ShowStatusMessage("Delete success"); } }
public CtrlParser(FileRef filepath) { m_scanner = new CSScanner <SymbolRecord, TokenRef.Type>(CreateSymbol, CreateSourceObject, new TokenRef.Type[] { TokenRef.Type.Keyword, TokenRef.Type.Modifier, TokenRef.Type.Operator, TokenRef.Type.Identifier }); if (!filepath.IsAbsoluteFilepath) { throw new ArgumentException($"Absolute Filepath required! ", nameof(filepath)); } FileRef designer = filepath.CreateAs("Designer.cs"); FileRef resource = filepath.CreateAs("resx"); m_srcRef = new SourceRef(filepath, designer, resource); int i = 0; foreach (SourceFile srcFile in m_srcRef.FileList) { SourceObject srcObj = m_scanner.Scan(srcFile); // After call, SourceObj sequence will be available through m_srcRef.FileList[n] (.Sequence) #if DEBUG srcObj = srcFile.Sequence; Debug.Write("", srcFile.Text); while (srcObj != null) { Debug.Write(srcObj.Text + " "); srcObj = srcObj.Sequence; } Debug.WriteLine(""); #endif } }
public void Should_cache_added_items() { var cache = new OutputWriter(new NullResponseWriter()); cache.WriteProject(new Project("")); var file = new FileRef("", null); cache.WriteFile(file); cache.WriteUsing(new Using(file, "", 0, 1)); cache.WriteNamespace(new Namespce(file, "", 0, 1)); cache.WriteClass(new Class(file, "", "", "", 0, 0)); cache.WriteInterface(new Interface(file, "", "", "", 0, 0)); cache.WriteStruct(new Struct(file, "", "", "", 0, 0)); cache.WriteEnum(new EnumType(file, "", "", "", 0, 0)); cache.WriteField(new Field(file, "", "", "", 0, 0, "")); cache.WriteMethod( new Method(file, "", "", "", 0, 0, "", new Parameter[] { new Parameter(file, "", "", "", 0, 0, "") })); cache.WriteVariable(new Variable(file, "", "", "", 0, 0, "")); Assert.That(cache.Projects.Count, Is.EqualTo(1)); Assert.That(cache.Files.Count, Is.EqualTo(1)); Assert.That(cache.Usings.Count, Is.EqualTo(1)); Assert.That(cache.Namespaces.Count, Is.EqualTo(1)); Assert.That(cache.Classes.Count, Is.EqualTo(1)); Assert.That(cache.Interfaces.Count, Is.EqualTo(1)); Assert.That(cache.Structs.Count, Is.EqualTo(1)); Assert.That(cache.Enums.Count, Is.EqualTo(1)); Assert.That(cache.Fields.Count, Is.EqualTo(1)); Assert.That(cache.Methods.Count, Is.EqualTo(1)); Assert.That(cache.Parameters.Count, Is.EqualTo(1)); Assert.That(cache.Variables.Count, Is.EqualTo(1)); }
private Unit LoadUnit(Package package, FileRef unitFile) { var source = Source.FromFile(unitFile); var tokenizer = new PonyTokenizer(Errors, source); tokenizer.Tokenize(); var parser = new PonyParser(Errors, source, tokenizer.Tokens); var ptUnit = parser.Unit(); var unit = new Unit(ptUnit, unitFile, package); foreach (var use in unit.Source.Uses) { switch (use) { case PtUseUri useUri: unit.Uses.Add(DecodeUseUri(useUri)); break; case PtUseFfi useFfi: unit.Uses.Add(DecodeUseFfi(useFfi)); break; default: throw new System.InvalidOperationException(); } } return(unit); }
private void Build() { var options = new HimeTaskOptions { Public = true, Namespace = "Lingu.Boot.Hime", //RNGLR = true, Debug = true, Grammar = "Lingu", }; Environment.CurrentDirectory = $"{ProjectDir}"; var source = FileRef.From($"{ProjectDir}Lingu.Grammar"); var parser = FileRef.From($"{ProjectDir}LinguParser.cs"); var lexer = FileRef.From($"{ProjectDir}LinguLexer.cs"); var visitor = FileRef.From($"{ProjectDir}LinguVisitor.cs"); Generate(options, source); var tweaker = new Tweaker(parser, visitor); Console.WriteLine($"[Info] Tweaking new Visitor at {visitor.FileName} ..."); tweaker.TweakVisitor(); tweaker.TweakLexer(lexer); tweaker.TweakParser(parser); }
private (Errors, Tree.Unit?) Compile(FileRef file, string name) { var source = Source.FromFile(file, name); var errors = new Errors(); var tokenizer = new Tokenizer(errors, source); var tokens = tokenizer.Tokenize(); if (!errors.NoError()) { return(errors, null); } var parser = new Parser(errors, tokens); try { var unit = parser.ParseUnit(); return(errors, unit); } catch { } return(errors, null); }
private static void Dump(FileRef file, Action <IWriter> dump) { var writer = new IndentWriter(); dump(writer); writer.Persist(file); }
public void Push(FileRef fref, string hash) { var bind = _ctx.MediaBindings.SingleOrDefault(x => x.Hash == hash); if (bind == null) { bind = _ctx.MediaBindings.Create(); bind.Hash = hash; _ctx.MediaBindings.Add(bind); } var key = GetKey(fref); var file = _ctx.MediaFiles.SingleOrDefault(x => x.Key == key); if (file == null) { file = _ctx.MediaFiles.Create(); file.Key = key; _ctx.MediaFiles.Add(file); } file.Path = fref.Path; file.Bytes = fref.Bytes; file.Hash = hash; file.LastModifiedUtc = fref.LastModifiedUtc; _ctx.SaveChanges(); }
[InlineData(@"C:\tests\tts>s.s")] // TODO: add more cases? public void invalid_characters_in_file_name_or_path_shall_be_validated_only_when_asked_on_absolute_refs(string fName) { var fileRef = FileRef.CreateAbsolute(fName); fileRef.ShouldNotBeNull(); fileRef.FilePathIsValid.ShouldBeFalse(); }
public SourceRef(FileRef srcFile, FileRef dsgnrFile, FileRef resxFile) { FileList = new SourceFile[3]; FileList[0] = new SourceFile(srcFile, SourceFile.Type.Form); FileList[1] = new SourceFile(dsgnrFile, SourceFile.Type.Designer); FileList[2] = new SourceFile(resxFile, SourceFile.Type.Resource); }
/// <summary> /// Creates an instance of TinyFileStream. /// </summary> /// <param name="fileSystem">TinyFileSystem instance on which the file this stream exposes exists.</param> /// <param name="fileRef">The file to expose through the TinyFileStream.</param> /// <remarks> /// Instances of this class should never be created directly. The should be created by calls to Create or Open /// on the TinyFileSystem instance. /// </remarks> internal TinyFileStream(TinyFileSystem fileSystem, FileRef fileRef) { _fs = fileSystem; _fileRef = fileRef; _filePointer = 0; _fileRef.OpenCount++; }
public void TestFilePathesInJson() { var root = EnvironmentV2.instance.GetOrAddTempFolder("TestFilePathesInJson"); var file1 = root.GetChildDir("SubDir1").GetChildDir("SubSubDir1").GetChild("child1.txt"); var savedText = "Test 123"; file1.SaveAsText(savedText); IFileRef x1 = new FileRef(); x1.SetPath(file1); var x2 = x1.DeepCopyViaJson(); AssertV2.AreEqualJson(x1, x2); Assert.NotEmpty(x1.fileName); Assert.NotEmpty(x2.fileName); // GetChild ensures that no special characters like / are in the file name: var fullPathViaGetChild = root.GetChild("" + x2.GetPath()); Assert.False(fullPathViaGetChild.Exists); // ResolveFilePath can be used to resolve full pathes including / characters: var file2 = root.ResolveFilePath("" + x2.GetPath()); Assert.True(file2.Exists); Assert.Equal(savedText, file2.LoadAs <string>()); }
private static void BuildCC() { var projectDir = DirRef.ProjectDir(); var linguCC = projectDir.Up.Dir("LinguCC"); var genDir = linguCC.Dir("Gen"); Environment.CurrentDirectory = genDir; var file = FileRef.From("./Lingu.Grammar"); var dumps = FileRef.From("./Lingu").Add(".Out"); var context = Timer.Time("context", () => new LinguContext()); var source = Timer.Time("source", () => Source.FromFile(file)); var lexer = Timer.Time("lexer", () => new Lexer(context, source)); var parser = Timer.Time("parser", () => new Parser(context, lexer)); var parseTree = Timer.Time("parse", () => parser.Parse()); Timer.Time("tree-dump", () => new TreeDumper(dumps.Add(".Tree")).Dump(parseTree)); var ast = Timer.Time("ast", () => new TreeBuilder().Visit(parseTree)); var grammar = Timer.Time("build", () => new GrammarBuilder(ast).Build()); Timer.Time("dump", () => new Dumper(grammar).Dump(dumps)); Timer.Time("write", () => new CSharpWriter(grammar, file, genDir).Write()); }
static CtrlParser() { NextStateRec next, back; // used to create a sequence of token states NextStateRec record; // used to create a sequence of token states NextStateRec @base = null; // holds the current record used as the base for a sequence of tokens FileRef ctrlParserDef = Settings.Default.CSLangDefFilePath; Initialise(ctrlParserDef); //string[] lines = File.ReadAllLines(filepath); //foreach (string line in lines) //{ // Match match = s_langDefRE.Match(line); // // HACK: building the definition by hand for now -just reading file to confirm completeness // if (!match.Success) // continue; // string name = match.Groups["name"].Value; //} NextStateFunc = s_nxtStateFuncBldr.NextStateFunc; }
public List <ICodeReference> ParseRefs(string resultString) { var refs = new List <ICodeReference>(); foreach (var command in resultString.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) { try { var chunks = command.Trim() .Split(new char[] { '|' }, StringSplitOptions.None); if (chunks.Length == 0) { continue; } if (chunks[0] == "file") { _currentFile = handleFile(chunks); } if (chunks[1] == "signature") { var reference = handleSignature(chunks); if (reference != null) { refs.Add(reference); } } } catch { } } return(refs); }
public bool testComponent() { TestUtilities.title("Testing FileNameEditor", '='); TestUtilities.putLine(); TestUtilities.title("Testing extension edits"); FileName fileName = "SomeFile.cs.2"; FileName test1Name = addXmlExt(fileName); bool t1 = test1Name.Contains(".xml"); showResult(t1, test1Name, "addXmlExt"); FileName test2Name = removeXmlExt(test1Name); bool t2 = test2Name == fileName; showResult(t2, test2Name, "removeXmlExt"); FileName test3Name = removeXmlExt(test2Name); bool t3 = test3Name == fileName; showResult(t3, test3Name, "removeXmlExt"); TestUtilities.putLine(); TestUtilities.title("Testing path construction"); DirName stagingdir = "Fawcett"; FullDir stagingpath = stagingPath(stagingdir); bool t4 = (stagingpath.Contains("C:/") || stagingpath.Contains("../")) && stagingpath.Contains(stagingdir); showResult(t4, stagingpath, "stagingPath"); DirName category = "SomeCategory"; FullDir storagepath = storagePath(category); bool t5 = (storagepath.Contains("C:/") || storagepath.Contains("../")) && storagepath.Contains(category); showResult(t5, storagepath, "storagePath"); FileName someFileName = "someFileName"; FileSpec filespec = fileSpec(storagepath, someFileName); bool t6 = filespec.Contains("/someFileName"); showResult(t6, filespec, "fileSpec"); FileRef fileref = storageFolderRef(filespec); bool t7 = fileref.IndexOf('/') == fileref.LastIndexOf('/'); showResult(t7, fileref, "storageFolderRef"); DirName cat = extractCategory(fileref); bool t8 = cat == category; showResult(t8, cat, "extractCategory"); FileName file = extractFileName(fileref); bool t9 = file == someFileName; showResult(t8, file, "extractFileName"); return(t1 && t2 && t3 && t4 && t5 && t6 && t7 && t8 && t9); }
public PartialType(FileRef file, Point location, string type, string parent, Action <string> resolve) { File = file; Location = location; Type = type; Parent = parent; _resolve = resolve; }
private SourceStruct m_lastStruct = null; // used to remember last structure created for use in linking more public SourceFile(FileRef filepath, Type type) : base(filepath.Filename, TokenRef.Type.Non) { Debug.Assert(type != Type.Null, "Cannot be of Type.Null"); Filepath = filepath; OfType = type; SourceStruct = null; }
public CSharpContext(Grammar grammar, FileRef sourceFile, string @namespace, DirRef output, CsWriter writer = null) { Grammar = grammar; SourceFile = sourceFile; Namespace = @namespace; Output = output; Writer = writer; }
public void WriteFile(FileRef file) { Files.Add(file); if (_visibility) { _writer.Write("file|" + file.File + "|filesearch"); } }
static void Main() { // Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdfservices-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance RotatePagesOperation rotatePagesOperation = RotatePagesOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"rotatePagesInput.pdf"); rotatePagesOperation.SetInput(sourceFileRef); // Sets angle by 90 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. PageRanges firstPageRange = GetFirstPageRangeForRotation(); rotatePagesOperation.SetAngleToRotatePagesBy(Angle._90, firstPageRange); // Sets angle by 180 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. PageRanges secondPageRange = GetSecondPageRangeForRotation(); rotatePagesOperation.SetAngleToRotatePagesBy(Angle._180, secondPageRange); // Execute the operation. FileRef result = rotatePagesOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/rotatePagesOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } catch (ServiceApiException ex) { log.Error("Exception encountered while executing operation", ex); } catch (SDKException ex) { log.Error("Exception encountered while executing operation", ex); } catch (IOException ex) { log.Error("Exception encountered while executing operation", ex); } catch (Exception ex) { log.Error("Exception encountered while executing operation", ex); } }
[InlineData(@"C:\tests\tts>s.s")] // TODO: add more cases? public void invalid_characters_in_file_name_shall_be_validated_when_asked_on_absolute_refs(string fName) { FileRef reff; Should.Throw <ArgumentException>(() => reff = FileRef.CreateAbsolute(fName)); //fileRef.ShouldNotBeNull(); //fileRef.FileNameIsValid.ShouldBeFalse(); }
private Process Launch(LaunchStrategy strategy) { Logger.Current.Trace("Launching configuration {0} with strategy {1}", Configuration.identifier, strategy); switch (strategy) { case LaunchStrategy.AttachOrLaunch: try { return Launch(LaunchStrategy.Attach); } catch (Exception e) { Logger.Current.Trace(e); try { return Launch(LaunchStrategy.Launch); } catch (Exception ex) { throw ex; } } case LaunchStrategy.Launch: Logger.Current.Trace("Launching path={0} args={1}", Configuration.appPath, Configuration.arguments); this.LaunchStrategy = LaunchStrategy.Launch; Process process = Process.Start(Configuration.appPath, Configuration.arguments); Factory.LockProcess(process); return process; case LaunchStrategy.Attach: FileRef runningApp = new FileRef(Configuration.appPath); foreach (Process candidate in Process.GetProcesses()) { if (candidate.Id == 0) // idle process continue; try { if (runningApp.Equals(new FileRef(candidate)) && Factory.TryLockProcess(candidate)) { Logger.Current.Info("Attaching to process {0} for configuration {1}: {2}", candidate.Id, Configuration.identifier, candidate.MainModule.FileName); this.LaunchStrategy = LaunchStrategy.Attach; return candidate; } } catch (Exception) { // couldn't read the process, e.g. svchost } } Logger.Current.Info("Couldn't find a process to attach to for configuration {0} with path {1}", Configuration.identifier, Configuration.appPath); throw new Exception("Could not find any process with path " + Configuration.appPath + " to bind to"); } throw new Exception("Unknown LaunchStrategy " + strategy); }
public void SetFileRef (FileRef file_ref) { this.file_ref = file_ref; }
public void CanLoadExistingFileWhenInitialising() { // arrange var moduleHash = Guid.NewGuid().ToString(); var persistence = new FilePersistance(_mockCommandLine.Object, _mockLogger.Object); persistence.Initialise(_filePath, false); var point = new SequencePoint() // BranchPoints within SequencePoint shorther than 3 characters will be removed {StartLine = 1, EndLine = 1, StartColumn = 1, EndColumn = 4}; var branchPoint = new BranchPoint{Path = 0, OffsetPoints = new List<int>()}; var branchPoint2 = new BranchPoint { Path = 1, OffsetPoints = new List<int>{1,2}}; var file = new OpenCover.Framework.Model.File(); var filref = new FileRef() {UniqueId = file.UniqueId}; persistence.PersistModule(new Module { Summary = new Summary {NumSequencePoints = 1}, Files = new[] {file}, ModuleHash = moduleHash, Classes = new[] { new Class { Summary = new Summary {NumSequencePoints = 1}, Files = new[] {file}, Methods = new[] { new Method { FileRef = filref, MetadataToken = 1234, Summary = new Summary {NumSequencePoints = 1}, MethodPoint = point, SequencePoints = new[] {point}, BranchPoints = new[] {branchPoint, branchPoint2} } } } } }); persistence.Commit(); var persistence2 = new FilePersistance(_mockCommandLine.Object, _mockLogger.Object); // act persistence2.Initialise(_filePath, true); // assert Assert.IsNotNull(persistence2.CoverageSession); Assert.AreEqual(moduleHash, persistence2.CoverageSession.Modules[0].ModuleHash); Assert.AreEqual(point.UniqueSequencePoint, persistence2.CoverageSession.Modules[0].Classes[0].Methods[0].SequencePoints[0].UniqueSequencePoint); Assert.AreEqual(point.UniqueSequencePoint, persistence2.CoverageSession.Modules[0].Classes[0].Methods[0].MethodPoint.UniqueSequencePoint); var method = persistence2.CoverageSession.Modules[0].Classes[0].Methods[0]; var br1 = persistence2.CoverageSession.Modules[0].Classes[0].Methods[0].BranchPoints[0]; var br2 = persistence2.CoverageSession.Modules[0].Classes[0].Methods[0].BranchPoints[1]; Assert.AreEqual(branchPoint.UniqueSequencePoint, br1.UniqueSequencePoint); Assert.AreEqual(branchPoint2.UniqueSequencePoint, br2.UniqueSequencePoint); Assert.AreEqual(0, br1.OffsetPoints.Count); Assert.AreEqual(2, br2.OffsetPoints.Count); Assert.AreEqual(1, br2.OffsetPoints[0]); Assert.AreEqual(2, br2.OffsetPoints[1]); // the method and sequence point if point to same offset need to merge Assert.AreSame(method.MethodPoint, method.SequencePoints[0]); // the loaded summary object needs to be cleared Assert.AreEqual(0, persistence2.CoverageSession.Summary.NumSequencePoints); Assert.AreEqual(0, persistence2.CoverageSession.Modules[0].Summary.NumSequencePoints); Assert.AreEqual(0, persistence2.CoverageSession.Modules[0].Classes[0].Summary.NumSequencePoints); Assert.AreEqual(0, persistence2.CoverageSession.Modules[0].Classes[0].Methods[0].Summary.NumSequencePoints); }