Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def check_bot(task_type=SYSTEM_TASK):
if glb.wxbot.bot.alive:
msg = generate_run_info()
message = Message(content=msg, receivers='status')
glb.wxbot.send_msg(message)
_logger.info(
'{0} Send status message {1} at {2:%Y-%m-%d %H:%M:%S}'.format(task_type, msg, datetime.datetime.now()))
else:
# todo
pass | [
"\n wxpy bot 健康检查任务\n "
] |
Please provide a description of the function:def timeout_message_report():
timeout_list = glb.ioloop._timeouts
delay_task = []
for timeout in timeout_list:
if not timeout.callback:
continue
if len(timeout.callback.args) == 2:
task_type, message = timeout.callback.args
delay_task.append(message)
msg = '当前已注册延时消息共有{0}条'.format(len(delay_task))
for i, itm in enumerate(delay_task):
msg = '{pre}\n[ID (序号) ]:D{index}\n[消息接收]:{receiver}\n[发送时间]:{remind}\n[消息时间]:{time}\n[消息标题]:{message}\n'.format(
pre=msg, index=i, remind=itm.remind, time=itm.time, message=itm.title or itm.content, receiver=itm.receiver)
interval_task = [(periodic.callback.args[1], periodic.is_running()) for periodic in glb.periodic_list if
len(periodic.callback.args) == 2 and periodic.callback.args[0] == PERIODIC_TASK]
msg = '{0}\n当前已注册周期消息共有{1}条'.format(msg, len(interval_task))
for i, itm in enumerate(interval_task):
msg = '{pre}\n[ID (序号) ]:P{index}\n[消息接收]:{receiver}\n[运行状态]:{status}\n[发送周期]:{interval}\n[消息标题]:{message}\n'.format(
pre=msg, index=i, interval=itm[0].interval, status='已激活' if itm[1] else '未激活',
message=itm[0].title or itm[0].content, receiver=itm[0].receiver)
return msg | [
"\n 周期/延时 消息报告\n "
] |
Please provide a description of the function:def register_listener_handle(wxbot):
from wxpy import TEXT
@wxbot.bot.register(wxbot.default_receiver, TEXT, except_self=False)
def sender_command_handle(msg):
command_dict = {MESSAGE_REPORT_COMMAND: timeout_message_report(),
MESSAGE_STATUS_COMMAND: generate_run_info()}
message = command_dict.get(msg.text, None)
if message:
return message
myself = wxbot.bot.registered.get_config(msg)
registered_copy = copy.copy(wxbot.bot.registered)
registered_copy.remove(myself)
pre_conf = registered_copy.get_config(msg)
if pre_conf:
my_name = sys._getframe().f_code.co_name
if my_name != pre_conf.func.__name__:
pre_conf.func(msg) | [
"\n wechat_sender 向 wxpy 注册控制消息 handler\n "
] |
Please provide a description of the function:def listen(bot, receivers=None, token=None, port=10245, status_report=False, status_receiver=None,
status_interval=DEFAULT_REPORT_TIME):
global glb
periodic_list = []
app = Application()
wxbot = WxBot(bot, receivers, status_receiver)
register_listener_handle(wxbot)
process = psutil.Process()
app.listen(port)
if status_report:
if isinstance(status_interval, datetime.timedelta):
status_interval = status_interval.seconds * 1000
check_periodic = tornado.ioloop.PeriodicCallback(functools.partial(check_bot, SYSTEM_TASK), status_interval)
check_periodic.start()
periodic_list.append(check_periodic)
glb = Global(wxbot=wxbot, run_info=process, periodic_list=periodic_list, ioloop=tornado.ioloop.IOLoop.instance(),
token=token)
tornado.ioloop.IOLoop.current().start() | [
"\n 传入 bot 实例并启动 wechat_sender 服务\n\n :param bot: (必填|Bot对象) - wxpy 的 Bot 对象实例\n :param receivers: (选填|wxpy.Chat 对象|Chat 对象列表) - 消息接收者,wxpy 的 Chat 对象实例, 或 Chat 对象列表,如果为 list 第一个 Chat 为默认接收者。如果为 Chat 对象,则默认接收者也是此对象。 不填为当前 bot 对象的文件接收者\n :param token: (选填|str) - 信令,防止 receiver 被非法滥用,建议加上 token 防止非法使用,如果使用 token 请在初始化 `Sender()` 时也使用统一 token,否则无法发送。token 建议为 32 位及以上的无规律字符串\n :param port: (选填|int) - 监听端口, 监听端口默认为 10245 ,如有冲突或特殊需要请自行指定,需要和 `Sender()` 统一\n :param status_report: (选填|bool) - 是否开启状态报告,如果开启,wechat_sender 将会定时发送状态信息到 status_receiver\n :param status_receiver: (选填|Chat 对象) - 指定 status_receiver,不填将会发送状态消息给默认接收者\n :param status_interval: (选填|int|datetime.timedelta) - 指定状态报告发送间隔时间,为 integer 时代表毫秒\n\n "
] |
Please provide a description of the function:def run(
target,
target_type,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
pull=None,
insecure=False,
skips=None,
timeout=None,
):
_set_logging(level=logging_level)
logger.debug("Checking started.")
target = Target.get_instance(
target=target,
logging_level=logging_level,
pull=pull,
target_type=target_type,
insecure=insecure,
)
checks_to_run = _get_checks(
target_type=target.__class__,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
)
result = go_through_checks(target=target, checks=checks_to_run, timeout=timeout)
return result | [
"\n Runs the sanity checks for the target.\n\n :param timeout: timeout per-check (in seconds)\n :param skips: name of checks to skip\n :param target: str (image name, ostree or dockertar)\n or ImageTarget\n or path/file-like object for dockerfile\n :param target_type: string, either image, dockerfile, dockertar\n :param tags: list of str (if not None, the checks will be filtered by tags.)\n :param ruleset_name: str (e.g. fedora; if None, default would be used)\n :param ruleset_file: fileobj instance holding ruleset configuration\n :param ruleset: dict, content of a ruleset file\n :param logging_level: logging level (default logging.WARNING)\n :param checks_paths: list of str, directories where the checks are present\n :param pull: bool, pull the image from registry\n :param insecure: bool, pull from an insecure registry (HTTP/invalid TLS)\n :return: Results instance\n "
] |
Please provide a description of the function:def get_checks(
target_type=None,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
skips=None,
):
_set_logging(level=logging_level)
logger.debug("Finding checks started.")
return _get_checks(
target_type=target_type,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
) | [
"\n Get the sanity checks for the target.\n\n :param skips: name of checks to skip\n :param target_type: TargetType enum\n :param tags: list of str (if not None, the checks will be filtered by tags.)\n :param ruleset_name: str (e.g. fedora; if None, default would be used)\n :param ruleset_file: fileobj instance holding ruleset configuration\n :param ruleset: dict, content of a ruleset file\n :param logging_level: logging level (default logging.WARNING)\n :param checks_paths: list of str, directories where the checks are present\n :return: list of check instances\n "
] |
Please provide a description of the function:def _set_logging(
logger_name="colin",
level=logging.INFO,
handler_class=logging.StreamHandler,
handler_kwargs=None,
format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s',
date_format='%H:%M:%S'):
if level != logging.NOTSET:
logger = logging.getLogger(logger_name)
logger.setLevel(level)
# do not readd handlers if they are already present
if not [x for x in logger.handlers if isinstance(x, handler_class)]:
handler_kwargs = handler_kwargs or {}
handler = handler_class(**handler_kwargs)
handler.setLevel(level)
formatter = logging.Formatter(format, date_format)
handler.setFormatter(formatter)
logger.addHandler(handler) | [
"\n Set personal logger for this library.\n\n :param logger_name: str, name of the logger\n :param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler\n :param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)\n :param handler_kwargs: dict, keyword arguments to handler's constructor\n :param format: str, formatting style\n :param date_format: str, date style in the logs\n "
] |
Please provide a description of the function:def check_label(labels, required, value_regex, target_labels):
present = target_labels is not None and not set(labels).isdisjoint(set(target_labels))
if present:
if required and not value_regex:
return True
elif value_regex:
pattern = re.compile(value_regex)
present_labels = set(labels) & set(target_labels)
for l in present_labels:
if not bool(pattern.search(target_labels[l])):
return False
return True
else:
return False
else:
return not required | [
"\n Check if the label is required and match the regex\n\n :param labels: [str]\n :param required: bool (if the presence means pass or not)\n :param value_regex: str (using search method)\n :param target_labels: [str]\n :return: bool (required==True: True if the label is present and match the regex if specified)\n (required==False: True if the label is not present)\n "
] |
Please provide a description of the function:def json(self):
return {
'name': self.name,
'message': self.message,
'description': self.description,
'reference_url': self.reference_url,
'tags': self.tags,
} | [
"\n Get json representation of the check\n\n :return: dict (str -> obj)\n "
] |
Please provide a description of the function:def get_checks_paths(checks_paths=None):
p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks")
p = os.path.abspath(p)
# let's utilize the default upstream checks always
if checks_paths:
p += [os.path.abspath(x) for x in checks_paths]
return [p] | [
"\n Get path to checks.\n\n :param checks_paths: list of str, directories where the checks are present\n :return: list of str (absolute path of directory with checks)\n "
] |
Please provide a description of the function:def get_ruleset_file(ruleset=None):
ruleset = ruleset or "default"
ruleset_dirs = get_ruleset_dirs()
for ruleset_directory in ruleset_dirs:
possible_ruleset_files = [os.path.join(ruleset_directory, ruleset + ext) for ext in EXTS]
for ruleset_file in possible_ruleset_files:
if os.path.isfile(ruleset_file):
logger.debug("Ruleset file '{}' found.".format(ruleset_file))
return ruleset_file
logger.warning("Ruleset with the name '{}' cannot be found at '{}'."
.format(ruleset, ruleset_dirs))
raise ColinRulesetException("Ruleset with the name '{}' cannot be found.".format(ruleset)) | [
"\n Get the ruleset file from name\n\n :param ruleset: str\n :return: str\n "
] |
Please provide a description of the function:def get_ruleset_dirs():
ruleset_dirs = []
cwd_rulesets = os.path.join(".", RULESET_DIRECTORY_NAME)
if os.path.isdir(cwd_rulesets):
logger.debug("Ruleset directory found in current directory ('{}').".format(cwd_rulesets))
ruleset_dirs.append(cwd_rulesets)
if "VIRTUAL_ENV" in os.environ:
venv_local_share = os.path.join(os.environ["VIRTUAL_ENV"],
RULESET_DIRECTORY)
if os.path.isdir(venv_local_share):
logger.debug("Virtual env ruleset directory found ('{}').".format(venv_local_share))
ruleset_dirs.append(venv_local_share)
local_share = os.path.join(os.path.expanduser("~"),
".local",
RULESET_DIRECTORY)
if os.path.isdir(local_share):
logger.debug("Local ruleset directory found ('{}').".format(local_share))
ruleset_dirs.append(local_share)
usr_local_share = os.path.join("/usr/local", RULESET_DIRECTORY)
if os.path.isdir(usr_local_share):
logger.debug("Global ruleset directory found ('{}').".format(usr_local_share))
ruleset_dirs.append(usr_local_share)
if not ruleset_dirs:
msg = "Ruleset directory cannot be found."
logger.warning(msg)
raise ColinRulesetException(msg)
return ruleset_dirs | [
"\n Get the directory with ruleset files\n First directory to check: ./rulesets\n Second directory to check: $HOME/.local/share/colin/rulesets\n Third directory to check: /usr/local/share/colin/rulesets\n :return: str\n "
] |
Please provide a description of the function:def get_rulesets():
rulesets_dirs = get_ruleset_dirs()
ruleset_files = []
for rulesets_dir in rulesets_dirs:
for f in os.listdir(rulesets_dir):
for ext in EXTS:
file_path = os.path.join(rulesets_dir, f)
if os.path.isfile(file_path) and f.lower().endswith(ext):
ruleset_files.append((f[:-len(ext)], file_path))
return ruleset_files | [
"\"\n Get available rulesets.\n "
] |
Please provide a description of the function:def get_checks(self, target_type, tags=None, skips=None):
skips = skips or []
result = []
for check_struct in self.ruleset_struct.checks:
if check_struct.name in skips:
continue
logger.debug("Processing check_struct {}.".format(check_struct))
usable_targets = check_struct.usable_targets
if target_type and usable_targets \
and target_type.get_compatible_check_class().check_type not in usable_targets:
logger.info("Skipping... Target type does not match.")
continue
if check_struct.import_name:
check_class = self.check_loader.import_class(check_struct.import_name)
else:
try:
check_class = self.check_loader.mapping[check_struct.name]
except KeyError:
logger.error("Check %s was not found -- it can't be loaded", check_struct.name)
raise ColinRulesetException(
"Check {} can't be loaded, we couldn't find it.".format(check_struct.name))
check_instance = check_class()
if check_struct.tags:
logger.info("Overriding check's tags %s with the one defined in ruleset: %s",
check_instance.tags, check_struct.tags)
check_instance.tags = check_struct.tags[:]
if check_struct.additional_tags:
logger.info("Adding additional tags: %s", check_struct.additional_tags)
check_instance.tags += check_struct.additional_tags
if not is_compatible(target_type=target_type, check_instance=check_instance):
logger.error(
"Check '{}' not compatible with the target type: {}".format(
check_instance.name, target_type.get_compatible_check_class().check_type))
raise ColinRulesetException(
"Check {} can't be used for target type {}".format(
check_instance, target_type.get_compatible_check_class().check_type))
if tags:
if not set(tags) < set(check_instance.tags):
logger.debug(
"Check '{}' not passed the tag control: {}".format(check_instance.name,
tags))
continue
# and finally, attach attributes from ruleset to the check instance
for k, v in check_struct.other_attributes.items():
# yes, this overrides things; yes, users may easily and severely broke their setup
setattr(check_instance, k, v)
result.append(check_instance)
logger.debug("Check instance {} added.".format(check_instance.name))
return result | [
"\n Get all checks for given type/tags.\n\n :param skips: list of str\n :param target_type: TargetType class\n :param tags: list of str\n :return: list of check instances\n "
] |
Please provide a description of the function:def get_version_msg_from_the_cmd(package_name, cmd=None, use_rpm=None,
max_lines_of_the_output=None):
if use_rpm is None:
use_rpm = is_rpm_installed()
if use_rpm:
rpm_version = get_rpm_version(package_name=package_name)
if rpm_version:
return "{} (rpm)".format(rpm_version)
try:
cmd = cmd or [package_name, "--version"]
version_result = subprocess.run(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if version_result.returncode == 0:
version_output = version_result.stdout.decode().rstrip()
if max_lines_of_the_output:
version_output = " ".join(version_output.split('\n')[:max_lines_of_the_output])
return version_output
else:
return "{}: cannot get version with {}".format(package_name, cmd)
except FileNotFoundError:
return "{} not accessible!".format(package_name) | [
"\n Get str with the version (or string representation of the error).\n\n :param package_name: str\n :param cmd: str or [str] (defaults to [package_name, \"--version\"])\n :param use_rpm: True/False/None (whether to use rpm -q for getting a version)\n :param max_lines_of_the_output: use first n lines of the output\n :return: str\n "
] |
Please provide a description of the function:def get_rpm_version(package_name):
version_result = subprocess.run(["rpm", "-q", package_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if version_result.returncode == 0:
return version_result.stdout.decode().rstrip()
else:
return None | [
"Get a version of the package with 'rpm -q' command."
] |
Please provide a description of the function:def is_rpm_installed():
try:
version_result = subprocess.run(["rpm", "--usage"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
rpm_installed = not version_result.returncode
except FileNotFoundError:
rpm_installed = False
return rpm_installed | [
"Tests if the rpm command is present."
] |
Please provide a description of the function:def exit_after(s):
def outer(fn):
def inner(*args, **kwargs):
timer = threading.Timer(s, thread.interrupt_main)
timer.start()
try:
result = fn(*args, **kwargs)
except KeyboardInterrupt:
raise TimeoutError("Function '{}' hit the timeout ({}s).".format(fn.__name__, s))
finally:
timer.cancel()
return result
return inner
return outer | [
"\n Use as decorator to exit process if\n function takes longer than s seconds.\n\n Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).\n\n Inspired by https://stackoverflow.com/a/31667005\n "
] |
Please provide a description of the function:def retry(retry_count=5, delay=2):
if retry_count <= 0:
raise ValueError("retry_count have to be positive")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for i in range(retry_count, 0, -1):
try:
return f(*args, **kwargs)
except Exception:
if i <= 1:
raise
time.sleep(delay)
return wrapper
return decorator | [
"\n Use as decorator to retry functions few times with delays\n\n Exception will be raised if last call fails\n\n :param retry_count: int could of retries in case of failures. It must be\n a positive number\n :param delay: int delay between retries\n "
] |
Please provide a description of the function:def parse(cls, image_name):
result = cls()
# registry.org/namespace/repo:tag
s = image_name.split('/', 2)
if len(s) == 2:
if '.' in s[0] or ':' in s[0]:
result.registry = s[0]
else:
result.namespace = s[0]
elif len(s) == 3:
result.registry = s[0]
result.namespace = s[1]
result.repository = s[-1]
try:
result.repository, result.digest = result.repository.rsplit("@", 1)
except ValueError:
try:
result.repository, result.tag = result.repository.rsplit(":", 1)
except ValueError:
result.tag = "latest"
return result | [
"\n Get the instance of ImageName from the string representation.\n\n :param image_name: str (any possible form of image name)\n :return: ImageName instance\n "
] |
Please provide a description of the function:def name(self):
name_parts = []
if self.registry:
name_parts.append(self.registry)
if self.namespace:
name_parts.append(self.namespace)
if self.repository:
name_parts.append(self.repository)
name = "/".join(name_parts)
if self.digest:
name += "@{}".format(self.digest)
elif self.tag:
name += ":{}".format(self.tag)
return name | [
"\n Get the string representation of the image\n (registry, namespace, repository and digest together).\n\n :return: str\n "
] |
Please provide a description of the function:def nicer_get(di, required, *path):
r = di
for p in path:
try:
r = r[p]
except KeyError:
if required:
logger.error("can't locate %s in ruleset dict, keys present: %s",
p, list(r.keys()))
logger.debug("full dict = %s", r)
raise ColinRulesetException("Validation error: can't locate %s in ruleset." % p)
return
return r | [
"\n this is a nicer way of doing dict.get()\n\n :param di: dict\n :param required: bool, raises an exc if value is not found, otherwise returns None\n :param path: list of str to navigate in the dict\n :return: your value\n "
] |
Please provide a description of the function:def other_attributes(self):
return {k: v for k, v in self.c.items() if
k not in ["name", "names", "tags", "additional_tags", "usable_targets"]} | [
" return dict with all other data except for the described above"
] |
Please provide a description of the function:def should_we_load(kls):
# we don't load abstract classes
if kls.__name__.endswith("AbstractCheck"):
return False
# and we only load checks
if not kls.__name__.endswith("Check"):
return False
mro = kls.__mro__
# and the class needs to be a child of AbstractCheck
for m in mro:
if m.__name__ == "AbstractCheck":
return True
return False | [
" should we load this class as a check? "
] |
Please provide a description of the function:def obtain_check_classes(self):
check_classes = set()
for path in self.paths:
for root, _, files in os.walk(path):
for fi in files:
if not fi.endswith(".py"):
continue
path = os.path.join(root, fi)
check_classes = check_classes.union(set(
load_check_classes_from_file(path)))
return list(check_classes) | [
" find children of AbstractCheck class and return them as a list "
] |
Please provide a description of the function:def import_class(self, import_name):
module_name, class_name = import_name.rsplit(".", 1)
mod = import_module(module_name)
check_class = getattr(mod, class_name)
self.mapping[check_class.name] = check_class
logger.info("successfully loaded class %s", check_class)
return check_class | [
"\n import selected class\n\n :param import_name, str, e.g. some.module.MyClass\n :return the class\n "
] |
Please provide a description of the function:def _dict_of_results(self):
result_json = {}
result_list = []
for r in self.results:
result_list.append({
'name': r.check_name,
'ok': r.ok,
'status': r.status,
'description': r.description,
'message': r.message,
'reference_url': r.reference_url,
'logs': r.logs,
})
result_json["checks"] = result_list
return result_json | [
"\n Get the dictionary representation of results\n\n :return: dict (str -> dict (str -> str))\n "
] |
Please provide a description of the function:def statistics(self):
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result | [
"\n Get the dictionary with the count of the check-statuses\n\n :return: dict(str -> int)\n "
] |
Please provide a description of the function:def generate_pretty_output(self, stat, verbose, output_function, logs=True):
has_check = False
for r in self.results:
has_check = True
if stat:
output_function(OUTPUT_CHARS[r.status],
fg=COLOURS[r.status],
nl=False)
else:
output_function(str(r), fg=COLOURS[r.status])
if verbose:
output_function(" -> {}\n"
" -> {}".format(r.description,
r.reference_url),
fg=COLOURS[r.status])
if logs and r.logs:
output_function(" -> logs:",
fg=COLOURS[r.status])
for l in r.logs:
output_function(" -> {}".format(l),
fg=COLOURS[r.status])
if not has_check:
output_function("No check found.")
elif stat and not verbose:
output_function("")
else:
output_function("")
for status, count in six.iteritems(self.statistics):
output_function("{}:{} ".format(status, count), nl=False)
output_function("") | [
"\n Send the formated to the provided function\n\n :param stat: if True print stat instead of full output\n :param verbose: bool\n :param output_function: function to send output to\n "
] |
Please provide a description of the function:def get_pretty_string(self, stat, verbose):
pretty_output = _PrettyOutputToStr()
self.generate_pretty_output(stat=stat,
verbose=verbose,
output_function=pretty_output.save_output)
return pretty_output.result | [
"\n Pretty string representation of the results\n\n :param stat: bool\n :param verbose: bool\n :return: str\n "
] |
Please provide a description of the function:def receive_fmf_metadata(name, path, object_list=False):
output = {}
fmf_tree = ExtendedTree(path)
logger.debug("get FMF metadata for test (path:%s name=%s)", path, name)
# ignore items with @ in names, to avoid using unreferenced items
items = [x for x in fmf_tree.climb() if x.name.endswith("/" + name) and "@" not in x.name]
if object_list:
return items
if len(items) == 1:
output = items[0]
elif len(items) > 1:
raise Exception("There is more FMF test metadata for item by name:{}({}) {}".format(
name, len(items), [x.name for x in items]))
elif not items:
raise Exception("Unable to get FMF metadata for: {}".format(name))
return output | [
"\n search node identified by name fmfpath\n\n :param path: path to filesystem\n :param name: str - name as pattern to search - \"/name\" (prepended hierarchy item)\n :param object_list: bool, if true, return whole list of found items\n :return: Tree Object or list\n "
] |
Please provide a description of the function:def check(target, ruleset, ruleset_file, debug, json, stat, skip, tag, verbose,
checks_paths, target_type, timeout, pull, insecure):
if ruleset and ruleset_file:
raise click.BadOptionUsage(
"Options '--ruleset' and '--file-ruleset' cannot be used together.")
if json and not os.path.isdir(os.path.dirname(os.path.realpath(json.name))):
raise click.BadOptionUsage(
"Parent directory for the json output file does not exist.")
try:
if not debug:
logging.basicConfig(stream=six.StringIO())
log_level = _get_log_level(debug=debug,
verbose=verbose)
results = run(
target=target,
ruleset_name=ruleset,
ruleset_file=ruleset_file,
logging_level=log_level,
tags=tag,
pull=pull,
checks_paths=checks_paths,
target_type=target_type,
timeout=timeout,
insecure=insecure,
skips=skip
)
_print_results(results=results, stat=stat, verbose=verbose)
if json:
results.save_json_to_file(file=json)
if not results.ok:
sys.exit(1)
elif results.fail:
sys.exit(3)
except ColinException as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex)) | [
"\n Check the image/dockerfile (default).\n "
] |
Please provide a description of the function:def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths):
if ruleset and ruleset_file:
raise click.BadOptionUsage(
"Options '--ruleset' and '--file-ruleset' cannot be used together.")
try:
if not debug:
logging.basicConfig(stream=six.StringIO())
log_level = _get_log_level(debug=debug,
verbose=verbose)
checks = get_checks(ruleset_name=ruleset,
ruleset_file=ruleset_file,
logging_level=log_level,
tags=tag,
checks_paths=checks_paths,
skips=skip)
_print_checks(checks=checks)
if json:
AbstractCheck.save_checks_to_json(file=json, checks=checks)
except ColinException as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex)) | [
"\n Print the checks.\n "
] |
Please provide a description of the function:def list_rulesets(debug):
try:
rulesets = get_rulesets()
max_len = max([len(r[0]) for r in rulesets])
for r in rulesets:
click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1]))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex)) | [
"\n List available rulesets.\n "
] |
Please provide a description of the function:def info():
installation_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
click.echo("colin {} {}".format(__version__, installation_path))
click.echo("colin-cli {}\n".format(os.path.realpath(__file__)))
# click.echo(get_version_of_the_python_package(module=conu))
rpm_installed = is_rpm_installed()
click.echo(get_version_msg_from_the_cmd(package_name="podman", use_rpm=rpm_installed))
click.echo(get_version_msg_from_the_cmd(package_name="skopeo", use_rpm=rpm_installed))
click.echo(get_version_msg_from_the_cmd(package_name="ostree",
use_rpm=rpm_installed,
max_lines_of_the_output=3)) | [
"\n Show info about colin and its dependencies.\n "
] |
Please provide a description of the function:def _print_results(results, stat=False, verbose=False):
results.generate_pretty_output(stat=stat,
verbose=verbose,
output_function=click.secho) | [
"\n Prints the results to the stdout\n\n :type verbose: bool\n :param results: generator of results\n :param stat: if True print stat instead of full output\n "
] |
Please provide a description of the function:def inspect_object(obj, refresh=True):
if hasattr(obj, "inspect"):
return obj.inspect(refresh=refresh)
return obj.get_metadata(refresh=refresh) | [
"\n inspect provided object (container, image) and return raw dict with the metadata\n\n :param obj: instance of Container or an Image\n :param refresh: bool, refresh the metadata or return cached?\n :return: dict\n "
] |
Please provide a description of the function:def get_instance(target_type, **kwargs):
if target_type in TARGET_TYPES:
cls = TARGET_TYPES[target_type]
try:
return cls(**kwargs)
except Exception:
logger.error("Please make sure that you picked the correct target type: "
"--target-type CLI option.")
raise
raise ColinException(
"Unknown target type '{}'. Please make sure that you picked the correct target type: "
"--target-type CLI option.".format(target_type)) | [
"\n :param target_type: string, either image, dockertar, ostree or dockerfile\n "
] |
Please provide a description of the function:def labels(self):
if self._labels is None:
self._labels = self.instance.labels
return self._labels | [
"\n Get list of labels from the target instance.\n\n :return: [str]\n "
] |
Please provide a description of the function:def read_file(self, file_path):
try:
with open(self.cont_path(file_path)) as fd:
return fd.read()
except IOError as ex:
logger.error("error while accessing file %s: %r", file_path, ex)
raise ColinException(
"There was an error while accessing file %s: %r" % (file_path, ex)) | [
"\n read file specified via 'file_path' and return its content - raises an ConuException if\n there is an issue accessing the file\n :param file_path: str, path to the file to read\n :return: str (not bytes), content of the file\n "
] |
Please provide a description of the function:def get_file(self, file_path, mode="r"):
return open(self.cont_path(file_path), mode=mode) | [
"\n provide File object specified via 'file_path'\n :param file_path: str, path to the file\n :param mode: str, mode used when opening the file\n :return: File instance\n "
] |
Please provide a description of the function:def file_is_present(self, file_path):
real_path = self.cont_path(file_path)
if not os.path.exists(real_path):
return False
if not os.path.isfile(real_path):
raise IOError("%s is not a file" % file_path)
return True | [
"\n check if file 'file_path' is present, raises IOError if file_path\n is not a file\n :param file_path: str, path to the file\n :return: True if file exists, False if file does not exist\n "
] |
Please provide a description of the function:def cont_path(self, path):
if path.startswith("/"):
path = path[1:]
real_path = os.path.join(self.mount_point, path)
logger.debug("path = %s", real_path)
return real_path | [
"\n provide absolute path within the container\n\n :param path: path with container\n :return: str\n "
] |
Please provide a description of the function:def mount_point(self):
if self._mount_point is None:
cmd_create = ["podman", "create", self.target_name, "some-cmd"]
self._mounted_container_id = subprocess.check_output(cmd_create).decode().rstrip()
cmd_mount = ["podman", "mount", self._mounted_container_id]
self._mount_point = subprocess.check_output(cmd_mount).decode().rstrip()
return self._mount_point | [
" podman mount -- real filesystem "
] |
Please provide a description of the function:def labels(self):
if self._labels is None:
cmd = ["skopeo", "inspect", self.skopeo_target]
self._labels = json.loads(subprocess.check_output(cmd))["Labels"]
return self._labels | [
"\n Provide labels without the need of dockerd. Instead skopeo is being used.\n\n :return: dict\n "
] |
Please provide a description of the function:def layers_path(self):
if self._layers_path is None:
self._layers_path = os.path.join(self.tmpdir, "layers")
return self._layers_path | [
" Directory with all the layers (docker save). "
] |
Please provide a description of the function:def mount_point(self):
if self._mount_point is None:
self._mount_point = os.path.join(self.tmpdir, "checkout")
os.makedirs(self._mount_point)
self._checkout()
return self._mount_point | [
" ostree checkout -- real filesystem "
] |
Please provide a description of the function:def ostree_path(self):
if self._ostree_path is None:
self._ostree_path = os.path.join(self.tmpdir, "ostree-repo")
subprocess.check_call(["ostree", "init", "--mode", "bare-user-only",
"--repo", self._ostree_path])
return self._ostree_path | [
" ostree repository -- content "
] |
Please provide a description of the function:def tmpdir(self):
if self._tmpdir is None:
self._tmpdir = mkdtemp(prefix="colin-", dir="/var/tmp")
return self._tmpdir | [
" Temporary directory holding all the runtime data. "
] |
Please provide a description of the function:def _checkout(self):
cmd = ["atomic", "mount", "--storage", "ostree", self.ref_image_name, self.mount_point]
# self.mount_point has to be created by us
self._run_and_log(cmd, self.ostree_path,
"Failed to mount selected image as an ostree repo.") | [
" check out the image filesystem on self.mount_point "
] |
Please provide a description of the function:def _run_and_log(cmd, ostree_repo_path, error_msg, wd=None):
logger.debug("running command %s", cmd)
kwargs = {
"stderr": subprocess.STDOUT,
"env": os.environ.copy(),
}
if ostree_repo_path:
# must not exist, ostree will create it
kwargs["env"]["ATOMIC_OSTREE_REPO"] = ostree_repo_path
if wd:
kwargs["cwd"] = wd
try:
out = subprocess.check_output(cmd, **kwargs)
except subprocess.CalledProcessError as ex:
logger.error(ex.output)
logger.error(error_msg)
raise
logger.debug("%s", out) | [
" run provided command and log all of its output; set path to ostree repo "
] |
Please provide a description of the function:def __remove_append_items(self, whole=False):
for node in self.climb(whole=whole):
for key in sorted(node.data.keys()):
if key.endswith('+'):
del node.data[key] | [
"\n internal method, delete all append items (ends with +)\n :param whole: pass thru 'whole' param to climb\n :return: None\n "
] |
Please provide a description of the function:def references(self, datatrees, whole=False):
if not isinstance(datatrees, list):
raise ValueError("datatrees argument has to be list of fmf trees")
reference_nodes = self.prune(whole=whole, names=["@"])
for node in reference_nodes:
node.data = node.original_data
ref_item_name = node.name.rsplit("@", 1)[1]
# match item what does not contain @ before name, otherwise it
# match same item
reference_node = None
for datatree in datatrees:
reference_node = datatree.search("[^@]%s" % ref_item_name)
if reference_node is not None:
break
if not reference_node:
raise ValueError("Unable to find reference for node: %s via name search: %s" %
(node.name, ref_item_name))
logger.debug("MERGING: %s @ %s from %s",
node.name,
reference_node.name,
reference_node.root)
node.merge(parent=reference_node)
self.__remove_append_items(whole=whole) | [
"\n Reference name resolver (eg. /a/b/c/[email protected] or /a/b/c/@y will search data in .x.y or y nodes)\n there are used regular expressions (re.search) to match names\n it uses simple references schema, do not use references to another references,\n avoid usind / in reference because actual solution creates also these tree items.\n\n datatree contains for example data like (original check data)\n /dockerfile/maintainer_check:\n class: SomeClass\n tags: [dockerfile]\n\n and reference could be like (ruleset)\n /default/check1@maintainer_check:\n tags+: [required]\n\n will produce output (output ruleset tree):\n /default/check1@maintainer_check:\n class: SomeClass\n tags: [dockerfile, required]\n\n\n :param whole: 'whole' param of original climb method, in colin this is not used anyhow now\n iterate over all items not only leaves if True\n :param datatrees: list of original trees with testcases to contain parent nodes\n :return: None\n "
] |
Please provide a description of the function:def search(self, name):
for node in self.climb():
if re.search(name, node.name):
return node
return None | [
" Search node with given name based on regexp, basic method (find) uses equality"
] |
Please provide a description of the function:def login(self, email, password):
params = {
'email': email,
'password': password
}
return self._get('login', params) | [
"Login to Todoist.\n\n :param email: The user's email address.\n :type email: str\n :param password: The user's password.\n :type password: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> response = api.login('[email protected]', 'password')\n >>> user_info = response.json()\n >>> full_name = user_info['full_name']\n >>> print(full_name)\n John Doe\n "
] |
Please provide a description of the function:def login_with_google(self, email, oauth2_token, **kwargs):
params = {
'email': email,
'oauth2_token': oauth2_token
}
req_func = self._get
if kwargs.get('auto_signup', 0) == 1: # POST if we're creating a user.
req_func = self._post
return req_func('login_with_google', params, **kwargs) | [
"Login to Todoist using Google's oauth2 authentication.\n\n :param email: The user's Google email address.\n :type email: str\n :param oauth2_token: The user's Google oauth2 token.\n :type oauth2_token: str\n :param auto_signup: If ``1`` register an account automatically.\n :type auto_signup: int\n :param full_name: The full name to use if the account is registered\n automatically. If no name is given an email based nickname is used.\n :type full_name: str\n :param timezone: The timezone to use if the account is registered\n automatically. If no timezone is given one is chosen based on the\n user's IP address.\n :type timezone: str\n :param lang: The user's language.\n :type lang: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> oauth2_token = 'oauth2_token' # Get this from Google.\n >>> response = api.login_with_google('[email protected]',\n ... oauth2_token)\n >>> user_info = response.json()\n >>> full_name = user_info['full_name']\n >>> print(full_name)\n John Doe\n "
] |
Please provide a description of the function:def register(self, email, full_name, password, **kwargs):
params = {
'email': email,
'full_name': full_name,
'password': password
}
return self._post('register', params, **kwargs) | [
"Register a new Todoist user.\n\n :param email: The user's email.\n :type email: str\n :param full_name: The user's full name.\n :type full_name: str\n :param password: The user's password.\n :type password: str\n :param lang: The user's language.\n :type lang: str\n :param timezone: The user's timezone.\n :type timezone: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> response = api.register('[email protected]', 'John Doe',\n ... 'password')\n >>> user_info = response.json()\n >>> full_name = user_info['full_name']\n >>> print(full_name)\n John Doe\n "
] |
Please provide a description of the function:def delete_user(self, api_token, password, **kwargs):
params = {
'token': api_token,
'current_password': password
}
return self._post('delete_user', params, **kwargs) | [
"Delete a registered Todoist user's account.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param password: The user's password.\n :type password: str\n :param reason_for_delete: The reason for deletion.\n :type reason_for_delete: str\n :param in_background: If ``0``, delete the user instantly.\n :type in_background: int\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def sync(self, api_token, sync_token, resource_types='["all"]', **kwargs):
params = {
'token': api_token,
'sync_token': sync_token,
}
req_func = self._post
if 'commands' not in kwargs: # GET if we're not changing data.
req_func = self._get
params['resource_types'] = resource_types
return req_func('sync', params, **kwargs) | [
"Update and retrieve Todoist data.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param seq_no: The request sequence number. On initial request pass\n ``0``. On all others pass the last seq_no you received.\n :type seq_no: int\n :param seq_no_global: The request sequence number. On initial request\n pass ``0``. On all others pass the last seq_no you received.\n :type seq_no_global: int\n :param resource_types: Specifies which subset of data you want to\n receive e.g. only projects. Defaults to all data.\n :type resources_types: str\n :param commands: A list of JSON commands to perform.\n :type commands: list (str)\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> response = api.register('[email protected]', 'John Doe',\n ... 'password')\n >>> user_info = response.json()\n >>> api_token = user_info['api_token']\n >>> response = api.sync(api_token, 0, 0, '[\"projects\"]')\n >>> print(response.json())\n {'seq_no_global': 3848029654, 'seq_no': 3848029654, 'Projects': ...}\n "
] |
Please provide a description of the function:def query(self, api_token, queries, **kwargs):
params = {
'token': api_token,
'queries': queries
}
return self._get('query', params, **kwargs) | [
"Search all of a user's tasks using date, priority and label queries.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param queries: A JSON list of queries to search. See examples\n `here <https://todoist.com/Help/timeQuery>`_.\n :type queries: list (str)\n :param as_count: If ``1`` then return the count of matching tasks.\n :type as_count: int\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def add_item(self, api_token, content, **kwargs):
params = {
'token': api_token,
'content': content
}
return self._post('add_item', params, **kwargs) | [
"Add a task to a project.\n\n :param token: The user's login token.\n :type token: str\n :param content: The task description.\n :type content: str\n :param project_id: The project to add the task to. Default is ``Inbox``\n :type project_id: str\n :param date_string: The deadline date for the task.\n :type date_string: str\n :param priority: The task priority ``(1-4)``.\n :type priority: int\n :param indent: The task indentation ``(1-4)``.\n :type indent: int\n :param item_order: The task order.\n :type item_order: int\n :param children: A list of child tasks IDs.\n :type children: str\n :param labels: A list of label IDs.\n :type labels: str\n :param assigned_by_uid: The ID of the user who assigns current task.\n Accepts 0 or any user id from the list of project collaborators.\n If value is unset or invalid it will automatically be set up by\n your uid.\n :type assigned_by_uid: str\n :param responsible_uid: The id of user who is responsible for\n accomplishing the current task. Accepts 0 or any user id from\n the list of project collaborators. If the value is unset or\n invalid it will automatically be set to null.\n :type responsible_uid: str\n :param note: Content of a note to add.\n :type note: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> response = api.login('[email protected]', 'password')\n >>> user_info = response.json()\n >>> user_api_token = user_info['token']\n >>> response = api.add_item(user_api_token, 'Install PyTodoist')\n >>> task = response.json()\n >>> print(task['content'])\n Install PyTodoist\n "
] |
Please provide a description of the function:def quick_add(self, api_token, text, **kwargs):
params = {
'token': api_token,
'text': text
}
return self._post('quick/add', params, **kwargs) | [
"Add a task using the Todoist 'Quick Add Task' syntax.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param text: The text of the task that is parsed. A project\n name starts with the `#` character, a label starts with a `@`\n and an assignee starts with a `+`.\n :type text: str\n :param note: The content of the note.\n :type note: str\n :param reminder: The date of the reminder, added in free form text.\n :type reminder: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def get_all_completed_tasks(self, api_token, **kwargs):
params = {
'token': api_token
}
return self._get('get_all_completed_items', params, **kwargs) | [
"Return a list of a user's completed tasks.\n\n .. warning:: Requires Todoist premium.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param project_id: Filter the tasks by project.\n :type project_id: str\n :param limit: The maximum number of tasks to return\n (default ``30``, max ``50``).\n :type limit: int\n :param offset: Used for pagination if there are more tasks than limit.\n :type offset: int\n :param from_date: Return tasks with a completion date on or older than\n from_date. Formatted as ``2007-4-29T10:13``.\n :type from_date: str\n :param to: Return tasks with a completion date on or less than\n to_date. Formatted as ``2007-4-29T10:13``.\n :type from_date: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> response = api.login('[email protected]', 'password')\n >>> user_info = response.json()\n >>> user_api_token = user_info['api_token']\n >>> response = api.get_all_completed_tasks(user_api_token)\n >>> completed_tasks = response.json()\n "
] |
Please provide a description of the function:def upload_file(self, api_token, file_path, **kwargs):
params = {
'token': api_token,
'file_name': os.path.basename(file_path)
}
with open(file_path, 'rb') as f:
files = {'file': f}
return self._post('upload_file', params, files, **kwargs) | [
"Upload a file suitable to be passed as a file_attachment.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param file_path: The path of the file to be uploaded.\n :type file_path: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def get_productivity_stats(self, api_token, **kwargs):
params = {
'token': api_token
}
return self._get('get_productivity_stats', params, **kwargs) | [
"Return a user's productivity stats.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def update_notification_settings(self, api_token, event,
service, should_notify):
params = {
'token': api_token,
'notification_type': event,
'service': service,
'dont_notify': should_notify
}
return self._post('update_notification_setting', params) | [
"Update a user's notification settings.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param event: Update the notification settings of this event.\n :type event: str\n :param service: ``email`` or ``push``\n :type service: str\n :param should_notify: If ``0`` notify, otherwise do not.\n :type should_notify: int\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> response = api.login('[email protected]', 'password')\n >>> user_info = response.json()\n >>> user_api_token = user_info['api_token']\n >>> response = api.update_notification_settings(user_api_token,\n ... 'user_left_project',\n ... 'email', 0)\n ...\n "
] |
Please provide a description of the function:def get_redirect_link(self, api_token, **kwargs):
params = {
'token': api_token
}
return self._get('get_redirect_link', params, **kwargs) | [
"Return the absolute URL to redirect or to open in\n a browser. The first time the link is used it logs in the user\n automatically and performs a redirect to a given page. Once used,\n the link keeps working as a plain redirect.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param path: The path to redirect the user's browser. Default ``/app``.\n :type path: str\n :param hash: The has part of the path to redirect the user's browser.\n :type hash: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import TodoistAPI\n >>> api = TodoistAPI()\n >>> response = api.login('[email protected]', 'password')\n >>> user_info = response.json()\n >>> user_api_token = user_info['api_token']\n >>> response = api.get_redirect_link(user_api_token)\n >>> link_info = response.json()\n >>> redirect_link = link_info['link']\n >>> print(redirect_link)\n https://todoist.com/secureRedirect?path=adflk...\n "
] |
Please provide a description of the function:def _get(self, end_point, params=None, **kwargs):
return self._request(requests.get, end_point, params, **kwargs) | [
"Send a HTTP GET request to a Todoist API end-point.\n\n :param end_point: The Todoist API end-point.\n :type end_point: str\n :param params: The required request parameters.\n :type params: dict\n :param kwargs: Any optional parameters.\n :type kwargs: dict\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def _post(self, end_point, params=None, files=None, **kwargs):
return self._request(requests.post, end_point, params, files, **kwargs) | [
"Send a HTTP POST request to a Todoist API end-point.\n\n :param end_point: The Todoist API end-point.\n :type end_point: str\n :param params: The required request parameters.\n :type params: dict\n :param files: Any files that are being sent as multipart/form-data.\n :type files: dict\n :param kwargs: Any optional parameters.\n :type kwargs: dict\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def _request(self, req_func, end_point, params=None, files=None, **kwargs):
url = self.URL + end_point
if params and kwargs:
params.update(kwargs)
return req_func(url, params=params, files=files) | [
"Send a HTTP request to a Todoist API end-point.\n\n :param req_func: The request function to use e.g. get or post.\n :type req_func: A request function from the :class:`requests` module.\n :param end_point: The Todoist API end-point.\n :type end_point: str\n :param params: The required request parameters.\n :type params: dict\n :param files: Any files that are being sent as multipart/form-data.\n :type files: dict\n :param kwargs: Any optional parameters.\n :type kwargs: dict\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n "
] |
Please provide a description of the function:def login(email, password):
user = _login(API.login, email, password)
user.password = password
return user | [
"Login to Todoist.\n\n :param email: A Todoist user's email address.\n :type email: str\n :param password: A Todoist user's password.\n :type password: str\n :return: The Todoist user.\n :rtype: :class:`pytodoist.todoist.User`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> print(user.full_name)\n John Doe\n "
] |
Please provide a description of the function:def login_with_api_token(api_token):
response = API.sync(api_token, '*', '["user"]')
_fail_if_contains_errors(response)
user_json = response.json()['user']
# Required as sync doesn't return the api_token.
user_json['api_token'] = user_json['token']
return User(user_json) | [
"Login to Todoist using a user's api token.\n\n .. note:: It is up to you to obtain the api token.\n\n :param api_token: A Todoist user's api token.\n :type api_token: str\n :return: The Todoist user.\n :rtype: :class:`pytodoist.todoist.User`\n\n >>> from pytodoist import todoist\n >>> api_token = 'api_token'\n >>> user = todoist.login_with_api_token(api_token)\n >>> print(user.full_name)\n John Doe\n "
] |
Please provide a description of the function:def _login(login_func, *args):
response = login_func(*args)
_fail_if_contains_errors(response)
user_json = response.json()
return User(user_json) | [
"A helper function for logging in. It's purpose is to avoid duplicate\n code in the login functions.\n "
] |
Please provide a description of the function:def register(full_name, email, password, lang=None, timezone=None):
response = API.register(email, full_name, password,
lang=lang, timezone=timezone)
_fail_if_contains_errors(response)
user_json = response.json()
user = User(user_json)
user.password = password
return user | [
"Register a new Todoist account.\n\n :param full_name: The user's full name.\n :type full_name: str\n :param email: The user's email address.\n :type email: str\n :param password: The user's password.\n :type password: str\n :param lang: The user's language.\n :type lang: str\n :param timezone: The user's timezone.\n :type timezone: str\n :return: The Todoist user.\n :rtype: :class:`pytodoist.todoist.User`\n\n >>> from pytodoist import todoist\n >>> user = todoist.register('John Doe', '[email protected]', 'password')\n >>> print(user.full_name)\n John Doe\n "
] |
Please provide a description of the function:def register_with_google(full_name, email, oauth2_token,
lang=None, timezone=None):
response = API.login_with_google(email, oauth2_token, auto_signup=1,
full_name=full_name, lang=lang,
timezone=timezone)
_fail_if_contains_errors(response)
user_json = response.json()
user = User(user_json)
return user | [
"Register a new Todoist account by linking a Google account.\n\n :param full_name: The user's full name.\n :type full_name: str\n :param email: The user's email address.\n :type email: str\n :param oauth2_token: The oauth2 token associated with the email.\n :type oauth2_token: str\n :param lang: The user's language.\n :type lang: str\n :param timezone: The user's timezone.\n :type timezone: str\n :return: The Todoist user.\n :rtype: :class:`pytodoist.todoist.User`\n\n .. note:: It is up to you to obtain the valid oauth2 token.\n\n >>> from pytodoist import todoist\n >>> oauth2_token = 'oauth2_token'\n >>> user = todoist.register_with_google('John Doe', '[email protected]',\n ... oauth2_token)\n >>> print(user.full_name)\n John Doe\n "
] |
Please provide a description of the function:def _fail_if_contains_errors(response, sync_uuid=None):
if response.status_code != _HTTP_OK:
raise RequestError(response)
response_json = response.json()
if sync_uuid and 'sync_status' in response_json:
status = response_json['sync_status']
if sync_uuid in status and 'error' in status[sync_uuid]:
raise RequestError(response) | [
"Raise a RequestError Exception if a given response\n does not denote a successful request.\n "
] |
Please provide a description of the function:def _perform_command(user, command_type, command_args):
command_uuid = _gen_uuid()
command = {
'type': command_type,
'args': command_args,
'uuid': command_uuid,
'temp_id': _gen_uuid()
}
commands = json.dumps([command])
response = API.sync(user.api_token, user.sync_token, commands=commands)
_fail_if_contains_errors(response, command_uuid)
response_json = response.json()
user.sync_token = response_json['sync_token'] | [
"Perform an operation on Todoist using the API sync end-point."
] |
Please provide a description of the function:def update(self):
args = {attr: getattr(self, attr) for attr in self.to_update}
_perform_command(self, 'user_update', args) | [
"Update the user's details on Todoist.\n\n This method must be called to register any local attribute changes\n with Todoist.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> user.full_name = 'John Smith'\n >>> # At this point Todoist still thinks the name is 'John Doe'.\n >>> user.update()\n >>> # Now the name has been updated on Todoist.\n "
] |
Please provide a description of the function:def sync(self, resource_types='["all"]'):
response = API.sync(self.api_token, '*', resource_types)
_fail_if_contains_errors(response)
response_json = response.json()
self.sync_token = response_json['sync_token']
if 'projects' in response_json:
self._sync_projects(response_json['projects'])
if 'items' in response_json:
self._sync_tasks(response_json['items'])
if 'notes' in response_json:
self._sync_notes(response_json['notes'])
if 'labels' in response_json:
self._sync_labels(response_json['labels'])
if 'filters' in response_json:
self._sync_filters(response_json['filters'])
if 'reminders' in response_json:
self._sync_reminders(response_json['reminders']) | [
"Synchronize the user's data with the Todoist server.\n\n This function will pull data from the Todoist server and update the\n state of the user object such that they match. It does not *push* data\n to Todoist. If you want to do that use\n :func:`pytodoist.todoist.User.update`.\n\n :param resource_types: A JSON-encoded list of Todoist resources which\n should be synced. By default this is everything, but you can\n choose to sync only selected resources. See\n `here <https://developer.todoist.com/#retrieve-data>`_ for a list\n of resources.\n "
] |
Please provide a description of the function:def _sync_projects(self, projects_json):
for project_json in projects_json:
project_id = project_json['id']
self.projects[project_id] = Project(project_json, self) | [
"\"Populate the user's projects from a JSON encoded list."
] |
Please provide a description of the function:def _sync_tasks(self, tasks_json):
for task_json in tasks_json:
task_id = task_json['id']
project_id = task_json['project_id']
if project_id not in self.projects:
# ignore orphan tasks
continue
project = self.projects[project_id]
self.tasks[task_id] = Task(task_json, project) | [
"\"Populate the user's tasks from a JSON encoded list."
] |
Please provide a description of the function:def _sync_notes(self, notes_json):
for note_json in notes_json:
note_id = note_json['id']
task_id = note_json['item_id']
if task_id not in self.tasks:
# ignore orphan notes
continue
task = self.tasks[task_id]
self.notes[note_id] = Note(note_json, task) | [
"\"Populate the user's notes from a JSON encoded list."
] |
Please provide a description of the function:def _sync_labels(self, labels_json):
for label_json in labels_json:
label_id = label_json['id']
self.labels[label_id] = Label(label_json, self) | [
"\"Populate the user's labels from a JSON encoded list."
] |
Please provide a description of the function:def _sync_filters(self, filters_json):
for filter_json in filters_json:
filter_id = filter_json['id']
self.filters[filter_id] = Filter(filter_json, self) | [
"\"Populate the user's filters from a JSON encoded list."
] |
Please provide a description of the function:def _sync_reminders(self, reminders_json):
for reminder_json in reminders_json:
reminder_id = reminder_json['id']
task_id = reminder_json['item_id']
if task_id not in self.tasks:
# ignore orphan reminders
continue
task = self.tasks[task_id]
self.reminders[reminder_id] = Reminder(reminder_json, task) | [
"\"Populate the user's reminders from a JSON encoded list."
] |
Please provide a description of the function:def quick_add(self, text, note=None, reminder=None):
response = API.quick_add(self.api_token, text,
note=note, reminder=reminder)
_fail_if_contains_errors(response)
task_json = response.json()
return Task(task_json, self) | [
"Add a task using the 'Quick Add Task' syntax.\n\n :param text: The text of the task that is parsed. A project\n name starts with the `#` character, a label starts with a `@`\n and an assignee starts with a `+`.\n :type text: str\n :param note: The content of the note.\n :type note: str\n :param reminder: The date of the reminder, added in free form text.\n :type reminder: str\n :return: The added task.\n :rtype: :class:`pytodoist.todoist.Task`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> task = user.quick_add('Install Pytodoist #personal @app')\n >>> print(task.content)\n Install PyTodoist\n "
] |
Please provide a description of the function:def add_project(self, name, color=None, indent=None, order=None):
args = {
'name': name,
'color': color,
'indent': indent,
'order': order
}
args = {k: args[k] for k in args if args[k] is not None}
_perform_command(self, 'project_add', args)
return self.get_project(name) | [
"Add a project to the user's account.\n\n :param name: The project name.\n :type name: str\n :return: The project that was added.\n :rtype: :class:`pytodoist.todoist.Project`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> project = user.add_project('PyTodoist')\n >>> print(project.name)\n PyTodoist\n "
] |
Please provide a description of the function:def get_project(self, project_name):
for project in self.get_projects():
if project.name == project_name:
return project | [
"Return the project with a given name.\n\n :param project_name: The name to search for.\n :type project_name: str\n :return: The project that has the name ``project_name`` or ``None``\n if no project is found.\n :rtype: :class:`pytodoist.todoist.Project`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> project = user.get_project('Inbox')\n >>> print(project.name)\n Inbox\n "
] |
Please provide a description of the function:def get_uncompleted_tasks(self):
tasks = (p.get_uncompleted_tasks() for p in self.get_projects())
return list(itertools.chain.from_iterable(tasks)) | [
"Return all of a user's uncompleted tasks.\n\n .. warning:: Requires Todoist premium.\n\n :return: A list of uncompleted tasks.\n :rtype: list of :class:`pytodoist.todoist.Task`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> uncompleted_tasks = user.get_uncompleted_tasks()\n >>> for task in uncompleted_tasks:\n ... task.complete()\n "
] |
Please provide a description of the function:def search_tasks(self, *queries):
queries = json.dumps(queries)
response = API.query(self.api_token, queries)
_fail_if_contains_errors(response)
query_results = response.json()
tasks = []
for result in query_results:
if 'data' not in result:
continue
all_tasks = result['data']
if result['type'] == Query.ALL:
all_projects = all_tasks
for project_json in all_projects:
uncompleted_tasks = project_json.get('uncompleted', [])
completed_tasks = project_json.get('completed', [])
all_tasks = uncompleted_tasks + completed_tasks
for task_json in all_tasks:
project_id = task_json['project_id']
project = self.projects[project_id]
task = Task(task_json, project)
tasks.append(task)
return tasks | [
"Return a list of tasks that match some search criteria.\n\n .. note:: Example queries can be found\n `here <https://todoist.com/Help/timeQuery>`_.\n\n .. note:: A standard set of queries are available\n in the :class:`pytodoist.todoist.Query` class.\n\n :param queries: Return tasks that match at least one of these queries.\n :type queries: list str\n :return: A list tasks that match at least one query.\n :rtype: list of :class:`pytodoist.todoist.Task`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> tasks = user.search_tasks(todoist.Query.TOMORROW, '18 Sep')\n "
] |
Please provide a description of the function:def add_label(self, name, color=None):
args = {
'name': name,
'color': color
}
_perform_command(self, 'label_register', args)
return self.get_label(name) | [
"Create a new label.\n\n .. warning:: Requires Todoist premium.\n\n :param name: The name of the label.\n :type name: str\n :param color: The color of the label.\n :type color: str\n :return: The newly created label.\n :rtype: :class:`pytodoist.todoist.Label`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> label = user.add_label('family')\n "
] |
Please provide a description of the function:def get_label(self, label_name):
for label in self.get_labels():
if label.name == label_name:
return label | [
"Return the user's label that has a given name.\n\n :param label_name: The name to search for.\n :type label_name: str\n :return: A label that has a matching name or ``None`` if not found.\n :rtype: :class:`pytodoist.todoist.Label`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> label = user.get_label('family')\n "
] |
Please provide a description of the function:def add_filter(self, name, query, color=None, item_order=None):
args = {
'name': name,
'query': query,
'color': color,
'item_order': item_order
}
_perform_command(self, 'filter_add', args)
return self.get_filter(name) | [
"Create a new filter.\n\n .. warning:: Requires Todoist premium.\n\n :param name: The name of the filter.\n :param query: The query to search for.\n :param color: The color of the filter.\n :param item_order: The filter's order in the filter list.\n :return: The newly created filter.\n :rtype: :class:`pytodoist.todoist.Filter`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> overdue_filter = user.add_filter('Overdue', todoist.Query.OVERDUE)\n "
] |
Please provide a description of the function:def get_filter(self, name):
for flter in self.get_filters():
if flter.name == name:
return flter | [
"Return the filter that has the given filter name.\n\n :param name: The name to search for.\n :return: The filter with the given name.\n :rtype: :class:`pytodoist.todoist.Filter`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> user.add_filter('Overdue', todoist.Query.OVERDUE)\n >>> overdue_filter = user.get_filter('Overdue')\n "
] |
Please provide a description of the function:def _update_notification_settings(self, event, service,
should_notify):
response = API.update_notification_settings(self.api_token, event,
service, should_notify)
_fail_if_contains_errors(response) | [
"Update the settings of a an events notifications.\n\n :param event: Update the notification settings of this event.\n :type event: str\n :param service: The notification service to update.\n :type service: str\n :param should_notify: Notify if this is ``1``.\n :type should_notify: int\n "
] |
Please provide a description of the function:def get_productivity_stats(self):
response = API.get_productivity_stats(self.api_token)
_fail_if_contains_errors(response)
return response.json() | [
"Return the user's productivity stats.\n\n :return: A JSON-encoded representation of the user's productivity\n stats.\n :rtype: A JSON-encoded object.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> stats = user.get_productivity_stats()\n >>> print(stats)\n {\"karma_last_update\": 50.0, \"karma_trend\": \"up\", ... }\n "
] |
Please provide a description of the function:def get_redirect_link(self):
response = API.get_redirect_link(self.api_token)
_fail_if_contains_errors(response)
link_json = response.json()
return link_json['link'] | [
"Return the absolute URL to redirect or to open in\n a browser. The first time the link is used it logs in the user\n automatically and performs a redirect to a given page. Once used,\n the link keeps working as a plain redirect.\n\n :return: The user's redirect link.\n :rtype: str\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> print(user.get_redirect_link())\n https://todoist.com/secureRedirect?path=%2Fapp&token ...\n "
] |
Please provide a description of the function:def delete(self, reason=None):
response = API.delete_user(self.api_token, self.password,
reason=reason, in_background=0)
_fail_if_contains_errors(response) | [
"Delete the user's account from Todoist.\n\n .. warning:: You cannot recover the user after deletion!\n\n :param reason: The reason for deletion.\n :type reason: str\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> user.delete()\n ... # The user token is now invalid and Todoist operations will fail.\n "
] |
Please provide a description of the function:def archive(self):
args = {'id': self.id}
_perform_command(self.owner, 'project_archive', args)
self.is_archived = '1' | [
"Archive the project.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.archive()\n "
] |
Please provide a description of the function:def add_task(self, content, date=None, priority=None):
response = API.add_item(self.owner.token, content, project_id=self.id,
date_string=date, priority=priority)
_fail_if_contains_errors(response)
task_json = response.json()
return Task(task_json, self) | [
"Add a task to the project\n\n :param content: The task description.\n :type content: str\n :param date: The task deadline.\n :type date: str\n :param priority: The priority of the task.\n :type priority: int\n :return: The added task.\n :rtype: :class:`pytodoist.todoist.Task`\n\n .. note:: See `here <https://todoist.com/Help/timeInsert>`_\n for possible date strings.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('[email protected]', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> task = project.add_task('Install PyTodoist')\n >>> print(task.content)\n Install PyTodoist\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.