Advertisement
Guest User

Untitled

a guest
May 30th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.12 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Jun  7 21:50:04 2010
  4.  
  5. @author: kevin
  6. """
  7.  
  8. import sys
  9. import os
  10. import subprocess
  11. import tempfile
  12. import tarfile
  13. import optparse
  14. from googlecode_upload import upload
  15. from time import clock
  16. import re
  17.  
  18. __author__='Kevin Brightwell (Nava2)'
  19.  
  20. _project = 'simbareflection'
  21.  
  22. if os.name == 'nt':
  23.     dir_sep = '\\'
  24. else:
  25.     dir_sep = '/'
  26.  
  27. _updated = False
  28. def get_rev():
  29.     '''Calls `svn info` and parses the output from the directory.
  30.    '''
  31.     # call `svn info' to get the rev.
  32.     global _updated
  33.     if not _updated:
  34.         print 'Updating SVN.'
  35.         orig_path = os.getcwd()
  36.         print orig_path
  37.        
  38.         # move to the head of the repos
  39.         max = 0
  40.         dir = os.getcwd()[str.rfind(os.getcwd(),dir_sep)+1:]
  41.         while not dir == 'Reflection' and max < 5:
  42.             os.chdir('..'+dir_sep)
  43.             dir = os.getcwd()[str.rfind(os.getcwd(),dir_sep)+1:]
  44.             max = max + 1
  45.            
  46.         p = subprocess.Popen(['svn up'],shell=True)
  47.         # restore the current placement.
  48.         _updated = True
  49.         os.chdir(orig_path)
  50.         p.wait()
  51.        
  52.     # get the svn info.
  53.     p = subprocess.Popen(['svn info'], stdout=subprocess.PIPE,shell=True)
  54.     p.wait()
  55.    
  56.     #trim the numbers out of the input.
  57.     rev_string = p.stdout.readlines()[4]
  58.     return rev_string.strip(' Revison:\n');
  59.        
  60. def regex_match_arr(p, s, flags=0):
  61.     #print s
  62.     for i in range(len(p)):
  63.         try:
  64.             l = re.findall(p[i],s)
  65.             if l:
  66.                 print l
  67.             if re.match(p[i], s, flags=flags):
  68.                 print 'Excluding: [%s] %s' % (p[i],s)
  69.                 return True
  70.         except:
  71.             print 'ERROR: [%s] %s' % (p[i],s)
  72.     else:
  73.         return False
  74.  
  75. def load_config(path='./stable_upload.config',silent=False):
  76.     '''Loads all of the settings in path. Defaults to `./stable_upload.config`.
  77.    Settings are returned as a dict.
  78.    '''
  79.     if not silent:
  80.         print 'Loading config file:',path
  81.    
  82.     configdict = dict()
  83.     if os.path.isfile(path):
  84.         with file(path, 'r+b') as fobj:
  85.             for l in fobj:
  86.                 key,value = l.split('=')
  87.                 configdict[key] = value.lstrip('=')[:len(value)-1]
  88.                 #print '%s=%s' % (key,value.lstrip('=')[:len(value)-1])
  89.    
  90.     return configdict
  91.            
  92. def save_config(path='.%sstable_upload.config'%dir_sep,silent=False,**settings):
  93.     '''Save settings to a config file. Saves to `./stable_upload.config` by
  94.    default.
  95.    '''
  96.     def sprint(*strs):
  97.         if not silent:
  98.             m = strs[0]
  99.             for i in range(1,len(strs)):
  100.                 m = '%s %s' % (m,strs[i])
  101.             print m
  102.    
  103.     sprint('Saving config file to:',path)
  104.    
  105.     if os.path.isfile(path):
  106.         sprint('Loading unloaded config definitions.')
  107.         dict = load_config(path=path,silent=True)
  108.         for k in dict.keys():
  109.             if not k in settings.keys():
  110.                 settings[k]=dict[k]
  111.         sprint('Removing old config file.')
  112.         os.remove(path)
  113.    
  114.     with file(path, 'w+b') as fobj:
  115.         for key in sorted(settings.keys()):
  116.             fobj.write('%s=%s\n' % (key, settings[key]))
  117.             #print '%s=%s' % (key, settings[key])
  118.  
  119. def tar_repos(exclude_files=None):
  120.     start_path = os.getcwd()
  121.    
  122.     # create tar object and file object, for archiving
  123.     tmppath = '%s%sReflection_Stable.tar.bz2' % (start_path,dir_sep)
  124.     if os.path.isfile(tmppath):
  125.         tar_exists = True
  126.         os.rename(tmppath,tmppath+'_old')
  127.         print 'Renamed old archive.'
  128.    
  129.     #Create tar object.
  130.     tar_obj = tarfile.open(name=tmppath, mode='w:bz2')
  131.     print 'Created archive:',tar_obj.name
  132.    
  133.     #find the reflection folder.
  134.     up=1
  135.     while not os.path.isfile('%s%sReflection'%(os.getcwd(),dir_sep)) and up < 5:
  136.       os.chdir('..'+dir_sep)
  137.       up = up+1
  138.    
  139.     # make sure .svn is not included.
  140.     if not exclude_files:
  141.         exclude_files = ['^\.svn',tmppath]
  142.     else:
  143.         exclude_files.append('^\.svn')
  144.         exclude_files.append(tmppath)
  145.    
  146.     # add the reflection files to the .tar.bz2
  147.     print 'Starting tar.'
  148.     t = clock()
  149.     tar_obj.add('.%sReflection%s' % (dir_sep,dir_sep),
  150.                 exclude=(lambda x: regex_match_arr(exclude_files,x)))
  151.     print 'Tar Finished. [%rs]' % (clock()-t)
  152.    
  153.     #restore things.
  154.     os.chdir(start_path)
  155.     tar_obj.close()
  156.    
  157.     if tar_exists:
  158.         os.remove(tmppath+'_old')
  159.         print 'Removal of old tar was successful: %s.' % (not os.path.isfile(tmppath+'_old'))
  160.    
  161.     return tmppath
  162.  
  163.  
  164. def upload_file(fileobj,user,passwd,summary,project=_project,labels=None):
  165.     # Upload the stable version
  166.    
  167.     # check if the fileobj is a file or a path. adjust accordingly.
  168.     if isinstance(fileobj, file):
  169.         path = fileobj.name
  170.     elif isinstance(fileobj, str):
  171.         path = fileobj
  172.        
  173.     print 'Uploading file %s' % path
  174.     time_mark = clock()
  175.    
  176.     status,reason,url = upload(path,_project,user,passwd,summary,labels)
  177.  
  178.     if url:
  179.         print 'File updated (%fs). Link: %s' % (clock()-time_mark,url)
  180.         print '[%s] [%s]' % (reason, status)
  181.         return 1
  182.     else:
  183.         print 'An error occurred. Your file was not uploaded.'
  184.         print 'Google Code upload server said: %s (%s)' % (reason, status)
  185.         return 0
  186.    
  187. def update_version_file():
  188.     # Upload the version:
  189.     version = get_rev()
  190.    
  191.     #Delete the file if its present.
  192.     tmppath = '%s%sReflection_Version' % (os.getcwd(),dir_sep)
  193.     if os.path.isfile(tmppath):
  194.         os.remove(tmppath)
  195.         print 'Removed old version file.'
  196.    
  197.     #Write the new version into the file.
  198.     with open(tmppath,'w+b') as fobj:
  199.         fobj.write(version)
  200.    
  201.     #return the path
  202.     return tmppath
  203.    
  204. def main():
  205.     '''
  206.    '''
  207.     parser = optparse.OptionParser(usage='update-stable.py');
  208.     parser.add_option('-u', '--username', dest='username',
  209.                       help='Your google code username.')
  210.     parser.add_option('-w', '--password', dest='password',
  211.                       help='Your google code password.')
  212.     parser.add_option('-e', '--exclude', dest='exclude',
  213.                       help='Files to exclude in archive, use ;; as a separator.')
  214.    # parser.add_option('-p', '--path', dest='path',
  215.    #                   help='Head location for creating tar from.')
  216.    
  217.     options, args = parser.parse_args()
  218.    
  219.     config = load_config()
  220.      
  221.     # set the user and pass depending if they are passed from params.  
  222.     if options.username:
  223.         repos_user = options.username
  224.     elif 'username' in config and config['username']:
  225.         repos_user = config['username']
  226.     else:
  227.         repos_user = None
  228.    
  229.     if options.password:
  230.         repos_pass = options.password
  231.     elif 'password' in config and config['password']:
  232.         repos_pass = config['password']
  233.     else:
  234.         repos_pass = None
  235.    
  236.     if options.exclude:
  237.         exclude_files = options.exclude.split(';;')
  238.     else:
  239.         exclude_files = []
  240.    
  241.     #If the repos info is still not set, ask for it.
  242.     if not repos_user:
  243.         repos_user = raw_input('Please input code.google.com user: ')
  244.     if not repos_pass:
  245.         repos_pass = raw_input('Please input code.google.com password: ')
  246.  
  247.     # create the tar archive.
  248.     tar_path = tar_repos(exclude_files=exclude_files)
  249.     version_path = update_version_file()
  250.    
  251.     upload_file(tar_path,repos_user,repos_pass,"Current Stable Include")
  252.     upload_file(version_path,repos_user,repos_pass,"Stable Version Information")
  253.    
  254.     if not 'save_repos_info' in config or not config['save_repos_info']:
  255.         config['save_repos_info'] = raw_input('Save repository user/pass '\
  256.                                               'info into config? (y/n)').strip() == 'y'
  257.    
  258.     if config['save_repos_info']:
  259.         save_config(username=repos_user,password=repos_pass,save_repos_info=True)
  260.    
  261.     print 'completed.'
  262.    
  263.    
  264. if __name__ == '__main__':
  265.     sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement