Beispiel #1
0
 private static SourceCodeFileDto CreateXmlSourceCodeFile(
     XmlProjectDataAccess projectAccess,
     AbsoluteDirectoryPath projectDirectory,
     ICSharpFileSyntaxTree syntaxTree,
     Dictionary <string, ClassDeclarationInfo> classDeclarationSignatures)
 {
     return(new SourceCodeFileDto(
                AtmaFileSystemPaths.RelativeFilePath(GetPathRelativeTo(projectDirectory, syntaxTree.FilePath)),
                syntaxTree.GetAllUniqueNamespaces().ToList(),
                projectAccess.RootNamespace(),
                projectAccess.DetermineAssemblyName(),
                syntaxTree.GetAllUsingsFrom(classDeclarationSignatures),
                classDeclarationSignatures.Values.ToList()));
 }
        public static void Run(AbsoluteDirectoryPath root, FuseRunner fuseRunner)
        {
            var exitCode = fuseRunner.Run("install -s android", Optional.None())
                           .WaitOrThrow(TimeSpan.FromMinutes(1))
                           .ExitCode;
            const int isInstalled     = 0;
            const int isNotInstalled  = 100;
            const int updateAvailable = 200;

            if (exitCode != isInstalled && exitCode != isNotInstalled && exitCode != updateAvailable)
            {
                throw new TestFailure("Unexpected exit code " + exitCode);
            }
        }
        public bool IsInstalledAt(AbsoluteDirectoryPath installPath, IProgress <InstallerEvent> progress)
        {
            if (ElCapitanWorkaround.IsInvalidWithMessage(progress, installPath))
            {
                return(false);
            }

            var androidTools = (installPath / new DirectoryName("tools"));

            return(_fs.Exists(installPath) &&
                   _fs.Exists(androidTools) &&
                   CheckIfCorruptInstallation(installPath, progress) &&
                   NotSpaceInPath(installPath, progress));
        }
Beispiel #4
0
 AbsoluteDirectoryPath FindOutputDir(BuildProject args, AbsoluteDirectoryPath basePath)
 {
     if (string.IsNullOrWhiteSpace(args.OutputDir))
     {
         var outputDirWithLock =
             _outputDirGenerator.CreateOrReuseOutputDir(_isHost ? basePath / "PreviewHost" : basePath / "Preview");
         _registerLock(outputDirWithLock.LockFile);
         return(outputDirWithLock.OutputDir);
     }
     else
     {
         return(AbsoluteDirectoryPath.Parse(args.OutputDir));
     }
 }
Beispiel #5
0
 private static TestResult Run(Test t, AbsoluteDirectoryPath root, FuseRunner fuseRunner)
 {
     try
     {
         t.Run(root, fuseRunner);
         Console.WriteLine(t.Name + " Passed");
         return(new TestResult(t, Result.Passed));
     }
     catch (Exception e)
     {
         Console.Error.WriteLine(e.Message);
         Console.WriteLine(t.Name + " Failed");
         return(new TestResult(t, Result.Failed));
     }
 }
Beispiel #6
0
 public FuseKiller(IReport log, AbsoluteDirectoryPath fuseRoot)
 {
     if (Platform.OperatingSystem == OS.Mac)
     {
         _impl = new MacFuseKiller(log, fuseRoot);
     }
     else if (Platform.OperatingSystem == OS.Windows)
     {
         _impl = new WinFuseKiller(log, fuseRoot);
     }
     else
     {
         throw new PlatformNotSupportedException();
     }
 }
Beispiel #7
0
 static void TryDeleteFolder(AbsoluteDirectoryPath folderToDelete, IFileSystem fs, IProgress <InstallerEvent> progress)
 {
     try
     {
         if (fs.Exists(folderToDelete))
         {
             progress.Report(new InstallerMessage(folderToDelete.NativePath + " already exists and will be overwritten."));
             fs.Delete(folderToDelete);
         }
     }
     catch (Exception)
     {
         // We ignore this, so use this function with care.
     }
 }
        static void AssertIfDiffers(MessageDatabase database, string filePathStr)
        {
#if DUMP_MODE
            var relativePath = RelativeFilePath.Parse(filePathStr);
            var dumpPath     = AbsoluteDirectoryPath.Parse("../../") / relativePath;
            database.Dump(dumpPath);
#endif
            var filePath         = AbsoluteFilePath.Parse(filePathStr);
            var originalDatabase = MessageDatabase.From(filePath);
            MessageDatabase.From(filePath);

            var errors = new Subject <string>();
            errors.Subscribe(Console.WriteLine);
            Assert.True(MessageDatabase.IsEqualWhileIgnoreComments(originalDatabase, database, errors), "Looks like you have changed the plugin API");
        }
        public static void Run(AbsoluteDirectoryPath root, FuseRunner fuseRunner)
        {
            var projectDir = root / "GeneratedTestData" / "AutomaticTestApp" / "App";
            var project    = projectDir / new FileName("App.unoproj");
            var timeout    = TimeSpan.FromMinutes(3);

            Console.WriteLine("Setting up project");
            IOHelpers.DeleteAndCopyDirectory(root / "Stuff" / "AutomatictestApp" / "App", projectDir);

            var testAppError = false;

            try
            {
                var wait = new ManualResetEvent(false);

                Console.WriteLine("Starting preview");
                fuseRunner.Preview(project, Optional.Some <Action <string> >(
                                       s =>
                {
                    if (s.Contains("TEST_APP_MSG:OK"))
                    {
                        wait.Set();
                    }
                    if (s.Contains("TEST_APP_MSG:ERROR"))
                    {
                        testAppError = true;
                        wait.Set();
                    }
                }));
                if (!wait.WaitOne(timeout))
                {
                    throw new TestFailure("Test timed out after " + timeout);
                }
                if (testAppError)
                {
                    throw new TestFailure("Test app failed");
                }
            }
            catch (Exception e)
            {
                throw new TestFailure(e.Message);
            }
            finally
            {
                ScreenCapture.Shoot("AutomaticTestApp-before-kill.png");
                fuseRunner.KillOrThrow();
            }
        }
Beispiel #10
0
        void LoadTemplateFiles(AbsoluteDirectoryPath directoryPath)
        {
            var files = _fileSystem.GetFiles(directoryPath);

            foreach (var file in files)
            {
                AddTemplateFile(file);
            }

            var directories = _fileSystem.GetDirectories(directoryPath);

            foreach (var dir in directories)
            {
                LoadTemplateFiles(dir);
            }
        }
Beispiel #11
0
        bool ChangeProject(string projectPath)
        {
            _currentProject = Project.Load(projectPath);

            new Shell()
            .Watch(AbsoluteFilePath.Parse(projectPath).ContainingDirectory, "*.unoproj")
            .Where(e => e.Event == FileSystemEvent.Changed || e.Event == FileSystemEvent.Removed)
            .Subscribe(f => _currentProject = null);

            MainPackage = PackageCache.GetPackage(Log.Default, _currentProject);
            MainPackage.SetCacheDirectory((AbsoluteDirectoryPath.Parse(MainPackage.CacheDirectory) / new DirectoryName("CodeCompletion")).NativePath);

            TriggerBuild();

            return(true);
        }
Beispiel #12
0
        public static void Run(AbsoluteDirectoryPath root, FuseRunner fuseRunner)
        {
            var shell      = new Shell();
            var projectDir = root / "GeneratedTestData" / "FuseBuild";
            var project    = projectDir / new FileName("SystemTest1.unoproj");

            Console.WriteLine("Setting up project");
            IOHelpers.DeleteAndCopyDirectory(root / "Projects" / "SystemTest1", projectDir);


            Console.WriteLine("Starting build");
            fuseRunner.Run("build " + project.NativePath, Optional.None())
            .WaitOrThrow(TimeSpan.FromMinutes(3))
            .AssertExitCode(0);
            IOHelpers.AssertExists(shell, projectDir / "build");
        }
Beispiel #13
0
        public static void Run(AbsoluteDirectoryPath root, FuseRunner fuseRunner)
        {
            var shell   = new Shell();
            var testDir = root / "GeneratedTestData" / "FuseCreate";
            var appDir  = testDir / "appname";

            shell.DeleteIfExistsAndCreateDirectory(testDir);
            using (TestHelpers.ChangeWorkingDirectory(testDir))
            {
                fuseRunner.Run("create app appname", Optional.None())
                .WaitOrThrow(TimeSpan.FromSeconds(10))
                .AssertExitCode(0);
                IOHelpers.AssertExists(shell, appDir / new FileName("MainView.ux"));
                IOHelpers.AssertExists(shell, appDir / new FileName("appname.unoproj"));
            }
        }
Beispiel #14
0
        public IEnumerable <AbsoluteDirectoryPath> GetPathToApplicationsThatContains(string name)
        {
            foreach (var app in GetApplications(name))
            {
                yield return(app);
            }

            var directories = Directory.GetDirectories("/Applications");

            foreach (var directory in directories)
            {
                if (directory.Contains(name))
                {
                    yield return(AbsoluteDirectoryPath.Parse(directory));
                }
            }
        }
Beispiel #15
0
        public static AbsoluteFilePath GetSystemGuidPath()
        {
            if (Platform.OperatingSystem == OS.Windows)
            {
                return(AbsoluteDirectoryPath.Parse(
                           Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)) / "Fusetools" / "Fuse" /
                       new FileName(".user"));
            }
            else if (Platform.OperatingSystem == OS.Mac)
            {
                return(AbsoluteDirectoryPath.Parse(
                           Environment.GetFolderPath(Environment.SpecialFolder.Personal)) / ".fuse" /
                       new FileName(".user"));
            }

            throw new PlatformNotSupportedException("Not implemented on platform: " + Platform.OperatingSystem);
        }
Beispiel #16
0
        public static void Run(AbsoluteDirectoryPath root, FuseRunner fuseRunner)
        {
            var shell      = new Shell();
            var projectDir = root / "GeneratedTestData" / "FuseImport";

            Console.WriteLine("Setting up project");
            IOHelpers.DeleteAndCopyDirectory(root / "Projects" / "SketchImportApp", projectDir);

            Console.WriteLine("Starting import");
            using (TestHelpers.ChangeWorkingDirectory(projectDir))
            {
                fuseRunner.Run("import Foo.sketch", Optional.None())
                .WaitOrThrow(TimeSpan.FromMinutes(1))
                .AssertExitCode(0);
                IOHelpers.AssertExists(shell, projectDir / "SketchSymbols" / new FileName("Sketch.Fuse.ux"));
            }
        }
Beispiel #17
0
        public static DownloadResultStatus DownloadZip(
            CancellationToken ct,
            Uri downloadUrl,
            AbsoluteDirectoryPath extractPath,
            IProgress <InstallerEvent> progress,
            IFileSystem fs)
        {
            TryDeleteFolder(extractPath, fs, progress);
            fs.Create(extractPath);

            fs.CreateEmpty(extractPath / new FileName(".progress"));
            var downloadRes = Download(ct, downloadUrl, extractPath, progress);

            fs.Delete(extractPath / new FileName(".progress"));

            return(downloadRes);
        }
Beispiel #18
0
        static void ExtractZipTo(CancellationToken ct, Stream stream, AbsoluteDirectoryPath outFolder, IProgress <InstallerEvent> progress)
        {
            progress.Report(new InstallerStep("Extracting"));

            var zipIn    = new ZipInputStream(stream);
            var zipEntry = zipIn.GetNextEntry();

            if (zipEntry.IsDirectory)
            {
                zipEntry = zipIn.GetNextEntry();
            }

            while (zipEntry != null)
            {
                ct.ThrowIfCancellationRequested();
                var entryFileName = zipEntry.Name;
                var parts         = zipEntry.IsDirectory ? RelativeDirectoryPath.Parse(entryFileName.Substring(0, entryFileName.Length - 1)).Parts :
                                    RelativeFilePath.Parse(entryFileName).Parts;

                var newPathStr = "";
                var partsArray = parts.ToArray();
                for (var i = 1; i < partsArray.Length; ++i)
                {
                    newPathStr += partsArray[i] + (i + 1 == partsArray.Length ? "" : Path.DirectorySeparatorChar.ToString());
                }

                var buffer        = new byte[4096];
                var fullZipToPath = Path.Combine(outFolder.NativePath, newPathStr);
                var directoryName = zipEntry.IsFile ? Path.GetDirectoryName(fullZipToPath) : fullZipToPath;
                if (directoryName.Length > 0)
                {
                    Directory.CreateDirectory(directoryName);
                }

                if (zipEntry.IsFile)
                {
                    progress.Report(new InstallerMessage("Extracting: " + newPathStr));
                    using (var streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipIn, streamWriter, buffer);
                    }
                }

                zipEntry = zipIn.GetNextEntry();
            }
        }
Beispiel #19
0
        static void CopyAllFilesRecursive(AbsoluteDirectoryPath dir, AbsoluteDirectoryPath outDir)
        {
            var files = Directory.GetFiles(dir.NativePath);

            foreach (var file in files)
            {
                File.Copy(file, (outDir / Path.GetFileName(file)).NativePath, true);
            }

            var childrenDirs = Directory.GetDirectories(dir.NativePath);

            foreach (var childrenDir in childrenDirs)
            {
                var childrenOutDir = outDir / new DirectoryName(Path.GetFileName(childrenDir));
                Create(childrenOutDir);
                CopyAllFilesRecursive(AbsoluteDirectoryPath.Parse(childrenDir), childrenOutDir);
            }
        }
Beispiel #20
0
 public DashboardCommand(
     string fuseVersion,
     IFileSystem fs,
     IReport log,
     IFuseLauncher launchFuse,
     IFuseKiller fuseKiller,
     AbsoluteDirectoryPath userDataDir,
     ColoredTextWriter outWriter)
     : base("dashboard", "Fire up the dashboard")
 {
     _fuseVersion = fuseVersion;
     _fs          = fs;
     _log         = log;
     _launchFuse  = launchFuse;
     _fuseKiller  = fuseKiller;
     _outWriter   = outWriter;
     _versionFile = userDataDir / new FileName(".fuseVersion");
 }
Beispiel #21
0
        public virtual Process Run(AbsoluteDirectoryPath workingDir)
        {
            var fileName = workingDir.NativePath + Path.DirectorySeparatorChar + Command;

            var processStartInfo = new ProcessStartInfo()
            {
                FileName               = fileName,
                UseShellExecute        = false,
                WorkingDirectory       = workingDir.NativePath,
                RedirectStandardInput  = false,
                RedirectStandardOutput = false,
                RedirectStandardError  = false,
                Arguments              = Arguments.Or(new string[0]).Join(" ")
            };

            var p = Process.Start(processStartInfo);

            return(p);
        }
Beispiel #22
0
        public static void Shoot(string name)
        {
            try
            {
                var shell = new Shell();

                var dir = AbsoluteDirectoryPath.Parse(Environment.CurrentDirectory).Combine("diagnostics");
                shell.Create(dir);
                var file = dir.Combine(new FileName(name));

                // Not taking screenshots on other platforms than Mac right now,
                // The preview tests running on Windows is not that unstable, so not currently important to do that.
                if (Platform.OperatingSystem != OS.Mac)
                {
                    return;
                }

                var psi = new ProcessStartInfo("screencapture", "\"" + file.NativePath + "\"")
                {
                    UseShellExecute = false,
                    CreateNoWindow  = true
                };
                var p = Process.Start(psi);
                if (p == null)
                {
                    throw new InvalidOperationException("Unable to start screencapture process");
                }

                if (!p.WaitForExit(5000))
                {
                    p.Kill();
                    throw new InvalidOperationException("Timeout while trying to take screenshot");
                }
                if (p.ExitCode != 0)
                {
                    throw new InvalidOperationException("Got exit code " + p.ExitCode + " while trying to take screenshot");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Unable to take screenshot, because: " + e);
            }
        }
Beispiel #23
0
        Project FindAndLoadProjectInDirectory(AbsoluteDirectoryPath directory)
        {
            if (directory.ContainingDirectory == null)
            {
                throw new ProjectNotFound();
            }

            var projectPath = _fileSystem.GetFiles(directory).FirstOrDefault(f => f.Name.HasExtension("unoproj"));

            if (projectPath == null)
            {
                return(FindAndLoadProjectInDirectory(directory.ContainingDirectory));
            }

            var unoProj = Project.Load(projectPath.NativePath);

            unoProj.AddDefaults();
            return(unoProj);
        }
Beispiel #24
0
        public CodeNinjaBuild(ILog logWriter, Project project, IEditorManager editors, SourcePackage mainPackage, List <SourcePackage> referencedPackages, string extraCode = null, AbsoluteFilePath extraSourcePath = null)
        {
            _log = new Log(logWriter.TextWriter);
            _log.MaxErrorCount = 0;

            _logWriter = logWriter;
            _editors   = editors;

            //var newPackages = new List<SourcePackage>();
            //mainPackage = Uno.Build.Packages.PackageResolver.ResolvePackages(_log, project, newPackages);

            AddNotAddedPackages(referencedPackages);
            mainPackage.References.Clear();
            _packages.Each(p => mainPackage.References.Add(p));

            ProjectPackage = mainPackage;

            _extraCode       = extraCode;
            _extraCodeSource = extraSourcePath;

            var configuration = new CodeNinjaBuildTarget();
            var backend       = configuration.CreateBackend();

            var projectDir = project.RootDirectory;
            var rootDir    = AbsoluteDirectoryPath.Parse(Path.Combine(projectDir, ".CodeNinja"));

            _compiler = new Compiler(
                _log,
                backend,
                ProjectPackage,
                new CompilerOptions
            {
                Debug = true,
                CodeCompletionMode = true,
                OutputDirectory    = (rootDir / "Output").ToString(),
                BuildTarget        = new DefaultBuild().Identifier,
                Strip = false
            });

            _projDir   = AbsoluteDirectoryPath.Parse(ProjectPackage.SourceDirectory);
            _filePaths = project.SourceFiles.Select(x => x.UnixPath).Select(RelativeFilePath.Parse).ToList();
        }
Beispiel #25
0
        public IEnumerable <AbsoluteDirectoryPath> GetJdkSearchPaths(IFileSystem fs)
        {
            var defaultInstallLocations = Enumerable.Empty <AbsoluteDirectoryPath>();

            if (Platform.OperatingSystem == OS.Windows)
            {
                var defaultSearchLocation = PathExtensions.GetEnvironmentPath(Environment.SpecialFolder.ProgramFiles)
                                            / new DirectoryName("Java");

                if (fs.Exists(defaultSearchLocation))
                {
                    defaultInstallLocations = fs.GetDirectories(defaultSearchLocation, "jdk*").Reverse();
                }

                return(defaultInstallLocations);
            }
            else if (Platform.OperatingSystem == OS.Mac)
            {
                var javaHome = Environment
                               .GetEnvironmentVariable("JAVA_HOME")
                               .ToOptional()
                               .SelectMany(AbsoluteDirectoryPath.TryParse);

                var defaultSearchLocation = AbsoluteDirectoryPath.Parse("/Library/Java/JavaVirtualMachines");
                if (fs.Exists(defaultSearchLocation))
                {
                    var jdkBaseDirectories = fs.GetDirectories(defaultSearchLocation, "jdk*").Reverse();
                    defaultInstallLocations = jdkBaseDirectories.Select(
                        dir =>
                        dir / new DirectoryName("Contents") / new DirectoryName("Home"));
                }

                return(new[]
                {
                    javaHome,
                }
                       .NotNone()
                       .Concat(defaultInstallLocations));
            }

            throw new PlatformNotSupportedException();
        }
        public static IEnumerable <Package> SearchForPackagesIn(IFileSystem fs, AbsoluteDirectoryPath searchPath)
        {
            var files = fs.GetFiles(searchPath);
            var sourcePropertyFile = files.FirstOrNone(f => f.Name == new FileName("source.properties"));

            if (sourcePropertyFile.HasValue)
            {
                var package = TryParse(fs.ReadAllText(sourcePropertyFile.Value, 5));
                if (package.HasValue)
                {
                    yield return(package.Value);
                }
            }

            foreach (var package in fs.GetDirectories(searchPath)
                     .SelectMany(dir => SearchForPackagesIn(fs, dir)))
            {
                yield return(package);
            }
        }
Beispiel #27
0
        static Optional <AbsoluteDirectoryPath> GetFuseRootWin(AbsoluteDirectoryPath baseSearchDir)
        {
            var fuseExe = Directory
                          .GetFiles(baseSearchDir.NativePath)
                          .Select(Path.GetFileName)
                          .FirstOrNone(f =>
                                       f.Equals(RelativeFilePath.Parse("Fuse.exe").Name.ToString(), StringComparison.InvariantCultureIgnoreCase));

            if (fuseExe.HasValue)
            {
                return(baseSearchDir);
            }

            if (baseSearchDir.ContainingDirectory != null)
            {
                return(GetFuseRootWin(baseSearchDir.ContainingDirectory));
            }

            return(Optional.None());
        }
Beispiel #28
0
        public IObservable <FileSystemEventData> Watch(AbsoluteDirectoryPath path, Optional <string> filter = default(Optional <string>))
        {
            return(Observable.Create <FileSystemEventData>(observer =>
            {
                if (!Exists(path))
                {
                    observer.OnError(new FileNotFoundException("Directory not found", path.ContainingDirectory.NativePath));
                    return Disposable.Empty;
                }

                var fsw = filter.Select(f => new FileSystemWatcher(path.NativePath, f)).Or(new FileSystemWatcher(path.NativePath));
                fsw.IncludeSubdirectories = false;
                fsw.NotifyFilter = NotifyFilters.CreationTime
                                   | NotifyFilters.FileName
                                   | NotifyFilters.LastWrite
                                   | NotifyFilters.Size;

                var garbage = Disposable.Combine(
                    fsw,
                    Observable.FromEventPattern <ErrorEventArgs>(fsw, "Error")
                    .Subscribe(_ => observer.OnError(_.EventArgs.GetException())),
                    Observable.FromEventPattern <FileSystemEventArgs>(fsw, "Changed")
                    .Subscribe(e => observer.OnNext(new FileSystemEventData(AbsoluteFilePath.Parse(e.EventArgs.FullPath), FileSystemEvent.Changed))),
                    Observable.FromEventPattern <FileSystemEventArgs>(fsw, "Created")
                    .Subscribe(e => observer.OnNext(new FileSystemEventData(AbsoluteFilePath.Parse(e.EventArgs.FullPath), FileSystemEvent.Created))),
                    Observable.FromEventPattern <RenamedEventArgs>(fsw, "Renamed")
                    .Subscribe(e =>
                {
                    observer.OnNext(new FileSystemEventData(
                                        AbsoluteFilePath.Parse(e.EventArgs.FullPath),
                                        FileSystemEvent.Renamed,
                                        AbsoluteFilePath.Parse(e.EventArgs.OldFullPath)));
                }),
                    Observable.FromEventPattern <FileSystemEventArgs>(fsw, "Deleted")
                    .Subscribe(e => observer.OnNext(new FileSystemEventData(AbsoluteFilePath.Parse(e.EventArgs.FullPath), FileSystemEvent.Removed))));

                fsw.EnableRaisingEvents = true;

                return garbage;
            }));
        }
Beispiel #29
0
        /// <exception cref="FailedToCreateOutputDir"></exception>
        public OutputDirWithLock CreateOrReuseOutputDir(AbsoluteDirectoryPath baseDir)
        {
            try
            {
                const int fileInUse  = 0x20;
                const int fileLocked = 0x21;

                LockFile lockFile = null;
                var      path     = _fileSystem.MakeUnique(baseDir,
                                                           createName: no => baseDir.Rename(MakePathUnique.CreateNumberName(baseDir.Name, no)),
                                                           condition: p =>
                {
                    try
                    {
                        if (!_fileSystem.Exists(p))
                        {
                            _fileSystem.Create(p);
                        }

                        var lockFilePath = p / new FileName(".lock");
                        lockFile         = new LockFile(lockFilePath);
                        return(false);                                // If the file wasn't locked, break creating of unique directories.
                    }
                    catch (IOException e)
                    {
                        var win32ErrorCode = e.HResult & 0xFFFF;
                        if (win32ErrorCode == fileLocked || win32ErrorCode == fileInUse)
                        {
                            return(true);                                    // If the file was locked, continue creating unique directories.
                        }
                        throw;
                    }
                });

                return(new OutputDirWithLock(path, lockFile));
            }
            catch (Exception e)
            {
                throw new FailedToCreateOutputDir(baseDir, e);
            }
        }
Beispiel #30
0
        protected void AssertCode(string code, [CallerMemberName] string path = "")
        {
            int caret = 0;
            var assertCodeSnippets = GetAsserts(ref code, ref caret);

            var ubProject = _project;

            var filePath = AbsoluteDirectoryPath.Parse(Directory.GetCurrentDirectory()) / new FileName(path);

            _log = new DummyLogger();
            var editors     = new DummyEditorManager();
            var mainPackage = new PackageCache(new Log(_log.TextWriter), ubProject.Config).GetPackage(ubProject);

            mainPackage.SetCacheDirectory((AbsoluteDirectoryPath.Parse(mainPackage.CacheDirectory) / new DirectoryName("CodeCompletion")).NativePath);
            var build = new CodeNinjaBuild(_log, ubProject, editors, mainPackage, mainPackage.References.ToList(), code, filePath);

            build.Execute();

            var engine        = new DummyEngine(build.Compiler);
            var codeCompleter = new CodeCompleter(engine.Compiler,
                                                  new Source(build.ProjectPackage, filePath.NativePath),
                                                  new CodeReader(code, caret),
                                                  caret,
                                                  Parser.Parse(code));

            if (codeCompleter.Context.NodePath.Count < 1)
            {
                throw new TestException("Invalid node path was generated for the test case");
            }

            ConfidenceLevel confidenceLevel;
            var             suggestions = codeCompleter.SuggestCompletion("", out confidenceLevel);

            if (assertCodeSnippets != null)
            {
                foreach (var codeSnippet in assertCodeSnippets)
                {
                    OnAssert(code, codeSnippet, suggestions);
                }
            }
        }
 ///<summary>
 ///Try get a new <see cref="IAbsoluteDirectoryPath"/> object from this string.
 ///</summary>
 ///<returns><i>true</i> if <paramref name="pathString"/> is a valid absolute directory path and as a consequence, the returned <paramref name="absoluteDirectoryPath"/> is not null.</returns>
 ///<remarks>The path represented by this string doesn't need to exist for this operation to complete properly.</remarks>
 ///<param name="pathString">Represents the path.</param>
 ///<param name="absoluteDirectoryPath">If this method returns <i>true</i>, this is the returned path object.</param>
 ///<param name="failureReason">If this method returns <i>false</i>, this is the plain english description of the failure.</param>
 public static bool TryGetAbsoluteDirectoryPath(this string pathString, out IAbsoluteDirectoryPath absoluteDirectoryPath, out string failureReason) {
    absoluteDirectoryPath = null;
    if (pathString.IsPathStringNullOrEmpty(out failureReason)) { return false; }
    if (!pathString.IsValidAbsoluteDirectoryPath(out failureReason)) { return false; }
    absoluteDirectoryPath = new AbsoluteDirectoryPath(pathString);
    return true;
 }
Beispiel #32
0
		/// <summary>
		///     Try get a new <see cref="IAbsoluteDirectoryPath" /> object from this string.
		/// </summary>
		/// <returns>
		///     <i>true</i> if <paramref name="path" /> is a valid absolute directory path and as a consequence, the returned
		///     <paramref name="absolutePath" /> is not null.
		/// </returns>
		/// <remarks>The path represented by this string doesn't need to exist for this operation to complete properly.</remarks>
		/// <param name="path">Represents the path.</param>
		/// <param name="absolutePath">If this method returns <i>true</i>, this is the returned path object.</param>
		/// <param name="failureMessage">If this method returns <i>false</i>, this is the plain english description of the failure.</param>
		public static bool TryGetAbsoluteDirectoryPath(this string path, out IAbsoluteDirectoryPath absolutePath, out string failureMessage)
		{
			absolutePath = null;

			if (IsNullOrEmpty(() => path, out failureMessage))
			{
				return false;
			}

			if (!path.IsValidAbsoluteDirectoryPath(out failureMessage))
			{
				return false;
			}

			absolutePath = new AbsoluteDirectoryPath(path);

			return true;
		}