Example #1
0
        public void CopyFile(RootedCanonicalPath source, RootedCanonicalPath destination)
        {
            var sourceNode = FindFileNodeByPath(source.FullPath);
            var parser = new PathParser(destination.FullPath);
            var destParentNode = parser.GetParentNode(_rootNode);
            string destName = parser.GetLeafNodeName();

            sourceNode.CopyTo(destParentNode, destName);
        }
        public DirectoryPath ConfigPathStringToPhysicalDirectoryPath(string pathString)
        {
            pathString = pathString._NonNullTrim();

            if (pathString._IsEmpty())
            {
                throw new ArgumentNullException(nameof(pathString));
            }

            pathString = PathParser.NormalizeDirectorySeparator(pathString, true);

            if (PathParser.IsAbsolutePath(pathString))
            {
                return(pathString);
            }
            else
            {
                pathString = "/" + PathParser.Linux.NormalizeDirectorySeparator(pathString, true);

                string[] elements = PathParser.Linux.SplitAbsolutePathToElementsUnixStyle(pathString);

                string tmp = PathParser.Linux.BuildAbsolutePathStringFromElements(elements);

                tmp = PathParser.Linux.NormalizeDirectorySeparator(tmp, true);

                if (tmp[0] != '/')
                {
                    throw new ApplicationException("tmp[0] != '/'");
                }

                tmp = tmp.Substring(1);

                tmp = PathParser.Combine(Env.AppRootDir, tmp, true);

                return(tmp);
            }
        }
Example #3
0
        internal static MsBuildPublishProfilePrimitive GetPublishProfileFromXmlFile(
            string localPath,
            string originalPublishProfileName)
        {
            try
            {
                var document = new XmlDocument();
                document.Load(localPath);
                var namespaceValue = document.CreateLegacyMsBuildNamespace();
                var publishUrl     =
                    document.GetSingleNodeInnerText("//ns:Project/ns:PropertyGroup/ns:publishUrl", namespaceValue);
                publishUrl = publishUrl.Replace("$(ProjectDir)", string.Empty);

                document = null;

                var parser                         = new PathParser();
                var publishProfileName             = parser.GetLastItemFromPath(localPath);
                var originalPublishProfileNameExpr = originalPublishProfileName != null
                    ? "<-" + originalPublishProfileName
                    : string.Empty;
                Console.WriteLine($"Found publish profile {publishProfileName} {originalPublishProfileNameExpr}");

                return(new MsBuildPublishProfilePrimitive
                {
                    Name = publishProfileName,
                    PublishUrl = publishUrl
                });
            }
            catch (Exception e)
            {
                return(new MsBuildPublishProfilePrimitive
                {
                    Failed = true,
                    Error = e
                });
            }
        }
        protected override void OnStart(IServiceContainer container)
        {
            PathParser pathParser = new PathParser();
            ExpressionPathFinder expressionPathFinder = new ExpressionPathFinder();
            ConverterRegistry converterRegistry = new ConverterRegistry();

            ObjectSourceProxyFactory objectSourceProxyFactory = new ObjectSourceProxyFactory();
            objectSourceProxyFactory.Register(new UniversalNodeProxyFactory(), 0);

            SourceProxyFactory sourceFactory = new SourceProxyFactory();
            sourceFactory.Register(new LiteralSourceProxyFactory(), 0);
            sourceFactory.Register(new ExpressionSourceProxyFactory(sourceFactory, expressionPathFinder), 1);
            sourceFactory.Register(objectSourceProxyFactory, 2);

            TargetProxyFactory targetFactory = new TargetProxyFactory();
            targetFactory.Register(new UniversalTargetProxyFactory(), 0);
            targetFactory.Register(new UnityTargetProxyFactory(), 10);

            BindingFactory bindingFactory = new BindingFactory(sourceFactory, targetFactory);
            StandardBinder binder = new StandardBinder(bindingFactory);

            container.Register<IBinder>(binder);
            container.Register<IBindingFactory>(bindingFactory);
            container.Register<IConverterRegistry>(converterRegistry);

            container.Register<IExpressionPathFinder>(expressionPathFinder);
            container.Register<IPathParser>(pathParser);

            container.Register<INodeProxyFactory>(objectSourceProxyFactory);
            container.Register<INodeProxyFactoryRegister>(objectSourceProxyFactory);

            container.Register<ISourceProxyFactory>(sourceFactory);
            container.Register<ISourceProxyFactoryRegistry>(sourceFactory);

            container.Register<ITargetProxyFactory>(targetFactory);
            container.Register<ITargetProxyFactoryRegister>(targetFactory);
        }
Example #5
0
        public IEnumerable <EditItem> Parse(IEnumerable <string> tokens)
        {
            //defaults
            EditItem.Location location = EditItem.Location.Beginning;
            Hive hive = Hive.User;

            char[] charsToTrim = { '\'', '\"' };
            foreach (var token in tokens)
            {
                string     trimmed    = token.Trim(charsToTrim);
                PathParser pathParser = new PathParser(trimmed);
                ParmParser parmParser = new ParmParser(trimmed);

                if (pathParser.IsPath)
                {
                    var item = new EditItem(pathParser.Path, pathParser.Action, hive, location);
                    editItemList.Add(item);
                }
                else if (parmParser.IsParm)
                {
                    if (parmParser.HiveParm.HasValue)
                    {
                        hive = parmParser.HiveParm.Value;
                    }
                    if (parmParser.LocationParm.HasValue)
                    {
                        location = parmParser.LocationParm.Value;
                    }
                }
                else
                {
                    throw new Exception($"Bad parameter: {token}");
                }
            }
            return(editItemList);
        }
Example #6
0
        public void GetAllPathAsyncTestR2()
        {
            // arrange
            Program.path = "C:\\Test";
            string        mainPuth   = "C:\\Test";
            bool          r1         = false;
            bool          r2         = true;
            List <string> resultList = new List <string>();

            resultList.Add("1tseT\\");
            resultList.Add("2tseT\\");
            resultList.Add("3tseT\\2tseT\\");
            PathParser pp = new PathParser();

            // act
            pp.GetAllPathAsync(mainPuth, r1, r2).GetAwaiter().GetResult();
            var actual = pp.Result;

            // assert
            for (int i = 0; i < actual.Count; i++)
            {
                Assert.AreEqual(resultList[i], actual[i]);
            }
        }
Example #7
0
        private FolderMetaData GetMetadataForUpdate(IHttpRequest request, UpdateReportData updatereport, TFSSourceControlProvider sourceControlProvider, out int targetRevision)
        {
            string         basePath = PathParser.GetLocalPath(request, updatereport.SrcPath);
            FolderMetaData metadata;

            if (updatereport.TargetRevision != null)
            {
                targetRevision = int.Parse(updatereport.TargetRevision);
            }
            else
            {
                targetRevision = GetSDKObject().GetLastestVersionNum(basePath);
                //    targetRevision = sourceControlProvider.GetLatestVersion();
            }

            /*
             * if (updatereport.IsCheckOut)
             * {
             *  metadata = (FolderMetaData)sourceControlProvider.GetItemsWithoutProperties(targetRevision, basePath, Recursion.Full);
             * }
             * else
             * {
             * */
            metadata = sourceControlProvider.GetChangedItems(basePath,
                                                             int.Parse(updatereport.Entries[0].Rev),
                                                             targetRevision,
                                                             updatereport);

            //      }
            if (metadata != null)
            {
                loader = new AsyncItemLoader(metadata, sourceControlProvider);
                ThreadPool.QueueUserWorkItem(state => loader.Start());
            }
            return(metadata);
        }
Example #8
0
        static void Main(string[] args)
        {
            PrintHello();

            var parser      = new PathParser(args);
            var filesToRead = parser.Files;

            if (filesToRead.Length == 0)
            {
                PrintByeByeAndExit();
            }

            var stringsTable = DataReader.Load_v1(filesToRead);
            var objectsTable = DataReader.Load_v2(filesToRead);

            var manipulator = new ObjectDataManipulator(objectsTable);
            var printer1    = new ConsolePrinter(manipulator);

            printer1.PrintEachSaldo();
            printer1.PrintGlobalSaldo();
            printer1.PrintMostHardworking();

            PrintByeByeAndExit();
        }
Example #9
0
        protected override void Handle(IHttpContext context,
                                       TFSSourceControlProvider sourceControlProvider)
        {
            IHttpRequest  request  = context.Request;
            IHttpResponse response = context.Response;

            MergeData data = Helper.DeserializeXml <MergeData>(request.InputStream);

            string activityId = PathParser.GetActivityId(data.Source.Href);

            response.AppendHeader("Cache-Control", "no-cache");

            try
            {
                MergeActivityResponse mergeResponse = sourceControlProvider.MergeActivity(activityId);
                SetResponseSettings(response, "text/xml", Encoding.UTF8, 200);
                response.SendChunked = true;
                using (StreamWriter output = new StreamWriter(response.OutputStream))
                {
                    WriteMergeResponse(request, mergeResponse, output);
                }
            }
            catch (ConflictException ex)
            {
                SetResponseSettings(response, "text/xml; charset=\"utf-8\"", Encoding.UTF8, 409);
                string responseContent =
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<D:error xmlns:D=\"DAV:\" xmlns:m=\"http://apache.org/dav/xmlns\" xmlns:C=\"svn:\">\n" +
                    "<C:error/>\n" +
                    "<m:human-readable errcode=\"160024\">\n" +
                    ex.Message + "\n" +
                    "</m:human-readable>\n" +
                    "</D:error>\n";
                WriteToResponse(response, responseContent);
            }
        }
Example #10
0
        public override void Execute(MonsterFighter fighter)
        {
            if (fighter.FighterStats.Stats.MovementPoints <= 0)
            {
                return;
            }

            Fighter lower = fighter.Team.LowerFighter();
            var     path  = new Pathfinder(fighter.Fight.Map, fighter.CellId);

            path.PutEntities(fighter.Fight.GetAllFighters());
            var cells = path.FindPath(lower.CellId);

            if (cells == null || cells.Count() <= 1)
            {
                return;
            }
            cells.Remove(cells.Last());
            cells.Insert(0, fighter.CellId);
            cells = cells.Take(fighter.FighterStats.Stats.MovementPoints + 1).ToList();
            sbyte direction = PathParser.GetDirection(cells.Last());

            fighter.Move(cells, cells.Last(), direction);
        }
Example #11
0
        private void CreateFileRecursive(ReadOnlySpan <byte> path, ref SaveFileInfo fileInfo)
        {
            var parser = new PathParser(path);
            var key    = new SaveEntryKey(parser.GetCurrent(), 0);

            int parentIndex = CreateParentDirectoryRecursive(ref parser, ref key);

            int index = FileTable.GetIndexFromKey(ref key).Index;
            TableEntry <SaveFileInfo> fileEntry = default;

            // File already exists. Update file info.
            if (index >= 0)
            {
                FileTable.GetValue(index, out fileEntry);
                fileEntry.Value = fileInfo;
                FileTable.SetValue(index, ref fileEntry);
                return;
            }

            fileEntry.Value = fileInfo;
            index           = FileTable.Add(ref key, ref fileEntry);

            LinkFileToParent(parentIndex, index);
        }
Example #12
0
        internal static MsBuildPublishProfilePrimitive GetPublicProfileWithMsBuild(
            string localPath,
            string originalPublishProfileName)
        {
            try
            {
                ProjectCollection.GlobalProjectCollection.UnloadAllProjects();

                var publishProfile                 = new Project(localPath);
                var parser                         = new PathParser();
                var publishProfileName             = parser.GetLastItemFromPath(localPath);
                var publishUrl                     = MsBuildPropertyStatics.GetPublishUrl(publishProfile);
                var originalPublishProfileNameExpr = originalPublishProfileName != null
                    ? "<-" + originalPublishProfileName
                    : string.Empty;

                Console.WriteLine($"Found publish profile {publishProfileName} {originalPublishProfileNameExpr}");

                return(new MsBuildPublishProfilePrimitive
                {
                    Name = publishProfileName,
                    PublishUrl = publishUrl
                });
            }
            catch (Exception e) when
                (e is InvalidProjectFileException ||
                e is InvalidOperationException ||
                e is IOException)
            {
                return(new MsBuildPublishProfilePrimitive
                {
                    Failed = true,
                    Error = e
                });
            }
        }
Example #13
0
        /// <summary>
        /// Get the static field/property/method of the class
        /// </summary>
        /// <param name="attribute"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        private static object GetStaticProperty(DataListAttribute attribute, IList <string> path)
        {
            Type   type;
            object property;
            string segment;
            int    count = 0;

            type = ClassType.GetType(attribute.DllName, attribute.ClassName);

            segment  = path[count++];
            property = Reflect.GetStaticDataMember(type, segment);


            for ( ; count < path.Count; count++)
            {
                segment = path[count];

                Property propertyInfo = PathParser.BreakVariable(segment);
                property = Reflect.GetDataMember(property, propertyInfo.Name);

                // If there was a subscript get the data object
                if (propertyInfo.Index != null)
                {
                    if (property is IDictionary)
                    {
                        property = ((IDictionary)property)[propertyInfo.Index];
                    }
                    else if (property is IList)
                    {
                        property = ((IList)property)[(int)propertyInfo.Index];
                    }
                }
            }

            return(property);
        }
Example #14
0
        public void Matches_Wildcard_NoMatch()
        {
            var parser = new PathParser("/foo/*", false);

            Assert.False(parser.Matches("/foo"));
        }
Example #15
0
        public void Matches_Parameter_NoMatch()
        {
            var parser = new PathParser("/foo/:param", false);

            Assert.False(parser.Matches("/foo/bar/baz"));
        }
Example #16
0
        public void Matches_Normal_FindsMatch()
        {
            var parser = new PathParser("/foo", true);

            Assert.True(parser.Matches("/foo"));
        }
Example #17
0
        public void Matches_EnforceTrailingSlash_NoMatch()
        {
            var parser = new PathParser("/foo/", false);

            Assert.False(parser.Matches("/foo"));
        }
Example #18
0
        private FileNode CreateFile(string path, Func<FolderNode, string, FileNode> createStrategy)
        {
            FileNode resultNode = null;
            var currentNode = _rootNode;

            var parser = new PathParser(path);
            parser.WithEachButLastFileSystemNodeNameDo(folderName => currentNode = currentNode.CreateOrReuseFolderNode(folderName));
            parser.WithLastFileSystemNodeNameDo(filename => resultNode = createStrategy(currentNode, filename));
            return resultNode;
        }
Example #19
0
        private FileSystemNode FindNodeByPath(string path)
        {
            FileSystemNode currentNode = _rootNode;

            var parser = new PathParser(path);
            parser.WithEachFileSystemNodeNameDo(delegate(string folderName)
                {
                    if (currentNode != null && currentNode is FolderNode)
                    {
                        var folderNode = (FolderNode)currentNode;
                        currentNode = folderNode.FindChildNodeNamed(folderName);
                    }
                });

            return currentNode;
        }
        private static IEnumerable <KeyValuePair <char, IList <float> > > GetCommands(string text)
        {
            var parser = new PathParser(text);

            float x1;
            float y1;
            float x2;
            float y2;
            float x3;
            float y3;

            var action = '\0';

            while (!parser.Eof)
            {
                if (parser.TryGetCommand(out var cmd))
                {
                    action = cmd;
                }

                switch (char.ToUpper(action))
                {
                case 'Z':
                    yield return(new KeyValuePair <char, IList <float> >(action, null));

                    break;

                case 'M':
                    if (parser.TryGetValue(out x1, out y1))
                    {
                        yield return(new KeyValuePair <char, IList <float> >(action, new List <float>()
                        {
                            x1, y1
                        }));
                    }
                    action = action == 'M' ? 'L' : 'l';
                    break;

                case 'L':
                    if (parser.TryGetValue(out x1, out y1))
                    {
                        yield return(new KeyValuePair <char, IList <float> >(action, new List <float>()
                        {
                            x1, y1
                        }));
                    }
                    break;

                case 'T':
                    if (parser.TryGetValue(out x1, out y1))
                    {
                        yield return(new KeyValuePair <char, IList <float> >(action, new List <float>()
                        {
                            x1, y1
                        }));
                    }
                    break;

                case 'H':
                case 'V':
                    if (parser.TryGetValue(out x1))
                    {
                        yield return(new KeyValuePair <char, IList <float> >(action, new List <float>()
                        {
                            x1
                        }));
                    }
                    break;

                case 'C':
                    if (parser.TryGetValue(out x1, out y1, out x2, out y2, out x3, out y3))
                    {
                        yield return(new KeyValuePair <char, IList <float> >(action, new List <float>()
                        {
                            x1, y1, x2, y2, x3, y3
                        }));
                    }
                    break;

                case 'S':
                case 'Q':
                    if (parser.TryGetValue(out x1, out y1, out x2, out y2))
                    {
                        yield return(new KeyValuePair <char, IList <float> >(action, new List <float>()
                        {
                            x1, y1, x2, y2
                        }));
                    }
                    break;

                case 'A':
                    if (parser.TryGetArcValue(out x1, out x2, out x3, out var flag1, out var flag2, out y1, out y2))
                    {
                        yield return(new KeyValuePair <char, IList <float> >(action,
                                                                             new List <float>()
                        {
                            x1, x2, x3, flag1, flag2, y1, y2
                        }));
                    }
                    break;

                default:
                    parser.TryGetValue(out x1);
                    break;
                }
            }
        }
Example #21
0
        private async Task GetSampleDataAsync()
        {
            if (this._groups.Count != 0)
            {
                return;
            }

            Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

            string jsonText = await FileIO.ReadTextAsync(file);

            JsonObject jsonObject = JsonObject.Parse(jsonText);
            JsonArray  jsonArray  = jsonObject["PointsOfInterest"].GetArray();

            foreach (JsonValue groupValue in jsonArray)
            {
                JsonObject groupObject = groupValue.GetObject();

                IJsonValue shapeValue;
                List <BasicGeoposition> shapeList;
                Geopath shapePath = null;

                if (groupObject.TryGetValue("Shape", out shapeValue))
                {
                    //JsonObject shapeObject = shapeValue.GetObject();
                    string shape = shapeValue.GetString();
                    if (PathParser.TryParseEncodedValue(shape, out shapeList))
                    {
                        shapePath = new Geopath(shapeList);
                    }
                }



                IJsonValue bestMapViewBoxValue;
                List <BasicGeoposition> bestMapViewBoxList = new List <BasicGeoposition>();
                GeoboundingBox          bestMapViewBox     = null;
                if (groupObject.TryGetValue("BestMapViewBox", out bestMapViewBoxValue))
                {
                    foreach (JsonValue itemValue in bestMapViewBoxValue.GetArray())
                    {
                        JsonObject       itemObject     = itemValue.GetObject();
                        IJsonValue       locationValue  = itemObject["location"];
                        JsonObject       locationObject = locationValue.GetObject();
                        BasicGeoposition location       = new BasicGeoposition {
                            Latitude = locationObject["lat"].GetNumber(), Longitude = locationObject["lng"].GetNumber()
                        };
                        bestMapViewBoxList.Add(location);
                    }
                    bestMapViewBox = GeoboundingBox.TryCompute(bestMapViewBoxList);
                }

                SampleDataGroup group = new SampleDataGroup(groupObject["UniqueId"].GetString(),
                                                            groupObject["Title"].GetString(),
                                                            groupObject["Subtitle"].GetString(),
                                                            groupObject["ImagePath"].GetString(),
                                                            groupObject["Description"].GetString(),
                                                            bestMapViewBox,
                                                            shapePath);

                foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                {
                    JsonObject itemObject = itemValue.GetObject();
                    IJsonValue geometryValue;
                    Geopoint   location = null;
                    string     address  = null;
                    if (itemObject.TryGetValue("geometry", out geometryValue))
                    {
                        JsonObject geometryObject = geometryValue.GetObject();
                        IJsonValue locationValue  = geometryObject["location"];
                        JsonObject locationObject = locationValue.GetObject();
                        location = new Geopoint(new BasicGeoposition {
                            Latitude = locationObject["lat"].GetNumber(), Longitude = locationObject["lng"].GetNumber()
                        });
                    }

                    IJsonValue addressValue = null;
                    if (itemObject.TryGetValue("formatted_address", out addressValue))
                    {
                        address = addressValue.GetString();
                    }

                    group.Items.Add(new SampleDataItem(itemObject["UniqueId"].GetString(),
                                                       itemObject["Title"].GetString(),
                                                       itemObject["Subtitle"].GetString(),
                                                       itemObject["ImagePath"].GetString(),
                                                       itemObject["Description"].GetString(),
                                                       itemObject["Content"].GetString(),
                                                       location,
                                                       address));
                }
                this.Groups.Add(group);
            }
        }
Example #22
0
 public int CompareCurrentSegment(PathParser other)
 {
     return(string.Compare(Path, _startIndex, other.Path, other._startIndex, _length, StringComparison.OrdinalIgnoreCase));
 }
Example #23
0
 public static List<PathInfo> ProcessPathData(string dv, double scale)
 {
     if (dv == null) return null;
     var pp = new PathParser(dv, scale);
     return pp.pathData;
 }
Example #24
0
 public static List<PathInfo> ProcessPathData(string dv)
 {
     var pp = new PathParser(dv);
     return pp.pathData;
 }
        internal PartitionedQueryExecutionInfoInternal GetPartitionedQueryExecutionInfoInternal(
            SqlQuerySpec querySpec,
            PartitionKeyDefinition partitionKeyDefinition,
            bool requireFormattableOrderByQuery,
            bool isContinuationExpected)
        {
            if (querySpec == null || partitionKeyDefinition == null)
            {
                return(DefaultInfoInternal);
            }

            string queryText = JsonConvert.SerializeObject(querySpec);

            List <string> paths = new List <string>(partitionKeyDefinition.Paths);

            List <string[]> pathParts = new List <string[]>();

            paths.ForEach(path =>
            {
                pathParts.Add(PathParser.GetPathParts(path).ToArray());
            });

            string[] allParts     = pathParts.SelectMany(parts => parts).ToArray();
            uint[]   partsLengths = pathParts.Select(parts => (uint)parts.Length).ToArray();

            PartitionKind partitionKind = partitionKeyDefinition.Kind;

            this.Initialize();

            byte[] buffer = new byte[InitialBufferSize];
            uint   errorCode;
            uint   serializedQueryExecutionInfoResultLength;

            unsafe
            {
                fixed(byte *bytePtr = buffer)
                {
                    errorCode = ServiceInteropWrapper.GetPartitionKeyRangesFromQuery(
                        this.serviceProvider,
                        queryText,
                        requireFormattableOrderByQuery,
                        isContinuationExpected,
                        allParts,
                        partsLengths,
                        (uint)partitionKeyDefinition.Paths.Count,
                        partitionKind,
                        new IntPtr(bytePtr),
                        (uint)buffer.Length,
                        out serializedQueryExecutionInfoResultLength);

                    if (errorCode == DISP_E_BUFFERTOOSMALL)
                    {
                        buffer = new byte[serializedQueryExecutionInfoResultLength];
                        fixed(byte *bytePtr2 = buffer)
                        {
                            errorCode = ServiceInteropWrapper.GetPartitionKeyRangesFromQuery(
                                this.serviceProvider,
                                queryText,
                                requireFormattableOrderByQuery,
                                isContinuationExpected,
                                allParts,
                                partsLengths,
                                (uint)partitionKeyDefinition.Paths.Count,
                                partitionKind,
                                new IntPtr(bytePtr2),
                                (uint)buffer.Length,
                                out serializedQueryExecutionInfoResultLength);
                        }
                    }
                }
            }

            string serializedQueryExecutionInfo = Encoding.UTF8.GetString(buffer, 0, (int)serializedQueryExecutionInfoResultLength);

            Exception exception = Marshal.GetExceptionForHR((int)errorCode);

            if (exception != null)
            {
                DefaultTrace.TraceInformation("QueryEngineConfiguration: " + this.queryengineConfiguration);
                throw new BadRequestException(
                          "Message: " + serializedQueryExecutionInfo,
                          exception);
            }

            PartitionedQueryExecutionInfoInternal queryInfoInternal =
                JsonConvert.DeserializeObject <PartitionedQueryExecutionInfoInternal>(
                    serializedQueryExecutionInfo,
                    new JsonSerializerSettings {
                DateParseHandling = DateParseHandling.None
            });

            return(queryInfoInternal);
        }
Example #26
0
    protected async Task <FileObject> AddFileAsync(FileParameters option, CreateFileCallback createFileCallback, CancellationToken cancel = default, bool noOpen = false)
    {
        using (VfsPathParserContext ctx = await ParsePathInternalAsync(option.Path, cancel))
        {
            if (ctx.Exception == null)
            {
                if (ctx.LastEntity is VfsFile file)
                {
                    // Already exists
                    if (option.Mode == FileMode.CreateNew)
                    {
                        throw new VfsException(option.Path, $"The file already exists.");
                    }

                    if (noOpen == false)
                    {
                        return(await file.OpenAsync(option, ctx.NormalizedPath, cancel));
                    }
                    else
                    {
                        return(null !);
                    }
                }
                else
                {
                    // There is existing another type object
                    throw new VfsException(option.Path, $"There are existing object at the speficied path.");
                }
            }

            if (ctx.Exception is VfsNotFoundException && ctx.RemainingPathElements.Count == 1 && ctx.LastEntity is VfsDirectory && option.Mode != FileMode.Open)
            {
                // Create new RAM file
                VfsDirectory lastDir = (VfsDirectory)ctx.LastEntity;

                string fileName = ctx.RemainingPathElements.Peek();

                var newFile = await createFileCallback(fileName, option, cancel);

                string fullPath = PathParser.Combine(ctx.NormalizedPath, fileName);

                try
                {
                    await lastDir.AddFileAsync(newFile);
                }
                catch
                {
                    await newFile.ReleaseLinkAsync(true);

                    throw;
                }

                if (noOpen == false)
                {
                    return(await newFile.OpenAsync(option, fullPath, cancel));
                }
                else
                {
                    return(null !);
                }
            }
            else
            {
                throw ctx.Exception;
            }
        }
    }
Example #27
0
 public TestPathParser()
 {
     _parser = new PathParser(new NullLogger(), '/');
 }
Example #28
0
        private static bool ControlTemplateMatchesPathComponent(ref InputTemplate.ControlTemplate controlTemplate, ref PathParser parser)
        {
            // Match template.
            var template = parser.current.template;

            if (template.length > 0)
            {
                if (!StringMatches(template, controlTemplate.template))
                {
                    return(false);
                }
            }

            // Match usage.
            var usage = parser.current.usage;

            if (usage.length > 0)
            {
                var usageCount      = controlTemplate.usages.Count;
                var anyUsageMatches = false;
                for (var i = 0; i < usageCount; ++i)
                {
                    if (StringMatches(usage, controlTemplate.usages[i]))
                    {
                        anyUsageMatches = true;
                        break;
                    }
                }

                if (!anyUsageMatches)
                {
                    return(false);
                }
            }

            // Match name.
            var name = parser.current.name;

            if (name.length > 0)
            {
                if (!StringMatches(name, controlTemplate.name))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #29
0
        private void MoveFileSystemItem(FileSystemNode sourceNode, RootedCanonicalPath destination)
        {
            var parser = new PathParser(destination.FullPath);
            var destParentNode = parser.GetParentNode(_rootNode);
            string destName = parser.GetLeafNodeName();

            sourceNode.MoveTo(destParentNode, destName);
        }
Example #30
0
 public VirtualFileSystemParams(FileSystemMode mode = FileSystemMode.Default) : base(PathParser.GetInstance(FileSystemStyle.Linux), mode)
 {
 }
Example #31
0
        internal static MsBuildProjectPrimitive GetProjectFromXmlFile(
            string localPath,
            string originalProjectName)
        {
            try
            {
                var document = new XmlDocument();
                document.Load(localPath);
                var           namespaceValue = document.CreateLegacyMsBuildNamespace();
                string        defaultNamespace = null, assemblyName;
                List <string> targetFrameworks = null, relativePaths;
                bool          isNetCoreProject;

                if (namespaceValue.NsManager != null)
                {
                    // legacy .NET Framework
                    defaultNamespace = document.GetSingleNodeInnerText("//ns:Project/ns:PropertyGroup/ns:RootNamespace",
                                                                       namespaceValue);
                    assemblyName = document.GetSingleNodeInnerText("//ns:Project/ns:PropertyGroup/ns:AssemblyName",
                                                                   namespaceValue);
                    relativePaths = document.GetNodesPropertyValue("//ns:Project/ns:ItemGroup/ns:ProjectReference",
                                                                   "Include", namespaceValue)?.ToList();
                    isNetCoreProject = false;
                }
                else
                {
                    // .NET Core and newer
                    assemblyName =
                        document.GetSingleNodeInnerText("//Project/PropertyGroup/AssemblyName", namespaceValue);
                    targetFrameworks = document
                                       .GetSingleNodeInnerText("//Project/PropertyGroup/TargetFramework", namespaceValue)?.Split(';')
                                       ?.ToList();
                    relativePaths = document
                                    .GetNodesPropertyValue("//Project/ItemGroup/ProjectReference", "Include", namespaceValue)
                                    ?.ToList();
                    isNetCoreProject = true;
                }

                document = null;

                var parser      = new PathParser();
                var projectName = parser.GetLastItemFromPath(localPath);
                var originalProjectNameExpr = originalProjectName != null
                    ? "<-" + originalProjectName
                    : string.Empty;
                Console.WriteLine($"Found project {projectName} {originalProjectNameExpr}");

                return(new MsBuildProjectPrimitive
                {
                    Name = projectName,
                    TargetFrameworks = targetFrameworks,
                    DefaultNamespace = defaultNamespace,
                    AssemblyName = assemblyName,
                    RelativeProjectReferencePaths = relativePaths,
                    IsNetCoreProject = isNetCoreProject
                });
            }
            catch (Exception e)
            {
                return(new MsBuildProjectPrimitive
                {
                    Failed = true,
                    Error = e
                });
            }
        }
Example #32
0
    protected override async Task <FileSystemEntity[]> EnumDirectoryImplAsync(string directoryPath, EnumDirectoryFlags flags, CancellationToken cancel = default)
    {
        using (VfsPathParserContext ctx = await ParsePathInternalAsync(directoryPath, cancel))
        {
            if (ctx.Exception != null)
            {
                throw ctx.Exception;
            }

            if (ctx.LastEntity is VfsDirectory thisDirObject)
            {
                var entities = await thisDirObject.EnumEntitiesAsync(flags, cancel);

                List <FileSystemEntity> ret = new List <FileSystemEntity>();

                FileSystemEntity thisDir = new FileSystemEntity(
                    fullPath: ctx.NormalizedPath,
                    name: ".",
                    attributes: thisDirObject.Attributes,
                    creationTime: thisDirObject.CreationTime,
                    lastWriteTime: thisDirObject.LastWriteTime,
                    lastAccessTime: thisDirObject.LastAccessTime
                    );

                ret.Add(thisDir);

                foreach (var entity in entities)
                {
                    if (entity is VfsDirectory dirObject)
                    {
                        FileMetadata meta = await dirObject.GetMetadataAsync(cancel);

                        FileSystemEntity dir = new FileSystemEntity(
                            fullPath: PathParser.Combine(ctx.NormalizedPath, entity.Name),
                            name: entity.Name,
                            attributes: meta.Attributes ?? FileAttributes.Directory,
                            creationTime: meta.CreationTime ?? Util.ZeroDateTimeOffsetValue,
                            lastWriteTime: meta.LastWriteTime ?? Util.ZeroDateTimeOffsetValue,
                            lastAccessTime: meta.LastAccessTime ?? Util.ZeroDateTimeOffsetValue
                            );

                        ret.Add(dir);
                    }
                    else if (entity is VfsFile fileObject)
                    {
                        FileMetadata meta = await fileObject.GetMetadataAsync(cancel);

                        FileSystemEntity file = new FileSystemEntity(
                            fullPath: PathParser.Combine(ctx.NormalizedPath, entity.Name),
                            name: entity.Name,
                            size: meta.Size,
                            physicalSize: meta.PhysicalSize,
                            attributes: meta.Attributes ?? FileAttributes.Directory,
                            creationTime: meta.CreationTime ?? Util.ZeroDateTimeOffsetValue,
                            lastWriteTime: meta.LastWriteTime ?? Util.ZeroDateTimeOffsetValue,
                            lastAccessTime: meta.LastAccessTime ?? Util.ZeroDateTimeOffsetValue
                            );
                        ret.Add(file);
                    }
                }

                return(ret.ToArray());
            }
            else
            {
                throw new VfsNotFoundException(directoryPath, "Directory not found.");
            }
        }
    }
Example #33
0
        public Path(string pathString)
        {
            var parser = new PathParser(pathString);

            PathCommands = parser.Commands.ToArray();
        }
Example #34
0
        static void Main(string[] args)
        {
            var exit = false;

            Console.CancelKeyPress += delegate {
                exit = true;
            };

            var arguments = ArgumentParser.Parse(args);

            if (arguments.Help)
            {
                Console.WriteLine("AutoTest.Server.exe command line arguments");
                Console.WriteLine("");
                Console.WriteLine("To specify watch directory on startup you can type:");
                Console.WriteLine("\tAutoTest.WinForms.exe [WATCH_DIRECTORY] [--local-config-location=/path]");
                return;
            }
            string token = null;

            if (arguments.WatchToken != null)
            {
                var tokenExists = Directory.Exists(arguments.WatchToken) || File.Exists(arguments.WatchToken);
                if (arguments.WatchToken.Contains(".." + Path.DirectorySeparatorChar) || !tokenExists)
                {
                    token = new PathParser(Environment.CurrentDirectory).ToAbsolute(arguments.WatchToken);
                }
                else
                {
                    token = arguments.WatchToken;
                }
            }
            else
            {
                token = Environment.CurrentDirectory;
            }
            Debug.EnableLogging(new ConsoleWriter());
            var watchDirectory = token;

            if (File.Exists(token))
            {
                watchDirectory = Path.GetDirectoryName(token);
            }
            BootStrapper.Configure();
            BootStrapper.Container
            .Register(
                Component.For <IMessageProxy>()
                .Forward <IRunFeedbackView>()
                .Forward <IInformationFeedbackView>()
                .Forward <IConsumerOf <AbortMessage> >()
                .ImplementedBy <MessageProxy>().LifeStyle.Singleton);

            using (var server = new MessageEndpoint(watchDirectory, createHandlers())) {
                var proxy = BootStrapper.Services.Locate <IMessageProxy>();
                proxy.SetMessageForwarder(server);
                BootStrapper.Services.Locate <IRunResultCache>().EnabledDeltas();
                BootStrapper.InitializeCache(token);
                using (var watcher = BootStrapper.Services.Locate <IDirectoryWatcher>())
                {
                    if (arguments.ConfigurationLocation != null)
                    {
                        var configurationLocation = arguments.ConfigurationLocation;
                        if (Directory.Exists(Path.Combine(token, configurationLocation)))
                        {
                            configurationLocation = Path.Combine(token, configurationLocation);
                        }
                        watcher.LocalConfigurationIsLocatedAt(configurationLocation);
                    }
                    watcher.Watch(token, false);
                    Debug.EnableLogging(new ConsoleWriter());

                    while (!exit && server.IsAlive)
                    {
                        Thread.Sleep(100);
                    }
                    Console.WriteLine("exiting");
                }
                Console.WriteLine("shutting down");
                BootStrapper.ShutDown();
                Console.WriteLine("disposing server");
            }
            Console.WriteLine("done");
        }
Example #35
0
        public void Matches_Normal_NoMatch()
        {
            var parser = new PathParser("/foo", true);

            Assert.False(parser.Matches("/bar"));
        }
Example #36
0
        private static bool ControlLayoutMatchesPathComponent(ref InputControlLayout.ControlItem controlItem, ref PathParser parser)
        {
            // Match layout.
            var layout = parser.current.layout;

            if (layout.length > 0)
            {
                if (!StringMatches(layout, controlItem.layout))
                {
                    return(false);
                }
            }

            // Match usage.
            var usage = parser.current.usage;

            if (usage.length > 0)
            {
                var usageCount      = controlItem.usages.Count;
                var anyUsageMatches = false;
                for (var i = 0; i < usageCount; ++i)
                {
                    if (StringMatches(usage, controlItem.usages[i]))
                    {
                        anyUsageMatches = true;
                        break;
                    }
                }

                if (!anyUsageMatches)
                {
                    return(false);
                }
            }

            // Match name.
            var name = parser.current.name;

            if (name.length > 0)
            {
                if (!StringMatches(name, controlItem.name))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #37
0
        private void CreateDirectory(string path)
        {
            FolderNode currentNode = null;

            var parser = new PathParser(path);
            parser.WithFirstFileSystemNodeNameDo(driveName => currentNode = (FolderNode) _rootNode.FindChildNodeNamed(driveName));
            if (currentNode == null) throw new DirectoryNotFoundException(string.Format("Can't create the directory '{0}' since the drive does not exist.", path));
            parser.WithEachButFirstFileSystemNodeNameDo(folderName => currentNode = currentNode.CreateOrReuseFolderNode(folderName));
        }