core: split PATH on ; on Windows
[nit.git] / lib / core / environ.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2006 Floréal Morandat <morandat@lirmm.fr>
4 # Copyright 2008 Jean Privat <jean@pryen.org>
5 #
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
12 # another product.
13
14 # Access to the environment variables of the process
15 module environ
16
17 import text
18 import file
19
20 # TODO prevoir une structure pour recup tout un environ, le modifier et le passer a process
21
22 redef class String
23 # Return environment value for the symbol.
24 # If there is no such environment variable, then return ""
25 #
26 # assert "PATH".environ != ""
27 # assert "NIT %\n".environ == ""
28 fun environ: String
29 do
30 var res = self.to_cstring.get_environ
31 # FIXME: There is no proper way to handle NULL C string yet. What a pitty.
32 var nulstr = once ("".to_cstring.get_environ)
33 if res != nulstr then
34 return res.to_s
35 else
36 return ""
37 end
38 end
39
40 # Set the enviroment value of a variable.
41 #
42 # "NITis".setenv("fun")
43 # assert "NITis".environ == "fun"
44 fun setenv(v: String) do to_cstring.setenv( v.to_cstring )
45
46 # Search for the program `self` in all directories from `PATH`
47 fun program_is_in_path: Bool
48 do
49 var sep = if is_windows then ";" else ":"
50 var full_path = "PATH".environ
51 var paths = full_path.split(sep)
52 for path in paths do if path.file_exists then
53 if path.join_path(self).file_exists then return true
54 if is_windows and (path / self + ".exe").file_exists then return true
55 end
56
57 return false
58 end
59 end
60
61 redef class CString
62 private fun get_environ: CString `{ return getenv(self); `}
63 private fun setenv(value: CString) `{
64 #ifdef _WIN32
65 _putenv_s(self, value);
66 #else
67 setenv(self, value, 1);
68 #endif
69 `}
70 end
71
72 redef class Sys
73 redef init
74 do
75 var x = "NIT_SRAND".environ
76 if x != "" then srand_from(x.to_i)
77 end
78 end