]> git.donarmstrong.com Git - lilypond.git/commitdiff
Fix style of Python buildscripts
authorJohn Mandereau <john.mandereau@gmail.com>
Sat, 26 Apr 2008 21:10:30 +0000 (23:10 +0200)
committerJohn Mandereau <john.mandereau@gmail.com>
Sat, 26 Apr 2008 21:10:30 +0000 (23:10 +0200)
- always use 4 spaces for indentation,

- rewrite lilypond-words.py in better Python style,

- replace deprecated constructs, mainly string functions and
exceptions,

- translations-status.py: load gettext catalogs via langdefs,

- mutopia-index.py: replace hand-made construct with dict.get().

Documentation/GNUmakefile
buildscripts/bib2html.py
buildscripts/gen-emmentaler-scripts.py
buildscripts/lilypond-words.py
buildscripts/mf-to-table.py
buildscripts/musicxml_generate_intervals.py
buildscripts/musicxml_generate_keys.py
buildscripts/musicxml_generate_timesignatures.py
buildscripts/mutopia-index.py
buildscripts/readlink.py
buildscripts/translations-status.py

index 610e9130b25e964373ec5131cd3ccc904528e620..21358e930248cc0aeb29bde81ea42de6f5d264ca 100644 (file)
@@ -69,4 +69,4 @@ update-translation:
 
 translation-status:
        make -C po out=www messages
-       $(PYTHON) $(buildscript-dir)/translations-status.py $(buildscript-dir) po/out-www
+       $(PYTHON) $(buildscript-dir)/translations-status.py $(buildscript-dir)
index f01e9d0051fa17c62822163626937a18f371fd55..c16f21cce28c9b91512bf08cf6393172bb96036a 100644 (file)
@@ -3,18 +3,16 @@ import os
 import sys
 import getopt
 import tempfile
-import string
 
 # usage:
 def usage ():
-  print 'usage: %s [-s style] [-o <outfile>] BIBFILES...';
+    print 'usage: %s [-s style] [-o <outfile>] BIBFILES...'
 
-#print os.environ['BSTINPUTS']
-
-(options, files) = getopt.getopt(sys.argv[1:], 's:o:', [])
+(options, files) = getopt.getopt (sys.argv[1:], 's:o:', [])
 
 output = 'bib.html'
 style = 'long'
+
 for (o,a) in options:
     if o == '-h' or o == '--help':
         usage ()
@@ -24,17 +22,17 @@ for (o,a) in options:
     elif o == '-o' or o == '--output':
         output = a
     else:
-        raise 'unknown opt ', o
+        raise Exception ('unknown option: %s' % o)
 
 
 if style not in ['alpha','index','long','longp','long-pario','short','short-pario','split']:
-  sys.stderr.write ("Unknown style \`%s'\n" % style)
+    sys.stderr.write ("Unknown style \`%s'\n" % style)
 
 tempfile = tempfile.mktemp ('bib2html')
 
 if not files:
-  usage ()
-  sys.exit (2)
+   usage ()
+   sys.exit (2)
 
 
 def strip_extension (f, ext):
@@ -45,22 +43,22 @@ def strip_extension (f, ext):
 
 nf = []
 for f in files:
-  nf.append (strip_extension(f, '.bib'))
+    nf.append (strip_extension (f, '.bib'))
 
-files = string.join (nf,',')
+files = ','.join (nf)
 
-open(tempfile + '.aux', 'w').write (r'''
+open (tempfile + '.aux', 'w').write (r'''
 \relax 
 \citation{*}
 \bibstyle{html-%(style)s}
 \bibdata{%(files)s}''' % vars ()) 
 
-cmd = "bibtex %s" % tempfile;
+cmd = "bibtex %s" % tempfile
 
 sys.stdout.write ("Invoking `%s'\n" % cmd)
 stat = os.system (cmd)
 if stat <> 0:
-  sys.exit(1)
+    sys.exit(1)
 
 
 #TODO: do tex -> html on output 
@@ -71,18 +69,8 @@ open (output, 'w').write  (bbl)
 
 
 def cleanup (tempfile):
-  for a in ['aux','bbl', 'blg']:
-    os.unlink (tempfile + '.' + a)
-
-cleanup(tempfile)
-
-
-
-
-
-
-
-
-
+    for a in ['aux','bbl', 'blg']:
+        os.unlink (tempfile + '.' + a)
 
+cleanup (tempfile)
 
index 291fc76d7b0dbe1be4329e86d21ae5a3c5e35516..3da88408690ae385014094feec293c49a94b8dde 100644 (file)
@@ -3,7 +3,6 @@ import sys
 import getopt
 import re 
 import os
-import string
 
 (options, files) = \
  getopt.getopt (sys.argv[1:],
@@ -89,7 +88,7 @@ Generate("%(filename)s-%(design_size)d.svg");
     for s in subfonts:
         ns.append ('%s' % (s % vars()))
         
-    subfonts_str = string.join (ns)
+    subfonts_str = ' '.join (ns)
     
     open (os.path.join (outdir, '%(filename)s-%(design_size)d.subfonts' % vars()), 'w').write (subfonts_str)
 
index 46b616bf66701895216a9472762db546c4aed241..8819db394cbac4efd0ddcffeb0bca10af095e478 100755 (executable)
@@ -1,38 +1,27 @@
 #!@PYTHON@
 
-
-###
-# FIXME: coding standards!
-###
-
 # Created 01 September 2003 by Heikki Junes.
+# Rewritten by John Mandereau
+
 # Generates lilypond-words.el for (X)Emacs and lilypond-words[.vim] for Vim.
 
-import string
 import re
 import sys
+import getopt
 
-kw = []
-rw = []
-notes = []
+keywords = []
+reserved_words = []
+note_names = []
 
 # keywords not otherwise found
-for line in ['include','maininput','version']:
-  kw = kw + [line]
+keywords += ['include', 'maininput', 'version']
 
 # the main keywords
-F = open('lily/lily-lexer.cc', 'r')
-for line in F.readlines():
-  m = re.search(r"(\s*{\")(.*)(\",\s*.*},\s*\n)",line)
-  if m:
-    kw = kw + [m.group(2)]
-
-# keywords in markup
-F = open('scm/markup.scm', 'r')
-for line in F.readlines():
-  m = re.search(r"^(\s*\(cons\s*)([a-z-]*)(-markup)",line)
-  if m:
-    kw = kw + [m.group(2)]
+s = open ('lily/lily-lexer.cc', 'r').read ()
+keywords += [w for w in re.findall (r"\s*{\"(.+)\",\s*.*},\s*\n", s)]
+
+s = open ('scm/markup.scm', 'r').read ()
+keywords += [w for w in re.findall (r"(?m)^\s*\(cons\s*([a-z-]+)-markup", s)]
 
 # identifiers and keywords
 for name in ['ly/chord-modifiers-init.ly',
@@ -45,24 +34,11 @@ for name in ['ly/chord-modifiers-init.ly',
              'ly/property-init.ly',
              'ly/scale-definitions-init.ly',
              'ly/script-init.ly',
-             'ly/spanners-init.ly']:
-  F = open(name, 'r')
-  for line in F.readlines():
-    m = re.search(r"^([a-zA-Z]+)(\s*=)",line)
-    if m:
-      kw = kw + [m.group(1)]
-
-# more identifiers
-for name in ['ly/declarations-init.ly',
+             'ly/spanners-init.ly',
              'ly/declarations-init.ly',
-             'ly/params-init.ly',
-             ]:
-  F = open(name, 'r')
-  for line in F.readlines():
-    m = re.search(r"^(\s*)([a-zA-Z]+)(\s*=)",line)
-    if m:
-      kw = kw + [m.group(2)]
-  F.close()
+             'ly/params-init.ly']:
+    s = open (name, 'r').read ()
+    keywords += [w for w in re.findall (r"(?m)^\s*([a-zA-Z]+)\s*=", s)]
 
 # note names
 for name in ['ly/catalan.ly',
@@ -76,123 +52,97 @@ for name in ['ly/catalan.ly',
              'ly/portugues.ly',
              'ly/suomi.ly',
              'ly/svenska.ly',
-             'ly/vlaams.ly',
-             ]:
-  F = open(name, 'r')
-  for line in F.readlines():
-    m = re.search(r"^(\s*\()([a-z]+)([^l]+ly:make-pitch)",line)
-    if m:
-      notes = notes + ['' + m.group(2)]
-
+             'ly/vlaams.ly']:
+    s = open (name, 'r').read ()
+    note_names += [n for n in re.findall (r"(?m)^\s*\(([a-z]+)[^l]+ly:make-pitch", s)]
 
 # reserved words
 for name in ['ly/engraver-init.ly',
              'ly/performer-init.ly']:
-  f = open(name, 'r')
-  for line in f.readlines():
-      for pattern in [r"^(\s*.consists\s+\")([a-zA-Z_]+)(\")",
-                      r"([\\]name\s+[\"]?)([a-zA-Z_]+)([\"]?)",
-                      r"(\s+)([a-zA-Z_]+)(\s*[\\]((set)|(override)))"]:
-          m = re.search(pattern,line)
-          if m:
-              rw = rw + ['' + m.group(2)]
-
-# the output file
-outdir = '.';
-suffix = ['skip','skip','skip'];
-outs  = ['','',''];
-for s in sys.argv[1:]:
-  if s == '--words':
-    suffix[0] = '';
-  if s == '--el':
-    suffix[1] = '.el';
-  if s == '--vim':
-    suffix[2] = '.vim';
-  m = re.search(r"(--dir=)(\S*)",s)
-  if m:
-    outdir = m.group(2)
-
-if '' in suffix:
-  outs[0] = open(outdir+'/lilypond-words'+suffix[0], 'w')
-if '.el' in suffix:
-  outs[1] = open(outdir+'/lilypond-words'+suffix[1], 'w')
-if '.vim' in suffix:
-  outs[2] = open(outdir+'/lilypond-words'+suffix[2], 'w')
-
-# alphabetically ordered words
-kw.sort()
-kw.reverse()
-prevline = ''
-if '.vim' in suffix:
- outs[2].write('syn match lilyKeyword \"[-_^]\\?\\\\\\(');
-for line in kw:
-  if line != prevline:
-    if '' in suffix:
-        outs[0].write('\\\\' + line + '\n')
-    if '.el' in suffix:
-        outs[1].write('\\\\' + line + '\n')
-    if '.vim' in suffix:
-        outs[2].write(line + '\\|')
-  prevline = line
-if '.vim' in suffix:
-  outs[2].write('n\\)\\(\\A\\|\\n\\)\"me=e-1\n')
-
-rw.sort()
-rw.reverse()
-prevline = ''
-if '.vim' in suffix:
-  outs[2].write('syn match lilyReservedWord \"\\(\\A\\|\\n\\)\\(')
-for line in rw:
-  if line != prevline:
-    if '' in suffix:
-      outs[0].write(line + '\n')
-    if '.el' in suffix:
-      outs[1].write(line + '\n')
-    if '.vim' in suffix:
-        outs[2].write(line + '\\|')
-  prevline = line
-if '.vim' in suffix:
-  outs[2].write('Score\\)\\(\\A\\|\\n\\)\"ms=s+1,me=e-1\n')
-
-notes.sort()
-notes.reverse()
-prevline = ''
-if '.vim' in suffix:
-  outs[2].write('syn match lilyNote \"\\<\\(\\(\\(');
-for line in notes:
-  if line != prevline:
-    if '' in suffix:
-      outs[0].write(line + '\n')
-    if '.el' in suffix:
-      outs[1].write(line + '\n')
-    if '.vim' in suffix:
-        outs[2].write(line + '\\|')
-  prevline = line
-if '.vim' in suffix:
-  outs[2].write('a\\)\\([,\']\\)\\{,4}\\([?!]\\)\\?\\)\\|s\\|r\\)\\(\\(128\\|64\\|32\\|16\\|8\\|4\\|2\\|1\\|\\\\breve\\|\\\\longa\\|\\\\maxima\\)[.]\\{,8}\\)\\?\\(\\A\\|\\n\\)\"me=e-1\n')
-
-# the menu in lilypond-mode.el
-for line in ['/( - _ /) -',
-             '/[ - _ /] -',
-             '< - _ > -',
-             '<< - _ >> -',
-             '///( - _ ///) -',
-             '///[ - _ ///] -',
-             '///< - _ ///! -',
-             '///> - _ ///! -',
-             '//center - / << _ >> -',
-             '//column - / << _ >> -',
-             '//context/ Staff/ = - % { _ } -',
-             '//context/ Voice/ = - % { _ } -',
-             '//markup - { _ } -',
-             '//notes - { _ } -',
-             '//relative - % { _ } -',
-             '//score - { //n /? //simultaneous { //n _ //n } /! //n //paper {  } //n /? //midi {  } //n /! } //n -',
-             '//simultaneous - { _ } -',
-             '//sustainDown - _ //sustainUp -',
-             '//times - % { _ } -',
-             '//transpose - % { _ } -',
-             ]:
-  # urg. escape char '/' is replaced with '\\' which python writes as a '\'.
-  if '.el' in suffix:
-    outs[1].write(string.join(string.split(line,'/'),'\\') + '\n')
+    s = open (name, 'r').read ()
+    for pattern in [r"(?m)^\s*.consists\s+\"([a-zA-Z_]+)\"",
+                    r"[\\]name\s+[\"]?([a-zA-Z_]+)[\"]?",
+                    r"\s+([a-zA-Z_]+)\s*\\(?:set|override)"]:
+        reserved_words += [w for w in re.findall (pattern, s)]
+
+keywords = list (set (keywords)).sort ()
+keywords.reverse ()
+
+reserved_words = list (set (reserved_words)).sort ()
+reserved_words.reverse ()
+
+note_names = list (set (note_names)).sort ()
+note_names.reverse()
+
+
+# output
+outdir = ''
+out_words = False
+out_el = False
+out_vim = False
+
+options = getopt.getopt (sys.argv[1:],
+  '', ['words', 'el', 'vim', 'dir='])[0]
+
+for (o, a) in options:
+    if o == '--words':
+        out_words = True
+    elif o == '--el':
+        out_el = True
+    elif o == '--vim':
+        out_vim = True
+    elif o == '--dir':
+        outdir = a
+
+if out_words or out_el:
+    outstring = ''.join (['\\\\' + w + '\n' for w in keywords])
+    outstring += ''.join ([w + '\n' for w in reserved_words])
+    outstring += ''.join ([w + '\n' for w in note_names])
+
+if out_words:
+    f = open (os.path.join (outdir, 'lilypond-words'), 'w')
+    f.write (outstring)
+
+if out_el:
+    f = open (os.path.join (outdir, 'lilypond-words.el'), 'w')
+    f.write (outstring)
+
+    # the menu in lilypond-mode.el
+    # for easier typing of this list, replace '/' with '\' below
+    # when writing to file
+    elisp_menu = ['/( - _ /) -',
+                  '/[ - _ /] -',
+                  '< - _ > -',
+                  '<< - _ >> -',
+                  '///( - _ ///) -',
+                  '///[ - _ ///] -',
+                  '///< - _ ///! -',
+                  '///> - _ ///! -',
+                  '//center - / << _ >> -',
+                  '//column - / << _ >> -',
+                  '//context/ Staff/ = - % { _ } -',
+                  '//context/ Voice/ = - % { _ } -',
+                  '//markup - { _ } -',
+                  '//notes - { _ } -',
+                  '//relative - % { _ } -',
+                  '//score - { //n /? //simultaneous { //n _ //n } /! //n //paper {  } //n /? //midi {  } //n /! } //n -',
+                  '//simultaneous - { _ } -',
+                  '//sustainDown - _ //sustainUp -',
+                  '//times - % { _ } -',
+                  '//transpose - % { _ } -',
+                  '']
+    f.write ('\n'.join ([line.replace ('/', '\\') for line in elisp_menu]))
+
+if out_vim:
+    f = open (os.path.join (outdir, 'lilypond-words.vim'), 'w')
+    f.write ('syn match lilyKeyword \"[-_^]\\?\\\\\\(')
+    f.write (''.join ([w + '\\|' for w in keywords]))
+    f.write ('n\\)\\(\\A\\|\\n\\)\"me=e-1\n')
+
+    f.write ('syn match lilyReservedWord \"\\(\\A\\|\\n\\)\\(')
+    f.write (''.join ([w + '\\|' for w in reserved_words]))
+    f.write ('Score\\)\\(\\A\\|\\n\\)\"ms=s+1,me=e-1\n')
+
+    f.write ('syn match lilyNote \"\\<\\(\\(\\(')
+    f.write (''.join ([w + '\\|' for w in note_names]))
+    f.write ('a\\)\\([,\']\\)\\{,4}\\([?!]\\)\\?\\)\\|s\\|r\\)\\(\\(128\\|64\\|32\\|16\\|8\\|4\\|2\\|1\\|\\\\breve\\|\\\\longa\\|\\\\maxima\\)[.]\\{,8}\\)\\?\\(\\A\\|\\n\\)\"me=e-1\n')
index f6629328ce3c6ff712cb0b267b2ecdb401d79ae8..3a07516048a45aa919b01b58f3ed2a763efe9441 100644 (file)
@@ -9,7 +9,6 @@
 import os
 import sys
 import getopt
-import string
 import re
 import time
 
@@ -41,7 +40,7 @@ class Char_metric:
 font_family = 'feta'
 
 def parse_logfile (fn):
-    (autolines, deps) = read_log_file (fn)
+    autolines, deps = read_log_file (fn)
     charmetrics = []
     
     global_info = {
@@ -50,7 +49,7 @@ def parse_logfile (fn):
     group = ''
 
     for l in autolines:
-        tags = string.split (l, '@:')
+        tags = l.split ('@:')
         if tags[0] == 'group':
             group = tags[1]
         elif tags[0] == 'puorg':
@@ -63,13 +62,13 @@ def parse_logfile (fn):
             m = {
                 'description': tags[1],
                 'name': name,
-                'code': string.atoi (tags[2]),
-                'breapth': string.atof (tags[3]),
-                'width': string.atof (tags[4]),
-                'depth': string.atof (tags[5]),
-                'height': string.atof (tags[6]),
-                'wx': string.atof (tags[7]),
-                'wy': string.atof (tags[8]),
+                'code': int (tags[2]),
+                'breapth': float (tags[3]),
+                'width': float (tags[4]),
+                'depth': float (tags[5]),
+                'height': float (tags[6]),
+                'wx': float (tags[7]),
+                'wy': float (tags[8]),
             }
             charmetrics.append (m)
         elif tags[0] == 'font':
@@ -84,11 +83,10 @@ def parse_logfile (fn):
             encoding = re.sub (' ','-', tags[5])
             tags = tags[:-1]
             name = tags[1:]
-            global_info['design_size'] = string.atof (tags[4])
-            global_info['FontName'] = string.join (name, '-')
-            global_info['FullName'] = string.join (name,' ')
-            global_info['FamilyName'] = string.join (name[1:-1],
-                                '-')
+            global_info['design_size'] = float (tags[4])
+            global_info['FontName'] = '-'.join (name)
+            global_info['FullName'] = ' '.join (name)
+            global_info['FamilyName'] = '-'.join (name[1:-1])
             if 1:
                 global_info['Weight'] = tags[4]
             else: # testing
@@ -106,8 +104,6 @@ def parse_logfile (fn):
 
 
 
-
-
 def character_lisp_table (global_info, charmetrics):
 
     def conv_char_metric (charmetric):
index dbde2bcee762294afbe788dfa972190063d50973..3c00715d1470b65fd9b3f3d14a8e069ddee97dc4 100755 (executable)
@@ -55,4 +55,4 @@ for octave in (start_octave, start_octave+1):
 print """    </measure>
   </part>
 </score-partwise>
-"""
\ No newline at end of file
+"""
index acf4cf10a8bd7d4e93371d419157923de569db86..d82b168fa96175f2a2af1e3e874fe2805a09d1da 100755 (executable)
@@ -69,4 +69,4 @@ for fifth in range(-max_range, max_range+1):
 
 print """  </part>
 </score-partwise>
-"""
\ No newline at end of file
+"""
index 9844f3d0f68346b43563136a38f3e86839bf026f..20e34cbf84f00c0651eb51a844b738135ed83a28 100755 (executable)
@@ -93,4 +93,4 @@ measure += 1
 
 print """  </part>
 </score-partwise>
-"""
\ No newline at end of file
+"""
index 57a9a3f3d51383d84b7574b3b6aa1f3e96c19857..c0d4e1fd25cfd2a4e4dc1c7472f7c8ca00e7540b 100644 (file)
@@ -1,10 +1,9 @@
-#!@PYTHON@
+#!/usr/bin/env python
 # mutopia-index.py
 
 import fnmatch
 import getopt
 import os
-import os
 import re
 import stat
 import sys
@@ -25,7 +24,7 @@ headertext= r"""
 <h1>LilyPond samples</h1>
 
 
-<p>You're looking at a page with some LilyPond samples.  These files
+<p>You are looking at a page with some LilyPond samples.  These files
 are also included in the distribution. The output is completely
 generated from the source file, without any further touch up.
 
@@ -113,15 +112,9 @@ hr { border:0; height:1; color: #000000; background-color: #000000; }\n
         ext = ext2 + ext
         
         header = read_lilypond_header (ex)
-        def read_dict (s, default, h = header):
-                try:
-                    ret = h[s]
-                except KeyError:
-                    ret = default
-                return ret
-        head = read_dict ('title', os.path.basename (base))
-        composer = read_dict ('composer', '')
-        desc = read_dict ('description', '')
+        head = header.get ('title', os.path.basename (base))
+        composer = header.get ('composer', '')
+        desc = header.get ('description', '')
         list.write ('<hr>\n')
         list.write ('<h1>%s</h1>\n' % head);
         if composer:
@@ -173,14 +166,12 @@ hr { border:0; height:1; color: #000000; background-color: #000000; }\n
     list.write ('</body></html>\n');
     list.close ()
 
-(options, files) = getopt.getopt (sys.argv[1:], 
+(options, files) = getopt.getopt (sys.argv[1:],
  'ho:', ['help', 'output='])
 outfile = 'examples.html'
 
 subdirs = []
-for opt in options:
-    o = opt[0]
-    a = opt[1]
+for (o, a) in options:
     if o == '--help' or o == '-h':
         help ()
     elif o == '--output' or o == '-o':
@@ -188,7 +179,7 @@ for opt in options:
 
 dirs  = []
 for f in files:
-    dirs = dirs + find ('out-www', f)
+    dirs += find ('out-www', f)
 
 if not dirs:
     dirs = ['.']
@@ -196,11 +187,11 @@ if not dirs:
 allfiles = []
 
 for d in dirs:
-    allfiles = allfiles + find ('*.ly', d)
-
-allfiles = filter (lambda x: not x.endswith ('snippet-map.ly') and not re.search ('lily-[0-9a-f]+', x), allfiles)
-allfiles = filter (lambda x: 'musicxml' not in x, allfiles)
+    allfiles += find ('*.ly', d)
 
+allfiles = [f for f in allfiles
+            if not x.endswith ('snippet-map.ly')
+            and not re.search ('lily-[0-9a-f]+', f)
+            and 'musicxml' not in f]
 
 gen_list (allfiles, outfile)
-
index 41be20b56ca7dec7cd8c4c593b5f8739409006d9..70267ffa59c8631faffe67cf8f691f1e16878ec7 100644 (file)
@@ -1,6 +1,6 @@
-#!/usr/bin/python
+#!/usr/bin/env python
 import os
 import sys
 
 for i in sys.argv[1:]:
-  print os.path.realpath(i)
+    print os.path.realpath (i)
index 9db307d1ef9d7a84c3213388fc762c3a870e0ee8..68c55e8c685875f398dd31ec5915c98167a433cf 100755 (executable)
@@ -19,25 +19,22 @@ import string
 import os
 import gettext
 
+import langdefs
+
 def progress (str):
     sys.stderr.write (str + '\n')
 
 progress ("translations-status.py")
 
 buildscript_dir = sys.argv[1]
-localedir = sys.argv[2]
 
 _doc = lambda s: s
 
 sys.path.append (buildscript_dir)
-import langdefs
 import buildlib
 
 # load gettext messages catalogs
-translation = {}
-for l in langdefs.LANGUAGES:
-    if l.enabled and l.code != 'en':
-        translation[l.code] = gettext.translation('lilypond-doc', localedir, [l.code]).gettext
+translation = langdefs.translation
 
 
 comments_re = re.compile (r'^@ignore\n(.|\n)*?\n@end ignore$|@c .*?$', re.M)