Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

396 lignes
12 KiB

  1. #!/usr/bin/python
  2. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  3. #
  4. # MIT License (MIT)
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a
  7. # copy of this software and associated documentation files (the "Software"),
  8. # to deal in the Software without restriction, including without limitation
  9. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. # and/or sell copies of the Software, and to permit persons to whom the
  11. # Software is furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  17. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  18. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  19. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  20. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  21. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. #
  23. from __future__ import unicode_literals
  24. import os, sys
  25. def replace_code(start, txt1, txt2, extn, search=None, force=False):
  26. """replace all txt1 by txt2 in files with extension (extn)"""
  27. import webnotes.utils
  28. import os, re
  29. esc = webnotes.utils.make_esc('[]')
  30. if not search: search = esc(txt1)
  31. for wt in os.walk(start, followlinks=1):
  32. for fn in wt[2]:
  33. if fn.split('.')[-1]==extn:
  34. fpath = os.path.join(wt[0], fn)
  35. if fpath != '/var/www/erpnext/erpnext/patches/jan_mar_2012/rename_dt.py': # temporary
  36. with open(fpath, 'r') as f:
  37. content = f.read()
  38. if re.search(search, content):
  39. res = search_replace_with_prompt(fpath, txt1, txt2, force)
  40. if res == 'skip':
  41. return 'skip'
  42. def search_replace_with_prompt(fpath, txt1, txt2, force=False):
  43. """ Search and replace all txt1 by txt2 in the file with confirmation"""
  44. from termcolor import colored
  45. with open(fpath, 'r') as f:
  46. content = f.readlines()
  47. tmp = []
  48. for c in content:
  49. if c.find(txt1) != -1:
  50. print fpath
  51. print colored(txt1, 'red').join(c[:-1].split(txt1))
  52. a = ''
  53. if force:
  54. c = c.replace(txt1, txt2)
  55. else:
  56. while a.lower() not in ['y', 'n', 'skip']:
  57. a = raw_input('Do you want to Change [y/n/skip]?')
  58. if a.lower() == 'y':
  59. c = c.replace(txt1, txt2)
  60. elif a.lower() == 'skip':
  61. return 'skip'
  62. tmp.append(c)
  63. with open(fpath, 'w') as f:
  64. f.write(''.join(tmp))
  65. print colored('Updated', 'green')
  66. def pull(remote, branch):
  67. os.chdir("lib")
  68. os.system('git pull %s %s' % (remote, branch))
  69. os.chdir("../app")
  70. os.system('git pull %s %s' % (remote, branch))
  71. rebuild()
  72. def rebuild():
  73. # build js / css
  74. from webnotes.utils import bundlejs
  75. bundlejs.bundle(options.no_compress)
  76. # build cache
  77. import website.web_cache
  78. website.web_cache.refresh_cache(['Blog'])
  79. def apply_latest_patches():
  80. import webnotes.modules.patch_handler
  81. webnotes.modules.patch_handler.run_all()
  82. print '\n'.join(webnotes.modules.patch_handler.log_list)
  83. def sync_all(force=0):
  84. import webnotes.model.sync
  85. webnotes.model.sync.sync_all(force)
  86. def update_erpnext(remote='origin', branch='master'):
  87. # do a pull
  88. pull(remote, branch)
  89. # apply latest patches
  90. apply_latest_patches()
  91. import webnotes.modules.patch_handler
  92. for l in webnotes.modules.patch_handler.log_list:
  93. if "failed: STOPPED" in l:
  94. return
  95. # sync all
  96. sync_all()
  97. def append_future_import():
  98. """appends from __future__ import unicode_literals to py files if necessary"""
  99. import os
  100. import conf
  101. conf_path = os.path.abspath(conf.__file__)
  102. if conf_path.endswith("pyc"):
  103. conf_path = conf_path[:-1]
  104. base_path = os.path.dirname(conf_path)
  105. for path, folders, files in os.walk(base_path):
  106. for f in files:
  107. if f.endswith('.py'):
  108. file_path = os.path.join(path, f)
  109. with open(file_path, 'r') as pyfile:
  110. content = pyfile.read()
  111. future_import = 'from __future__ import unicode_literals'
  112. if future_import in content: continue
  113. content = content.split('\n')
  114. idx = -1
  115. for c in content:
  116. idx += 1
  117. if c and not c.startswith('#'):
  118. break
  119. content.insert(idx, future_import)
  120. content = "\n".join(content)
  121. with open(file_path, 'w') as pyfile:
  122. pyfile.write(content)
  123. def setup_options():
  124. from optparse import OptionParser
  125. parser = OptionParser()
  126. parser.add_option("-d", "--db",
  127. dest="db_name",
  128. help="Apply the patches on given db")
  129. parser.add_option("--password",
  130. help="Password for given db", nargs=1)
  131. # build
  132. parser.add_option("-b", "--build", default=False, action="store_true",
  133. help="minify + concat js files")
  134. parser.add_option("-w", "--watch", default=False, action="store_true",
  135. help="watch and minify + concat js files, if necessary")
  136. parser.add_option("--no_compress", default=False, action="store_true",
  137. help="do not compress when building js bundle")
  138. parser.add_option("--build_web_cache", default=False, action="store_true",
  139. help="build web cache")
  140. parser.add_option("--domain", metavar="DOMAIN",
  141. help="store domain in Website Settings", nargs=1)
  142. # git
  143. parser.add_option("--status", default=False, action="store_true",
  144. help="git status")
  145. parser.add_option("--git", nargs=1, default=False,
  146. metavar = "git options",
  147. help="run git with options in both repos")
  148. parser.add_option("--pull", nargs=2, default=False,
  149. metavar = "remote branch",
  150. help="git pull (both repos)")
  151. parser.add_option("--push", nargs=3, default=False,
  152. metavar = "remote branch comment",
  153. help="git commit + push (both repos) [remote] [branch] [comment]")
  154. parser.add_option("--checkout", nargs=1, default=False,
  155. metavar = "branch",
  156. help="git checkout [branch]")
  157. parser.add_option("-l", "--latest",
  158. action="store_true", dest="run_latest", default=False,
  159. help="Apply the latest patches")
  160. # patch
  161. parser.add_option("-p", "--patch", nargs=1, dest="patch_list", metavar='patch_module',
  162. action="append",
  163. help="Apply patch")
  164. parser.add_option("-f", "--force",
  165. action="store_true", dest="force", default=False,
  166. help="Force Apply all patches specified using option -p or --patch")
  167. parser.add_option('--reload_doc', nargs=3, metavar = "module doctype docname",
  168. help="reload doc")
  169. parser.add_option('--export_doc', nargs=2, metavar = "doctype docname",
  170. help="export doc")
  171. # install
  172. parser.add_option('--install', nargs=2, metavar = "dbname source",
  173. help="install fresh db")
  174. # diff
  175. parser.add_option('--diff_ref_file', nargs=0, \
  176. help="Get missing database records and mismatch properties, with file as reference")
  177. parser.add_option('--diff_ref_db', nargs=0, \
  178. help="Get missing .txt files and mismatch properties, with database as reference")
  179. # scheduler
  180. parser.add_option('--run_scheduler', default=False, action="store_true",
  181. help="Trigger scheduler")
  182. parser.add_option('--run_scheduler_event', nargs=1, metavar="[all|daily|weekly|monthly]",
  183. help="Run scheduler event")
  184. # misc
  185. parser.add_option("--replace", nargs=3, default=False,
  186. metavar = "search replace_by extension",
  187. help="file search-replace")
  188. parser.add_option("--sync_all", help="Synchronize all DocTypes using txt files",
  189. nargs=0)
  190. parser.add_option("--sync", help="Synchronize given DocType using txt file",
  191. nargs=2, metavar="module doctype (use their folder names)")
  192. parser.add_option("--update", help="Pull, run latest patches and sync all",
  193. nargs=2, metavar="ORIGIN BRANCH")
  194. parser.add_option("--cleanup_data", help="Cleanup test data", default=False,
  195. action="store_true")
  196. parser.add_option("--append_future_import", default=False, action="store_true",
  197. help="append from __future__ import unicode literals to py files")
  198. parser.add_option("--backup", help="Takes backup of database in backup folder",
  199. default=False, action="store_true")
  200. return parser.parse_args()
  201. def run():
  202. sys.path.append('.')
  203. sys.path.append('lib')
  204. sys.path.append('app')
  205. import webnotes
  206. import conf
  207. (options, args) = setup_options()
  208. from webnotes.db import Database
  209. import webnotes.modules.patch_handler
  210. # connect
  211. if options.db_name is not None:
  212. if options.password:
  213. webnotes.connect(options.db_name, options.password)
  214. else:
  215. webnotes.connect(options.db_name)
  216. elif not any([options.install, options.pull]):
  217. webnotes.connect(conf.db_name)
  218. # build
  219. if options.build:
  220. from webnotes.utils import bundlejs
  221. bundlejs.bundle(options.no_compress)
  222. if options.watch:
  223. from webnotes.utils import bundlejs
  224. bundlejs.watch(options.no_compress)
  225. # code replace
  226. elif options.replace:
  227. print options.replace
  228. replace_code('.', options.replace[0], options.replace[1], options.replace[2], force=options.force)
  229. # git
  230. elif options.status:
  231. os.chdir('lib')
  232. os.system('git status')
  233. os.chdir('../app')
  234. os.system('git status')
  235. elif options.git:
  236. os.chdir('lib')
  237. os.system('git %s' % options.git)
  238. os.chdir('../app')
  239. os.system('git %s' % options.git)
  240. elif options.pull:
  241. pull(options.pull[0], options.pull[1])
  242. elif options.push:
  243. os.chdir('lib')
  244. os.system('git commit -a -m "%s"' % options.push[2])
  245. os.system('git push %s %s' % (options.push[0], options.push[1]))
  246. os.chdir('../app')
  247. os.system('git commit -a -m "%s"' % options.push[2])
  248. os.system('git push %s %s' % (options.push[0], options.push[1]))
  249. elif options.checkout:
  250. os.chdir('lib')
  251. os.system('git checkout %s' % options.checkout)
  252. os.chdir('../app')
  253. os.system('git checkout %s' % options.checkout)
  254. # patch
  255. elif options.patch_list:
  256. # clear log
  257. webnotes.modules.patch_handler.log_list = []
  258. # run individual patches
  259. for patch in options.patch_list:
  260. webnotes.modules.patch_handler.run_single(\
  261. patchmodule = patch, force = options.force)
  262. print '\n'.join(webnotes.modules.patch_handler.log_list)
  263. # reload
  264. elif options.reload_doc:
  265. webnotes.modules.patch_handler.reload_doc(\
  266. {"module":options.reload_doc[0], "dt":options.reload_doc[1], "dn":options.reload_doc[2]})
  267. print '\n'.join(webnotes.modules.patch_handler.log_list)
  268. elif options.export_doc:
  269. from webnotes.modules import export_doc
  270. export_doc(options.export_doc[0], options.export_doc[1])
  271. # run all pending
  272. elif options.run_latest:
  273. apply_latest_patches()
  274. elif options.install:
  275. from webnotes.install_lib.install import Installer
  276. inst = Installer('root')
  277. inst.import_from_db(options.install[0], source_path=options.install[1], \
  278. password='admin', verbose = 1)
  279. elif options.diff_ref_file is not None:
  280. import webnotes.modules.diff
  281. webnotes.modules.diff.diff_ref_file()
  282. elif options.diff_ref_db is not None:
  283. import webnotes.modules.diff
  284. webnotes.modules.diff.diff_ref_db()
  285. elif options.run_scheduler:
  286. import webnotes.utils.scheduler
  287. print webnotes.utils.scheduler.execute()
  288. elif options.run_scheduler_event is not None:
  289. import webnotes.utils.scheduler
  290. print webnotes.utils.scheduler.trigger('execute_' + options.run_scheduler_event)
  291. elif options.sync_all is not None:
  292. sync_all(options.force or 0)
  293. elif options.sync is not None:
  294. import webnotes.model.sync
  295. webnotes.model.sync.sync(options.sync[0], options.sync[1], options.force or 0)
  296. elif options.update:
  297. update_erpnext(options.update[0], options.update[1])
  298. elif options.cleanup_data:
  299. from utilities import cleanup_data
  300. cleanup_data.run()
  301. elif options.domain:
  302. webnotes.conn.set_value('Website Settings', None, 'subdomain', options.domain)
  303. webnotes.conn.commit()
  304. print "Domain set to", options.domain
  305. elif options.build_web_cache:
  306. import website.web_cache
  307. website.web_cache.refresh_cache(['Blog'])
  308. elif options.append_future_import:
  309. append_future_import()
  310. elif options.backup:
  311. from webnotes.utils.backups import scheduled_backup
  312. scheduled_backup()
  313. # print messages
  314. if webnotes.message_log:
  315. print '\n'.join(webnotes.message_log)
  316. if __name__=='__main__':
  317. run()