Racket: How to retrieve the path of the running file? - path

I need a way to get the path of the running script (the directory that contains the source file), but
(current-directory)
never points there (in this case an external drive), but rather to some predefined location.
I created a file to try all the 'find-system-path's, but none of them are the running file! The Racket docs are not helping.
#lang web-server/insta
(define (start request)
(local [{define (build-ul items)
`(ul ,#(map itemize items))}
{define (itemize item)
`(li ,(some-system-path->string (find-system-path item)))}]
(response/xexpr
`(html
(head (title "Directories"))
(body (h1 ,"Some Paths")
(p ,(build-ul special-paths)))))))
(define special-paths (list 'home-dir
'pref-dir
'pref-file
'temp-dir
'init-dir
'init-file
;'links-file ; not available for Linux
'addon-dir
'doc-dir
'desk-dir
'sys-dir
'exec-file
'run-file
'collects-dir
'orig-dir))
The purpose is for a local web-server application (music server) that will modify sub-directories under the directory that contains the source file. I will be carrying the app on a USB stick, so it needs to be able to locate its own directory as I carry it between machines and operating systems with Racket installed.

Easy way: take the running script name, make it into a complete path,then take its directory:
(path-only (path->complete-path (find-system-path 'run-file)))
But you're more likely interested not in the file that was used to execute things (the web server), but in the actual source file that you're putting your code in. Ie, you want some resources to be close to your source. An older way of doing this is:
(require mzlib/etc)
(this-expression-source-directory)
A better way of doing this is to use `runtime-path', which is a way to define such resources:
(require racket/runtime-path)
(define-runtime-path my-picture "pic.png")
This is better since it also registers the path as something that your script depends on -- so if you were to package your code as an installer, for example, Racket would know to package up that png file too.
And finally, you can use it to point at a whole directory:
(define-runtime-path HERE ".")
... (build-path HERE "pic.png") ...

If you want the absolute path, then I think this should do it:
(build-path (find-system-path 'orig-dir)
(find-system-path 'run-file))

Related

Call $readmemh() on global path of file

I am currently calling $readmemh() from /< WORKSPACE>/< RUN_DIR> on file.txt.
Currently, the function only works for $readmemh(file.txt, memory), i.e., relative path of the file. How can I get it to work for $readmemh(/< WORKSPACE>/< RUN_DIR>/file.txt, memory), i.e., global path?
I have tried to prefix the global path with a '~' but that doesn't work, and just the raw global path also doesn't work.
You should be able to specify an absolute path to a file when you call $readmemh. This code works for me on different simulators:
module tb;
reg [1:0] memory [0:3];
initial begin
$readmemh("/tmp/verilog/file.txt", memory);
for (int i=0; i<4; i++) $display(memory[i]);
end
endmodule
The file /tmp/verilog/file.txt exists for me on my linux OS. I am running my simulation from a different directory from /tmp/verilog.
file.text contains:
0
1
2
3
I would not expect ~ to work since that is a character which has special meaning within a shell.
If you run your simulation as part of a script (which is a common practice), you could avoid the issue you are facing by either copying file.txt into the directory where you run the simulation or by linking to the file. This would be done prior to running the simulation command. In this case, you could then use the simple syntax:
$readmemh("file.txt", memory);

How to write Bazel rules that work with external repositories?

The Bazel Starlark API does strange things with files in external repositories. I have the following Starlark snippet:
print(ctx.genfiles_dir)
print(ctx.genfiles_dir.path)
print(output_filename)
ret = ctx.new_file(ctx.genfiles_dir, output_filename)
print(ret.path)
It is creating the following output:
DEBUG: build_defs.bzl:292:5: <derived root>
DEBUG: build_defs.bzl:293:5: bazel-out/k8-fastbuild/genfiles
DEBUG: build_defs.bzl:294:5: google/protobuf/descriptor.upb.c
DEBUG: build_defs.bzl:296:5: bazel-out/k8-fastbuild/genfiles/external/com_google_protobuf/google/protobuf/descriptor.upb.c
That extra external/com_google_protobuf comes seemingly out of nowhere, and it makes my rule fail:
I tell protoc to generate into ctx.genfiles_dir.path (which is bazel-out/k8-fastbuild/genfiles).
So protoc generates bazel-out/k8-fastbuild/genfiles/google/protobuf/descriptor.upb.c
Bazel fails because I didn't generate bazel-out/k8-fastbuild/genfiles/external/com_google_protobuf/google/protobuf/descriptor.upb.c
Likewise, when I try to call file.short_path on a source file from an external repository, I get a result like ../com_google_protobuf/google/protobuf/descriptor.proto. This seems quite unhelpful, so I just wrote some manual code to strip off the leading ../com_google_protobuf/.
Am I missing something? How can I write this rule in a way that doesn't feel like I'm fighting Bazel the whole time?
Am I missing something?
The basic problem, as you already realized, is that you have two path "namespaces" the one that protoc sees (i.e. import paths) and the one that bazel sees (i.e. the path you pass to declare_file().
2 things to note:
1) All paths declared with declare_file() get the path <bin dir>/<package path incl. workspace>/<path you passed to declare_file()>
2) All actions are executed from <bin dir> (unless output_to_genfils=True in which case this switches to <gen dir> as in your example.
Trying to solve the exact same problem you encountered, I resorted to stripping the known path from the output_file's path to determine which directory to pass as p:
# This code is run from the context of the external protobuf dependency
proto_path = "google/a/b.proto"
output_file = ctx.actions.declare_file(proto_path)
# output_file.path would be `<gen_dir>/external/protobuf/google/a/b.proto`
# Strip the known proto_path from output_file.path
protoc_prefix = output_file.path[:-len(proto_path)]
print(protoc_prefix) # Prints: <gen_dir>/external/protobuf
command = "{protoc} {proto_paths} {cpp_out} {plugin} {plugin_options} {proto_file}".format(
...
cpp_out = "--cpp_out=" + protoc_prefix,
...
)
Alternatives
You may also be able to construct the same path with ctx.bin_dir, ctx.label.workspace_name, ctx.label.package, and ctx.label.name.
Misc.
proto_library recently gained an attribute strip_import_prefix. When used, the above is not correct, as all dependent files are symlinked into a new directory from which they have the relative paths declared with strip_import_prefix.
The path format is:
<bin dir>/<repo>/<package>/_virtual_base/<label name>/<path `import`ed in .proto files>
i.e.
<bin dir>/external/protobuf/_virtual_base/b_proto/google/a/b.proto
Assuming you are building an external repo called protobuf, which contains a BUILD file at its root with a target named b_proto, which in turn, relies on a proto_library wrapping google/a/b.proto AND uses the strip_import_prefix attribute.

Fsx execution path

I have a c# .net library I am looking to use within FSI/FSX. As part of the initialization of the .net lib, by default it expects and references a custom config file (MyAppConfig.xml) which loads various things before it can be used. When using it in c# it gets copied to the bin folder and the app by default expects it to be there and references it there unless there is a specific entry in the app.config to tell it otherwise. (I should add that it does it all by convention rather than injecting a path + filename, as per NLog, say)
I have an f# source file in a console app which will execute this initialization find, but I can't quite work out how to achieve this with FSI/FSX.
So my program.fs looks simply like
open System
open myApp
module Program =
[<EntryPoint>]
let Main(args) =
myApp.Initialization.Load() // references MyAppConfig.xml
Console.WriteLine("do my stuff!")
Console.ReadLine() |> ignore
0
If I try and do the same in FSI or using FSX, I have
#r #"E:\...path to MyApp...\MyApp.dll"
#I #"E:\...path to MyAppConfig.xml ..."
Environment.CurrentDirectory <- #"E:\...path to MyAppConfig.xml ..."
myApp.Initialization.Load() |> ignore // fails ... can't find MyAppConfig.xml
//do my stuff
I suspect that I've not got the paths quite right.
I'd be grateful of a steer
EDIT:
So I've managed to attach a debugger to the c# lib and see where it is looking for the config file - turns out it is "c:\Program Files\Microsoft F#\v4.0\" ( System.AppDomain.CurrentDomain.BaseDirectory) which again shows I've not quite understood how to tell FSI/FSX to use a particular path. If I copy the config file (MyAppConfig.xml) to that location it works fine.
Many thx
S
I'm not sure of the implications, but one possiblity might be temporarily changing the app base:
let origAppBase = AppDomain.CurrentDomain.BaseDirectory
AppDomain.CurrentDomain.SetData("APPBASE", "path_to_MyAppConfig.xml")
myApp.Initialization.Load() |> ignore
AppDomain.CurrentDomain.SetData("APPBASE", origAppBase) //restore original app base

Why can't waf find a path that exists?

Let's say I have x.y file in /mydir/a/b (on Linux)
When I run waf, it does not find the file.
def configure(context):
pass
def build(build_context):
build_context(source='/mydir/a/b/x.y',
rule='echo ${SRC} > ${TGT}',
target='test.out')
Result: source not found: '/mydir/a/b/x.y' in bld(features=[], idx=1, meths=['process_rule', 'process_source'] ...
Ok, maybe you want a relative path, Waf? And you are not telling me?
def build(context):
path_str = '/mydir/a/b'
xy_node = context.path.find_dir(path_str)
if xy_node is None:
exit ("Error: Failed to find path {}".format(path_str))
# just refer to the current script
orig_path = context.path.find_resource('wscript')
rel_path = xy_node.path_from(orig_path)
print "Relative path: ", rel_path
Result: Error: Failed to find path /mydir/a/b
But that directory exists! What's up with that?
And, by the way, the relative path for some subdirectory (which it can find) is one off. e.g. a/b under current directory results in relative path "../a/b". I'd expect "a/b"
In general there are (at least) two node objects in each context:
- path: is pointing to the location of the wscript
- root: is pointing to the filesystem root
So in you case the solution is to use context.root:
def build(context):
print context.path.abspath()
print context.root.abspath()
print context.root.find_dir('/mydir/a/b')
Hmm, looks like I found an answer on the waf-users group forum, answered by Mr. Nagy himself:
The source files must be present under the top-level directory. You
may either:
create a symlink to the source directory
copy the external source files into the build directory (which may cause problem if there is a structure of folders to copy)
set top to a common folder such as '/' (may require superuse permissions, so it is a bad idea in general)
The recommendation in conclusion is to add a symlink to the outside directory during the configuration step. I wonder how that would work, if I need this on both, Linux and Windows...
Just pass the Node to the copy rule instead of passing the string representing the path:
def build(build_context):
source_node = build_context.root.find_node('/mydir/a/b/x.y')
build_context(source=source_node,
rule='echo ${SRC} > ${TGT}',
target='test.out')
Waf will be able to find the file even if outside of the top level directory.

Check Free Space in Windows NT 5.1 and newer platforms in NSIS

I am trying to use this script:
http://nsis.sourceforge.net/CheckSpaceFree
But it lacks some fundamental checks and adjustments ( comments ) for the case(s), where:
1) The $INSTDIR Path contains Program Files directory, which is Access protected, therefore, even if running setup with admin priviledges, you still get 0 integer return when, for example, your path ( absolute or relative ) lands on program files directory.
Failing Test path: C:\Program Files(x86)\BlaBlaBla\
Working test path: C:\BlaBlaBla
2) If I try to use relative path containing one level up (..\BlaBlaBla) AND point it to Disk root ( C:\ ), then path summerizes to C:\..\BlaBlaBla , resulting that nsis simply crashes.
Any best-pratice based way to gracefully work around these limitations?
Thank you all for any input!
Have you tried DriveSpace from the "useful headers" included with NSIS?

Resources