Exemplo n.º 1
0
    def _compile(self, md, ars):
        mcp = md.Compile()
        smsg = mcp.get_name()
        try:
            cflgs = self._cpp_compiler_flags
            if cflgs is not None:
                if utils.is_windows():
                    mcp.set_cpp_compiler_flags("windows", cflgs)
                elif utils.is_linux():
                    mcp.set_cpp_compiler_flags("linux", cflgs)
                elif utils.is_mac():
                    mcp.set_cpp_compiler_flags("mac", cflgs)

            lflgs = self._linker_flags
            if lflgs is not None:
                if utils.is_windows():
                    mcp.set_linker_flags("windows", lflgs)
                elif utils.is_linux():
                    mcp.set_linker_flags("linux", lflgs)
                elif utils.is_mac():
                    mcp.set_linker_flags("mac", lflgs)

            mcp.run()
            smsg += " - OK!"
            ars.append(smsg)
        except Exception as e:
            smsg += " - ERROR: " + utils.exception_to_string(e)
            ars.append(smsg)
            raise e
Exemplo n.º 2
0
    def __init__(self,
                 reference_folder=None,
                 screenshot_folder=None,
                 keyword_on_failure='ImageHorizonLibrary.Take A Screenshot'):
        '''ImageHorizonLibrary can be imported with several options.

        ``reference_folder`` is path to the folder where all reference images
        are stored. It must be a _valid absolute path_. As the library
        is suite-specific (ie. new instance is created for every suite),
        different suites can have different folders for it's reference images.

        ``screenshot_folder`` is path to the folder where screenshots are
        saved. If not given, screenshots are saved to the current working
        directory.

        ``keyword_on_failure`` is the keyword to be run, when location-related
        keywords fail. If you wish to not take screenshots, use for example
        `BuiltIn.No Operation`. Keyword must however be a valid keyword.
        '''

        self.reference_folder = reference_folder
        self.screenshot_folder = screenshot_folder
        self.keyword_on_failure = keyword_on_failure
        self.open_applications = OrderedDict()
        self.screenshot_counter = 1
        self.is_windows = utils.is_windows()
        self.is_mac = utils.is_mac()
        self.is_linux = utils.is_linux()
Exemplo n.º 3
0
def getCode():
    '''
    Apre una finestra che chiede il codice licenza. Resituisce il codice licenza e chiude la finestra.
    '''
    appresult = None
    root = None
    root = Tk()
    if utils.is_windows():
        root.wm_iconbitmap('../Nemesys.ico')
    app = LoginGui(master=root)
    app.master.title("Attivazione Ne.Me.Sys")
    app.mainloop()
    appresult = str(app.result)
    logger.info(appresult)

    if appresult == 'Cancel':
        logger.info("User pressed Cancel button, exiting")
        raise LoginCancelledException()

    if appresult == '' or len(appresult) < 4:
        appresult = None
        logger.error('Exit: wrong activation code')
        CodeError()
        raise LoginAuthenticationException('Wrong username/password')

    if root:
        root.destroy()
    return appresult
Exemplo n.º 4
0
    def __write_read(self, write_fn, read_fn, ep, length = 8):
        intf = self.backend.get_interface_descriptor(self.dev, 0, 0, 0).bInterfaceNumber
        for data in (utils.get_array_data1(length), utils.get_array_data2(length)):
            length = len(data) * data.itemsize

            try:
                ret = write_fn(self.handle, ep, intf, data, 1000)
            except NotImplementedError:
                return

            self.assertEqual(ret,
                             length,
                             'Failed to write data: ' + \
                                str(data) + \
                                ', in EP = ' + \
                                str(ep))

            buff = usb.util.create_buffer(length)

            try:
                ret = read_fn(self.handle, ep | usb.util.ENDPOINT_IN, intf, buff, 1000)
            except NotImplementedError:
                return

            self.assertEqual(ret, length, str(ret) + ' != ' + str(length))

            self.assertEqual(buff,
                             data,
                             'Failed to read data: ' + \
                                str(data) + \
                                ', in EP = ' + \
                                str(ep))

            if utils.is_windows():
                time.sleep(0.5)
Exemplo n.º 5
0
def create_semlock(obj, cpid, tp, val, imax):
    sid = None
    if utils.is_windows():
        obj._semlock = _multiprocessing.SemLock(tp, val, imax)
        chandle = _multiprocessing.win32.OpenProcess(
            _multiprocessing.win32.PROCESS_ALL_ACCESS, False, cpid)
        sid = multiprocessing.forking.duplicate(obj._semlock.handle, chandle)
        multiprocessing.forking.close(chandle)
    else:
        cnttry = 0
        while True:
            _sharememmap["semaphore"].acquire()
            try:
                _sharememmap["sem_counter"] += 1
                sid = _sharememmap["sem_counter"]
            finally:
                _sharememmap["semaphore"].release()
            obj._sem_name = _sharememmap["sem_name"] + str(sid)
            obj._sem_t = _sharememmap["libbase"].semaphoreCreate(
                obj._sem_name, val)
            if obj._sem_t != -1:
                break
            cnttry += 1
            if cnttry >= 100:
                raise Exception("semaphoreOpen failed.")
        obj._semlock = _multiprocessing.SemLock._rebuild(*(obj._sem_t, tp,
                                                           imax))

    obj._make_methods()
    return (sid, tp, imax)
Exemplo n.º 6
0
    def _generate_id(self):
        if os.getenv("JENKINS_HOME"):
            prefix = "jenkins"
        elif os.getenv("TRAVIS"):
            prefix = "travis"
        elif any([key.startswith("bamboo") for key in os.environ.keys()]):
            prefix = "bamboo"
        elif os.getenv("TEAMCITY_VERSION"):
            prefix = "teamcity"
        elif os.getenv("DOCKER_HOST"):
            prefix = "docker"
        elif os.getenv("AWS_"):
            prefix = "amazon"
        elif os.getenv("GOOGLE_APPLICATION_CREDENTIALS") or os.getenv("CLOUDSDK_CONFIG"):
            prefix = "google_cloud"
        elif os.getenv("WEBJOBS_NAME"):
            prefix = "azure"
        elif is_linux():
            prefix = 'linux'
        elif is_windows():
            prefix = 'windows'
        else:
            prefix = 'macos'

        return "%s-%x" % (prefix, uuid.getnode())
Exemplo n.º 7
0
    def get_logs(cls):
        config = Config.getInstance()
        if not config.logs() or cls.MOCK_MODE:
            yield
            return

        filename = config.log_name()
        if not filename:
            filename = str(time()).replace('.', '')
        filename += '.log'
        filename = join(config.defaults.get('folder'), filename)
        logger().info('Starting logs capture to ' + filename)
        with open(filename, 'w') as f:
            cls._action(cls._get_adb_command_prefix() + ['logcat', '-c'])
            cmd = cls._get_adb_command_prefix() + ['logcat', '-v', 'time']
            if is_windows():
                CREATE_NO_WINDOW = 0x08000000  # Doesn't really work, shows a window and hides it
                p = Popen(cmd, stdout=f, creationflags=CREATE_NO_WINDOW)
            else:
                p = Popen(cmd, stdout=f)
            try:
                yield
            finally:
                p.kill()
                logger().info('finished logs capture to ' + filename)
    def __init__(self, reference_folder=None, screenshot_folder=None,
                 keyword_on_failure='ImageHorizonLibrary.Take A Screenshot'):
        '''ImageHorizonLibrary can be imported with several options.

        ``reference_folder`` is path to the folder where all reference images
        are stored. It must be a _valid absolute path_. As the library
        is suite-specific (ie. new instance is created for every suite),
        different suites can have different folders for it's reference images.

        ``screenshot_folder`` is path to the folder where screenshots are
        saved. If not given, screenshots are saved to the current working
        directory.

        ``keyword_on_failure`` is the keyword to be run, when location-related
        keywords fail. If you wish to not take screenshots, use for example
        `BuiltIn.No Operation`. Keyword must however be a valid keyword.
        '''

        self.reference_folder = reference_folder
        self.screenshot_folder = screenshot_folder
        self.keyword_on_failure = keyword_on_failure
        self.open_applications = OrderedDict()
        self.screenshot_counter = 1
        self.is_windows = utils.is_windows()
        self.is_mac = utils.is_mac()
        self.is_linux = utils.is_linux()
Exemplo n.º 9
0
 def connect(cls):
     if is_windows():
         logger().error('iOS not yet supported on Windows')
         return False
     device_name = Config.getInstance().ui_main.ios_device_var.get()
     if not device_name:
         logger().warning('No device to connect to')
         return False
     if not exists(cls._PIPE_PATH):
         try:
             mkfifo(cls._PIPE_PATH)
         except OSError:
             logger().error("Pipe operation isn't supported here")
             return False
     typethree_path = join(getenv('DEV_ENV_PATH'), 'AutoFill', 'TypeThree',
                           'TypeThree')
     if not typethree_path:
         logger().error("Can't locate typethree")
         return False
     cls._typethree_process = Popen(
         [typethree_path, device_name, '-p', cls._PIPE_PATH], stderr=PIPE)
     ready = False
     while not ready:
         ready = 'Trying to read input from' in cls._typethree_process.stderr.readline(
         )
     logger().debug('iOS connected')
     return True
Exemplo n.º 10
0
    def run(self):
        bok = True
        arstatus = []
        utils.info("BEGIN COMPILE ALL")
        try:
            self._compile(compile_lib_z, arstatus)
            self._compile(compile_lib_core, arstatus)
            self._compile(compile_lib_gdi, arstatus)
            self._compile(compile_lib_osutil, arstatus)
            if utils.is_windows():
                self._compile(compile_os_win_launcher, arstatus)
                self._compile(compile_os_win_service, arstatus)
                self._compile(compile_os_win_updater, arstatus)
            self._compile(compile_lib_screencapture, arstatus)
            utils.info("END COMPILE ALL")
        except:
            bok = False
            utils.info("ERROR COMPILE ALL")

        utils.info("")
        utils.info("")
        utils.info("COMPILATION STATUS:")
        for n in arstatus:
            utils.info(n)
        utils.info("")
        if bok:
            utils.info("ALL COMPILED CORRECTLY.")
        else:
            utils.info("ERRORS OCCURRED DURING COMPILATION.")
Exemplo n.º 11
0
 def _parse_ping_stdout(self, raw_text):
     if utils.is_windows():
         raw_text = raw_text.decode('gbk')
         end = -1
         begin = -1
         for e in raw_text.splitlines():
             if e.find('无法访问目标主机') != -1:
                 break
             end = e.find('%')
             if end != -1:
                 begin = e.rfind('(')
                 last_line = e
                 break
         if begin + 1 >= end:
             loss_rate = 100.0
         else:
             loss_rate = float(last_line[begin + 1:end].strip())
         # print('loss_rate=', loss_rate)
     else:
         raw_text = raw_text.decode('utf-8')
         last_line = raw_text.splitlines()[-1]
         end = last_line.find('%')
         begin = last_line.rfind(',')
         if begin + 1 >= end:
             loss_rate = 100.0
         else:
             loss_rate = float(last_line[begin + 1:end].strip())
     return loss_rate
Exemplo n.º 12
0
def getCode():
    '''
    Apre una finestra che chiede il codice licenza. Resituisce il codice licenza e chiude la finestra.
    '''
    appresult = None
    root = None
    root = Tk()
    if utils.is_windows():
        root.wm_iconbitmap('../Nemesys.ico')
    app = LoginGui(master=root)
    app.master.title("Attivazione Ne.Me.Sys")
    app.mainloop()
    appresult = str(app.result)
    logger.info(appresult)
    
    if appresult == 'Cancel':
        logger.info("User pressed Cancel button, exiting")
        raise LoginCancelledException()
    
    if appresult == '' or len(appresult) < 4:
        appresult = None
        logger.error('Exit: wrong activation code')
        CodeError()
        raise LoginAuthenticationException('Wrong username/password')

    if root:
        root.destroy()
    return appresult
Exemplo n.º 13
0
def download_file(url, desc, filename, file_size, verbose=False, req_timeout=(5, None)):
    """
    Download file with progressbar

    Usage:
        download_file('http://web4host.net/5MB.zip')
    """
    with requests.get(url, stream=True, timeout=req_timeout) as r:
        r.raise_for_status()
        chunk_size = 1024
        num_bars = int(file_size / chunk_size) + 1
        if verbose:
            print("size = %d, url = %s" % (file_size, url))
        download_size = 0

        with open(filename+'.canvas_tmp', 'wb') as fp:
            with tqdm.tqdm(
                r.iter_content(chunk_size=chunk_size),
                total=num_bars, unit='KB',
                desc=desc, bar_format='{l_bar}{bar}{r_bar}', ascii=is_windows()
            ) as pbar:
                for chunk in pbar:
                    fp.write(chunk)
                    download_size += len(chunk)
        if download_size != file_size:
            raise Exception(
                f"Incomplete file: expected {file_size}, downloaded {download_size}")
        os.replace(filename+'.canvas_tmp', filename)
    return
Exemplo n.º 14
0
def download_file(url,
                  desc,
                  filename=False,
                  verbose=False,
                  req_timeout=(5, None)):
    """
    Download file with progressbar

    Usage:
        download_file('http://web4host.net/5MB.zip')  
    """
    if not filename:
        local_filename = os.path.join(".", url.split('/')[-1])
    else:
        local_filename = filename
    r = requests.get(url, stream=True, timeout=req_timeout)
    file_size = int(r.headers.get('Content-Length', 0))
    chunk = 1
    chunk_size = 1024
    num_bars = int(file_size / chunk_size) + 1
    if verbose:
        print(dict(file_size=file_size))
        print(dict(num_bars=num_bars))

    with open(local_filename + '.canvas_tmp', 'wb') as fp:
        for chunk in tqdm.tqdm(r.iter_content(chunk_size=chunk_size),
                               total=num_bars,
                               unit='KB',
                               desc=desc,
                               bar_format='{l_bar}{bar}{r_bar}',
                               ascii=is_windows()):
            fp.write(chunk)
    os.replace(local_filename + '.canvas_tmp', local_filename)
    return
Exemplo n.º 15
0
 def __init__(self, master=None):
     Frame.__init__(self, master)
     self.config(width="800")
     if utils.is_windows():
         self.master.wm_iconbitmap(os.path.join('..', 'nemesys.ico'))
     self.pack()
     self.createWidgets()
     self.result = None
Exemplo n.º 16
0
 def __init__(self, agent_main):
     self._agent_main=agent_main
     if utils.is_windows():
         self._osnative = Windows(self._agent_main)
     elif utils.is_linux():
         self._osnative = Linux()
     elif utils.is_mac():
         self._osnative = Mac()
Exemplo n.º 17
0
def ErrorDialog(message):
    root = Tk()
    if utils.is_windows():
        root.wm_iconbitmap('../Nemesys.ico')
    root.withdraw()
    title = 'Errore'
    tkMessageBox.showerror(title, message, parent=root)
    root.destroy()
Exemplo n.º 18
0
 def __init__(self, master=None):
     Frame.__init__(self, master)
     self.config(width="800")
     if utils.is_windows():
         self.master.wm_iconbitmap(os.path.join('..', 'nemesys.ico'))
     self.pack()
     self.createWidgets()
     self.result = None
Exemplo n.º 19
0
def get_suffix():
    if utils.is_windows():
        return "win"
    elif utils.is_linux():
        return "linux"
    elif utils.is_mac():
        return "mac"
    return None
Exemplo n.º 20
0
def ErrorDialog(message):
    root = Tk()
    if utils.is_windows():
        root.wm_iconbitmap('../Nemesys.ico')
    root.withdraw()
    title = 'Errore'
    tkMessageBox.showerror(title, message, parent=root)
    root.destroy()
Exemplo n.º 21
0
    def run(self):
        bok = True
        arstatus = []
        utils.init_path(self.get_path_native())
        utils.info("BEGIN DEPENDENCIES")
        try:
            if utils.is_windows():
                self._dependency("lib_gcc", "8.1.0", arstatus)
                self._dependency("lib_stdcpp", "8.1.0", arstatus)
            self._dependency("lib_z", "1.2.11", arstatus)
            self._dependency("lib_turbojpeg", "2.0.3", arstatus)
            self._dependency("lib_opus", "21.3.1", arstatus)
            self._dependency("lib_rtaudio", "5.1.0", arstatus)
            utils.info("END DEPENDENCIES")
        except:
            bok = False
            utils.info("ERROR DEPENDENCIES")

        if bok:
            utils.info("BEGIN COMPILE ALL")
            try:
                self._compile(compile_lib_core, arstatus)
                self._compile(compile_lib_gdi, arstatus)
                self._compile(compile_lib_osutil, arstatus)
                if utils.is_windows():
                    self._compile(compile_os_win_launcher, arstatus)
                    self._compile(compile_os_win_service, arstatus)
                    self._compile(compile_os_win_updater, arstatus)
                self._compile(compile_lib_screencapture, arstatus)
                self._compile(compile_lib_soundcapture, arstatus)
                utils.info("END COMPILE ALL")
            except:
                bok = False
                utils.info("ERROR COMPILE ALL")

        utils.info("")
        utils.info("")
        utils.info("STATUS:")
        for n in arstatus:
            utils.info(n)
        utils.info("")
        if bok:
            utils.info("ALL COMPILED CORRECTLY.")
        else:
            utils.info("ERRORS OCCURRED.")
Exemplo n.º 22
0
def OkDialog():
    root = Tk()
    if utils.is_windows():
        root.wm_iconbitmap('../Nemesys.ico')
    root.withdraw()
    title = 'Ne.Me.Sys autenticazione corretta'
    message = 'Username e password corrette e verificate'
    tkMessageBox.showinfo(title, message, parent=root)
    root.destroy()
Exemplo n.º 23
0
def init_parameter_path(value, default):
    if value is None:
        value = default
    else:
        # expand variables in no-windows
        if not utils.is_windows():
            value = value.replace('~', utils.get_real_home())
        value = os.path.abspath(value)
    return value
Exemplo n.º 24
0
 def _prepare_map(self):
     if self.ftype == "F":
         self._mmap = mmap.mmap(self.file.fileno(), 0)
     elif self.ftype == "M":
         if not utils.is_windows():
             self._mmap = mmap.mmap(self.fd, MapFile._SIZE)
         else:
             self._mmap = mmap.mmap(0, MapFile._SIZE,
                                    "Global\\" + self.fname)
Exemplo n.º 25
0
def OkDialog():
    root = Tk()
    if utils.is_windows():
        root.wm_iconbitmap('../Nemesys.ico')
    root.withdraw()
    title = 'Ne.Me.Sys autenticazione corretta'
    message = 'Username e password corrette e verificate'
    tkMessageBox.showinfo(title, message, parent=root)
    root.destroy()
Exemplo n.º 26
0
def connect_semlock(obj, state):
    if utils.is_windows():
        obj._semlock = _multiprocessing.SemLock._rebuild(*state)
    else:
        obj._sem_name = _sharememmap["sem_name"] + str(state[0])
        obj._sem_t = _sharememmap["libbase"].semaphoreOpen(obj._sem_name)
        obj._semlock = _multiprocessing.SemLock._rebuild(*(obj._sem_t,
                                                           state[1], state[2]))
    obj._make_methods()
Exemplo n.º 27
0
    def run(self):
        is_windows = utils.is_windows()

        subprocess.call(shlex.split('hexo generate --cwd {}'.format(
            self.blog_path)),
                        shell=is_windows)
        if self.deploy:
            subprocess.call(shlex.split('hexo deploy --cwd {}'.format(
                self.blog_path)),
                            shell=is_windows)
Exemplo n.º 28
0
def destroy_semlock(obj):
    if obj._semlock is not None:
        try:
            obj._semlock.release()
        except:
            None
        obj._semlock = None
    if utils.is_windows():
        None
    else:
        _sharememmap["libbase"].semaphoreClose(obj._sem_t)
        _sharememmap["libbase"].semaphoreUnlink(obj._sem_name)
Exemplo n.º 29
0
def _unload_lib_obj(olib):
    if utils.is_windows():
        import _ctypes
        _ctypes.FreeLibrary(olib._handle)
        del olib
    elif utils.is_linux():
        import _ctypes
        _ctypes.dlclose(olib._handle)
        del olib
    elif utils.is_mac():
        import _ctypes
        _ctypes.dlclose(olib._handle)
        del olib
Exemplo n.º 30
0
    def __init__(self):
        self.message_queue = None
        self.ping_count = 1
        self.ping_size = 1
        self.ping_wait_time = 1
        if utils.is_windows():
            self.ping_count_arg = '-n'
            self.ping_size_arg = '-l'
            self.ping_wait_time_arg = "-w"
        else:

            self.ping_count_arg = '-c'
            self.ping_size_arg = '-s'
            self.ping_wait_time_arg = '-W'
Exemplo n.º 31
0
 def run(self):
     utils.info("BEGIN " + self.get_name())
     utils.make_tmppath()
     tarname=CONF["name"] + "-" + CONF["version"] + ".tar.gz"        
     utils.remove_from_native(CONF)
     if os.path.exists(CONF["pathdst"]):
         utils.remove_path(CONF["pathdst"])
     if os.path.exists(utils.PATHTMP + os.sep + tarname):
         utils.remove_path(utils.PATHTMP + os.sep + tarname)
     if os.path.exists(utils.PATHTMP + os.sep + CONF["name"] + "-" + CONF["version"]):
         utils.remove_path(utils.PATHTMP + os.sep + CONF["name"] + "-" + CONF["version"])
     utils.download_file(CONF["urlsrc"], utils.PATHTMP + os.sep + tarname)
     utils.untar_file(utils.PATHTMP + os.sep + tarname, utils.PATHTMP)
     utils.remove_file(utils.PATHTMP + os.sep + tarname)
     os.rename(utils.PATHTMP + os.sep + CONF["name"] + "-" + CONF["version"], CONF["pathdst"])
     
     if utils.is_mac():
         #CORREGGE configure
         apppth=CONF["pathdst"] + os.sep + "configure"
         f = codecs.open(apppth, encoding='utf-8')
         appdata = f.read()
         f.close()
         appdata=appdata.replace('.dylib','.so').replace("-dynamiclib","-shared")
         os.remove(apppth)
         f = codecs.open(apppth, encoding='utf-8', mode='w+')
         f.write(appdata)
         f.close()
         os.chmod(apppth, stat.S_IRWXU)
         
     
     if utils.is_windows():
         utils.system_exec(["mingw32-make.exe", "-fwin32/Makefile.gcc"],CONF["pathdst"])
     else:
         utils.system_exec(["./configure"],CONF["pathdst"])
         utils.system_exec(["make"],CONF["pathdst"])
      
     if utils.is_mac():   
         #CORREGGE zutil.h
         apppth=CONF["pathdst"] + os.sep + "zutil.h"
         f = codecs.open(apppth, encoding='utf-8')
         appdata = f.read()
         f.close()
         appdata=appdata.replace('#  define local static','//#  define local static')
         os.remove(apppth)
         f = codecs.open(apppth, encoding='utf-8', mode='w+')
         f.write(appdata)
         f.close()
     
     utils.copy_to_native(CONF)
     utils.info("END " + self.get_name())
Exemplo n.º 32
0
    def run(self, edit, cmd, resolve=None, reject=None):
        command = cmd.split(' ') if isinstance(cmd, str) else cmd
        proc = Popen(command,
                     stdin=PIPE,
                     stderr=PIPE,
                     stdout=PIPE,
                     env=get_proc_env(),
                     shell=is_windows())

        stdout, stderr = proc.communicate()

        if proc.returncode == 0 and resolve:
            self.view.run_command(resolve)
        elif reject:
            self.view.run_command(reject)
Exemplo n.º 33
0
def move_old_config():
    # FIXME: This function will be removed at the next release.
    old_file = os.path.join(os.path.expanduser("~"), "." + CONFIG_FILE)
    if not os.path.exists(old_file):
        return False
    with open(old_file) as f:
        data = f.read()
    with open(CONFIG_PATH, "w") as f:
        if "DOTCLOUD_CONFIG_FILE" not in os.environ:
            data = data.replace("http://", "https://")
        f.write(data)
        if not is_windows():
            os.fchmod(f.fileno(), 0600)
    info("Migrated from {0}".format(old_file))
    return True
Exemplo n.º 34
0
 def destroy(self):
     if not self.bdestroy:
         self.bdestroy = True
         if self.bcreate:
             if self.ftype == "F":
                 if utils.path_exists(self.fpath):
                     utils.path_remove(self.fpath)
             elif self.ftype == "M":
                 if not utils.is_windows():
                     iret = _sharememmap["libbase"].sharedMemoryUnlink(
                         self.fname)
                     if iret != 0:
                         raise Exception("sharedMemoryUnlink fail")
                 else:
                     MapFile._memlistname.remove(self.fname)
Exemplo n.º 35
0
def setup():
    import re

    if not os.path.exists(CONFIG_DIR):
        os.mkdir(CONFIG_DIR, 0700)
    if move_old_config() is True:
        return
    conf = {"url": "https://api.dotcloud.com/"}
    apikey = raw_input("Enter your api key (You can find it at http://www.dotcloud.com/account/settings): ")
    if not re.match("\w{20}:\w{40}", apikey):
        die("Not a valid api key.")
    conf["apikey"] = apikey
    with open(CONFIG_PATH, "w") as f:
        json.dump(conf, f, indent=4)
        if not is_windows():
            os.fchmod(f.fileno(), 0600)
Exemplo n.º 36
0
    def get(self, key):
        try:
            self._semaphore.acquire()
            try:
                if self._lang_current is None:
                    applng = None
                    try:
                        if utils.is_windows():
                            import ctypes
                            windll = ctypes.windll.kernel32
                            windll.GetUserDefaultUILanguage()
                            wl = locale.windows_locale[
                                windll.GetUserDefaultUILanguage()]
                            applng = wl.split("_")[0]
                        elif utils.is_mac():
                            p = subprocess.Popen(
                                ['defaults', 'read', '-g', 'AppleLocale'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
                            sout, serr = p.communicate()
                            if sout is not None:
                                applng = sout.replace("\n",
                                                      "").replace(" ",
                                                                  "_")[:10]
                    except:
                        None
                    try:
                        if applng is None:
                            l = locale.getdefaultlocale()
                            if l is not None:
                                applng = l[0]
                    except:
                        None

                    self._set_locale(applng)

            finally:
                self._semaphore.release()

            if key in self._data_current:
                return self._data_current[key]
            elif key in self._data_default:
                return self._data_default[key]
            else:
                return "RES_MISSING#" + key
        except:
            return "RES_ERROR#" + key
Exemplo n.º 37
0
 def _action(cls, cmd):
     logger().debug(" ".join(cmd))
     if not cls.MOCK_MODE:
         try:
             if is_windows():
                 CREATE_NO_WINDOW = 0x08000000  # Doesn't really work, shows a window and hides it
                 # TODO synchronicity should be according to param, sometimes it might be could to cancel it
                 Popen(cmd,
                       shell=True,
                       stdout=PIPE,
                       stderr=PIPE,
                       creationflags=CREATE_NO_WINDOW).communicate()
             else:
                 system(" ".join(cmd))
         except Exception as e:
             logger().error("Command failed " +
                            str(e))  #TODO eran also check ret code
Exemplo n.º 38
0
def setup():
    import re
    if not os.path.exists(CONFIG_DIR):
        os.mkdir(CONFIG_DIR, 0700)
    if move_old_config() is True:
        return
    conf = {'url': 'https://api.dotcloud.com/'}
    apikey = raw_input('Enter your api key (You can find it at http://www.dotcloud.com/accounts/settings): ')
    if not re.match('\w{20}:\w{40}', apikey):
        die('Not a valid api key.')
    conf['apikey'] = apikey
    with open(CONFIG_PATH, 'w') as f:
        json.dump(conf, f, indent=4)
        if not is_windows():
            os.fchmod(f.fileno(), 0600)
    if os.path.exists(CONFIG_KEY):
        os.remove(CONFIG_KEY)
Exemplo n.º 39
0
def create_default_config():
    if not Path(CONFIG_FILE).exists():
        src = Path(CONFIG_EXAMPLE)
        if not src.exists():
            if sys._MEIPASS:  # for portable exe created by pyinstaller
                # load config from temporary dirertory
                src = Path(sys._MEIPASS) / CONFIG_EXAMPLE
            else:
                print(
                    f"{Fore.RED}Config not found, default config not found either{Style.RESET_ALL}"
                )
                if is_windows():
                    # for windows double-click user
                    input()
                exit()
        dst = Path(CONFIG_FILE)
        dst.write_bytes(src.read_bytes())
Exemplo n.º 40
0
 def _annotate_files(self):
     """Annotate Source files: add acc_period/period for each source file.
        1. Annotate java source files, which have $JAVA_SRC_ROOT prefix.
        2. Annotate c++ source files.
     """
     dest_dir = self.config['annotate_dest_dir']
     for key in self.file_periods:
         from_path = key
         if not os.path.isfile(from_path):
             log_warning("can't find source file for path %s" % from_path)
             continue
         if from_path.startswith('/'):
             to_path = os.path.join(dest_dir, from_path[1:])
         elif is_windows() and ':\\' in from_path:
             to_path = os.path.join(dest_dir, from_path.replace(':\\', os.sep))
         else:
             to_path = os.path.join(dest_dir, from_path)
         is_java = from_path.endswith('.java')
         self._annotate_file(from_path, to_path, self.file_periods[key], is_java)
Exemplo n.º 41
0
def run_codex(result_file):

    if utils.is_windows():
        cur_path = os.path.dirname(os.path.realpath(__file__))
        print(cur_path)
        codex_path = os.path.join(cur_path, "CodeX", "CodeX64.exe")
        if not os.path.exists(codex_path):
            log.info("Hint: put CodeX to CodeX folder to Cubifier dir, Cubifier calls CodeX automatically")
            return

        log.info("Found CodeX, encoding file. This might take a while...")
        _dir, fname = os.path.split(result_file)
        name, ext = os.path.splitext(fname)
        cube_file = os.path.join(_dir,  name + ".cube")
        args = [codex_path,
                "CubePro",
                "EnCode",
                result_file,
                cube_file]
        subprocess.call(args)
Exemplo n.º 42
0
	def load_paths(self):
		''' The global load paths for Sass files. This is meant for plugins and
  			libraries to register the paths to their Sass stylesheets to that they may
  			be `@imported`. This load path is used by every instance of [sass.Engine].
  			They are lower-precedence than any load paths passed in via the
  			{file:SASS_REFERENCE.md#load_paths-option `:load_paths` option}.
  			
  			If the `SASS_PATH` environment variable is set,
  			the initial value of `load_paths` will be initialized based on that.
  			The variable should be a colon-separated list of path names
  			(semicolon-separated on Windows).
  
  			Note that files on the global load path are never compiled to CSS
  			themselves, even if they aren't partials. They exist only to be imported.
  
  			@example
  			   Sass.load_paths().append(os.path.dirname(__file__ + '/sass'))
  			@return [list<str, sass.importers.Base>]
  		'''
		if not self._load_paths:
			self._load_paths = os.getenv('SASS_PATH','').split(';' if utils.is_windows() else ':')

		return self._load_paths
Exemplo n.º 43
0
 def key(self, data):
     with open(config.CONFIG_KEY, 'w') as f:
         f.write(data)
         if not utils.is_windows():
             os.fchmod(f.fileno(), 0600)
Exemplo n.º 44
0
def main():
    parser = ArgParser(description=('Command line interface '
                                    'to web2exe. {}'.format(__version__)),
                                     prog='web2execmd')
    command_base = CommandBase()
    command_base.init()
    parser.add_argument('project_dir', metavar='project_dir',
                        help='The project directory.', type=unicode_arg)
    parser.add_argument('--output-dir', dest='output_dir',
                        help='The output directory for exports.',
                        type=unicode_arg)
    parser.add_argument('--quiet', dest='quiet', action='store_true',
                        default=False,
                        help='Silences output messages')
    parser.add_argument('--verbose', dest='verbose', action='store_true',
                        default=False,
                        help=('Prints debug errors and messages instead '
                              'of logging to files/errors.log'))
    parser.add_argument('--package-json',
                        dest='load_json',
                        nargs='?',
                        default='',
                        const=True,
                        help=('Loads the package.json '
                              'file in the project directory. '
                              'Ignores other command line arguments.'))
    parser.add_argument('--cmd-version', action='version', version='%(prog)s {}'.format(__version__))

    for setting_group_dict in command_base.settings['setting_groups']+[command_base.settings['compression']]:
        for setting_name, setting in setting_group_dict.items():
            kwargs = {}
            if setting_name == 'name':
                kwargs.update({'default': command_base.project_name})
            else:
                kwargs.update({'required': setting.required,
                               'default': setting.default_value})
            action = 'store'
            option_name = setting_name.replace('_', '-')

            if setting.type in ['file', 'string', 'strings']:
                kwargs.update({'type': unicode_arg})

            if isinstance(setting.default_value, bool):
                action = ('store_true' if setting.default_value is False
                          else 'store_false')
                kwargs.update({'action': action})
                if setting.default_value is True:
                    option_name = u'disable-{}'.format(option_name)
            else:
                if setting.values:
                    kwargs.update({'choices': setting.values})
                    setting.description += u' Possible values: {{{}}}'.format(', '.join([unicode(x) for x in setting.values]))
                    kwargs.update({'metavar': ''})
                else:
                    kwargs.update({'metavar': '<{}>'.format(setting.display_name)})

            parser.add_argument(u'--{}'.format(option_name),
                                dest=setting_name,
                                help=setting.description,
                                **kwargs
                                )

    export_args = [arg for arg in command_base.settings['export_settings']]
    parser.add_argument('--export-to', dest='export_options',
                        nargs='+', required=True,
                        choices=export_args,
                        help=('Choose at least one system '
                              'to export to.'))

    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(
            stream=sys.stdout,
            format=("%(levelname) -10s %(module)s.py: "
                    "%(lineno)s %(funcName)s - %(message)s"),
            level=logging.DEBUG
        )
    else:
        logging.basicConfig(
            filename=LOG_FILENAME,
            format=("%(levelname) -10s %(asctime)s %(module)s.py: "
                    "%(lineno)s %(funcName)s - %(message)s"),
            level=logging.DEBUG
        )

    global logger
    global handler

    logger = logging.getLogger('CMD Logger')
    handler = lh.RotatingFileHandler(LOG_FILENAME, maxBytes=100000, backupCount=2)
    logger.addHandler(handler)

    def my_excepthook(type_, value, tback):
        output_err = u''.join([unicode(x) for x in traceback.format_exception(type_, value, tback)])
        logger.error(u'{}'.format(output_err))
        sys.__excepthook__(type_, value, tback)

    sys.excepthook = my_excepthook

    command_base.logger = logger

    if args.quiet:
        command_base.quiet = True

    if utils.is_windows() and os.path.isabs(args.project_dir):
        command_base._project_dir = u'//?/' + args.project_dir
    else:
        command_base._project_dir = args.project_dir

    command_base._output_dir = (args.output_dir or
                                utils.path_join(command_base._project_dir, 'output'))

    if args.app_name is None:
        args.app_name = command_base.project_name()

    if args.name is not None:
        setting = command_base.get_setting('name')
        args.name = setting.filter_name(args.name if not callable(args.name) else args.name())

    command_base._project_name = args.app_name if not callable(args.app_name) else args.app_name()

    if not args.title:
        args.title = command_base.project_name()

    for name, val in args._get_kwargs():
        if callable(val):
            val = val()
        if name == 'export_options':
            for opt in val:
                setting = command_base.get_setting(opt)
                if setting is not None:
                    setting.value = True
        else:
            setting = command_base.get_setting(name)
            if setting is not None:
                setting.value = val

    if args.load_json is True:
        command_base.load_package_json()
    elif args.load_json:
        command_base.load_package_json(args.load_json)

    command_base.export()
Exemplo n.º 45
0
 def delay(alt):
     # Hack to avoid two consecutive isochronous transfers to fail
     if alt == devinfo.INTF_ISO and utils.is_windows():
         time.sleep(0.5)
Exemplo n.º 46
0
def is_installed():
    uninst = get_file('uninst.exe')
    return utils.is_windows() and os.path.exists(uninst)