Example #1
0
		public AndroidToolbox (FilePath androidPath, FilePath javaBinPath)
		{
			this.androidToolsPath = androidPath.Combine ("tools");
			this.androidPlatformToolsPath = androidPath.Combine ("platform-tools");
			this.javaBinPath = javaBinPath;
			
			pathOverride = Environment.GetEnvironmentVariable ("PATH");
			if (string.IsNullOrEmpty (pathOverride))
				pathOverride = javaBinPath;
			else
				pathOverride = javaBinPath + Path.PathSeparator + pathOverride;
		}
Example #2
0
		internal static bool ValidateSdkLocation (FilePath location, out FilePath versionPlist)
		{
			versionPlist = location.Combine ("..", "version.plist");
			if (System.IO.File.Exists (versionPlist))
				return true;
			
			versionPlist = location.Combine ("Library", "version.plist");
			if (System.IO.File.Exists (versionPlist))
				return true;
			
			versionPlist = FilePath.Empty;
			return false;
		}
		public virtual string GetDirectoryDotSvn (FilePath path)
		{
			if (Directory.Exists (path.Combine (".svn")))
				return path;

			return String.Empty;
		}
Example #4
0
		static bool ValidatePaths (FilePath xcode, FilePath vplist, FilePath devroot)
		{
			return Directory.Exists (xcode)
				&& Directory.Exists (devroot)
				&& File.Exists (vplist)
				&& File.Exists (xcode.Combine ("Contents", "Info.plist"));
		}
		static FilePath GetPath (XmlElement xmlElement, string attributeName, FilePath baseDirectory)
		{
			string directory = GetAttribute (xmlElement, attributeName, null);
			if (directory == null)
				return FilePath.Null;

			return baseDirectory.Combine (directory).FullPath;
		}
		void CreateGitIgnoreFile (FilePath solutionPath)
		{
			FilePath gitIgnoreFilePath = solutionPath.Combine (".gitignore");
			if (!File.Exists (gitIgnoreFilePath)) {
				FilePath sourceGitIgnoreFilePath = GetSourceGitIgnoreFilePath ();
				File.Copy (sourceGitIgnoreFilePath, gitIgnoreFilePath);
			}
		}
Example #7
0
		public override Repository GetRepositoryReference (FilePath path, string id)
		{
			if (path.IsEmpty || path.ParentDirectory.IsEmpty || path.IsNull || path.ParentDirectory.IsNull)
				return null;
			if (System.IO.Directory.Exists (path.Combine (".git")))
				return new GitRepository (path, null);
			else
				return GetRepositoryReference (path.ParentDirectory, id);
		}
		internal static string GetDirectoryDotSvn (FilePath path)
		{
			if (path.IsEmpty || path.ParentDirectory.IsEmpty || path.IsNull || path.ParentDirectory.IsNull)
				return String.Empty;

			if (Directory.Exists (path.Combine (".svn")))
				return path;

			return GetDirectoryDotSvn (path.ParentDirectory);
		}
		public override Repository GetRepositoryReference (FilePath path, string id)
		{
			if (path.IsEmpty || path.ParentDirectory.IsEmpty || path.IsNull || path.ParentDirectory.IsNull)
				return null;
			if (System.IO.Directory.Exists (path.Combine (".git"))) {
				GitRepository repo;
				if (!repositories.TryGetValue (path.CanonicalPath, out repo))
					repositories [path.CanonicalPath] = repo = new GitRepository (path, null);
				return repo;
			}
			return GetRepositoryReference (path.ParentDirectory, id);
		}
        public void DeleteFolder_EmptyFolderExists(string vPath)
        {
            Assert.NotNull(controller);

            var currentFolder = SetupFoldersHierarchy(vPath);
            var newFolderName = "folderNew";

            currentFolder.CreateFolder(newFolderName);
            Assert.That(currentFolder.FolderExists(newFolderName));

            var actionResult = controller.DeleteFolder(FilePath.Combine(vPath, newFolderName));

            Assert.That(actionResult, Is.AssignableFrom <NoContentResult>());
            var result = (NoContentResult)actionResult;

            Assert.That(result.StatusCode, Is.EqualTo(204));
            Assert.That(currentFolder.FolderExists(newFolderName), Is.False);
        }
        public override void OnNodeDrop(object dataObject, DragOperation operation)
        {
            FilePath targetPath    = ShowAllFilesBuilderExtension.GetFolderPath(CurrentNode.DataItem);
            Project  targetProject = (Project)CurrentNode.GetParentDataItem(typeof(Project), true);
            FilePath source        = ((SystemFile)dataObject).Path;

            targetPath = targetPath.Combine(source.FileName);
            if (targetPath == source)
            {
                targetPath = ProjectOperations.GetTargetCopyName(targetPath, false);
            }

            using (IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor(GettextCatalog.GetString("Copying files..."), Stock.StatusWorking, true))
            {
                bool move = operation == DragOperation.Move;
                IdeApp.ProjectOperations.TransferFiles(monitor, null, source, targetProject, targetPath, move, false);
            }
        }
Example #12
0
        public async Task WatchDirectories_DirectoryDoesNotExist_NoExceptionThrown()
        {
            FilePath rootProject      = Util.GetSampleProject("FileWatcherTest", "Root.csproj");
            var      invalidDirectory = rootProject.Combine("Invalid");
            var      directories      = new [] {
                invalidDirectory
            };

            var id = new object();

            try {
                await FileWatcherService.WatchDirectories(id, directories);

                Assert.IsFalse(Directory.Exists(invalidDirectory));
            } finally {
                await FileWatcherService.WatchDirectories(id, null);
            }
        }
Example #13
0
        protected override FilePath GetDefaultBaseDirectory( )
        {
            // Since solution folders don't are not bound to a specific directory, we have to guess it.
            // First of all try to find a common root of all child projects

            if (ParentSolution == null)
            {
                return(FilePath.Null);
            }

            if (ParentFolder == null)
            {
                return(ParentSolution.BaseDirectory);
            }

            FilePath path = GetCommonPathRoot();

            if (!string.IsNullOrEmpty(path))
            {
                return(path);
            }

            // Now try getting the folder using the folder name

            SolutionFolder folder = this;

            path = FilePath.Empty;
            do
            {
                // Root folder name is ignored
                path   = path.Combine(folder.Name);
                folder = folder.ParentFolder;
            }while (folder.ParentFolder != null);

            path = ParentSolution.BaseDirectory.Combine(path);
            if (!Directory.Exists(path))
            {
                return(ParentFolder.BaseDirectory);
            }
            else
            {
                return(path);
            }
        }
Example #14
0
        public static bool IsPossiblySupported(FilePath path)
        {
            if (path.Extension != dottedExtension)
            {
                return(false);
            }

            if (path.FileExists)
            {
                return(true);
            }

            if (path.DirectoryExists && path.Combine(indexPageFileName).FileExists)
            {
                return(true);
            }

            return(false);
        }
Example #15
0
        public void Directory_Contents()
        {
            var          tmpSrc     = GetNewFileNameOnTempPath("");
            var          tmpSrcInfo = DSCore.IO.Directory.FromPath(tmpSrc);
            const string fileName   = @"temp.txt";
            var          newFile    = FilePath.Combine(tmpSrc, fileName);

            File.WriteText(newFile, "test");

            const string dirName = @"subDir";
            var          newDir  = FilePath.Combine(tmpSrc, dirName);

            Directory.CreateDirectory(newDir);

            var contents = DSCore.IO.Directory.Contents(tmpSrcInfo);

            Assert.AreEqual(new[] { newFile }, contents["files"]);
            Assert.AreEqual(new[] { newDir }, contents["directories"]);
        }
Example #16
0
        public void Directory_Delete()
        {
            var tmpSrc = GetNewFileNameOnTempPath("");

            Directory.CreateDirectory(tmpSrc);
            const string fileName = @"temp.txt";

            File.WriteText(FilePath.Combine(tmpSrc, fileName), "test");

            Assert.Throws <IOException>(() => DSCore.IO.Directory.Delete(tmpSrc));
            DSCore.IO.Directory.Delete(tmpSrc, recursive: true);
            Assert.IsFalse(DSCore.IO.Directory.Exists(tmpSrc));

            var tmpSrc2 = GetNewFileNameOnTempPath("");

            Directory.CreateDirectory(tmpSrc2);
            DSCore.IO.Directory.Delete(tmpSrc2);
            Assert.IsFalse(DSCore.IO.Directory.Exists(tmpSrc2));
        }
Example #17
0
        public bool FolderIsEmpty(string folderName = "")
        {
            var fullPath = FilePath.Combine(RootPath, folderName);
            var dirInfo  = new DirectoryInfo(fullPath);

            if (!dirInfo.Exists)
            {
                throw new InvalidOperationException(string.Format("Folder {0} does not exists.", fullPath));
            }

            if (dirInfo.EnumerateFileSystemInfos().Count() == 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #18
0
        public void Directory_Copy()
        {
            var          tmpSrc     = GetNewFileNameOnTempPath("");
            var          tmpSrcInfo = DSCore.IO.Directory.FromPath(tmpSrc);
            const string fileName   = @"temp.txt";

            File.WriteText(FilePath.Combine(tmpSrc, fileName), "test");

            var tmpDest = GetNewFileNameOnTempPath("");

            DSCore.IO.Directory.Copy(tmpSrcInfo, tmpDest);
            Assert.IsTrue(DSCore.IO.Directory.Exists(tmpSrc));
            Assert.IsTrue(DSCore.IO.Directory.Exists(tmpDest));

            var destFileName = FilePath.Combine(tmpDest, fileName);

            Assert.IsTrue(File.Exists(destFileName));
            Assert.AreEqual("test", File.ReadText(File.FromPath(destFileName)));
        }
        static bool CheckCacheDirectoryIsCorrect(FilePath filename, FilePath candidate, out string result)
        {
            CanonicalizePath(ref filename);
            CanonicalizePath(ref candidate);
            lock (cacheDirectoryCache) {
                CacheDirectoryInfo info;
                if (!cacheDirectoryCache.TryGetValue(candidate, out info))
                {
                    var dataPath = candidate.Combine("data.xml");

                    try {
                        if (!File.Exists(dataPath))
                        {
                            result = null;
                            return(false);
                        }
                        using (var reader = XmlReader.Create(dataPath)) {
                            while (reader.Read())
                            {
                                if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "File")
                                {
                                    info.Version  = reader.GetAttribute("version");
                                    info.FileName = reader.GetAttribute("name");
                                }
                            }
                        }
                        cacheDirectoryCache [candidate] = info;
                    } catch (Exception e) {
                        LoggingService.LogError("Error while reading derived data file " + dataPath, e);
                    }
                }

                if (info.Version == CurrentVersion && info.FileName == filename)
                {
                    result = candidate;
                    return(true);
                }

                result = null;
                return(false);
            }
        }
Example #20
0
        public void Ctor_ShouldCreateEdiorRoot_IfNotExists()
        {
            var rootPath = FilePath.Combine(Directory.GetCurrentDirectory(), "../../../editor-root1");

            if (Directory.Exists(rootPath))
            {
                Directory.Delete(rootPath, true);
            }

            var config = new ExplorerOptions
            {
                EditorRoot        = rootPath,
                CreateIfNotExists = true
            };

            GetPathMapService(config);

            Assert.That(Directory.Exists(rootPath));
            Directory.Delete(rootPath);
        }
Example #21
0
        static List <AssemblyInfo> ScanAssemblyDirectory(TargetFrameworkMoniker tfm, FilePath dir)
        {
            var assemblies = new List <AssemblyInfo> ();

            foreach (var f in Directory.EnumerateFiles(dir, "*.dll"))
            {
                try {
                    var an    = SystemAssemblyService.GetAssemblyNameObj(dir.Combine(f));
                    var ainfo = new AssemblyInfo();
                    ainfo.Update(an);
                    assemblies.Add(ainfo);
                } catch (BadImageFormatException ex) {
                    LoggingService.LogError("Invalid assembly in framework '{0}': {1}{2}{3}", tfm, f, Environment.NewLine, ex.ToString());
                } catch (Exception ex) {
                    LoggingService.LogError("Error reading assembly '{0}' in framework '{1}':{2}{3}",
                                            f, tfm, Environment.NewLine, ex.ToString());
                }
            }
            return(assemblies);
        }
        static IEnumerable <ITestCaseData> GetWorkbookTestCases()
        {
            foreach (var workbook in InTreeWorkbooks)
            {
                yield return new TestCaseData(PathToSaveAndLoad.Combine(workbook).ToString())
                       {
                           TestName = new FilePath(workbook).Name
                       }
            }
            ;

            foreach (var workbook in GetExternalWorkbookTestCases())
            {
                yield return new TestCaseData(workbook.FullPath)
                       {
                           TestName = workbook.Name
                       }
            }
            ;
        }
Example #23
0
        public virtual UpdateInfo GetUpdateInfo()
        {
            var absolutePath = UpdateInfoFile;

            if (absolutePath != null && !absolutePath.IsAbsolute)
            {
#if MAC
                // relative paths are relative the bundle root
                FilePath bundlePath = Foundation.NSBundle.MainBundle.BundlePath;
                absolutePath = bundlePath.Combine(UpdateInfoFile);
#endif
            }

            if (File.Exists(absolutePath))
            {
                return(UpdateInfo.FromFile(absolutePath));
            }

            return(null);
        }
 public override Repository GetRepositoryReference(FilePath path, string id)
 {
     if (path.IsEmpty || path.ParentDirectory.IsEmpty || path.IsNull || path.ParentDirectory.IsNull)
     {
         return(null);
     }
     if (System.IO.Directory.Exists(path.Combine(".git")))
     {
         GitRepository repo;
         if (!repositories.TryGetValue(path.CanonicalPath, out repo))
         {
             repositories [path.CanonicalPath] = repo = new GitRepository(path, null);
         }
         return(repo);
     }
     else
     {
         return(GetRepositoryReference(path.ParentDirectory, id));
     }
 }
Example #25
0
        private TreeEntry RetrieveFromPath(FilePath relativePath)
        {
            if (relativePath.IsNullOrEmpty())
            {
                return(null);
            }

            using (TreeEntrySafeHandle_Owned treeEntryPtr = Proxy.git_tree_entry_bypath(repo.Handle, Id, relativePath))
            {
                if (treeEntryPtr == null)
                {
                    return(null);
                }

                string posixPath  = relativePath.Posix;
                string filename   = posixPath.Split('/').Last();
                string parentPath = posixPath.Substring(0, posixPath.Length - filename.Length);
                return(new TreeEntry(treeEntryPtr, Id, repo, path.Combine(parentPath)));
            }
        }
Example #26
0
        public void Directory_Move()
        {
            var tmpSrc = GetNewFileNameOnTempPath("");

            System.IO.Directory.CreateDirectory(tmpSrc);
            const string fileName = @"temp.txt";

            DSCore.IO.File.WriteText(FilePath.Combine(tmpSrc, fileName), "test");

            var tmpDest = GetNewFileNameOnTempPath("");

            DSCore.IO.Directory.Move(tmpSrc, tmpDest);
            Assert.IsFalse(DSCore.IO.Directory.Exists(tmpSrc));
            Assert.IsTrue(DSCore.IO.Directory.Exists(tmpDest));

            var destFileName = FilePath.Combine(tmpDest, fileName);

            Assert.IsTrue(DSCore.IO.File.Exists(destFileName));
            Assert.AreEqual("test", DSCore.IO.File.ReadText(DSCore.IO.File.FromPath(destFileName)));
        }
Example #27
0
        public async Task UserPreferencesAreMigratedToNewLocation()
        {
            FilePath directory = Util.CreateTmpDir("MigrateUserPreferences");
            var      fileName  = directory.Combine("MigrateUserPreferences.sln");

            var solution = new Solution();

            solution.FileName = fileName;
            solution.UserProperties.SetValue("Test", "Test-Value");

            // Create a user prefs file.
            await solution.SaveAsync(Util.GetMonitor());

            Assert.IsTrue(File.Exists(solution.GetPreferencesFileName()));

            var userPreferencesOldLocationFileName = solution.FileName.ChangeExtension(".userprefs");

            Assert.IsFalse(File.Exists(userPreferencesOldLocationFileName));

            // Create a legacy user prefs file.
            FilePath preferencesFileName = solution.GetPreferencesFileName();

            File.Move(preferencesFileName, userPreferencesOldLocationFileName);

            // Ensure migration handles the missing directory for the new prefs file.
            Directory.Delete(preferencesFileName.ParentDirectory);

            solution = (Solution)await Services.ProjectService.ReadWorkspaceItem(Util.GetMonitor(), fileName);

            Assert.AreEqual("Test-Value", solution.UserProperties.GetValue <string> ("Test"));

            // Change user property and save user prefs.
            solution.UserProperties.SetValue("Test", "Test-Value-Updated");
            await solution.SaveUserProperties();

            Assert.IsFalse(File.Exists(userPreferencesOldLocationFileName));

            solution = (Solution)await Services.ProjectService.ReadWorkspaceItem(Util.GetMonitor(), fileName);

            Assert.AreEqual("Test-Value-Updated", solution.UserProperties.GetValue <string> ("Test"));
        }
Example #28
0
        public ClientWebServer(FilePath clientResourcesBundledBasePath)
        {
            this.clientResourcesBundledBasePath = clientResourcesBundledBasePath;
            this.clientResourcesSourceBasePath  = DevEnvironment.RepositoryRootDirectory;

            if (clientResourcesSourceBasePath.DirectoryExists)
            {
                clientResourcesSourceBasePath = clientResourcesSourceBasePath.Combine(
                    "Xamarin.Interactive.Client", "ClientApp");
            }

            if (!clientResourcesBundledBasePath.IsNull && !clientResourcesBundledBasePath.DirectoryExists)
            {
                throw new DirectoryNotFoundException(clientResourcesSourceBasePath);
            }

            Start();

            AgentIdentificationManager = new AgentIdentificationManager(
                new Uri(BaseUri, "/api/identify"));
        }
Example #29
0
        static ImmutableArray <ResolvedAssembly> Resolve(
            AgentType agentType,
            InteractivePackageManager project,
            FilePath frameworkPath)
        {
            var result    = ImmutableArray <ResolvedAssembly> .Empty;
            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();
            try {
                return(result = new NativeDependencyResolver(agentType)
                                .AddAssemblySearchPath(frameworkPath.Combine("Facades"))
                                .AddAssemblySearchPath(frameworkPath)
                                .Resolve(project.InstalledPackages.SelectMany(
                                             p => p.AssemblyReferences)));
            } finally {
                stopwatch.Stop();
                Console.WriteLine("DependencyResolver.Resolve: {0} in {1}s",
                                  result.Length, stopwatch.Elapsed.TotalSeconds);
            }
        }
Example #30
0
        async Task OpenFolder(FilePath folder)
        {
            FilePath fileName = folder.Combine("." + folder.FileName + ".fws");

            Directory.CreateDirectory(fileName.ParentDirectory);

            if (File.Exists(fileName))
            {
                await IdeApp.Workspace.OpenWorkspaceItem(fileName);

                return;
            }

            var workspace = new Workspace();

            workspace.FileName = fileName;
            await IdeApp.ProjectOperations.SaveAsync(workspace);

            workspace.MarkAsFolder();
            IdeApp.Workspace.Items.Add(workspace);
        }
Example #31
0
        public async Task AllFilesExcludedFromDirectory()
        {
            FilePath projFile         = Util.GetSampleProject("msbuild-glob-tests", "glob-test2.csproj");
            FilePath ignoredDirectory = projFile.ParentDirectory.Combine("ignored");

            Directory.CreateDirectory(ignoredDirectory);
            File.WriteAllText(ignoredDirectory.Combine("c4.cs"), "");
            var p = (DotNetProject)await Services.ProjectService.ReadSolutionItem(Util.GetMonitor(), projFile);

            p.UseAdvancedGlobSupport = true;

            var files = p.Files.Select(f => f.FilePath.FileName).OrderBy(f => f).ToArray();

            Assert.AreEqual(new string [] {
                "c1.cs",
                "c2.cs",
                "c3.cs",
            }, files);

            p.Dispose();
        }
Example #32
0
 protected override void OnSetLocation(FilePath newFilePath, bool isRename = true)
 {
     if (!Directory.Exists((string)newFilePath))
     {
         Directory.CreateDirectory((string)newFilePath);
     }
     foreach (ResourceItem resourceItem in (Collection <ResourceItem>) this.items)
     {
         string str = (string)newFilePath.Combine(new string[1]
         {
             resourceItem.Name
         });
         resourceItem.SetLocation((FilePath)str, isRename);
     }
     if (Directory.Exists((string)this.BaseDirectory) && !isRename)
     {
         this.BaseDirectory.Delete();
     }
     this.BaseDirectory = newFilePath;
     base.OnSetLocation(newFilePath, isRename);
 }
Example #33
0
        public static async Task <DependencyGraphSpec> GetSolutionRestoreSpec(
            Solution solution,
            IEnumerable <BuildIntegratedNuGetProject> projects,
            ConfigurationSelector configuration,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            logger.Log(LogLevel.Information, GettextCatalog.GetString("Getting restore information for solution {0}", solution.FileName));

            using (var inputTargetPath = new TempFile(".nugetinputs.targets"))
                using (var resultsPath = new TempFile(".output.dg")) {
                    var properties = CreateMSBuildProperties(solution, configuration, resultsPath);

                    FilePath msbuildBinDirectory = MSBuildProcessService.GetMSBuildBinDirectory();
                    string   restoreTargetPath   = msbuildBinDirectory.Combine("NuGet.targets");

                    XDocument inputTargetXML = GetRestoreInputFile(restoreTargetPath, properties, projects);
                    inputTargetXML.Save(inputTargetPath);

                    string arguments = GetMSBuildArguments(inputTargetPath, solution);

                    using (var monitor = new LoggingProgressMonitor()) {
                        var process = MSBuildProcessService.StartMSBuild(
                            arguments,
                            solution.BaseDirectory,
                            monitor.Log,
                            monitor.ErrorLog,
                            null);
                        using (process) {
                            process.SetCancellationToken(cancellationToken);
                            await process.Task;
                            if (process.ExitCode != 0)
                            {
                                throw new ApplicationException(GettextCatalog.GetString("MSBuild exited with code {0}", process.ExitCode));
                            }
                        }
                    }
                    return(MSBuildPackageSpecCreator.GetDependencyGraph(resultsPath));
                }
        }
Example #34
0
        public static void ReportUnhandledException(Exception ex, bool willShutDown)
        {
            if (UnhandledErrorOccured != null)
            {
                ReportCrashes = UnhandledErrorOccured(ReportCrashes, ex, willShutDown);
            }

            // If crash reporting has been explicitly disabled, disregard this crash
            if (ReportCrashes.HasValue && !ReportCrashes.Value)
            {
                return;
            }

            byte[] data;
            using (var stream = new MemoryStream()) {
                using (var writer = System.Xml.XmlWriter.Create(stream)) {
                    writer.WriteStartElement("CrashLog");
                    writer.WriteAttributeString("version", ServiceVersion);

                    writer.WriteElementString("SystemInformation", SystemInformation.ToText());
                    writer.WriteElementString("Exception", ex.ToString());

                    writer.WriteEndElement();
                }
                data = stream.ToArray();
            }

            // Log to disk only if uploading fails.
            var filename = string.Format("{0}.{1}.crashlog", SystemInformation.SessionUuid, Interlocked.Increment(ref CrashId));

            if (!TryUploadReport(filename, data))
            {
                if (!Directory.Exists(CrashLogDirectory))
                {
                    Directory.CreateDirectory(CrashLogDirectory);
                }

                File.WriteAllBytes(CrashLogDirectory.Combine(filename), data);
            }
        }
Example #35
0
        async Task <bool> OpenDocumentsInContainer(ProgressMonitor pm, FilePath baseDir, List <Tuple <Document, string> > docViews, List <DocumentUserPrefs> list, DockNotebookContainer container)
        {
            int          currentNotebook = -1;
            DockNotebook nb = container.GetFirstNotebook();

            foreach (var doc in list)
            {
                string fileName = baseDir.Combine(doc.FileName).FullPath;
                if (GetDocument(fileName) == null && File.Exists(fileName))
                {
                    if (doc.NotebookId != currentNotebook)
                    {
                        if (currentNotebook != -1 || nb == null)
                        {
                            nb = container.InsertRight(null);
                        }
                        currentNotebook = doc.NotebookId;
                    }
                    // TODO: Get the correct project.
                    var document = await documentManager.BatchOpenDocument(pm, fileName, null, doc.Line, doc.Column, nb);

                    if (document != null)
                    {
                        try {
                            var tab = ((SdiWorkspaceWindow)document.Window).DockNotebookTab;
                            if (tab != null)
                            {
                                tab.IsPinned = doc.IsPinned;
                            }
                        } catch (Exception ex) {
                            LoggingService.LogInternalError(ex);
                        }

                        var t = new Tuple <Document, string> (document, fileName);
                        docViews.Add(t);
                    }
                }
            }
            return(true);
        }
Example #36
0
        public IActionResult Createfile([FromRoute] string targetPath, [FromForm] string name)
        {
            ValidateRequired(targetPath, nameof(targetPath));
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            targetPath = NormalizeTargetPath(targetPath);
            ValidateTargetPath(targetPath);
            ValidateRequired(name);
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            var localPath = _pathMap.ToLocalPath(targetPath);

            if (!Directory.Exists(localPath))
            {
                return(new NotFoundResult());
            }

            string fullPath = FilePath.Combine(localPath, name);

            //We create file only if it does not exists; existing file is Ok since we do not provide any content at this point
            if (!System.IO.File.Exists(fullPath))
            {
                using (System.IO.File.Create(fullPath)) { }
            }

            return(new CreatedAtRouteResult("GetFile", new { targetPath = _pathMap.ToVirtulPath(fullPath) },
                                            new FileSystemInfoDto()
            {
                Name = name,
                Path = _pathMap.ToVirtulPath(fullPath),
                IsFile = true
            }));
        }
        public void GetFileContent_EmptyFileExists(string vPath)
        {
            Assert.NotNull(controller);

            var currentFolder = SetupFoldersHierarchy(vPath);
            var newFilename   = "newFile.txt";

            currentFolder.CreateFile(newFilename);
            Assert.That(currentFolder.FileExists(newFilename));

            var actionResult = controller.GetFileContent(FilePath.Combine(vPath, newFilename));

            Assert.That(actionResult, Is.AssignableFrom <FileStreamResult>());
            FileStreamResult result = (FileStreamResult)actionResult;

            Assert.That(result.FileStream, Is.Not.Null);
            Assert.That(result.ContentType, Is.EqualTo("text/plain"));
            using (StreamReader reader = new StreamReader(result.FileStream))
            {
                Assert.True(reader.EndOfStream);
            }
        }
		public void CanCreateVariousPaths ()
		{
			FilePath path;
			string expected;

			expected = Path.Combine ("this", "is", "a", "path");
			path = FilePath.Build ("this", "is", "a", "path");
			Assert.AreEqual (expected, path.ToString ());

			expected = "";
			path = FilePath.Empty;
			Assert.AreEqual (expected, path.ToString ());
			Assert.IsTrue (path.IsEmpty);
			Assert.IsTrue (path.IsNullOrEmpty);

			expected = null;
			path = FilePath.Null;
			Assert.AreEqual (expected, path.ToString ());
			Assert.IsTrue (path.IsNull);
			Assert.IsTrue (path.IsNullOrEmpty);

			expected = Path.Combine ("this", "is", "a", "path");
			path = new FilePath (expected);
			Assert.AreEqual (expected, path.ToString ());

			expected = Path.Combine (expected, "and", "more");
			path = path.Combine ("and", "more");
			Assert.AreEqual (expected, path.ToString ());

			expected = "file.txt";
			path = new FilePath ("file").ChangeExtension (".txt");
			Assert.AreEqual (expected, path.ToString ());

			expected = "file.txt";
			path = new FilePath ("file.type").ChangeExtension (".txt");
			Assert.AreEqual (expected, path.ToString ());

			// TODO: Test file:// scheme
		}
        public async Task InstallPackageAsync_MultiTargetPartialInstallNonStandardOriginalFramework_OriginalFrameworkUsedInCondition()
        {
            CreateNuGetProject();
            FilePath projectDirectory = Util.CreateTmpDir("MultiTargetInstallTest");

            dotNetProject.FileName      = projectDirectory.Combine("MultiTargetTest.csproj");
            project.CallBaseSaveProject = true;

            var net472Framework = NuGetFramework.Parse("net472");

            var successfulFrameworks = new NuGetFramework [] {
                net472Framework
            };

            var unsuccessfulFrameworks = new NuGetFramework [] {
                NuGetFramework.Parse("netstandard1.5")
            };

            var originalFrameworks = new Dictionary <NuGetFramework, string> ();

            originalFrameworks [net472Framework] = ".NETFramework4.7.2";

            var installationContext = new BuildIntegratedInstallationContext(
                successfulFrameworks,
                unsuccessfulFrameworks,
                originalFrameworks);

            bool result = await InstallPackageAsync("TestPackage", "2.6.1", installationContext);

            var packageReference = dotNetProject
                                   .MSBuildProject
                                   .GetAllItems()
                                   .SingleOrDefault(item => item.Include == "TestPackage");

            Assert.AreEqual("'$(TargetFramework)' == '.NETFramework4.7.2'", packageReference.ParentGroup.Condition);
            Assert.AreEqual(packageReference.Metadata.GetValue("Version"), "2.6.1");
            Assert.IsTrue(result);
            Assert.IsTrue(project.IsSaved);
        }
        public void GetFileContent_NonEmptyFileExist(string vPath)
        {
            Assert.NotNull(controller);

            var currentFolder = SetupFoldersHierarchy(vPath);
            var newFilename   = "newFile.txt";

            System.Text.StringBuilder contentBuilder = new System.Text.StringBuilder();
            var       linePattern = "at line{0}: some initial content";
            const int lineCount   = 10;

            for (int i = 1; i <= lineCount; i++)
            {
                contentBuilder.AppendFormat(linePattern, i);
                contentBuilder.Append("\n");
            }

            currentFolder.CreateFileWithContent(newFilename, contentBuilder.ToString());
            Assert.That(currentFolder.FileExists(newFilename));

            var actionResult = controller.GetFileContent(FilePath.Combine(vPath, newFilename));

            Assert.That(actionResult, Is.AssignableFrom <FileStreamResult>());
            var result = (FileStreamResult)actionResult;

            Assert.That(result.FileStream, Is.Not.Null);
            Assert.That(result.ContentType, Is.EqualTo("text/plain"));
            using (StreamReader reader = new StreamReader(result.FileStream))
            {
                int linesRead = 0;
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    linesRead++;
                    Assert.That(line, Is.EqualTo(string.Format(linePattern, linesRead)));
                }
                Assert.That(linesRead, Is.EqualTo(lineCount));
            }
        }
		bool RegisterRedistAssemblies (FilePath location)
		{
			var info = new SystemPackageInfo () {
				Name = "moonlight-web-" + fxVersion + "-redist",
				Description = "Moonlight " + fxVersion + " Redistributable Assemblies",
				Version = pluginVersion,
				IsFrameworkPackage = true,
				IsGacPackage = false,
				IsCorePackage = false,
				TargetFramework = framework.Id,
			};
			var dir = location.Combine (fxVersion + "-redist");
			try {
				var files = Directory.GetFiles (dir, "*.dll");
				runtime.RegisterPackage (info, files);
				return true;
			} catch (IOException ex) {
				LoggingService.LogError ("Could not enumerate redist assemblies from directory '" + dir + "'", ex);
				return false;
			}
		}
Example #42
0
		static bool FallbackProbeDirectoryDotSvn (FilePath path)
		{
			while (!path.IsNullOrEmpty) {
				if (Directory.Exists (path.Combine (".svn")))
					return true;
				path = path.ParentDirectory;
			}
			return false;
		}
		static string GetExeLocation (TargetRuntime runtime, string toolsVersion, bool requiresMicrosoftBuild)
		{
			var builderDir = new FilePath (typeof(MSBuildProjectService).Assembly.Location).ParentDirectory.Combine ("MSBuild");

			var version = Version.Parse (toolsVersion);
			bool useMicrosoftBuild = 
				requiresMicrosoftBuild ||
				((version >= new Version (15, 0)) && Runtime.Preferences.BuildWithMSBuild) ||
				(version >= new Version (4, 0) && runtime is MsNetTargetRuntime);

			if (useMicrosoftBuild) {
				toolsVersion = "dotnet." + (version >= new Version (15, 0) ? "14.1" : toolsVersion);
			}

			var exe = builderDir.Combine (toolsVersion, "MonoDevelop.Projects.Formats.MSBuild.exe");
			if (File.Exists (exe))
				return exe;
			
			throw new InvalidOperationException ("Unsupported MSBuild ToolsVersion '" + version + "'");
		}
Example #44
0
		static void RedirectOutputToFileWindows (FilePath logDirectory)
		{
			// First try to move any generic MonoDevelop.log files to a timestamped filename
			foreach (var path in GetGenericLogFiles (logDirectory)) {
				try {
					var creationTime = File.GetCreationTime (path);
					var destination = logDirectory.Combine (FormattedUniqueFileName (creationTime));
					File.Copy (path, destination, true);
					File.Delete (path);
				} catch {}
			}

			// Find the first free filename, try MonoDevelop.log first and then MonoDevelop-{0}.log
			int count = 0;
			var newLogFileName = GenericLogFile;
			var existingFiles = GetGenericLogFiles (logDirectory).Select (f => Path.GetFileName (f)).ToList ();
			while (existingFiles.Contains (newLogFileName))
				newLogFileName = FormattedGenericLogFile (count ++);

			var logFile = new StreamWriter (logDirectory.Combine (newLogFileName));
			logFile.AutoFlush = true;
			Console.SetOut (logFile);
			Console.SetError (logFile);
		}
Example #45
0
		public void TransferFiles (IProgressMonitor monitor, Project sourceProject, FilePath sourcePath, Project targetProject,
		                           FilePath targetPath, bool removeFromSource, bool copyOnlyProjectFiles)
		{
			// When transfering directories, targetPath is the directory where the source
			// directory will be transfered, including the destination directory or file name.
			// For example, if sourcePath is /a1/a2/a3 and targetPath is /b1/b2, the
			// new folder or file will be /b1/b2
			
			if (targetProject == null)
				throw new ArgumentNullException ("targetProject");

			if (!targetPath.IsChildPathOf (targetProject.BaseDirectory))
				throw new ArgumentException ("Invalid project folder: " + targetPath);

			if (sourceProject != null && !sourcePath.IsChildPathOf (sourceProject.BaseDirectory))
				throw new ArgumentException ("Invalid project folder: " + sourcePath);
				
			if (copyOnlyProjectFiles && sourceProject == null)
				throw new ArgumentException ("A source project must be specified if copyOnlyProjectFiles is True");
			
			bool sourceIsFolder = Directory.Exists (sourcePath);

			bool movingFolder = (removeFromSource && sourceIsFolder && (
					!copyOnlyProjectFiles ||
					IsDirectoryHierarchyEmpty (sourcePath)));

			// We need to remove all files + directories from the source project
			// but when dealing with the VCS addins we need to process only the
			// files so we do not create a 'file' in the VCS which corresponds
			// to a directory in the project and blow things up.
			List<ProjectFile> filesToRemove = null;
			List<ProjectFile> filesToMove = null;
			try {
				//get the real ProjectFiles
				if (sourceProject != null) {
					if (sourceIsFolder) {
						var virtualPath = sourcePath.ToRelative (sourceProject.BaseDirectory);
						// Grab all the child nodes of the folder we just dragged/dropped
						filesToRemove = sourceProject.Files.GetFilesInVirtualPath (virtualPath).ToList ();
						// Add the folder itself so we can remove it from the soruce project if its a Move operation
						var folder = sourceProject.Files.Where (f => f.ProjectVirtualPath == virtualPath).FirstOrDefault ();
						if (folder != null)
							filesToRemove.Add (folder);
					} else {
						filesToRemove = new List<ProjectFile> ();
						var pf = sourceProject.Files.GetFileWithVirtualPath (sourceProject.GetRelativeChildPath (sourcePath));
						if (pf != null)
							filesToRemove.Add (pf);
					}
				}
				//get all the non-project files and create fake ProjectFiles
				if (!copyOnlyProjectFiles || sourceProject == null) {
					var col = new List<ProjectFile> ();
					GetAllFilesRecursive (sourcePath, col);
					if (sourceProject != null) {
						var names = new HashSet<string> (filesToRemove.Select (f => sourceProject.BaseDirectory.Combine (f.ProjectVirtualPath).ToString ()));
						foreach (var f in col)
							if (names.Add (f.Name))
							    filesToRemove.Add (f);
					} else {
						filesToRemove = col;
					}
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Could not get any file from '{0}'.", sourcePath), ex);
				return;
			}
			
			// Strip out all the directories to leave us with just the files.
			filesToMove = filesToRemove.Where (f => f.Subtype != Subtype.Directory).ToList ();
			
			// If copying a single file, bring any grouped children along
			ProjectFile sourceParent = null;
			if (filesToMove.Count == 1 && sourceProject != null) {
				var pf = filesToMove[0];
				if (pf != null && pf.HasChildren)
					foreach (ProjectFile child in pf.DependentChildren)
						filesToMove.Add (child);
				sourceParent = pf;
			}
			
			// Ensure that the destination folder is created, even if no files
			// are copied
			
			try {
				if (sourceIsFolder && !Directory.Exists (targetPath) && !movingFolder)
					FileService.CreateDirectory (targetPath);
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Could not create directory '{0}'.", targetPath), ex);
				return;
			}

			// Transfer files
			// If moving a folder, do it all at once
			
			if (movingFolder) {
				try {
					FileService.MoveDirectory (sourcePath, targetPath);
				} catch (Exception ex) {
					monitor.ReportError (GettextCatalog.GetString ("Directory '{0}' could not be moved.", sourcePath), ex);
					return;
				}
			}
			
			monitor.BeginTask (GettextCatalog.GetString ("Copying files..."), filesToMove.Count);
			
			ProjectFile targetParent = null;
			foreach (ProjectFile file in filesToMove) {
				bool fileIsLink = file.Project != null && file.IsLink;
				
				var sourceFile = fileIsLink
					? file.Project.BaseDirectory.Combine (file.ProjectVirtualPath)
					: file.FilePath;
				
				FilePath newFile;
				if (sourceIsFolder)
					newFile = targetPath.Combine (sourceFile.ToRelative (sourcePath));
				else if (sourceFile == sourcePath)
					newFile = targetPath;
				else if (sourceFile.ParentDirectory != targetPath.ParentDirectory)
					newFile = targetPath.ParentDirectory.Combine (sourceFile.ToRelative (sourcePath.ParentDirectory));
				else
					newFile = GetTargetCopyName (sourceFile, false);
				
				if (!movingFolder && !fileIsLink) {
					try {
						FilePath fileDir = newFile.ParentDirectory;
						if (!Directory.Exists (fileDir) && !file.IsLink)
							FileService.CreateDirectory (fileDir);
						if (removeFromSource)
							FileService.MoveFile (sourceFile, newFile);
						else
							FileService.CopyFile (sourceFile, newFile);
					} catch (Exception ex) {
						monitor.ReportError (GettextCatalog.GetString ("File '{0}' could not be created.", newFile), ex);
						monitor.Step (1);
						continue;
					}
				}
				
				if (sourceProject != null) {
					if (fileIsLink) {
						var linkFile = (ProjectFile) file.Clone ();
						if (movingFolder) {
							var abs = linkFile.Link.ToAbsolute (sourceProject.BaseDirectory);
							var relSrc = abs.ToRelative (sourcePath);
							var absTarg = relSrc.ToAbsolute (targetPath);
							linkFile.Link = absTarg.ToRelative (targetProject.BaseDirectory);
						} else {
							linkFile.Link = newFile.ToRelative (targetProject.BaseDirectory);
						}
						targetProject.Files.Add (linkFile);
					} else if (targetProject.Files.GetFile (newFile) == null) {
						ProjectFile projectFile = (ProjectFile) file.Clone ();
						projectFile.Name = newFile;
						if (targetParent == null) {
							if (file == sourceParent)
								targetParent = projectFile;
						} else if (sourceParent != null) {
							if (projectFile.DependsOn == sourceParent.Name)
								projectFile.DependsOn = targetParent.Name;
						}
						targetProject.Files.Add (projectFile);
					}
				}
				
				monitor.Step (1);
			}
			
			if (removeFromSource) {
				// Remove all files and directories under 'sourcePath'
				foreach (var v in filesToRemove)
					sourceProject.Files.Remove (v);
			}
			
			var pfolder = sourcePath.ParentDirectory;
			
			// If this was the last item in the folder, make sure we keep
			// a reference to the folder, so it is not deleted from the tree.
			if (removeFromSource && sourceProject != null && pfolder.CanonicalPath != sourceProject.BaseDirectory.CanonicalPath && pfolder.IsChildPathOf (sourceProject.BaseDirectory)) {
				pfolder = pfolder.ToRelative (sourceProject.BaseDirectory);
				if (!sourceProject.Files.GetFilesInVirtualPath (pfolder).Any ()) {
					var folderFile = new ProjectFile (sourceProject.BaseDirectory.Combine (pfolder));
					folderFile.Subtype = Subtype.Directory;
					sourceProject.Files.Add (folderFile);
				}
			}
			
			monitor.EndTask ();
		}
        protected void CreateReference(FilePath sPath)
        {
            // Get the resource and write it out?
            FilePath sFileName = sPath.Combine("MonoBrickFirmware.dll");

            FileStream OutputStream = new FileStream(sFileName, FileMode.Create);
            Assembly ass = Assembly.GetExecutingAssembly();

            Stream DBStream = ass.GetManifestResourceStream("MonoBrick.MonoBrickFirmware.dll");
            for (int l = 0; l < DBStream.Length; l++)
            {
                OutputStream.WriteByte((byte)DBStream.ReadByte());
            }
            OutputStream.Close();
        }
Example #47
0
		public static TargetFramework FromFrameworkDirectory (TargetFrameworkMoniker moniker, FilePath dir)
		{
			var fxList = dir.Combine ("RedistList", "FrameworkList.xml");
			if (!File.Exists (fxList))
				return null;
			
			var fx = new TargetFramework (moniker);
			
			using (var reader = System.Xml.XmlReader.Create (fxList)) {
				if (!reader.ReadToDescendant ("FileList"))
					throw new Exception ("Missing FileList element");
				
				//not sure what this is for
				//if (reader.MoveToAttribute ("Redist") && reader.ReadAttributeValue ())
				//	redist = reader.ReadContentAsString ();
				
				if (reader.MoveToAttribute ("Name") && reader.ReadAttributeValue ())
					fx.name = reader.ReadContentAsString ();
				
				if (reader.MoveToAttribute ("RuntimeVersion") && reader.ReadAttributeValue ()) {
					string runtimeVersion = reader.ReadContentAsString ();
					switch (runtimeVersion) {
					case "2.0":
						fx.clrVersion = ClrVersion.Net_2_0;
						break;
					case "4.0":
						fx.clrVersion = ClrVersion.Net_4_0;
						break;
					case "4.5":
					case "4.5.1":
						fx.clrVersion = ClrVersion.Net_4_5;
						break;
					default:
						LoggingService.LogInfo ("Framework {0} has unknown RuntimeVersion {1}", moniker, runtimeVersion);
						return null;
					}
				}
				
				if (reader.MoveToAttribute ("ToolsVersion") && reader.ReadAttributeValue ()) {
					string toolsVersion = reader.ReadContentAsString ();
					switch (toolsVersion) {
					case "2.0":
						fx.toolsVersion = TargetFrameworkToolsVersion.V2_0;
						break;
					case "3.5":
						fx.toolsVersion = TargetFrameworkToolsVersion.V3_5;
						break;
					case "4.0":
						fx.toolsVersion = TargetFrameworkToolsVersion.V4_0;
						break;
					case "4.5":
						fx.toolsVersion = TargetFrameworkToolsVersion.V4_5;
						break;
					default:
						LoggingService.LogInfo ("Framework {0} has unknown ToolsVersion {1}", moniker, toolsVersion);
						return null;
					}
				}
				
				if (reader.MoveToAttribute ("IncludeFramework") && reader.ReadAttributeValue ()) {
					string include = reader.ReadContentAsString ();
					if (!string.IsNullOrEmpty (include)) {
						fx.IncludedFrameworks.Add (new TargetFrameworkMoniker (fx.Id.Identifier, include));
					}
				}
				
				//this is a Mono-specific extension
				if (reader.MoveToAttribute ("TargetFrameworkDirectory") && reader.ReadAttributeValue ()) {
					string targetDir = reader.ReadContentAsString ();
					if (!string.IsNullOrEmpty (targetDir)) {
						targetDir = targetDir.Replace ('\\', System.IO.Path.DirectorySeparatorChar);
						dir = fxList.ParentDirectory.Combine (targetDir).FullPath;
					}
				}
				
				var assemblies = new List<AssemblyInfo> ();
				if (reader.ReadToFollowing ("File")) {
					do {
						var ainfo = new AssemblyInfo ();
						assemblies.Add (ainfo);
						if (reader.MoveToAttribute ("AssemblyName") && reader.ReadAttributeValue ())
							ainfo.Name = reader.ReadContentAsString ();
						if (string.IsNullOrEmpty (ainfo.Name))
							throw new Exception ("Missing AssemblyName attribute");
						if (reader.MoveToAttribute ("Version") && reader.ReadAttributeValue ())
							ainfo.Version = reader.ReadContentAsString ();
						if (reader.MoveToAttribute ("PublicKeyToken") && reader.ReadAttributeValue ())
							ainfo.PublicKeyToken = reader.ReadContentAsString ();
						if (reader.MoveToAttribute ("Culture") && reader.ReadAttributeValue ())
							ainfo.Culture = reader.ReadContentAsString ();
						if (reader.MoveToAttribute ("ProcessorArchitecture") && reader.ReadAttributeValue ())
							ainfo.ProcessorArchitecture = (ProcessorArchitecture)
								Enum.Parse (typeof (ProcessorArchitecture), reader.ReadContentAsString (), true);
						if (reader.MoveToAttribute ("InGac") && reader.ReadAttributeValue ())
							ainfo.InGac = reader.ReadContentAsBoolean ();
					} while (reader.ReadToFollowing ("File"));
				} else {

					// HACK: we were using EnumerateFiles but it's broken in some Mono releases
					// https://bugzilla.xamarin.com/show_bug.cgi?id=2975
					var files = System.IO.Directory.GetFiles (dir, "*.dll");
					foreach (var f in files) {
						try {
							var an = SystemAssemblyService.GetAssemblyNameObj (dir.Combine (f));
							var ainfo = new AssemblyInfo ();
							ainfo.Update (an);
							assemblies.Add (ainfo);
						} catch (Exception ex) {
							LoggingService.LogError ("Error reading name for assembly '{0}' in framework '{1}':\n{2}",
								f, fx.Id, ex.ToString ());
						}
					}
				}
				
				fx.Assemblies = assemblies.ToArray ();
			}
			
			var supportedFrameworksDir = dir.Combine ("SupportedFrameworks");
			if (Directory.Exists (supportedFrameworksDir)) {
				foreach (var sfx in Directory.GetFiles (supportedFrameworksDir))
					fx.SupportedFrameworks.Add (SupportedFramework.Load (fx, sfx));
			}
			
			return fx;
		}
		static void RedirectOutputToFileUnix (FilePath logDirectory, string logName)
		{
			const int STDOUT_FILENO = 1;
			const int STDERR_FILENO = 2;
			
			Mono.Unix.Native.OpenFlags flags = Mono.Unix.Native.OpenFlags.O_WRONLY
				| Mono.Unix.Native.OpenFlags.O_CREAT | Mono.Unix.Native.OpenFlags.O_TRUNC;
			var mode = Mono.Unix.Native.FilePermissions.S_IFREG
				| Mono.Unix.Native.FilePermissions.S_IRUSR | Mono.Unix.Native.FilePermissions.S_IWUSR
				| Mono.Unix.Native.FilePermissions.S_IRGRP | Mono.Unix.Native.FilePermissions.S_IWGRP;
			
			var file = logDirectory.Combine (logName);
			int fd = Mono.Unix.Native.Syscall.open (file, flags, mode);
			if (fd < 0)
				//error
				return;
			try {
				int res = Mono.Unix.Native.Syscall.dup2 (fd, STDOUT_FILENO);
				if (res < 0)
					//error
					return;
				
				res = Mono.Unix.Native.Syscall.dup2 (fd, STDERR_FILENO);
				if (res < 0)
					//error
					return;

				var genericLog = logDirectory.Combine (GenericLogFile);
				File.Delete (genericLog);
				Mono.Unix.Native.Syscall.symlink (file, genericLog);
			} finally {
				Mono.Unix.Native.Syscall.close (fd);
			}
		}
Example #49
0
		static void CopyDirectoryRec (IProgressMonitor monitor, FilePath src, FilePath target, FilePath targetRoot)
		{
			Directory.CreateDirectory (target);
			foreach (FilePath file in Directory.GetFiles (src)) {
				if (monitor.IsCancelRequested)
					return;
				var t = target.Combine (file.FileName);
				monitor.Log.WriteLine (t.ToRelative (targetRoot));
				File.Copy (file, t);
			}
			foreach (FilePath dir in Directory.GetDirectories (src)) {
				CopyDirectoryRec (monitor, dir, target.Combine (dir.FileName), targetRoot);
			}
		}
Example #50
0
		VersionInfo[] GetDirectoryVersionInfo (FilePath localDirectory, string fileName, bool getRemoteStatus, bool recursive)
		{
			StringReader sr = RunCommand ("log -1 --format=format:%H", true);
			string strRev = sr.ReadLine ();
			sr.Close ();
			
			HashSet<FilePath> existingFiles = new HashSet<FilePath> ();
			if (fileName != null) {
				FilePath fp = localDirectory.Combine (fileName).CanonicalPath;
				if (File.Exists (fp))
					existingFiles.Add (fp);
			} else
				CollectFiles (existingFiles, localDirectory, recursive);
			
			GitRevision rev = new GitRevision (this, strRev);
			List<VersionInfo> versions = new List<VersionInfo> ();
			FilePath p = fileName != null ? localDirectory.Combine (fileName) : localDirectory;
			sr = RunCommand ("status -s " + ToCmdPath (p), true);
			string line;
			while ((line = sr.ReadLine ()) != null) {
				char staged = line[0];
				char nostaged = line[1];
				string file = line.Substring (3);
				FilePath srcFile = FilePath.Null;
				int i = file.IndexOf ("->");
				if (i != -1) {
					srcFile = path.Combine (file.Substring (0, i - 1));
					file = file.Substring (i + 3);
				}
				FilePath statFile = path.Combine (file);
				if (statFile.ParentDirectory != localDirectory && (!statFile.IsChildPathOf (localDirectory) || !recursive))
					continue;
				VersionStatus status;
				if (staged == 'M' || nostaged == 'M')
					status = VersionStatus.Versioned | VersionStatus.Modified;
				else if (staged == 'A')
					status = VersionStatus.Versioned | VersionStatus.ScheduledAdd;
				else if (staged == 'D' || nostaged == 'D')
					status = VersionStatus.Versioned | VersionStatus.ScheduledDelete;
				else if (staged == 'U' || nostaged == 'U')
					status = VersionStatus.Versioned | VersionStatus.Conflicted;
				else if (staged == 'R') {
					// Renamed files are in reality files delete+added to a different location.
					existingFiles.Remove (srcFile.CanonicalPath);
					VersionInfo rvi = new VersionInfo (srcFile, "", false, VersionStatus.Versioned | VersionStatus.ScheduledDelete, rev, VersionStatus.Versioned, null);
					versions.Add (rvi);
					status = VersionStatus.Versioned | VersionStatus.ScheduledAdd;
				}
				else
					status = VersionStatus.Unversioned;
				
				existingFiles.Remove (statFile.CanonicalPath);
				VersionInfo vi = new VersionInfo (statFile, "", false, status, rev, VersionStatus.Versioned, null);
				versions.Add (vi);
			}
			
			// Files for which git did not report an status are supposed to be tracked
			foreach (FilePath file in existingFiles) {
				VersionInfo vi = new VersionInfo (file, "", false, VersionStatus.Versioned, rev, VersionStatus.Versioned, null);
				versions.Add (vi);
			}
			
			return versions.ToArray ();
		}
Example #51
0
		/// <summary>
		/// Returns true if the folder is in a case sensitive file system
		/// </summary>
		public static bool IsFolderCaseSensitive (FilePath path)
		{
			var testFile = path.Combine (Guid.NewGuid ().ToString ().ToLower ());
			try {
				File.WriteAllText (testFile, "");
				return !File.Exists (testFile.ToString ().ToUpper ());
			} catch (Exception ex) {
				// Don't crashh
				LoggingService.LogError ("IsFolderCaseSensitive failed", ex);
				return false;
			} finally {
				File.Delete (testFile);
			}
		}
        static void CreateFileFromTemplate(Project project, SolutionItem policyItem, FilePath templateSourceDirectory, string fileTemplateName)
        {
            string templateFileName = templateSourceDirectory.Combine (fileTemplateName + ".xft.xml");
            using (Stream stream = File.OpenRead (templateFileName)) {
                var document = new XmlDocument ();
                document.Load (stream);

                foreach (XmlElement templateElement in document.DocumentElement["TemplateFiles"].ChildNodes.OfType<XmlElement> ()) {
                    var template = FileDescriptionTemplate.CreateTemplate (templateElement, templateSourceDirectory);
                    template.AddToProject (policyItem, project, "C#", project.BaseDirectory, null);
                }
            }
        }
Example #53
0
		public GitRepository (FilePath path, string url)
		{
			RootPath = path;
			RootRepository = new LocalGitRepository (path.Combine (Constants.DOT_GIT));
			Url = url;
		}
		protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, ProgressMonitor monitor)
		{
			// Initialize the repository
			RootRepository = new LibGit2Sharp.Repository (LibGit2Sharp.Repository.Init (localPath));
			RootPath = localPath;
			RootRepository.Network.Remotes.Add ("origin", Url);

			// Add the project files
			ChangeSet cs = CreateChangeSet (localPath);
			foreach (FilePath fp in files) {
				RootRepository.Stage (RootRepository.ToGitPath (fp));
				cs.AddFile (fp);
			}

			// Create the initial commit
			cs.GlobalComment = message;
			Commit (cs, monitor);

			RootRepository.Branches.Update (RootRepository.Branches ["master"], branch => branch.TrackedBranch = "refs/remotes/origin/master");

			RetryUntilSuccess (monitor, credType => RootRepository.Network.Push (RootRepository.Head, new PushOptions {
				OnPushStatusError = delegate (PushStatusError e) {
					RootRepository.Dispose ();
					RootRepository = null;
					if (RootPath.Combine (".git").IsDirectory)
						Directory.Delete (RootPath.Combine (".git"), true);
					throw new VersionControlException (e.Message);
				},
				CredentialsProvider = (url, userFromUrl, types) => GitCredentials.TryGet (url, userFromUrl, types, credType)
			}));

			return this;
		}
		/// <summary>
		/// Creates locations in a specific folder, for testing.
		/// </summary>
		internal static UserProfile ForTest (string version, FilePath profileLocation)
		{
			string appId = APP_ID + "-" + version;
			return new UserProfile () {
				CacheDir = profileLocation.Combine (appId, "Cache"),
				UserDataRoot = profileLocation.Combine (appId, "UserData"),
				ConfigDir = profileLocation.Combine (appId, "Config"),
				LocalConfigDir = profileLocation.Combine (appId, "LocalConfig"),
				LogDir = profileLocation.Combine (appId, "Logs"),
				LocalInstallDir = profileLocation.Combine (appId, "LocalInstall"),
				TempDir = profileLocation.Combine (appId, "Temp"),
			};
		}
Example #56
0
		static IEnumerable<MSBuildItemEvaluated> ExpandWildcardFilePath (ProjectInfo pinfo, MSBuildProject project, MSBuildEvaluationContext context, MSBuildItem sourceItem, FilePath basePath, FilePath baseRecursiveDir, bool recursive, string[] filePath, int index)
		{
			var res = Enumerable.Empty<MSBuildItemEvaluated> ();

			if (index >= filePath.Length)
				return res;

			var path = filePath [index];

			if (path == "..")
				return ExpandWildcardFilePath (pinfo, project, context, sourceItem, basePath.ParentDirectory, baseRecursiveDir, recursive, filePath, index + 1);
			
			if (path == ".")
				return ExpandWildcardFilePath (pinfo, project, context, sourceItem, basePath, baseRecursiveDir, recursive, filePath, index + 1);

			if (!Directory.Exists (basePath))
				return res;

			if (path == "**") {
				// if this is the last component of the path, there isn't any file specifier, so there is no possible match
				if (index + 1 >= filePath.Length)
					return res;
				
				// If baseRecursiveDir has already been set, don't overwrite it.
				if (baseRecursiveDir.IsNullOrEmpty)
					baseRecursiveDir = basePath;
				
				return ExpandWildcardFilePath (pinfo, project, context, sourceItem, basePath, baseRecursiveDir, true, filePath, index + 1);
			}

			if (recursive) {
				// Recursive search. Try to match the remaining subpath in all subdirectories.
				foreach (var dir in Directory.GetDirectories (basePath))
					res = res.Concat (ExpandWildcardFilePath (pinfo, project, context, sourceItem, dir, baseRecursiveDir, true, filePath, index));
			}

			if (index == filePath.Length - 1) {
				// Last path component. It has to be a file specifier.
				string baseDir = basePath.ToRelative (project.BaseDirectory).ToString().Replace ('/','\\');
				if (baseDir == ".")
					baseDir = "";
				else if (!baseDir.EndsWith ("\\", StringComparison.Ordinal))
					baseDir += '\\';
				var recursiveDir = baseRecursiveDir.IsNullOrEmpty ? FilePath.Null : basePath.ToRelative (baseRecursiveDir);
				res = res.Concat (Directory.GetFiles (basePath, path).Select (f => {
					context.SetItemContext (f, recursiveDir);
					var ev = baseDir + Path.GetFileName (f);
					return CreateEvaluatedItem (context, pinfo, project, sourceItem, ev);
				}));
			}
			else {
				// Directory specifier
				// Look for matching directories.
				// The search here is non-recursive, not matter what the 'recursive' parameter says, since we are trying to match a subpath.
				// The recursive search is done below.

				if (path.IndexOfAny (wildcards) != -1) {
					foreach (var dir in Directory.GetDirectories (basePath, path))
						res = res.Concat (ExpandWildcardFilePath (pinfo, project, context, sourceItem, dir, baseRecursiveDir, false, filePath, index + 1));
				} else
					res = res.Concat (ExpandWildcardFilePath (pinfo, project, context, sourceItem, basePath.Combine (path), baseRecursiveDir, false, filePath, index + 1));
			}

			return res;
		}
Example #57
0
		public IList<ProjectFile> AddFilesToProject (Project project, FilePath[] files, FilePath targetDirectory,
			string buildAction)
		{
			Debug.Assert (targetDirectory.CanonicalPath == project.BaseDirectory.CanonicalPath
				|| targetDirectory.IsChildPathOf (project.BaseDirectory));
			
			var targetPaths = new FilePath[files.Length];
			for (int i = 0; i < files.Length; i++)
				targetPaths[i] = targetDirectory.Combine (files[i].FileName);
			
			return AddFilesToProject (project, files, targetPaths, buildAction);
		}
Example #58
0
		public static TargetFramework FromFrameworkDirectory (TargetFrameworkMoniker moniker, FilePath dir)
		{
			var fxList = dir.Combine ("RedistList", "FrameworkList.xml");
			if (!File.Exists (fxList))
				return null;
			
			var fx = new TargetFramework (moniker);
			
			using (var reader = System.Xml.XmlReader.Create (fxList)) {
				if (!reader.ReadToDescendant ("FileList"))
					throw new Exception ("Missing FileList element");
				
				//not sure what this is for
				//if (reader.MoveToAttribute ("Redist") && reader.ReadAttributeValue ())
				//	redist = reader.ReadContentAsString ();
				
				if (reader.MoveToAttribute ("Name") && reader.ReadAttributeValue ())
					fx.name = reader.ReadContentAsString ();
				
				if (reader.MoveToAttribute ("RuntimeVersion") && reader.ReadAttributeValue ()) {
					string runtimeVersion = reader.ReadContentAsString ();
					switch (runtimeVersion) {
					case "2.0":
						fx.clrVersion = ClrVersion.Net_2_0;
						break;
					case "4.0":
						fx.clrVersion = ClrVersion.Net_4_0;
						break;
					//The concept of "ClrVersion" breaks down hard after 4.5 and is essentially meaningless
					default:
						fx.clrVersion = ClrVersion.Net_4_5;
						break;
					}
				}
				
				if (reader.MoveToAttribute ("ToolsVersion") && reader.ReadAttributeValue ()) {
					string toolsVersion = reader.ReadContentAsString ();
					switch (toolsVersion) {
					case "2.0":
						fx.toolsVersion = TargetFrameworkToolsVersion.V2_0;
						break;
					case "3.5":
						fx.toolsVersion = TargetFrameworkToolsVersion.V3_5;
						break;
					case "4.0":
						fx.toolsVersion = TargetFrameworkToolsVersion.V4_0;
						break;
					case "4.5":
						fx.toolsVersion = TargetFrameworkToolsVersion.V4_5;
						break;
					default:
						LoggingService.LogInfo ("Framework {0} has unknown ToolsVersion {1}", moniker, toolsVersion);
						return null;
					}
				}
				
				if (reader.MoveToAttribute ("IncludeFramework") && reader.ReadAttributeValue ()) {
					string include = reader.ReadContentAsString ();
					if (!string.IsNullOrEmpty (include))
						fx.includesFramework = include;
				}
				
				//this is a Mono-specific extension
				if (reader.MoveToAttribute ("TargetFrameworkDirectory") && reader.ReadAttributeValue ()) {
					string targetDir = reader.ReadContentAsString ();
					if (!string.IsNullOrEmpty (targetDir)) {
						targetDir = targetDir.Replace ('\\', System.IO.Path.DirectorySeparatorChar);
						dir = fxList.ParentDirectory.Combine (targetDir).FullPath;
					}
				}
				
				var assemblies = new List<AssemblyInfo> ();
				if (reader.ReadToFollowing ("File")) {
					do {
						var ainfo = new AssemblyInfo ();
						assemblies.Add (ainfo);
						if (reader.MoveToAttribute ("AssemblyName") && reader.ReadAttributeValue ())
							ainfo.Name = reader.ReadContentAsString ();
						if (string.IsNullOrEmpty (ainfo.Name))
							throw new Exception ("Missing AssemblyName attribute");
						if (reader.MoveToAttribute ("Version") && reader.ReadAttributeValue ())
							ainfo.Version = reader.ReadContentAsString ();
						if (reader.MoveToAttribute ("PublicKeyToken") && reader.ReadAttributeValue ())
							ainfo.PublicKeyToken = reader.ReadContentAsString ();
						if (reader.MoveToAttribute ("Culture") && reader.ReadAttributeValue ())
							ainfo.Culture = reader.ReadContentAsString ();
						if (reader.MoveToAttribute ("ProcessorArchitecture") && reader.ReadAttributeValue ())
							ainfo.ProcessorArchitecture = (ProcessorArchitecture)
								Enum.Parse (typeof (ProcessorArchitecture), reader.ReadContentAsString (), true);
						if (reader.MoveToAttribute ("InGac") && reader.ReadAttributeValue ())
							ainfo.InGac = reader.ReadContentAsBoolean ();
					} while (reader.ReadToFollowing ("File"));
				} else if (Directory.Exists (dir)) {
					
					foreach (var f in Directory.EnumerateFiles (dir, "*.dll")) {
						try {
							var an = SystemAssemblyService.GetAssemblyNameObj (dir.Combine (f));
							var ainfo = new AssemblyInfo ();
							ainfo.Update (an);
							assemblies.Add (ainfo);
						} catch (BadImageFormatException ex) {
							LoggingService.LogError ("Invalid assembly in framework '{0}': {1}{2}{3}", fx.Id, f, Environment.NewLine, ex.ToString ());
						} catch (Exception ex) {
							LoggingService.LogError ("Error reading assembly '{0}' in framework '{1}':{2}{3}",
								f, fx.Id, Environment.NewLine, ex.ToString ());
						}
					}
				}
				
				fx.Assemblies = assemblies.ToArray ();
			}
			
			var supportedFrameworksDir = dir.Combine ("SupportedFrameworks");
			if (Directory.Exists (supportedFrameworksDir)) {
				foreach (var sfx in Directory.GetFiles (supportedFrameworksDir))
					fx.SupportedFrameworks.Add (SupportedFramework.Load (fx, sfx));
			}
			
			return fx;
		}
		static void RedirectOutputToFileWindows (FilePath logDirectory, string logName)
		{
			var stream = File.Open (logDirectory.Combine (logName), FileMode.Create, FileAccess.Write, FileShare.Read);
			var writer = new StreamWriter (stream) { AutoFlush = true };
			
			var stderr = new MonoDevelop.Core.ProgressMonitoring.LogTextWriter ();
			stderr.ChainWriter (Console.Error);
			stderr.ChainWriter (writer);
			defaultError = Console.Error;
			Console.SetError (stderr);

			var stdout = new MonoDevelop.Core.ProgressMonitoring.LogTextWriter ();
			stdout.ChainWriter (Console.Out);
			stdout.ChainWriter (writer);
			defaultOut = Console.Out;
			Console.SetOut (stdout);
		}
		public override SolutionItemConfiguration CreateConfiguration (string name)
		{
			var conf = new IPhoneProjectConfiguration (name);
			
			var dir = new FilePath ("bin");
			if (!String.IsNullOrEmpty (conf.Platform))
				dir.Combine (conf.Platform);
			dir.Combine (conf.Name);
			
			conf.OutputDirectory = BaseDirectory.IsNullOrEmpty? dir : BaseDirectory.Combine (dir);
			conf.OutputAssembly = Name;
			if (conf.Platform == PLAT_IPHONE) {
				conf.CodesignKey = Keychain.DEV_CERT_PREFIX;
			} else if (conf.Platform == PLAT_SIM) {
				conf.MtouchLink = MtouchLinkMode.None;
			}
			
			if (LanguageBinding != null)
				conf.CompilationParameters = LanguageBinding.CreateCompilationParameters (null);
			return conf;
		}