def main(argv=None):  # IGNORE:C0111
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by user_name on %s.
  Copyright 2016 organization_name. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter)
        parser.add_argument('-V', '--version', action='version', version=program_version_message)
        parser.add_argument('--agilefant-host', dest='agilefant_host', default='127.0.0.1', help='Host IP of the Agilefant database (default: 127.0.0.1')
        parser.add_argument('--agilefant-user', dest='agilefant_user', default='agilefant', help='Agilefant database user (default: agilefant)')
        parser.add_argument('--afilefant-password', dest='agilefant_password', default='agilefant', help='Agilefant database password for the defined user (default: agilefant)')
        parser.add_argument('--agilefant-db', dest='agilefant_db', default='agilefant', help='Agilefant database name (default: agilefant)')
        parser.add_argument('--taiga-host', dest='taiga_host', default='127.0.0.1', help='Host IP or FQDN of the Taiga API server (default: 127.0.0.1)')

        # Process arguments
        args = parser.parse_args()
        
        cnx = mysql.connector.connect(user=args.agilefant_user, password=args.agilefant_password, host=args.agilefant_host, database=args.agilefant_db)
        
        taiga = TaigaAPI(host='http://%s' % args.taiga_host)
        taiga.auth(username='******',password='******')
        
        migrate_products(cnx, taiga=taiga)
        
        cnx.close()
        
    except KeyboardInterrupt:
        ### handle keyboard interrupt ###
        return 0
    except Exception as e:
        if DEBUG or TESTRUN:
            raise(e)
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2
Exemple #2
0
    def taiga_api(self):

        us = UserService.objects.get(user=self.user, name='ServiceTaiga')
        if us.token:
            api = TaigaAPI(token=us.token, host=us.host)
        else:
            api = TaigaAPI(host=us.host)
            api.auth(us.username, us.password)
        return api
Exemple #3
0
    def taiga_api(self):

        us = UserService.objects.get(user=self.user, name='ServiceTaiga')
        if us.token:
            api = TaigaAPI(token=us.token, host=us.host)
        else:
            api = TaigaAPI(host=us.host)
            api.auth(us.username, us.password)
        return api
Exemple #4
0
    def create_issue(self, request, group, form_data, **kwargs):

        url = self.get_option('taiga_url', group.project)
        username = self.get_option('taiga_username', group.project)
        password = self.get_option('taiga_password', group.project)
        project_slug = self.get_option('taiga_project', group.project)
        labels = self.get_option('taiga_labels', group.project)
        
        tg = TaigaAPI(host=url)

        try:
            tg.auth(username=username, password=password)
        except Exception as e:
            raise forms.ValidationError(_('Error Communicating '
                                        'with Taiga: %s') % (e,))

        projects = tg.projects.list()
        
        project = projects.get(slug=project_slug)
        if project is None:
            raise forms.ValidationError(_('No project found in Taiga with slug %s') % 
                                        (project_slug,))

        if not project.is_issues_activated:
            raise forms.ValidationError(_('Project %s has issues disabled.') % 
                                        (project_slug,))

        default_priority = project.default_priority
        default_issue_status = project.default_issue_status
        default_issue_type = project.default_issue_type
        default_severity = project.default_severity

        if default_priority is None:
            raise forms.ValidationError(_('Project %s has no default priority. '
                'Set the default priority in Taiga') % (project.name,))
        if default_issue_status is None:
            raise forms.ValidationError(_('Project %s has no default status. '
                'Set the default issue status in Taiga') % (project.name,))
        if default_issue_type is None:
            raise forms.ValidationError(_('Project %s has no default type. '
                'Set the default issue type in Taiga') % (project.name,))
        if default_severity is None:
            raise forms.ValidationError(_('Project %s has no default severity. '
                'Set the default severity in Taiga') % (project.name,))

        data = {'subject': form_data['title'], 
            'priority': default_priority, 'status': default_issue_status,
            'issue_type': default_issue_type, 'severity': default_severity,
            'description': form_data['description'], 
            'tags': map(lambda x:x.strip(), labels.split(","))}

        issue = project.add_issue(**data)

        return issue.ref
Exemple #5
0
 def api(self):
     if not self._api:
         api = TaigaAPI(host=self.host)
         if self.token:
             api.token = self.token
         else:
             if not self.username or not self.password:
                 raise j.exceptions.Runtime("Token or username and password are required")
             api.auth(self.username, self.password)
         self._api = api
     return self._api
Exemple #6
0
    def create_issue(self, request, group, form_data, **kwargs):

        api = self.get_option('taiga_api', group.project)
        username = self.get_option('taiga_username', group.project)
        password = self.get_option('taiga_password', group.project)
        project_slug = self.get_option('taiga_project', group.project)
        labels = self.get_option('taiga_labels', group.project)

        tg = TaigaAPI(host=api)

        try:
            tg.auth(username=username, password=password)
        except Exception as e:
            raise forms.ValidationError(
                _('Error Communicating '
                  'with Taiga: %s') % (e, ))

        project = tg.projects.get_by_slug(slug=project_slug)
        if project is None:
            raise forms.ValidationError(
                _('No project found in Taiga with slug %s') % (project_slug, ))

        default_issue_status = project.default_issue_status
        priority = project.default_priority
        issue_type = project.default_issue_type
        severity = project.default_severity

        if default_issue_status is None:
            raise forms.ValidationError(
                _('Project %s has no default status. '
                  'Set the default issue status in Taiga') % (project.name, ))

        if not labels:
            labels = ''
        data = {
            'subject': form_data['title'],
            'status': default_issue_status,
            'description': form_data['description'],
            'priority': priority,
            'issue_type': issue_type,
            'severity': severity,
            'tags': [label.strip() for label in labels.split(",") if label]
        }

        if self.is_issue(group.project):
            issue = project.add_issue(**data)
        else:
            issue = project.add_user_story(**data)

        return issue.ref
Exemple #7
0
    def create_taiga_channels(self, username, password, desc, course_id):
        api = TaigaAPI()
        try:
            api.auth(username=username, password=password)
        except:
            return 'invalid auth'
        group_data = self.get_groupsdata(course_id)
        for key in group_data:
            new_project = api.projects.create(key, desc)
            new_project.is_private = "false"
            new_project.update()

            for member in group_data[key]:
                email = member + '@asu.edu'
                new_project.add_membership(role=new_project.roles[0].id,
                                           username=email,
                                           email=email)
Exemple #8
0
class TaigaClient(JSConfigClient):
    _SCHEMATEXT = """
        @url = jumpscale.taiga.clients
        name** = "" (S)
        username = "" (S)
        password_ = "" (S)
        token_ = "" (S)
        host = "https://projects.threefold.me"
        """

    def _init(self, **kwargs):
        self.api = TaigaAPI(host=self.host)
        if self.token_:
            self.api.token = self.token_
        else:
            if not self.username or not self.password_:
                raise RuntimeError("username and password are required")
            self.api.auth(self.username, self.password_)
Exemple #9
0
    def create_issue(self, request, group, form_data, **kwargs):

        url = self.get_option('taiga_url', group.project)
        username = self.get_option('taiga_username', group.project)
        password = self.get_option('taiga_password', group.project)
        project_slug = self.get_option('taiga_project', group.project)

        tg = TaigaAPI(host=url)

        try:
            tg.auth(username=username, password=password)
        except Exception as e:
            raise forms.ValidationError(
                _('Error Communicating '
                  'with Taiga: %s') % (e, ))

        project = tg.projects.get_by_slug(slug=project_slug)
        if project is None:
            raise forms.ValidationError(
                _('No project found in Taiga with slug %s') % (project_slug, ))

        default_us_status = project.default_us_status
        if default_us_status is None:
            raise forms.ValidationError(
                _('Project %s has no default status. '
                  'Set the default user story status in Taiga') %
                (project.name, ))

        data = {
            'subject': form_data['title'],
            'status': default_us_status,
            'description': form_data['description'],
            'tags': map(lambda x: x.strip(), labels.split(","))
        }

        us = project.add_user_story(**data)

        return us.ref
Exemple #10
0
 def test_auth_success(self, requests):
     requests.post.return_value = MockResponse(
         200, create_mock_json('tests/resources/auth_user_success.json'))
     api = TaigaAPI(host='host')
     api.auth('valid_user', 'valid_password')
     self.assertEqual(api.token, 'f4k3')
Exemple #11
0
 def test_auth_success(self, requests):
     requests.post.return_value = MockResponse(200, create_mock_json('tests/resources/auth_user_success.json'))
     api = TaigaAPI(host='host')
     api.auth('valid_user', 'valid_password')
     self.assertEqual(api.token, 'f4k3')
Exemple #12
0
from taiga import TaigaAPI
import config as c
import logging
from send import send

logging.basicConfig(level=logging.DEBUG)

api = TaigaAPI()

api.auth(username=c.TAIGA_USER, password=c.TAIGA_PASSWORD)

logging.info('Initializing connection and authenticating ...')
project = api.projects.get_by_slug(c.PROJECT_SLUG)

logging.info('Getting user stories ...')
user_stories = api.user_stories.list(project=project.id)
user_story_dict = {x.id: x.name for x in project.list_user_story_statuses()}
user_story_dict_inv = {
    x.name: x.id
    for x in project.list_user_story_statuses()
}

current_sprints = list(filter(lambda x: not x.closed, project.milestones))
current_sprints = sorted(current_sprints, key=lambda x: x.id)

assert len(
    current_sprints
) >= 2, "There must be at least 2 active sprints to migrate to a new sprint"
new_sprint = current_sprints[-1]
old_sprint = current_sprints[-2]
Exemple #13
0
#!/usr/bin/env python3

from taiga import TaigaAPI

import email.parser
import sys
import os

body = email.parser.Parser().parsestr(sys.stdin.read())
text = body.get_payload() if not body.is_multipart() else body.get_payload(i=0)

api = TaigaAPI(host=os.environ.get('TAIGA_HOST', 'http://z.ero.cool/'))
api.auth(username=os.environ.get('TAIGA_USER', 'email'),
         password=os.environ.get('TAIGA_PASS', None))
project = api.projects.get(os.environ.get('TAIGA_PROJECT', '2'))

project.add_user_story(body['Subject'],
                       description="""\
From: {fro}
Message-Id: {messageid}

{text}
""".format(fro=body['From'], messageid=body['Message-Id'], text=text))
Exemple #14
0
def manage_issue(
    module,
    taiga_host,
    project_name,
    issue_subject,
    issue_priority,
    issue_status,
    issue_type,
    issue_severity,
    issue_description,
    issue_attachment,
    issue_attachment_description,
    issue_tags,
    state,
    check_mode=False,
):
    """
    Method that creates/deletes issues depending whether they exist and the state desired

    The credentials should be passed via environment variables:
        - TAIGA_TOKEN
        - TAIGA_USERNAME and TAIGA_PASSWORD

    Returns a tuple with these elements:
        - A boolean representing the success of the operation
        - A descriptive message
        - A dict with the issue attributes, in case of issue creation, otherwise empty dict
    """

    changed = False

    try:
        token = getenv("TAIGA_TOKEN")
        if token:
            api = TaigaAPI(host=taiga_host, token=token)
        else:
            api = TaigaAPI(host=taiga_host)
            username = getenv("TAIGA_USERNAME")
            password = getenv("TAIGA_PASSWORD")
            if not any([username, password]):
                return (False, changed, "Missing credentials", {})
            api.auth(username=username, password=password)

        user_id = api.me().id
        project_list = filter(lambda x: x.name == project_name, api.projects.list(member=user_id))
        if len(project_list) != 1:
            return (False, changed, "Unable to find project %s" % project_name, {})
        project = project_list[0]
        project_id = project.id

        priority_list = filter(lambda x: x.name == issue_priority, api.priorities.list(project=project_id))
        if len(priority_list) != 1:
            return (
                False,
                changed,
                "Unable to find issue priority %s for project %s" % (issue_priority, project_name),
                {},
            )
        priority_id = priority_list[0].id

        status_list = filter(lambda x: x.name == issue_status, api.issue_statuses.list(project=project_id))
        if len(status_list) != 1:
            return (False, changed, "Unable to find issue status %s for project %s" % (issue_status, project_name), {})
        status_id = status_list[0].id

        type_list = filter(lambda x: x.name == issue_type, project.list_issue_types())
        if len(type_list) != 1:
            return (False, changed, "Unable to find issue type %s for project %s" % (issue_type, project_name), {})
        type_id = type_list[0].id

        severity_list = filter(lambda x: x.name == issue_severity, project.list_severities())
        if len(severity_list) != 1:
            return (False, changed, "Unable to find severity %s for project %s" % (issue_severity, project_name), {})
        severity_id = severity_list[0].id

        issue = {
            "project": project_name,
            "subject": issue_subject,
            "priority": issue_priority,
            "status": issue_status,
            "type": issue_type,
            "severity": issue_severity,
            "description": issue_description,
            "tags": issue_tags,
        }

        # An issue is identified by the project_name, the issue_subject and the issue_type
        matching_issue_list = filter(lambda x: x.subject == issue_subject and x.type == type_id, project.list_issues())
        matching_issue_list_len = len(matching_issue_list)

        if matching_issue_list_len == 0:
            # The issue does not exist in the project
            if state == "present":
                # This implies a change
                changed = True
                if not check_mode:
                    # Create the issue
                    new_issue = project.add_issue(
                        issue_subject,
                        priority_id,
                        status_id,
                        type_id,
                        severity_id,
                        tags=issue_tags,
                        description=issue_description,
                    )
                    if issue_attachment:
                        new_issue.attach(issue_attachment, description=issue_attachment_description)
                        issue["attachment"] = issue_attachment
                        issue["attachment_description"] = issue_attachment_description
                return (True, changed, "Issue created", issue)

            else:
                # If does not exist, do nothing
                return (True, changed, "Issue does not exist", {})

        elif matching_issue_list_len == 1:
            # The issue exists in the project
            if state == "absent":
                # This implies a change
                changed = True
                if not check_mode:
                    # Delete the issue
                    matching_issue_list[0].delete()
                return (True, changed, "Issue deleted", {})

            else:
                # Do nothing
                return (True, changed, "Issue already exists", {})

        else:
            # More than 1 matching issue
            return (
                False,
                changed,
                "More than one issue with subject %s in project %s" % (issue_subject, project_name),
                {},
            )

    except TaigaException:
        msg = "An exception happened: %s" % sys.exc_info()[1]
        return (False, changed, msg, {})
def main(argv=None):  # IGNORE:C0111
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version,
                                                     program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by user_name on %s.
  Copyright 2016 organization_name. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ArgumentParser(description=program_license,
                                formatter_class=RawDescriptionHelpFormatter)
        parser.add_argument('-V',
                            '--version',
                            action='version',
                            version=program_version_message)
        parser.add_argument(
            '--agilefant-host',
            dest='agilefant_host',
            default='127.0.0.1',
            help='Host IP of the Agilefant database (default: 127.0.0.1')
        parser.add_argument(
            '--agilefant-user',
            dest='agilefant_user',
            default='agilefant',
            help='Agilefant database user (default: agilefant)')
        parser.add_argument(
            '--afilefant-password',
            dest='agilefant_password',
            default='agilefant',
            help=
            'Agilefant database password for the defined user (default: agilefant)'
        )
        parser.add_argument(
            '--agilefant-db',
            dest='agilefant_db',
            default='agilefant',
            help='Agilefant database name (default: agilefant)')
        parser.add_argument(
            '--taiga-host',
            dest='taiga_host',
            default='127.0.0.1',
            help='Host IP or FQDN of the Taiga API server (default: 127.0.0.1)'
        )

        # Process arguments
        args = parser.parse_args()

        cnx = mysql.connector.connect(user=args.agilefant_user,
                                      password=args.agilefant_password,
                                      host=args.agilefant_host,
                                      database=args.agilefant_db)

        taiga = TaigaAPI(host='http://%s' % args.taiga_host)
        taiga.auth(username='******', password='******')

        migrate_products(cnx, taiga=taiga)

        cnx.close()

    except KeyboardInterrupt:
        ### handle keyboard interrupt ###
        return 0
    except Exception as e:
        if DEBUG or TESTRUN:
            raise (e)
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2
Exemple #16
0
from taiga import TaigaAPI
import argparse

parser = argparse.ArgumentParser(description='Create Taiga issue')
parser.add_argument('--user', dest='user')
parser.add_argument('--passwd', dest='passwd')
parser.add_argument('--project', dest='project')
parser.add_argument('--storyid', dest='storyid')
parser.add_argument('--status', dest='status')


args = parser.parse_args()

api = TaigaAPI()

api.auth(username=args.user, password=args.passwd)

proj =  api.projects.get_by_slug(args.project)

us = proj.list_user_stories().get(ref=int(args.storyid))

us.update(status=proj.list_user_story_statuses().get(name=args.status).id)
from taiga import TaigaAPI
from settings import USER, PASS

api = TaigaAPI()
api.auth( username=USER, password=PASS)

me = api.me()

#Search for the members of all your projects
members = []
projects = api.projects.list(member=me.id)
for project in projects: 
	members += project.members

#Get the username of the members
for user_id in list(set(members)):
	user = api.users.get(user_id)
	print "({1}) {0}".format(user.username, user.id)
Exemple #18
0
def init_taiga_api(host, username, password):
    api = TaigaAPI(host=host)
    api.auth(username=username, password=password)
    return api
Exemple #19
0
 def test_auth_success(self, requests):
     requests.post.return_value = MockResponse(
         200, create_mock_json("tests/resources/auth_user_success.json"))
     api = TaigaAPI(host="host")
     api.auth("valid_user", "valid_password")
     self.assertEqual(api.token, "f4k3")
Exemple #20
0
# -*- coding: utf-8 -*-

from taiga import TaigaAPI
from taiga.exceptions import TaigaException

api = TaigaAPI(host='http://127.0.0.1:8000')

api.auth(username='******', password='******')

print(api.me())

new_project = api.projects.create('TEST PROJECT', 'TESTING API')

new_project.name = 'TEST PROJECT 3'
new_project.update()

print(new_project.members)

for member in new_project.members:
    print(member)

jan_feb_milestone = new_project.add_milestone('New milestone jan feb',
                                              '2015-01-26', '2015-02-26')

userstory = new_project.add_user_story('New Story',
                                       description='Blablablabla',
                                       milestone=jan_feb_milestone.id)
userstory.attach('README.md')

userstory.add_task('New Task 2',
                   new_project.task_statuses[0].id).attach('README.md')
import datetime, pickle, os
from taiga import TaigaAPI
from settings import USER, PASS, TEAM, OUTPUT_FOLDER
from taiga_reports.snapshot import Snapshot

api = TaigaAPI(); api.auth( username=USER, password=PASS)

Snapshot(OUTPUT_FOLDER,api,TEAM)
Exemple #22
0
    def create_issue(self, request, group, form_data, **kwargs):

        url = self.get_option('taiga_url', group.project)
        username = self.get_option('taiga_username', group.project)
        password = self.get_option('taiga_password', group.project)
        project_slug = self.get_option('taiga_project', group.project)
        labels = self.get_option('taiga_labels', group.project)

        tg = TaigaAPI(host=url)

        try:
            tg.auth(username=username, password=password)
        except Exception as e:
            raise forms.ValidationError(
                _('Error Communicating '
                  'with Taiga: %s') % (e, ))

        projects = tg.projects.list()

        project = projects.get(slug=project_slug)
        if project is None:
            raise forms.ValidationError(
                _('No project found in Taiga with slug %s') % (project_slug, ))

        if not project.is_issues_activated:
            raise forms.ValidationError(
                _('Project %s has issues disabled.') % (project_slug, ))

        default_priority = project.default_priority
        default_issue_status = project.default_issue_status
        default_issue_type = project.default_issue_type
        default_severity = project.default_severity

        if default_priority is None:
            raise forms.ValidationError(
                _('Project %s has no default priority. '
                  'Set the default priority in Taiga') % (project.name, ))
        if default_issue_status is None:
            raise forms.ValidationError(
                _('Project %s has no default status. '
                  'Set the default issue status in Taiga') % (project.name, ))
        if default_issue_type is None:
            raise forms.ValidationError(
                _('Project %s has no default type. '
                  'Set the default issue type in Taiga') % (project.name, ))
        if default_severity is None:
            raise forms.ValidationError(
                _('Project %s has no default severity. '
                  'Set the default severity in Taiga') % (project.name, ))

        data = {
            'subject': form_data['title'],
            'priority': default_priority,
            'status': default_issue_status,
            'issue_type': default_issue_type,
            'severity': default_severity,
            'description': form_data['description'],
            'tags': map(lambda x: x.strip(), labels.split(","))
        }

        issue = project.add_issue(**data)

        return issue.ref
Exemple #23
0
from __future__ import print_function
import tkinter as tk
from tkinter import messagebox
from flask import Flask, flash, redirect, render_template, request, url_for
from taiga import TaigaAPI
import pdb
import sys
import pymysql

api = TaigaAPI()

api.auth(username='******', password='******')

root = tk.Tk()
root.withdraw()
pdb.set_trace()
new_project = api.projects
app = Flask(__name__)

db = pymysql.connect(host='localhost',
                     database='users',
                     user='******',
                     password='******',
                     autocommit=True)
cur = db.cursor()


@app.route('/')
def index():
    return render_template('index.html')
Exemple #24
0
from taiga import TaigaAPI
import re
import os
import time

BOT_ID = os.environ.get('BOT_ID')
TG_PATTERN = 'tg#'
TG_BASE_URL = os.environ.get('taiga_host')
TG_USER = os.environ.get('taiga_user')
TG_PASSWORD = os.environ.get('taiga_pass')
TG_PROJECT = os.environ.get('taiga_project')

slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))

api = TaigaAPI(host=TG_BASE_URL)
api.auth(username=TG_USER, password=TG_PASSWORD)


def fetch_taiga(message, channel, thread, user):
    m = set(re.findall('tg#\d*', message.lower()))
    attachments = []
    if m:
        for match in m:
            print(match)
            text_response = ""

            project = api.projects.get_by_slug(TG_PROJECT)
            project.name = TG_PROJECT
            tg_element_id = match.lower().split(TG_PATTERN)[1].strip().lower()
            taiga_element = project.get_item_by_ref(tg_element_id)
            if taiga_element is not None:
Exemple #25
0
from taiga import TaigaAPI
import pygal


API_HOST = "https://api.taiga.io/"


if __name__ == "__main__":
    api = TaigaAPI(host=API_HOST)

    # Login
    username = input("Type your username or email:\n> ")
    password = getpass.getpass("Type your password:\n> ")

    api.auth(username=username, password=password)
    me = api.me()

    # List all my projects
    projects = api.projects.list(member=me.id)

    project_list_display = "\n".join(
        ["  {} - {}".format(i, p.name) for i, p in enumerate(projects)]
    )
    index = int(input("Select project: \n{}\n> ".format(project_list_display)))
    project = projects[index]

    # Get issues stats data
    issues_stats = project.issues_stats()

    # GRAPHS
Exemple #26
0
# -*- coding: utf-8 -*-

from taiga import TaigaAPI
from taiga.exceptions import TaigaException

api = TaigaAPI(
    host='http://127.0.0.1:8000'
)

api.auth(
    username='******',
    password='******'
)

print (api.me())

new_project = api.projects.create('TEST PROJECT', 'TESTING API')

new_project.name = 'TEST PROJECT 3'
new_project.update()

print (new_project.members)

for member in new_project.members:
    print (member)

jan_feb_milestone = new_project.add_milestone(
    'New milestone jan feb', '2015-01-26', '2015-02-26'
)

userstory = new_project.add_user_story(
Exemple #27
0
def setup_taiga_api(hostname, username, password):
    api = TaigaAPI(host=hostname)
    api.auth(username=username, password=password)
    return api
Exemple #28
0
def manage_issue(module,
                 taiga_host,
                 project_name,
                 issue_subject,
                 issue_priority,
                 issue_status,
                 issue_type,
                 issue_severity,
                 issue_description,
                 issue_attachment,
                 issue_attachment_description,
                 issue_tags,
                 state,
                 check_mode=False):
    """
    Method that creates/deletes issues depending whether they exist and the state desired

    The credentials should be passed via environment variables:
        - TAIGA_TOKEN
        - TAIGA_USERNAME and TAIGA_PASSWORD

    Returns a tuple with these elements:
        - A boolean representing the success of the operation
        - A descriptive message
        - A dict with the issue attributes, in case of issue creation, otherwise empty dict
    """

    changed = False

    try:
        token = getenv('TAIGA_TOKEN')
        if token:
            api = TaigaAPI(host=taiga_host, token=token)
        else:
            api = TaigaAPI(host=taiga_host)
            username = getenv('TAIGA_USERNAME')
            password = getenv('TAIGA_PASSWORD')
            if not any([username, password]):
                return (False, changed, "Missing credentials", {})
            api.auth(username=username, password=password)

        user_id = api.me().id
        project_list = filter(lambda x: x.name == project_name,
                              api.projects.list(member=user_id))
        if len(project_list) != 1:
            return (False, changed, "Unable to find project %s" % project_name,
                    {})
        project = project_list[0]
        project_id = project.id

        priority_list = filter(lambda x: x.name == issue_priority,
                               api.priorities.list(project=project_id))
        if len(priority_list) != 1:
            return (False, changed,
                    "Unable to find issue priority %s for project %s" %
                    (issue_priority, project_name), {})
        priority_id = priority_list[0].id

        status_list = filter(lambda x: x.name == issue_status,
                             api.issue_statuses.list(project=project_id))
        if len(status_list) != 1:
            return (False, changed,
                    "Unable to find issue status %s for project %s" %
                    (issue_status, project_name), {})
        status_id = status_list[0].id

        type_list = filter(lambda x: x.name == issue_type,
                           project.list_issue_types())
        if len(type_list) != 1:
            return (False, changed,
                    "Unable to find issue type %s for project %s" %
                    (issue_type, project_name), {})
        type_id = type_list[0].id

        severity_list = filter(lambda x: x.name == issue_severity,
                               project.list_severities())
        if len(severity_list) != 1:
            return (False, changed,
                    "Unable to find severity %s for project %s" %
                    (issue_severity, project_name), {})
        severity_id = severity_list[0].id

        issue = {
            "project": project_name,
            "subject": issue_subject,
            "priority": issue_priority,
            "status": issue_status,
            "type": issue_type,
            "severity": issue_severity,
            "description": issue_description,
            "tags": issue_tags,
        }

        # An issue is identified by the project_name, the issue_subject and the issue_type
        matching_issue_list = filter(
            lambda x: x.subject == issue_subject and x.type == type_id,
            project.list_issues())
        matching_issue_list_len = len(matching_issue_list)

        if matching_issue_list_len == 0:
            # The issue does not exist in the project
            if state == "present":
                # This implies a change
                changed = True
                if not check_mode:
                    # Create the issue
                    new_issue = project.add_issue(
                        issue_subject,
                        priority_id,
                        status_id,
                        type_id,
                        severity_id,
                        tags=issue_tags,
                        description=issue_description)
                    if issue_attachment:
                        new_issue.attach(
                            issue_attachment,
                            description=issue_attachment_description)
                        issue["attachment"] = issue_attachment
                        issue[
                            "attachment_description"] = issue_attachment_description
                return (True, changed, "Issue created", issue)

            else:
                # If does not exist, do nothing
                return (True, changed, "Issue does not exist", {})

        elif matching_issue_list_len == 1:
            # The issue exists in the project
            if state == "absent":
                # This implies a change
                changed = True
                if not check_mode:
                    # Delete the issue
                    matching_issue_list[0].delete()
                return (True, changed, "Issue deleted", {})

            else:
                # Do nothing
                return (True, changed, "Issue already exists", {})

        else:
            # More than 1 matching issue
            return (False, changed,
                    "More than one issue with subject %s in project %s" %
                    (issue_subject, project_name), {})

    except TaigaException as exc:
        msg = "An exception happened: %s" % to_native(exc)
        return (False, changed, msg, {})
def index(request):
	folder = settings.TAIGA_DATA_FOLDER
	directories = [os.path.join(folder,o) for o in os.listdir(folder) if os.path.isdir(os.path.join(folder,o))]

	
	report = Report(settings.TAIGA_DATA_FOLDER)

	status_points_filename = os.path.join(settings.MEDIA_ROOT,'status_points_{0}.png'.format(int(time.time()))  ) 
	status_count_filename = os.path.join(settings.MEDIA_ROOT,'status_count_{0}.png'.format(int(time.time())) ) 
	tags_points_filename = os.path.join(settings.MEDIA_ROOT,'tags_points_{0}.png'.format(int(time.time())) ) 
	tags_count_filename = os.path.join(settings.MEDIA_ROOT,'tags_count_{0}.png'.format(int(time.time())) ) 
	
	report.save_status_points_graph( status_points_filename )
	report.save_status_counts_graph( status_count_filename )
	report.save_tags_points_graph( tags_points_filename )
	report.save_tags_counts_graph( tags_count_filename )

	closed_status_points_filename 	= os.path.join(settings.MEDIA_ROOT,'status_points_{0}.png'.format(int(time.time()))  ) 
	closed_status_count_filename 	= os.path.join(settings.MEDIA_ROOT,'status_count_{0}.png'.format(int(time.time())) ) 
	closed_tags_points_filename 	= os.path.join(settings.MEDIA_ROOT,'tags_points_{0}.png'.format(int(time.time())) ) 
	closed_tags_count_filename  	= os.path.join(settings.MEDIA_ROOT,'tags_count_{0}.png'.format(int(time.time())) ) 
	
	report.save_status_points_graph( closed_status_points_filename,  closed=True )
	report.save_status_counts_graph( closed_status_count_filename,   closed=True )
	report.save_tags_points_graph( 	 closed_tags_points_filename, 	 closed=True )
	report.save_tags_counts_graph( 	 closed_tags_count_filename, 	 closed=True )

	
	api = TaigaAPI()
	api.auth(username=settings.USER, password=settings.PASS)

	workload_imgs 	= []
	last_moment 	= report.last_snapshot

	for user_id in settings.TEAM:
		user = api.users.get(user_id)

		user_report 		= UserReport(user_id, last_moment)
		workload_filename 	= os.path.join(settings.MEDIA_ROOT,'workload_{1}_{0}.png'.format(int(time.time()), user_id) ) 
	
		user_report.save_workload_4_next_days_graph(workload_filename, settings.TAGS_PRIORITIES)


		username = (user.full_name if user.full_name!='' else user.username)
		workload_imgs.append( (username, workload_filename) )

	data = {
		'status_points_filename': 	status_points_filename,
		'status_count_filename': 	status_count_filename, 
		'tags_points_filename':		tags_points_filename,
		'tags_count_filename':		tags_count_filename,
		'closed_status_points_filename': 	closed_status_points_filename,
		'closed_status_count_filename': 	closed_status_count_filename, 
		'closed_tags_points_filename':		closed_tags_points_filename,
		'closed_tags_count_filename':		closed_tags_count_filename,
		'workload_images':		workload_imgs,
		'not_assigned_stories': last_moment.not_assigned_stories()
	}

	template_directory = os.path.dirname(os.path.realpath(__file__))
	template_file = os.path.join(template_directory, 'templates', 'index.html')
	return render_to_response(template_file, data)