Exemplo n.º 1
0
    def complete_adb(self, text, line, begidx, endidx):
        """ auto complete of file name.
        """
        # tmp_line = line.split(' ')
        if not check_input(line, self.adb_match):
            line = line.split(' ')
            # TODO 以后再考虑这块
            if len(line) < 3:
                filename = ''
                path = './'
            else:
                path = line[len(line) - 1]
                if (os.sep in path) and path:
                    i = path.rfind(os.sep)
                    filename = path[i + 1:]
                    path = path[:i]
                else:
                    filename = path
                    path = './'
            ls = dircache.listdir(path)
            ls = ls[:]  # for overwrite in annotate.
            dircache.annotate(path, ls)
            if filename == '':
                del self.adb_match[:]
                self.adb_match = map(deal_coding, ls)
            else:
                del self.adb_match[:]
                for f in ls:
                    try:
                        if f.startswith(filename):
                            self.adb_match.append(deal_coding(f))
                    except UnicodeDecodeError, e:
                        print(e)

            self.tmp_match_count = 0
Exemplo n.º 2
0
def get_environments(environ, warn=False):
    """Retrieve canonical environment name to path mapping.

    The environments may not be all valid environments, but they are good
    candidates.
    """
    env_paths = environ.get('trac.env_paths', [])
    env_parent_dir = environ.get('trac.env_parent_dir')
    if env_parent_dir:
        env_parent_dir = os.path.normpath(env_parent_dir)
        paths = dircache.listdir(env_parent_dir)[:]
        dircache.annotate(env_parent_dir, paths)
        env_paths += [os.path.join(env_parent_dir, project) \
                      for project in paths 
                      if project[-1] == '/' and project != '.egg-cache/']
    envs = {}
    for env_path in env_paths:
        env_path = os.path.normpath(env_path)
        if not os.path.isdir(env_path):
            continue
        env_name = os.path.split(env_path)[1]
        if env_name in envs:
            if warn:
                print >> sys.stderr, ('Warning: Ignoring project "%s" since '
                                      'it conflicts with project "%s"'
                                      % (env_path, envs[env_name]))
        else:
            envs[env_name] = env_path
    return envs
Exemplo n.º 3
0
def get_environments(environ, warn=False):
    """Retrieve canonical environment name to path mapping.

    The environments may not be all valid environments, but they are good
    candidates.
    """
    env_paths = environ.get('trac.env_paths', [])
    env_parent_dir = environ.get('trac.env_parent_dir')
    if env_parent_dir:
        env_parent_dir = os.path.normpath(env_parent_dir)
        paths = dircache.listdir(env_parent_dir)[:]
        dircache.annotate(env_parent_dir, paths)
        env_paths += [os.path.join(env_parent_dir, project) \
                      for project in paths if project[-1] == '/']
    envs = {}
    for env_path in env_paths:
        env_path = os.path.normpath(env_path)
        if not os.path.isdir(env_path):
            continue
        env_name = os.path.split(env_path)[1]
        if env_name in envs:
            if warn:
                print >> sys.stderr, ('Warning: Ignoring project "%s" since '
                                      'it conflicts with project "%s"' %
                                      (env_path, envs[env_name]))
        else:
            envs[env_name] = env_path
    return envs
Exemplo n.º 4
0
 def load_dir(self, cwd):
     self.cwd = cwd
     
     self.dirlist = [".."] + dircache.listdir(u"%s" % cwd)
     dircache.annotate(cwd, self.dirlist)
     
     self.set_caption(" %s : [%s]" % (self.name, cwd))
Exemplo n.º 5
0
def get_environments(environ, warn=False):
    """Retrieve canonical environment name to path mapping.

    The environments may not be all valid environments, but they are
    good candidates.
    """
    env_paths = environ.get('trac.env_paths', [])
    env_parent_dir = environ.get('trac.env_parent_dir')
    if env_parent_dir:
        env_parent_dir = os.path.normpath(env_parent_dir)
        paths = dircache.listdir(env_parent_dir)[:]
        dircache.annotate(env_parent_dir, paths)

        # Filter paths that match the .tracignore patterns
        ignore_patterns = get_tracignore_patterns(env_parent_dir)
        paths = [path[:-1] for path in paths if path[-1] == '/'
                 and not any(fnmatch.fnmatch(path[:-1], pattern)
                             for pattern in ignore_patterns)]
        env_paths.extend(os.path.join(env_parent_dir, project)
                         for project in paths)
    envs = {}
    for env_path in env_paths:
        env_path = os.path.normpath(env_path)
        if not os.path.isdir(env_path):
            continue
        env_name = os.path.split(env_path)[1]
        if env_name in envs:
            if warn:
                print >> sys.stderr, ('Warning: Ignoring project "%s" since '
                                      'it conflicts with project "%s"'
                                      % (env_path, envs[env_name]))
        else:
            envs[env_name] = env_path
    return envs
Exemplo n.º 6
0
def get_environments(ENV_PARENT_DIR, warn=False):
    """Retrieve canonical environment name to path mapping.

    The environments may not be all valid environments, but they are good
    candidates.
    """

    env_paths = []  # Initialize variable

    if ENV_PARENT_DIR:
        ENV_PARENT_DIR = os.path.normpath(ENV_PARENT_DIR)
        paths = dircache.listdir(ENV_PARENT_DIR)[:]
        dircache.annotate(ENV_PARENT_DIR, paths)
        env_paths += [os.path.join(ENV_PARENT_DIR, project) \
                      for project in paths if project[-1] == '/']
    envs = {}
    for env_path in env_paths:
        env_path = os.path.normpath(env_path)
        if not os.path.isdir(env_path):
            continue
        env_name = os.path.split(env_path)[1]
        if env_name in envs:
            if warn:
                print >> sys.stderr, ('Warning: Ignoring project "%s" since '
                                      'it conflicts with project "%s"' %
                                      (env_path, envs[env_name]))
        else:
            envs[env_name] = env_path
    return envs
Exemplo n.º 7
0
def get_environments(ENV_PARENT_DIR, warn=False):
    """Retrieve canonical environment name to path mapping.

    The environments may not be all valid environments, but they are good
    candidates.
    """

    env_paths = []	# Initialize variable

    if ENV_PARENT_DIR:
        ENV_PARENT_DIR = os.path.normpath(ENV_PARENT_DIR)
        paths = dircache.listdir(ENV_PARENT_DIR)[:]
        dircache.annotate(ENV_PARENT_DIR, paths)
        env_paths += [os.path.join(ENV_PARENT_DIR, project) \
                      for project in paths if project[-1] == '/']
    envs = {}
    for env_path in env_paths:
        env_path = os.path.normpath(env_path)
        if not os.path.isdir(env_path):
            continue
        env_name = os.path.split(env_path)[1]
        if env_name in envs:
            if warn:
                print >> sys.stderr, ('Warning: Ignoring project "%s" since '
                                      'it conflicts with project "%s"'
                                      % (env_path, envs[env_name]))
        else:
            envs[env_name] = env_path
    return envs
Exemplo n.º 8
0
    def complete_adb(self, text, line, begidx, endidx):
        """ auto complete of file name.
        """
        # tmp_line = line.split(' ')
        if not check_input(line, self.adb_match):
            line = line.split(' ')
            # TODO 以后再考虑这块
            if len(line) < 3:
                filename = ''
                path = './'
            else:
                path = line[len(line) - 1]
                if (os.sep in path) and path:
                    i = path.rfind(os.sep)
                    filename = path[i + 1:]
                    path = path[:i]
                else:
                    filename = path
                    path = './'
            ls = dircache.listdir(path)
            ls = ls[:]  # for overwrite in annotate.
            dircache.annotate(path, ls)
            if filename == '':
                del self.adb_match[:]
                self.adb_match = map(deal_coding, ls)
            else:
                del self.adb_match[:]
                for f in ls:
                    try:
                        if f.startswith(filename):
                            self.adb_match.append(deal_coding(f))
                    except UnicodeDecodeError, e:
                        print(e)

            self.tmp_match_count = 0
Exemplo n.º 9
0
def open(name):
	name = path.cat(name, '')
	list = dircache.opendir(name)[:]
	list.sort()
	dircache.annotate(name, list)
	w = listwin.open(name, list)
	w.name = name
	w.action = action
	return w
Exemplo n.º 10
0
def open(name):
       name = path.cat(name, '')
       list = dircache.opendir(name)[:]
       list.sort()
       dircache.annotate(name, list)
       w = listwin.open(name, list)
       w.name = name
       w.action = action
       return w
Exemplo n.º 11
0
	def getMembers(self):
		"""Get immediate members of this collection."""
		l = dircache.listdir(self.fsname)[:] # obtain a copy of dirlist
		dircache.annotate(self.fsname, l)
		r = []
		for f in l:
			if f[-1] != '/':
				m = FileMember(f, self) # Member is a file
			else:
				m = DirCollection(self.fsname + f, self.virname + f, self) # Member is a collection
			r.append(m)
		return r
Exemplo n.º 12
0
def get_toolkit_names(dir):
    toolkits = []
    listing = dircache.listdir(dir)
    dircache.annotate(dir, listing)
    for toolkit in listing:
        if toolkit.endswith(".py") and toolkit != "__init__.py":
            toolkits.append(toolkit[:-3])
        elif toolkit.endswith("module.so"):
            toolkits.append(toolkit[:-9])
        elif (toolkit.endswith("/") and "__init__.py" in dircache.listdir(
                os.path.join(dir, toolkit))):
            toolkits.append(toolkit[:-1])
    return toolkits
Exemplo n.º 13
0
def get_toolkit_names(dir):
    toolkits = []
    listing = dircache.listdir(dir)
    dircache.annotate(dir, listing)
    for toolkit in listing:
        if toolkit.endswith(".py") and toolkit != "__init__.py":
            toolkits.append(toolkit[:-3])
        elif toolkit.endswith("module.so"):
            toolkits.append(toolkit[:-9])
        elif (toolkit.endswith("/") and
              "__init__.py" in dircache.listdir(os.path.join(dir, toolkit))):
            toolkits.append(toolkit[:-1])
    return toolkits
Exemplo n.º 14
0
	def findMember(self, name):
		"""Search for a particular member."""
		l = dircache.listdir(self.fsname)[:] # obtain a copy of dirlist
		dircache.annotate(self.fsname, l)
		print "%s - %s, find %s" % (self.fsname, repr(l), name)

		if name in l:
			if name[-1] != '/':
				return FileMember(name, self)
			else:
				return DirCollection(self.fsname + name, self.virname + name, self)
		elif name[-1] != '/':
			name += '/'
			if name in l:
				return DirCollection(self.fsname + name, self.virname + name, self)
Exemplo n.º 15
0
def chooseFile(dir):
  	dircache.reset()
  	list = dircache.listdir(dir)
  	dircache.annotate(dir, list )
 	if list == []:
		print 'restarting'
		return chooseFile('C:\Users\iharrison\publicprint')
 	else: 
 		filename = random.choice(list)
 		path = os.path.join(dir, filename)
	if path[-1] == '/':	
		path = path[:-1]
		return chooseFile(path)
	else:
 		return path
Exemplo n.º 16
0
def diffdata(a, b, flags):  # Compute directory differences.
    #
    a_only = [("A only:", header_action), ("", header_action)]
    b_only = [("B only:", header_action), ("", header_action)]
    ab_diff = [("A <> B:", header_action), ("", header_action)]
    ab_same = [("A == B:", header_action), ("", header_action)]
    data = [a_only, b_only, ab_diff, ab_same]
    #
    a_list = dircache.listdir(a)[:]
    b_list = dircache.listdir(b)[:]
    dircache.annotate(a, a_list)
    dircache.annotate(b, b_list)
    a_list.sort()
    b_list.sort()
    #
    for x in a_list:
        if x in ["./", "../"]:
            pass
        elif x not in b_list:
            a_only.append((x, a_only_action))
        else:
            ax = os.path.join(a, x)
            bx = os.path.join(b, x)
            if os.path.isdir(ax) and os.path.isdir(bx):
                if flags == "-r":
                    same = dircmp(ax, bx)
                else:
                    same = 0
            else:
                try:
                    same = cmp.cmp(ax, bx)
                except (RuntimeError, os.error):
                    same = 0
            if same:
                ab_same.append((x, ab_same_action))
            else:
                ab_diff.append((x, ab_diff_action))
                #
    for x in b_list:
        if x in ["./", "../"]:
            pass
        elif x not in a_list:
            b_only.append((x, b_only_action))
            #
    return data
Exemplo n.º 17
0
def diffdata(a, b, flags): # Compute directory differences.
	#
	a_only = [('A only:', header_action), ('', header_action)]
	b_only = [('B only:', header_action), ('', header_action)]
	ab_diff = [('A <> B:', header_action), ('', header_action)]
	ab_same = [('A == B:', header_action), ('', header_action)]
	data = [a_only, b_only, ab_diff, ab_same]
	#
	a_list = dircache.listdir(a)[:]
	b_list = dircache.listdir(b)[:]
	dircache.annotate(a, a_list)
	dircache.annotate(b, b_list)
	a_list.sort()
	b_list.sort()
	#
	for x in a_list:
		if x in ['./', '../']:
			pass
		elif x not in b_list:
			a_only.append(x, a_only_action)
		else:
			ax = os.path.join(a, x)
			bx = os.path.join(b, x)
			if os.path.isdir(ax) and os.path.isdir(bx):
				if flags == '-r':
					same = dircmp(ax, bx)
				else:
					same = 0
			else:
				try:
					same = cmp.cmp(ax, bx)
				except (RuntimeError, os.error):
					same = 0
			if same:
				ab_same.append(x, ab_same_action)
			else:
				ab_diff.append(x, ab_diff_action)
	#
	for x in b_list:
		if x in ['./', '../']:
			pass
		elif x not in a_list:
			b_only.append(x, b_only_action)
	#
	return data
Exemplo n.º 18
0
def read_config(file_path):
    """
    Lee la configuracion de "min_pines.cfg" y devuelve un
    diccionario con los valores leidos "Nombre":num_entero.
    """
    config = ConfigParser.RawConfigParser()
    config.read(file_path)
    parsed_config = {}

    for (name, value) in config.items("config"):
        parsed_config[name] = str(value)

    parsed_config["interval_min"] = int(parsed_config["interval_min"])

    hour =  int(parsed_config["daily_send_hour"].split(":")[0])
    min =  int(parsed_config["daily_send_hour"].split(":")[1])
    parsed_config["daily_send_hour"] = datetime.time(hour, min)

    hour =  int(parsed_config["weekly_send_hour"].split(":")[0])
    min =  int(parsed_config["weekly_send_hour"].split(":")[1])
    parsed_config["weekly_send_hour"] = datetime.time(hour, min)

    week_days = ["Mon", "Tue", "Wen", "Thu", "Fri", "Sat", "Sun"]
    parsed_config["weekly_send_day"] = week_days.index(
                                            parsed_config["weekly_send_day"])

    if not os.path.isdir(parsed_config["stock_dir"]):
        raise IOError("Stock dir erroneus")

    available_files = dircache.listdir(parsed_config["stock_dir"])
    available_files = available_files[:]
    dircache.annotate(parsed_config["stock_dir"], available_files)
    available_dirs = [ item[:-1] for item in available_files if '/' in item]
    parsed_config["min_pines"] = {}
    for (name, value) in config.items("num_min_pines"):
        parsed_config["min_pines"][name] = int(value)
        if name not in available_dirs:
            raise KeyError("Config name without dir")

    if len(available_dirs) != len(parsed_config["min_pines"]):
        raise KeyError("Dir without definition in config file")
    return parsed_config
Exemplo n.º 19
0
    def complete_read(self, text, line, start_idx, end_idx):
        line = line.split()
        if len(line) < 2:
            filename = ''
            path = './'
        else:
            path = line[1]
            if '/' in path:
                i = path.rfind('/')
                filename = path[i + 1:]
                path = path[:i]
            else:
                filename = path
                path = './'

        ls = dircache.listdir(path)
        ls = ls[:]
        dircache.annotate(path, ls)
        if filename == '':
            return ls
        else:
            return [f for f in ls if f.startswith(filename)]
Exemplo n.º 20
0
    def on_cboSearchDirectoryEntry_changed(self, entry):
        text = entry.get_text()
        if text and self._autoCompleteList != None:
            path = os.path.dirname(text)
            start = os.path.basename(text)

            self._autoCompleteList.clear()
            try:
                files = dircache.listdir(path)[:]
            except OSError:
                return
            dircache.annotate(path, files)
            for f in files:
                if f.startswith(".") and not (start.startswith(".")):
                    # show hidden dirs only if explicitly requested by user
                    continue
                if f.startswith(start) and f.endswith("/"):
                    if path == "/":
                        match = path + f
                    else:
                        match = path + os.sep + f
                    self._autoCompleteList.append([match])
Exemplo n.º 21
0
    def on_cboSearchDirectoryEntry_changed(self, entry):
        text = entry.get_text()
        if text and self._autoCompleteList != None:
            path = os.path.dirname(text)
            start = os.path.basename(text)

            self._autoCompleteList.clear()
            try:
                files = dircache.listdir(path)[:]
            except OSError:
                return
            dircache.annotate(path, files)
            for f in files:
                if f.startswith(".") and not (start.startswith(".")):
                    # show hidden dirs only if explicitly requested by user
                    continue
                if f.startswith(start) and f.endswith("/"):
                    if path == "/":
                        match = path + f
                    else:
                        match = path + os.sep + f
                    self._autoCompleteList.append([match])
Exemplo n.º 22
0
def comp_path(text, line, begidx, endidx):
    """ auto complete for file name and path. """
    line = line.split()
    if len(line) < 2:
        filename = ''
        path = './'
    else:
        path = line[1]
        if '/' in path:
            i = path.rfind('/')
            filename = path[i + 1:]
            path = path[:i]
        else:
            filename = path
            path = './'

    ls = dircache.listdir(path)
    ls = ls[:]  # for overwrite in annotate.
    dircache.annotate(path, ls)
    if filename == '':
        return ls
    else:
        return [f for f in ls if f.startswith(filename)]
Exemplo n.º 23
0
 def completedefault(self,text, line, begidx, endidx):
     """ auto complete of file name
         Note:Needs fixing if path start from root
     """
     line = line.split()
     if len(line) < 2:
         filename = ''
         path = './'
     else:
         path = line[1]
         if '/' in path:
             i = path.rfind('/')
             filename = path[i+1:]
             path = path[:i]
         else:
             filename = path
             path = './'
     ls = dircache.listdir(path)
     ls = ls[:] # for overwrite in annotate.
     dircache.annotate(path, ls)
     if filename == '':
         return ls
     else:
         return [f for f in ls if f.startswith(filename)]
Exemplo n.º 24
0
def get_environments(environ, warn=False):
    """Retrieve canonical environment name to path mapping.

    The environments may not be all valid environments, but they are
    good candidates.
    """
    env_paths = environ.get('trac.env_paths', [])
    env_parent_dir = environ.get('trac.env_parent_dir')
    if env_parent_dir:
        env_parent_dir = os.path.normpath(env_parent_dir)
        paths = dircache.listdir(env_parent_dir)[:]
        dircache.annotate(env_parent_dir, paths)

        # Filter paths that match the .tracignore patterns
        ignore_patterns = get_tracignore_patterns(env_parent_dir)
        paths = [
            path[:-1] for path in paths if path[-1] == '/' and not any(
                fnmatch.fnmatch(path[:-1], pattern)
                for pattern in ignore_patterns)
        ]
        env_paths.extend(
            os.path.join(env_parent_dir, project) for project in paths)
    envs = {}
    for env_path in env_paths:
        env_path = os.path.normpath(env_path)
        if not os.path.isdir(env_path):
            continue
        env_name = os.path.split(env_path)[1]
        if env_name in envs:
            if warn:
                print('Warning: Ignoring project "%s" since it conflicts with'
                      ' project "%s"' % (env_path, envs[env_name]),
                      file=sys.stderr)
        else:
            envs[env_name] = env_path
    return envs
Exemplo n.º 25
0
def traverseTree(dirName):
    """ Recursively traverses the directory outputting ngc files """

    try:
        direct = dircache.listdir(dirName)
        dircache.annotate(dirName, direct)
        #print "direct OK", dirName, direct

    except IOError:
        #print "direct NG", dirName
        return

    # now traverse the children one at a time

    # for each child that is a directory
    for d in direct[:]:
        # print "---", d
        # if a directory, recurse
        if d[-1] == '/':
            traverseTree(dirName + d)
        # if an ngc file, append to the output
        elif d[-4:] == '.ngc':
            print "(from wizard:", dirName + d, ")"
            copyFile(dirName + d)
Exemplo n.º 26
0
 def test_annotate(self):
     self.writeTemp("test2")
     self.mkdirTemp("A")
     lst = ['A', 'test2', 'test_nonexistent']
     dircache.annotate(self.tempdir, lst)
     self.assertEquals(lst, ['A/', 'test2', 'test_nonexistent'])
Exemplo n.º 27
0
#! /us/bin/env/python
# -*- coding:utf-8 -*-

import dircache
from pprint import pprint
import os

path = '../../'

contents = dircache.listdir(path)
annotated = contents[:]
dircache.annotate(path, annotated)

fmt = '%25s\t%25s'

print fmt % ('ORIGINAL', 'ANNOTATED')
print fmt % (('-' * 25, ) * 2)
for o, a in zip(contents, annotated):
    print fmt % (o, a)
Exemplo n.º 28
0
	def main(self):
		# order is important here. setup_window must be setup first! Likewise with font
		self.win = self.setup_window()
		ft = self.setup_font()
		
		self.root = Tkinter.Tk()
		self.root.withdraw()
		
		if (sys.platform != "win32") and hasattr(sys, 'frozen'):
			self.root.tk.call('console', 'hide')
					
		if len(sys.argv) < 2:
			dirname = tkFileDialog.askdirectory(parent=self.root,initialdir="~",title='Please select a directory')
						
			if len(dirname ) > 0:
				import dircache
				ls = dircache.listdir(dirname)
				ls = list(ls)
				dircache.annotate(dirname, ls)
				
				self.files = ["%s%s%s"%(dirname,os.path.sep,e) for e in ls if not e.endswith('/')]
			else:
				sys.exit(1)
		else:		
			self.files = sys.argv[1:]
				
		self.win.set_visible()
		self.setup_trash()	
		
		assert self.win != None
		assert ft != None
		
		# generate our oft used black background
		image_pattern = pyglet_image.SolidColorImagePattern((0,0,0,255))
	
		# load the resizer graphic
		resizer = image_to_psurf(Image.open('resizer.jpg'))

	
		# start loading files
		self.win.set_visible()
		self.unloaded = list(self.files)
		self.update_renderables()
		print "loading %d files"%(len(self.unloaded))
		start_time = time.time()
		while not self.win.has_exit:
			time_passed = clock.tick()
			
			self.win.dispatch_events()
			glClear(GL_COLOR_BUFFER_BIT)
			
			if len(self.unloaded) > 0:
				f = self.unloaded.pop()
				t = font.Text(ft, self.to_unicode(f), config.text_yoffset, config.text_yoffset)
				t.draw()			
				#win.flip()
				
				self.load_file(f)
				
				if len(self.unloaded) %3 == 0:
					self.update_renderables(sort=False)

				if len(self.unloaded) == 0:
					print "loading took %f seconds"%(time.time()-start_time)
					
					# limit fps to reduce cpu usage
					clock.set_fps_limit(config.fps)
			else:
				# raise Exception
				pass
			
			# if we need to display a full image, do so
			if self.display_picture != None:
				w = self.display_picture.width
				h = self.display_picture.height
				self.display_picture.blit((self.win.width-w)/2,(self.win.height-h)/2)
				self.win.flip()
				continue
			
			# adjust the xoffset if required 		
			if self.xmotion < 0:
				if self.strip_width() + self.xoffset > self.win.width:
					self.xoffset+=self.xmotion * time_passed / config.xmotion_time 
					
			if self.xmotion > 0:
				if self.xoffset < 0:
					self.xoffset+=self.xmotion * time_passed / config.xmotion_time 

			# clamp xoffset to 0 if xoffset is > 0
			self.xoffset = min(self.xoffset, 0)
			
			# render the tiles
			x = self.xoffset 
			y = self.yoffset
			pix_name = None
			pix_size = None
			drawn = 0
			self.hovering_over = None
			blit_position = ()
			for filename, image in self.renderables:
				img = image[0]
				
				if ( x >= -config.crop_size and x < self.win.width):
					img.blit(x,y)				
					
					# if the cursor is over this tile, render some information
					if self.is_over_image(x,y,self.hoverx, self.hovery) and (not pix_name or filename != pix_name.text):
						# draw some information
						pix_size = font.Text(ft,"%dx%d"%(image[1][0], image[1][1]), x, y+config.text_yoffset)
						pix_name = font.Text(ft, self.to_unicode(os.path.basename(filename)), x, y+config.text_yoffset+int(pix_size.height))						
						
						# calculate the black background required to make text show up
						# width needs to be in integer multiples of tile size
						w = max(pix_size.width, pix_name.width)
						w = max(config.crop_size, (w/config.crop_size+1)*config.crop_size)
							
						w = int(w)
						h = int(pix_name.height+pix_size.height+config.text_yoffset)
						text_bg = image_pattern.create_image(w,h)
						blit_position=(x, y)
					
						# remember which image we are hovering over so when a click is seen
						# we know which image to display 
						self.hovering_over = filename

				drawn+=1
				y-=config.crop_size
				
				if drawn % self.rows == 0:
					x+=config.crop_size
					y = self.yoffset

			# everything drawn here is drawn over everything else
			if self.fps_display:
				self.fps_display.draw()
			
			if self.hovering_over:
				text_bg.blit(blit_position[0], blit_position[1])
				pix_name.draw()
				pix_size.draw()
		
			w = self.win.width
			w = w - resizer.width
			resizer.blit(w,0)

			self.win.flip()
Exemplo n.º 29
0
def menu(screen):
    bgimage = pygame.image.load("gfx/menu.png")
    main = ["New game", "Custom Level", "Quit"]
    levels = dircache.listdir('levels/')
    buttons = main
    dircache.annotate('levels/', levels)
    button_height = 37
    menu_margin = 30

    offset = 0
    clevel = False
    update = True

    fgcolor = 0, 0, 0
    #bgcolor = 0, 0, 0

    menuhover = -1

    font = pygame.font.SysFont("Bitstream Vera Sans", 24)

    labels = []
    for button in buttons:
        labels.append(font.render(button, 1, fgcolor))

    while True:
        event = pygame.event.wait()
        if update:
            update = False
            labels = []
            if clevel:
                i = offset * 8
                labels.append(font.render("Return to main menu", 1, fgcolor))
                labels.append(font.render("Previous page", 1, fgcolor))
                while i < (1 + offset) * 8:
                    if i < len(levels):
                        labels.append(font.render(levels[i], 1, fgcolor))
                    else:
                        labels.append(font.render("(empty)", 1, fgcolor))
                    i += 1
                labels.append(font.render("Next page", 1, fgcolor))
            else:
                for choices in main:
                    labels.append(font.render(choices, 1, fgcolor))

        if event.type == pygame.VIDEOEXPOSE:
            screen.blit(bgimage, (0, 0))

            for i in range(len(labels)):
                screen.blit(labels[i],
                            (menu_margin, i * button_height + menu_margin))
            if menuhover != -1:
                rect = labels[menuhover].get_rect()
                rect[0] += menu_margin - 4
                rect[1] += menu_margin + menuhover * button_height - 3
                rect[2] += 8
                rect[3] += 6
                pygame.draw.rect(screen, (255, 0, 0), rect, 3)

            pygame.display.update()
            pygame.event.clear(pygame.VIDEOEXPOSE)

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                sys.exit(0)
            elif event.key == pygame.K_RETURN:
                return 1, "levels/level"

        elif event.type == pygame.MOUSEBUTTONDOWN:
            for i in range(len(labels)):
                rect = labels[i].get_rect()
                if (event.pos[0] < rect[2] + menu_margin
                        and event.pos[0] > menu_margin
                        and event.pos[1] > menu_margin + i * button_height
                        and event.pos[1] < menu_margin +
                    (i + 1) * button_height):
                    if clevel:
                        if i == 0:
                            clevel = False
                            update = True
                        elif i == 1:
                            if offset != 0:
                                offset -= 1
                                update = True
                        elif i == 10:
                            update = True
                            offset += 1
                        else:
                            if i + offset * 6 - 2 < len(levels):
                                return 1, "levels/" + levels[offset * 6 + i -
                                                             2]
                    else:
                        if i == 0:
                            return 1, "levels/level"
                        elif i == 1:
                            clevel = True
                            update = True
                        elif i == 2:
                            return -1, ""
        elif event.type == pygame.MOUSEMOTION:
            menuhover = -1
            for i in range(len(labels)):
                rect = labels[i].get_rect()
                if (event.pos[0] < rect[2] + menu_margin
                        and event.pos[0] > menu_margin
                        and event.pos[1] > menu_margin + i * button_height
                        and event.pos[1] < menu_margin +
                    (i + 1) * button_height):
                    menuhover = i
Exemplo n.º 30
0
 def test_annotate(self):
     self.writeTemp("test2")
     self.mkdirTemp("A")
     lst = ["A", "test2", "test_nonexistent"]
     dircache.annotate(self.tempdir, lst)
     self.assertEquals(lst, ["A/", "test2", "test_nonexistent"])
Exemplo n.º 31
0
Arquivo: dir.py Projeto: knaka/src
#!/usr/bin/python

import dircache
path = "/etc/"
files = dircache.listdir(path)
dircache.annotate(path, files)
files = map(lambda file: path + file, files)
print files

Exemplo n.º 32
0
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import dircache

salida=open("haz.bat","w")
salida.write("@echo off\ndel *.com\ndel gag.asm\ndel messages.msg\n\ncopy .\src\gag.asm .\gag.asm\n\n")

directories=dircache.listdir("src/")
directories2=directories[:]
dircache.annotate("src/",directories2)
for elemento in directories2:
	if elemento[-1]=="/":
		elem=elemento[:-1]
		salida.write("copy .\\src\\"+elem+"\\messages.msg .\\\n")
		salida.write("copy .\\src\\"+elem+"\\font.fnt .\\\n")
		salida.write("tasm gag.asm\n")
		salida.write("tlink /t gag.obj\n")
		salida.write("del *.obj\n")
		salida.write("del *.map\n")
		salida.write("del messages.msg\n")
		salida.write("del font.fnt\n")
		salida.write("ren gag.com "+elem+".com\n\n")

salida.write("tasm src\\boot.asm\ntlink /t boot.obj\ntasm src\\install.asm\ntlink /t install.obj\n\n")
salida.write("tasm src\\hdboot.asm\ntlink /t hdboot.obj\n\n")
Exemplo n.º 33
0
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""

__version__ = "$Id: dircache_annotate.py 1882 2009-01-04 15:38:33Z dhellmann $"
#end_pymotw_header

import dircache
from pprint import pprint

path = '../../trunk'

contents = dircache.listdir(path)

annotated = contents[:]
dircache.annotate(path, annotated)

fmt = '%20s\t%20s'

print fmt % ('ORIGINAL', 'ANNOTATED')
print fmt % (('-' * 20,)*2)

for o, a in zip(contents, annotated):
    print fmt % (o, a)
Exemplo n.º 34
0
def main(argv):
    global settings, tmpdir, CONFIGDIR

    scriptdir = os.path.abspath(os.path.dirname(argv[0]))

    # Read Configuration File
    cfg = ConfigParser.ConfigParser(settings)
    cfg.read([os.path.join(scriptdir, "testrunner.cfg")])

    # getConfig - embedded function to wrap loading configuration settings w/defaults
    # -------------------------------------------------------------------------------
    # string getConfig(string sect, string opt, string default) {
    def getConfig(sect, opt, default):
        try:
            global settings
            val = cfg.get(sect, opt, False, settings)
            return val
        except:
            return default

    # } // End of getConfig()

    # Setup Global Settings
    #  - settings that begin with an underscore (i.e. _testrunner_name) are for internal use and are not intended for
    #    use as variables in test_list configuration files
    settings[
        "default_app"] = ""  # App is defined later, since values like builddir can be modified by cmdline settings
    settings["builddir"] = getConfig("testrunner", "builddir", "build")
    settings["mode"] = getConfig("testrunner", "mode", "local")
    settings["scm"] = getConfig("testrunner", "scm", "none")

    settings["git"] = getConfig("git", "cmd", "git")
    settings["git_submodule"] = getConfig("git", "submodule", "")

    settings["svn"] = getConfig("svn", "cmd", "svn")
    settings["svnversion"] = getConfig("svn", "svnversion", "svnversion")
    settings["svnmetadir"] = getConfig("svn", "metadir", ".svn")

    settings["testdir"] = getConfig("testrunner", "testdir", "tests")

    settings["_testrunner_name"] = "testrunner.py"

    settings["perf_user_margin"] = float(
        getConfig("performance", "usermargin", .05))
    settings["perf_wall_margin"] = float(
        getConfig("performance", "wallmargin", .05))
    settings["perf_repeat"] = int(getConfig("performance", "repeat", 5))

    settings["cpus"] = 1

    settings["diff-max-threshold"] = 1536

    # Process Command Line Arguments
    try:
        opts, args = getopt.getopt(argv[1:], "fhj:lm:pg:s:v", \
          ["diff-max-threshold=","builddir=", "force-perf", "help", "help-test-cfg", "ignore-consistency", "list-tests", "long-tests", \
           "mode=", "scm=", "reset-expected", "reset-perf-base", "run-perf-tests", "show-diff", "skip-tests", "git=", "svnmetadir=", "svn=", "svnversion=", \
           "testdir=", "verbose", "version", "xml-report=", "-testrunner-name="])
    except getopt.GetoptError:
        usage()
        return -1

    # Define Option Flags
    opt_forceperf = False
    opt_ignoreconsistency = False
    opt_listtests = False
    opt_long = False
    opt_runperf = False
    opt_showhelp = False
    opt_showtestcfg = False
    opt_showversion = False

    # Process Supplied Options
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            opt_showhelp = True
        elif opt == "--builddir":
            settings["builddir"] = arg
        elif opt == "--diff-max-threshold":
            settings["diff-max-threshold"] = arg
        elif opt == "--help-test-cfg":
            opt_showtestcfg = True
        elif opt == "-j":
            cpus = int(arg)
            if cpus < 1: cpus = 1
            settings["cpus"] = cpus
        elif opt == "--scm":
            settings["scm"] = arg
        elif opt in ("-f", "--force-perf"):
            opt_forceperf = True
        elif opt == "--ignore-consistency":
            opt_ignoreconsistency = True
        elif opt in ("-l", "--list-tests"):
            opt_listtests = True
        elif opt == "--long-tests":
            opt_long = True
        elif opt in ("-m", "--mode"):
            settings["mode"] = arg
        elif opt == "--reset-expected":
            settings["_reset_expected"] = ""
        elif opt == "--reset-perf-base":
            settings["_reset_perf_base"] = ""
        elif opt in ("-p", "--run-perf-tests"):
            opt_runperf = True
        elif opt == "--show-diff":
            settings["show-diff"] = ""
        elif opt == "--skip-tests":
            settings["skip-tests"] = ""
        elif opt in ("-g", "--git"):
            settings["git"] = arg
        elif opt == "--svnmetadir":
            settings["svnmetadir"] = arg
        elif opt in ("-s", "--svn"):
            settings["svn"] = arg
        elif opt == "--svnversion":
            settings["svnversion"] = arg
        elif opt == "--testdir":
            settings["testdir"] = arg
        elif opt in ("-v", "--verbose"):
            settings["_verbose"] = ""
        elif opt == "--version":
            opt_showversion = True
        elif opt == "--xml-report":
            settings["xml_report"] = arg
        elif opt == "---testrunner-name":
            settings["_testrunner_name"] = arg

    # Show help or version and exit, if requested to do so
    if opt_showhelp or opt_showtestcfg or opt_showversion:
        if opt_showversion: version()
        if opt_showhelp: usage()
        if opt_showtestcfg: sample_test_list()
        return 0

    # Get the path to the test directory
    testdir = os.path.abspath(getConfig("main", "testdir", "."))
    settings["testdir"] = testdir

    # Re-read Configuration File with filled settings
    cfg = ConfigParser.ConfigParser(settings)
    cfg.read([os.path.join(scriptdir, "testrunner.cfg")])

    # Load the default app to test
    try:
        settings["default_app"] = os.path.abspath(cfg.get("main", "app"))
    except:
        print "Warning: No default app configured"

    if settings["scm"] == "git":
        settings["scm"] = SCMWrapper_Git()
    elif settings["scm"] == "svn":
        settings["scm"] = SCMWrapper_SVN()
    elif settings["scm"] == "none":
        settings["scm"] = SCMWrapper_None()
    else:
        print "Error: Unsupported SCM '%s'" % (settings["scm"])
        return -1

    # Load in all tests
    print "Reading Test Configurations:\n"
    tests = []

    prefix_filter = ["."]
    dlist = []
    if len(args) != 0:
        for d in dircache.listdir(testdir):
            for a in args:
                if fnmatch.fnmatch(d, a):
                    dlist.append(d)
                    break

    else:
        dlist = dircache.listdir(testdir)
        prefix_filter.append("_")

    dircache.annotate(testdir, dlist)
    for d in dlist:
        # Directories with preceeding underscore or period are ignored, as are files
        if d[0] in prefix_filter or d[len(d) - 1] != "/": continue

        name = d[:len(d) - 1]
        curtdir = os.path.join(testdir, name)
        contents = dircache.listdir(curtdir)
        if CONFIGDIR in contents:
            test = cTest(name, curtdir)
            test.describe()
            tests.append(test)

    # If selected, display available tests and exit
    if opt_listtests:
        return 0

    # Make temp directory to hold active tests
    tmpdir = tempfile.mkdtemp("_testrunner")

    success = 0
    disabled = 0
    fail = 0

    try:
        # Run Consistency Tests
        csuccess = 0
        cdisabled = 0
        cfail = 0
        if (not opt_runperf or not opt_ignoreconsistency):
            (csuccess, cdisabled, cfail) = runConsistencyTests(tests, opt_long)
            success += csuccess
            disabled += cdisabled
            fail += cfail

        # Run Performance Tests
        psuccess = 0
        pdisabled = 0
        pfail = 0
        if (opt_ignoreconsistency or fail == 0) and opt_runperf:
            (psuccess, pdisabled,
             pfail) = runPerformanceTests(tests, opt_long, opt_forceperf,
                                          not opt_ignoreconsistency)
            success += psuccess
            disabled += pdisabled
            fail += pfail

        if settings.has_key("xml_report"):
            f = open(settings["xml_report"], "w")
            f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            f.write(
                "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" time=\"0\" name=\"AllTests\">\n"
                % (success + disabled + fail, fail, disabled))

            f.write(
                "  <testsuite name=\"ConsistencyTests\" tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" time=\"0\">\n"
                % (csuccess + cdisabled + cfail, cfail, cdisabled))
            for test in tests:
                if test.isConsistencyTest():
                    (tsuccess, message) = test.getConsistencyResults()
                    run = "run"
                    if test.wasConsistencySkipped(): run = "disabled"
                    if not tsuccess:
                        f.write(
                            "    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\">\n"
                            % (test.getName(), run))
                        f.write("      <failure message=\"%s\" type=\"\"/>\n" %
                                (message))
                        f.write("    </testcase>\n")
                    else:
                        f.write(
                            "    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\"/>\n"
                            % (test.getName(), run))
            f.write("  </testsuite>\n")

            if (opt_ignoreconsistency or fail == 0) and opt_runperf:
                f.write(
                    "  <testsuite name=\"PerformanceTests\" tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" time=\"0\">\n"
                    % (psuccess + pdisabled + pfail, pfail, pdisabled))
                for test in tests:
                    if test.isPerformanceTest():
                        (tsuccess, message) = test.getPerformanceResults()
                        run = "run"
                        if test.wasPerformanceSkipped(): run = "disabled"
                        if not tsuccess:
                            f.write(
                                "    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\">\n"
                                % (test.getName(), run))
                            f.write(
                                "      <failure message=\"%s\" type=\"\"/>\n" %
                                (message))
                            f.write("    </testcase>\n")
                        else:
                            f.write(
                                "    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\"/>\n"
                                % (test.getName(), run))
                f.write("  </testsuite>\n")

            f.write("</testsuites>\n")
            f.close()

        # Clean up test directory
        try:
            shutil.rmtree(tmpdir, True)
        except (IOError, OSError):
            pass

        if fail == 0:
            print "\nAll tests passed."
            return 0
        else:
            if disabled != 0:
                print "\n%d of %d tests failed (%d disabled)." % (
                    fail, fail + disabled + success, disabled)
            else:
                print "\n%d of %d tests failed." % (fail, fail + success)
            return fail
    except (KeyboardInterrupt):
        print "\nInterrupted... Terminanting Tests."
Exemplo n.º 35
0
def main(screen):
    bgimage = pygame.image.load("gfx/menu.png")
    main = ["New game", "Custom Level", "Level Editor", "Quit."]
    levels = dircache.listdir('levels/')
    buttons = main
    dircache.annotate('levels/', levels)
    button_height = 37
    menu_margin = 30

    offset = 0
    clevel = False
    edit = False
    update = True

    fgcolor = 255, 255, 255
    #bgcolor = 0, 0, 0

    menuhover = -1

    font = pygame.font.SysFont("Bitstream Vera Sans", 24)

    labels = []
    for button in buttons:
        labels.append(font.render(button, 1, fgcolor))

    while True:
        event = pygame.event.wait()
        if update:
            update = False
            labels = []
            if clevel:
                i = offset*8
                labels.append(font.render("Return to main menu", 1, fgcolor))
                labels.append(font.render("Previous page", 1, fgcolor))
                while i < (1+offset)*8:
                    if i < len(levels):
                        labels.append(font.render(levels[i], 1, fgcolor))
                    else:
                        labels.append(font.render("(empty)", 1, fgcolor))
                    i += 1
                labels.append(font.render("Next page", 1, fgcolor))
            else:
                for choices in main:
                    labels.append(font.render(choices, 1, fgcolor))

        if event.type == pygame.VIDEOEXPOSE:
            screen.blit(bgimage, (0,0))

            for i in range(len(labels)):
                screen.blit(labels[i], (menu_margin, i * button_height + menu_margin))
            if menuhover != -1:
                rect = labels[menuhover].get_rect()
                rect[0] += menu_margin - 4
                rect[1] += menu_margin + menuhover * button_height - 3
                rect[2] += 8
                rect[3] += 6
                pygame.draw.rect(screen, (255,0,0), rect, 3)

            pygame.display.update()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                sys.exit(0)

        elif event.type == pygame.MOUSEBUTTONDOWN:
            for i in range(len(labels)):
                rect = labels[i].get_rect()
                if (event.pos[0] < rect[2] + menu_margin and event.pos[0] > menu_margin and event.pos[1] > menu_margin + i*button_height and event.pos[1] < menu_margin + (i+1)*button_height):
                    if clevel:
                        if i == 0:
                            clevel = False
                            update = True
                        elif i == 1:
                            if offset != 0:
                                offset -= 1
                                update = True
                        elif i == 10:
                            update = True
                            offset += 1
                        else:
                            if i+offset*6 - 2 < len(levels):
                                if "/" in levels[offset*6+i-2]:
                                    returnlist = ["levels/" + levels[offset*6+i-2] + x for x in dircache.listdir("levels/"+ levels[offset*6+i-2] )]

                                else:
                                    returnlist = ["levels/" + levels[offset*6+i-2]]
                                return edit, returnlist
                    else:
                        if i == 0:
                            return False, ["levels/campaign/" + x for x in dircache.listdir("levels/campaign/")]
                        elif i == 1:
                            clevel = True
                            edit = False
                            update = True
                        elif i == 2:
                            edit = True
                            clevel = True
                            update = True
                        elif i == 3:
                            sys.exit(0)
        elif event.type == pygame.MOUSEMOTION:
            menuhover = -1
            for i in range(len(labels)):
                rect = labels[i].get_rect()
                if (event.pos[0] < rect[2] + menu_margin and event.pos[0] > menu_margin and event.pos[1] > menu_margin + i*button_height and event.pos[1] < menu_margin + (i+1)*button_height):
                    menuhover = i
Exemplo n.º 36
0
def main(argv):
    global settings, tmpdir, CONFIGDIR

    scriptdir = os.path.abspath(os.path.dirname(argv[0]))

    # Read Configuration File
    cfg = ConfigParser.ConfigParser(settings)
    cfg.read([os.path.join(scriptdir, "testrunner.cfg")])

    # getConfig - embedded function to wrap loading configuration settings w/defaults
    # -------------------------------------------------------------------------------
    # string getConfig(string sect, string opt, string default) {
    def getConfig(sect, opt, default):
        try:
            global settings
            val = cfg.get(sect, opt, False, settings)
            return val
        except:
            return default
    # } // End of getConfig()

    # Setup Global Settings
    #  - settings that begin with an underscore (i.e. _testrunner_name) are for internal use and are not intended for
    #    use as variables in test_list configuration files
    # App is defined later, since values like builddir can be modified by
    # cmdline settings
    settings["default_app"] = ""
    settings["builddir"] = getConfig("testrunner", "builddir", "build")
    settings["mode"] = getConfig("testrunner", "mode", "local")
    settings["scm"] = getConfig("testrunner", "scm", "none")

    settings["git"] = getConfig("git", "cmd", "git")
    settings["git_submodule"] = getConfig("git", "submodule", "")

    settings["svn"] = getConfig("svn", "cmd", "svn")
    settings["svnversion"] = getConfig("svn", "svnversion", "svnversion")
    settings["svnmetadir"] = getConfig("svn", "metadir", ".svn")

    settings["testdir"] = getConfig("testrunner", "testdir", "tests")

    settings["_testrunner_name"] = "testrunner.py"

    settings["perf_user_margin"] = float(
        getConfig("performance", "usermargin", .05))
    settings["perf_wall_margin"] = float(
        getConfig("performance", "wallmargin", .05))
    settings["perf_repeat"] = int(getConfig("performance", "repeat", 5))

    settings["cpus"] = 1

    settings["diff-max-threshold"] = 1536

    # Process Command Line Arguments
    try:
        opts, args = getopt.getopt(argv[1:], "fhj:lm:pg:s:v",
                                   ["diff-max-threshold=", "builddir=", "force-perf", "help", "help-test-cfg", "ignore-consistency", "list-tests", "long-tests",
                                    "mode=", "scm=", "reset-expected", "reset-perf-base", "run-perf-tests", "show-diff", "skip-tests", "git=", "svnmetadir=", "svn=", "svnversion=",
                                    "testdir=", "verbose", "version", "xml-report=", "-testrunner-name="])
    except getopt.GetoptError:
        usage()
        return -1

    # Define Option Flags
    opt_forceperf = False
    opt_ignoreconsistency = False
    opt_listtests = False
    opt_long = False
    opt_runperf = False
    opt_showhelp = False
    opt_showtestcfg = False
    opt_showversion = False

    # Process Supplied Options
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            opt_showhelp = True
        elif opt == "--builddir":
            settings["builddir"] = arg
        elif opt == "--diff-max-threshold":
            settings["diff-max-threshold"] = arg
        elif opt == "--help-test-cfg":
            opt_showtestcfg = True
        elif opt == "-j":
            cpus = int(arg)
            if cpus < 1:
                cpus = 1
            settings["cpus"] = cpus
        elif opt == "--scm":
            settings["scm"] = arg
        elif opt in ("-f", "--force-perf"):
            opt_forceperf = True
        elif opt == "--ignore-consistency":
            opt_ignoreconsistency = True
        elif opt in ("-l", "--list-tests"):
            opt_listtests = True
        elif opt == "--long-tests":
            opt_long = True
        elif opt in ("-m", "--mode"):
            settings["mode"] = arg
        elif opt == "--reset-expected":
            settings["_reset_expected"] = ""
        elif opt == "--reset-perf-base":
            settings["_reset_perf_base"] = ""
        elif opt in ("-p", "--run-perf-tests"):
            opt_runperf = True
        elif opt == "--show-diff":
            settings["show-diff"] = ""
        elif opt == "--skip-tests":
            settings["skip-tests"] = ""
        elif opt in ("-g", "--git"):
            settings["git"] = arg
        elif opt == "--svnmetadir":
            settings["svnmetadir"] = arg
        elif opt in ("-s", "--svn"):
            settings["svn"] = arg
        elif opt == "--svnversion":
            settings["svnversion"] = arg
        elif opt == "--testdir":
            settings["testdir"] = arg
        elif opt in ("-v", "--verbose"):
            settings["_verbose"] = ""
        elif opt == "--version":
            opt_showversion = True
        elif opt == "--xml-report":
            settings["xml_report"] = arg
        elif opt == "---testrunner-name":
            settings["_testrunner_name"] = arg

    # Show help or version and exit, if requested to do so
    if opt_showhelp or opt_showtestcfg or opt_showversion:
        if opt_showversion:
            version()
        if opt_showhelp:
            usage()
        if opt_showtestcfg:
            sample_test_list()
        return 0

    # Get the path to the test directory
    testdir = os.path.abspath(getConfig("main", "testdir", "."))
    settings["testdir"] = testdir

    # Re-read Configuration File with filled settings
    cfg = ConfigParser.ConfigParser(settings)
    cfg.read([os.path.join(scriptdir, "testrunner.cfg")])

    # Load the default app to test
    try:
        settings["default_app"] = os.path.abspath(cfg.get("main", "app"))
    except:
        print "Warning: No default app configured"

    if settings["scm"] == "git":
        settings["scm"] = SCMWrapper_Git()
    elif settings["scm"] == "svn":
        settings["scm"] = SCMWrapper_SVN()
    elif settings["scm"] == "none":
        settings["scm"] = SCMWrapper_None()
    else:
        print "Error: Unsupported SCM '%s'" % (settings["scm"])
        return -1

    # Load in all tests
    print "Reading Test Configurations:\n"
    tests = []

    prefix_filter = ["."]
    dlist = []
    if len(args) != 0:
        for d in dircache.listdir(testdir):
            for a in args:
                if fnmatch.fnmatch(d, a):
                    dlist.append(d)
                    break

    else:
        dlist = dircache.listdir(testdir)
        prefix_filter.append("_")

    dircache.annotate(testdir, dlist)
    for d in dlist:
        # Directories with preceeding underscore or period are ignored, as are
        # files
        if d[0] in prefix_filter or d[len(d) - 1] != "/":
            continue

        name = d[:len(d) - 1]
        curtdir = os.path.join(testdir, name)
        contents = dircache.listdir(curtdir)
        if CONFIGDIR in contents:
            test = cTest(name, curtdir)
            test.describe()
            tests.append(test)

    # If selected, display available tests and exit
    if opt_listtests:
        return 0

    # Make temp directory to hold active tests
    tmpdir = tempfile.mkdtemp("_testrunner")

    success = 0
    disabled = 0
    fail = 0

    try:
        # Run Consistency Tests
        csuccess = 0
        cdisabled = 0
        cfail = 0
        if (not opt_runperf or not opt_ignoreconsistency):
            (csuccess, cdisabled, cfail) = runConsistencyTests(tests, opt_long)
            success += csuccess
            disabled += cdisabled
            fail += cfail

        # Run Performance Tests
        psuccess = 0
        pdisabled = 0
        pfail = 0
        if (opt_ignoreconsistency or fail == 0) and opt_runperf:
            (psuccess, pdisabled, pfail) = runPerformanceTests(
                tests, opt_long, opt_forceperf, not opt_ignoreconsistency)
            success += psuccess
            disabled += pdisabled
            fail += pfail

        if settings.has_key("xml_report"):
            f = open(settings["xml_report"], "w")
            f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            f.write("<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" time=\"0\" name=\"AllTests\">\n" % (
                success + disabled + fail, fail, disabled))

            f.write("  <testsuite name=\"ConsistencyTests\" tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" time=\"0\">\n" % (
                csuccess + cdisabled + cfail, cfail, cdisabled))
            for test in tests:
                if test.isConsistencyTest():
                    (tsuccess, message) = test.getConsistencyResults()
                    run = "run"
                    if test.wasConsistencySkipped():
                        run = "disabled"
                    if not tsuccess:
                        f.write("    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\">\n" % (
                            test.getName(), run))
                        f.write(
                            "      <failure message=\"%s\" type=\"\"/>\n" % (message))
                        f.write("    </testcase>\n")
                    else:
                        f.write(
                            "    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\"/>\n" % (test.getName(), run))
            f.write("  </testsuite>\n")

            if (opt_ignoreconsistency or fail == 0) and opt_runperf:
                f.write("  <testsuite name=\"PerformanceTests\" tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" time=\"0\">\n" % (
                    psuccess + pdisabled + pfail, pfail, pdisabled))
                for test in tests:
                    if test.isPerformanceTest():
                        (tsuccess, message) = test.getPerformanceResults()
                        run = "run"
                        if test.wasPerformanceSkipped():
                            run = "disabled"
                        if not tsuccess:
                            f.write("    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\">\n" % (
                                test.getName(), run))
                            f.write(
                                "      <failure message=\"%s\" type=\"\"/>\n" % (message))
                            f.write("    </testcase>\n")
                        else:
                            f.write(
                                "    <testcase name=\"%s\" status=\"%s\" time=\"0\" classname=\"ConsistencyTests\"/>\n" % (test.getName(), run))
                f.write("  </testsuite>\n")

            f.write("</testsuites>\n")
            f.close()

        # Clean up test directory
        try:
            shutil.rmtree(tmpdir, True)
        except (IOError, OSError):
            pass

        if fail == 0:
            print "\nAll tests passed."
            return 0
        else:
            if disabled != 0:
                print "\n%d of %d tests failed (%d disabled)." % (fail, fail + disabled + success, disabled)
            else:
                print "\n%d of %d tests failed." % (fail, fail + success)
            return fail
    except (KeyboardInterrupt):
        print "\nInterrupted... Terminanting Tests."
Exemplo n.º 37
0
 def generate(self, rsp):
     contents = dircache.listdir(self.filename)[:]
     dircache.annotate(self.filename, contents)
     rsp.data = Template('<html><head><title>Listing of ${dirname}</title></head>'
                         '<body><h1>Listing of <tt>${dirname}</tt></h1><ul><% for d in contents %><li><a href="${d}">${d}</a></li><% endfor %></ul></body></html>'
                         ).render(dirname=self.filename, contents=contents)
Exemplo n.º 38
0
	def on_key_press(self,symbol, modifier):
		if symbol == key.LEFT:
			self.xmotion = 10
					
		if symbol == key.RIGHT:
			self.xmotion -= 10

		if modifier == key.MOD_SHIFT:
			self.xmotion*=4

		if self.hovering_over != None:
			if symbol == key.D:
				assert self.images.has_key(self.hovering_over)
				del self.images[self.hovering_over]
				self.update_renderables()
				shutil.move(self.hovering_over, "%s/%s"%(os.path.basename(self.hovering_over),config.trash_dir))
				self.last_deleted.append(self.hovering_over)
				
				self.display_picture = None
			
		if symbol == key.U and len(self.last_deleted) > 0:
			self.last = self.last_deleted.pop()
			shutil.move("%s/%s"%(config.trash_dir, os.path.basename(last)), self.last)
			self.load_file(last)
			self.update_renderables()
			
		if symbol == key.F:
			if self.fps_display:
				self.fps_display = None
			else:
				self.fps_display = clock.ClockDisplay()		
				
		if symbol == key.C:
			self.cluster_renderables()
			
		if symbol == key.W and modifier == key.MOD_CTRL:
			sys.exit(0)
			
		if symbol == key.Q and modifier == key.MOD_COMMAND:
			sys.exit(0)
			
		if symbol == key.Q:
			sys.exit(0)
		
		if symbol == key.V:
			self.toggle_full_view()
			
		if symbol == key.S:
			if self.hovering_over != None:
				print "sorting by %s"%(self.hovering_over)
				self.selected = self.images[self.hovering_over]
				self.renderables_key_func = self.sort_func
				self.update_renderables()
				self.xoffset = 0
		
		if symbol == key.O:
			dirname = tkFileDialog.askdirectory(parent=self.root,initialdir="~",title='Please select a directory')

			if len(dirname ) > 0:
				import dircache
				ls = dircache.listdir(dirname)
				ls = list(ls)
				dircache.annotate(dirname, ls)

				files = ["%s%s%s"%(dirname,os.path.sep,e) for e in ls if not e.endswith('/')]
				self.unloaded = list(files)
				
				self.images = dict()
					
		if symbol == key.R:
			self.unloaded = list(files)
			self.images = dict()
Exemplo n.º 39
0
Arquivo: dir.py Projeto: dot-Sean/src
#!/usr/bin/python

import dircache

path = "/etc/"
files = dircache.listdir(path)
dircache.annotate(path, files)
files = map(lambda file: path + file, files)
print files
Exemplo n.º 40
0
 def test_annotate(self):
     self.writeTemp("test2")
     self.mkdirTemp("A")
     lst = ['A', 'test2', 'test_nonexistent']
     dircache.annotate(self.tempdir, lst)
     self.assertEquals(lst, ['A/', 'test2', 'test_nonexistent'])
Exemplo n.º 41
0
"""
Exemplo n.º 42
0
Arquivo: main.py Projeto: jun66j5/TraM
def dispatch_request(environ, start_response):
    """Main entry point for the Trac web interface.
    
    @param environ: the WSGI environment dict
    @param start_response: the WSGI callback for starting the response
    """
    if 'mod_python.options' in environ:
        options = environ['mod_python.options']
        environ.setdefault('trac.env_path', options.get('TracEnv'))
        environ.setdefault('trac.env_parent_dir', options.get('TracEnvParentDir'))
        environ.setdefault('trac.env_index_template', options.get('TracEnvIndexTemplate'))
        environ.setdefault('trac.template_vars', options.get('TracTemplateVars'))
        environ.setdefault('trac.locale', options.get('TracLocale'))

        if 'TracUriRoot' in options:
            # Special handling of SCRIPT_NAME/PATH_INFO for mod_python, which
            # tends to get confused for whatever reason
            root_uri = options['TracUriRoot'].rstrip('/')
            request_uri = environ['REQUEST_URI'].split('?', 1)[0]
            if not request_uri.startswith(root_uri):
                raise ValueError('TracUriRoot set to %s but request URL '
                                 'is %s' % (root_uri, request_uri))
            environ['SCRIPT_NAME'] = root_uri
            environ['PATH_INFO'] = urllib.unquote(request_uri[len(root_uri):])

    else:
        environ.setdefault('trac.env_path', os.getenv('TRAC_ENV'))
        environ.setdefault('trac.env_parent_dir',
                           os.getenv('TRAC_ENV_PARENT_DIR'))
        environ.setdefault('trac.env_index_template',
                           os.getenv('TRAC_ENV_INDEX_TEMPLATE'))
        environ.setdefault('trac.template_vars',
                           os.getenv('TRAC_TEMPLATE_VARS'))
        environ.setdefault('trac.locale', '')

    locale.setlocale(locale.LC_ALL, environ['trac.locale'])

    env_parent_dir = environ.get('trac.env_parent_dir')
    env_paths = environ.get('trac.env_paths', [])
    import dircache
    paths = dircache.listdir(env_parent_dir)[:]
    dircache.annotate(env_parent_dir, paths)
    env_paths += [os.path.join(env_parent_dir, project) \
                  for project in paths 
                  if project[-1] == '/' and project != '.egg-cache/']


    # Determine the environment
    env_path = environ.get('trac.env_path')
    req = Request(environ, start_response)

    if not env_path:
        if env_parent_dir or env_paths:
            try:
                # The first component of the path is the base name of the
                # environment
                path_info = environ.get('PATH_INFO', '').lstrip('/').split('/')
                env_name = path_info.pop(0)
                if env_name == '':
                    env_name = 'all'
                if env_name == 'all':
                    try:
                        # go on...                       
                        #req = Request(environ, start_response)
                        dispatcher = TramRequestDispatcher(get_allenv(environ, req))
                        dispatcher.dispatch(environ, start_response, env_parent_dir, env_paths, req)
                    except RequestDone, e:
                        return req._response or []
                    #except Exception, e:
                        #raise Exception(e)

                if env_name == 'chrome':
                    env_name = 'all'
                    path_info.insert(0,'chrome')

                # here we send tram chrome, denoted by using the chrome/tram/ parent
                possible_tram_chrome = '/'.join(path_info)
                if (possible_tram_chrome.startswith('chrome/tram/')):
                    file = possible_tram_chrome[12:]
                    path = os.path.dirname(__file__) + "/htdocs/" + file
                    if (os.path.isfile(path)):
                        #req = Request(environ, start_response)
                        try:
                            req.send_file(path, mimeview.get_mimetype(path))
                        except RequestDone, e:
                            return req._response or [];
                    else:
                        raise HTTPNotFound('File %s not found', file)

                if not env_name:
                    # We need to be in the 'all' environment for the auth cookies etc

                    #req = Request(environ, start_response)
                    req.redirect(req.abs_href() + '/all')

            except HTTPException, e:
                #req = Request(environ, start_response)
                prepare_request(req, environ)
                loadpaths = []
                loadpaths.insert(0, os.path.dirname(__file__) + "/templates/")
                data = {
                        'title': e.reason or 'Error',
                        'type': 'TracError',
                        #'message': e.message
                        'message': e.reason or 'Error'
                }
                try:
                    req.send_error(sys.exc_info(), status=e.code, env=Environment(env_path), data=data)
                except RequestDone, e:
                    return []
Exemplo n.º 43
0
def FileDirChooser(Prompt, Mode="f", Exts=(),startdir=os.getcwd()+'/'):
    """Asks the user to browse for a file or directory.

    Prompt - The string the user will be prompted with. A colon is always added to its end.

    Optional:
        Mode - 'f' or 'd' depending on whether the user is to select a file or directory.
               Default is 'f' for files.
        Exts - A tuple containing the extensions (without periods) of the types of files the
               user will be able to select. Default is an empty tuple for any extension."""
    
    if Mode != "f" and Mode != "d":
        raise ValueError, "Mode must be 'f' or 'd', not: "+`Mode`
    if platform.count("unix") or platform.count("linux") or platform.count("gnu")\
       or platform.count("sun"):
        Dir = startdir#~" Check if "~" works on unix
    else:
        Dir = startdir
    while True:
        Dir = Dir.replace("\\","/")
        Contents = listdir(Dir)
        annotate(Dir,Contents)
        Contents.sort()
        DescrObjs = [(Item,Item) for Item in Contents if _FileDirNameChk(Item, Exts)]
        if Dir != "/":
            DescrObjs.append(("Go Up One Directory Level",1))
        DescrObjs.append(("Create a New Subdirectory",2))
        if platform == "win32":
            DescrObjs.append(("Go to Your Desktop",3))
            DescrObjs.append(("Go to Shared Desktop",4))
            DescrObjs.append(("Go to My Documents",5))
            DescrObjs.append(("Go to C:\\",6))
            DescrObjs.append(("Go to A:\\",7))
            DescrObjs.append(("Go to Another Drive",8))
        DescrObjs.append(("Cancel",9))
        FileDir = RadioButtons(Prompt, DescrObjs, "Current Directory", Dir)
        if FileDir == 9:
            FileDir = -1
            break
        elif FileDir == 1:
            Dir = "/".join( Dir.split("/")[:-2] )+"/"
            continue
        elif FileDir == 2:
            NewDir = Dir+TextEntry("Enter a name for the new directory")+"/"
            try:
                mkdir(NewDir)
                Dir = NewDir
            except EnvironmentError:
                pass
            continue
        elif FileDir == 3:
            Dir = "/Documents and Settings/"+getuser()+"/Desktop/"
            continue
        elif FileDir == 4:
            Dir = "/Documents and Settings/All Users/Desktop/"
            continue
        elif FileDir == 5:
            Dir = "/Documents and Settings/"+getuser()+"/My Documents/"
            continue
        elif FileDir == 6:
            Dir = "C:/"
            continue
        elif FileDir == 7:
            try:
                d = listdir("A:/")
                Dir = "A:/"
            except EnvironmentError:
                pass
            continue
        elif FileDir == 8:
            NewDir = TextEntry("Enter the drive letter(s)")+":/"
            try:
                if exists(NewDir):
                    Dir = NewDir
            except WindowsError:
                pass
            continue
        elif Mode == "d" and FileDir[-1] == "/":
            Action = RadioButtons("Choose an action",( ("Browse in this Directory",1),("Select this Directory",2) ))
            if Action == 1:
                Dir = Dir+FileDir
                continue
            elif Action == 2:
                break
        elif FileDir[-1] == "/":
            Dir = Dir+FileDir
            continue
        else:
            break
    if FileDir==-1: return FileDir
    return Dir+FileDir