Пересобранный и видоизмененный conky для ОСГОС
This commit is contained in:
commit
3a48cf8c86
738 changed files with 217718 additions and 0 deletions
34
bin/changelog2html.py
Executable file
34
bin/changelog2html.py
Executable file
|
|
@ -0,0 +1,34 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
import sys
|
||||
|
||||
if len(sys.argv) <= 1:
|
||||
print >> sys.stderr, "Usage: ./changelog2html.py [changelog file]"
|
||||
sys.exit(1)
|
||||
|
||||
f = sys.argv[1]
|
||||
|
||||
blah = 0
|
||||
|
||||
print '<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8" /></head><body>'
|
||||
|
||||
for i in open(f).read().splitlines():
|
||||
# ignore empty lines
|
||||
|
||||
if i and i[0].isspace():
|
||||
if not '*' in i:
|
||||
print ' ' + i.strip()
|
||||
else:
|
||||
s = i.split('*', 1)[1].strip()
|
||||
print ' <li>' + s.replace('<', '<').replace('>', '>')
|
||||
else:
|
||||
if blah:
|
||||
print '</ul>'
|
||||
print '<h3>%s</h3>' % i.strip()
|
||||
print '<ul>'
|
||||
blah = 1
|
||||
|
||||
if blah:
|
||||
print '</ul>'
|
||||
|
||||
print '</html></body>'
|
||||
12
bin/check-style.sh
Executable file
12
bin/check-style.sh
Executable file
|
|
@ -0,0 +1,12 @@
|
|||
#!/bin/bash
|
||||
set -euxo pipefail
|
||||
|
||||
DIR="$( dirname "${BASH_SOURCE[0]}" )"
|
||||
# Run clang-tidy only for the lines of code which have changed.
|
||||
git diff -U0 $TRAVIS_COMMIT_RANGE | \
|
||||
$DIR/clang-tidy-diff.py -p1 \
|
||||
-checks=*,-clang-analyzer-alpha.* \
|
||||
-quiet \
|
||||
-- \
|
||||
-warnings-as-errors=*,-clang-analyzer-alpha.* \
|
||||
-format-style='{BasedOnStyle: google, IndentWidth: 2}'
|
||||
258
bin/check_docs.py
Executable file
258
bin/check_docs.py
Executable file
|
|
@ -0,0 +1,258 @@
|
|||
#!/usr/bin/python
|
||||
#
|
||||
# This script will check the documentation consistency against the code. It
|
||||
# doesn't check the actual accuracy of the documentation, it just ensures that
|
||||
# everything is documented and that nothing which doesn't exist in Conky
|
||||
# appears in the documentation.
|
||||
#
|
||||
# This script also updates the vim and nano syntax files so it doesn't have to
|
||||
# be done manually.
|
||||
#
|
||||
# Requires the ElementTree Python module for the sorting stuff, see:
|
||||
# http://effbot.org/zone/element-index.htm
|
||||
#
|
||||
# You should also install htmltidy, but it's not necessary.
|
||||
#
|
||||
|
||||
import os.path
|
||||
import re
|
||||
import sys
|
||||
import mmap
|
||||
from datetime import *
|
||||
|
||||
file_names = dict()
|
||||
file_names["text_objects"] = "src/text_object.h"
|
||||
file_names["conky"] = "src/conky.c"
|
||||
file_names["vim_syntax"] = "extras/vim/syntax/conkyrc.vim"
|
||||
file_names["nano_syntax"] = "extras/nano/conky.nanorc"
|
||||
file_names["variables"] = "doc/variables.xml"
|
||||
file_names["config_settings"] = "doc/config_settings.xml"
|
||||
file_names["lua"] = "doc/lua.xml"
|
||||
file_names["docs"] = "doc/docs.xml"
|
||||
file_names["command_options"] = "doc/command_options.xml"
|
||||
|
||||
for fn in file_names.values():
|
||||
if not os.path.exists(fn) or not os.path.isfile(fn):
|
||||
print "'%s' doesn't exist, or isn't a file" % (fn)
|
||||
exit(1)
|
||||
|
||||
print 'sorting/tidying docs...'
|
||||
|
||||
# sort the docs by variable/config setting
|
||||
import string
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
vars_xml = ET.parse(file_names['variables'])
|
||||
config_xml = ET.parse(file_names['config_settings'])
|
||||
|
||||
getkey = lambda x: x.findtext('term/command/option')
|
||||
|
||||
vars = vars_xml.getroot()
|
||||
vars[:] = sorted(vars, key=getkey)
|
||||
|
||||
configs = config_xml.getroot()
|
||||
configs[:] = sorted(configs, key=getkey)
|
||||
|
||||
vars_xml.write(file_names['variables'])
|
||||
config_xml.write(file_names['config_settings'])
|
||||
|
||||
def tidy(file):
|
||||
command = ['tidy', '-qim', '-xml', '-utf8', '--indent-spaces', '4']
|
||||
os.system('%s %s 2>/dev/null' % (string.join(command), file))
|
||||
|
||||
tidy(file_names['variables'])
|
||||
tidy(file_names['config_settings'])
|
||||
tidy(file_names['lua'])
|
||||
tidy(file_names['command_options'])
|
||||
|
||||
#
|
||||
# Do all the objects first
|
||||
#
|
||||
|
||||
objects = []
|
||||
|
||||
file = open(file_names["text_objects"], "r")
|
||||
exp = re.compile("\s*OBJ_(\w*).*")
|
||||
while file:
|
||||
line = file.readline()
|
||||
if len(line) == 0:
|
||||
break
|
||||
res = exp.match(line)
|
||||
if res:
|
||||
obj = res.group(1)
|
||||
if not re.match("color\d", obj) and obj != "text":
|
||||
# ignore colourN stuff
|
||||
objects.append(res.group(1))
|
||||
file.close()
|
||||
print 'counted %i text objects' % len(objects)
|
||||
|
||||
doc_objects = []
|
||||
exp = re.compile("\s*<command><option>(\w*)</option></command>.*")
|
||||
print "checking docs -> objs consistency (in %s)" % (file_names["text_objects"])
|
||||
for var in vars:
|
||||
term = getkey(var)
|
||||
doc_objects.append(term)
|
||||
if ['templaten', 'colorn'].count(doc_objects[len(doc_objects) - 1].lower()):
|
||||
# ignore these
|
||||
continue
|
||||
if doc_objects[len(doc_objects) - 1] not in objects:
|
||||
print " '%s' is documented, but doesn't seem to be an object" % (doc_objects[len(doc_objects) - 1])
|
||||
print "done\n"
|
||||
|
||||
print "checking objs -> docs consistency (in %s)" % (file_names["variables"])
|
||||
for obj in objects:
|
||||
if obj not in doc_objects:
|
||||
print " '%s' seems to be undocumented" % (obj)
|
||||
print "done\n"
|
||||
|
||||
#
|
||||
# Now we'll do config settings
|
||||
#
|
||||
|
||||
config_entries = []
|
||||
|
||||
file = open(file_names["conky"], "r")
|
||||
exp1 = re.compile('\s*CONF\("(\w*)".*')
|
||||
exp2 = re.compile('\s*CONF2\("(\w*)".*')
|
||||
exp3 = re.compile('\s*CONF3\("(\w*)".*')
|
||||
while file:
|
||||
line = file.readline()
|
||||
if len(line) == 0:
|
||||
break
|
||||
res = exp1.match(line)
|
||||
if not res:
|
||||
res = exp2.match(line)
|
||||
if not res:
|
||||
res = exp3.match(line)
|
||||
if res:
|
||||
conf = res.group(1)
|
||||
if re.match("color\d", conf):
|
||||
conf = "colorN"
|
||||
if config_entries.count(conf) == 0:
|
||||
config_entries.append(conf)
|
||||
file.close()
|
||||
print 'counted %i config settings' % len(config_entries)
|
||||
|
||||
doc_configs = []
|
||||
print "checking docs -> configs consistency (in %s)" % (file_names["conky"])
|
||||
for config in configs:
|
||||
term = getkey(config)
|
||||
doc_configs.append(term)
|
||||
if ['text', 'templaten'].count(doc_configs[len(doc_configs) - 1].lower()):
|
||||
# ignore these
|
||||
continue
|
||||
if doc_configs[len(doc_configs) - 1] not in config_entries:
|
||||
print " '%s' is documented, but doesn't seem to be a config setting" % (doc_configs[len(doc_configs) - 1])
|
||||
print "done\n"
|
||||
|
||||
print "checking configs -> docs consistency (in %s)" % (file_names["config_settings"])
|
||||
for obj in config_entries:
|
||||
if obj != "text" and obj != "template" and obj not in doc_configs:
|
||||
print " '%s' seems to be undocumented" % (obj)
|
||||
print "done\n"
|
||||
|
||||
|
||||
|
||||
# Cheat and add the colour/template stuff.
|
||||
|
||||
for i in range(0, 10):
|
||||
objects.append("color" + str(i))
|
||||
config_entries.append("color" + str(i))
|
||||
objects.append("template" + str(i))
|
||||
config_entries.append("template" + str(i))
|
||||
|
||||
# Finally, sort everything.
|
||||
objects.sort()
|
||||
config_entries.sort()
|
||||
|
||||
#
|
||||
# Update nano syntax stuff
|
||||
#
|
||||
|
||||
print "updating nano syntax...",
|
||||
sys.stdout.flush()
|
||||
file = open(file_names["nano_syntax"], "rw+")
|
||||
lines = []
|
||||
while file:
|
||||
line = file.readline()
|
||||
if len(line) == 0:
|
||||
break
|
||||
lines.append(line)
|
||||
|
||||
# find the line we want to update
|
||||
for line in lines:
|
||||
if re.match("color green ", line):
|
||||
idx = lines.index(line)
|
||||
lines.pop(idx) # remove old line
|
||||
line = 'color green "\<('
|
||||
for obj in config_entries:
|
||||
line += "%s|" % (obj)
|
||||
line = line[:len(line) - 1]
|
||||
line += ')\>"\n'
|
||||
lines.insert(idx, line)
|
||||
if re.match("color brightblue ", line):
|
||||
idx = lines.index(line)
|
||||
lines.pop(idx) # remove old line
|
||||
line = 'color brightblue "\<('
|
||||
for obj in objects:
|
||||
line += "%s|" % (obj)
|
||||
line = line[:len(line) - 1]
|
||||
line += ')\>"\n'
|
||||
lines.insert(idx, line)
|
||||
break # want to ignore everything after this line
|
||||
file.truncate(0)
|
||||
file.seek(0)
|
||||
file.writelines(lines)
|
||||
file.close()
|
||||
print "done."
|
||||
|
||||
#
|
||||
# Update vim syntax stuff
|
||||
#
|
||||
|
||||
print "updating vim syntax...",
|
||||
sys.stdout.flush()
|
||||
file = open(file_names["vim_syntax"], "rw+")
|
||||
lines = []
|
||||
while file:
|
||||
line = file.readline()
|
||||
if len(line) == 0:
|
||||
break
|
||||
lines.append(line)
|
||||
|
||||
# find the line we want to update
|
||||
for line in lines:
|
||||
if re.match("syn keyword ConkyrcSetting ", line):
|
||||
idx = lines.index(line)
|
||||
lines.pop(idx) # remove old line
|
||||
line = 'syn keyword ConkyrcSetting '
|
||||
for obj in config_entries:
|
||||
line += "%s " % (obj)
|
||||
line = line[:len(line) - 1]
|
||||
line += '\n'
|
||||
lines.insert(idx, line)
|
||||
if re.match("syn keyword ConkyrcVarName contained nextgroup=ConkyrcNumber,ConkyrcColour skipwhite ", line):
|
||||
idx = lines.index(line)
|
||||
lines.pop(idx) # remove old line
|
||||
line = 'syn keyword ConkyrcVarName contained nextgroup=ConkyrcNumber,ConkyrcColour skipwhite '
|
||||
for obj in objects:
|
||||
line += "%s " % (obj)
|
||||
line = line[:len(line) - 1]
|
||||
line += '\n'
|
||||
lines.insert(idx, line)
|
||||
break # want to ignore everything after this line
|
||||
file.truncate(0)
|
||||
file.seek(0)
|
||||
file.writelines(lines)
|
||||
file.close()
|
||||
|
||||
# lastly, update the date in docs.xml
|
||||
file = open(file_names["docs"], 'r+')
|
||||
map = mmap.mmap(file.fileno(), os.path.getsize(file_names["docs"]))
|
||||
d = map.find("<date>")
|
||||
d += 6 # skip over first date stuff
|
||||
map[d:d+10] = datetime.now().strftime("%F")
|
||||
map.close()
|
||||
file.close()
|
||||
|
||||
print "done."
|
||||
146
bin/clang-tidy-diff.py
Executable file
146
bin/clang-tidy-diff.py
Executable file
|
|
@ -0,0 +1,146 @@
|
|||
#!/usr/bin/env python3
|
||||
#
|
||||
#===- clang-tidy-diff.py - ClangTidy Diff Checker ------------*- python -*--===#
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
#===------------------------------------------------------------------------===#
|
||||
|
||||
r"""
|
||||
ClangTidy Diff Checker
|
||||
======================
|
||||
|
||||
This script reads input from a unified diff, runs clang-tidy on all changed
|
||||
files and outputs clang-tidy warnings in changed lines only. This is useful to
|
||||
detect clang-tidy regressions in the lines touched by a specific patch.
|
||||
Example usage for git/svn users:
|
||||
|
||||
git diff -U0 HEAD^ | clang-tidy-diff.py -p1
|
||||
svn diff --diff-cmd=diff -x-U0 | \
|
||||
clang-tidy-diff.py -fix -checks=-*,modernize-use-override
|
||||
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=
|
||||
'Run clang-tidy against changed files, and '
|
||||
'output diagnostics only for modified '
|
||||
'lines.')
|
||||
parser.add_argument('-clang-tidy-binary', metavar='PATH',
|
||||
default='clang-tidy',
|
||||
help='path to clang-tidy binary')
|
||||
parser.add_argument('-p', metavar='NUM', default=0,
|
||||
help='strip the smallest prefix containing P slashes')
|
||||
parser.add_argument('-regex', metavar='PATTERN', default=None,
|
||||
help='custom pattern selecting file paths to check '
|
||||
'(case sensitive, overrides -iregex)')
|
||||
parser.add_argument('-iregex', metavar='PATTERN', default=
|
||||
r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc)',
|
||||
help='custom pattern selecting file paths to check '
|
||||
'(case insensitive, overridden by -regex)')
|
||||
|
||||
parser.add_argument('-fix', action='store_true', default=False,
|
||||
help='apply suggested fixes')
|
||||
parser.add_argument('-checks',
|
||||
help='checks filter, when not specified, use clang-tidy '
|
||||
'default',
|
||||
default='')
|
||||
parser.add_argument('-format-style',
|
||||
help='style format',
|
||||
default='')
|
||||
parser.add_argument('-path', dest='build_path',
|
||||
help='Path used to read a compile command database.')
|
||||
parser.add_argument('-extra-arg', dest='extra_arg',
|
||||
action='append', default=[],
|
||||
help='Additional argument to append to the compiler '
|
||||
'command line.')
|
||||
parser.add_argument('-extra-arg-before', dest='extra_arg_before',
|
||||
action='append', default=[],
|
||||
help='Additional argument to prepend to the compiler '
|
||||
'command line.')
|
||||
parser.add_argument('-quiet', action='store_true', default=False,
|
||||
help='Run clang-tidy in quiet mode')
|
||||
clang_tidy_args = []
|
||||
argv = sys.argv[1:]
|
||||
if '--' in argv:
|
||||
clang_tidy_args.extend(argv[argv.index('--'):])
|
||||
argv = argv[:argv.index('--')]
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
# Extract changed lines for each file.
|
||||
filename = None
|
||||
lines_by_file = {}
|
||||
for line in sys.stdin:
|
||||
match = re.search('^\+\+\+\ \"?(.*?/){%s}([^ \t\n\"]*)' % args.p, line)
|
||||
if match:
|
||||
filename = match.group(2)
|
||||
if filename == None:
|
||||
continue
|
||||
|
||||
if args.regex is not None:
|
||||
if not re.match('^%s$' % args.regex, filename):
|
||||
continue
|
||||
else:
|
||||
if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
|
||||
continue
|
||||
|
||||
match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
|
||||
if match:
|
||||
start_line = int(match.group(1))
|
||||
line_count = 1
|
||||
if match.group(3):
|
||||
line_count = int(match.group(3))
|
||||
if line_count == 0:
|
||||
continue
|
||||
end_line = start_line + line_count - 1;
|
||||
lines_by_file.setdefault(filename, []).append([start_line, end_line])
|
||||
|
||||
if len(lines_by_file) == 0:
|
||||
print("No relevant changes found.")
|
||||
sys.exit(0)
|
||||
|
||||
line_filter_json = json.dumps(
|
||||
[{"name" : name, "lines" : lines_by_file[name]} for name in lines_by_file],
|
||||
separators = (',', ':'))
|
||||
|
||||
quote = "";
|
||||
if sys.platform == 'win32':
|
||||
line_filter_json=re.sub(r'"', r'"""', line_filter_json)
|
||||
else:
|
||||
quote = "'";
|
||||
|
||||
# Run clang-tidy on files containing changes.
|
||||
command = [args.clang_tidy_binary]
|
||||
command.append('-line-filter=' + quote + line_filter_json + quote)
|
||||
if args.fix:
|
||||
command.append('-fix')
|
||||
if args.checks != '':
|
||||
command.append('-checks=' + quote + args.checks + quote)
|
||||
if args.format_style != '':
|
||||
command.append('-format-style=' + quote + args.format_style + quote)
|
||||
if args.quiet:
|
||||
command.append('-quiet')
|
||||
if args.build_path is not None:
|
||||
command.append('-p=%s' % args.build_path)
|
||||
command.extend(lines_by_file.keys())
|
||||
for arg in args.extra_arg:
|
||||
command.append('-extra-arg=%s' % arg)
|
||||
for arg in args.extra_arg_before:
|
||||
command.append('-extra-arg-before=%s' % arg)
|
||||
command.extend(clang_tidy_args)
|
||||
|
||||
sys.exit(subprocess.call(' '.join(command), shell=True))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
7
bin/format-colors.sh
Executable file
7
bin/format-colors.sh
Executable file
|
|
@ -0,0 +1,7 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Prepares stdin input YAML for gperf consumption
|
||||
|
||||
echo "struct rgb { const char *name; uint8_t red; uint8_t green; uint8_t blue; };"
|
||||
echo "%%"
|
||||
tr -d '[]"' | tr ":" ","
|
||||
326
bin/run-clang-format.py
Executable file
326
bin/run-clang-format.py
Executable file
|
|
@ -0,0 +1,326 @@
|
|||
#!/usr/bin/env python3
|
||||
"""A wrapper script around clang-format, suitable for linting multiple files
|
||||
and to use for continuous integration.
|
||||
|
||||
This is an alternative API for the clang-format command line.
|
||||
It runs over multiple files and directories in parallel.
|
||||
A diff output is produced and a sensible exit code is returned.
|
||||
|
||||
Source: https://raw.githubusercontent.com/Sarcasm/run-clang-format/master/run-clang-format.py
|
||||
"""
|
||||
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
import argparse
|
||||
import codecs
|
||||
import difflib
|
||||
import fnmatch
|
||||
import io
|
||||
import multiprocessing
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from functools import partial
|
||||
|
||||
DEFAULT_EXTENSIONS = 'c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx'
|
||||
|
||||
|
||||
class ExitStatus:
|
||||
SUCCESS = 0
|
||||
DIFF = 1
|
||||
TROUBLE = 2
|
||||
|
||||
|
||||
def list_files(files, recursive=False, extensions=None, exclude=None):
|
||||
if extensions is None:
|
||||
extensions = []
|
||||
if exclude is None:
|
||||
exclude = []
|
||||
|
||||
out = []
|
||||
for file in files:
|
||||
if recursive and os.path.isdir(file):
|
||||
for dirpath, dnames, fnames in os.walk(file):
|
||||
fpaths = [os.path.join(dirpath, fname) for fname in fnames]
|
||||
for pattern in exclude:
|
||||
# os.walk() supports trimming down the dnames list
|
||||
# by modifying it in-place,
|
||||
# to avoid unnecessary directory listings.
|
||||
dnames[:] = [
|
||||
x for x in dnames
|
||||
if
|
||||
not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)
|
||||
]
|
||||
fpaths = [
|
||||
x for x in fpaths if not fnmatch.fnmatch(x, pattern)
|
||||
]
|
||||
for f in fpaths:
|
||||
ext = os.path.splitext(f)[1][1:]
|
||||
if ext in extensions:
|
||||
out.append(f)
|
||||
else:
|
||||
out.append(file)
|
||||
return out
|
||||
|
||||
|
||||
def make_diff(file, original, reformatted):
|
||||
return list(
|
||||
difflib.unified_diff(
|
||||
original,
|
||||
reformatted,
|
||||
fromfile='{}\t(original)'.format(file),
|
||||
tofile='{}\t(reformatted)'.format(file),
|
||||
n=3))
|
||||
|
||||
|
||||
class DiffError(Exception):
|
||||
def __init__(self, message, errs=None):
|
||||
super(DiffError, self).__init__(message)
|
||||
self.errs = errs or []
|
||||
|
||||
|
||||
class UnexpectedError(Exception):
|
||||
def __init__(self, message, exc=None):
|
||||
super(UnexpectedError, self).__init__(message)
|
||||
self.formatted_traceback = traceback.format_exc()
|
||||
self.exc = exc
|
||||
|
||||
|
||||
def run_clang_format_diff_wrapper(args, file):
|
||||
try:
|
||||
ret = run_clang_format_diff(args, file)
|
||||
return ret
|
||||
except DiffError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise UnexpectedError('{}: {}: {}'.format(file, e.__class__.__name__,
|
||||
e), e)
|
||||
|
||||
|
||||
def run_clang_format_diff(args, file):
|
||||
try:
|
||||
with io.open(file, 'r', encoding='utf-8') as f:
|
||||
original = f.readlines()
|
||||
except IOError as exc:
|
||||
raise DiffError(str(exc))
|
||||
invocation = [args.clang_format_executable, file]
|
||||
|
||||
# Use of utf-8 to decode the process output.
|
||||
#
|
||||
# Hopefully, this is the correct thing to do.
|
||||
#
|
||||
# It's done due to the following assumptions (which may be incorrect):
|
||||
# - clang-format will returns the bytes read from the files as-is,
|
||||
# without conversion, and it is already assumed that the files use utf-8.
|
||||
# - if the diagnostics were internationalized, they would use utf-8:
|
||||
# > Adding Translations to Clang
|
||||
# >
|
||||
# > Not possible yet!
|
||||
# > Diagnostic strings should be written in UTF-8,
|
||||
# > the client can translate to the relevant code page if needed.
|
||||
# > Each translation completely replaces the format string
|
||||
# > for the diagnostic.
|
||||
# > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation
|
||||
#
|
||||
# It's not pretty, due to Python 2 & 3 compatibility.
|
||||
encoding_py3 = {}
|
||||
if sys.version_info[0] >= 3:
|
||||
encoding_py3['encoding'] = 'utf-8'
|
||||
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
invocation,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
universal_newlines=True,
|
||||
**encoding_py3)
|
||||
except OSError as exc:
|
||||
raise DiffError(str(exc))
|
||||
proc_stdout = proc.stdout
|
||||
proc_stderr = proc.stderr
|
||||
if sys.version_info[0] < 3:
|
||||
# make the pipes compatible with Python 3,
|
||||
# reading lines should output unicode
|
||||
encoding = 'utf-8'
|
||||
proc_stdout = codecs.getreader(encoding)(proc_stdout)
|
||||
proc_stderr = codecs.getreader(encoding)(proc_stderr)
|
||||
# hopefully the stderr pipe won't get full and block the process
|
||||
outs = list(proc_stdout.readlines())
|
||||
errs = list(proc_stderr.readlines())
|
||||
proc.wait()
|
||||
if proc.returncode:
|
||||
raise DiffError("clang-format exited with status {}: '{}'".format(
|
||||
proc.returncode, file), errs)
|
||||
return make_diff(file, original, outs), errs
|
||||
|
||||
|
||||
def bold_red(s):
|
||||
return '\x1b[1m\x1b[31m' + s + '\x1b[0m'
|
||||
|
||||
|
||||
def colorize(diff_lines):
|
||||
def bold(s):
|
||||
return '\x1b[1m' + s + '\x1b[0m'
|
||||
|
||||
def cyan(s):
|
||||
return '\x1b[36m' + s + '\x1b[0m'
|
||||
|
||||
def green(s):
|
||||
return '\x1b[32m' + s + '\x1b[0m'
|
||||
|
||||
def red(s):
|
||||
return '\x1b[31m' + s + '\x1b[0m'
|
||||
|
||||
for line in diff_lines:
|
||||
if line[:4] in ['--- ', '+++ ']:
|
||||
yield bold(line)
|
||||
elif line.startswith('@@ '):
|
||||
yield cyan(line)
|
||||
elif line.startswith('+'):
|
||||
yield green(line)
|
||||
elif line.startswith('-'):
|
||||
yield red(line)
|
||||
else:
|
||||
yield line
|
||||
|
||||
|
||||
def print_diff(diff_lines, use_color):
|
||||
if use_color:
|
||||
diff_lines = colorize(diff_lines)
|
||||
if sys.version_info[0] < 3:
|
||||
sys.stdout.writelines((l.encode('utf-8') for l in diff_lines))
|
||||
else:
|
||||
sys.stdout.writelines(diff_lines)
|
||||
|
||||
|
||||
def print_trouble(prog, message, use_colors):
|
||||
error_text = 'error:'
|
||||
if use_colors:
|
||||
error_text = bold_red(error_text)
|
||||
print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
'--clang-format-executable',
|
||||
metavar='EXECUTABLE',
|
||||
help='path to the clang-format executable',
|
||||
default='clang-format')
|
||||
parser.add_argument(
|
||||
'--extensions',
|
||||
help='comma separated list of file extensions (default: {})'.format(
|
||||
DEFAULT_EXTENSIONS),
|
||||
default=DEFAULT_EXTENSIONS)
|
||||
parser.add_argument(
|
||||
'-r',
|
||||
'--recursive',
|
||||
action='store_true',
|
||||
help='run recursively over directories')
|
||||
parser.add_argument('files', metavar='file', nargs='+')
|
||||
parser.add_argument(
|
||||
'-q',
|
||||
'--quiet',
|
||||
action='store_true')
|
||||
parser.add_argument(
|
||||
'-j',
|
||||
metavar='N',
|
||||
type=int,
|
||||
default=0,
|
||||
help='run N clang-format jobs in parallel'
|
||||
' (default number of cpus + 1)')
|
||||
parser.add_argument(
|
||||
'--color',
|
||||
default='auto',
|
||||
choices=['auto', 'always', 'never'],
|
||||
help='show colored diff (default: auto)')
|
||||
parser.add_argument(
|
||||
'-e',
|
||||
'--exclude',
|
||||
metavar='PATTERN',
|
||||
action='append',
|
||||
default=[],
|
||||
help='exclude paths matching the given glob-like pattern(s)'
|
||||
' from recursive search')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# use default signal handling, like diff return SIGINT value on ^C
|
||||
# https://bugs.python.org/issue14229#msg156446
|
||||
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
||||
try:
|
||||
signal.SIGPIPE
|
||||
except AttributeError:
|
||||
# compatibility, SIGPIPE does not exist on Windows
|
||||
pass
|
||||
else:
|
||||
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
||||
|
||||
colored_stdout = False
|
||||
colored_stderr = False
|
||||
if args.color == 'always':
|
||||
colored_stdout = True
|
||||
colored_stderr = True
|
||||
elif args.color == 'auto':
|
||||
colored_stdout = sys.stdout.isatty()
|
||||
colored_stderr = sys.stderr.isatty()
|
||||
|
||||
retcode = ExitStatus.SUCCESS
|
||||
files = list_files(
|
||||
args.files,
|
||||
recursive=args.recursive,
|
||||
exclude=args.exclude,
|
||||
extensions=args.extensions.split(','))
|
||||
|
||||
if not files:
|
||||
return
|
||||
|
||||
njobs = args.j
|
||||
if njobs == 0:
|
||||
njobs = multiprocessing.cpu_count() + 1
|
||||
njobs = min(len(files), njobs)
|
||||
|
||||
if njobs == 1:
|
||||
# execute directly instead of in a pool,
|
||||
# less overhead, simpler stacktraces
|
||||
it = (run_clang_format_diff_wrapper(args, file) for file in files)
|
||||
pool = None
|
||||
else:
|
||||
pool = multiprocessing.Pool(njobs)
|
||||
it = pool.imap_unordered(
|
||||
partial(run_clang_format_diff_wrapper, args), files)
|
||||
while True:
|
||||
try:
|
||||
outs, errs = next(it)
|
||||
except StopIteration:
|
||||
break
|
||||
except DiffError as e:
|
||||
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
|
||||
retcode = ExitStatus.TROUBLE
|
||||
sys.stderr.writelines(e.errs)
|
||||
except UnexpectedError as e:
|
||||
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
|
||||
sys.stderr.write(e.formatted_traceback)
|
||||
retcode = ExitStatus.TROUBLE
|
||||
# stop at the first unexpected error,
|
||||
# something could be very wrong,
|
||||
# don't process all files unnecessarily
|
||||
if pool:
|
||||
pool.terminate()
|
||||
break
|
||||
else:
|
||||
sys.stderr.writelines(errs)
|
||||
if outs == []:
|
||||
continue
|
||||
if not args.quiet:
|
||||
print_diff(outs, use_color=colored_stdout)
|
||||
if retcode == ExitStatus.SUCCESS:
|
||||
retcode = ExitStatus.DIFF
|
||||
return retcode
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
40
bin/text2c.sh
Executable file
40
bin/text2c.sh
Executable file
|
|
@ -0,0 +1,40 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# text2c.sh - convert a text file to C code
|
||||
#
|
||||
# Copyright (C) 2008 Phil Sutter <phil@nwl.cc>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it
|
||||
# under the terms of the GNU General Public License as published by the Free
|
||||
# Software Foundation, either version 3 of the License, or (at your option)
|
||||
# any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but
|
||||
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
|
||||
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
# for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
# Invocation is as follows:
|
||||
# $1: text file
|
||||
# $2: output file
|
||||
# $3: name of variable
|
||||
#
|
||||
# The output will be a char **, with each field containing a single line of $1.
|
||||
# Additionally, a macro with the name print_$3 will be defined, with acts as
|
||||
# a parameter-less function, printing the text to stdout.
|
||||
|
||||
[ $# -eq 3 ] || {
|
||||
echo "Usage: `basename $0` <inputfile> <outputfile> <variablename>"
|
||||
exit 1
|
||||
}
|
||||
|
||||
outupper="`basename "$2" | tr '[a-z-.]' '[A-Z__]'`"
|
||||
|
||||
(
|
||||
printf "const char %s[] = \n" "$3"
|
||||
sed -e 's/["\]/\\&/g' -e 's/^/ "/' -e 's/$/\\n"/' -e '$s/$/;/' "$1"
|
||||
) > "$2"
|
||||
Loading…
Add table
Add a link
Reference in a new issue