//todo: Link content to a content cache similar to openwraps package cache. Use same mechanism?
        public ContentLocator()
        {
            var environment = ServiceLocator.GetService<IEnvironment>();
            var packageManager = ServiceLocator.GetService<IPackageManager>();

            var baseDirectory = LocalFileSystem.Instance.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory);

            contentRoot = baseDirectory.GetDirectory("Content");
            contentRoot.MustExist();

            foreach (var scopedDescriptor in environment.ScopedDescriptors)
            {
                var files = packageManager.GetProjectExports<ContentFolderExport>(scopedDescriptor.Value.Value,
                                                                                  environment.ProjectRepository,
                                                                                  environment.ExecutionEnvironment);

                contentPathSources = files.SelectMany(x => x).Distinct().Select(x => x.Directory).ToList();
                foreach (
                    var pathSource in
                        contentPathSources.SelectMany(contentPathSource => contentPathSource.Directories()))
                {
                    pathSource.LinkTo(contentRoot.GetDirectory(pathSource.Name).MustExist().Path.FullPath);
                }
            }
        }
 public static void CopyFilesInfo(this IDirectory source, IDirectory target, bool overwrite = true)
 {
     foreach (var file in source.Files())
     {
         file.CopyInto(target, overwrite);
     }
 }
Example #3
0
        public void OnFileRequested(HttpRequest request, IDirectory directory)
        {
            request.Response.ResponseContent = new MemoryStream();
            StreamWriter writer = new StreamWriter(request.Response.ResponseContent);

            Console.WriteLine("[EXIT] Disconnecting users..");

            System.Threading.Thread.Sleep(1000);

            foreach (KeyValuePair<Guid, User> entry in users)
            {
                try {
                    User user = entry.Value;
                    //Guid session = (Guid)entry.Key;
                    if (user.Events != null)
                    {
                        user.Events.Network_Disconnected(this, new DisconnectedEventArgs(NetworkManager.DisconnectType.ServerInitiated, "Your deviMobile session has timed out."));
                        Console.WriteLine("[EXIT] Transmitted logout alert to " + user.Client.Self.FirstName + " " + user.Client.Self.LastName + ". Waiting...");
                        System.Threading.Thread.Sleep(1000);
                        user.Events.deactivate();
                    }
                    Console.WriteLine("[EXIT] Disconnecting " + user.Client.Self.FirstName + " " + user.Client.Self.LastName + "...");
                    user.Client.Network.Logout();
                } catch(Exception e) {
                    Console.WriteLine("[ERROR] " + e.Message);
                }
            }

            System.Threading.Thread.Sleep(1000);
            Console.WriteLine("[EXIT] Done.");
            Environment.Exit(0);
        }
Example #4
0
        public string Compile(string source, IFile sourceFile)
        {
            lock (_lock)
            {
                rootDirectory = sourceFile.Directory;
                Initialize();

                StartRecordingOpenedFiles();
                dependentFileList.Add(sourceFile.FullPath);

                try
                {
                    var compilerOptions = GetCompilerOptions(sourceFile);
                    return (string)sassCompiler.compile(source, compilerOptions);
                }
                catch (Exception e)
                {
                    // Provide more information for SassSyntaxErrors
                    if (e.Message == "Sass::SyntaxError")
                    {
                        throw CreateSassSyntaxError(sourceFile, e);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    StopRecordingOpenedFiles();
                }
            }
        }
Example #5
0
 public UrlGenerator(IUrlModifier urlModifier, IDirectory sourceDirectory, string cassetteHandlerPrefix)
 {
     this.urlModifier = urlModifier;
     this.cassetteHandlerPrefix = urlModifier.GetHandlerPrefix(cassetteHandlerPrefix);
     this.sourceDirectory = sourceDirectory;
     urlModifier.SetSourceDirectory(sourceDirectory);
 }
Example #6
0
        public override void Write(Stream output, IDirectory inputDirectory)
        {
            BinaryWriter writer = new BinaryWriter(output, Encoding.ASCII, true);

            const int sbpHeaderSize = 8;
            int entityHeaderSize = Entries.Count * SbpEntry.HeaderSize;
            int headerSize = sbpHeaderSize + entityHeaderSize;

            long headerPosition = output.Position;
            output.Position += headerSize;
            output.AlignWrite(16, 0x00);

            foreach (var entry in Entries)
            {
                entry.WriteData(output, inputDirectory);
                output.AlignWrite(16, 0x00);
            }

            long endPosition = output.Position;

            output.Position = headerPosition;
            writer.Write(0x4C504253); // SBPL
            writer.Write(Convert.ToByte(Entries.Count));
            writer.Write(Convert.ToUInt16(headerSize));
            writer.Write((byte)0x00);

            foreach (var entry in Entries)
            {
                entry.Write(output);
            }

            output.Position = endPosition;
        }
        /// <summary>
        /// Loads configuration for the specified directory and its subdirectories and file using the specified configuration node as parent node
        /// </summary>
        internal void LoadConfiguration(IConfigurationNode parentNode, IDirectory directory)
        {
            m_Logger.Info($"Loading configuration for directory '{directory.FullPath}'");

            // determine configuration node for directory
            IConfigurationNode configNode;

            // config file present in directory => create new node
            if (directory.FileExists(s_DirectoryConfigName))
            {
                configNode = new HierarchicalConfigurationNode(parentNode, LoadConfigurationFile(directory.GetFile(s_DirectoryConfigName)));
            }
            // no config file found => use parent node
            else
            {
                configNode = parentNode;
            }

            m_Mapper.AddMapping(configNode, directory);

            // load configuration for files in the directory
            foreach (var file in directory.Files)
            {
                LoadConfiguration(configNode, file);
            }

            // load configuration for subdirectories
            foreach (var dir in directory.Directories)
            {
                LoadConfiguration(configNode, dir);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SelfMediaDatabase.Core.Operations.Prune.PruneOperation"/> class.
        /// </summary>
        /// <param name="directory">Injection wrapper of <see cref="System.IO.Directory"/>.</param>
        /// <param name="file">Injection wrapper of <see cref="System.IO.File"/>.</param>
        /// <param name="path">Injection wrapper of <see cref="System.IO.Path"/>.</param>
        /// <param name="imageComparer">Image comparer.</param>
        /// <param name="fileSystemHelper">Helper to access to files.</param>
        public PruneOperation(
            IDirectory directory, 
            IFile file, 
            IPath path, 
            IImageComparer imageComparer, 
            IFileSystemHelper fileSystemHelper,
            IDialog dialog,
            IRenameOperation renameOperation)
        {
            if (directory == null)
                throw new ArgumentNullException("directory");
            if (file == null)
                throw new ArgumentNullException("file");
            if (imageComparer == null)
                throw new ArgumentNullException("imageComparer");
            if (fileSystemHelper == null)
                throw new ArgumentNullException("fileSystemHelper");
            if (path == null)
                throw new ArgumentNullException("path");
            if (dialog == null)
                throw new ArgumentNullException("dialog");
            if (renameOperation == null)
                throw new ArgumentNullException("renameOperation");

            _directory = directory;
            _file = file;
            _path = path;
            _imageComparer = imageComparer;
            _fileSystemHelper = fileSystemHelper;
            _dialog = dialog;
            _renameOperation = renameOperation;
        }
 public CachedZipPackage(IPackageRepository source, IFile packageFile, IDirectory cacheDirectoryPath, IEnumerable<IExportBuilder> builders)
     : base(packageFile)
 {
     Source = source;
     _cacheDirectoryPathPath = cacheDirectoryPath;
     _builders = builders;
 }
Example #10
0
 public void Given()
 {
     _fs = new InMemoryFileSystem();
     var ks = new KeyStore<string>(_fs, new Settings(@"c:\db\raptile.db"));
     ks.Dispose();
     _dir = _fs.GetDirectory(@"c:\db");
 }
 public XunitFrameworkProvider_2_0(IServiceProvider serviceProvider, IConfigurationSettings configurationSettings, INaming naming, IDirectory directory)
     : base(serviceProvider, configurationSettings, naming, directory,
            displayName: "xUnit.net 2.0",
            xunitPackageVersion: "2.0.0",
            xunitCoreAssemblyVersionPrefix: "2.0.0.",
            visualStudioRunnerPackageVersion: "2.1.0")
 { }
        public UncompressedPackage(IPackageRepository source,
                                   IFile originalPackageFile,
                                   IDirectory wrapCacheDirectory)
        {
            Check.NotNull(source, "source");
            if (originalPackageFile == null || originalPackageFile.Exists == false)
            {
                IsValid = false;
                return;
            }
            _originalPackageFile = originalPackageFile;
            BaseDirectory = wrapCacheDirectory;
            // get the descriptor file inside the package

            Source = source;
            var wrapDescriptor = wrapCacheDirectory.Files("*.wrapdesc").SingleOrDefault();

            if (wrapDescriptor == null)
            {
                IsValid = false;
                return;
            }

            var versionFile = wrapCacheDirectory.GetFile("version");
            _descriptor = new PackageDescriptorReader().Read(wrapDescriptor);
            _semver = _descriptor.SemanticVersion ?? _descriptor.Version.ToSemVer();
            if (_semver == null)
                _semver = versionFile.Exists ? versionFile.ReadString().ToSemVer() : null;

            IsValid = string.IsNullOrEmpty(Name) == false && _semver != null;
            if (IsValid)
                Identifier = new PackageIdentifier(Name, _semver);
        }
 public ProcessIsolatedEnvironment(IDirectory baseDirectory)
 {
     _baseDirectory = baseDirectory;
     _environmentId = Guid.NewGuid().ToString();
     _handle = new EventWaitHandle(false, EventResetMode.AutoReset, _environmentId);
     _hostProcess = CreateProcess(_environmentId);
 }
        bool TryInitialize()
        {
            try
            {
                _dte = SiteManager.GetGlobalService<DTE>();
                _running = _dte != null;
            }
            catch
            {
                _running = false;
            }
            if (!_running) return false;
            // TODO:  seen in the wild, _dte.Solution is null (?), need to schedule and restart initialization for those scenarios.
            _solution = new DteSolution(_dte.Solution);
            _solution.ProjectChanged += HandleProjectChange;
            var environment = ServiceLocator.GetService<IEnvironment>();
            _packageManager = ServiceLocator.GetService<IPackageManager>();

            _assembliesChanged = new EventWaitHandle(false, EventResetMode.AutoReset, System.Diagnostics.Process.GetCurrentProcess().Id + ASSEMBLY_NOTIFY);
            _rootDirectory = environment.DescriptorFile.Parent;
            _projectRepository = environment.ProjectRepository;
            RegisterFileListener();
            RefreshProjects();
            _timer = new Timer(_ => RefreshProjects(), null, Timeout.Infinite, Timeout.Infinite);
            return true;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="SelfMediaDatabase.Console.OptionsUtils"/> class.
		/// </summary>
		/// <param name="directory">Wrapper for <see cref="System.IO.Directory"/>.</param>
		public OptionsUtils(IDirectory directory)
		{
			if (directory == null)
				throw new ArgumentNullException("directory");

			_directory = directory;
		}
        protected Bundle ProcessSingleBundle(IFileHelper fileHelper, IDirectory directory, List<Bundle> bundlesToSort,
            Dictionary<string, string> uncachedToCachedFiles, Bundle bundle, AssignHash hasher)
        {
            Trace.Source.TraceInformation("Processing {0} {1}", bundle.GetType().Name, bundle.Path);

            //need to process early to generate an accurate hash.
            if (IsCompositeBundle(bundle))
            {
                bundle.Process(settings);
            }
            else
            {
                hasher.Process(bundle, settings);
            }

            var bundleKey = CassetteSettings.bundles.GetSafeString(Encoding.Default.GetString(bundle.Hash));
            if (CassetteSettings.bundles.ContainsKey(fileHelper, directory, uncachedToCachedFiles, bundleKey, bundle))
            {
                bundle = CassetteSettings.bundles.GetBundle(fileHelper, directory, uncachedToCachedFiles, bundleKey, bundle);
                bundlesToSort.Add(bundle);
            }
            else
            {
                var unprocessedAssetPaths = CassetteSettings.bundles.GetAssetPaths(bundle);
                if (!IsCompositeBundle(bundle))
                {
                    bundle.Process(settings);
                }
                CassetteSettings.bundles.AddBundle(fileHelper, uncachedToCachedFiles, bundleKey, bundle, unprocessedAssetPaths);
            }
            return bundle;
        }
Example #17
0
 public UrlGenerator(IUrlModifier urlModifier, IDirectory sourceDirectory, string cassetteHandlerPrefix, bool isFileNameWithHashDisabled = false)
 {
     this.urlModifier = urlModifier;
     this.cassetteHandlerPrefix = cassetteHandlerPrefix;
     this.isFileNameWithHashDisabled = isFileNameWithHashDisabled;
     this.sourceDirectory = sourceDirectory;
 }
Example #18
0
 public BuildWrapCommand(IFileSystem fileSystem, IEnvironment environment)
 {
     _fileSystem = fileSystem;
     _environment = environment;
     _currentDirectory = environment.CurrentDirectory;
     _wildcards = new string[0].ToLookup(_ => _, _ => default(string));
 }
 protected void when_finding_source()
 {
     source = PathFinder.GetSourceDirectory(
         descriptor.DirectoryStructure,
         root
         );
 }
Example #20
0
        /// <summary>
        /// Copy "this" directory (<paramref name="a_this"/>) to the given destination directory (<paramref name="a_destination"/>).
        /// </summary>
        /// <param name="a_this">"This" directory.</param>
        /// <param name="a_destination">Destination directory.</param>
        /// <exception cref="NullReferenceException">Thrown if <paramref name="a_this"/> is null.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="a_destination"/> is null.</exception>
        public static void CopyTo(this IDirectory a_this, IDirectory a_destination)
        {
            #region Argument Validation

            if (a_this == null)
                throw new NullReferenceException(nameof(a_this));

            if (a_destination == null)
                throw new ArgumentNullException(nameof(a_destination));

            #endregion

            a_destination.Create();

            foreach (var file in a_this.Files())
            {
                var dest = a_destination.File(file.Name);
                file.CopyTo(dest);
            }

            foreach (var directory in a_this.Directories())
            {
                var dest = a_destination.Directory(directory.Name);
                directory.CopyTo(dest);
            }
        }
Example #21
0
		internal virtual void PrintBody(StreamWriter writer,
			HttpRequest request,
			IDirectory directory,
			ICollection dirs,
			ICollection files
			)
		{

			writer.WriteLine("<h2>Index of " + HttpWebServer.GetDirectoryPath(directory) + "</h2>");

			if(directory.Parent != null)
				writer.WriteLine("<a href=\"..\">[..]</a><br>");

			foreach(IDirectory dir in dirs)
			{
				//if(dir is IPhysicalResource)
				//	if((File.GetAttributes((dir as IPhysicalResource).Path) & FileAttributes.Hidden) != 0)
				//		continue;

				writer.WriteLine("<a href=\"" + UrlEncoding.Encode(dir.Name) + "/\">[" + dir.Name + "]</a><br>");
			}

			foreach(IFile file in files)
			{
				//if(file is IPhysicalResource)
				//	if((File.GetAttributes((file as IPhysicalResource).Path) & FileAttributes.Hidden) != 0)
				//		continue;
				writer.WriteLine("<a href=\"" + UrlEncoding.Encode(file.Name) + "\">" + file.Name + "</a><br>");
			}
		}
Example #22
0
		/// <summary>
		/// Called when the file is requested by a client.
		/// </summary>
		/// <param name="request">The <see cref="HttpRequest"/> requesting the file.</param>
		/// <param name="directory">The <see cref="IDirectory"/> of the parent directory.</param>
		public void OnFileRequested(HttpRequest request, IDirectory directory)
		{
			ICollection dirs;
			ICollection files;
			try
			{
				dirs = directory.GetDirectories();
				files = directory.GetFiles();
			}
			catch(UnauthorizedAccessException)
			{
				throw new HttpRequestException("403");
			}

			request.Response.BeginChunkedOutput();
			StreamWriter writer = new StreamWriter(request.Response.ResponseContent);

			writer.WriteLine("<html>");
			writer.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
			writer.WriteLine("<head><title>Index of " + HttpWebServer.GetDirectoryPath(directory) + "</title></head>");
			writer.WriteLine("<body>");

			PrintBody(writer, request, directory, dirs, files);
			
			writer.WriteLine("<hr>" + request.Server.ServerName);
			writer.WriteLine("</body></html>");

			writer.WriteLine("</body>");
			writer.WriteLine("</html>");
			writer.Flush();
		}
Example #23
0
		/// <summary>
		/// Called when the file is requested by a client.
		/// </summary>
		/// <param name="request">The <see cref="HttpRequest"/> requesting the file.</param>
		/// <param name="directory">The <see cref="IDirectory"/> of the parent directory.</param>
		public void OnFileRequested(HttpRequest request, IDirectory directory)
		{
			if(request.IfModifiedSince != DateTime.MinValue)
			{
				if(File.GetLastWriteTimeUtc(path) < request.IfModifiedSince)
					request.Response.ResponseCode = "304";
				return;
			}
			if(request.IfUnmodifiedSince != DateTime.MinValue)
			{
				if(File.GetLastWriteTimeUtc(path) > request.IfUnmodifiedSince)
					request.Response.ResponseCode = "304";
				return;
			}

			if(System.IO.Path.GetFileName(path).StartsWith("."))
			{
				request.Response.ResponseCode = "403";
				return;
			}

			try
			{
				request.Response.ResponseContent = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
			}
			catch(FileNotFoundException)
			{
				request.Response.ResponseCode = "404";
			}
			catch(IOException e)
			{
				request.Response.ResponseCode = "500";
				request.Server.Log.WriteLine(e);
			}
		}
Example #24
0
		/// <summary>
		/// Creates a new virtual directory.
		/// </summary>
		/// <param name="name">The name of the directory as it will be seen in the directory.</param>
		/// <param name="parent">An <see cref="IDirectory" /> specifying the parent directory. This value should be <c>null</c> if this directory is to be the root directory.</param>
		public VirtualDirectory(string name, IDirectory parent)
		{
			this.name = name;
			this.parent = parent;
			directories = new Hashtable();
			files = new Hashtable();
		}
Example #25
0
 /// <summary>
 /// Searches the given directory for files matching the search parameters of this object.
 /// </summary>
 /// <param name="directory">The directory to search.</param>
 /// <returns>A collection of files.</returns>
 public IEnumerable<IFile> FindFiles(IDirectory directory)
 {
     return from pattern in GetFilePatterns()
            from file in directory.GetFiles(pattern, SearchOption)
            where IsAssetFile(file)
            select file;
 }
Example #26
0
 // Methods
 public BasicStats(string name, IDirectory parent, Dictionary<Guid, User> users)
 {
     this.name = name;
     this.parent = parent;
     this.users = users;
     this.started = DateTime.UtcNow;
 }
 public async Task<IFile> CopyAsync(IDirectory destDirectory)
 {
     if (!(destDirectory is DirectoryWindowsStore))
         throw new InvalidDirectoryException("destDirectory must be of WindowsStore Type");
     var storeDirectory = destDirectory as DirectoryWindowsStore;
     return new FileWindowsStore(await _storageFile.CopyAsync(storeDirectory.StorageFolder));
 }
Example #28
0
        public void WriteData(BinaryWriter writer, IDirectory inputDirectory)
        {
            long ftexHeaderPosition = writer.BaseStream.Position;
            writer.BaseStream.Position += HeaderSize + Entries.Count * PftxsFtexsFileEntry.HeaderSize;

            foreach (var entry in Entries)
            {
                entry.CalculateHash();
                var data = inputDirectory.ReadFile(Hashing.NormalizeFilePath(entry.FilePath));
                entry.Offset = Convert.ToInt32(writer.BaseStream.Position - ftexHeaderPosition);
                entry.Size = Convert.ToInt32(data.Length);
                writer.Write(data);
            }
            CalculateHash();

            long endPosition = writer.BaseStream.Position;
            writer.BaseStream.Position = ftexHeaderPosition;

            writer.Write(Convert.ToUInt32(0x58455446)); // FTEX
            writer.Write(Convert.ToUInt32(endPosition - ftexHeaderPosition)); // Size
            writer.Write(Hash);
            writer.Write(Convert.ToUInt32(Entries.Count));
            writer.Write(0U);
            writer.Write(0U);
            writer.Write(0U);

            foreach (var entry in Entries)
            {
                entry.Write(writer);
            }

            writer.BaseStream.Position = endPosition;
        }
Example #29
0
 public GitDirectory(IDirectory parent, string name, DateTime commitTime, Tree tree) : base(parent, name, Enumerable.Empty<IDirectory>(), Enumerable.Empty<IFile>())
 {
     m_Name = name;
     m_CommitTime = commitTime;
     m_Tree = tree;                    
     
 }
Example #30
0
        public UncompressedPackage(IPackageRepository source,
            IFile originalPackageFile,
            IDirectory wrapCacheDirectory)
        {
            Check.NotNull(source, "source");
            if (originalPackageFile == null || originalPackageFile.Exists == false)
            {
                IsValid = false;
                return;
            }
            _originalPackageFile = originalPackageFile;
            BaseDirectory = wrapCacheDirectory;
            // get the descriptor file inside the package

            Source = source;
            var wrapDescriptor = wrapCacheDirectory.Files("*.wrapdesc").SingleOrDefault();

            if (wrapDescriptor == null)
            {
                IsValid = false;
                return;
            }

            var versionFile = wrapCacheDirectory.GetFile("version");
            _descriptor = new PackageDescriptorReaderWriter().Read(wrapDescriptor);
            PackageInfo = new DefaultPackageInfo(originalPackageFile.Name,
                                                versionFile.Exists ? versionFile.Read(x => x.ReadString().ToVersion()) : null,
                                                _descriptor);
            Identifier = new PackageIdentifier(Name, Version);
            IsValid = true;
        }
Example #31
0
 public File(FileInfo fileInfo, IDirectory parent)
 {
     _fileInfo = fileInfo;
     Name      = _fileInfo.Name;
     Directory = parent;
 }
Example #32
0
        public void CreatesAnchorFile()
        {
            string json =
                @"{
    ""name"": ""jsii$aws_cdk$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.CdkNamespace"",
            ""packageId"": ""Aws.CdkPackageId""
        }
    },
    ""version"": ""1.2.3"",
    ""types"": {},
    ""dependencies"": {
        ""jsii$aws_cdk_cx_api$"": {
            ""package"": ""aws-cdk-cx-api"",
            ""version"": """",
            ""targets"": {
                ""dotnet"": {
                    ""namespace"": ""Aws.Cdk.CxApi"",
                    ""packageId"": ""Aws.Cdk.CxApi""
                }
            }
        }
    }
}";
            string cxJson =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""version"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""types"": {}
}";

            string jsonPath       = GetJsonPath("aws-cdk");
            string cxJsonPath     = Path.Combine(Path.GetDirectoryName(jsonPath), "node_modules", "jsii$aws_cdk_cx_api$");
            string anchorFilePath = GetAnchorFilePath("Aws.CdkPackageId", "Aws.CdkNamespace");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);
            file.ReadAllText(Path.Combine(cxJsonPath, ".jsii")).Returns(cxJson);

            IDirectory directory = Substitute.For <IDirectory>();

            directory.Exists(cxJsonPath).Returns(true);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(directory);
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk", "Aws.CdkPackageId");
            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApiNamespace");
            Symbols.MapAssemblyName("jsii$aws_cdk_cx_api$", "Aws.Cdk.CxApiPackageId");

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk", "aws-cdk-1.2.3.4.tgz"),
                Symbols
            );

            string expected =
                @"namespace Aws.CdkNamespace.Internal.DependencyResolution
{
    public class Anchor
    {
        public Anchor()
        {
            new Aws.Cdk.CxApiNamespace.Internal.DependencyResolution.Anchor();
        }
    }
}";

            file.Received().WriteAllText(anchorFilePath, Arg.Do <string>(actual => PlatformIndependentEqual(expected, actual)));
        }
Example #33
0
 protected void given_descriptor(IDirectory projectDirectory, PackageDescriptor packageDescriptor)
 {
     using (var descriptor = projectDirectory.GetFile(packageDescriptor.Name + ".wrapdesc").OpenWrite())
         new PackageDescriptorReaderWriter().Write(packageDescriptor, descriptor);
     Environment.Descriptor = packageDescriptor;
 }
Example #34
0
 public ResultGenerator(IDirectory iDirectory, IFileFilter iFileFilter)
 {
     this.iFileFilter = iFileFilter;
     this.iDirectory  = iDirectory;
 }
        public IEnumerable <IOperationProvider> ConfigureFromJObject(JObject rawConfiguration, IDirectory templateRoot)
        {
            IReadOnlyList <string> ifToken               = rawConfiguration.ArrayAsStrings("if");
            IReadOnlyList <string> elseToken             = rawConfiguration.ArrayAsStrings("else");
            IReadOnlyList <string> elseIfToken           = rawConfiguration.ArrayAsStrings("elseif");
            IReadOnlyList <string> actionableIfToken     = rawConfiguration.ArrayAsStrings("actionableIf");
            IReadOnlyList <string> actionableElseToken   = rawConfiguration.ArrayAsStrings("actionableElse");
            IReadOnlyList <string> actionableElseIfToken = rawConfiguration.ArrayAsStrings("actionableElseif");
            IReadOnlyList <string> actionsToken          = rawConfiguration.ArrayAsStrings("actions");
            IReadOnlyList <string> endIfToken            = rawConfiguration.ArrayAsStrings("endif");
            string id        = rawConfiguration.ToString("id");
            bool   trim      = rawConfiguration.ToBool("trim");
            bool   wholeLine = rawConfiguration.ToBool("wholeLine");

            string             evaluatorName = rawConfiguration.ToString("evaluator");
            ConditionEvaluator evaluator     = EvaluatorSelector.Select(evaluatorName);

            ConditionalTokens tokenVariants = new ConditionalTokens
            {
                IfTokens               = ifToken,
                ElseTokens             = elseToken,
                ElseIfTokens           = elseIfToken,
                EndIfTokens            = endIfToken,
                ActionableElseIfTokens = actionableElseIfToken,
                ActionableElseTokens   = actionableElseToken,
                ActionableIfTokens     = actionableIfToken,
                ActionableOperations   = actionsToken
            };

            yield return(new Conditional(tokenVariants, wholeLine, trim, evaluator, id));
        }
 // Token: 0x06000751 RID: 1873 RVA: 0x0002AB33 File Offset: 0x00028D33
 internal CoexistenceRpcHttpProxyRules(IDirectory rule)
 {
     this.directory = (rule ?? new Directory());
     this.RefreshServerList(null);
 }
Example #37
0
        public void AccessesFileSystemThroughShim()
        {
            const string json =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""version"": """",
    ""types"": {
        ""jsii$aws_cdk_cx_api$.MissingContext"": {
            ""kind"": ""class"",
            ""fqn"": ""jsii$aws_cdk_cx_api$.MissingContext"",
            ""assembly"": ""jsii$aws_cdk_cx_api$"",
            ""name"": ""MissingContext"",
            ""initializer"": {
                ""initializer"": true
            }
        }
    }
}";

            string jsonPath          = GetJsonPath("aws-cdk-cx-api");
            string packageOutputRoot = GetPackageOutputRoot("Aws.Cdk.CxApiPackageId");
            string projectFilePath   = GetProjectFilePath("Aws.Cdk.CxApiPackageId", "Aws.Cdk.CxApiPackageId");
            string typeFilePath      = GetTypeFilePath("Aws.Cdk.CxApiPackageId", "Aws.Cdk.CxApiNamespace", "MissingContext");

            IDirectory directory = Substitute.For <IDirectory>();

            directory.Exists(packageOutputRoot).Returns(true, false);

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(directory);
            fileSystem.File.Returns(file);

            //Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApi");
            Symbols.MapNamespace("jsii$aws_cdk_cx_api$", "Aws.Cdk.CxApiNamespace");
            Symbols.MapTypeName("jsii$aws_cdk_cx_api$.MissingContext", "MissingContext", TypeKind.Class);

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk-cx-api", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk-cx-api", "aws-cdk-cx-api-1.2.3.5.tgz"),
                Symbols
            );

            directory.Received().Delete(packageOutputRoot, true);
            directory.Received().CreateDirectory(packageOutputRoot);
            file.Received().ReadAllText(jsonPath);
            file.Received().WriteAllText(projectFilePath, Arg.Any <string>());
            file.Received().WriteAllText(typeFilePath, Arg.Any <string>());
        }
Example #38
0
 public PFSFile(string name, IDirectory parent, Stream img, long offset, long size, long inodeIdx)
     : base(name, parent, img, offset, size)
 {
     ExtendedInfo.Add("InodeIdx", inodeIdx);
 }
Example #39
0
 public RelativeDirectoryRoot(IDirectory baseDirectory)
 {
     BaseDirectory = baseDirectory;
 }
Example #40
0
        public void CreatesProjectFileWithDependencies()
        {
            string json =
                @"{
    ""name"": ""jsii$aws_cdk$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.CdkNamespace"",
            ""packageId"": ""Aws.CdkPackageId""
        }
    },
    ""version"": ""1.2.3"",
    ""types"": {},
    ""dependencies"": {
        ""jsii$aws_cdk_cx_api$"": {
            ""package"": ""aws-cdk-cx-api"",
            ""version"": """",
            ""targets"": {
                ""dotnet"": {
                    ""namespace"": ""Aws.Cdk.CxApi"",
                    ""packageId"": ""Aws.Cdk.CxApi""
                }
            }
        }
    }
}";
            string cxJson =
                @"{
    ""name"": ""jsii$aws_cdk_cx_api$"",
    ""description"": """",
    ""homepage"": """",
    ""repository"": {
      ""type"": """",
      ""url"": """"
    },
    ""author"": {
      ""name"": """",
      ""roles"": []
    },
    ""fingerprint"": """",
    ""license"": """",
    ""version"": """",
    ""targets"": {
        ""dotnet"": {
            ""namespace"": ""Aws.Cdk.CxApiNamespace"",
            ""packageId"": ""Aws.Cdk.CxApiPackageId""
        }
    },
    ""types"": {}
}";

            string jsonPath        = GetJsonPath("aws-cdk");
            string cxJsonPath      = Path.Combine(Path.GetDirectoryName(jsonPath), "node_modules", "jsii$aws_cdk_cx_api$");
            string projectFilePath = GetProjectFilePath("Aws.CdkPackageId", "Aws.CdkPackageId");

            IFile file = Substitute.For <IFile>();

            file.ReadAllText(jsonPath).Returns(json);
            file.ReadAllText(Path.Combine(cxJsonPath, ".jsii")).Returns(cxJson);

            IDirectory directory = Substitute.For <IDirectory>();

            directory.Exists(cxJsonPath).Returns(true);

            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Directory.Returns(directory);
            fileSystem.File.Returns(file);

            Symbols.MapTypeToPackage("aws-cdk", "Aws.CdkPackageId");
            Symbols.MapTypeToPackage("aws-cdk-cx-api", "Aws.Cdk.CxApiNamespace");
            Symbols.MapAssemblyName("jsii$aws_cdk_cx_api$", "Aws.Cdk.CxApiPackageId");

            AssemblyGenerator generator = new AssemblyGenerator
                                          (
                OutputRoot,
                fileSystem
                                          );

            generator.Generate
            (
                Path.Combine(InputRoot, "aws-cdk", "dist", Constants.SPEC_FILE_NAME),
                Path.Combine(InputRoot, "aws-cdk", "aws-cdk-1.2.3.4.tgz"),
                Symbols
            );

            string expected =
                @"<Project Sdk=""Microsoft.NET.Sdk"">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <Authors>myAuthors</Authors>
    <Company>myCompany</Company>
    <PackageVersion>1.2.3</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <EmbeddedResource Include=""aws-cdk-1.2.3.4.tgz"" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include=""Amazon.JSII.Runtime"" Version=""" + JsiiVersion.Version + @""" />
    <ProjectReference Include=""..\Aws.Cdk.CxApi\Aws.Cdk.CxApi.csproj"" Version=""" + JsiiVersion.Version + @""" />
  </ItemGroup>
</Project>";

            file.Received().WriteAllText(projectFilePath, Arg.Do <string>(actual => PlatformIndependentEqual(expected, actual)));
        }
Example #41
0
        private static IReadOnlyList <IOperationProvider> SetupCustomOperations(IReadOnlyList <ICustomOperationModel> customModel, IDirectory templateRoot, IVariableCollection variables)
        {
            ITemplateEngineHost       host             = templateRoot.MountPoint.EnvironmentSettings.Host;
            List <IOperationProvider> customOperations = new List <IOperationProvider>();

            foreach (ICustomOperationModel opModelUntyped in customModel)
            {
                CustomOperationModel opModel = opModelUntyped as CustomOperationModel;
                if (opModel == null)
                {
                    host.LogMessage($"Operation type = [{opModelUntyped.Type}] could not be cast as a CustomOperationModel");
                    continue;
                }

                string opType    = opModel.Type;
                string condition = opModel.Condition;

                if (string.IsNullOrEmpty(condition) ||
                    CppStyleEvaluatorDefinition.EvaluateFromString(templateRoot.MountPoint.EnvironmentSettings, condition, variables))
                {
                    IOperationConfig realConfigObject;
                    if (_operationConfigLookup.TryGetValue(opType, out realConfigObject))
                    {
                        customOperations.AddRange(
                            realConfigObject.ConfigureFromJObject(opModel.Configuration, templateRoot));
                    }
                    else
                    {
                        host.LogMessage($"Operation type = [{opType}] from configuration is unknown.");
                    }
                }
            }

            return(customOperations);
        }
Example #42
0
 private IDirectory MakeImmediateChild(IDirectory arg) => SubDirectory(arg.Name);
Example #43
0
        protected override void RegisterTasks()
        {
            //// ----------------------------------------------------------------------------------------------------------------------------
            var initTask = Task(
                "Init the workflow",
                _ =>
            {
                IDirectory currentDirectory = WorkDirectory.Closest(dir => dir.Name.Equals("src", StringComparison.InvariantCultureIgnoreCase));

                if (currentDirectory == null)
                {
                    throw new Exception("Could not find Src directory " + WorkDirectory);
                }

                IDirectory artifacts = currentDirectory.Parent / "Artifacts";
                artifacts.EnsureExists();
                artifacts.Files.IncludeByExtension("nupkg", "nuspec").DeleteAll();

                IDirectory mergedBin = currentDirectory.Parent / "bin" / "Merged";
                mergedBin.EnsureExists();

                return(new
                {
                    Version = "4.1.1.0",
                    Configuration = "Debug",
                    Solution = new SolutionStructure(currentDirectory.Parent)
                }.AsTaskResult());
            });

            //// ----------------------------------------------------------------------------------------------------------------------------
            var generateCommonAssemblyInfo = Task(
                "Generate common assembly info",
                from data in initTask
                select new GenerateAssemblyInfo(data.Solution.Src / "CommonAssemblyInfo.cs")
            {
                Attributes =
                {
                    _ => new AssemblyProductAttribute("CrystalQuartz"),
                    _ => new AssemblyVersionAttribute(data.Version),
                    _ => new AssemblyFileVersionAttribute(data.Version)
                }
            });

            //// ----------------------------------------------------------------------------------------------------------------------------
            var compileTypescript = Task(
                "Compile TypescriptFiles",
                from data in initTask
                select new ExecTask
            {
                ToolPath  = "tsc",
                Arguments =
                    (data.Solution.CrystalQuartz_Application / "Client" / "Scripts" / "Application.ts").AsFile().GetRelativePath(WorkDirectory) + " -out " +
                    (data.Solution.CrystalQuartz_Application / "Content" / "Scripts" / "application.js").AsFile().GetRelativePath(WorkDirectory)
            });

            //// ----------------------------------------------------------------------------------------------------------------------------
            var transformIndexHtml = Task(
                "Transform intex.html template",
                from data in initTask
                select new ExecTask
            {
                ToolPath  = (data.Solution.Src / "packages").AsDirectory().Directories.Last(dir => dir.Name.StartsWith("Mono.TextTransform")) / "tools" / "TextTransform.exe",
                Arguments = data.Solution.CrystalQuartz_Application / "Content" / "index.tt"
            });

            //// ----------------------------------------------------------------------------------------------------------------------------
            var buildSolution = Task(
                "Build solution",
                new MsBuildTask(),

                DependsOn(generateCommonAssemblyInfo),
                DependsOn(compileTypescript),
                DependsOn(transformIndexHtml));

            //// ----------------------------------------------------------------------------------------------------------------------------
            var cleanArtifacts = Task(
                "Clean artifacts",
                from data in initTask
                select _ => data.Solution.Artifacts.Files.IncludeByExtension("nupkg", "nuspec").DeleteAll());

            var mergeBinaries = Task(
                "MergeBinaries",

                from data in initTask
                select new MergeBinariesTask(data.Solution, data.Configuration).AsSubflow(),

                DependsOn(buildSolution));


            var generateNuspecs = Task(
                "GenerateNuspecs",
                from data in initTask
                select new GenerateNuspecsTask(data.Solution, data.Configuration, data.Version),

                DependsOn(cleanArtifacts),
                DependsOn(mergeBinaries));

            //// ----------------------------------------------------------------------------------------------------------------------------

            var buildPackages = Task(
                "Build packages",
                from data in initTask
                select ForEach(data.Solution.Artifacts.Files.IncludeByExtension(".nuspec")).Do(
                    nuspec => new GeneratePackageTask(nuspec)
            {
                WorkDirectory = data.Solution.Artifacts,
                ToolPath      = data.Solution.Src / ".nuget" / "NuGet.exe"
            },
                    nuspec => string.Format("Generate NuGet package for {0}", nuspec.NameWithoutExtension)),

                Default(),
                DependsOn(generateNuspecs));

            //// ----------------------------------------------------------------------------------------------------------------------------

            Task(
                "PushPackages",

                from data in initTask
                select
                ForEach(data.Solution.Artifacts.Files.IncludeByExtension("nupkg")).Do(
                    package => new PushPackageTask(package)
            {
                WorkDirectory = data.Solution.Artifacts,
                ToolPath      = data.Solution.Src / ".nuget" / "NuGet.exe"
            },
                    package => "Push" + package.NameWithoutExtension),

                DependsOn(buildPackages));
        }
Example #44
0
 public sealed record RmIState(IRepository <RepositoryEntry, string> Repositorys, IDirectory Bucket, DataTransferManager DataTransferManager);
Example #45
0
 protected abstract Result OpenDirectoryImpl(out IDirectory directory, U8Span path, OpenDirectoryMode mode);
Example #46
0
        // Returns a list of operations which contains the custom operations and the default operations.
        // If there are custom Conditional operations, don't include the default Conditionals.
        //
        // Note: we may need a more robust filtering mechanism in the future.
        private static IReadOnlyList <IOperationProvider> ResolveOperations(IGlobalRunConfig runConfig, IDirectory templateRoot, IVariableCollection variables, IParameterSet parameters)
        {
            IReadOnlyList <IOperationProvider> customOperations  = SetupCustomOperations(runConfig.CustomOperations, templateRoot, variables);
            IReadOnlyList <IOperationProvider> defaultOperations = SetupOperations(templateRoot.MountPoint.EnvironmentSettings, parameters, runConfig);

            List <IOperationProvider> operations = new List <IOperationProvider>(customOperations);

            if (customOperations.Any(x => x is Conditional))
            {
                operations.AddRange(defaultOperations.Where(op => !(op is Conditional)));
            }
            else
            {
                operations.AddRange(defaultOperations);
            }

            return(operations);
        }
 public async IAsyncEnumerable <TaskResult <IFile> > EmitCopyDirResult(DirectoryInfo tempdir, IDirectory dir)
 {
     await foreach (var tr in new CopyDirectoryContentsTask(tempdir, dir))
     {
         yield return(tr);
     }
 }
 IDirectory ITenantActionsSync.CreateDirectory(IDirectory directory)
 => this.GetInternalSyncDataStore().Create(DirectoriesPropertyName, directory);
 public async IAsyncEnumerable <TaskResult <IFile> > EmitZipResult(string tempFile, IDirectory dir)
 {
     await foreach (var tr in new ExtractZipTask(new FileInfo(tempFile), dir))
     {
         yield return(tr);
     }
 }
        public IEnumerable <IOperationProvider> ConfigureFromJObject(JObject rawConfiguration, IDirectory templateRoot)
        {
            string startToken     = rawConfiguration.ToString("startToken");
            string realEndToken   = rawConfiguration.ToString("realEndToken");
            string pseudoEndToken = rawConfiguration.ToString("pseudoEndToken");
            string id             = rawConfiguration.ToString("id");
            string resetFlag      = rawConfiguration.ToString("resetFlag");
            bool   onByDefault    = rawConfiguration.ToBool("onByDefault");

            yield return(new BalancedNesting(startToken.TokenConfig(), realEndToken.TokenConfig(), pseudoEndToken.TokenConfig(), id, resetFlag, onByDefault));
        }
Example #51
0
 static void AddPackageFolders(IDirectory projectDirectory)
 {
     projectDirectory.GetDirectory("src").MustExist();
     projectDirectory.GetDirectory("wraps").GetDirectory("_cache").MustExist();
 }
 public async IAsyncEnumerable <TaskResult <IFile> > EmitCopyResult(string tempFile, IDirectory dir)
 {
     yield return(await new CopyFileTask(new FileInfo(tempFile), dir));
 }
Example #53
0
 public sealed record AppQueryHandlerState(IRepository <AppData, string> Apps, IDirectory Files, DataTransferManager DataTransfer, IActorRef ChangeTracker);
Example #54
0
        IEnumerable <ICommandOutput> CopyOpenWrap(PackageDescriptor projectDescriptor, IDirectory projectDirectory)
        {
            var packageManager = ServiceLocator.GetService <IPackageManager>();

            var repositoryOptions = FolderRepositoryOptions.AnchoringEnabled;

            if (projectDescriptor.UseSymLinks)
            {
                repositoryOptions |= FolderRepositoryOptions.UseSymLinks;
            }
            if (projectDescriptor.StorePackages)
            {
                repositoryOptions |= FolderRepositoryOptions.PersistPackages;
            }
            var projectRepository = new FolderRepository(projectDirectory.GetDirectory("wraps"), repositoryOptions)
            {
                Name = "Project repository"
            };

            packageManager.AddProjectPackage(PackageRequest.Any("openwrap"),
                                             new[] { Environment.SystemRepository },
                                             projectDescriptor,
                                             projectRepository,
                                             PackageAddOptions.Default | PackageAddOptions.Anchor | PackageAddOptions.Content).ToList();

            yield return(new Info("Project repository initialized."));
        }
Example #55
0
 public void Scaffold(IFile configFile, IDirectory inputDirectory)
 {
     throw new NotImplementedException();
 }
Example #56
0
 public MakeFile(string name, IDirectory parent)
 {
     this.name   = name;
     this.parent = parent;
 }
Example #57
0
        public IEnumerable<IOperationProvider> ConfigureFromJObject(JObject rawConfiguration, IDirectory templateRoot)
        {
            string commentStyle = rawConfiguration.ToString("style");
            IEnumerable<IOperationProvider> operations = null;

            if (string.IsNullOrEmpty(commentStyle) || string.Equals(commentStyle, "custom", StringComparison.OrdinalIgnoreCase))
            {
                operations = ConditionalCustomConfig.ConfigureFromJObject(rawConfiguration);
            }
            else if (string.Equals(commentStyle, "line", StringComparison.OrdinalIgnoreCase))
            {
                operations = ConditionalLineCommentConfig.ConfigureFromJObject(rawConfiguration);
            }
            else if (string.Equals(commentStyle, "block", StringComparison.OrdinalIgnoreCase))
            {
                operations = ConditionalBlockCommentConfig.ConfigureFromJObject(rawConfiguration);
            }
            else
            {
                throw new TemplateAuthoringException($"Template authoring error. Invalid comment style [{commentStyle}].", "style");
            }

            foreach (IOperationProvider op in operations)
            {
                yield return op;
            }
        }
Example #58
0
 public static IPreparedFeature New(IRepository <AppData, string> apps, IDirectory files, DataTransferManager dataTransfer, IActorRef changeTracker)
 => Feature.Create(() => new AppQueryHandler(), _ => new AppQueryHandlerState(apps, files, dataTransfer, changeTracker));
Example #59
0
 public LapsConfigurationViewModel(IDialogCoordinator dialogCoordinator, ICertificateProvider certificateProvider, IDirectory directory, IX509Certificate2ViewModelFactory certificate2ViewModelFactory, IServiceSettingsProvider serviceSettings, ILogger <LapsConfigurationViewModel> logger)
 {
     this.directory                    = directory;
     this.certificateProvider          = certificateProvider;
     this.certificate2ViewModelFactory = certificate2ViewModelFactory;
     this.dialogCoordinator            = dialogCoordinator;
     this.serviceSettings              = serviceSettings;
     this.logger  = logger;
     this.Forests = new List <Forest>();
     this.AvailableCertificates = new BindableCollection <X509Certificate2ViewModel>();
     this.DisplayName           = "Local admin passwords";
 }
Example #60
0
 public File(IDirectory parent, string name)
 {
     Name      = name;
     Directory = parent;
 }