def replace_client_name(view, old_client_name, new_client_name):
    '''
    Convert "//depot/... //old_client/..." to "//depot/... //new_client"

    Accepts view as P4.Map, str. or list.
    Returns view as P4.Map().
    '''
    if isinstance(view, P4.Map):
        old_map = view
    elif isinstance(view, str):
        view_lines = view.splitlines()
        old_map = P4.Map(view_lines)
    else:
        view_lines = view
        old_map = P4.Map(view_lines)

    lhs = old_map.lhs()
    new_prefix = '//{}/'.format(new_client_name)
    old_prefix = '//{}/'.format(old_client_name)
    old_len = len(old_prefix)
    rhs = [new_prefix + p4gf_path.dequote(r)[old_len:] for r in old_map.rhs()]
    new_map = P4.Map()
    for (l, r) in zip(lhs, rhs):
        new_map.insert(l, r)

    return new_map
def convert_view_from_no_client_name(view, new_client_name):
    '''
    Convert a view mapping's right-hand-side from its original client
    name to a new client name:

        //depot/dir/...  dir/...
        //depot/durr/... durr/...

    becomes

        //depot/dir/...  //client/dir/...
        //depot/durr/... //client/durr/...

    Accepts view as P4.Map, str. or list.
    Returns view as P4.Map().
    '''
    if isinstance(view, P4.Map):
        old_map = view
    elif isinstance(view, str):
        view_lines = view.splitlines()
        old_map = P4.Map(view_lines)
    else:
        view_lines = view
        old_map = P4.Map(view_lines)

    lhs = old_map.lhs()
    new_prefix = '//{}/'.format(new_client_name)
    rhs = [new_prefix + p4gf_path.dequote(r) for r in old_map.rhs()]
    new_map = P4.Map()
    for (l, r) in zip(lhs, rhs):
        new_map.insert(l, r)

    return new_map
Exemple #3
0
def convert_view_to_no_client_name(view):
    '''
    Convert a view mapping's right-hand-side from its original client
    name to a new client name:

        //depot/dir/...  //client/dir/...
        //depot/durr/... //client/durr/...

    becomes

        //depot/dir/...  dir/...
        //depot/durr/... durr/...
    '''
    if not view:
        return []
    old_client_name = view_map_to_client_name(view)

    old_map = P4.Map(view)
    lhs = old_map.lhs()
    old_prefix = '//{}/'.format(old_client_name)
    new_prefix = ''
    rhs = [r.replace(old_prefix, new_prefix) for r in old_map.rhs()]
    new_map = P4.Map()
    for (l, r) in zip(lhs, rhs):
        new_map.insert(l, r)
    return '\n'.join(new_map.as_array())
 def connectToPerforce(self, retry=3):
     # if (
     #     not hasattr(self, "p4")
     #     or not hasattr(self, "sgPrjId")
     #     or (user and not hasattr(self, "sgUserId"))
     # ):
     is_connected_p4 = False
     try:
         self.p4.disconnect()
     except:
         pass
     self.p4.port = self.core.getConfig("perforce", "port", configPath = self.core.prismIni)
     self.p4.user = self.core.getConfig("perforce", "p4username")
     self.p4.client = self.core.getConfig("perforce", "p4userworkspacename")
     self.p4.password = self.core.getConfig("perforce", "p4userpassword")
     try:
         self.p4.connect()
     except P4.P4Exception as why:
         raise P4.P4Exception("Failed to connect to p4. {}".format(why))
     try:
         self.p4.run_login('-s')
         is_connected_p4 = True
     except P4.P4Exception as why:
         try:
             self.p4.run_login()
             is_connected_p4 = True
         except P4.P4Exception as why:
             raise P4.P4Exception("Failed to login to p4. {}".format(why))
     while not is_connected_p4 and retry != 0:
         is_connected_p4 = self.connectToPerforce(retry-1)
     return is_connected_p4
    def _calc_fully_populated_basis(self, dbi, branch_view_p4map):
        """Return an FPBasis tuple that is this lightweight branch's
        divergence from fully populated Perforce.

        Searches up the first-parent line until it either finds an
        ancestor with an already-cached basis, or hits fully populated
        Perforce.

        Never returns None. Returns FPBASIS_NONE if no basis.
        """
        change_num_dbi = self._find_fp_change_num_change_dbi(dbi)
        if not (change_num_dbi and change_num_dbi.change_num
                and change_num_dbi.child_dbi):
            return FPBASIS_NONE

            # What subset of fully populated Perforce is
            # inherited into that first child depot branch?
            #
            # If first child has already cached a mapping, use that
            # mapping, rerooted to our new depot root.
            #
        child_dbi = change_num_dbi.child_dbi
        if child_dbi.fp_basis_known:
            map_line_list = reroot_rhs(
                map_line_list=child_dbi.fp_basis_map_line_list,
                old_rhs_root=child_dbi.root_depot_path,
                new_rhs_root=dbi.root_depot_path)
            return FPBasis(change_num=change_num_dbi.change_num,
                           map_line_list=map_line_list,
                           map_rhs_root=dbi.root_depot_path)

            # Use the current branch VIEW as the lens through which
            # to view fully populated perforce. What subset of
            # fully populated Perforce can be seen in the current
            # branch view? That's the portion that is "inherited"
            # into lightweight branches. That's the portion that we
            # record in the fp_basis_map_line_list. That's
            # represented in the LHS side, which we'll reroot to FP
            # Perforce, and then  repeat on the RHS, rooted to our
            # LW depot branch root.

            # LHS is view, rerooted to FP Perforce.
        rerooter = P4.Map("//...", dbi.root_depot_path + "/...")
        rerooted = P4.Map.join(rerooter, branch_view_p4map)
        # RHS is LHS, rerooted to our LW depot branch root.
        lhs = rerooted.lhs()
        rhs = p4gf_util.map_lhs_to_relative_rhs_list(lhs)
        m = P4.Map()
        for l, r in zip(lhs, rhs):
            m.insert(l, r)
        map_line_list = reroot_rhs(map_line_list=m.as_array(),
                                   old_rhs_root="",
                                   new_rhs_root=dbi.root_depot_path)
        return FPBasis(change_num=change_num_dbi.change_num,
                       map_line_list=map_line_list,
                       map_rhs_root=dbi.root_depot_path)
Exemple #6
0
    def get_depot_path_map(self, root=None):
        '''get depot -> abs path mapping of current client in p4
    
        @return instance of P4.Map, from depot to abs path
        '''
        ws_spec = self.fetch_client(self.client)
        depot_to_root = P4.Map(ws_spec._view)
        root = root if root else ws_spec._root

        root_to_path = P4.Map('//%s/...   %s/...' % (self.client, root))
        depot_to_path = P4.Map.join(depot_to_root, root_to_path)

        return depot_to_path
Exemple #7
0
def _calc_branch_p4map(ctx, depot_root):
    """Return a branch view, rerooted at depot_root."""
    view_lines = ctx.repo_config.get(p4gf_config.SECTION_GIT_TO_PERFORCE,
                                     p4gf_config.KEY_NDB_VIEW)
    if not view_lines:
        view_lines = p4gf_config.VALUE_NDB_VIEW_DEFAULT
    view_lines = p4gf_config.to_view_lines(view_lines)

    relative_p4map = P4.Map(view_lines)
    relative_p4map = p4gf_branch.convert_view_from_no_client_name(
        relative_p4map, ctx.config.p4client)
    remapper = P4.Map(os.path.join(depot_root, '...'), '...')
    remapped = P4.Map.join(remapper, relative_p4map)
    return remapped
Exemple #8
0
    def testMap(self):
        # don't need connection, simply test all the Map features

        map = P4.Map()
        self.assertEqual(map.count(), 0, "Map does not have count == 0")
        self.assertEqual(map.is_empty(), True, "Map is not empty")

        map.insert("//depot/main/... //ws/...")
        self.assertEqual(map.count(), 1, "Map does not have 1 entry")
        self.assertEqual(map.is_empty(), False, "Map is still empty")

        self.assertEqual(map.includes("//depot/main/foo"), True,
                         "Map does not map //depot/main/foo")
        self.assertEqual(map.includes("//ws/foo", False), True,
                         "Map does not map //ws/foo")

        map.insert("-//depot/main/exclude/... //ws/exclude/...")
        self.assertEqual(map.count(), 2, "Map does not have 2 entries")
        self.assertEqual(map.includes("//depot/main/foo"), True,
                         "Map does not map foo anymore")
        self.assertEqual(map.includes("//depot/main/exclude/foo"), False,
                         "Map still maps foo")
        self.assertEqual(map.includes("//ws/foo", False), True,
                         "Map does not map foo anymore (reverse)")
        self.assertEqual(map.includes("//ws/exclude/foo"), False,
                         "Map still maps foo (reverse)")

        map.clear()
        self.assertEqual(map.count(), 0, "Map has elements after clearing")
        self.assertEqual(map.is_empty(), True,
                         "Map is still not empty after clearing")

        a = [
            "//depot/main/... //ws/main/...",
            "//depot/main/doc/... //ws/doc/..."
        ]
        map = P4.Map(a)
        self.assertEqual(map.count(), 3, "Map does not contain 3 elements")

        map2 = P4.Map("//ws/...", "C:\Work\...")
        self.assertEqual(map2.count(), 1, "Map2 does not contain any elements")

        map3 = P4.Map.join(map, map2)
        self.assertEqual(map3.count(), 3, "Join did not produce three entries")

        map.clear()
        map.insert('"//depot/dir with spaces/..." "//ws/dir with spaces/..."')
        self.assertEqual(map.includes("//depot/dir with spaces/foo"), True,
                         "Quotes not handled correctly")
def _fetch(ctx):
    """If the Perforce server has a 'p4 typemap' configured, return it
    as a P4.Map instance.
    To accomodate mappings of multiple right-hand patterns to the same <type>
    append the <rhs> to the left hand <type>.
    Mapping will be unique, but require stripping the appended <rhs> postfix.
    If not, return None.
    """
    r = ctx.p4gfrun('typemap', '-o')
    raw_lines = p4gf_util.first_value_for_key(r, "TypeMap")
    if not raw_lines:
        return None

    typem = P4.Map()
    for mapline in raw_lines:
        lhs, sep, rhs = mapline.partition(
            ' ')  # the P4 typemap types are delimited by the first ' '
        # if <rhs> does not start with '/',
        # insert one when constructing new <lhs> = <type>/<rhs>
        # We dont care that '"' are embedded in the constructed new <lhs>
        # We do need to ensure that the <type> is followed immediately by a '/'
        # So we may append the <type> with the <rhs> as  <type><rhs> or <type>/<rhs>
        # and <rhs> may itself start with '/' or '"' or neither.
        # Our regex lookup will detect on the first '/'
        sep = ''  # concatenate <lhs><sep><rhs>
        if not rhs.startswith('/'):  # if there is no '/' .. then add '/'
            sep = '/'
        lhs = lhs + sep + rhs
        typem.insert(lhs, rhs)

    return typem
def create_read_permissions_map(protects_dict_list, requested_perm=READ):
    """The results are used to test for repo read permissions
    and as such are filtered to serve the algorithm.
    Return a new MapApi instance that maps in all of
    protects_dict_list depotFile lines that grant the requested_perm
    Also map in exclusion lines which which do not start with '=' except
    those which start with '=requested_perm'.
    Additionally exclude list inclusions.
    """

    # Build a list of matching lines.
    lines = []
    for pd in protects_dict_list:
        # skip all =perm unless it matches the requested perm
        if (pd['perm'].startswith('=') and
                pd['perm'] != "=" + requested_perm):   # eg: "=read user x * -//path/"
            continue
        if 'unmap' in pd: # Unmapping ANY permission unmaps ALL permissions
            lines.append('-' + pd['depotFile'])
            continue
        if permission_includes(pd['perm'], requested_perm):
            if pd['perm'] != 'list':  # skip list inclusions
                lines.append(pd['depotFile'])

    # P4.Map() requires space-riddled paths to be quoted paths
    # to avoid accidentally splitting a # single path into lhs/rhs.
    quoted = [enquote(x) for x in lines]
    mapapi = P4.Map(quoted)
    return mapapi
Exemple #11
0
def get_perforce_change(perforce_server, user, password):
    """ function to login to perforce and get the TOT
   change.

   @params perforce_server : perforce server to login to
   @params user : perforce user
   @params password password to login to perforce.

   @returns change TOT change
   """

    p4 = P4.P4()
    p4.user = user
    p4.password = password
    p4.port = perforce_server
    try:
        p4.connect()
        p4.run_login("-a")
        changes = p4.run("changes", "-s", "submitted", "-m", "1")
    except P4.P4Exception:
        for e in p4.errors:
            print "error =%s while getting TOT change" % e
    change = changes[0]['change']
    if not change:
        print "Failed to get TOT change"
        return False
    else:
        return change
    def __init__(self, core, plugin):
        self.core = core
        self.plugin = plugin
        self.p4 = P4.P4()

        self.callbacks = []
        self.registerCallbacks()
Exemple #13
0
    def _overlapping_branch_list(self):
        """Return a list of fully populated branches that overlap
        other fully populated branches.

        Caches the result because we check every file revision
        path for overlap, and for huge repos with thousands of
        non-overlapping LW branches, just iterating through the
        branch list starts to waste measurable CPU time.
        """
        if self._cached_overlapping_branch_list is not None:
            return self._cached_overlapping_branch_list

        have_overlap = set()
        for outer in p4gf_branch.iter_fp_non_deleted(self.ctx.branch_dict()):
            outer_lhs = P4.Map()
            outer_lhs.insert(outer.view_p4map.lhs())
            for inner in p4gf_branch.iter_fp_non_deleted(
                    self.ctx.branch_dict()):
                if outer == inner:
                    continue
                overlap = P4.Map.join(outer_lhs, inner.view_p4map)
                # Any non-exclusionary lines shared between branches?
                for line in overlap.as_array():
                    if line.startswith('-') or line.startswith('"-'):
                        continue
                    # Yep. Non-exclusionary line implies overlap
                    have_overlap.add(outer)
                    have_overlap.add(inner)
                    break

        self._cached_overlapping_branch_list = have_overlap
        return self._cached_overlapping_branch_list
    def __init__(self, user, client, password):
        self._p4 = perforce.P4()
        self._p4.exception_level = 1
        # self._p4.api_level = 1

        self.user = user
        self.client = client
        self.password = password
        # self.port = port

        if self.user:
            self._p4.user = self.user
        elif self.client:
            self._p4.client = self.client
        elif self.password:
            self._p4.password = self.password
        # elif self.port:
        #     self._p4.port = self.port

        #Lets start talking to the server
        self._p4.connect()

        # if self.user and self.password:
        # #attempt to login as a specific user/password for a ticketed system
        # self._p4.run_login()

        if self.connected():
            self.p4info = self._p4.run("info")[0]
Exemple #15
0
    def __init__(self,
                 path,
                 username,
                 password,
                 encoding='',
                 host=None,
                 client_name=None,
                 local_site_name=None,
                 use_ticket_auth=False):
        """Initialize the client.

        Args:
            path (unicode):
                The path to the repository (equivalent to :envvar:`P4PORT`).

            username (unicode):
                The username for the connection.

            password (unicode):
                The password for the connection.

            encoding (unicode, optional):
                The encoding to use for the connection.

            host (unicode, optional):
                The client's host name to use for the connection (equivalent
                to :envvar:`P4HOST`).

            client_name (unicode, optional):
                The name of the Perforce client (equivalent to
                :envvar:`P4CLIENT`).

            local_site_name (unicode, optional):
                The name of the local site used for the repository.

            use_ticket_auth (bool, optional):
                Whether to use ticket-based authentication. By default, this
                is not used.
        """
        if path.startswith('stunnel:'):
            path = path[8:]
            self.use_stunnel = True
        else:
            self.use_stunnel = False

        self.p4port = path
        self.username = username
        self.password = password or ''
        self.encoding = encoding
        self.p4host = host
        self.client_name = client_name
        self.local_site_name = local_site_name
        self.use_ticket_auth = use_ticket_auth

        import P4
        self.p4 = P4.P4()

        if self.use_stunnel and not is_exe_in_path('stunnel'):
            raise AttributeError('stunnel proxy was requested, but stunnel '
                                 'binary is not in the exec path.')
Exemple #16
0
def stream_view_submods(submod_views, change_views=None):
    """Produce a list of tuples suitable for creating submodule repos.

    Arguments:
        submod_views -- list of stream view entries.
        change_views -- optional list of view/change lines from stream's ChangeView field.

    Returns:
        list of tuples consisting of depot path, change number, local path;
        the change number will be None if change_views did not have a match

    """
    # make the order predictable for testing purposes
    submod_map = OrderedDict()
    change_nums = OrderedDict()
    p4map = P4.Map(submod_views)
    for left, right in zip(p4map.lhs(), p4map.rhs()):
        submod_map[left] = right
        change_nums[left] = None
    if change_views:
        for cview in change_views:
            cpath, cnum = cview.split('@')
            if cpath in submod_map:
                change_nums[cpath] = cnum
    results = []
    for cpath, cnum in change_nums.items():
        results.append((cpath, cnum, submod_map[cpath]))
    return results
Exemple #17
0
def newInstance(dialog=False):
    global DEFAULT_USER_VALIDATED
    global DEFAULT_LOGGED_IN

    if P4 is None or not hasattr(P4, 'P4'):
        raise ValueError("Couldn't find P4 or P4API")

    p4 = P4.P4()
    if not p4.connected():
        p4.connect()

    if not DEFAULT_LOGGED_IN:
        if dialog:
            import gui
            gui.login(p4)
        else:
            try:
                p4.run_login("-s")
            except P4.P4Exception:
                raise ValueError("Couldn't login to P4")
        DEFAULT_LOGGED_IN = True

    if not DEFAULT_USER_VALIDATED:
        if not is_valid_user(p4):
            raise ValueError("P4 User Doesn't Exist: {0}".format(p4.user))
        DEFAULT_USER_VALIDATED = True

    return p4
def raise_if_homedir(homedir, view_name, rm_list):
    """If any path in rm_list is user's home directory, fail with error
    rather than delete the home directory."""
    for e in rm_list:
        if e == homedir:
            raise P4.P4Exception(("One of view {}'s directories is" +
                                  " user's home directory!").format(view_name))
def _branch_view_union_p4map_one(p4map, branch):
    '''
    Accumulate one branch's view in the map
    '''
    if not branch.view_lines:
        return
    branch_p4map = P4.Map()
    for line in branch.view_lines:
        # Skip exclusion lines.
        if line.startswith('-') or line.startswith('"-'):
            continue
        # Flatten overlay lines, remove leading +
        if line.startswith('+'):
            line = line[1:]
        elif line.startswith('"+'):
            line = '"' + line[2:]

        branch_p4map.insert(line)

    # Replace branch view's RHS (client side) with a copy of its LHS
    # (depot side) so that each depot path "//depot/foo" maps to a client
    # path "depot/foo". This new RHS allows us un-exclude
    # P4.Map-generated minus/exclusion lines that P4.Map had to insert
    # into branch_p4map when multiple LHS collided on the same RHS.
    lhs = branch_p4map.lhs()
    rhs = [_lhs_to_relative_rhs(l) for l in lhs]

    for (ll, rr) in zip(lhs, rhs):
        if ll.startswith('-') or ll.startswith('"-'):
            continue
        p4map.insert(ll, rr)
Exemple #20
0
 def setUp(self):
     self.setDirectories()
     self.p4d = "p4d"
     self.port = "rsh:%s -r \"%s\" -L log -vserver=3 -i" % (
         self.p4d, self.server_root)
     self.p4 = P4.P4()
     self.p4.port = self.port
Exemple #21
0
def get_p4_from_path(path):
    p4 = P4.P4()
    if not p4.connected():
        p4.connect()
    try:
        p4.run_login("-s")
    except P4.P4Exception, e:
        raise ValueError("Couldn't login to perforce: {0}".format(e))
def p4ClientRoot():
    import P4
    p4 = P4.P4()
    p4.connect()
    all_clients = p4.run_client('-o')
    client_root = all_clients[0]['Root']

    return client_root
def get_p4_conn():
    global _p4_conn
    import P4
    if not _p4_conn:
        _p4_conn = P4.P4()
    if not _p4_conn.connected():
        _p4_conn.connect()
    return _p4_conn
 def __init__(self, core, plugin):
     self.core = core
     self.plugin = plugin
     self.p4 = P4.P4()
     self.logger = get_logger(
         __name__, True,
         os.path.join(os.path.dirname(core.prismIni),
                      "perforce_logging.log"))
Exemple #25
0
def convert_client(args, p4, client_name):
    """Convert the named Perforce client and its workspace. Raises
    P4Exception if the client is not present, or the client configuration is
    not set up as expected.

    Keyword arguments:
    args        -- parsed command line arguments
    p4          -- Git user's Perforce client
    client_name -- name of client to be deleted

    """
    group_list = [
        p4gf_const.P4GF_GROUP_VIEW_PULL, p4gf_const.P4GF_GROUP_VIEW_PUSH
    ]
    p4.user = p4gf_const.P4GF_USER
    old_client = p4.client
    p4.client = client_name

    print("  Processing client {}...".format(client_name))
    if not p4gf_util.spec_exists(p4, 'client', client_name):
        raise P4.P4Exception('No such client "{}" defined'.format(client_name))

    view_name = client_name[len(p4gf_const.P4GF_CLIENT_PREFIX):]
    client = p4.fetch_client()
    command_path = client["Root"]

    if not args.convert:
        print("    Removing client files for {}...".format(client_name))
        print("      p4 sync -fqk {}/...#none".format(command_path))
        print("    Create config for client {}...".format(client_name))
        p4.client = old_client
        for group_template in group_list:
            group = group_template.format(view=view_name)
            print("    Leaving existing group {}".format(group))
        print("    Remove client lock counter")
        print("      p4 counter -u -d {}".format(
            p4gf_lock.view_lock_name(view_name)))

    else:
        LOG_FILE.write("Processing client {}\n".format(client_name))
        print("    Removing client files for {}...".format(client_name))
        print("      p4 sync -fqk {}/...#none".format(command_path))
        LOG_FILE.write("p4 sync -fqk {}/...#none\n".format(command_path))
        p4.run('sync', '-fqk', command_path + '/...#none')
        print("    Creating config for client {}...".format(client_name))
        LOG_FILE.write(
            "Creating config for client {}...\n".format(client_name))
        p4.client = old_client
        create_from_12x_gf_client_name(p4, client_name)
        for group_template in group_list:
            group = group_template.format(view=view_name)
            print("    Leaving existing group {}".format(group))
        print("    Remove client lock counter")
        print("      p4 counter -u -d {}".format(
            p4gf_lock.view_lock_name(view_name)))
        LOG_FILE.write("p4 counter -u -d {}\n".format(
            p4gf_lock.view_lock_name(view_name)))
        _delete_counter(p4, p4gf_lock.view_lock_name(view_name))
Exemple #26
0
 def __init__(self, user, client, allowed_patterns=None, trigger=False):
     self.p4 = P4.P4()
     self.p4.user = user
     self.p4.client = client
     self.p4.exception_level = 1
     self.p4.connect()
     self.allowed_patterns = allowed_patterns if allowed_patterns else []
     self.trigger = trigger
     self.unshelve_changelist = None
    def __init__(self, repository):
        SCMTool.__init__(self, repository)

        import P4
        self.p4 = P4.P4()
        self.p4.port = str(repository.mirror_path or repository.path)
        self.p4.user = str(repository.username)
        self.p4.password = str(repository.password)
        self.p4.exception_level = 1
def reroot_rhs(map_line_list, old_rhs_root, new_rhs_root):
    """Return a new list of map lines, replacing RHS prefix
    with a new prefix.
    """
    # Permit missing views.
    if not map_line_list:
        return map_line_list
        # +++ NOP if nothing to change.
    if old_rhs_root == new_rhs_root:
        return map_line_list

    orig = P4.Map(map_line_list)
    if old_rhs_root:
        rerooter = P4.Map("{old}/... {new}/...".format(old=old_rhs_root,
                                                       new=new_rhs_root))
    else:
        rerooter = P4.Map("... {new}/...".format(new=new_rhs_root))
    rerooted = P4.Map.join(orig, rerooter)
    return rerooted.as_array()
Exemple #29
0
    def from_dict(d):
        """For easier JSON parsing."""

        ndb = NDB(ctx=None,
                  prt=PreReceiveTuple.from_dict(d['prt']),
                  orig_prt=PreReceiveTuple.from_dict(d['orig_prt']),
                  git_branch_name=d['git_branch_name'],
                  depot_root=d['depot_root'],
                  view_p4map=P4.Map(d['view_lines']))
        return ndb
Exemple #30
0
def PerformDailyBuild():
    print "  changes detected, starting daily build"
    # update the counter to be what we're verifying
    change = P4.SubmittedChangelist( g_szP4SrcFilesToWatch )
    g_nP4MostRecentCheckin = change
    g_nP4LastVerifiedCheckin = P4.GetCounter(g_szP4VerifiedCounter)
    if g_nP4MostRecentCheckin and g_nP4LastVerifiedCheckin:
        print "Most recent checkin is " + g_nP4MostRecentCheckin + "\n"
        print "Last verified checkin is " + g_nP4LastVerifiedCheckin + "\n"
    # the p4 command can occasionally fail to deliver a valid changelist number, unclear why
    # can't update the counter, it just means we'll run twice
    if change:
        P4.SetCounter(g_szP4ChangeCounter, change)
    # sync to the new files
    if ( g_bSync ):
        SystemHelpers.ChangeDir("\\src")
        print( "Cleaning\n" )
        os.system("cleanalltargets.bat > silence")
        SystemHelpers.ChangeDir("\\")        
        print "Synching force files."
        P4.Sync( g_szP4ForceFilesToWatch, 1 )
        print "Synching other files."
        P4.Sync( g_szP4SyncFilesToWatch, 0 )
        print( "Setting up VPC" )
        os.system("setupVPC.bat")
        
    #P4.UnlockMutex(g_szP4Mutex)
    # build and test in each configuration
    if not RunAllBuilds():
        print "Daily build failed"
        return
        
    # send a success email, from past the last successful checkin to the current
    if change:
        szVerifiedOrig = P4.GetCounter(g_szP4VerifiedCounter)
        if szVerifiedOrig:
            szVerifiedPlusOne = str( int( szVerifiedOrig ) + 1 )
            changes = P4.GetChangelistRange(szVerifiedPlusOne, change, g_szP4SrcFilesToWatch );
            for ch in changes:
                if len(ch) > 1:
                    szEmail = P4.GetEmailFromChangeLine(ch)
                    SendSuccessEmail(szEmail, ch)
                    #SendSuccessEmail("jason", ch)
            # remember this change that we've verified
            P4.SetCounter(g_szP4VerifiedCounter, change)

    print "Daily build: AN UNEQUIVOCAL SUCCESS"
Exemple #31
0
from mrjob.job import MRJob
import math
import sys
import P4

if __name__ == '__main__':
	# want to stop running if there are no changes made (set converged)
	converged = False
	
	init_input = open('graph.txt', 'r')

	while(not converged):
		# setup and run MRJob instance
		mrJobInstance = P4.mrGraphAlg()
		mrJobInstance.stdin = init_input
		runner = mrJobInstance.make_runner()
		runner.run()
		# pull out the counts from the MRJob 
		counts = runner.counters()
	        # if the counter is 0, no changes, graph converged
		if (counts[0]['graph']['node'] == 0):
			converged = True
		# save all of the new graph information for the next run, or as output
		f_out = open('out.txt','w')
		for line in runner.stream_output():
			f_out.write(line)
		f_out.close()
		init_input.close()
		# reopen out.txt and use that for next iteration
		init_input = open('out.txt','r')
Exemple #32
0
    print("\n1. New Vehicle Registration")
    print("2. Auto Transaction")
    print("3. Driver License Registration")
    print("4. Violation Record")
    print("5. Search Engine")
    selection = input("Please select your program number or 'exit':\n")
    
    
    try:
        digit = int(selection)
        if digit == 1:
            P1.regV(conString)
        elif digit == 2:
            P2.AutoTransaction(conString)
        elif digit == 3:
            P3.DriverLiRegis(conString)
        elif digit == 4:
            P4.violation(conString)
        elif digit == 5:
            P5.search_engine(conString)
        else:
            print("Must be between 1 and 5")
                
    except ValueError:
        if selection == 'exit':
            run = False
        else:
            print("Please enter a digit or 'exit'")
    
                 
Exemple #33
0
import Constant, Init, P4, Build, Sign, Upload, Email, Check

import sys



if __name__ == '__main__':
	
	Init.system_init()

	project=Init.init_choice(len(sys.argv))

	project.project_init()

	P4.download( project )

	P4.getDescribe (project , "1")
#	Check.check( project )
	
#	Build.build( project )

#	Sign.sign( project)		

#	Upload.upload( project )

#	Email.send( project )

#    project.apk_file_name = project.projectName + ".apk"
#    if(sys.argv[1]=='--normal'):
#	project.build_style="normal"