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

/share/tools/import_bash_settings.py

https://github.com/psychocandy/fish-shell
Python | 299 lines | 280 code | 7 blank | 12 comment | 8 complexity | 2ac00993a8d327b892637d3808e6eb53 MD5 | raw file
Possible License(s): LGPL-2.0
  1. #!/usr/bin/env python
  2. """
  3. <OWNER> = Siteshwar Vashisht
  4. <YEAR> = 2012
  5. Copyright (c) 2012, Siteshwar Vashisht
  6. All rights reserved.
  7. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  8. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  9. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  10. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11. """
  12. import os, sys, re
  13. import bash_converter
  14. config_file = None
  15. output_buff = ""
  16. prompt_buff = ""
  17. i = 0
  18. quote_started = False
  19. bash_builtins = ["export"]
  20. #Remove leading and trailing single quotes from a string
  21. def remove_single_quotes(input):
  22. start = 0
  23. end = len(input)
  24. if input[0] == "'":
  25. start = 1
  26. if input[end-1] == "'":
  27. end = end - 1
  28. return input[start:end]
  29. #Find outside quotes
  30. def contains_outside_quotes(input, ch):
  31. in_quotes = False
  32. i = 0
  33. while i < len(input):
  34. if input[i] == ch and in_quotes == False:
  35. return True
  36. elif input[i] == '\\' and in_quotes == True:
  37. i = i+1
  38. elif input[i] == '"':
  39. in_quotes = not in_quotes
  40. elif input[i] == "'" and not in_quotes:
  41. i = i + 1
  42. while input[i] != "'":
  43. i = i + 1
  44. i = i + 1
  45. return False
  46. #Replace characters outside double quotes
  47. def replace_outside_quotes(input, oldchar, newchar, change_all = True):
  48. in_quotes = False
  49. newstr = []
  50. i = 0
  51. while i < len(input):
  52. if input[i] == oldchar and in_quotes == False:
  53. newstr.append(newchar)
  54. i = i+1
  55. if change_all == True:
  56. continue
  57. else:
  58. while i < len(input):
  59. newstr.append(input[i])
  60. i = i + 1
  61. #Break loop and return all the characters in list by joining them
  62. break
  63. elif input[i] == '\\' and in_quotes == True:
  64. newstr.append(input[i])
  65. i = i+1
  66. elif input[i] == '"':
  67. in_quotes=not in_quotes
  68. elif input[i] == "'" and not in_quotes:
  69. newstr.append(input[i])
  70. i = i + 1
  71. while input[i] != "'":
  72. newstr.append(input[i])
  73. i = i + 1
  74. newstr.append(input[i])
  75. i = i + 1
  76. return ''.join(newstr)
  77. #Parse input passed to the script
  78. def parse_input(input):
  79. global output_buff
  80. env_regex = re.compile("(.*?)=(.*)")
  81. env_regex_matched = re.search(env_regex, input)
  82. while env_regex_matched != None:
  83. env_name = env_regex_matched.group(1)
  84. env_value = env_regex_matched.group(2)
  85. env_var = env_regex_matched.group(0)
  86. if env_name[:5] == "alias":
  87. add_alias(env_name[6:], env_value)
  88. input = input[env_regex_matched.end():]
  89. elif env_name == "PS1":
  90. if len(env_value) > 0:
  91. parse_bash_prompt(env_value)
  92. input = input[env_regex_matched.end():]
  93. elif env_name == "PATH":
  94. output_buff += "set -x " + env_name + ' ' + env_value.replace(":"," ")
  95. input = input[env_regex_matched.end():]
  96. else:
  97. full_value = env_value
  98. input = input[env_regex_matched.end():]
  99. while len(env_value) > 0 and env_value[len(env_value)-1] == "\\":
  100. one_line_regex = re.compile("\n.*")
  101. one_line_matched = re.search(one_line_regex, input)
  102. env_value = one_line_matched.group(0)
  103. full_value = full_value + env_value
  104. input = input[one_line_matched.end():]
  105. output_buff += "set_default " + env_name + ' "' + full_value + '"'
  106. #Move to next line
  107. output_buff += "\n"
  108. config_file.write(output_buff)
  109. output_buff = ""
  110. env_regex_matched = re.search(env_regex, input)
  111. #Add an alias as a function in fish
  112. def add_alias(alias_name, alias_value):
  113. global output_buff
  114. alias_value = remove_single_quotes(alias_value)
  115. output_buff += "function " + alias_name
  116. output_buff = bash_converter.parse_input(alias_value, output_buff)
  117. output_buff += " $argv\nend;\n"
  118. def parse_control_sequence():
  119. ch = next_prompt_char()
  120. ch2 = None
  121. while (ch != ""):
  122. if ch == "\\":
  123. ch2 = next_prompt_char()
  124. if (ch2 == "]"):
  125. return
  126. ch = next_prompt_char()
  127. def is_digit(ch):
  128. if ch>='0' and ch<='9':
  129. return True
  130. return False
  131. def set_prompt_buff(value):
  132. global i, buff
  133. i = 0
  134. buff = value
  135. def next_prompt_char():
  136. global i, buff
  137. if (i < len(buff)):
  138. next = buff[i]
  139. i = i+1
  140. else:
  141. next = ""
  142. return next
  143. def unget_prompt_char():
  144. global i
  145. i = i - 1
  146. def add_to_echo(str, is_special=True):
  147. global quote_started
  148. if (is_special == True):
  149. if (quote_started == True):
  150. config_file.write('"')
  151. quote_started = False
  152. else:
  153. if (quote_started == False):
  154. config_file.write('"')
  155. quote_started = True
  156. config_file.write(str)
  157. def check_end_quote():
  158. global quote_started
  159. if quote_started == True:
  160. # print "Ending quote",
  161. config_file.write('"')
  162. def parse_bash_prompt(bash_prompt):
  163. set_prompt_buff(bash_prompt)
  164. config_file.write("function fish_prompt\n")
  165. if ("\\$" in bash_prompt):
  166. config_file.write("\tif test (id -u) -eq \"0\"\n")
  167. config_file.write("\t\tset uid_prompt \"#\"\n")
  168. config_file.write("\telse\n")
  169. config_file.write("\t\tset uid_prompt \"\\$\"\n")
  170. config_file.write("\tend;\n")
  171. config_file.write('\techo -n ')
  172. ch = next_prompt_char()
  173. ch2 = None
  174. while (ch != ""):
  175. if ( ch == "\\"):
  176. ch2 = next_prompt_char()
  177. if (ch2 == ""):
  178. continue
  179. elif (ch2 == "a"):
  180. add_to_echo('\\a')
  181. elif (ch2 == "d"):
  182. add_to_echo(' (date +"%a %b %d")')
  183. elif (ch2 == "e"):
  184. add_to_echo('\e')
  185. elif (ch2 == "h"):
  186. add_to_echo("(hostname | cut -d\".\" -f1)")
  187. elif (ch2 == "H"):
  188. add_to_echo("(hostname)")
  189. elif (ch2 == "j"):
  190. add_to_echo("(jobs | wc -l)")
  191. elif (ch2 == "l"):
  192. add_to_echo("basename (tty)")
  193. elif (ch2 == "n"):
  194. add_to_echo(' \\n ')
  195. elif (ch2 == "r"):
  196. add_to_echo(' \\r ')
  197. elif (ch2 == "s"):
  198. add_to_echo("fish", False)
  199. elif (ch2 == "t"):
  200. add_to_echo('(date +"%H:%M:%S")')
  201. elif (ch2 == "T"):
  202. add_to_echo('(date +"%I:%M:%S")')
  203. elif (ch2 == "@"):
  204. add_to_echo('(date +"%I:%M %p")')
  205. elif (ch2 == "u"):
  206. add_to_echo("$USER")
  207. elif (ch2 == "w"):
  208. add_to_echo("(pwd)")
  209. elif (ch2 == "W"):
  210. add_to_echo("(basename ( pwd ) )")
  211. elif (ch2 == "$"):
  212. add_to_echo("$uid_prompt ")
  213. elif (is_digit(ch2)):
  214. temp = int(ch2)
  215. ch = next_prompt_char()
  216. if (is_digit(ch)):
  217. temp = (temp*8) + int(ch)
  218. else:
  219. add_to_echo(chr(temp), False)
  220. unget_prompt_char()
  221. ch = next_prompt_char()
  222. if (is_digit(ch)):
  223. temp = ((temp/10)*64) + ((temp%10)*8) + int(ch)
  224. add_to_echo(chr(temp), False)
  225. else:
  226. add_to_echo(chr(temp), False)
  227. unget_prompt_char()
  228. elif (ch2 == "\\"):
  229. add_to_echo("\\")
  230. elif (ch2 == "["):
  231. parse_control_sequence()
  232. elif (ch2 == "]"):
  233. # print "Unexpected ]"
  234. pass
  235. elif (ch2 == "v" or ch2 == "V"):
  236. add_to_echo("(fish -v 2>| cut -d\" \" -f3)")
  237. else:
  238. # print "Unknown escape character"
  239. pass
  240. else:
  241. if (ch == "$"):
  242. add_to_echo("\\", False)
  243. add_to_echo(ch,False)
  244. ch = next_prompt_char()
  245. check_end_quote()
  246. config_file.write("\nend\n")
  247. if __name__ == "__main__":
  248. input = sys.stdin.read()
  249. config_file = open("{0}/.config/fish/bash_config.fish".format(os.environ["HOME"]),"a")
  250. parse_input(input)