Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

13 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
13 anos atrás
13 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
12 anos atrás
12 anos atrás
12 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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('--export_csv', nargs=2, metavar="DOCTYPE PATH",
  228. help="""Dump DocType as csv.""")
  229. parser.add_option('--import_doclist', nargs=1, metavar="PATH",
  230. help="""Import (insert/update) doclist. If the argument is a directory, all files ending with .json are imported""")
  231. return parser.parse_args()
  232. def run():
  233. sys.path.append('.')
  234. sys.path.append('lib')
  235. sys.path.append('app')
  236. (options, args) = setup_options()
  237. # build
  238. if options.build:
  239. from webnotes import build
  240. if options.no_cms:
  241. cms_make = False
  242. else:
  243. cms_make = True
  244. build.bundle(False, cms_make)
  245. return
  246. elif options.watch:
  247. from webnotes import build
  248. build.watch(True)
  249. return
  250. # code replace
  251. elif options.replace:
  252. print options.replace
  253. replace_code('.', options.replace[0], options.replace[1], options.replace[2], force=options.force)
  254. return
  255. # git
  256. elif options.status:
  257. os.chdir('lib')
  258. os.system('git status')
  259. os.chdir('../app')
  260. os.system('git status')
  261. return
  262. elif options.git:
  263. os.chdir('lib')
  264. os.system('git %s' % options.git)
  265. os.chdir('../app')
  266. os.system('git %s' % options.git)
  267. return
  268. import webnotes
  269. try:
  270. import conf
  271. except ImportError, e:
  272. conf = webnotes._dict({})
  273. from webnotes.db import Database
  274. import webnotes.modules.patch_handler
  275. webnotes.print_messages = True
  276. # connect
  277. if options.db_name is not None:
  278. if options.password:
  279. webnotes.connect(options.db_name, options.password)
  280. else:
  281. webnotes.connect(options.db_name)
  282. elif not any([options.install, options.pull, options.install_fresh, options.reinstall, options.make_conf]):
  283. webnotes.connect(conf.db_name)
  284. if options.pull:
  285. pull(options.pull[0], options.pull[1], build=True)
  286. elif options.commit:
  287. os.chdir('lib')
  288. os.system('git commit -a -m "%s"' % (options.commit))
  289. os.chdir('../app')
  290. os.system('git commit -a -m "%s"' % (options.commit))
  291. elif options.push:
  292. if not args:
  293. args = ["origin", conf.branch]
  294. os.chdir('lib')
  295. os.system('git push %s %s' % (args[0], args[1]))
  296. os.chdir('../app')
  297. os.system('git push %s %s' % (args[0], args[1]))
  298. elif options.checkout:
  299. os.chdir('lib')
  300. os.system('git checkout %s' % options.checkout)
  301. os.chdir('../app')
  302. os.system('git checkout %s' % options.checkout)
  303. # patch
  304. elif options.patch_list:
  305. # clear log
  306. webnotes.modules.patch_handler.log_list = []
  307. # run individual patches
  308. for patch in options.patch_list:
  309. webnotes.modules.patch_handler.run_single(\
  310. patchmodule = patch, force = options.force)
  311. print '\n'.join(webnotes.modules.patch_handler.log_list)
  312. # reload
  313. elif options.reload_doc:
  314. webnotes.modules.patch_handler.reload_doc(\
  315. {"module":options.reload_doc[0], "dt":options.reload_doc[1], "dn":options.reload_doc[2]})
  316. print '\n'.join(webnotes.modules.patch_handler.log_list)
  317. elif options.export_doc:
  318. from webnotes.modules import export_doc
  319. export_doc(options.export_doc[0], options.export_doc[1])
  320. # run all pending
  321. elif options.run_latest:
  322. apply_latest_patches()
  323. elif options.install:
  324. from webnotes.install_lib.install import Installer
  325. inst = Installer('root')
  326. inst.import_from_db(options.install[0], source_path=options.install[1],
  327. verbose = 1)
  328. elif options.install_fresh:
  329. from webnotes.install_lib.install import Installer
  330. inst = Installer('root')
  331. inst.import_from_db(options.install_fresh, verbose = 1)
  332. elif options.reinstall:
  333. from webnotes.install_lib.install import Installer
  334. inst = Installer('root')
  335. import conf
  336. inst.import_from_db(conf.db_name, verbose = 1)
  337. elif options.make_demo:
  338. import utilities.demo.make_demo
  339. utilities.demo.make_demo.make()
  340. elif options.make_demo_fresh:
  341. import utilities.demo.make_demo
  342. utilities.demo.make_demo.make(reset=True)
  343. elif options.diff_ref_file is not None:
  344. import webnotes.modules.diff
  345. webnotes.modules.diff.diff_ref_file()
  346. elif options.diff_ref_db is not None:
  347. import webnotes.modules.diff
  348. webnotes.modules.diff.diff_ref_db()
  349. elif options.run_scheduler:
  350. import webnotes.utils.scheduler
  351. print webnotes.utils.scheduler.execute()
  352. elif options.run_scheduler_event is not None:
  353. import webnotes.utils.scheduler
  354. print webnotes.utils.scheduler.trigger('execute_' + options.run_scheduler_event)
  355. elif options.sync_all is not None:
  356. sync_all(options.force or 0)
  357. elif options.sync is not None:
  358. webnotes.reload_doc(options.sync[0], "doctype", options.sync[1])
  359. elif options.update:
  360. if not args:
  361. args = ["origin", conf.branch]
  362. update_erpnext(args[0], args[1])
  363. elif options.patch_sync_build:
  364. patch_sync_build()
  365. elif options.patch_sync:
  366. patch_sync()
  367. elif options.cleanup_data:
  368. from utilities import cleanup_data
  369. cleanup_data.run()
  370. elif options.domain:
  371. webnotes.conn.set_value('Website Settings', None, 'subdomain', options.domain)
  372. webnotes.conn.commit()
  373. print "Domain set to", options.domain
  374. elif options.clear_web:
  375. # build wn-web.js and wn-web.css
  376. from website.doctype.website_settings.make_web_include_files import make
  377. make()
  378. import webnotes.webutils
  379. webnotes.webutils.clear_cache()
  380. elif options.clear_cache:
  381. clear_cache()
  382. elif options.clear_defaults:
  383. import webnotes.defaults
  384. webnotes.defaults.clear_cache()
  385. webnotes.clear_cache()
  386. elif options.append_future_import:
  387. append_future_import()
  388. elif options.backup:
  389. from webnotes.utils.backups import scheduled_backup
  390. scheduled_backup(ignore_files = True)
  391. # print messages
  392. if webnotes.message_log:
  393. print '\n'.join(webnotes.message_log)
  394. elif options.build_message_files:
  395. import webnotes.translate
  396. webnotes.translate.build_message_files()
  397. elif options.export_messages:
  398. import webnotes.translate
  399. webnotes.translate.export_messages(*options.export_messages)
  400. elif options.import_messages:
  401. import webnotes.translate
  402. webnotes.translate.import_messages(*options.import_messages)
  403. elif options.google_translate:
  404. from webnotes.translate import google_translate
  405. google_translate(*options.google_translate)
  406. elif options.translate:
  407. from webnotes.translate import translate
  408. translate(options.translate)
  409. elif options.docs:
  410. from core.doctype.documentation_tool.documentation_tool import write_static
  411. write_static()
  412. elif options.export_doclist:
  413. from core.page.data_import_tool.data_import_tool import export_json
  414. export_json(*list(options.export_doclist))
  415. elif options.export_csv:
  416. from core.page.data_import_tool.data_import_tool import export_csv
  417. export_csv(*options.export_csv)
  418. elif options.import_doclist:
  419. import json
  420. if os.path.isdir(options.import_doclist):
  421. docs = [os.path.join(options.import_doclist, f) \
  422. for f in os.listdir(options.import_doclist)]
  423. else:
  424. docs = [options.import_doclist]
  425. for f in docs:
  426. if f.endswith(".json"):
  427. with open(f, "r") as infile:
  428. b = webnotes.bean(json.loads(infile.read())).insert_or_update()
  429. print "Imported: " + b.doc.doctype + " / " + b.doc.name
  430. webnotes.conn.commit()
  431. if f.endswith(".csv"):
  432. from core.page.data_import_tool.data_import_tool import import_file_by_path
  433. import_file_by_path(f, ignore_links=True)
  434. webnotes.conn.commit()
  435. elif options.reset_perms:
  436. for d in webnotes.conn.sql_list("""select name from `tabDocType`
  437. where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
  438. try:
  439. webnotes.clear_cache(doctype=d)
  440. webnotes.reset_perms(d)
  441. except:
  442. pass
  443. elif options.make_conf:
  444. if os.path.exists("conf.py"):
  445. os.system("mv conf.py conf.py.bak")
  446. with open("lib/conf/conf.py", "r") as confsrc:
  447. confstr = confsrc.read()
  448. db_name = raw_input("Database Name: ")
  449. if not db_name:
  450. print "Database Name Required"
  451. return
  452. db_password = raw_input("Database Password: ")
  453. if not db_password:
  454. print "Database Name Required"
  455. return
  456. with open("conf.py", "w") as conftar:
  457. conftar.write(confstr % {"db_name": db_name, "db_password": db_password })
  458. if __name__=='__main__':
  459. run()