How do I conditionally declare variables in go templates? - go-templates

I am working on helmfile and stuck at the point where I want the conditional variable declaration. Roughly like this but in go standard templates.
ENV = "prod"
folder = ""
if ENV == "prod":
folder = "production"
elif ENV == "qa"
folder == "qa"
else
folder = "dev"
How can I achieve something like that?
Thanks

Use the {{if}} action and the eq template function to compare the ENV variable to certain values:
{{$ENV := "prod"}}
{{$folder := ""}}
{{if eq $ENV "prod"}}
{{$folder = "production"}}
{{else if eq $ENV "qa"}}
{{$folder = "qa"}}
{{else}}
{{$folder = "dev"}}
{{end}}
Note that this is not "conditional declaration". We declare $folder "unconditionally" and used {{if}} to change its value.
Here's a runnable demo to test the above template:
func main() {
t := template.Must(template.New("").Parse(src))
for _, env := range []string{"prod", "qa", "other"} {
if err := t.Execute(os.Stdout, env); err != nil {
panic(err)
}
}
}
const src = `{{$ENV := .}}
{{- $folder := "" -}}
{{- if eq $ENV "prod"}}
{{$folder = "production"}}
{{else if eq $ENV "qa"}}
{{- $folder = "qa" -}}
{{else}}
{{- $folder = "dev" -}}
{{end}}
$ENV = {{$ENV}}; $folder = {{$folder}}`
Output (try it on the Go Playground):
$ENV = prod; $folder = production
$ENV = qa; $folder = qa
$ENV = other; $folder = dev

If you do have the Sprig functions available to you (in both standard Helm and in Helmfile) then you can create a dict, then look up a value in it (probably using the standard index function) with a default.
{{ $ENV := ... }}
{{ $folders := dict "prod" "production" "qa" "qa" }}
{{ $folder := index $folders $ENV | default "dev" }}
Helmfile also has its own version of get that includes defaulting functionality; so in Helmfile specifically (but not in core Go text/template or the Sprig extensions, so not standard Helm) you can say
{{/* get "key" "default" (dict ...) */}}
{{ $folder := get $ENV "dev" $folders }}
Both of these in Python would look like:
folders = { "prod": "production", "qa": "qa" }
folder = folders.get(ENV, "dev")
which should be equivalent to your logic.

Related

dont work lappend in proc tcl

I want get list of included files in HDL designer with tcl script. I get example that printed list of files into a log and change it. I add global variable filenames and append all filenames to it, but when proc will be executes my variable is empty.
proc walkDependencies {decl} {
global alreadyDone filenames
# Only look at each declaration once.
if {[info exists alreadyDone($decl)]} {
return
}
set alreadyDone($decl) 1
# Only report each file once.
set declFile [$decl file]
if {[info exists alreadyDone($declFile)]} {
set reportFile 0
} else {
set reportFile 1
set alreadyDone($declFile) 1
}
foreach pkg [$decl packages] {
walkDependencies $pkg
}
if {[$decl configure class] eq "architecture"} {
walkDependencies [$decl entity]
foreach inst [$decl instances] {
if {![catch {$inst child} child]} {
walkDependencies $child
}
}
}
set file [$decl file]
set fileType [$file configure type]
if {![regexp {Text$} $fileType]} {
if {[lsearch {symbol blockInterface} $fileType] != -1} {
# This assumes ent+arch are generated to a single file.
set reportFile 0
} else {
set file [$file generated]
}
}
if {$reportFile} {
set lib [$file library]
# Exclude standard and downstreamOnly libraries.
if {[$lib configure type] eq "regular"} {
# puts "[$lib configure hardHdlDir]/[$file configure relativePathname]"
set tmp "[$lib configure hardHdlDir]/[$file configure relativePathname]"
lappend $filenames $tmp
}
}
if {[$decl configure class] eq "packageHeader"} {
walkDependencies [$decl body]
}
}
set filenames
catch {unset alreadyDone}
set lib [library open Travers_lib]
walkDependencies [$lib declaration Travers_top struct]
foreach i $filenames {
puts $i
}
if uncomment line # puts "[$lib configure hardHdlDir]/[$file configure relativePathname]" all included files will be printed into a log.
Your problem is most likely that you are using
lappend $filenames $tmp
which means that you are appending the value of tmp to a local variable whose name is equal to the value of filenames. Try
lappend filenames $tmp
instead.
Documentation:
lappend

Show product prices in Prestashop Wishlist Module

Currently the wishlist module in my Prestashop store only displays the product image and title. There are two wishlist views, the customer account view and the shared link view. I would like to display the price in both of these views. I've tried adding
$price = Product::getPriceStatic($productid);
to different parts of managewishlist.php and adding
<span id="our_price_display">{convertPrice price=$productPrice}</span>
to the managewishlist tpl file but nothing shows up. I'm running version 1.5.6.2.
EDIT: I also tried adding
{if !$priceDisplay || $priceDisplay == 2}
{assign var='productPrice' value=$product->getPrice(true, $smarty.const.NULL, $priceDisplayPrecision)}
{assign var='productPriceWithoutReduction' value=$product->getPriceWithoutReduct(false, $smarty.const.NULL)}
{elseif $priceDisplay == 1}
{assign var='productPrice' value=$product->getPrice(false, $smarty.const.NULL, $priceDisplayPrecision)}
{assign var='productPriceWithoutReduction' value=$product->getPriceWithoutReduct(true, $smarty.const.NULL)}
{/if}
to managewishlist.tpl but it made the wishlist disappear
Not sure about the actual files you need to edit but this should be right for PS 1.5.x
in blockwishlist/view.php add the commented line:
for ($i = 0; $i < sizeof($products); ++$i)
{
$obj = new Product($products[$i]['id_product'], false, $context->language->id);
if (!Validate::isLoadedObject($obj))
continue;
else
{
if ($products[$i]['id_product_attribute'] != 0 && isset($combination_imgs[$products[$i]['id_product_attribute']][0]))
{
$combination_imgs = $obj->getCombinationImages($context->language->id);
$products[$i]['cover'] = $obj->id.'-'.$combination_imgs[$products[$i]['id_product_attribute']][0]['id_image'];
}
else
{
$images = $obj->getImages($context->language->id);
foreach ($images AS $k => $image)
{
if ($image['cover'])
{
$products[$i]['cover'] = $obj->id.'-'.$image['id_image'];
break;
}
}
if (!isset($products[$i]['cover']))
$products[$i]['cover'] = $context->language->iso_code.'-default';
}
// ADD THIS LINE!
$products[$i]['price'] = Product::getPriceStatic($obj->id);
}
}
then in view.tpl (not sure if PS 1.5.x uses the /templates/view/ dir or not try both) you can just use {convertPrice price=$product.price} wherever you need.
Haven't actually tested this but it should give you a good starting point at least.
EDIT Also please be aware that that editing module files directly is not recommended. However, since there is no option to override modules in PS 1.5.x your only options are:
a) editing module directly - meaning it will break if / when you update said module
b) copying the module and renaming it - which is messy but imho preferable to the downside of a)

Perl6: How to find all installed modules whose filename matches a pattern?

Is it possible in Perl6 to find all installed modules whose file-name matches a pattern?
In Perl5 I would write it like this:
use File::Spec::Functions qw( catfile );
my %installed;
for my $dir ( #INC ) {
my $glob_pattern = catfile $dir, 'App', 'DBBrowser', 'DB', '*.pm';
map { $installed{$_}++ } glob $glob_pattern;
}
There is currently no way to get the original file name of an installed module. However it is possible to get the module names
sub list-installed {
my #curs = $*REPO.repo-chain.grep(*.?prefix.?e);
my #repo-dirs = #curs>>.prefix;
my #dist-dirs = |#repo-dirs.map(*.child('dist')).grep(*.e);
my #dist-files = |#dist-dirs.map(*.IO.dir.grep(*.IO.f).Slip);
my $dists := gather for #dist-files -> $file {
if try { Distribution.new( |%(from-json($file.IO.slurp)) ) } -> $dist {
my $cur = #curs.first: {.prefix eq $file.parent.parent}
take $_ for $dist.hash<provides>.keys;
}
}
}
.say for list-installed();
see: Zef::Client.list-installed()

issue accessing lexical scope using B

For debugging purposes I'd like to Access the lexical scope of different subroutines with a specific Attribute set. That works fine. I get a Problem when the first variable stores a string, then I get a empty string. I do something like this:
$pad = $cv->PADLIST; # $cv is the coderef to the sub
#scatchpad = $pad->ARRAY; # getting the scratchpad
#varnames = $scratchpad[0]->ARRAY; # getting the variablenames
#varcontents = $scratchpad[1]->ARRAY; # getting the Content from the vars
for (0 .. $#varnames) {
eval {
my $name = $varnames[$_]->PV;
my $content;
# following line matches numbers, works so far
$content = $varcontent[$_]->IVX if (scalar($varcontent[$_]) =~ /PVIV=/);
# should match strings, but does give me undef
$content = B::perlstring($varcontent[$_]->PV) if (scalar($varcontent[$_]) =~ /PV=/);
print "DEBUGGER> Local variable: ", $name, " = ", $content, "\n";
}; # there are Special vars that throw a error, but i don't care about them
}
Like I said in the comment the eval is to prevent the Errors from the B::Special objects in the scratchpad.
Output:
Local variable: $test = 42
Local variable: $text = 0
The first Output is okay, the second should Output "TEXT" instead of 0.
What am I doing wrong?
EDIT: With a little bit of coding I got all values of the variables , but not stored in the same indexes of #varnames and #varcontents. So now is the question how (in which order) the values are stored in #varcontents.
use strict;
use warnings;
use B;
sub testsub {
my $testvar1 = 42;
my $testvar2 = 21;
my $testvar3 = "testval3";
print "printtest1";
my $testvar4 = "testval4";
print "printtest2";
return "returnval";
}
no warnings "uninitialized";
my $coderef = \&testsub;
my $cv = B::svref_2object ( $coderef );
my $pad = $cv->PADLIST; # get scratchpad object
my #scratchpad = $pad->ARRAY;
my #varnames = $scratchpad[0]->ARRAY; # get varnames out of scratchpad
my #varcontents = $scratchpad[1]->ARRAY; # get content array out of scratchpad
my #vars; # array to store variable names adn "undef" for special objects (print-values, return-values, etc.)
for (0 .. $#varnames) {
eval { push #vars, $varnames[$_]->PV; };
if ($#) { push #vars, "undef"; }
}
my #cont; # array to store the content of the variables and special objects
for (0 .. $#varcontents) {
eval { push #cont, $varcontents[$_]->IV; };
eval { push #cont, $varcontents[$_]->PV; };
}
print $vars[$_], "\t\t\t", $cont[$_], "\n" for (0 .. $#cont);
EDIT2: Added runnable script to demonstrate the issue: Variablenames and variablevalues are not stored in the same index of the two Arrays (#varnames and #varcontents).

Check if file exists in 2 directories using ASP or PHP

I am looking for a way to compare 2 directories to see if a file exists in both. What I want to do is delete a file in 1 of the directories if it exists in both.
I can either use ASP or PHP.
Example:
/devices/1001
/devices/1002
/devices/1003
/devices/1004
/devices/1005
/disabled/1001
/disabled/1002
/disabled/1003
So since 1001, 1002, 1003 exist in /disabled/, I want to remove them from /devices/ and only be left with 1004, 1005 in /devices/.
Using scandir() to get an array of the file names in each directory, and then using array_intersect() to find elements of the first array that are present in any additional arguments given.
http://au.php.net/manual/en/function.scandir.php
http://au.php.net/manual/en/function.array-intersect.php
<?php
$devices = scandir('/i/auth/devices/');
$disabled = scandir('/i/auth/disabled/');
foreach(array_intersect($devices, $disabled) as $file) {
if ($file == '.' || $file == '..')
continue;
unlink('/i/auth/devices/'.$file);
}
Applied as a function including checking the directories are valid:
<?php
function removeDuplicateFiles($removeFrom, $compareTo) {
$removeFromDir = realpath($removeFrom);
if ($removeFromDir === false)
die("Invalid remove from directory: $removeFrom");
$compareToDir = realpath($compareTo);
if ($compareToDir === false)
die("Invalid compare to directory: $compareTo");
$devices = scandir($removeFromDir);
$disabled = scandir($compareToDir);
foreach(array_intersect($devices, $disabled) as $file) {
if ($file == '.' || $file == '..')
continue;
unlink($removeFromDir.DIRECTORY_SEPARATOR.$file);
}
}
removeDuplicateFiles('/i/auth/devices/', '/i/auth/disabled/');
It's very easy with PHP - in this example we set the two base directories and the filename... this could easily be an array in a foreach() loop. Then we check in both directories to see if it does indeed reside in each. If so, we delete from the first. This can be easily modified to delete from the second.
See below:
<?php
$filename = 'foo.html';
$dir1 = '/var/www/';
$dir2 = '/var/etc/';
if(file_exists($dir1 . $filename) && file_exists($dir2 . $filename)){
unlink($dir1 . $filename);
}
if ($handle = opendir('/disabled/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
unlink('/devices/' . $file);
}
}
closedir($handle);
}
In php, use this for checking if the file exists.... it will return true or false...
file_exists(relative file_path)
For each file in devices check to see if it exists in disabled using the disabled path and the file name from devices.
<%
Set fso = server.createobject("Scripting.FileSystemObject")
Set devices = fso.getfolder(server.mappath("/i/auth/devices/"))
Set disabledpath = server.mappath("/i/auth/disabled/")
For each devicesfile in devices.files
if directory.fileExists(disablepath & devicesfile.name ) Then
Response.Write " YES "
Response.write directoryfile.name & "<br>"
Else
Response.Write " NO "
Response.write directoryfile.name & "<br>"
End if
Next
%>