[fileio] get_absolute_file_path() with no input arg 25/21525/15
mottelet [Fri, 3 Jul 2020 11:20:00 +0000 (13:20 +0200)]
http://bugzilla.scilab.org/show_bug.cgi?id=13933

Change-Id: I2de7aa994a52fb16ad773d45402be289ed90acb4

21 files changed:
scilab/contrib/toolbox_skeleton/builder.sce
scilab/contrib/toolbox_skeleton/demos/toolbox_skeleton.dem.gateway.sce
scilab/contrib/toolbox_skeleton/help/builder_help.sce
scilab/contrib/toolbox_skeleton/help/cleaner_help.sce
scilab/contrib/toolbox_skeleton/help/en_US/build_help.sce
scilab/contrib/toolbox_skeleton/help/fr_FR/build_help.sce
scilab/contrib/toolbox_skeleton/macros/buildmacros.sce
scilab/contrib/toolbox_skeleton/macros/cleanmacros.sce
scilab/contrib/toolbox_skeleton/sci_gateway/builder_gateway.sce
scilab/contrib/toolbox_skeleton/sci_gateway/c/builder_gateway_c.sce
scilab/contrib/toolbox_skeleton/sci_gateway/cpp/builder_gateway_cpp.sce
scilab/contrib/toolbox_skeleton/sci_gateway/fortran/builder_gateway_fortran.sce
scilab/contrib/toolbox_skeleton/src/builder_src.sce
scilab/contrib/toolbox_skeleton/src/c/builder_c.sce
scilab/contrib/toolbox_skeleton/src/fortran/builder_fortran.sce
scilab/contrib/toolbox_skeleton/src/java/builder_java.sce
scilab/modules/fileio/help/en_US/path_filename/get_absolute_file_path.xml
scilab/modules/fileio/help/ru_RU/path_filename/get_absolute_file_path.xml
scilab/modules/fileio/sci_gateway/cpp/fileio_gw.vcxproj
scilab/modules/fileio/sci_gateway/cpp/sci_get_absolute_file_path.cpp
scilab/modules/fileio/tests/unit_tests/get_absolute_file_path.tst

index f818934..6748a36 100644 (file)
@@ -9,7 +9,7 @@ lines(0);
 function main_builder()
     TOOLBOX_NAME  = "toolbox_skeleton";
     TOOLBOX_TITLE = "Toolbox Skeleton";
-    toolbox_dir   = get_absolute_file_path("builder.sce");
+    toolbox_dir   = get_absolute_file_path();
 
     // Check Scilab's version
     // =============================================================================
index 09d6bf6..75f9f84 100644 (file)
@@ -2,7 +2,7 @@
 // This file is released under the 3-clause BSD license. See COPYING-BSD.
 
 function subdemolist = demo_gateway()
-    demopath = get_absolute_file_path("toolbox_skeleton.dem.gateway.sce");
+    demopath = get_absolute_file_path();
 
     subdemolist = ["sum with Scilab"             ,"scilab_sum.dem.sce"; ..
     "A c sum "                    ,"c_sum.dem.sce"     ; ..
index 8f93d27..2e19328 100644 (file)
@@ -1,6 +1,6 @@
 // This file is released under the 3-clause BSD license. See COPYING-BSD.
 
-here = get_absolute_file_path("builder_help.sce");
+here = get_absolute_file_path();
 d = dir(here);
 d = d.name(d.isdir);
 la_LA = d(grep(d, "/[a-z]{2}_[A-Z]{2}/", "r"));  // filtering out ./images/ ./mml/, ...
index a2b5e7e..6061eb4 100644 (file)
@@ -1,7 +1,7 @@
 // This file is released under the 3-clause BSD license. See COPYING-BSD.
 
 function cleaner_help()
-    path = get_absolute_file_path("cleaner_help.sce");
+    path = get_absolute_file_path();
     langdirs = dir(path);
     langdirs = langdirs.name(langdirs.isdir);
 
index 7065316..a042bbd 100644 (file)
@@ -1,3 +1,3 @@
 // This file is released under the 3-clause BSD license. See COPYING-BSD.
 
-tbx_build_help(TOOLBOX_TITLE,get_absolute_file_path("build_help.sce"));
+tbx_build_help(TOOLBOX_TITLE,get_absolute_file_path());
index 7065316..a042bbd 100644 (file)
@@ -1,3 +1,3 @@
 // This file is released under the 3-clause BSD license. See COPYING-BSD.
 
-tbx_build_help(TOOLBOX_TITLE,get_absolute_file_path("build_help.sce"));
+tbx_build_help(TOOLBOX_TITLE,get_absolute_file_path());
index 5a872bb..e7ba8f6 100644 (file)
@@ -1,7 +1,7 @@
 // This file is released under the 3-clause BSD license. See COPYING-BSD.
 
 function buildmacros()
-    macros_path = get_absolute_file_path("buildmacros.sce");
+    macros_path = get_absolute_file_path();
     tbx_build_macros(TOOLBOX_NAME, macros_path);
 endfunction
 
index a6428b2..fb3cf8c 100644 (file)
@@ -3,7 +3,7 @@
 // ====================================================================
 function cleanmacros()
 
-    libpath = get_absolute_file_path("cleanmacros.sce");
+    libpath = get_absolute_file_path();
 
     binfiles = ls(libpath+"/*.bin");
     for i = 1:size(binfiles,"*")
index 0db1558..a8a672c 100644 (file)
@@ -2,7 +2,7 @@
 
 function builder_gateway()
 
-    sci_gateway_dir = get_absolute_file_path("builder_gateway.sce");
+    sci_gateway_dir = get_absolute_file_path();
     languages       = ["c" "fortran" "cpp"];
 
     tbx_builder_gateway_lang(languages,sci_gateway_dir);
index 55b8a83..b1fd568 100644 (file)
@@ -2,7 +2,7 @@
 
 function builder_gw_c()
 
-    includes_src_c = ilib_include_flag(get_absolute_file_path("builder_gateway_c.sce") + "../../src/c");
+    includes_src_c = ilib_include_flag(get_absolute_file_path() + "../../src/c");
 
     // PutLhsVar managed by user in sci_sum and in sci_sub
     // if you do not this variable, PutLhsVar is added
index b27d887..8233fd6 100644 (file)
@@ -2,7 +2,7 @@
 
 function builder_gw_cpp()
 
-    includes_src_c = ilib_include_flag(get_absolute_file_path("builder_gateway_cpp.sce") + "../../src/c");
+    includes_src_c = ilib_include_flag(get_absolute_file_path() + "../../src/c");
 
     //adapt to compiler capabilities
     l = ilib_language();
index 478320e..9b78cd8 100644 (file)
@@ -5,7 +5,7 @@ function builder_gw_fortran()
     tbx_build_gateway("skeleton_fortran", ..
     ["fortran_sum","sci_fsum"], ..
     ["sci_fsum.c"], ..
-    get_absolute_file_path("builder_gateway_fortran.sce"), ..
+    get_absolute_file_path(), ..
     ["../../src/fortran/libfsum"]);
 
 endfunction
index db7ff7f..7f0c180 100644 (file)
@@ -2,7 +2,7 @@
 
 function builder_src()
     langage_src = ["fortran" "c" "java"];
-    path_src = get_absolute_file_path("builder_src.sce");
+    path_src = get_absolute_file_path();
     tbx_builder_src_lang(langage_src, path_src);
 endfunction
 
index e1bb2ea..50429f2 100644 (file)
@@ -4,7 +4,7 @@
 
 function builder_c()
 
-    src_c_path = get_absolute_file_path("builder_c.sce");
+    src_c_path = get_absolute_file_path();
 
     CFLAGS = ilib_include_flag(src_c_path);
 
index 6bc3285..f1f4216 100644 (file)
@@ -5,7 +5,7 @@ function builder_fortran()
     tbx_build_src(["fsum"],   ..
     ["fsum.f"], ..
     "f",        ..
-    get_absolute_file_path("builder_fortran.sce"));
+    get_absolute_file_path());
 
 endfunction
 
index f089090..a1c7367 100644 (file)
@@ -3,7 +3,7 @@
 // This macro compiles JAR from Java files
 
 function builder_java()
-    src_java_dir = get_absolute_file_path("builder_java.sce");
+    src_java_dir = get_absolute_file_path();
 
     curdir = pwd();
     cd(src_java_dir);
index f9cbc93..418c32a 100644 (file)
@@ -4,6 +4,7 @@
  * Copyright (C) XXXX-2008 - INRIA
  *
  * Copyright (C) 2012 - 2016 - Scilab Enterprises
+ * Copyright (C) 2020 - Stephane MOTTELET
  *
  * This file is hereby licensed under the terms of the GNU GPL v2.0,
  * pursuant to article 5.3.4 of the CeCILL v.2.1.
@@ -22,7 +23,8 @@
     </refnamediv>
     <refsynopsisdiv>
         <title>Syntax</title>
-        <synopsis>pathname = get_absolute_file_path(filename)</synopsis>
+        <synopsis>[filepath, filename] = get_absolute_file_path()</synopsis>
+        <synopsis>filepath = get_absolute_file_path(filename)</synopsis>
     </refsynopsisdiv>
     <refsection>
         <title>Arguments</title>
             <varlistentry>
                 <term>filename</term>
                 <listitem>
-                    <para>a character string: filename.</para>
+                    <para>a character string: name of the file.</para>
                 </listitem>
             </varlistentry>
             <varlistentry>
-                <term>pathname</term>
+                <term>filepath</term>
                 <listitem>
-                    <para>a character string: an absolute pathname.</para>
+                    <para>a character string: an absolute path.</para>
                 </listitem>
             </varlistentry>
         </variablelist>
     <refsection>
         <title>Description</title>
         <para>
-            <function>get_absolute_file_path</function> gives an absolute pathname
-            of a file already opened in Scilab.
-        </para>
-        <para>
-            <function>get_absolute_file_path</function> searches in Scilab's
-            internal list of files currently opened <varname>filename</varname>
+            <function>get_absolute_file_path(filename)</function> searches in Scilab's
+            internal list of currently opened files the file with name <varname>filename</varname>
             and returns its path <varname>pathname</varname>.
         </para>
-        <para>If file is not opened, it will return an error.</para>
+       <para>If file is not opened, it will return an error.</para>
+      <para>Without input arguments and called from a script, <function>get_absolute_file_path()</function>
+        returns the absolute path of the script and optionally its name. When called without input arguments
+        from the command line <function>get_absolute_file_path()</function> returns an error.
+      </para>
         <para>
             <warning>
                 In previous version (Scilab 5.0.x) current directory was
                 returned if file was not found.
             </warning>
         </para>
-        <para>This function can be used to find from where (path) is executed a
-            Scilab script.
-        </para>
     </refsection>
     <refsection>
         <title>Examples</title>
         <programlisting role="example"><![CDATA[
-// exec this script
-
-a=mopen(TMPDIR+'test.sce','wt');
-disp(get_absolute_file_path('test.sce'));
-mclose(a);
+mputl(['[filepath,filename]=get_absolute_file_path()'
+       'disp(filepath,filename)'],TMPDIR+'/script.sce');
+exec(TMPDIR+'/script.sce',-1)
  ]]></programlisting>
+        <programlisting role="example"><![CDATA[
+fd = mopen(TMPDIR+'/foo.txt','wt');
+filepath = get_absolute_file_path("foo.txt")
+mclose(fd)
+filepath = get_absolute_file_path("foo.txt")
+]]></programlisting>
     </refsection>
     <refsection role="see also">
         <title>See also</title>
index 0b4b4fd..e6fb5f2 100644 (file)
@@ -4,6 +4,7 @@
  * Copyright (C) XXXX-2008 - INRIA
  *
  * Copyright (C) 2012 - 2016 - Scilab Enterprises
+ * Copyright (C) 2020 - Stephane MOTTELET
  *
  * This file is hereby licensed under the terms of the GNU GPL v2.0,
  * pursuant to article 5.3.4 of the CeCILL v.2.1.
     <refnamediv>
         <refname>get_absolute_file_path</refname>
         <refpurpose>
-            даёт имя абсолютного пути к файлу, открытому в Scilab'е
+            даёт абсолютный путь к файлу, открытому в Scilab
         </refpurpose>
     </refnamediv>
     <refsynopsisdiv>
         <title>Синтаксис</title>
-        <synopsis>pathname = get_absolute_file_path(filename)</synopsis>
+        <synopsis>[filepath, filename] = get_absolute_file_path()</synopsis>
+        <synopsis>filepath = get_absolute_file_path(filename)</synopsis>
     </refsynopsisdiv>
     <refsection>
         <title>Аргументы</title>
@@ -34,9 +36,9 @@
                 </listitem>
             </varlistentry>
             <varlistentry>
-                <term>pathname</term>
+                <term>filepath</term>
                 <listitem>
-                    <para>символьная строка: имя абсолютного пути.</para>
+                    <para>символьная строка: абсолютный путь.</para>
                 </listitem>
             </varlistentry>
         </variablelist>
     <refsection>
         <title>Описание</title>
         <para>
-            <function>get_absolute_file_path</function> даёт имя абсолютного пути к файлу <varname>filename</varname>, который уже открыт в Scilab'е.
+            <function>get_absolute_file_path</function> даёт абсолютный путь к
+            файлу уже открытому в Scilab.
         </para>
         <para>
-            <function>get_absolute_file_path</function> ищет во внутреннем списке
-            файлов Scilab'а открытый в данный момент файл <varname>filename</varname>
-            и возвращает его путь <varname>pathname</varname>.
+            <function>get_absolute_file_path(filename)</function> ищет
+            <varname>filename</varname>во внутреннем списке файлов, открытых в
+            данный момент и возвращает его путь <varname>pathname</varname>.
         </para>
-        <para>Если файл не открыт, то будет возвращена ошибка.</para>
         <para>
-            <warning>
-                В предыдущих версиях (Scilab 5.0.x) возвращалась текущая директория, если файл не был найден.
-            </warning>
+            Если файл не открыт, то будет возвращена ошибка.
         </para>
+      <para>
+          Без входных аргументов и при вызове из сценария
+          <function>get_absolute_file_path()</function> возвращает абсолютный путь
+          сценария и, по выбору, его имя. При вызове без входных аргументов из
+          командной строки <function>get_absolute_file_path()</function> возвращает
+          ошибку.
+      </para>
         <para>
-            Эта функция может быть использована для определения того, откуда (путь) исполняется сценарий Scilab'а.
+            <warning>
+                В прежней версии (Scilab 5.0.x), если файл не был найден,
+                возвращалась текущая директория.
+            </warning>
         </para>
     </refsection>
     <refsection>
         <title>Примеры</title>
         <programlisting role="example"><![CDATA[
-// Выполните следующий сценарий
-
-a=mopen(TMPDIR+'test.sce','wt');
-disp(get_absolute_file_path('test.sce'));
-mclose(a);
+mputl(['[filepath,filename]=get_absolute_file_path()'
+       'disp(filepath,filename)'],TMPDIR+'/script.sce');
+exec(TMPDIR+'/script.sce',-1)
  ]]></programlisting>
+        <programlisting role="example"><![CDATA[
+fd = mopen(TMPDIR+'/foo.txt','wt');
+filepath = get_absolute_file_path("foo.txt")
+mclose(fd)
+filepath = get_absolute_file_path("foo.txt")
+]]></programlisting>
     </refsection>
     <refsection role="see also">
         <title>Смотрите также</title>
@@ -92,4 +106,3 @@ mclose(a);
         </simplelist>
     </refsection>
 </refentry>
-
index 190cdb2..e23fadc 100644 (file)
@@ -88,7 +88,8 @@
       <PrecompiledHeader>
       </PrecompiledHeader>
       <WarningLevel>Level3</WarningLevel>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <LanguageStandard>stdcpp17</LanguageStandard>
     </ClCompile>
     <Link>
       <OutputFile>$(SolutionDir)bin\$(ProjectName).dll</OutputFile>
       </PrecompiledHeader>
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <LanguageStandard>stdcpp17</LanguageStandard>
     </ClCompile>
     <Link>
       <OutputFile>$(SolutionDir)bin\$(ProjectName).dll</OutputFile>
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
+      <LanguageStandard>stdcpp17</LanguageStandard>
     </ClCompile>
     <Link>
       <OutputFile>$(SolutionDir)bin\$(ProjectName).dll</OutputFile>
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
+      <LanguageStandard>stdcpp17</LanguageStandard>
     </ClCompile>
     <Link>
       <OutputFile>$(SolutionDir)bin\$(ProjectName).dll</OutputFile>
index 1999111..3a349d6 100644 (file)
@@ -1,9 +1,8 @@
 /*
  * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
  * Copyright (C) 2011 - Digiteo - Cedric DELAMARRE
- *
- *
  * Copyright (C) 2012 - 2016 - Scilab Enterprises
+ * Copyright (C) 2020 - Stéphane MOTTELET
  *
  * This file is hereby licensed under the terms of the GNU GPL v2.0,
  * pursuant to article 5.3.4 of the CeCILL v.2.1.
@@ -19,6 +18,8 @@
 #include "function.hxx"
 #include "string.hxx"
 #include "filemanager.hxx"
+#include "configvariable.hxx"
+#include <filesystem>
 
 extern "C"
 {
@@ -38,12 +39,50 @@ types::Function::ReturnValue sci_get_absolute_file_path(types::typed_list &in, i
     wchar_t* wcsTemp = NULL;
     wchar_t* wcsPath = NULL;
 
-    if (in.size() != 1)
+    if (in.size() > 1)
     {
-        Scierror(77, _("%s: Wrong number of input argument(s): %d expected.\n"), "get_absolute_file_path", 1);
+        Scierror(77, _("%s: Wrong number of input argument(s): at most %d expected.\n"), "get_absolute_file_path", 1);
         return types::Function::Error;
     }
 
+    if (in.size() == 0)
+    {
+        if (_iRetCount > 2)
+        {
+            Scierror(77, _("%s: Wrong number of output argument(s): at most %d expected.\n"), "get_absolute_file_path", 2);
+            return types::Function::Error;
+        }
+
+        const std::vector<ConfigVariable::WhereEntry>& where = ConfigVariable::getWhere();
+
+        for (auto it = where.rbegin(); it != where.rend(); ++it)
+        {
+            if (it->m_file_name != NULL && it->m_file_name->length() > 0)
+            {
+                std::filesystem::path p = std::filesystem::path(it->m_file_name->c_str());
+                std::filesystem::path filepath = p.parent_path() / "";
+                out.push_back(new types::String(filepath.c_str()));
+                if (_iRetCount == 2)
+                {
+                    out.push_back(new types::String(p.filename().c_str()));
+                }
+                // taking only the more recently pushed filename allows
+                // to cope with nested script execution.
+                break;
+            }
+        }
+
+        if (out.size() > 0)
+        {
+            return types::Function::OK;
+        }
+        else
+        {
+            Scierror(999, _("%s: Without arguments, this function must be called from a script.\n"), "get_absolute_file_path");
+            return types::Function::Error;
+        }
+    }
+
     if (in[0]->isString() == false || in[0]->getAs<types::String>()->isScalar() == false)
     {
         Scierror(999, _("%s: Wrong type for input argument #%d: A String expected.\n"), "get_absolute_file_path", 1);
index 1d7ff74..6f0a64a 100644 (file)
@@ -1,17 +1,16 @@
 // =============================================================================
 // Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
 // Copyright (C) 2008 - DIGITEO - Allan CORNET
+// Copyright (C) 2020 - Stéphane MOTTELET
 //
 //  This file is distributed under the same license as the Scilab package.
 // =============================================================================
 
 // <-- CLI SHELL MODE -->
+// <-- NO CHECK REF -->
 
-ierr = execstr("get_absolute_file_path();","errcatch");
-if ierr <> 77 then pause,end
-
-ierr = execstr("get_absolute_file_path(''test.sce'',''test.sce'');","errcatch");
-if ierr <> 77 then pause,end
+mess = msprintf(_("%s: Wrong number of input argument(s): at most %d expected.\n"),"get_absolute_file_path",1)
+assert_checkerror("get_absolute_file_path(''test.sce'',''test.sce'')",mess);
 
 current_dir = pwd()+ filesep();
 
@@ -19,8 +18,44 @@ a = mopen(TMPDIR+'/test.sce','wt');
 // get_absolute_file_path since 5.1.1 returns path with path separator @ the end
 d1 = get_absolute_file_path('test.sce');
 mclose(a);
-if d1 <> TMPDIR + filesep() then pause,end
+assert_checkequal(d1,TMPDIR + filesep());
 
 // file 'test.sce' closed then not found
-ierr = execstr('d3 = get_absolute_file_path(''test.sce'');','errcatch');
-if ierr <> 999 then pause,end
+mess = msprintf(_("%s: The file %s is not opened in scilab.\n"),"get_absolute_file_path","test.sce");
+assert_checkerror("get_absolute_file_path(''test.sce'')",mess);
+
+// one input arg form, within new script
+mputl("filepath = get_absolute_file_path(""script1.sce"")",TMPDIR+'/script1.sce');
+exec(TMPDIR+'/script1.sce');
+assert_checkequal(filepath,TMPDIR + filesep());
+
+// one input arg form, within a function in a new script
+mputl(["function fp = test()"
+       "fp = get_absolute_file_path(""script2.sce"")"
+       "end"
+       "filepath = test()"],TMPDIR+'/script2.sce');
+exec(TMPDIR+'/script2.sce');
+assert_checkequal(filepath,TMPDIR + filesep());
+
+// no input arg form, within new script
+mputl("[filepath,filename] = get_absolute_file_path()",TMPDIR+'/script3.sce');
+exec(TMPDIR+'/script3.sce');
+assert_checkequal(filepath,TMPDIR + filesep());
+assert_checkequal(filename,"script3.sce");
+
+// no input arg form, within a function in a new script
+mputl(["function [fp,fn] = test()"
+       "[fp,fn] = get_absolute_file_path()"
+       "end"
+       "[filepath,filename] = test()"],TMPDIR+'/script4.sce');
+exec(TMPDIR+'/script4.sce');
+assert_checkequal(filepath,TMPDIR + filesep());
+assert_checkequal(filename,"script4.sce");
+
+// no input arg form, within current script
+// filepath is TMPDIR of scilab instance calling the test
+[filepath1,filename] = get_absolute_file_path();
+[filepath2] = get_absolute_file_path("get_absolute_file_path.tst");
+assert_checkequal(filename,"get_absolute_file_path.tst");
+assert_checkequal(filepath1,filepath2);
+