Как я реализую Рычаг Фиксации Сообщения с Trac & SVN в Windows Environment?

В Java все переменные, которые вы объявляете, на самом деле являются «ссылками» на объекты (или примитивы), а не самими объектами.

При попытке выполнить один метод объекта , ссылка просит живой объект выполнить этот метод. Но если ссылка ссылается на NULL (ничего, нуль, void, nada), то нет способа, которым метод будет выполнен. Тогда runtime сообщит вам об этом, выбросив исключение NullPointerException.

Ваша ссылка «указывает» на нуль, таким образом, «Null -> Pointer».

Объект живет в памяти виртуальной машины пространство и единственный способ доступа к нему - использовать ссылки this. Возьмем этот пример:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

И в другом месте вашего кода:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

Это важно знать - когда больше нет ссылок на объект (в пример выше, когда reference и otherReference оба указывают на null), тогда объект «недоступен». Мы не можем работать с ним, поэтому этот объект готов к сбору мусора, и в какой-то момент VM освободит память, используемую этим объектом, и выделит другую.

6
задан Dean Poulin 17 September 2008 в 15:01
поделиться

6 ответов

Хорошо, теперь, когда у меня есть некоторое время для регистрации моего опыта после расчета этого всего, и благодаря Craig для получения меня на правильном пути. Вот то, что необходимо сделать (по крайней мере, с SVN v1.4 и Trac v0.10.3):

  1. Найдите свой репозиторий SVN, для которого Вы хотите включить Рычаг Фиксации Сообщения.
  2. в репозитории SVN существует каталог, названный рычагами, это - то, куда Вы будете помещать рычаг фиксации сообщения.
  3. создайте файл post-commit.bat (это - пакетный файл, которым это автоматически называет фиксация сообщения SVN).
  4. Поместите следующий код в файле post-commit.bat (это будет звонить, Ваше сообщение фиксируют передачу командного файла в параметрах, которые SVN автоматически передает %1, репозиторий, %2 пересмотр, который фиксировался.

% ~dp0\trac-post-commit-hook.cmd %1%2

  1. Теперь создайте trac-post-commit-hook.cmd файл следующим образом:

@ECHO ПРОЧЬ
::
:: Сценарий Trac post-commit-hook для Windows
::
:: Внесенный markus, измененным cboos.

:: Использование:
::
:: 1) Вставьте следующую строку в свой сценарий post-commit.bat
::
:: назовите % ~dp0\trac-post-commit-hook.cmd %1%2
::
:: 2) Проверка раздел 'Modify paths' ниже, убедиться установить, по крайней мере, TRAC_ENV


:: ----------------------------------------------------------
:: Измените пути здесь:

:: - этот должен быть установлен
НАБОР TRAC_ENV=C:\trac\MySpecialProject

:: - набор, если Python не находится в системном пути
:: НАБОР PYTHON_PATH =

:: - набор к папке, содержащей trac/, если установлено в нестандартном месте
:: НАБОР TRAC_PATH =
:: ----------------------------------------------------------

:: Не выполняйте рычаг, если trac среда не существует
ЕСЛИ НЕ СУЩЕСТВУЮТ %TRAC_ENV % GOTO: EOF

установите ПУТЬ = % % PYTHON_PATH; % ПУТИ %
набор PYTHONPATH = % % TRAC_PATH; % % PYTHONPATH

ВЕРСИЯ НАБОРА = % 2

:: ПОЛУЧИТЕ АВТОРА И СООБЩЕНИЕ ЖУРНАЛА
для/F %% в ('svnlook автор-r %REV % %1') действительно устанавливают АВТОРА = %% A
для/F "удаляет известь ==" %% B в ('svnlook, регистрируют-r %REV, % %1') действительно устанавливают ЖУРНАЛ = %% B

:: НАЗОВИТЕ СЦЕНАРИЙ PYTHON
Python "% ~dp0\trac-post-commit-hook"-p "%TRAC_ENV %"-r "%REV %"-u "%AUTHOR %"-m "%LOG %"

Самые важные части здесь должны установить Ваш TRAC_ENV, который является путем к корневому каталогу хранилища (УСТАНОВИТЕ TRAC_ENV=C:\trac\MySpecialProject),

Следующая АБСОЛЮТНО ВАЖНАЯ ВЕЩЬ в этом сценарии состоит в том, чтобы сделать следующее:

:: ПОЛУЧИТЕ АВТОРА И СООБЩЕНИЕ ЖУРНАЛА
для/F %% в ('svnlook автор-r %REV % %1') действительно устанавливают АВТОРА = %% A
для/F "удаляет известь ==" %% B в ('svnlook, регистрируют-r %REV, % %1') действительно устанавливают ЖУРНАЛ = %% B

если Вы видите в файле сценария выше, я использую svnlook (который является утилитой командной строки с SVN) получить сообщение ЖУРНАЛА и автора, который сделал фиксацию в репозиторий.

Затем следующая строка сценария на самом деле называет код Python, чтобы выполнить закрытие билетов и проанализировать сообщение журнала. Я должен был изменить это для передачи в сообщении Журнала и авторе (который имена пользователей, которые я использую в Trac, соответствуют именам пользователей в SVN так, чтобы было легко).

НАЗОВИТЕ СЦЕНАРИЙ PYTHON
Python "% ~dp0\trac-post-commit-hook"-p "%TRAC_ENV %"-r "%REV %"-u "%AUTHOR %"-m "%LOG %"

Вышеупомянутая строка в сценарии передаст в сценарий Python Среду Trac, пересмотр, человек, который сделал фиксацию и их комментарий.

Вот сценарий Python, который я использовал. Одна вещь, которую я сделал дополнительный к обычному сценарию, мы используем пользовательское поле (fixed_in_ver), который используется нашей командой QA, чтобы сказать, находится ли фиксация, которую они проверяют, в версии кода, который они тестируют в QA. Так, я изменил код в сценарии Python для обновления того поля на билете. Можно удалить тот код, поскольку Вам не будет нужен он, но это - хороший пример того, что можно сделать для обновления пользовательских полей в Trac, если Вы также хотите сделать это.

Я сделал это при наличии пользователей дополнительно включает в их комментарий что-то как:

(версия 2.1.2223.0)

Я затем использую ту же технику, которую сценарий Python использует с регулярными выражениями для получения информации. Это не было слишком плохо.

Так или иначе вот сценарий Python, который я использовал, Надо надеяться, это - хорошее учебное руководство на точно, что я сделал, чтобы заставить его работать в мире окон, таким образом, можно усилить это в собственном магазине...

Если Вы не хотите иметь дело с моим дополнительным кодом для обновления пользовательского поля, получать основной сценарий от этого местоположения, как упомянуто Craig выше (Сценарий От Edgewall)

#!/usr/bin/env python

# trac-post-commit-hook
# ----------------------------------------------------------------------------
# Copyright (c) 2004 Stephen Hansen 
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be included in
#   all copies or substantial portions of the Software. 
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------

# This Subversion post-commit hook script is meant to interface to the
# Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc 
# system.
# 
# It should be called from the 'post-commit' script in Subversion, such as
# via:
#
# REPOS="$1"
# REV="$2"
# LOG=`/usr/bin/svnlook log -r $REV $REPOS`
# AUTHOR=`/usr/bin/svnlook author -r $REV $REPOS`
# TRAC_ENV='/somewhere/trac/project/'
# TRAC_URL='http://trac.mysite.com/project/'
#
# /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \
#  -p "$TRAC_ENV"  \
#  -r "$REV"       \
#  -u "$AUTHOR"    \
#  -m "$LOG"       \
#  -s "$TRAC_URL"
#
# It searches commit messages for text in the form of:
#   command #1
#   command #1, #2
#   command #1 & #2 
#   command #1 and #2
#
# You can have more then one command in a message. The following commands
# are supported. There is more then one spelling for each command, to make
# this as user-friendly as possible.
#
#   closes, fixes
#     The specified issue numbers are closed with the contents of this
#     commit message being added to it. 
#   references, refs, addresses, re 
#     The specified issue numbers are left in their current status, but 
#     the contents of this commit message are added to their notes. 
#
# A fairly complicated example of what you can do is with a commit message
# of:
#
#    Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.
#
# This will close #10 and #12, and add a note to #12.

import re
import os
import sys
import time 

from trac.env import open_environment
from trac.ticket.notification import TicketNotifyEmail
from trac.ticket import Ticket
from trac.ticket.web_ui import TicketModule
# TODO: move grouped_changelog_entries to model.py
from trac.util.text import to_unicode
from trac.web.href import Href

try:
    from optparse import OptionParser
except ImportError:
    try:
        from optik import OptionParser
    except ImportError:
        raise ImportError, 'Requires Python 2.3 or the Optik option parsing library.'

parser = OptionParser()
parser.add_option('-e', '--require-envelope', dest='env', default='',
                  help='Require commands to be enclosed in an envelope. If -e[], '
                       'then commands must be in the form of [closes #4]. Must '
                       'be two characters.')
parser.add_option('-p', '--project', dest='project',
                  help='Path to the Trac project.')
parser.add_option('-r', '--revision', dest='rev',
                  help='Repository revision number.')
parser.add_option('-u', '--user', dest='user',
                  help='The user who is responsible for this action')
parser.add_option('-m', '--msg', dest='msg',
                  help='The log message to search.')
parser.add_option('-c', '--encoding', dest='encoding',
                  help='The encoding used by the log message.')
parser.add_option('-s', '--siteurl', dest='url',
                  help='The base URL to the project\'s trac website (to which '
                       '/ticket/## is appended).  If this is not specified, '
                       'the project URL from trac.ini will be used.')

(options, args) = parser.parse_args(sys.argv[1:])

if options.env:
    leftEnv = '\\' + options.env[0]
    rghtEnv = '\\' + options.env[1]
else:
    leftEnv = ''
    rghtEnv = ''

commandPattern = re.compile(leftEnv + r'(?P<action>[A-Za-z]*).?(?P<ticket>#[0-9]+(?:(?:[, &]*|[ ]?and[ ]?)#[0-9]+)*)' + rghtEnv)
ticketPattern = re.compile(r'#([0-9]*)')
versionPattern = re.compile(r"\(version[ ]+(?P<version>([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+))\)")

class CommitHook:
    _supported_cmds = {'close':      '_cmdClose',
                       'closed':     '_cmdClose',
                       'closes':     '_cmdClose',
                       'fix':        '_cmdClose',
                       'fixed':      '_cmdClose',
                       'fixes':      '_cmdClose',
                       'addresses':  '_cmdRefs',
                       're':         '_cmdRefs',
                       'references': '_cmdRefs',
                       'refs':       '_cmdRefs',
                       'see':        '_cmdRefs'}

    def __init__(self, project=options.project, author=options.user,
                 rev=options.rev, msg=options.msg, url=options.url,
                 encoding=options.encoding):
        msg = to_unicode(msg, encoding)
        self.author = author
        self.rev = rev
        self.msg = "(In [%s]) %s" % (rev, msg)
        self.now = int(time.time()) 
        self.env = open_environment(project)
        if url is None:
            url = self.env.config.get('project', 'url')
        self.env.href = Href(url)
        self.env.abs_href = Href(url)

        cmdGroups = commandPattern.findall(msg)


        tickets = {}

        for cmd, tkts in cmdGroups:
            funcname = CommitHook._supported_cmds.get(cmd.lower(), '')

            if funcname:

                for tkt_id in ticketPattern.findall(tkts):
                    func = getattr(self, funcname)
                    tickets.setdefault(tkt_id, []).append(func)

        for tkt_id, cmds in tickets.iteritems():
            try:
                db = self.env.get_db_cnx()

                ticket = Ticket(self.env, int(tkt_id), db)
                for cmd in cmds:
                    cmd(ticket)

                # determine sequence number... 
                cnum = 0
                tm = TicketModule(self.env)
                for change in tm.grouped_changelog_entries(ticket, db):
                    if change['permanent']:
                        cnum += 1

                # get the version number from the checkin... and update the ticket with it.
                version = versionPattern.search(msg)
                if version != None and version.group("version") != None:
                    ticket['fixed_in_ver'] = version.group("version")

                ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)
                db.commit()

                tn = TicketNotifyEmail(self.env)
                tn.notify(ticket, newticket=0, modtime=self.now)
            except Exception, e:
                # import traceback
                # traceback.print_exc(file=sys.stderr)
                print>>sys.stderr, 'Unexpected error while processing ticket ' \
                                   'ID %s: %s' % (tkt_id, e)


    def _cmdClose(self, ticket):
        ticket['status'] = 'closed'
        ticket['resolution'] = 'fixed'

    def _cmdRefs(self, ticket):
        pass


if __name__ == "__main__":
    if len(sys.argv) < 5:
        print "For usage: %s --help" % (sys.argv[0])
    else:
        CommitHook()
3
ответ дан 17 December 2019 в 00:17
поделиться

Фиксация сообщения сцепляется живой в каталоге "рычагов", где когда-либо у Вас есть репозиторий, живущий на стороне сервера. Я не знаю, где у Вас есть они в Вашей среде, таким образом, это - просто пример

например, (окна):

C:\Subversion\repositories\repo1\hooks\post-commit

например, (llinux/unix):

/usr/local/subversion/repositories/repo1/hooks/post-commit
0
ответ дан 17 December 2019 в 00:17
поделиться

Ответ Benjamin близок, но в Windows необходимо дать файлам сценария рычага исполняемое расширение, такое как .bat или .cmd. Я использую .cmd. Можно взять шаблонные сценарии, которые являются сценариями оболочки Unix, сценариями оболочки и преобразовывают их в .bat/.cmd синтаксис.

Но отвечать на вопрос интеграции с Trac, выполните эти шаги.

  1. Удостоверьтесь, что Python.exe находится на системном пути. Это сделает Вашу жизнь легче.

  2. Создайте post-commit.cmd в \hooks папке. Это - фактический сценарий рычага, который Подверсия выполнит на событии постфиксации.

    @ECHO OFF
    
    :: POST-COMMIT HOOK
    ::
    :: The post-commit hook is invoked after a commit.  Subversion runs
    :: this hook by invoking a program (script, executable, binary, etc.)
    :: named 'post-commit' (for which this file is a template) with the 
    :: following ordered arguments:
    ::
    ::   [1] REPOS-PATH   (the path to this repository)
    ::   [2] REV          (the number of the revision just committed)
    ::
    :: The default working directory for the invocation is undefined, so
    :: the program should set one explicitly if it cares.
    ::
    :: Because the commit has already completed and cannot be undone,
    :: the exit code of the hook program is ignored.  The hook program
    :: can use the 'svnlook' utility to help it examine the
    :: newly-committed tree.
    ::
    :: On a Unix system, the normal procedure is to have 'post-commit'
    :: invoke other programs to do the real work, though it may do the
    :: work itself too.
    ::
    :: Note that 'post-commit' must be executable by the user(s) who will
    :: invoke it (typically the user httpd runs as), and that user must
    :: have filesystem-level permission to access the repository.
    ::
    :: On a Windows system, you should name the hook program
    :: 'post-commit.bat' or 'post-commit.exe',
    :: but the basic idea is the same.
    :: 
    :: The hook program typically does not inherit the environment of
    :: its parent process.  For example, a common problem is for the
    :: PATH environment variable to not be set to its usual value, so
    :: that subprograms fail to launch unless invoked via absolute path.
    :: If you're having unexpected problems with a hook program, the
    :: culprit may be unusual (or missing) environment variables.
    :: 
    :: Here is an example hook script, for a Unix /bin/sh interpreter.
    :: For more examples and pre-written hooks, see those in
    :: the Subversion repository at
    :: http://svn.collab.net/repos/svn/trunk/tools/hook-scripts/ and
    :: http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/
    
    setlocal
    
    :: Debugging setup
    :: 1. Make a copy of this file.
    :: 2. Enable the command below to call the copied file.
    :: 3. Remove all other commands
    ::call %~dp0post-commit-run.cmd %* > %1/hooks/post-commit.log 2>&1
    
    :: Call Trac post-commit hook
    call %~dp0trac-post-commit.cmd %* || exit 1
    
    endlocal
    
  3. Создайте trac-post-commit.cmd в \hooks папке:

    @ECHO OFF
    ::
    :: Trac post-commit-hook script for Windows
    ::
    :: Contributed by markus, modified by cboos.
    
    :: Usage:
    ::
    :: 1) Insert the following line in your post-commit.bat script
    ::
    :: call %~dp0\trac-post-commit-hook.cmd %1 %2
    ::
    :: 2) Check the 'Modify paths' section below, be sure to set at least TRAC_ENV
    
    setlocal
    
    :: ----------------------------------------------------------
    :: Modify paths here:
    
    :: -- this one *must* be set
    SET TRAC_ENV=D:\projects\trac\membershipdnn
    
    :: -- set if Python is not in the system path
    SET PYTHON_PATH=
    
    :: -- set to the folder containing trac/ if installed in a non-standard location
    SET TRAC_PATH=
    :: ----------------------------------------------------------
    
    :: Do not execute hook if trac environment does not exist
    IF NOT EXIST %TRAC_ENV% GOTO :EOF
    
    set PATH=%PYTHON_PATH%;%PATH%
    set PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%
    
    SET REV=%2
    
    :: Resolve ticket references (fixes, closes, refs, etc.)
    Python "%~dp0trac-post-commit-resolve-ticket-ref.py" -p "%TRAC_ENV%" -r "%REV%"
    
    endlocal
    
  4. Создайте trac-post-commit-resolve-ticket-ref.py в \hooks папке. Я использовал тот же сценарий от EdgeWall, только я переименовал его для лучше разъяснения его цели.

4
ответ дан 17 December 2019 в 00:17
поделиться

Я добавлю одну вещь: «Ответ Code Monkey ИДЕАЛЬНЫЙ» - это остерегаться этого (моя ошибка)

:: Modify paths here:

:: -- this one must be set
SET TRAC_ENV=d:\trac\MySpecialProject

:: -- set if Python is not in the system path
:: SET PYTHON_PATH=**d:\python**

:: -- set to the folder containing trac/ if installed in a non-standard location 
:: SET TRAC_PATH=**d:\python\Lib\site-packages\trac**

Я не установил Несистемные пути и взял меня немного, чтобы увидеть очевидное: D

Просто сопоставьте, чтобы никто другой не совершил такую ​​же ошибку! Спасибо, Code Monkey! 1000000000 баллов: D

0
ответ дан 17 December 2019 в 00:17
поделиться

Прежде всего, большое спасибо Code Monkey!

Однако важно получить правильный скрипт python в зависимости от версии trac. Чтобы получить соответствующую версию, SVN проверьте папку:

http://svn.edgewall.com/repos/trac/branches/ xxx -stable / contrib

где xxx соответствует используемой вами версии trac, например: 0.11

В противном случае вы получите сообщение об ошибке после фиксации, которое выглядит следующим образом:

сбой фиксации (подробности см. Ниже): MERGE of '/ svn / project / trunk / web / directory / ': 200 ОК

0
ответ дан 17 December 2019 в 00:17
поделиться

For all Windows users who wants to install newest trac (0.11.5): Follow the instructions on Trac's site named TracOnWindows.

Download 32bit 1.5 Python even if You have 64bit Windows. note: I saw somewhere instructions how to compile trac to work natively on 64bit system.

When You install all that is required go to the repository folder. There is folder hooks. Inside it put files Code Monkey mentioned, but dont create "trac-post-commit-resolve-ticket-ref.py" like he did. Take advice from Quant Analyst and do like he said:

"However, it's important to get the right python script depending on your trac version. To get the appropriate version, SVN check out the folder: http://svn.edgewall.com/repos/trac/branches/xxx-stable/contrib where xxx corresponds to the trac version you're using, for instance: 0.11"

From there downoad file "trac-post-commit-hook" and put it in hooks folder.

Edit these lines in trac-post-commit.cmd

SET PYTHON_PATH="Path to python installation folder"

SET TRAC_ENV="Path to folder where you did tracd initenv"

Remember no last \ !!!

I have removed quotes from last line -r "%REV%" to be -r %REV% but i dont know if this is needed. This will not work now ( at least on my win 2008 server ), because hook will fail ( commit will go ok). This got to do with permissions. By default permissions are restricted and we need to allow python or svn or trac ( whatever i dont know ) to change trac information. So go to your trac folder,project folder,db folder, right click trac.db and choose properties. Go to the security tab and edit permissions to allow everyone full control. This isn't so secure but i wasted all day on this security matter and i don't want to waste another just to find for which user you should enable permissions.

Hope this helps....

0
ответ дан 17 December 2019 в 00:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: