public int Execute(Execution execution)
        {
            if (!Directory.Exists(execution.PackageSourceFolder))
            {
                throw new InvalidOperationException("The source folder " + execution.PackageSourceFolder + " does not exist.");
            }

            if (execution.PackagePlatform == "Template" && execution.PackageFormat != PackageManager.ARCHIVE_FORMAT_NUGET_ZIP)
            {
                return(ExecuteForTemplate(execution));
            }

            var        allowAutopackage   = true;
            var        moduleExpectedPath = Path.Combine(execution.PackageSourceFolder, "Build", "Module.xml");
            ModuleInfo rootModule         = null;

            if (!File.Exists(moduleExpectedPath))
            {
                if (execution.PackageFilterFile == null)
                {
                    RedirectableConsole.WriteLine(
                        "There is no module in the path '" + execution.PackageSourceFolder + "' (expected to " +
                        "find a Build\\Module.xml file within that directory).");
                    return(1);
                }
                else
                {
                    // We allow this mode if the user has provided a filter file and are constructing
                    // the package manually.
                    allowAutopackage = false;
                }
            }
            else
            {
                rootModule = ModuleInfo.Load(moduleExpectedPath);
            }

            var temporaryFiles = new List <string>();

            try
            {
                var customDirectives = new Dictionary <string, Action <FileFilter> >()
                {
                    {
                        "autopackage",
                        f =>
                        {
                            if (allowAutopackage && rootModule != null)
                            {
                                this.m_AutomaticProjectPackager.Autopackage(
                                    execution.WorkingDirectory,
                                    f,
                                    execution,
                                    rootModule,
                                    execution.PackageSourceFolder,
                                    execution.PackagePlatform,
                                    execution.PackageFormat,
                                    temporaryFiles);
                            }
                            else
                            {
                                RedirectableConsole.WriteLine(
                                    "WARNING: There is no module in the path '" + execution.PackageSourceFolder +
                                    "' (expected to " +
                                    "find a Build\\Module.xml file within that directory).  Ignoring the 'autopackage' directive.");
                            }
                        }
                    }
                };

                RedirectableConsole.WriteLine("Starting package creation for " + execution.PackagePlatform);

                var filter =
                    new FileFilter(_getRecursiveUtilitiesInPath.GetRecursiveFilesInPath(execution.PackageSourceFolder));
                if (execution.PackageFilterFile != null)
                {
                    using (var reader = new StreamReader(execution.PackageFilterFile))
                    {
                        var contents = reader.ReadToEnd();
                        contents = contents.Replace("%PLATFORM%", execution.PackagePlatform);

                        using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(contents)))
                        {
                            this.m_FileFilterParser.ParseAndApply(filter, inputStream, customDirectives);
                        }
                    }
                }
                else
                {
                    customDirectives["autopackage"](filter);
                }

                if (File.Exists(execution.PackageDestinationFile))
                {
                    RedirectableConsole.WriteLine("The destination file " + execution.PackageDestinationFile +
                                                  " already exists; it will be overwritten.");
                    File.Delete(execution.PackageDestinationFile);
                }

                filter.ImplyDirectories();

                if (execution.PackageFormat != PackageManager.ARCHIVE_FORMAT_NUGET_ZIP)
                {
                    if (!filter.ContainsTargetPath("Build/"))
                    {
                        RedirectableConsole.WriteLine("ERROR: The Build directory does not exist in the source folder.");
                        if (execution.PackageFilterFile != null)
                        {
                            this.PrintFilterMappings(filter);
                        }
                        return(1);
                    }

                    if (!filter.ContainsTargetPath("Build/Projects/"))
                    {
                        RedirectableConsole.WriteLine("ERROR: The Build\\Projects directory does not exist in the source folder.");
                        if (execution.PackageFilterFile != null)
                        {
                            this.PrintFilterMappings(filter);
                        }
                        return(1);
                    }

                    if (!filter.ContainsTargetPath("Build/Module.xml"))
                    {
                        RedirectableConsole.WriteLine("ERROR: The Build\\Module.xml file does not exist in the source folder.");
                        if (execution.PackageFilterFile != null)
                        {
                            this.PrintFilterMappings(filter);
                        }
                        return(1);
                    }
                }

                if (filter.ContainsTargetPath("Protobuild.exe"))
                {
                    RedirectableConsole.WriteLine("ERROR: The Protobuild.exe file should not be included in the package file.");
                    if (execution.PackageFilterFile != null)
                    {
                        this.PrintFilterMappings(filter);
                    }
                    return(1);
                }

                using (
                    var target = new FileStream(execution.PackageDestinationFile, FileMode.CreateNew, FileAccess.Write,
                                                FileShare.None))
                {
                    _packageCreator.Create(
                        target,
                        filter,
                        execution.PackageSourceFolder,
                        execution.PackageFormat,
                        execution.PackagePlatform,
                        execution.PackageDestinationFile);
                }

                RedirectableConsole.WriteLine("\rPackage written to " + execution.PackageDestinationFile + " successfully.");
                return(0);
            }
            finally
            {
                foreach (var file in temporaryFiles)
                {
                    File.Delete(file);
                }
            }
        }
        public void Autopackage(
            string workingDirectory,
            FileFilter fileFilter,
            Execution execution,
            ModuleInfo module,
            string rootPath,
            string platform,
            string packageFormat,
            List <string> temporaryFiles)
        {
            var definitions    = module.GetDefinitionsRecursively(platform).ToArray();
            var loadedProjects = new List <LoadedDefinitionInfo>();

            foreach (var definition in definitions)
            {
                RedirectableConsole.WriteLine("Loading: " + definition.Name);
                loadedProjects.Add(
                    this.m_ProjectLoader.Load(
                        platform,
                        module,
                        definition));
            }

            var            serviceManager = new ServiceManager(platform);
            List <Service> services;

            serviceManager.SetRootDefinitions(module.GetDefinitions());

            var enabledServices  = execution.EnabledServices.ToArray();
            var disabledServices = execution.DisabledServices.ToArray();

            foreach (var service in enabledServices)
            {
                serviceManager.EnableService(service);
            }

            foreach (var service in disabledServices)
            {
                serviceManager.DisableService(service);
            }

            if (execution.DebugServiceResolution)
            {
                serviceManager.EnableDebugInformation();
            }

            services = serviceManager.CalculateDependencyGraph(loadedProjects.Select(x => x.Project).ToList());

            foreach (var service in services)
            {
                if (service.ServiceName != null)
                {
                    RedirectableConsole.WriteLine("Enabled service: " + service.FullName);
                }
            }

            var packagePaths = module.Packages
                               .Select(x => new DirectoryInfo(System.IO.Path.Combine(module.Path, x.Folder)).FullName)
                               .ToArray();

            foreach (var definition in definitions)
            {
                if (definition.SkipAutopackage)
                {
                    RedirectableConsole.WriteLine("Skipping: " + definition.Name);
                    continue;
                }

                var definitionNormalizedPath = new FileInfo(definition.AbsolutePath).FullName;
                if (packagePaths.Any(definitionNormalizedPath.StartsWith))
                {
                    RedirectableConsole.WriteLine("Skipping: " + definition.Name + " (part of another package)");
                    continue;
                }

                switch (definition.Type)
                {
                case "External":
                    RedirectableConsole.WriteLine("Packaging: " + definition.Name);
                    this.AutomaticallyPackageExternalProject(definitions, services, fileFilter, rootPath, platform, definition, temporaryFiles);
                    break;

                case "Include":
                    RedirectableConsole.WriteLine("Packaging: " + definition.Name);
                    this.AutomaticallyPackageIncludeProject(definitions, services, fileFilter, rootPath, platform, definition);
                    break;

                case "Content":
                    RedirectableConsole.WriteLine("Content project definition skipped: " + definition.Name);
                    break;

                default:
                    RedirectableConsole.WriteLine("Packaging: " + definition.Name);
                    this.AutomaticallyPackageNormalProject(definitions, services, fileFilter, rootPath, platform, definition, temporaryFiles);
                    break;
                }
            }

            // If there is no Module.xml in the source mappings already, then copy the current module.
            if (!fileFilter.ContainsTargetPath("Build/Module.xml"))
            {
                fileFilter.AddManualMapping(Path.Combine(module.Path, "Build", "Module.xml"), "Build/Module.xml");
            }
        }
        public int ExecuteForTemplate(Execution execution)
        {
            if (!Directory.Exists(execution.PackageSourceFolder))
            {
                throw new InvalidOperationException("The source folder " + execution.PackageSourceFolder + " does not exist.");
            }

            RedirectableConsole.WriteLine("Starting package creation for " + execution.PackagePlatform);

            var filter = new FileFilter(_getRecursiveUtilitiesInPath.GetRecursiveFilesInPath(execution.PackageSourceFolder));

            if (execution.PackageFilterFile != null)
            {
                using (var reader = new StreamReader(execution.PackageFilterFile))
                {
                    var contents = reader.ReadToEnd();
                    contents = contents.Replace("%PLATFORM%", execution.PackagePlatform);

                    using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(contents)))
                    {
                        this.m_FileFilterParser.ParseAndApply(filter, inputStream, new Dictionary <string, Action <FileFilter> >());
                    }
                }
            }
            else
            {
                filter.ApplyInclude("^.*$");
                filter.ApplyExclude("^\\.git/.*$");
                filter.ApplyExclude("^\\.hg/.*$");
                filter.ApplyExclude("^\\.svn/.*$");
            }

            if (File.Exists(execution.PackageDestinationFile))
            {
                RedirectableConsole.WriteLine("The destination file " + execution.PackageDestinationFile + " already exists; it will be overwritten.");
                File.Delete(execution.PackageDestinationFile);
            }

            filter.ImplyDirectories();

            var filterDictionary = filter.ToDictionary(k => k.Key, v => v.Value);

            if (!filter.ContainsTargetPath("Build/"))
            {
                RedirectableConsole.WriteLine("ERROR: The Build directory does not exist in the source folder.");
                if (execution.PackageFilterFile != null)
                {
                    this.PrintFilterMappings(filter);
                }
                return(1);
            }

            if (!filter.ContainsTargetPath("Build/Projects/"))
            {
                RedirectableConsole.WriteLine("ERROR: The Build\\Projects directory does not exist in the source folder.");
                if (execution.PackageFilterFile != null)
                {
                    this.PrintFilterMappings(filter);
                }
                return(1);
            }

            if (!filter.ContainsTargetPath("Build/Module.xml"))
            {
                RedirectableConsole.WriteLine("ERROR: The Build\\Module.xml file does not exist in the source folder.");
                if (execution.PackageFilterFile != null)
                {
                    this.PrintFilterMappings(filter);
                }
                return(1);
            }

            if (filter.ContainsTargetPath("Protobuild.exe"))
            {
                RedirectableConsole.WriteLine("ERROR: The Protobuild.exe file should not be included in the package file.");
                if (execution.PackageFilterFile != null)
                {
                    this.PrintFilterMappings(filter);
                }
                return(1);
            }

            using (var target = new FileStream(execution.PackageDestinationFile, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                _packageCreator.Create(
                    target,
                    filter,
                    execution.PackageSourceFolder,
                    execution.PackageFormat,
                    execution.PackagePlatform,
                    execution.PackageDestinationFile);
            }

            RedirectableConsole.WriteLine("\rPackage written to " + execution.PackageDestinationFile + " successfully.");
            return(0);
        }