public override void CreateDirectory (FilePath path)
		{
			Repository repo = GetRepository (path);
			repo.ClearCachedVersionInfo (path);
			System.IO.Directory.CreateDirectory (path);
			repo.Add (path, false, new ProgressMonitor ());
		}
		public virtual string GetDirectoryDotSvn (FilePath path)
		{
			if (Directory.Exists (path.Combine (".svn")))
				return path;

			return String.Empty;
		}
Exemplo n.º 3
0
		public override void Setup ()
		{
			svnRoot = new FilePath (FileService.CreateTempDirectory ());
			repoLocation = "file://" + svnRoot + "/repo";
			backend = new UnixSvnBackend ();
			base.Setup ();
		}
Exemplo n.º 4
0
		WorkspaceObjectReader GetObjectReaderForFile (FilePath file, Type type)
		{
			foreach (var r in GetObjectReaders ())
				if (r.CanRead (file, type))
					return r;
			return null;
		}
Exemplo n.º 5
0
		public override void Setup ()
		{
			// Generate directories and a svn util.
			rootUrl = new FilePath (FileService.CreateTempDirectory () + Path.DirectorySeparatorChar);
			rootCheckout = new FilePath (FileService.CreateTempDirectory () + Path.DirectorySeparatorChar);
			Directory.CreateDirectory (rootUrl.FullPath + "repo.git");
			repoLocation = "file:///" + rootUrl.FullPath + "repo.git";

			// Initialize the bare repo.
			InitCommand ci = new InitCommand ();
			ci.SetDirectory (new Sharpen.FilePath (rootUrl.FullPath + "repo.git"));
			ci.SetBare (true);
			ci.Call ();
			FileRepository bare = new FileRepository (new Sharpen.FilePath (rootUrl.FullPath + "repo.git"));
			string branch = Constants.R_HEADS + "master";

			RefUpdate head = bare.UpdateRef (Constants.HEAD);
			head.DisableRefLog ();
			head.Link (branch);

			// Check out the repository.
			Checkout (rootCheckout, repoLocation);
			repo = GetRepo (rootCheckout, repoLocation);
			DOT_DIR = ".git";
		}
Exemplo n.º 6
0
        public MSBuildProject(FilePath filePath)
        {
            FilePath = filePath;

            _msBuildProject = ProjectRootElement.Open(filePath.FullPath, _globalCollection);

            foreach (var item in _msBuildProject.Items)
            {
                if (item.ItemType == "Reference")
                    References.Add(item.Include);
                else if (item.ItemType == "Compile" || item.ItemType == "None")
                {
                    var entry = new ProjectFileEntry(new FilePath(this.ProjectDirectory, item.Include));

                    foreach (var element in item.Metadata)
                    {
                        if (element.Name == "DependentUpon")
                        {
                            entry.Dependencies.Add(element.Value);
                        }
                    }

                    entry.ParentProject = this;
                    AddFileEventHandlers(entry);
                    ProjectFiles.Add(entry);
                }
            }

            SetupEventHandlers();
            HasUnsavedData = false;
        }
Exemplo n.º 7
0
		bool RunDialog (OpenFileDialogData data)
		{			
			Application.EnableVisualStyles ();
			
			FileDialog fileDlg = null;
			if (data.Action == Gtk.FileChooserAction.Open)
				fileDlg = new OpenFileDialog ();
			else
				fileDlg = new SaveFileDialog ();
			
			var dlg = new CustomOpenFileDialog (fileDlg, data);
				
			SelectFileDialogHandler.SetCommonFormProperties (data, dlg.FileDialog);
			
			using (dlg) {
				rootForm = new WinFormsRoot ();
				if (dlg.ShowDialog (rootForm) == DialogResult.Cancel) {
					return false;
				}
	
				FilePath[] paths = new FilePath [fileDlg.FileNames.Length];
				for (int n = 0; n < fileDlg.FileNames.Length; n++)	
					paths [n] = fileDlg.FileNames [n];
				data.SelectedFiles = paths;
				
				if (dlg.SelectedEncodingId != null)
					data.Encoding = dlg.SelectedEncodingId > 0 ? Encoding.GetEncoding (dlg.SelectedEncodingId) : null;
				if (dlg.SelectedViewer != null)
					data.SelectedViewer = dlg.SelectedViewer;
				
				data.CloseCurrentWorkspace = dlg.CloseCurrentWorkspace;
			}
			
			return true;
		}
Exemplo n.º 8
0
		public bool Exists(FilePath filePath)
		{
			var path = filePath.Path;
			return filePath.IsDirectory
				? Directory.Exists(path)
				: File.Exists(path);
		}
Exemplo n.º 9
0
		public static IAsyncOperation Package (MonoMacProject project, ConfigurationSelector configSel,
			MonoMacPackagingSettings settings, FilePath target)
		{
			IProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor (
				GettextCatalog.GetString ("Packaging Output"),
				MonoDevelop.Ide.Gui.Stock.RunProgramIcon, true, true);
			
			 var t = new System.Threading.Thread (() => {
				try {
					using (mon) {
						BuildPackage (mon, project, configSel, settings, target);
					}	
				} catch (Exception ex) {
					mon.ReportError ("Unhandled error in packaging", null);
					LoggingService.LogError ("Unhandled exception in packaging", ex);
				} finally {
					mon.Dispose ();
				}
			}) {
				IsBackground = true,
				Name = "Mac Packaging",
			};
			t.Start ();
			
			return mon.AsyncOperation;
		}
Exemplo n.º 10
0
		public static BuildResult CompileXibFiles (IProgressMonitor monitor, IEnumerable<ProjectFile> files,
		                                           FilePath outputRoot)
		{
			var result = new BuildResult ();
			var ibfiles = GetIBFilePairs (files, outputRoot).Where (NeedsBuilding).ToList ();
			
			if (ibfiles.Count > 0) {
				monitor.BeginTask (GettextCatalog.GetString ("Compiling interface definitions"), 0);	
				foreach (var file in ibfiles) {
					file.EnsureOutputDirectory ();
					var args = new ProcessArgumentBuilder ();
					args.AddQuoted (file.Input);
					args.Add ("--compile");
					args.AddQuoted (file.Output);
					var psi = new ProcessStartInfo ("ibtool", args.ToString ());
					monitor.Log.WriteLine (psi.FileName + " " + psi.Arguments);
					psi.WorkingDirectory = outputRoot;
					string errorOutput;
					int code;
					try {
					code = ExecuteCommand (monitor, psi, out errorOutput);
					} catch (System.ComponentModel.Win32Exception ex) {
						LoggingService.LogError ("Error running ibtool", ex);
						result.AddError (null, 0, 0, null, "ibtool not found. Please ensure the Apple SDK is installed.");
						return result;
					}
					if (code != 0) {
						//FIXME: parse the plist that ibtool returns
						result.AddError (null, 0, 0, null, "ibtool returned error code " + code);
					}
				}
				monitor.EndTask ();
			}
			return result;
		}
Exemplo n.º 11
0
		FileSystemExtension GetNextForPath (FilePath file, bool isDirectory)
		{
			FileSystemExtension nx = next;
			while (nx != null && !nx.CanHandlePath (file, isDirectory))
				nx = nx.next;
			return nx;
		}
		/// <summary>
		/// Retrieve and display annotations for a given VersionControlItem
		/// </summary>
		/// <param name="repo">
		/// A <see cref="Repository"/> to which file belongs
		/// </param>
		/// <param name="file">
		/// A <see cref="FilePath"/>: The file to annotate
		/// </param>
		/// <param name="test">
		/// A <see cref="System.Boolean"/>: Whether this is a test run
		/// </param>
		/// <returns>
		/// A <see cref="System.Boolean"/>: Whether annotations are supported
		/// </returns>
		public static bool Show (Repository repo, FilePath file, bool test)
		{
			if (test){ 
				if (null != repo && repo.CanGetAnnotations (file)) {
					foreach (Ide.Gui.Document guidoc in IdeApp.Workbench.Documents) {
						if (guidoc.FileName.Equals (file)) {
							SourceEditorView seview  = guidoc.ActiveView as SourceEditorView;
							if (null != seview && 
							    seview.TextEditor.HasMargin (typeof (AnnotationMargin)) && 
							    seview.TextEditor.GetMargin (typeof (AnnotationMargin)).IsVisible) { 
								return false;
							}
						}
					}
					return true;
				}
				return false;
			}
			
			MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.OpenDocument (file, true);
			SourceEditorView view = doc.ActiveView as SourceEditorView;
			if (view != null) {
				if (view.TextEditor.HasMargin (typeof (AnnotationMargin))) { 
					view.TextEditor.GetMargin (typeof (AnnotationMargin)).IsVisible = true;
				} else {
					view.TextEditor.InsertMargin (0, new AnnotationMargin (repo, view.TextEditor, doc));
				}
				view.TextEditor.QueueDraw ();
			}
			
			return true;
		}
Exemplo n.º 13
0
		public override string GetPathUrl (FilePath path)
		{
			lock (client) {
				Uri u = client.GetUriFromWorkingCopy (path);
				return u != null ? u.ToString () : null;
			}
		}
Exemplo n.º 14
0
		public IncludeNewFilesDialog (string title, FilePath baseDirectory)
		{
			this.Build ();
			this.Title = title;
			this.baseDirectory = baseDirectory;
			
			treeviewFiles.Model = store;
			
			treeviewFiles.HeadersVisible = false; // Headers are untranslated because they're hidden as default
			
			TreeViewColumn textColumn = new TreeViewColumn ();
			
			CellRendererToggle toggleRender = new CellRendererToggle ();
			toggleRender.Toggled += ToggleRenderToggled;
			textColumn.PackStart (toggleRender, false);
			textColumn.AddAttribute (toggleRender, "active", Columns.IsToggled);
			
			textColumn.Title = "Name";
			var pixbufRenderer = new CellRendererImage ();
			textColumn.PackStart (pixbufRenderer, false);
			textColumn.AddAttribute (pixbufRenderer, "image", Columns.IconOpened);
			textColumn.AddAttribute (pixbufRenderer, "image-expander-open", Columns.IconOpened);
			textColumn.AddAttribute (pixbufRenderer, "image-expander-closed", Columns.IconClosed);
			
			CellRendererText textRenderer = new CellRendererText ();
			textColumn.PackStart (textRenderer, false);
			textColumn.AddAttribute (textRenderer, "text", Columns.Text);
			treeviewFiles.AppendColumn (textColumn);
			buttonExcludeAll.Clicked += ButtonExcludeAllClicked;
			buttonIncludeAll.Clicked += ButtonIncludeAllClicked;
			buttonOk.Clicked += ButtonOkClicked;
		}
Exemplo n.º 15
0
		protected override void Run ()
		{
			var doc = IdeApp.Workbench.ActiveDocument;
			var currentLocation = doc.Editor.Caret.Location;

			var controller = doc.ParsedDocument.GetTopLevelTypeDefinition (currentLocation);
			string controllerName = controller.Name;
			int pos = controllerName.LastIndexOf ("Controller", StringComparison.Ordinal);
			if (pos > 0)
				controllerName = controllerName.Remove (pos);

			var baseDirectory = doc.FileName.ParentDirectory.ParentDirectory;

			string actionName = doc.ParsedDocument.GetMember (currentLocation).Name;
			var viewFoldersPaths = new FilePath[] {
				baseDirectory.Combine ("Views", controllerName),
				baseDirectory.Combine ("Views", "Shared")
			};
			var viewExtensions = new string[] { ".aspx", ".cshtml" };

			foreach (var folder in viewFoldersPaths) {
				foreach (var ext in viewExtensions) {
					var possibleFile = folder.Combine (actionName + ext);
					if (File.Exists (possibleFile)) {
						IdeApp.Workbench.OpenDocument (possibleFile);
						return;
					}
				}
			}

			MessageService.ShowError ("Matching view cannot be found.");
		}
Exemplo n.º 16
0
		public XcodeSyncBackContext (FilePath projectDir, Dictionary<string,DateTime> syncTimes,
			NSObjectInfoService infoService, DotNetProject project)
			: base (projectDir, syncTimes)
		{
			InfoService = infoService;
			Project = project;
		}
		public override Repository GetRepositoryReference(FilePath path, string id)
		{
			if (!IsVersioned(path))
				return null;

			return new GitRepository(this, FindRepositoryPath(path));
		}
		public override IEnumerable<MemberReference> FindReferences (ProjectDom dom, FilePath fileName, IEnumerable<INode> searchedMembers)
		{
			HashSet<int > positions = new HashSet<int> ();
			var editor = TextFileProvider.Instance.GetTextEditorData (fileName);
			FindMemberAstVisitor visitor = new FindMemberAstVisitor (editor.Document);
			visitor.IncludeXmlDocumentation = IncludeDocumentation;
			visitor.Init (searchedMembers);
			if (!visitor.FileContainsMemberName ()) {
				yield break;
			}
			var doc = ProjectDomService.ParseFile (dom, fileName, () => editor.Text);
			if (doc == null || doc.CompilationUnit == null)
				yield break;
			var resolver = new NRefactoryResolver (dom, doc.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, editor, fileName);

			visitor.ParseFile (resolver);
			visitor.RunVisitor (resolver);
			foreach (var reference in visitor.FoundReferences) {
				if (positions.Contains (reference.Position))
					continue;
				positions.Add (reference.Position);
				yield return reference;
			}
			visitor.ClearParsers ();
		}
Exemplo n.º 19
0
		public override void Setup ()
		{
			rootUrl = new FilePath (FileService.CreateTempDirectory ());
			repoLocation = "svn://localhost:3690/repo";
			svnServe = new Process ();
			base.Setup ();
		}
Exemplo n.º 20
0
		public bool ContainsFile (FilePath fileName)
		{
			for (int n=0; n<items.Count; n++)
				if (items [n].LocalPath == fileName)
					return true;
			return false;
		}
Exemplo n.º 21
0
        public RuleFactory(FilePath rootDirectory, IFileSystem files)
        {
            _rootDirectory = rootDirectory;
            _files = files;

            _modulesPath = new FilePath("_rules/Modules.rule");
        }
		public override Repository GetRepositoryReference (FilePath path, string id)
		{
			GitRepository repo;
			if (!repositories.TryGetValue (path.CanonicalPath, out repo) || repo.Disposed)
				repositories [path.CanonicalPath] = repo = new GitRepository (this, path, null);
			return repo;
		}
Exemplo n.º 23
0
        public bool Run(SelectFileDialogData data)
        {
            CommonDialog dlg = null;
            if (data.Action == Gtk.FileChooserAction.Open)
                dlg = new OpenFileDialog();
            else if (data.Action == Gtk.FileChooserAction.Save)
                dlg = new SaveFileDialog();
			else if (data.Action == Gtk.FileChooserAction.SelectFolder)
				dlg = new FolderBrowserDialog ();
			
			if (dlg is FileDialog)
				SetCommonFormProperties (data, dlg as FileDialog);
			else
				SetFolderBrowserProperties (data, dlg as FolderBrowserDialog);
			

			using (dlg) {
                WinFormsRoot root = new WinFormsRoot();
                if (dlg.ShowDialog(root) == DialogResult.Cancel)
                    return false;
				
				if (dlg is FileDialog) {
					var fileDlg = dlg as OpenFileDialog;
					FilePath[] paths = new FilePath [fileDlg.FileNames.Length];
					for (int n=0; n < fileDlg.FileNames.Length; n++)
						paths [n] = fileDlg.FileNames [n];
                    data.SelectedFiles = paths;    
				} else {
					var folderDlg = dlg as FolderBrowserDialog;
					data.SelectedFiles = new [] { new FilePath (folderDlg.SelectedPath) };
				}

				return true;
			}
        }
Exemplo n.º 24
0
		public override void Setup ()
		{
			RemotePath = new FilePath (FileService.CreateTempDirectory ());
			RemoteUrl = "svn://localhost:3690/repo";
			SvnServe = new Process ();
			base.Setup ();
		}
        public bool Run(ConfigNode cfg)
        {
            fLastException = null;

             Console.WriteLine("Starting CreateHDFFromASC...");

             fWorkingDir = cfg["working.dir", AppDomain.CurrentDomain.BaseDirectory].AsFilePath();

             try
             {
            if (cfg["from.asc.to.xyz", false].AsBool())
               ConvertToXYZ(cfg);

            if (cfg["from.xyz.to.mgd", false].AsBool())
               ConvertToMGD(cfg);

            if (cfg["from.mgd.to.hdf", false].AsBool())
               ConvertToHDF(cfg);

            if (cfg["glue.hdfs", false].AsBool())
               GlueHDFs(cfg);

            Console.WriteLine("CreateHDFFromASC finished successfully...");
            return true;
             }
             catch (Exception ex)
             {
            fLastException = ex;
            return false;
             }
        }
Exemplo n.º 26
0
 public override bool CanExecute(FilePath path)
 {
     UnixFileInfo fi = new UnixFileInfo (path);
     if (!fi.Exists)
         return false;
     return 0 != (fi.FileAccessPermissions & (FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute));
 }
Exemplo n.º 27
0
        void androidPackageTest (bool signed)
        {                        
            var projectFile = context.WorkingDirectory
                .Combine ("TestProjects/HelloWorldAndroid/HelloWorldAndroid/")
                .CombineWithFilePath ("HelloWorldAndroid.csproj");

            projectFile = new FilePath ("./TestProjects/HelloWorldAndroid/HelloWorldAndroid/HelloWorldAndroid.csproj");

            FilePath apkFile = null;

            try {
                apkFile = context.CakeContext.AndroidPackage(
                    projectFile,
                    signed,
                    c => {
                        c.Verbosity = Verbosity.Diagnostic;
                        c.Configuration = "Release";
                    });
            } catch (Exception ex) {
                Console.WriteLine(ex);
                context.DumpLogs();
                Assert.Fail(context.GetLogs());
            }
            
            Assert.IsNotNull (apkFile);
            Assert.IsNotNull (apkFile.FullPath);
            Assert.IsNotEmpty (apkFile.FullPath);
            Assert.IsTrue (System.IO.File.Exists (apkFile.FullPath));
        }
Exemplo n.º 28
0
		//TODO: handle errors
		public AvdWatcher ()
		{
			VirtualDevices = new AndroidVirtualDevice[0];
			
			FilePath home = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
			if (PropertyService.IsWindows) {
				home = home.ParentDirectory;
			}
			avdDir = home.Combine (".android", "avd");
			if (!Directory.Exists (avdDir))
				Directory.CreateDirectory (avdDir);
			
			var avds = Directory.GetFiles (avdDir, "*.ini");
			UpdateAvds (avds, null);
			
			//FSW on mac is unreliable
			if (PropertyService.IsMac) {
				modTimes = new Dictionary<string, DateTime> ();
				foreach (var f in avds)
					modTimes[f] = File.GetLastWriteTimeUtc (f);
				timeoutId = GLib.Timeout.Add (750, HandleTimeout);
			} else {
				CreateFsw ();
			}
		}
		public override IEnumerable<MemberReference> FindReferences (ProjectDom dom, FilePath fileName, IEnumerable<INode> searchedMembers)
		{
			var editor = TextFileProvider.Instance.GetTextEditorData (fileName);
			AspNetAppProject project = dom.Project as AspNetAppProject;
			if (project == null)
				yield break;
			
			var unit = AspNetParserService.GetCompileUnit (project, fileName, true);
			if (unit == null)
				yield break;
			var refman = new DocumentReferenceManager (project);
			
			var parsedAspDocument = (AspNetParsedDocument)new AspNetParser ().Parse (dom, fileName, editor.Text);
			refman.Doc = parsedAspDocument;
			
			var usings = refman.GetUsings ();
			var documentInfo = new DocumentInfo (dom, unit, usings, refman.GetDoms ());
			
			var builder = new AspLanguageBuilder ();
			
			
			var buildDocument = new Mono.TextEditor.Document ();
			var offsetInfos = new List<LocalDocumentInfo.OffsetInfo> ();
			buildDocument.Text = builder.BuildDocumentString (documentInfo, editor, offsetInfos, true);
			var parsedDocument = AspLanguageBuilder.Parse (dom, fileName, buildDocument.Text);
			foreach (var member in searchedMembers) {
				foreach (var reference in SearchMember (member, dom, fileName, editor, buildDocument, offsetInfos, parsedDocument)) {
					yield return reference;
				}
			}
		}
		public bool ShouldOpenInXcode (FilePath fileName)
		{
			if (!HasInterfaceDefinitionExtension (fileName))
				return false;
			var file = dnp.Files.GetFile (fileName);
			return file != null && (file.BuildAction == BuildAction.InterfaceDefinition);
		}
Exemplo n.º 31
0
 public static void S3Upload(this ICakeContext context, FilePath filePath, string key, UploadSettings settings)
 {
     context.CreateManager().Upload(filePath, key, settings);
 }
Exemplo n.º 32
0
 /// <summary>
 /// Queries the related ini file and looks for Archive ordering information
 /// </summary>
 /// <param name="release">GameRelease to query for</param>
 /// <param name="path">Path to the file containing INI data</param>
 /// <returns>Any Archive ordering info retrieved from the ini definition</returns>
 public static IEnumerable <FileName> GetIniListings(GameRelease release, FilePath path)
 {
     return(GetIniListings(release, FileSystem.File.OpenRead(path.Path)));
 }
        public static async Task <string> CompareCoverage(this ICakeContext context, FilePath upstream, FilePath current)
        {
            var fromCurrentTable = await ExtractTableFromHtml(current.FullPath);

            var fromMasterTable = await ExtractTableFromHtml(upstream.FullPath);

            var coveredFiles = ExtractCoveredClasses(fromCurrentTable, isFromMaster: false)
                               .Concat(ExtractCoveredClasses(fromMasterTable, isFromMaster: true));

            var coverageResult = from item in coveredFiles.GroupBy(x => x.FullName)
                                 let fromMaster = item.FirstOrDefault(x => x.IsFromMasterBranch)
                                                  let fromCurrent = item.FirstOrDefault(x => !x.IsFromMasterBranch)
                                                                    select new CoveredClassReport(fromCurrent.FullName ?? fromMaster.FullName, fromCurrent.TotalCovered, fromMaster.TotalCovered);

            var sb = new StringBuilder()
                     .AppendLine("File | Current branch coverage | Upstream branch coverage | Difference")
                     .AppendLine("---- | ----------------------  | ------------------------ | ----------");

            foreach (var item in coverageResult.Where(x => x.CoverageDifference != 0))
            {
                sb.AppendLine($"{item.FullName} | {item.TotalCoveredCurrent:N} | {item.TotalCoveredMaster:N} | {item.CoverageDifference / 100:P} {item.CoverageDifferenceEmoji}");
            }
            var result = sb.ToString();

            return(result);
        }
Exemplo n.º 34
0
        protected override void ClientHelper_ReceivedServiceResponse(object sender, EventArgs <ServiceResponse> e)
        {
            List <object> attachments = e.Argument.Attachments;

            // Handle any special attachments coming in from service
            if (attachments != null)
            {
                foreach (object attachment in attachments)
                {
                    if (attachment is ConfigurationErrorFrame)
                    {
                        Console.WriteLine("Received configuration error frame, invocation request for device configuration has failed. See common phasor services response for reason.\r\n");
                    }
                    else if (attachment is IConfigurationFrame)
                    {
                        // Attachment is a configuration frame, serialize it to XML and open it in a browser
                        IConfigurationFrame configurationFrame = attachment as IConfigurationFrame;
                        string        fileName      = string.Format("{0}\\DownloadedConfiguration-ID[{1}].xml", FilePath.GetAbsolutePath(""), configurationFrame.IDCode);
                        FileStream    configFile    = File.Create(fileName);
                        SoapFormatter xmlSerializer = new SoapFormatter();

                        xmlSerializer.AssemblyFormat = FormatterAssemblyStyle.Simple;
                        xmlSerializer.TypeFormat     = FormatterTypeStyle.TypesWhenNeeded;

                        try
                        {
                            // Attempt to serialize configuration frame as XML
                            xmlSerializer.Serialize(configFile, configurationFrame);
                        }
                        catch (Exception ex)
                        {
                            byte[] errorMessage = Encoding.UTF8.GetBytes(ex.Message);
                            configFile.Write(errorMessage, 0, errorMessage.Length);
                            Console.Write("Failed to serialize configuration frame: {0}", ex.Message);
                        }

                        configFile.Close();

                        // Open captured XML sample file in explorer...
                        Process.Start("explorer.exe", fileName);
                    }
                }
            }

            // Allow base class to handle common response
            base.ClientHelper_ReceivedServiceResponse(sender, e);
        }
Exemplo n.º 35
0
 public static string S3SyncDownload(this ICakeContext context, FilePath filePath, SyncSettings settings)
 {
     return(context.CreateManager().SyncDownload(filePath, settings));
 }
Exemplo n.º 36
0
 public static void GenerateEncryptionKey(this ICakeContext context, FilePath filePath, int size)
 {
     context.CreateManager().GenerateEncryptionKey(filePath, size);
 }
Exemplo n.º 37
0
 public static void S3Download(this ICakeContext context, FilePath filePath, string key, string version, DownloadSettings settings)
 {
     context.CreateManager().Download(filePath, key, version, settings);
 }
 public void GivenScriptExist(FilePath path, string content)
 {
     FileSystem.CreateFile(path).SetContent(content);
 }
Exemplo n.º 39
0
 public bool IsWorkspaceItemFile(FilePath file)
 {
     return(IsWorkspaceItemFileImpl(file.ToString()));
 }
Exemplo n.º 40
0
        static async Task Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed(o => Option = o)
            .WithNotParsed(o => Environment.Exit(-1));

            Option.FFArgument   = Option.FFArgument.Replace("\\", "");
            Option.ExifArgument = Option.ExifArgument.Replace("\\", "");

            List <string> ExtensionFilters = Option.Extensions.ToList();

            var FilePaths = Directory.GetFiles(Option.Source, "*", SearchOption.AllDirectories)
                            .Where(f => ExtensionFilters.Any(e => f.EndsWith(e, StringComparison.CurrentCultureIgnoreCase)))
                            .ToList();

            int Process_cnt = 0, Ignored_cnt = 0, Keep_cnt = 0;
            var TaskList = new List <Task>();

            foreach (var FilePath in FilePaths)
            {
                var SavePath = FilePath.Replace(Option.Source, Option.Destination);

                //multi thread
                if (TaskList.Count >= Option.Thread)
                {
                    Task FinishedTask = await Task.WhenAny(TaskList);

                    TaskList.Remove(FinishedTask);
                    Interlocked.Increment(ref Process_cnt);
                }

                //Check Ignore
                if (Option.Ignore && File.Exists(SavePath))
                {
                    Console.WriteLine($"File exist, ignored:{SavePath}");
                    Interlocked.Increment(ref Ignored_cnt);
                    continue;//skip
                }

                Directory.CreateDirectory(Path.GetDirectoryName(SavePath));

                Task t = Task.Run(() => {
                    //Check Comment
                    if (String.IsNullOrEmpty(Option.Comment) == false &&
                        Option.Comment == ReadComment(FilePath))
                    {
                        Console.WriteLine($"File already has comment, ignored:{SavePath}");
                        Interlocked.Increment(ref Ignored_cnt);
                        return;//skip
                    }

                    if (String.IsNullOrEmpty(Option.FFArgument) == false)
                    {
                        RunFFMPEG(FilePath, SavePath);
                    }

                    if (String.IsNullOrEmpty(Option.ExifArgument) == false)
                    {
                        RunExifTool(FilePath, SavePath);
                    }

                    if (String.IsNullOrEmpty(Option.Date) == false)
                    {
                        CopyDate(FilePath, SavePath);
                    }

                    if (Option.Keep && CheckFileSize(FilePath, SavePath))
                    {
                        Console.WriteLine($"Output file is larger, copy original:{SavePath}");
                        Interlocked.Increment(ref Keep_cnt);
                    }
                });

                TaskList.Add(t);
                Console.WriteLine($"Processing:{SavePath}");
                WriteOnBottomLine($"File Count:{FilePaths.Count}, Processed:{Process_cnt.ToString()}, Ignored:{Ignored_cnt.ToString()}, Keep:{Keep_cnt.ToString()}");
            }


            while (TaskList.Count != 0)
            {
                Task FinishedTask = await Task.WhenAny(TaskList);

                TaskList.Remove(FinishedTask);
                Interlocked.Increment(ref Process_cnt);
            }
            WriteOnBottomLine($"File Count:{FilePaths.Count}, Processed:{Process_cnt.ToString()}, Ignored:{Ignored_cnt.ToString()}, Keep:{Keep_cnt.ToString()}");
        }
Exemplo n.º 41
0
        bool CopyFiles(IProgressMonitor monitor, IWorkspaceFileObject obj, IEnumerable <FilePath> files, FilePath targetBasePath, bool ignoreExternalFiles)
        {
            FilePath baseDir = obj.BaseDirectory.FullPath;

            foreach (FilePath file in files)
            {
                if (!File.Exists(file))
                {
                    monitor.ReportWarning(GettextCatalog.GetString("File '{0}' not found.", file));
                    continue;
                }
                FilePath fname = file.FullPath;

                // Can't export files from outside the root solution directory
                if (!fname.IsChildPathOf(baseDir))
                {
                    if (ignoreExternalFiles)
                    {
                        continue;
                    }
                    if (obj is Solution)
                    {
                        monitor.ReportError("The solution '" + obj.Name + "' is referencing the file '" + Path.GetFileName(file) + "' which is located outside the root solution directory.", null);
                    }
                    else
                    {
                        monitor.ReportError("The project '" + obj.Name + "' is referencing the file '" + Path.GetFileName(file) + "' which is located outside the project directory.", null);
                    }
                    return(false);
                }

                FilePath rpath = fname.ToRelative(baseDir);
                rpath = rpath.ToAbsolute(targetBasePath);

                if (!Directory.Exists(rpath.ParentDirectory))
                {
                    Directory.CreateDirectory(rpath.ParentDirectory);
                }

                File.Copy(file, rpath, true);
            }
            return(true);
        }
 public ScriptAnalyzerResult Analyze(FilePath script)
 {
     return(CreateAnalyzer().Analyze(script, new ScriptAnalyzerSettings()));
 }
Exemplo n.º 43
0
        public async Task MonitorFileTailAsync(FilePath path,
                                               Func <string, Task> onChange,
                                               TimeSpan period = default,
                                               CancellationToken cancellationToken = default)
        {
            if (period == default)
            {
                period = TimeSpan.FromSeconds(1);
            }

            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            if (onChange is null)
            {
                throw new ArgumentNullException(nameof(onChange));
            }

            const int bufferLength = 4096;

            var initialFileLength = new FileInfo(path).Length;
            var lastReadLength    = initialFileLength - bufferLength;

            if (lastReadLength < 0)
            {
                lastReadLength = 0;
            }

            while (!cancellationToken.IsCancellationRequested)
            {
                var fileLength = new FileInfo(path).Length;

                if (fileLength < lastReadLength)
                {
                    throw new
                          IOException("Something was deleted from the watched file. Deletion events doesn't support now");
                }

                if (fileLength > lastReadLength)
                {
                    using (var fileStream = new FileStream(path,
                                                           FileMode.Open,
                                                           FileAccess.Read,
                                                           FileShare.ReadWrite,
                                                           bufferLength,
                                                           FileOptions.Asynchronous))
                    {
                        if (!fileStream.CanSeek)
                        {
                            throw new InvalidOperationException("Can't seek the file watch stream");
                        }

                        fileStream.Seek(lastReadLength, SeekOrigin.Begin);

                        var buffer = new byte[bufferLength];

                        int bytesRead;

                        while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) >
                               0)
                        {
                            lastReadLength += bytesRead;

                            var text = Encoding.ASCII.GetString(buffer, 0, bytesRead);

                            await onChange(text);
                        }
                    }
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                await Task.Delay(period, cancellationToken);
            }
        }
Exemplo n.º 44
0
 public bool IsSolutionItemFile(FilePath file)
 {
     return(IsSolutionItemFileImpl(file.ToString()));
 }
Exemplo n.º 45
0
 internal static void StartUpdatesInstaller(FilePath installerDataFile, FilePath updatedInstallerPath)
 {
     PlatformService.StartUpdatesInstaller(installerDataFile, updatedInstallerPath);
 }
Exemplo n.º 46
0
        string Export(IProgressMonitor monitor, IWorkspaceFileObject obj, string[] includedChildIds, string targetPath, FileFormat format)
        {
            string rootSourceFile = obj.FileName;
            string sourcePath     = Path.GetFullPath(Path.GetDirectoryName(rootSourceFile));

            targetPath = Path.GetFullPath(targetPath);

            if (sourcePath != targetPath)
            {
                if (!CopyFiles(monitor, obj, obj.GetItemFiles(true), targetPath, true))
                {
                    return(null);
                }

                string newFile = Path.Combine(targetPath, Path.GetFileName(rootSourceFile));
                if (IsWorkspaceItemFile(rootSourceFile))
                {
                    obj = ReadWorkspaceItem(monitor, newFile);
                }
                else
                {
                    obj = (SolutionEntityItem)ReadSolutionItem(monitor, newFile);
                }

                using (obj) {
                    List <FilePath> oldFiles = obj.GetItemFiles(true);
                    ExcludeEntries(obj, includedChildIds);
                    if (format != null)
                    {
                        obj.ConvertToFormat(format, true);
                    }
                    obj.Save(monitor);
                    List <FilePath> newFiles = obj.GetItemFiles(true);

                    foreach (FilePath f in newFiles)
                    {
                        if (!f.IsChildPathOf(targetPath))
                        {
                            if (obj is Solution)
                            {
                                monitor.ReportError("The solution '" + obj.Name + "' is referencing the file '" + f.FileName + "' which is located outside the root solution directory.", null);
                            }
                            else
                            {
                                monitor.ReportError("The project '" + obj.Name + "' is referencing the file '" + f.FileName + "' which is located outside the project directory.", null);
                            }
                        }
                        oldFiles.Remove(f);
                    }

                    // Remove old files
                    foreach (FilePath file in oldFiles)
                    {
                        if (File.Exists(file))
                        {
                            File.Delete(file);

                            // Exclude empty directories
                            FilePath dir = file.ParentDirectory;
                            if (Directory.GetFiles(dir).Length == 0 && Directory.GetDirectories(dir).Length == 0)
                            {
                                try {
                                    Directory.Delete(dir);
                                } catch (Exception ex) {
                                    monitor.ReportError(null, ex);
                                }
                            }
                        }
                    }
                    return(obj.FileName);
                }
            }
            else
            {
                using (obj) {
                    ExcludeEntries(obj, includedChildIds);
                    if (format != null)
                    {
                        obj.ConvertToFormat(format, true);
                    }
                    obj.Save(monitor);
                    return(obj.FileName);
                }
            }
        }
Exemplo n.º 47
0
 public static void OpenFolder(FilePath folderPath)
 {
     PlatformService.OpenFolder(folderPath);
 }
Exemplo n.º 48
0
        public async Task UnzipAsync(FilePath archivePath, DirectoryPath destination)
        {
            logAction?.Invoke($"Unzipping {archivePath}  ==>>  {destination}");

            await Task.Run(() => ZipFile.ExtractToDirectory(archivePath, destination));
        }
Exemplo n.º 49
0
 public bool IsSolutionItemFile(FilePath file)
 {
     return(FileIsObjectOfType(file, typeof(SolutionItem)));
 }
Exemplo n.º 50
0
 public static void OpenInTerminal(FilePath directory)
 {
     PlatformService.OpenInTerminal(directory);
 }
Exemplo n.º 51
0
        async Task <string> Export(ProgressMonitor monitor, IMSBuildFileObject obj, string[] includedChildIds, string targetPath, MSBuildFileFormat format)
        {
            string rootSourceFile = obj.FileName;
            string sourcePath     = Path.GetFullPath(Path.GetDirectoryName(rootSourceFile));

            targetPath = Path.GetFullPath(targetPath);

            if (sourcePath != targetPath)
            {
                if (!CopyFiles(monitor, obj, obj.GetItemFiles(true), targetPath, true))
                {
                    return(null);
                }

                string newFile = Path.Combine(targetPath, Path.GetFileName(rootSourceFile));
                if (IsWorkspaceItemFile(rootSourceFile))
                {
                    obj = (Solution) await ReadWorkspaceItem(monitor, newFile);
                }
                else
                {
                    obj = await ReadSolutionItem(monitor, newFile);
                }

                using (obj) {
                    var oldFiles = obj.GetItemFiles(true).ToList();
                    ExcludeEntries(obj, includedChildIds);
                    if (format != null)
                    {
                        obj.ConvertToFormat(format);
                    }
                    await obj.SaveAsync(monitor);

                    var newFiles           = obj.GetItemFiles(true);
                    var resolvedTargetPath = new FilePath(targetPath).ResolveLinks().FullPath;

                    foreach (FilePath f in newFiles)
                    {
                        if (!f.IsChildPathOf(resolvedTargetPath))
                        {
                            if (obj is Solution)
                            {
                                monitor.ReportError(GettextCatalog.GetString("The solution '{0}' is referencing the file '{1}' which is located outside the root solution directory.", obj.Name, f.FileName), null);
                            }
                            else
                            {
                                monitor.ReportError(GettextCatalog.GetString("The project '{0}' is referencing the file '{1}' which is located outside the project directory.", obj.Name, f.FileName), null);
                            }
                        }
                        oldFiles.Remove(f);
                    }

                    // Remove old files
                    foreach (FilePath file in oldFiles)
                    {
                        if (File.Exists(file))
                        {
                            File.Delete(file);

                            // Exclude empty directories
                            FilePath dir = file.ParentDirectory;
                            if (Directory.GetFiles(dir).Length == 0 && Directory.GetDirectories(dir).Length == 0)
                            {
                                try {
                                    Directory.Delete(dir);
                                } catch (Exception ex) {
                                    monitor.ReportError(null, ex);
                                }
                            }
                        }
                    }
                    return(obj.FileName);
                }
            }
            else
            {
                using (obj) {
                    ExcludeEntries(obj, includedChildIds);
                    if (format != null)
                    {
                        obj.ConvertToFormat(format);
                    }
                    await obj.SaveAsync(monitor);

                    return(obj.FileName);
                }
            }
        }
Exemplo n.º 52
0
 public bool IsWorkspaceItemFile(FilePath file)
 {
     return(FileIsObjectOfType(file, typeof(WorkspaceItem)));
 }
        internal static string FromMSBuildPathRelative(string basePath, string relPath)
        {
            FilePath file = FromMSBuildPath(basePath, relPath);

            return(file.ToRelative(basePath));
        }
Exemplo n.º 54
0
        public bool FileIsObjectOfType(FilePath file, Type type)
        {
            var filename = GetTargetFile(file);

            return(GetObjectReaderForFile(filename, type) != null);
        }
Exemplo n.º 55
0
        /// <summary>
        /// Load sprite data from a sprite sheet
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="textureLoader"></param>
        /// <returns></returns>
        public SpriteDataCollection LoadSpriteSheet(FilePath filePath, ITextureLoader textureLoader)
        {
            var result = new SpriteDataCollection();

            using (var br = new StreamReader(filePath))
            {
                //Read line-by-line:
                SpriteData               currentSprite    = null;
                SpriteAnimation          currentAnimation = null;
                SpriteAnimationDirection currentDirection = null;
                ITexture image = null;

                String line = br.ReadLine();
                if (line != null)
                {
                    //First line gives image filename
                    image = textureLoader.GetTexture(filePath.Directory + line);
                }
                while (line != null)
                {
                    line = br.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        //Store and clear current sprite data:
                        if (currentSprite != null)
                        {
                            result.Add(currentSprite);
                        }
                        currentSprite    = null;
                        currentAnimation = null;
                    }
                    else
                    {
                        String[] splitLine = line.Split('\t'); // Split on tabs
                        if (currentSprite == null)
                        {
                            //Initialise sprite:
                            currentSprite      = new SpriteData();
                            currentSprite.Name = line;
                            //currentSprite.Texture(image);
                        }
                        else if (currentAnimation == null || !splitLine.IsNumeric())
                        {
                            currentAnimation = new SpriteAnimation();
                            currentSprite.Animations.Add(line, currentAnimation);
                            currentDirection = null;
                        }
                        else if (currentDirection == null || splitLine.Length <= 1)
                        {
                            currentDirection = new SpriteAnimationDirection();
                            currentAnimation.Directions.Add(double.Parse(line), currentDirection);
                        }
                        else
                        {
                            TextureBrush frame = new TextureBrush(image, splitLine);
                            currentDirection.Frames.Add(frame);
                        }
                    }
                }
            }
            return(result);
        }
Exemplo n.º 56
0
 public IFile GetFile(FilePath path)
 {
     return(new LongPathFile(path));
 }
Exemplo n.º 57
0
 public ViewContent CreateContent(FilePath fileName, string mimeType, Project ownerProject)
 {
     return(new DotDesktopView());
 }
        internal static string ToMSBuildPathRelative(string baseDirectory, string absPath)
        {
            FilePath file = ToMSBuildPath(baseDirectory, absPath);

            return(file.ToRelative(baseDirectory));
        }
Exemplo n.º 59
0
 public bool CanHandle(FilePath fileName, string mimeType, Project ownerProject)
 {
     return((fileName.IsNotNull && fileName.HasExtension(".desktop")) ||
            (mimeType != null && mimeType == "application/x-desktop"));
 }
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestFailAbort()
        {
            JobConf job = new JobConf();

            job.Set(FileSystem.FsDefaultNameKey, "faildel:///");
            job.SetClass("fs.faildel.impl", typeof(TestMRCJCFileOutputCommitter.FakeFileSystem
                                                   ), typeof(FileSystem));
            SetConfForFileOutputCommitter(job);
            JobContext          jContext  = new JobContextImpl(job, ((JobID)taskID.GetJobID()));
            TaskAttemptContext  tContext  = new TaskAttemptContextImpl(job, taskID);
            FileOutputCommitter committer = new FileOutputCommitter();

            FileOutputFormat.SetWorkOutputPath(job, committer.GetTaskAttemptPath(tContext));
            // do setup
            committer.SetupJob(jContext);
            committer.SetupTask(tContext);
            string   file      = "test.txt";
            FilePath jobTmpDir = new FilePath(committer.GetJobAttemptPath(jContext).ToUri().GetPath
                                                  ());
            FilePath taskTmpDir = new FilePath(committer.GetTaskAttemptPath(tContext).ToUri()
                                               .GetPath());
            FilePath expectedFile = new FilePath(taskTmpDir, file);
            // A reporter that does nothing
            Reporter reporter = Reporter.Null;
            // write output
            FileSystem       localFs         = new TestMRCJCFileOutputCommitter.FakeFileSystem();
            TextOutputFormat theOutputFormat = new TextOutputFormat();
            RecordWriter     theRecordWriter = theOutputFormat.GetRecordWriter(localFs, job, expectedFile
                                                                               .GetAbsolutePath(), reporter);

            WriteOutput(theRecordWriter, reporter);
            // do abort
            Exception th = null;

            try
            {
                committer.AbortTask(tContext);
            }
            catch (IOException ie)
            {
                th = ie;
            }
            NUnit.Framework.Assert.IsNotNull(th);
            NUnit.Framework.Assert.IsTrue(th is IOException);
            NUnit.Framework.Assert.IsTrue(th.Message.Contains("fake delete failed"));
            NUnit.Framework.Assert.IsTrue(expectedFile + " does not exists", expectedFile.Exists
                                              ());
            th = null;
            try
            {
                committer.AbortJob(jContext, JobStatus.State.Failed);
            }
            catch (IOException ie)
            {
                th = ie;
            }
            NUnit.Framework.Assert.IsNotNull(th);
            NUnit.Framework.Assert.IsTrue(th is IOException);
            NUnit.Framework.Assert.IsTrue(th.Message.Contains("fake delete failed"));
            NUnit.Framework.Assert.IsTrue("job temp dir does not exists", jobTmpDir.Exists());
        }