Exemplo n.º 1
0
        public void JsonSupportsVariableInVariable()
        {
            var variables = new VariableDictionary
            {
                ["Prop"] = "Foo",
                ["Val"]  = "Bar",
                ["Test"] = "{#{Prop}: \"#{Val}\"}",
            };

            variables.Evaluate("#{Test[Foo]}").Should().Be("Bar");
            variables.Evaluate("#{Test.Foo}").Should().Be("Bar");
            variables.Evaluate("#{Test[#{Prop}]}").Should().Be("Bar");
        }
Exemplo n.º 2
0
        public void IndexWithUnkownVariableDoesntFail()
        {
            var pattern = "#{Location[#{Continent}]}";

            var variables = new VariableDictionary();

            variables.Evaluate(pattern).Should().Be(pattern);

            variables.Set("Location[Europe]", "Madrid");
            variables.Evaluate(pattern).Should().Be(pattern);

            variables.Set("Continent", "Europe");
            variables.Evaluate(pattern).Should().Be("Madrid");
        }
Exemplo n.º 3
0
        public void JsonDoesNotOverrideExisting()
        {
            var variables = new VariableDictionary
            {
                ["Test.Hello"]       = "Go Away",
                ["Test"]             = "{\"Hello\": \"World\", \"Foo\": \"Bar\", \"Donkey\" : {\"Kong\": 12}}",
                ["Test[Foo]"]        = "Nope",
                ["Test.Donkey.Kong"] = "MARIO",
            };

            variables.Evaluate("#{Test.Hello}").Should().Be("Go Away");
            variables.Evaluate("#{Test[Foo]}").Should().Be("Nope");
            variables.Evaluate("#{Test.Donkey.Kong}").Should().Be("MARIO");
        }
Exemplo n.º 4
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);
 }
Exemplo n.º 5
0
        private static void ProcessFile(TomlTable toml)
        {
            string templateFile = Command.TemplateFile.Replace('\\', Path.DirectorySeparatorChar);
            string resultFile   = Command.ResultFile.Replace('\\', Path.DirectorySeparatorChar);

            if (!File.Exists(templateFile))
            {
                Console.WriteLine($"Error: File {templateFile} does not exist");
                Environment.Exit(1);
            }

            IList <Variable> vars = GetVariablesFromToml(toml, Command.Multifile, Command.ResultFile).ToList();
            Dictionary <string, Variable> lookup = vars.ToDictionary(x => x.Key);

            if (Command.Verbose)
            {
                LogVars(vars, Command.VariableFile, true);
            }

            string           template     = File.ReadAllText(templateFile);
            HashSet <string> templateVars = ParseTemplate(template, templateFile);

            if (Command.Verbose)
            {
                LogVars(GetVariablesFromLookup(templateVars, lookup), templateFile, true);
            }

            ProcessUnusedVarsWarningsAndErrors(vars, templateVars, templateFile, lookup);
            VariableDictionary octoVars = SubstituteVaultValues(templateFile, vars);

            File.WriteAllText(resultFile, octoVars.Evaluate(template));
        }
        private async Task <int> OnExecute()
        {
            var octoVariables = new VariableDictionary();

            var envVariables = Environment.GetEnvironmentVariables();

            foreach (var key in envVariables.Keys)
            {
                octoVariables.Add(key.ToString(), envVariables[key]?.ToString());
            }

            var content = await ReadInput(Input);

            var replaced = octoVariables.Evaluate(content, out var error);

            await WriteOutput(Output ?? Input, replaced);

            if (!string.IsNullOrEmpty(error))
            {
                Console.Error.WriteLine(error);
                return(1);
            }

            return(0);
        }
Exemplo n.º 7
0
        public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
        {
            var source = File.ReadAllText(sourceFile);

            var result = variables.Evaluate(source);
            File.WriteAllText(targetFile, result);
        }
Exemplo n.º 8
0
        public override void DoExecute(IGenerateDockerComposeFileContext input)
        {
            var variableDictionary = new VariableDictionary();

            variableDictionary.Set("Project.Name", input.ProjectInstance.Name);
            variableDictionary.Set("Project.Id", $"{input.ProjectInstance.Id:N}");
            variableDictionary.Set("Project.WorkingPath", Regex.Escape(input.WorkingPath));

            foreach (var(key, value) in input.ProjectInstance.VariableDictionary)
            {
                variableDictionary.Set(key, value);
            }

            foreach (var(key, value) in input.Project.VariableDictionary)
            {
                variableDictionary.Set(key, value);
            }

            var templateFilePath = Path.Combine(
                input.ProjectInstance.SourceCodeLocation,
                input.Project.DockerComposeTemplateFileName);

            var template = File.ReadAllText(templateFilePath);

            var dockerCompose = variableDictionary.Evaluate(template, out var error);

            if (!string.IsNullOrEmpty(error))
            {
                throw new FileGenerationFailed(error);
            }

            var environmentFileNamePath = Path.Combine(input.WorkingPath, "docker-compose.yml");

            File.WriteAllText(environmentFileNamePath, dockerCompose);
        }
Exemplo n.º 9
0
        public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
        {
            var source = File.ReadAllText(sourceFile);

            var result = variables.Evaluate(source);

            File.WriteAllText(targetFile, result);
        }
Exemplo n.º 10
0
        public void JsonInvalidDoesNotReplace()
        {
            var variables = new VariableDictionary
            {
                ["Test"] = "{Name: NoComma}",
            };

            variables.Evaluate("#{Test.Name}").Should().Be("#{Test.Name}");
        }
Exemplo n.º 11
0
        public void SuccessfulJsonParsing(string json, string pattern, string expectedResult, string testName)
        {
            var variables = new VariableDictionary
            {
                ["Test"] = json
            };

            variables.Evaluate(pattern).Should().Be(expectedResult);
        }
        string GetInitialExtractionDirectory(VariableDictionary variables)
        {
            var root = variables.Get(SpecialVariables.Tentacle.Agent.ApplicationDirectoryPath)
                       ?? variables.Evaluate("#{env:SystemDrive}\\Applications");

            root = AppendEnvironmentNameIfProvided(variables, root);
            fileSystem.EnsureDirectoryExists(root);
            fileSystem.EnsureDiskHasEnoughFreeSpace(root);
            return(root);
        }
Exemplo n.º 13
0
        public void JsonEvaluatesConditionalsWithEscapes()
        {
            var variables = new VariableDictionary
            {
                ["Foo"] = "test text"
            };

            var pattern = "{\"Bar\":\"#{if Foo == \\\"test text\\\"}Blaa#{/if}\"}";

            variables.Evaluate(pattern).Should().Be("{\"Bar\":\"Blaa\"}");
        }
Exemplo n.º 14
0
        public void JsonObjectSupportsIterator()
        {
            var variables = new VariableDictionary
            {
                ["Octopus.Sizes"] = "{\"Small\": \"11.5\",  Large: 15.21}",
            };

            var pattern = @"#{each size in Octopus.Sizes}#{size}:#{size.Value},#{/each}";

            variables.Evaluate(pattern).Should().Be("Small:11.5,Large:15.21,");
        }
Exemplo n.º 15
0
        public void JsonArraySafeguardedFromNullValues()
        {
            var variables = new VariableDictionary
            {
                ["Test"] = "{Blah: null}",
            };

            var pattern = "Before:#{each number in Test.Blah}#{number}#{/each}:After";

            variables.Evaluate(pattern).Should().Be("Before::After");
        }
Exemplo n.º 16
0
        public void JsonArraySupportsIterator()
        {
            var variables = new VariableDictionary
            {
                ["Test"] = "[2,3,5,8]",
            };

            var pattern = "#{each number in Test}#{number}#{if Octopus.Template.Each.Last == \"False\"}-#{/if}#{/each}";

            variables.Evaluate(pattern).Should().Be("2-3-5-8");
        }
Exemplo n.º 17
0
        public void NullJsonPropertyTreatedAsEmptyString()
        {
            var variables = new VariableDictionary
            {
                ["Foo"] = "{Bar: null}",
            };

            var pattern = @"Alpha#{Foo.Bar}bet";

            variables.Evaluate(pattern).Should().Be("Alphabet");
        }
Exemplo n.º 18
0
        public void JsonObjectSupportsIteratorWithInnerSelection()
        {
            var variables = new VariableDictionary
            {
                ["Octopus.Sizes"] = "{\"X-Large\": {\"Error\": \"Not Stocked\"}}",
            };

            var pattern = @"#{each size in Octopus.Sizes}#{size.Key} - #{size.Value.Error}#{/each}";

            variables.Evaluate(pattern).Should().Be("X-Large - Not Stocked");
        }
Exemplo n.º 19
0
        public void ShouldAddEnvironmentVariables()
        {
            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.Evaluate("My OS is #{env:OS}"), Is.StringStarting("My OS is Windows"));
            Assert.That(variables.GetRaw(SpecialVariables.Tentacle.Agent.InstanceName), Is.EqualTo("#{env:TentacleInstanceName}"));
        }
Exemplo n.º 20
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));
        }
Exemplo n.º 21
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}'");
        }
        // 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)));
        }
Exemplo n.º 23
0
        public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
        {
            var source = fileSystem.ReadFile(sourceFile);
            var encoding = GetEncoding(sourceFile, variables);

            string error;
            var result = variables.Evaluate(source, out error);

            if (!string.IsNullOrEmpty(error))
                Log.VerboseFormat("Parsing file '{0}' with Octostache returned the following error: `{1}`", sourceFile, error);

            fileSystem.OverwriteFile(targetFile, result, encoding);
        }
Exemplo n.º 24
0
        public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
        {
            var source   = fileSystem.ReadFile(sourceFile);
            var encoding = GetEncoding(sourceFile, variables);

            string error;
            var    result = variables.Evaluate(source, out error);

            if (!string.IsNullOrEmpty(error))
            {
                Log.VerboseFormat("Parsing file '{0}' with Octostache returned the following error: `{1}`", sourceFile, error);
            }

            fileSystem.OverwriteFile(targetFile, result, encoding);
        }
Exemplo n.º 25
0
        public void EncryptText()
        {
            var certificate = MakeCert();

            if (certificate != null)
            {
                var variableDictionary = new VariableDictionary
                {
                    //TODO: Verify this is how Octopus certificate variables create certificate base64 strings. #{CertificateVariable.Certificate}
                    ["CertificateBase64String"] = Convert.ToBase64String(certificate.RawData),
                    ["Data"]          = "Test",
                    ["EncryptedData"] = "#{Data | RSAEncrypt #{CertificateBase64String}}"
                };

                var encryptedString = variableDictionary.Evaluate("#{EncryptedData}");
                encryptedString.Should().NotBeNullOrWhiteSpace();
            }
        }
Exemplo n.º 26
0
        internal static ICollection <PrivateKeyAccessRule> GetPrivateKeyAccessRules(VariableDictionary variables)
        {
            // The private-key access-rules are stored as escaped JSON. However, they may contain nested
            // variables (for example the user-name may be an Octopus variable) which may not be escaped,
            // causing JSON parsing to fail.

            // So, we get the raw text
            var raw = variables.GetRaw(SpecialVariables.Action.Certificate.PrivateKeyAccessRules);

            if (string.IsNullOrWhiteSpace(raw))
            {
                return(new List <PrivateKeyAccessRule>());
            }

            // Unescape it (we only care about backslashes)
            var unescaped = raw.Replace(@"\\", @"\");
            // Perform variable-substitution and re-escape
            var escapedAndSubstituted = variables.Evaluate(unescaped).Replace(@"\", @"\\");

            return(PrivateKeyAccessRule.FromJson(escapedAndSubstituted));
        }
Exemplo n.º 27
0
        public void DocumentationIntroduction()
        {
            var variables = new VariableDictionary();

            variables.Set("Server", "Web01");
            variables.Set("Port", "10933");
            variables.Set("Url", "http://#{Server | ToLower}:#{Port}");
            variables.Set("Protocol", "#{Proto}");

            var url  = variables.Get("Url");
            var raw  = variables.GetRaw("Url");
            var eval = variables.Evaluate("#{Url}/foo");

            string error;

            variables.Get("Protocol", out error);

            Assert.AreEqual("http://web01:10933", url);
            Assert.AreEqual("http://#{Server | ToLower}:#{Port}", raw);
            Assert.AreEqual("http://web01:10933/foo", eval);
            Assert.IsNotNull(error);
        }
Exemplo n.º 28
0
        public void DocumentationIntroduction()
        {
            var variables = new VariableDictionary();

            variables.Set("Server", "Web01");
            variables.Set("Port", "10933");
            variables.Set("Url", "http://#{Server | ToLower}:#{Port}");
            variables.Set("Protocol", "#{Proto}");

            var url  = variables.Get("Url");
            var raw  = variables.GetRaw("Url");
            var eval = variables.Evaluate("#{Url}/foo");

            string error;

            variables.Get("Protocol", out error);

            url.Should().Be("http://web01:10933");
            raw.Should().Be("http://#{Server | ToLower}:#{Port}");
            eval.Should().Be("http://web01:10933/foo");
            error.Should().NotBeNull();
        }
 private void LinuxEnvironmentVariableTest(VariableDictionary variables)
 {
     Assert.That(variables.Evaluate("My home starts at #{env:HOME}"), Is.StringStarting("My home starts at /home"));
 }
 private void WindowsEnvironmentVariableTest(VariableDictionary variables)
 {
     Assert.That(variables.Evaluate("My OS is #{env:OS}"), Is.StringStarting("My OS is Windows"));
 }
Exemplo n.º 31
0
 private void WindowsEnvironmentVariableTest(VariableDictionary variables)
 {
     Assert.That(variables.Evaluate("My OS is #{env:OS}"), Is.StringStarting("My OS is Windows"));
 }
Exemplo n.º 32
0
 private void LinuxEnvironmentVariableTest(VariableDictionary variables)
 {
     Assert.That(variables.Evaluate("My home starts at #{env:HOME}"), Is.StringStarting("My home starts at /home"));
 }
Exemplo n.º 33
0
 public string ResolveAndSubstituteFile(ICalamariFileSystem fileSystem, string relativeFilePath, bool inPackage, VariableDictionary variables)
 {
     return(GetAbsolutePath(fileSystem, relativeFilePath, inPackage, variables)
            .Map(path => variables.Evaluate(fileSystem.ReadFile(path))));
 }
Exemplo n.º 34
0
        public Maybe <ResolvedTemplatePath> MaybeResolve(string relativeFilePath, bool inPackage, VariableDictionary variables)
        {
            var absolutePath = relativeFilePath.ToMaybe().Select(path => inPackage
                ? Path.Combine(variables.Get(SpecialVariables.OriginalPackageDirectoryPath), variables.Evaluate(path))
                : Path.Combine(Environment.CurrentDirectory, path));

            return(absolutePath.SelectValueOr(x =>
                                              !filesystem.FileExists(x) ? Maybe <ResolvedTemplatePath> .None : new ResolvedTemplatePath(x).AsSome(),
                                              Maybe <ResolvedTemplatePath> .None
                                              ));
        }