aboutsummaryrefslogtreecommitdiff
path: root/giti
blob: 15f3239009798ac9e3900c95966327785df8eed2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python
# coding=utf-8
import os
import sys
import requests

__author__ = 'Victor Häggqvist'
__version__ = '0.3.0'


def repo_url(kind: str, global_dir=False) -> str:
    if global_dir:
        return 'https://raw.githubusercontent.com/github/gitignore/master/Global/%s.gitignore' % kind
    else:
        return 'https://raw.githubusercontent.com/github/gitignore/master/%s.gitignore' % kind


def get_ignore_file(kind: str, global_dir=False, path=False) -> str:
    """
    Download the file
    """
    if not path:
        url = repo_url(kind, global_dir)
    else:
        if kind[0] == '/':
            kind = kind[1:]
        url = 'https://raw.githubusercontent.com/github/gitignore/master/%s' % kind

    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.text


def search_for_file(kind: str) -> str:
    """
    Search for file in https://github.com/github/gitignore
    """
    headers = {
        'User-Agent': 'giti.py/'+__version__,
        'Accept': 'application/vnd.github.v3+json'
    }
    r = requests.get('https://api.github.com/search/code?q=repo:github/gitignore %s' % kind, headers=headers)
    cont = r.json()

    # Check is any result match when ignoring case
    for i in range(0, len(cont['items'])):
        name = cont['items'][i]['name'].split('.')[0]
        if name.lower() == kind.lower():
            print("Found match {}".format(name))
            return cont['items'][i]['path']

    if len(cont['items']) < 1:
        print("Search found nothing")
        return None

    print('One of these might be good:')
    for i in range(0, len(cont['items'])):
        name = cont['items'][i]['name'].split('.')[0]
        print('[%s] %s' % (i, name))

    try:
        choice = input('Enter index [0]: ')
        if choice == "":
            choice = 0
        else:
            choice = int(choice)
    except TypeError:
        return None
    except KeyboardInterrupt:
        print('\n')
        return None

    if -1 < choice < len(cont['items']):
        return cont['items'][choice]['path']
    else:
        return None


def save_file(file: str):
    """
    Store content in file
    """
    merge = 'y'
    replace = 'n'
    if os.path.isfile('.gitignore'):
        try:
            merge = input('Do you want to merge with existing .gitignore [Y/n]: ')
            merge = 'y' if merge == '' else 'n'
        except KeyError:
            merge = 'y'
        except KeyboardInterrupt:
            terminate_gracefully()

        if merge.lower() == "n":
            try:
                replace = input('Do you want to replace existing .gitignore [y/N]: ')
            except KeyError:
                replace = 'n'
            except KeyboardInterrupt:
                terminate_gracefully()

    if merge.lower() == 'y':
        with open('.gitignore', 'a') as f:
            f.write(file)
        print('.gitignore baked :)')

    elif replace.lower() == 'y':
        with open('.gitignore', 'w') as f:
            f.write(file)
        print('.gitignore replaced')

    else:
        print('Did nothing, your .gitignore lives like before')


def giti(kind: str):
    kind = kind[0].upper() + kind[1:]
    print('Fetching .gitignore for %s' % kind)

    gifile = get_ignore_file(kind)

    if not gifile:
        print('Not found in master')
        gifile = get_ignore_file(kind, global_dir=True)

    if not gifile:
        print('Found no exact match, let\'s give searching a try...')
        filepath = search_for_file(kind)
        if not filepath:
            terminate_gracefully()
        gifile = get_ignore_file(filepath, path=True)

    if not gifile:
        terminate_gracefully()

    save_file(gifile)

def terminate_gracefully():
    print('Can\'t help any more, exiting')
    print('No changes made')
    exit(0)


def show_help():
    print('Usage: giti [language or stuff]')
    print('giti v%s' % __version__)


def main():
    if len(sys.argv) == 2:
        giti(sys.argv[1])
    else:
        show_help()

if __name__ == '__main__':
    main()