]> git.evergreen-ils.org Git - working/Evergreen.git/blob - build/i18n/scripts/add_translations.py
LP2045292 Color contrast for AngularJS patron bills
[working/Evergreen.git] / build / i18n / scripts / add_translations.py
1 #!/usr/bin/env python3
2 # -*- Mode: python; coding: utf-8 -*-
3 # ---------------------------------------------------------------
4 # Copyright © 2015 Jason J.A. Stephenson <jason@sigio.com>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 # ---------------------------------------------------------------
16
17 """A program to assist with the process of adding new po and pot files
18 into the Evergreen git repository.
19 """
20
21 import argparse, os, re, subprocess
22
23 __version__ = "1.0.2"
24
25 modifiedFiles = []
26 acceptedFiles = []
27 rejectedFiles = []
28
29 def cd_root():
30     """Change working directory to the root of the git repository."""
31     with subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], 
32                            stdout=subprocess.PIPE) as git:
33         output = git.stdout.read().decode('utf8')
34         directory = output.strip()
35         if directory != os.getcwd():
36             os.chdir(directory)
37
38 def commit():
39     """Commit the accepted files into git with a default message."""
40     with subprocess.Popen(['git', 'commit', '-sm',
41                            'Translation updates - newpot'],
42                           stdout=subprocess.PIPE) as git:
43         output = git.stdout.read().decode('utf8')
44         return output
45
46 def get_files():
47     """Get list of changed or new files in build/i18n/po."""
48     args = ['git', 'status', '--porcelain', '--', 'build/i18n/po']
49     with subprocess.Popen(args, stdout=subprocess.PIPE) as git:
50         lines = git.stdout.read().decode('utf8').splitlines()
51         for line in lines:
52             if line.startswith(' M'):
53                 modifiedFiles.append(line[3:])
54             elif line.startswith('??'):
55                 path = line[3:]
56                 if os.path.isdir(path):
57                     path += '.'
58                 acceptedFiles.append(path)
59
60 def add_files():
61     """Stage (git add) accepted files to be committed."""
62     args = ['git', 'add']
63     args += acceptedFiles
64     with subprocess.Popen(args, stdout=subprocess.PIPE) as git:
65         output = git.stdout.read().decode('utf8')
66         return output
67
68 def reset_files():
69     """'Reset' rejected file changes by checking the files out again."""
70     args = ['git', 'checkout', '--']
71     args += rejectedFiles
72     with subprocess.Popen(args, stdout=subprocess.PIPE) as git:
73         output = git.stdout.read().decode('utf8')
74         return output
75
76 def diff_file(file):
77     """Run git diff to get file changes."""
78     with subprocess.Popen(['git', 'diff', file], stdout=subprocess.PIPE) as git:
79         output = git.stdout.read().decode('utf8')
80         return output
81
82 def process_modified():
83     """Process diff output and ask human if a change should be kept."""
84     for file in modifiedFiles:
85         print(diff_file(file))
86         print('====================  K for keep ==')
87         x = input()
88         if x == 'k' or x == 'K':
89             acceptedFiles.append(file)
90         else:
91             rejectedFiles.append(file)
92
93 def autoprocess_modified():
94     """Process diff output without human intervention."""
95     isDiff = re.compile(r'^(?:\+[^\+]|-[^-])')
96     isMeta = re.compile(r'^(?:\+|-)"[-a-zA-z]+: ')
97     for file in modifiedFiles:
98         keep = False
99         diffLines = diff_file(file).splitlines()
100         for line in diffLines:
101             if re.match(isDiff, line) and not re.match(isMeta, line):
102                 keep = True
103                 break
104         if keep:
105             acceptedFiles.append(file)
106         else:
107             rejectedFiles.append(file)
108
109 def parse_arguments():
110     """Parse command line arguments."""
111     parser = argparse.ArgumentParser(
112         description=__doc__,
113         epilog="Run this in your Evergreen git repo after running make newpot."
114     )
115     parser.add_argument("-m", "--manual", action="store_true",
116                         help="manually decide which files to add")
117     parser.add_argument("-c", "--commit", action="store_true",
118                         help="automatically commit added files")
119     return parser.parse_args()
120         
121 def main():
122     arguments = parse_arguments()
123     cd_root()
124     get_files()
125     if arguments.manual:
126         process_modified()
127     else:
128         autoprocess_modified()
129     if len(rejectedFiles) > 0:
130         reset_files()
131     if len(acceptedFiles) > 0:
132         add_files()
133         if arguments.commit:
134             print(commit())
135
136 ########################################
137
138 if __name__ == '__main__':
139     main()