Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Mon Jun 7 21:50:04 2010
- @author: kevin
- """
- import sys
- import os
- import subprocess
- import tempfile
- import tarfile
- import optparse
- from googlecode_upload import upload
- from time import clock
- import re
- __author__='Kevin Brightwell (Nava2)'
- _project = 'simbareflection'
- if os.name == 'nt':
- dir_sep = '\\'
- else:
- dir_sep = '/'
- _updated = False
- def get_rev():
- '''Calls `svn info` and parses the output from the directory.
- '''
- # call `svn info' to get the rev.
- global _updated
- if not _updated:
- print 'Updating SVN.'
- orig_path = os.getcwd()
- print orig_path
- # move to the head of the repos
- max = 0
- dir = os.getcwd()[str.rfind(os.getcwd(),dir_sep)+1:]
- while not dir == 'Reflection' and max < 5:
- os.chdir('..'+dir_sep)
- dir = os.getcwd()[str.rfind(os.getcwd(),dir_sep)+1:]
- max = max + 1
- p = subprocess.Popen(['svn up'],shell=True)
- # restore the current placement.
- _updated = True
- os.chdir(orig_path)
- p.wait()
- # get the svn info.
- p = subprocess.Popen(['svn info'], stdout=subprocess.PIPE,shell=True)
- p.wait()
- #trim the numbers out of the input.
- rev_string = p.stdout.readlines()[4]
- return rev_string.strip(' Revison:\n');
- def regex_match_arr(p, s, flags=0):
- #print s
- for i in range(len(p)):
- try:
- l = re.findall(p[i],s)
- if l:
- print l
- if re.match(p[i], s, flags=flags):
- print 'Excluding: [%s] %s' % (p[i],s)
- return True
- except:
- print 'ERROR: [%s] %s' % (p[i],s)
- else:
- return False
- def load_config(path='./stable_upload.config',silent=False):
- '''Loads all of the settings in path. Defaults to `./stable_upload.config`.
- Settings are returned as a dict.
- '''
- if not silent:
- print 'Loading config file:',path
- configdict = dict()
- if os.path.isfile(path):
- with file(path, 'r+b') as fobj:
- for l in fobj:
- key,value = l.split('=')
- configdict[key] = value.lstrip('=')[:len(value)-1]
- #print '%s=%s' % (key,value.lstrip('=')[:len(value)-1])
- return configdict
- def save_config(path='.%sstable_upload.config'%dir_sep,silent=False,**settings):
- '''Save settings to a config file. Saves to `./stable_upload.config` by
- default.
- '''
- def sprint(*strs):
- if not silent:
- m = strs[0]
- for i in range(1,len(strs)):
- m = '%s %s' % (m,strs[i])
- print m
- sprint('Saving config file to:',path)
- if os.path.isfile(path):
- sprint('Loading unloaded config definitions.')
- dict = load_config(path=path,silent=True)
- for k in dict.keys():
- if not k in settings.keys():
- settings[k]=dict[k]
- sprint('Removing old config file.')
- os.remove(path)
- with file(path, 'w+b') as fobj:
- for key in sorted(settings.keys()):
- fobj.write('%s=%s\n' % (key, settings[key]))
- #print '%s=%s' % (key, settings[key])
- def tar_repos(exclude_files=None):
- start_path = os.getcwd()
- # create tar object and file object, for archiving
- tmppath = '%s%sReflection_Stable.tar.bz2' % (start_path,dir_sep)
- if os.path.isfile(tmppath):
- tar_exists = True
- os.rename(tmppath,tmppath+'_old')
- print 'Renamed old archive.'
- #Create tar object.
- tar_obj = tarfile.open(name=tmppath, mode='w:bz2')
- print 'Created archive:',tar_obj.name
- #find the reflection folder.
- up=1
- while not os.path.isfile('%s%sReflection'%(os.getcwd(),dir_sep)) and up < 5:
- os.chdir('..'+dir_sep)
- up = up+1
- # make sure .svn is not included.
- if not exclude_files:
- exclude_files = ['^\.svn',tmppath]
- else:
- exclude_files.append('^\.svn')
- exclude_files.append(tmppath)
- # add the reflection files to the .tar.bz2
- print 'Starting tar.'
- t = clock()
- tar_obj.add('.%sReflection%s' % (dir_sep,dir_sep),
- exclude=(lambda x: regex_match_arr(exclude_files,x)))
- print 'Tar Finished. [%rs]' % (clock()-t)
- #restore things.
- os.chdir(start_path)
- tar_obj.close()
- if tar_exists:
- os.remove(tmppath+'_old')
- print 'Removal of old tar was successful: %s.' % (not os.path.isfile(tmppath+'_old'))
- return tmppath
- def upload_file(fileobj,user,passwd,summary,project=_project,labels=None):
- # Upload the stable version
- # check if the fileobj is a file or a path. adjust accordingly.
- if isinstance(fileobj, file):
- path = fileobj.name
- elif isinstance(fileobj, str):
- path = fileobj
- print 'Uploading file %s' % path
- time_mark = clock()
- status,reason,url = upload(path,_project,user,passwd,summary,labels)
- if url:
- print 'File updated (%fs). Link: %s' % (clock()-time_mark,url)
- print '[%s] [%s]' % (reason, status)
- return 1
- else:
- print 'An error occurred. Your file was not uploaded.'
- print 'Google Code upload server said: %s (%s)' % (reason, status)
- return 0
- def update_version_file():
- # Upload the version:
- version = get_rev()
- #Delete the file if its present.
- tmppath = '%s%sReflection_Version' % (os.getcwd(),dir_sep)
- if os.path.isfile(tmppath):
- os.remove(tmppath)
- print 'Removed old version file.'
- #Write the new version into the file.
- with open(tmppath,'w+b') as fobj:
- fobj.write(version)
- #return the path
- return tmppath
- def main():
- '''
- '''
- parser = optparse.OptionParser(usage='update-stable.py');
- parser.add_option('-u', '--username', dest='username',
- help='Your google code username.')
- parser.add_option('-w', '--password', dest='password',
- help='Your google code password.')
- parser.add_option('-e', '--exclude', dest='exclude',
- help='Files to exclude in archive, use ;; as a separator.')
- # parser.add_option('-p', '--path', dest='path',
- # help='Head location for creating tar from.')
- options, args = parser.parse_args()
- config = load_config()
- # set the user and pass depending if they are passed from params.
- if options.username:
- repos_user = options.username
- elif 'username' in config and config['username']:
- repos_user = config['username']
- else:
- repos_user = None
- if options.password:
- repos_pass = options.password
- elif 'password' in config and config['password']:
- repos_pass = config['password']
- else:
- repos_pass = None
- if options.exclude:
- exclude_files = options.exclude.split(';;')
- else:
- exclude_files = []
- #If the repos info is still not set, ask for it.
- if not repos_user:
- repos_user = raw_input('Please input code.google.com user: ')
- if not repos_pass:
- repos_pass = raw_input('Please input code.google.com password: ')
- # create the tar archive.
- tar_path = tar_repos(exclude_files=exclude_files)
- version_path = update_version_file()
- upload_file(tar_path,repos_user,repos_pass,"Current Stable Include")
- upload_file(version_path,repos_user,repos_pass,"Stable Version Information")
- if not 'save_repos_info' in config or not config['save_repos_info']:
- config['save_repos_info'] = raw_input('Save repository user/pass '\
- 'info into config? (y/n)').strip() == 'y'
- if config['save_repos_info']:
- save_config(username=repos_user,password=repos_pass,save_repos_info=True)
- print 'completed.'
- if __name__ == '__main__':
- sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement