Example #1
0
def copy_astyle_top(dist_top, to_dos=False):
    """Copy files in the top directory to a distribution directory.
    """
    print("copying top")
    deleted = 0
    docfiles = glob.glob(__astyle_dir + "/*")
    docfiles.sort()
    for filepath in docfiles:
        sep = filepath.rfind(os.sep)
        filename = filepath[sep + 1:]
        if (filename == "LICENSE.txt"
        or filename == "README.txt"):
            shutil.copy(filepath, dist_top)
            print("    " + filename)
        else:
            deleted += 1
    convert_line_ends(dist_top, to_dos)
    # verify copy - had a problem with bad filenames
    distfiles = (glob.glob(dist_top + "/*.txt"))
    if len(distfiles) != len(docfiles) - deleted:
        libastyle.system_exit("Error copying top: " + str(len(distfiles)))
    # change file permissions
    for srcfile in distfiles:
        # read/write by the owner and read only by everyone else (-rw-r--r--)
        mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
        os.chmod(srcfile, mode)
def build_testi18n_executable():
	"""Build the Visual Studio AStyleTestI18n debug executable.
	"""
	print ("Building Visual Studio AStyleTestI18n Debug")
	# Compile the astyle executable for Windows.
	sdk = "v3.5"
	vsdir = "vs2008"
	if builddir.find("vs2010") != -1:
		sdk = "v4.0.30319"
		vsdir = "vs2010"
	# remove the cache file as a precaution
	cachepath = (builddir
			+ "/AStyle.sln.cache")
	if os.path.isfile(cachepath):
		os.remove(cachepath)
	# call MSBuild
	buildpath =  (os.getenv("WINDIR")
			+ "/Microsoft.NET/Framework/"
			+ sdk
			+ "/MSBuild.exe")
	configProp = "/property:Configuration=Debug"
	slnpath = (builddir
			+ "/AStyleTestI18n.sln")
	platform = "/property:Platform=Win32"
	msbuild = ([buildpath, configProp, platform, slnpath])
	buildfile = libastyle.get_temp_directory() + "/build.txt"
	outfile = open(buildfile, 'w')
	retval = subprocess.call(msbuild, stdout=outfile)
	if retval:
		libastyle.system_exit("Bad msbuild return: " + str(retval))
	outfile.close()
	os.remove(buildfile)
Example #3
0
def main():
    """Main processing function."""

    astyle_strings = []     # _() translation strings in astyle_main.cpp
    test_strings = []           # test strings in TranslationF
    astyle_path = libastyle.get_astyle_directory() + "/src/astyle_main.cpp"
    if not os.path.exists(astyle_path):
        libastyle.system_exit("\nCannot locate file " + astyle_path)
    test_path = libastyle.get_astyletest_directory() + "/srcloc/AStyleTestLoc.cpp"
    if not os.path.exists(test_path):
        libastyle.system_exit("\nCannot locate file " + test_path)
    libastyle.set_text_color()
    print(libastyle.get_python_version())
    get_astyle_strings(astyle_strings, astyle_path)
    get_test_strings(test_strings, test_path)

    print("Checking astyle_main strings to TranslationF.")
    total_astyle_strings = len(astyle_strings)
    print("There are {0} translated strings in astyle_main.".format(total_astyle_strings))
    print()

    find_string_diffs(astyle_strings, test_strings)

    if __print_variables:
        astyle_strings.sort()
        test_strings.sort()
        print(astyle_strings)
        print(test_strings)
def main():
	"""Main processing function.
	"""
	# initialization
	libastyle.set_text_color()
	print(libastyle.get_python_version())
	verify_os()
	exepath = "C:/Windows/AppPatch/AppLoc.exe"
	i18npath = __builddir + "/bin/AStyleTestI18nd.exe"
	command = exepath + ' ' + i18npath + ' ' + "\"--terse_printer --no_close\"" + ' '
	# verify files
	if not os.path.exists(exepath):
		libastyle.system_exit("AppLoc not installed: " + exepath)
	build_testi18n_executable()

	# for some reason the subprocess call must be one long statement and quoted as follows???
	# the country LCID is added by the subprocess call
	command = exepath + ' ' + i18npath + ' ' + "\"--terse_printer --no_close\"" + ' '
	# run tests
	print("\nWAIT for a test to finish before running the next")
	print("Reply OK to continue ...")
	print("Running Greek Test")
	subprocess.call(command + "/L0408")
	time.sleep(2)		# must finish before running the next test
	print("Running Japanese Test")
	subprocess.call(command + "/L0411")
	time.sleep(2)		# must finish before running the next test
	print("Running Russian Test")
	subprocess.call(command + "/L0419")
	time.sleep(2)		# must finish before running the next test
Example #5
0
def extract_project(project, all_files_option):
	"""Call the procedure to extract the requested project.
	   The main processing procedure called by other functions.
	"""
	global __extract_all_files
	if all_files_option == True:
		__extract_all_files = True
	if project == libastyle.CODEBLOCKS:
		extract_codeblocks()
	elif project == libastyle.DRJAVA:
		extract_drjava()
	elif project == libastyle.GWORKSPACE:
		extract_gworkspace()
	elif project == libastyle.JEDIT:
		extract_jedit()
#	elif project == libastyle.KDEVELOP:
#		extract_kdevelop()
#	elif project == libastyle.MONODEVELOP:
#		extract_monodevelop()
	elif project == libastyle.SCITE:
		extract_scite()
	elif project == libastyle.SHARPDEVELOP:
		extract_sharpdevelop()
	elif project == libastyle.SHARPMAIN:
		extract_sharpmain()
	elif project == libastyle.TESTPROJECT:
		extract_testproject()
	else:
		libastyle.system_exit("Bad extract_files project id: " + str(project))
Example #6
0
def call_7zip(filepath, outdir, fileext):
	"""Call 7zip to extract an archive.
	   This uses a tempfile and the 'os' methods instead of
	   the built-in functions open, close, and remove.
	"""
	filepath = filepath.replace('\\', '/')
	prtfile = strip_directory_prefix(filepath)
	print("extract " + prtfile)
	exepath = libastyle.get_7zip_path()
	extract = [exepath, "x", "-ry", "-o" + outdir, filepath]
	if __extract_all_files:
		print("extracting ALL files", )
	else:
		extract.extend(fileext)
		print("extracting " + str(fileext))
	# open a tempfile and access it with the 'os' methods
	fd, filename = tempfile.mkstemp(prefix="extract.", suffix=".tmp",
								dir=libastyle.get_temp_directory(), text=True)
#	print(os.path.basename(filename))
	try:
		subprocess.check_call(extract, stdout=fd)
	except subprocess.CalledProcessError as err:
		libastyle.system_exit("Bad 7zip return: " + str(err.returncode))
	except OSError:
		libastyle.system_exit("Cannot find executable: " + exepath)
	os.close(fd)
	os.remove(filename)
Example #7
0
def rename_output_file(filepaths):
    """Rename the output file by appending the options variable number (0-3).
    """
    print('\n' + ('-' * 60))
    # extract filename
    filepath = filepaths[0]
    filepath = filepath.replace('\\', '/')
    testdir = libastyle.get_test_directory()
    start = len(testdir) + 1
    end = filepath.find('/', start)
    if end == -1:
        libastyle.system_exit("Cannot find filename for rename: " + filepath)
    dirname = filepath[start:end]
    dirpath = testdir + '/' + dirname
    options_suffix = get_options_variable_name()[-1]
    newname = dirname + options_suffix
    newpath = dirpath + options_suffix
    # rename by adding the option number to the end
    if os.path.isdir(newpath):
        libextract.remove_test_directory(newname)
    print("rename {0} {1}".format(dirname, newname))
    try:
        shutil.move(dirpath, newpath)
    except WindowsError as err:
        time.sleep(2)
        try:
            shutil.move(dirpath, newpath)
        except WindowsError as err:
            print()
            print(err)
            libastyle.system_exit("Error in renaming output file: " + dirpath)
Example #8
0
def main():
    """Main processing function.
    """
    files = []
    totfiles = 0
    testfile = "test.txt"
    sharpfile = "test-csharp.txt"

    # initialization
    libastyle.set_text_color()
    os.chdir(libastyle.get_file_py_directory())
    if not os.path.exists(testfile):
        libastyle.system_exit(
            "Run regression2-test.py to create " + testfile)
    print(libastyle.get_python_version())
    print("extracting C# test data")

    # process formatted files
    files = libtest.get_formatted_files(testfile)
    outfile = open(sharpfile, 'w')
    for filepath in files:
        filepath = filepath.replace('\\', '/')  # replace file separators
        filepath = '\"' + filepath + '\",'      # add quotes to filepath
        outfile.write(filepath + '\n')
        totfiles += 1
    outfile.close()
    print ("saved " + sharpfile)
    print("files extracted " + str(totfiles))
    formatted, unused, unused, unused = libtest.get_astyle_totals(testfile)
    if totfiles != formatted:
        libastyle.system_exit(
            "totals not equal {0} {1}".format(totfiles, formatted))
Example #9
0
def convert_line_ends(dist_dir, to_dos):
    """Convert line ends to dos (CRLF) or linux (LF).
       Needs tofrodos package.
       All files in a directory are converted.
    """
    files = glob.glob(dist_dir + "*.*")
    if os.name == "nt":
        exedir = "C:/Programs/tofrodos/"
        if to_dos:
            call_list = [exedir + "todos"] + files
        else:
            call_list = [exedir + "fromdos"] + files
    else:
        if to_dos:
            call_list = ["todos"] + files
        else:
            call_list = ["fromdos"] + files

    # call the conversion program
    try:
        subprocess.check_call(call_list)
    except subprocess.CalledProcessError as err:
        libastyle.system_exit("Bad tofro return: " + str(err.returncode))
    except OSError:
        libastyle.system_exit("Cannot find executable: " + call_list[0])
Example #10
0
def copy_build_directories_vs(dist_build, build_dir):
    """Copy the build/visual-studio directories to the distribution directory.
    """
    buildfiles = __astyle_dir + "/build/"
    # copy solution files
    vsdir = '/' + build_dir + '/'
    dist_astyle_vs20xx = dist_build + vsdir
    os.mkdir(dist_astyle_vs20xx)
    slnfiles = glob.glob(buildfiles + vsdir + "*.sln")
    for sln in slnfiles:
        shutil.copy(sln, dist_astyle_vs20xx)

    # build project directories
    for projdir in ("/AStyle/",
                    "/AStyle Dll/",
                    "/AStyle Java/",
                    "/AStyle Lib/"):
        dist_astyle_proj = dist_astyle_vs20xx[:-1] + projdir
        os.mkdir(dist_astyle_proj)

        # copy project files
        projfiles = glob.glob(buildfiles + vsdir[:-1] + projdir + "*.*proj")
        files_copied = 0
        for proj in projfiles:
            files_copied += 1
            shutil.copy(proj, dist_astyle_proj)
        if vsdir[1:-1] >= "vs2010":
            filtfiles = glob.glob(buildfiles + vsdir[:-1] + projdir + "*.*.filters")
            for filter_in in filtfiles:
                files_copied += 1
                shutil.copy(filter_in, dist_astyle_proj)
        # verify number of files copied
        if files_copied != 2:
            libastyle.system_exit("Error in number of build files copied: " + str(files_copied))
Example #11
0
def copy_astyle_doc(distDoc, toDos=False):
	"""Copy astyle doc directory to a distribution directory.
	"""
	deleted = 0
	docfiles = glob.glob(astyleDir + "/doc/*")
	for filepath in docfiles:
		# don't copy these files
		if filepath.find("Archive") != -1: 
			deleted += 1
			sep = filepath.rfind(os.sep)
			print ("    " + filepath[sep+1:] + " - not copied")
		else:
			shutil.copy(filepath, distDoc)
	convert_line_ends(distDoc, toDos)
	# verify copy - had a problem with bad filenames
	distfiles = (glob.glob(distDoc + "/*.html")
					+ glob.glob(distDoc + "/*.css"))
	if len(distfiles) != len(docfiles) - deleted:
		libastyle.system_exit("Error copying doc: " + str(len(distfiles)))
	# change file permissions
	for srcfile in distfiles:
		# read/write by the owner and read only by everyone else (-rw-r--r--)
		mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
		os.chmod(srcfile, mode)
	print ("doc copied")
def verify_astyle_executables(exe1, exe2):
	"""Verify that the astyle test executables are available.
	"""
	# get paths
	exe1path = get_astyle_path(exe1)
	exe2path = get_astyle_path(exe2)
	regress1path = libastyle.get_astyle_directory() + "/regress/" + exe1
	# add "exe" extension
	if os.name == "nt":
		if not exe1path.endswith(".exe"):
			exe1path += ".exe"
		if not exe2path.endswith(".exe"):
			exe2path += ".exe"
		if not regress1path.endswith(".exe"):
			regress1path += ".exe"
	# verify exe1
	if not os.path.exists(exe1path):
		# try to copy exe1 from the "regress" directory
		if os.path.exists(regress1path):
			print ("Copying " + exe1)
			shutil.copy(regress1path, exe1path)
		else:
			libastyle.system_exit("Cannot find executable 1: " + exe1path)
	# verify exe2
	if not os.path.exists(exe2path):
		libastyle.system_exit("Cannot find executable 2: " + exe2path)
Example #13
0
def copy_astyle_doc(dist_doc, to_dos=False):
    """Copy astyle doc directory to a distribution directory.
    """
    print("copying doc")
    deleted = 0
    docfiles = glob.glob(__astyle_dir + "/doc/*")
    docfiles.sort()
    for filepath in docfiles:
        sep = filepath.rfind(os.sep)
        filename = filepath[sep + 1:]
        if (filename == "astyle.html"
        or filename == "install.html"
        or filename == "news.html"
        or filename == "notes.html"
        or filename == "styles.css"):
            shutil.copy(filepath, dist_doc)
            print("    " + filename)
        else:
            deleted += 1
    convert_line_ends(dist_doc, to_dos)
    # verify copy - had a problem with bad filenames
    distfiles = (glob.glob(dist_doc + "/*.html")
                    + glob.glob(dist_doc + "/*.css"))
    if len(distfiles) != len(docfiles) - deleted:
        libastyle.system_exit("Error copying doc: " + str(len(distfiles)))
    # change file permissions
    for srcfile in distfiles:
        # read/write by the owner and read only by everyone else (-rw-r--r--)
        mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
        os.chmod(srcfile, mode)
Example #14
0
def open_filein(filename, mode):
    """Open an input file and handle the error.
       Arguments are the same as for the python 'open' statement.
    """
    try:
        infile = open(filename, mode)
    except IOError:
        libastyle.system_exit("Cannot open input file: " + filename)
    return infile
Example #15
0
def verify_localizer_signature():
    """Verify that ASLocalizer.cpp does NOT have a signature (BOM).
    """
    localizerpath = libastyle.get_astyle_directory() + "/src/ASLocalizer.cpp"
    file_fd = os.open(localizerpath, os.O_RDONLY)
    file_bytes = os.read(file_fd, 8)
    if file_bytes[:3] == b"\xEF\xBB\xBF":
        libastyle.system_exit("\nASLocalizer.cpp must NOT have a signature")
    os.close(file_fd)
def verify_test_directory(name):
    """Verify that a directory exists in the TestData directory.
    """
    testdir = libastyle.get_test_directory(True) + name
    dirs = glob.glob(testdir)
    if len(dirs) == 0:
        msg = ("No test directory " + name +
               ", must use formatOLD = True")
        libastyle.system_exit(msg)
Example #17
0
def build_windows_distribution():
    """Copy astyle files to the windows directory.
    """
    print()
    print("* * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
    print("*          Copying AStyle Windows Distribution          *")
    print("* * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
    # the following variables may be modified
    vsdir = libastyle.VS_RELEASE
    vscfg= libastyle.STATIC

    print("Compiling with", vsdir)
    print("Building release", __release)
    if not vsdir >= "vs2013":
        libastyle.system_exit("Must compile with vs2013 or greater in libastyle: " + vsdir)
    dist_base = __base_dir + "/DistWindows"
    dist_astyle = dist_base + "/AStyle"
    os.makedirs(dist_astyle)
    libastyle.build_astyle_executable(vscfg)

    # Windows includes an executable in the bin directory
    print("copying exe")
    dist_astyle_bin = dist_astyle + "/bin/"
    os.mkdir(dist_astyle_bin)
    astyle_build_directory = libastyle.get_astyle_build_directory(vscfg)
    if vscfg ==  libastyle.DEBUG:
        shutil.copy(astyle_build_directory + "/debug/AStyle.exe", dist_astyle_bin)
    elif vscfg ==  libastyle.RELEASE:
        shutil.copy(astyle_build_directory + "/bin/AStyle.exe", dist_astyle_bin)
    elif vscfg ==  libastyle.STATIC:
        shutil.copy(astyle_build_directory + "/binstatic/AStyle.exe", dist_astyle_bin)
    else:
        libastyle.system_exit("Invalid compile configuration: " + vscfg)

    # top directory
    dist_top = dist_astyle + "/"
    copy_astyle_top(dist_top, True)

    # build directory
    dist_build = dist_astyle + "/build"
    os.mkdir(dist_build)
    copy_windows_build_directories(dist_build)

    # doc directory
    dist_doc = dist_astyle + "/doc/"
    os.mkdir(dist_doc)
    copy_astyle_doc(dist_doc, True)

    # src directory
    dist_src = dist_astyle + "/src/"
    os.mkdir(dist_src)
    copy_astyle_src(dist_src, True)

    # create zip
    zipfile = "AStyle_{0}_windows.zip".format(__release)
    call_7zip(dist_base, zipfile)
Example #18
0
def call_diff_program(filepath1, filepath2):
    """Call diff program.
    """
    diff = [libastyle.get_diff_path(), filepath1, filepath2]
    try:
        subprocess.check_call(diff)
    except subprocess.CalledProcessError as err:
        libastyle.system_exit("Bad diff return: " + str(err.returncode))
    except OSError:
        libastyle.system_exit("Cannot find executable: " + diff[0])
def main():
    """Main processing function."""
    libastyle.set_text_color("yellow")
    print(libastyle.get_python_version())
    print("Modify AStyle Version from", __old_release, "to", __new_release)
    print("Modify Solib  Version from", __old_solibver, "to", __new_solibver)
    if not __file_update:
        print("\nFILES NOT UPDATED")
    # must use this version for newline option on the file open
    if platform.python_implementation() == "CPython" and sys.version_info[0] >= 3:
        pass
    else:
        libastyle.system_exit("Must use CPython version 3 or greater")
    print()

    # project file directories
    project_extension_list = ["Makefile", ".cbp", ".vcproj", ".vcxproj", ".pbxproj"]
    project_directory_list = [libastyle.get_project_directory(True) + "AStyle/build",
                              libastyle.get_project_directory(True) + "AStyleDev/build",
                              libastyle.get_project_directory(True) + "AStyleTest/build",
                              libastyle.get_project_directory(True) + "AStyleWin/build",
                              libastyle.get_project_directory(True) + "AStyleWx/build",
                              libastyle.get_project_directory(True) + "AStyleWxTest/build"]
    update_project_files(project_directory_list, project_extension_list)

    # source file directories
    source_extension_list = [".properties", ".cpp", ".m", ".java", ".cs"]
    source_directory_list = [libastyle.get_project_directory(True) + "AStyle/src",
                             libastyle.get_project_directory(True) + "AStyleDev/src-c",
                             libastyle.get_project_directory(True) + "AStyleDev/src-j",
                             libastyle.get_project_directory(True) + "AStyleDev/src-o",
                             libastyle.get_project_directory(True) + "AStyleDev/src-p",
                             libastyle.get_project_directory(True) + "AStyleDev/src-s",
                             libastyle.get_project_directory(True) + "AStyleTest/src",
                             libastyle.get_project_directory(True) + "AStyleTest/srccon",
                             libastyle.get_project_directory(True) + "AStyleTest/srci18n",
                             libastyle.get_project_directory(True) + "AStyleTest/srclib",
                             libastyle.get_project_directory(True) + "AStyleTest/srcloc",
                             libastyle.get_project_directory(True) + "AStyleTest/srcx",
                             libastyle.get_project_directory(True) + "AStyleWin/src",
                             libastyle.get_project_directory(True) + "AStyleWx/src",
                             libastyle.get_project_directory(True) + "AStyleWxTest/src",
                             libastyle.get_project_directory(True) + "AStyleWxTest/srcx"]
    update_source_files(source_directory_list, source_extension_list)

    # change the internal version number in cmake
    cmakelists_file_path = libastyle.get_project_directory(True) + "AStyle/CMakeLists.txt"
    update_cmakelists(cmakelists_file_path)

    # change the internal version number in astyle_main source
    astyle_main_file_path = libastyle.get_project_directory(True) + "AStyle/src/astyle_main.cpp"
    update_astyle_main(astyle_main_file_path)

    if not __file_update:
        print("\nFILES NOT UPDATED")
Example #20
0
def call_artistic_style(astyle, testfile):
    """Call artistic style.
    """
    outfile = open(testfile, 'w')
    try:
        subprocess.check_call(astyle, stdout=outfile)
    except subprocess.CalledProcessError as err:
        libastyle.system_exit("Bad astyle return: " + str(err.returncode))
    except OSError:
        libastyle.system_exit("Cannot find executable: " + astyle[0])
    outfile.close()
Example #21
0
def remove_dist_directories():
	"""Remove directories from a previous run.
	"""
	dirs = glob.glob(baseDir + "/[Dd]ist*/")
	for directory in dirs:
		directory = directory.replace('\\', '/')
		print ("remove " + directory)
		shutil.rmtree(directory, True)
		# this is a problem with Windows only
		if os.path.isdir(directory):
			libastyle.system_exit("Directory not removed: " + directory)
Example #22
0
def main():
    """Main processing function.
    """
    libastyle.set_text_color("yellow")
    print(libastyle.get_python_version())
    os.chdir(libastyle.get_file_py_directory())
    remove_dist_directories()
    verify_localizer_signature()
    if os.name == "nt":
        build_windows_distribution()
    else:
        libastyle.system_exit("This is for Windows distribution only!")
Example #23
0
def extract_directory_from_line(line):
    """Get the directory from the 'directory line' in the astyle report.
    """
    # get the directory path
    linesplit = line.split()
    path = linesplit[1]
    # remove the wildcard
    pathsplit = os.path.split(path)
    directory = pathsplit[0]
    # verify result
    if directory == "":
        libastyle.system_exit("Cannot extract directory from line: " + line)
    return directory
def extract_project():
	"""Extract files from archive to test directory.
	"""
	if not os.path.isfile(libastyle.get_archive_directory(True) + archive):
		 libastyle.system_exit("Cannot find archive: " + archive)
	tarfile, ext = os.path.splitext(archive)
	print (tarfile)
	if ext == ".gz" or ext == ".bz2":
		extract_test_tar(tarfile)
	elif ext == ".zip" or ext == ".7z":
		extract_test_zip(tarfile)
	else:
		libastyle.system_exit("Cannot open archive: " + archive)
Example #25
0
def get_options_variable_name():
    """Get the name of the options variable from the global __options.
    """
    if __options == libastyle.OPT0:
        return "OPT0"
    elif __options == libastyle.OPT1:
        return "OPT1"
    elif __options == libastyle.OPT2:
        return "OPT2"
    elif __options == libastyle.OPT3:
        return "OPT3"
    else:
        libastyle.system_exit("\nCannot find options variable name: " + __options)
Example #26
0
def copy_astyle_src(dist_src, to_dos=False):
    """Copy astyle src directory to a distribution directory.
    """
    print("copying src")
    srcfiles = sorted(glob.glob(__astyle_dir + "/src/*"))
    for srcpath in srcfiles:
        shutil.copy(srcpath, dist_src)
    convert_line_ends(dist_src, to_dos)
    # verify copy - had a problem with bad filenames
    distfiles = (glob.glob(dist_src + "/*.cpp")
                 + glob.glob(dist_src + "/*.h"))
    if len(distfiles) != len(srcfiles):
        libastyle.system_exit("Error copying src: " + str(len(distfiles)))
Example #27
0
def build_testi18n_executable():
    """Build the Embarcadero AStyleTestI18n debug executable.
    """
    print("Building Embarcadero AStyleTestI18n Debug")
    # Compile the astyle executable for Windows.
    buildpath = "C:/Program Files (x86)/CodeBlocks/codeblocks.exe"
    if not os.path.isfile(buildpath):
        message = "Cannot find CodeBlocks executable: " + buildpath
        libastyle.system_exit(message)
    print("Close the build window when finished ...")
    arg1 = "--build"
    arg2 = "--target=Debug"
    arg3 = "--no-batch-window-close"
    gmpath = __builddir + "/Bcc GTest Lib.cbp"
    gmbuild = ([buildpath, arg1, arg2, arg3, gmpath])
    cbpath = __builddir + "/Bcc AStyleTestI18n.cbp"
    cbbuild = ([buildpath, arg1, arg2, arg3, cbpath])
    buildfile = libastyle.get_temp_directory() + "/build.txt"
    outfile = open(buildfile, 'w')
    retvalgm = subprocess.call(gmbuild, stdout=outfile)
    if retvalgm:
        libastyle.system_exit("Bad gmbuild return: " + str(retval))
    retvalcb = subprocess.call(cbbuild, stdout=outfile)
    if retvalcb:
        libastyle.system_exit("Bad cbbuild return: " + str(retval))
    outfile.close()
    try:
        os.remove(buildfile)
    except PermissionError as err:
        libastyle.system_exit(str(err))
def call_file_compare_program(filepath, testout, fcout):
    """Call the file compare program for a given filepath.
       Write files with a diff to to testout.
    """
    oldpath = libtest.get_old_filepath(filepath)
    # call file compare
    fclist = get_file_compare_list(filepath, oldpath)
    retval = subprocess.call(fclist, stdout=fcout)
    if retval > 1:
        libastyle.system_exit("Bad file compare return: " + str(retval))
    if retval == 1:
        testout.write(filepath + '\n')
        return True
    return False
def call_artistic_style(astyle, testfile):
    """Call artistic style.
    """
    outfile = open(testfile, 'w')
    try:
        subprocess.check_call(astyle, stdout=outfile)
    except subprocess.CalledProcessError as err:
        libastyle.system_exit("Bad astyle return: " + str(err.returncode))
    except OSError as err:
        if err.errno == 13:
            libastyle.system_exit("Permission denied: " + astyle[0])
        else:
            print(err)
    outfile.close()
Example #30
0
def extract_test_tar(pattern, tarpattern, fileext):
	"""Extract a tarball given the search pattern.
	   If necessary, the tarball will be extracted first.
	   There must be one and only one matching file.
	   arg 1- search pattern for the compressed file.
	   arg 2- serach pattern for the tarball.
	   arg 3- a list of search patterns for the source files.
	"""
	arcdir = libastyle.get_archive_directory(True)
	testdir = libastyle.get_test_directory(True)
	# check for existing tarball
	files = glob.glob(arcdir + tarpattern)
	if len(files) == 1:
		call_7zip(files[0], testdir, fileext)
		return
	# extract the tarball
	files = glob.glob(arcdir + pattern)
	if len(files) == 0:
		libastyle.system_exit("No file to extract: " + pattern)
	if len(files) > 1:
		libastyle.system_exit(str(files) + "\nToo many files to extract")
	call_7zip(files[0], arcdir, [])
	# extract files from the tarball
	files = glob.glob(arcdir + tarpattern)
	if len(files) == 0:
		libastyle.system_exit("No tarball to extract: " + tarpattern)
	if len(files) > 1:
		libastyle.system_exit(str(files) + "\nToo many tarballs to extract")
	call_7zip(files[0], testdir, fileext)
Example #31
0
def build_windows_distribution():
    """Copy astyle files to the windows directory.
    """
    print()
    print("* * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
    print("*        Copying AStyle Windows XP Distribution         *")
    print("* * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
    # the following variables may be modified except vscfg=libastyle.STATIC_XP
    vsdir = libastyle.VS_RELEASE
    vscfg = libastyle.STATIC_XP

    print("Compiling with ({})".format(vsdir))
    print("Building AStyle release", AS_RELEASE)
    if vsdir < "vs2013":
        libastyle.system_exit(
            "Must compile with vs2013 or greater in libastyle: " + vsdir)
    dist_base = __base_dir + "/DistWindowsXP"
    dist_astyle = dist_base + "/AStyleXP"
    os.makedirs(dist_astyle)
    libastyle.build_astyle_executable(vscfg)

    # Windows includes an executable in the bin directory
    print("copying exe")
    dist_astyle_bin = dist_astyle + "/bin/"
    os.mkdir(dist_astyle_bin)
    astyle_build_directory = libastyle.get_astyle_build_directory(vscfg)
    if vscfg == libastyle.DEBUG:
        shutil.copy(astyle_build_directory + "/debug/AStyle.exe",
                    dist_astyle_bin)
    elif vscfg == libastyle.RELEASE:
        shutil.copy(astyle_build_directory + "/bin/AStyle.exe",
                    dist_astyle_bin)
    elif vscfg == libastyle.STATIC_XP:
        shutil.copy(astyle_build_directory + "/binstatic/AStyle.exe",
                    dist_astyle_bin)
    else:
        libastyle.system_exit("Invalid compile configuration: " + vscfg)

    # top directory
    dist_top = dist_astyle + "/"
    copy_astyle_top(dist_top, True)

    # build directory
    dist_build = dist_astyle + "/build"
    os.mkdir(dist_build)
    copy_windows_build_directories(dist_build)

    # doc directory
    dist_doc = dist_astyle + "/doc/"
    os.mkdir(dist_doc)
    copy_astyle_doc(dist_doc, True)

    # file directory
    dist_file = dist_astyle + "/file/"
    os.mkdir(dist_file)
    copy_astyle_file(dist_file, True)

    # src directory
    dist_src = dist_astyle + "/src/"
    os.mkdir(dist_src)
    copy_astyle_src(dist_src, True)

    # create zip
    zipfile = "AStyle_{0}_windows_xp.zip".format(AS_RELEASE)
    call_7zip(dist_base, zipfile)
Example #32
0
def main():
    """Main processing function.
    """
    if os.name != "nt":
        libastyle.system_exit("This script is for Windows only!")

    if platform.python_implementation() == "IronPython":
        libastyle.system_exit("IronPython is not currently supported")

    libastyle.set_text_color()
    print(libastyle.get_python_version())

    languages = (
        # "chinese",                    # returns chinese-simplified
        "chinese-simplified",
        "chinese-traditional",
        "czech",
        "danish",
        "dutch",
        "belgian",
        "english",
        "finnish",
        "french",
        "german",
        "greek",
        "hungarian",
        "icelandic",
        "italian",
        "japanese",
        "korean",
        "norwegian",
        "polish",
        "portuguese",
        "russian",
        "slovak",
        "spanish",
        "swedish",
        "turkish",
    )

    # build list of locale names
    locale_names = []
    for language in languages:
        # print language
        try:
            locale.setlocale(locale.LC_ALL, language)
        except locale.Error:
            print("unsupported locale: " + language)
        # print(locale.getlocale(locale.LC_CTYPE))
        locale_name = locale.setlocale(locale.LC_ALL, None)

        locale_names.append(locale_name)
    # sort the list of locale names
    # the call changed with version 3
    if sys.version_info[0] < 3:
        locale_names.sort(sort_compare)
    else:
        locale_names.sort(key=get_codepage)
    # print the list of locale names
    prevoius_codepage = 0
    total1252 = 0
    for locale_name in locale_names:
        codepage = get_codepage(locale_name)
        if codepage == "1252":
            total1252 += 1
        if codepage != prevoius_codepage:
            if prevoius_codepage == "1252":
                print("1252 TOTAL " + str(total1252))
            print()
            prevoius_codepage = codepage
        print(codepage + ' ' + locale_name)
Example #33
0
       if not __file_update the new file will have a .new extension..
    """
    if __file_update:
        orig_file = file_path + ".orig"
        # remove an existing .orig file
        if os.path.isfile(orig_file):
            os.remove(orig_file)
        # rename the current file
        os.rename(file_path, orig_file)
        # write the file
        with open(file_path, mode='w', newline='\r\n') as file_out:
            for line in file_out_list:
                file_out.write(line)
    else:
        new_file = file_path + ".new"
        # remove an existing .new file
        if os.path.isfile(new_file):
            os.remove(new_file)
        # write the new file
        with open(new_file, mode='w', newline='\r\n') as file_out:
            for line in file_out_list:
                file_out.write(line)


# -----------------------------------------------------------------------------

# make the module executable
if __name__ == "__main__":
    main()
    libastyle.system_exit()
Example #34
0
def run_clang_tidy(tidy_exepath, tidy_version, file_name):
    """Run the clang-tidy program for the specified file.
       List of clang-tidy checks:
       https://clang.llvm.org/extra/clang-tidy/checks/list.html
       NOTE: The window stays open only if run from the console.
    """
    # cert-err34-c warns of using atoi errors - astyle_main checks the input length to avoid
    # cert-err58-cpp warns of static storage exceptions for static variables in ASResource
    #
    # to fix one option: (disable checks, add the option, include -fix)
    # clangtidy.append("-checks=-*,readability-implicit-bool-cast")
    # clangtidy.append("-fix")
    #
    tidy_checks = ("-checks=*,"
                   "-cert-err34-c,"
                   "-cert-err58-cpp,"
                   "-cppcoreguidelines-owning-memory,"
                   "-cppcoreguidelines-pro-bounds-array-to-pointer-decay,"
                   "-cppcoreguidelines-pro-bounds-pointer-arithmetic,"
                   "-cppcoreguidelines-pro-type-member-init,"
                   "-cppcoreguidelines-pro-type-vararg,"
                   "-cppcoreguidelines-special-member-functions,"
                   "-fuchsia-default-arguments,"
                   "-google-build-using-namespace,"
                   "-google-readability-braces-around-statements,"
                   "-google-readability-casting,"
                   "-google-readability-todo,"
                   "-google-runtime-references,"
                   "-hicpp-braces-around-statements,"
                   "-hicpp-member-init,"
                   "-hicpp-no-array-decay,"
                   "-hicpp-signed-bitwise,"
                   "-hicpp-special-member-functions,"
                   "-hicpp-use-auto,"
                   "-hicpp-use-noexcept,"
                   "-hicpp-vararg,"
                   "-llvm-header-guard,"
                   "-misc-misplaced-widening-cast,"
                   "-misc-unused-parameters,"
                   "-readability-braces-around-statements,"
                   "-readability-implicit-bool-cast,"
                   "-readability-implicit-bool-conversion,"
                   "-readability-simplify-boolean-expr,"
                   "-modernize-use-auto,"
                   "-modernize-use-noexcept")
    # version 7 checks
    # if tidy_version[:1] > "6":
    #     tidy_checks += (",")

    clangtidy = [tidy_exepath]
    clangtidy.append(tidy_checks)
    clangtidy.append("-header-filter=.*")
    clangtidy.append(__src_dir + file_name)
    clangtidy.append("--")                  # compiler options follow
    clangtidy.append("-std=c++14")          # c++14 minimum is required for clang
    clangtidy.append("-fno-rtti")
    clangtidy.append("-fno-exceptions")
#    clangtidy.append("-DASTYLE_LIB")

    # stdout file must have full path
    filename = __src_dir + "xclang-" + file_name + ".txt"
    outfile = open(filename, 'w')
    print()
    print(file_name)
    # shell=True keeps the console window open, but will not display if run from an editor
    # subprocess.check_call() doesn't work from an editor
    try:
        subprocess.check_call(clangtidy, stdout=outfile)
    except subprocess.CalledProcessError as err:
        libastyle.system_exit("Bad clang-tidy return: " + str(err.returncode))
    except OSError:
        libastyle.system_exit("Cannot find executable: " + clangtidy[0])
Example #35
0
def verify_formatted_files(numformat, totformat):
    """Check that the formatted files list equals the astyle report total.
    """
    if totformat != numformat:
        message = "files != report ({0},{1})".format(numformat, totformat)
        libastyle.system_exit(message)