백엔드 개발 파이썬 튜토리얼 ReadmeGenie 리팩토링

ReadmeGenie 리팩토링

Oct 09, 2024 am 10:14 AM

Refactoring ReadmeGenie

Introduction

This week I was tasked to refactor the ReadmeGenie. If you just arrived here, ReadmeGenie is my open-source project that uses AI to generate readmes based on the files that the user inputs.

Initially, my thoughts were, "The program is working fine. I’ve been developing it in an organized way since day one... so why change it?"

Well, after taking a week-long break from the project, I opened it up again and immediately thought, "What is this?"

Why refactor?

To give you some context, here’s an example: One of my core functions, which I once thought was perfect, turned out to be much more complex than necessary. During the refactoring process, I broke it down into five separate functions—and guess what? The code is much cleaner and easier to manage now.

Take a look at the original version of this function:

def generate_readme(file_paths, api_key, base_url, output_filename, token_usage):
    try:
        load_dotenv()

        # Check if the api_key was provided either as an environment variable or as an argument
        if not api_key and not get_env():
            logger.error(f"{Fore.RED}API key is required but not provided. Exiting.{Style.RESET_ALL}")
            sys.exit(1)

        # Concatenate content from multiple files
        file_content = ""
        try:
            for file_path in file_paths:
                with open(file_path, 'r') as file:
                    file_content += file.read() + "\\n\\n"
        except FileNotFoundError as fnf_error:
            logger.error(f"{Fore.RED}File not found: {file_path}{Style.RESET_ALL}")
            sys.exit(1)

        # Get the base_url from arguments, environment, or use the default
        chosenModel = selectModel(base_url)
        try:
            if chosenModel == 'cohere':
                base_url = os.getenv("COHERE_BASE_URL", "https://api.cohere.ai/v1")
                response = cohereAPI(api_key, file_content)
                readme_content = response.generations[0].text.strip() + FOOTER_STRING
            else:
                base_url = os.getenv("GROQ_BASE_URL", "https://api.groq.com")
                response = groqAPI(api_key, base_url, file_content)
                readme_content = response.choices[0].message.content.strip() + FOOTER_STRING
        except AuthenticationError as auth_error:
            logger.error(f"{Fore.RED}Authentication failed: Invalid API key. Please check your API key and try again.{Style.RESET_ALL}")
            sys.exit(1)
        except Exception as api_error:
            logger.error(f"{Fore.RED}API request failed: {api_error}{Style.RESET_ALL}")
            sys.exit(1)

        # Process and save the generated README content
        if readme_content[0] != '*':
            readme_content = "\n".join(readme_content.split('\n')[1:])

        try:
            with open(output_filename, 'w') as output_file:
                output_file.write(readme_content)
            logger.info(f"README.md file generated and saved as {output_filename}")
            logger.warning(f"This is your file's content:\n{readme_content}")
        except IOError as io_error:
            logger.error(f"{Fore.RED}Failed to write to output file: {output_filename}. Error: {io_error}{Style.RESET_ALL}")
            sys.exit(1)

        # Save API key if needed
        if not get_env() and api_key is not None:
            logger.warning("Would you like to save your API key and base URL in a .env file for future use? [y/n]")
            answer = input()
            if answer.lower() == 'y':
                create_env(api_key, base_url, chosenModel)
        elif get_env():
            if chosenModel == 'cohere' and api_key != os.getenv("COHERE_API_KEY"):
                if api_key is not None:
                    logger.warning("Would you like to save this API Key? [y/n]")
                    answer = input()
                    if answer.lower() == 'y':
                        create_env(api_key, base_url, chosenModel)
            elif chosenModel == 'groq' and api_key != os.getenv("GROQ_API_KEY"):
                if api_key is not None:
                    logger.warning("Would you like to save this API Key? [y/n]")
                    answer = input()
                    if answer.lower() == 'y':
                        create_env(api_key, base_url, chosenModel)

        # Report token usage if the flag is set
        if token_usage:
            try:
                usage = response.usage
                logger.info(f"Token Usage Information: Prompt tokens: {usage.prompt_tokens}, Completion tokens: {usage.completion_tokens}, Total tokens: {usage.total_tokens}")
            except AttributeError:
                logger.warning(f"{Fore.YELLOW}Token usage information is not available for this response.{Style.RESET_ALL}")
        logger.info(f"{Fore.GREEN}File created successfully")
        sys.exit(0)
로그인 후 복사

1. Eliminate Global Variables
Global variables can lead to unexpected side effects. Keep the state within the scope it belongs to, and pass values explicitly when necessary.

2. Use Functions for Calculations
Avoid storing intermediate values in variables where possible. Instead, use functions to perform calculations when needed—this keeps your code flexible and easier to debug.

3. Separate Responsibilities
A single function should do one thing, and do it well. Split tasks like command-line argument parsing, file reading, AI model management, and output generation into separate functions or classes. This separation allows for easier testing and modification in the future.

4. Improve Naming
Meaningful variable and function names are crucial. When revisiting your code after some time, clear names help you understand the flow without needing to re-learn everything.

5. Reduce Duplication
If you find yourself copying and pasting code, it’s a sign that you could benefit from shared functions or classes. Duplication makes maintenance harder, and small changes can easily result in bugs.

Commiting and pushing to GitHub

1. Create a branch
I started by creating a branch using:

git checkout -b <branch-name>
로그인 후 복사

This command creates a new branch and switches to it.

2. Making a Series of Commits
Once on the new branch, I made incremental commits. Each commit represents a logical chunk of work, whether it was refactoring a function, fixing a bug, or adding a new feature. Making frequent, small commits helps track changes more effectively and makes it easier to review the history of the project.

git status
git add <file_name>
git commit -m "Refactored function"
로그인 후 복사

3. Rebasing to Keep a Clean History
After making several commits, I rebased my branch to keep the history clean and linear. Rebasing allows me to reorder, combine, or modify commits before they are pushed to GitHub. This is especially useful if some of the commits are very small or if I want to avoid cluttering the commit history with too many incremental changes.

git rebase -i main
로그인 후 복사

In this step, I initiated an interactive rebase on top of the main branch. The -i flag allows me to modify the commit history interactively. I could squash some of my smaller commits into one larger, cohesive commit. For instance, if I had a series of commits like:

Refactor part 1
Refactor part 2
Fix bug in refactor

I could squash them into a single commit with a clearer message

4. Pushing Changes to GitHub
Once I was satisfied with the commit history after the rebase, I pushed the changes to GitHub. If you’ve just created a new branch, you’ll need to push it to the remote repository with the -u flag, which sets the upstream branch for future pushes.

git push -u origin <branch-name>
로그인 후 복사

5. Merging
In the last step I did a fast-forward merge to the main branch and pushed again

git checkout main # change to the main branch
git merge --ff-only <branch-name> # make a fast-forward merge
git push origin main # push to the main
로그인 후 복사

Takeaways

Everything has room to improve. Refactoring may seem like a hassle, but it often results in cleaner, more maintainable, and more efficient code. So, the next time you feel hesitant about refactoring, remember: there’s always a better way to do things.
Even though I think it's perfect now, I will definitely have something to improve on my next commit.

위 내용은 ReadmeGenie 리팩토링의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? 중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? Apr 02, 2025 am 07:15 AM

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? 10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? Apr 02, 2025 am 07:18 AM

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Apr 02, 2025 am 07:03 AM

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.

Python 3.6 피클 파일로드 오류 modulenotfounderRor : 피클 파일 '__builtin__'를로드하면 어떻게해야합니까? Python 3.6 피클 파일로드 오류 modulenotfounderRor : 피클 파일 '__builtin__'를로드하면 어떻게해야합니까? Apr 02, 2025 am 06:27 AM

Python 3.6에 피클 파일 로딩 3.6 환경 오류 : ModulenotFounderRor : nomodulename ...

SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유는 무엇입니까? SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유는 무엇입니까? Apr 02, 2025 am 06:45 AM

SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유에 대한 논의 지속적인 데이터 저장을 위해 SCAPY 크롤러를 사용할 때 파이프 라인 파일이 발생할 수 있습니다 ...

See all articles