您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

582 行
17 KiB

  1. #!/usr/bin/env python
  2. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  3. # MIT License. See license.txt
  4. from __future__ import unicode_literals
  5. import os, sys
  6. def replace_code(start, txt1, txt2, extn, search=None, force=False):
  7. """replace all txt1 by txt2 in files with extension (extn)"""
  8. import webnotes.utils
  9. import os, re
  10. esc = webnotes.utils.make_esc('[]')
  11. if not search: search = esc(txt1)
  12. for wt in os.walk(start, followlinks=1):
  13. for fn in wt[2]:
  14. if fn.split('.')[-1]==extn:
  15. fpath = os.path.join(wt[0], fn)
  16. with open(fpath, 'r') as f:
  17. content = f.read()
  18. if re.search(search, content):
  19. res = search_replace_with_prompt(fpath, txt1, txt2, force)
  20. if res == 'skip':
  21. return 'skip'
  22. def search_replace_with_prompt(fpath, txt1, txt2, force=False):
  23. """ Search and replace all txt1 by txt2 in the file with confirmation"""
  24. from termcolor import colored
  25. with open(fpath, 'r') as f:
  26. content = f.readlines()
  27. tmp = []
  28. for c in content:
  29. if c.find(txt1) != -1:
  30. print fpath
  31. print colored(txt1, 'red').join(c[:-1].split(txt1))
  32. a = ''
  33. if force:
  34. c = c.replace(txt1, txt2)
  35. else:
  36. while a.lower() not in ['y', 'n', 'skip']:
  37. a = raw_input('Do you want to Change [y/n/skip]?')
  38. if a.lower() == 'y':
  39. c = c.replace(txt1, txt2)
  40. elif a.lower() == 'skip':
  41. return 'skip'
  42. tmp.append(c)
  43. with open(fpath, 'w') as f:
  44. f.write(''.join(tmp))
  45. print colored('Updated', 'green')
  46. def pull(remote, branch, build=False):
  47. os.system('cd lib && git pull %s %s' % (remote, branch))
  48. os.system('cd app && git pull %s %s' % (remote, branch))
  49. if build: rebuild()
  50. def rebuild():
  51. # build js / css
  52. from webnotes import build
  53. build.bundle(False)
  54. def apply_latest_patches():
  55. import webnotes.modules.patch_handler
  56. webnotes.modules.patch_handler.run_all()
  57. print '\n'.join(webnotes.modules.patch_handler.log_list)
  58. def sync_all(force=0):
  59. import webnotes.model.sync
  60. webnotes.model.sync.sync_all(force)
  61. def update_erpnext(remote='origin', branch='master'):
  62. pull(remote, branch)
  63. from webnotes.utils import execute_in_shell
  64. execute_in_shell("lib/wnf.py --patch_sync_build", verbose=1)
  65. def patch_sync_build():
  66. patch_sync()
  67. rebuild()
  68. def patch_sync():
  69. apply_latest_patches()
  70. import webnotes.modules.patch_handler
  71. for l in webnotes.modules.patch_handler.log_list:
  72. if "failed: STOPPED" in l:
  73. return
  74. sync_all()
  75. clear_cache()
  76. def clear_cache():
  77. import webnotes.sessions
  78. webnotes.sessions.clear_cache()
  79. def append_future_import():
  80. """appends from __future__ import unicode_literals to py files if necessary"""
  81. import os
  82. import conf
  83. conf_path = os.path.abspath(conf.__file__)
  84. if conf_path.endswith("pyc"):
  85. conf_path = conf_path[:-1]
  86. base_path = os.path.dirname(conf_path)
  87. for path, folders, files in os.walk(base_path):
  88. for f in files:
  89. if f.endswith('.py'):
  90. file_path = os.path.join(path, f)
  91. with open(file_path, 'r') as pyfile:
  92. content = pyfile.read()
  93. future_import = 'from __future__ import unicode_literals'
  94. if future_import in content: continue
  95. content = content.split('\n')
  96. idx = -1
  97. for c in content:
  98. idx += 1
  99. if c and not c.startswith('#'):
  100. break
  101. content.insert(idx, future_import)
  102. content = "\n".join(content)
  103. with open(file_path, 'w') as pyfile:
  104. pyfile.write(content)
  105. def setup_options():
  106. from optparse import OptionParser
  107. parser = OptionParser()
  108. # install
  109. parser.add_option('--install', nargs=2, metavar = "NEW_DB_NAME SOURCE_PATH",
  110. help="install db")
  111. parser.add_option('--install_fresh', nargs=1, metavar = "NEW_DB_NAME",
  112. help="install fresh db")
  113. parser.add_option('--reinstall', default=False, action="store_true",
  114. help="install fresh db in db_name specified in conf.py")
  115. parser.add_option('--make_demo', default=False, action="store_true",
  116. help="install in database 'demo'")
  117. parser.add_option('--make_demo_fresh', default=False, action="store_true",
  118. help="install in database 'demo'")
  119. # update
  120. parser.add_option("-u", "--update",
  121. help="Pull, run latest patches and sync all",
  122. default=False, action="store_true", metavar="ORIGIN BRANCH")
  123. parser.add_option("--backup", help="Takes backup of database in backup folder",
  124. default=False, action="store_true")
  125. # build
  126. parser.add_option("-b", "--build", default=False, action="store_true",
  127. help="minify + concat js files")
  128. parser.add_option("-w", "--watch", default=False, action="store_true",
  129. help="watch and minify + concat js files, if necessary")
  130. parser.add_option("--no_cms", default=False, action="store_true",
  131. help="do not build wn-web.js and wn-css.js")
  132. parser.add_option("--docs", default=False, action="store_true",
  133. help="Build docs")
  134. parser.add_option("-d", "--db",
  135. dest="db_name",
  136. help="Apply the patches on given db")
  137. parser.add_option("--password",
  138. help="Password for given db", nargs=1)
  139. parser.add_option("--clear_web", default=False, action="store_true",
  140. help="clear web cache")
  141. parser.add_option("--clear_cache", default=False, action="store_true",
  142. help="clear cache")
  143. parser.add_option("--clear_defaults", default=False, action="store_true",
  144. help="clear cache of defaults")
  145. parser.add_option("--domain", metavar="DOMAIN",
  146. help="store domain in Website Settings", nargs=1)
  147. # git
  148. parser.add_option("--status", default=False, action="store_true",
  149. help="git status")
  150. parser.add_option("--git", nargs=1, default=False,
  151. metavar = "git options",
  152. help="run git with options in both repos")
  153. parser.add_option("--pull", nargs=2, default=False,
  154. metavar = "remote branch",
  155. help="git pull (both repos)")
  156. parser.add_option("-c", "--commit", nargs=1, default=False,
  157. metavar = "commit both repos",
  158. help="git commit -a -m [comment]")
  159. parser.add_option("-p", "--push", default=False,
  160. action="store_true",
  161. metavar = "remote branch",
  162. help="git push (both repos) [remote] [branch]")
  163. parser.add_option("--checkout", nargs=1, default=False,
  164. metavar = "branch",
  165. help="git checkout [branch]")
  166. parser.add_option("-l", "--latest",
  167. action="store_true", dest="run_latest", default=False,
  168. help="Apply the latest patches")
  169. # patch
  170. parser.add_option("--patch", nargs=1, dest="patch_list",
  171. metavar='patch_module',
  172. action="append",
  173. help="Apply patch")
  174. parser.add_option("-f", "--force",
  175. action="store_true", dest="force", default=False,
  176. help="Force Apply all patches specified using option -p or --patch")
  177. parser.add_option('--reload_doc', nargs=3, metavar = "module doctype docname",
  178. help="reload doc")
  179. parser.add_option('--export_doc', nargs=2, metavar = "doctype docname",
  180. help="export doc")
  181. # diff
  182. parser.add_option('--diff_ref_file', nargs=0, \
  183. help="Get missing database records and mismatch properties, with file as reference")
  184. parser.add_option('--diff_ref_db', nargs=0, \
  185. help="Get missing .txt files and mismatch properties, with database as reference")
  186. # scheduler
  187. parser.add_option('--run_scheduler', default=False, action="store_true",
  188. help="Trigger scheduler")
  189. parser.add_option('--run_scheduler_event', nargs=1, metavar="[all|daily|weekly|monthly]",
  190. help="Run scheduler event")
  191. # misc
  192. parser.add_option("--replace", nargs=3, default=False,
  193. metavar = "search replace_by extension",
  194. help="file search-replace")
  195. parser.add_option("--sync_all", help="Synchronize all DocTypes using txt files",
  196. nargs=0)
  197. parser.add_option("--sync", help="Synchronize given DocType using txt file",
  198. nargs=2, metavar="module doctype (use their folder names)")
  199. parser.add_option("--patch_sync_build", action="store_true", default=False,
  200. help="run latest patches, sync all and rebuild js css")
  201. parser.add_option("--patch_sync", action="store_true", default=False,
  202. help="run latest patches, sync all")
  203. parser.add_option("--cleanup_data", help="Cleanup test data", default=False,
  204. action="store_true")
  205. parser.add_option("--append_future_import", default=False, action="store_true",
  206. help="append from __future__ import unicode literals to py files")
  207. parser.add_option("--build_message_files", default=False, action="store_true",
  208. help="Build message files for translation")
  209. parser.add_option('--export_messages', nargs=2, metavar="LANG FILENAME",
  210. help="""Export all messages for a language to translation in a csv file.
  211. Example, lib/wnf.py --export_messages hi hindi.csv""")
  212. parser.add_option('--import_messages', nargs=2, metavar="LANG FILENAME",
  213. help="""Import messages for a language and make language files.
  214. Example, lib/wnf.py --import_messages hi hindi.csv""")
  215. parser.add_option('--google_translate', nargs=3, metavar="LANG INFILE OUTFILE",
  216. help="""Auto translate using Google Translate API""")
  217. parser.add_option('--translate', nargs=1, metavar="LANG",
  218. help="""Rebuild translation for the given langauge and
  219. use Google Translate to tranlate untranslated messages. use "all" """)
  220. parser.add_option("--reset_perms", default=False, action="store_true",
  221. help="Reset permissions for all doctypes.")
  222. parser.add_option("--make_conf", default=False, action="store_true",
  223. help="Create new conf.py file")
  224. # bean helpers
  225. parser.add_option('--export_doclist', nargs=3, metavar="DOCTYPE NAME PATH",
  226. help="""Export doclist as json to the given path, use '-' as name for Singles.""")
  227. parser.add_option('--import_doclist', nargs=1, metavar="PATH",
  228. help="""Import (insert/update) doclist. If the argument is a directory, all files ending with .json are imported""")
  229. return parser.parse_args()
  230. def run():
  231. sys.path.append('.')
  232. sys.path.append('lib')
  233. sys.path.append('app')
  234. (options, args) = setup_options()
  235. # build
  236. if options.build:
  237. from webnotes import build
  238. if options.no_cms:
  239. cms_make = False
  240. else:
  241. cms_make = True
  242. build.bundle(False, cms_make)
  243. return
  244. elif options.watch:
  245. from webnotes import build
  246. build.watch(True)
  247. return
  248. # code replace
  249. elif options.replace:
  250. print options.replace
  251. replace_code('.', options.replace[0], options.replace[1], options.replace[2], force=options.force)
  252. return
  253. # git
  254. elif options.status:
  255. os.chdir('lib')
  256. os.system('git status')
  257. os.chdir('../app')
  258. os.system('git status')
  259. return
  260. elif options.git:
  261. os.chdir('lib')
  262. os.system('git %s' % options.git)
  263. os.chdir('../app')
  264. os.system('git %s' % options.git)
  265. return
  266. import webnotes
  267. import conf
  268. from webnotes.db import Database
  269. import webnotes.modules.patch_handler
  270. webnotes.print_messages = True
  271. # connect
  272. if options.db_name is not None:
  273. if options.password:
  274. webnotes.connect(options.db_name, options.password)
  275. else:
  276. webnotes.connect(options.db_name)
  277. elif not any([options.install, options.pull, options.install_fresh, options.reinstall, options.make_conf]):
  278. webnotes.connect(conf.db_name)
  279. if options.pull:
  280. pull(options.pull[0], options.pull[1], build=True)
  281. elif options.commit:
  282. os.chdir('lib')
  283. os.system('git commit -a -m "%s"' % (options.commit))
  284. os.chdir('../app')
  285. os.system('git commit -a -m "%s"' % (options.commit))
  286. elif options.push:
  287. if not args:
  288. args = ["origin", conf.branch]
  289. os.chdir('lib')
  290. os.system('git push %s %s' % (args[0], args[1]))
  291. os.chdir('../app')
  292. os.system('git push %s %s' % (args[0], args[1]))
  293. elif options.checkout:
  294. os.chdir('lib')
  295. os.system('git checkout %s' % options.checkout)
  296. os.chdir('../app')
  297. os.system('git checkout %s' % options.checkout)
  298. # patch
  299. elif options.patch_list:
  300. # clear log
  301. webnotes.modules.patch_handler.log_list = []
  302. # run individual patches
  303. for patch in options.patch_list:
  304. webnotes.modules.patch_handler.run_single(\
  305. patchmodule = patch, force = options.force)
  306. print '\n'.join(webnotes.modules.patch_handler.log_list)
  307. # reload
  308. elif options.reload_doc:
  309. webnotes.modules.patch_handler.reload_doc(\
  310. {"module":options.reload_doc[0], "dt":options.reload_doc[1], "dn":options.reload_doc[2]})
  311. print '\n'.join(webnotes.modules.patch_handler.log_list)
  312. elif options.export_doc:
  313. from webnotes.modules import export_doc
  314. export_doc(options.export_doc[0], options.export_doc[1])
  315. # run all pending
  316. elif options.run_latest:
  317. apply_latest_patches()
  318. elif options.install:
  319. from webnotes.install_lib.install import Installer
  320. inst = Installer('root')
  321. inst.import_from_db(options.install[0], source_path=options.install[1],
  322. verbose = 1)
  323. elif options.install_fresh:
  324. from webnotes.install_lib.install import Installer
  325. inst = Installer('root')
  326. inst.import_from_db(options.install_fresh, verbose = 1)
  327. elif options.reinstall:
  328. from webnotes.install_lib.install import Installer
  329. inst = Installer('root')
  330. import conf
  331. inst.import_from_db(conf.db_name, verbose = 1)
  332. elif options.make_demo:
  333. import utilities.demo.make_demo
  334. utilities.demo.make_demo.make()
  335. elif options.make_demo_fresh:
  336. import utilities.demo.make_demo
  337. utilities.demo.make_demo.make(reset=True)
  338. elif options.diff_ref_file is not None:
  339. import webnotes.modules.diff
  340. webnotes.modules.diff.diff_ref_file()
  341. elif options.diff_ref_db is not None:
  342. import webnotes.modules.diff
  343. webnotes.modules.diff.diff_ref_db()
  344. elif options.run_scheduler:
  345. import webnotes.utils.scheduler
  346. print webnotes.utils.scheduler.execute()
  347. elif options.run_scheduler_event is not None:
  348. import webnotes.utils.scheduler
  349. print webnotes.utils.scheduler.trigger('execute_' + options.run_scheduler_event)
  350. elif options.sync_all is not None:
  351. sync_all(options.force or 0)
  352. elif options.sync is not None:
  353. webnotes.reload_doc(options.sync[0], "doctype", options.sync[1])
  354. elif options.update:
  355. if not args:
  356. args = ["origin", conf.branch]
  357. update_erpnext(args[0], args[1])
  358. elif options.patch_sync_build:
  359. patch_sync_build()
  360. elif options.patch_sync:
  361. patch_sync()
  362. elif options.cleanup_data:
  363. from utilities import cleanup_data
  364. cleanup_data.run()
  365. elif options.domain:
  366. webnotes.conn.set_value('Website Settings', None, 'subdomain', options.domain)
  367. webnotes.conn.commit()
  368. print "Domain set to", options.domain
  369. elif options.clear_web:
  370. # build wn-web.js and wn-web.css
  371. from website.doctype.website_settings.make_web_include_files import make
  372. make()
  373. import webnotes.webutils
  374. webnotes.webutils.clear_cache()
  375. elif options.clear_cache:
  376. clear_cache()
  377. elif options.clear_defaults:
  378. import webnotes.defaults
  379. webnotes.defaults.clear_cache()
  380. webnotes.clear_cache()
  381. elif options.append_future_import:
  382. append_future_import()
  383. elif options.backup:
  384. from webnotes.utils.backups import scheduled_backup
  385. scheduled_backup(ignore_files = True)
  386. # print messages
  387. if webnotes.message_log:
  388. print '\n'.join(webnotes.message_log)
  389. elif options.build_message_files:
  390. import webnotes.translate
  391. webnotes.translate.build_message_files()
  392. elif options.export_messages:
  393. import webnotes.translate
  394. webnotes.translate.export_messages(*options.export_messages)
  395. elif options.import_messages:
  396. import webnotes.translate
  397. webnotes.translate.import_messages(*options.import_messages)
  398. elif options.google_translate:
  399. from webnotes.translate import google_translate
  400. google_translate(*options.google_translate)
  401. elif options.translate:
  402. from webnotes.translate import translate
  403. translate(options.translate)
  404. elif options.docs:
  405. from core.doctype.documentation_tool.documentation_tool import write_static
  406. write_static()
  407. elif options.export_doclist:
  408. import json
  409. from webnotes.handler import json_handler
  410. args = list(options.export_doclist)
  411. if args[1]=="-": args[1] = args[0]
  412. with open(args[2], "w") as outfile:
  413. outfile.write(json.dumps([d.fields for d in \
  414. webnotes.bean(args[0], args[1]).doclist], default=json_handler, indent=1, sort_keys=True))
  415. elif options.import_doclist:
  416. import json
  417. if os.path.isdir(options.import_doclist):
  418. docs = [os.path.join(options.import_doclist, f) \
  419. for f in os.listdir(options.import_doclist) if f.endswith(".json")]
  420. else:
  421. docs = [options.import_doclist]
  422. for f in docs:
  423. with open(f, "r") as infile:
  424. doclist = json.loads(infile.read())
  425. if webnotes.conn.exists(doclist[0]["doctype"], doclist[0]["name"]):
  426. b = webnotes.bean(doclist).save()
  427. print "Updated: %s, %s" % (b.doc.doctype, b.doc.name)
  428. else:
  429. b = webnotes.bean(doclist).insert()
  430. print "Inserted: %s, %s" % (b.doc.doctype, b.doc.name)
  431. elif options.reset_perms:
  432. for d in webnotes.conn.sql_list("""select name from `tabDocType`
  433. where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
  434. try:
  435. webnotes.clear_cache(doctype=d)
  436. webnotes.reset_perms(d)
  437. except:
  438. pass
  439. elif options.make_conf:
  440. if os.path.exists("conf.py"):
  441. os.system("mv conf.py conf.py.bak")
  442. with open("lib/conf/conf.py", "r") as confsrc:
  443. confstr = confsrc.read()
  444. db_name = raw_input("Database Name: ")
  445. if not db_name:
  446. print "Database Name Required"
  447. return
  448. db_password = raw_input("Database Password: ")
  449. if not db_password:
  450. print "Database Name Required"
  451. return
  452. with open("conf.py", "w") as conftar:
  453. conftar.write(confstr % {"db_name": db_name, "db_password": db_password })
  454. if __name__=='__main__':
  455. run()