Groonga 3.0.9 Source Code Document
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
update_execution_example.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8; -*- 
3 
4 from subprocess import *
5 from select import select
6 from sys import argv,stdout
7 import os
8 import os.path
9 import shutil
10 import re
11 import json
12 
13 DB_DIRECTORY = "/tmp/groonga-databases"
14 DEFAULT_DB_NAME = "tutorial.db"
15 
16 shutil.rmtree(DB_DIRECTORY, ignore_errors=True)
17 os.makedirs(DB_DIRECTORY)
18 
19 groonga_process = None
21  global groonga_process
22  if groonga_process:
23  groonga_process.stdin.close()
24  groonga_process.stdout.close()
25  groonga_process = None
26  print '###<<< database: close'
27 
28 def reconnect(name):
29  global groonga_process
31  db_path = os.path.join(DB_DIRECTORY, name)
32  if os.path.exists(db_path):
33  groonga_process = Popen(["groonga", db_path], stdin=PIPE, stdout=PIPE)
34  else:
35  groonga_process = Popen(["groonga", "-n", db_path], stdin=PIPE, stdout=PIPE)
36  print '###>>> database: open <%s>' % db_path
37 
38 fout = None
39 
40 def normalize_output(output):
41  status = output[0]
42  if status:
43  normalized_start_time = 1337566253.89858
44  normalized_elapsed_time = 0.000355720520019531
45  status[1] = normalized_start_time
46  status[2] = normalized_elapsed_time
47  return output
48 
49 def execmd(command, fout):
50  stdout.write(command + "\n")
51  stdout.flush()
52  groonga_process.stdin.write(command + "\n")
53  groonga_process.stdin.flush()
54  is_command = re.match("[a-z/]", command)
55  is_load_command = re.match("load ", command)
56  is_console = not re.match("/", command)
57  if fout:
58  if is_console:
59  prefix = " "
60  else:
61  prefix = " % curl http://localhost:10041"
62  formatted_command_line = prefix + command + "\n"
63  fout.write(formatted_command_line)
64  is_load_data_end = re.match("^\]", command)
65  if is_load_command:
66  return
67  if not is_command and not is_load_data_end:
68  return
69  output_buffer = ""
70  first_timeout = 1
71  rest_timeout = 0.1
72  timeout = first_timeout
73  while True:
74  out = select([groonga_process.stdout], [], [], timeout)
75  timeout = rest_timeout
76  if len(out[0]):
77  char = groonga_process.stdout.read(1)
78  if char is None:
79  stdout.write(output_buffer)
80  if fout:
81  fout.write(output_buffer)
82  else:
83  output_buffer += char
84  if char == '\n':
85  parsed_output = json.loads(output_buffer)
86  normalized_output = normalize_output(parsed_output)
87  if len(output_buffer) < 80:
88  formatted_output = json.dumps(normalized_output,
89  ensure_ascii=False)
90  else:
91  formatted_output = json.dumps(normalized_output,
92  indent=2,
93  ensure_ascii=False)
94  formatted_output += "\n"
95  formatted_output = formatted_output.encode("utf-8")
96  stdout.write(formatted_output)
97  stdout.write("\n")
98  if fout:
99  if is_console:
100  prefix = " # "
101  else:
102  prefix = " "
103  first_lines_re = re.compile("^", re.M)
104  fout.write(first_lines_re.sub(prefix, formatted_output.strip()))
105  fout.write("\n")
106  output_buffer = ""
107  else:
108  stdout.flush()
109  break
110 
111 processed_files = []
112 def readfile(fname, outflag):
113  if fname in processed_files:
114  print "skipped processed file: %s" % fname
115  return
116  if outflag > 32:
117  print "!!!! INCLUDE DEPTH OVER !!!!"
118  raise
119  processed_files.append(fname)
120 
121  b = fname.rfind('/')
122  if b < 0:
123  rootdir = './'
124  else:
125  rootdir = fname[0:b+1]
126 
127  fi = open(fname, 'r')
128  dat = fi.read().split("\n")
129  fi.close()
130 
131  line = 0;
132  while len(dat):
133  cmd = dat.pop(0)
134  if cmd.startswith('.. groonga-command'):
135  print '### command start'
136  fout = None
137  while len(dat):
138  cmd = dat.pop(0)
139  if cmd.startswith('.. database:'):
140  database_name = cmd[cmd.index(":")+1:].strip()
141  reconnect(database_name)
142  elif cmd.startswith('.. include:: '):
143  a = rootdir + cmd[13:]
144  dir_name = os.path.dirname(a)
145  if not os.path.exists(dir_name):
146  os.makedirs(dir_name)
147  fout = open(a, 'w')
148  print '### write start : ' + a
149  fout.write("Execution example::\n\n")
150  elif cmd.startswith('.. % '):
151  command_line = cmd[5:]
152  if fout:
153  fout.write(" " + command_line + "\n")
154  print command_line
155  os.system(command_line)
156  elif cmd.startswith('.. .. '):
157  command_line = cmd[6:]
158  if fout:
159  fout.write(" " + command_line + "\n")
160  print command_line
161  elif cmd.startswith('..'):
162  if cmd.replace(' ', '').replace("\t", '') == '..':
163  while len(dat):
164  if dat[0] == '' or (dat[0][0] != ' ' and dat[0][0] != ' '):
165  break
166  execmd(dat.pop(0), fout)
167  else:
168  cmd = cmd[3:]
169  execmd(cmd, fout)
170  else:
171  print '### command end'
172  if fout:
173  fout.close()
174  break
175  elif cmd.startswith('.. groonga-include : '):
176  a = rootdir + cmd[21:]
177  print '###>>> include : ' + a
178  readfile(a, outflag + 1)
179  print '###<<< include end'
180 
181 entry_point = "source/"
182 if len(argv) == 2:
183  entry_point = argv[1]
184 if os.path.isfile(entry_point):
185  readfile(entry_point, 0)
186 else:
187  for root, dirs, files in os.walk(entry_point):
188  for fname in files:
189  if fname.lower().endswith('.txt'):
190  b = os.path.join(root, fname)
191  print "===" + b
192  readfile(b, 0)
193 
194 if fout:
195  fout.close()
197