how to include (i.e. execute) a file in psql but only if it exists? - psql

Sometimes for automated scripts/systems you need to be able to check if a file exists before attempting to execute it. psql doesn't have a native means for this, so I need a way to accomplish the same using native code.
I looked around for a solution to this and was surprised that I didn't find anything. Posting my solution here for anyone who might be able to use it in the future.

As a general template, this is a pretty compact way of doing it:
\if `[ -f "<file_path>" ] && echo 1 || echo 0`
-- file exists
\i <file_path>
\else
-- file doesn't exist
\endif
The "else" part is obviously optional.

Related

Detect Whether Script Was Imported or Executed in Lua

In python, there is a common construction of the form if __name__ == "__main__": to detect whether the file was imported or executed directly. Usually, the only action taken in this conditional is to execute some "sensible, top level" function. This allows the same file to be used as a basic script and as a library module (and also as something an interactive user can import and use).
I was wondering if there is a clean and reliable way to do this in lua. I thought I could use the _REQUIREDNAME global variable, but it turns out that this was changed in Lua 5.1. Currently, the lua require passes arguments (in the variadic ...), so in principle, these can be examined. However, this is either not reliable, not clean, or probably both, because obviously when a script is executed arguments can be passed. So to do this safely, you would have to examine the arguments.
FWIW, require passes the module name as argument 1 (the string you called require on), and the path to the file it eventually found as argument 2. So there is a obviously some examination that can be done to try to detect this, which if not nearly as nice as if __name__ == "__main__": and can always be bypassed by a user by passing two suitably constructed arguments to the script. Not exactly a security threat, but I would hope there is a better solution.
I also experimented with another method, which I found very ugly but promising. This was to use debug.traceack(). If the script is executed directly, the traceback is very predictable, in fact, it only has 3 lines. I thought this might be it, although, like I said, an ugly hack for sure.
Do any more frequent lua users have advice? In effect, if I am writing module X, I want to either return X.main_func() in script mode or return X in import mode.
EDIT:
I took out an item which was actually incorrect (and makes my traceback solution workable). Additionally, the link provided in the comment by Egor Skriptunoff did provide another trick from the debug library which is even cleaner than using the traceback. Other than that, it seems that everyone ran into the same issues as me and the lua team has been disinterested in providing an official means to support this.
Based on the links provided by Egor, the current cleanest and safest way to do this seems to be as outlined here:
How to determine whether my code is running in a lua module?
which I repeat for ease of reference:
if pcall(debug.getlocal, 4, 1) then
print("in package")
else
print("in main script")
end
There is a whole thread about it here:
http://lua.2524044.n2.nabble.com/Modules-with-standalone-main-program-td7681497.html
Like I said, it seems this is a popular feature which is going to remain unsupported for the time being, but the debug.getlocal method seems to be what common lua developers have settled on for now.
A require() returning in package.loaded.
So simply check package.loaded for what you want.
Also as a good start for more experience in that methodic i suggest to write package.preload functions for require() stuff without manipulating the path.
A simple example for showing this...
# /usr/local/bin/lua -i
Lua 5.4.3 Copyright (C) 1994-2021 Lua.org, PUC-Rio
> package.preload.mymod=function() return {dump=function(...)
>> local args={...}
>> local test,dump=pcall(assert,args[1])
>> if test then
>> for key,value in pairs(dump) do
>> io.write(string.format("%s=%s\n",key,value)):flush()
>> end
>> return true
>> else
>> return test,dump
>> end
>> end} end
> mymod=require('mymod')
> mymod.dump(package.loaded)
string=table: 0x56693590
mymod=table: 0x566aa890
utf8=table: 0x56694d80
package=table: 0x56691ed0
math=table: 0x56693cb0
table=table: 0x566920d0
_G=table: 0x56690730
debug=table: 0x566950e0
coroutine=table: 0x56692310
os=table: 0x56692e60
io=table: 0x566921b0
true

Oneliner to load Lua script from online (Gist) and run in current context

I have a lua REPL, and would like to run a lua script file stored as plain text at HTTPS://URL. I understand os.execute() can run OS commands so we can use curl etc. to grab the script then load(). Is that something possible to do in lua REPL with a single line?
Note: If you're going to run source code directly from the web, use https at least, to avoid easy MitM attacks.
To give this question an answer, since Egor will probably not post it as such:
(loadstring or load)(io.popen("wget -qO- https://i.imgur.com/91HtaFp.gif"):read"*a")()
For why this prints Hello world:
loadstring or load is to be compatible with different Lua versions, as the functions loadstring and load were merged at some point (5.2 I believe). io.popen executes its first argument in the shell and returns a file pointer to its stdout.
The "gif" from Egor is not really a GIF (open this in your browser: view-source:https://i.imgur.com/91HtaFp.gif) but a plain text file that contains this text:
GIF89a=GIF89a
print'Hello world'
Basically a GIF starts with GIF89a and the =GIF89a afterwards is just to produce valid Lua, meaning you don't have to use imgur or gifs, you can just as well use raw gists or github.
Now, it's rather unlikely that os.execute is available in a sandbox when io.popen is not, but if it is, you can achieve a one-liner (though drastically longer) using os.execute and temporary files
Lets first write this out because in a single line it will be a bit complex:
(function(u,f)
-- get a temp file name, Windows prefixes those with a \, so remove that
f=f or os.tmpname():gsub('^\\','')
-- run curl, make it output into our temp file
os.execute(('curl -s "%s" -o "%s"'):format(u,f))
-- load/run temp file
loadfile(f)()
os.remove(f)
end)("https://i.imgur.com/91HtaFp.gif");
And you can easily condense that into a single line by removing comments, tabs and newlines:
(function(u,f)f=f or os.tmpname():gsub('^\\','')os.execute(('curl -s "%s" -o "%s"'):format(u,f))loadfile(f)()os.remove(f)end)("https://i.imgur.com/91HtaFp.gif");

Is there a way to show custom warnings when building a project in XCode?

Let's say I want to detect something in my code which I cannot check by tests.
e.g.:
- Go over my entire code base to detect there I have a space between brackets and curly brackets (using a regex).
- Go over my entire code base and detect style smells.
etc...
If one of these checks fails, I'd like to show a custom warning I define myself.
Is there anything like this in XCode?
Thanks.
I wrote a run script for Xcode that does exactly what you requested. It searches by regex for predefined "code smells" or "style smells" and warns you at compile time
Read the blog post, but the final script is here
#test if git exists.
command -v git > /dev/null 2>$1 || {exit 0}
#separate code smells with | i.e. (code_smell_1|code_smell_2)
KEYWORDS="(didDeselectRowAtIndexPath)"
git diff --name-only HEAD | grep "\.m" | xargs egrep -s --with-filename --line-number --only-matching "$KEYWORDS.*[^\/]*$" | perl -p -e "s/($KEYWORDS)/ warning: Are you sure you want to use \$1?\nTo remove this warning, append a comment at the end of this line \$1/"
This particular script searches for appearances of didDeselectRowAtIndexPath in the code, but you can change that to any string
You would need to create a project target that runs a script, which searches through your source files and does your checks (this is not trivial) and returns non-zero to indicate error.
Then make your app target dependent on this "check target" and the build will fail if the check fails.
If you want some indication of how you write this "check script" then I would be inclined to employ the clang static analyzer. However, unfortunately, scan-build is not installed as part of the Xcode Command Line tools, so you would need to use the LLVM-binaries in some way, or perhaps the macports version contains it.
For trivial checks, relating to spaces and other stylistic issues rather than real, live, code problems, then you will have to employ some other mechanism, and I have no idea how to start with that, sorry.

Preventing multiple executions of a Lua script

I am writing a Lua script in Linux that can only have one instance running. To accomplish this in Bash I would use mkdir to create a lock file, and then return from the script immediately if the file exists; if no previous instance is running, allow the script to continue and remove the lock file once it completes.
Is there a way to atomically "check if a file exists or create it if it does not exist" in Lua? I cannot find any such functionality in the Lua documentation, but I'm new to the language. io.open("filename","w") does not look like it fulfills these requirements. If there is no native analog to mkdir, is there a better way to accomplish this type of script locking in Lua? Thanks!
Just transcribing the answer you ended up with:
if not os.execute("mkdir lockfile >/dev/null 2>&1") then
return
end
--do protected stuff
os.execute("rmdir lockfile")

Examples of getting it wrong first, on purpose

I just caught myself doing something I do a lot, and wanted to generalize it, express it, share it and see who else is following this general practice, to find some other example situations where it might be relevant.
The general practice is getting something wrong first, on purpose, to establish that everything else is right before undertaking the current task.
What I was trying to do, specifically, was to find examples in our code base where the dojo TextArea widget was used. I knew (because I had it in front of me - existence proof) that the TextBox widget was present in at least one file. So I looked first for what I knew was there:
grep -r digit.form.TextBox | grep -v
svn
This wasn't right - I had made a common (for me) mistake of leaving off the star, so I fixed that:
grep -r digit.form.TextBox * | grep
-v svn
which found no results! Quick comparison with the file I was looking at showed me I had misspelled "dijit":
grep -r dijit.form.TextBox * | grep
-v svn
And now I got results. Cool; doing it wrong first on purpose meant my query was correct except for looking for the wrong thing, so now I could construct the right query:
grep -r dijit.form.TextArea * | grep
-v svn
and be confident that when it gave me no results, it was because there are no such files, and not because I had malformed the query.
I'll add three other examples as answers; please add any others you're aware of.
TDD
The red-green-refactor cycle of test-driven development may be the archetype of this practice. With red, demonstrate that the functionality doesn't exist; then make it exist and demonstrate that you've done so by witnessing the green bar.
http://support.microsoft.com/kb/275085
This VBA routine turns off the "subdatasheets" property for every table in your MS Access database. The user is instructed to make sure error-handling is set to "Break only on unhandled errors." The routine identifies tables needing the fix by the error that is thrown. I'm not sure this precisely fits your question, but it's always interesting to me that the error is being used in a non-error way.
Here's an example from VBA:
I also use camel case when I Dim my variables. ThisIsAnExampleOfCamelCase. As soon as I exit the VBA code line if Access doesn't change the lower case variable to camel case then I know I've got a typo. [OR, Option Explicit isn't set, which is the post topic.]
I also use this trick, several times an hour at least.
arrange - assert - act - assert
I sometimes like, in my tests, to add a counter-assertion before the action to show that the action is actually responsible for producing the desired outcome demonstrated by the concluding assertion.
When in doubt of my spelling, and of my editor's spell-checking
We use many editors. Many of them highlight misspelled words as I type them - some do not. I rely on automatic spell checking, but I can't always remember whether the editor of the moment has that feature. So I'll enter, say, "circuitx" and hit space. If it highlights, I'll back up over the space and the "x" and type another space - and learn that I spelled circuit correctly - but if it doesn't, I'll copy the word and paste it into a known spell-checker to see whether I did.
I'm not sure it's the best way to act, as it does not prevent you from mispelling the final command, for example typing "TestArea" or something like that instead of "TextArea" (your finger just have to slip a little for such a mistake).
IMHO the best way is to run your "final" command, but on two sample files first : one containing the requested text, another that doesn't.
In other words, instead of running a "similar" command, run the real one, but over "similar" data.
(Not sure if this would be a good idea to try for real!)
For example, you might give the system to the users for testing and tell them the password to get started is "Apple".
You know the users are fully up and ready to test (everything is installed and connections to databases working) when they contact you and say the password doesn't work (it's actually "Orange").

Resources