
#
#    ========== licence begin LGPL
#    Copyright (C) 2002 SAP AG
#
#    This library is free software; you can redistribute it and/or
#    modify it under the terms of the GNU Lesser General Public
#    License as published by the Free Software Foundation; either
#    version 2.1 of the License, or (at your option) any later version.
#
#    This library is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with this library; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#    ========== licence end
#

import string
import re
import os
import shutil

import optlib

#
# files to exclude
#

def stripComment (line):
    pos = string.find (line, '#')
    if pos == -1:
        result = line
    else:
        result = line [pos+1:]
    return result

def getExcludeLines (lines):
    lines = map (stripComment, lines)
    result = []
    noDir = '-noDir:'
    for line in lines:
        if line [:len (noDir)] == noDir:
            result.append (string.strip (line [len (noDir):]))
    return result

def getExcludeLinesFromFile (fname):
    lines = open (fname, 'r').readlines ()
    return getExcludeLines (lines)

defaultExclude = os.path.join (os.environ.get ('OWN', ''), 'sys', 'config', 'noOpenSource')

def loadExcludes (path = defaultExclude):
    files = os.listdir (path)
    result = ['/config/noOpenSource/']
    for file in files:
        result.extend (getExcludeLinesFromFile (os.path.join (path, file)))
    return result

def isExcluded (fname, patterns):
    for pattern in patterns:
        if fname [:len (pattern)] == pattern:
            return 1
    return None

def loadExcludesFromPerforce (p4, path):
    files = p4.listdir (path)
    result = []
    for file in files:
        data = p4.readFile (file)
        lines = string.split (data, '\n')
        result.extend (getExcludeLines (lines))
    return result

#
# command line options
#

import perforce.perforceLib

_cmdlineOptions = [
        ('ftp', None, ':', 'FileExchange:ExchangeFile@p48047', 'ftp login'),
        ('staging', None, ':', '/staging/sapdb', 'staging dir on FTP server'),
        ('p4', 'perforceClient', ':', None, 'name of perforce client'),
        ('root', None, '::', None, 'root dir in depot notation'),
        ('perforceRoot', None, ':', None, 'use all directories under this root'),
        ('o', 'outdir', ':', '.', 'output directory'),
]

def checkOptions (options):
    if not options.perforceClient:
        optlib.fatalError ('perforce client must be specified (-p4)')
    options.p4 = perforce.perforceLib.PerforceSession (options.perforceClient)
    options.root = getRoots (options)
    assert options.root, '-root must be specified'
    for root in options.root:
        if root [:2] != '//':
            optlib.fatalError ('-root not in perforce depot notation\n')
    options.outdir = os.path.abspath (options.outdir)

def getRoots (options):
    if options.perforceRoot:
        lines = options.p4.getLines (' dirs ' + options.perforceRoot + '/*')
        return map (string.strip, lines)
    else:
        return options.root

#
# copy standard source files
#
_licenceFiles = [
    'licence/gpl.txt', 'licence/lesser.txt', 'licence/fdl.txt',
]

_standardFiles = _licenceFiles [:]

def copyStandardFiles (targetDir, readmes = []):
    candidates = [
        # os.path.join (os.environ ['SRC'], 'data'),
        os.path.join (os.environ ['TOOL'], 'data')]
    result = []
    for file in _standardFiles:
        fullSource = findFile (file, candidates)
        if not fullSource:
            continue
        fullTarget = os.path.join (targetDir, file)
        fullDir = os.path.dirname (fullTarget)
        if not os.path.isdir (fullDir):
            os.makedirs (fullDir)
        shutil.copyfile (fullSource, fullTarget)
        result.append (file)
    candidates = [
        os.path.join (os.environ ['SRC'], 'data'),
        os.path.join (os.environ ['TOOL'], 'data')]
    for inname, outname in readmes:
        readmeIn = findFile (inname, candidates)
        if readmeIn:
            shutil.copyfile (readmeIn, os.path.join (targetDir, outname))
        result.append (outname)
    return result

def findFile (fname, dirs):
    for dir in dirs:
        fullPath = os.path.join (dir, fname)
        print 'trying', fullPath
        if os.path.exists (fullPath):
            return fullPath
    return None

#
# ftp
#

import ftplib

def transferByFTP (options, fname, subdir = '/7.3/updates'):
    """transfer a file to the FTP staging area
    """
    if not options.ftp:
        return
    match = re.match ('(.*):(.*)@(.*)', options.ftp)
    user, password, host = match.group (1, 2, 3)
    session = ftplib.FTP (host, user, password)
    try:
        remoteDir = options.staging + subdir
        session.cwd (remoteDir)
        remoteName = os.path.basename (fname)
        stream = open (fname, 'rb')
        session.storbinary ('STOR ' + remoteName, stream, 4096)
    finally:
        session.quit ()

#
# test
#
if __name__ == "__main__":
    import perforce.perforceLib
    p4 = perforce.perforceLib.PerforceSession ()
    excludeLines = loadExcludesFromPerforce (p4, '//sapdb/V73/c_00/develop/sys/config/noOpenSource')
    print excludeLines

