Salome HOME
[FORUM 505] prepare command fix on windows
[tools/sat.git] / src / system.py
index 553aab9100c0ba2d063a9ebabdcbd10531f87c85..7b8d1492bbbb3082f4c9b0eb04b5c7ef74401c0a 100644 (file)
@@ -25,7 +25,6 @@ import os
 import subprocess as SP
 import time
 import tarfile
-import psutil
 import time
  
 
@@ -54,7 +53,7 @@ def show_in_editor(editor, filePath, logger):
         logger.write('Launched command:\n' + cmd + '\n', 5)
         p = SP.Popen(cmd, shell=True)
         p.communicate()
-    except:
+    except Exception:
         logger.write(printcolors.printcError(_("Unable to edit file %s\n") 
                                              % filePath), 1)
 
@@ -65,6 +64,7 @@ def show_in_webbrowser(editor, filePath, logger):
     :param editor str: The web browser to use.
     :param filePath str: The path to the file to open.
     '''
+    import psutil
     # default editor is firefox
     if editor is None or len(editor) == 0:
         editor = 'firefox'
@@ -72,22 +72,21 @@ def show_in_webbrowser(editor, filePath, logger):
     path, namefile = os.path.split(filePath)
     basefile, ext = os.path.splitext(namefile)
 
-    # previouly http.server 8765 kill ... or not ? TODO wait and see REX
+    # previouly http.server 8765/6/7... kill ... or not ? TODO wait and see REX
+    port = os.getenv('SAT_PORT_LOG', '8765')
     for proc in psutil.process_iter():
       # help(proc)
       cmdline = " ".join(proc.cmdline())
-      if "python3 -m http.server 8765" in cmdline:
+      if "python3 -m http.server %s" % port in cmdline:
         print("kill previous process '%s'" % cmdline)
-        proc.kill()  # TODO may be not owner ? -> change 8765+n
+        proc.kill()  # TODO may be not owner ? -> change 8766/7/8... as SAT_PORT_LOG
         
-    # The argument -u will make it so that stdout and stderr are not buffered 
-    # and will be written in real time.
     cmd = """
 set -x
 cd %(path)s
-python3 -m http.server 8765 &> /dev/null &
-%(editor)s http://localhost:8765/%(namefile)s
-""" % {"path": path, "editor": editor, "namefile": namefile}
+python3 -m http.server %(port)s &> /dev/null &
+%(editor)s http://localhost:%(port)s/%(namefile)s
+""" % {"path": path, "editor": editor, "namefile": namefile, 'port': port}
 
     # print("show_in_webbrowser:\n%s" % cmd)
     
@@ -95,7 +94,7 @@ python3 -m http.server 8765 &> /dev/null &
         # launch cmd using subprocess.Popen
         logger.write('Launched command:\n%s\n' % cmd, 5)
         p = SP.Popen(cmd, shell=True, stdout=SP.PIPE, stderr=SP.STDOUT)
-        res_out, res_err = p.communicate() # res_err = None as stderr=SP.STDOUT
+        res_out, _ = p.communicate()   # _ = None as stderr=SP.STDOUT
         # print("Launched command stdout:\n%s" % res_out)
     except Exception as e:
         logger.write(printcolors.printcError(_("Unable to display file %s\n%s\n") 
@@ -121,7 +120,7 @@ def git_describe(repo_path):
 
 def git_extract(from_what, tag, git_options, where, logger, environment=None):
   '''Extracts sources from a git repository.
-
+87
   :param from_what str: The remote git repository.
   :param tag str: The tag.
   :param git_options str: git options
@@ -153,7 +152,7 @@ exit $res
     # NOTICE: this command only works with recent version of git
     #         because --work-tree does not work with an absolute path
     if src.architecture.is_windows():
-      cmd = "rm -rf %(where)s && git clone %(git_options)s %(remote)s %(where)s && git --git-dir=%(where_git)s --work-tree=%(where)s checkout %(tag)s"
+      cmd = "rmdir /S /Q %(where)s && git clone %(git_options)s %(remote)s %(where)s && git --git-dir=%(where_git)s --work-tree=%(where)s checkout %(tag)s"
     else:
 # for sat compile --update : changes the date of directory, only for branches, not tag
       cmd = r"""
@@ -245,13 +244,13 @@ rm -rf $tmpDir
     cmd = r"""
 
 set tmpDir=%(tmpWhere)s && \
-rm -rf $tmpDir
-git clone %(git_options)s %(remote)s $tmpDir && \
-cd $tmpDir && \
+rmdir /S /Q %tmpDir%
+git clone %(git_options)s %(remote)s %tmpDir% && \
+cd %tmpDir% && \
 git checkout %(tag)s && \
 mv %(sub_dir)s %(where)s && \
-git log -1 > %(where)s/README_git_log.txt && \
-rm -rf $tmpDir
+git log -1 > %(where)s\\README_git_log.txt && \
+rmdir /S /Q %tmpDir%
 """ % aDict
 
   DBG.write("cmd", cmd)
@@ -395,22 +394,28 @@ def get_pkg_check_cmd(dist_name):
         linux="DB"
         manager_msg_err="Error : command failed because sat was not able to find rpm command"
 
-    # 1- search for an installed package manager (rpm on rh, apt on db)
-    cmd_which_rpm=["which", "rpm"]
-    cmd_which_apt=["which", "apt"]
+    # 1- search for an installed package manager (rpm on rh, apt or dpkg-query on db)
+    cmd_which_rpm  = ["which", "rpm"]
+    cmd_which_apt  = ["which", "apt"]
+    cmd_which_dpkg = ["which", "dpkg-query"]
     with open(os.devnull, 'w') as devnull:
         # 1) we search for apt (debian based systems)
-        completed=SP.call(cmd_which_apt,stdout=devnull, stderr=SP.STDOUT)
+        completed=SP.call(cmd_which_dpkg,stdout=devnull, stderr=SP.STDOUT)
         if completed==0 and linux=="DB":
-            cmd_is_package_installed=["apt", "list", "--installed"]
+            cmd_is_package_installed = ["dpkg-query", "-l"]
         else:
-            # 2) if apt not found search for rpm (redhat)
-            completed=SP.call(cmd_which_rpm,stdout=devnull, stderr=SP.STDOUT) # only 3.8! ,capture_output=True)
-            if completed==0 and linux=="RH":
-                cmd_is_package_installed=["rpm", "-q"]
+            # 2) if dpkg not found search for apt
+            completed = SP.call(cmd_which_apt, stdout=devnull, stderr=SP.STDOUT)
+            if completed == 0 and linux == "DB":
+                cmd_is_package_installed = ["apt", "list", "--installed"]
             else:
-                # no package manager was found corresponding to dist_name
-                raise src.SatException(manager_msg_err)
+                # 3) if apt not found search for rpm (redhat)
+                completed=SP.call(cmd_which_rpm,stdout=devnull, stderr=SP.STDOUT) # only 3.8! ,capture_output=True)
+                if completed==0 and linux=="RH":
+                    cmd_is_package_installed=["rpm", "-q"]
+                else:
+                    # no package manager was found corresponding to dist_name
+                    raise src.SatException(manager_msg_err)
     return cmd_is_package_installed
 
 def check_system_pkg(check_cmd,pkg):
@@ -439,9 +444,24 @@ def check_system_pkg(check_cmd,pkg):
         try:
             output = SP.check_output(['grep', pkg], stdin=p.stdout)
             msg_status=src.printcolors.printcSuccess("OK")
-        except:
+        except Exception:
             msg_status=src.printcolors.printcError("KO")
             msg_status+=" (package is not installed!)\n"
+    elif check_cmd[0] == "dpkg-query":
+        # special treatment for dpkg-query
+        # some debian packages have version numbers in their name, we need to add a *
+        # also dpkg-query do not return status, we need to use grep
+        # and dpkg-query output is too messy for being used
+        cmd_is_package_installed[-1] = (
+            cmd_is_package_installed[-1] + "*"
+        )  # we don't specify in pyconf the exact name because of version numbers
+        p = SP.Popen(cmd_is_package_installed, stdout=SP.PIPE, stderr=FNULL)
+        try:
+            output = SP.check_output(["grep", "^ii"], stdin=p.stdout)
+            msg_status = src.printcolors.printcSuccess("OK")
+        except SP.CalledProcessError:
+            msg_status = src.printcolors.printcError("KO")
+            msg_status += " (package is not installed!)\n"
     else:
         p=SP.Popen(cmd_is_package_installed, stdout=SP.PIPE, stderr=FNULL)
         output, err = p.communicate()