def message (self, msg): ly.warning (msg) p = self while p: ly.progress (' In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items ()]))) p = p.get_parent ()
def message(self, msg): ly.warning(msg) p = self while p: ly.progress(' In: <%s %s>\n' % (p._name, ' '.join( ['%s=%s' % item for item in p._attribute_dict.items()]))) p = p.get_parent()
def do_conversion (str, from_version, to_version): """Apply conversions from FROM_VERSION to TO_VERSION. Return tuple (LAST,LASTCHANGED,STR,ERRORS), with the last applied conversion, the last conversion resulting in a change, the resulting string and the number of errors.""" conv_list = get_conversions (from_version, to_version) ly.progress (_ ("Applying conversion: "), newline = False) last_conversion = None last_change = None errors = 0 try: for x in conv_list: if x != conv_list[-1]: ly.progress (tup_to_str (x[0]), newline = False) ly.progress (', ', newline = False) else: ly.progress (tup_to_str (x[0])) newstr = x[1] (str) last_conversion = x[0] if (newstr != str): last_change = last_conversion str = newstr except convertrules.FatalConversionError: ly.error (_ ("Error while converting") + '\n' + _ ("Stopping at last successful rule")) errors += 1 return (last_conversion, last_change, str, errors)
def do_conversion (str, from_version, to_version): """Apply conversions from FROM_VERSION to TO_VERSION. Return tuple (LAST,STR), with the last successful conversion and the resulting string.""" conv_list = get_conversions (from_version, to_version) ly.progress (_ ("Applying conversion: "), newline = False) last_conversion = () try: if not conv_list: last_conversion = to_version for x in conv_list: if x != conv_list[-1]: ly.progress (tup_to_str (x[0]), newline = False) ly.progress (', ', newline = False) else: ly.progress (tup_to_str (x[0])) str = x[1] (str) last_conversion = x[0] except convertrules.FatalConversionError: ly.error (_ ("Error while converting") + '\n' + _ ("Stopping at last successful rule")) return (last_conversion, str)
def do_conversion(s, from_version, to_version): """Apply conversions from FROM_VERSION to TO_VERSION. Return tuple (LAST,LASTCHANGED,STR,ERRORS), with the last applied conversion, the last conversion resulting in a change, the resulting string and the number of errors.""" conv_list = get_conversions(from_version, to_version) ly.progress(_("Applying conversion: "), newline=False) last_conversion = None last_change = None errors = 0 try: for x in conv_list: if x != conv_list[-1]: ly.progress(tup_to_str(x[0]), newline=False) ly.progress(', ', newline=False) else: ly.progress(tup_to_str(x[0])) newstr = x[1](s) last_conversion = x[0] if newstr != s: last_change = last_conversion s = newstr except convertrules.FatalConversionError: ly.error( _("Error while converting") + '\n' + _("Stopping at last successful rule")) errors += 1 return (last_conversion, last_change, s, errors)
def do_conversion (str, from_version, to_version): """Apply conversions from FROM_VERSION to TO_VERSION. Return tuple (LAST,STR), with the last successful conversion and the resulting string.""" conv_list = get_conversions (from_version, to_version) ly.progress (_ ("Applying conversion: "), newline = False) last_conversion = None errors = 0 try: for x in conv_list: if x != conv_list[-1]: ly.progress (tup_to_str (x[0]), newline = False) ly.progress (', ', newline = False) else: ly.progress (tup_to_str (x[0])) str = x[1] (str) last_conversion = x[0] except convertrules.FatalConversionError: ly.error (_ ("Error while converting") + '\n' + _ ("Stopping at last successful rule")) errors += 1 return (last_conversion, str, errors)
def convert_from_musicxml(self): name = self.filename xml2ly_option_list = [] for (key, value) in list(self.option_dict.items()): cmd_key = self.musicxml_options_dict.get(key, None) if cmd_key is None: continue if value is None: xml2ly_option_list.append(cmd_key) else: xml2ly_option_list.append(cmd_key + '=' + value) if ('.mxl' in name) and ('--compressed' not in xml2ly_option_list): xml2ly_option_list.append('--compressed') self.compressed = True opts = " ".join(xml2ly_option_list) ly.progress(_("Converting MusicXML file `%s'...") % self.filename) cmd = 'musicxml2ly %s --out=- - ' % opts ly_code = self.filter_pipe(self.get_contents(), cmd).decode('utf-8') return ly_code
def system_in_directory(cmd_str, directory, log_file): """Execute a command in a different directory.""" if global_options.redirect_output: ly.progress(_("Processing %s.ly") % log_file) else: if ly.is_verbose(): ly.progress(_("Invoking `%s\'") % cmd_str) else: name = command_name(cmd_str) ly.progress(_("Running %s...") % name) output_location = None if global_options.redirect_output: output_location = open(log_file + '.log', 'w') try: subprocess.run(cmd_str, stdout=output_location, stderr=output_location, cwd=directory, shell=True, check=True) except subprocess.CalledProcessError as e: sys.stderr.write("%s\n" % e) sys.exit(1)
def main(): files = do_options() # should parse files[] to read \version? if global_options.show_rules: show_rules(sys.stdout, global_options.from_version, global_options.to_version) sys.exit(0) identify() for f in files: if f == "-": f = "" elif not os.path.isfile(f): ly.error(_("%s: Unable to open file") % f) if len(files) == 1: sys.exit(1) continue try: do_one_file(f) except UnknownVersion: ly.error(_("%s: Unable to determine version. Skipping") % f) except InvalidVersion: # Compat code for 2.x and 3.0 syntax ("except .. as v" doesn't # work in python 2.4!): t, v, b = sys.exc_info() ly.error( _( "%s: Invalid version string `%s' \n" "Valid version strings consist of three numbers, " "separated by dots, e.g. `2.8.12'" ) % (f, v.version) ) ly.progress("\n")
def do_one_file (infile_name): ly.progress (_ (u"Processing `%s\'... ") % infile_name, True) if infile_name: infile = open (infile_name, 'r') input = infile.read () infile.close () else: input = sys.stdin.read () from_version = None to_version = None if global_options.from_version: from_version = global_options.from_version else: guess = guess_lilypond_version (input) if not guess: raise UnknownVersion () from_version = str_to_tuple (guess) if global_options.to_version: to_version = global_options.to_version else: to_version = latest_version () if len (from_version) != 3: raise InvalidVersion (".".join ([str(n) for n in from_version])) (last, last_change, result, errors) = \ do_conversion (input, from_version, to_version) if global_options.force_current_version and \ (last is None or last == to_version): last = str_to_tuple (program_version) if last: if global_options.diff_version_update: # Note that last_change can be set even if the result is # the same if two conversion rules cancelled out if result == input: # check the y in x.y.z (minor version number) previous_stable = (last[0], 2*(last[1]/2), 0) if ((last[0:2] != from_version[0:2]) and (previous_stable > from_version)): # previous stable version last = previous_stable else: # make no (actual) change to the version number last = from_version else: last = last_change newversion = r'\version "%s"' % tup_to_str (last) if lilypond_version_re.search (result): result = re.sub (lilypond_version_re_str, '\\' + newversion, result) elif not global_options.skip_version_add: result = newversion + '\n' + result ly.progress ('\n') if global_options.edit: backup = back_up (infile_name, global_options.backup_numbered) outfile = open (infile_name, 'w') else: outfile = sys.stdout outfile.write (result) sys.stderr.flush () return errors
def get_latex_textwidth(source, global_options): # default value textwidth = 550.0 m = re.search(r'''(?P<preamble>\\begin\s*{document})''', source) if m is None: ly.warning(_("cannot find \\begin{document} in LaTeX document")) return textwidth preamble = source[:m.start(0)] latex_document = LATEX_INSPECTION_DOCUMENT % {'preamble': preamble} (handle, tmpfile) = tempfile.mkstemp('.tex') tmpfileroot = os.path.splitext(tmpfile)[0] tmpfileroot = os.path.split(tmpfileroot)[1] auxfile = tmpfileroot + '.aux' logfile = tmpfileroot + '.log' tmp_handle = os.fdopen(handle, 'w') tmp_handle.write(latex_document) tmp_handle.close() ly.progress( _("Running `%s' on file `%s' to detect default page settings.\n") % (global_options.latex_program, tmpfile)) cmd = '%s %s' % (global_options.latex_program, tmpfile) ly.debug_output("Executing: %s\n" % cmd) run_env = os.environ.copy() run_env['LC_ALL'] = 'C' run_env['TEXINPUTS'] = os.path.pathsep.join( (global_options.input_dir, run_env.get('TEXINPUTS', ''))) # unknown why this is necessary universal_newlines = True if sys.platform == 'mingw32': universal_newlines = False # use os.system to avoid weird sleep() problems on # GUB's python 2.4.2 on mingw # make file to write to output_dir = tempfile.mkdtemp() output_filename = os.path.join(output_dir, 'output.txt') # call command cmd += " > %s" % output_filename oldtexinputs = os.environ.get('TEXINPUTS') os.environ['TEXINPUTS'] = run_env['TEXINPUTS'] returncode = os.system(cmd) if oldtexinputs: os.environ['TEXINPUTS'] = oldtexinputs else: del os.environ['TEXINPUTS'] parameter_string = open(output_filename, encoding="utf8").read() if returncode != 0: ly.warning(_("Unable to auto-detect default settings:\n")) # clean up os.remove(output_filename) os.rmdir(output_dir) else: proc = subprocess.Popen(cmd, env=run_env, universal_newlines=universal_newlines, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (parameter_string, error_string) = proc.communicate() if proc.returncode != 0: ly.warning( _("Unable to auto-detect default settings:\n%s") % error_string) os.unlink(tmpfile) if os.path.exists(auxfile): os.unlink(auxfile) if os.path.exists(logfile): parameter_string = open(logfile, encoding="utf8").read() os.unlink(logfile) columns = 0 m = re.search('columns=([0-9.]+)', parameter_string) if m: columns = int(m.group(1)) columnsep = 0 m = re.search('columnsep=([0-9.]+)pt', parameter_string) if m: columnsep = float(m.group(1)) m = re.search('textwidth=([0-9.]+)pt', parameter_string) if m: textwidth = float(m.group(1)) else: ly.warning(_("cannot detect textwidth from LaTeX")) return textwidth ly.debug_output('Detected values:') ly.debug_output(' columns = %s' % columns) ly.debug_output(' columnsep = %s' % columnsep) ly.debug_output(' textwidth = %s' % textwidth) if m and columns: textwidth = (textwidth - columnsep) / columns ly.debug_output('Adjusted value:') ly.debug_output(' textwidth = %s' % textwidth) return textwidth
def identify(): ly.progress('%s (GNU LilyPond) %s\n' % (ly.program_name, program_version))
def do_one_file(infile_name): ly.progress(_("Processing `%s\'... ") % infile_name, True) if infile_name: infile = open(infile_name, 'rb') original = infile.read() infile.close() # Cope early with encoding change in 2.5.13: Try UTF-8 and attempt # conversion from latin1 if that fails. try: input = original.decode('utf-8') except UnicodeError: ly.progress(_("Attempting conversion from `latin1'...")) input = original.decode('latin1') else: input = sys.stdin.read() to_version = None org_version = None guess = guess_lilypond_version(input) org_version = guess and str_to_tuple(guess) from_version = global_options.from_version or org_version if not from_version: raise UnknownVersion() if global_options.to_version: to_version = global_options.to_version else: to_version = latest_version() if len(from_version) != 3: raise InvalidVersion(".".join([str(n) for n in from_version])) (last, last_change, result, errors) = \ do_conversion(input, from_version, to_version) if global_options.force_current_version and \ (last is None or last == to_version): last = str_to_tuple(program_version) if last: if global_options.diff_version_update: # Note that last_change can be set even if the result is # the same if two conversion rules cancelled out if result == input: # make no (actual) change to the version number last = org_version or from_version else: last = last_change # If the last update was to an unstable version # number, and the final update target is no longer in # the same unstable series, we update to the stable # series following the unstable version. if last[1] % 2: # unstable next_stable = (last[0], last[1] + 1, 0) if next_stable <= to_version: last = next_stable newversion = r'\version "%s"' % tup_to_str(last) if lilypond_version_re.search(result): result = re.sub(lilypond_version_re_str, '\\' + newversion, result) elif not global_options.skip_version_add: result = newversion + '\n' + result ly.progress('\n') if global_options.edit: backup = back_up(infile_name, global_options.backup_numbered) outfile = open(infile_name, 'w', encoding='utf8') else: outfile = sys.stdout outfile.write(result) sys.stderr.flush() return errors
def do_one_file(infile_name): ly.progress(_(u"Processing `%s'... ") % infile_name, True) if infile_name: infile = open(infile_name, "r") input = infile.read() infile.close() else: input = sys.stdin.read() to_version = None org_version = None guess = guess_lilypond_version(input) org_version = guess and str_to_tuple(guess) from_version = global_options.from_version or org_version if not from_version: raise UnknownVersion() if global_options.to_version: to_version = global_options.to_version else: to_version = latest_version() if len(from_version) != 3: raise InvalidVersion(".".join([str(n) for n in from_version])) (last, last_change, result, errors) = do_conversion(input, from_version, to_version) if global_options.force_current_version and (last is None or last == to_version): last = str_to_tuple(program_version) if last: if global_options.diff_version_update: # Note that last_change can be set even if the result is # the same if two conversion rules cancelled out if result == input: # make no (actual) change to the version number last = org_version or from_version else: last = last_change # If the last update was to an unstable version # number, and the final update target is no longer in # the same unstable series, we update to the stable # series following the unstable version. if last[1] % 2: # unstable next_stable = (last[0], last[1] + 1, 0) if next_stable <= to_version: last = next_stable newversion = r'\version "%s"' % tup_to_str(last) if lilypond_version_re.search(result): result = re.sub(lilypond_version_re_str, "\\" + newversion, result) elif not global_options.skip_version_add: result = newversion + "\n" + result ly.progress("\n") if global_options.edit: backup = back_up(infile_name, global_options.backup_numbered) outfile = open(infile_name, "w") else: outfile = sys.stdout outfile.write(result) sys.stderr.flush() return errors
def convert_midi(in_file, out_file): global midi import midi global clocks_per_1, clocks_per_4, key global start_quant_clocks global duration_quant_clocks global allowed_tuplet_clocks global time full_content = open(in_file, 'rb').read() clocks_max = bar_max * clocks_per_1 * 2 midi_dump = midi.parse(full_content, clocks_max) clocks_per_1 = midi_dump[0][1] clocks_per_4 = clocks_per_1 / 4 time = Time(4, 4) if global_options.start_quant: start_quant_clocks = clocks_per_1 / global_options.start_quant if global_options.duration_quant: duration_quant_clocks = clocks_per_1 / global_options.duration_quant allowed_tuplet_clocks = [] for (dur, num, den) in global_options.allowed_tuplets: allowed_tuplet_clocks.append(clocks_per_1 / dur * num / den) if global_options.verbose: print('allowed tuplet clocks:', allowed_tuplet_clocks) tracks = [create_track(t) for t in midi_dump[1]] # urg, parse all global track events, such as Key first # this fixes key in different voice/staff problem for t in tracks: t.music = t.parse() prev = None staves = [] for t in tracks: voices = t.get_voices() if ((t.name and prev and prev.name) and t.name.split(':')[0] == prev.name.split(':')[0]): # staves[-1].voices += voices # all global track events first staves[-1].voices = ([staves[-1].voices[0]] + [voices[0]] + staves[-1].voices[1:] + voices[1:]) else: staves.append(Staff(t)) prev = t tag = '%% Lily was here -- automatically converted by %s from %s' % ( ly.program_name, in_file) s = tag s += r''' \version "2.14.0" ''' s += r''' \layout { \context { \Voice \remove "Note_heads_engraver" \consists "Completion_heads_engraver" \remove "Rest_engraver" \consists "Completion_rest_engraver" } } ''' for i in global_options.include_header: s += '\n%% included from %(i)s\n' % locals() s += open(i, encoding='utf8').read() if s[-1] != '\n': s += '\n' s += '% end\n' for i, t in enumerate(staves): s += t.dump(i) s += '\n\\score {\n <<\n' control_track = False i = 0 output_track_count = 0 for i, staff in enumerate(staves): track_name = get_track_name(i) item = track_first_item(staff.voices) staff_name = track_name context = None if not i and not item and len(staves) > 1: control_track = track_name continue elif (item and item.__class__ == Note): context = 'Staff' if control_track: s += ' \\context %(context)s=%(staff_name)s \\%(control_track)s\n' % locals() elif item and item.__class__ == Text: context = 'Lyrics' if context: output_track_count += 1 s += ' \\context %(context)s=%(staff_name)s \\%(track_name)s\n' % locals() # If we found a control track but no other tracks with which # to combine it, create a Staff for the control track alone. if (output_track_count == 0) and control_track: s += ' \\context Staff \\%(control_track)s\n' % locals() s = s + r''' >> \layout {} \midi {} } ''' if not global_options.quiet: ly.progress(_("%s output to `%s'...") % ('LY', out_file)) if out_file == '-': handle = sys.stdout else: handle = open(out_file, 'w', encoding='utf8') handle.write(s) handle.close()
def do_one_file(infile_name): ly.progress(_("Processing `%s'... ") % infile_name, True) if infile_name: infile = open(infile_name, "r") input = infile.read() infile.close() else: input = sys.stdin.read() from_version = None to_version = None if global_options.from_version: from_version = global_options.from_version else: guess = guess_lilypond_version(input) if not guess: raise UnknownVersion() from_version = str_to_tuple(guess) if global_options.to_version: to_version = global_options.to_version else: to_version = latest_version() if len(from_version) != 3: raise InvalidVersion(".".join([str(n) for n in from_version])) (last, result) = do_conversion(input, from_version, to_version) if last: if global_options.force_current_version and last == to_version: last = str_to_tuple(program_version) if global_options.diff_version_update: if result == input: # check the y in x.y.z (minor version number) previous_stable = (last[0], 2 * (last[1] / 2), 0) if (last[0:2] != from_version[0:2]) and (previous_stable > from_version): # previous stable version last = previous_stable else: # make no (actual) change to the version number last = from_version newversion = r'\version "%s"' % tup_to_str(last) if lilypond_version_re.search(result): result = re.sub(lilypond_version_re_str, "\\" + newversion, result) elif not global_options.skip_version_add: result = newversion + "\n" + result ly.progress("\n") if global_options.edit: try: os.remove(infile_name + "~") except: pass os.rename(infile_name, infile_name + "~") outfile = open(infile_name, "w") else: outfile = sys.stdout outfile.write(result) sys.stderr.flush()
def get_texinfo_width_indent(source, global_options): #TODO: Check for end of header command "@c %**end of header" # only use material before that comment ? # extract all relevant papter settings from the input: pagesize = None texinfo_paper_size_regexp = r'''(@(?:afourpaper|afourwide|afourlatex|afivepaper|smallbook|letterpaper))''' m = re.search(texinfo_paper_size_regexp, source) if m: pagesize = m.group(1) relevant_settings_regexp = r'''(@(?:fonttextsize|pagesizes|cropmarks|exampleindent).*)\n''' m = re.findall(relevant_settings_regexp, source) if pagesize: m.insert(0, pagesize) # all relevant options to insert into the test document: preamble = "\n".join(m) texinfo_document = TEXINFO_INSPECTION_DOCUMENT % {'preamble': preamble} (handle, tmpfile) = tempfile.mkstemp('.texi') outfile = os.path.splitext(tmpfile)[0] + '.pdf' tmp_handle = os.fdopen(handle, 'w') tmp_handle.write(texinfo_document) tmp_handle.close() # Work around a texi2pdf bug: if LANG=C is not given, a broken regexp is # used to detect relative/absolute paths, so the absolute path is not # detected as such and this command fails: ly.progress( _("Running texi2pdf on file %s to detect default page settings.\n") % tmpfile) # execute the command and pipe stdout to the parameter_string: cmd = '%s --batch -c -o %s %s' % (global_options.texinfo_program, outfile, tmpfile) ly.debug_output("Executing: %s\n" % cmd) run_env = os.environ.copy() run_env['LC_ALL'] = 'C' ### unknown why this is necessary universal_newlines = True if sys.platform == 'mingw32': universal_newlines = False ### use os.system to avoid weird sleep() problems on ### GUB's python 2.4.2 on mingw # make file to write to output_dir = tempfile.mkdtemp() output_filename = os.path.join(output_dir, 'output.txt') # call command cmd += " > %s" % output_filename returncode = os.system(cmd) parameter_string = open(output_filename).read() if returncode != 0: ly.warning(_("Unable to auto-detect default settings:\n")) # clean up os.remove(output_filename) os.rmdir(output_dir) else: proc = subprocess.Popen(cmd, env=run_env, universal_newlines=universal_newlines, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (parameter_string, error_string) = proc.communicate() if proc.returncode != 0: ly.warning( _("Unable to auto-detect default settings:\n%s") % error_string) os.unlink(tmpfile) if os.path.exists(outfile): os.unlink(outfile) # Find textwidth and exampleindent and format it as \\mm or \\in # Use defaults if they cannot be extracted textwidth = 0 m = re.search('textwidth=([0-9.]+)pt', parameter_string) if m: val = float(m.group(1)) / 72.27 if pagesize and pagesize.startswith("@afour"): textwidth = "%g\\mm" % round(val * 25.4, 3) else: textwidth = "%g\\in" % round(val, 3) else: textwidth = texinfo_line_widths.get(pagesize, "6\\in") exampleindent = 0 m = re.search('exampleindent=([0-9.]+)pt', parameter_string) if m: val = float(m.group(1)) / 72.27 if pagesize and pagesize.startswith("@afour"): exampleindent = "%g\\mm" % round(val * 25.4, 3) else: exampleindent = "%g\\in" % round(val, 3) else: exampleindent = "0.4\\in" retval = { book_snippets.LINE_WIDTH: textwidth, book_snippets.EXAMPLEINDENT: exampleindent } ly.debug_output("Auto-detected values are: %s\n" % retval) return retval
def identify (): ly.progress ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
def do_one_file (infile_name): ly.progress (_ (u"Processing `%s\'... ") % infile_name, True) if infile_name: infile = open (infile_name, 'r') input = infile.read () infile.close () else: input = sys.stdin.read () from_version = None to_version = None if global_options.from_version: from_version = global_options.from_version else: guess = guess_lilypond_version (input) if not guess: raise UnknownVersion () from_version = str_to_tuple (guess) if global_options.to_version: to_version = global_options.to_version else: to_version = latest_version () if len (from_version) != 3: raise InvalidVersion (".".join ([str(n) for n in from_version])) (last, result, errors) = do_conversion (input, from_version, to_version) if global_options.force_current_version and \ (last is None or last == to_version): last = str_to_tuple (program_version) if last: if global_options.diff_version_update: if result == input: # check the y in x.y.z (minor version number) previous_stable = (last[0], 2*(last[1]/2), 0) if ((last[0:2] != from_version[0:2]) and (previous_stable > from_version)): # previous stable version last = previous_stable else: # make no (actual) change to the version number last = from_version newversion = r'\version "%s"' % tup_to_str (last) if lilypond_version_re.search (result): result = re.sub (lilypond_version_re_str, '\\' + newversion, result) elif not global_options.skip_version_add: result = newversion + '\n' + result ly.progress ('\n') if global_options.edit: try: os.remove (infile_name + '~') except: pass os.rename (infile_name, infile_name + '~') outfile = open (infile_name, 'w') else: outfile = sys.stdout outfile.write (result) sys.stderr.flush () return errors