Пример #1
0
 public FileChange[] GetFileChanges()
 {
     FileChange[] result = new FileChange[changes.Count];
     changes.CopyTo(result);
     changes.Clear();
     return result;
 }
        public void Handle(string oldPath, string newPath)
        {
            lock (locker)
            {
                var change = new FileChange
                {
                    NewPath = newPath,
                    OldPath = oldPath
                };

                if (pendingChanges.Contains(change))
                {
                    return;
                }

                pendingChanges.Add(change);

                if (watch.IsRunning)
                {
                    watch.Stop();
                }

                watch.Start();

                Logger.Log("delaying for {0}ms", CurrentDelay.Milliseconds);
            }
        }
        private static CheckResult CheckDataIfStartMenuIsExpectedToNotExist(ICollection<FileChange> fileChanges, ICollection<Registryhange> registryChanges,
            FileChange fileChange, StartMenuData startMenuData, Registryhange registryChange)
        {
            if (fileChange == null)
            {
               return CheckResult.Succeeded(startMenuData);
            }

            if (fileChange.Type != FileChangeType.Delete)
            {
                fileChanges.Remove(fileChange);
                if (registryChange != null)
                {
                    registryChanges.Remove(registryChange);
                }
                return CheckResult.Failure("Found menu item:'" + startMenuData.Name + "' when is was not expected");
            }

            // When uninstalling this key get changed
            const string startPageKey = @"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartPage";
            var uninstallStartMenuKey =
                registryChanges.FirstOrDefault(x => string.Equals(x.Key, startPageKey, StringComparison.InvariantCultureIgnoreCase) &&
                                                    x.ValueName == "FavoritesRemovedChanges" &&
                                                    x.Type == RegistryChangeType.SetValue);

            if (uninstallStartMenuKey == null)
            {
                fileChanges.Remove(fileChange);
                return CheckResult.Failure("");
            }

            registryChanges.Remove(uninstallStartMenuKey);
            fileChanges.Remove(fileChange);
            return CheckResult.Succeeded(startMenuData);
        }
Пример #4
0
        void FileChanged(FileChange change, IFile file)
        {
            if(_appliedConfigFile == null ||
               _appliedConfigFile != file)
                return;

            Apply (file);
        }
 protected override void Analyze(
     FileChange fileChange,
     string fileChangePointer)
 {
     EnsureRelativeUriWithUriBaseId(
         fileChange.Uri,
         fileChange.UriBaseId,
         fileChangePointer);
 }
Пример #6
0
        private void AssertFileChange(
            string initialString,
            string expectedString,
            FileChange fileChange)
        {
            // Create an in-memory file from the StringReader
            ScriptFile fileToChange = CreateScriptFile(initialString);

            // Apply the FileChange and assert the resulting contents
            fileToChange.ApplyChange(fileChange);
            Assert.Equal(expectedString, fileToChange.Contents);
        }
Пример #7
0
        public bool Copy(FileChange targetChange)
        {
            try
            {
                var sourceFile = targetChange.OldPath;
                var destFile   = targetChange.NewPath;
                var oldFoler   = Path.GetDirectoryName(sourceFile);

                if (!Directory.Exists($"{targetChange.NewPath}"))
                {
                    Directory.CreateDirectory($"{targetChange.NewPath}");
                }

                if (!Directory.Exists(oldFoler))
                {
                    throw new FileNotFoundException();
                }

                var files = Directory.GetFiles(oldFoler);

                foreach (var pathToFile in files)
                {
                    var fileName = Path.GetFileName(pathToFile);
                    destFile = Path.Combine(targetChange.NewPath, fileName);
                    File.Copy(pathToFile, destFile, true);
                }

                var directories = Directory.GetDirectories(oldFoler);

                foreach (var pathToDirectory in directories)
                {
                    var relativePathToParent = pathToDirectory.Replace(targetChange.OldPath, "");
                    var newPath = $"{targetChange.NewPath}//{targetChange.OldName}//{relativePathToParent}";

                    var targetChangeForInner = new FileChange
                    {
                        Force   = targetChange.Force,
                        Mode    = targetChange.Mode,
                        OldPath = pathToDirectory,
                        NewPath = newPath
                    };

                    this.Copy(targetChangeForInner);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(false);
            }
        }
Пример #8
0
        public CakeScript Generate(FileChange fileChange)
        {
            if (_generationService == null)
            {
                throw new InvalidOperationException("Cake.Bakery not initialized.");
            }

            if (!fileChange.FromDisk && fileChange.Buffer is null && fileChange.LineChanges.Count == 0)
            {
                return(new CakeScript
                {
                    Source = null
                });
            }

            var cakeScript = _generationService.Generate(fileChange);

            if (string.IsNullOrEmpty(cakeScript?.Source))
            {
                return(new CakeScript
                {
                    Source = null
                });
            }

            // Set line processor for generated aliases. TODO: Move to Cake.Bakery
            cakeScript.Source = cakeScript.Source.Insert(0, $"{Constants.Directive.Generated}\n");

            // Check if references changed
            if (!_cachedReferences.TryGetValue(fileChange.FileName, out var references))
            {
                references = new HashSet <string>();
            }
            if (!cakeScript.References.SetEquals(references))
            {
                _cachedReferences[fileChange.FileName] = cakeScript.References;
                OnReferencesChanged(new ReferencesChangedEventArgs(fileChange.FileName, cakeScript.References));
            }

            // Check if usings changed
            if (!_cachedUsings.TryGetValue(fileChange.FileName, out var usings))
            {
                usings = new HashSet <string>();
            }
            if (!cakeScript.Usings.SetEquals(usings))
            {
                _cachedUsings[fileChange.FileName] = cakeScript.Usings;
                OnUsingsChanged(new UsingsChangedEventArgs(fileChange.FileName, cakeScript.Usings.ToList()));
            }

            return(cakeScript);
        }
Пример #9
0
 private void QueueFileChangeForProcessing(FileChange fc)
 {
     lock (Globals.SyncLockObject)
     {
         Globals.FileChangeQueue.Enqueue(fc);
         if (!Globals.FileAnalyzerThreadRunning)
         {
             Globals.FileAnalyzerThreadRunning = true;
             Thread t = new Thread(new ThreadStart(ProcessQueueEntry));
             t.Start();
         }
     }
 }
Пример #10
0
        public static FileChange Deserialize(BinaryReader reader, out byte version)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            // TypeId and Version
            var typeAndVersion = reader.ReadInt16();

            version = (byte)(typeAndVersion & 0x00FF);
            if (typeAndVersion != Constants.FileChange.TypeAndVersion)
            {
                var type = (byte)((typeAndVersion & 0xFF00) >> 8);
                if (type != Constants.FileChange.TypeId)
                {
                    throw new InvalidOperationException($"Unsupported type: {type}");
                }
                if (version > Constants.Protocol.Latest)
                {
                    throw new InvalidOperationException($"Unsupported version: {version}");
                }
            }

            var fileChange = new FileChange();

            // From disk
            fileChange.FromDisk = reader.ReadBoolean();

            // Buffer
            fileChange.Buffer = reader.ReadString();

            // Filename
            fileChange.FileName = reader.ReadString();

            // LineChanges
            var lineChanges = reader.ReadInt32();

            for (var i = 0; i < lineChanges; i++)
            {
                var lineChange = new LineChange();
                lineChange.StartLine   = reader.ReadInt32();
                lineChange.EndLine     = reader.ReadInt32();
                lineChange.StartColumn = reader.ReadInt32();
                lineChange.EndColumn   = reader.ReadInt32();
                lineChange.NewText     = reader.ReadString();
                fileChange.LineChanges.Add(lineChange);
            }

            return(fileChange);
        }
Пример #11
0
        public async Task UpdatesColdTarget()
        {
            var svrFile = CreateFile.WithRandomText();
            var locFile = svrFile.MakeTempCopy(".locFile1");
            var server  = FcServer.StartWith(svrFile, 1, out VersionKeeperSettings cfg);
            var client  = await FcClient.StartWith(locFile, cfg);

            FileChange.Trigger(svrFile);
            await Task.Delay(1000 * 2);

            locFile.MustMatchHashOf(svrFile);

            await TmpDir.Cleanup(server, svrFile, client, locFile);
        }
Пример #12
0
        public bool Post(FileChange change)
        {
            switch (change.Mode)
            {
            case "Cut":
                return(_fileTransfer.Cut(change));

            case "Copy":
                return(_fileTransfer.Copy(change));

            default:
                return(false);
            }
        }
Пример #13
0
    public static void FileSystemWatcher_Recursive()
    {
        string currentDir   = Utility.GetRandomDirectory();
        string fileName     = Path.GetRandomFileName();
        string subDirectory = new DirectoryInfo(currentDir).CreateSubdirectory("sub").FullName;
        string fullName     = Path.Combine(subDirectory, fileName);

        bool eventRaised = false;

        using (PollingFileSystemWatcher watcher = new PollingFileSystemWatcher(currentDir, options: new EnumerationOptions {
            RecurseSubdirectories = true
        })
        {
            PollingInterval = 1
        })
        {
            AutoResetEvent signal = new AutoResetEvent(false);

            watcher.Error += (e, error) =>
            {
                throw  error.GetException();
            };

            watcher.ChangedDetailed += (e, changes) =>
            {
                Assert.Equal(1, changes.Changes.Length);
                FileChange change = changes.Changes[0];
                Assert.Equal(WatcherChangeTypes.Created, change.ChangeType);
                Assert.Equal(fileName, change.Name);
                Assert.Equal(subDirectory, change.Directory);
                eventRaised             = true;
                watcher.PollingInterval = Timeout.Infinite;
                signal.Set();
            };

            watcher.Start();

            using (FileStream file = File.Create(fullName)) { }
            signal.WaitOne(10000);
        }

        try
        {
            Assert.True(eventRaised);
        }
        finally
        {
            Directory.Delete(currentDir, true);
        }
    }
        public void TestGetChangesByCommitTwoParentsWithChange()
        {
            string             repoDir            = TestUtils.ExtractZippedRepo("vcpkg.git");
            RepositoryAnalyzer repositoryAnalyzer = new RepositoryAnalyzer(repoDir);
            CommitDelta        changes            = repositoryAnalyzer.GetChanges("dbab03a1a82913ae96bfa3c1613ade20b5ac438d");

            Assert.AreEqual(0, changes.Added.Count);
            Assert.AreEqual(0, changes.Deleted.Count);
            Assert.AreEqual(1, changes.Modified.Count);
            FileChange portfileChanges = changes.Modified.Where(x => x.Path == @"ports\openssl\portfile.cmake").First();

            Assert.AreEqual(1, portfileChanges.NumberOfLinesDeleted);
            Assert.AreEqual(0, portfileChanges.NumberOfLinesAdded);
        }
Пример #15
0
        public IEnumerable <Metric> ParseLine(FileChange change)
        {
            PowerShell shell = PowerShell.Create();

            shell.Runspace = this.runspace;

            shell
            .AddCommand("Add-Type")
            .AddParameter("Path", typeof(FileChange).Assembly.Location);

            shell.Invoke();

            shell.AddScript(this.script);
            shell.Invoke();

            shell
            .AddCommand("MetricProcessor")
            .AddParameter("change", change);

            Collection <PSObject> results;

            try
            {
                results = shell.Invoke();
            }
            catch (RuntimeException exception)
            {
                Trace.TraceError(exception.Format());

                yield break;
            }
            finally
            {
                if (shell != null)
                {
                    shell.Dispose();
                }
            }

            foreach (var obj in results)
            {
                var metric = obj.BaseObject as Metric;

                if (metric != null)
                {
                    yield return(metric);
                }
            }
        }
        public void FileChangeModel_FromFileChange_RelativePath()
        {
            FileChange fileChange = new FileChange
            {
                FileLocation = new FileLocation
                {
                    Uri = new Uri(@"\src\tools\util.cs", UriKind.RelativeOrAbsolute)
                },
                Replacements = new List <Replacement>()
            };

            FileChangeModel model = fileChange.ToFileChangeModel();

            model.FilePath.Should().Be(@"\src\tools\util.cs");
        }
        internal FileChange CreateFileChange(FileChangeVersionOne v1FileChange)
        {
            FileChange fileChange = null;

            if (v1FileChange != null)
            {
                fileChange = new FileChange
                {
                    FileLocation = CreateFileLocation(v1FileChange),
                    Replacements = v1FileChange.Replacements?.Select(CreateReplacement).ToList()
                };
            }

            return(fileChange);
        }
        private void AssertFileChange(
            string initialString,
            string expectedString,
            FileChange fileChange)
        {
            using (StringReader stringReader = new StringReader(initialString))
            {
                // Create an in-memory file from the StringReader
                ScriptFile fileToChange = new ScriptFile("TestFile.ps1", "TestFile.ps1", stringReader);

                // Apply the FileChange and assert the resulting contents
                fileToChange.ApplyChange(fileChange);
                Assert.Equal(expectedString, fileToChange.Contents);
            }
        }
Пример #19
0
        private void HandleFileChange(FilePath path, FileChange fileChange)
        {
            if (fileChange.FromDisk)
            {
                _fileSystem.RemoveFileFromBuffer(path);
                return;
            }
            if (fileChange.LineChanges != null && fileChange.LineChanges.Any())
            {
                _fileSystem.UpdateFileBuffer(path, fileChange.LineChanges);
                return;
            }

            _fileSystem.UpdateFileBuffer(path, fileChange.Buffer);
        }
Пример #20
0
        private void Visit(Fix fix, string fixPointer)
        {
            if (fix.FileChanges != null)
            {
                FileChange[] fileChanges        = fix.FileChanges.ToArray();
                string       fileChangesPointer = fixPointer.AtProperty(SarifPropertyName.FileChanges);

                for (int i = 0; i < fileChanges.Length; ++i)
                {
                    FileChange fileChange        = fileChanges[i];
                    string     fileChangePointer = fileChangesPointer.AtIndex(i);

                    Visit(fileChange, fileChangePointer);
                }
            }
        }
Пример #21
0
        private static void OnProcess(object sender, FileSystemEventArgs e)
        {
            // 用于修正触发两次的问题
            if (_lastFileChange != null && e.FullPath == _lastFileChange.FileName && _lastFileChange.Time.AddSeconds(1) > DateTime.Now)
            {
                return;
            }

            _lastFileChange = new FileChange {
                Time = DateTime.Now, FileName = e.FullPath
            };

            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                OnChanged(sender, e);
            }
        }
Пример #22
0
 private void AttachComments(FileChange change, FileDiffModel file)
 {
     foreach (var groups in change.Comments.GroupBy(c => c.DiffLineIndex))
     {
         foreach (var comment in groups.OrderBy(c => c.PostedOn))
         {
             file.Lines[groups.Key.Value].Comments.Add(new CommentModel()
             {
                 Id = comment.Id,
                 Author = UserModel.FromUser(comment.User),
                 Body = comment.Content,
                 IsAuthor = comment.UserId == User.Identity.UserId,
                 PostedOn = comment.PostedOn.ToLocalTime()
             });
         }
     }
 }
Пример #23
0
        public async Task UpdatesRunningExe()
        {
            var svrExe = CreateFile.TempCopy("windirstat.exe");
            var locExe = svrExe.MakeTempCopy("locWds.exe");
            var server = FcServer.StartWith(svrExe, 3, out VersionKeeperSettings cfg);
            var client = await FcClient.StartWith(locExe, cfg);

            var locPrc = Process.Start(locExe);

            FileChange.Trigger(svrExe);
            await Task.Delay(1000 * 2);

            locExe.MustMatchHashOf(svrExe);

            locPrc.Kill(); locPrc.Dispose();

            await TmpDir.Cleanup(server, svrExe, client, locExe);
        }
Пример #24
0
        static void Should_Install_Addins()
        {
            // Given
            var fileChange = new FileChange
            {
                FileName = CakeAddinDirectiveFile,
                FromDisk = true
            };

            // When
            var response = service.Generate(fileChange);

            // Then
            var addin = Path.GetFullPath("./tools/Addins/Cake.Wyam2.3.0.0-rc2/lib/netstandard2.0/Cake.Wyam.dll")
                        .Replace('\\', '/');

            Assert.Contains(addin, response.References);
        }
Пример #25
0
        public async Task UpdatesSelf()
        {
            var svrExe = FcClient.GetDebugExe().MakeTempCopy(".dbgSvrExe");
            var server = FcServer.StartWith(svrExe, 4,
                                            out VersionKeeperSettings cfg,
                                            CheckerRelease.FileKey);
            var client = await FcClient.StartWith("", cfg, true);

            var updatr = client.MainModule.FileName;

            FileChange.Trigger(svrExe);
            await Task.Delay(1000 * 4);

            updatr.MustMatchHashOf(svrExe);

            var newProc = FcClient.FindRunningProcess();
            await TmpDir.Cleanup(server, svrExe, newProc, updatr);
        }
        public void TestGetChangesByCommitOneParentFilesAdded()
        {
            string             repoDir            = TestUtils.ExtractZippedRepo("csharplang.git");
            RepositoryAnalyzer repositoryAnalyzer = new RepositoryAnalyzer(repoDir);
            CommitDelta        changes            = repositoryAnalyzer.GetChanges("7981ea1fb4d89571fd41e3b75f7c9f7fc178e837");

            Assert.AreEqual(2, changes.Added.Count);
            Assert.AreEqual(0, changes.Deleted.Count);
            Assert.AreEqual(0, changes.Modified.Count);
            FileChange nullableChanges = changes.Added.Where(x => x.Path == @"proposals\nullable-reference-types.md").First();

            Assert.AreEqual(0, nullableChanges.NumberOfLinesDeleted);
            Assert.AreEqual(126, nullableChanges.NumberOfLinesAdded);
            FileChange notesChanges = changes.Added.Where(x => x.Path == @"design-notes\Notes-2016-11-16.md").First();

            Assert.AreEqual(0, notesChanges.NumberOfLinesDeleted);
            Assert.AreEqual(74, notesChanges.NumberOfLinesAdded);
        }
        public void TestGetChangesByCommitOneParentFilesModified()
        {
            string             repoDir            = TestUtils.ExtractZippedRepo("csharplang.git");
            RepositoryAnalyzer repositoryAnalyzer = new RepositoryAnalyzer(repoDir);
            CommitDelta        changes            = repositoryAnalyzer.GetChanges("a5f82604eab5826bd1913cf63c7dfb8c2b187641");

            Assert.AreEqual(0, changes.Added.Count);
            Assert.AreEqual(0, changes.Deleted.Count);
            Assert.AreEqual(2, changes.Modified.Count);
            FileChange readmeChanges = changes.Modified.Where(x => x.Path == @"README.md").First();

            Assert.AreEqual(4, readmeChanges.NumberOfLinesDeleted);
            Assert.AreEqual(12, readmeChanges.NumberOfLinesAdded);
            FileChange proposalsReadmeChanges = changes.Modified.Where(x => x.Path == @"proposals\README.md").First();

            Assert.AreEqual(1, proposalsReadmeChanges.NumberOfLinesAdded);
            Assert.AreEqual(1, proposalsReadmeChanges.NumberOfLinesDeleted);
        }
Пример #28
0
        public IEnumerable<Metric> ParseLine(FileChange change)
        {
            PowerShell shell = PowerShell.Create();
            shell.Runspace = this.runspace;

            shell
                .AddCommand("Add-Type")
                .AddParameter("Path", typeof(FileChange).Assembly.Location);

            shell.Invoke();

            shell.AddScript(this.script);
            shell.Invoke();

            shell
                .AddCommand("MetricProcessor")
                .AddParameter("change", change);

            Collection<PSObject> results;

            try
            {
                results = shell.Invoke();
            }
            catch (RuntimeException exception)
            {
                Trace.TraceError(exception.Format());

                yield break;
            }
            finally
            {
                if (shell != null)
                    shell.Dispose();
            }

            foreach (var obj in results)
            {
                var metric = obj.BaseObject as Metric;

                if (metric != null)
                    yield return metric;
            }
        }
Пример #29
0
        public async Task <object> Handle(UpdateBufferRequest request)
        {
            if (request.FileName == null)
            {
                return(true);
            }

            var fileChange = new FileChange
            {
                FileName = request.FileName
            };

            if (request.Changes != null)
            {
                foreach (var change in request.Changes)
                {
                    fileChange.LineChanges.Add(new LineChange
                    {
                        StartLine   = change.StartLine,
                        StartColumn = change.StartColumn,
                        EndLine     = change.EndLine,
                        EndColumn   = change.EndColumn,
                        NewText     = change.NewText
                    });
                }

                fileChange.FromDisk = false;
            }
            else
            {
                fileChange.Buffer   = request.Buffer;
                fileChange.FromDisk = request.FromDisk;
            }
            var script = _scriptService.Generate(fileChange);

            // Avoid having buffer manager reading from disk
            request.FromDisk = false;
            request.Buffer   = script.Source;
            request.Changes  = null;

            await _workspace.BufferManager.UpdateBufferAsync(request);

            return(true);
        }
Пример #30
0
        public async Task UpdatesHotSource()
        {
            var svrFile = CreateFile.WithRandomText();
            var locFile = svrFile.MakeTempCopy(".locFile2");
            var server  = FcServer.StartWith(svrFile, 2, out VersionKeeperSettings cfg);

            FileChange.Trigger(svrFile);
            var fileRef = new FileStream(svrFile, FileMode.Open, FileAccess.ReadWrite);

            var client = await FcClient.StartWith(locFile, cfg);

            await Task.Delay(1000 * 2);

            fileRef.Dispose();

            locFile.MustMatchHashOf(svrFile);

            await TmpDir.Cleanup(server, svrFile, client, locFile);
        }
Пример #31
0
        public void FileChangeRestoreOriginal()
        {
            FileChange f;
            String     filePath;
            String     origMD5;


            //
            // Put some original content in.
            //
            filePath = Path.GetTempFileName();
            using (FileStream writer = new FileInfo(filePath).OpenWrite())
            {
                byte[] data = new System.Text.UTF8Encoding().GetBytes("This is a test message.");

                writer.Write(data, 0, data.Length);
            }
            origMD5 = InstallTest.MD5FromPath(filePath);
            f       = new FileChange(new FileInfo(filePath));

            //
            // Update the content.
            //
            using (FileStream writer = new FileInfo(filePath).OpenWrite())
            {
                byte[] data = new System.Text.UTF8Encoding().GetBytes("Some new content to replace the old.");

                writer.Write(data, 0, data.Length);
            }

            //
            // Verify the changed data.
            //
            Assert.IsTrue((origMD5.Equals(InstallTest.MD5FromPath(filePath)) == false), "Failed to update the file contents.");

            //
            // Restore the file and verify original contents.
            //
            f.Restore();
            Assert.IsTrue(origMD5.Equals(InstallTest.MD5FromPath(filePath)), "Restore operation failed.");

            new FileInfo(filePath).Delete();
        }
Пример #32
0
        public static FileChange Deserialize(BinaryReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            // TypeId and Version
            var typeAndVersion = reader.ReadInt16();

            if (typeAndVersion != Constants.FileChange.TypeAndVersion)
            {
                throw new InvalidOperationException("Type and version does not match");
            }

            var fileChange = new FileChange();

            // From disk
            fileChange.FromDisk = reader.ReadBoolean();

            // Buffer
            fileChange.Buffer = reader.ReadString();

            // Filename
            fileChange.FileName = reader.ReadString();

            // LineChanges
            var lineChanges = reader.ReadInt32();

            for (var i = 0; i < lineChanges; i++)
            {
                var lineChange = new LineChange();
                lineChange.StartLine   = reader.ReadInt32();
                lineChange.EndLine     = reader.ReadInt32();
                lineChange.StartColumn = reader.ReadInt32();
                lineChange.EndColumn   = reader.ReadInt32();
                lineChange.NewText     = reader.ReadString();
                fileChange.LineChanges.Add(lineChange);
            }

            return(fileChange);
        }
Пример #33
0
    public static void FileSystemWatcher_Filter()
    {
        string currentDir  = Utility.GetRandomDirectory();
        string fileName    = $"{Path.GetRandomFileName()}.csv";
        string fullName    = Path.Combine(currentDir, fileName);
        bool   eventRaised = false;

        using (PollingFileSystemWatcher watcher = new PollingFileSystemWatcher(currentDir, filter: "*.csv")
        {
            PollingInterval = 1
        })
        {
            AutoResetEvent signal = new AutoResetEvent(false);

            watcher.ChangedDetailed += (e, changes) =>
            {
                Assert.Equal(1, changes.Changes.Length);
                FileChange change = changes.Changes[0];
                Assert.Equal(WatcherChangeTypes.Created, change.ChangeType);
                Assert.Equal(fileName, change.Name);
                Assert.Equal(currentDir, change.Directory);
                eventRaised             = true;
                watcher.PollingInterval = Timeout.Infinite;
                signal.Set();
            };

            watcher.Start();

            using (FileStream file = File.Create(fullName)) { }
            signal.WaitOne(1000);
        }

        try
        {
            Assert.True(eventRaised);
        }
        finally
        {
            Directory.Delete(currentDir, true);
        }
    }
Пример #34
0
        public void Process(FileChange change, Metric[] metrics)
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException(typeof(OutputFilter).Name);
            }

            var matchedTargets = targets.Where(t => t.IsFileMatch(change.File));

            if (!matchedTargets.Any())
            {
                Trace.TraceWarning("Not output configuration matches the file \"{0}\".", change.File);

                return;
            }

            List <Metric> processed = new List <Metric>();

            foreach (OutputTarget target in matchedTargets)
            {
                metrics
                .Where(m => target.IsMetricMatch(m))
                .Each(m =>
                {
                    target.Process(m);
                    processed.Add(m);
                });
            }

            var warnings = new StringBuilder();

            foreach (Metric metric in metrics.Except(processed))
            {
                warnings.AppendLine("Not output configuration matches the metric \"{0}\", \"{1}\".".FormatWith(metric.Key, metric.Type));
            }

            if (warnings.Length > 0)
            {
                Trace.TraceWarning(warnings.ToString());
            }
        }
Пример #35
0
        public CakeScript Generate(FileChange fileChange)
        {
            _initializedEvent.WaitOne();

            lock (_sendReceiveLock)
            {
                // Send
                _logger.LogDebug("Sending request to server");
                FileChangeSerializer.Serialize(_writer, fileChange, Constants.Protocol.Latest);
                _writer.Flush();

                while (!_stream.DataAvailable)
                {
                    Task.Delay(10).Wait();
                }

                // Receive
                _logger.LogDebug("Received response from server");
                return(CakeScriptSerializer.Deserialize(_reader));
            }
        }
Пример #36
0
        public void Process(FileChange change, Metric[] metrics)
        {
            if (this.disposed)
                throw new ObjectDisposedException(typeof(OutputFilter).Name);

            var matchedTargets = targets.Where(t => t.IsFileMatch(change.File));

            if (!matchedTargets.Any())
            {
                Trace.TraceWarning("Not output conifguration matches the file \"{0}\".", change.File);

                return;
            }

            List<Metric> processed = new List<Metric>();

            foreach (OutputTarget target in matchedTargets)
            {
                metrics
                    .Where(m => target.IsMetricMatch(m))
                    .Each(m =>
                    {
                        target.Process(m);
                        processed.Add(m);
                    });
            }

            var warnings = new StringBuilder();

            foreach (Metric metric in metrics.Except(processed))
            {
                warnings.AppendLine("Not output configuration matches the metric \"{0}\", \"{1}\".".FormatWith(metric.Key, metric.Type));
            }

            if (warnings.Length > 0)
            {
                Trace.TraceWarning(warnings.ToString());
            }
        }
Пример #37
0
    public static void FileSystemWatcher_Renamed_Directory()
    {
        string currentDir = Utility.GetRandomDirectory();
        string fileName   = Path.GetRandomFileName();
        string subDir     = Path.Combine(currentDir, "subdir");
        string fullName   = Path.Combine(currentDir, fileName);
        string newName    = Path.Combine(subDir, fileName);

        FileSystemState watcher = new FileSystemState(currentDir, options: new EnumerationOptions()
        {
            RecurseSubdirectories = true
        });

        Directory.CreateDirectory(subDir);

        using (FileStream file = File.Create(fullName)) { }
        watcher.LoadState();

        File.Move(fullName, Path.Combine(currentDir, newName));

        var changes = watcher.GetChanges();

        try
        {
            Assert.Single(changes);
            FileChange change = changes[0];
            Assert.Equal(WatcherChangeTypes.Renamed, change.ChangeType);
            Assert.Equal(fileName, change.OldName);
            Assert.Equal(currentDir, change.OldDirectory);
            Assert.Equal(fileName, change.Name);
            Assert.Equal(subDir, change.Directory);
        }
        finally
        {
            Directory.Delete(subDir, true);
            Directory.Delete(currentDir, true);
        }
    }
Пример #38
0
        public static FileChangeModel ToFileChangeModel(this FileChange fileChange)
        {
            if (fileChange == null)
            {
                return(null);
            }

            FileChangeModel model = new FileChangeModel();

            if (fileChange.Replacements != null)
            {
                model.FilePath = fileChange.Uri.IsAbsoluteUri ?
                                 fileChange.Uri.AbsoluteUri :
                                 fileChange.Uri.OriginalString;

                foreach (Replacement replacement in fileChange.Replacements)
                {
                    model.Replacements.Add(replacement.ToReplacementModel());
                }
            }

            return(model);
        }
        private void cdeCreateConstructorCall_Apply(object sender, ApplyContentEventArgs ea)
        {
            FileChange newFileChange = new FileChange();
            newFileChange.Path = CodeRush.Documents.ActiveTextDocument.FileNode.Name;
            newFileChange.Range = _DeleteRange;
            newFileChange.Text = _NewCall;
            CodeRush.Markers.Drop(_DeleteRange.Start, MarkerStyle.Transient);
            if (_Changes == null)
                _Changes = new FileChangeCollection();
            else
                _Changes.Clear();

            _Changes.Add(newFileChange);

            TextDocument textDocument = CodeRush.Documents.Get(_TypeElement.FirstFile.Name) as TextDocument;
            if (textDocument == null)
            {
                _WaitingForViewActivate = true;
                CodeRush.File.Activate(_TypeElement.FirstFile.Name);
                return;
            }

            StartTargetPicker(textDocument);
        }
        private static CheckResult CheckDataIfStartMenuIsExpectedToExist(ICollection<FileChange> fileChanges, ICollection<Registryhange> registryChanges,
            FileChange fileChange, StartMenuData startMenuData, Registryhange registryChange)
        {
            if (fileChange == null)
            {
                return CheckResult.Failure("Could not find start menu item:'" + startMenuData.Name + "'");
            }

            if (fileChange.Type == FileChangeType.Delete)
            {
                fileChanges.Remove(fileChange);
                return CheckResult.Failure("Could not find start menu item:'" + startMenuData.Name + "'");
            }

            if (registryChange == null)
            {
                fileChanges.Remove(fileChange);
                return CheckResult.Failure("Could not find start menu item:'" + startMenuData.Name + "'");
            }

            fileChanges.Remove(fileChange);
            registryChanges.Remove(registryChange);
            return CheckResult.Succeeded(startMenuData);
        }
 protected bool Equals(FileChange other)
 {
     return Type == other.Type && string.Equals(Path, other.Path) && string.Equals(OldPath, other.OldPath) && IsDirectory.Equals(other.IsDirectory);
 }
Пример #42
0
 private bool IsAuthorized(FileChange change)
 {
     return true;
 }
Пример #43
0
        private void AddLoggingToMethod(Method method)
        {
            System.Diagnostics.Debug.WriteLine(string.Format("StartLine: >{0}< >{1}<", method.StartLine, method.StartOffset));
            System.Diagnostics.Debug.WriteLine(string.Format("EndLine:   >{0}< >{1}<", method.EndLine, method.EndOffset));
            SourceRange methodBody = method.BlockCodeRange;
            SourcePoint startBody = methodBody.Start;
            SourcePoint endBody = methodBody.End;
            System.Diagnostics.Debug.WriteLine(string.Format("StartBody: >{0}< >{1}<", startBody.Line, startBody.Offset));
            System.Diagnostics.Debug.WriteLine(string.Format("EndBody:   >{0}< >{1}<", endBody.Line, endBody.Offset));

            SourcePoint logEntryPoint = new SourcePoint();
            SourcePoint logExitPoint = new SourcePoint();

            logEntryPoint.Line = startBody.Line;
            logEntryPoint.Offset = 1;

            logExitPoint.Line = method.EndLine - 1;
            logExitPoint.Offset = endBody.Offset;

            try
            {
                SourceFile activeFile = CodeRush.Source.ActiveSourceFile;

                string LOGENTRY = @"
            #If TRACE
            Dim startTicks As Long = Log.Trace(""Enter"", LOG_APPNAME, BASE_ERRORNUMBER + 0)
            #End If

            ";

                string LOGEXIT = @"
            #If TRACE
            Log.Trace(""Exit"", LOG_APPNAME, BASE_ERRORNUMBER + 0, startTicks)
            #End If
            ";

                //FileChangeCollection fileChangeCollection = new FileChangeCollection();

                FileChange logExitFileChange = new FileChange(activeFile.Name, logExitPoint, LOGEXIT);
                fileChangeCollection.Add(logExitFileChange);

                //method.ParseOnDemandIfNeeded();

                //CodeRush.Source.ParseIfTextChanged();

                FileChange logEntryFileChange = new FileChange(activeFile.Name, logEntryPoint, LOGENTRY);
                fileChangeCollection.Add(logEntryFileChange);

                //CodeRush.Source.ParseIfTextChanged();
                // TODO(crhodes):
                // Need to figure out how to force a reparse.

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
Пример #44
0
		void FileChanged(FileChange change, IFile file)
		{
            foreach (var harness in _harnesses)
            {
				IEnumerable<Suite> affectedSuites = null;
				
                if (harness.IsSystem(file) || harness.IsDescription(file))
                {
					if( change == FileChange.Added ) 
					{
						affectedSuites = harness.HandleFiles(new[] {file});
					}
                    else if (change == FileChange.Deleted)
                    {
                        var suitesToRemove = new List<Suite>();
                        foreach (var suite in harness.Suites)
                        {
                            if (suite.SystemFile.FullPath == file.FullPath)
                                suitesToRemove.Add(suite);
                            else
                            {
                                var descriptionsToRemove = new List<Description>();
                                foreach (var description in suite.Descriptions)
                                {
                                    if (description.File.FullPath == file.FullPath)
                                        descriptionsToRemove.Add(description);
                                }
                                suite.RemoveDescriptions(descriptionsToRemove);
                            }
                        }
                        harness.RemoveSuites(suitesToRemove);
                    }
                    else
                    {
                        foreach (var suite in harness.Suites)
                        {
                            var runSuite = false;
                            if (suite.SystemFile.FullPath == file.FullPath)
                            {
                                runSuite = true;
                            }

                            foreach (var description in suite.Descriptions)
                            {
                                if (description.File.FullPath == file.FullPath)
                                    runSuite = true;
                            }

                            if (runSuite)
                                affectedSuites = new[] { suite };
                        }
                    }
                }

                if (affectedSuites != null)
                {
                    foreach (var suite in affectedSuites)
                    {
                        var now = DateTime.Now;
                        Execute(harness, new[] { suite });
                        suite.LastRun = now;
                    }
                }
            }
		}
Пример #45
0
		void NotifySubscribers(FileChange fileChange, IFile file)
		{
            foreach (var subscriber in _subscribers)
                subscriber(fileChange, file);
		}
Пример #46
0
 public void TriggerChange(FileChange changeType, IFile file)
 {
     foreach (var subscriber in _subcribers)
         subscriber.Invoke(changeType, file);
 }
		protected static void FireFileChanged(FileChange change, IFile file)
		{
			foreach( var file_changed_delegate in file_changed_delegates ) 
				file_changed_delegate(change, file);
		}
Пример #48
0
		void FileChanged(FileChange change, IFile file)
		{
            foreach (var harness in _harnesses)
            {
				IEnumerable<Suite> affectedSuites = null;
				
                if (harness.IsSystem(file) || harness.IsDescription(file))
                {
					if( change == FileChange.Added ) 
					{
						affectedSuites = harness.HandleFiles(new[] {file});
					}
                    else if (change == FileChange.Deleted)
                    {
                        var suitesToRemove = new List<Suite>();
                        foreach (var suite in harness.Suites)
                        {
                            if (suite.SystemFile == file)
                                suitesToRemove.Add(suite);
                            else
                            {
                                var descriptionsToRemove = new List<Description>();
                                foreach (var description in suite.Descriptions)
                                {
                                    if (description.File.FullPath == file.FullPath)
                                        descriptionsToRemove.Add(description);
                                }
                                suite.RemoveDescriptions(descriptionsToRemove);
                            }
                        }
                        harness.RemoveSuites(suitesToRemove);
                    }
                    else
                    {
                        foreach (var suite in harness.Suites)
                        {
                            var runSuite = false;
                            var suiteOrDescription = Path.GetFileNameWithoutExtension(file.Filename);
                            if (suite.System == suiteOrDescription)
                                runSuite = true;

                            foreach (var description in suite.Descriptions)
                            {
                                if (description.Name == suiteOrDescription)
                                    runSuite = true;
                            }

                            if (runSuite)
                                affectedSuites = new[] { suite };
                        }
                    }
                }
				
				if( affectedSuites != null )
				{
					foreach( var suite in affectedSuites )
					{
	                    var now = DateTime.Now;
	                    var delta = now.Subtract(suite.LastRun);
	                    if (delta.TotalSeconds > 2)
	                    {
	                        Execute(harness, new[] { suite });
	                        suite.LastRun = now;
	                    }
					}
				}
            }
		}
        private void targetPicker1_TargetSelected(object sender, TargetSelectedEventArgs ea)
        {
            ElementBuilder elementBuilder = new ElementBuilder();
            bool missingDefaultConstructor = _TypeElement.HasDefaultConstructor();
            if (missingDefaultConstructor)
            {
                Method defaultConstructor = elementBuilder.BuildConstructor(null);
                defaultConstructor.Visibility = MemberVisibility.Public;
                defaultConstructor.Name = _TypeElement.Name;
                elementBuilder.AddNode(null, defaultConstructor);
            }
            Method constructor = elementBuilder.BuildConstructor(null);
            constructor.Visibility = MemberVisibility.Public;
            constructor.Name = _TypeElement.Name;
            elementBuilder.AddNode(null, constructor);

            foreach (Expression initializer in _InitializerExpression.Initializers)
            {
                MemberInitializerExpression memberInitializerExpression = initializer as MemberInitializerExpression;
                if (memberInitializerExpression == null)
                    continue;

                string parameterName = FormatAsParameter(memberInitializerExpression.Name);
                IElement initializerType = memberInitializerExpression.GetInitializerType();
                if (initializerType != null)
                {
                    Param param = new Param(initializerType.Name, parameterName);
                    constructor.Parameters.Add(param);

                    Assignment assignment = new Assignment();
                    ElementReferenceExpression leftSide = new ElementReferenceExpression(memberInitializerExpression.Name);
                    if (CodeRush.Language.IdentifiersMatch(memberInitializerExpression.Name, parameterName))
                    {
                        // Old way of building a "this.Xxxx" expression:
                        //string selfQualifier = CodeRush.Language.GenerateElement(new ThisReferenceExpression());
                        //leftSide = new ElementReferenceExpression(selfQualifier +  CodeRush.Language.MemberAccessOperator + memberInitializerExpression.Name);

                        // Recommended way of building a "this.Xxxx" expression:
                        leftSide = new QualifiedElementReference(memberInitializerExpression.Name);
                        leftSide.Qualifier = new ThisReferenceExpression();
                    }
                    assignment.LeftSide = leftSide;
                    assignment.Expression = new ElementReferenceExpression(parameterName);
                    constructor.AddNode(assignment);
                }
            }
            string newConstructorCode = elementBuilder.GenerateCode();
            // Use FileChange for multi-file changes...
            FileChange newConstructor = new FileChange();
            newConstructor.Path = _TypeElement.FirstFile.Name;
            newConstructor.Range = new SourceRange(ea.Location.SourcePoint, ea.Location.SourcePoint);
            newConstructor.Text = newConstructorCode;
            _Changes.Add(newConstructor);

            DevExpress.DXCore.TextBuffers.ICompoundAction action = CodeRush.TextBuffers.NewMultiFileCompoundAction("Create Constructor from Initializer");
            try
            {
                CodeRush.File.ApplyChanges(_Changes, true, false);
            }
            finally
            {
                action.Close();
                _Changes.Clear();
            }
        }
 protected override void Analyze(FileChange fileChange, string fileChangePointer)
 {
     AnalyzeUri(fileChange.Uri, fileChangePointer);
 }