def get_fn (self,s,tag): pc = self c = pc.c fn = s or c.p.h[len(tag):] fn = fn.strip() # Similar to code in g.computeFileUrl if fn.startswith('~'): # Expand '~' and handle Leo expressions. fn = fn[1:] fn = g.os_path_expanduser(fn) fn = g.os_path_expandExpression(fn,c=c) fn = g.os_path_finalize(fn) else: # Handle Leo expressions. fn = g.os_path_expandExpression(fn,c=c) # Handle ancestor @path directives. if c and c.openDirectory: base = c.getNodePath(c.p) fn = g.os_path_finalize_join(c.openDirectory,base,fn) else: fn = g.os_path_finalize(fn) ok = g.os_path_exists(fn) return ok,fn
def git_dump_f(event): c = event['c'] hl = [] def dump_nodes(): for p in c.all_unique_positions(): #name, date, num = p.v.fileIndex fname = contfile(c,p) #gnx = '%s%s%s' % (name, date, num) gnx = p.gnx hl.append('<a href="%s">%s%s</a><br/>' % (gnx, '-' * p.level(), p.h)) fname = gnx codecs.open(fname,'w', encoding='utf-8').write(p.b) print("wrote",fname) flatroot = g.os_path_finalize('~/.leo/dump') if not os.path.isdir(flatroot): g.es("Initializing git repo at " + flatroot) os.makedirs(flatroot) os.chdir(flatroot) os.system('git init') assert os.path.isdir(flatroot) comment = g.app.gui.runAskOkCancelStringDialog(c,"Checkin comment","Comment") if not comment: comment = "Leo dump" wb = c.config.getString(setting='default_leo_file') wb = g.os_path_finalize(wb) shutil.copy2(wb, flatroot) os.chdir(flatroot) dump_nodes() lis = "\n".join(hl) html = "<body>\n<tt>\n" + lis + "\n</tt></body>" #titlename = c.frame.getTitle() + '.html' pth, bname = os.path.split(c.mFileName) if pth and bname: dbdirname = bname + "_" + hashlib.md5(c.mFileName).hexdigest() titlename = dbdirname + '.html' codecs.open(titlename,'w', encoding='utf-8').write(html) g.es("committing to " + flatroot) os.system('git add *') out = os.popen('git commit -m "%s"' % comment).read() g.es("committed") g.es(out) g.es('Outline in ' + os.path.abspath(titlename))
def git_dump_f(event): c = event['c'] hl = [] def dump_nodes(): for p in c.all_unique_positions(): #name, date, num = p.v.fileIndex fname = contfile(c, p) #gnx = '%s%s%s' % (name, date, num) gnx = p.gnx hl.append('<a href="%s">%s%s</a><br/>' % (gnx, '-' * p.level(), p.h)) fname = gnx codecs.open(fname, 'w', encoding='utf-8').write(p.b) print("wrote", fname) flatroot = g.os_path_finalize('~/.leo/dump') if not os.path.isdir(flatroot): g.es("Initializing git repo at " + flatroot) os.makedirs(flatroot) os.chdir(flatroot) os.system('git init') assert os.path.isdir(flatroot) comment = g.app.gui.runAskOkCancelStringDialog(c, "Checkin comment", "Comment") if not comment: comment = "Leo dump" wb = c.config.getString(setting='default_leo_file') wb = g.os_path_finalize(wb) shutil.copy2(wb, flatroot) os.chdir(flatroot) dump_nodes() lis = "\n".join(hl) html = "<body>\n<tt>\n" + lis + "\n</tt></body>" #titlename = c.frame.getTitle() + '.html' pth, bname = os.path.split(c.mFileName) if pth and bname: dbdirname = bname + "_" + hashlib.md5(c.mFileName).hexdigest() titlename = dbdirname + '.html' codecs.open(titlename, 'w', encoding='utf-8').write(html) g.es("committing to " + flatroot) os.system('git add *') out = os.popen('git commit -m "%s"' % comment).read() g.es("committed") g.es(out) g.es('Outline in ' + os.path.abspath(titlename))
def baseDirName(self): c = self.c filename = c.fileName() if filename: return g.os_path_dirname(g.os_path_finalize(filename)) # 1341 self.error('Can not compute shadow path: .leo file has not been saved') return None
def make_at_file_node(line, path): ''' Make and populate an @auto node for the given path. ''' c = g.app.log.c if not c: return None path = g.os_path_finalize(path).replace('\\','/') if not g.os_path_exists(path): g.trace('Not found:', repr(path)) return None # Create the new node. p = c.lastTopLevel().insertAfter() # Like c.looksLikeDerivedFile, but retaining the contents. with open(path, 'r') as f: file_s = f.read() is_derived = file_s.find('@+leo-ver=') > -1 if is_derived: # Set p.v.gnx from the derived file. is_derived = get_gnx_from_file(file_s, p, path) kind = '@file' if is_derived else '@auto' p.h = '%s %s' % (kind, path) c.selectPosition(p) c.refreshFromDisk() return p
def show_line(line, fn): """ Put the cursor on the requested line of the given file. fn should be a full path to a file. """ c = g.app.log.c target = g.os_path_finalize(fn).replace('\\', '/') if not g.os_path_exists(fn): g.trace('===== Does not exist', fn) return for p in c.all_positions(): if p.isAnyAtFileNode(): path = g.fullPath(c, p).replace('\\', '/') if target == path: # Select the line. junk_p, junk_offset, ok = c.gotoCommands.find_file_line(n=line, p=p) if not ok: g.trace('FAIL:', target) c.bodyWantsFocusNow() return p = make_at_file_node(line, target) junk_p, junk_offset, ok = c.gotoCommands.find_file_line(n=line, p=p) if not ok: g.trace('FAIL:', target)
def make_at_file_node(line, path): ''' Make and populate an @auto node for the given path. ''' c = g.app.log.c if not c: return path = g.os_path_finalize(path).replace('\\','/') if not g.os_path_exists(path): g.trace('Not found:', repr(path)) return # Create the new node. p = c.lastTopLevel().insertAfter() # Like c.looksLikeDerivedFile, but retaining the contents. with open(path, 'r') as f: file_s = f.read() is_derived = file_s.find('@+leo-ver=') > -1 if is_derived: # Set p.v.gnx from the derived file. is_derived = get_gnx_from_file(file_s, p, path) kind = '@file' if is_derived else '@auto' p.h = '%s %s' % (kind, path) c.selectPosition(p) c.refreshFromDisk() return p
def command_helper(self, event, kind, preview, verbose): def predicate(p): return self.filename(p) # Find all roots. t1 = time.time() c = self.c self.kind = kind p = event.p if event and hasattr(event, 'p') else c.p roots = g.findRootsWithPredicate(c, p, predicate=predicate) if not roots: g.warning('No @adoc nodes in', p.h) return [] # Write each root to a file. i_paths = [] for p in roots: try: i_path = self.filename(p) # #1398. i_path = c.expand_path_expression(i_path) i_path = g.os_path_finalize(i_path) with open(i_path, 'w', encoding='utf-8', errors='replace') as self.output_file: self.write_root(p) i_paths.append(i_path) except IOError: g.es_print(f"Can not open {i_path!r}") except Exception: g.es_print(f"Unexpected exception opening {i_path!r}") g.es_exception() # Convert each file to html. o_paths = [] for i_path in i_paths: o_path = self.compute_opath(i_path) o_paths.append(o_path) if kind == 'adoc': self.run_asciidoctor(i_path, o_path) elif kind == 'pandoc': self.run_pandoc(i_path, o_path) elif kind == 'sphinx': self.run_sphinx(i_path, o_path) else: g.trace('BAD KIND') return None if kind != 'sphinx': print(f"{kind}: wrote {o_path}") if preview: if kind == 'sphinx': g.es_print('preview not available for sphinx') else: # open .html files in the default browser. g.execute_shell_commands(o_paths) t2 = time.time() if verbose: n = len(i_paths) g.es_print(f"{kind}: wrote {n} file{g.plural(n)} " f"in {(t2-t1):4.2f} sec.") return i_paths
def run_sphinx(self, i_path, o_path): """Process i_path and o_path with sphinx.""" trace = True # cd to the command directory, or i_path's directory. command_dir = g.os_path_finalize(self.sphinx_command_dir or os.path.dirname(i_path)) if os.path.exists(command_dir): if trace: g.trace(f"\nos.chdir: {command_dir!r}") os.chdir(command_dir) else: g.error(f"command directory not found: {command_dir!r}") return # # If a default command exists, just call it. # The user is responsible for making everything work. if self.sphinx_default_command: if trace: g.trace(f"\ncommand: {self.sphinx_default_command!r}\n") g.execute_shell_commands(self.sphinx_default_command) return # Compute the input directory. input_dir = g.os_path_finalize(self.sphinx_input_dir or os.path.dirname(i_path)) if not os.path.exists(input_dir): g.error(f"input directory not found: {input_dir!r}") return # Compute the output directory. output_dir = g.os_path_finalize(self.sphinx_output_dir or os.path.dirname(o_path)) if not os.path.exists(output_dir): g.error(f"output directory not found: {output_dir!r}") return # # Call sphinx-build to write the output file. # sphinx-build [OPTIONS] SOURCEDIR OUTPUTDIR [FILENAMES...] command = f"sphinx-build {input_dir} {output_dir} {i_path}" if trace: g.trace(f"\ncommand: {command!r}\n") g.execute_shell_commands(command)
def get_home(): """Returns the user's home directory.""" home = g.os_path_expanduser("~") # Windows searches the HOME, HOMEPATH and HOMEDRIVE # environment vars, then gives up. if home and len(home) > 1 and home[0] == '%' and home[-1] == '%': # Get the indirect reference to the true home. home = os.getenv(home[1:-1], default=None) if home: # Important: This returns the _working_ directory if home is None! # This was the source of the 4.3 .leoID.txt problems. home = g.os_path_finalize(home) if (not g.os_path_exists(home) or not g.os_path_isdir(home)): home = None return home
def get_home(): """Returns the user's home directory.""" home = g.os_path_expanduser("~") # Windows searches the HOME, HOMEPATH and HOMEDRIVE # environment vars, then gives up. if home and len(home) > 1 and home[0] == '%' and home[-1] == '%': # Get the indirect reference to the true home. home = os.getenv(home[1: -1], default=None) if home: # Important: This returns the _working_ directory if home is None! # This was the source of the 4.3 .leoID.txt problems. home = g.os_path_finalize(home) if ( not g.os_path_exists(home) or not g.os_path_isdir(home) ): home = None return home
def createDirectoryForFile(self, fn): """ Create the directory for fn if a) it doesn't exist and b) the user options allow it. Return True if the directory existed or was made. """ c, ok = self.c, False # 1815. # Create the directory if it doesn't exist. theDir, junk = g.os_path_split(fn) theDir = g.os_path_finalize(theDir) # 1341 if g.os_path_exists(theDir): return True if c and c.config and c.config.create_nonexistent_directories: theDir = c.expand_path_expression(theDir) ok = g.makeAllNonExistentDirectories(theDir) if not ok: g.error('did not create:', theDir) return ok
def show_line(line, fn): ''' Put the cursor on the requested line of the given file. fn should be a full path to a file. ''' c = g.app.log.c target = g.os_path_finalize(fn).replace('\\','/') if not g.os_path_exists(fn): g.trace('===== Does not exist', fn) return for p in c.all_positions(): if p.isAnyAtFileNode(): path = g.fullPath(c, p).replace('\\','/') if target == path: # Select the line. junk_p, junk_offset, ok = c.gotoCommands.find_file_line(n=line, p=p) if not ok: g.trace('FAIL:', target) c.bodyWantsFocusNow() return p = make_at_file_node(line, target) junk_p, junk_offset, ok = c.gotoCommands.find_file_line(n=line, p=p) if not ok: g.trace('FAIL:', target)
def findDebugger(self): """Find the winpdb debugger.""" c = self.c pythonDir = g.os_path_dirname(sys.executable) debugger_path = c.expand_path_expression( c.config.getString('debugger-path')) debuggers = ( # #1431: only expand path expression in @string debugger-path. debugger_path or '@string debugger-path', g.os_path_join(pythonDir, 'Lib', 'site-packages', 'winpdb.py'), # winpdb 1.1.2 or newer. g.os_path_join(pythonDir, 'scripts', '_winpdb.py'), # Older version. ) for debugger in debuggers: if debugger: debugger = g.os_path_finalize(debugger) if g.os_path_exists(debugger): return debugger # g.es_print('debugger does not exist:', debugger) g.es_print('winpdb not found in...') for z in debuggers: print(z) return None
def report(self, name, p): """Issue a report to the log pane.""" if self.silent: return name = g.os_path_finalize(name) # 1341 g.pr(f"wrote: {name}")