public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageFile, "No package file was specified. Please pass --package YourPackage.nupkg");

            if (!File.Exists(packageFile))
                throw new CommandException("Could not find package file: " + packageFile);

            if (variablesFile != null && !File.Exists(variablesFile))
                throw new CommandException("Could not find variables file: " + variablesFile);

            Log.Info("Deploying package:    " + packageFile);
            if (variablesFile != null)
                Log.Info("Using variables from: " + variablesFile);

            var variables = new VariableDictionary(variablesFile);

            var fileSystem = new WindowsPhysicalFileSystem();
            var embeddedResources = new ExecutingAssemblyEmbeddedResources();
            var scriptEngine = new CombinedScriptEngine();
            var commandLineRunner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));
            var azurePackageUploader = new AzurePackageUploader();
            var certificateStore = new CalamariCertificateStore();
            var cloudCredentialsFactory = new SubscriptionCloudCredentialsFactory(certificateStore);
            var cloudServiceConfigurationRetriever = new AzureCloudServiceConfigurationRetriever();
            var substituter = new FileSubstituter();
            var configurationTransformer = new ConfigurationTransformer(variables.GetFlag(SpecialVariables.Package.IgnoreConfigTransformationErrors), variables.GetFlag(SpecialVariables.Package.SuppressConfigTransformationLogging));
            var replacer = new ConfigurationVariablesReplacer();

            var conventions = new List<IConvention>
            {
                new ContributeEnvironmentVariablesConvention(),
                new LogVariablesConvention(),
                new ExtractPackageToStagingDirectoryConvention(new LightweightPackageExtractor(), fileSystem),
                new FindCloudServicePackageConvention(fileSystem),
                new EnsureCloudServicePackageIsCtpFormatConvention(fileSystem),
                new ExtractAzureCloudServicePackageConvention(fileSystem),
                new ChooseCloudServiceConfigurationFileConvention(fileSystem),
                new ConfiguredScriptConvention(DeploymentStages.PreDeploy, scriptEngine, fileSystem, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfigureAzureCloudServiceConvention(fileSystem, cloudCredentialsFactory, cloudServiceConfigurationRetriever),
                new SubstituteInFilesConvention(fileSystem, substituter),
                new ConfigurationTransformsConvention(fileSystem, configurationTransformer),
                new ConfigurationVariablesConvention(fileSystem, replacer),
                new PackagedScriptConvention(DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.Deploy, scriptEngine, fileSystem, commandLineRunner),
                new RePackageCloudServiceConvention(fileSystem),
                new UploadAzureCloudServicePackageConvention(fileSystem, azurePackageUploader, cloudCredentialsFactory),
                new DeployAzureCloudServicePackageConvention(fileSystem, embeddedResources, scriptEngine, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PostDeploy, scriptEngine, fileSystem, commandLineRunner),
            };

            var deployment = new RunningDeployment(packageFile, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);
            conventionRunner.RunConventions();

            return 0;
        }
예제 #2
0
        public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
        {
            var source = File.ReadAllText(sourceFile);

            var result = variables.Evaluate(source);
            File.WriteAllText(targetFile, result);
        }
		public OctopusConfigurationProviderTests()
		{
			Options = new OctopusConfigurationProviderOptions();
			VariableDictionaryProvider = new Mock<IVariableDictionaryProvider>();
			VariableDictionary = new VariableDictionary();
			VariableDictionaryProvider.Setup(value => value.Get(Options)).Returns(VariableDictionary);
		}
        public CalamariVariableDictionary(string storageFilePath, string sensitiveFilePath, string sensitiveFilePassword)
        {
            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            if (!string.IsNullOrEmpty(storageFilePath))
            {
                if (!fileSystem.FileExists(storageFilePath))
                    throw new CommandException("Could not find variables file: " + storageFilePath);

                var nonSensitiveVariables =  new VariableDictionary(storageFilePath);
                nonSensitiveVariables.GetNames().ForEach(name => Set(name, nonSensitiveVariables.GetRaw(name)));
            }

            if (!string.IsNullOrEmpty(sensitiveFilePath))
            {
                var rawVariables = string.IsNullOrWhiteSpace(sensitiveFilePassword)
                    ? fileSystem.ReadFile(sensitiveFilePath)
                    : Decrypt(fileSystem.ReadAllBytes(sensitiveFilePath), sensitiveFilePassword);


                try
                {
                    var sensitiveVariables = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawVariables);
                    foreach (var variable in sensitiveVariables)
                    {
                        SetSensitive(variable.Key, variable.Value);
                    }
                }
                catch (JsonReaderException)
                {
                    throw new CommandException("Unable to parse sensitive-variables as valid JSON.");
                }
            }
        }
 public void SetUp()
 {
     variables = new VariableDictionary();
     variables.Set(SpecialVariables.OriginalPackageDirectoryPath, stagingDirectory);
     fileSystem = Substitute.For<ICalamariFileSystem>();
     deployment = new RunningDeployment(packageFilePath, variables);
 }
        public void Deploy()
        {
            OctopusTestAzureSubscription.IgnoreIfCertificateNotInstalled();

            var nugetPackageFile = PackageBuilder.BuildSamplePackage("Octopus.Sample.AzureCloudService", "1.0.0");

            var variablesFile = Path.GetTempFileName();
            var variables = new VariableDictionary();
            OctopusTestAzureSubscription.PopulateVariables(variables);
            OctopusTestCloudService.PopulateVariables(variables);
            variables.Set(SpecialVariables.Action.Azure.Slot, "Staging");
            variables.Set(SpecialVariables.Action.Azure.SwapIfPossible, false.ToString());
            variables.Set(SpecialVariables.Action.Azure.UseCurrentInstanceCount, false.ToString());

            variables.Set(SpecialVariables.Action.Name, "AzureCloudService");
            variables.Set(SpecialVariables.Release.Number, "1.0.0");

            // Disable cspkg extraction
            variables.Set(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled, true.ToString());

            fileSystem = new WindowsPhysicalFileSystem();
            stagingDirectory = Path.GetTempPath();
            variables.Set(SpecialVariables.Action.Azure.PackageExtractionPath, stagingDirectory);

            variables.Save(variablesFile);

            result = Invoke(
                Calamari()
                    .Action("deploy-azure-cloud-service")
                    .Argument("package", nugetPackageFile)
                    .Argument("variables", variablesFile));
        }
예제 #7
0
 public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
 {
     var source = fileSystem.ReadFile(sourceFile);
     var encoding = GetEncoding(sourceFile, variables);
     var result = variables.Evaluate(source);
     fileSystem.OverwriteFile(targetFile, result, encoding);
 }
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageFile, "No package file was specified. Please pass -cspkg YourPackage.cspkg");

            if (!File.Exists(packageFile))
                throw new CommandException("Could not find package file: " + packageFile);

            var variables = new VariableDictionary();
            variables.Set(SpecialVariables.Action.Azure.CloudServicePackagePath, packageFile);
            variables.Set(SpecialVariables.OriginalPackageDirectoryPath, !string.IsNullOrWhiteSpace(destinationDirectory) ? destinationDirectory : Path.GetDirectoryName(packageFile));

            var fileSystem = new WindowsPhysicalFileSystem();

            var conventions = new List<IConvention>
            {
                new EnsureCloudServicePackageIsCtpFormatConvention(fileSystem),
                new ExtractAzureCloudServicePackageConvention(fileSystem),
            };

            var deployment = new RunningDeployment(packageFile, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);
            conventionRunner.RunConventions();

            return 0;
        }
예제 #9
0
 static void AddVariables(VariableDictionary variableDictionary, IDictionary<string, string> items)
 {
     foreach (var variableName in items.Keys)
     {
        variableDictionary.Set(variableName, items[variableName]);
     }
 }
예제 #10
0
 protected CalamariResult Invoke(CommandLine command, VariableDictionary variables)
 {
     var capture = new CaptureCommandOutput();
     var runner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables), capture));
     var result = runner.Execute(command.Build());
     return new CalamariResult(result.ExitCode, capture);
 }
        static void UpdateConfigurationSettings(XContainer configurationFile, VariableDictionary variables)
        {
            Log.Verbose("Updating configuration settings...");
            var foundSettings = false;

            WithConfigurationSettings(configurationFile, (roleName, settingName, settingValueAttribute) =>
            {
                var setting = variables.Get(roleName + "/" + settingName) ??
                            variables.Get(roleName + "\\" + settingName) ??
                            variables.Get(settingName) ??
                            (variables.GetNames().Contains(settingName) ? "" : null);
                
                if (setting != null)
                {
                    foundSettings = true;
                    Log.Info("Updating setting for role {0}: {1} = {2}", roleName, settingName, setting);
                    settingValueAttribute.Value = setting;
                }
            });

            if (!foundSettings)
            {
                Log.Info("No settings that match provided variables were found.");
            }
        }
예제 #12
0
        public void SetUp()
        {
            fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            // Ensure tenticle directory exists
            tentacleDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestTentacle");
            var tentacleHiddenDirectory = Path.Combine(tentacleDirectory, ".tentacle"); 
            fileSystem.EnsureDirectoryExists(tentacleDirectory);
            fileSystem.EnsureDirectoryExists(tentacleHiddenDirectory);
            fileSystem.PurgeDirectory(tentacleHiddenDirectory, FailureOptions.ThrowOnFailure);

            Environment.SetEnvironmentVariable("TentacleJournal", Path.Combine(tentacleHiddenDirectory, "DeploymentJournal.xml" ));

            variables = new VariableDictionary();
            variables.EnrichWithEnvironmentVariables();

            deploymentJournal = new DeploymentJournal(fileSystem, new SystemSemaphore(), variables);

            packagesDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestPackages");
            fileSystem.EnsureDirectoryExists(packagesDirectory);
            stagingDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestStaging");
            fileSystem.EnsureDirectoryExists(stagingDirectory);

            // Create some artificats
            const string retentionPolicySet1 = "retentionPolicySet1";

            CreateDeployment(Path.Combine(packagesDirectory, "Acme.1.0.0.nupkg"), Path.Combine(stagingDirectory, "Acme.1.0.0"), 
                new DateTimeOffset(new DateTime(2015, 01, 26), new TimeSpan(10, 0,0)), retentionPolicySet1);

            CreateDeployment(Path.Combine(packagesDirectory, "Acme.1.1.0.nupkg"), Path.Combine(stagingDirectory, "Acme.1.1.0"), 
                new DateTimeOffset(new DateTime(2015, 02, 01), new TimeSpan(10, 0,0)), retentionPolicySet1);

            CreateDeployment(Path.Combine(packagesDirectory, "Acme.1.2.0.nupkg"), Path.Combine(stagingDirectory, "Acme.1.2.0"), 
                new DateTimeOffset(new DateTime(2015, 02, 10), new TimeSpan(10, 0,0)), retentionPolicySet1);
        }
        static IEnumerable<string> ReplaceAppSettingOrConnectionString(XNode document, string xpath, string keyAttributeName, string keyAttributeValue, string valueAttributeName, VariableDictionary variables)
        {
            var changes = new List<string>();
            var settings = (
                from element in document.XPathSelectElements(xpath)
                let keyAttribute = element.Attribute(keyAttributeName)
                where keyAttribute != null
                where string.Equals(keyAttribute.Value, keyAttributeValue, StringComparison.InvariantCultureIgnoreCase)
                select element).ToList();

            if (settings.Count == 0)
                return changes;

            var value = variables.Get(keyAttributeValue) ?? string.Empty;

            foreach (var setting in settings)
            {
                changes.Add(string.Format("Setting '{0}' = '{1}'", keyAttributeValue, value));

                var valueAttribute = setting.Attribute(valueAttributeName);
                if (valueAttribute == null)
                {
                    setting.Add(new XAttribute(valueAttributeName, value));
                }
                else
                {
                    valueAttribute.SetValue(value);
                }
            }

            return changes;
        }
예제 #14
0
 void SetOutputVariable(string name, string value, VariableDictionary variables)
 {
     if (variables.Get(name) != value)
     {
         Log.SetOutputVariable(name, value, variables);
     }
 }
예제 #15
0
        private static string BuildPath(string site, VariableDictionary variables)
        {
            var relativePath = (variables.Get(SpecialVariables.Action.Azure.PhysicalPath) ?? "").TrimStart('\\');

            return relativePath != ""
                ? site + "\\" + relativePath
                : site;
        }
        private string GetInitialExtractionDirectory(VariableDictionary variables)
        {
            var root = GetApplicationDirectoryPath(variables);
            root = AppendEnvironmentNameIfProvided(variables, root);
            fileSystem.EnsureDirectoryExists(root);
            fileSystem.EnsureDiskHasEnoughFreeSpace(root);

            return root;
        }
        public void SetUp()
        {
            fileSystem = Substitute.For<ICalamariFileSystem>();
            variables = new VariableDictionary();
            variables.Set(SpecialVariables.OriginalPackageDirectoryPath, StagingDirectory);
            deployment = new RunningDeployment(StagingDirectory, variables);

            convention = new ChooseCloudServiceConfigurationFileConvention(fileSystem);
        }
예제 #18
0
파일: Log.cs 프로젝트: sergio/Calamari
        public static void SetOutputVariable(string name, string value, VariableDictionary variables)
        {
            Info(String.Format("##octopus[setVariable name=\"{0}\" value=\"{1}\"]",
                ConvertServiceMessageValue(name),
                ConvertServiceMessageValue(value)));

            if (variables != null)
                variables.SetOutputVariable(name, value);
        }
        private VariableDictionary AddEnvironmentVariables()
        {
            var variables = new VariableDictionary();
            var convention = new ContributeEnvironmentVariablesConvention();
            convention.Install(new RunningDeployment("C:\\Package.nupkg", variables));

            Assert.That(variables.GetNames().Count, Is.GreaterThan(3));
            Assert.That(variables.GetRaw(SpecialVariables.Tentacle.Agent.InstanceName), Is.EqualTo("#{env:TentacleInstanceName}"));
            return variables;
        }
 public void SetUp()
 {
     variables = new VariableDictionary();
     fileSystem = Substitute.For<ICalamariFileSystem>();
     iis = Substitute.For<IInternetInformationServer>();
     deployment = new RunningDeployment("C:\\packages", variables)
     {
         StagingDirectory = stagingDirectory
     };
 }
예제 #21
0
 string PerformTest(string sampleFile, VariableDictionary variables)
 {
     var temp = Path.GetTempFileName();
     using (new TemporaryFile(temp))
     {
         var substituter = new FileSubstituter();
         substituter.PerformSubstitution(sampleFile, variables, temp);
         return File.ReadAllText(temp);
     }
 }
        public void DoesNotAddXmlHeader()
        {
            var variables = new VariableDictionary();
            variables.Set("WelcomeMessage", "Hello world");
            variables.Set("LogFile", "C:\\Log.txt");
            variables.Set("DatabaseConnection", null);

            var text = PerformTest(GetFixtureResouce("Samples", "NoHeader.config"), variables);
            Assert.That(text, Is.StringStarting("<configuration"));
        }
        public static void PopulateVariables(VariableDictionary variables)
        {
            var certificate = GetCertificate();

            variables.Set(SpecialVariables.Account.Name, "OctopusAzureTestAccount");
            variables.Set(SpecialVariables.Account.AccountType, "AzureSubscription");
            variables.Set(SpecialVariables.Action.Azure.CertificateBytes, Convert.ToBase64String(certificate.Export(X509ContentType.Pfx)));
            variables.Set(SpecialVariables.Action.Azure.CertificateThumbprint, CertificateThumbprint);
            variables.Set(SpecialVariables.Action.Azure.SubscriptionId, AzureSubscriptionId);
        }
예제 #24
0
        public void ShouldKeepExistingValues()
        {
            var variables = new VariableDictionary();
            variables.Set("MyMessage", "Hello world!");
            variables.Set("EmailSettings:SmtpPort", "24");
            variables.Set("EmailSettings:DefaultRecipients:Cc", "*****@*****.**");

            var generated = Generate(variables, existingFile: "appsettings.existing-expected.json");
            AssertJsonEquivalent(generated, "appsettings.existing-expected.json");
        }
        public void SetUp()
        {
            fileSystem = Substitute.For<ICalamariFileSystem>();
            substituter = Substitute.For<IFileSubstituter>();
            variables = new VariableDictionary();

            deployment = new RunningDeployment(TestEnvironment.ConstructRootedPath("packages"), variables)
            {
                StagingDirectory = StagingDirectory
            };
        }
        string AppendEnvironmentNameIfProvided(VariableDictionary variables, string root)
        {
            var environment = variables.Get(SpecialVariables.Environment.Name);
            if (!string.IsNullOrWhiteSpace(environment))
            {
                environment = fileSystem.RemoveInvalidFileNameChars(environment);
                root = Path.Combine(root, environment);
            }

            return root;
        }
예제 #27
0
 public void ShouldIgnoreOctopusPrefix()
 {
     var variables = new VariableDictionary();
     variables.Set("MyMessage", "Hello world");
     variables.Set("IThinkOctopusIsGreat", "Yes, I do");
     variables.Set("OctopusRocks", "This is ignored");
     variables.Set("Octopus.Rocks", "So is this");
     
     var generated = Generate(variables);
     AssertJsonEquivalent(generated, "appsettings.ignore-octopus.json");
 }
        public void SetUp()
        {
            extractor = Substitute.For<IPackageExtractor>();
            extractor.GetMetadata(PackageLocation).Returns(new PackageMetadata { Id = "Acme.Web", Version = "1.0.0" });

            fileSystem = Substitute.For<ICalamariFileSystem>();
            fileSystem.RemoveInvalidFileNameChars(Arg.Any<string>()).Returns(c => c.Arg<string>().Replace("!", ""));

            variables = new VariableDictionary();
            convention = new ExtractPackageToApplicationDirectoryConvention(extractor, fileSystem, new SystemSemaphore());
        }
예제 #29
0
        private int InvokeScript(VariableDictionary variables)
        {
            if (!File.Exists(scriptFile))
                throw new CommandException("Could not find script file: " + scriptFile);

            var scriptEngine = new CombinedScriptEngine();
            var runner = new CommandLineRunner(
                new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));
            var result = scriptEngine.Execute(scriptFile, variables, runner);
            return result.ExitCode;
        }
예제 #30
0
        protected CalamariResult Invoke(CommandLine command, VariableDictionary variables = null)
        {
            var capture = new CaptureCommandOutput();
            var runner  = new CommandLineRunner(
                new SplitCommandOutput(
                    new ConsoleCommandOutput(),
                    new ServiceMessageCommandOutput(variables ?? new VariableDictionary()),
                    capture));
            var result = runner.Execute(command.Build());

            return(new CalamariResult(result.ExitCode, capture));
        }
예제 #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModelOptionsBase"/> class.
        /// </summary>
        protected ModelOptionsBase(VariableDictionary variables, string prefix)
            : base(variables, prefix)
        {
            // null so shared option is used
            this.Namespace = null;
            this.Directory = null;

            this.Generate = false;

            this.Include = new SelectionOptions();
            this.Exclude = new SelectionOptions();
        }
예제 #32
0
        public void ShouldSetVariables()
        {
            var variables = new VariableDictionary();

            var output = Invoke(Calamari()
                                .Action("run-script")
                                .Argument("script", MapSamplePath("Scripts\\CanSetVariable.ps1")), variables);

            output.AssertZero();
            output.AssertOutput("##octopus[setVariable name='VGVzdEE=' value='V29ybGQh']");
            Assert.AreEqual("World!", variables.Get("TestA"));
        }
        public void DoesNotAddXmlHeader()
        {
            var variables = new VariableDictionary();

            variables.Set("WelcomeMessage", "Hello world");
            variables.Set("LogFile", "C:\\Log.txt");
            variables.Set("DatabaseConnection", null);

            var text = PerformTest("Samples\\NoHeader.config", variables);

            Assert.That(text, Is.StringStarting("<configuration"));
        }
예제 #34
0
 private static void ApplyPreserveAppDataDeploymentRule(DeploymentSyncOptions syncOptions,
                                                        VariableDictionary variables)
 {
     // If PreserveAppData variable set, then create SkipDelete rules for App_Data directory
     if (variables.GetFlag(SpecialVariables.Action.Azure.PreserveAppData))
     {
         syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataFiles", "Delete", "filePath",
                                                      "\\\\App_Data\\\\.*", null));
         syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataDir", "Delete", "dirPath",
                                                      "\\\\App_Data(\\\\.*|$)", null));
     }
 }
예제 #35
0
        public void ShouldSaveAsString()
        {
            var variables = new VariableDictionary();

            variables.Set("Name", "Web01");
            variables.Set("Port", "10933");

            variables.SaveAsString().Should().Be("{" + Environment.NewLine +
                                                 "  \"Name\": \"Web01\"," + Environment.NewLine +
                                                 "  \"Port\": \"10933\"" + Environment.NewLine +
                                                 "}");
        }
예제 #36
0
        public void VariablesThatResolveToUnresolvableReturnError(string variable, string pattern, string expectedResult, string testName)
        {
            var variables = new VariableDictionary
            {
                ["Test"] = variable
            };

            string err;

            variables.Evaluate(pattern, out err).Should().Be(expectedResult);
            err.Should().Be($"The following tokens were unable to be evaluated: '{expectedResult}'");
        }
예제 #37
0
 static void WriteScriptModules(VariableDictionary variables, string parentDirectory, StringBuilder output)
 {
     foreach (var variableName in variables.GetNames().Where(SpecialVariables.IsLibraryScriptModule))
     {
         var name           = "Library_" + new string(SpecialVariables.GetLibraryScriptModuleName(variableName).Where(char.IsLetterOrDigit).ToArray()) + "_" + DateTime.Now.Ticks;
         var moduleFileName = $"{name}.psm1";
         var moduleFilePath = Path.Combine(parentDirectory, moduleFileName);
         CalamariFileSystem.OverwriteFile(moduleFilePath, variables.Get(variableName), Encoding.UTF8);
         output.AppendLine($"Import-ScriptModule '{SpecialVariables.GetLibraryScriptModuleName(variableName)}' '{moduleFilePath}'");
         output.AppendLine();
     }
 }
예제 #38
0
        public void InfiniteLoop()
        {
            var dictionary = new VariableDictionary();

            dictionary.Set("Database.Name", "{Project.Name}");
            dictionary.Set("Project.Name", "{Database.Name}");
            dictionary.Set("Project.Namespace", "{Database.Name}.Core");

            var result = dictionary.Get("Project.Namespace");

            result.Should().Be(".Core");
        }
예제 #39
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DatabaseOptions"/> class.
        /// </summary>
        /// <param name="variables">The shared variables dictionary.</param>
        /// <param name="prefix">The variable key prefix.</param>
        public DatabaseOptions(VariableDictionary variables, string prefix)
            : base(variables, AppendPrefix(prefix, "Database"))
        {
            Provider    = DatabaseProviders.SqlServer;
            TableNaming = TableNaming.Singular;

            Name = "{Database.ModelDatabaseName}";

            Tables  = new List <string>();
            Schemas = new List <string>();
            Exclude = new List <MatchOptions>();
        }
        public void NoInstructions()
        {
            var variables = new VariableDictionary
            {
                { SpecialVariables.Execution.Manifest, "[]" }
            };

            var result = ExecuteCommand(variables);

            result.AssertFailure();
            result.AssertErrorOutput("The execution manifest must have at least one instruction.");
        }
예제 #41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseModelOptions"/> class.
        /// </summary>
        protected BaseModelOptions(VariableDictionary variables, string prefix)
            : base(variables, prefix)
        {
            // null so shared option is used
            Namespace = null;
            Directory = null;

            Generate = false;

            Include = new SelectionOptions();
            Exclude = new SelectionOptions();
        }
예제 #42
0
    public void SetTwoValues(object value1, object value2)
    {
        var sut = new VariableDictionary();

        sut["alpha"] = value1;
        sut["beta"]  = value2;
        sut.Count.Should().Be(2);
        sut.IsSet("alpha").Should().BeTrue();
        sut.IsSet("beta").Should().BeTrue();
        sut["alpha"].Should().Be(value1);
        sut["beta"].Should().Be(value2);
    }
예제 #43
0
        public void ShouldKeepExistingValues()
        {
            var variables = new VariableDictionary();

            variables.Set("MyMessage", "Hello world!");
            variables.Set("EmailSettings:SmtpPort", "24");
            variables.Set("EmailSettings:DefaultRecipients:Cc", "*****@*****.**");

            var generated = Generate(variables, existingFile: "appsettings.existing-expected.json");

            AssertJsonEquivalent(generated, "appsettings.existing-expected.json");
        }
        string PerformTest(string sampleFile, VariableDictionary variables)
        {
            var temp = Path.GetTempFileName();

            File.Copy(sampleFile, temp, true);

            using (new TemporaryFile(temp))
            {
                configurationVariablesReplacer.ModifyConfigurationFile(temp, variables);
                return(File.ReadAllText(temp));
            }
        }
예제 #45
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProfileOptions"/> class.
        /// </summary>
        public ProfileOptions(ProfileInfo profile)
        {
            Variables = new VariableDictionary();

            Options = new OptionsOptions(profile, Variables, null);

            Project  = new ProjectOptions(Variables, null);
            Database = new DatabaseOptions(Variables, null);
            Data     = new DataOptions(Variables, null);
            Model    = new ModelOptions(Variables, null);
            Script   = new ScriptOptions(Variables, null);
        }
예제 #46
0
        public void ShouldSetVariables()
        {
            var variables = new VariableDictionary();

            var output = Invoke(Calamari()
                                .Action("run-script")
                                .Argument("script", GetFixtureResouce("Scripts", "CanSetVariable.ps1")), variables);

            output.AssertSuccess();
            output.AssertOutput("##octopus[setVariable name='VGVzdEE=' value='V29ybGQh']");
            Assert.AreEqual("World!", variables.Get("TestA"));
        }
        static string AppendTenantNameIfProvided(ICalamariFileSystem fileSystem, VariableDictionary variables, string root)
        {
            var tenant = variables.Get(SpecialVariables.Deployment.Tenant.Name);

            if (!string.IsNullOrWhiteSpace(tenant))
            {
                tenant = fileSystem.RemoveInvalidFileNameChars(tenant);
                root   = Path.Combine(root, tenant);
            }

            return(root);
        }
예제 #48
0
        protected string Evaluate(string template, IDictionary <string, string> variables, bool haltOnError = true)
        {
            var dictionary = new VariableDictionary();

            foreach (var pair in variables)
            {
                dictionary[pair.Key] = pair.Value;
            }
            string error;

            return(dictionary.Evaluate(template, out error, haltOnError));
        }
예제 #49
0
        private static string DeclareVariables(VariableDictionary variables)
        {
            var output = new StringBuilder();

            WriteScriptModules(variables, output);
            output.AppendLine();
            WriteVariableDictionary(variables, output);
            output.AppendLine();
            WriteLocalVariables(variables, output);

            return(output.ToString());
        }
        public static void LogVariables(this VariableDictionary variables)
        {
            if (variables.GetFlag(SpecialVariables.PrintVariables))
            {
                Log.Verbose("The following variables are available:" + Environment.NewLine + variables.ToString(IsPrintable, true));
            }

            if (variables.GetFlag(SpecialVariables.PrintEvaluatedVariables))
            {
                Log.Verbose("The following evaluated variables are available:" + Environment.NewLine + variables.ToString(IsPrintable, false));
            }
        }
예제 #51
0
        public void ShouldRevertToExistingEncodingIfInvalid()
        {
            var filePath  = GetFixtureResouce("Samples", "UTF16LE.ini");
            var variables = new VariableDictionary();

            variables[SpecialVariables.Package.SubstituteInFilesOutputEncoding] = "utf-666";

            var encoding = (Encoding)PerformTest(filePath, variables).Encoding;

            Assert.AreEqual(Encoding.Unicode, FileSystem.GetFileEncoding(filePath));
            Assert.AreEqual(Encoding.Unicode, encoding);
        }
        string AppendEnvironmentNameIfProvided(VariableDictionary variables, string root)
        {
            var environment = variables.Get(SpecialVariables.Environment.Name);

            if (!string.IsNullOrWhiteSpace(environment))
            {
                environment = fileSystem.RemoveInvalidFileNameChars(environment);
                root        = Path.Combine(root, environment);
            }

            return(root);
        }
예제 #53
0
        public void ShouldSetActionIndexedOutputVariables()
        {
            var variables = new VariableDictionary();
            variables.Set(SpecialVariables.Action.Name, "run-script");

            var output = Invoke(Calamari() 
                .Action("run-script")
                .Argument("script", GetFixtureResouce("Scripts", "CanSetVariable.ps1")), 
                variables);

            Assert.AreEqual("World!", variables.Get("Octopus.Action[run-script].Output.TestA"));
        }
예제 #54
0
        IEnumerable <string> ExecuteAndReturnLogOutput(Action <VariableDictionary> populateVariables, string folderName, params Type[] commandTypes)
        {
            void Copy(string sourcePath, string destinationPath)
            {
                foreach (var dirPath in Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
                }

                foreach (var newPath in Directory.EnumerateFiles(sourcePath, "*.*", SearchOption.AllDirectories))
                {
                    File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
                }
            }

            using (var currentDirectory = TemporaryDirectory.Create())
            {
                var variablesFile = Path.GetTempFileName();
                var variables     = new VariableDictionary();
                variables.Set(TerraformSpecialVariables.Calamari.TerraformCliPath, Path.GetDirectoryName(customTerraformExecutable));
                variables.Set(SpecialVariables.OriginalPackageDirectoryPath, currentDirectory.DirectoryPath);
                variables.Set(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable, customTerraformExecutable);

                populateVariables(variables);

                var terraformFiles = TestEnvironment.GetTestPath("Terraform", folderName);

                Copy(terraformFiles, currentDirectory.DirectoryPath);

                variables.Save(variablesFile);

                using (new TemporaryFile(variablesFile))
                {
                    foreach (var commandType in commandTypes)
                    {
                        var sb = new StringBuilder();
                        Log.StdOut = new IndentedTextWriter(new StringWriter(sb));

                        var command = (ICommand)Activator.CreateInstance(commandType);
                        var result  = command.Execute(new[] { "--variables", $"{variablesFile}" });

                        result.Should().Be(0);

                        var output = sb.ToString();

                        Console.WriteLine(output);

                        yield return(output);
                    }
                }
            }
        }
예제 #55
0
        public CalamariVariableDictionary(string storageFilePath, string sensitiveFilePath, string sensitiveFilePassword, string outputVariablesFilePath = null, string outputVariablesFilePassword = null)
        {
            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            if (!string.IsNullOrEmpty(storageFilePath))
            {
                if (!fileSystem.FileExists(storageFilePath))
                {
                    throw new CommandException("Could not find variables file: " + storageFilePath);
                }

                var nonSensitiveVariables = new VariableDictionary(storageFilePath);
                nonSensitiveVariables.GetNames().ForEach(name => Set(name, nonSensitiveVariables.GetRaw(name)));
            }

            if (!string.IsNullOrEmpty(sensitiveFilePath))
            {
                var rawVariables = string.IsNullOrWhiteSpace(sensitiveFilePassword)
                    ? fileSystem.ReadFile(sensitiveFilePath)
                    : Decrypt(fileSystem.ReadAllBytes(sensitiveFilePath), sensitiveFilePassword);

                try
                {
                    var sensitiveVariables = JsonConvert.DeserializeObject <Dictionary <string, string> >(rawVariables);
                    foreach (var variable in sensitiveVariables)
                    {
                        SetSensitive(variable.Key, variable.Value);
                    }
                }
                catch (JsonReaderException)
                {
                    throw new CommandException("Unable to parse sensitive-variables as valid JSON.");
                }
            }

            if (!string.IsNullOrEmpty(outputVariablesFilePath))
            {
                var rawVariables = DecryptWithMachineKey(fileSystem.ReadFile(outputVariablesFilePath), outputVariablesFilePassword);
                try
                {
                    var outputVariables = JsonConvert.DeserializeObject <Dictionary <string, string> >(rawVariables);
                    foreach (var variable in outputVariables)
                    {
                        Set(variable.Key, variable.Value);
                    }
                }
                catch (JsonReaderException e)
                {
                    throw new CommandException("Unable to parse output variables as valid JSON.");
                }
            }
        }
예제 #56
0
        public void NestedEvaluation()
        {
            var dictionary = new VariableDictionary();

            dictionary.Set("Database.Name", "Tester");
            dictionary.Set("Project.Name", "{Database.Name}");
            dictionary.Set("Project.Namespace", "{Database.Name}.Core");
            dictionary.Set("Entity.Namespace", "{Project.Namespace}.Data");

            var result = dictionary.Get("Entity.Namespace");

            result.Should().Be("Tester.Core.Data");
        }
예제 #57
0
        CalamariResult ExecuteCommand(VariableDictionary variables, string extensions = "")
        {
            using (var variablesFile = new TemporaryFile(Path.GetTempFileName()))
            {
                variables.Save(variablesFile.FilePath);

                return(Invoke(Calamari()
                              .Action("execute-manifest")
                              .Argument("variables", variablesFile.FilePath)
                              .Argument("sensitiveVariablesPassword", "GB8KdBqYRlgAON9ISUPdnQ==")
                              .Argument("extensions", extensions)));
            }
        }
예제 #58
0
        public void ShouldSubstitute()
        {
            var variables = new VariableDictionary();

            variables["ServerEndpoints[FOREXUAT01].Name"] = "forexuat01.local";
            variables["ServerEndpoints[FOREXUAT01].Port"] = "1566";
            variables["ServerEndpoints[FOREXUAT02].Name"] = "forexuat02.local";
            variables["ServerEndpoints[FOREXUAT02].Port"] = "1566";

            var text = PerformTest(GetFixtureResouce("Samples", "Servers.json"), variables).Text;

            Assert.That(Regex.Replace(text, "\\s+", ""), Is.EqualTo(@"{""Servers"":[{""Name"":""forexuat01.local"",""Port"":1566},{""Name"":""forexuat02.local"",""Port"":1566}]}"));
        }
            public void AddsVariables(string appSettingsKey, string configurationKey, string value)
            {
                VariableDictionary.Set(appSettingsKey, value);
                var appSettingsKeyDelimiter = string.Empty;
                var provider = new OctopusConfigurationProvider(Options, VariableDictionaryProvider.Object, appSettingsKeyDelimiter);

                provider.Load();

                string configurationValue;

                Assert.True(provider.TryGet(configurationKey, out configurationValue));
                Assert.Equal(value, configurationValue);
            }
        // The template and parameter files are relative paths, and may be located either inside or outside of the package.
        string ResolveAndSubstituteFile(string relativeFilePath, bool inPackage, VariableDictionary variables)
        {
            var absolutePath = inPackage
                ? Path.Combine(variables.Get(SpecialVariables.OriginalPackageDirectoryPath), variables.Evaluate(relativeFilePath))
                : Path.Combine(Environment.CurrentDirectory, relativeFilePath);

            if (!File.Exists(absolutePath))
            {
                throw new CommandException($"Could not resolve '{relativeFilePath}' to physical file");
            }

            return(variables.Evaluate(fileSystem.ReadFile(absolutePath)));
        }