def make_branch(repo_path, config):
    repo = git.Repo(repo_path)
    submodules = {}
    name = config.get("submodule_name")
    for submodule in repo.submodules:
        submodules[submodule.name] = submodule
    if not submodules:
        raise SubmoduleFindingError("No submodules found")
    elif len(submodules) > 1 and not name:
        raise SubmoduleFindingError(f"Found more than 1 ({submodule.keys()}")
    elif not name:
        submodule, = list(submodules.values())
        name = submodule.name
    else:
        submodule = submodules[name]

    submodule.update(init=True)
    branch_name = config.get("submodule_branch") or "master"
    origin_name = config.get("submodule_origin") or "origin"
    sub_repo = submodule.module()
    sub_repo.git.checkout(branch_name)
    for remote in sub_repo.remotes:
        if remote.name == origin_name:
            break
    else:
        raise SubmoduleFindingError(f"Can't find origin {origin_name!r}")
    sha = sub_repo.head.object.hexsha

    short_sha = sub_repo.git.rev_parse(sha, short=7)
    remote.pull(branch_name)
    sha2 = sub_repo.head.object.hexsha
    short_sha2 = sub_repo.git.rev_parse(sha2, short=7)

    if sha == sha2:
        raise NothingToUpdateError(f"Latest sha is already {sha}")

    new_branch_name = f"update-{name}-{short_sha}-to-{short_sha2}"
    print("New branch name", new_branch_name)

    # Check that the branch and PR doesn't already exist
    g = Github(GITHUB_ACCESS_TOKEN)
    # Bail if we already have a PR by this branch name
    repo_name = config["repo_name"]
    g_repo = g.get_repo(repo_name)
    if config["git_server"] != "github.com":
        raise NotImplementedError
    # pulls = repo.get_pulls(state='open', sort='created', base='master')
    pulls = g_repo.get_pulls(sort="created", base="master")
    for pull in pulls:
        branch_ref_name = pull.raw_data["head"]["ref"]
        if new_branch_name in branch_ref_name:
            url = pull.raw_data["_links"]["html"]["href"]
            raise PullRequestError(f"Already at a pull request at {url}")

    current = repo.create_head(new_branch_name)
    current.checkout()
    repo.git.add(A=True)
    msg = f"Update submodule {name!r} from {short_sha} to {short_sha2}"
    repo.git.commit(["-m", msg])
    pushed = repo.git.push("origin", new_branch_name)
    print("PUSHED:")
    print(repr(pushed))

    # https://github.com/PyGithub/PyGithub/blob/6e79d2704b8812d26435b21c1258c766418ab25e/github/Repository.py#L1207
    body = "Updating the submodule! 😊\n"
    created_pr = g_repo.create_pull(msg, body, "master", new_branch_name)
    print(created_pr.html_url)
    return created_pr
Exemple #2
0
    batch = client.new_batch_http_request()
    for event in events:
        batch.add(client.events().delete(calendarId=calendar["id"],
                                         eventId=event["id"],
                                         sendUpdates="all"))

    batch.execute()

# Search and read for TOML files. Aggregate the ones that contains `slot` configuration.
slots = []
conferences = Path(config("CONFERENCES_PATH", "conferencias"))
for config_file in conferences.glob("**/*.toml"):
    print("Reading config file:", config_file)
    with config_file.open() as fp:
        config = toml.load(fp)
        slots.extend(config.get("slot", []))

# Create Calendar Event for each slot found on configuration files
print("Total events found:", len(slots))
batch = client.new_batch_http_request()
for slot in slots:
    start_at = slot["start_at"]
    if not start_at.year == today.year:
        continue
    duration = slot["duration"]
    end_at = start_at + timedelta(minutes=duration)

    author = slot.get("author", "")
    photo_url = slot.get("photo_url", "")
    if not photo_url and author:
        photo_url = PHOTO_URL.format(slugify(author, separator="_"))
Exemple #3
0
def play_game(li, game_id, control_queue, engine_factory, user_profile,
              config):
    #game state
    gg_said = False

    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')),
                      user_profile["username"], li.baseUrl,
                      config.get("abort_time", 20))
    board = setup_board(game)
    engine = engine_factory(board)
    conversation = Conversation(game, engine, li, __version__)

    print("+++ {}".format(game))

    engine_cfg = config["engine"]
    polyglot_cfg = engine_cfg.get("polyglot", {})

    if not polyglot_cfg.get("enabled") or not play_first_book_move(
            game, engine, board, li, config):
        play_first_move(game, engine, board, li)

    engine.set_time_control(game)

    if board.fullmove_number == 1:
        cnt = 0
        glms = config["good_luck_messages"]
        for glm in glms:
            game_chat(li, game.id, glm, public=(cnt < (len(glms) - 1)))
            cnt += 1

    watch_engine[game.id] = True

    def print_engine_info(engine, game):
        global watch_engine
        while watch_engine[game.id]:
            try:
                if not engine.engine.idle:
                    info = engine.engine.info_handlers[0].info
                    score = info["score"][1]
                    print(
                        "{} - {}\n  {:8s} {:8s}".format(
                            game.white, game.black, str(score.cp),
                            str(score.mate)),
                        " ".join(list(map(chess.Move.uci,
                                          info["pv"][1][0:5]))))
            except:
                pass
            time.sleep(1)
        print("engine watch finished")

    th = threading.Thread(target=print_engine_info, args=(engine, game))
    th.start()

    try:
        for binary_chunk in updates:
            upd = json.loads(
                binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if u_type == "chatLine":
                conversation.react(ChatLine(upd), game)
            elif u_type == "gameState":
                game.state = upd
                moves = upd["moves"].split()
                board = update_board(board, moves[-1])

                if is_engine_move(game, moves):
                    best_move = None

                    pos_eval = 0
                    best_move = get_book_move(board, config)

                    if best_move == None:
                        print("searching for move")
                        best_move = engine.search(board, upd["wtime"],
                                                  upd["btime"], upd["winc"],
                                                  upd["binc"])
                        info = engine.engine.info_handlers[0].info
                        score = info["score"][1]
                        if score[1] == None:
                            pos_eval = score[0]
                        else:
                            mate = score[1]
                            if mate > 0:
                                pos_eval = MATE_SCORE - mate
                            else:
                                pos_eval = -MATE_SCORE - mate
                        print("best move", best_move, pos_eval)
                    else:
                        pass

                    opp_time = int(upd["wtime"])

                    if game.is_white:
                        opp_time = int(upd["btime"])

                    is_inc = (int(upd["winc"]) > 0) or (int(upd["binc"]) > 0)

                    if (pos_eval > RESIGN_SCORE) or (
                        (opp_time < TIME_TROUBLE_LIMIT) and (not is_inc)):
                        if pos_eval > WON_SCORE and not gg_said:
                            ggm = config["good_game_message"]
                            if not ggm is None:
                                game_chat(li, game.id, ggm, public=True)
                            gg_said = True
                        li.make_move(game.id, best_move)
                        game.abort_in(config.get("abort_time", 20))
                    else:
                        print("resign")
                        game_chat(li, game.id, "good game", public=True)
                        li.resign_hopeless_game(game.id)
            elif u_type == "ping":
                if game.should_abort_now():
                    print("    Aborting {} by lack of activity".format(
                        game.url()))
                    li.abort(game.id)
    except (RemoteDisconnected, ChunkedEncodingError, ConnectionError,
            ProtocolError, HTTPError) as exception:
        print("Abandoning game due to connection error")
        traceback.print_exception(type(exception), exception,
                                  exception.__traceback__)
    finally:
        print("--- {} Game over".format(game.url()))
        engine.quit()
        watch_engine[game.id] = False
        # This can raise queue.NoFull, but that should only happen if we're not processing
        # events fast enough and in this case I believe the exception should be raised
        control_queue.put_nowait({"type": "local_game_done"})