Upload attachment to a workitem

        :param filepath: the attachment file path
        :return: the :class:`rtcclient.models.Attachment` object
        :rtype: rtcclient.models.Attachment
771223
def addAttachment(self, filepath):
        

        proj_id = self.contextId

        fa = self.rtc_obj.getFiledAgainst(self.filedAgainst,
                                          projectarea_id=proj_id)
        fa_id = fa.url.split("/")[-1]

        headers = copy.deepcopy(self.rtc_obj.headers)
        if headers.__contains__("Content-Type"):
            headers.__delitem__("Content-Type")

        filename = os.path.basename(filepath)
        fileh = open(filepath, "rb")
        files = {"attach": (filename, fileh, "application/octet-stream")}

        params = {"projectId": proj_id,
                  "multiple": "true",
                  "category": fa_id}
        req_url = "".join([self.rtc_obj.url,
                           "/service/com.ibm.team.workitem.service.",
                           "internal.rest.IAttachmentRestService/"])
        resp = self.post(req_url,
                         verify=False,
                         headers=headers,
                         proxies=self.rtc_obj.proxies,
                         params=params,
                         files=files)
        raw_data = xmltodict.parse(resp.content)
        json_body = json.loads(raw_data["html"]["body"]["textarea"])
        attachment_info = json_body["files"][0]
        return self._add_attachment_link(attachment_info)
518968
def _loadfilepath(self, filepath, **kwargs):
        
        with open(filepath, "r") as f:
            data = json.load(f, **kwargs)
        return data
1199531
def setFilepath(self, filepath):
        
        if not filepath:
            self._filepathEdit.setText('')
            return
        
        if self.normalizePath():
            filepath = os.path.normpath(nativestring(filepath))
        else:
            filepath = os.path.normpath(nativestring(filepath)).replace('\\', '/')
            
        self._filepathEdit.setText(filepath)
465110
def to_email_attachment(self, filename, filedata, **kw):
        
        maintype = "application"
        subtype = "octet-stream"

        mime_type = mimetypes.guess_type(filename)[0]
        if mime_type is not None:
            maintype, subtype = mime_type.split("/")

        attachment = MIMEBase(maintype, subtype, **kw)
        attachment.set_payload(filedata)
        encoders.encode_base64(attachment)
        attachment.add_header("Content-Disposition",
                              "attachment; filename=%s" % filename)
        return attachment
1287734
def open(self, filepath):
        
        with io.open(filepath, 'r', encoding='utf-8') as fp:
            content = fp.read()
        return content
516327
def save(self, filepath):
        # type: (str) -> None
        
        sections = [
            "Connection",
            "Proxies",
            "RedirectPolicy"]
        for section in sections:
            self._config.add_section(section)

        self._config.set("Connection", "timeout", self.connection.timeout)
        self._config.set("Connection", "verify", self.connection.verify)
        self._config.set("Connection", "cert", self.connection.cert)

        self._config.set("Proxies", "proxies", self.proxies.proxies)
        self._config.set("Proxies", "env_settings",
                         self.proxies.use_env_settings)

        self._config.set("RedirectPolicy", "allow", self.redirect_policy.allow)
        self._config.set("RedirectPolicy", "max_redirects",
                         self.redirect_policy.max_redirects)

        try:
            with open(filepath, 'w') as configfile:
                self._config.write(configfile)
        except (KeyError, EnvironmentError):
            error = "Supplied config filepath invalid."
            raise_with_traceback(ValueError, error)
        finally:
            self._clear_config()
359567
def delete(self, filepath):
        
        try:
            self.fs.delete(filepath)
            self.write({'msg':'File deleted at {}'.format(filepath)})
        except OSError:
            raise tornado.web.HTTPError(404)
1224690
def get_file(self, file_path, mode="r"):
        
        return open(self.cont_path(file_path), mode=mode)
1229604
def copy_file(self, filepath):
        
        copy_file = False
        try:
            copy_file = self.data[filepath]['copy']
        except KeyError:
            return False
        return copy_file
1068111
def load(self, filepath):
        # type: (str) -> None
        
        try:
            self._config.read(filepath)
            import ast
            self.connection.timeout = \
                self._config.getint("Connection", "timeout")
            self.connection.verify = \
                self._config.getboolean("Connection", "verify")
            self.connection.cert = \
                self._config.get("Connection", "cert")

            self.proxies.proxies = \
                ast.literal_eval(self._config.get("Proxies", "proxies"))
            self.proxies.use_env_settings = \
                self._config.getboolean("Proxies", "env_settings")

            self.redirect_policy.allow = \
                self._config.getboolean("RedirectPolicy", "allow")
            self.redirect_policy.max_redirects = \
                self._config.getint("RedirectPolicy", "max_redirects")

        except (ValueError, EnvironmentError, NoOptionError):
            error = "Supplied config file incompatible."
            raise_with_traceback(ValueError, error)
        finally:
            self._clear_config()
698867
def upload(self, wg_uuid, file_path, description=None, parent=None):
        
        url = "%(base)s/%(wg_uuid)s/nodes" % {
            'base': self.local_base_url,
            'wg_uuid': wg_uuid
        }
        param = {}
        if parent:
            # I use only the last folder uuid, the first ones are not really useful
            if isinstance(parent, (list,)):
                if len(parent) >= 1:
                    parent = parent[-1]
            param['parent'] = parent
        encode = urllib.urlencode(param)
        if encode:
            url += "?"
            url += encode
        return self.core.upload(file_path, url, description)
805439
def _add_file(self, path, **params):
        
        log = self._getparam('log', self._discard, **params)
        fd = None
        try:
            fd = os.open(path, os.O_RDONLY)
        except Exception as e:
            if not self.paths[path]:
                log.error("Open failed on watched path %r -- %s", path, e, exc_info=log.isEnabledFor(logging.DEBUG))
                raise e
            elif path in self.paths_pending:
                log.debug("path %r is still pending -- %s", path, e)
            else:
                self.paths_pending[path] = True
                log.debug("Added %r to pending list after open failure -- %s", path, e)
            return False
        if self._mode == WF_KQUEUE:
            log.debug("path %s opened as fd %d", path, fd)
            try:
                ev = select.kevent(fd,
                    filter=select.KQ_FILTER_VNODE,
                    flags=select.KQ_EV_ADD | select.KQ_EV_CLEAR,
                    fflags=select.KQ_NOTE_WRITE | select.KQ_NOTE_ATTRIB | select.KQ_NOTE_LINK |
                                select.KQ_NOTE_DELETE | select.KQ_NOTE_RENAME)
                self._kq.control([ev], 0, 0)
            except Exception as e:
                log.error("kevent failed on watched path %r -- %s", path, e)
                try: os.close(fd)
                except: pass
                raise e

        elif self._mode == WF_INOTIFYX:
            #  inotify doesn't need the target paths open, so now it is known to be
            #  accessible, close the actual fd and use the watch-descriptor as the fd.
            #
            #  However, due to an apparent simfs bug where inotify does not fire either
            #  IN_DELETE_SELF or IN_MOVE_SELF, we need to record the inode so that we
            #  can detect deletes and renames internally.  simfs is used in containers.
            #
            try:
                s = os.fstat(fd)
                self._inx_inode[path] = s.st_ino
            except Exception as e:
                log.error("fstat(%d) failed on open path %r -- %s", fd, path, e)
                try: os.close(fd)
                except: pass
                raise e
            try: os.close(fd)
            except: pass
            try:
                fd = pynotifyx.add_watch(self._inx_fd, path, self._inx_mask)
                log.debug("path %s watched with wd %d", path, fd)
            except Exception as e:
                log.error("inotify failed on watched path %r -- %s", path, e)
                raise e

        elif self._mode == WF_POLLING:
            log.debug("path %s opened as fd %d", path, fd)
            fstate = self._poll_get_stat(fd, path)
            if fstate:
                self._poll_stat[fd] = fstate

        self.paths_open[path] = fd
        self.fds_open[fd] = path
        return True
1163683
def load(filepath):
        '''
        
        '''

        try:
            with open(filepath, "r") as fh:
                source = fh.read()
        except Exception as e:
            return None, e
        return source, None
252879
def add_file_path_in_work_tree(self, path, work_tree, verbose=True):
        
        args = ['--work-tree', work_tree, 'add', '-f']
        if verbose:
            args.append('--verbose')
        args.append(path)
        self.command_exec(args, show_output=verbose)
862823
def stage_import_from_filesystem(self, filepath):
        
        schema = ImportSchema()
        resp = self.service.post(self.base,
                                 params={'path': filepath})
        return self.service.decode(schema, resp)
1140898
def upload_file(self, container, src_file_path, dst_name=None, put=True,
                    content_type=None):
        """"""
        if not os.path.exists(src_file_path):
            raise RuntimeError('file not found: ' + src_file_path)
        if not dst_name:
            dst_name = os.path.basename(src_file_path)
        if not content_type:
            content_type = "application/octet.stream"
        headers = dict(self._base_headers)
        if content_type:
            headers["content-length"] = content_type
        else:
            headers["content-length"] = "application/octet.stream"
        headers["content-length"] = str(os.path.getsize(src_file_path))
        headers['content-disposition'] = 'attachment; filename=' + dst_name
        if put:
            method = 'PUT'
            url = self.make_url(container, dst_name, None)
        else:
            method = 'POST'
            url = self.make_url(container, None, None)
        with open(src_file_path, 'rb') as up_file:
            try:
                rsp = requests.request(method, url, headers=headers,
                                       data=up_file, timeout=self._timeout)
            except requests.exceptions.ConnectionError as e:
                RestHttp._raise_conn_error(e)

        return self._handle_response(rsp)
844050
def attach_related_file(self, path, mimetype=None):
        """"""
        filename = os.path.basename(path)
        content = open(path, 'rb').read()
        self.attach_related(filename, content, mimetype)