Python Basic Learning: SVN export diff File script

Source: Internet
Author: User
Tags diff

Because it is just contact with Python soon, so many are not very skilled, can only be used to what enumeration. So if there is any bug or not rigorous grammar or other, I hope you will correct me.

In view of the company's platform development department needs to direct SVN in the difference code export and packaging automatically uploaded to the specified server, and then a release from the specified server on the update. Because our development and publishing server environment is very special, the middle of a lot of network agents involved. That's why it's so troublesome.

Requirements are as follows:

1. Automatically export the diff file between the specified versions

2. Filter out the specified folders and files according to the given options, for example, given option A, only the contents of the admin are retained in the exported file.

3. Automatically package these contents and name them according to the current time

4. Uploading to the specified server in FTP mode


Mainly in Windows operation these, really can't think of any good method, so the network search for help. The network is a magical thing, of course, I still did not search for any results. So add some script of the group, randomly find an administrator asked if there is no relevant script or ideas. It's despair. The first one to ask the friend gave me an answer. Python can take care of it (certainly more than that).

So now I'm learning Python, and by the way it's done (in fact, I don't know what to do with it)


After several Google, Baidu. The following script has been written, and the test is currently available to meet the basic requirements:

Python's environmental needs: PY32-PYSVN, python-3.2

PYSVN Download official website: http://pysvn.tigris.org/

Python's official website is not available.

Paste the code below:

#-*- coding: utf-8 -*-#!/usr/bin/env python# ======================================== ============================## svnchanged_export.py## export files in a revision  range# usage: python script_name.py -r beginrev:endrev [ --username  user --password passwd ] svnurl site_version_name (a/s/p) # a [admin]  s [static] p [platform]## ========================================================== ==========import pysvn # http://pysvn.tigris.org/import getopt, time, string,  sys, shutilimport os, urllib, tarfile, getpassimport unicodedatafrom  urllib.parse import urlparsefrom ftplib import ftp# options by  Defaultdate_folder=time.strftime (R "%y%m%d%h%m%s",  time.localtime ()) site_version= "P" #targetPath  =   "."  # currenT directoryexport_dir= "xxxx" # change into a folder you want to  export, the store path relative to the scriptusername =  "" password =  "url = " "ftp_host=" xxx.xxx.xxx.xxx "ftp_port=xxxftp_user= ' xxxx ' ftp_pass= ' xxxx ' Revision_min = pysvn. Revision ( pysvn.opt_revision_kind.number, 0 ) revision_max = pysvn. Revision ( pysvn.opt_revision_kind.head ) hasrevision = falsecurrent_dir =  OS.GETCWD () Os.chdir (R '%s/%s '  % (OS.GETCWD (), Export_dir)) Os.makedirs (R '%s '  % (date_folder)) Os.chdir ('.. /') targetpath= (r "%s\%s")  %  (Export_dir,date_folder) Try:    optlist, args  = getopt.getopt  (sys.argv[1:],  "r:u:p:",                                     ["revision=",  "username=",  "password="])     if  len (args)  == 1 or len (args)  == 2:         url = args[0]        if len (args)  ==  2:             #targetPath  = args[1 ]            SITE_VERSION = ARGS[1]     else:        raise Exception  ("Input  url [site_version] ")             for  option, value in optlist:        if option  ==  "--username"  or option ==  "U":             username = value                     elif option ==  "--password"  or option ==   "-P":             password = value         elif option ==  "--revision"  or option  ==  "-R":             revision =  value            if str.find (Value,   ":")  >= 0:                  (revision_min0, revision_max0)  = str.split (value,  ":")                  revision_min = pysvn. Revision ( pysvn.opt_reviSion_kind.number, int (revision_min0)  )                  if revision_max0 !=  "HEAD":                     revision_max =  pysvn. Revision ( pysvn.opt_revision_kind.number, int (revision_max0)  )                  hasRevision = True             else:                 raise Exception  ("please input  revision range  " + str (option))         else:             raise Exception  ("unknown  option  " + STR (option))                  if hasRevision == False:        raise  exception  ("Please input revision range -r min:max")               #urlObject  = urlparse (URL)     # if urlobject.scheme ==  ' http '  or urlObject.scheme ==  ' https ':     #    url = urlobject.scheme+ "://" +urlobject.netloc+urllib.quote ( UrlObject.path.decode (sys.stdin.encoding). Encode (' UTF8 '))      #else:          #url  = unicode (url, sys.stdin.encoding)     # print  (sys.stdin.encoding)     # print (URL)     if not  url.endswith ("/"):   &NBsp;     url = url +  "/"                  except getopt.error as reason: raise  exception ("usage: "  + sys.argv[0] +  ": "  + str (reason)) f_list=[] F_list=os.listdir (TargetPath)  for f in f_list:    f_path=os.path.join ( TARGETPATH, F)     if os.path.isfile (F_path):         os.remove (F_path)         print  (f_path+ " removed .")     else:        shutil.rmtree (F_path)          print  (f_path+  " removed.") print  (targetpath+ " is already empty.")     def get_login (realm,user,may_save):     return true, username, password, false   print  ("SVN Path:" +url+ "     ' + ' Diff file path: "+targetpath) client = pysvn. Client () if username !=  ""  and password !=  "":     Client.callback_get_login = get_loginsummary = client.diff_summarize (Url, revision_ Min, url, revision_max) #print  summaryfor changed in summary:      #path, summarize_kind, node_kind, prop_changed     #for  key  In changed.iterkeys ():    #    print key          if pysvn.diff_summarize_kind.delete == changed[' Summarize_ Kind ']:      fullpath = targetpath+ '/' +changed[' path ']          if os.paTh.exists (FullPath):         os.remove (FullPath)          if pysvn.diff_summarize_kind.added == changed[' Summarize_kind ']  or pysvn.diff_summarize_kind.modified == changed[' Summarize_kind ']:         print  (changed[' summarize_kind '], changed[' path ')          if changed[' Node_kind '] == pysvn.node_kind.file:                           #uniPath  = changed[' path '].decode (' UTF8 '). Encode ()              file_text = client.cat (Url+urllib.parse.quote ( changed[' path '].encode (' UTF8 '),  revision_max)                          fullpath = targetpath+ "/" +changed[' path ']                 dirPath =  Fullpath[0:fullpath.rfind ("/")]            if  not os.path.exists (Dirpath):                 os.makedirs (Dirpath)                                       f = open (FullPath, ' WB ')              f.write (File_text)              f.close     #f  = open (FullPath, ' WB ')       #f. Write (File_text)              #f. close#f_tar= "./" +os.path.basename ( TargetPath) + ". Tar" #if  os.path.exists (F_tar): #    os.remove (F_tar) #     print  (Os.path.basename (F_tar) + " is removed.") #else:#    print  (Os.path.basename (F_tar) + " is not exists.") # folder filter regulationos.chdir ((r "%s")  % targetpath) p_list = a_list  = s_list = os.listdir (OS.GETCWD ()) P_outer_list = list (Filter (lambda x:x  !=  "website"  and x !=  "framework",  p_list)) A_outer_list = list ( Filter (lambda x:x !=  "website"  and x !=  "framework"  and x !=   "Service",  a_list)) S_outer_list = list (Filter (lambda x:x !=  "website",  s_list)) Os.chdir ((r "%s\website")  % targetpath) P_INNER_LIST =&NBSp;a_inner_list = s_inner_list = os.listdir (OS.GETCWD ()) P_inner_list = list ( Filter (lambda x:x !=  "platform",  p_inner_list)) A_inner_list = list (filter (lambda  x:x !=  "Admin"  and x !=  "union",  a_inner_list) s_inner_list =  list (Filter (lambda x:x !=  "Static",  s_inner_list)) Def inner_filter (LIST_OP):     for i in list_op:         Shutil.rmtree ((r "%s\website\%s")  %  (Targetpath,i))     os.chdir ((r "%s")  %  t_path)     print  (Os.listdir (OS.GETCWD ()) Def filter_site (SITE_OP):     if site_version ==  "P":         for  p_o in p_outer_list:             Shutil.rmtree (r "%s\%s")  %  (targetpath,p_o))         inner_filter (p_inner_list)      elif site_version ==  "a":         for a _o in a_outer_list:             Shutil.rmtree (r "%s\%s")  %  (targetpath,a_o)         inner_ Filter (a_inner_list)     elif site_version ==  "s":         for s_o in s_outer_list:             shutil.rmtree (r "%s\%s")  %  (targetpath,s_o)          inner_filter (s_inner_list)     else:         raise Exception  (("unknown site_option: %s")  % site_op) Filter_ Site (site_version) print  ("Export file: %s_%s "+ '. Tar ')  %  (Site_version,date_folder)) Def make_tar (folder_to_tar,dst_ folder):     fold_name = os.path.basename (Folder_to_tar)      dst_name =  "%s_%s.tar"  % (site_version,fold_name)     dst_path =  Os.path.join (Dst_folder, dst_name)     tar = tarfile. Tarfile.open (dst_path,  ' W ')     tar.add (folder_to_tar, fold_name)      tar.close ()     return dst_pathdst_file = make_tar (TargetPath, '. /') # print  (dst_file) def upload_file (localfile):     ftp=ftp ()      ftp.connect (Ftp_host,ftp_port)     ftp.login (ftp_user,ftp_pass)      FTP.CWD ('./')     file=open (LocalFile, ' RB ')      Ftp.storbinary (' stor %s '  % os.path.basename (LocalFile), file)     ftp.retrlines (' LIST ')     file.close ()      ftp.close ()     ftp.quitupload_file (dst_file) print  (' File Upload  successful. ')


Code is like so many, in the middle there must be a lot of grammar is not rigorous and bug, we have to correct. If necessary can be directly taken to the corresponding change is basically can be used.


This article is from the "Soul" blog, make sure to keep this source http://chenpipi.blog.51cto.com/8563610/1604039

Python Basic Learning: SVN export diff File script

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.