PageRenderTime 62ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/relic/relic

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