bump_copyright.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 """
3 Walk the directory tree and replace the '20XX' copyright dates in lines with
4 'Copyright 2003-20XX' with '2016'. Usage:
5 
6  ./bump_copyright.py # use "." as the start directory
7  ./bump_copyright.py dirname # use dirname as the start directory
8 """
9 
10 from __future__ import print_function
11 import os
12 import re
13 import sys
14 
15 
16 search_string = r'Copyright \(c\) 2003-20\d\d'
17 replace_string = r'Copyright (c) 2003-2020'
18 
19 
20 def has_hidden_dirs(dirpath):
21  """
22  Check if the directory path has any directories leading with a '.' (accept
23  the current working directory as okay).
24  """
25  dirs = dirpath.split("/")
26  for dir in dirs:
27  # match - anchor a "." at the beginning, then 1 or more of any char
28  m = re.match(r'^\.(.+)', dir)
29  if m:
30  return True
31  return False
32 
33 
34 def get_the_paths(root_dir):
35  """
36  Get all the files NOT in hidden directories
37  """
38  path_collection = []
39  for dirpath, dirnames, filenames in os.walk(root_dir):
40  use_dir = not has_hidden_dirs(dirpath)
41  if use_dir:
42  for filename in filenames:
43  # Don't try to replace the strings in this script
44  if not re.search(sys.argv[0].split("/")[-1], filename):
45  fullpath = os.path.join(dirpath, filename)
46  path_collection.append(fullpath)
47  return path_collection
48 
49 
50 def do_the_subs(path_collection, search, replace):
51  """
52  Look for the copyright string and sub the date
53  """
54  for path in path_collection:
55  with open(path, 'r+') as p:
56  contents = p.read()
57  pattern = re.compile(search)
58  contents = pattern.sub(replace, contents)
59  p.seek(0)
60  p.truncate()
61  p.write(contents)
62 
63 
64 if __name__ == '__main__':
65 
66  if '-h' in sys.argv or '--help' in sys.argv:
67  print(__doc__)
68  sys.exit(1)
69 
70  d = "."
71  if len(sys.argv) > 1:
72  d = sys.argv[1]
73 
74  path_collection = get_the_paths(d)
75  do_the_subs(path_collection, search_string, replace_string)
int open(const char *, int)
Opens a file descriptor.
void split(std::string const &s, char c, OutIter dest)
Definition: split.h:35