Exemple #1
0
    def load_asset_if_not(self, db, asset_names):
        """Load none asset loaded into show
            :param:
                   asset_names (list/str): a valid code name for asset
        """
        from dsk.base.db_helper.db_helper_funct import ShotgunQuery as SQ
        if isinstance(asset_names, basestring):
            asset_names = [asset_names]

        assets = self.get_assets()
        in_all_ready = assets.childNames()

        to_query = list()
        all_ready_there = list()
        for s in asset_names:
            if s not in in_all_ready:
                to_query.append(s)
            else:
                ch = assets.getChildByName(s)
                if ch is None:
                    log.error("cannot retrieve asset: %s", s)
                else:
                    all_ready_there.append(ch)

        asset_list = list()
        if len(to_query) > 0:
            asset_list = SQ.assets_with_id(self.id, to_query, db.get_conn())
            self.init_with_assets(asset_list)
        return asset_list + all_ready_there
def H_addSubOptionMenu(widgetApp, amenu, aname, dd):
    alreadyThere = [
        x for x in [x for x in amenu.actions() if str(x.text()) == aname]
    ]
    if len(alreadyThere) == 0:
        if dd == None or len(dd) == 0:
            amenu.addAction(aname)
        else:

            subMenu = QtT.QtWidgets.QMenu(aname, amenu)
            subMenu.setObjectName(aname)
            amenu.addMenu(subMenu)

            for a in dd:

                if len(dd[a]) == 4:
                    la = dd[a][BK.K_TOOL_LABEL]
                    subMenu2 = QtT.QtWidgets.QMenu(la, widgetApp)
                    subMenu2.setObjectName(a)
                    subMenu.addMenu(subMenu2)
                    for b in dd[a][BK.K_TOOL_EXTRA]:
                        act = subMenu2.addAction(b)
                        act.setObjectName(b)
                elif len(dd[a]) == 3:
                    la = dd[a][BK.K_TOOL_LABEL]
                    act = subMenu.addAction(la)
                    act.setObjectName(a)
                    if dd[a][BK.K_TOOL_CHECKABLE]:
                        act.setCheckable(True)
                        act.setChecked(dd[a][BK.K_TOOL_DEFAULT])
                else:
                    log.error(
                        "in H_addSubOptionMenuwrong submenu description %s" %
                        dd[a])
Exemple #3
0
    def write(self, afile="", pretty=False):
        if afile != "":
            if self._doc == None:
                MsgUtils.warning("has no document")
                return False
            try:
                #if pretty:
                #    print(self.getEncoding())
                #    pstr = self._doc.toprettyxml("\t", "\n", self.getEncoding())
                #    afile.write(pstr)

                #else:
                self._doc.writexml(afile, "\t", "\t", "\n", self.getEncoding())

            except Exception as e:
                MsgUtils.error(str(e))
                MsgUtils.error("can't write the current document")
                return False
            return True
        else:
            if self._doc != None:
                if pretty:
                    print(
                        str(
                            self._doc.toprettyxml("\t", "\n",
                                                  self.getEncoding())))
                else:
                    print(self._doc.toxml(self.getEncoding()))
                return True
        return False
Exemple #4
0
    def simple_clone(self, release_top_location, branch=""):
        """Clone an accessible remote git address to a top location

            :param release_top_location: (str existing branch)  a place to install
            :param branch: (str)  an optional existing branch
            :return ResultRepoInstall: success errors log atag
        """

        if not os.path.isdir(release_top_location):
            log.error("release area needs to exist, %s doen't" %
                      release_top_location)
            return False

        x = GitUtils(release_top_location)

        try:
            #The repo gets clone in this function
            x.clone_repo(self.src_repo, "", branch)
        except Exception as e:
            log.error(str(e))
            return ResultRepoInstall(False, [str(e)], ['failed simple_clone'],
                                     None)

        return ResultRepoInstall(True, ["no error"], ['done simple_clone'],
                                 None)
Exemple #5
0
    def _init_root_path(self):
        if self._userInfo == None:
            return False
        toCheck = [self._userInfo.local_area,
                   self._userInfo.log_dir]
        checkLayout = False
        for d in toCheck:
            if not DiskUtils.is_dir_exist(d):
                checkLayout = True
                MsgUtils.warning("%r is needed, create..." % d)
                if DiskUtils.create_path_rec(d) == False:
                    MsgUtils.error("can't create %r" % d)
                else:
                    MsgUtils.info("%r created" % d)

                #only on creation,copy if exist the defaultLayoutFile from
                # from the module
        if checkLayout:
            import shutil
            fromlayout = os.path.join(self._resource.resource_path,
                                      initDefault.DEFAULT_LAYOUT_ROOT)
            tolayout = os.path.join(self._userInfo.local_area,
                                    initDefault.DEFAULT_LAYOUT_ROOT)
            fromlayout += ".lyt"
            tolayout += ".lyt"
            if os.path.exists(fromlayout) and not os.path.exists(tolayout):
                shutil.copyfile(fromlayout, tolayout)
                MsgUtils.info("found a defaut layout file %s" % fromlayout)
        self.valid_to_save = self.is_persistant()
Exemple #6
0
 def updateEnable(self, msg):
     if msg.widgetFrom() != self:
         log.error("updateEnable,should be not getting this update")
         return
     if msg.succeed():
         for item in msg.getOptions():
             item.updateEnable()
Exemple #7
0
    def start_engine(engine_name="tk-shell"):
        """Start the given engine in the given context. If no context is provided, start
        the engine in the project context

        :param engine_name:  Name of the engine to start
        :returns:            The running engine
        """
        import tank

        current_engine = tank.platform.current_engine()
        if current_engine:
            return current_engine

        pc_path = os.environ.get("TANK_CURRENT_PC")
        #---------------------------------------------------------------------------
        try:
            tk = tank.sgtk_from_path(pc_path)
            ctx = tk.context_from_path(tk.project_path)
            current_engine = tank.platform.start_engine(engine_name, tk, ctx)
            return current_engine

        except Exception as e:
            log.error("Failed to start Engine - %s" % str(e))
            traceback.print_exc()
        return None
Exemple #8
0
    def get_iconfile(self, db, location, base_res=64):
        """Return  iconfile. if iconfile == "", use thumbnailurl
            - download thumbnailurl
            - convert and resize image to png of the needed res

                :param location: a directory to download the image
                :param conn: a shotgun connection
                :param base_res: resolution in x, keep aspect

        """
        if self.iconfile != "" and os.path.isfile(self.iconfile):
            return self.iconfile

        if self.thumbnailurl != "":
            dest = os.path.join(location, self.getName() + ".jpg")
            # destpng = os.path.join(location, self.getName()+".png")
            destjpg = dest
            if not os.path.isfile(destjpg):
                try:
                    db.download_icon(self.thumbnailurl, dest)
                except Exception as e:
                    log.error(str(e))
                    return ""
            self.iconfile = destjpg

        return self.iconfile
 def checkAdminPath():
     for path in DefaultPath.__ADMIN_CREATED__:
         if not DiskUtils.is_dir_exist(path):
             MsgUtils.warning("%r needed, creating" % path)
             if DiskUtils.create_path(path) == False:
                 MsgUtils.error("can't create %r" % path)
                 sys.exit(1)
     return True
Exemple #10
0
    def OpenFile(self, afile, mode="r"):
        try:
            fFile = open(afile, mode)
        except:
            MsgUtils.error("Can't open %s" % afile)
            fFile = None

        return fFile
Exemple #11
0
    def treeTextUpdate(self, msg):
        if msg.widgetFrom() != self:
            log.error("treeTextUpdate,should be not getting this update")
            return

        i = msg.getItem()
        if i:
            self.disconnectLocalSignal()  # to avoid bouncing
            i.setText(msg.getWhich(), msg.getProposedName())
            self.connectLocalSignal()
Exemple #12
0
 def buildDict(myTask, theDict):
     if JsonHelper.isContainerClass(myTask):
         dd = dict()
         myTask.getVariableMember(
             dd)  # ask the class for what it need to save
         for ch in myTask.getChildrenForXml():
             JsonHelper.buildDict(ch, dd)
         theDict[myTask.getName()] = dd
     else:
         MsgUtils.error("canno't builddict on this object")
Exemple #13
0
    def to_python(self, stream, acontext):
        super(GenMelTask, self).to_python(stream, acontext)

        # command
        command = GenMelTask._LockupMelAttr['command'].get(self, 'command')
        if command == None:
            log.error("'command' is required for a mel task")
            return

        # output
        output = GenMelTask._LockupMelAttr['output'].get(self, 'output')

        # source
        source = GenMelTask._LockupMelAttr['source'].get(self, 'source')

        module = "maya.mel"
        tab = acontext['tab']

        GenTask.do_python_module(stream, acontext, tab, module)

        if source != None:
            stream.write(("%smaya.mel.eval('" % tab) +
                         ('source "%s"' % source) + "')\n")

        res = do_clean_command(command)
        final = ""
        if res.success:
            if output == None:
                final = ("%smaya.mel.eval('" %
                         tab) + res.newCommand + "'" + res.addOn + ")"
            else:
                final = (
                    "%s%s = maya.mel.eval('" %
                    (tab, output)) + res.newCommand + "'" + res.addOn + ")"
        else:
            if output == None:
                final = ("%smaya.mel.eval('" % tab) + command + "')"
            else:
                final = ("%s%s = maya.mel.eval('" %
                         (tab, output)) + command + "')"

        evalEcho = GenMelTask._LockupMelAttr['evalEcho'].get(self, 'evalEcho')
        if evalEcho == True:
            p = re.compile("\(.*\)", re.DOTALL)
            m = p.search(final)
            if m:
                stream.write("%sprint%s\n" % (tab, m.group()))
            stream.write(final + "\n")
            if output != None:
                stream.write("%sprint 'return value " % tab + "%s' % " +
                             output + "\n")
        else:
            stream.write(final + "\n")
        return True
Exemple #14
0
    def instanciate(self, d):
        if (JsonHelper._CLASSKEY not in d or JsonHelper._MODULEKEY not in d):
            # this is a basic dict
            return d

        # create an instance
        aclass = d[JsonHelper._CLASSKEY]
        amodule = d[JsonHelper._MODULEKEY]

        if (amodule != '__builtin__'):
            cmd = "import %s" % amodule
            try:
                exec(cmd)
            except:
                traceback.print_exc()
                MsgUtils.warning("cannot import %r" % amodule)
                MsgUtils.msg("Creating a generic class container")
                amodule = "tdata"
                aclass = "container"

        cmd = "%s.%s()" % (amodule, aclass)
        newInstance = None
        try:
            newInstance = eval(cmd)
        except:
            traceback.print_exc()
            MsgUtils.error("COMMAND %r" % cmd)
            MsgUtils.msg("class definition %r not found in %r" %
                         (aclass, amodule))
            assert newInstance != None

        # name value and typevalue
        if JsonHelper._NAMEKEY in d:
            newInstance.setName(d[JsonHelper._NAMEKEY])

        if JsonHelper._VALTYPEKEY in d:
            newInstance.setTypeValue(d[JsonHelper._VALTYPEKEY])

        if JsonHelper._VALKEY in d:
            newInstance.setValue(d[JsonHelper._VALKEY])
        if JsonHelper._PROPKEY in d:
            newInstance.setVariableMember(d[JsonHelper._PROPKEY])

        if JsonHelper._CHKEY in d:
            assert type(d[JsonHelper._CHKEY]) == dict
            for k, vn in list(d[JsonHelper._CHKEY].items()):
                chInstance = self.instanciate(vn)
                if JsonHelper.isContainerClass(chInstance):
                    chInstance.setName(str(k))
                    newInstance.addChild(chInstance, False)
                else:
                    MsgUtils.error("trouble reading %r" % type(chInstance))
        return newInstance
    def to_python(self,stream,acontext):
        super(GenPyImportTask, self).to_python(stream,acontext)
        # command
        command = GenPyImportTask._LockupImportAttr['command'].get(self,'command')
        if command == None:
            log.error("'import contents' is required for an import task")
            return False

        scommand = command.split("\n")
        for c in scommand:
            stream.write("%s%s\n" % (acontext['tab'],c))
        return True
Exemple #16
0
    def print_info(self, debug=False):
        if not self.is_valid() or self.start_from_cmds == True:
            log.error("no app, cannot print anything")
            return

        log.info("project Entity %s" % self.get_project_entity())
        log.info("user_context %s" % self.get_user_context())
        log.info("status %s debug %s" %
                 (self.is_allow('Artist', debug), debug))
        log.info("config name %s" % self._app.tank.configuration_name)
        log.info("config version %s" % self._app.tank.version)
        log.info("project path %s" % self._app.tank.project_path)
Exemple #17
0
 def findChildRec(self, parent, aPathAsList):
     if len(aPathAsList) == 0:
         return parent
     for i in range(self.childCount(parent)):
         item = self.childAt(parent, i)
         if not item:
             log.error("in base_tw: findChildRec")
             return None
         if item.text(0) == aPathAsList[0]:
             if len(aPathAsList) <= 1:
                 return item
             return self.findChildRec(item,aPathAsList[1:])
     return None
Exemple #18
0
    def loadRaw(self, elmt, pTask, maxLevel):
        # foreign xml
        creationList = []
        nb = "n%d:"
        index = 0

        while elmt != None:

            if elmt.nodeType == elmt.ELEMENT_NODE:
                if maxLevel == 0:
                    return []
                if maxLevel != -1:
                    maxLevel -= 1

                if elmt.nodeName != "#text":
                    atask = tdata.container()
                    atask.setName(nb % index + elmt.nodeName)

                    pTask.addChild(atask)

                    index += 1
                    adict = {}
                    if self.getXmlAttr(elmt, adict):
                        atask.__dict__.update(adict)
                    result = self.getKidsRaw(elmt, atask, maxLevel)
                    for r in result:
                        if r[0] == "TexType":
                            atask.setValue(r[1])
                        else:
                            MsgUtils.error("not done  %r %r t=%s v=%s n=%s" %
                                           (pTask.getName(), atask.getName(),
                                            r[0], r[1], r[2]))
            elif elmt.nodeType == elmt.TEXT_NODE:
                edata = self.getTextValue(elmt).strip()
                if edata != "":
                    creationList.append(["TextType", edata, elmt.nodeName])
            elif elmt.nodeType == elmt.COMMENT_NODE:
                edata = self.getTextValue(elmt).strip()
                if edata != "":
                    creationList.append(["CommentType", edata, elmt.nodeName])

            elif elmt.nodeType == elmt.CDATA_SECTION_NODE:
                data = self.getcData(elmt)
                if data != "" and len(data.strip()) > 0:
                    creationList.append(["CdType", data, elmt.nodeName])
            else:
                MsgUtils.warning("NOT YETXX %r %r" %
                                 (elmt.nodeName, elmt.nodeType))

            elmt = elmt.nextSibling
        return creationList
 def run(self, with_log, run_dry):
     log_info = ['mxinfocreatedir']
     if with_log:
         log_info.append("ensure_folder_exists {}".format(self.parm1))
     try:
         if run_dry == False:
             FileSystemUtils.ensure_folder_exists(self.parm1, self.mode)
         success = True
         errors = []
     except Exception as e:
         log.error(str(e))
         success = False
         errors = [str(e)]
     return ResultFileProc(success, errors, log_info, None)
 def run(self, with_log, run_dry):
     log_info = ['mxinfocopy']
     if with_log:
         log_info.append("Copy File {} {}".format(self.parm1,self.parm2))
     try:
         if run_dry == False:
             FileSystemUtils.copy_file(self.parm1, self.parm2, self.mode)
         success = True
         errors = []
     except Exception as e:
         log.error(str(e))
         success = False
         errors = [str(e)]
     return ResultFileProc(success, errors, log_info, None)
Exemple #21
0
    def checkBasicPath():
        # required will exist if not found
        for path in DefaultPath.__REQUIRED__:
            if not DiskUtils.is_dir_exist(path):
                MsgUtils.error("%r (REQUIRED)" % path)
                sys.exit(1)

        for path in DefaultPath.__SELF_CREATED__:
            if not DiskUtils.is_dir_exist(path):
                MsgUtils.warning("%r needed, creating..." % path)
                if DiskUtils.create_path_rec(path) == False:
                    MsgUtils.error("can't create %r" % path)
                    sys.exit(1)
        return True
Exemple #22
0
    def install(self,
                release_top_location,
                branch="",
                do_version=False,
                new_version=False):
        """Clone an accessible remote git address to a top location by using
            name and tag to build the install area

            :param    release_top_location: (str existing branch)
            :param    branch: (str)  an optional existing branch
            :param do_version: add a tag
            :param new_version: when do_version is incremental try incremenent
            :returns ResultRepoInstall: success errors log atag

        """

        if not os.path.isdir(release_top_location):
            log.error("release area needs to exist, %s doen't" %
                      release_top_location)
            return False

        tempdir = GitUtils.get_temp_git_clone_place_dir()
        x = GitUtils(tempdir)
        tempdest = x.get_temp_zone("REPO")

        res = ""
        try:
            #The repo gets clone in this function
            res = x.clone_repo(self.src_repo, tempdest, branch)
        except Exception as e:
            log.error(str(e))
            return ResultRepoInstall(False, [str(e)], None)

        if isinstance(res, str):
            res = [res]

        for r in res:
            # most likely to belong to the output in case of failure
            if 'fatal' in r:
                return ResultRepoInstall(False, res, "")

        if new_version == True and do_version == True and branch == "":
            # query tag, increment pach tag, push tag
            self._push_new_version(tempdest)

        # copy the temp repo contain in the release area
        res = self._copy_versionned_to_area(tempdest, release_top_location,
                                            branch, do_version)
        return res
 def run(self, with_log, run_dry):
     log_info = ['mxinfocreate_userdev']
     x = None
     if with_log:
         log_info.append("ProxyEnv({})".format(self.parm1))
     try:
         if run_dry == False:
             x = ProxyEnv(self.parm1)
         success = True
         errors = []
     except Exception as e:
         log.error(str(e))
         success = False
         errors = [str(e)]
     return ResultFileProc(success, errors, log_info, x)
 def run(self, with_log, run_dry):
     log_info = ['safe_delete_file']
     x = None
     if with_log:
         log_info.append("safe_delete_file: {}".format(self.parm1))
     try:
         if run_dry == False:
             FileSystemUtils.safe_delete_file(self.parm1)
         success = True
         errors = []
     except Exception as e:
         log.error(str(e))
         success = False
         errors = [str(e)]
     return ResultFileProc(success, errors, log_info, x)
Exemple #25
0
 def __getitem__(self, item):
     if not item in self.childNames():
         if item in list(self.__dict__.keys()):
             return self.__dict__[item]
         log.error(
             "in genTree, we should throw an exception KeyError or use variable use before set... to do %s %r %r"
             % (self, self.getName(), item))
         return GenTree()
     ch = self.getChildByName(item)
     if ch == None:
         log.error(
             "in genTree, we should throw an exception KeyError  or use variable use before set... to do %s %r %r"
             % (self, self.getName().item))
         return GenTree()
     return ch
Exemple #26
0
 def OpenFileGz(self, afile, mode="r"):
     fFile = None
     if mode == "r":
         try:
             fFile = gzip.open(afile, "rb")
         except IOError:
             # can't read the file
             MsgUtils.error("Can't read %r" % afile)
             fFile = None
     else:  ## for write
         try:
             fFile = gzip.open(afile, "wb")
         except IOError:
             MsgUtils.error("Can't read %r" % afile)
             fFile = None
     return fFile
 def run(self, with_log, run_dry):
     log_info = ['copy_folder_release']
     x = None
     if with_log:
         log_info.append("copy_folder_release: {} {}".format(self.parm1,self.parm2))
     try:
         if run_dry == False:
             FileSystemUtils.copy_folder(self.parm1,
                                         self.parm2,
                                         folder_permissions=self.mode,
                                         skip_list=None)
         success = True
         errors = []
     except Exception as e:
         log.error(str(e))
         success = False
         errors = [str(e)]
     return ResultFileProc(success, errors, log_info, x)
Exemple #28
0
    def setValue(self,val,key=""):
        if type(key) == list:
            if len(key) > 0:
                kk = key[0]
                if hasattr(self,"__dict__"): 
                    if kk in self.__dict__:
                        self.__dict__[kk] = val
                        return 
                for ch in self.getChildren():
                    if kk == ch.getName():
                        ch.setValue(val,key[1:])
                        return
                MsgUtils.error("unknown key %r" % key)
            else:
                self.setValue(val)

        elif key != "":
            if hasattr(self,"__dict__"): 
                if key in self.__dict__:
                    self.__dict__[key] = val
                    return 
            path = Tdata.splitPath(key)
            if len(path) > 0:
                for ch in self.getChildren():
                    if path[0] == ch.getName():
                        ch.setValue(val,path[1:])
                        return
                MsgUtils.error("unknown key %r" % key)
            else:
                self.setValue(val)
        else:
            # temp code need works
            mvaltype = self.__TypeValue
            #ivaltype = type(val).__name__
            # need to be clean up before hack for now
            if isinstance(val,str):
                if val.find("'")!=-1:
                    val = val.replace("'","\"")
            if mvaltype in CashType:
                self.__Value = CashType[mvaltype](val)
            else:
                self.__Value = val # temporary
Exemple #29
0
    def get_source_audio_offset_with_meta_old(cls, afile=""):

        dirname = ""
        try:
            dirname = os.path.dirname(afile)
        except:
            log.error("cannot get dirname from %r" % afile)
            return ""

        pp = os.path.join(dirname, cls.SOURCE_INFO)

        if os.path.exists(pp):
            import yaml
            try:
                meta_mov = yaml.load(open(pp).read())
                return meta_mov['audio_offset']
            except:
                log.error("cannot read audio_offset %s" % pp)

        return ""
Exemple #30
0
    def start_an_app(self,
                     engine_name="tk-shell",
                     app_name="mgtk-multi-extract"):
        # THIS IS TO TEST (there is an application development context) needs work
        # it will return an engine instance if it find a current engine
        current_engine = None
        app = None
        try:
            current_engine = self.start_engine(engine_name)
            app = current_engine.apps.get(app_name)
        except Exception as e:
            log.error("couldn't start app %r for engine %r" %
                      (app_name, engine_name))
            log.error(str(e))
            return

        sg = None
        if hasattr(current_engine, "tank"):
            sg = current_engine.tank.shotgun
        if self.set_app(app, sg):
            self.start_from_cmds = True