[Python] gitignore 만들고 github에 올리는 스크립트를 작성해보자

[Python] gitignore 만들고 github에 올리는 스크립트를 작성해보자

728x90

반응형

[ 목표 ]

새로운 프로젝트를 시작하고 (로컬 프로젝트를 만들고)

깃헙에 올릴 때,

1. gitignore 파일을 만들기

2. Adding an existing project to GitHub using the command line 문서따라 명령어 입력하기

하는데 좀 귀찮아서 스크립트를 만들어봅니다.

스크립트는

깃헙 연동할 프로젝트가 있는 디렉토리로 이동 후

& remote_url과 gitignore_url를 설정해주고

& 이걸가지고 gitignore파일을 만들고 깃헙관련 명령어들을 실행해주는 순서입니다.

[1] move_to_local_project

import os def move_to_local_project(): directory = input('프로젝트 디렉토리를 입력해주세요

') os.chdir(directory)

os패키지를 import하고 chdir (change directory의 줄임말) 메소드로

현재 디렉토리를 바꿔줍니다.

(참고로 os.system('cd 어떤 디렉토리') 하면 안되더라구요..! chdir써줘야합니다.)

[2] set_github_remote_url

def set_github_remote_url(): global remote_url remote_url = input('REMOTE_URL을 입력해주세요

');

원격저장소 url을 입력받습니다.

[3] set_gitignore_url

gitignore 추가할 때를 생각해보면

gitignore파일을 만든 후,

github.com/github/gitignore 여기서 각 환경에 맞는 코드를 해당 파일에 복붙해줍니다 .

근데 이제 스크립트가 gitignore파일을 만들고

프로젝트 타입? 플랫폼?에 해당하는 url에서 코드를 다운받아서 파일에 쓰게 해줍니다.

이것을 set_gitignore_url, make_gitignore_file 두개의 메소드로 구현해줄 건데요

먼저 set_gitignore_url입니다.

import requests class GitignoreUrl: ios = 'https://raw.githubusercontent.com/github/gitignore/master/Swift.gitignore' flutter = 'https://raw.githubusercontent.com/github/gitignore/master/Dart.gitignore' django = 'https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore' def set_gitignore_url(): candidates = ['ios', 'flutter', 'django'] project_type = input(' | '.join(candidates) + ' 중 어떤 프로젝트인가요?

') if project_type in candidates: global gitignore_url if project_type == 'ios': gitignore_url = GitignoreUrl.ios elif project_type == 'flutter': gitignore_url = GitignoreUrl.flutter elif project_type == 'django': gitignore_url = GitignoreUrl.django

저는 평소 프로젝트로 ios, flutter, django 3종류만 만들어서 저렇게 세 타입만 추가해줬습니다.

그리고 딱 텍스트만 가져올 수 있도록

여기서 Raw누르면 나오는 url로 설정해줬습니다.

(파이썬은 swift처럼 enum을 확장성있게 못써서 넘 아쉽네요,,)

[4] make_gitignore_file

gitignore파일을 만들어줍니다.

그리고 위의 단계에서 설정된 gitignore_url로 부터 text를 가져와서

gitignore파일에 써줍니다.

def make_gitignore_file(): os.system('touch .gitignore') response = requests.get(gitignore_url) data = response.text f = open('.gitignore', 'w') f.write(data) f.close()

[5] run_commands

Adding an existing project to GitHub using the command line 에 있는 명령어들을 복붙해줍니다.

def run_commands(): os.system('git init') os.system('git add .') os.system('git commit -m "First commit"') os.system('git remote add origin %s' % remote_url) # 연결된 원격저장소 확인 os.system('git remote -v') # 원격저장소에 master라는 branch를 생성하고 push한다. os.system('git push -u origin master')

[ 최종코드 ]

[ 사용예시 ]

iOS 프로젝트를 만들어볼게요 (이름은 MySample)

gitignore 추가 + 깃헙에 올리고싶다!! 할때 스크립트를 실행해줍니다.

프로젝트 디렉토리를 입력해달라고 나오는데,

프로젝트 폴더를 터미널로 끌어오면 디렉토리가 입력됩니다.

그다음 Remote url을 입력하라고 나오는데

깃헙에 들어가서 원격저장소를 만들고

저 url을 입력해줍니다.

그 다음 어떤 프로젝트인지 물어보면 대답해줍니다.

그럼 이렇게 쭉 로그가 출력됩니다. (에러안나면 성공한 것임)

깃헙들어가보면 잘 동작했네요..!

728x90

반응형

from http://eunjin3786.tistory.com/311 by ccl(A) rewrite - 2021-01-23 00:00:40