code
stringlengths
1
18.2k
def _report(self, action, key_mapper=mappers._report_key_mapper): '''Return the dictionary of **kwargs with the correct datums attribute names and data types for the top level of the report, and return the nested levels separately. ''' _top_level = [ k for k, v in self.report.items() if not isinstance(v, dict)] _nested...
for key in _nested_level: nested_levels_dict[key] = self.report[key] # Add the parent report ID nested_levels_dict[key][ 'reportUniqueIdentifier'] = mappers._key_type_mapper[ 'uniqueIdentifier'](str(self.report['uniqueIdentifier'])) if key == 'placemark': # Add the parent location report UUID nested_levels_dict[key][ '...
def write_to_file(path_file, callback): """ Reads the content of the given file, puts the content into the callback and writes the result back to the file. :param path_file: the path to the file :type path_file: str :param callback: the callback function :type callback: function """ try: with open(path_file, 'r+', enco...
def is_disjoint(self,other): """ Check whether two Intervals are disjoint. :param Interval other: The Interval to check disjointedness with. """ if self.is_empty() or other.is_empty(): return True if self.bounds[0] < other.bounds[0]: i1,i2 = self,other elif self.bounds[0] > other.bounds[0]: i2,i1 = self,other else: #co...
def intersection(self,other): """ Return a new Interval with the intersection of the two intervals, i.e. all elements that are in both self and other. :param Interval other: Interval to intersect with :rtype: Interval """ if self.bounds[0] < other.bounds[0]: i1,i2 = self,other else: i2,i1 = self,other if self.is_disjoi...
def is_empty(self): """ Check whether this interval is empty. :rtype: bool """ if self.bounds[1] < self.bounds[0]: return True if self.bounds[1] == self.bounds[0]: return not (self.included[0] and self.included[1])
def is_discrete(self): """ Check whether this interval contains exactly one number :rtype: bool """ return self.bounds[1] == self.bounds[0] and\ self.included == (True,True)
def iter_members(self): """ Iterate over all elements of the set. :raises ValueError: if self is a set of everything """ if not self.is_discrete(): raise ValueError("non-discrete IntervalSet can not be iterated") for i in self.ints: yield i.get_point()
def intersection(self,other): """ Return a new IntervalSet with the intersection of the two sets, i.e. all elements that are both in self and other. :param IntervalSet other: Set to intersect with :rtype: IntervalSet """ res = [] for i1 in self.ints: for i2 in other.ints: res.append(i1.intersection(i2)) return Interval...
def difference(self,other): """ Return a new IntervalSet with the difference of the two sets, i.e. all elements that are in self but not in other. :param IntervalSet other: Set to subtract :rtype: IntervalSet """ res = IntervalSet.everything() for j in other.ints: tmp = [] for i in self.ints: tmp.extend(i._difference(j...
def intersection(self,other): """ Return a new DiscreteSet with the intersection of the two sets, i.e. all elements that are in both self and other. :param DiscreteSet other: Set to intersect with :rtype: DiscreteSet """ if self.everything: if other.everything: return DiscreteSet() else: return DiscreteSet(other.elemen...
def difference(self,other): """ Return a new DiscreteSet with the difference of the two sets, i.e. all elements that are in self but not in other. :param DiscreteSet other: Set to subtract :rtype: DiscreteSet :raises ValueError: if self is a set of everything """ if self.everything: raise ValueError("Can not remove fro...
def union(self,other): """ Return a new DiscreteSet with the union of the two sets, i.e. all elements that are in self or in other. :param DiscreteSet other: Set to unite with :rtype: DiscreteSet """ if self.everything: return self elif other.everything: return other else: return DiscreteSet(self.elements.union(other.e...
def iter_members(self): """ Iterate over all elements of the set. :raises ValueError: if self is a set of everything """ if self.everything: raise ValueError("Can not iterate everything") for coord in sorted(self.elements): yield coord
def intersection(self,other): "intersection with another patch" res = {} if set(self.sets.keys()) != set(other.sets.keys()): raise KeyError('Incompatible patches in intersection') for name,s1 in self.sets.items(): s2 = other.sets[name] res[name] = s1.intersection(s2) return Patch(res)
def iter_points(self): "returns a list of tuples of names and values" if not self.is_discrete(): raise ValueError("Patch is not discrete") names = sorted(self.sets.keys()) icoords = [self.sets[name].iter_members() for name in names] for coordinates in product(*icoords): yield tuple(zip(names,coordinates))
def update_form_labels(self, request=None, obj=None, form=None): """Returns a form obj after modifying form labels referred to in custom_form_labels. """ for form_label in self.custom_form_labels: if form_label.field in form.base_fields: label = form_label.get_form_label( request=request, obj=obj, model=self.model, for...
def open_filezip(file_path, find_str): """ Open the wrapped file. Read directly from the zip without extracting its content. """ if zipfile.is_zipfile(file_path): zipf = zipfile.ZipFile(file_path) interesting_files = [f for f in zipf.infolist() if find_str in f] for inside_file in interesting_files: yield zipf.open(ins...
def extract_filezip(path_to_file, dest_path, target_zipfiles=None): """ Extract file zip to destiny path folder targeting only some kind of files. """ target_zipfiles = ['.*'] if target_zipfiles is None else target_zipfiles files = [] _, ext = os.path.splitext(path_to_file) if ext == '.zip': file = open(path_to_file, '...
def download_file(url, destination, **kwargs): """ Download file process: - Open the url - Check if it has been downloaded and it hanged. - Download it to the destination folder. Args: :urls: url to take the file. :destionation: place to store the downloaded file. """ web_file = open_remote_url(url, **kwargs) file_size...
def open_remote_url(urls, **kwargs): """Open the url and check that it stores a file. Args: :urls: Endpoint to take the file """ if isinstance(urls, str): urls = [urls] for url in urls: try: web_file = requests.get(url, stream=True, **kwargs) if 'html' in web_file.headers['content-type']: raise ValueError("HTML source ...
def is_remote_file_modified(web_file, destination): """ Check if online file has been modified. Args: :web_file: online file to check. :destination: path of the offline file to compare. """ try: # check datetime of last modified in file. last_mod = web_file.headers.get('last-modified') if last_mod: web_file_time = time...
def copy_remote_file(web_file, destination): """ Check if exist the destination path, and copy the online resource file to local. Args: :web_file: reference to online file resource to take. :destination: path to store the file. """ size = 0 dir_name = os.path.dirname(destination) if not os.path.exists(dir_name): os.mak...
def remove_file(paths): """ Remove file from paths introduced. """ for path in force_list(paths): if os.path.exists(path): os.remove(path)
def generate_headers(self, client_type, client_id, secret): """ generate_headers is used to generate the headers automatically for your http request :param client_type (str): remoteci or feeder :param client_id (str): remoteci or feeder id :param secret (str): api secret :return: Authorization headers (dict) """ self.r...
def addLadder(settings): """define a new Ladder setting and save to disk file""" ladder = Ladder(settings) ladder.save() getKnownLadders()[ladder.name] = ladder return ladder
def delLadder(name): """forget about a previously defined Ladder setting by deleting its disk file""" ladders = getKnownLadders() try: ladder = ladders[name] os.remove(ladder.filename) # delete from disk del ladders[name] # deallocate object return ladder except KeyError: raise ValueError("given ladder name '%s' is not...
def getKnownLadders(reset=False): """identify all of the currently defined ladders""" if not ladderCache or reset: jsonFiles = os.path.join(c.LADDER_FOLDER, "*.json") for ladderFilepath in glob.glob(jsonFiles): filename = os.path.basename(ladderFilepath) name = re.search("^ladder_(.*?).json$", filename).groups()[0] lad...
def load(cls, json_file_path, schema=None): """ :param str json_file_path: Path to the JSON file to be read. :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON. :rtype: dictionary :raises ImportError: :raises InvalidFilePathError: :raises FileNotFoundError: :raises Runti...
def loads(cls, json_text, schema=None): """ :param str json_text: json text to be parse :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON :rtype: dictionary :raises ImportError: :raises RuntimeError: :raises ValueError: """ try: json_text = json_text.decode("ascii") exc...
def get_samples(self, sample_count): """ Fetch a number of samples from self.wave_cache Args: sample_count (int): Number of samples to fetch Returns: ndarray """ if self.amplitude.value <= 0: return None # Build samples by rolling the period cache through the buffer rolled_array = numpy.roll(self.wave_cache, -1 * self....
def _cmp_key(self, obj=None): """Comparison key for sorting results from all linters. The sort should group files and lines from different linters to make it easier for refactoring. """ if not obj: obj = self line_nr = int(obj.line_nr) if obj.line_nr else 0 col = int(obj.col) if obj.col else 0 return (obj.path, line_nr...
def command_with_options(self): """Add arguments from config to :attr:`command`.""" if 'args' in self.config: return ' '.join((self.command, self.config['args'])) return self.command
def _get_relative_path(self, full_path): """Return the relative path from current path.""" try: rel_path = Path(full_path).relative_to(Path().absolute()) except ValueError: LOG.error("%s: Couldn't find relative path of '%s' from '%s'.", self.name, full_path, Path().absolute()) return full_path return str(rel_path)
def _parse_by_pattern(self, lines, pattern): """Match pattern line by line and return Results. Use ``_create_output_from_match`` to convert pattern match groups to Result instances. Args: lines (iterable): Output lines to be parsed. pattern: Compiled pattern to match against lines. result_fn (function): Receive results...
def _create_output_from_match(self, match_result): """Create Result instance from pattern match results. Args: match: Pattern match. """ if isinstance(match_result, dict): return LinterOutput(self.name, **match_result) return LinterOutput(self.name, *match_result)
def get_single_file_info(self, rel_path): """ Gets last change time for a single file """ f_path = self.get_full_file_path(rel_path) return get_single_file_info(f_path, rel_path)
def read_local_manifest(self): """ Read the file manifest, or create a new one if there isn't one already """ manifest = file_or_default(self.get_full_file_path(self.manifest_file), { 'format_version' : 2, 'root' : '/', 'have_revision' : 'root', 'files' : {}}, json.loads) if 'format_version' not in manifest or manifest...
def fs_put(self, rpath, data): """ Add a file to the FS """ try: self.begin() # Add the file to the fs self.file_put_contents(rpath, data) # Add to the manifest manifest = self.read_local_manifest() manifest['files'][rpath] = self.get_single_file_info(rpath) self.write_local_manifest(manifest) self.commit() except: sel...
def respond_to_SIGTERM(signal_number, frame, target=None): """ these classes are instrumented to respond to a KeyboardInterrupt by cleanly shutting down. This function, when given as a handler to for a SIGTERM event, will make the program respond to a SIGTERM as neatly as it responds to ^C. This function is used in reg...
SIGTERM') # by setting the quit flag to true, any calls to the 'quit_check' # method that is so liberally passed around in this framework will # result in raising the quit exception. The current quit exception # is KeyboardInterrupt target.task_manager.quit = True else: raise KeyboardInterrupt
def _get_iterator(self): """The iterator passed in can take several forms: a class that can be instantiated and then iterated over; a function that when called returns an iterator; an actual iterator/generator or an iterable collection. This function sorts all that out and returns an iterator that can be used""" try: r...
def _responsive_sleep(self, seconds, wait_log_interval=0, wait_reason=''): """When there is litte work to do, the queuing thread sleeps a lot. It can't sleep for too long without checking for the quit flag and/or logging about why it is sleeping. parameters: seconds - the number of seconds to sleep wait_log_interval - ...
if wait_log_interval and not x % wait_log_interval: self.logger.info('%s: %dsec of %dsec', wait_reason, x, seconds) self.quit_check() time.sleep(1.0)
def blocking_start(self, waiting_func=None): """this function starts the task manager running to do tasks. The waiting_func is normally used to do something while other threads are running, but here we don't have other threads. So the waiting func will never get called. I can see wanting this function to be called at l...
quit request') finally: self.quit = True self.logger.debug("ThreadlessTaskManager dies quietly")
def makePartitions(self): """Make partitions with gmane help. """ class NetworkMeasures: pass self.nm=nm=NetworkMeasures() nm.degrees=self.network.degree() nm.nodes_= sorted(self.network.nodes(), key=lambda x : nm.degrees[x]) nm.degrees_=[nm.degrees[i] for i in nm.nodes_] nm.edges= self.network.edges(data=True) nm.E=se...
def makeImages(self): """Make spiral images in sectors and steps. Plain, reversed, sectorialized, negative sectorialized outline, outline reversed, lonely only nodes, only edges, both """ # make layout self.makeLayout() self.setAgraph() # make function that accepts a mode, a sector # and nodes and edges True and False ...
def plotGraph(self,mode="plain",nodes=None,filename="tgraph.png"): """Plot graph with nodes (iterable) into filename """ if nodes==None: nodes=self.nodes else: nodes=[i for i in self.nodes if i in nodes] for node in self.nodes: n_=self.A.get_node(node) if mode=="plain": nmode=1 else: nmode=-1 pos="{},{}".format(self.xi...
def makeSong(self): """Render abstract animation """ self.makeVisualSong() self.makeAudibleSong() if self.make_video: self.makeAnimation()
def makeVisualSong(self): """Return a sequence of images and durations. """ self.files=os.listdir(self.basedir) self.stairs=[i for i in self.files if ("stair" in i) and ("R" in i)] self.sectors=[i for i in self.files if "sector" in i] self.stairs.sort() self.sectors.sort() filenames=[self.basedir+i for i in self.sector...
def makeAudibleSong(self): """Use mass to render wav soundtrack. """ sound0=n.hstack((sy.render(220,d=1.5), sy.render(220*(2**(7/12)),d=2.5), sy.render(220*(2**(-5/12)),d=.5), sy.render(220*(2**(0/12)),d=1.5), )) sound1=n.hstack((sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), sy.render(220*(2**(0/1...
def makeAnimation(self): """Use pymovie to render (visual+audio)+text overlays. """ aclip=mpy.AudioFileClip("sound.wav") self.iS=self.iS.set_audio(aclip) self.iS.write_videofile("mixedVideo.webm",15,audio=True) print("wrote "+"mixedVideo.webm")
def cutoff_filename(prefix, suffix, input_str): """ Cuts off the start and end of a string, as specified by 2 parameters Parameters ---------- prefix : string, if input_str starts with prefix, will cut off prefix suffix : string, if input_str end with suffix, will cut off suffix input_str : the string to be processed R...
def get_frame_src(f:Frame) -> str: ''' inspects a frame and returns a string with the following <src-path>:<src-line> -> <function-name> <source-code> ''' path, line, src, fn = _get_frame( inspect.getframeinfo(f) ) return '{}:{} -> {}\n{}'.format( path.split(os.sep)[-1], line, fn, repr(src[0][:-1]) # shave off \n )
def get_locals(f:Frame) -> str: ''' returns a formatted view of the local variables in a frame ''' return pformat({i:f.f_locals[i] for i in f.f_locals if not i.startswith('__')})
def default_profiler(f:Frame, _type:str, _value:Any): ''' inspects an input frame and pretty prints the following: <src-path>:<src-line> -> <function-name> <source-code> <local-variables> ---------------------------------------- ''' try: profile_print( '\n'.join([ get_frame_src(f), get_locals(f), '---------------------...
def trace(fn=None, profiler=None) -> Callable: ''' This decorator allows you to visually trace the steps of a function as it executes to see what happens to the data as things are being processed. If you want to use a custom profiler, use the @trace(profiler=my_custom_profiler) syntax. Example Usage: def count_to(targe...
@trace profiler = default_profiler # validate input assert callable(fn) assert callable(profiler) # build the decorator @wraps(fn) def wrapper(*args, **kwargs): # flag for default_profiler to know to ignore this scope wafflestwaffles = None # save the previous profiler old_profiler = sys.getprofile() # set the new prof...
def on_close(self, filename): """Move this file to destination folder.""" shutil.move(filename, self.destination_folder) path, fn = os.path.split(filename) return os.path.join(self.destination_folder, fn)
def getAllRegexp(): ''' Method that recovers ALL the list of <RegexpObject> classes to be processed.... :return: Returns a list [] of <RegexpObject> classes. ''' logger = logging.getLogger("entify") logger.debug("Recovering all the available <RegexpObject> classes.") listAll = [] # For demo only #listAll.append(Demo())...
def getAllRegexpNames(regexpList = None): ''' Method that recovers the names of the <RegexpObject> in a given list. :param regexpList: list of <RegexpObject>. If None, all the available <RegexpObject> will be recovered. :return: Array of strings containing the available regexps. ''' if regexpList == None: regexpList = ...
def getRegexpsByName(regexpNames = ['all']): ''' Method that recovers the names of the <RegexpObject> in a given list. :param regexpNames: list of strings containing the possible regexp. :return: Array of <RegexpObject> classes. ''' allRegexpList = getAllRegexp() if 'all' in regexpNames: return allRegexpList regexpList...
def from_str(cls: Type[CRCPubkeyType], crc_pubkey: str) -> CRCPubkeyType: """ Return CRCPubkey instance from CRC public key string :param crc_pubkey: CRC public key :return: """ data = CRCPubkey.re_crc_pubkey.match(crc_pubkey) if data is None: raise Exception("Could not parse CRC public key {0}".format(crc_pubkey)) pub...
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType: """ Return CRCPubkey instance from public key string :param pubkey: Public key :return: """ hash_root = hashlib.sha256() hash_root.update(base58.b58decode(pubkey)) hash_squared = hashlib.sha256() hash_squared.update(hash_root.digest()) b58_checksu...
def is_valid(self) -> bool: """ Return True if CRC is valid :return: """ return CRCPubkey.from_pubkey(self.pubkey).crc == self.crc
def delete(self): """Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id""" if self.parent is None: raise RuntimeError( "Current statement has no parent, so it cannot " + "be deleted form a procmailrc structure" ) elif self.id...
def get_office365edu_prod_subs(netid): """ Return a restclients.models.uwnetid.Subscription objects on the given uwnetid """ subs = get_netid_subscriptions(netid, Subscription.SUBS_CODE_OFFICE_365) if subs is not None: for subscription in subs: if (subscription.subscription_code == Subscription.SUBS_CODE_OFFICE_365): r...
def _metahash(self): """Include genrule cmd in the metahash.""" if self._cached_metahash: return self._cached_metahash mhash = base.BaseBuilder._metahash(self) log.debug('[%s]: Metahash input: cmd="%s"', self.address, self.cmd) mhash.update(self.cmd) self._cached_metahash = mhash return mhash
def expand_cmd_labels(self): """Expand make-style variables in cmd parameters. Currently: $(location <foo>) Location of one dependency or output file. $(locations <foo>) Space-delimited list of foo's output files. $(SRCS) Space-delimited list of this rule's source files. $(OUTS) Space-delimited list of this rule's outp...
# Expand $(location foo) and $(locations foo): label = None tagstr = re_match.groups()[0] tag_location = re.match( r'\s*location\s+([A-Za-z0-9/\-_:\.]+)\s*', tagstr) tag_locations = re.match( r'\s*locations\s+([A-Za-z0-9/\-_:\.]+)\s*', tagstr) if tag_location: label = tag_location.groups()[0] elif tag_locations: label ...
len(paths) > 1 and tag_location: raise error.TargetBuildFailed( self.address, 'Bad substitution in cmd: Expected exactly one ' 'file, but %s expands to %s files.' % ( addr, len(paths))) else: return ' '.join( [os.path.join(self.buildroot, x) for x in paths]) # Expand $(OUTS): elif re.match(r'OUTS', tagstr): return ' '....
substitutions. cmd, _ = re.subn(self.noparen_tag_re, _expand_makevar, cmd) # Now that we're done looking for $(blabla) and $bla parameters, clean # up any $$ escaping: cmd, _ = re.subn(r'\$\$', '$', cmd) # Maybe try heuristic label expansion? Actually on second thought # that's a terrible idea. Use the explicit syntax,...
def output_files(self): """Returns list of output files from this rule, relative to buildroot. In this case it's simple (for now) - the output files are enumerated in the rule definition. """ outs = [os.path.join(self.address.repo, self.address.path, x) for x in self.params['outs']] return outs
def parse(self, response): ''' 根据对 ``start_urls`` 中提供链接的请求响应包内容,解析生成具体文章链接请求 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content_raw = response.body.decode() self.logger.debug('响应body原始数据:{}'.format(content_raw)) content = json.loads(content_raw, encoding='UTF-8') self.logger.debug(content) # 文章发布日期 date = ...
def parse_post(self, response): ''' 根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容, 并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content = json.loads(response.body.decode(), encoding='UTF-8') post = response.meta['post'] post['origin_url'] = content.get('share_url'...
def closed(self, reason): ''' 异步爬取全部结束后,执行此关闭方法,对 ``item_list`` 中的数据进行 **JSON** 序列化,并输出到指定文件中,传递给 :meth:`.ZhihuDaily.crawl` :param obj reason: 爬虫关闭原因 ''' self.logger.debug('结果列表: {}'.format(self.item_list)) output_strings = json.dumps(self.item_list, ensure_ascii=False) with open(self.output_file, 'w') as fh: fh.write(...
def get_current_branch(self) -> str: """ :return: current branch :rtype: str """ current_branch: str = self.repo.active_branch.name LOGGER.debug('current branch: %s', current_branch) return current_branch
def tag(self, tag: str, overwrite: bool = False) -> None: """ Tags the current commit :param tag: tag :type tag: str :param overwrite: overwrite existing tag :type overwrite: bool """ LOGGER.info('tagging repo: %s', tag) try: self.repo.create_tag(tag) except GitCommandError as exc: if 'already exists' in exc.stderr and...
def list_tags(self, pattern: str = None) -> typing.List[str]: """ Returns list of tags, optionally matching "pattern" :param pattern: optional pattern to filter results :type pattern: str :return: existing tags :rtype: list of str """ tags: typing.List[str] = [str(tag) for tag in self.repo.tags] if not pattern: LOGGER....
def remove_tag(self, *tag: str): """ Removes tag(s) from the rpo :param tag: tags to remove :type tag: tuple """ LOGGER.info('removing tag(s) from repo: %s', tag) self.repo.delete_tag(*tag)
def is_on_tag(self) -> bool: """ :return: True if latest commit is tagged :rtype: bool """ if self.get_current_tag(): LOGGER.debug('latest commit is tagged') return True LOGGER.debug('latest commit is NOT tagged') return False
def get_current_tag(self) -> typing.Optional[str]: """ :return: tag name if current commit is on tag, else None :rtype: optional str """ tags = list(self.repo.tags) if not tags: LOGGER.debug('no tag found') return None for tag in tags: LOGGER.debug('tag found: %s; comparing with commit', tag) if tag.commit == self.late...
def stash(self, stash_name: str): """ Stashes the current working tree changes :param stash_name: name of the stash :type stash_name: str """ if self.stashed: LOGGER.error('already stashed') sys.exit(-1) else: if not self.index_is_empty(): LOGGER.error('cannot stash; index is not empty') sys.exit(-1) if self.untracked_...
def unstash(self): """ Pops the last stash if EPAB made a stash before """ if not self.stashed: LOGGER.error('no stash') else: LOGGER.info('popping stash') self.repo.git.stash('pop') self.stashed = False
def ensure(): """ Makes sure the current working directory is a Git repository. """ LOGGER.debug('checking repository') if not os.path.exists('.git'): LOGGER.error('This command is meant to be ran in a Git repository.') sys.exit(-1) LOGGER.debug('repository OK')
def last_commit_msg(self) -> str: """ :return: last commit message :rtype: str """ last_msg: str = self.latest_commit().message.rstrip() LOGGER.debug('last msg: %s', last_msg) return last_msg
def untracked_files(self) -> typing.List[str]: """ :return: of untracked files :rtype: list """ untracked_files = list(self.repo.untracked_files) LOGGER.debug('untracked files: %s', untracked_files) return untracked_files
def status(self) -> str: """ :return: Git status :rtype: str """ status: str = self.repo.git.status() LOGGER.debug('git status: %s', status) return status
def list_staged_files(self) -> typing.List[str]: """ :return: staged files :rtype: list of str """ staged_files: typing.List[str] = [x.a_path for x in self.repo.index.diff('HEAD')] LOGGER.debug('staged files: %s', staged_files) return staged_files
def index_is_empty(self) -> bool: """ :return: True if index is empty (no staged changes) :rtype: bool """ index_empty: bool = len(self.repo.index.diff(self.repo.head.commit)) == 0 LOGGER.debug('index is empty: %s', index_empty) return index_empty
def changed_files(self) -> typing.List[str]: """ :return: changed files :rtype: list of str """ changed_files: typing.List[str] = [x.a_path for x in self.repo.index.diff(None)] LOGGER.debug('changed files: %s', changed_files) return changed_files
def stage_all(self): """ Stages all changed and untracked files """ LOGGER.info('Staging all files') self.repo.git.add(A=True)
def stage_modified(self): """ Stages modified files only (no untracked) """ LOGGER.info('Staging modified files') self.repo.git.add(u=True)
def stage_subset(self, *files_to_add: str): """ Stages a subset of files :param files_to_add: files to stage :type files_to_add: str """ LOGGER.info('staging files: %s', files_to_add) self.repo.git.add(*files_to_add, A=True)
def add_skip_ci_to_commit_msg(message: str) -> str: """ Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message :param message: commit message :type message: str :return: edited commit message :rtype: str """ first_line_index = message.find('\n') if first_line_index == -1: edited_message = message +...
def commit( self, message: str, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, allow_empty: bool = False, ): """ Commits changes to the repo :param message: first line of the message :type message: str :param files_to_add: files to commit :type files_to_add: optional list of str :param allow...
def amend_commit( self, append_to_msg: typing.Optional[str] = None, new_message: typing.Optional[str] = None, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, ): """ Amends last commit with either an entirely new commit message, or an edited version of the previous one Note: it is an error to ...
LOGGER.info('going back one commit') branch = self.repo.head.reference try: branch.commit = self.repo.head.commit.parents[0] except IndexError: LOGGER.error('cannot amend the first commit') sys.exit(-1) if files_to_add: self.stage_subset(*files_to_add) else: self.stage_all() self.repo.index.commit(message, skip_hooks=T...
def merge(self, ref_name: str): """ Merges two refs Args: ref_name: ref to merge in the current one """ if self.is_dirty(): LOGGER.error('repository is dirty; cannot merge: %s', ref_name) sys.exit(-1) LOGGER.info('merging ref: "%s" into branch: %s', ref_name, self.get_current_branch()) self.repo.git.merge(ref_name)