PageRenderTime 63ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/relic/relic

https://bitbucket.org/lahabana/mozilla-central
Python | 2457 lines | 2324 code | 38 blank | 95 comment | 84 complexity | 5b9034b45760e048515e2881c9d79d2e MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0, AGPL-1.0, LGPL-2.1, BSD-3-Clause, JSON, 0BSD, MIT, MPL-2.0-no-copyleft-exception
  1. #!/usr/bin/python
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. # Adapted from the 'lick' and 'ripl' Python scripts. (See:
  6. # <http://bugzilla.mozilla.org/show_bug.cgi?id=98089>)
  7. """
  8. relic - RE-LICense a given file, set of files, or directory of files
  9. from the Mozilla source tree
  10. Usage:
  11. relic [options...] [files...]
  12. relic [options...] < files...
  13. Options to Select Mode (use one):
  14. <none> List the licenses in each file.
  15. -s, --statistics Should a summary table of licenses in each file.
  16. The -x, --extended option may be added to show
  17. some additional detail to the stats.
  18. -r, --relicense Modify the given files to include to
  19. appropriate Mozilla license, where
  20. "appropriate" is either the NPL/GPL/LPGL
  21. tri-license if was already under the NPL or
  22. the MPL/LPGL/GPL license in all other cases.
  23. -R, --force-relicense
  24. Relicenses files (as -r|--relicense), but
  25. does NOT skip files that already appear to
  26. have a complete license.
  27. -A, --add Add a license to files that do not appear to
  28. have one.
  29. -I, --initial-developers
  30. Display initial developer for each file.
  31. General Options:
  32. -h, --help dump this help and exit
  33. -V, --version dump this script's version and exit
  34. -v, --verbose verbose output
  35. -d, --debug more verbose output
  36. -f, --force Continue processing after an error. (Errors
  37. are summarized at end.)
  38. -q, --quick Quick scanning. Use only basic license checks
  39. (only use in report mode).
  40. -M, --MPL Replace NPL licenses with MPL ones.
  41. -a, --all Check all files (only skip CVS directories).
  42. --dry-run Go through motions but don't actually change
  43. any files.
  44. --backup Make backups of changes files with
  45. relicensing. Backup filenames are the
  46. original filename suffixed with a ~# where
  47. "#" is the lowest number to avoid a file
  48. conflict.
  49. -o <orig_code_is> Provide fallback value for the "Original
  50. Code is" block.
  51. -D <orig_code_date> Provide fallback value for the date
  52. that is part of the "Original Code is" block.
  53. -i <initial_dev> Provide fallback value for the "Initial
  54. Developer of the Original Code is" block.
  55. -y <year> Provide fallback value for "Initial
  56. Developer" copyright year.
  57. --defaults Use the following default fallback values:
  58. original_code_is: "mozilla.org Code"
  59. initial_copyright_date: "2001"
  60. initial_developer: "Netscape Communications
  61. Corporation"
  62. Note: the "Original Code" date is generally
  63. not required, so a default is not included
  64. here.
  65. Examples:
  66. # List license in files under mozilla/js/src.
  67. relic mozilla/js/src # list licenses in files
  68. relic -s mozilla/js/src # show summary stats on licenses
  69. relic -r mozilla/js/src # re-license files
  70. """
  71. import os
  72. import sys
  73. import re
  74. import getopt
  75. import pprint
  76. import shutil
  77. class RelicError(Exception):
  78. pass
  79. #---- setup logging
  80. try:
  81. # This package will be std in Python 2.3, but many Python 2.2
  82. # installation will not have it.
  83. import logging
  84. logging.basicConfig()
  85. except ImportError:
  86. # Local fallback logging module.
  87. try:
  88. import _logging as logging
  89. except ImportError:
  90. sys.stderr.write("Your Python installation does not have the logging "
  91. "package, nor could the fallback _logging module be "
  92. "found. One of the two is required to run this "
  93. "script.\n\n")
  94. raise
  95. log = logging.getLogger("relic")
  96. #---- globals
  97. _version_ = (0, 7, 2)
  98. # When processing files, 'relic' skips files and directories according
  99. # to these settings. Note: files identified in .cvsignore files are also
  100. # skipped.
  101. _g_skip_exts = [".mdp", ".order", ".dsp", ".dsw", ".uf"]
  102. _g_skip_file_basenames = [
  103. # Used by CVS (and this script)
  104. ".cvsignore",
  105. # GPL with autoconf exception
  106. "config.guess",
  107. "config.sub",
  108. # Auto-generated from other files
  109. "configure",
  110. # license and readme files
  111. "license",
  112. "readme",
  113. "copyright",
  114. "LICENSE-MPL",
  115. "MPL-1.1.txt",
  116. ]
  117. _g_skip_files = [
  118. # TODO: update with MPL block - or CVS remove (check history)
  119. "tools/wizards/templates/licenses/MPL/lic.mak",
  120. "tools/wizards/templates/licenses/MPL/lic.pl",
  121. ###########################################################################
  122. # Everything in _g_skip_files below this line needs no further work.
  123. ###########################################################################
  124. # Files containing copies of licence text which confuses the script
  125. "LICENSE",
  126. "js2/COPYING",
  127. "security/svrcore/LICENSE",
  128. "extensions/xmlterm/doc/MPL",
  129. "gfx/cairo/cairo/COPYING-LGPL-2.1",
  130. "gfx/cairo/cairo/COPYING-MPL-1.1",
  131. # Files containing global licensing information
  132. "xpfe/global/resources/content/license.html",
  133. "toolkit/content/license.html",
  134. # Ben Bucksch - files are tri-licensed with an extra clause.
  135. "netwerk/streamconv/converters/mozTXTToHTMLConv.cpp",
  136. "netwerk/streamconv/converters/mozTXTToHTMLConv.h",
  137. "netwerk/streamconv/public/mozITXTToHTMLConv.idl",
  138. # GPLed build tools
  139. "config/preprocessor.pl",
  140. "intl/uconv/tools/parse-mozilla-encoding-table.pl",
  141. "intl/uconv/tools/gen-big5hkscs-2001-mozilla.pl",
  142. "js2/missing",
  143. # Files which the script doesn't handle well. All have been relicensed
  144. # manually.
  145. "xpinstall/wizard/windows/builder/readme.txt",
  146. "xpfe/bootstrap/icons/windows/readme.txt",
  147. "embedding/qa/testembed/README.TXT",
  148. "security/nss/lib/freebl/ecl/README.FP",
  149. "nsprpub/pkg/linux/sun-nspr.spec",
  150. "security/nss/pkg/linux/sun-nss.spec",
  151. "security/jss/pkg/linux/sun-jss.spec",
  152. "security/nss/lib/freebl/mpi/utils/README",
  153. "security/nss/lib/freebl/ecl/README",
  154. "security/nss/lib/freebl/mpi/README",
  155. "lib/mac/UserInterface/Tables/TableClasses.doc",
  156. "parser/htmlparser/tests/html/bug23680.html",
  157. "security/nss/lib/freebl/mpi/montmulfv9.s",
  158. "tools/performance/pageload/base/lxr.mozilla.org/index.html",
  159. "testing/performance/win32/page_load_test/" +\
  160. "base/lxr.mozilla.org/index.html",
  161. "testing/performance/win32/page_load_test/" +\
  162. "base/lxr.mozilla.org/20001028.html.orig",
  163. # Not sure what to do with this...
  164. "gfx/cairo/stdint.diff",
  165. # GPL with autoconf exception (same license as files distributed with)
  166. "build/autoconf/codeset.m4",
  167. "toolkit/airbag/airbag/autotools/depcomp",
  168. "toolkit/airbag/airbag/autotools/missing",
  169. "toolkit/airbag/airbag/autotools/ltmain.sh",
  170. "js/tamarin/pcre/ltmain.sh",
  171. "security/svrcore/compile",
  172. "security/svrcore/ltmain.sh",
  173. "security/svrcore/missing",
  174. "security/svrcore/depcomp",
  175. "security/svrcore/aclocal.m4",
  176. # Public domain or equivalent
  177. "nsprpub/config/nspr.m4",
  178. "toolkit/airbag/airbag/aclocal.m4",
  179. "security/nss/lib/freebl/mpi/mp_comba_amd64_sun.s",
  180. # GSSAPI has BSD-like licence requiring some attribution
  181. "extensions/auth/gssapi.h",
  182. # This script
  183. "tools/relic/relic",
  184. ]
  185. _g_skip_dir_basenames = [
  186. "CVS",
  187. ]
  188. _g_skip_dir_basenames_cvs_only = [
  189. "CVS",
  190. ]
  191. # Complete path from mozilla dir to a dir to skip.
  192. _g_skip_dirs = [
  193. # Test files for this script, which cause it to crash!
  194. "tools/relic/test",
  195. # License template files (TODO: this directory may disappear)
  196. "tools/wizards/templates/licenses",
  197. # As per the "New Original Source Files" section of:
  198. # http://www.mozilla.org/MPL/license-policy.html
  199. # with obsolete or now-relicensed directories removed
  200. "apache", # Obsolete mod_gzip code
  201. "cck", # mkaply's baby; not core code anyway.
  202. "dbm",
  203. "js/rhino", # Currently MPL/GPL - may end up BSD
  204. "webtools", # Various MPLed webtools
  205. # These could be done, but no-one's clamouring for it, and it's a hassle
  206. # sorting it all out, so let sleeping dogs lie.
  207. "msgsdk",
  208. "java",
  209. "privacy",
  210. # These have their own BSD-like license
  211. "media/libjpeg",
  212. # The following are not supposed to be relicensed, but they do have a
  213. # few files in we care about (like makefiles)
  214. "media/libpng",
  215. "modules/zlib",
  216. "gc/boehm",
  217. "other-licenses",
  218. # Copy of GPLed tool
  219. "tools/buildbot",
  220. # Other directories we want to exclude
  221. "embedding/tests", # Agreed as BSD
  222. "calendar/libical", # LGPL/MPL
  223. "gfx/cairo/cairo/src", # LGPL/MPL
  224. ]
  225. _g_basename_to_comment_info = {
  226. "configure": (["dnl"], ),
  227. "Makefile": (["#"], ),
  228. "makefile": (["#"], ),
  229. "nfspwd": (["#"], ),
  230. "typemap": (["#"], ),
  231. "xmplflt.conf": (["#"], ),
  232. "ldapfriendly": (["#"], ),
  233. "ldaptemplates.conf": (["#"], ),
  234. "ldapsearchprefs.conf": (["#"], ),
  235. "ldapfilter.conf": (["#"], ),
  236. "README.configure": (["#"], ),
  237. "Options.txt": (["#"], ),
  238. "fdsetsize.txt": (["#"], ),
  239. "prototype": (["#"], ),
  240. "prototype_i386": (["#"], ),
  241. "prototype3_i386": (["#"], ),
  242. "prototype_com": (["#"], ),
  243. "prototype3_com": (["#"], ),
  244. "prototype_sparc": (["#"], ),
  245. "prototype3_sparc": (["#"], ),
  246. "nglayout.mac": (["#"], ),
  247. "pkgdepend": (["#"], ),
  248. "Maketests": (["#"], ),
  249. "depend": (["#"], ),
  250. "csh-aliases": (["#"], ),
  251. "csh-env": (["#"], ),
  252. ".cshrc": (["#"], ),
  253. "MANIFEST": (["#"], ),
  254. "mozconfig": (["#"], ),
  255. "makecommon": (["#"], ),
  256. "bld_awk_pkginfo": (["#"], ),
  257. "prototype_i86pc": (["#"], ),
  258. "pkgdepend_5_6": (["#"], ),
  259. "awk_pkginfo-i386": (["#"], ),
  260. "awk_pkginfo-sparc": (["#"], ),
  261. "pkgdepend_64bit": (["#"], ),
  262. "WIN32": (["#"], ),
  263. "WIN16": (["#"], ),
  264. "Makefile.linux": (["#"], ),
  265. "README": ([""], ["#"]),
  266. "copyright": ([""], ),
  267. "xptcstubs_asm_ppc_darwin.s.m4": (["/*", "*", "*/"], ),
  268. "xptcstubs_asm_mips.s.m4": (["/*", "*", "*/"], ),
  269. "nsIDocCharsetTest.txt": (["<!--", "-", "-->"], ),
  270. "nsIFontListTest.txt": (["<!--", "-", "-->"], ),
  271. "ComponentListTest.txt": (["<!--", "-", "-->"], ),
  272. "nsIWebBrowserPersistTest1.txt": (["<!--", "-", "-->"], ),
  273. "nsIWebBrowserPersistTest2.txt": (["<!--", "-", "-->"], ),
  274. "nsIWebBrowserPersistTest3.txt": (["<!--", "-", "-->"], ),
  275. "plugins.txt": (["<!--", "-", "-->"], ),
  276. "NsISHistoryTestCase1.txt": (["<!--", "-", "-->"], ),
  277. "EmbedSmokeTest.txt": (["<!--", "-", "-->"], ),
  278. "lineterm_LICENSE": (["/*", "*", "*/"], ),
  279. "XMLterm_LICENSE": (["/*", "*", "*/"], ),
  280. "BrowserView.cpp.mod": (["/*", "*", "*/"], ),
  281. "header_template": (["/*", "*", "*/"], ),
  282. "cpp_template": (["/*", "*", "*/"], ),
  283. "abcFormat470.txt": (["//"], ),
  284. "opcodes.tbl": (["//"], ),
  285. }
  286. _g_ext_to_comment_info = {
  287. ".txt": (["##", "#", ], ["#"]),
  288. ".TXT": (["##", "#", ]),
  289. ".doc": (["", ]),
  290. ".build": (["", ]),
  291. ".1st": (["", ]),
  292. ".lsm": (["", ]),
  293. ".FP": (["", ]),
  294. ".spec": (["", ]),
  295. ".CPP": (["/*", "*", "*/"], ),
  296. ".cpp": (["/*", "*", "*/"], ),
  297. ".H": (["/*", "*", "*/"], ),
  298. ".h": (["/*", "*", "*/"], ),
  299. ".hxx": (["/*", "*", "*/"], ),
  300. ".c": (["/*", "*", "*/"], ),
  301. ".css": (["/*", "*", "*/"], ['#']),
  302. ".js": (["/*", "*", "*/"], ['#']),
  303. ".idl": (["/*", "*", "*/"], ),
  304. ".ut": (["/*", "*", "*/"], ),
  305. ".rc": (["/*", "*", "*/"], ),
  306. ".rc2": (["/*", "*", "*/"], ),
  307. ".RC": (["/*", "*", "*/"], ),
  308. ".Prefix": (["/*", "*", "*/"], ),
  309. ".prefix": (["/*", "*", "*/"], ),
  310. ".cfg": (["/*", "*", "*/"], ["#"]),
  311. ".cp": (["/*", "*", "*/"], ),
  312. ".cs": (["/*", "*", "*/"], ),
  313. ".java": (["/*", "*", "*/"], ),
  314. ".jst": (["/*", "*", "*/"], ),
  315. ".tbl": (["/*", "*", "*/"], ),
  316. ".tab": (["/*", "*", "*/"], ),
  317. ".cc": (["/*", "*", "*/"], ),
  318. ".msg": (["/*", "*", "*/"], ),
  319. ".y": (["/*", "*", "*/"], ),
  320. ".r": (["/*", "*", "*/"], ),
  321. ".mm": (["/*", "*", "*/"], ),
  322. ".x-ccmap":(["/*", "*", "*/"], ),
  323. ".ccmap": (["/*", "*", "*/"], ),
  324. ".sql": (["/*", "*", "*/"], ),
  325. ".pch++": (["/*", "*", "*/"], ),
  326. ".xpm": (["/*", "*", "*/"], ),
  327. ".uih": (["/*", "*", "*/"], ),
  328. ".uil": (["/*", "*", "*/"], ),
  329. ".ccmap": (["/*", "*", "*/"], ),
  330. ".map": (["/*", "*", "*/"], ),
  331. ".win98": (["/*", "*", "*/"], ),
  332. ".php": (["/*", "*", "*/"], ),
  333. ".m": (["/*", "*", "*/"], ),
  334. ".jnot": (["/*", "*", "*/"], ),
  335. ".l": (["/*", "*", "*/"], ),
  336. ".htp": (["/*", "*", "*/"], ),
  337. ".xs": (["/*", "*", "*/"], ),
  338. ".as": (["/*", "*", "*/"], ),
  339. ".api": (["/*", "*", "*/"], ['#']),
  340. ".applescript": (["(*", "*", "*)"], ["--"], ["#"]),
  341. ".html": (["<!--", "-", "-->"], ["#"]),
  342. ".xml": (["<!--", "-", "-->"], ["#"]),
  343. ".xbl": (["<!--", "-", "-->"], ["#"]),
  344. ".xsl": (["<!--", "-", "-->"], ),
  345. ".xul": (["<!--", "-", "-->"], ["#"]),
  346. ".dtd": (["<!--", "-", "-->"], ["#"]),
  347. ".rdf": (["<!--", "-", "-->"], ["#"]),
  348. ".htm": (["<!--", "-", "-->"], ),
  349. ".out": (["<!--", "-", "-->"], ),
  350. ".resx": (["<!--", "-", "-->"], ),
  351. ".bl": (["<!--", "-", "-->"], ),
  352. ".xif": (["<!--", "-", "-->"], ),
  353. ".xhtml":(["<!--", "-", "-->"], ["#"]),
  354. ".inc": (["<!--", "-", "-->"],
  355. ["#"],
  356. ["@!"],
  357. ["/*", "*", "*/"]),
  358. ".properties": (["#"], ),
  359. ".win": (["#"], ),
  360. ".dsp": (["#"], ),
  361. ".exp": (["#"], ),
  362. ".mk": (["#"], ),
  363. ".mn": (["#"], ),
  364. ".mak": (["#"], ),
  365. ".MAK": (["#"], ),
  366. ".perl": (["#"], ),
  367. ".pl": (["#"], ),
  368. ".PL": (["#"], ),
  369. ".sh": (["#"], ),
  370. ".dsw": (["#"], ),
  371. ".cgi": (["#"], ),
  372. ".pm": (["#"], ),
  373. ".pod": (["#"], ),
  374. ".src": (["#"], ),
  375. ".csh": (["#"], ),
  376. ".DLLs": (["#"], ),
  377. ".ksh": (["#"], ),
  378. ".toc": (["#"], ),
  379. ".am": (["#"], ),
  380. ".df": (["#"], ),
  381. ".client": (["#"], ),
  382. ".ref": (["#"], ), # all of them "Makefile.ref"
  383. ".ldif": (["#"], ),
  384. ".ex": (["#"], ),
  385. ".reg": (["#"], ),
  386. ".py": (["#"], ),
  387. ".adb": (["#"], ),
  388. ".dtksh": (["#"], ),
  389. ".pkg": (["#"], ),
  390. ".et": (["#"], ),
  391. ".stub": (["#"], ),
  392. ".nss": (["#"], ),
  393. ".os2": (["#"], ),
  394. ".Solaris": (["#"], ),
  395. ".rep": (["#"], ),
  396. ".NSS": (["#"], ),
  397. ".server": (["#"], ),
  398. ".awk": (["#"], ),
  399. ".targ": (["#"], ),
  400. ".gnuplot": (["#"], ),
  401. ".bash": (["#"], ),
  402. ".tmpl": (["#"], ),
  403. ".com": (["#"], ),
  404. ".dat": (["#"], ),
  405. ".rpm": (["#"], ),
  406. ".nsi": (["#"], ),
  407. ".nsh": (["#"], ),
  408. ".template": (["#"], ),
  409. ".ldkd": (["#"], ),
  410. ".ldku": (["#"], ),
  411. ".arm": (["#"], ),
  412. ".tdf": ([";"], ),
  413. ".def": ([";+#"], [";"]),
  414. ".DEF": ([";+#"], [";"]),
  415. ".ini": ([";"], ),
  416. ".it": ([";"], ),
  417. ".lisp": ([";;;"], ),
  418. ".cmd": (["rem"], ["REM"]),
  419. ".bat": (["rem"], ["REM"]),
  420. ".tex": (["%"], ),
  421. ".texi": (["%"], ),
  422. ".m4": (["dnl"], ),
  423. ".asm": ([";"], ),
  424. ".vbs": (["'"], ),
  425. ".il": (["!"], ),
  426. ".ad": (["!"], ),
  427. ".script": (["(*", " *", "*)"], ),
  428. ".3x": (['.\\"'], ),
  429. # What a mess...
  430. ".s": (["#"], ["//"], ["/*", "*", "*/"], ["!"], [";"], ["/"]),
  431. }
  432. _g_shebang_pattern_to_comment_info = [
  433. (re.compile(ur'\A#!.*/bin/(ba)?sh.*$', re.IGNORECASE), (["#"], )),
  434. (re.compile(ur'\A#!.*perl.*$', re.IGNORECASE), (["#"], )),
  435. (re.compile(ur'\A#!.*php.*$', re.IGNORECASE), (["#"], )),
  436. (re.compile(ur'\A#!.*python.*$', re.IGNORECASE), (["#"], )),
  437. (re.compile(ur'\A#!.*ruby.*$', re.IGNORECASE), (["#"], )),
  438. (re.compile(ur'\A#!.*tclsh.*$', re.IGNORECASE), (["#"], )),
  439. (re.compile(ur'\A#!.*wish.*$', re.IGNORECASE), (["#"], )),
  440. (re.compile(ur'\A#!.*expect.*$', re.IGNORECASE), (["#"], )),
  441. ]
  442. _g_trilicense_parts = {
  443. "mpl": """\
  444. ***** BEGIN LICENSE BLOCK *****
  445. Version: MPL 1.1/GPL 2.0/LGPL 2.1
  446. The contents of this file are subject to the Mozilla Public License Version
  447. 1.1 (the "License"); you may not use this file except in compliance with
  448. the License. You may obtain a copy of the License at
  449. http://www.mozilla.org/MPL/
  450. Software distributed under the License is distributed on an "AS IS" basis,
  451. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  452. for the specific language governing rights and limitations under the
  453. License.
  454. """,
  455. "npl": """\
  456. ***** BEGIN LICENSE BLOCK *****
  457. Version: NPL 1.1/GPL 2.0/LGPL 2.1
  458. The contents of this file are subject to the Netscape Public License
  459. Version 1.1 (the "License"); you may not use this file except in
  460. compliance with the License. You may obtain a copy of the License at
  461. http://www.mozilla.org/NPL/
  462. Software distributed under the License is distributed on an "AS IS" basis,
  463. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  464. for the specific language governing rights and limitations under the
  465. License.
  466. """,
  467. "original_code_is": """\
  468. The Original Code is %(original_code_is)s.
  469. """,
  470. "original_code_is_with_date": """\
  471. The Original Code is %(original_code_is)s, released
  472. %(original_code_date)s.
  473. """,
  474. "initial_developer": """\
  475. The Initial Developer of the Original Code is
  476. %(initial_developer)s.
  477. Portions created by the Initial Developer are Copyright (C) %(initial_copyright_date)s
  478. the Initial Developer. All Rights Reserved.
  479. """,
  480. "contributors": """\
  481. Contributor(s):
  482. %s
  483. """,
  484. "gpl for mpl": """\
  485. Alternatively, the contents of this file may be used under the terms of
  486. the GNU General Public License Version 2 or later (the "GPL"), in which
  487. case the provisions of the GPL are applicable instead of those above. If
  488. you wish to allow use of your version of this file only under the terms of
  489. the GPL and not to allow others to use your version of this file under the
  490. MPL, indicate your decision by deleting the provisions above and replacing
  491. them with the notice and other provisions required by the GPL. If you do
  492. not delete the provisions above, a recipient may use your version of this
  493. file under either the MPL or the GPL.
  494. ***** END LICENSE BLOCK *****""",
  495. "gpl for npl": """\
  496. Alternatively, the contents of this file may be used under the terms of
  497. the GNU General Public License Version 2 or later (the "GPL"), in which
  498. case the provisions of the GPL are applicable instead of those above. If
  499. you wish to allow use of your version of this file only under the terms of
  500. the GPL and not to allow others to use your version of this file under the
  501. NPL, indicate your decision by deleting the provisions above and replacing
  502. them with the notice and other provisions required by the GPL. If you do
  503. not delete the provisions above, a recipient may use your version of this
  504. file under either the NPL or the GPL.
  505. ***** END LICENSE BLOCK *****""",
  506. "gpl/lgpl for mpl": """\
  507. Alternatively, the contents of this file may be used under the terms of
  508. either the GNU General Public License Version 2 or later (the "GPL"), or
  509. the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  510. in which case the provisions of the GPL or the LGPL are applicable instead
  511. of those above. If you wish to allow use of your version of this file only
  512. under the terms of either the GPL or the LGPL, and not to allow others to
  513. use your version of this file under the terms of the MPL, indicate your
  514. decision by deleting the provisions above and replace them with the notice
  515. and other provisions required by the GPL or the LGPL. If you do not delete
  516. the provisions above, a recipient may use your version of this file under
  517. the terms of any one of the MPL, the GPL or the LGPL.
  518. ***** END LICENSE BLOCK *****""",
  519. "gpl/lgpl for npl": """\
  520. Alternatively, the contents of this file may be used under the terms of
  521. either the GNU General Public License Version 2 or later (the "GPL"), or
  522. the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  523. in which case the provisions of the GPL or the LGPL are applicable instead
  524. of those above. If you wish to allow use of your version of this file only
  525. under the terms of either the GPL or the LGPL, and not to allow others to
  526. use your version of this file under the terms of the NPL, indicate your
  527. decision by deleting the provisions above and replace them with the notice
  528. and other provisions required by the GPL or the LGPL. If you do not delete
  529. the provisions above, a recipient may use your version of this file under
  530. the terms of any one of the NPL, the GPL or the LGPL.
  531. ***** END LICENSE BLOCK *****""",
  532. }
  533. _g_dry_run = 0 # iff true, don't modify any files
  534. _g_force = 0
  535. _g_check_all = 0
  536. #---- internal support routines
  537. def _is_binary(filename):
  538. """Return true iff the given filename is binary.
  539. Raises an EnvironmentError if the file does not exist or cannot be
  540. accessed.
  541. """
  542. fin = open(filename, 'rb')
  543. try:
  544. CHUNKSIZE = 1024
  545. while 1:
  546. chunk = fin.read(CHUNKSIZE)
  547. if '\0' in chunk: # found null byte
  548. return 1
  549. if len(chunk) < CHUNKSIZE:
  550. break # done
  551. finally:
  552. fin.close()
  553. return 0
  554. _g_cvsignore_cache = {} # optimization: keep a cache of .cvsignore content
  555. def _should_skip_according_to_cvsignore(path):
  556. dirname, basename = os.path.split(path)
  557. cvsignore = os.path.join(dirname, ".cvsignore")
  558. if not os.path.exists(cvsignore):
  559. return 0
  560. elif cvsignore not in _g_cvsignore_cache:
  561. fin = open(cvsignore, 'r')
  562. to_ignore = []
  563. try:
  564. for f in fin:
  565. if f[-1] == "\n": f = f[:-1] # chomp
  566. if not f: continue # skip empty lines
  567. to_ignore.append(f)
  568. finally:
  569. fin.close()
  570. _g_cvsignore_cache[cvsignore] = to_ignore
  571. # At this point .cvsignore exists and its contents are in the cache.
  572. to_ignore = _g_cvsignore_cache[cvsignore]
  573. if basename in to_ignore:
  574. return 1
  575. else:
  576. return 0
  577. _g_backup_pattern = re.compile("~\d+$")
  578. def _should_skip_file(path):
  579. log.debug("_should_skip_file(path='%s')", path)
  580. if _g_check_all:
  581. return 0
  582. ext = os.path.splitext(path)[1]
  583. if ext in _g_skip_exts:
  584. log.info("Skipping '%s' (according to '_g_skip_exts').", path)
  585. return 1
  586. xpath = '/'.join(path.split(os.sep)) # use same sep as in _g_skip_files
  587. for sf in _g_skip_files:
  588. if xpath.endswith(sf):
  589. log.info("Skipping '%s' (according to '_g_skip_files').", path)
  590. return 1
  591. if os.path.basename(path) in _g_skip_file_basenames:
  592. log.info("Skipping '%s' (according to '_g_skip_file_basenames').", path)
  593. return 1
  594. if _should_skip_according_to_cvsignore(path):
  595. log.info("Skipping '%s' (according to .cvsignore).", path)
  596. return 1
  597. if _g_backup_pattern.search(path):
  598. log.info("Skipping '%s' (looks like backup file).", path)
  599. return 1
  600. return 0
  601. def _should_skip_dir(path):
  602. log.debug("_should_skip_dir(path='%s')", path)
  603. if _g_check_all:
  604. if os.path.basename(path) in _g_skip_dir_basenames_cvs_only:
  605. return 1
  606. return 0
  607. if os.path.basename(path) in _g_skip_dir_basenames:
  608. log.info("Skipping '%s' (according to _g_skip_dir_basenames).", path)
  609. return 1
  610. xpath = '/'.join(path.split(os.sep)) # use same sep as in _g_skip_dirs
  611. # These could do with being a proper path canonicalisation function...
  612. if xpath[-1] == '/': xpath = xpath[:-1] # treat "calendar/" the same as "calendar"
  613. if xpath[0:2] == './': xpath = xpath[2:] # treat "./calendar" the same as "calendar"
  614. for sd in _g_skip_dirs:
  615. # Changed by gerv to make skip_dirs require whole path
  616. if xpath == sd:
  617. log.info("Skipping '%s' (according to _g_skip_dirs).", path)
  618. return 1
  619. if _should_skip_according_to_cvsignore(path):
  620. log.info("Skipping '%s' (according to .cvsignore).", path)
  621. return 1
  622. return 0
  623. def _get_license_info(filename, show_initial=0, quick=0):
  624. """Return license block information for the given file.
  625. "filename" is the path to the file to scan.
  626. "show_initial" is a boolean that indicates if initial developer info
  627. should be displayed.
  628. "quick" is a boolean that can be set for a quick scan. In this
  629. case, only the "parts" field of the return dictionary will
  630. be filled out.
  631. Returns a dictionary adequately describing the license block in the
  632. given file for the purpose of determining whether to patch the
  633. license block and how. Returns a dictionary of the following form:
  634. {"parts": <list of zero or more of "mpl", "npl", "gpl", "lgpl",
  635. "unknown", "block_begin", "block_end" in the
  636. order in which they were found>,
  637. # if necessary, the following keys are included as well
  638. "begin_line": <(0-based) index at which license block starts>,
  639. "end_line": <(0-based) index at which license block ends>,
  640. "first_prefix": <prefix to use for new license block first line>,
  641. "subsequent_prefix": <prefix to use for subsequent lines>,
  642. "last_suffix": <suffix to use for last line>,
  643. # The following fields are correspond to the file specific
  644. # portions of the license template as described here:
  645. # http://www.mozilla.org/MPL/relicensing-faq.html#new-license
  646. # If the associated block is not found, then the value is None.
  647. "original_code_is": ...,
  648. "original_code_date": ...,
  649. "initial_developer": ...,
  650. "initial_copyright_date": ...,
  651. "contributors": ...,
  652. }
  653. precondition: should not be called on binary files
  654. """
  655. lic_info = {
  656. "parts": [],
  657. }
  658. fin = open(filename, 'r')
  659. try:
  660. content = fin.read()
  661. finally:
  662. fin.close()
  663. # Help me find filena
  664. log.info("Next file is: %s", filename)
  665. # do quick search to see if any of the desired licenses is in here
  666. # - if it looks like all the parts are there, good, done
  667. # - if some but not all parts, continue
  668. parts_pattern = re.compile("""(
  669. (?P<block_begin>\*\*\*\*\*\ BEGIN\ LICENSE\ BLOCK\ \*\*\*\*\*)
  670. | (?P<mpl>The\ contents\ of\ this\ file\ are\ subject\ to\ the\ Mozilla)
  671. | (?P<npl>The\ contents\ of\ this\ file\ are\ subject\ to\ the\ Netscape)
  672. | (?P<gpl>GNU\ (General\ )?Public\ License)
  673. | (?P<lgpl>(Library|Lesser)\ General\ Public\ License)
  674. | (?P<block_end>\*\*\*\*\*\ END\ LICENSE\ BLOCK\ \*\*\*\*\*)
  675. )""",
  676. re.VERBOSE)
  677. parts = [] # found license parts in this file
  678. start = 0
  679. blocks = 0
  680. while 1:
  681. match = parts_pattern.search(content, start)
  682. if match:
  683. # Skip this block, if the last license block is more than 10 lines
  684. # away (file is probably used for autogeneration of files then).
  685. if blocks == 1 and (match.start()-start) > 10:
  686. break
  687. else:
  688. parts = match.groupdict()
  689. for part in parts:
  690. if parts[part]:
  691. lic_info["parts"].append(part)
  692. log.info("%s license/delimeter found", part)
  693. start = match.end()
  694. if part == "block_end":
  695. blocks = blocks + 1
  696. else:
  697. blocks = 0
  698. break
  699. else:
  700. raise RelicError("unexpected license part: %r" % parts)
  701. else:
  702. break
  703. # no license block at all
  704. if not parts:
  705. # - if not, check to see if License or Copyright shows up in the
  706. # file; if so, then error out; if not, skip out
  707. any_lic_pattern = re.compile("(Copyright|Licen[sc]e)", re.IGNORECASE)
  708. match = any_lic_pattern.search(content)
  709. if match:
  710. lic_info["parts"].append("unknown")
  711. log.info("unknown license found: %r",
  712. content[max(match.start()-20,0):match.end()+20])
  713. else:
  714. log.info("no license found")
  715. return lic_info
  716. # license block with non-tri-license version headers
  717. elif lic_info["parts"] == ["block_begin", "block_end"]:
  718. lic_info["parts"].append("unknown")
  719. log.info("unknown license found (license block with non-tri-license)")
  720. return lic_info
  721. # license block with tri-license version headers
  722. elif (lic_info["parts"] == ["block_begin", "mpl", "gpl", "lgpl", "block_end"] or
  723. lic_info["parts"] == ["block_begin", "npl", "gpl", "lgpl", "block_end"]):
  724. log.info("license looks good, no changes necessary")
  725. if quick:
  726. return lic_info
  727. # Otherwise, the license needs to be fixed, so gather more detailed
  728. # information. Here is the algorithm we will use:
  729. # - find first license line
  730. # - find the end of this comment block (assumption: from the first
  731. # license line to the end of the comment block is the full
  732. # license block)
  733. # This is a bad assumption in two cases and steps have been taken
  734. # to try to deal with those cases:
  735. # - There could be a trailing part bit of comment that is
  736. # NOT part of the license but is part of the same comment
  737. # block. A common example are the:
  738. # This Original Code has been modified by IBM...
  739. # files (about 130 of them in the moz tree).
  740. # (c.f. test_relicense_ibm_copyright_suffix.c)
  741. # - Some files have split up the license paragraphs into
  742. # multiple comment blocks, e.g.
  743. # "mozilla/build/unix/abs2rel.pl":
  744. # # The contents of this file are subject to the
  745. # # ...
  746. # # the License at http://www.mozilla.org/MPL/
  747. #
  748. # # The Initial Developer of the Original Code
  749. # # ...
  750. # # Rights Reserved.
  751. # (c.f. test_relicense_separated_license_comment_blocks.pl)
  752. # - these are the lines to replace
  753. # - gather embedded lic data
  754. # - use second line to determine line prefix
  755. # ? Should we only allow processing of unknown-delimiter-files with
  756. # an option?
  757. # Get comment delimiter info for this file.
  758. comment_delim_sets = _get_comment_delim_sets(filename)
  759. # - find first license line (and determine which set of comment
  760. # delimiters are in use)
  761. lines = content.splitlines()
  762. for comment_delims in comment_delim_sets:
  763. if len(comment_delims) == 3:
  764. # Note: allow for whitespace before continuation character
  765. prefix_pattern = "%s|\s*%s|" % (re.escape(comment_delims[0]),
  766. re.escape(comment_delims[1]))
  767. suffix_pattern = "%s" % re.escape(comment_delims[2])
  768. elif len(comment_delims) == 2:
  769. prefix_pattern = "%s|" % re.escape(comment_delims[0])
  770. suffix_pattern = "%s" % re.escape(comment_delims[1])
  771. elif len(comment_delims) == 1:
  772. prefix_pattern = re.escape(comment_delims[-1])
  773. suffix_pattern = ""
  774. else: # len(comment_delims) == 0
  775. prefix_pattern = ""
  776. suffix_pattern = ""
  777. lic_begin_pattern = re.compile("""
  778. ^(?P<prefix>%s)
  779. (?P<space>\s*)
  780. (\*+\ BEGIN\ LICENSE\ BLOCK\ \*+
  781. |\-+\ BEGIN\ LICENSE\ BLOCK\ \-+
  782. | Version:\ MPL\ \d+\.\d+/GPL\ \d+\.\d+/LGPL\ \d+\.\d+
  783. | The\ contents\ of\ this\ file\ are\ subject\ to\ the\ Mozilla[\w ]*
  784. | The\ contents\ of\ this\ file\ are\ subject\ to\ the\ Netscape[\w ]*
  785. | Alternatively,\ the\ contents\ of\ this\ file\ may\ be\ used\ under\ the[\w ]*)
  786. (?P<suffix>%s|)\s*?$
  787. """ % (prefix_pattern, suffix_pattern), re.VERBOSE)
  788. for i in range(len(lines)):
  789. match = lic_begin_pattern.search(lines[i])
  790. if match:
  791. beginline = {
  792. "content": lines[i],
  793. "linenum": i,
  794. "prefix": match.group("prefix"),
  795. "space": match.group("space"),
  796. "suffix": match.group("suffix")
  797. }
  798. # Optimization: If the line before the "beginline" is simply
  799. # a block comment open the include that line in parsed out
  800. # license block. E.g.,
  801. # <!--
  802. # - ***** BEGIN LICENSE BLOCK *****
  803. # ...
  804. if (len(comment_delims) > 1 # only for block comments
  805. and beginline["prefix"] != comment_delims[0]
  806. and i-1 >= 0
  807. and lines[i-1].strip() == comment_delims[0]):
  808. beginline["linenum"] -= 1
  809. beginline["prefix"] = comment_delims[0]
  810. break
  811. if match: break
  812. else:
  813. raise RelicError("couldn't find start line with this pattern (even "
  814. "though it looks like there is a license block in "
  815. "%s): %s" % (filename, lic_begin_pattern.pattern))
  816. log.info("comment delimiters: %s", comment_delims)
  817. log.debug("beginline dict: %s", beginline)
  818. lic_info["comment_delims"] = comment_delims
  819. lic_info["begin_line"] = beginline["linenum"]
  820. lic_info["first_prefix"] = beginline["prefix"]
  821. log.info("prefix for first line: '%s'", beginline["prefix"])
  822. # - get second license line
  823. lic_middle_pattern = re.compile("""
  824. ^(?P<prefix>%s|)
  825. (?P<space>\s*)
  826. (?P<content>.*)
  827. (?P<suffix>%s|)\s*?$
  828. """ % (prefix_pattern, suffix_pattern),
  829. re.VERBOSE)
  830. # skip empty lines which might result in bogus scanning later, e.g.:
  831. # mozilla/layout/html/tests/table/marvin/x_thead_align_center.xml
  832. second_linenum = beginline["linenum"]+1
  833. while second_linenum < len(lines):
  834. if lines[second_linenum].strip():
  835. break
  836. log.debug("skip blank 'second' line: %d", second_linenum)
  837. second_linenum +=1
  838. else:
  839. raise RelicError("all lines after the first license block line (%d) "
  840. "were empty" % (beginline["linenum"]+1))
  841. match = lic_middle_pattern.search(lines[second_linenum])
  842. if match:
  843. secondline = {
  844. "content": lines[second_linenum],
  845. "linenum": second_linenum,
  846. "prefix": match.group("prefix"),
  847. "space": match.group("space"),
  848. "suffix": match.group("suffix")
  849. }
  850. else:
  851. raise RelicError("didn't find second line with pattern: %s"
  852. % lic_middle_pattern.pattern)
  853. log.debug("secondline dict: %s", secondline)
  854. lic_info["subsequent_prefix"] = secondline["prefix"]
  855. log.info("prefix for subsequent lines: '%s'", secondline["prefix"])
  856. # - find block comment end
  857. orig_code_modified_pattern = re.compile("This Original Code has been "
  858. "modified", re.I)
  859. non_lic_content_in_same_comment_block = 0
  860. if len(comment_delims) == 1:
  861. # line-style comments: The comment block "end" is defined as the
  862. # last line before a line NOT using the block comment delimiter.
  863. #XXX:BUG: This is not good enough for:
  864. # test/inputs/separated_license_comment_blocks.pl
  865. if comment_delims[0] == "":
  866. raise RelicError(
  867. "Don't know how to find the end of a line-style comment "
  868. "block when the delimiter is the empty string. (Basically "
  869. "this script cannot handle this type of file.)")
  870. for i in range(beginline["linenum"]+1, len(lines)):
  871. if not lines[i].startswith(comment_delims[0]):
  872. endlinenum = i-1
  873. break
  874. elif lines[i].find("END LICENSE BLOCK") != -1:
  875. endlinenum = i
  876. break
  877. # As per "test_relicense_trailing_orig_code_modified.pl", a
  878. # paragraph starting with:
  879. # This Original Code has been modified
  880. # is deemed to be OUTside the license block, i.e. it is not
  881. # replaced for relicensing.
  882. if orig_code_modified_pattern.search(lines[i]):
  883. non_lic_content_in_same_comment_block = 1
  884. # The endline is the first non-blank line before this one.
  885. endlinenum = i-1
  886. while 1:
  887. line = lines[endlinenum]
  888. match = lic_middle_pattern.search(line)
  889. if not match:
  890. raise RelicError("Line did not match lic_middle_pattern "
  891. "unexpectedly: %r" % line)
  892. if match.group("content").strip(): # non-empty line
  893. break
  894. endlinenum -= 1
  895. break
  896. else:
  897. raise RelicError("Could not find license comment block end "
  898. "line in '%s'." % filename)
  899. elif len(comment_delims) >= 2: # block-style comments
  900. for i in range(beginline["linenum"]+1, len(lines)):
  901. if lines[i].find(comment_delims[-1]) != -1:
  902. endlinenum = i
  903. break
  904. elif lines[i].find("END LICENSE BLOCK") != -1:
  905. endlinenum = i
  906. non_lic_content_in_same_comment_block = 1
  907. break
  908. # As per "test_relicense_ibm_copyright_suffix.c", a
  909. # paragraph starting with:
  910. # This Original Code has been modified
  911. # is deemed to be OUTside the license block, i.e. it is not
  912. # replaced for relicensing.
  913. if orig_code_modified_pattern.search(lines[i]):
  914. non_lic_content_in_same_comment_block = 1
  915. # The endline is the first non-blank line before this one.
  916. endlinenum = i-1
  917. while 1:
  918. line = lines[endlinenum]
  919. match = lic_middle_pattern.search(line)
  920. if not match:
  921. raise RelicError("Line did not match lic_middle_pattern "
  922. "unexpectedly: %r" % line)
  923. if match.group("content").strip(): # non-empty line
  924. break
  925. endlinenum -= 1
  926. break
  927. else:
  928. raise RelicError("Could not find license comment block end "
  929. "line in '%s'." % filename)
  930. if not non_lic_content_in_same_comment_block\
  931. and not lines[endlinenum].strip().endswith(comment_delims[-1]):
  932. raise RelicError(
  933. "There is text AFTER the license block comment end "
  934. "delimiter, but on the SAME LINE. This is unexpected. "
  935. "Bailing.\n%s:%s:%r"
  936. % (filename, endlinenum, lines[endlinenum]))
  937. else: # len(comment_delims) == 0
  938. # For files without a comment character to help out, we ONLY
  939. # successfully break one the full correct "END LICENSE BLOCK"
  940. # token.
  941. for i in range(beginline["linenum"]+1, len(lines)):
  942. if lines[i].find("END LICENSE BLOCK") != -1:
  943. endlinenum = i
  944. break
  945. elif i > beginline["linenum"]+1+50:
  946. raise RelicError("Haven't found 'END LICENSE BLOCK' marker "
  947. "within 50 lines of the start of the "
  948. "license block on line %d. Aborting."
  949. % (beginline["linenum"]+1))
  950. # As per "test_relicense_trailing_orig_code_modified.pl", a
  951. # paragraph starting with:
  952. # This Original Code has been modified
  953. # is deemed to be OUTside the license block, i.e. it is not
  954. # replaced for relicensing.
  955. if orig_code_modified_pattern.search(lines[i]):
  956. non_lic_content_in_same_comment_block = 1
  957. # The endline is the first non-blank line before this one.
  958. endlinenum = i-1
  959. while 1:
  960. line = lines[endlinenum]
  961. match = lic_middle_pattern.search(line)
  962. if not match:
  963. raise RelicError("Line did not match lic_middle_pattern "
  964. "unexpectedly: %r" % line)
  965. if match.group("content").strip(): # non-empty line
  966. break
  967. endlinenum -= 1
  968. break
  969. else:
  970. raise RelicError("Could not find license comment block end "
  971. "line in '%s'." % filename)
  972. # Test case: test_relicense_separated_license_comment_blocks.pl
  973. # It is possible that a separate comment block immediately following
  974. # the license block we just parsed should be included in the license
  975. # block.
  976. if (not non_lic_content_in_same_comment_block
  977. and len(comment_delims) == 1): # only do this for line-style comments
  978. lic_indicators = [
  979. re.compile("^The content of this file are subject to", re.I),
  980. re.compile("^Software distributed under the License", re.I),
  981. re.compile("^The Original Code is", re.I),
  982. re.compile("^The Initial Developer", re.I),
  983. re.compile("^Contributor", re.I),
  984. re.compile("^Alternatively, the content of this file", re.I),
  985. ]
  986. comment_line_pattern = re.compile("""
  987. ^(?P<prefix>%s|)
  988. (?P<space>\s*)
  989. (?P<content>.*)
  990. (?P<suffix>%s|)\s*?$
  991. """ % (prefix_pattern, suffix_pattern),
  992. re.VERBOSE)
  993. i = endlinenum
  994. while i+1 < len(lines):
  995. i += 1; line = lines[i]
  996. comment_index = line.find(comment_delims[0])
  997. if comment_index != -1:
  998. content = line[:comment_index].strip()
  999. comment = line[comment_index+len(comment_delims[0]):].strip()
  1000. else:
  1001. content = line.strip()
  1002. comment = ""
  1003. if content: # if non-comment content, then skip out
  1004. break
  1005. if not comment:
  1006. continue
  1007. for indicator in lic_indicators:
  1008. if indicator.search(comment):
  1009. # include this paragraph in the lic block
  1010. while i < len(lines):
  1011. i += 1; line = lines[i]
  1012. if not line.strip().startswith(comment_delims[0]):
  1013. break
  1014. if not line.strip()[len(comment_delims[0]):]:
  1015. break
  1016. endlinenum = i-1
  1017. break
  1018. else:
  1019. break # this is a non-lic-related comment
  1020. # Get the end-line data.
  1021. if non_lic_content_in_same_comment_block:
  1022. lic_end_pattern = re.compile(
  1023. "^(?P<prefix>%s)(?P<space>\s*).*?\s*?$"
  1024. % prefix_pattern)
  1025. else:
  1026. lic_end_pattern = re.compile(
  1027. "^(?P<prefix>%s)(?P<space>\s*).*?(?P<suffix>%s)\s*?$"
  1028. % (prefix_pattern, suffix_pattern))
  1029. match = lic_end_pattern.match(lines[endlinenum])
  1030. if match:
  1031. endline = {
  1032. "content": lines[endlinenum],
  1033. "linenum": endlinenum,
  1034. "prefix": match.group("prefix"),
  1035. "space": match.group("space"),
  1036. "suffix": match.groupdict().get("suffix", ""),
  1037. }
  1038. else:
  1039. raise RelicError("license block end line did not match: line='%s', "
  1040. "pattern='%s'"
  1041. % (lines[endlinenum], lic_end_pattern.pattern))
  1042. log.debug("endline dict: %s", endline)
  1043. lic_info["last_suffix"] = endline["suffix"]
  1044. log.info("suffix for last line: '%s'", endline["suffix"])
  1045. lic_info["end_line"] = endline["linenum"]
  1046. log.info("license lines: %d-%d", beginline["linenum"], endline["linenum"])
  1047. # So at this point we have the beginline, secondline, and endline
  1048. # dicts describing and bounding the license block.
  1049. # - gather embedded lic data
  1050. # As described here:
  1051. # http://www.mozilla.org/MPL/relicensing-faq.html#new-license
  1052. # we have to parse out the following possible fields:
  1053. # original_code_is
  1054. # original_code_date
  1055. # initial_developer
  1056. # initial_copyright_date
  1057. # contributors
  1058. lic_line_pattern = re.compile( # regex to parse out the line _body_
  1059. "^(?P<prefix>%s)(?P<space>\s*)(?P<body>.*?)(?P<suffix>%s|)\s*?$"
  1060. % (prefix_pattern, suffix_pattern))
  1061. original_code_is = None
  1062. original_code_date = None
  1063. # Parse out the "The Original Code is ..." paragraph _content_.
  1064. paragraph = ""
  1065. in_paragraph = 0
  1066. for i in range(beginline["linenum"], endline["linenum"]+1):
  1067. body = lic_line_pattern.match(lines[i]).group("body")
  1068. if (not in_paragraph and body.startswith("The Original Code is")):
  1069. in_paragraph = 1
  1070. if in_paragraph:
  1071. if not body.strip(): # i.e. a blank line, end of paragraph
  1072. break
  1073. # ensure one space btwn lines
  1074. if paragraph: paragraph = paragraph.rstrip() + " "
  1075. paragraph += body
  1076. if paragraph:
  1077. pattern1 = re.compile('^The Original Code is (.*), released (.*)\.')
  1078. match = pattern1.search(paragraph)
  1079. if match:
  1080. original_code_is = match.group(1)
  1081. original_code_date = match.group(2)
  1082. else:
  1083. pattern2 = re.compile('^The Original Code is (.*?)\.?$')
  1084. match = pattern2.search(paragraph)
  1085. if match:
  1086. original_code_is = match.group(1)
  1087. else:
  1088. raise RelicError(
  1089. "%s: 'The Original Code is' paragraph did not match the "
  1090. "expected patterns. paragraph=\n\t%r\n"
  1091. "pattern1=\n\t%r\npattern2=\n\t%r"
  1092. % (filename, paragraph, pattern1.pattern, pattern2.pattern))
  1093. lic_info["original_code_is"] = original_code_is
  1094. lic_info["original_code_date"] = original_code_date
  1095. log.info("original code is: %s", original_code_is)
  1096. log.info("original_code_date: %s", original_code_date)
  1097. initial_developer = None
  1098. initial_copyright_date = None
  1099. # Parse out the "The Initial Developer..." paragraph _content_.
  1100. paragraph = ""
  1101. in_paragraph = 0
  1102. for i in range(beginline["linenum"], endline["linenum"]+1):
  1103. body = lic_line_pattern.match(lines[i]).group("body")
  1104. if (not in_paragraph and
  1105. (body.startswith("The Initial Developer of") or
  1106. body.startswith("The Initial Developers of"))):
  1107. in_paragraph = 1
  1108. if in_paragraph:
  1109. if not body.strip(): # i.e. a blank line, end of paragraph
  1110. # Catch the possible case where there is an empty line
  1111. # but the paragraph picks up on the next line with
  1112. # "Portions created by"
  1113. # (test_relicense_no_period_after_origcodeis.cpp).
  1114. try:
  1115. nextlinebody = lic_line_pattern.match(lines[i+1]).group("body")
  1116. except:
  1117. nextlinebody = ""
  1118. if not nextlinebody.startswith("Portions created by"):
  1119. break
  1120. # ensure one space btwn lines
  1121. if paragraph: paragraph = paragraph.rstrip() + " "
  1122. paragraph += body
  1123. if paragraph:
  1124. pattern = re.compile("""^
  1125. The\ Initial\ Developers?\ of\
  1126. (the\ Original\ Code\ (is\ |are\ |is\.)|this\ code\ under\ the\ [MN]PL\ (is|are)\ )
  1127. (?P<developer>.*?)
  1128. \.? # maybe a trailing period
  1129. (
  1130. \s+Portions\ created\ by\ .*?
  1131. are\ Copyright\ \(C\)\[?\ (?P<date>[\d-]+)
  1132. .*? # maybe a trailing period
  1133. (\s+All\ Rights\ Reserved\.)?
  1134. )?
  1135. $""", re.VERBOSE)
  1136. match = pattern.search(paragraph)
  1137. if not match:
  1138. raise RelicError(
  1139. "%s: 'This Initial Developer' paragraph did not match the "
  1140. "expected pattern. paragraph=\n\t%r\npattern=\n\t%s"
  1141. % (filename, paragraph, pattern.pattern))
  1142. initial_developer = match.group("developer")
  1143. initial_copyright_date = match.group("date")
  1144. lic_info["initial_developer"] = initial_developer
  1145. lic_info["initial_copyright_date"] = initial_copyright_date
  1146. log.info("initial developer paragraph: %r", paragraph)
  1147. log.info("initial developer: %r", initial_developer)
  1148. log.info("initial copyright date: %r", initial_copyright_date)
  1149. contributors = []
  1150. normal_leading_space = None
  1151. in_contributors_block = 0
  1152. contrib_end = endline["linenum"]
  1153. # If line-style comment, include the last line in the block in the
  1154. # range we examine; if block-style comment, we only allow it if the
  1155. # comment-block doesn't end on the endline. On top of these
  1156. # conditions we don't search the last line if it includes the
  1157. # special end-of-license marker.
  1158. if len(comment_delims) == 1 or not endline["suffix"]:
  1159. if endline["content"].find("END LICENSE BLOCK") == -1:
  1160. contrib_end += 1
  1161. for i in range(beginline["linenum"], contrib_end):
  1162. match = lic_line_pattern.match(lines[i])
  1163. body = match.group("body")
  1164. space = match.group("space").replace('\t', ' '*8)
  1165. if not in_contributors_block \
  1166. and body.startswith("Contributor"):
  1167. in_contributors_block = 1
  1168. normal_leading_space = space
  1169. # Try to pickup "foo@bar.org" as a contributor for a
  1170. # possible line like this:
  1171. # Contributor(s): foo@bar.org
  1172. pivot = body.find(':')
  1173. if pivot != -1:
  1174. remainder = body[pivot+1:].strip()
  1175. if remainder:
  1176. contributors.append(remainder)
  1177. elif in_contributors_block:
  1178. if not body.strip():
  1179. # i.e. a blank line, end of paragraph
  1180. #XXX:BUG This condition causes the latter two
  1181. # contributor lines to be lost from, e.g.,
  1182. # test/x_thead_align_center.xml.
  1183. break
  1184. if len(space) <= len(normal_leading_space):
  1185. # A line in the "Contributor(s) paragraph is not
  1186. # indented. This is considered an error. Likely this is
  1187. # a (not indented) contributor, but it might also be the
  1188. # start of another paragraph (i.e. no blank line
  1189. # terminating the "Contributor(s):" paragraph). We could
  1190. # just error out here, but this is very common in the
  1191. # Moz tree (~500) so lets try to deal with it.
  1192. # - Heuristic #1: if the line contains what looks like
  1193. # an email address then this it is a contributor.
  1194. # - Heuristic #2 (to accomodate js/rhino): if the line
  1195. # looks like just a person's name.
  1196. # Otherwise, error out.
  1197. words = body.split()
  1198. if '@' in body:
  1199. lic_info["unindented_contributor_lines"] = 1
  1200. elif (2 <= len(words) <= 3 and
  1201. words == [word[0].upper()+word[1:] for word in words]):
  1202. # Try to accept the following names:
  1203. # Norris Boyd
  1204. # Mike McCabe
  1205. # George C. Scott
  1206. lic_info["unindented_contributor_lines"] = 1
  1207. else:
  1208. raise RelicError("This line is part of the "
  1209. "'Contributor(s):' paragraph but (1) is not indented "
  1210. "and (2) does not look like it contains an email "
  1211. "address: %s:%s: %r" % (filename, i, lines[i]))
  1212. contributors.append(body.strip())
  1213. log.info("contributors: %s", contributors)
  1214. lic_info["contributors"] = contributors
  1215. ## Optimization: The only content in the remain license block lines
  1216. ## (i.e. after the contributors block) should really be the GPL/LGPL
  1217. ## or nothing. Trapping this will avoid losing the latter two
  1218. ## contributor lines in test/x_thead_align_center.xml.
  1219. #gpl_lgpl_lines = _g_trilicense_parts["gpl/lgpl"].splitlines(0)
  1220. #gpl_lgpl = " ".join(gpl_lgpl_lines)
  1221. #for i in range(i, endline["linenum"]):
  1222. # match = lic_line_pattern.match(lines[i])
  1223. # body = match.group("body")
  1224. # space = match.group("space").replace('\t', ' '*8)
  1225. # if not body.strip():
  1226. # continue
  1227. # #XXX This test is no robust enough to use.
  1228. # if (gpl_lgpl.find(body) == -1 and
  1229. # body.find(gpl_lgpl) == -1):
  1230. # print "QQQ: bogus following text: %r" % body
  1231. return lic_info
  1232. def _report_on_file(path, (results, switch_to_mpl, show_initial, quick, _errors)):
  1233. log.debug("_report_on_file(path='%s', results)", path)
  1234. output = path + "\n"
  1235. lic_info = {}
  1236. if _is_binary(path):
  1237. output += "... binary, skipping this file\n"
  1238. else:
  1239. try:
  1240. lic_info = _get_license_info(path, show_initial, quick)
  1241. except RelicError, ex:
  1242. return _relicensing_error(ex, path, _errors)
  1243. if log.isEnabledFor(logging.DEBUG):
  1244. pprint.pprint(lic_info)
  1245. parts = lic_info["parts"]
  1246. if not parts:
  1247. output += "... no license found\n"
  1248. elif "unknown" in parts:
  1249. output += "... unknown license (possibly) found\n"
  1250. elif ((parts == ["block_begin", "mpl", "gpl", "lgpl", "block_end"] or
  1251. parts == ["block_begin", "npl", "gpl", "lgpl", "block_end"]) and
  1252. not lic_info.get("unindented_contributor_lines")):
  1253. if (switch_to_mpl and
  1254. parts == ["block_begin", "npl", "gpl", "lgpl", "block_end"]):
  1255. output += "... %s found (looks complete, but is not MPL)"\
  1256. % "/".join(parts) + "\n"
  1257. else:
  1258. output += "... %s found (looks complete)"\
  1259. % "/".join(parts) + "\n"
  1260. else:
  1261. output += "... %s found" % "/".join(parts) + "\n"
  1262. if not quick:
  1263. if "begin_line" in lic_info and "end_line" in lic_info:
  1264. output += "... license block lines: %(begin_line)d-%(end_line)d"\
  1265. % lic_info + "\n"
  1266. if "original_code_is" in lic_info:
  1267. output += "... original code is: %(original_code_is)s"\
  1268. % lic_info + "\n"
  1269. if "original_code_date" in lic_info:
  1270. output += "... original code date: %(original_code_date)s"\
  1271. % lic_info + "\n"
  1272. if "initial_developer" in lic_info:
  1273. output += "... initial developer: %(initial_developer)s"\
  1274. % lic_info + "\n"
  1275. if "initial_copyright_date" in lic_info:
  1276. output += "... initial copyright date: %(initial_copyright_date)s"\
  1277. % lic_info + "\n"
  1278. if "contributors" in lic_info:
  1279. output += "... contributors: %s"\
  1280. % ", ".join(lic_info["contributors"]) + "\n"
  1281. if lic_info.get("unindented_contributor_lines"):
  1282. output += "... one or more contributor lines were not indented properly"\
  1283. + "\n"
  1284. if show_initial:
  1285. if "initial_developer" in lic_info:
  1286. print lic_info["initial_developer"]
  1287. else:
  1288. print output;
  1289. def _gather_info_on_file(path, (results, _errors)):
  1290. log.debug("_gather_info_on_file(path='%s', results)", path)
  1291. # Skip binary files.
  1292. try:
  1293. if _is_binary(path):
  1294. log.debug("Skipping binary file '%s'.", path)
  1295. return
  1296. except Exception, ex:
  1297. return _relicensing_error(
  1298. "error determining if file is binary: %s" % ex,
  1299. path, _errors)
  1300. try:
  1301. results[path] = _get_license_info(path)
  1302. except RelicError, ex:
  1303. return _relicensing_error(ex, path, _errors, 1)
  1304. def _make_backup_path(path):
  1305. for n in range(100):
  1306. backup_path = "%s~%d" % (path, n)
  1307. if not os.path.exists(backup_path):
  1308. return backup_path
  1309. raise RelicError("Could not find an unused backup path for '%s'." % path)
  1310. def _relicensing_error(err, path, cache=None, quiet=1):
  1311. """Handle an error during relicensing.
  1312. "err" may be an error string or an exception instance.
  1313. "path" is the path of the file on which this error occured.
  1314. "cache" is a mapping of path to errors on which errors may be
  1315. stored for later reporting.
  1316. "quiet" optionally allows one to silence the stdout output when
  1317. force is in effect.
  1318. If the --force option is in-effect then errors may be remembered and
  1319. processing continues, rather than halting the whole process.
  1320. """
  1321. if _g_force:
  1322. if not quiet:
  1323. print "...", err
  1324. if cache is not None:
  1325. cache[path] = err
  1326. elif isinstance(err, Exception):
  1327. raise
  1328. else:
  1329. raise RelicError("%s: %s" % (path, err))
  1330. def _get_comment_delim_sets(filename):
  1331. comment_delims = None
  1332. if os.path.splitext(filename)[1] == ".in":
  1333. # "<foo>.in" is generally a precursor for a filetype
  1334. # identifiable without the ".in". Drop it.
  1335. xfilename = os.path.splitext(filename)[0]
  1336. else:
  1337. xfilename = filename
  1338. # special cases for some basenames
  1339. basename = os.path.basename(xfilename)
  1340. try:
  1341. comment_delims = _g_basename_to_comment_info[basename]
  1342. except KeyError:
  1343. pass
  1344. if not comment_delims: # use the file extension
  1345. ext = os.path.splitext(xfilename)[1]
  1346. try:
  1347. comment_delims = _g_ext_to_comment_info[ext]
  1348. except KeyError:
  1349. pass
  1350. if not comment_delims: # try to use the shebang line, if any
  1351. fin = open(filename, 'r')
  1352. firstline = fin.readline()
  1353. fin.close()
  1354. if firstline.startswith("#!"):
  1355. for pattern, cds in _g_shebang_pattern_to_comment_info:
  1356. if pattern.match(firstline):
  1357. comment_delims = cds
  1358. break
  1359. if not comment_delims:
  1360. raise RelicError("%s: couldn't determine file type (and "
  1361. "comment delimiter info) from basename '%s' or "
  1362. "extension '%s'): you may need to add to "
  1363. "'_g_basename_to_comment_info', "
  1364. "'_g_ext_to_comment_info', "
  1365. "'_g_shebang_pattern_to_comment_info' "
  1366. "or one of the '_g_skip_*' globals"
  1367. % (filename, basename, ext))
  1368. return comment_delims
  1369. def _relicense_file(original_path,
  1370. (fallback_initial_copyright_date,
  1371. fallback_initial_developer,
  1372. fallback_original_code_is,
  1373. fallback_original_code_date,
  1374. switch_to_mpl,
  1375. backup,
  1376. results,
  1377. force_relicensing,
  1378. _errors)):
  1379. """Relicense the given file.
  1380. "original_path" is the file to relicense
  1381. "fallback_initial_copyright_date"
  1382. "fallback_initial_developer"
  1383. "fallback_original_code_is"
  1384. "fallback_original_code_date"
  1385. User-specified fallback values to use for the new license
  1386. block if they cannot be found in the original.
  1387. "switch_to_mpl" is a boolean indicating if an NPL-based license
  1388. should be converted to MPL.
  1389. "backup" (optional, default false) is a boolean indicating if
  1390. backups should be made
  1391. "results" is a dictionary in which to store statistics and errors.
  1392. See relicense() for schema.
  1393. "force_relicensing" is a boolean indicating if relicensing
  1394. should be done even if the license block looks complete.
  1395. "_errors" is a dictionary on which errors are reported
  1396. (keyed by file path) when the force option is in effect.
  1397. The function does not return anything.
  1398. """
  1399. log.debug("_relicense_file(original_path='%s')", original_path)
  1400. print original_path
  1401. # Ensure can access file.
  1402. if not os.access(original_path, os.R_OK|os.W_OK):
  1403. return _relicensing_error("cannot access", original_path, _errors)
  1404. else:
  1405. log.info("have read/write access")
  1406. # Skip binary files.
  1407. try:
  1408. if _is_binary(original_path):
  1409. print "... binary, skipping this file"
  1410. results["binary"] += 1
  1411. return
  1412. except Exception, ex:
  1413. return _relicensing_error(
  1414. "error determining if file is binary: %s" % ex,
  1415. original_path, _errors)
  1416. try:
  1417. lic_info = _get_license_info(original_path, 0)
  1418. except RelicError, ex:
  1419. return _relicensing_error(ex, original_path, _errors)
  1420. # Load fallback info if necessary.
  1421. if not lic_info.get("initial_copyright_date"):
  1422. lic_info["initial_copyright_date"] = fallback_initial_copyright_date
  1423. if not lic_info.get("initial_developer"):
  1424. lic_info["initial_developer"] = fallback_initial_developer
  1425. if not lic_info.get("original_code_is"):
  1426. lic_info["original_code_is"] = fallback_original_code_is
  1427. if not lic_info.get("original_code_date"):
  1428. lic_info["original_code_date"] = fallback_original_code_date
  1429. # Return/abort if cannot or do not need to re-license.
  1430. parts = lic_info["parts"]
  1431. if not parts:
  1432. results["no license"] += 1
  1433. print "... no license found, skipping this file"
  1434. return
  1435. elif "unknown" in parts:
  1436. return _relicensing_error("unknown license (possibly) found",
  1437. original_path, _errors)
  1438. elif parts.count("block_begin") > 1: # sanity check
  1439. return _relicensing_error(
  1440. "'BEGIN LICENSE BLOCK' delimiter found more than once",
  1441. original_path, _errors)
  1442. elif parts.count("block_end") > 1: # sanity check
  1443. return _relicensing_error(
  1444. "'END LICENSE BLOCK' delimiter found more than once",
  1445. original_path, _errors)
  1446. elif not lic_info["initial_developer"]:
  1447. return _relicensing_error(
  1448. "no 'Initial Developer' section was found -- use "
  1449. "the -i option to specify your own",
  1450. original_path, _errors)
  1451. elif not lic_info["initial_copyright_date"]:
  1452. return _relicensing_error(
  1453. "no initial copyright year was found -- use "
  1454. "the -y option to specify your own",
  1455. original_path, _errors)
  1456. elif not lic_info["original_code_is"]:
  1457. return _relicensing_error(
  1458. "no 'Original Code is' section was found -- use "
  1459. "the -o option to specify your own",
  1460. original_path, _errors)
  1461. elif ((parts == ["block_begin", "mpl", "gpl", "lgpl", "block_end"] or
  1462. parts == ["block_begin", "npl", "gpl", "lgpl", "block_end"]) and
  1463. not lic_info.get("unindented_contributor_lines")):
  1464. #XXX Should add an option to relicense anyway because matching
  1465. # is not super-strict. E.g. nsWidgetFactory.cpp.
  1466. if (switch_to_mpl and
  1467. parts == ["block_begin", "npl", "gpl", "lgpl", "block_end"]):
  1468. print "... %s found (looks complete, but is not MPL)"\
  1469. % "/".join(parts)
  1470. elif force_relicensing:
  1471. print "... %s found (looks complete, but forcing relicensing)"\
  1472. % "/".join(parts)
  1473. else:
  1474. results["good"] += 1
  1475. print "... %s found (looks complete), nothing to do"\
  1476. % "/".join(parts)
  1477. return
  1478. # We need to re-license this file.
  1479. print "... %s found, need to relicense" % "/".join(parts)
  1480. if lic_info["original_code_is"]:
  1481. print "... original code is: %(original_code_is)s" % lic_info
  1482. if lic_info["original_code_date"]:
  1483. print "... original code date: %(original_code_date)s" % lic_info
  1484. if lic_info["initial_developer"]:
  1485. print "... initial developer: %(initial_developer)s" % lic_info
  1486. if lic_info["initial_copyright_date"]:
  1487. print "... initial copyright date: %(initial_copyright_date)s" % lic_info
  1488. if lic_info["contributors"]:
  1489. print "... contributors: %s" % ", ".join(lic_info["contributors"])
  1490. # Put the license block together.
  1491. # - build up the license block from the appropriate parts
  1492. trilicense = ""
  1493. if (not switch_to_mpl) and ( "npl" in parts ):
  1494. trilicense_name = "NPL/GPL/LGPL"
  1495. trilicense += _g_trilicense_parts["npl"]
  1496. else:
  1497. trilicense_name = "MPL/GPL/LGPL"
  1498. trilicense += _g_trilicense_parts["mpl"]
  1499. print "... replacing lines %d-%d with %s tri-license"\
  1500. % (lic_info["begin_line"], lic_info["end_line"], trilicense_name)
  1501. if lic_info["original_code_is"] is not None:
  1502. if lic_info["original_code_date"] is not None:
  1503. trilicense += _g_trilicense_parts["original_code_is_with_date"] % lic_info
  1504. else:
  1505. trilicense += _g_trilicense_parts["original_code_is"] % lic_info
  1506. #else:
  1507. # raise RelicError("Gerv, how should the new license block handle no "
  1508. # "'Originial Code is...' information? --TM")
  1509. if (lic_info["initial_developer"] is not None
  1510. and lic_info["initial_copyright_date"] is not None):
  1511. trilicense += _g_trilicense_parts["initial_developer"] % lic_info
  1512. #else:
  1513. # raise RelicError("Gerv, how should the new license block handle no "
  1514. # "'Initial Developer is...' information? --TM")
  1515. if lic_info["contributors"]:
  1516. contributors = " " + "\n ".join(lic_info["contributors"]) + "\n"
  1517. else:
  1518. contributors = ""
  1519. trilicense += _g_trilicense_parts["contributors"] % contributors
  1520. if trilicense_name == "NPL/GPL/LGPL":
  1521. trilicense += _g_trilicense_parts["gpl/lgpl for npl"]
  1522. else: # trilicense_name == "MPL/GPL/LGPL"
  1523. trilicense += _g_trilicense_parts["gpl/lgpl for mpl"]
  1524. # get fallback comment subsequent prefix
  1525. fallback_prefix = _get_comment_delim_sets(original_path)
  1526. # - add the comment delimiters
  1527. lines = trilicense.splitlines()
  1528. for i in range(len(lines)):
  1529. if i == 0:
  1530. prefix = lic_info["first_prefix"]
  1531. else:
  1532. if lic_info["subsequent_prefix"]:
  1533. prefix = lic_info["subsequent_prefix"]
  1534. else:
  1535. prefix = fallback_prefix[0][1]
  1536. if lines[i]:
  1537. if len(lic_info["comment_delims"]) == 0:
  1538. lines[i] = prefix + lines[i]
  1539. else:
  1540. lines[i] = prefix + ' ' + lines[i]
  1541. else: # don't add trailing whitespace
  1542. lines[i] = prefix
  1543. if lic_info["last_suffix"]: # don't add that ' ' if there is no suffix
  1544. lines[-1] += ' ' + lic_info["last_suffix"]
  1545. for i in range(len(lines)): lines[i] += '\n'
  1546. trilicense_lines = lines
  1547. ##### uncomment to debug license block
  1548. # pprint.pprint(lines)
  1549. # return
  1550. # Skip out now if doing a dry-run.
  1551. if _g_dry_run:
  1552. results["relicensed"] += 1
  1553. return
  1554. # Make a backup.
  1555. if backup:
  1556. backup_path = _make_backup_path(original_path)
  1557. print "... backing up to '%s'" % backup_path
  1558. try:
  1559. shutil.copy(original_path, backup_path)
  1560. except EnvironmentError, ex:
  1561. return _relicensing_error(ex, original_path, _errors)
  1562. # Re-license the file.
  1563. try:
  1564. fin = open(original_path, "r")
  1565. try:
  1566. lines = fin.readlines()
  1567. finally:
  1568. fin.close()
  1569. lines[lic_info["begin_line"]:lic_info["end_line"]+1] = trilicense_lines
  1570. fout = open(original_path, "w")
  1571. try:
  1572. fout.write(''.join(lines))
  1573. finally:
  1574. fout.close()
  1575. results["relicensed"] += 1
  1576. print "... done relicensing '%s'" % original_path
  1577. except:
  1578. if backup:
  1579. print "... error relicensing, restoring original"
  1580. if os.path.exists(original_path):
  1581. os.remove(original_path)
  1582. os.rename(backup_path, original_path)
  1583. else:
  1584. print "... error relicensing, file may be corrupted"
  1585. # fallback to type_ for string exceptions
  1586. type_, value, tb = sys.exc_info()
  1587. return _relicensing_error(value or type_,
  1588. original_path, _errors)
  1589. def _add_license_to_file(original_path,
  1590. (initial_copyright_date,
  1591. initial_developer,
  1592. original_code_is,
  1593. original_code_date,
  1594. backup,
  1595. results,
  1596. _errors)):
  1597. """Relicense the given file.
  1598. "original_path" is the file to relicense
  1599. "initial_copyright_date"
  1600. "initial_developer"
  1601. "original_code_is"
  1602. "original_code_date"
  1603. User-specified values to use for the new license. All but
  1604. "original_code_date" are required.
  1605. "backup" (optional, default false) is a boolean indicating if
  1606. backups should be made
  1607. "results" is a dictionary in which to store statistics and errors.
  1608. See relicense() for schema.
  1609. "_errors" is a dictionary on which errors are reported
  1610. (keyed by file path) when the force option is in effect.
  1611. The function does not return anything.
  1612. """
  1613. log.debug("_add_license_to_file(original_path='%s')", original_path)
  1614. print original_path
  1615. # Ensure can access file.
  1616. if not os.access(original_path, os.R_OK|os.W_OK):
  1617. return _relicensing_error("cannot access", original_path, _errors)
  1618. else:
  1619. log.info("have read/write access")
  1620. # Skip binary files.
  1621. try:
  1622. if _is_binary(original_path):
  1623. print "... binary, skipping this file"
  1624. results["binary"] += 1
  1625. return
  1626. except Exception, ex:
  1627. return _relicensing_error(
  1628. "error determining if file is binary: %s" % ex,
  1629. original_path, _errors)
  1630. try:
  1631. lic_info = _get_license_info(original_path, 0)
  1632. except RelicError, ex:
  1633. return _relicensing_error(ex, original_path, _errors)
  1634. # Return/abort if cannot or do not need to re-license.
  1635. parts = lic_info["parts"]
  1636. if lic_info["parts"]: # has a license
  1637. results["license"] += 1
  1638. print "... license found, skipping this file"
  1639. return
  1640. #... else we need to add a license to this file.
  1641. print "... no license found, need to add one"
  1642. # Load license info.
  1643. lic_info["initial_developer"] = initial_developer
  1644. print "... initial developer: %(initial_developer)s" % lic_info
  1645. lic_info["initial_copyright_date"] = initial_copyright_date
  1646. print "... initial copyright date: %(initial_copyright_date)s" % lic_info
  1647. lic_info["original_code_is"] = original_code_is
  1648. print "... original code is: %(original_code_is)s" % lic_info
  1649. if original_code_date:
  1650. lic_info["original_code_date"] = original_code_date
  1651. print "... original code date: %(original_code_date)s" % lic_info
  1652. else:
  1653. lic_info["original_code_date"] = None
  1654. # Determine what line we can start putting the license block on.
  1655. # Typically this would be line 0, but for the following exceptions:
  1656. # - Shebang (#!) lines
  1657. # - Emacs local variables line:
  1658. # /* -*- Mode: C++; ... -*- */
  1659. # This line does not HAVE to be first, but that seems to be a
  1660. # trend, so might as well honour it.
  1661. # - XML magic "number": <?xml version="2.0" ... ?>
  1662. # where "..." might include newlines
  1663. startline = 0
  1664. try:
  1665. comment_delim_sets = _get_comment_delim_sets(original_path)
  1666. except RelicError, ex:
  1667. return _relicensing_error(ex, original_path, _errors, 1)
  1668. fin = open(original_path, 'r')
  1669. try:
  1670. lines = fin.readlines()
  1671. finally:
  1672. fin.close()
  1673. # If this is an XML file, advance past the magic number tag.
  1674. if lines and lines[0].find("<?xml") != -1:
  1675. line = lines[0]
  1676. if (line.find('encoding="utf-8"') != -1
  1677. and line.startswith("\xef\xbb\xbf")):
  1678. # remove UTF-8 BOM
  1679. # Note: this is hardly robust Unicode XML handling :)
  1680. line = line[3:]
  1681. if line.startswith("<?xml"):
  1682. end_index = lines[startline].find("?>")
  1683. while startline < len(lines):
  1684. startline += 1
  1685. if end_index != -1: # found end of tag
  1686. break
  1687. # Note: this does not catch something like this:
  1688. # <?xml version="2.0"?> <?stylesheet ...
  1689. # ...?>
  1690. # but that is just crazy.
  1691. # else, advance past a possible shebang line.
  1692. else:
  1693. for comment_delims in comment_delim_sets:
  1694. if (len(comment_delims) == 1 and comment_delims[0] == "#"
  1695. and lines[0].startswith("#!")):
  1696. startline += 1
  1697. # Advance past an Emacs local variable line.
  1698. comment_delims = None
  1699. if lines[startline].find("-*-") != -1:
  1700. for comment_delims in comment_delim_sets:
  1701. if lines[startline].find(comment_delims[0]) != -1:
  1702. break
  1703. else:
  1704. # We were hoping to be able to determine which of the set of
  1705. # possible commenting styles was in use by finding the
  1706. # comment start token on the same line as the -*-
  1707. # Emacs-modeline signifier, but could not. This likely means
  1708. # that this file uses a block-style comment but the block
  1709. # doesn't start on the same line. Fallback to the
  1710. # block-style comment delimiter set, if there is one.
  1711. for comment_delims in comment_delim_sets:
  1712. if len(comment_delims) == 3:
  1713. break
  1714. else:
  1715. comment_delims = comment_delim_sets[0]
  1716. if len(comment_delims) == 1: # line-style comments
  1717. startline += 1
  1718. else: # block-style comments
  1719. in_comment = 0
  1720. while startline < len(lines):
  1721. line = lines[startline]
  1722. linepos = 0
  1723. while linepos < len(line):
  1724. if not in_comment:
  1725. i = line.find(comment_delims[0], linepos)
  1726. if i == -1:
  1727. break
  1728. else:
  1729. in_comment = 1
  1730. linepos = i+1
  1731. else:
  1732. i = line.find(comment_delims[-1], linepos)
  1733. if i == -1:
  1734. break
  1735. else:
  1736. in_comment = 0
  1737. linepos = i+1
  1738. startline += 1
  1739. if not in_comment:
  1740. break
  1741. # Put the license block together.
  1742. # - build up the license block from the appropriate parts
  1743. trilicense_name = "MPL/GPL/LGPL"
  1744. print "... adding %s tri-license starting at line %s (zero-based)"\
  1745. % (trilicense_name, startline)
  1746. trilicense = _g_trilicense_parts["mpl"]
  1747. if lic_info["original_code_date"] is not None:
  1748. trilicense += _g_trilicense_parts["original_code_is_with_date"] % lic_info
  1749. else:
  1750. trilicense += _g_trilicense_parts["original_code_is"] % lic_info
  1751. trilicense += _g_trilicense_parts["initial_developer"] % lic_info
  1752. if lic_info.get("contributors"):
  1753. contributors = " " + "\n ".join(lic_info["contributors"]) + "\n"
  1754. else:
  1755. contributors = ""
  1756. trilicense += _g_trilicense_parts["contributors"] % contributors
  1757. trilicense += _g_trilicense_parts["gpl/lgpl for mpl"]
  1758. # - add the comment delimiters
  1759. if comment_delims is None:
  1760. for comment_delims in comment_delim_sets:
  1761. if lines[startline].find(comment_delims[0]) != -1:
  1762. break
  1763. elif len(comment_delims) == 3 and lines[startline].find(comment_delims[1]) != -1:
  1764. break
  1765. else:
  1766. # We were hoping to be able to determine which of the set of
  1767. # possible commenting styles was in use by finding the
  1768. # comment start token on the same line as the -*-
  1769. # Emacs-modeline signifier, but could not. This likely means
  1770. # that this file uses a block-style comment but the block
  1771. # doesn't start on the same line. Fallback to the
  1772. # block-style comment delimiter set, if there is one.
  1773. for comment_delims in comment_delim_sets:
  1774. if len(comment_delims) == 3:
  1775. break
  1776. else:
  1777. comment_delims = comment_delim_sets[0]
  1778. print "comment delims were none: %r" % comment_delims
  1779. t_lines = trilicense.splitlines()
  1780. if len(comment_delims) == 1: # line-style comments
  1781. for i in range(len(t_lines)):
  1782. if t_lines[i]:
  1783. t_lines[i] = comment_delims[0] + ' ' + t_lines[i]
  1784. else: # don't add trailing whitespace
  1785. t_lines[i] = comment_delims[0]
  1786. else: # block-style comments
  1787. if t_lines[0]:
  1788. t_lines[0] = comment_delims[0] + ' ' + t_lines[0]
  1789. else: # don't add trailing whitespace
  1790. t_lines[0] = comment_delims[0]
  1791. for i in range(1, len(t_lines)):
  1792. if t_lines[i]:
  1793. t_lines[i] = comment_delims[1] + ' ' + t_lines[i]
  1794. else: # don't add trailing whitespace
  1795. t_lines[i] = comment_delims[1]
  1796. t_lines[-1] += ' ' + comment_delims[-1]
  1797. for i in range(len(t_lines)): t_lines[i] += '\n'
  1798. t_lines[-1] += '\n' # add a blank line at end of lic block
  1799. trilicense_lines = t_lines
  1800. #pprint.pprint(t_lines)
  1801. # Skip out now if doing a dry-run.
  1802. if _g_dry_run:
  1803. results["added"] += 1
  1804. return
  1805. # Make a backup.
  1806. if backup:
  1807. backup_path = _make_backup_path(original_path)
  1808. print "... backing up to '%s'" % backup_path
  1809. try:
  1810. shutil.copy(original_path, backup_path)
  1811. except EnvironmentError, ex:
  1812. return _relicensing_error(ex, original_path, _errors)
  1813. # Add the license to the file.
  1814. try:
  1815. lines[startline:startline] = trilicense_lines
  1816. fout = open(original_path, "w")
  1817. try:
  1818. fout.write(''.join(lines))
  1819. finally:
  1820. fout.close()
  1821. results["added"] += 1
  1822. print "... done adding license to '%s'" % original_path
  1823. except:
  1824. if backup:
  1825. print "... error adding license, restoring original"
  1826. if os.path.exists(original_path):
  1827. os.remove(original_path)
  1828. os.rename(backup_path, original_path)
  1829. else:
  1830. print "... error adding license, file may be corrupted"
  1831. # fallback to type_ for string exceptions
  1832. type_, value, tb = sys.exc_info()
  1833. return _relicensing_error(value or type_,
  1834. original_path, _errors)
  1835. def _traverse_dir((file_handler, results), dirname, names):
  1836. """os.path.walk target to traverse the give dir"""
  1837. log.debug("_traverse_dir((file_handler, results), dirname='%s', "
  1838. "names=%s)", dirname, names)
  1839. # Iterate over names backwards because may modify it in-place.
  1840. # Modifying it in-place ensures that removed entries are not
  1841. # traversed by os.path.walk.
  1842. for i in range(len(names)-1, -1, -1):
  1843. path = os.path.join(dirname, names[i])
  1844. if os.path.isdir(path):
  1845. if _should_skip_dir(path):
  1846. del names[i]
  1847. continue
  1848. if os.path.isfile(path):
  1849. if _should_skip_file(path):
  1850. del names[i]
  1851. continue
  1852. if file_handler is not None:
  1853. file_handler(path, results)
  1854. def _traverse(paths, file_handler, arg):
  1855. """Traverse the given path(s) and call the given callback for each.
  1856. "paths" is either a list of files or directories, or it is an
  1857. input stream with a path on each line.
  1858. "file_handler" is a callable to be called on each file traversed.
  1859. It is called with the following signature:
  1860. file_handler(path, arg)
  1861. "arg" is some object passed to each callback. This is useful for
  1862. recording results.
  1863. This method takes care of skipping files and directories that should
  1864. be skipped according to .cvsignore files and the configured skip
  1865. paths. This method does not return anything.
  1866. """
  1867. log.debug("_traverse(paths=%s, file_handler=%s, arg=%s)",
  1868. paths, file_handler, arg)
  1869. for path in paths:
  1870. if path[-1] == "\n": path = path[:-1] # chomp if 'paths' is a stream
  1871. if not os.path.exists(path):
  1872. log.warn("'%s' does not exist, skipping", path)
  1873. elif os.path.isfile(path):
  1874. if _should_skip_file(path):
  1875. continue
  1876. if file_handler is not None:
  1877. file_handler(path, arg)
  1878. elif os.path.isdir(path):
  1879. if _should_skip_dir(path):
  1880. continue
  1881. os.path.walk(path, _traverse_dir, (file_handler, arg))
  1882. else:
  1883. raise RelicError("unexpected path type '%s'" % path)
  1884. #---- public routines
  1885. def relicense(paths,
  1886. fallback_initial_copyright_date=None,
  1887. fallback_initial_developer=None,
  1888. fallback_original_code_is=None,
  1889. fallback_original_code_date=None,
  1890. switch_to_mpl=0,
  1891. backup=0,
  1892. force_relicensing=0,
  1893. _errors=None):
  1894. """Relicense the given file(s) (or files in the given dir).
  1895. "paths" is either a list of files or directories, or it is an
  1896. input stream with a path on each line.
  1897. "fallback_initial_copyright_date"
  1898. "fallback_initial_developer"
  1899. "fallback_original_code_is"
  1900. "fallback_original_code_date"
  1901. User-specified fallback values to use for the new license
  1902. block if they cannot be found in the original.
  1903. "switch_to_mpl" (optional, default false) is a boolean
  1904. indicating if an NPL-based license should be converted to
  1905. MPL.
  1906. "backup" (optional, default false)is a boolean indicating if
  1907. backups should be made
  1908. "force_relicensing" (option, default false) is a boolean
  1909. indicating if relicensing should happen even if the license
  1910. block looks complete
  1911. "_errors" (optional) is a dictionary on which errors are reported
  1912. (keyed by file path) when the force option is in effect.
  1913. This method does not return anything. It will raise RelicError if
  1914. there is a problem. Note that OSError/IOError may also be raised.
  1915. """
  1916. log.debug("relicense(paths=%s, backup=%r)", paths, backup)
  1917. results = {
  1918. "relicensed": 0,
  1919. "no license": 0,
  1920. "good": 0,
  1921. "binary": 0,
  1922. }
  1923. _traverse(paths, _relicense_file,
  1924. (fallback_initial_copyright_date,
  1925. fallback_initial_developer,
  1926. fallback_original_code_is,
  1927. fallback_original_code_date,
  1928. switch_to_mpl,
  1929. backup,
  1930. results,
  1931. force_relicensing,
  1932. _errors))
  1933. print
  1934. print "--------------------- Summary of Results ------------------------"
  1935. print "Files skipped b/c they are binary:", results["binary"]
  1936. print "Files skipped b/c they already had proper license:", results["good"]
  1937. print "Files skipped b/c they had no license:", results["no license"]
  1938. if _g_dry_run:
  1939. print "Files re-licensed: %d (dry-run)" % results["relicensed"]
  1940. else:
  1941. print "Files re-licensed:", results["relicensed"]
  1942. print "-----------------------------------------------------------------"
  1943. def addlicense(paths,
  1944. initial_copyright_date,
  1945. initial_developer,
  1946. original_code_is,
  1947. original_code_date=None,
  1948. backup=0,
  1949. _errors=None):
  1950. """Add a license to those of the given file(s) that do not appear to
  1951. have one.
  1952. "paths" is either a list of files or directories, or it is an
  1953. input stream with a path on each line.
  1954. "initial_copyright_date"
  1955. "initial_developer"
  1956. "original_code_is"
  1957. "original_code_date"
  1958. User-specified values to use for the new license block. All
  1959. but "original_code_date" are required.
  1960. "backup" (optional, default false) is a boolean indicating if
  1961. backups should be made
  1962. "_errors" (optional) is a dictionary on which errors are reported
  1963. (keyed by file path) when the force option is in effect.
  1964. This method does not return anything. It will raise RelicError if
  1965. there is a problem. Note that OSError/IOError may also be raised.
  1966. """
  1967. log.debug("addlicense(paths=%s, backup=%r)", paths, backup)
  1968. if not initial_copyright_date:
  1969. raise RelicError("no Initial Developer copyright year was "
  1970. "specified -- use the -y option")
  1971. if not initial_developer:
  1972. raise RelicError("no 'Initial Developer' section was specified "
  1973. "-- use the -i option")
  1974. if not original_code_is:
  1975. raise RelicError("no 'Original Code is' section was specified "
  1976. "-- use the -o option")
  1977. results = {
  1978. "added": 0,
  1979. "license": 0,
  1980. "binary": 0,
  1981. }
  1982. _traverse(paths, _add_license_to_file,
  1983. (initial_copyright_date,
  1984. initial_developer,
  1985. original_code_is,
  1986. original_code_date,
  1987. backup,
  1988. results,
  1989. _errors))
  1990. print
  1991. print "--------------------- Summary of Results ------------------------"
  1992. print "Files skipped b/c they are binary:", results["binary"]
  1993. print "Files skipped b/c they already had a license:", results["license"]
  1994. if _g_dry_run:
  1995. print "Files to which a license was added: %d (dry-run)" % results["added"]
  1996. else:
  1997. print "Files to which a license was added: %d" % results["added"]
  1998. print "-----------------------------------------------------------------"
  1999. def report(paths, switch_to_mpl=0, show_initial=1, quick=0, _errors=None):
  2000. """Report on the existing licenses in the given file(s).
  2001. "paths" is either a list of files or directories, or it is an
  2002. input stream with a path on each line.
  2003. "switch_to_mpl" (optional, default false) is a boolean
  2004. indicating if an NPL-based license should be converted to
  2005. MPL.
  2006. "show_initial" (optional, default true) is a boolean indicating
  2007. if the initial developer should be displayed for each file.
  2008. "quick" (optional, default false) is a boolean indicating if only
  2009. basic license checking should be applied.
  2010. "_errors" (optional) is a dictionary on which errors are reported
  2011. (keyed by file path) when the force option is in effect.
  2012. This method does not return anything. It will raise RelicError if
  2013. there is a problem.
  2014. """
  2015. log.debug("report(paths=%s)", paths)
  2016. results = {}
  2017. _traverse(paths,\
  2018. _report_on_file,\
  2019. (results, switch_to_mpl, show_initial, quick, _errors))
  2020. def statistics(paths, extended=0, quick=0, _errors=None):
  2021. """Show a summary table of licenses in files in the given path(s).
  2022. "paths" is either a list of files or directories, or it is an
  2023. input stream with a path on each line.
  2024. "extended" (optional) is a boolean indicating if extended
  2025. statistics should be shown
  2026. "quick" (optional) is a boolean indicating if quick scan mode should
  2027. be enabled.
  2028. "_errors" (optional) is a dictionary on which errors are reported
  2029. (keyed by file path) when the force option is in effect.
  2030. This method does not return anything.
  2031. """
  2032. #XXX Info gathering returns a lot more info now. We might be able to
  2033. # output more interesting stats.
  2034. log.debug("statistics(paths=%s, extended=%s)",
  2035. paths, extended)
  2036. results = {}
  2037. _traverse(paths, _gather_info_on_file, (results, _errors))
  2038. # Process results and print out some stats.
  2039. stats = {
  2040. # <lic type>: [<number of hits>, [<files>...]]
  2041. }
  2042. for file, info in results.items():
  2043. lic_types = [p for p in info["parts"]
  2044. if p not in ["block_begin", "block_end"]]
  2045. if not lic_types:
  2046. name = "<none found>"
  2047. elif "unknown" in lic_types:
  2048. name = "<unknown license>"
  2049. # Distinguish between complete mpl/gpl/lgpl (i.e. with the block
  2050. # begin and end tokens) and incomplete mpl/gpl/lgpl. Likewise
  2051. # NPL.
  2052. elif (info["parts"] == ["block_begin", "mpl", "gpl", "lgpl", "block_end"]):
  2053. name = "mpl/gpl/lgpl (complete)"
  2054. elif (info["parts"] == ["block_begin", "npl", "gpl", "lgpl", "block_end"]):
  2055. name = "npl/gpl/lgpl (complete)"
  2056. else:
  2057. name = "/".join(lic_types)
  2058. if name not in stats: stats[name] = [0, []]
  2059. stats[name][0] += 1
  2060. stats[name][1].append(file)
  2061. statslist = [(hits, name, files) for name, (hits, files) in stats.items()]
  2062. statslist.sort() # sort by number of hits
  2063. statslist.reverse() # most common first
  2064. print "Summary of Licenses in Files"
  2065. print "============================"
  2066. print " Number Percent License"
  2067. print "------- -------- -----------"
  2068. # 115 55.55% npl/gpl
  2069. for hits, name, files in statslist:
  2070. print "%7d %7.2f%% %s"\
  2071. % (hits, (hits*100.0/len(results)), name)
  2072. #XXX Removed for now because I am not clear if this is at all
  2073. # useful.
  2074. #if extended:
  2075. # hits_per_ext = {}
  2076. # for file in files:
  2077. # ext = os.path.splitext(file)[1]
  2078. # if ext not in hits_per_ext: hits_per_ext[ext] = 0
  2079. # hits_per_ext[ext] += 1
  2080. # hits_per_ext_list = [(h, e) for e, h in hits_per_ext.items()]
  2081. # hits_per_ext_list.sort()
  2082. # hits_per_ext_list.reverse()
  2083. # for ext_hits, ext in hits_per_ext_list:
  2084. # if not ext: ext = "<no extension>"
  2085. # print " %7d %s" % (ext_hits, ext)
  2086. print "----------------------------"
  2087. print "%7d files processed" % len(results)
  2088. # Print some other interesting statistics.
  2089. no_original_code_is = []
  2090. no_initial_developer = []
  2091. unindented_contributor_lines = []
  2092. for file, info in results.items():
  2093. if "original_code_is" in info and info["original_code_is"] is None:
  2094. no_original_code_is.append(file)
  2095. if "initial_developer" in info and info["initial_developer"] is None:
  2096. no_initial_developer.append(file)
  2097. if info.get("unindented_contributor_lines"):
  2098. unindented_contributor_lines.append(file)
  2099. print
  2100. print "Licensed files with no 'Initial Developer...' info: %d" % len(no_initial_developer)
  2101. if extended:
  2102. for f in no_initial_developer:
  2103. print " %s" % f
  2104. print "Licensed files with no 'Original Code is...' info: %d" % len(no_original_code_is)
  2105. if extended:
  2106. for f in no_original_code_is:
  2107. print " %s" % f
  2108. print "Licensed files with improperly indented 'Contributor(s):' line(s): %d" % len(unindented_contributor_lines)
  2109. if extended:
  2110. for f in unindented_contributor_lines:
  2111. print " %s" % f
  2112. if extended:
  2113. for hits, name, files in statslist:
  2114. print "Files in license category '%s'" % name
  2115. sortedFiles = files[:]
  2116. sortedFiles.sort()
  2117. for file in sortedFiles:
  2118. print " %s" % file
  2119. print
  2120. #---- mainline
  2121. def main(argv):
  2122. try:
  2123. opts, args = getopt.getopt(argv[1:], "VvadhqfML:sxry:i:o:D:ARI",
  2124. ["version", "verbose", "all", "help", "debug",
  2125. "dry-run", "force", "MPL", "license=",
  2126. "statistics", "relicense", "backup", "add", "defaults",
  2127. "force-relicense", "initial-developers", "quick"])
  2128. except getopt.GetoptError, ex:
  2129. log.error(str(ex))
  2130. log.error("Try `%s --help'.", argv[0])
  2131. return 2
  2132. debug = 0
  2133. mode = "report"
  2134. extended = 0
  2135. backup = 0
  2136. quick = 0
  2137. force_relicensing = 0
  2138. fallback_initial_copyright_date = None
  2139. fallback_initial_developer = None
  2140. fallback_original_code_is = None
  2141. fallback_original_code_date = None
  2142. switch_to_mpl = 0
  2143. show_initial = 0
  2144. for opt, optarg in opts:
  2145. if opt in ("-h", "--help"):
  2146. sys.stdout.write(__doc__)
  2147. return
  2148. elif opt in ("-V", "--version"):
  2149. ver = '.'.join([str(part) for part in _version_])
  2150. print "relic %s" % ver
  2151. return
  2152. elif opt in ("-v", "--verbose"):
  2153. log.setLevel(logging.INFO)
  2154. elif opt in ("-a", "--all"):
  2155. global _g_check_all
  2156. _g_check_all = 1
  2157. elif opt in ("-M", "--MPL"):
  2158. switch_to_mpl = 1
  2159. elif opt in ("-d", "--debug"):
  2160. log.setLevel(logging.DEBUG)
  2161. debug = 1
  2162. elif opt in ("--dry-run",):
  2163. global _g_dry_run
  2164. _g_dry_run = 1
  2165. elif opt in ("-f", "--force"):
  2166. global _g_force
  2167. _g_force = 1
  2168. elif opt in ("-s", "--statistics"):
  2169. mode = "statistics"
  2170. elif opt in ("-x",):
  2171. extended = 1
  2172. elif opt in ("-r", "--relicense"):
  2173. mode = "relicense"
  2174. elif opt in ("-R", "--force-relicense"):
  2175. mode = "relicense"
  2176. force_relicensing = 1
  2177. elif opt in ("-A", "--add"):
  2178. mode = "add"
  2179. elif opt == "--backup":
  2180. backup = 1
  2181. elif opt == "-y":
  2182. fallback_initial_copyright_date = optarg
  2183. elif opt == "-i":
  2184. fallback_initial_developer = optarg
  2185. elif opt == "-o":
  2186. fallback_original_code_is = optarg
  2187. elif opt == "-D":
  2188. fallback_original_code_date = optarg
  2189. elif opt in ("-I", "--initial-developers"):
  2190. show_initial = 1
  2191. elif opt == "--defaults":
  2192. fallback_original_code_is = "mozilla.org Code"
  2193. fallback_initial_copyright_date = "2001"
  2194. fallback_initial_developer = "Netscape Communications Corporation"
  2195. elif opt in ("-q", "--quick"):
  2196. quick = 1
  2197. try:
  2198. # Prepare the input.
  2199. if not args:
  2200. log.debug("no given files, trying stdin")
  2201. paths = sys.stdin
  2202. else:
  2203. paths = args
  2204. # Invoke the requested action.
  2205. _errors = {}
  2206. if mode == "relicense":
  2207. relicense(paths,
  2208. fallback_initial_copyright_date,
  2209. fallback_initial_developer,
  2210. fallback_original_code_is,
  2211. fallback_original_code_date,
  2212. switch_to_mpl,
  2213. backup,
  2214. force_relicensing,
  2215. _errors=_errors)
  2216. elif mode == "statistics":
  2217. statistics(paths, extended, quick, _errors=_errors)
  2218. elif mode == "report":
  2219. report(paths, switch_to_mpl, show_initial, quick, _errors=_errors)
  2220. elif mode == "add":
  2221. addlicense(paths,
  2222. fallback_initial_copyright_date,
  2223. fallback_initial_developer,
  2224. fallback_original_code_is,
  2225. fallback_original_code_date,
  2226. backup,
  2227. _errors=_errors)
  2228. else:
  2229. raise RelicError("unexpected mode: '%s'" % mode)
  2230. # Report any delayed errors.
  2231. if _errors:
  2232. print
  2233. print "=================== Summary of Errors ==========================="
  2234. print "Files with processing errors:", len(_errors)
  2235. print "================================================================="
  2236. for file, error in _errors.items():
  2237. print "%s: %s" % (file, error)
  2238. print
  2239. print "================================================================="
  2240. except RelicError, ex:
  2241. log.error(str(ex) +
  2242. " (the --force option can be used to skip problematic "
  2243. "files and continue processing rather than aborting)")
  2244. if debug:
  2245. print
  2246. import traceback
  2247. traceback.print_exception(*sys.exc_info())
  2248. return 1
  2249. except KeyboardInterrupt:
  2250. pass
  2251. if __name__ == "__main__":
  2252. sys.exit( main(sys.argv) )