Esempio n. 1
0
async def start(onBind, c):
    global config
    config = c

    import logging
    logger = logging.Logger("server")
    logger.setLevel(logging.DEBUG)

    # Create an app and a runner
    app = web.Application()
    app.add_routes([web.post("/fromGitlab", fromGitlab)])
    app.add_routes([web.post("/fromNest", fromNest)])
    runner = web.AppRunner(app, logger=logger)
    await runner.setup()

    site, port = await start_somewhere(runner)
    cur_ip = await get("https://api.ipify.org")
    await onBind(f"{cur_ip}:{port}")

    print(chalk.green(chalk.bold("  Initialization finished!")))

    # Listen for IP changes
    while True:
        await asyncio.sleep(5)
        ip = await get("https://api.ipify.org")
        if ip != cur_ip:
            print(
                chalk.yellow(
                    f"IP changed from {cur_ip} to {ip}, restarting server..."))
            await site.stop()
            site, port = await start_somewhere(runner)
            cur_ip = ip
            await onBind(f"{cur_ip}:{port}")
Esempio n. 2
0
async def sync(config):
    await pullGit(config["git"]["url"])
    await pullPijul(config["pijul"]["url"])
    presync = await presyncGitToPijul(urlToPath(config["git"]["url"]),
                                      urlToPath(config["pijul"]["url"]))
    await syncPijulToGit(urlToPath(config["git"]["url"]),
                         urlToPath(config["pijul"]["url"]))
    await syncGitToPijul(urlToPath(config["git"]["url"]),
                         urlToPath(config["pijul"]["url"]), presync)
    print(chalk.green(chalk.bold("  Sync complete!")))
Esempio n. 3
0
    async def on_command(self, ctx):
        botguild = next((item for item in self.bot.guilds if item.id == 615228970568515626), None)
        log = botguild.get_channel(625767405641007106)
        try:
            print(chalk.bold(chalk.cyan(f'{ctx.guild.name}')) + chalk.yellow(' > ') + chalk.bold(
                chalk.green(f'{ctx.author}')) + chalk.yellow(': ') + f'{ctx.message.clean_content}')
            await log.send(f'```md\n[{ctx.guild.name}]({ctx.channel.name}) {ctx.author}: {ctx.message.clean_content}```')

        except AttributeError:
            print(chalk.yellow(f"Private message > {ctx.author} > {ctx.message.clean_content}"))
            await log.send(f'```md\n< Private message > {ctx.author}: {ctx.message.clean_content}```')
Esempio n. 4
0
    async def on_ready(self):
        botguild = next((item for item in self.bot.guilds if item.id == 615228970568515626), None)
        log = botguild.get_channel(625767405641007106)
        if not hasattr(self.bot, 'uptime'):
            self.bot.uptime = datetime.utcnow()

        print(chalk.bold(chalk.cyan('Ready: ')) + chalk.green(f'{self.bot.user}') + chalk.yellow(' | ') + chalk.bold(
            chalk.cyan('Servers: ')) + chalk.green(
            f'{len(self.bot.guilds)}'))
        await self.bot.change_presence(activity=discord.Game(type=0, name=self.config.playing),
                                       status=discord.Status.online)

        await log.send(f'```css\nReady! Guilds: {len(self.bot.guilds)}```')
Esempio n. 5
0
@author: Wu Liang
@contact: [email protected]
@date 2015-05-09 23:29
"""

import os
import sys

currentPath = os.path.normpath(os.path.dirname(os.path.realpath(__file__)))
rootPath = os.path.normpath(os.path.dirname(currentPath))
sys.path.insert(0, rootPath)

import chalk

print "%s %s %s %s %s %s %s" % (
    chalk.bold("bold"),
    chalk.dim("dim"),
    chalk.italic("italic"),
    chalk.underline("underline"),
    chalk.inverse("inverse"),
    chalk.strikethrough("strikethrough"),
    chalk.black(chalk.gray("black")),
)
print "%s %s %s %s %s %s %s %s" % (
    chalk.red("red"), chalk.green("green"), chalk.yellow("yellow"),
    chalk.blue("blue"), chalk.magenta("magenta"), chalk.cyan("cyan"),
    chalk.white("white"), chalk.gray("gray"))
print "%s %s %s %s %s %s %s" % (
    chalk.bgRed("bgRed"), chalk.bgGreen("bgGreen"), chalk.bgYellow("bgYellow"),
    chalk.bgBlue("bgBlue"), chalk.bgMagenta("bgMagenta"),
    chalk.bgCyan("bgCyan"), chalk.bgWhite("bgWhite"))
Esempio n. 6
0
 def produce_report(self):
     linter_version = self.master.get_linter_version()
     if self.master.is_plugin is True:
         linter_doc_url = (self.master.linter_url or self.master.linter_repo
                           or
                           "[linter_url should be defined on descriptor]")
     else:
         linter_doc_url = (
             f"{DOCS_URL_DESCRIPTORS_ROOT}/{self.master.descriptor_id.lower()}_"
             f"{self.master.linter_name.lower().replace('-', '_')}")
     # Linter header prints
     msg = [
         "",
         c.bold(f"### Processed [{self.master.descriptor_id}] files"),
         f"- Using [{self.master.linter_name} v{linter_version}] {linter_doc_url}",
     ]
     if self.master.descriptor_id != self.master.name:
         msg += [f"- MegaLinter key: [{self.master.name}]"]
     if self.master.config_file is not None:
         msg += [f"- Rules config: [{self.master.config_file_label}]"]
     else:
         msg += [
             f"- Rules config: identified by [{self.master.linter_name}]"
         ]
     if self.master.config_file_error is not None:
         logging.warning(self.master.config_file_error)
     if self.print_all_files is False and self.master.cli_lint_mode != "project":
         msg += [
             f"- Number of files analyzed: [{len(self.master.files_lint_results)}]"
         ]
     logging.info("\n".join(msg))
     # Output results
     for res in self.master.files_lint_results:
         file_nm = utils.normalize_log_string(res["file"])
         if self.master.cli_lint_mode == "file":
             file_errors = str(res.get("errors_number", 0))
             line = f"[{self.master.linter_name}] {file_nm} - {res['status'].upper()} - {file_errors} error(s)"
         else:
             line = f"[{self.master.linter_name}] {file_nm}"
         if res["fixed"] is True:
             line += " - FIXED"
             line = c.cyan(line)
         if res["status_code"] in [0, None
                                   ]:  # file ok or file from list_of_files
             if self.print_all_files is True:
                 logging.info(line)
         else:
             logging.error(c.red(line))
             logging.error(c.red(f"--Error detail:\n{res['stdout']}"))
     # Output stdout if not file by file
     if self.master.cli_lint_mode in ["list_of_files", "project"]:
         if self.master.status != "success":
             logging.error(f"--Error detail:\n{self.master.stdout}")
         elif self.report_type == "detailed":
             logging.info(f"--Log detail:\n{self.master.stdout}")
     # Output linter status
     base_phrase = f"Linted [{self.master.descriptor_id}] files with [{self.master.linter_name}]"
     elapse = str(round(self.master.elapsed_time_s, 2)) + "s"
     total_errors = str(self.master.total_number_errors)
     if self.master.return_code == 0 and self.master.status == "success":
         logging.info(c.green(f"✅ {base_phrase} successfully - ({elapse})"))
     elif self.master.return_code == 0 and self.master.status != "success":
         logging.warning(
             c.yellow(
                 f"✅ {base_phrase}: Found {total_errors} non blocking error(s) - ({elapse})"
             ))
     elif self.master.return_code != 0 and self.master.status != "success":
         logging.error(
             c.red(
                 f"❌ {base_phrase}: Found {total_errors} error(s) - ({elapse})"
             ))
     else:
         logging.error(
             f"❌ There is a MegaLinter issue, please report it: {self.master.return_code} / {self.master.status}"
         )
Esempio n. 7
0
entities = [rescue]
animals = []

for i in range(random.randint(5, 10)):
    ei, ej = board.random_location()
    animal = Animal(ei, ej)
    entities.append(animal)
    animals.append(animal)

while True:

    board.print(entities)
    #int(animal.location_i, animal.location_j)
    print(
        chalk.bold(
            'Some dangerous animals broke out of Portland zoo and hiding in Forst park. Help animal control to tranquilize and bring them back'
        ))
    print(Fore.RED + Back.LIGHTBLACK_EX + Style.NORMAL)
    print(chalk.bold(len(animals)), 'animals are out there')
    command = input('Whih direction do you want to move? l,r,u,d '
                    )  # get the command from the user

    if command == 'done':
        break  # exit the game
    elif command in ['l', 'left', 'w', 'west', '']:
        rescue.location_j -= 1  # move left
    elif command in ['r', 'right', 'e', 'east']:
        rescue.location_j += 1  # move right
    elif command in ['u', 'up', 'n', 'north']:
        rescue.location_i -= 1  # move up
    elif command in ['d', 'down', 's', 'south']:
Esempio n. 8
0
async def main():
    global config

    # Try to read config
    setup_config = "--setup-config" in sys.argv[1:]
    if setup_config:
        sys.argv.remove("--setup-config")
    try:
        config_path = sys.argv[1]
    except IndexError:
        config_path = "~/.config/pgproxy.conf"
    if setup_config:
        config = None
    else:
        try:
            with open(os.path.expanduser(config_path)) as f:
                config = json.loads(f.read())
        except IOError as e:
            if e.errno == 2:  # No such file or directory
                config = None
            else:
                print(
                    chalk.red(
                        f"Unable to read config file from {config_path}:"))
                print(chalk.red(str(e)))
                raise SystemExit(1)

    print(chalk.yellow(chalk.bold("Welcome to PijulGit proxy!")))

    # Set up configuration file if required
    if config is None:
        if setup_config:
            print(f"Setting up a config for you at {config_path}.")
            go = True
        elif config_path == "~/.config/pgproxy.conf":
            print("Please configure the proxy via ~/.config/pgproxy.conf.")
            print(
                "If you want to run several proxies at once, you can pass the path to the config"
            )
            print(
                "via CLI arguments, like this: `python3 -m PijulGit ~/AwesomeProj/pgproxy.conf`"
            )
            prompt = "You can do it now if you want to. [Y/n] "
            go = input(chalk.blue(prompt)) in "yY"
        else:
            prompt = f"Do you want to setup a configuration file at {config_path}? [Y/n] "
            go = input(chalk.blue(prompt)) in "yY"

        if go:
            print("Here we go:")

            # Git
            git_conf = {}
            print(
                chalk.blue(
                    "What's your Git project URL? Make sure to include login and password if you're"
                ))
            print(
                chalk.blue(
                    "using http(s), and that your keychain is unlocked if you're using ssh."
                ))
            git_conf["url"] = input(chalk.blue("> "))
            git_host = git.getUrlHost(git_conf["url"])
            if git_host in git.hook_supported_hosts:
                print(f"The proxy supports {git_host} hooks.")
                git_conf["login"] = input(
                    chalk.blue(
                        "Please enter your login if you want to init hooks. "))
                if git_conf["login"] != "":
                    git_conf["password"] = getpass.getpass(
                        chalk.blue("Please enter your password. "))
                else:
                    print(
                        chalk.yellow(f"No problem, will use pooling instead."))
            else:
                print(
                    chalk.yellow(
                        f"{git_host} hooks aren't supported, will use pooling instead."
                    ))

            # Pijul
            pijul_conf = {}
            print(
                chalk.blue(
                    "What's your Pijul project URL? Make sure that your keychain is unlocked."
                ))
            pijul_conf["url"] = input(chalk.blue("> "))
            pijul_host = pijul.getUrlHost(pijul_conf["url"])
            if pijul_host in pijul.hook_supported_hosts:
                print(f"The proxy supports {pijul_host} hooks.")
                pijul_conf["login"] = input(
                    chalk.blue(
                        "Please enter your login if you want to init hooks. "))
                if pijul_conf["login"] != "":
                    pijul_conf["password"] = getpass.getpass(
                        chalk.blue("Please enter your password. "))
                else:
                    print(
                        chalk.yellow(f"No problem, will use pooling instead."))
            else:
                print(
                    chalk.yellow(
                        f"{pijul_host} hooks aren't supported, will use pooling instead."
                    ))

            config = {"git": git_conf, "pijul": pijul_conf}
            os.makedirs(os.path.dirname(
                os.path.abspath(os.path.expanduser(config_path))),
                        exist_ok=True)
            with open(os.path.expanduser(config_path), "w") as f:
                f.write(json.dumps(config))
            print(
                chalk.green(
                    f"Configuration file was saved successfully at {config_path}."
                ))
        else:
            print(chalk.red("Aborting. Fill the config yourself please."))
            raise SystemExit(0)
    else:
        print(chalk.green(f"Found existing config at {config_path}, using it"))

    await www.init()

    # Authorize
    git_host = git.getUrlHost(config["git"]["url"])
    if "login" in config["git"] and git_host in git.hook_supported_hosts:
        print(f"Authorizing on {git_host}...")
        r = await git.authorize(git_host, config["git"]["login"],
                                config["git"]["password"])
        if r == "ok":
            print(chalk.green("Authorized successfully!"))
        else:
            print(chalk.red(r))
            raise SystemExit(1)

    pijul_host = pijul.getUrlHost(config["pijul"]["url"])
    if "login" in config["pijul"] and pijul_host in pijul.hook_supported_hosts:
        print(f"Authorizing on {pijul_host}...")
        r = await pijul.authorize(pijul_host, config["pijul"]["login"],
                                  config["pijul"]["password"])
        if r == "ok":
            print(chalk.green("Authorized successfully!"))
        else:
            print(chalk.red(r))
            raise SystemExit(1)

    # Start pooling threads
    if "login" not in config["git"]:
        await asyncio.create_task(gitPool())
        print(chalk.green("Started Git pooling thread"))
    if "login" not in config["pijul"]:
        await asyncio.create_task(pijulPool())
        print(chalk.green("Started Pijul pooling thread"))

    print("Initial sync...")
    await sync(config)

    # Start server
    await server.start(onBind, config)

    await www.destroy()